static void Execute(Application app) { // TODO: add here your code Patient curpat = app.OpenPatientById("002441"); Course curcourse = curpat.Courses.Where(x => x.Id == "advanced.3").Single(); //ExternalPlanSetup cureps = curcourse.ExternalPlanSetups.Where(x => x.Id == "NCPTestScript").Single(); StructureSet curstructset = curpat.StructureSets.Where(x => x.Id == "StdNomenclature").First(); //Create a list of Tuples to pass target information:Target Type,Structure ID, Minimum dose constraint, dose units (Gy v cGy) List <Tuple <string, string, float, string> > targetstructureconstraints = new List <Tuple <string, string, float, string> >(); targetstructureconstraints.Add(new Tuple <string, string, float, string>("PTV_High", "PTV_6800", 68.0f, "Gy")); //This maps the contoured PTV_6800 structure to the generic PTV_High type and assigns prescribed dose targetstructureconstraints.Add(new Tuple <string, string, float, string>("PTV_Low", "PTV_5600", 56.0f, "Gy")); //This maps the contoured PTV_5600 structure to the generic PTV_Low type and assigns prescribed dose List <string> listallowednontargetStructures = new List <string>() { "Rectum", "Bladder", "Femur_Head_L", "Femur_Head_R", "Femur_Heads", "LN", "PenileBulb" }; Planning(app, curpat, curstructset, targetstructureconstraints, listallowednontargetStructures, 68, 34); }
public void Load(DicomFile file, StructureSet structureSet, IProgress <double> progress) { structureSet.FileName = file.File.Name; structureSet.Name = file.Dataset.GetSingleValueOrDefault <string>(DicomTag.StructureSetLabel, ""); Dictionary <int, string> roi_names = new Dictionary <int, string>(); DicomSequence structs = file.Dataset.GetSequence(DicomTag.StructureSetROISequence); foreach (DicomDataset item in structs) { roi_names.Add(item.GetSingleValue <int>(DicomTag.ROINumber), item.GetSingleValue <string>(DicomTag.ROIName)); } DicomSequence s = file.Dataset.GetSequence(DicomTag.ROIContourSequence); //Track the item number to report progress double total = s.Items.Count; double num = 0; foreach (DicomDataset item in s.Items) { num++; if (progress != null) { progress.Report(100 * num / total); } RegionOfInterest roi = new RegionOfInterest(); int[] color = new int[] { 0, 0, 0 }; if (item.TryGetValues <int>(DicomTag.ROIDisplayColor, out int[] tmp))
/// <summary> /// This splits a structure into two. It creates a margin around the target, /// so that it approximately crosses the mass center of the structure, and then /// uses boolean operators to create two new structures. Note: due to the nature /// of the segment model in Eclipse, the new structures do not always perfectly cover /// the whole volume of the original structure. /// </summary> /// <param name="s"></param> /// <param name="ss"></param> /// <returns></returns> bool SplitStructure(StructureSet ss, Structure target, Structure roi) { if (ss.CanAddStructure(roi.DicomType, roi.Id + "_spl1")) { Structure newStr1 = ss.AddStructure(roi.DicomType, roi.Id + "_spl1"); Structure newStr2 = ss.AddStructure(roi.DicomType, roi.Id + "_spl2"); VVector targetCenter = target.CenterPoint; VVector roiCenter = roi.CenterPoint; double dist = (targetCenter - roiCenter).Length; //figure out distance from target center to target surface System.Collections.BitArray buffer = new System.Collections.BitArray(100); SegmentProfile profile = target.GetSegmentProfile(targetCenter, roiCenter, buffer); double distToTargetSurface = 0; foreach (SegmentProfilePoint point in profile) { if (point.Value == false) { //first point outside structure distToTargetSurface = (point.Position - targetCenter).Length; break; } } //SegmentVolume seg = target.Margin(dist - distToTargetSurface); SegmentVolume seg = target.LargeMargin(dist - distToTargetSurface); newStr1.SegmentVolume = seg.And(roi); newStr2.SegmentVolume = roi.Sub(newStr1); return(true); } return(false); }
public MROQCStructureCheck(string structureName, ScriptContext context) { Structure = structureName; StructureSet ss = context.StructureSet; if (ss.Structures.Where(x => x.Id == Structure).Count() > 0) { Structure mroqcStructure = ss.Structures.Where(x => x.Id == Structure).First(); if (!mroqcStructure.IsEmpty && mroqcStructure.HasSegment) { Result = "Pass"; ResultColor = "LightGreen"; } else { Result = $"{Structure} is not contoured"; ResultColor = "Salmon"; } } else { Result = $"{Structure} not found in structure set"; ResultColor = "Salmon"; } }
Structure FindStructureFromAlias(StructureSet ss, string ID, string[] aliases) { // search through the list of alias ids until we find an alias that matches an existing structure. Structure oar = null; string actualStructId = ""; oar = (from s in ss.Structures where s.Id.ToUpper().CompareTo(ID.ToUpper()) == 0 select s).FirstOrDefault(); if (oar == null) { foreach (string volumeId in aliases) { oar = (from s in ss.Structures where s.Id.ToUpper().CompareTo(volumeId.ToUpper()) == 0 select s).FirstOrDefault(); if (oar != null) { actualStructId = oar.Id; break; } } } return(oar); }
public string GetEditableRingName(Patient patient, string structureSetId, string ringId) { StructureSet structureSet = patient.StructureSets.FirstOrDefault(x => x.Id == structureSetId); bool ringInStructureSet = false; bool possibleInStructureSet = false; bool canEditRing = true; string possibleStructureId = String.Empty; foreach (var structure in structureSet.Structures) { if (structure.Id == ringId) { ringInStructureSet = true; if (Helpers.CheckStructure(structure) == true) //ring is present but editable { return(structure.Id); } else { canEditRing = false; } } } if (ringInStructureSet == true && canEditRing == false) //ring is present but not editable { for (int i = 1; i <= 5; i++) { foreach (var structure in structureSet.Structures) { if (structure.Id == ringId + i.ToString()) //possible already present { possibleInStructureSet = true; if (Helpers.CheckStructure(structure) == true) //possible is editable { return(structure.Id); } else { possibleInStructureSet = false; possibleStructureId = ringId + (i + 1).ToString(); break; } } else { possibleStructureId = ringId + i.ToString(); } } if (possibleInStructureSet == false) //possible not in structure and can be added { return(possibleStructureId); } } } if (ringInStructureSet == false) //ring not in structure set and can be added { return(ringId); } throw new Exception("Too many uneditable rings in structure set."); }
//--------------------------------------------------------------------------------------------- /// <summary> /// This method creates a Plan Quality Metric report for the specified plan. /// </summary> /// <param name="patient">loaded patient</param> /// <param name="ss">structure set to use while generating Plan Quality Metrics</param> /// <param name="plan">Plan for which the report is going to be generated.</param> /// <param name="rootPath">root directory for the report. This method creates a subdirectory /// 'patientid' under the root, then creates the xml and html reports in the subdirectory.</param> /// <param name="userId">User whose id will be stamped on the report.</param> /// <param name="xmlFilePath">Raw unformatted XML report.</param> //--------------------------------------------------------------------------------------------- public string generateReport(Patient patient, StructureSet ss, PlanningItem plan, out string xmlFilePath) { string rootDir = string.Format(@"{0}\{1}", rootPath, MakeFilenameValid(patient.Id)); Directory.CreateDirectory(rootDir); string fileRoot = string.Format(@"{0}\PQMReport-{1}", rootDir, MakeFilenameValid(plan.Id)); // build exported XML filename, put it in the root path (likely is users temp directory) xmlFilePath = string.Format(@"{0}.xml", fileRoot); string htmlFilePath = string.Format(@"{0}.html", fileRoot); dumpReportXML(patient, ss, plan, xmlFilePath); // PQM stylesheet should already be loaded into memory, transform report XML into HTML, show that to the user. try { myXslTransform.Transform(xmlFilePath, htmlFilePath); return(htmlFilePath); } catch (System.Xml.Xsl.XsltCompileException e) { throw new ApplicationException("Failed to load xsl stylesheet '" + stylesheet + "'. details:\n" + e.ToString()); } catch (System.Xml.Xsl.XsltException e) { throw new ApplicationException("General stylesheet problem when applying '" + stylesheet + "'. details:\n" + e.ToString()); } }
public static Structure SelectStructure(StructureSet ss) { m_w = new Window(); m_w.Width = 400; m_w.Height = 400; m_w.Title = "Select structure:"; var grid = new Grid(); m_w.Content = grid; var list = new ListBox(); foreach (var s in ss.Structures) { list.Items.Add(s); } list.VerticalAlignment = VerticalAlignment.Top; list.Margin = new Thickness(10, 10, 10, 10); grid.Children.Add(list); var button = new Button(); button.Content = "OK"; button.Height = 40; button.VerticalAlignment = VerticalAlignment.Bottom; button.Margin = new Thickness(10, 10, 10, 10); button.Click += button_Click; grid.Children.Add(button); if (m_w.ShowDialog() == true) { return((Structure)list.SelectedItem); } return(null); }
public ObservableCollection <PQMSummaryViewModel> AddPQMSummary(ObservableCollection <PQMSummaryViewModel> PqmSummaries, ConstraintViewModel constraintPath, PlanningItemViewModel planningItem, Patient patient) { StructureSet structureSet = planningItem.PlanningItemStructureSet; Structure evalStructure; var calculator = new PQMSummaryCalculator(); if (planningItem.PlanningItemObject is PlanSum) { var waitWindowPQM = new WaitWindowPQM(); PlanSum plansum = (PlanSum)planningItem.PlanningItemObject; if (plansum.IsDoseValid() == true) { waitWindowPQM.Show(); foreach (PQMSummaryViewModel pqm in PqmSummaries) { evalStructure = calculator.FindStructureFromAlias(structureSet, pqm.TemplateId, pqm.TemplateAliases, pqm.TemplateCodes); if (evalStructure != null) { var pqmSummary = calculator.GetObjectiveProperties(pqm, planningItem, structureSet, new StructureViewModel(evalStructure)); pqm.Achieved_Comparison = pqmSummary.Achieved; pqm.AchievedColor_Comparison = pqmSummary.AchievedColor; pqm.AchievedPercentageOfGoal_Comparison = pqmSummary.AchievedPercentageOfGoal; pqm.Met_Comparison = pqmSummary.Met; } } waitWindowPQM.Close(); } } else //is plansetup { var waitWindowPQM = new WaitWindowPQM(); PlanSetup planSetup = (PlanSetup)planningItem.PlanningItemObject; if (planSetup.IsDoseValid() == true) { waitWindowPQM.Show(); foreach (PQMSummaryViewModel pqm in PqmSummaries) { evalStructure = calculator.FindStructureFromAlias(structureSet, pqm.TemplateId, pqm.TemplateAliases, pqm.TemplateCodes); if (evalStructure != null) { if (evalStructure.Id.Contains("PTV") == true) { foreach (Structure s in structureSet.Structures) { if (s.Id == planSetup.TargetVolumeID) { evalStructure = s; } } } var pqmSummary = calculator.GetObjectiveProperties(pqm, planningItem, structureSet, new StructureViewModel(evalStructure)); pqm.Achieved_Comparison = pqmSummary.Achieved; } } waitWindowPQM.Close(); } } return(PqmSummaries); }
public void CleanUpRings(StructureSet structureSet, string ptvHighId, string ptvMidId, string ptvLowId, string ptv4Id, string ringHighId, string ringMidId, string ringLowId, string ring4Id) { Structure ptvHigh = structureSet.Structures.Where(structure => structure.Id == ptvHighId).FirstOrDefault(); Structure ringHigh = structureSet.Structures.Where(structure => structure.Id == ringHighId).FirstOrDefault(); if (ptvMidId != null) { Structure ptvMid = structureSet.Structures.Where(structure => structure.Id == ptvMidId).FirstOrDefault(); Structure ringMid = structureSet.Structures.Where(structure => structure.Id == ringMidId).FirstOrDefault(); ringMid.SegmentVolume = ringMid.SegmentVolume.Sub(ringHigh.SegmentVolume); ringMid.SegmentVolume = ringMid.SegmentVolume.Sub(ptvHigh.SegmentVolume); if (ptvLowId != null) { Structure ptvLow = structureSet.Structures.Where(structure => structure.Id == ptvLowId).FirstOrDefault(); Structure ringLow = structureSet.Structures.Where(structure => structure.Id == ringLowId).FirstOrDefault(); ringLow.SegmentVolume = ringLow.SegmentVolume.Sub(ringMid.SegmentVolume); ringLow.SegmentVolume = ringLow.SegmentVolume.Sub(ptvMid.SegmentVolume); ringLow.SegmentVolume = ringLow.SegmentVolume.Sub(ringHigh.SegmentVolume); ringLow.SegmentVolume = ringLow.SegmentVolume.Sub(ptvHigh.SegmentVolume); if (ptv4Id != null) { Structure ptv4 = structureSet.Structures.Where(structure => structure.Id == ptv4Id).FirstOrDefault(); Structure ring4 = structureSet.Structures.Where(structure => structure.Id == ring4Id).FirstOrDefault(); ring4.SegmentVolume = ring4.SegmentVolume.Sub(ringLow.SegmentVolume); ring4.SegmentVolume = ring4.SegmentVolume.Sub(ptvLow.SegmentVolume); ring4.SegmentVolume = ring4.SegmentVolume.Sub(ringMid.SegmentVolume); ring4.SegmentVolume = ring4.SegmentVolume.Sub(ptvMid.SegmentVolume); ring4.SegmentVolume = ring4.SegmentVolume.Sub(ringHigh.SegmentVolume); ring4.SegmentVolume = ring4.SegmentVolume.Sub(ptvHigh.SegmentVolume); } } } }
public static string GetVolumeAtDose(StructureSet structureSet, PlanningItem planningItem, Structure evalStructure, MatchCollection testMatch, Group evalunit) { //check for sufficient sampling and dose coverage DVHData dvh = planningItem.GetDVHCumulativeData(evalStructure, DoseValuePresentation.Absolute, VolumePresentation.Relative, 0.1); //MessageBox.Show(evalStructure.Id + "- Eval unit: " + evalunit.Value.ToString() + "Achieved unit: " + dvAchieved.UnitAsString + " - Sampling coverage: " + dvh.SamplingCoverage.ToString() + " Coverage: " + dvh.Coverage.ToString()); if ((dvh.SamplingCoverage < 0.9) || (dvh.Coverage < 0.9)) { return("Unable to calculate - insufficient dose or sampling coverage"); } Group eval = testMatch[0].Groups["evalpt"]; Group unit = testMatch[0].Groups["unit"]; DoseValue.DoseUnit du = (unit.Value.CompareTo("%") == 0) ? DoseValue.DoseUnit.Percent : (unit.Value.CompareTo("cGy") == 0) ? DoseValue.DoseUnit.cGy : DoseValue.DoseUnit.Unknown; VolumePresentation vp = (unit.Value.CompareTo("%") == 0) ? VolumePresentation.Relative : VolumePresentation.AbsoluteCm3; DoseValue dv = new DoseValue(double.Parse(eval.Value), du); double volume = double.Parse(eval.Value); VolumePresentation vpFinal = (evalunit.Value.CompareTo("%") == 0) ? VolumePresentation.Relative : VolumePresentation.AbsoluteCm3; DoseValuePresentation dvpFinal = (evalunit.Value.CompareTo("%") == 0) ? DoseValuePresentation.Relative : DoseValuePresentation.Absolute; double volumeAchieved = planningItem.GetVolumeAtDose(evalStructure, dv, vpFinal); return(string.Format("{0:0.00} {1}", volumeAchieved, evalunit.Value)); // todo: better formatting based on VolumePresentation //#if false // string message = string.Format("{0} - Dose unit = {1}, Volume Presentation = {2}, vpFinal = {3}, dvpFinal ={4}", // objective.DVHObjective, du.ToString(), vp.ToString(), vpFinal.ToString(), dvpFinal.ToString()); // MessageBox.Show(message); //#endif }
public generateTS(List <Tuple <string, string, double> > list, StructureSet ss, double tm, bool st) { spareStructList = list; selectedSS = ss; targetMargin = tm; scleroTrial = st; }
public void CreateRingFromPTV(StructureSet structureSet, string ptvId, string ringId, double innerMargin, double outerMargin) { structureSet.Patient.BeginModifications(); Structure ptv = structureSet.Structures.Where(structure => structure.Id == ptvId).FirstOrDefault(); Structure ring; Structure spacerTemp; try { ring = structureSet.AddStructure("CONTROL", ringId); //doesnt exist yet } catch { ring = structureSet.Structures.FirstOrDefault(x => x.Id == ringId); //already exists ring.SegmentVolume = ring.Sub(structureSet.Structures.Single(x => x.Id == "BODY")); //cleanup } try { spacerTemp = structureSet.AddStructure("CONTROL", "spacerTemp"); //doesnt exist yet } catch { spacerTemp = structureSet.Structures.FirstOrDefault(x => x.Id == "spacerTemp"); //already exists spacerTemp.SegmentVolume = spacerTemp.Sub(structureSet.Structures.Single(x => x.Id == "BODY")); //cleanup } //ring.ConvertToHighResolution(); ring.SegmentVolume = ptv.Margin(outerMargin); spacerTemp.SegmentVolume = ptv.Margin(innerMargin); //3 mm between ring and PTV ring.SegmentVolume = ring.Sub(ptv); ring.SegmentVolume = ring.Sub(spacerTemp); ring.SegmentVolume = ring.And(structureSet.Structures.Single(x => x.Id == "BODY")); //clear outside of body structureSet.RemoveStructure(spacerTemp); }
public void Run( User user, Patient patient, Image image, StructureSet structureSet, PlanSetup planSetup, IEnumerable <PlanSetup> planSetupsInScope, IEnumerable <PlanSum> planSumsInScope, Window mainWindow) { if (planSetup == null) { string message = "No active plan, please load a plan"; MessageBox.Show(message); return; } try { var mainViewModel = new MainViewModel(user, patient, planSetup, planSetupsInScope); MainView mainView = new MainView(mainViewModel); mainWindow.Content = mainView; } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace); } }
public async void BeginOpenStructuresAsync() { string[] files; if ((files = getFileNames("Open Structure Set", true)) != null) { var pi = ProgressService.CreateNew("Loading Structure Set...", false); var progress = new Progress <double>(x => { pi.ProgressAmount = (int)x; }); StructureSet openedObject = null; await Task.Run(async() => { try { openedObject = await DicomLoader.LoadStructureSetAsync(files, progress); } catch (Exception e) { Messenger.Default.Send(new NotificationMessage("Could not open file: " + e.Message)); } }); if (openedObject != null) { Messenger.Default.Send(new RTDicomViewer.Message.RTObjectAddedMessage <StructureSet>(openedObject)); } ProgressService.End(pi); } }
public static string GetCoveredVolumeAtDose(StructureSet structureSet, PlanningItemViewModel planningItem, StructureViewModel evalStructure, MatchCollection testMatch, Group evalunit) { try { var structure = structureSet.Structures.FirstOrDefault(x => x.Id == evalStructure.StructureName); //check for sufficient sampling and dose coverage DVHData dvh = planningItem.PlanningItemObject.GetDVHCumulativeData(structure, DoseValuePresentation.Absolute, VolumePresentation.Relative, 0.1); if ((dvh.SamplingCoverage < 0.9) || (dvh.Coverage < 0.9)) { return("Unable to calculate - insufficient dose or sampling coverage"); } Group eval = testMatch[0].Groups["evalpt"]; Group unit = testMatch[0].Groups["unit"]; DoseValue.DoseUnit du = (unit.Value.CompareTo("%") == 0) ? DoseValue.DoseUnit.Percent : (unit.Value.CompareTo("cGy") == 0) ? DoseValue.DoseUnit.cGy : DoseValue.DoseUnit.Unknown; VolumePresentation vp = (unit.Value.CompareTo("%") == 0) ? VolumePresentation.Relative : VolumePresentation.AbsoluteCm3; DoseValue dv = new DoseValue(double.Parse(eval.Value), du); double volume = double.Parse(eval.Value); VolumePresentation vpFinal = (evalunit.Value.CompareTo("%") == 0) ? VolumePresentation.Relative : VolumePresentation.AbsoluteCm3; DoseValuePresentation dvpFinal = (evalunit.Value.CompareTo("%") == 0) ? DoseValuePresentation.Relative : DoseValuePresentation.Absolute; double volumeAchieved = planningItem.PlanningItemObject.GetVolumeAtDose(structure, dv, vpFinal); double organVolume = Convert.ToDouble(evalStructure.VolumeValue); double coveredVolume = organVolume - volumeAchieved; return(string.Format("{0:0.00} {1}", coveredVolume, evalunit.Value)); // todo: better formatting based on VolumePresentation } catch (NullReferenceException) { return("Unable to calculate - DVH is not valid"); } }
public void Load(DicomFile[] files, StructureSet structureSet, IProgress <double> progress) { base.Load(files, structureSet, progress); DicomFile file = files[0]; Load(file, structureSet, progress); }
public static ExternalPlanSetup AddNewPlan(Course course, StructureSet structureSet, string planId) { try { var oldPlans = course.PlanSetups.Where(x => x.Id == planId); if (oldPlans.Any()) { var plansToBeRemoved = oldPlans.ToArray(); foreach (var p in plansToBeRemoved) { course.RemovePlanSetup(p); } } } catch { var message = string.Format("Could not cleanup old plans."); throw new Exception(message); } ExternalPlanSetup plan = course.AddExternalPlanSetup(structureSet); plan.Id = planId; return(plan); }
public override void Run(PluginScriptContext context) { // TODO : Add here the code that is called when the script is launched from Eclipse. User user = context.CurrentUser; StructureSet structureSet = context.StructureSet; if (structureSet == null) { MessageBox.Show("No structureSet is loaded."); return; } System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); string scriptVersion = fvi.FileVersion; var window = new Window(); var mainWindow = new AutoStructure.MainControl(); window.Title = "AutoStructureMaker " + scriptVersion; window.Content = mainWindow; mainWindow.structureSet = structureSet; mainWindow.UserId = user.Name; window.ShowDialog(); }
public void Run(User user, Patient patient, Image image, StructureSet structureSet, PlanSetup planSetup, IEnumerable <PlanSetup> planSetups, IEnumerable <PlanSum> planSums, Window window) { // //Dose profiles // var prof = Profile.getBeamDoseProfile(planSetup.Beams.First(), new VVector(1.0, 0, 0), distanceFromIsocenterTowardSourceInmm: 30); Helpers.DumpIntoMatlab(prof.Select(val => double.IsNaN(val.Value) ? 0 : val.Value).ToArray(), new int[] { prof.Count }, "orthogonalDoseProfile"); var dprof = Profile.getBeamDepthDoseProfileAlongBeamAxis(structureSet.Structures.Single(st => st.Id == "BODY"), planSetup.Beams.ToArray()[4]); Helpers.DumpIntoMatlab(dprof.Select(val => double.IsNaN(val.Value) ? 0 : val.Value).ToArray(), new int[] { dprof.Count }, "depthdoseProfile"); var dprof2 = Profile.getBeamDoseProfile(planSetup.Beams.First(), new VVector(0, -1.0, 0)); Helpers.DumpIntoMatlab(dprof2.Select(val => double.IsNaN(val.Value) ? 0 : val.Value).ToArray(), new int[] { dprof2.Count }, "depthdoseProfile2"); // // Dose plane // var plane = Plane.OrthogonalDoseCrossSection(planSetup.Beams.ToArray()[4]); var planeAsArray = new double[plane.Length]; Buffer.BlockCopy(plane, 0, planeAsArray, 0, plane.Length * sizeof(double)); Helpers.DumpIntoMatlab(planeAsArray, new int[] { plane.GetLength(1), plane.GetLength(0) }, "orthogonalPlane"); // // Image profiles // var(xProf, yProf, zProf) = Profile.getImageProfilesThroughIsocenter(planSetup); Helpers.DumpIntoMatlab(xProf.Select(val => double.IsNaN(val.Value) ? 0 : val.Value).ToArray(), new int[] { xProf.Count }, "XProfile"); Helpers.DumpIntoMatlab(xProf.Select(val => double.IsNaN(val.Value) ? 0 : val.Value).ToArray(), new int[] { xProf.Count }, "XProfile"); Helpers.DumpIntoMatlab(zProf.Select(val => double.IsNaN(val.Value) ? 0 : val.Value).ToArray(), new int[] { zProf.Count }, "ZProfile"); // // DVH with dose profiles. // planSetup.DoseValuePresentation = DoseValuePresentation.Absolute; var p2 = patient.Courses.Single(cr => cr.Id == planSetup.Course.Id).PlanSetups.Single(pl => pl.Id == "Plan2"); p2.DoseValuePresentation = DoseValuePresentation.Absolute; var doses = new Dose[] { planSetup.Dose //p2.Dose }; var(cDVH, dDVH, sampleCoverage) = DVH.StructureDVH(doses, structureSet.Structures.Single(st => st.Id == "CTV"), new DVH.NoConversion()); Helpers.DumpIntoMatlab(Helpers.into1DArray(dDVH.Select(val => new double[] { val.doseValue, val.Volume }).ToArray()), new int[] { 2, dDVH.Length }, "dDVH"); Helpers.DumpIntoMatlab(Helpers.into1DArray(cDVH.Select(val => new double[] { val.doseValue, val.Volume }).ToArray()), new int[] { 2, cDVH.Length }, "cDVH"); return; }
public void Execute(ScriptContext context /*, System.Windows.Window window, ScriptEnvironment environment*/) { // declare local variables that reference the objects we need. PlanSetup plan = context.PlanSetup; if (plan == null) { MessageBox.Show("Please load a plan before running this script."); return; } StructureSet ss = context.StructureSet; if (ss == null) { MessageBox.Show("Please load a structure set before running this script."); return; } var listStructures = context.StructureSet.Structures; // 'listStructures' if of type IEnumerable<Structure> // loop through structure list and find a structure named "Bladder" Structure bladder = null; foreach (Structure scan in listStructures) { if (scan.Id == "Bladder") { bladder = scan; } } if (bladder == null) { MessageBox.Show("Bladder not found!"); return; } string msg = string.Format("bladder volume = {0}", bladder.Volume); MessageBox.Show(msg, "Varian Developer"); // extract DVH data for bladder using bin width of 0.1. DVHData dvh = plan.GetDVHCumulativeData(bladder, DoseValuePresentation.Absolute, VolumePresentation.Relative, 0.1); string filename = string.Format(@"c:\temp\bladder_dvh-{0}.csv", context.CurrentUser.Name); System.IO.StreamWriter dvhFile = new System.IO.StreamWriter(filename); // write a header dvhFile.WriteLine("Dose,Volume"); // write all dvh points for the PTV. foreach (DVHPoint pt in dvh.CurveData) { string line = string.Format("{0},{1}", pt.DoseValue.Dose, pt.Volume); dvhFile.WriteLine(line); } dvhFile.Close(); msg = string.Format("dvh file written to {0}", filename); MessageBox.Show(msg, "Varian Developer"); }
private Tuple <string, string, AutoCheckStatus> GetOptimizationInfo(StructureSet structureSet, PlanSetup planSetup) { string value = string.Empty; string details = string.Empty; AutoCheckStatus status = AutoCheckStatus.MANUAL; List <Structure> strList = structureSet.Structures.Where(s => s.Id.ToLower().StartsWith("z_ptv")).ToList(); List <string> lowerPTVObjectiveStructures = new List <string>(); //J Add list for name of all structures that have an lower objective foreach (OptimizationObjective optimizationObjective in planSetup.OptimizationSetup.Objectives) { if (optimizationObjective.GetType() == typeof(OptimizationPointObjective)) { OptimizationPointObjective optimizationPointObjective = (OptimizationPointObjective)optimizationObjective; if (((optimizationPointObjective.Operator.ToString().ToLower() == "lower") || (optimizationPointObjective.Operator.ToString().ToLower() == "upper")) && optimizationPointObjective.StructureId.StartsWith("Z_PTV")) { // Generates a list for with name of all structures that have a lower objective (ie finds the PTVs). lowerPTVObjectiveStructures.Add(optimizationPointObjective.StructureId); } details += (details.Length == 0 ? "Optimization objectives:\r\n " : "\r\n ") + optimizationPointObjective.StructureId + ": " + optimizationPointObjective.Operator.ToString() + ", dose: " + optimizationPointObjective.Dose.Dose.ToString("0.000") + ", volume: " + optimizationPointObjective.Volume.ToString("0.0") + ", priority: " + optimizationPointObjective.Priority.ToString(); } } if (!strList.Any() && !lowerPTVObjectiveStructures.Any()) { value += "Inget optimeringsPTV hittat, verifera"; status = AutoCheckStatus.MANUAL; } else if (strList.Any() && !lowerPTVObjectiveStructures.Any()) { value += "OptimeringsPTV har ritats men ej används i optimering, vänligen verifera"; status = AutoCheckStatus.WARNING; } else if (strList.Any() && lowerPTVObjectiveStructures.Any()) { value += "OptimeringsPTV har ritats och använts optimering, vänligen verifiera"; status = AutoCheckStatus.MANUAL; } // JSR foreach (OptimizationParameter optimizationParameter in planSetup.OptimizationSetup.Parameters) { if (optimizationParameter.GetType() == typeof(OptimizationPointCloudParameter)) { OptimizationPointCloudParameter optimizationPointCloudParameter = (OptimizationPointCloudParameter)optimizationParameter; details += (details.Length == 0 ? string.Empty : "\r\n") + "Point cloud parameter: " + optimizationPointCloudParameter.Structure.Id + "=" + optimizationPointCloudParameter.Structure.DicomType.ToString(); } else if (optimizationParameter.GetType() == typeof(OptimizationNormalTissueParameter)) { OptimizationNormalTissueParameter optimizationNormalTissueParameter = (OptimizationNormalTissueParameter)optimizationParameter; details += (details.Length == 0 ? string.Empty : "\r\n") + "Normal tissue parameter: priority=" + optimizationNormalTissueParameter.Priority.ToString(); } else if (optimizationParameter.GetType() == typeof(OptimizationExcludeStructureParameter)) { OptimizationExcludeStructureParameter optimizationExcludeStructureParameter = (OptimizationExcludeStructureParameter)optimizationParameter; details += (details.Length == 0 ? string.Empty : "\r\n") + "Exclude structure parameter: " + optimizationExcludeStructureParameter.Structure.Id; } } return(new Tuple <string, string, AutoCheckStatus>(value, details, status)); }
public static IEnumerable <int> _GetMeshBounds(Structure structure, StructureSet SS) { var mesh = structure.MeshGeometry.Bounds; var meshLow = _GetSlice(mesh.Z, SS); var meshUp = _GetSlice(mesh.Z + mesh.SizeZ, SS) + 1; return(Enumerable.Range(meshLow, meshUp)); }
public CoursePlan(Course Course, PlanSetup Plan, string CoursePlanId, StructureSet StructureSet, bool IsCheckedPlan) { this.Course = Course; this.Plan = Plan; this.CoursePlanId = CoursePlanId; this.StructureSet = StructureSet; this.IsCheckedPlan = IsCheckedPlan; }
private ReportData CreateReportData(PartnerModel model, StructureSet structureSet) { return(new ReportData { Patient = model, StructureSet = structureSet }); }
/// <summary> /// Method to remove a single Structure from a given StructureSet /// </summary> /// <param name="ss">StructureSet</param> /// <param name="structureIdToRemove">Structure Id</param> public static void RemoveStructure(StructureSet ss, string structureIdToRemove) { if (ss.Structures.Any(st => st.Id == structureIdToRemove)) { var st = ss.Structures.Single(x => x.Id == structureIdToRemove); ss.RemoveStructure(st); } }
public static StructureSet LoadStructureSetSync(DicomFile dicomFile, IProgress <double> progress) { var loader = new ROILoader(); var structureSet = new StructureSet(); loader.Load(dicomFile, structureSet, progress); return(structureSet); }
public SegShift(VVector mMDisplacement, StructureSet structureSet, Structure structure) { MMDisplacement = mMDisplacement; Structure = structure; SS = structureSet; OriginalContours = GetContours(); Contours = OriginalContours; }
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(); } }
public void Execute(ScriptContext context) { // Check for patient loaded if (context.Patient == null) { MessageBox.Show("Shucks: No patient selected! :("); return; } // Check for patient plan loaded PlanSetup plan = context.PlanSetup; if (plan == null) { MessageBox.Show("Darn: No plan loaded! :( "); return; } //Is there a structure set? if (context.StructureSet == null) { MessageBox.Show("Oh No!: no structure set found! :("); } Patient testPatient = context.Patient; PlanSetup plan1 = context.PlanSetup; Image image = context.Image; Dose dose = plan1.Dose; plan.DoseValuePresentation = DoseValuePresentation.Absolute; //Get the structures: StructureSet structureSet = context.StructureSet; //Make A list for structure names, and a list for structure mean doses double[] organDoses = new double[19]; string[] organNames = new string[19]; organNames[0] = ("stem"); //0 organNames[1] = ("stemPRV"); //1 organNames[2] = ("cord"); //2 organNames[3] = ("cordPRV"); //3 organNames[4] = ("PTV70"); //4 organNames[5] = ("PTV66"); organNames[6] = ("PTV63"); //5 organNames[7] = ("PTV60"); //6 organNames[8] = ("PTV56"); //7 organNames[9] = ("PTV54"); //8 organNames[10] = ("PTV50"); //9 organNames[11] = ("PTV45"); //10 organNames[12] = ("PTV35"); //11 organNames[13] = ("RPar"); //12 organNames[14] = ("LPar"); //13 organNames[15] = ("RSub"); //14 organNames[16] = ("LSub"); //15 organNames[17] = ("OCav"); //16 organNames[18] = ("Lar"); //17 //Make the CSV: DoseExporter(structureSet, organDoses, organNames, plan1, testPatient); }