Пример #1
0
        private void OnCalculatePlan()
        {
            patient.BeginModifications();
            Course            course_temp = patient.AddCourse();
            ExternalPlanSetup plan_temp   = course_temp.
                                            AddExternalPlanSetup(patient.StructureSets.FirstOrDefault());
            ExternalBeamMachineParameters exBeamParams = new ExternalBeamMachineParameters(
                "HESN10",
                "6X",
                600,
                "STATIC",
                null);

            foreach (string fs in FieldSizes.Split(';'))
            {
                double fsd = Convert.ToDouble(fs);
                plan_temp.AddStaticBeam(exBeamParams,
                                        new VRect <double>(-fsd / 2 * 10, -fsd / 2 * 10, fsd / 2 * 10, fsd / 2 * 10),
                                        0,
                                        0,
                                        0,
                                        new VVector(0, -200, 0));
            }
            plan_temp.SetPrescription(1, new DoseValue(100, DoseValue.DoseUnit.cGy), 1);
            plan_temp.CalculateDose();

            _app.SaveModifications();
            AddCourses(patient);
            SelectedCourse = course_temp.Id;
            SelectedPlan   = plan_temp.Id;
        }
Пример #2
0
        public void Execute(ScriptContext context /*, System.Windows.Window window, ScriptEnvironment environment*/)
        {
            // TODO : Add here the code that is called when the script is launched from Eclipse.
            Patient p = context.Patient;

            p.BeginModifications();//this line for scripting automation.

            //find the ctv in the structures.
            Structure ctv = context.StructureSet.Structures.First(o => o.DicomType == "CTV");
            //create on the structureset a PTV from the ctv.
            Structure ptv = context.StructureSet.AddStructure("PTV", "PTVAuto");

            ptv.SegmentVolume = ctv.Margin(8);

            //create a new plan.
            Course c_auto = p.AddCourse();

            c_auto.Id = "Course_Auto";
            ExternalPlanSetup plan = c_auto.AddExternalPlanSetup(context.StructureSet);

            plan.Id = "Plan_Auto";

            //create the fields.
            //define the externalBeam Parameters
            ExternalBeamMachineParameters ebmp = new ExternalBeamMachineParameters(
                "TrueBeam",
                "6X",
                600,
                "STATIC",
                null);

            //set gantry angles
            double[] g_angles = new double[] { 270, 0, 90, 180 };
            foreach (double ga in g_angles)
            {
                //add a new beam with intial parametres
                Beam b = plan.AddMLCBeam(
                    ebmp,
                    new float[2, 60],
                    new VRect <double>(-10, -10, 10, 10),
                    0,
                    ga,
                    0,
                    ptv.CenterPoint);
                //fit the MLC to the structure outline of the PTV.
                b.FitMLCToStructure(new FitToStructureMargins(10),
                                    ptv,
                                    false,
                                    JawFitting.FitToRecommended,
                                    OpenLeavesMeetingPoint.OpenLeavesMeetingPoint_Middle,
                                    ClosedLeavesMeetingPoint.ClosedLeavesMeetingPoint_Center);
            }

            //Calculate Dose
            plan.CalculateDose();
            //Set Normalization
            plan.PlanNormalizationValue = plan.Beams.Count() * 100;
            //Set Prescription.
            plan.SetPrescription(30, new DoseValue(180, DoseValue.DoseUnit.cGy), 1);
        }
Пример #3
0
        public Patient abrirPaciente(string ID)
        {
            VMS.TPS.Common.Model.API.Application app = VMS.TPS.Common.Model.API.Application.CreateApplication(null, null);
            Patient paciente = app.OpenPatientById(ID);

            paciente.BeginModifications();
            return(paciente);
        }
Пример #4
0
        static void Execute(Application app)
        {
            Patient pat = app.OpenPatientById("exercise5-0");

            try
            {
                pat.BeginModifications();

                const string courseId = "AutoPlanned";
                Course       course   = pat.Courses.Where(o => o.Id == courseId).SingleOrDefault();
                if (course == null)
                {
                    if (course == null)
                    {
                        course    = pat.AddCourse();
                        course.Id = courseId;
                    }
                }
                StructureSet ss = pat.StructureSets.First(x => x.Id == "CT_1");
                if (course.CanAddPlanSetup(ss))
                {
                    // find the PTV
                    Structure ptv = ss.Structures.First(x => x.Id == "PTV");
                    // Put isocenter to the center of the ptv.
                    var isocenter = ptv.CenterPoint;
                    //add plan and beams
                    ExternalPlanSetup plan = course.AddExternalPlanSetup(ss);
                    plan.SetPrescription(5, new DoseValue(2, DoseValue.DoseUnit.Gy), 1.0);
                    Beam g0   = plan.AddMLCBeam(MachineParameters, null, new VRect <double>(-10, -10, 10, 10), 0, 0, 0, isocenter);
                    Beam g180 = plan.AddMLCBeam(MachineParameters, null, new VRect <double>(-10, -10, 10, 10), 0, 180.0, 0, isocenter);

                    // fit beam jaws and MLC
                    bool useAsymmetricXJaw = true, useAsymmetricYJaws = true, optimizeCollimatorRotation = true;
                    g0.FitCollimatorToStructure(new FitToStructureMargins(0), ptv, useAsymmetricXJaw, useAsymmetricYJaws, optimizeCollimatorRotation);

                    FitToStructureMargins    margins = new FitToStructureMargins(1);
                    JawFitting               jawFit  = JawFitting.FitToRecommended;
                    OpenLeavesMeetingPoint   olmp    = OpenLeavesMeetingPoint.OpenLeavesMeetingPoint_Middle;
                    ClosedLeavesMeetingPoint clmp    = ClosedLeavesMeetingPoint.ClosedLeavesMeetingPoint_BankOne;
                    g0.FitMLCToStructure(margins, ptv, optimizeCollimatorRotation, jawFit, olmp, clmp);
                    g180.FitMLCToStructure(margins, ptv, optimizeCollimatorRotation, jawFit, olmp, clmp);

                    // format the field ids
                    g0.Id = string.Format("g{0}c{1}",
                                          g0.GantryAngleToUser(g0.ControlPoints[0].GantryAngle),
                                          g0.CollimatorAngleToUser(g0.ControlPoints[0].CollimatorAngle)
                                          );
                    g180.Id = string.Format("g{0}c{1}",
                                            g180.GantryAngleToUser(g180.ControlPoints[0].GantryAngle),
                                            g180.CollimatorAngleToUser(g180.ControlPoints[0].CollimatorAngle)
                                            );
                    app.SaveModifications();
                }
            }
            finally {
                app.ClosePatient();
            }
        }
Пример #5
0
        public static PlanSetup CopyAndMakeNewIscPlan(double thresholdPc, string newPlanId, Course course, PlanSetup originalPlanSetup, int numberOfSteps = 1)
        {
            if (course.PlanSetups.Where(p => p.Id == newPlanId).Count() > 0)
            {
                throw new ArgumentException($"{newPlanId} already exists");
            }

            Patient patient = originalPlanSetup.Course.Patient;

            patient.BeginModifications();

            CopyPlan.CopyDynamicMlcPlan(newPlanId, course, (ExternalPlanSetup)originalPlanSetup);
            PlanSetup newPlanSetup = Esapi.IscFluenceOptimizer.Helpers.GetPlanSetup(course, newPlanId);

            // Get Body and Maximum dose
            var query = from s in originalPlanSetup.StructureSet.Structures where (s.Id == "BODY" || s.Id == "Body") select s;

            if (query.Count() != 1)
            {
                throw new InvalidOperationException("No BODY in StructureSet");
            }
            var     body          = query.First();
            double  binWidth      = 0.001;
            DVHData dvh           = originalPlanSetup.GetDVHCumulativeData(body, DoseValuePresentation.Relative, VolumePresentation.Relative, binWidth);
            double  maximumDosePc = dvh.MaxDose.Dose;

            int numberOfMainBeams = originalPlanSetup.Beams.Count();

            if (maximumDosePc <= thresholdPc)
            {
                throw new InvalidOperationException($"Maximum dose ({maximumDosePc}) is less than threholdPc ({thresholdPc})");
            }

            double thresholdPcStep = (maximumDosePc - thresholdPc) / numberOfSteps;

            for (int i = 0; i < numberOfSteps; i++)
            {
                double thresholdPcTmp      = thresholdPc + thresholdPcStep * (numberOfSteps - 1 - i);
                var    iscFluenceOptimizer = new IscFluenceOptimizer(newPlanSetup, thresholdPcTmp);

                foreach (var beam in iscFluenceOptimizer.BeamInfos)
                {
                    var newFluence = beam.GetReducedFluence();
                    beam.BeamEsapi.SetOptimalFluence(newFluence);
                }

                var externalPlanSetup = (ExternalPlanSetup)newPlanSetup;

                externalPlanSetup.CalculateLeafMotions(new LMCVOptions(true));
                externalPlanSetup.CalculateDose();
                var newDvh           = newPlanSetup.GetDVHCumulativeData(body, DoseValuePresentation.Relative, VolumePresentation.Relative, binWidth);
                var newMaximumDosePc = newDvh.MaxDose.Dose;
            }

            return(newPlanSetup);
        }
