def chooseRoi(prompt='Choose an ROI and press OK', title='Choose an ROI'):
    """
    Ask user to select an ROI from the ROIs in the active patient
    """
    case = rsl.get_current('Case')
    roiNames = [roi.Name for roi in case.PatientModel.RegionsOfInterest]
    return getChoiceFromList(choiceList=roiNames, prompt=prompt, title=title)
Exemplo n.º 2
0
def main():
    """
    Function will take the optional input of the protocol file name
    :return:
    """
    filename = None
    status = UserInterface.ScriptStatus(steps=[
        'Finding correct protocol', 'Matching Structure List',
        'Getting target Doses', 'Adding Goals'
    ],
                                        docstring=__doc__,
                                        help=__help__)

    protocol_folder = r'../protocols'
    institution_folder = r'UW'
    path_protocols = os.path.join(os.path.dirname(__file__), protocol_folder,
                                  institution_folder)

    # Get current patient, case, exam, and plan
    # note that the interpreter handles a missing plan as an Exception
    try:
        patient = connect.get_current("Patient")
    except SystemError:
        raise IOError("No Patient loaded. Load patient case and plan.")

    try:
        case = connect.get_current("Case")
def choosePlan(prompt='Choose a Plan and press OK', title='Choose a Plan'):
    """
    Ask user to select an Image from the Images in the active patient
    """
    case = rsl.get_current('Case')
    planNames = [pln.Name for pln in case.TreatmentPlans]
    return getChoiceFromList(choiceList=planNames, prompt=prompt, title=title)
Exemplo n.º 4
0
def main():
    # UW Inputs
    # If machines names change they need to be modified here:
    institution_inputs_machine_name = ['TrueBeamSTx', 'TrueBeam']
    institution_inputs_sites = ['Liver', 'Lung', 'Breast']
    institution_inputs_motion = ['MIBH', 'MEBH', 'Free-Breathing']
    status = UserInterface.ScriptStatus(steps=[
        'SimFiducials point declaration', 'Enter Plan Parameters',
        'Make plan for dry run', 'Confirm iso placement'
    ],
                                        docstring=__doc__,
                                        help=__help__)
    try:
        patient = connect.get_current('Patient')
        case = connect.get_current("Case")
        examination = connect.get_current("Examination")
        patient_db = connect.get_current('PatientDB')
    except:
        UserInterface.WarningBox(
            'This script requires a patient, case, and exam to be loaded')
        sys.exit('This script requires a patient, case, and exam to be loaded')

    # Capture the current list of ROI's to avoid saving over them in the future
    rois = case.PatientModel.StructureSets[examination.Name].RoiGeometries

    # Capture the current list of POI's to avoid a crash
    pois = case.PatientModel.PointsOfInterest

    # Find all targets
    plan_targets = []
    for r in case.PatientModel.RegionsOfInterest:
        if r.OrganData.OrganType == 'Target':
            plan_targets.append(r.Name)
def choosePoi(prompt='Choose a Point and press OK', title='Choose a POI'):
    """
    Ask user to select an POI from the POIs in the active patient
    """
    case = rsl.get_current('Case')
    poiNames = [poi.Name for poi in case.PatientModel.PointsOfInterest]
    return getChoiceFromList(choiceList=poiNames, prompt=prompt, title=title)
def chooseImage(prompt='Choose an Image and press OK',
                title='Choose an Image'):
    """
    Ask user to select an Image from the Images in the active patient
    """
    case = rsl.get_current('Case')
    imageNames = [img.Name for img in case.Examinations]
    return getChoiceFromList(choiceList=imageNames, prompt=prompt, title=title)
