Instruction:
Write a Python 3 function for
reading data from current WD measurement. txt or magic_measurements. txt and sorts it into main measurements data structures given bellow

Response:
def get_data(self):
        """
        reads data from current WD measurement.txt or magic_measurements.txt
        depending on data model and sorts it into main measurements data
        structures given bellow:
        Data - {specimen: {
                zijdblock:[[treatment temp-str,dec-float, inc-float,
                        mag_moment-float, ZI-float, meas_flag-str ('b','g'),
                        method_codes-str]],
                zijdblock_geo:[[treatment temp-str,dec-float, inc-float,
                        mag_moment-float, ZI-float, meas_flag-str ('b','g'),
                        method_codes-str]],
                zijdblock_tilt:[[treatment temp-str,dec-float, inc-float,
                        mag_moment-float, ZI-float, meas_flag-str ('b','g'),
                        method_codes-str]],
                zijdblock_lab_treatments: [str],
                zijdblock_steps: [str],
                measurement_flag: [str ('b','g')],
                mag_meas_data_index: [int],
                csds: [float],
                pars: {},
                zdata: array.shape = 2x2 (float),
                zdata_geo: array.shape = 2x2 (float),
                zdata_tilt: array.shape = 2x2 (float),
                vector_diffs: [float],
                vds: float }}
        Data_hierarchy - {specimen: {
                            study: {}
                            locations: {}
                            sites: {}
                            samples: {}
                            specimens: {}
                            sample_of_specimen: {}
                            site_of_specimen: {}
                            site_of_sample: {}
                            location_of_site: {}
                            location_of_specimen: {}
                            study_of_specimen: {}
                            expedition_name_of_specimen: {} }}
        """
        # ------------------------------------------------
        # Read magic measurement file and sort to blocks
        # ------------------------------------------------

        # All meas data information is stored in Data[secimen]={}
        Data = {}
        Data_hierarchy = {}
        Data_hierarchy['study'] = {}
        Data_hierarchy['locations'] = {}
        Data_hierarchy['sites'] = {}
        Data_hierarchy['samples'] = {}
        Data_hierarchy['specimens'] = {}
        Data_hierarchy['sample_of_specimen'] = {}
        Data_hierarchy['site_of_specimen'] = {}
        Data_hierarchy['site_of_sample'] = {}
        Data_hierarchy['location_of_site'] = {}
        Data_hierarchy['location_of_specimen'] = {}
        Data_hierarchy['study_of_specimen'] = {}
        Data_hierarchy['expedition_name_of_specimen'] = {}

        if self.data_model == 3:

            if 'measurements' not in self.con.tables:
                self.user_warning(
                    "Measurement data file is empty and the GUI cannot start, aborting")
                return Data, Data_hierarchy

            if self.con.tables['measurements'].df.empty:
                self.user_warning(
                    "Measurement data file is empty and the GUI cannot start, aborting")
                return Data, Data_hierarchy

            # extract specimen data from measurements table
            if not len(self.spec_data):
                specs = self.con.tables['measurements'].df['specimen'].unique()
                df = pd.DataFrame(index=specs, columns=['specimen'])
                df.index.name = 'specimen_name'
                df['specimen'] = specs
                self.con.tables['specimens'].df = df
                self.spec_data = df

            if not len(self.spec_data):
                self.user_warning(
                    "Measurement data file does not seem to have specimen data and the GUI cannot start, aborting")
                return Data, Data_hierarchy

            if 'sample' not in self.spec_data.columns or 'sample' not in self.samp_data.columns:
                if 'specimen' not in self.spec_data.columns:
                    self.spec_data['specimen'] = self.con.tables['measurements'].df['specimen']
                    self.spec_data.set_index('specimen', inplace=True)
                    self.spec_data['specimen'] = self.spec_data.index

                ui_dialog = demag_dialogs.user_input(
                    self, ["# of characters to remove"], heading="Sample data could not be found attempting to generate sample names by removing characters from specimen names")
                self.show_dlg(ui_dialog)
                ui_data = ui_dialog.get_values()
                try:
                    samp_ncr = int(ui_data[1]["# of characters to remove"])
                except ValueError:
                    self.user_warning(
                        "Invalid input, specimen names will be used for sample names instead")
                    samp_ncr = 0
                self.spec_data['sample'] = [x[:-samp_ncr]
                                            for x in self.spec_data['specimen']]

                self.samp_data['sample'] = self.spec_data['sample']
                self.samp_data.set_index('sample', inplace=True)
                self.samp_data['sample'] = self.samp_data.index

            if 'site' not in self.samp_data.columns or 'site' not in self.site_data.columns:
                ui_dialog = demag_dialogs.user_input(
                    self, ["# of characters to remove", "site delimiter"], heading="No Site Data found attempting to create site names from specimen names")
                self.show_dlg(ui_dialog)
                ui_data = ui_dialog.get_values()
                try:
                    site_ncr = int(ui_data[1]["# of characters to remove"])
                    self.samp_data['site'] = [x[:-site_ncr]
                                              for x in self.spec_data['specimen']]
                except ValueError:
                    try:
                        sd = ui_data[1]["site delimiter"]
                        self.samp_data['site'] = [
                            x.split(sd)[0] for x in self.spec_data['specimen']]
                    except ValueError:
                        self.samp_data['site'] = [
                            x for x in self.spec_data['specimen']]

                self.site_data['site'] = self.samp_data['site']
                self.site_data.drop_duplicates(inplace=True)
                self.site_data.set_index('site', inplace=True)
                self.site_data['site'] = self.site_data.index

            if 'location' not in self.site_data.columns or 'location' not in self.loc_data.columns:
                ui_dialog = demag_dialogs.user_input(
                    self, ["location name for all sites"], heading="No Location found")
                self.show_dlg(ui_dialog)
                ui_data = ui_dialog.get_values()
                self.site_data['location'] = ui_data[1]["location name for all sites"]

                self.loc_data['location'] = self.site_data['location']
                self.loc_data.drop_duplicates(inplace=True)
                self.loc_data.set_index('location', inplace=True)
                self.loc_data['location'] = self.loc_data.index

            # add data to other dataframes
            self.con.propagate_location_to_measurements()
            self.con.propagate_location_to_specimens()

            # get measurement data from contribution object
            meas_container = self.con.tables['measurements']
            meas_data3_0 = meas_container.df

            meas_data3_0.replace({'specimen': {nan: 'unknown'}, 'sample': {nan: 'unknown'}, 'site': {
                                 nan: 'unknown'}, 'location': {nan: 'unknown'}}, inplace=True)
            meas_data3_0['specimen'] = meas_data3_0['specimen'].apply(str)
            meas_data3_0['sample'] = meas_data3_0['sample'].apply(str)
            meas_data3_0['site'] = meas_data3_0['site'].apply(str)
            meas_data3_0['location'] = meas_data3_0['location'].apply(str)

            # do some filtering