Пример #6
0
        public void Execute(ScriptContext context, Window MainWin)
        {
            // Open current patient
            Patient currPt = context.Patient;

            // If there's no selected patient, throw an exception
            if (currPt == null)
            {
                throw new ApplicationException("Please open a patient before using this script.");
            }
            currPt.BeginModifications();

            // Open current course
            Course currCrs = context.Course;

            // If there's no selected course, throw an exception
            if (currCrs == null)
            {
                throw new ApplicationException("Please select at least one course before using this script.");
            }

            // Open current plan
            ExternalPlanSetup currPln = context.ExternalPlanSetup;

            // If there's no selected plan, throw an exception
            if (currPln == null)
            {
                throw new ApplicationException("Please creat a plan with one beam with the preferred machine and energy.");
            }

            // Check if plan is approved
            if (currPln.ApprovalStatus != PlanSetupApprovalStatus.UnApproved)
            {
                throw new ApplicationException("Please unapprove plan before using this script.");
            }

            // Open beam
            Beam currBm = currPln.Beams.FirstOrDefault();

            if (currBm == null)
            {
                throw new ApplicationException("Please insert one beam with the preferred machine and energy.");
            }

            // Call WPF Win
            var MainWinCtr = new createMLCPicture.MainWindow(context);

            MainWin.Content    = MainWinCtr;
            MainWin.Title      = "Create MLC Picture";
            MainWin.Width      = 440;
            MainWin.Height     = 240;
            MainWin.ResizeMode = ResizeMode.NoResize;
        }
        public void Execute(ScriptContext context /*, System.Windows.Window window, ScriptEnvironment environment*/)
        {
            Patient p = context.Patient;

            if (p == null)
            {
                throw new ApplicationException("Please load a patient");
            }

            ExternalPlanSetup plan = context.ExternalPlanSetup;

            if (plan == null)
            {
                throw new ApplicationException("Please load an external beam plan that will be verified.");
            }

            p.BeginModifications();
            // TODO: look whether the phantom scan exists in this patient before copying it
            StructureSet ssQA = p.CopyImageFromOtherPatient(QAPatientID, QAStudyID, QAImageID);

            // Get or create course with Id 'IMRTQA'
            const string courseId = "IMRTQA";
            Course       course   = p.Courses.Where(o => o.Id == courseId).SingleOrDefault();

            if (course == null)
            {
                course    = p.AddCourse();
                course.Id = courseId;
            }
#if false
            // Create an individual verification plan for each field.
            foreach (var beam in plan.Beams)
            {
                CreateVerificationPlan(course, new List <Beam> {
                    beam
                }, plan, ssQA, beam.Id, calculateDose: false);
            }
#endif
            // Create a verification plan that contains all fields (Composite).
            ExternalPlanSetup verificationPlan = CreateVerificationPlan(course, plan.Beams, plan, ssQA, "Composite", calculateDose: true);

            //ExternalPlanSetup verificationPlan = course.AddExternalPlanSetupAsVerificationPlan(ssQA, plan);

            // nagivate back from verificationPlan to verified plan
            PlanSetup verifiedPlan = verificationPlan.VerifiedPlan;
            if (plan != verifiedPlan)
            {
                MessageBox.Show(string.Format("ERROR! verified plan {0} != loaded plan {1}", verifiedPlan.Id
                                              , plan.Id));
            }
            MessageBox.Show(string.Format("Success - verification plan {0} created in course {1}.", verificationPlan.Id, course.Id));
        }
Пример #8
0
 public void Run(
     User user,
     Patient patient,
     Image image,
     StructureSet structureSet,
     PlanSetup planSetup,
     IEnumerable <PlanSetup> planSetupsInScope,
     IEnumerable <PlanSum> planSumsInScope,
     Window mainWindow)
 {
     // Your main code now goes here
     patient.BeginModifications();
 }
Пример #9
0
        public void Execute(ScriptContext context)
        {
            //Assembly assembly = Assembly.LoadFrom(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319");
            //Type type = assembly.GetType(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319.DialogBox");


            //Is patient loaded?
            if (context.Patient == null)
            {
                throw new System.ArgumentException("Please load a patient and try again.");
            }
            //Is there a structure set?
            if (context.StructureSet == null)
            {
                throw new System.ArgumentException("Failed to find a structure set for patient " + context.Patient.Name);
            }
            //Is there a course?
            if (context.Course == null)
            {
                throw new System.ArgumentException("Please check that a course has been selected for " + context.Patient.Name);
            }

            PlanSetup ps = context.PlanSetup;
            Patient   p  = context.Patient;

            p.BeginModifications();
            StructureSet ss = context.StructureSet;

            foreach (Structure structure in ss.Structures.ToList())
            {
                if (structure.Name.ToLower().Contains("subsegment"))
                {
                    ss.RemoveStructure(structure);
                }
            }
            MainForm mainForm = new MainForm(ref context);

            System.Windows.Forms.Application.Run(mainForm);
            //System.Windows.System.Windows.MessageBox.Show("Hello", "input", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information, System.Windows.MessageBoxResult.OK);
        }
Пример #10
0
 public static Course AddCourse(Patient patient, string courseId)
 {
     patient.BeginModifications();
     try
     {
         var res = patient.Courses.Where(c => c.Id == courseId);
         if (res.Any())
         {
             var oldCourse = res.Single();
             patient.RemoveCourse(oldCourse);
         }
         var course = patient.AddCourse();
         course.Id = courseId;
         return(course);
     }
     catch
     {
         var course = patient.AddCourse();
         course.Id = courseId;
         return(course);
     }
 }
Пример #11
0
        public void Execute(ScriptContext context, System.Windows.Window window /*, ScriptEnvironment environment*/)
        {
            // TODO : Add here the code that is called when the script is launched from Eclipse.
            //access the patient
            Patient p = context.Patient;

            p.BeginModifications();
            //access the course and plan.
            Course            c  = context.Course;
            ExternalPlanSetup ps = context.ExternalPlanSetup;
            var mainWindow       = new ManualControlPoints.MainWindow();



            //set window properties.
            window.Width   = mainWindow.Width + 10;
            window.Height  = mainWindow.Height + 5;
            window.Content = mainWindow;
            //send data to mainwindow.
            mainWindow.p  = p;
            mainWindow.c  = c;
            mainWindow.ps = ps;
        }
Пример #12
0
 private void OnCalculatePlan()
 {
     if (Patient != null)
     {
         Patient.BeginModifications();
         var      localCourse = Patient.AddCourse();
         var      localPlan   = localCourse.AddExternalPlanSetup(Patient.StructureSets.First());
         double[] fieldSizes  = new double[] { 30, 40, 50, 177, 200 };
         ExternalBeamMachineParameters beamP = new ExternalBeamMachineParameters("HESN10", "6X", 600, "STATIC", null);
         foreach (var fs in fieldSizes)
         {
             var localBeam = localPlan.AddStaticBeam(beamP,
                                                     new VRect <double>(-1.0 * fs / 2.0, -1.0 * fs / 2.0, fs / 2.0, fs / 2.0),
                                                     0,
                                                     0,
                                                     0,
                                                     new VVector(0, -200, 0));
         }
         localPlan.SetPrescription(1, new DoseValue(100, DoseValue.DoseUnit.cGy), 1.0);
         localPlan.CalculateDose();
         _app.SaveModifications();
     }
 }