def main():
    try:
        Patient = connect.get_current("Patient")
    except SystemError:
        raise IOError("No Patient loaded. Load patient case and plan.")

    try:
        case = connect.get_current("Case")
    def get_current(self):
        try:
            patient = get_current('Patient')
            self.patient_name = patient.PatientName.replace(' ', '^')
            self.patient_id = patient.PatientID
        except SystemError:
            self.patient_name = '<No patient selected>'
            self.patient_id = '<No patient ID>'
        except NameError:
            # to allow python-sphinx to process this code when not connected
            # to RayStation
            pass

        try:
            plan = get_current('Plan')
            self.plan_name = plan.Name
        except SystemError:
            self.plan_name = '<No plan selected>'
        except NameError:
            # to allow python-sphinx to process this code when not connected
            # to RayStation
            pass

        try:
            beamset = get_current('BeamSet')
            self.beamset_name = beamset.DicomPlanLabel
        except SystemError:
            self.beamset_name = '<No beamset selected>'
        except NameError:
            # to allow python-sphinx to process this code when not connected
            # to RayStation
            pass

        try:
            exam = get_current('Examination')
            self.exam_name = exam.Name
        except SystemError:
            self.exam_name = '<No examination selected>'
        except NameError:
            # to allow python-sphinx to process this code when not connected
            # to RayStation
            pass

        try:
            self.user = getenv('USERNAME')

            self.extra = {
                'user': self.user,
                'patient': self.patient_name,
                'patient_id': self.patient_id,
                'plan': self.plan_name,
                'beamset': self.beamset_name,
                'examination': self.exam_name
            }
        except:
            pass
Exemplo n.º 9
0
def get_object_for_type(object_type):
    try:
        import connect as rsl
    except:
        pass

    if object_type == "Machine":
        return rsl.get_current("MachineDB").GetTreatmentMachine(machineName=rsl.get_current("BeamSet").MachineReference.MachineName, lockMode=None)
    else:
        return rsl.get_current(object_type)
Exemplo n.º 10
0
def main():
    # Get current patient, case, exam, and plan
    # note that the interpreter handles a missing plan as an Exception
    try:
        patient = connect.get_current("Patient")
    except SystemError:
        raise IOError("No Patient loaded. Load patient case and plan.")

    try:
        case = connect.get_current("Case")
Exemplo n.º 11
0
def main():

    # Get current 'Patient' object plus 'Case' and 'Plan' names
    try: 
        patient = rsl.get_current('Patient')
    except:
        RmhMessageBox.message("No patient selected!", title=DEFAULT_TITLE)
        return
    
    try:     
        case = rsl.get_current('Case')
Exemplo n.º 12
0
def main():
    # Get current patient, case, and exam
    try:
        patient = connect.get_current('Patient')
        case = connect.get_current('Case')
        exam = connect.get_current('Examination')
        patient.Save()

    except Exception:
        UserInterface.WarningBox('This script requires a patient to be loaded')
        sys.exit('This script requires a patient to be loaded')

    # Start timer
    tic = time.time()

    # Start script status
    status = UserInterface.ScriptStatus(steps=['Enter plan information for TPO',
                                               'Clean up structure list',
                                               'Approve structures',
                                               'Initialize plan and beamsets',
                                               'Set clinical goals',
                                               'Add planning goals',
                                               'Generate TPO'],
                                        docstring=__doc__,
                                        help=__help__)

    # Display input dialog box for TPO
    status.next_step(text='In order to approve the plan and create a TPO, please fill out the displayed form ' +
                          'with information about the plan. Once completed, click Continue.')

    tpo = UserInterface.TpoDialog(patient=patient, title='TPO Dialog', match=0.6, rx=3, priority=priority)
    tpo.load_protocols(os.path.join(os.path.dirname(__file__), protocol_folder, institution_folder))
    response = tpo.show(case=case, exam=exam)
    if response == {}:
        status.finish('Script cancelled, inputs were not supplied')
        sys.exit('Script cancelled')

    # Re-name/organize structures based on TPO form
    status.next_step(text='The structures are now being renamed and organized based on your input...')
    changes = 0

    for roi in case.PatientModel.RegionsOfInterest:
        approved = False
        for a in case.PatientModel.StructureSets[exam.Name].ApprovedStructureSets:
            try:
                if a.ApprovedRoiStructures[roi.Name].OfRoi.RoiNumber > 0 and a.Review.ApprovalStatus == 'Approved':
                    approved = True
                    logging.debug('Structure {} was approved by {} and therefore will not be modified'.
                                  format(roi.Name, a.Review.ReviewerName))
                    break

            except Exception:
                logging.debug('Structure {} is not list approved by {}'.format(roi.Name, a.Review.ReviewerName))