#            if 'location' in meas_data3_0.columns:
#                if any(meas_data3_0['location'].isnull()):
#                    print("-W- Some measurements are missing location data, and will not be used")
#                meas_data3_0 = meas_data3_0[meas_data3_0['location'].notnull()]
# meas_data3_0.replace({'location':float('nan')},'unknown',inplace=True)
#            if 'site' in meas_data3_0.columns:
#                if any(meas_data3_0['site'].isnull()):
#                    print("-W- Some measurements are missing site data, and will not be used")
#                meas_data3_0 = meas_data3_0[meas_data3_0['site'].notnull()]
# meas_data3_0.replace({'site':float('nan')},'unknown',inplace=True)
#            if 'sample' in meas_data3_0.columns:
#                if any(meas_data3_0['sample'].isnull()):
#                    print("-W- Some measurements are missing sample data, and will not be used")
#                meas_data3_0 = meas_data3_0[meas_data3_0['sample'].notnull()]
# meas_data3_0.replace({'sample':float('nan')},'unknown',inplace=True)
#            if 'specimen' in meas_data3_0.columns:
#                missing = meas_data3_0[meas_data3_0['specimen'].isnull()]
#                if len(missing):
#                    print("-W- {} measurements are missing specimen data, and will not be used".format(missing))
#                meas_data3_0 = meas_data3_0[meas_data3_0['specimen'].notnull()]
# meas_data3_0.replace({'specimen':float('nan')},'unknown',inplace=True)

#            col_names = ['specimen', 'sample', 'site', 'location']
#            for col_name in col_names:
#                if col_name in meas_data3_0.columns:
#                    pruned = meas_data3_0[meas_data3_0[col_name].apply(cb.not_null)]
#                    num_missing = len(meas_data3_0) - len(pruned)
#                    if num_missing:
#                        msg = "{} measurements cannot be associated with a {} and will be excluded\nTry using Pmag GUI (step 3) to make sure you have provided the full chain from specimen to location.".format(num_missing, col_name)
#                        pw.simple_warning(msg)
#                        print("-W- {} measurements are missing {} data and will be excluded".format(num_missing, col_name))
#                        meas_data3_0 = pruned
            Mkeys = ['magn_moment', 'magn_volume', 'magn_mass']
# fish out all the relavent data
            meas_data3_0 = meas_data3_0[meas_data3_0['method_codes'].str.contains(
                'LT-NO|LT-AF-Z|LT-T-Z|LT-M-Z|LT-LT-Z') == True]
            if not len(meas_data3_0):
                self.user_warning("Your measurements table contains none of the required method codes to run Demag GUI: [LT-NO, LT-AF-Z, LT-T-Z, LT-M-Z, LT-LT-Z]")
                return {}, {}
# now convert back to 2.5  changing only those keys that are necessary for thellier_gui
            meas_con_dict = map_magic.get_thellier_gui_meas_mapping(
                meas_data3_0, output=2)
            intensity_col = cb.get_intensity_col(meas_data3_0)
            if not intensity_col:
                self.user_warning("Your measurements table must have one of the following columns to run Demag GUI: 'magn_moment', 'magn_volume', 'magn_mass',or 'magn_uncal'")
                return {}, {}

            print('-I- Using {} for intensity'.format(intensity_col))
            self.intensity_col = meas_con_dict[intensity_col]
            meas_data2_5 = meas_data3_0.rename(columns=meas_con_dict)
            # make a list of dictionaries to maintain backward compatibility
            mag_meas_data = meas_data2_5.to_dict("records")

        else:  # data model 2.5
            try:
                print(("-I- Read magic file %s" % self.magic_file))
            except ValueError:
                self.magic_measurement = self.choose_meas_file()
                print(("-I- Read magic file %s" % self.magic_file))
            mag_meas_data, file_type = pmag.magic_read(self.magic_file)
            if file_type != "magic_measurements":
                self.user_warning("You have selected data model 2.5, but your measurements file is either not in 2.5, or is not a measurements file.\n{} has file type: {}".format(self.magic_file, file_type))
                return {}, {}

        self.mag_meas_data = self.merge_pmag_recs(mag_meas_data)

        # get list of unique specimen names with measurement data
        CurrRec = []
        sids = pmag.get_specs(self.mag_meas_data)  # specimen ID's
        for s in sids:
            if s not in list(Data.keys()):
                Data[s] = {}
                Data[s]['zijdblock'] = []
                Data[s]['zijdblock_geo'] = []
                Data[s]['zijdblock_tilt'] = []
                Data[s]['zijdblock_lab_treatments'] = []
                Data[s]['pars'] = {}
                Data[s]['csds'] = []
                Data[s]['zijdblock_steps'] = []
                Data[s]['measurement_flag'] = []  # a list of points 'g' or 'b'
                # index in original magic_measurements.txt
                Data[s]['mag_meas_data_index'] = []
                Data[s]['measurement_names'] = []

        prev_s = None
        cnt = -1
        # list of excluded lab protocols. copied from pmag.find_dmag_rec(s,data)
        self.excluded_methods = ["LP-AN-ARM", "LP-AN-TRM", "LP-ARM-AFD",
                                 "LP-ARM2-AFD", "LP-TRM-AFD", "LP-TRM", "LP-TRM-TD", "LP-X", "LP-PI-ARM"]
        self.included_methods = [
            "LT-NO", "LT-AF-Z", "LT-T-Z", "LT-M-Z", "LT-LT-Z"]
