示例#1
0
def reinitialize_roi_categories_in_database():
    roi_map = DatabaseROIs()
    dvh_data = QuerySQL('DVHs', "mrn != ''")
    cnx = DVH_SQL()

    for i in range(0, len(dvh_data.roi_name)):
        uid = dvh_data.study_instance_uid[i]
        physician = get_physician_from_uid(uid)
        roi_name = dvh_data.roi_name[i]

        new_physician_roi = roi_map.get_physician_roi(physician, roi_name)
        new_institutional_roi = roi_map.get_institutional_roi(
            physician, roi_name)

        print(i,
              physician,
              new_institutional_roi,
              new_physician_roi,
              roi_name,
              sep=' ')
        condition = "study_instance_uid = '" + uid + "'" + "and roi_name = '" + roi_name + "'"
        cnx.update('DVHs', 'physician_roi', new_physician_roi, condition)
        cnx.update('DVHs', 'institutional_roi', new_institutional_roi,
                   condition)

    cnx.close()
示例#2
0
def recalculate_total_mu(*custom_condition):

    if custom_condition:
        custom_condition = " AND " + custom_condition[0]
    else:
        custom_condition = ''

    # Get entire table
    beam_data = QuerySQL('Beams', "mrn != ''" + custom_condition)
    cnx = DVH_SQL()

    plan_mus = {}
    for i in range(0, len(beam_data.study_instance_uid)):
        uid = beam_data.study_instance_uid[i]
        beam_mu = beam_data.beam_mu[i]
        fxs = float(beam_data.fx_count[i])
        if uid not in list(plan_mus):
            plan_mus[uid] = 0.

        plan_mus[uid] += beam_mu * fxs

    for uid in list(plan_mus):
        cnx.update('Plans', 'total_mu', str(round(plan_mus[uid], 1)),
                   "study_instance_uid = '%s'" % uid)

    cnx.close()
示例#3
0
    def update_plan_data(self, uids):

        cond_str = "study_instance_uid in ('" + "', '".join(uids) + "')"
        plan_data = QuerySQL('Plans', cond_str)

        # Determine Groups
        groups = self.get_group_list(plan_data.study_instance_uid)

        anon_id = [
            self.anon_id_map[plan_data.mrn[i]]
            for i in range(len(plan_data.mrn))
        ]

        attributes = [
            'mrn', 'age', 'birth_date', 'dose_grid_res', 'fxs',
            'patient_orientation', 'patient_sex', 'physician', 'rx_dose',
            'sim_study_date', 'total_mu', 'tx_modality', 'tx_site',
            'heterogeneity_correction', 'baseline'
        ]
        data = {attr: getattr(plan_data, attr) for attr in attributes}
        data['anon_id'] = anon_id
        data['group'] = groups
        data['uid'] = plan_data.study_instance_uid

        self.sources.plans.data = data
示例#4
0
    def update_beam_data(self, uids):

        cond_str = "study_instance_uid in ('" + "', '".join(uids) + "')"
        beam_data = QuerySQL('Beams', cond_str)

        groups = self.get_group_list(beam_data.study_instance_uid)

        anon_id = [
            self.anon_id_map[beam_data.mrn[i]]
            for i in range(len(beam_data.mrn))
        ]

        attributes = [
            'mrn', 'beam_dose', 'beam_energy_min', 'beam_energy_max',
            'beam_mu', 'beam_mu_per_deg', 'beam_mu_per_cp', 'beam_name',
            'beam_number', 'beam_type', 'scan_mode', 'scan_spot_count',
            'control_point_count', 'fx_count', 'fx_grp_beam_count',
            'fx_grp_number', 'gantry_start', 'gantry_end', 'gantry_rot_dir',
            'gantry_range', 'gantry_min', 'gantry_max', 'collimator_start',
            'collimator_end', 'collimator_rot_dir', 'collimator_range',
            'collimator_min', 'collimator_max', 'couch_start', 'couch_end',
            'couch_rot_dir', 'couch_range', 'couch_min', 'couch_max',
            'radiation_type', 'ssd', 'treatment_machine'
        ]
        data = {attr: getattr(beam_data, attr) for attr in attributes}
        data['anon_id'] = anon_id
        data['group'] = groups
        data['uid'] = beam_data.study_instance_uid

        self.sources.beams.data = data