Exemplo n.º 13
0
def main():
    protocol = r'../protocols/SampleGoal.xml'
    #protocol_file = r'SampleGoal.xml'
    protocol_name = os.path.join(os.path.dirname(__file__), protocol)

    tree = xml.etree.ElementTree.parse(protocol_name)
    for g in tree.findall('//goals/roi'):
        print 'Adding goal ' + Goals.print_goal(g, 'xml')
        Goals.add_goal(g, connect.get_current('Plan'))
    ui = connect.get_current('ui')
    ui.TitleBar.MenuItem['Plan Optimization'].Click()
    ui.TitleBar.MenuItem['Plan Optimization'].Popup.MenuItem[
        'Plan Optimization'].Click()
    ui.Workspace.TabControl['DVH'].TabItem['Clinical Goals'].Select()
def main():

    # Get current patient, case, and machine DB
    machine_db = connect.get_current('MachineDB')
    try:
        patient = connect.get_current('Patient')
        case = connect.get_current('Case')
        patient.Save()

    except Exception:
        UserInterface.WarningBox('This script requires a patient to be loaded')
        sys.exit('This script requires a patient to be loaded')

    # Start script status
    status = UserInterface.ScriptStatus(steps=[
        'Verify CT density table and external are set',
        'Enter script runtime options'
    ],
                                        docstring=__doc__,
                                        help=__help__)

    # Confirm a CT density table, boxes, and external contour was set
    status.next_step(
        text=
        'Prior to execution, the script will make sure that a CT density table, External, '
        +
        'and Box_1/Box_2 contours are set for the current plan. Also, at least one contour must be '
        + 'overridden to water.')
    time.sleep(1)

    examination = connect.get_current('Examination')
    if examination.EquipmentInfo.ImagingSystemReference is None:
        connect.await_user_input(
            'The CT imaging system is not set. Set it now, then continue the script.'
        )
        patient.Save()

    else:
        patient.Save()

    external = False
    bounds = [-30, 30, 0, 40, -30, 30]
    for r in case.PatientModel.RegionsOfInterest:
        if r.Type == 'External':
            external = True
            b = case.PatientModel.StructureSets[
                examination.Name].RoiGeometries[r.Name].GetBoundingBox()
            bounds = [b[0].x, b[1].x, b[0].y, b[1].y, b[0].z, b[1].z]
Exemplo n.º 15
0
def find_scope(level=None, find_scope=False):
    """
    Find the current available scope in RS at the level of level.
        If level is used, and the level is not in the current scope, produce a fault
        If find_scope is used, go as deep as possible and return a dictionary of all levels
            with None used for those not in current scope.
    :param level: if specified, return the RS object at level if it exists
    :param find_scope: if True, return a dict of the available scopes
    :return: if level is specified the RS object is returned.
        If find_scope, then a dict of plan variables is used
    """

    # Find the deepest available scope and return a dict with available names
    scope = {}
    scope_levels = ['ui', 'Patient', 'Case', 'Examination', 'Plan', 'BeamSet']

    for l in scope_levels:
        try:
            rs_obj = connect.get_current(l)
        except:
            rs_obj = None
        if l == level:
            if rs_obj is None:
                raise IOError("No {} loaded, load {}".format(l, l))
            else:
                return rs_obj
        elif find_scope:
            scope[l] = rs_obj

    if find_scope:
        return scope
Exemplo n.º 16
0
def chooseBeams(prompt='Select Beams and press OK', title='Choose from Beams'):
    """
    Ask user to select an Image from the Images in the active patient
    """
    bs = rsl.get_current('BeamSet')
    beamNames = [bm.Name for bm in bs.Beams]
    return getChoicesFromList(choiceList=beamNames, prompt=prompt, title=title)