#        self.mag_meas_data.sort(key=meas_key)
        # asiigned default values for NRM
        if len(self.mag_meas_data) > 0 and self.intensity_col in list(self.mag_meas_data[0].keys()):
            NRM = float(self.mag_meas_data[0][self.intensity_col])
        for rec in self.mag_meas_data:
            # if "measurement_number" in rec.keys() and str(rec['measurement_number']) == '1' and "magic_method_codes" in rec.keys() and "LT-NO" not in rec["magic_method_codes"].split(':'):
            #    NRM = 1 #not really sure how to handle this case but assume that data is already normalized
            cnt += 1  # index counter
            s = rec["er_specimen_name"]
            if "er_sample_name" in list(rec.keys()):
                sample = rec["er_sample_name"]
            else:
                sample = ''
            if "er_site_name" in list(rec.keys()):
                site = rec["er_site_name"]
            else:
                site = ''
            if "er_location_name" in list(rec.keys()):
                location = rec["er_location_name"]
            else:
                location = ''
            expedition_name = ""
            if "er_expedition_name" in list(rec.keys()):
                expedition_name = rec["er_expedition_name"]

            methods = rec["magic_method_codes"].replace(
                " ", "").strip("\n").split(":")
            LP_methods = []
            LT_methods = []

            for k in ['zdata', 'zdata_geo', 'zdata_tilt', 'vector_diffs']:
                if k not in Data[s]:
                    Data[s][k] = []

            for i in range(len(methods)):
                methods[i] = methods[i].strip()
            if 'measurement_flag' not in list(rec.keys()):
                rec['measurement_flag'] = 'g'
            SKIP = True
            lab_treatment = ""
            for meth in methods:
                if 'DIR' in meth:
                    SKIP = False
                if meth in self.included_methods:
                    lab_treatment = meth
                    SKIP = False
                if "LP" in meth:
                    LP_methods.append(meth)
            for meth in self.excluded_methods:
                if meth in methods:
                    SKIP = True
                    break
            if SKIP:
                continue
            tr, LPcode, measurement_step_unit = "", "", ""
            if "LT-NO" in methods:
                tr = 0
                if prev_s != s and self.intensity_col in rec:
                    try:
                        NRM = float(rec[self.intensity_col])
                    except ValueError:
                        NRM = 1
                for method in methods:
                    if "AF" in method:
                        LPcode = "LP-DIR-AF"
                        measurement_step_unit = "mT"
                    if "TRM" in method:
                        LPcode = "LP-DIR-T"
                        measurement_step_unit = "C"
            elif "LT-AF-Z" in methods:
                try:
                    tr = float(rec["treatment_ac_field"])*1e3  # (mT)
                except ValueError:
                    print(("Could not convert ac field for measurement, was given %s, skipping" %
                           rec["treatment_ac_field"]))
                    continue
                measurement_step_unit = "mT"  # in magic its T in GUI its mT
                LPcode = "LP-DIR-AF"
            elif "LT-T-Z" in methods or "LT-LT-Z" in methods:
                try:
                    tr = float(rec["treatment_temp"])-273.  # celsius
                except ValueError:
                    print(
                        ("Could not convert temperature for measurement, was given %s, skipping" % rec["treatment_temp"]))
                    continue
                measurement_step_unit = "C"  # in magic its K in GUI its C
                LPcode = "LP-DIR-T"
            elif "LT-M-Z" in methods:
                # temporary for microwave
                tr = float(rec["measurement_number"])
            else:
                # attempt to determine from treatment data
                if all(im not in methods for im in self.included_methods):
                    if 'treatment_temp' in list(rec.keys()) and not str(rec['treatment_temp']).isalpha() and rec['treatment_temp'] != '' and float(rec['treatment_temp']) > 0:
                        tr = float(rec["treatment_temp"])-273.  # celsius
                        measurement_step_unit = "C"  # in magic its K in GUI its C
                        LPcode = "LP-DIR-T"
                    elif 'treatment_ac_field' in list(rec.keys()) and not str(rec['treatment_ac_field']).isalpha() and rec['treatment_ac_field'] != '' and float(rec['treatment_ac_field']) > 0:
                        tr = float(rec["treatment_ac_field"])*1e3  # (mT)
                        measurement_step_unit = "mT"  # in magic its T in GUI its mT
                        LPcode = "LP-DIR-AF"
                    else:
                        tr = 0
                        if prev_s != s and self.intensity_col in rec:
                            try:
                                NRM = float(rec[self.intensity_col])
                            except ValueError:
                                NRM = 1
                        for method in methods:
                            if "AF" in method:
                                LPcode = "LP-DIR-AF"
                                measurement_step_unit = "mT"
                            if "TRM" in method:
                                LPcode = "LP-DIR-T"
                                measurement_step_unit = "C"
                else:
                    tr = float(rec["measurement_number"])
            if prev_s != s and len(Data[s]['zijdblock']) > 0:
                NRM = Data[s]['zijdblock'][0][3]

            ZI = 0
            if tr != "":
                Data[s]['mag_meas_data_index'].append(
                    cnt)  # magic_measurement file intex
                if not int(self.data_model) == 2:
                    try:
                        Data[s]['measurement_names'].append(rec['measurement'])
                    except KeyError:
                        Data[s]['measurement_names'].append(rec['measurement_number'])
                Data[s]['zijdblock_lab_treatments'].append(lab_treatment)
                if measurement_step_unit != "":
                    if 'measurement_step_unit' in list(Data[s].keys()):
                        if measurement_step_unit not in Data[s]['measurement_step_unit'].split(":"):
                            Data[s]['measurement_step_unit'] = Data[s]['measurement_step_unit'] + \
                                ":"+measurement_step_unit
                    else:
                        Data[s]['measurement_step_unit'] = measurement_step_unit
                dec, inc, inten = "", "", ""
                if "measurement_dec" in list(rec.keys()) and cb.not_null(rec["measurement_dec"], False):
                    dec = float(rec["measurement_dec"])
                else:
                    continue
                if "measurement_inc" in list(rec.keys()) and cb.not_null(rec["measurement_inc"], False):
                    inc = float(rec["measurement_inc"])
                else:
                    continue
                if self.intensity_col in list(rec.keys()) and cb.not_null(rec[self.intensity_col], False):
                    intensity = float(rec[self.intensity_col])
                else:
                    intensity = 1.  # just assume a normal vector
                if 'magic_instrument_codes' not in list(rec.keys()):
                    rec['magic_instrument_codes'] = ''
                if 'measurement_csd' in list(rec.keys()):
                    csd = str(rec['measurement_csd'])
                else:
                    csd = ''
                Data[s]['zijdblock'].append(
                    [tr, dec, inc, intensity, ZI, rec['measurement_flag'], rec['magic_instrument_codes']])
                Data[s]['csds'].append(csd)
                DIR = [dec, inc, intensity/NRM]
                cart = pmag.dir2cart(DIR)
                Data[s]['zdata'].append(array([cart[0], cart[1], cart[2]]))

                if 'magic_experiment_name' in list(Data[s].keys()) and Data[s]['magic_experiment_name'] != rec["magic_experiment_name"]:
                    print(("-E- ERROR: specimen %s has more than one demagnetization experiment name. You need to merge them to one experiment-name?" % (s)))
                if float(tr) == 0 or float(tr) == 273:
                    Data[s]['zijdblock_steps'].append("0")
                elif measurement_step_unit == "C":
                    Data[s]['zijdblock_steps'].append(
                        "%.0f%s" % (tr, measurement_step_unit))
                else:
                    Data[s]['zijdblock_steps'].append(
                        "%.1f%s" % (tr, measurement_step_unit))
                # --------------
                if 'magic_experiment_name' in list(rec.keys()):
                    Data[s]['magic_experiment_name'] = rec["magic_experiment_name"]
                if "magic_instrument_codes" in list(rec.keys()):
                    Data[s]['magic_instrument_codes'] = rec['magic_instrument_codes']
                Data[s]["magic_method_codes"] = LPcode

                # --------------
                # ""good" or "bad" data
                # --------------

                flag = 'g'
                if 'measurement_flag' in list(rec.keys()):
                    if str(rec["measurement_flag"]) == 'b':
                        flag = 'b'
                Data[s]['measurement_flag'].append(flag)

                # gegraphic coordinates
                try:
                    sample_azimuth = float(
                        self.Data_info["er_samples"][sample]['sample_azimuth'])
                    sample_dip = float(
                        self.Data_info["er_samples"][sample]['sample_dip'])
                    d_geo, i_geo = pmag.dogeo(
                        dec, inc, sample_azimuth, sample_dip)
                    # if d_geo or i_geo is null, we can't do geographic coordinates
                    # otherwise, go ahead
                    if not any([np.isnan(val) for val in [d_geo, i_geo]]):
                        Data[s]['zijdblock_geo'].append(
                            [tr, d_geo, i_geo, intensity, ZI, rec['measurement_flag'], rec['magic_instrument_codes']])
                        DIR = [d_geo, i_geo, intensity/NRM]
                        cart = pmag.dir2cart(DIR)
                        Data[s]['zdata_geo'].append([cart[0], cart[1], cart[2]])
                except (IOError, KeyError, ValueError, TypeError) as e:
                    pass
                #                    if prev_s != s:
                #                        print( "-W- can't find sample_azimuth,sample_dip for sample %s"%sample)

                # tilt-corrected coordinates
                try:
                    sample_bed_dip_direction = float(
                        self.Data_info["er_samples"][sample]['sample_bed_dip_direction'])
                    sample_bed_dip = float(
                        self.Data_info["er_samples"][sample]['sample_bed_dip'])
                    d_tilt, i_tilt = pmag.dotilt(
                        d_geo, i_geo, sample_bed_dip_direction, sample_bed_dip)
                    Data[s]['zijdblock_tilt'].append(
                        [tr, d_tilt, i_tilt, intensity, ZI, rec['measurement_flag'], rec['magic_instrument_codes']])
                    DIR = [d_tilt, i_tilt, intensity/NRM]
                    cart = pmag.dir2cart(DIR)
                    Data[s]['zdata_tilt'].append([cart[0], cart[1], cart[2]])
                except (IOError, KeyError, TypeError, ValueError, UnboundLocalError) as e:
                    pass
                #                    if prev_s != s:
                #                        printd("-W- can't find tilt-corrected data for sample %s"%sample)

                if len(Data[s]['zdata']) > 1:
                    Data[s]['vector_diffs'].append(
                        sqrt(sum((array(Data[s]['zdata'][-2])-array(Data[s]['zdata'][-1]))**2)))

            # ---------------------
            # hierarchy is determined from magic_measurements.txt
            # ---------------------

            if sample not in list(Data_hierarchy['samples'].keys()):
                Data_hierarchy['samples'][sample] = {}
                Data_hierarchy['samples'][sample]['specimens'] = []

            if site not in list(Data_hierarchy['sites'].keys()):
                Data_hierarchy['sites'][site] = {}
                Data_hierarchy['sites'][site]['samples'] = []
                Data_hierarchy['sites'][site]['specimens'] = []

            if location not in list(Data_hierarchy['locations'].keys()):
                Data_hierarchy['locations'][location] = {}
                Data_hierarchy['locations'][location]['sites'] = []
                Data_hierarchy['locations'][location]['samples'] = []
                Data_hierarchy['locations'][location]['specimens'] = []

            if 'this study' not in list(Data_hierarchy['study'].keys()):
                Data_hierarchy['study']['this study'] = {}
                Data_hierarchy['study']['this study']['sites'] = []
                Data_hierarchy['study']['this study']['samples'] = []
                Data_hierarchy['study']['this study']['specimens'] = []

            if s not in Data_hierarchy['samples'][sample]['specimens']:
                Data_hierarchy['samples'][sample]['specimens'].append(s)

            if s not in Data_hierarchy['sites'][site]['specimens']:
                Data_hierarchy['sites'][site]['specimens'].append(s)

            if s not in Data_hierarchy['locations'][location]['specimens']:
                Data_hierarchy['locations'][location]['specimens'].append(s)

            if s not in Data_hierarchy['study']['this study']['specimens']:
                Data_hierarchy['study']['this study']['specimens'].append(s)

            if sample not in Data_hierarchy['sites'][site]['samples']:
                Data_hierarchy['sites'][site]['samples'].append(sample)

            if sample not in Data_hierarchy['locations'][location]['samples']:
                Data_hierarchy['locations'][location]['samples'].append(sample)

            if sample not in Data_hierarchy['study']['this study']['samples']:
                Data_hierarchy['study']['this study']['samples'].append(sample)

            if site not in Data_hierarchy['locations'][location]['sites']:
                Data_hierarchy['locations'][location]['sites'].append(site)

            if site not in Data_hierarchy['study']['this study']['sites']:
                Data_hierarchy['study']['this study']['sites'].append(site)

            # Data_hierarchy['specimens'][s]=sample
            Data_hierarchy['sample_of_specimen'][s] = sample
            Data_hierarchy['site_of_specimen'][s] = site
            Data_hierarchy['site_of_sample'][sample] = site
            Data_hierarchy['location_of_site'][site] = location
            Data_hierarchy['location_of_specimen'][s] = location
            if expedition_name != "":
                Data_hierarchy['expedition_name_of_specimen'][s] = expedition_name
            prev_s = s

        print("-I- done sorting meas data")
        self.specimens = list(Data.keys())

        for s in self.specimens:
            if len(Data[s]['zdata']) > 0:
                Data[s]['vector_diffs'].append(
                    sqrt(sum(array(Data[s]['zdata'][-1])**2)))  # last vector of the vds
            vds = sum(Data[s]['vector_diffs'])  # vds calculation
            Data[s]['vector_diffs'] = array(Data[s]['vector_diffs'])
            Data[s]['vds'] = vds
            Data[s]['zdata'] = array(Data[s]['zdata'])
            Data[s]['zdata_geo'] = array(Data[s]['zdata_geo'])
            Data[s]['zdata_tilt'] = array(Data[s]['zdata_tilt'])
        return(Data, Data_hierarchy)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_interpretations3(self):
        if "specimen" not in self.spec_data.columns or \
           "meas_step_min" not in self.spec_data.columns or \
           "meas_step_max" not in self.spec_data.columns or \
           "meas_step_unit" not in self.spec_data.columns or \
           "method_codes" not in self.spec_data.columns:
               return
        if "dir_comp" in self.spec_data.columns:
            fnames = 'dir_comp'
        elif "dir_comp_name" in self.spec_data.columns:
            fnames = 'dir_comp_name'
        else:
            fnames = 'dir_comp'
            self.spec_data['dir_comp'] = 'Fit 1'
            #print("No specimen interpretation name found in specimens.txt")
            #return
        if "result_quality" not in self.spec_data.columns:
            self.spec_data["result_quality"] = "g"
        if "dir_tilt_correction" not in self.spec_data.columns:
            self.spec_data["dir_tilt_correction"] = ""
        fdict = self.spec_data[['specimen', fnames, 'meas_step_min', 'meas_step_max', 'meas_step_unit',
                                'dir_tilt_correction', 'method_codes', 'result_quality']].to_dict("records")
        for i in range(len(fdict)):
            spec = fdict[i]['specimen']
            if spec not in self.specimens:
                print(("-E- specimen %s does not exist in measurement data" % (spec)))
                continue
            fname = fdict[i][fnames]
            if fname == None or (spec in list(self.pmag_results_data['specimens'].keys()) and fname in [x.name for x in self.pmag_results_data['specimens'][spec]]):
                continue
            if fdict[i]['meas_step_unit'] == "K":
                fmin = int(float(fdict[i]['meas_step_min'])-273)
                fmax = int(float(fdict[i]['meas_step_max'])-273)
                if fmin == 0:
                    fmin = str(fmin)
                else:
                    fmin = str(fmin)+"C"
                if fmax == 0:
                    fmax = str(fmax)
                else:
                    fmax = str(fmax)+"C"
            elif fdict[i]['meas_step_unit'] == "T":
                fmin = float(fdict[i]['meas_step_min'])*1000
                fmax = float(fdict[i]['meas_step_max'])*1000
                if fmin == 0:
                    fmin = str(int(fmin))
                else:
                    fmin = str(fmin)+"mT"
                if fmax == 0:
                    fmax = str(int(fmax))
                else:
                    fmax = str(fmax)+"mT"
            else:
                fmin = fdict[i]['meas_step_min']
                fmax = fdict[i]['meas_step_max']

            PCA_types = ["DE-BFL", "DE-BFL-A", "DE-BFL-O", "DE-FM", "DE-BFP"]
            PCA_type_list = [x for x in str(fdict[i]['method_codes']).split(
                ':') if x.strip() in PCA_types]
            if len(PCA_type_list) > 0:
                PCA_type = PCA_type_list[0].strip()
            else:
                PCA_type = "DE-BFL"

            fit = self.add_fit(spec, fname, fmin, fmax, PCA_type)

            if fdict[i]['result_quality'] == 'b':
                self.bad_fits.append(fit)

