/**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     Eloquent::unguard();
     if (!Config::get('gosmart.integrated_patient_database')) {
         \Log::warning("Can only seed simulations if a patient database is available");
         return;
     }
     $this->clean();
     //$this->deepClean();
     $organs = ['liver', 'kidney'];
     foreach ($organs as $organ) {
         $referenceSimulation[$organ] = [];
         $sim = Simulation::join('ItemSet_Patient AS IS_P', 'IS_P.Id', '=', 'Simulation.Patient_Id')->join('ItemSet AS IS', 'IS.Id', '=', 'IS_P.Id')->join('Simulation_Needle AS SN', 'SN.Simulation_Id', '=', 'Simulation.Id')->where('IS_P.OrganType', '=', ContextEnum::value($organ))->where('IS.IsDeleted', '=', 'FALSE')->select('Simulation.*')->first();
         if ($sim) {
             $referenceSimulation[$organ]["patient"] = DB::table('ItemSet_Patient')->whereId($sim->Patient_Id)->first();
             $referenceNeedle = $sim->SimulationNeedles->first();
             $referenceSimulation[$organ]["target"] = $referenceNeedle->Target;
             $referenceSimulation[$organ]["entry"] = $referenceNeedle->Entry;
         } else {
             $referenceSimulation[$organ]["patient"] = NULL;
             $referenceSimulation[$organ]["target"] = PointSet::fromArray([0, 0, 0]);
             $referenceSimulation[$organ]["entry"] = PointSet::fromArray([1, 1, 1]);
         }
     }
     foreach (['5cm', '4cm', '3cm', '2cm'] as $length) {
         $this->makeSimulation("{$length} RITA RFA", $referenceSimulation["liver"]["patient"], 'liver', 'NUMA RFA Basic SIF', "RITA Starburst {$length} Protocol", [], ['organ' => ["organ.vtp"], 'vessels' => ["vessels1.vtp"], 'tumour' => ["tumour.vtp"]], [["Manufacturer" => "RITA", "Name" => "Starburst MRI", "Parameters" => ['NEEDLE_TIP_LOCATION' => $referenceSimulation["liver"]["target"]->asString, 'NEEDLE_ENTRY_LOCATION' => $referenceSimulation["liver"]["entry"]->asString]]]);
     }
     $this->makeSimulation('Cryoablation', $referenceSimulation["kidney"]["patient"], 'kidney', 'NUMA Cryoablation Basic SIF', 'Empty', ['SETTING_FINAL_TIMESTEP' => '300'], ['organ' => ["organ.vtp"], 'vessels' => ["vessels1.vtp"], 'tumour' => ["tumour.vtp"]], [["Manufacturer" => "Galil Medical", "Name" => "IceROD", "Parameters" => ['NEEDLE_TIP_LOCATION' => $referenceSimulation["kidney"]["target"]->asString, 'NEEDLE_ENTRY_LOCATION' => $referenceSimulation["kidney"]["entry"]->asString]]]);
     $needleDeltas = [[10, 8, -5], [10, 8, 5], [10, -8, -5], [10, -8, 5], [10, 5, 0], [10, -5, 0]];
     $ireTipCentre = $referenceSimulation["liver"]["target"]->asArray;
     $ireEntryCentre = $referenceSimulation["liver"]["entry"]->asArray;
     $parallel = array_map(function ($c) use($ireTipCentre, $ireEntryCentre) {
         return $ireTipCentre[$c] - $ireEntryCentre[$c];
     }, [0, 1, 2]);
     $norm = sqrt($parallel[0] * $parallel[0] + $parallel[1] * $parallel[1] + $parallel[2] * $parallel[2]);
     $parallel = array_map(function ($c) use($norm) {
         return $c / $norm;
     }, $parallel);
     $randVec = [0, 1.2384717624, 3.42878E-6];
     $perp1 = crossProduct($parallel, $randVec);
     $perp2 = crossProduct($parallel, $perp1);
     //$parallel = [1, 0, 0];
     //$perp1 = [0, 1, 0];
     //$perp2 = [0, 0, 1];
     $ireNeedles = [];
     foreach ($needleDeltas as $needleDelta) {
         $needleOffset = array_map(function ($c) use($needleDelta, $parallel, $perp1, $perp2) {
             return $needleDelta[0] * $parallel[$c] + $needleDelta[1] * $perp1[$c] + $needleDelta[2] * $perp2[$c];
         }, [0, 1, 2]);
         $needleTip = array_map(function ($p) {
             return $p[0] + $p[1];
         }, array_map(null, $ireTipCentre, $needleOffset));
         $ireNeedle = ["Manufacturer" => "Angiodynamics", "Name" => "Basic", "Parameters" => ['NEEDLE_TIP_LOCATION' => json_encode($needleTip), 'NEEDLE_ENTRY_LOCATION' => json_encode(array_map(function ($p) {
             return $p[0] + $p[1];
         }, array_map(null, $ireEntryCentre, $needleOffset)))]];
         $ireNeedles[] = $ireNeedle;
     }
     $this->makeSimulation('IRE', $referenceSimulation["liver"]["patient"], 'liver', 'NUMA IRE 3D SIF', 'Empty', ['CONSTANT_IRE_POTENTIAL_DIFFERENCES' => "[1300, 1500, 1300, 1900, 1300, 1300, 1300, 1900, 1300]"], ['organ' => ["organ.vtp"], 'vessels' => ["vessels1.vtp"], 'tumour' => ["tumour.vtp"]], $ireNeedles);
     $this->makeSimulation('Amica MWA', $referenceSimulation["kidney"]["patient"], 'kidney', 'NUMA MWA Nonlinear SIF', 'Generic modifiable power', [], ['organ' => ["organ.vtp"], 'vessels' => ["vessels1.vtp"], 'tumour' => ["tumour.vtp"]], [["Manufacturer" => "HS", "Name" => "APK11150T19V5", "Parameters" => ['NEEDLE_TIP_LOCATION' => $referenceSimulation["kidney"]["target"]->asString, 'NEEDLE_ENTRY_LOCATION' => $referenceSimulation["kidney"]["entry"]->asString]]]);
 }
 public static function fromXml($xml)
 {
     $xpath = new DOMXpath($xml);
     $simulation = new static();
     $simulationNode = $xpath->query('//simulationDefinition/simulation')->item(0);
     $simulation->Id = strtoupper($simulationNode->getAttribute('id'));
     $simulationAttributes = ['Caption', 'SegmentationType', 'Progress', 'State', 'Color', 'Active'];
     foreach ($simulationAttributes as $simulationAttribute) {
         $simulation->{$simulationAttribute} = $simulationNode->getAttribute(strtolower($simulationAttribute));
     }
     //if (Simulation::find($simulation->Id))
     //  return [false, "Simulation with this ID already exists"];
     $simulationNeedle = [];
     $combination = Combination::find($xpath->query('//simulationDefinition/combination/@id')->item(0)->value);
     if (!$combination) {
         throw new Exception("Cannot find combination (you may be able to work around this manually from the XML)");
     }
     $patient = DB::table('ItemSet_Patient')->where('Id', '=', $xpath->query('//simulationDefinition/simulation/patient/@id')->item(0)->value)->get();
     if (empty($patient)) {
         throw new Exception("Patient no longer exists");
     }
     $patient = $patient[0];
     $simulation->Combination_Id = $combination->Combination_Id;
     $simulation->Patient_Id = $patient->Id;
     $simulation->Id = null;
     $simulation->save();
     $parameterNodes = $xpath->query('//simulationDefinition/parameters/parameter');
     $parameters = [];
     foreach ($parameterNodes as $parameterNode) {
         $parameter = Parameter::whereName($parameterNode->getAttribute("name"))->first();
         $simulation->Parameters()->attach($parameter, ["ValueSet" => $parameterNode->getAttribute("value")]);
     }
     $needleNodes = $xpath->query('//simulationDefinition/numericalModel/needles/needle');
     foreach ($needleNodes as $needleNode) {
         $needle = Needle::find($needleNode->getAttribute("id"));
         if (!$needle) {
             throw new Exception("Needle not found");
         }
         $simulationNeedle = new SimulationNeedle();
         $simulationNeedle->Needle_Id = $needle->Id;
         $simulationNeedle->Simulation_Id = $simulation->Id;
         $simulationNeedle->save();
         $parameterNodes = $xpath->query('//simulationDefinition/numericalModel/needles/needle/parameters/parameter');
         $parameters = [];
         foreach ($parameterNodes as $parameterNode) {
             $parameter = Parameter::whereName($parameterNode->getAttribute("name"))->first();
             switch ($parameter->Name) {
                 case "NEEDLE_TIP_LOCATION":
                     $target = PointSet::fromArray(json_decode($parameterNode->getAttribute("value")));
                     $target->save();
                     $simulationNeedle->Target_Id = $target->Id;
                     break;
                 case "NEEDLE_ENTRY_LOCATION":
                     $entry = PointSet::fromArray(json_decode($parameterNode->getAttribute("value")));
                     $entry->save();
                     $simulationNeedle->Entry_Id = $entry->Id;
                     break;
                 default:
                     $simulationNeedle->Parameters()->attach($parameter, ["ValueSet" => $parameterNode->getAttribute("value")]);
             }
         }
         $simulationNeedle->save();
     }
     //foreach ($parameters as $sP)
     //{
     //  $sP->Simulation_Id = $simulation->Id;
     //  $sP->save();
     //}
     $simulation->save();
     return $simulation;
 }