Exemplo n.º 17
0
def main():
    try:
        patient = connect.get_current('Patient')
        case = connect.get_current('Case')
        examination = connect.get_current("Examination")
        patient_db = connect.get_current('PatientDB')
        plan = connect.get_current('Plan')
        beamset = connect.get_current('BeamSet')
    except Exception as ex:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(ex).__name__, ex.args)
        UserInterface.WarningBox(message)
        UserInterface.WarningBox(
            'This script requires a patient, case, and beamset to be loaded')
        sys.exit(
            'This script requires a patient, case, and beamset to be loaded')

    # Capture the current list of ROI's to avoid saving over them in the future
    targets = so.find_targets(case)
    for t in targets:
        patient.Set2DvisualizationForRoi(RoiName=t, Mode='filled')

    max_dose = find_max_dose_in_plan(examination=examination,
                                     case=case,
                                     plan=plan)

    try:
        ref_dose = beamset.Prescription.PrimaryDosePrescription.DoseValue
    except AttributeError:
        ref_dose = max_dose
        logging.info(
            'Neither prescription nor max dose are defined in the plan. Setting to default max_dose'
        )

    isodose_reconfig(case=case, ref_dose=ref_dose, max_dose=max_dose)
Exemplo n.º 18
0
def get_machine(machine_name):
    """Finds the current machine name from the list of currently commissioned machines
    :param: machine_name (name of the machine in raystation,
    usually this is machine_name = beamset.MachineReference.MachineName
    return: machine (RS object)"""
    machine_db = connect.get_current('MachineDB')
    machine = machine_db.GetTreatmentMachine(machineName=machine_name,
                                             lockMode=None)
    return machine
Exemplo n.º 19
0
def main():

    # Import packages
    import sys
    import os
    import connect
    import csv
    import UserInterface
    from collections import namedtuple

    # Set the current scope of RayStation to the open patient.
    try:
        patient = connect.get_current("Patient")
    except SystemError:
        raise IOError("No Patient loaded. Load patient case and plan.")

    try:
        case = connect.get_current("Case")
Exemplo n.º 20
0
def main():
    import connect
    import UserInterface
    import sys

    plan = connect.get_current("Plan")
    beam_set = connect.get_current(
        "BeamSet")  # for the currently selected beam set
    QA_Plan_Name = beam_set.DicomPlanLabel + "QA"

    try:
        patient = connect.get_current('Patient')
        case = connect.get_current('Case')
        exam = connect.get_current('Examination')
        plan = connect.get_current('Plan')
        beamset = connect.get_current("BeamSet")

    except Exception:
        UserInterface.WarningBox(
            'This script requires a Beam Set to be loaded')
        sys.exit('This script requires a Beam Set to be loaded')

    # Click magic
    ui = connect.get_current('ui')
    ui.TitleBar.MenuItem['QA Preparation'].Button_QA_Preparation.Click()

    try:
        beamset.CreateQAPlan(PhantomName="50cm Cube_2",
                             PhantomId="50cm Cube",
                             QAPlanName=QA_Plan_Name,
                             IsoCenter={
                                 'x': 0,
                                 'y': -30,
                                 'z': 25
                             },
                             DoseGrid={
                                 'x': 0.25,
                                 'y': 0.25,
                                 'z': 0.25
                             },
                             GantryAngle=0,
                             CollimatorAngle=None,
                             CouchAngle=0,
                             ComputeDoseWhenPlanIsCreated=True,
                             NumberOfMonteCarloHistories=500000)
    except Exception:
        UserInterface.WarningBox('QA Plan failed to create')
        sys.exit('QA Plan failed to create')