Response: Get interpretations from contribution objects in data model 3. 0.


Instruction:
Can you tell what is the following Python 3 function doing
def get_data_info(self):
        Data_info = {}
        data_er_samples = {}
        data_er_sites = {}
        data_er_locations = {}
        data_er_ages = {}

        if self.data_model == 3.0:
            print(("data model: %1.1f" % (self.data_model)))
            Data_info["er_samples"] = []
            Data_info["er_sites"] = []
            Data_info["er_locations"] = []
            Data_info["er_ages"] = []

            # self.magic_file may have a full path, but this breaks cb.Contribution
            # determine if magic_file exists in WD, and if it doesn't, copy it in

            magic_file_real = os.path.realpath(self.magic_file)
            magic_file_short = os.path.split(self.magic_file)[1]
            WD_file_real = os.path.realpath(
                os.path.join(self.WD, magic_file_short))
            if magic_file_real == WD_file_real:
                fnames = {'measurements': magic_file_short}
            else:
                # copy measurements file to WD, keeping original name
                shutil.copy(magic_file_real, WD_file_real)
                fnames = {'measurements': magic_file_short}
            self.con = cb.Contribution(self.WD, custom_filenames=fnames, read_tables=[
                                       'measurements', 'specimens', 'samples', 'sites', 'locations', 'criteria', 'ages'])
            if 'specimens' in self.con.tables:
                spec_container = self.con.tables['specimens']
                self.spec_data = spec_container.df
            else:
                self.con.add_empty_magic_table('specimens')
                self.spec_data = self.con.tables['specimens'].df
            if 'samples' in self.con.tables:
                samp_container = self.con.tables['samples']
                samp_container.front_and_backfill(['azimuth', 'dip'])
                self.samp_data = samp_container.df
                samp_data2 = self.samp_data.rename(
                    columns=map_magic.samp_magic3_2_magic2_map)
                data_er_samples = samp_data2.T.to_dict()
            else:
                self.con.add_empty_magic_table('samples')
                self.samp_data = self.con.tables['samples'].df
            if 'sites' in self.con.tables:
                site_container = self.con.tables['sites']
                self.site_data = site_container.df
                if 'age' in self.site_data.columns:
                    self.site_data = self.site_data[self.site_data['age'].notnull(
                    )]
                    age_ids = [col for col in self.site_data.columns if col.startswith(
                        "age") or col == "site"]
                    age_data = self.site_data[age_ids].rename(
                        columns=map_magic.site_magic3_2_magic2_map)
                    # save this in 2.5 format
                    er_ages = age_data.to_dict('records')
                    data_er_ages = {}
                    for s in er_ages:
                        s = self.convert_ages_to_calendar_year(s)
                        data_er_ages[s['er_site_name']] = s
                sites = self.site_data.rename(
                    columns=map_magic.site_magic3_2_magic2_map)
                # pick out what is needed by thellier_gui and put in 2.5 format
                er_sites = sites.to_dict('records')
                data_er_sites = {}
                for s in er_sites:
                    data_er_sites[s['er_site_name']] = s
            else:
                self.con.add_empty_magic_table('sites')
                self.site_data = self.con.tables['sites'].df
            if 'locations' in self.con.tables:
                location_container = self.con.tables["locations"]
                self.loc_data = location_container.df  # only need this for saving tables
                if self.loc_data['location'].isnull().any():
                    self.loc_data.replace(
                        {'location': {None: 'unknown'}}, inplace=True)
                    self.loc_data.set_index('location', inplace=True)
                    self.loc_data['location'] = self.loc_data.index
                loc2_data = self.loc_data.rename(
                    columns=map_magic.loc_magic3_2_magic2_map)
                data_er_locations = loc2_data.to_dict('index')
            else:
                self.con.add_empty_magic_table('locations')
                self.loc_data = self.con.tables['locations'].df

        else:  # try 2.5 data model

            print(("data model: %1.1f" % (self.data_model)))
            self.read_magic_file(os.path.join(
                self.WD, "er_samples.txt"), 'er_sample_name')

            try:
                data_er_samples = self.read_magic_file(
                    os.path.join(self.WD, "er_samples.txt"), 'er_sample_name')
            except:
                print("-W- Can't find er_sample.txt in project directory")

            try:
                data_er_sites = self.read_magic_file(
                    os.path.join(self.WD, "er_sites.txt"), 'er_site_name')
            except:
                print("-W- Can't find er_sites.txt in project directory")

            try:
                data_er_locations = self.read_magic_file(os.path.join(
                    self.WD, "er_locations.txt"), 'er_location_name')
            except:
                print("-W- Can't find er_locations.txt in project directory")

            try:
                data_er_ages = self.read_magic_file(
                    os.path.join(self.WD, "er_ages.txt"), 'er_sample_name')
            except:
                try:
                    data_er_ages = self.read_magic_file(
                        os.path.join(self.WD, "er_ages.txt"), 'er_site_name')
                except:
                    print("-W- Can't find er_ages in project directory")

        Data_info["er_samples"] = data_er_samples
        Data_info["er_sites"] = data_er_sites
        Data_info["er_locations"] = data_er_locations
        Data_info["er_ages"] = data_er_ages

        return(Data_info)