Пример #13
0
        public void Execute(ScriptContext context /*, System.Windows.Window window*/)
        {
            Patient patient = context.Patient;

            if (patient == null)
            {
                throw new ApplicationException("Please load a patient.");
            }

            // Get active structureset
            StructureSet ss = context.StructureSet;

            if (ss == null)
            {
                throw new ApplicationException("Please load a structure set.");
            }

            // Check that unique body structure, PTV and Rectum structures exist
            Structure body   = ss.Structures.Where(o => o.Id == "BODY").FirstOrDefault();
            Structure ptv    = ss.Structures.Where(o => o.Id == "PTV").FirstOrDefault();
            Structure rectum = ss.Structures.Where(o => o.Id == "Rectum1").FirstOrDefault();

            if (body == null || ptv == null || rectum == null)
            {
                throw new ApplicationException(string.Format("Cannot find required structures (BODY, PTV, Rectum) from Structureset '{0}'", ss.Id));
            }

            // Enable modifications
            patient.BeginModifications();

            // Get or create course with Id 'Superplan'
            const string courseId = "Superplan";
            Course       course   = patient.Courses.Where(o => o.Id == courseId).SingleOrDefault();

            if (course == null)
            {
                course    = patient.AddCourse();
                course.Id = courseId;
            }

            // Create a new plan
            ExternalPlanSetup plan         = course.AddExternalPlanSetup(ss);
            int       fractions            = 20;
            double    prescribedPercentage = 1.0;
            DoseValue fractiondose         = new DoseValue(2.50, DoseValue.DoseUnit.Gy); // TODO: if needed change to cGy to match your system configuration

            plan.UniqueFractionation.SetPrescription(fractions, fractiondose, prescribedPercentage);

            // Add fields
            const int nfields = 5;
            ExternalBeamMachineParameters parameters = new ExternalBeamMachineParameters("Varian 23EX", "6X", 600, "STATIC", null); // TODO: change machine id to yours
            VVector isocenter = ptv.CenterPoint;

            for (int n = 0; n < nfields; n++)
            { // add a 10 cm x 10 cm field
                Beam beam = plan.AddStaticBeam(parameters, new VRect <double>(-50, -50, 50, 50), 0, Math.Round(360.0 / nfields * n, 0), 0, isocenter);
            }
            // end of first part.
            MessageBox.Show("Plan created, open course SuperPlan, Choose Plan1 to view results.", "Varian Developer");

            // Set optimization constraints
            OptimizationSetup optimizationSetup = plan.OptimizationSetup;

            optimizationSetup.AddPointObjective(ptv, OptimizationObjectiveOperator.Lower, new DoseValue(49.50, DoseValue.DoseUnit.Gy), 100, 100.0);
            optimizationSetup.AddPointObjective(ptv, OptimizationObjectiveOperator.Upper, new DoseValue(52.00, DoseValue.DoseUnit.Gy), 0, 100.0);
            optimizationSetup.AddPointObjective(rectum, OptimizationObjectiveOperator.Upper, new DoseValue(20.00, DoseValue.DoseUnit.Gy), 40.0, 100.0);
            MessageBox.Show("Plan '" + plan.Id + "' in course '" + course.Id + "' for patient '" + patient.Id + "' has been created");

            // optimize for 30 iterations
            if (!plan.Optimize(30).Success)
            {
                MessageBox.Show("Optimization failed", "Varian Developer", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // run LMC
            if (!plan.CalculateLeafMotions().Success)
            {
                MessageBox.Show("LMC failed", "Varian Developer", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // calculate final dose
            CalculationResult doseCalc = plan.CalculateDose();

            if (!doseCalc.Success)
            {
                MessageBox.Show("Dose calculation failed, logs shown next.", "Varian Developer", MessageBoxButton.OK, MessageBoxImage.Error);
                // write calculate logs to a file and show them to the user.
                string filename = writeCalculationLogs(plan);
                // 'Start' generated TXT file to launch Notepad window
                System.Diagnostics.Process.Start(filename);
                // Sleep for a few seconds to let Excel window start
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3));
                return;
            }

            MessageBox.Show("Done");
        }
Пример #14
0
        public void Execute(ScriptContext context /*, System.Windows.Window window, ScriptEnvironment environment*/)
        {
            if (context.Patient != null)
            {
                MessageBox.Show("Patient id is " + context.Patient.Id);
                Patient patient = context.Patient;
                patient.BeginModifications();
                foreach (IonBeam ionBeam in context.IonPlanSetup.IonBeams)
                {
                    IonBeamParameters             beamParameters  = ionBeam.GetEditableParameters();
                    IonControlPointPairCollection layers          = beamParameters.IonControlPointPairs;
                    List <List <double> >         allLayersParams = new List <List <double> >();

                    double minEnergy = 70;
                    double maxEnergy = 250;
                    double spotWeightLowerLimitAtMinEnergy = 0.1;
                    double spotWeightLowerLimitAtMaxEnergy = 2;
                    double spotWeightUpperLimitAtMinEnergy = 15;
                    double spotWeightUpperLimitAtMaxEnergy = 30;

                    foreach (IonControlPointPair layer in layers)
                    {
                        List <double> thisLayerParams               = new List <double>();
                        double        energyForThisLayer            = layer.NominalBeamEnergy;
                        double        minSpotWeightFromOptimization = 1000;
                        double        maxSpotWeightFromOptimization = 0;
                        double        minSpotWeightAfterProcessing  = 1000;
                        double        maxSpotWeightAfterProcessing  = 0;

                        double spotWeightLowerLimitForThisLayer = spotWeightLowerLimitAtMinEnergy + (spotWeightLowerLimitAtMaxEnergy - spotWeightLowerLimitAtMinEnergy) * (energyForThisLayer - minEnergy) / (maxEnergy - minEnergy);
                        double spotWeightUpperLimitForThisLayer = spotWeightUpperLimitAtMinEnergy + (spotWeightUpperLimitAtMaxEnergy - spotWeightUpperLimitAtMinEnergy) * (energyForThisLayer - minEnergy) / (maxEnergy - minEnergy);

                        foreach (IonSpotParameters spot in layer.RawSpotList)
                        {
                            if (spot.Weight < minSpotWeightFromOptimization)
                            {
                                minSpotWeightFromOptimization = spot.Weight;
                            }
                            if (spot.Weight > maxSpotWeightFromOptimization)
                            {
                                maxSpotWeightFromOptimization = spot.Weight;
                            }

                            if (spot.Weight < spotWeightLowerLimitForThisLayer)
                            {
                                if (spot.Weight < 0.5 * spotWeightLowerLimitForThisLayer)
                                {
                                    spot.Weight = 0;
                                }
                                else
                                {
                                    spot.Weight = (float)spotWeightLowerLimitForThisLayer;
                                }
                            }

                            if (spot.Weight > spotWeightUpperLimitForThisLayer)
                            {
                                spot.Weight = (float)spotWeightUpperLimitForThisLayer;
                            }

                            if (spot.Weight < minSpotWeightAfterProcessing)
                            {
                                minSpotWeightAfterProcessing = spot.Weight;
                            }
                            if (spot.Weight > maxSpotWeightAfterProcessing)
                            {
                                maxSpotWeightAfterProcessing = spot.Weight;
                            }
                        }

                        thisLayerParams.Add(energyForThisLayer);
                        thisLayerParams.Add(minSpotWeightFromOptimization);
                        thisLayerParams.Add(maxSpotWeightFromOptimization);
                        thisLayerParams.Add(minSpotWeightAfterProcessing);
                        thisLayerParams.Add(maxSpotWeightAfterProcessing);
                        allLayersParams.Add(thisLayerParams);
                    }

                    ionBeam.ApplyParameters(beamParameters);
                    string report = "";
                    report += "Energy Raw min Raw max PP min PP max\n";
                    foreach (List <double> line in allLayersParams)
                    {
                        report += String.Format("{0,8:F1} {1,12:f2} {2,13:f2} {3,10:f2} {4,10:f2} \n", line[0], line[1], line[2], line[3], line[4]);
                    }
                    MessageBox.Show(report);
                }
            }
        }
Пример #15
0
        public void Execute(ScriptContext context /*, System.Windows.Window window, ScriptEnvironment environment*/)
        {
            //USER INPUT
            double s_ssd = 100;                                         // SSD
            string cmach = "HESN5";                                     // MACHINE

            string[] erg       = new string[] { "6X", "10X" };          // ENERGY LIST
            double[] jaw_sizes = new double[] { 4, 8, 10, 20 };         // FIELD SIZE LIST

            // Define local _patient, could be pointed to UI
            Patient _patient = context.Patient;

            _patient.BeginModifications();

            // SET STRUCTURE SET
            StructureSet _structureSet = _patient.StructureSets.FirstOrDefault();

            // DETERMINE EXTERNAL STRUCTURE
            var bst     = _structureSet.Structures.First(x => x.DicomType == "EXTERNAL");
            var bst_mgb = bst.MeshGeometry.Bounds;

            // CREATE NEW COURSE AND NAME IT
            Course C_Auto = _patient.AddCourse();

            C_Auto.Id = string.Format("C_{0}_{1}SSD", cmach, s_ssd.ToString());

            // LOOP THROUGH ENERGIES PROVIDED BY USER, CREATE A PLAN FOR EACH ENERGY
            foreach (var evar in erg)
            {
                // CREATE PLAN
                ExternalPlanSetup eps = C_Auto.AddExternalPlanSetup(_structureSet);

                // SET PRESCRIPTION
                eps.SetPrescription(1, new DoseValue(100, "cGy"), 1);
                eps.Id = evar.ToString();

                // SET FIELD PARAMETERS
                ExternalBeamMachineParameters ebmp = new ExternalBeamMachineParameters(cmach, evar, 600, "STATIC", null);

                // LOOP THROUGH FIELD SIZES, CREATE A BEAM FOR EACH FIELD SIZE
                foreach (double js in jaw_sizes)
                {
                    // SET JAW POSITION BASED ON USER FIELD SIZES - (ASSUMES ALL FIELDS ARE SYMMETRIC)
                    double xjaw = js * 10;
                    double yjaw = js * 10;

                    // DEFINE BEAM PARAMETERS - (ASSUMES NO ANGLES)
                    double coll    = 0;
                    double gant_a  = 0;
                    double couch_a = 0;

                    // SET ISOCENTER BASED ON USER SSD
                    double  iso_x  = 0;
                    double  iso_y  = -10 * (Math.Round(bst_mgb.SizeY / 10) + Math.Round(bst_mgb.Location.Y / 10) + (s_ssd - 100));
                    double  iso_z  = 0;
                    VVector isovec = new VVector(iso_x, iso_y, iso_z);

                    // CREATE BEAM
                    Beam b = eps.AddStaticBeam(
                        ebmp,
                        new VRect <double>(-0.5 * xjaw, -0.5 * yjaw, 0.5 * xjaw, 0.5 * yjaw),
                        coll, gant_a, couch_a, isovec);

                    // SET BEAM ID
                    b.Id = String.Format("{0}_{1:F1}x{2:F1}", evar, xjaw / 10, yjaw / 10);
                }
                // CALCULATE DOSE
                eps.CalculateDose();
            }
            MessageBox.Show("DONE");
        }
Пример #16
0
        private void startOpt_Click(object sender, RoutedEventArgs e)
        {
            //start the optimization loop
            //checks
            if (opt_parameters.Children.Count == 0)
            {
                MessageBox.Show("No optimization parameters present to assign to the VMAT plan!");
                return;
            }
            if (!int.TryParse(numOptLoops.Text, out int numOptimizations))
            {
                MessageBox.Show("Error! Invalid input for number of optimization loops! \nFix and try again.");
                return;
            }
            //get an instnace of the VMAT TBI plan
            ExternalPlanSetup plan = getPlan();

            if (plan == null)
            {
                return;
            }

            if (!double.TryParse(targetNormTB.Text, out double planNorm))
            {
                MessageBox.Show("Error! Target normalization is NaN \nFix and try again.");
                return;
            }
            if (planNorm < 0.0 || planNorm > 100.0)
            {
                MessageBox.Show("Error! Target normalization is is either < 0% or > 100% \nExiting!");
                return;
            }

            //get constraints
            //same code as from the binary plug in
            List <Tuple <string, string, double, double, int> > optParametersList = new List <Tuple <string, string, double, double, int> > {
            };
            string structure      = "";
            string constraintType = "";
            double dose           = -1.0;
            double vol            = -1.0;
            int    priority       = -1;
            int    txtbxNum       = 1;
            bool   firstCombo     = true;
            bool   headerObj      = true;

            foreach (object obj in opt_parameters.Children)
            {
                if (!headerObj)
                {
                    foreach (object obj1 in ((StackPanel)obj).Children)
                    {
                        if (obj1.GetType() == typeof(ComboBox))
                        {
                            if (firstCombo)
                            {
                                structure  = (obj1 as ComboBox).SelectedItem.ToString();
                                firstCombo = false;
                            }
                            else
                            {
                                constraintType = (obj1 as ComboBox).SelectedItem.ToString();
                            }
                        }
                        else if (obj1.GetType() == typeof(TextBox))
                        {
                            if (!string.IsNullOrWhiteSpace((obj1 as TextBox).Text))
                            {
                                if (txtbxNum == 1)
                                {
                                    double.TryParse((obj1 as TextBox).Text, out vol);
                                }
                                else if (txtbxNum == 2)
                                {
                                    double.TryParse((obj1 as TextBox).Text, out dose);
                                }
                                else
                                {
                                    int.TryParse((obj1 as TextBox).Text, out priority);
                                }
                            }
                            txtbxNum++;
                        }
                    }
                    if (structure == "--select--" || constraintType == "--select--")
                    {
                        MessageBox.Show("Error! \nStructure or Sparing Type not selected! \nSelect an option and try again");
                        return;
                    }
                    else if (dose == -1.0 || vol == -1.0 || priority == -1.0)
                    {
                        MessageBox.Show("Error! \nDose, volume, or priority values are invalid! \nEnter new values and try again");
                        return;
                    }
                    else
                    {
                        optParametersList.Add(Tuple.Create(structure, constraintType, dose, vol, priority));
                    }
                    firstCombo = true;
                    txtbxNum   = 1;
                    dose       = -1.0;
                    vol        = -1.0;
                    priority   = -1;
                }
                else
                {
                    headerObj = false;
                }
            }

            if (optParametersList.Where(x => x.Item1.ToLower().Contains("flash")).Any())
            {
                useFlash = true;
            }

            //does the user want to run the initial dose coverage check?
            runCoverageCheck = runCoverageCk.IsChecked.Value;
            //does the user want to run one additional optimization to reduce hotspots?
            runOneMoreOpt = runAdditionalOpt.IsChecked.Value;
            //does the user want to copy and save each plan after it's optimized (so the user can choose between the various plans)?
            copyAndSavePlanItr = copyAndSave.IsChecked.Value;

            //start the optimization loop (all saving to the database is performed in the progressWindow class)
            pi.BeginModifications();
            optimizationLoop optLoop = new optimizationLoop(plan, optParametersList, planNorm, numOptimizations, scleroTrial, runCoverageCheck, runOneMoreOpt, copyAndSavePlanItr, useFlash, MLCmodel, app);
        }
Пример #17
0
        static void Planning(Application curapp, Patient curpat, StructureSet curstructset, List <Tuple <string, string, float, string> > TargetStructures, List <string> AllowedNonTargetStructures, float RxDose, int NFractions)
        {
            curpat.BeginModifications();

            string IDofptv_low  = string.Empty;
            string IDofptv_high = string.Empty; //

            StringBuilder sb = new StringBuilder();

            //Check structure nameing
            sb.AppendLine("Check Structure Naming");
            sb.AppendLine("Structure ID        \tIs Standard Name?");
            foreach (Structure curstruct in curstructset.Structures.OrderBy(x => x.Id))
            {
                if (curstruct.DicomType == "PTV" | curstruct.DicomType == "CTV" | curstruct.DicomType == "GTV")
                {
                    if (TargetStructures.Where(x => x.Item1 == curstruct.Id).Any() || TargetStructures.Where(x => curstruct.DicomType.ToString() + "_" + x.Item3 + (x.Item4 == "Gy" ? "00" : string.Empty) == curstruct.Id).Any())
                    {
                        sb.AppendLine(curstruct.Id.PadRight(curstruct.Id.Length < 20 ? 20 - curstruct.Id.Length : 0) + "\tYes");
                    }
                    else
                    {
                        sb.AppendLine(curstruct.Id.PadRight(curstruct.Id.Length < 20 ? 20 - curstruct.Id.Length : 0) + "\tNo");
                    }
                }
                else
                {
                    if (AllowedNonTargetStructures.Where(x => x == curstruct.Id).Any() || curstruct.Id.ToString().StartsWith("z"))
                    {
                        sb.AppendLine(curstruct.Id.PadRight(curstruct.Id.Length < 20 ? 20 - curstruct.Id.Length : 0) + "\tYes");
                    }
                    else
                    {
                        sb.AppendLine(curstruct.Id.PadRight(curstruct.Id.Length < 20 ? 20 - curstruct.Id.Length : 0) + "\tNo");
                    }
                }
            }
            sb.AppendLine();
            sb.AppendLine("Press OK to continue with creating optimization structures");
            System.Windows.MessageBox.Show(sb.ToString());



            //Create optimization structures
            if (TargetStructures.Where(x => x.Item1 == "PTV_Low").Any())
            {
                IDofptv_low = TargetStructures.Where(x => x.Item1 == "PTV_Low").Select(x => x.Item2).First();                                                      //Get the ID of the structure identified as PTV_Low
            }
            if (TargetStructures.Where(x => x.Item1 == "PTV_High").Any())
            {
                IDofptv_high = TargetStructures.Where(x => x.Item1 == "PTV_High").Select(x => x.Item2).First();                                                      //Get the ID of the structure identified as PTV_High
            }
            Structure ptv_low  = null;
            Structure ptv_high = null;


            //Check that PT_High structure exists, issue warning if it does not.
            if (curstructset.Structures.Where(x => x.Id == IDofptv_low).Any())
            {
                ptv_low = curstructset.Structures.Where(x => x.Id == IDofptv_low).First();
            }
            else
            {
                System.Windows.MessageBox.Show("Did not find a PTV_High Structure. Fix before proceeding");
            }

            //Check that PT_Low structure exists, issue warning if it does not.
            if (curstructset.Structures.Where(x => x.Id == IDofptv_high).Any())
            {
                ptv_high = curstructset.Structures.Where(x => x.Id == IDofptv_high).First();
            }
            else
            {
                System.Windows.MessageBox.Show("Did not find a PTV_Low Structure. Fix before proceeding");
            }


            //Creation of optimization structures. If a copy already exitst delete it first.

            //Optimization structure for the PTV_Low volume is named zPTV_Low^Opt
            if (curstructset.Structures.Where(x => x.Id.Contains("zPTV_Low^Opt")).Any())
            {
                curstructset.RemoveStructure(curstructset.Structures.Where(x => x.Id.Contains("zPTV_Low^Opt")).First());
            }
            Structure zptvlowopt = curstructset.AddStructure("ORGAN", "zPTV_Low^Opt");

            //Dose limiting annulus (DLA) structure is used to make the prescribed dose conformal. DLA for PTV_Low is named zDLA_Low
            if (curstructset.Structures.Where(x => x.Id.Contains("zDLA__Low")).Any())
            {
                curstructset.RemoveStructure(curstructset.Structures.Where(x => x.Id.Contains("zDLA__Low")).First());
            }
            Structure zdlalow = curstructset.AddStructure("ORGAN", "zDLA__Low");

            //Optimization structure for the PTV_High volume is named zPTV_High^Opt
            if (curstructset.Structures.Where(x => x.Id.Contains("zPTV_High^Opt")).Any())
            {
                curstructset.RemoveStructure(curstructset.Structures.Where(x => x.Id.Contains("zPTV_High^Opt")).First());
            }
            Structure zptvhighopt = curstructset.AddStructure("ORGAN", "zPTV_High^Opt");


            //Dose limiting annulus (DLA) structure is used to make the prescribed dose conformal. DLA for PTV_High is named zDLA_High
            if (curstructset.Structures.Where(x => x.Id.Contains("zDLA__High")).Any())
            {
                curstructset.RemoveStructure(curstructset.Structures.Where(x => x.Id.Contains("zDLA__High")).First());
            }
            Structure zdlahigh = curstructset.AddStructure("ORGAN", "zDLA__High");

            //Make zPTV_High^Opt from PTV_High and boolean out the rectum
            zptvhighopt.SegmentVolume = ptv_high.Margin(0.0f);
            zptvhighopt.SegmentVolume = zptvhighopt.Sub(curstructset.Structures.Where(x => x.Id.Contains("Rectum")).Single());//Boolean the Rectum out of the high dose ptv optimization structure


            //Make zPTV_Low^Opt from PTV_Low and boolean out the PTV_High structure
            zptvlowopt.SegmentVolume = ptv_low.Margin(0.0f);
            zptvlowopt.SegmentVolume = zptvlowopt.Sub(ptv_high.Margin(1.0f));//Boolean the ptv_high out of ptv_low optimization structure


            //Make a dose limiting annulus arround the low dose ptv optimization structure
            zdlalow.SegmentVolume = zptvlowopt.SegmentVolume;
            zdlalow.SegmentVolume = zdlalow.Margin(10.0f);
            zdlalow.SegmentVolume = zdlalow.Sub(zptvlowopt.Margin(1.0f));
            zdlalow.SegmentVolume = zdlalow.Sub(zptvhighopt.Margin(5.0f));

            //Make a dose limiting annulus arround the high dose ptv optimization structure
            zdlahigh.SegmentVolume = zptvhighopt.SegmentVolume;
            zdlahigh.SegmentVolume = zdlahigh.Margin(10.0f);
            zdlahigh.SegmentVolume = zdlahigh.Sub(zptvhighopt.Margin(1.0f));

            sb = new StringBuilder();
            sb.AppendLine("Done with creating optimization strutures");
            sb.AppendLine("Click OK to proceed with setting up course and VMAT plan");
            System.Windows.MessageBox.Show(sb.ToString());

            //Add course
            Course curcourse;

            if (curpat.Courses.Where(x => x.Id == "AutoPlan").Any())
            {
                curcourse = curpat.Courses.Where(x => x.Id == "AutoPlan").Single();
            }
            else
            {
                curcourse    = curpat.AddCourse();
                curcourse.Id = "AutoPlan";
            }

            //Remove PlanSetup if it exists then create new plan setup

            if (curcourse.PlanSetups.Where(x => x.Id == "AutoPlanVMAT").Any())
            {
                curcourse.RemovePlanSetup(curcourse.PlanSetups.Where(x => x.Id == "AutoPlanVMAT").Single());
            }
            ExternalPlanSetup cureps = curcourse.AddExternalPlanSetup(curstructset);

            cureps.Id = "AutoPlanVMAT";



            //Add VMAT Beams
            VVector isocenter = new VVector(Math.Round(ptv_high.CenterPoint.x / 10.0f) * 10.0f, Math.Round(ptv_high.CenterPoint.y / 10.0f) * 10.0f, Math.Round(ptv_high.CenterPoint.z / 10.0f) * 10.0f);
            ExternalBeamMachineParameters ebmp = new ExternalBeamMachineParameters("Truebeam", "6X", 600, "ARC", null);
            Beam VMAT1 = cureps.AddArcBeam(ebmp, new VRect <double>(-100, -100, 100, 100), 30, 181, 179, GantryDirection.Clockwise, 0, isocenter);
            Beam VMAT2 = cureps.AddArcBeam(ebmp, new VRect <double>(-100, -100, 100, 100), 330, 179, 181, GantryDirection.CounterClockwise, 0, isocenter);

            VMAT1.Id = "CW";
            VMAT2.Id = "CCW";

            VMAT1.FitCollimatorToStructure(new FitToStructureMargins(10), ptv_low, true, true, false);
            VMAT2.FitCollimatorToStructure(new FitToStructureMargins(10), ptv_low, true, true, false);



            cureps.SetCalculationModel(CalculationType.PhotonVMATOptimization, "PO_15014");
            cureps.SetPrescription(NFractions, new DoseValue(RxDose / NFractions, "Gy"), 1);

            curapp.SaveModifications();

            sb = new StringBuilder();
            sb.AppendLine("Done with setting up course and VMAT plan");
            sb.AppendLine("Click OK to proceed with plan optimization");
            System.Windows.MessageBox.Show(sb.ToString());

            float doseobjectivevalue_low  = TargetStructures.Where(x => x.Item1 == "PTV_Low").Select(x => x.Item3).First();
            float doseobjectivevalue_high = TargetStructures.Where(x => x.Item1 == "PTV_High").Select(x => x.Item3).First();


            cureps.OptimizationSetup.AddPointObjective(zptvlowopt, OptimizationObjectiveOperator.Lower, new DoseValue(doseobjectivevalue_low, "Gy"), 100, 100);
            cureps.OptimizationSetup.AddPointObjective(zptvlowopt, OptimizationObjectiveOperator.Upper, new DoseValue(doseobjectivevalue_low + 3.0f, "Gy"), 30, 50);
            cureps.OptimizationSetup.AddPointObjective(zdlalow, OptimizationObjectiveOperator.Upper, new DoseValue(doseobjectivevalue_low, "Gy"), 0, 50);

            cureps.OptimizationSetup.AddPointObjective(zptvhighopt, OptimizationObjectiveOperator.Lower, new DoseValue(doseobjectivevalue_high, "Gy"), 100, 120);
            cureps.OptimizationSetup.AddPointObjective(zptvhighopt, OptimizationObjectiveOperator.Upper, new DoseValue(doseobjectivevalue_high + 2.0f, "Gy"), 0, 100);
            cureps.OptimizationSetup.AddPointObjective(zdlahigh, OptimizationObjectiveOperator.Upper, new DoseValue(doseobjectivevalue_high, "Gy"), 0, 50);

            cureps.OptimizationSetup.AddNormalTissueObjective(80.0f, 0.0f, 100.0f, 40.0f, 0.05f);
            OptimizerResult optresult = cureps.OptimizeVMAT(new OptimizationOptionsVMAT(OptimizationIntermediateDoseOption.NoIntermediateDose, string.Empty));



            sb = new StringBuilder();
            sb.AppendLine("VMAT optimization is done");
            sb.AppendLine("NIterattions:" + optresult.NumberOfIMRTOptimizerIterations.ToString() + " , ObjectiveFunctionValue: " + optresult.TotalObjectiveFunctionValue.ToString());
            sb.AppendLine("Click OK to proceed with optimization");

            cureps.OptimizeVMAT();

            curapp.SaveModifications();

            sb = new StringBuilder();
            sb.AppendLine("Done with optimization");
            sb.AppendLine("Click OK to proceed with dose calculation");
            System.Windows.MessageBox.Show(sb.ToString());

            cureps.CalculateDose();
            //cureps.PlanNormalizationValue = 99.0f;

            curapp.SaveModifications();
            sb = new StringBuilder();
            sb.AppendLine("Done with dose calculation");

            if (cureps.StructureSet.Structures.Where(x => x.Id == "Rectum").Any())
            {
                Structure reportstructure = cureps.StructureSet.Structures.Where(x => x.Id == "Rectum").First();
                sb.AppendLine("Rectum:V65Gy[%]:" + cureps.GetVolumeAtDose(reportstructure, new DoseValue(65.0f, DoseValue.DoseUnit.Gy), VolumePresentation.Relative).ToString());
            }

            sb.AppendLine("PTV_High:D95%[Gy]:" + cureps.GetDoseAtVolume(ptv_high, 95.0f, VolumePresentation.Relative, DoseValuePresentation.Absolute).ToString());


            sb.AppendLine("Click OK to finish script");
            System.Windows.MessageBox.Show(sb.ToString());
        }
Пример #18
0
        public void Execute(ScriptContext context, Window MainWin)
        {
            // Check version of the ESAPI dll
            String esapiVer  = FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(ExternalPlanSetup)).Location).FileVersion;
            Match  mEsapiVer = Regex.Match(esapiVer, @"^(\d+).");

            if (mEsapiVer.Success)
            {
                int esapiVer0 = Int32.Parse(mEsapiVer.Groups[1].Value);
                if (esapiVer0 < 16)
                {
                    throw new ApplicationException("ESAPI ver." + esapiVer + ", script cannot run on version below 16.");
                }
            }

            // Open current patient
            Patient currPt = context.Patient;

            // If there's no selected patient, throw an exception
            if (currPt == null)
            {
                throw new ApplicationException("Please open a patient before using this script.");
            }
            currPt.BeginModifications();

            // Open current course
            Course currCrs = context.Course;

            // If there's no selected course, throw an exception
            if (currCrs == null)
            {
                throw new ApplicationException("Please select at least one course before using this script.");
            }

            // Read setting file
            String            locPath     = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); // path of the compiled dll file
            String            setFilePath = Path.Combine(locPath, @"createQAPlan.setting");
            List <QASettings> qaSetLs     = new List <QASettings>();

            if (File.Exists(setFilePath))
            {
                try
                {
                    using (StreamReader readr = new StreamReader(setFilePath))
                    {
                        String currLine;
                        while ((currLine = readr.ReadLine()) != null)
                        {
                            QASettings qaSet = new QASettings();
                            bool       succ  = qaSet.ReadSettings(currLine);
                            if (succ)
                            {
                                qaSetLs.Add(qaSet);
                            }
                            else
                            {
                                throw new ApplicationException("Something wrong in createQAPlan.setting, please check the file before using this script");
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    throw new ApplicationException("Error in reading createQAPlan.setting, please check the file before using this script");
                }
            }
            else
            {
                throw new ApplicationException("Cannot locate createQAPlan.setting, please check the file before using this script");
            }

            // Call WPF Win
            var MainWinCtr = new createQAPlan.MainWindow(context, currPt, qaSetLs);

            MainWin.Content    = MainWinCtr;
            MainWin.Title      = "Create QA Plan";
            MainWin.Width      = 515;
            MainWin.Height     = 342;
            MainWin.ResizeMode = ResizeMode.NoResize;
        }
Пример #19
0
        public bool CopyAndCreate(Application app, string ptId_Tgt, string crsId_Tgt, string plnId_Tgt, string structId_Tgt, PlanParameters plnParam_Ref)
        {
            //Open patient//
            PatientSummary ptSumm = app.PatientSummaries.FirstOrDefault(ps => ps.Id == ptId_Tgt);

            if (ptSumm == null)
            {
                Console.WriteLine("--Cannot find patient" + ptId_Tgt + ".");
                return(false);
            }
            Patient pt = app.OpenPatient(ptSumm);

            try
            {
                pt.BeginModifications();
                //Open or create course//
                Course crs = pt.Courses.FirstOrDefault(c => c.Id == crsId_Tgt);
                if (crs == null)
                {
                    Console.WriteLine("-Create course " + crsId_Tgt + ".");
                    crs    = pt.AddCourse();
                    crs.Id = crsId_Tgt;
                }
                //Create plan//
                ExternalPlanSetup pln = crs.ExternalPlanSetups.FirstOrDefault(p => p.Id == plnId_Tgt);
                if (pln == null)
                {
                    StructureSet structSet = pt.StructureSets.FirstOrDefault(ss => ss.Id == structId_Tgt);
                    if (structSet == null)
                    {
                        Console.WriteLine("--Cannot find structure set " + structId_Tgt + ". Plan is not created\n");
                        app.ClosePatient();
                        return(false);
                    }
                    pln    = crs.AddExternalPlanSetup(structSet);
                    pln.Id = plnId_Tgt;
                }
                //Return if there is already a plan with the same name//
                else
                {
                    Console.WriteLine("--A plan with name " + plnId_Tgt + " already exists. Plan is not created\n");
                    app.ClosePatient();
                    return(false);
                }
                Console.WriteLine("-Start creating plan " + plnId_Tgt + ".");
                //Set plan prescription properties//
                pln.SetPrescription(plnParam_Ref.N_Fx, plnParam_Ref.DoseperFx, plnParam_Ref.TrtPct);
                ///////////Create beam by copying from the beams in reference plan parameters////////////
                //Create empty list of MU values for each beam//
                List <KeyValuePair <string, MetersetValue> > muValues = new List <KeyValuePair <string, MetersetValue> >();
                foreach (PlanParameters.BmParam bmParam in plnParam_Ref.BmParamLs)
                {
                    //Add beam, type based on reference MLC beam technique//
                    IEnumerable <double> muSet = bmParam.CtrPtParam.ControlPoints.Select(cp => cp.MetersetWeight).ToList();
                    switch (bmParam.MLCBmTechnique)
                    {
                    case "StaticMLC":
                        Beam bm =
                            pln.AddMLCBeam(bmParam.MachParam, new float[2, 60],
                                           new VRect <double>(-10.0, -10.0, 10.0, 10.0), 0.0, 0.0, 0.0, bmParam.CtrPtParam.Isocenter);
                        bm.Id = bmParam.bmId;
                        bm.ApplyParameters(bmParam.CtrPtParam);
                        break;

                    case "StaticSegWin":
                        bm =
                            pln.AddMultipleStaticSegmentBeam(bmParam.MachParam, muSet, 0.0, 0.0, 0.0, bmParam.CtrPtParam.Isocenter);
                        bm.Id = bmParam.bmId;
                        muValues.Add(new KeyValuePair <string, MetersetValue>(bmParam.bmId, bmParam.mu));
                        bm.ApplyParameters(bmParam.CtrPtParam);
                        break;

                    case "StaticSlidingWin":
                        bm =
                            pln.AddSlidingWindowBeam(bmParam.MachParam, muSet, 0.0, 0.0, 0.0, bmParam.CtrPtParam.Isocenter);
                        bm.Id = bmParam.bmId;
                        muValues.Add(new KeyValuePair <string, MetersetValue>(bmParam.bmId, bmParam.mu));
                        bm.ApplyParameters(bmParam.CtrPtParam);
                        break;

                    case "ConformalArc":
                        bm =
                            pln.AddConformalArcBeam(bmParam.MachParam, 0.0, bmParam.CtrPtParam.ControlPoints.Count(),
                                                    bmParam.CtrPtParam.ControlPoints.First().GantryAngle, bmParam.CtrPtParam.ControlPoints.Last().GantryAngle,
                                                    bmParam.CtrPtParam.GantryDirection, 0.0, bmParam.CtrPtParam.Isocenter);
                        bm.Id = bmParam.bmId;
                        bm.ApplyParameters(bmParam.CtrPtParam);
                        break;

                    case "VMAT":
                        bm =
                            pln.AddVMATBeam(bmParam.MachParam, muSet, 0.0,
                                            bmParam.CtrPtParam.ControlPoints.First().GantryAngle, bmParam.CtrPtParam.ControlPoints.Last().GantryAngle,
                                            bmParam.CtrPtParam.GantryDirection, 0.0, bmParam.CtrPtParam.Isocenter);
                        bm.Id = bmParam.bmId;
                        bm.ApplyParameters(bmParam.CtrPtParam);
                        break;

                    default:
                        Console.WriteLine("--At least one of the beams is unidentified, plan is not created.\n");
                        app.ClosePatient();
                        return(false);
                    }
                }
                //Set the plan normalization value//
                pln.PlanNormalizationValue = plnParam_Ref.PlnNormFactr;
                //Set the plan calculation model//
                pln.SetCalculationModel(CalculationType.PhotonVolumeDose, plnParam_Ref.CalcModel);
                //If one of the beams is static IMRT, compute dose to enforce MUs to beams//
                if (plnParam_Ref.BmParamLs.Any(bm => bm.MLCBmTechnique == "StaticSegWin" || bm.MLCBmTechnique == "StaticSlidingWin"))
                {
                    Console.WriteLine("--Start computing static beam IMRT plan.");
                    pln.CalculateDoseWithPresetValues(muValues);
                }
                Console.WriteLine("-Finish plan creation.\n");
                app.SaveModifications();
                app.ClosePatient();
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                app.ClosePatient();
                return(false);
            }
        }
Пример #20
0
        protected void WriteDoseStatisticsXML_HeadAndNeck2GyOrLess(Patient patient, StructureSet ss, PlanningItem plan, XmlWriter writer)
        {
            // find stats for the Brachial Plexus structure
            addStructurePQM(plan, ss, BrachialPlexus.searchIds, BrachialPlexus.PQMs, writer);

            // find stats for the Brain structure
            addStructurePQM(plan, ss, Brain.searchIds, Brain.PQMs, writer);

            // find stats for the Brainstem structure
            addStructurePQM(plan, ss, Brainstem.searchIds, Brainstem.PQMs, writer);

            // find stats for the Cochlea structure
            addStructurePQM(plan, ss, Cochlea.searchIds, Cochlea.PQMs, writer);

            // find stats for the Esophagus structure
            addStructurePQM(plan, ss, Esophagus.searchIds, Esophagus.PQMs, writer);

            // find stats for the Eye lens structures
            addStructurePQM(plan, ss, LensLeft.searchIds, LensLeft.PQMs, writer);
            addStructurePQM(plan, ss, LensRight.searchIds, LensRight.PQMs, writer);

            // find stats for the Eye structures
            addStructurePQM(plan, ss, OrbitLeft.searchIds, OrbitLeft.PQMs, writer);
            addStructurePQM(plan, ss, OrbitRight.searchIds, OrbitRight.PQMs, writer);

            // find stats for the Optic Nerve structures
            addStructurePQM(plan, ss, OpticNerveLeft.searchIds, OpticNerveLeft.PQMs, writer);
            addStructurePQM(plan, ss, OpticNerveRight.searchIds, OpticNerveRight.PQMs, writer);
            addStructurePQM(plan, ss, OpticChiasm.searchIds, OpticChiasm.PQMs, writer);

            // find stats for the Larynx structures
            addStructurePQM(plan, ss, Larynx.searchIds, Larynx.PQMs, writer);

            // find stats for the Lung structures (Lung (whole organ; target volume is NOT within the lung))
            addStructurePQM(plan, ss, LungLeft.searchIds, LungLeft.PQMs, writer);
            addStructurePQM(plan, ss, LungRight.searchIds, LungRight.PQMs, writer);

            // parotids
            addStructurePQM(plan, ss, ParotidLeft.searchIds, ParotidLeft.PQMs, writer);
            addStructurePQM(plan, ss, ParotidRight.searchIds, ParotidRight.PQMs, writer);

            // combined parotids (cut this out for version 11, won't work)
#if v13_ESAPI
            if (patient.CanModifyData())
            {
                int count = 0;
                patient.BeginModifications(); // enable writing with this script.
                // create the empty "Parotid Combined" structure
                string    ID = "Parotid Combined";
                Structure parotid_combined = ss.AddStructure("AVOIDANCE", ID);

                // search for left parotid, if found combine it into 'parotid_combined'
                foreach (string volumeId in ParotidLeft.searchIds)
                {
                    Structure oar = (from s in ss.Structures
                                     where s.Id.ToUpper().CompareTo(volumeId.ToUpper()) == 0
                                     select s).FirstOrDefault();
                    if (oar != null)
                    {
                        count++;
                        parotid_combined.SegmentVolume = parotid_combined.Or(oar);
                        break;
                    }
                }

                // search for right parotid, if found combine it into 'parotid_combined'
                foreach (string volumeId in ParotidRight.searchIds)
                {
                    Structure oar = (from s in ss.Structures
                                     where s.Id.ToUpper().CompareTo(volumeId.ToUpper()) == 0
                                     select s).FirstOrDefault();
                    if (oar != null)
                    {
                        count++;
                        parotid_combined.SegmentVolume = parotid_combined.Or(oar);
                        break;
                    }
                }
                if (count > 0)
                {
                    string[] searchIds = { ID };
                    addStructurePQM(plan, ss, searchIds, ParotidsCombined.PQMs, writer);
                }
                ss.RemoveStructure(parotid_combined);
            }
#endif
            // find stats for the spinal cord structure
            addStructurePQM(plan, ss, SpinalCord.searchIds, SpinalCord.PQMs, writer);

            // find stats for the Mandible structure
            addStructurePQM(plan, ss, Mandible.searchIds, Mandible.PQMs, writer);

            // find stats for the Oral Cavity structure
            addStructurePQM(plan, ss, OralCavity.searchIds, OralCavity.PQMs, writer);

            // find stats for the Pharynx structure
            addStructurePQM(plan, ss, Pharynx.searchIds, Pharynx.PQMs, writer);

            // find stats for the PharyngealConstrictor structure
            addStructurePQM(plan, ss, PharyngealConstrictor.searchIds, PharyngealConstrictor.PQMs, writer);

            // find stats for the submandibular structure
            addStructurePQM(plan, ss, Submandibular.searchIds, Submandibular.PQMs, writer);

            // find stats for the Thyroid structure
            addStructurePQM(plan, ss, Thyroid.searchIds, Thyroid.PQMs, writer);

            //      writer.WriteEndElement(); // </DoseStatistics>
        }
Пример #21
0
        public void Execute(ScriptContext context /*, System.Windows.Window window, ScriptEnvironment environment*/)
        {
            Patient p = context.Patient;

            if (p == null)
            {
                throw new ApplicationException("Please load a patient");
            }

            ExternalPlanSetup plan = context.ExternalPlanSetup;

            if (plan == null)
            {
                throw new ApplicationException("Please load an external beam plan that will be verified.");
            }

            // Get or create course with Id 'QA'
            Course course = p.Courses.Where(o => o.Id == QAId).SingleOrDefault();

            if (course == null)
            {
                course    = p.AddCourse();
                course.Id = QAId;
            }
            if (course.CompletedDateTime != null)
            {
                MessageBox.Show("Course QA is set to 'COMPLETED', please set to 'ACTIVE'");
            }

            p.BeginModifications();

            StructureSet ssQA = p.CopyImageFromOtherPatient(QAPatientID_Trilogy, QAStudyID_Trilogy, QAImageID_Trilogy);

            foreach (StructureSet ss in course.Patient.StructureSets)
            {
                if (plan.Beams.FirstOrDefault().TreatmentUnit.Name == QAMachine_Trilogy)
                {
                    if (ss.Image.Id == QAImageID_Trilogy)
                    {
                        ssQA = ss;
                        break;
                    }
                    else
                    {
                        ssQA = p.CopyImageFromOtherPatient(QAPatientID_Trilogy, QAStudyID_Trilogy, QAImageID_Trilogy);
                    }
                }
                else
                {
                    if (plan.Beams.FirstOrDefault().TreatmentUnit.Id == QAMachine_iX)
                    {
                        if (ss.Image.Id == QAImageID_iX)
                        {
                            ssQA = ss;
                            break;
                        }
                        else
                        {
                            ssQA = p.CopyImageFromOtherPatient(QAPatientID_iX, QAStudyID_iX, QAImageID_iX);
                        }
                    }
                    else
                    {
                        MessageBox.Show(string.Format("Treatment machine {0} in plan not recognized.", plan.Beams.FirstOrDefault().TreatmentUnit.Id));
                        ssQA = null;
                    }
                }
            }

#if false
            // Create an individual verification plan for each field.
            foreach (var beam in plan.Beams)
            {
                CreateVerificationPlan(course, new List <Beam> {
                    beam
                }, plan, ssQA, beam.Id, calculateDose: false);
            }
#endif


            // Create a verification plan that contains all fields (Composite).
            ExternalPlanSetup verificationPlan = CreateVerificationPlan(course, plan.Beams, plan, ssQA, calculateDose: true);

            // nagivate back from verificationPlan to verified plan
            PlanSetup verifiedPlan = verificationPlan.VerifiedPlan;
            if (plan != verifiedPlan)
            {
                MessageBox.Show(string.Format("ERROR! verified plan {0} != loaded plan {1}", verifiedPlan.Id
                                              , plan.Id));
            }
            MessageBox.Show(string.Format("Success - verification plan {0} created in course {1}.", verificationPlan.Id, course.Id));
        }
Пример #22
0
        public void Execute(ScriptContext context)
        {
            // First check version of the ESAPI dll
            String esapiVer  = FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(ExternalPlanSetup)).Location).FileVersion;
            Match  mEsapiVer = Regex.Match(esapiVer, @"^(\d+).");

            if (mEsapiVer.Success)
            {
                int esapiVer0 = Int32.Parse(mEsapiVer.Groups[1].Value);
                if (esapiVer0 < 16)
                {
                    throw new ApplicationException("ESAPI ver." + esapiVer + ", script cannot run on version below 16.");
                }
            }

            // Open current patient
            Patient currPt = context.Patient;

            // If there's no selected patient, throw an exception
            if (currPt == null)
            {
                throw new ApplicationException("Please open a patient before using this script.");
            }

            // Open current plan
            ExternalPlanSetup currPln = context.ExternalPlanSetup;

            // If there's no selected plan, throw an exception
            if (currPln == null)
            {
                throw new ApplicationException("Please select a plan before using this script.");
            }

            // Check if plan is approved
            if (currPln.ApprovalStatus != PlanSetupApprovalStatus.UnApproved)
            {
                throw new ApplicationException("Please unapprove plan before using this script.");
            }

            // Get first beam
            Beam currBm = currPln.Beams.FirstOrDefault();

            // If there's no beam in plan, throw an exception
            if (currBm == null)
            {
                throw new ApplicationException("Please add a beam with valid isocenter in current plan before using this script.");
            }

            // Get patient orientation
            String ptOrient = "";

            switch (currPln.TreatmentOrientation)
            {
            case PatientOrientation.HeadFirstSupine:
                ptOrient = "HFS";
                break;

            case PatientOrientation.HeadFirstProne:
                ptOrient = "HFP";
                break;

            case PatientOrientation.FeetFirstSupine:
                ptOrient = "FFS";
                break;

            case PatientOrientation.FeetFirstProne:
                ptOrient = "FFP";
                break;

            default:
                ptOrient = "UK";
                break;
            }
            if (ptOrient == "UK")
            {
                throw new ApplicationException("Cannot determine beam orientation relative to patient orientation, no setup beam created.");
            }

            // Create DRR parameters
            Regex brstMatch = new Regex("BREAST|CAVITY|LUMPECTOMY");               // potential plan ID for breast plans
            DRRCalculationParameters drrParam = new DRRCalculationParameters(500); // 50 cm DRR size

            if (brstMatch.IsMatch(currPln.Id.ToUpper()))                           // breast plan uses chest DRR setting
            {
                drrParam.SetLayerParameters(0, 0.6, -990.0, 0.0, 10.0, 50.0);
                drrParam.SetLayerParameters(1, 0.1, -450.0, 0.0, -40.0, 80.0);
                drrParam.SetLayerParameters(2, 1.0, 100.0, 1000.0);
            }
            else  // all other plan uses the default DRR setting
            {
                drrParam.SetLayerParameters(0, 2.0, 0.0, 130.0, -1000.0, 1000.0);
                drrParam.SetLayerParameters(1, 10.0, 100.0, 1000.0, -1000.0, 1000.0);
            }

            // Determine beam number based on the largest number currently in the setup beam ID under the current patient
            int bmIdNo = 0;

            foreach (Course crs in currPt.Courses)
            {
                foreach (ExternalPlanSetup pln in crs.ExternalPlanSetups)
                {
                    foreach (Beam bm in pln.Beams)
                    {
                        Match bmId = Regex.Match(bm.Id, @"^[A-Z](\d+)$");
                        if (bmId.Success)
                        {
                            bmIdNo = Math.Max(bmIdNo, Int32.Parse(bmId.Groups[1].Value));
                        }
                    }
                }
            }
            bmIdNo = bmIdNo + 1;

            currPt.BeginModifications();
            // Change or add DRR to existing beam
            foreach (Beam bm in currPln.Beams)
            {
                bm.CreateOrReplaceDRR(drrParam);
            }
            // Create setup beam
            SetupBeam setupBm = new SetupBeam(currBm);

            setupBm.AddBeam(currPln, Double.NaN, ptOrient, drrParam, bmIdNo);  // CBCT
            setupBm.AddBeam(currPln, 0.0, ptOrient, drrParam, bmIdNo);
            setupBm.AddBeam(currPln, 270.0, ptOrient, drrParam, bmIdNo);
            setupBm.AddBeam(currPln, 90.0, ptOrient, drrParam, bmIdNo);
            setupBm.AddBeam(currPln, 180.0, ptOrient, drrParam, bmIdNo);

            MessageBox.Show("Set of setup beam has been created in plan " + currPln.Id + ".");
        }