Exemplo n.º 21
0
def main(m_local, m_module, m_library, m_logs, m_api, m_token):
    # Link .NET assemblies
    clr.AddReference('System.Windows.Forms')
    clr.AddReference('System.Drawing')
    import System

    try:
        patient = connect.get_current('Patient')
        pat_id = patient.PatientID
    except Exception:
        patient = False
        pat_id = 'NO_PATIENT'

    # Configure file logging
    logging.captureWarnings(True)
    if m_logs != '':
        m_logs_dir = os.path.join(m_logs, pat_id)
        if not os.path.isdir(m_logs_dir):
            os.mkdir(m_logs_dir)
        logging.basicConfig(filename=os.path.normpath('{}/{}.txt'.format(m_logs_dir, pat_id)),
                            level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S', filemode='a',
                            format='%(asctime)s\t%(levelname)s\t%(filename)s: %(message)s')

    # Log system, RayStation, and patient info
    ui = connect.get_current('ui')
    logging.debug('*** Python {} ***'.format(sys.version))

    logging.debug('*** RayStation {} ***'.format(ui.GetApplicationVersion()))
    logging.debug('*** Server: {} ***'.format(socket.getfqdn()))
    logging.debug('*** User: {} ***'.format(getpass.getuser()))

    if pat_id != 'NO_PATIENT':
        logging.info('*** Patient: {}, {} ***'.format(pat_id, patient.Name))

    else:
        logging.info('*** Patient: NO_PATIENT ***')

    try:
        case = connect.get_current('Case')
        logging.info('*** Case: {} ***'.format(case.CaseName))
Exemplo n.º 22
0
def main():
    
    patient = rsl.get_current("Patient")
    case = rsl.get_current("Case")
    
    #Select original
    original_scan = select_scan(case, "Select previous planning scan (target)")
    old_exam = case.Examinations[original_scan]

    #Select rescan
    rescan = select_scan(case, "Select rescan (reference)")   
    new_exam = case.Examinations[rescan]
    
   
    makeDIR( old_exam, new_exam, patient=patient, case=case )
    
    
    
    
    
    
    
def main():

    # Get current patient, case, and machine DB
    machine_db = connect.get_current('MachineDB')
    try:
        patient = connect.get_current('Patient')
        case = connect.get_current('Case')

    except Exception:
        UserInterface.WarningBox('This script requires a patient to be loaded')
        sys.exit('This script requires a patient to be loaded')

    # Start script status
    status = UserInterface.ScriptStatus(steps=['Verify CT density table and external are set',
                                               'Select folder to import DICOM RT plans from',
                                               'Select folder to export calculated dose to',
                                               'Choose import overrides and calculation options',
                                               'Import, re-calculate, and export plans'],
                                        docstring=__doc__,
                                        help=__help__)

    # Confirm a CT density table and external contour was set
    status.next_step(text='Prior to execution, the script will make sure that a CT density table and External ' +
                          'contour are set for the current plan. These are required for dose calculation.')
    examination = connect.get_current('Examination')
    if examination.EquipmentInfo.ImagingSystemReference is None:
        connect.await_user_input('The CT imaging system is not set. Set it now, then continue the script.')
        patient.Save()

    else:
        patient.Save()

    external = False
    for r in case.PatientModel.RegionsOfInterest:
        if r.Type == 'External':
            external = True
