Ejemplo n.º 1
0
        static void Execute(Application app)
        {
            // very important line. otherwise it will not work. Read here for more info: https://www.reddit.com/r/esapi/comments/hkpa6q/pdsapi_problem_with_createtransientanalysis_in/
            VMS.DV.PD.UI.Base.VTransientImageDataMgr.CreateInstance(true);

            // Iterate through all patients
            int counter = 0;


            foreach (var patientSummary in app.PatientSummaries.Reverse())
            {
                DateTime startDate = new DateTime(2019, 01, 01);

                // Iterate through all patients

                #region useful methods for loop
                double GetMinXSize(PDBeam beam)
                {
                    double minX = 42;

                    foreach (ControlPoint cp in beam.Beam.ControlPoints)
                    {
                        if ((cp.JawPositions.X2 - cp.JawPositions.X1) / 10 < minX)
                        {
                            //jaw size returned in mm. div by 10 for cm.
                            minX = (cp.JawPositions.X2 - cp.JawPositions.X1) / 10;
                        }
                    }
                    return(minX);
                }

                double GetMinYSize(PDBeam beam)
                {
                    double minY = 42;

                    foreach (ControlPoint cp in beam.Beam.ControlPoints)
                    {
                        if ((cp.JawPositions.Y2 - cp.JawPositions.Y1) / 10 < minY)
                        {
                            minY = (cp.JawPositions.Y2 - cp.JawPositions.Y1) / 10;
                        }
                    }
                    return(minY);
                }

                double GetMaxXSize(PDBeam beam)
                {
                    double maxX = 0;

                    foreach (ControlPoint cp in beam.Beam.ControlPoints)
                    {
                        if ((cp.JawPositions.X2 - cp.JawPositions.X1) / 10 > maxX)
                        {
                            //jaw size returned in mm. div by 10 for cm.
                            maxX = (cp.JawPositions.X2 - cp.JawPositions.X1) / 10;
                        }
                    }
                    return(maxX);
                }

                double GetMaxYSize(PDBeam beam)
                {
                    double maxY = 0;

                    foreach (ControlPoint cp in beam.Beam.ControlPoints)
                    {
                        if ((cp.JawPositions.Y2 - cp.JawPositions.Y1) / 10 > maxY)
                        {
                            maxY = (cp.JawPositions.Y2 - cp.JawPositions.Y1) / 10;
                        }
                    }
                    return(maxY);
                }

                double GetAverageYSize(PDBeam beam)
                {
                    double averageY = 0;

                    foreach (ControlPoint cp in beam.Beam.ControlPoints)
                    {
                        averageY += (cp.JawPositions.Y2 - cp.JawPositions.Y1) / 10;
                    }
                    averageY = averageY / beam.Beam.ControlPoints.Count();
                    return(averageY);
                }

                double GetAverageXSize(PDBeam beam)
                {
                    double averageX = 0;

                    foreach (ControlPoint cp in beam.Beam.ControlPoints)
                    {
                        averageX += (cp.JawPositions.X2 - cp.JawPositions.X1) / 10;
                    }
                    averageX = averageX / beam.Beam.ControlPoints.Count();
                    return(averageX);
                }

                #endregion useful methods for loop

                // Retrieve patient information
                Patient p = app.OpenPatient(patientSummary);

                if (p != null)
                {
                    #region Data acquisition (sorry for using try/catch so much -> sometimes a mining process crashes because of one weird patient or field and for this Test-Mining-script I did not want this. Maybe will change it later.)

                    foreach (PDPlanSetup pdPlan in p.PDPlanSetups.OrderByDescending(y => y.HistoryDateTime))
                    {
                        foreach (PDBeam pdBeam in pdPlan.Beams.Where(x => x.Beam.CreationDateTime > startDate))
                        {
                            counter++;

                            // Stop after when a few records have been found
                            if (counter > 10000000)
                            {
                                break;
                            }


                            double gammaResult                     = 0;
                            double maxDoseDifferenceResult         = 0;
                            double averageDoseDifferenceResult     = 0;
                            double maxDoseDifferenceRelResult      = 0;
                            double maxDoseDifferenceRel2Result     = 0;
                            double averageDoseDifferenceRelResult  = 0;
                            double averageDoseDifferenceRel2Result = 0;

                            try
                            {
                                //
                                List <EvaluationTestDesc> evaluationTestDescs = new List <EvaluationTestDesc>();

                                EvaluationTestDesc evaluationTestDesc  = new EvaluationTestDesc(EvaluationTestKind.MaxDoseDifferenceRelative, double.NaN, 0.95, false);
                                EvaluationTestDesc evaluationTestDesc2 = new EvaluationTestDesc(EvaluationTestKind.AverageDoseDifferenceRelative, double.NaN, 0.33, false);

                                evaluationTestDescs.Add(evaluationTestDesc);
                                evaluationTestDescs.Add(evaluationTestDesc2);

                                PDTemplate pDTemplate = new PDTemplate(false, false, false, false, AnalysisMode.Relative, NormalizationMethod.MaxPredictedDose, false, 0.1, ROIType.CIAO, 0, 0.04, 4, false, evaluationTestDescs);

                                PortalDoseImage portaldoseImage = pdBeam.PortalDoseImages.LastOrDefault();

                                DoseImage predictedDoseImage = pdBeam.PredictedDoseImage;

                                PDAnalysis pDAnalysis = new PDAnalysis();

                                try
                                {
                                    pDAnalysis = portaldoseImage.CreateTransientAnalysis(pDTemplate, predictedDoseImage);
                                    EvaluationTest maxDoseDifferenceRel2Test = pDAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.MaxDoseDifferenceRelative);
                                    maxDoseDifferenceRel2Result = Math.Round(maxDoseDifferenceRel2Test.TestValue * 100, 2);

                                    EvaluationTest averageDoseDifferenceRel2Test = pDAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.AverageDoseDifferenceRelative);
                                    averageDoseDifferenceRel2Result = Math.Round(averageDoseDifferenceRel2Test.TestValue * 100, 2);
                                }
                                catch { maxDoseDifferenceRel2Result     = -1;
                                        averageDoseDifferenceRel2Result = -1; }

                                //

                                PDAnalysis pdAnalysis = pdBeam.PortalDoseImages.LastOrDefault().Analyses.OrderBy(x => x.CreationDate).LastOrDefault();
                                if (pdAnalysis == null)
                                {
                                    int pdBeamcount = pdBeam.PortalDoseImages.Count();
                                    pdAnalysis = pdBeam.PortalDoseImages.FirstOrDefault().Analyses.OrderBy(x => x.CreationDate).LastOrDefault();
                                    if (pdAnalysis == null)
                                    {
                                        Console.WriteLine($"No Analysis for: {p.Id}, {pdPlan.Id}, {pdBeam.Id}");
                                        gammaResult                    = -2;
                                        maxDoseDifferenceResult        = -2;
                                        averageDoseDifferenceResult    = -2;
                                        maxDoseDifferenceRelResult     = -2;
                                        averageDoseDifferenceRelResult = -2;
                                    }
                                    else
                                    {
                                        try
                                        {
                                            EvaluationTest gammaTest = pdAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.GammaAreaLessThanOne);
                                            gammaResult = Math.Round(gammaTest.TestValue, 2);
                                        }
                                        catch { gammaResult = -3; }
                                        try
                                        {
                                            EvaluationTest maxDoseDifferenceTest = pdAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.MaxDoseDifference);
                                            if (pdBeam.Beam.ExternalBeam.SerialNumber.ToString() != "2479")
                                            {
                                                maxDoseDifferenceResult = Math.Round(maxDoseDifferenceTest.TestValue * 100, 2);
                                            }
                                            else
                                            {
                                                maxDoseDifferenceResult = Math.Round(maxDoseDifferenceTest.TestValue, 2);
                                            }
                                        }
                                        catch { maxDoseDifferenceResult = -3; }
                                        try
                                        {
                                            EvaluationTest averageDoseDifferenceTest = pdAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.AverageDoseDifference);
                                            if (pdBeam.Beam.ExternalBeam.SerialNumber.ToString() != "2479")
                                            {
                                                averageDoseDifferenceResult = Math.Round(averageDoseDifferenceTest.TestValue * 100, 2);
                                            }
                                            else
                                            {
                                                averageDoseDifferenceResult = Math.Round(averageDoseDifferenceTest.TestValue, 2);
                                            }
                                        }
                                        catch { averageDoseDifferenceResult = -3; }
                                        try
                                        {
                                            EvaluationTest maxDoseDifferenceRelTest = pdAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.MaxDoseDifferenceRelative);
                                            maxDoseDifferenceRelResult = Math.Round(maxDoseDifferenceRelTest.TestValue * 100, 2);
                                        }
                                        catch { maxDoseDifferenceRelResult = -3; }
                                        try
                                        {
                                            EvaluationTest averageDoseDifferenceRelTest = pdAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.AverageDoseDifferenceRelative);
                                            averageDoseDifferenceRelResult = Math.Round(averageDoseDifferenceRelTest.TestValue * 100, 2);
                                        }
                                        catch { averageDoseDifferenceRelResult = -3; }



                                        Console.WriteLine($"{p.Id}, {pdPlan.Id}, {pdBeam.Id},  {maxDoseDifferenceRel2Result},  {averageDoseDifferenceRel2Result}");
                                    }
                                }
                                else
                                {
                                    try { EvaluationTest gammaTest = pdAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.GammaAreaLessThanOne);
                                          gammaResult = Math.Round(gammaTest.TestValue, 2); }
                                    catch { gammaResult = -3; }
                                    try { EvaluationTest maxDoseDifferenceTest = pdAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.MaxDoseDifference);
                                          if (pdBeam.Beam.ExternalBeam.SerialNumber.ToString() != "2479")
                                          {
                                              maxDoseDifferenceResult = Math.Round(maxDoseDifferenceTest.TestValue * 100, 2);
                                          }
                                          else
                                          {
                                              maxDoseDifferenceResult = Math.Round(maxDoseDifferenceTest.TestValue, 2);
                                          } }
                                    catch { maxDoseDifferenceResult = -3; }
                                    try { EvaluationTest averageDoseDifferenceTest = pdAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.AverageDoseDifference);
                                          if (pdBeam.Beam.ExternalBeam.SerialNumber.ToString() != "2479")
                                          {
                                              averageDoseDifferenceResult = Math.Round(averageDoseDifferenceTest.TestValue * 100, 2);
                                          }
                                          else
                                          {
                                              averageDoseDifferenceResult = Math.Round(averageDoseDifferenceTest.TestValue, 2);
                                          } }
                                    catch { averageDoseDifferenceResult = -3; }
                                    try
                                    {
                                        EvaluationTest maxDoseDifferenceRelTest = pdAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.MaxDoseDifferenceRelative);
                                        maxDoseDifferenceRelResult = Math.Round(maxDoseDifferenceRelTest.TestValue * 100, 2);
                                    }
                                    catch { maxDoseDifferenceRelResult = -3; }
                                    try
                                    {
                                        EvaluationTest averageDoseDifferenceRelTest = pdAnalysis.EvaluationTests.FirstOrDefault(x => x.EvaluationTestKind == EvaluationTestKind.AverageDoseDifferenceRelative);
                                        averageDoseDifferenceRelResult = Math.Round(averageDoseDifferenceRelTest.TestValue * 100, 2);
                                    }
                                    catch { averageDoseDifferenceRelResult = -3; }



                                    Console.WriteLine($"{p.Id}, {pdPlan.Id}, {pdBeam.Id}, {maxDoseDifferenceRel2Result},  {averageDoseDifferenceRel2Result}");
                                }
                            }
                            //catch { Console.WriteLine($"Error for: {p.Id}, {p.LastName}^{p.FirstName}, {pdPlans.Id}, {pdBeam.Id} "); }
                            catch {
                                Console.WriteLine($"Error for: {p.Id}, {pdPlan.Id}, {pdBeam.Id} ");
                                gammaResult                    = -1;
                                maxDoseDifferenceResult        = -1;
                                averageDoseDifferenceResult    = -1;
                                maxDoseDifferenceRelResult     = -1;
                                averageDoseDifferenceRelResult = -1;
                            }

                            #region File-Writer -> User-Log-File-Syntax -> mainly copy from other project and therefore maybe strange names

                            string        userLogPath;
                            StringBuilder userLogCsvContent = new StringBuilder();
                            if (Directory.Exists(@"\\Network-Path"))
                            {
                                userLogPath = @"\\Network-Path\PD-Mining\" + System.DateTime.Now.ToString("yyyy-MM-dd") + "_PD-Mining.csv";
                            }
                            else
                            {
                                userLogPath = Path.GetTempFileName() + "_" + System.DateTime.Now.ToString("yyyy-MM-dd") + "_PD - Mining.csv";
                            }


                            // add headers if the file doesn't exist

                            if (!File.Exists(userLogPath))
                            {
                                List <string> dataHeaderList = new List <string>();
                                dataHeaderList.Add("ID");
                                dataHeaderList.Add("Nachname");
                                dataHeaderList.Add("Vorname");
                                dataHeaderList.Add("Kurs");
                                dataHeaderList.Add("Plan");
                                dataHeaderList.Add("Beam");
                                dataHeaderList.Add("MU");
                                dataHeaderList.Add("Energy");
                                dataHeaderList.Add("DoseRate");
                                dataHeaderList.Add("BeamWeight");
                                dataHeaderList.Add("BeamCreation");
                                dataHeaderList.Add("Linac");
                                dataHeaderList.Add("MinX-Jaw");
                                dataHeaderList.Add("MinY-Jaw");
                                dataHeaderList.Add("AverageX-Jaw");
                                dataHeaderList.Add("AverageY-Jaw");
                                dataHeaderList.Add("AverageA-Jaws");

                                dataHeaderList.Add("Gamma");
                                dataHeaderList.Add("MaxDoseDifference[KE]");
                                dataHeaderList.Add("AverageDoseDifference[KE]");
                                dataHeaderList.Add("MaxDoseDifferenceRelative[KE]");
                                dataHeaderList.Add("AverageDoseDifferenceRelative[KE]");
                                dataHeaderList.Add("ExtraTest-MaxDoseDiff[%]");
                                dataHeaderList.Add("ExtraTest-AverageDoseDiff[%]");


                                string concatDataHeader = string.Join(",", dataHeaderList.ToArray());

                                userLogCsvContent.AppendLine(concatDataHeader);
                            }


                            List <object> userStatsList = new List <object>();


                            userStatsList.Add(p.Id);
                            userStatsList.Add(p.LastName.Replace(",", ""));
                            userStatsList.Add(p.FirstName.Replace(",", ""));
                            userStatsList.Add(pdPlan.PlanSetup.Course.Id.Replace(",", ""));
                            userStatsList.Add(pdPlan.Id.Replace(",", ""));
                            userStatsList.Add(pdBeam.Id.Replace(",", ""));
                            userStatsList.Add(Math.Round(pdBeam.PlannedMUs, 0).ToString().Replace(",", "."));
                            userStatsList.Add(pdBeam.Beam.EnergyModeDisplayName.Replace(",", ""));
                            userStatsList.Add(pdBeam.Beam.DoseRate);
                            userStatsList.Add(Math.Round(pdBeam.Beam.WeightFactor, 2).ToString().Replace(",", "."));
                            userStatsList.Add(pdBeam.Beam.CreationDateTime);
                            userStatsList.Add(pdBeam.Beam.ExternalBeam.SerialNumber.ToString() == "1233" ? "Linac2" : (pdBeam.Beam.ExternalBeam.SerialNumber.ToString() == "1334" ? "Linac1" : (pdBeam.Beam.ExternalBeam.SerialNumber.ToString() == "2479"?"Linac3": pdBeam.Beam.ExternalBeam.SerialNumber.ToString())));

                            userStatsList.Add(Math.Round(GetMinXSize(pdBeam), 2).ToString().Replace(",", "."));
                            userStatsList.Add(Math.Round(GetMinYSize(pdBeam), 2).ToString().Replace(",", "."));
                            userStatsList.Add(Math.Round(GetAverageXSize(pdBeam), 2).ToString().Replace(",", "."));
                            userStatsList.Add(Math.Round(GetAverageYSize(pdBeam), 2).ToString().Replace(",", "."));
                            userStatsList.Add(Math.Round(GetAverageXSize(pdBeam) * GetAverageYSize(pdBeam), 2).ToString().Replace(",", "."));
                            userStatsList.Add(gammaResult == -1 ? "Error" : (gammaResult == -2 ? "NoAnalysis" : (gammaResult.ToString().Replace(",", "."))));
                            userStatsList.Add(maxDoseDifferenceResult == -1 ? "Error" : (maxDoseDifferenceResult == -2 ? "NoAnalysis" : (maxDoseDifferenceResult == -3 ? "SpecificFail" : maxDoseDifferenceResult.ToString().Replace(",", "."))));
                            userStatsList.Add(averageDoseDifferenceResult == -1 ? "Error" : (averageDoseDifferenceResult == -2 ? "NoAnalysis" : (averageDoseDifferenceResult == -3 ? "SpecificFail" : averageDoseDifferenceResult.ToString().Replace(",", "."))));
                            userStatsList.Add(maxDoseDifferenceRelResult == -1 ? "Error" : (maxDoseDifferenceRelResult == -2 ? "NoAnalysis" : (maxDoseDifferenceRelResult == -3 ? "SpecificFail" : maxDoseDifferenceRelResult.ToString().Replace(",", "."))));
                            userStatsList.Add(averageDoseDifferenceRelResult == -1 ? "Error" : (averageDoseDifferenceRelResult == -2 ? "NoAnalysis" : (averageDoseDifferenceRelResult == -3 ? "SpecificFail" : averageDoseDifferenceRelResult.ToString().Replace(",", "."))));
                            userStatsList.Add(maxDoseDifferenceRel2Result == -1 ? "Error" : (maxDoseDifferenceRel2Result == -2 ? "NoAnalysis" : maxDoseDifferenceRel2Result.ToString().Replace(",", ".")));
                            userStatsList.Add(averageDoseDifferenceRel2Result == -1 ? "Error" : (averageDoseDifferenceRel2Result == -2 ? "NoAnalysis" : averageDoseDifferenceRel2Result.ToString().Replace(",", ".")));

                            string concatUserStats = string.Join(",", userStatsList.ToArray());

                            userLogCsvContent.AppendLine(concatUserStats);

                            File.AppendAllText(userLogPath, userLogCsvContent.ToString(), Encoding.Unicode);

                            #endregion
                        }
                    }
                }
                #endregion Data acquisition


                // Close the current patient, otherwise we will not be able to open another patient
                app.ClosePatient();
            }
            // purpose: console stays open after finishing
            Console.WriteLine("DataMining finished?");
            Console.ReadLine();
        }
        static void Execute(Application app)
        {
            VMS.DV.PD.UI.Base.VTransientImageDataMgr.CreateInstance(true);
            Stopwatch sw = new Stopwatch();

            sw.Start();
            List <EvaluationTestDesc> evaluationTestDescs = new List <EvaluationTestDesc>();
            EvaluationTestDesc        evaluationTestDesc  = new EvaluationTestDesc(EvaluationTestKind.GammaAreaLessThanOne, double.NaN, 0.95, true);

            evaluationTestDescs.Add(evaluationTestDesc);
            PDTemplate    pDTemplate = new PDTemplate(false, false, false, false, AnalysisMode.CU, NormalizationMethod.MaxEachDose, false, 0.1, ROIType.Field, 10, 0.04, 4, false, evaluationTestDescs);
            List <string> salida     = new List <string>();
            List <string> log        = new List <string>();
            string        encabezado = ("ID;Nombre;Plan;Patología;Campo;Fecha;Fecha Inicio;Resultado");

            File.WriteAllText(@"\\Ariadb-cdt\va_transfer\03_PABLO\Registro.txt", encabezado);

            Console.WriteLine("Iniciando...");
            int           i         = 1;
            List <string> excluidas = new List <string> {
                "CAP-0001", "1-01861-0", "Prueba", "19-24419-0"
            };
            string patologia = "";

            foreach (PatientSummary PacienteSum in app.PatientSummaries)
            {
                if (!excluidas.Contains(PacienteSum.Id))
                {
                    int j = 0;
                    Console.WriteLine(i.ToString() + ". Paciente: " + PacienteSum.Id);
                    Patient Paciente = app.OpenPatient(PacienteSum);
                    if (Paciente.PDPlanSetups.Count() > 0)
                    {
                        foreach (PDPlanSetup pDPlanSetup in Paciente.PDPlanSetups)
                        {
                            if (!pDPlanSetup.PlanSetup.Course.Id.Contains("QA") && pDPlanSetup.Beams.Count > 0)
                            {
                                patologia = Patologia(pDPlanSetup.PlanSetup);
                                foreach (PDBeam campo in pDPlanSetup.Beams)
                                {
                                    if (campo.PortalDoseImages.Count > 1)
                                    {
                                        foreach (PortalDoseImage imagen in campo.PortalDoseImages.Skip(1)) //saltea el primero
                                        {
                                            try
                                            {
                                                //double diasDesdeInicio = Math.Ceiling((imagen.Session.SessionDate - campo.PortalDoseImages.First().Session.SessionDate).TotalDays);
                                                PDAnalysis pDAnalysis = imagen.CreateTransientAnalysis(pDTemplate, campo.PortalDoseImages.First());
                                                string     aux        = Paciente.Id + ";" + Paciente.Name + ";" + pDPlanSetup.Id + ";" + patologia + ";" + campo.Id + ";" + imagen.Session.SessionDate.ToShortDateString() + ";" + campo.PortalDoseImages.First().Session.SessionDate.ToShortDateString() + ";" + Math.Round(pDAnalysis.EvaluationTests.First().TestValue, 4).ToString();
                                                salida.Add(aux);
                                                j++;
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine("Error: ");
                                                log.Add(Paciente.Id + " " + imagen.Id + " " + campo.PortalDoseImages.First() + e.ToString());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    Console.WriteLine("Se analizaron " + j.ToString() + " imágenes");
                    app.ClosePatient();
                    i++;
                    if (i % 40 == 0)
                    {
                        Console.WriteLine("Se escribieron " + (salida.Count - 1).ToString() + " registros");
                        Console.WriteLine("Demoró " + sw.Elapsed.ToString());
                        File.AppendAllLines(@"\\Ariadb-cdt\va_transfer\03_PABLO\Registro.txt", salida.ToArray());
                        File.WriteAllLines(@"\\Ariadb-cdt\va_transfer\03_PABLO\log.txt", log.ToArray());
                        salida.Clear();
                    }
                }
            }
            sw.Stop();
            Console.WriteLine("Se escribieron " + (salida.Count - 1).ToString() + " registros");
            Console.WriteLine("Demoró " + sw.Elapsed.ToString());
            salida.Add(sw.Elapsed.ToString());
            File.AppendAllLines(@"\\Ariadb-cdt\va_transfer\03_PABLO\Registro.txt", salida.ToArray());
            File.WriteAllLines(@"\\Ariadb-cdt\va_transfer\03_PABLO\log.txt", log.ToArray());
            Console.Read();
        }
        private void calc_btn_Click(object sender, RoutedEventArgs e)
        {
            //pulling initial values from the MainWindow class.
            newcontext = PD_AdvAnalysis.MainWindow.newcontext;
            field      = PD_AdvAnalysis.MainWindow.field;
            if (newcontext == null)
            {
                MessageBox.Show("No Patient Selected.");
                return;
            }
            gamma_grd.Children.Clear();
            //here's where all the magic happens!!
            //check the fields are selected
            if (meas_ddl.SelectedIndex == -1)
            {
                MessageBox.Show("Please select a field");
            }
            else if (String.IsNullOrEmpty(startdd_txt.Text) || string.IsNullOrEmpty(startdta_txt.Text) || string.IsNullOrEmpty(enddd_txt.Text) || string.IsNullOrEmpty(enddta_txt.Text) || string.IsNullOrEmpty(deldd_txt.Text) || string.IsNullOrEmpty(deldta_txt.Text) || string.IsNullOrEmpty(tol_txt.Text))
            {
                MessageBox.Show("Please input all numeric parameters in the appropriate box");
            }
            else if (comp_ddl.SelectedItem.ToString() == "No Predicted Image")
            {
                MessageBox.Show("This field contains no predicted image.");
            }
            else
            {
                //check for any empty mandatory boxes with this bool.
                bool any_empty = false;
                //This portion of the code makes the textboxes red if they are empty
                List <Control> mandatory_boxes = new List <Control>()
                {
                    startdd_txt, enddd_txt, deldd_txt, startdta_txt, enddta_txt, deldta_txt, tol_txt
                };
                foreach (Control c in mandatory_boxes)
                {
                    double test_double;
                    if (!Double.TryParse((c as TextBox).Text, out test_double))
                    {
                        (c as TextBox).Focus();
                        (c as TextBox).BorderBrush     = Brushes.Red;
                        (c as TextBox).BorderThickness = new Thickness(2);
                        any_empty = true;
                    }
                    else
                    {
                        (c as TextBox).BorderBrush = Brushes.Transparent;
                    }
                }
                //this is testing to see if the the threshold percentage is added.
                if ((bool)threshold_chk.IsChecked)
                {
                    double test_double2;
                    if (!Double.TryParse((threshold_txt).Text, out test_double2))
                    {
                        (threshold_txt).Focus();
                        (threshold_txt).BorderBrush     = Brushes.Red;
                        (threshold_txt).BorderThickness = new Thickness(2);
                        any_empty = true;
                    }
                    else
                    {
                        (threshold_txt).BorderBrush = Brushes.Transparent;
                    }
                }
                //if the test contains a necessary test parameter, then make sure the test parameter is selected.
                //for instance, the test gamma area < _____ must be > ______ needs to have the parameters defined.
                int[] threshold_parm = new int[] { 4, 5, 8, 9, 12, 13 };

                if (threshold_parm.Contains(EvalTestKind_cmb.SelectedIndex))
                {
                    double test_double3;
                    if (!Double.TryParse((testparam_txt).Text, out test_double3))
                    {
                        (testparam_txt).Focus();
                        (testparam_txt).BorderBrush     = Brushes.Red;
                        (testparam_txt).BorderThickness = new Thickness(2);
                        any_empty = true;
                    }
                    else
                    {
                        (testparam_txt).BorderBrush = Brushes.Transparent;
                    }
                }
                //final catch in case any necessary inputs are missed.
                if (any_empty)
                {
                    return;
                }
                //get beams
                fieldm = field.PortalDoseImages.First(i => i.Id == meas_ddl.SelectedItem.ToString());
                //don't need to do the where clause for the predicted.
                double startdd = Convert.ToDouble(startdd_txt.Text); double endd = Convert.ToDouble(enddd_txt.Text); double deldd = Convert.ToDouble(deldd_txt.Text);
                double startdta = Convert.ToDouble(startdta_txt.Text); double enddta = Convert.ToDouble(enddta_txt.Text); double deldta = Convert.ToDouble(deldta_txt.Text);
                double tol = Convert.ToDouble(tol_txt.Text) / 100;
                double parm;
                Double.TryParse(testparam_txt.Text, out parm);

                //setup portal dosimetry analysis template.
                IEnumerable <EvaluationTestDesc> tested = new List <EvaluationTestDesc> {
                    new EvaluationTestDesc((EvaluationTestKind)EvalTestKind_cmb.SelectedIndex, parm, tol, false)
                };


                //new EvaluationTestDesc()
                //loop through all testable queries
                //columns go here.;
                //lay down the dta and dd labels.
                int bw = 50; int bh = 25;
                int marginx = bw; int marginy = bh;
                for (double i = startdd; i <= endd; i += deldd)
                {
                    TextBox dbox = new TextBox(); dbox.IsReadOnly = true; dbox.Text = String.Format("{0}%", i);
                    dbox.Width = bw; dbox.Background = Brushes.White; dbox.BorderBrush = Brushes.Black;
                    dbox.HorizontalAlignment = HorizontalAlignment.Left; dbox.VerticalAlignment = VerticalAlignment.Top;
                    dbox.Height = bh;
                    dbox.Margin = new Thickness(marginx, 0, 0, 0);
                    gamma_grd.Children.Add(dbox);
                    marginx += bw;
                }
                for (double j = startdta; j <= enddta; j += deldta)
                {
                    TextBox dbox = new TextBox(); dbox.IsReadOnly = true; dbox.Text = String.Format("{0}mm", j);
                    dbox.Width = bw; dbox.Background = Brushes.White; dbox.BorderBrush = Brushes.Black;
                    dbox.HorizontalAlignment = HorizontalAlignment.Left; dbox.VerticalAlignment = VerticalAlignment.Top;
                    dbox.Height = bh;
                    dbox.Margin = new Thickness(0, marginy, 0, 0);
                    marginy    += bh;
                    gamma_grd.Children.Add(dbox);
                }
                marginx = bw; marginy = 0;

                //now calculate all the boxes for the matrix.
                for (double i = startdta; i <= enddta; i += deldta)
                {
                    //lay down a new header for the column.
                    marginy += bh;
                    marginx  = 0;
                    //rows go here
                    double margins_txt;
                    Double.TryParse(marg_txt.Text, out margins_txt);
                    double th_txt;
                    double.TryParse(threshold_txt.Text, out th_txt);
                    int analysisMode = (bool)abs_rdb.IsChecked ? 0 : 2;
                    for (double j = startdd; j <= endd; j += deldd)
                    {
                        marginx += bw;
                        //lay down an initial grid for the dta and dd
                        TextBox header_box = new TextBox();
                        //modify the template
                        PDTemplate template1 = new PDTemplate(false, false, false, (AnalysisMode)analysisMode, (NormalizationMethod)Normalizaton_cmb.SelectedIndex, (bool)threshold_chk.IsChecked, th_txt, (ROIType)ROITypes_cmb.SelectedIndex, margins_txt, j / 100, i, false, tested);
                        //apply the template to the analysis.
                        PDAnalysis analysis = fieldm.CreateTransientAnalysis(template1, field.PredictedDoseImage);
                        //This code determines if the Gamma Test Parameters are in absolute or relative value
                        int[]  selec_in = new int[] { 0, 1, 4, 5, 8, 9, 12, 13 };
                        double gamma_pass;

                        if (selec_in.Contains(EvalTestKind_cmb.SelectedIndex))
                        {
                            gamma_pass = analysis.EvaluationTests.First().TestValue * 100;
                        }
                        else
                        {
                            gamma_pass = analysis.EvaluationTests.First().TestValue;
                        }
                        //The Code below shows the results from the gamma test. It is color coded to show where the gamma passes or failes.
                        TextBox gamma_box = new TextBox(); gamma_box.IsReadOnly = true; gamma_box.Text = gamma_pass.ToString("F3");
                        gamma_box.Width = bw; gamma_box.Height = bh; gamma_box.Background = gamma_pass < tol * 100 ? Brushes.Pink : Brushes.LightGreen; gamma_box.BorderBrush = Brushes.Black;
                        gamma_box.HorizontalAlignment = HorizontalAlignment.Left; gamma_box.VerticalAlignment = VerticalAlignment.Top;
                        gamma_box.Margin = new Thickness(marginx, marginy, 0, 0);
                        gamma_grd.Children.Add(gamma_box);
                    }
                }
            }
        }