示例#5
0
    def __init__(self, uid=None, dvh_condition=None):
        """
        This class will retrieve DVHs and other data in the DVH SQL table meeting the given constraints,
        it will also parse the DVH_string into python lists and retrieve the associated Rx dose
        :param uid: a list of allowed study_instance_uids in data set
        :param dvh_condition: a string in SQL syntax applied to a DVH Table query
        """

        if uid:
            constraints_str = "study_instance_uid in ('%s')" % "', '".join(uid)
            if dvh_condition:
                constraints_str = " and " + constraints_str
        else:
            constraints_str = ''

        if dvh_condition:
            constraints_str = "(%s)%s" % (dvh_condition, constraints_str)
            self.query = dvh_condition
        else:
            self.query = ''

        cnx = DVH_SQL()

        # Get DVH data from SQL
        dvh_data = QuerySQL('DVHs', constraints_str)
        for key, value in dvh_data.__dict__.items():
            if not key.startswith("__"):
                setattr(self, key, value)

        # Add these properties to dvh_data since they aren't in the DVHs SQL table
        self.count = len(self.mrn)
        self.rx_dose = []

        self.bin_count = 0
        for value in self.dvh_string:
            current_dvh_str = np.array(str(value).split(','))
            current_size = np.size(current_dvh_str)
            if current_size > self.bin_count:
                self.bin_count = current_size
        self.dvh = np.zeros([self.bin_count, self.count])

        # Get needed values not in DVHs table
        for i in range(self.count):
            # Get Rx Doses
            condition = "mrn = '%s' and study_instance_uid = '%s'" % (
                self.mrn[i], self.study_instance_uid[i])
            rx_dose_cursor = cnx.query('Plans', 'rx_dose', condition)
            self.rx_dose.append(rx_dose_cursor[0][0])

            # Process dvh_string to numpy array, and pad with zeros at the end
            # so that all dvhs are the same length
            current_dvh = np.array(self.dvh_string[i].split(','),
                                   dtype='|S4').astype(np.float)
            current_dvh_max = np.max(current_dvh)
            if current_dvh_max > 0:
                current_dvh = np.divide(current_dvh, current_dvh_max)
            zero_fill = np.zeros(self.bin_count - len(current_dvh))
            self.dvh[:, i] = np.concatenate((current_dvh, zero_fill))
def print_uncategorized_rois():
    dvh_data = QuerySQL('DVHs', "physician_roi = 'uncategorized'")
    print('physician, institutional_roi, physician_roi, roi_name')
    for i in range(0, len(dvh_data.roi_name)):
        uid = dvh_data.study_instance_uid[i]
        physician = get_physician_from_uid(uid)
        roi_name = dvh_data.roi_name[i]
        physician_roi = dvh_data.physician_roi[i]
        institutional_roi = dvh_data.institutional_roi[i]
        print(physician, institutional_roi, physician_roi, roi_name, sep=' ')
示例#7
0
def get_study_instance_uids(**kwargs):
    uids = {}
    complete_list = []
    for key, value in listitems(kwargs):
        uids[key] = QuerySQL(key, value).study_instance_uid
        complete_list.extend(uids[key])

    uids['unique'] = list(set(complete_list))
    uids['union'] = [uid for uid in uids['unique'] if is_uid_in_all_keys(uid, uids)]

    return uids
示例#8
0
def recalculate_ages(*custom_condition):

    if custom_condition:
        custom_condition = " AND " + custom_condition[0]
    else:
        custom_condition = ''

    dvh_data = QuerySQL('Plans', "mrn != ''" + custom_condition)
    cnx = DVH_SQL()

    for i in range(0, len(dvh_data.mrn)):
        mrn = dvh_data.mrn[i]
        uid = dvh_data.study_instance_uid[i]
        sim_study_date = dvh_data.sim_study_date[i].split('-')
        birth_date = dvh_data.birth_date[i].split('-')

        try:
            birth_year = int(birth_date[0])
            birth_month = int(birth_date[1])
            birth_day = int(birth_date[2])
            birth_date_obj = datetime(birth_year, birth_month, birth_day)

            sim_study_year = int(sim_study_date[0])
            sim_study_month = int(sim_study_date[1])
            sim_study_day = int(sim_study_date[2])
            sim_study_date_obj = datetime(sim_study_year, sim_study_month,
                                          sim_study_day)

            if sim_study_date == '1800-01-01':
                age = '(NULL)'
            else:
                age = relativedelta(sim_study_date_obj, birth_date_obj).years

            condition = "study_instance_uid = '" + uid + "'"
            cnx.update('Plans', 'age', str(age), condition)
        except:
            print("Update Failed for",
                  mrn,
                  "sim date:",
                  sim_study_date,
                  "birthdate",
                  birth_date,
                  sep=' ')

    cnx.close()
def get_study_instance_uids(**kwargs):
    study_instance_uids = {}
    complete_list = []
    for key, value in listitems(kwargs):
        if key not in {'Plans', 'DVHs', 'Beams', 'Rxs'}:
            print(key, ' is not a valid table name\nSelect from Plans, DVHs, Beams, or Rxs.', sep=' ')
            return
        study_instance_uids[key] = QuerySQL(key, value).study_instance_uid
        for sub_value in study_instance_uids[key]:
            complete_list.append(sub_value)
    study_instance_uids['unique'] = get_unique_list(complete_list)
    union_list = []
    for value in study_instance_uids['unique']:
        if is_uid_in_all_keys(value, study_instance_uids):
            union_list.append(value)
    study_instance_uids['union'] = union_list

    return study_instance_uids