Exemplo n.º 24
0
def main():

    # Offer to continue or abort without saving
    stopOption.giveStopOption(
        "\n\n\tAdd couch and set localisation before continuing     \n\n\tAll changes will be saved\n\tDo you wish to continue?",
        "     --- WARNING --- ")

    patient = rsl.get_current("Patient")
    case = rsl.get_current("Case")
    plan = rsl.get_current("Plan")
    exam = rsl.get_current("Examination")
    beam_set = rsl.get_current("BeamSet")

    tot_nr_fx = len([tf for tf in plan.TreatmentCourse.TreatmentFractions])
    adapted_ct_name = _find_ReplanCT(case, beam_set)
    adapt_exam = case.Examinations[adapted_ct_name]
    adapt_from_fx = _find_adaptionNumFractions(adapt_exam, tot_nr_fx)

    prompt = "Select new prescription dose level.\n(Cancel to keep current prescription)"
    title = "Dose Escalation"
    pres = chooseFromList.getChoiceFromList(choiceList=doseEscalatePrescList,
                                            prompt=prompt,
                                            title=title)

    #Make message box summarising all details of replan
    max_arc_deliv = plan.PlanOptimizations[
        0].OptimizationParameters.TreatmentSetupSettings[0].BeamSettings[
            0].ArcConversionPropertiesPerBeam.MaxArcDeliveryTime
    p_orig = str(beam_set.Prescription.PrimaryDosePrescription.DoseValue)
    p_new = ""
    if pres is None:
        p_new = p_orig + " cGy"
    else:
        p_new = pres
    msg = 'Creating adapted plan:\n\n'
    msg = msg + "    Adapting plan: " + plan.Name + "\n"
    msg = msg + "    Adapting exam: " + exam.Name + " (" + str(
        exam.GetExaminationDateTime(
        )) + ") to " + adapt_exam.Name + " (" + str(
            adapt_exam.GetExaminationDateTime()) + ")     \n"
    msg = msg + "    Prescription from " + p_orig + " to " + p_new + "\n"
    msg = msg + "    Adapting from fraction " + str(int(adapt_from_fx)) + "\n"
    msg = msg + "    Max arc delivery time = " + str(max_arc_deliv) + " s\n"
    RmhMessageBox.message(msg, 'Please check details')

    makeAdaptedPlan(adapt_from_fx,
                    adapted_ct_name,
                    tot_nr_fx=tot_nr_fx,
                    newTargetPresc=pres,
                    patient=patient,
                    case=case,
                    plan=plan,
                    beam_set=beam_set)
Exemplo n.º 25
0
def main():
    """ Temp chunk of code to try to open an xml file"""
    try:
        patient = connect.get_current('Patient')
        case = connect.get_current("Case")
        examination = connect.get_current("Examination")
        plan = connect.get_current("Plan")
        beamset = connect.get_current("BeamSet")
    except:
        logging.warning("patient, case and examination must be loaded")

    protocol_folder = r'../protocols'
    institution_folder = r'UW'
    file = 'planning_structs_conventional.xml'
    path_protocols = os.path.join(os.path.dirname(__file__), protocol_folder,
                                  institution_folder, file)
    tree = select_objectives(filename=path_protocols)
    logging.debug("selected file {}".format(path_protocols))
    # TODO::
    # Extend this for multiple objective sets found within a file
    # Consider adding functionality for protocols, orders, etc...
    # Parse each type in a separate function
    # Add matching elements
    # Add objective function should know whether something is absolute or relative for dose and volume
    if tree.getroot().tag == 'objectiveset':
        logging.debug("parsing xml: {}".format(file))
        n = tree.find('name').text
        logging.debug('Found protocol {} in {}'.format(n, file))
        objectiveset = tree.getroot()
        objectives = objectiveset.findall('./objectives/roi')
        for o in objectives:
            o_name = o.find('name').text
            o_type = o.find('type').text
            logging.debug("objective: {} found with type {}".format(
                o_name, o_type))
            # TESTING ONLY - TO DO ELIMINATE THIS NEXT LINE
            if o.find('dose').attrib['units'] == '%':
                s_dose = '50'
            else:
                s_dose = None

            add_objective(o,
                          case=case,
                          plan=plan,
                          beamset=beamset,
                          s_roi=None,
                          s_dose=s_dose,
                          s_weight=None,
                          restrict_beamset=None)
    else:
        logging.debug(
            'Could not find objective set using tree = {}'.format(tree))