Response: Get the data structure of the current instance of the class.


Instruction:
Can you tell what is the following Python 3 function doing
def get_preferences(self):
        # default
        preferences = {}
        preferences['gui_resolution'] = 100.
        preferences['show_Zij_treatments'] = True
        preferences['show_Zij_treatments_steps'] = 2.
        preferences['show_eqarea_treatments'] = False
        preferences['auto_save'] = True
        # preferences['show_statistics_on_gui']=["int_n","int_ptrm_n","frac","scat","gmax","b_beta","int_mad","dang","f","fvds","g","q","drats"]#,'ptrms_dec','ptrms_inc','ptrms_mad','ptrms_angle']
        #
        # try to read preferences file:
        #user_data_dir = find_pmag_dir.find_user_data_dir("demag_gui")
        # if not user_data_dir:
        #    return preferences
        # if os.path.exists(user_data_dir):
        #    pref_file = os.path.join(user_data_dir, "demag_gui_preferences.json")
        #    if os.path.exists(pref_file):
        #        with open(pref_file, "r") as pfile:
        #            return json.load(pfile)
        return preferences

Response: Gets preferences for certain display variables from zeq_gui_preferences. json file.


Instruction:
Can you generate the documentation for the following Python 3 function
def read_magic_file(self, path, sort_by_this_name):
        DATA = {}
        try:
            with open(path, 'r') as finput:
                lines = list(finput.readlines()[1:])
        except FileNotFoundError:
            return []
        # fin=open(path,'r')
        # fin.readline()
        line = lines[0]
        header = line.strip('\n').split('\t')
        error_strings = []
        for line in lines[1:]:
            tmp_data = {}
            tmp_line = line.strip('\n').split('\t')
            for i in range(len(tmp_line)):
                tmp_data[header[i]] = tmp_line[i]
            if tmp_data[sort_by_this_name] in list(DATA.keys()):
                error_string = "-E- ERROR: magic file %s has more than one line for %s %s" % (
                    path, sort_by_this_name, tmp_data[sort_by_this_name])
                # only print each error message once
                if error_string not in error_strings:
                    print(error_string)
                    error_strings.append(error_string)
            DATA[tmp_data[sort_by_this_name]] = tmp_data
        # fin.close()
        finput.close()
        return(DATA)