示例#10
0
def update_uncategorized_rois_in_database():
    roi_map = DatabaseROIs()
    dvh_data = QuerySQL('DVHs', "physician_roi = 'uncategorized'")
    cnx = DVH_SQL()

    for i in range(len(dvh_data.roi_name)):
        uid = dvh_data.study_instance_uid[i]
        mrn = dvh_data.mrn[i]
        physician = get_physician_from_uid(uid)
        roi_name = dvh_data.roi_name[i]

        new_physician_roi = roi_map.get_physician_roi(physician, roi_name)
        new_institutional_roi = roi_map.get_institutional_roi(physician, roi_name)

        if new_physician_roi != 'uncategorized':
            print(mrn, physician, new_institutional_roi, new_physician_roi, roi_name, sep=' ')
            condition = "study_instance_uid = '" + uid + "'" + "and roi_name = '" + roi_name + "'"
            cnx.update('DVHs', 'physician_roi', new_physician_roi, condition)
            cnx.update('DVHs', 'institutional_roi', new_institutional_roi, condition)

    cnx.close()
示例#11
0
    def update_rx_data(self, uids):

        cond_str = "study_instance_uid in ('" + "', '".join(uids) + "')"
        rx_data = QuerySQL('Rxs', cond_str)

        groups = self.get_group_list(rx_data.study_instance_uid)

        anon_id = [
            self.anon_id_map[rx_data.mrn[i]] for i in range(len(rx_data.mrn))
        ]

        attributes = [
            'mrn', 'plan_name', 'fx_dose', 'rx_percent', 'fxs', 'rx_dose',
            'fx_grp_count', 'fx_grp_name', 'fx_grp_number',
            'normalization_method', 'normalization_object'
        ]
        data = {attr: getattr(rx_data, attr) for attr in attributes}
        data['anon_id'] = anon_id
        data['group'] = groups
        data['uid'] = rx_data.study_instance_uid

        self.sources.rxs.data = data
    def __init__(self, **kwargs):

        if 'uid' in kwargs:
            study_instance_uid = kwargs['uid']
            db_constraints_list = []
            for i in range(0, len(study_instance_uid)):
                db_constraints_list.append(study_instance_uid[i])
            uid_constraints_str = "study_instance_uid in ('"
            uid_constraints_str += "', '".join(db_constraints_list)
            uid_constraints_str += "')"
            if 'dvh_condition' in kwargs and kwargs['dvh_condition']:
                uid_constraints_str = " and " + uid_constraints_str
        else:
            uid_constraints_str = ''

        if 'dvh_condition' in kwargs and kwargs['dvh_condition']:
            uid_constraints_str = '(' + kwargs['dvh_condition'] + ')' + uid_constraints_str
            self.query = kwargs['dvh_condition']
        else:
            self.query = ''

        if 'uncategorized' in kwargs:
            if kwargs['uncategorized']:
                self.uncategorized = True
            else:
                self.uncategorized = False
        else:
            self.uncategorized = False

        cnx = DVH_SQL()

        # Get DVH data from SQL
        dvh_data = QuerySQL('DVHs', uid_constraints_str)
        for key, value in dvh_data.__dict__.items():
            if not key.startswith("__"):
                setattr(self, key, value)

        # Add this properties to dvh_data since they aren't in the DVHs SQL table
        self.count = len(self.mrn)
        setattr(self, 'rx_dose', [])

        self.bin_count = 0
        for value in self.dvh_string:
            current_dvh_str = np.array(str(value).split(','))
            current_size = np.size(current_dvh_str)
            if current_size > self.bin_count:
                self.bin_count = current_size
        setattr(self, 'dvh', np.zeros([self.bin_count, self.count]))

        # Get needed values not in DVHs table
        for i in range(0, self.count):
            # Get Rx Doses
            condition = "mrn = '" + self.mrn[i]
            condition += "' and study_instance_uid = '"
            condition += str(self.study_instance_uid[i]) + "'"
            rx_dose_cursor = cnx.query('Plans', 'rx_dose', condition)
            self.rx_dose.append(rx_dose_cursor[0][0])

            # Process dvh_string to numpy array, and pad with zeros at the end
            # so that all dvhs are the same length
            current_dvh = np.array(self.dvh_string[i].split(','), dtype='|S4').astype(np.float)
            if np.max(current_dvh) > 0:
                current_dvh = np.divide(current_dvh, np.max(current_dvh))
            zero_fill = np.zeros(self.bin_count - len(current_dvh))
            self.dvh[:, i] = np.concatenate((current_dvh, zero_fill))