Exemplo n.º 26
0
def export(number):
  # Database:
  db = get_current('PatientDB')
  # Query patients:
  patients = db.QueryPatientInfo(Filter = {'LastName': name(number)})
  if len(patients) != 1:
    LogFile.write('Unexpected result! Got ' + str(len(patients)) + ' patient(s) for query ' + name(number) + ' \n')
    sys.exit()
  else:
    # Load patient and case:
    patient = db.LoadPatient(PatientInfo = patients[0])
    case = patient.Cases[0]
    # Create a folder for this patient:
    mkdir(patient.Name)
    case.ScriptableDicomExport(
      ExportFolderPath = path.join(getcwd(), patient.Name),
      Examinations = [e.Name for e in case.Examinations],
      RtStructureSetsForExaminations = [e.Name for e in case.Examinations],
      IgnorePreConditionWarnings = True
    )
    print('Export complete for patient {}'.format(name(number)))
    LogFile.write('Export complete for patient ' + patient.Name + ' \n')
Exemplo n.º 27
0
def select_treatment_adaptation_tab():
    """ Attempt to move to treatment adaptation tab """

    ui = rsl.get_current('ui')

    try:
        ui.TitleBar.MenuItem[
            'Treatment Adaptation'].Button_Treatment_Adaptation.Click()
    except SystemError as se:
        if "is not present in the collection" in se.message:
            print("No 'Treatment Adaptation' Title tab")
    try:
        ui.TabControl_Modules.TabItem[
            'Adaptive Replanning'].Button_Adaptive_Replanning.Click()
    except SystemError as se:
        if "is not present in the collection" in se.message:
            print("No 'Adaptive Replanning' tab")
    # Also bring up scripting tab
    try:
        ui.ToolPanel.TabItem._Scripting.Select()
    except SystemError as se:
        if "is not present in the collection" in se.message:
            print("No 'Scripting' tab in ToolPanel")
Exemplo n.º 28
0
def get_dvh(roi_list):
    """Get dose-volume histogram curves from current plan.

    Parameters
    ----------
    roi_list : list of str
        Regions of interest to include in results.

    Returns
    -------
    dict
        Dose and volumes for given regions of interest.

    """
    dose = connect.get_current('Plan').TreatmentCourse.TotalDose
    max_dose = max([
        dose.GetDoseStatistic(RoiName=roi, DoseType='Max') for roi in roi_list
    ])
    dvh_dict = {'Dose': np.linspace(0, max_dose, 100)}
    for roi in roi_list:
        vals = dose.GetRelativeVolumeAtDoseValues(RoiName=roi,
                                                  DoseValues=dvh_dict['Dose'])
        dvh_dict[roi] = vals
    return dvh_dict
Exemplo n.º 29
0
def main():
    """ Temp chunk of code to try to open an xml file"""
    try:
        patient = connect.get_current('Patient')
        case = connect.get_current("Case")
        examination = connect.get_current("Examination")
        plan = connect.get_current("Plan")
        beamset = connect.get_current("BeamSet")
    except:
        logging.warning("patient, case and examination must be loaded")

    file = 'planning_structs_conventional.xml'
    #obj = {'function_type': 'MinEud',
    #       'roi_name': 'PTV1',
    #       'constraint': False,
    #       'eud_a': 3,
    #       'dose': 50}
    add_objective(plan=plan,
                  function_type='MinEud',
                  roi_name='PTV1',
                  eud_a=3,
                  dose=50)
Exemplo n.º 30
0
                    roi.ExcludeFromExport = True

                except Exception:
                    logging.debug(
                        'Exclude flag could not be set on structure {}'.format(
                            roi.Name))

    # Prompt user to approve structures
    logging.debug('Prompting user to approve structure set')
    status.next_step(
        text=
        'You will now be prompted to approve the structure set. Once completed, continue the script.'
    )

    if changes > 0:
        ui = connect.get_current('ui')
        ui.TitleBar.MenuItem['Patient Modeling'].Click()
        ui.TitleBar.MenuItem['Patient Modeling'].Popup.MenuItem[
            'Structure Definition'].Click()
        ui.TabControl_ToolBar.Approval.Select()
        ui.ToolPanel.TabItem._Scripting.Select()
        connect.await_user_input(
            'Approve the structure set now, then continue the script')

    # Create new plan (ICDa-z Protocol)
    status.next_step(
        text=
        'A new plan will now be created and populated with the TPO template clinical goals...'
    )
    patient.Save()