Response: reads a magic formated data file from path and sorts the keysbythis_name according to sort_by_this_name


Instruction:
Can you tell what is the following Python 3 function doing
def read_from_LSQ(self, LSQ_file):
        cont = self.user_warning(
            "LSQ import only works if all measurements are present and not averaged during import from magnetometer files to magic format. Do you wish to continue reading interpretations?")
        if not cont:
            return
        self.clear_interpretations(
            message="""Do you wish to clear all previous interpretations on import?""")
        old_s = self.s
        for specimen in self.specimens:
            self.select_specimen(specimen)
            for i in range(len(self.Data[specimen]['zijdblock'])):
                self.mark_meas_good(i)
        self.select_specimen(old_s)
        print("Reading LSQ file")
        interps = read_LSQ(LSQ_file)
        for interp in interps:
            specimen = interp['er_specimen_name']
            if specimen not in self.specimens:
                print(
                    ("specimen %s has no registered measurement data, skipping interpretation import" % specimen))
                continue
            PCA_type = interp['magic_method_codes'].split(':')[0]
            tmin = self.Data[specimen]['zijdblock_steps'][interp['measurement_min_index']]
            tmax = self.Data[specimen]['zijdblock_steps'][interp['measurement_max_index']]
            if 'specimen_comp_name' in list(interp.keys()):
                name = interp['specimen_comp_name']
            else:
                name = None
            new_fit = self.add_fit(specimen, name, tmin, tmax, PCA_type)
            if 'bad_measurement_index' in list(interp.keys()):
                old_s = self.s
                self.select_specimen(specimen)
                for bmi in interp["bad_measurement_index"]:
                    try:
                        self.mark_meas_bad(bmi)
                    except IndexError:
                        print(
                            "Magic Measurments length does not match that recorded in LSQ file")
                self.select_specimen(old_s)
        if self.ie_open:
            self.ie.update_editor()
        self.update_selection()

Response: Reads interpretations from an LSQ file and replaces them with interpretations read from the magic format.


Instruction:
Write a Python 3 function that can
read a. redo formated file and replaces all current interpretations with interpretations taken from the. redo file.

Response:
def read_redo_file(self, redo_file):
        """
        Reads a .redo formated file and replaces all current interpretations
        with interpretations taken from the .redo file

        Parameters
        ----------
        redo_file : path to .redo file to read
        """
        if not self.clear_interpretations():
            return
        print("-I- read redo file and processing new bounds")
        fin = open(redo_file, 'r')

        new_s = ""
        for Line in fin.read().splitlines():
            line = Line.split('\t')
            specimen = line[0]
            if specimen.startswith("current_"):
                specimen = specimen.lstrip("current_")
                new_s = specimen
                if len(line) < 6:
                    continue

            if len(line) < 6:
                print(("insuffecent data for specimen %s and fit %s" %
                       (line[0], line[4])))
                continue
            if len(line) == 6:
                line.append('g')
            if specimen not in self.specimens:
                print(
                    ("specimen %s not found in this data set and will be ignored" % (specimen)))
                continue

            tmin, tmax = self.parse_bound_data(line[2], line[3], specimen)
            new_fit = self.add_fit(
                specimen, line[4], tmin, tmax, line[1], line[5])

            if line[6] == 'b' and new_fit != None:
                self.bad_fits.append(new_fit)

        fin.close()

        if new_s != "":
            self.select_specimen(new_s)
        if (self.s not in self.pmag_results_data['specimens']) or (not self.pmag_results_data['specimens'][self.s]):
            self.current_fit = None
        else:
            self.current_fit = self.pmag_results_data['specimens'][self.s][-1]
        self.calculate_high_levels_data()
        if self.ie_open:
            self.ie.update_editor()
        self.update_selection()


Instruction:
Write a Python 3 function that can
change Demag GUI s current WD to new_WD

Response:
def change_WD(self, new_WD, meas_file=""):
        """
        Changes Demag GUI's current WD to new_WD if possible

        Parameters
        ----------
        new_WD : WD to change to current GUI's WD
        """
        new_WD = os.path.abspath(new_WD)
        if not os.path.isdir(new_WD):
            return
        self.WD = new_WD
        if not meas_file:
            if self.data_model == None:
                if os.path.isfile(os.path.join(self.WD, "measurements.txt")) and os.path.isfile(os.path.join(self.WD, "magic_measurements.txt")):
                    ui_dialog = demag_dialogs.user_input(self, ['data_model'], parse_funcs=[
                                                         float], heading="More than one measurement file found in CWD with different data models please input prefered data model (2.5,3.0)", values=[3])
                    self.show_dlg(ui_dialog)
                    ui_data = ui_dialog.get_values()
                    self.data_model = ui_data[1]['data_model']
                elif os.path.isfile(os.path.join(self.WD, "measurements.txt")):
                    self.data_model = 3.0
                elif os.path.isfile(os.path.join(self.WD, "magic_measurements.txt")):
                    self.data_model = 2.5
                else:
                    self.user_warning(
                        "No measurement file found in chosen directory")
                    self.data_model = 3
            try:
                self.data_model = float(self.data_model)
                if int(self.data_model) == 3:
                    meas_file = os.path.join(self.WD, "measurements.txt")
                elif int(self.data_model) == 2:
                    meas_file = os.path.join(self.WD, "magic_measurements.txt")
                else:
                    meas_file = ''
                    self.data_model = 3
            except (ValueError, TypeError) as e:
                self.user_warning(
                    "Provided data model is unrecognized or invalid, assuming you want data model 3")
                self.data_model = 3

        if os.path.isfile(meas_file):
            self.magic_file = meas_file
        else:
            self.magic_file = self.choose_meas_file()

        if not self.data_model:
            self.data_model = 3


Instruction:
Can you generate the documentation for the following Python 3 function
def init_log_file(self):
        # redirect terminal output
        self.old_stdout = sys.stdout
        sys.stdout = open(os.path.join(self.WD, "demag_gui.log"), 'w+')

Response:
Redirect stdout to a log file to prevent printing to a hanging
        terminal when dealing with the compiled binary.


Instruction:
How would you explain what the following Python 3 function does
def update_pmag_tables(self):
        pmag_specimens, pmag_samples, pmag_sites = [], [], []
        print("-I- Reading previous interpretations from specimen/sample/site tables")
        try:
            pmag_specimens, file_type = pmag.magic_read(
                os.path.join(self.WD, "pmag_specimens.txt"))
        except:
            print("-I- Can't read pmag_specimens.txt")
        try:
            pmag_samples, file_type = pmag.magic_read(
                os.path.join(self.WD, "pmag_samples.txt"))
        except:
            print("-I- Can't read pmag_samples.txt")
        try:
            pmag_sites, file_type = pmag.magic_read(
                os.path.join(self.WD, "pmag_sites.txt"))
        except:
            print("-I- Can't read pmag_sites.txt")
        # --------------------------
        # reads pmag_specimens.txt and
        # update pmag_results_data['specimens'][specimen]
        # with the new interpretation
        # --------------------------

        if self.COORDINATE_SYSTEM == 'geographic':
            current_tilt_correction = 0
        elif self.COORDINATE_SYSTEM == 'tilt-corrected':
            current_tilt_correction = 100
        else:
            current_tilt_correction = -1

        if 'specimens' not in list(self.pmag_results_data.keys()):
            self.pmag_results_data['specimens'] = {}
        for rec in pmag_specimens:
            if 'er_specimen_name' in rec:
                specimen = rec['er_specimen_name']
            else:
                continue

            # initialize list of interpretations
            if specimen not in list(self.pmag_results_data['specimens'].keys()):
                self.pmag_results_data['specimens'][specimen] = []

            if any(k not in list(rec.keys()) for k in ['measurement_step_min', 'measurement_step_max']):
                continue

            methods = rec['magic_method_codes'].strip(
                "\n").replace(" ", "").split(":")
            LPDIR = False
            calculation_type = ""

            for method in methods:
                if "LP-DIR" in method:
                    LPDIR = True
                if "DE-" in method:
                    calculation_type = method

            msu = ''
            if 'measurement_step_unit' in list(rec.keys()):
                msu = rec['measurement_step_unit']

            # if interpretation doesn't exsist create it.
            if float(rec['measurement_step_min']) == 0. or float(rec['measurement_step_min']) == 273.:
                tmin = "0"
            elif msu == 'K' or float(rec['measurement_step_min']) > 3.:  # thermal
                tmin = "%.0fC" % (float(rec['measurement_step_min'])-273.)
            else:  # AF
                tmin = "%.1fmT" % (float(rec['measurement_step_min'])*1000.)

            if float(rec['measurement_step_max']) == 0. or float(rec['measurement_step_max']) == 273.:
                tmax = "0"
            elif msu == 'K' or float(rec['measurement_step_max']) > 3.:  # thermal
                tmax = "%.0fC" % (float(rec['measurement_step_max'])-273.)
            else:  # AF
                tmax = "%.1fmT" % (float(rec['measurement_step_max'])*1000.)

            if 'specimen_comp_name' in list(rec.keys()):
                fname = rec['specimen_comp_name']
            else:
                fname = None
            if calculation_type == "":
                calculation_type = "DE-BFL"

            if (tmin, tmax) in [(f.tmin, f.tmax) for f in self.pmag_results_data['specimens'][specimen]] and calculation_type in [f.PCA_type for f in self.pmag_results_data['specimens'][specimen]]:
                fit = None
            else:
                fit = self.add_fit(specimen, fname, tmin,
                                   tmax, calculation_type)

            if 'specimen_flag' in list(rec.keys()) and rec['specimen_flag'] == 'b':
                self.bad_fits.append(fit)

        # BUG FIX-almost replaced first sample with last due to above assignment to self.s
        if self.specimens:
            self.select_specimen(self.specimens[0])
            self.specimens_box.SetSelection(0)
        if self.s in self.pmag_results_data['specimens'] and self.pmag_results_data['specimens'][self.s]:
            self.initialize_CART_rot(self.specimens[0])
            self.pmag_results_data['specimens'][self.s][-1].select()

        # --------------------------
        # reads pmag_sample.txt and
        # if finds a mean in pmag_samples.txt
        # calculate the mean for self.high_level_means['samples'][samples]
        # If the program finds a codes "DE-FM","DE-FM-LP","DE-FM-UV"in magic_method_codes
        # then the program repeat teh fisher mean
        # --------------------------

        for rec in pmag_samples:
            if "magic_method_codes" in list(rec.keys()):
                methods = rec['magic_method_codes'].strip(
                    "\n").replace(" ", "").split(":")

            else:
                methods = ""
            sample = rec['er_sample_name'].strip("\n")
            LPDIR = False
            calculation_method = ""
            for method in methods:
                if "LP-DIR" in method:
                    LPDIR = True
                if "DE-" in method:
                    calculation_method = method
            if LPDIR:  # this a mean of directions
                calculation_type = "Fisher"
                for dirtype in self.dirtypes:
                    self.calculate_high_level_mean(
                        'samples', sample, calculation_type, 'specimens', self.mean_fit)

        # --------------------------
        # reads pmag_sites.txt and
        # if finds a mean in pmag_sites.txt
        # calculate the mean for self.high_level_means['sites'][site]
        # using specimens or samples, depends on the er_specimen_names or er_samples_names
        #  The program repeat the fisher calculation and oevrwrites it
        # --------------------------

        for rec in pmag_sites:
            methods = rec['magic_method_codes'].strip(
                "\n").replace(" ", "").split(":")
            site = rec['er_site_name'].strip("\n")
            LPDIR = False
            calculation_method = ""
            elements_type = "specimens"
            for method in methods:
                if "LP-DIR" in method or "DA-DIR" in method or "DE-FM" in method:
                    LPDIR = True
                if "DE-" in method:
                    calculation_method = method
            if LPDIR:  # this a mean of directions
                if calculation_method in ["DE-BS"]:
                    calculation_type = "Bingham"
                else:
                    calculation_type = "Fisher"
                if 'er_sample_names' in list(rec.keys()) and len(rec['er_sample_names'].strip('\n').replace(" ", "").split(":")) > 0:
                    elements_type = 'samples'
                if 'er_specimen_names' in list(rec.keys()) and len(rec['er_specimen_names'].strip('\n').replace(" ", "").split(":")) > 0:
                    elements_type = 'specimens'
                self.calculate_high_level_mean(
                    'sites', site, calculation_type, elements_type, self.mean_fit)

Response:
Reads pmag tables from data model 2. 5 and updates them with updates
            their data


Instruction:
Create a Python 3 function for
writing current GUI acceptance criteria to criteria. txt or pmag_criteria. txt depending on data model

Response:
def write_acceptance_criteria_to_file(self):
        """
        Writes current GUI acceptance criteria to criteria.txt or
        pmag_criteria.txt depending on data model
        """
        crit_list = list(self.acceptance_criteria.keys())
        crit_list.sort()
        rec = {}
        rec['pmag_criteria_code'] = "ACCEPT"
        # rec['criteria_definition']=""
        rec['criteria_definition'] = "acceptance criteria for study"
        rec['er_citation_names'] = "This study"

        for crit in crit_list:
            if type(self.acceptance_criteria[crit]['value']) == str:
                if self.acceptance_criteria[crit]['value'] != "-999" and self.acceptance_criteria[crit]['value'] != "":
                    rec[crit] = self.acceptance_criteria[crit]['value']
            elif type(self.acceptance_criteria[crit]['value']) == int:
                if self.acceptance_criteria[crit]['value'] != -999:
                    rec[crit] = "%.i" % (
                        self.acceptance_criteria[crit]['value'])
            elif type(self.acceptance_criteria[crit]['value']) == float:
                if float(self.acceptance_criteria[crit]['value']) == -999:
                    continue
                decimal_points = self.acceptance_criteria[crit]['decimal_points']
                if decimal_points != -999:
                    command = "rec[crit]='%%.%sf'%%(self.acceptance_criteria[crit]['value'])" % (
                        decimal_points)
                    exec(command)
                else:
                    rec[crit] = "%e" % (
                        self.acceptance_criteria[crit]['value'])
        pmag.magic_write(os.path.join(self.WD, "pmag_criteria.txt"), [
                         rec], "pmag_criteria")


Instruction:
Can you implement a function in Python 3 that
shows a dialog that allows user to choose a working directory

Response:
def get_DIR(self):
        """
        Dialog that allows user to choose a working directory
        """
        dlg = wx.DirDialog(self, "Choose a directory:", defaultPath=self.currentDirectory,
                           style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON | wx.DD_CHANGE_DIR)
        ok = self.show_dlg(dlg)
        if ok == wx.ID_OK:
            new_WD = dlg.GetPath()
            dlg.Destroy()
        else:
            new_WD = os.getcwd()
            dlg.Destroy()
        return new_WD


Instruction:
Can you implement a function in Python 3 that
opens a dialog allowing the user to choose a measurement file

Response:
def choose_meas_file(self, event=None):
        """
        Opens a dialog allowing the user to pick a measurement file
        """
        dlg = wx.FileDialog(
            self, message="Please choose a measurement file",
            defaultDir=self.WD,
            defaultFile="measurements.txt",
            wildcard="measurement files (*.magic,*.txt)|*.magic;*.txt",
            style=wx.FD_OPEN | wx.FD_CHANGE_DIR
        )
        if self.show_dlg(dlg) == wx.ID_OK:
            meas_file = dlg.GetPath()
            dlg.Destroy()
        else:
            meas_file = ''
            self.data_model = 2.5
            dlg.Destroy()
        return meas_file


Instruction:
Implement a function in Python 3 to
show a dialog that tells the user that a file has been saved

Response:
def saved_dlg(self, message, caption='Saved:'):
        """
        Shows a dialog that tells the user that a file has been saved

        Parameters
        ----------
        message : message to display to user
        caption : title for dialog (default: "Saved:")
        """
        dlg = wx.MessageDialog(self, caption=caption,
                               message=message, style=wx.OK)
        result = self.show_dlg(dlg)
        dlg.Destroy()


Instruction:
How would you code a function in Python 3 to
show a dialog that warns the user about some action

Response:
def user_warning(self, message, caption='Warning!'):
        """
        Shows a dialog that warns the user about some action

        Parameters
        ----------
        message : message to display to user
        caption : title for dialog (default: "Warning!")

        Returns
        -------
        continue_bool : True or False
        """
        dlg = wx.MessageDialog(self, message, caption,
                               wx.OK | wx.CANCEL | wx.ICON_WARNING)
        if self.show_dlg(dlg) == wx.ID_OK:
            continue_bool = True
        else:
            continue_bool = False
        dlg.Destroy()
        return continue_bool


Instruction:
How would you code a function in Python 3 to
function called when a close of change acceptance criteria dialog is shown.

Response:
def on_close_criteria_box(self, dia):
        """
        Function called on close of change acceptance criteria dialog that
        writes new criteria to the hardrive and sets new criteria as GUI's
        current criteria.

        Parameters
        ----------
        dia : closed change criteria dialog
        """
        window_list_specimens = [
            'specimen_n', 'specimen_mad', 'specimen_dang', 'specimen_alpha95']
        window_list_samples = ['sample_n', 'sample_n_lines',
                               'sample_n_planes', 'sample_k', 'sample_r', 'sample_alpha95']
        window_list_sites = ['site_n', 'site_n_lines',
                             'site_n_planes', 'site_k', 'site_r', 'site_alpha95']
        demag_gui_supported_criteria = window_list_specimens + \
            window_list_samples+window_list_sites

        if self.data_model == 3:
            new_crits = []
            for crit in demag_gui_supported_criteria:
                new_crit = {}
                command = "dia.set_%s.GetValue()" % (crit)
                new_value = pmag.execute(command, dia=dia)
                if new_value == None or new_value == '':
                    continue
                d = findall(r"[-+]?\d*\.\d+|\d+", new_value)
                if len(d) > 0:
                    d = d[0]
                comp = new_value.strip(str(d))
                if comp == '':
                    comp = '>='
                if 'specimen' in crit:
                    col = "specimens."+map_magic.spec_magic2_2_magic3_map[crit]
                elif 'sample' in crit:
                    col = "samples."+map_magic.samp_magic2_2_magic3_map[crit]
                elif 'site' in crit:
                    col = "sites."+map_magic.site_magic2_2_magic3_map[crit]
                else:
                    print("no way this like is impossible")
                    continue
                new_crit['criterion'] = "ACCEPT"
                new_crit['criterion_value'] = d
                new_crit['criterion_operation'] = comp
                new_crit['table_column'] = col
                new_crit['citations'] = "This study"
                new_crit['description'] = ''
                new_crits.append(new_crit)
            cdf = DataFrame(new_crits)
            cdf = cdf.set_index("table_column")
            cdf["table_column"] = cdf.index
            cdf = cdf.reindex_axis(sorted(cdf.columns), axis=1)
            if 'criteria' not in self.con.tables:
                cols = ['criterion', 'criterion_value', 'criterion_operation',
                        'table_column', 'citations', 'description']
                self.con.add_empty_magic_table('criteria', col_names=cols)
            self.con.tables['criteria'].df = cdf
            self.con.tables['criteria'].write_magic_file(dir_path=self.WD)
        else:
            for crit in demag_gui_supported_criteria:
                command = "new_value=dia.set_%s.GetValue()" % (crit)
                exec(command)
                # empty box
                if new_value == "":
                    self.acceptance_criteria[crit]['value'] = -999
                    continue
                # box with no valid number
                try:
                    float(new_value)
                except:
                    self.show_crit_window_err_messege(crit)
                    continue
                self.acceptance_criteria[crit]['value'] = float(new_value)

            #  message dialog
            self.saved_dlg(message="changes saved to criteria")
            self.write_acceptance_criteria_to_file()
            dia.Destroy()


Instruction:
Can you write a function in Python 3 where it
shows a dialog to show a message if a valid naumber is not entered to criteria dialog box

Response:
def show_crit_window_err_messege(self, crit):
        """
        error message if a valid naumber is not entered to criteria dialog
        boxes
        """
        dlg = wx.MessageDialog(
            self, caption="Error:", message="not a vaild value for statistic %s\n ignoring value" % crit, style=wx.OK)
        result = self.show_dlg(dlg)
        if result == wx.ID_OK:
            dlg.Destroy()