Instruction:
Here you have a function in Python 3, explain what it does
def On_close_MagIC_dialog(self, dia):

        def add_missing_ages(df):
            """
            Take a dataframe and add min/max age, age, age_sigma, age_units.
            Use values gained from dialog, but don't overwrite values already
            in the dataframe.
            """
            age_columns = df.columns[df.columns.str.startswith('age')]
            for col, value in {'age_high': max_age, 'age_low': min_age,
                            'age': age, 'age_sigma': age_sigma, 'age_unit': age_units}.items():
                if cb.not_null(value):
                    if col in age_columns:
                        df[col] = np.where(df[col].apply(cb.not_null), df[col], value)
                    else:
                        df[col] = value
            return df

        if dia.cb_acceptance_criteria.GetValue():
            use_criteria = 'existing'
        else:
            use_criteria = 'none'

        # -- coordinate system
        if dia.rb_spec_coor.GetValue():
            coord = "s"
        elif dia.rb_geo_coor.GetValue():
            coord = "g"
        elif dia.rb_tilt_coor.GetValue():
            coord = "t"
        elif dia.rb_geo_tilt_coor.GetValue():
            coord = "b"
        else:
            coord = "s"

        # -- default age options
        DefaultAge = ["none"]
        add_ages = dia.add_ages.GetValue()
        if add_ages:
            age_units = dia.default_age_unit.GetValue()
            min_age = dia.default_age_min.GetValue()
            max_age = dia.default_age_max.GetValue()
            age = dia.default_age.GetValue()
            age_sigma = dia.default_age_sigma.GetValue()
            if (min_age and max_age) or age:
                # enough age data provided
                pass
            else:
                go_on = self.user_warning("Not enough age data provided (you must provide lower and upper bound, or age).\nPress OK to skip ages for now, or cancel to end this process.")
                if not go_on:
                    self.user_warning("Aborting, please try again.", caption="Message")
                    return
                add_ages = False

            if min_age and max_age:
                DefaultAge = [min_age, max_age, age_units]

        # -- sample mean
        avg_directions_by_sample = False
        if dia.cb_sample_mean.GetValue():
            avg_directions_by_sample = True

        vgps_level = 'site'
        if dia.cb_sample_mean_VGP.GetValue():
            vgps_level = 'sample'

        # -- site mean

        if dia.cb_site_mean.GetValue():
            pass

        # -- location mean
        avg_by_polarity = False
        if dia.cb_location_mean.GetValue():
            avg_by_polarity = True

        if self.data_model == 3.0:
            # update or add age data to the sites table, but don't overwrite existing data
            if add_ages:
                site_df = self.con.tables['sites'].df
                self.con.tables['sites'].df = add_missing_ages(site_df)
                self.con.write_table_to_file("sites")

            # set some variables
            priorities = ['DA-AC-ARM', 'DA-AC-TRM']
            for p in priorities:
                if not p.startswith('DA-AC-'):
                    p = 'DA-AC-'+p
            # translate coord into coords
            if coord == 's':
                coords = ['-1']
            elif coord == 'g':
                coords = ['0']
            elif coord == 't':
                coords = ['100']
            elif coord == 'b':
                coords = ['0', '100']
            else:
                coords = ['-1']

            if vgps_level == 'sample':
                vgps = 1  # save sample level VGPS/VADMs
            else:
                vgps = 0  # site level

            nositeints = 0
            version_num = pmag.get_version()
            get_model_lat = 0  # skips VADM calculation entirely
            Dcrit, Icrit, nocrit = 0, 0, 0  # default criteria input

            # still broken (needs translation or determination of translation necessity)
            if use_criteria == 'none':
                Dcrit, Icrit, nocrit = 1, 1, 1  # no selection criteria
                crit_data = pmag.default_criteria(nocrit)
            elif use_criteria == 'existing':
                crit_data = self.read_criteria_file()
                if crit_data == None:
                    crit_data = pmag.default_criteria(nocrit)
                    print(
                        "No acceptance criteria found in criteria.txt defualt PmagPy criteria used instead")
                else:
                    print("Acceptance criteria from criteria.txt used")
            else:
                # use default criteria
                crit_data = pmag.default_criteria(nocrit)
                print("PmagPy default criteria used")

            accept = {}
            for critrec in crit_data:
                if type(critrec) != dict:
                    continue
                for key in list(critrec.keys()):
                    # need to migrate specimen_dang to specimen_int_dang for intensity data using old format
                    if 'IE-SPEC' in list(critrec.keys()) and 'specimen_dang' in list(critrec.keys()) and 'specimen_int_dang' not in list(critrec.keys()):
                        critrec['specimen_int_dang'] = critrec['specimen_dang']
                        del critrec['specimen_dang']
                    # need to get rid of ron shaars sample_int_sigma_uT
                    if 'sample_int_sigma_uT' in list(critrec.keys()):
                        critrec['sample_int_sigma'] = '%10.3e' % (
                            eval(critrec['sample_int_sigma_uT'])*1e-6)
                    if key not in list(accept.keys()) and critrec[key] != '':
                        accept[key] = critrec[key]

            if use_criteria == 'default':
                pmag.magic_write(critout, [accept], 'pmag_criteria')
                print("\n Pmag Criteria stored in ", critout, '\n')

            if 'specimens' not in self.con.tables:
                self.user_warning(
                    "No specimen interpretations found in the current contribution samples, sites, and locations cannot be exported, aborting")
                return
            spec_df = self.con.tables['specimens'].df
            if 'sites' not in self.con.tables:
                self.con.add_empty_magic_table('sites')
            site_df = self.con.tables['sites'].df
            SiteNFO = site_df.to_dict("records")
            Data = spec_df.to_dict("records")

            comment = ""
            orient = list(spec_df[spec_df['dir_tilt_correction'].notnull(
            )]['dir_tilt_correction'].drop_duplicates())
            samples = sorted(list(spec_df['sample'].dropna().drop_duplicates()))
            sites = sorted(list(spec_df['site'].dropna().drop_duplicates()))
            locations = sorted(list(spec_df['location'].dropna().drop_duplicates()))
            Comps = sorted(
                list(spec_df[spec_df['dir_comp'].notnull()]['dir_comp'].drop_duplicates()))
            Comps = [c for c in Comps if type(c) == str]
            # find all the sites with height info.
            height_info = pmag.get_dictitem(SiteNFO, 'height', '', 'F')

            nocorrection = ['DA-NL', 'DA-AC', 'DA-CR']
            SpecInts = []
            # retrieve specimens with intensity data
            IntData = pmag.get_dictitem(Data, 'int_abs', '', 'F')
            if nocrit == 0:  # use selection criteria
                for rec in IntData:  # do selection criteria
                    kill = pmag.grade(
                        rec, accept, 'specimen_int', data_model=3.0)
                    if len(kill) == 0:
                        # intensity record to be included in sample, site calculations
                        SpecInts.append(rec)
            else:
                # take everything - no selection criteria
                SpecInts = IntData[:]
            # check for required data adjustments
            if len(nocorrection) > 0 and len(SpecInts) > 0:
                for cor in nocorrection:
                    # exclude the corrections not specified for inclusion
                    SpecInts = pmag.get_dictitem(
                        SpecInts, 'method_codes', cor, 'not')
            # take top priority specimen of its name in remaining specimens (only one per customer)
            PrioritySpecInts = []
            # get list of uniq specimen names
            specimens = pmag.get_specs(SpecInts)
            for spec in specimens:
                # all the records for this specimen
                ThisSpecRecs = pmag.get_dictitem(
                    SpecInts, 'specimen', spec, 'T')
                if len(ThisSpecRecs) == 1:
                    PrioritySpecInts.append(ThisSpecRecs[0])
                elif len(ThisSpecRecs) > 1:  # more than one
                    prec = []
                    for p in priorities:
                        # all the records for this specimen
                        ThisSpecRecs = pmag.get_dictitem(
                            SpecInts, 'method_codes', p, 'has')
                        if len(ThisSpecRecs) > 0:
                            prec.append(ThisSpecRecs[0])
                            PrioritySpecInts.append(
                                prec[0])  # take the best one
            SpecInts = PrioritySpecInts  # this has the first specimen record

            # apply criteria to directional data
            # retrieve specimens with directed lines and planes and some measuremnt data
            Ns = spec_df[spec_df['dir_n_measurements']
                         != ''].to_dict("records")
            SpecDirs = []
            if nocrit != 1:  # use selection criteria
                for rec in Ns:  # look through everything with specimen_n for "good" data
                    kill = pmag.grade(
                        rec, accept, 'specimen_dir', data_model=3.0)
                    if len(kill) == 0:  # nothing killed it
                        SpecDirs.append(rec)
            else:  # no criteria
                SpecDirs = Ns[:]  # take them all

            # list of all sample data and list of those that pass the DE-SAMP criteria
            PmagSamps, SampDirs = [], []
            PmagSites = []  # list of all site data
            SampInts = []
            renamelnp = {'R': 'dir_r', 'n': 'dir_n_samples', 'n_total': 'dir_n_specimens', 'alpha95': 'dir_alpha95',
                         'n_lines': 'dir_n_specimens_lines', 'K': 'dir_k', 'dec': 'dir_dec', 'n_planes': 'dir_n_specimens_planes', 'inc': 'dir_inc'}
            for samp in samples:  # run through the sample names
                if not avg_directions_by_sample:
                    break
                # get all the directional data for this sample
                SampDir = pmag.get_dictitem(SpecDirs, 'sample', samp, 'T')
                if len(SampDir) <= 0:
                    continue  # if no directions
                for coord in coords:  # step through desired coordinate systems
                    # get all the directions for this sample
                    CoordDir = pmag.get_dictitem(
                        SampDir, 'dir_tilt_correction', coord, 'T')
                    if len(CoordDir) <= 0:
                        continue  # no data for this coordinate system
                    for comp in Comps:
                        # get all directions from this component
                        CompDir = pmag.get_dictitem(
                            CoordDir, 'dir_comp', comp, 'T')
                        CompDir = [
                            x for x in CompDir if 'result_quality' in x and x['result_quality'] == 'g']
                        if len(CompDir) <= 0:
                            continue  # no data for comp
                        PmagSampRec = pmag.dolnp3_0(CompDir)
                        for k, v in list(renamelnp.items()):
                            if k in PmagSampRec:
                                PmagSampRec[v] = PmagSampRec[k]
                                del PmagSampRec[k]
                        # decorate the sample record
                        PmagSampRec["location"] = CompDir[0]['location']
                        PmagSampRec["site"] = CompDir[0]['site']
                        PmagSampRec["sample"] = samp
                        PmagSampRec["citations"] = "This study"
                        PmagSampRec['software_packages'] = version_num + \
                            ': demag_gui.v.3.0'
                        if CompDir[0]['result_quality'] == 'g':
                            PmagSampRec['result_quality'] = 'g'
                        else:
                            PmagSampRec['result_quality'] = 'b'
                        if nocrit != 1:
                            PmagSampRec['criteria'] = "ACCEPT"
                        site_height = pmag.get_dictitem(
                            height_info, 'site', PmagSampRec['site'], 'T')
                        if len(site_height) > 0:
                            # add in height if available
                            PmagSampRec["height"] = site_height[0]['height']
                        PmagSampRec['dir_comp_name'] = comp
                        PmagSampRec['dir_tilt_correction'] = coord
                        specs = [d['specimen'] for d in CompDir]
                        if 'dir_n_specimens' not in PmagSampRec:
                            PmagSampRec['dir_n_specimens'] = len(specs)
                        # get a list of the specimen names used
                        PmagSampRec['specimens'] = reduce(
                            lambda x, y: str(x)+':'+str(y), specs)
                        # get old method codes
                        prev_meth_codes = self.con.tables['samples'].df.loc[samp]['method_codes']
                        # get a list of the methods used
                        new_meth_codes = pmag.get_list(CompDir, 'method_codes')
                        if isinstance(prev_meth_codes, Series):
                            merged_meths = self.merge_meth_codes(
                                prev_meth_codes.iloc[0], new_meth_codes)
                        else:
                            merged_meths = self.merge_meth_codes(
                                prev_meth_codes, new_meth_codes)
                        PmagSampRec['method_codes'] = merged_meths
                        if nocrit != 1:  # apply selection criteria
                            kill = pmag.grade(
                                PmagSampRec, accept, 'sample_dir', data_model=3.0)
                        else:
                            kill = []
                        if len(kill) > 0:
                            PmagSampRec['result_quality'] = 'b'
                        else:
                            SampDirs.append(PmagSampRec)
                        if vgps == 1:  # if sample level VGP info desired, do that now
                            try:
                                PmagResRec = pmag.getsampVGP(
                                    PmagSampRec, SiteNFO, data_model=self.data_model)
                            except KeyError:
                                print(
                                    ("no lat lon data for sample %s skipping VGP calculation" % samp))
                                PmagResRec = ""
                            if PmagResRec != "":
                                for k in ['vgp_dp', 'vgp_dm', 'vgp_lat', 'vgp_lon']:
                                    PmagSampRec[k] = PmagResRec[k]
                        PmagSamps.append(PmagSampRec)

            # removed average_all_components check because demag GUI never averages directional components
            # removed intensity average portion as demag GUI has no need of this also cause translating this is a bitch

            if len(PmagSamps) > 0:
                if 'samples' not in self.con.tables:
                    self.con.add_empty_magic_table('samples')
                for dc in ['magic_method_codes']:
                    if dc in self.con.tables['samples'].df:
                        del self.con.tables['samples'].df[dc]
                samps_df = DataFrame(PmagSamps)
                samps_df = samps_df.set_index('sample')
                samps_df['sample'] = samps_df.index
                nsdf = self.con.tables['samples'].merge_dfs(samps_df)
                if not vgps == 1:
                    nsdf.drop([col for col in nsdf.columns if type(
                        col) == str and col.startswith('vgp')], axis=1, inplace=True)
                nsdf = nsdf.reindex_axis(sorted(nsdf.columns), axis=1)
                self.con.tables['samples'].df = nsdf
                self.con.tables['samples'].write_magic_file(dir_path=self.WD)

            # create site averages from specimens or samples as specified
            for site in sites:
                for coord in coords:
                    if dia.combo_site_mean.GetValue() == 'samples' and avg_directions_by_sample:
                        # if sample averages at site level desired
                        key, comp_key, dirlist = 'sample', 'dir_comp_name', SampDirs
                    else:
                        # if specimen averages at site level desired
                        key, comp_key, dirlist = 'specimen', 'dir_comp', SpecDirs
                    # get all the sites with  directions
                    tmp = pmag.get_dictitem(dirlist, 'site', site, 'T')
                    tmp1 = pmag.get_dictitem(
                        tmp, 'dir_tilt_correction', coord, 'T', float_to_int=True)
                    # fish out site information (lat/lon, etc.)
                    sd = pmag.get_dictitem(SiteNFO, 'site', site, 'T')
                    if len(sd) <= 0:  # no data for this site
                        print(
                            ('site information not found in sites.txt for site, %s. skipping.' % site))
                        continue
                    for comp in Comps:
                        # get all components comp
                        siteD = pmag.get_dictitem(tmp1, comp_key, comp, 'T')
                        # remove bad data from means
                        siteD = [
                            x for x in siteD if 'result_quality' in x and x['result_quality'] == 'g']
                        if len(siteD) <= 0:
                            # print("no data for comp %s in site %s. skipping"%(comp,site))
                            continue
                        PmagSiteRec = PmagSampRec = pmag.dolnp3_0(
                            siteD)  # get an average for this site
                        for k, v in list(renamelnp.items()):
                            if k in PmagSiteRec:
                                PmagSiteRec[v] = PmagSiteRec[k]
                                del PmagSiteRec[k]
                        # decorate the site record
                        PmagSiteRec['dir_comp_name'] = comp
                        PmagSiteRec["location"] = siteD[0]['location']
                        PmagSiteRec["site"] = siteD[0]['site']
                        PmagSiteRec['dir_tilt_correction'] = coord
                        PmagSiteRec['samples'] = pmag.get_list(siteD, 'sample')
                        if dia.combo_site_mean.GetValue() == 'samples' and avg_directions_by_sample:
                            PmagSiteRec['specimens'] = pmag.get_list(
                                siteD, 'specimens')
                        else:
                            PmagSiteRec['specimens'] = pmag.get_list(
                                siteD, 'specimen')
                        if 'dir_n_samples' not in list(PmagSiteRec.keys()):
                            PmagSiteRec['dir_n_samples'] = len(
                                PmagSiteRec['samples'].split(':'))
                        if 'dir_n_specimens' not in list(PmagSiteRec.keys()):
                            PmagSiteRec['dir_n_specimens'] = len(
                                PmagSiteRec['specimens'].split(':'))
                        # determine the demagnetization code (DC3,4 or 5) for this site
                        AFnum = len(pmag.get_dictitem(
                            siteD, 'method_codes', 'LP-DIR-AF', 'has'))
                        Tnum = len(pmag.get_dictitem(
                            siteD, 'method_codes', 'LP-DIR-T', 'has'))
                        DC = 3
                        if AFnum > 0:
                            DC += 1
                        if Tnum > 0:
                            DC += 1
                        PmagSiteRec['method_codes'] = pmag.get_list(
                            siteD, 'method_codes')+':' + 'LP-DC'+str(DC)
                        PmagSiteRec['method_codes'].strip(":")

                        PmagSiteRec["citations"] = "This study"
                        PmagSiteRec['software_packages'] = version_num + \
                            ': demag_gui.v.3.0'

                        # here we need to grab ages from sites or ages
                        site_age_rec = Series()
                        if 'ages' in self.con.tables:
                            ages_df = self.con.tables['ages'].df
                            if 'site' in ages_df.columns:
                                site_age_records = ages_df[ages_df['site'] == site]
                                if len(site_age_records):
                                    if isinstance(site_age_records, Series):
                                        site_age_rec = site_age_records
                                    else:
                                        site_age_rec = site_age_records.iloc[0]
                        if not len(site_age_rec):
                            sites_df = self.con.tables['sites'].df
                            site_age_records = sites_df.loc[site]
                            if len(site_age_records):
                                if isinstance(site_age_records, Series):
                                    site_age_rec = site_age_records
                                else:
                                    site_age_rec = site_age_records.iloc[0]

                        PmagSiteRec['criteria'] = 'ACCEPT'
                        if 'dir_n_specimens_lines' in list(PmagSiteRec.keys()) and 'dir_n_specimens_planes' in list(PmagSiteRec.keys()) and PmagSiteRec['dir_n_specimens_lines'] != "" and PmagSiteRec['dir_n_specimens_planes'] != "":
                            if int(PmagSiteRec["dir_n_specimens_planes"]) > 0:
                                PmagSiteRec["method_codes"] = PmagSiteRec['method_codes']+":DE-FM-LP"
                            elif int(PmagSiteRec["dir_n_specimens_lines"]) > 2:
                                PmagSiteRec["method_codes"] = PmagSiteRec['method_codes']+":DE-FM"

                        site_height = pmag.get_dictitem(
                            height_info, 'site', site, 'T')
                        if len(site_height) > 0:
                            PmagSiteRec["height"] = site_height[0]['height']
                        if '0' in PmagSiteRec['dir_tilt_correction'] and "DA-DIR-GEO" not in PmagSiteRec['method_codes']:
                            PmagSiteRec['method_codes'] = PmagSiteRec['method_codes']+":DA-DIR-GEO"
                        if '100' in PmagSiteRec['dir_tilt_correction'] and "DA-DIR-TILT" not in PmagSiteRec['method_codes']:
                            PmagSiteRec['method_codes'] = PmagSiteRec['method_codes'] + \
                                ":DA-DIR-TILT"
                        PmagSiteRec['dir_polarity'] = ""
# assign polarity based on angle of pole lat to spin axis - may want to re-think this sometime

                        if dia.cb_site_mean_VGP.GetValue():
                            dec = float(PmagSiteRec["dir_dec"])
                            inc = float(PmagSiteRec["dir_inc"])
                            if 'dir_alpha95' in list(PmagSiteRec.keys()) and PmagSiteRec['dir_alpha95'] != "":
                                a95 = float(PmagSiteRec["dir_alpha95"])
                            else:
                                a95 = 180.
                            # fish out site information (lat/lon, etc.)
                            sitedat = [x for x in pmag.get_dictitem(
                                SiteNFO, 'site', PmagSiteRec['site'], 'T') if x['lat'] != None and x['lon'] != None]
                            if len(sitedat) != 0:
                                sitedat = sitedat[0]
                            else:
                                sitedat = {}
                            try:
                                PmagSiteRec['lat'] = float(sitedat['lat'])
                                PmagSiteRec['lon'] = float(sitedat['lon'])
                                lat, lon = PmagSiteRec['lat'], PmagSiteRec['lon']
                                calculate = True
                            except (KeyError, ValueError, TypeError) as e:
                                calculate = False
                                ui_dialog = demag_dialogs.user_input(self, ['Latitude', 'Longitude'], parse_funcs=[
                                                                     float, float], heading="Missing Latitude or Longitude data for site: %s" % site)
                                self.show_dlg(ui_dialog)
                                ui_data = ui_dialog.get_values()
                                if ui_data[0]:
                                    PmagSiteRec['lat'] = ui_data[1]['Latitude']
                                    PmagSiteRec['lon'] = ui_data[1]['Longitude']
                                    lat, lon = PmagSiteRec['lat'], PmagSiteRec['lon']
                                    calculate = True
                                else:
                                    self.user_warning(
                                        "insuffecent data provided skipping VGP calculation for site %s and comp %s" % (site, comp))
                            if calculate:
                                plong, plat, dp, dm = pmag.dia_vgp(
                                    dec, inc, a95, lat, lon)  # get the VGP for this site
                                PmagSiteRec["vgp_lat"] = '%7.1f ' % (plat)
                                PmagSiteRec["vgp_lon"] = '%7.1f ' % (plong)
                                PmagSiteRec["vgp_dp"] = '%7.1f ' % (dp)
                                PmagSiteRec["vgp_dm"] = '%7.1f ' % (dm)

                                angle = pmag.angle([0, 0], [0, (90-plat)])
                                if angle <= 55.:
                                    PmagSiteRec["dir_polarity"] = 'n'
                                if angle > 55. and angle < 125.:
                                    PmagSiteRec["dir_polarity"] = 't'
                                if angle >= 125.:
                                    PmagSiteRec["dir_polarity"] = 'r'

                        kill = pmag.grade(PmagSiteRec, accept, 'site_dir')
                        if len(kill) > 0:
                            PmagSiteRec['result_quality'] = 'b'
                        else:
                            PmagSiteRec['result_quality'] = 'g'

                        # Carry over data from previous sites
                        prev_dat = pmag.get_dictitem(
                            SiteNFO, 'site', PmagSiteRec['site'], 'T')
                        if len(prev_dat) != 0:
                            for ndd in set(PmagSiteRec.keys()).symmetric_difference(set(prev_dat[0].keys())):
                                sitedat = [
                                    x for x in prev_dat if ndd in x and x[ndd] != None]
                                if len(sitedat) != 0:
                                    sitedat = sitedat[0]
                                else:
                                    continue
                                PmagSiteRec[ndd] = sitedat[ndd]

                        PmagSites.append(PmagSiteRec)

            if len(PmagSites) > 0:
                if 'sites' not in self.con.tables:
                    self.con.tables.add_empty_magic_table('sites')
                sites_df = DataFrame(PmagSites)
                if 'tilt_correction' in sites_df.columns:
                    sites_df.drop('tilt_correction', axis=1, inplace=True)
                sites_df = sites_df.set_index('site')
                sites_df['site'] = sites_df.index
                nsdf = self.con.tables['sites'].merge_dfs(sites_df)
                if not dia.cb_site_mean_VGP.GetValue():
                    nsdf.drop([col for col in nsdf.columns if type(
                        col) == str and col.startswith('vgp')], axis=1, inplace=True)
                nsdf = nsdf.reindex_axis(sorted(nsdf.columns), axis=1)
                self.con.tables['sites'].df = nsdf
                self.con.tables['sites'].write_magic_file(dir_path=self.WD)

            # location mean section
            PmagLocs = []
            for location in locations:
                if not avg_by_polarity:
                    break
                locrecs = pmag.get_dictitem(
                    PmagSites, 'location', location, 'T')
                if len(locrecs) < 2:
                    print(("no data for location %s" % location))
                    continue
                for coord in coords:
                    # find the tilt corrected data
                    coordrecs = pmag.get_dictitem(
                        locrecs, 'dir_tilt_correction', coord, 'T')
                    if len(coordrecs) < 2:
                        print(
                            ("not enough data of %s percent tilt corrected data in sites to calculate locations mean or vgp" % coord))
                        continue
                    for comp in Comps:
                        # fish out all of the component
                        crecs = pmag.get_dictitem(
                            coordrecs, 'dir_comp_name', comp, 'T')
                        if len(crecs) < 2:
                            print(
                                ("insuffecent data for comp %s when calculating location" % comp))
                            continue
                        precs = []
                        for rec in crecs:
                            prec = {'dec': rec['dir_dec'], 'inc': rec['dir_inc'],
                                    'name': rec['site'], 'loc': rec['location']}
                            prec = {k: v if v != None else 'None' for k,
                                    v in list(prec.items())}
                            precs.append(prec)
                        # calculate average by polarity
                        polpars = pmag.fisher_by_pol(precs)
                        # hunt through all the modes (normal=A, reverse=B, all=ALL)
                        for mode in list(polpars.keys()):
                            PolRes = {}
                            PolRes['citations'] = 'This study'
                            PolRes["result_name"] = "Polarity Average: Polarity "+mode
                            PolRes["pole_comp_name"] = comp+':'+mode
                            PolRes["dir_dec"] = '%7.1f' % (
                                polpars[mode]['dec'])
                            PolRes["dir_inc"] = '%7.1f' % (
                                polpars[mode]['inc'])
                            PolRes["dir_n_sites"] = '%i' % (polpars[mode]['n'])
                            PolRes["dir_r"] = '%5.4f' % (polpars[mode]['r'])
                            PolRes["dir_k"] = '%6.0f' % (polpars[mode]['k'])
                            PolRes["dir_alpha95"] = '%7.1f' % (
                                polpars[mode]['alpha95'])
                            PolRes['sites'] = polpars[mode]['sites']
                            sites_dat = self.con.tables['sites'].df
                            for e in ['samples', 'specimens']:
                                PolRes[e] = reduce(lambda x, y: x+':'+y, [sites_dat.loc[site][e].iloc[0] if isinstance(
                                    sites_dat.loc[site][e], Series) else sites_dat.loc[site][e] for site in PolRes['sites'].split(':')])
                            PolRes['dir_n_samples'] = len(
                                PolRes['samples'].split(':'))
                            PolRes['dir_n_specimens'] = len(
                                PolRes['specimens'].split(':'))
                            PolRes['location'] = polpars[mode]['locs']
                            PolRes['software_packages'] = version_num + \
                                ': demag_gui.v.3.0'
                            PolRes['dir_tilt_correction'] = coord
                            if add_ages:
                                loc_rec = {}
                                if 'locations' in self.con.tables:
                                    locs_df = self.con.tables['locations'].df
                                    self.con.tables['locations'].df = add_missing_ages(locs_df)
                                    loc_recs = locs_df.loc[location]
                                    if len(loc_recs):
                                        if isinstance(loc_recs, Series):
                                            loc_rec = loc_recs
                                        else:
                                            loc_rec = loc_recs.iloc[0]
                                PolRes['age_high'] = loc_rec.get('age_high', max_age)
                                PolRes['age_low'] = loc_rec.get('age_low', min_age)
                                PolRes['age'] = loc_rec.get('age', age)
                                PolRes['age_sigma'] = loc_rec.get('age_sigma', age_sigma)
                                PolRes['age_unit'] = loc_rec.get('age_unit', age_units)
                            if dia.cb_location_mean_VGP.GetValue():
                                sucess_lat_lon_info = True
                                if 'locations' in self.con.tables:
                                    locs_dat = self.con.tables['locations'].df
                                    if 'lat_n' in locs_dat.columns:
                                        lat = locs_dat['lat_n'][location].iloc[0] if isinstance(
                                            locs_dat['lat_n'][location], Series) else locs_dat['lat_n'][location]
                                    elif 'lat_s' in locs_dat.columns:
                                        lat = locs_dat['lat_s'][location].iloc[0] if isinstance(
                                            locs_dat['lat_s'][location], Series) else locs_dat['lat_s'][location]
                                    else:
                                        sucess_lat_lon_info = False
                                    if 'lon_e' in locs_dat.columns:
                                        lon = locs_dat['lon_e'][location].iloc[0] if isinstance(
                                            locs_dat['lon_e'][location], Series) else locs_dat['lon_e'][location]
                                    elif 'lon_w' in locs_dat.columns:
                                        lon = locs_dat['lon_w'][location].iloc[0] if isinstance(
                                            locs_dat['lon_w'][location], Series) else locs_dat['lon_w'][location]
                                    else:
                                        sucess_lat_lon_info = False
                                if not sucess_lat_lon_info:
                                    ui_dialog = demag_dialogs.user_input(self, ['North Boundary Latitude', 'South Boundary Latitude', 'East Boundary Longitude', 'West Boundary Longitude'], parse_funcs=[
                                                                         float, float, float, float], heading="Missing Latitude or Longitude data for location %s please define the boundary of this region so VGP calculations can be preformed" % location)
                                    ui_data = ui_dialog.get_values()
                                    if ui_data[0]:
                                        PolRes['lat_n'] = ui_data[1]['North Boundary Latitude']
                                        PolRes['lat_s'] = ui_data[1]['South Boundary Latitude']
                                        PolRes['lon_e'] = ui_data[1]['East Boundary Longitude']
                                        PolRes['lon_w'] = ui_data[1]['West Boundary Longitude']
                                        lat, lon = PolRes['lat_n'], PolRes['lon_e']
                                        sucess_lat_lon_info = True
                                    else:
                                        self.user_warning(
                                            "insuffecent data provided skipping VGP calculation for location %s" % location)
                                try:
                                    dec, inc, a95, lat, lon = float(polpars[mode]['dec']), float(
                                        polpars[mode]['inc']), float(polpars[mode]['alpha95']), float(lat), float(lon)
                                except (UnboundLocalError, TypeError):
                                    print(
                                        "unable to obtain all data needed for VGP calculation, skipping")
                                    sucess_lat_lon_info = False
                                if sucess_lat_lon_info:
                                    # get the VGP for this pole component
                                    plong, plat, dp, dm = pmag.dia_vgp(
                                        dec, inc, a95, lat, lon)
                                    PolRes["pole_lat"] = '%7.1f ' % (plat)
                                    PolRes["pole_lon"] = '%7.1f ' % (plong)
                                    PolRes["pole_dp"] = '%7.1f ' % (dp)
                                    PolRes["pole_dm"] = '%7.1f ' % (dm)
                                    PolRes["pole_alpha95"] = PolRes['dir_alpha95']
                                    PolRes["pole_r"] = PolRes['dir_r']
                                    PolRes["pole_k"] = PolRes['dir_k']
                                    angle = pmag.angle([0, 0], [0, (90-plat)])
                                    if angle <= 55.:
                                        PolRes["dir_polarity"] = 'n'
                                    if angle > 55. and angle < 125.:
                                        PolRes["dir_polarity"] = 't'
                                    if angle >= 125.:
                                        PolRes["dir_polarity"] = 'r'

                            # fix not duplicating data
                            prev_dat = pmag.get_dictitem(locs_dat.to_dict(
                                'records'), 'location', location, 'T')
                            # merge method codes
                            methods = []
                            for prd in prev_dat:
                                if 'method_codes' not in list(prd.keys()) or prd['method_codes'] == None:
                                    continue
                                for mc in prd['method_codes'].split(':'):
                                    if mc not in methods:
                                        methods.append(mc)
                            if len(methods) > 1:
                                PolRes['method_codes'] = reduce(
                                    lambda x, y: x+':'+y, methods)
                            elif len(methods) > 0:
                                PolRes['method_codes'] = methods[0]
                            else:
                                PolRes['method_codes'] = ''
                            if len(prev_dat) != 0:
                                for ndd in set(PolRes.keys()).symmetric_difference(set(prev_dat[0].keys())):
                                    dat = [
                                        x for x in prev_dat if ndd in x and x[ndd] != None]
                                    if len(dat) != 0:
                                        dat = dat[0]
                                    else:
                                        continue
                                    PolRes[ndd] = dat[ndd]

                            PmagLocs.append(PolRes)

            if len(PmagLocs) > 0:
                locs_df = DataFrame(PmagLocs)
                locs_df = locs_df.set_index('location')
                locs_df['location'] = locs_df.index
                nsdf = self.con.tables['locations'].merge_dfs(locs_df)
                if not dia.cb_location_mean_VGP.GetValue():
                    nsdf.drop([col for col in nsdf.columns if type(col) == str and col.startswith(
                        'pole') and col != 'pol_comp_name'], axis=1, inplace=True)
                nsdf = nsdf.reindex_axis(sorted(nsdf.columns), axis=1)
                self.con.tables['locations'].df = nsdf
                self.con.tables['locations'].write_magic_file(dir_path=self.WD)

        else:
            for FILE in ['pmag_samples.txt', 'pmag_sites.txt', 'pmag_results.txt']:
                self.PmagRecsOld[FILE] = []
                try:
                    meas_data, file_type = pmag.magic_read(
                        os.path.join(self.WD, FILE))
                    print(("-I- Read old magic file  %s" %
                           os.path.join(self.WD, FILE)))
                    if FILE != 'pmag_specimens.txt':
                        os.remove(os.path.join(self.WD, FILE))
                        print(("-I- Delete old magic file  %s" %
                               os.path.join(self.WD, FILE)))
                except:
                    continue

            for rec in meas_data:
                if "magic_method_codes" in list(rec.keys()):
                    if "LP-DIR" not in rec['magic_method_codes'] and "DE-" not in rec['magic_method_codes']:
                        self.PmagRecsOld[FILE].append(rec)

            print(('coord', coord, 'vgps_level', vgps_level, 'DefaultAge', DefaultAge, 'avg_directions_by_sample',
                   avg_directions_by_sample, 'avg_by_polarity', avg_by_polarity, 'use_criteria', use_criteria))
            prev_cwd = os.getcwd()
            os.chdir(self.WD)
            ipmag.specimens_results_magic(coord=coord, vgps_level=vgps_level, DefaultAge=DefaultAge,
                                          avg_directions_by_sample=avg_directions_by_sample, avg_by_polarity=avg_by_polarity, use_criteria=use_criteria)
            os.chdir(prev_cwd)

            # reads new pmag tables, and merge the old lines:
            for FILE in ['pmag_samples.txt', 'pmag_sites.txt', 'pmag_results.txt']:
                pmag_data = []
                try:
                    pmag_data, file_type = pmag.magic_read(
                        os.path.join(self.WD, FILE))
                except:
                    pass
                if FILE in list(self.PmagRecsOld.keys()):
                    for rec in self.PmagRecsOld[FILE]:
                        pmag_data.append(rec)
                if len(pmag_data) > 0:
                    pmag_data_fixed = self.merge_pmag_recs(pmag_data)
                    pmag.magic_write(os.path.join(self.WD, FILE),
                                     pmag_data_fixed, FILE.split(".")[0])
                    print(("write new interpretations in %s\n" %
                           (os.path.join(self.WD, FILE))))

            # make pmag_criteria.txt if it does not exist
            if not os.path.isfile(os.path.join(self.WD, "pmag_criteria.txt")):
                Fout = open(os.path.join(self.WD, "pmag_criteria.txt"), 'w')
                Fout.write("tab\tpmag_criteria\n")
                Fout.write("er_citation_names\tpmag_criteria_code\n")
                Fout.write("This study\tACCEPT\n")

            self.update_pmag_tables()
            self.update_selection()

        TEXT = "interpretations saved"
        self.saved_dlg(TEXT)
        self.close_warning = False

Response: Function called when the user closes the MagIC dialog. It calculates VGPs and saves them the hard drive.


Instruction:
Given the following Python 3 function, write the documentation
def update_selection(self):

        self.clear_boxes()
        # commented out to allow propogation of higher level viewing state
        self.clear_high_level_pars()

        if self.UPPER_LEVEL_SHOW != "specimens":
            self.mean_type_box.SetValue("None")

        # --------------------------
        # check if the coordinate system in the window exists (if not change to "specimen" coordinate system)
        # --------------------------

        coordinate_system = self.coordinates_box.GetValue()
        if coordinate_system == 'tilt-corrected' and \
           len(self.Data[self.s]['zijdblock_tilt']) == 0:
            self.coordinates_box.SetStringSelection('specimen')
        elif coordinate_system == 'geographic' and \
                len(self.Data[self.s]['zijdblock_geo']) == 0:
            self.coordinates_box.SetStringSelection("specimen")
        if coordinate_system != self.coordinates_box.GetValue() and self.ie_open:
            self.ie.coordinates_box.SetStringSelection(
                self.coordinates_box.GetValue())
            self.ie.update_editor()
        coordinate_system = self.coordinates_box.GetValue()
        self.COORDINATE_SYSTEM = coordinate_system

        # --------------------------
        # update treatment list
        # --------------------------

        self.update_bounds_boxes()

        # --------------------------
        # update high level boxes
        # --------------------------

        high_level = self.level_box.GetValue()
        old_string = self.level_names.GetValue()
        new_string = old_string
        if high_level == 'sample':
            if self.s in self.Data_hierarchy['sample_of_specimen']:
                new_string = self.Data_hierarchy['sample_of_specimen'][self.s]
            else:
                new_string = ''
        if high_level == 'site':
            if self.s in self.Data_hierarchy['site_of_specimen']:
                new_string = self.Data_hierarchy['site_of_specimen'][self.s]
            else:
                new_string = ''
        if high_level == 'location':
            if self.s in self.Data_hierarchy['location_of_specimen']:
                new_string = self.Data_hierarchy['location_of_specimen'][self.s]
            else:
                new_string = ''
        self.level_names.SetValue(new_string)
        if self.ie_open and new_string != old_string:
            self.ie.level_names.SetValue(new_string)
            self.ie.on_select_level_name(-1, True)

        # --------------------------
        # update PCA box
        # --------------------------

        self.update_PCA_box()

        # update warning
        self.generate_warning_text()
        self.update_warning_box()
        # update choices in the fit box
        self.update_fit_boxes()
        self.update_mean_fit_box()
        # measurements text box
        self.Add_text()
        # draw figures
        if self.current_fit:
            self.draw_figure(self.s, False)
        else:
            self.draw_figure(self.s, True)
        # update high level stats
        self.update_high_level_stats()
        # redraw interpretations
        self.update_GUI_with_new_interpretation()

Response: Update the selection of the current specimen and its high level boxes and statistics windows.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update_warning_box(self):
        self.warning_box.Clear()
        if self.warning_text == "":
            self.warning_box.AppendText("No Problems")
        else:
            self.warning_box.AppendText(self.warning_text)

Response: Updates the warning box with the current warning_text variable.


Instruction:
Create a Python 3 function to
update statistics boxes and figures with a new interpretatiom when selecting new temperature bound

Response:
def update_GUI_with_new_interpretation(self):
        """
        update statistics boxes and figures with a new interpretatiom when
        selecting new temperature bound
        """

        self.update_fit_bounds_and_statistics()
        self.draw_interpretations()
        self.calculate_high_levels_data()
        self.plot_high_levels_data()


Instruction:
Implement a Python 3 function for
updating the high level statistics in bottom left of GUI.

Response:
def update_high_level_stats(self):
        """
        updates high level statistics in bottom left of GUI.
        """
        self.clear_high_level_pars()
        dirtype = str(self.coordinates_box.GetValue())
        if dirtype == 'specimen':
            dirtype = 'DA-DIR'
        elif dirtype == 'geographic':
            dirtype = 'DA-DIR-GEO'
        elif dirtype == 'tilt-corrected':
            dirtype = 'DA-DIR-TILT'
        if str(self.level_box.GetValue()) == 'sample':
            high_level_type = 'samples'
        elif str(self.level_box.GetValue()) == 'site':
            high_level_type = 'sites'
        elif str(self.level_box.GetValue()) == 'location':
            high_level_type = 'locations'
        elif str(self.level_box.GetValue()) == 'study':
            high_level_type = 'study'
        high_level_name = str(self.level_names.GetValue())
        elements_type = self.UPPER_LEVEL_SHOW
        if high_level_name in list(self.high_level_means[high_level_type].keys()):
            mpars = []
            for mf in list(self.high_level_means[high_level_type][high_level_name].keys()):
                if mf in list(self.high_level_means[high_level_type][high_level_name].keys()) and self.mean_fit == 'All' or mf == self.mean_fit:
                    if dirtype in list(self.high_level_means[high_level_type][high_level_name][mf].keys()):
                        mpar = deepcopy(
                            self.high_level_means[high_level_type][high_level_name][mf][dirtype])
                        if 'n' in mpar and mpar['n'] == 1:
                            mpar['calculation_type'] = "Fisher:"+mf
                            mpars.append(mpar)
                        elif mpar['calculation_type'] == 'Fisher by polarity':
                            for k in list(mpar.keys()):
                                if k == 'color' or k == 'calculation_type':
                                    continue
                                mpar[k]['calculation_type'] += ':'+k+':'+mf
                                mpar[k]['color'] = mpar['color']
                                if 'K' not in mpar[k] and 'k' in mpar[k]:
                                    mpar[k]['K'] = mpar[k]['k']
                                if 'R' not in mpar[k] and 'r' in mpar[k]:
                                    mpar[k]['R'] = mpar[k]['r']
                                if 'n_lines' not in mpar[k] and 'n' in mpar[k]:
                                    mpar[k]['n_lines'] = mpar[k]['n']
                                mpars.append(mpar[k])
                        else:
                            mpar['calculation_type'] += ":"+mf
                            mpars.append(mpar)
            self.switch_stats_button.SetRange(0, len(mpars)-1)
            self.show_high_levels_pars(mpars)
            if self.ie_open:
                self.ie.switch_stats_button.SetRange(0, len(mpars)-1)


Instruction:
Can you generate the documentation for the following Python 3 function
def update_bounds_boxes(self):
        if self.s not in list(self.Data.keys()):
            self.select_specimen(list(self.Data.keys())[0])
        self.T_list = self.Data[self.s]['zijdblock_steps']
        if self.current_fit:
            self.tmin_box.SetItems(self.T_list)
            self.tmax_box.SetItems(self.T_list)
            if type(self.current_fit.tmin) == str and type(self.current_fit.tmax) == str:
                self.tmin_box.SetStringSelection(self.current_fit.tmin)
                self.tmax_box.SetStringSelection(self.current_fit.tmax)
        if self.ie_open:
            self.ie.update_bounds_boxes(self.T_list)

Response: Updates bounds boxes with current specimen and fit.


Instruction:
Explain what the following Python 3 code does
def update_PCA_box(self):
        if self.s in list(self.pmag_results_data['specimens'].keys()):

            if self.current_fit:
                tmin = self.current_fit.tmin
                tmax = self.current_fit.tmax
                calculation_type = self.current_fit.PCA_type
            else:
                calculation_type = self.PCA_type_box.GetValue()
                PCA_type = "None"

            # update calculation type windows
            if calculation_type == "DE-BFL":
                PCA_type = "line"
            elif calculation_type == "DE-BFL-A":
                PCA_type = "line-anchored"
            elif calculation_type == "DE-BFL-O":
                PCA_type = "line-with-origin"
            elif calculation_type == "DE-FM":
                PCA_type = "Fisher"
            elif calculation_type == "DE-BFP":
                PCA_type = "plane"
            else:
                print("no PCA type found setting to line")
                PCA_type = "line"
            self.PCA_type_box.SetStringSelection(PCA_type)

Response: updates PCA box with current fit s PCA type


Instruction:
How would you code a function in Python 3 to
update the fit box and mean fit box lists to match with changes in the specimen or new or removed interpretations in .

Response:
def update_fit_boxes(self, new_fit=False):
        """
        alters fit_box and mean_fit_box lists to match with changes in
        specimen or new/removed interpretations

        Parameters
        ----------
        new_fit : boolean representing if there is a new fit

        Alters
        ------
        fit_box selection, tmin_box selection, tmax_box selection,
        mean_fit_box selection, current_fit
        """
        # update the fit box
        self.update_fit_box(new_fit)
        # select new fit
        self.on_select_fit(None)
        # update the high level fits box
        self.update_mean_fit_box()


Instruction:
How would you explain what the following Python 3 function does
def update_fit_box(self, new_fit=False):
        # get new fit data
        if self.s in list(self.pmag_results_data['specimens'].keys()):
            self.fit_list = list(
                [x.name for x in self.pmag_results_data['specimens'][self.s]])
        else:
            self.fit_list = []
        # find new index to set fit_box to
        if not self.fit_list:
            new_index = 'None'
        elif new_fit:
            new_index = len(self.fit_list) - 1
        else:
            if self.fit_box.GetValue() in self.fit_list:
                new_index = self.fit_list.index(self.fit_box.GetValue())
            else:
                new_index = 'None'
        # clear old box
        self.fit_box.Clear()
        # update fit box
        self.fit_box.SetItems(self.fit_list)
        fit_index = None
        # select defaults
        if new_index == 'None':
            self.fit_box.SetStringSelection('None')
        else:
            self.fit_box.SetSelection(new_index)

Response: Update the fit_box with the new values from specimen or new


Instruction:
Write a Python 3 function for
updating the high level mean fit box and the menu for the current entry.

Response:
def update_mean_fit_box(self):
        """
        alters mean_fit_box list to match with changes in specimen or new/
        removed interpretations

        Alters
        ------
        mean_fit_box selection and choices, mean_types_box string selection
        """
        self.mean_fit_box.Clear()
        # update high level mean fit box
        fit_index = None
        if self.mean_fit in self.all_fits_list:
            fit_index = self.all_fits_list.index(self.mean_fit)
        self.all_fits_list = []
        for specimen in self.specimens:
            if specimen in self.pmag_results_data['specimens']:
                for name in [x.name for x in self.pmag_results_data['specimens'][specimen]]:
                    if name not in self.all_fits_list:
                        self.all_fits_list.append(name)
        self.mean_fit_box.SetItems(['None', 'All'] + self.all_fits_list)
        # select defaults
        if not isinstance(fit_index, type(None)):
            self.mean_fit_box.SetValue(self.all_fits_list[fit_index])
        elif self.mean_fit == 'All':
            self.mean_fit_box.SetValue('All')
        else:
            self.mean_fit_box.SetValue('None')
            self.mean_type_box.SetValue('None')
            self.clear_high_level_pars()
        self.update_toggleable_means_menu()
        if self.ie_open:
            self.ie.mean_fit_box.Clear()
            self.ie.mean_fit_box.SetItems(['None', 'All'] + self.all_fits_list)
            if fit_index:
                self.ie.mean_fit_box.SetValue(self.all_fits_list[fit_index])
            elif self.mean_fit == 'All':
                self.ie.mean_fit_box.SetValue('All')
            else:
                self.ie.mean_fit_box.SetValue('None')
                self.ie.mean_type_box.SetValue('None')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def show_high_levels_pars(self, mpars):
        FONT_WEIGHT = self.GUI_RESOLUTION+(self.GUI_RESOLUTION-1)*5
        font2 = wx.Font(12+min(1, FONT_WEIGHT), wx.SWISS,
                        wx.NORMAL, wx.NORMAL, False, self.font_type)

        if self.mean_type_box.GetValue() != "None" and self.mean_fit_box.GetValue() != "None" and mpars:

            if isinstance(mpars, list):
                i = self.switch_stats_button.GetValue()
                if i >= len(mpars):
                    print(("Cannot display statistics as mpars does not have index %d. Was given mpars %s, aborting." % (
                        i, str(mpars))))
                    return
                self.show_high_levels_pars(mpars[i])
            elif mpars["calculation_type"].startswith('Fisher'):
                if "alpha95" in list(mpars.keys()):
                    for val in ['mean_type:calculation_type', 'dec:dec', 'inc:inc', 'alpha95:alpha95', 'K:K', 'R:R', 'n_lines:n_lines', 'n_planes:n_planes']:
                        val, ind = val.split(":")
                        COMMAND = """self.%s_window.SetValue(str(mpars['%s']))""" % (
                            val, ind)
                        exec(COMMAND)

                if self.ie_open:
                    ie = self.ie
                    if "alpha95" in list(mpars.keys()):
                        for val in ['mean_type:calculation_type', 'dec:dec', 'inc:inc', 'alpha95:alpha95', 'K:K', 'R:R', 'n_lines:n_lines', 'n_planes:n_planes']:
                            val, ind = val.split(":")
                            COMMAND = """ie.%s_window.SetValue(str(mpars['%s']))""" % (
                                val, ind)
                            exec(COMMAND)

            elif mpars["calculation_type"].startswith('Fisher by polarity'):
                i = self.switch_stats_button.GetValue()
                keys = list(mpars.keys())
                keys.remove('calculation_type')
                if 'color' in keys:
                    keys.remove('color')
                keys.sort()
                name = keys[i % len(keys)]
                mpars = mpars[name]
                if type(mpars) != dict:
                    print(
                        ("error in showing high level mean, reseaved %s" % str(mpars)))
                    return
                if mpars["calculation_type"] == 'Fisher' and "alpha95" in list(mpars.keys()):
                    for val in ['mean_type:calculation_type', 'dec:dec', 'inc:inc', 'alpha95:alpha95', 'K:k', 'R:r', 'n_lines:n', 'n_planes:n_planes']:
                        val, ind = val.split(":")
                        if val == 'mean_type':
                            COMMAND = """self.%s_window.SetValue('%s')""" % (
                                val, mpars[ind] + ":" + name)
                        else:
                            COMMAND = """self.%s_window.SetValue(str(mpars['%s']))""" % (
                                val, ind)
                        exec(COMMAND)

                if self.ie_open:
                    ie = self.ie
                    if mpars["calculation_type"] == 'Fisher' and "alpha95" in list(mpars.keys()):
                        for val in ['mean_type:calculation_type', 'dec:dec', 'inc:inc', 'alpha95:alpha95', 'K:k', 'R:r', 'n_lines:n', 'n_planes:n_planes']:
                            val, ind = val.split(":")
                            if val == 'mean_type':
                                COMMAND = """ie.%s_window.SetValue('%s')""" % (
                                    val, mpars[ind] + ":" + name)
                            else:
                                COMMAND = """ie.%s_window.SetValue(str(mpars['%s']))""" % (
                                    val, ind)
                            exec(COMMAND)

        self.set_mean_stats_color()

Response: shows in the bottom left of the high level mean display area in the bottom left of the main window


Instruction:
Can you tell what is the following Python 3 function doing
def clear_boxes(self):
        self.tmin_box.Clear()
        self.tmin_box.SetStringSelection("")
        if self.current_fit:
            self.tmin_box.SetItems(self.T_list)
            self.tmin_box.SetSelection(-1)

        self.tmax_box.Clear()
        self.tmax_box.SetStringSelection("")
        if self.current_fit:
            self.tmax_box.SetItems(self.T_list)
            self.tmax_box.SetSelection(-1)

        self.fit_box.Clear()
        self.fit_box.SetStringSelection("")
        if self.s in self.pmag_results_data['specimens'] and self.pmag_results_data['specimens'][self.s]:
            self.fit_box.SetItems(
                list([x.name for x in self.pmag_results_data['specimens'][self.s]]))

        for parameter in ['dec', 'inc', 'n', 'mad', 'dang', 'alpha95']:
            COMMAND = "self.s%s_window.SetValue('')" % parameter
            exec(COMMAND)
            COMMAND = "self.s%s_window.SetBackgroundColour(wx.Colour('grey'))" % parameter
            exec(COMMAND)

Response: Clear all boxes in the current directory


Instruction:
Explain what the following Python 3 code does
def clear_high_level_pars(self):
        for val in ['mean_type', 'dec', 'inc', 'alpha95', 'K', 'R', 'n_lines', 'n_planes']:
            COMMAND = """self.%s_window.SetValue("")""" % (val)
            exec(COMMAND)
        if self.ie_open:
            for val in ['mean_type', 'dec', 'inc', 'alpha95', 'K', 'R', 'n_lines', 'n_planes']:
                COMMAND = """self.ie.%s_window.SetValue("")""" % (val)
                exec(COMMAND)
        self.set_mean_stats_color()

Response: Clears all high level pars display boxes


Instruction:
Can you generate the documentation for the following Python 3 function
def on_menu_make_MagIC_results_tables(self, event):

        # ---------------------------------------
        # save pmag_*.txt.tmp without directional data
        # ---------------------------------------
        self.on_menu_save_interpretation(None)

        # ---------------------------------------
        # dialog box to choose coordinate systems for pmag_specimens.txt
        # ---------------------------------------
        dia = demag_dialogs.magic_pmag_specimens_table_dialog(None)
        CoorTypes = []
        if self.test_mode:
            CoorTypes = ['DA-DIR']
        elif dia.ShowModal() == wx.ID_OK:  # Until the user clicks OK, show the message
            if dia.cb_spec_coor.GetValue() == True:
                CoorTypes.append('DA-DIR')
            if dia.cb_geo_coor.GetValue() == True:
                CoorTypes.append('DA-DIR-GEO')
            if dia.cb_tilt_coor.GetValue() == True:
                CoorTypes.append('DA-DIR-TILT')
        else:
            self.user_warning("MagIC tables not saved")
            print("MagIC tables not saved")
            return
        # ------------------------------

        self.PmagRecsOld = {}
        if self.data_model == 3.0:
            FILES = []
        else:
            FILES = ['pmag_specimens.txt']
        for FILE in FILES:
            self.PmagRecsOld[FILE] = []
            meas_data = []
            try:
                meas_data, file_type = pmag.magic_read(
                    os.path.join(self.WD, FILE))
                print(("-I- Read old magic file  %s\n" %
                       os.path.join(self.WD, FILE)))
                # if FILE !='pmag_specimens.txt':
                os.remove(os.path.join(self.WD, FILE))
                print(("-I- Delete old magic file  %s\n" %
                       os.path.join(self.WD, FILE)))

            except (OSError, IOError) as e:
                continue

            for rec in meas_data:
                if "magic_method_codes" in list(rec.keys()):
                    if "LP-DIR" not in rec['magic_method_codes'] and "DE-" not in rec['magic_method_codes']:
                        self.PmagRecsOld[FILE].append(rec)

        # ---------------------------------------
        # write a new pmag_specimens.txt
        # ---------------------------------------

        specimens_list = list(self.pmag_results_data['specimens'].keys())
        specimens_list.sort()
        PmagSpecs = []
        for specimen in specimens_list:
            for dirtype in CoorTypes:
                i = 0
                for fit in self.pmag_results_data['specimens'][specimen]:
                    mpars = fit.get(dirtype)
                    if not mpars:
                        mpars = self.get_PCA_parameters(
                            specimen, fit, fit.tmin, fit.tmax, dirtype, fit.PCA_type)
                        if not mpars or 'specimen_dec' not in list(mpars.keys()):
                            self.user_warning("Could not calculate interpretation for specimen %s and fit %s in coordinate system %s while exporting pmag tables, skipping" % (
                                specimen, fit.name, dirtype))
                            continue

                    PmagSpecRec = {}
                    PmagSpecRec["magic_software_packages"] = pmag.get_version(
                    ) + ': demag_gui'
                    PmagSpecRec["er_specimen_name"] = specimen
                    PmagSpecRec["er_sample_name"] = self.Data_hierarchy['sample_of_specimen'][specimen]
                    PmagSpecRec["er_site_name"] = self.Data_hierarchy['site_of_specimen'][specimen]
                    PmagSpecRec["er_location_name"] = self.Data_hierarchy['location_of_specimen'][specimen]
                    if specimen in list(self.Data_hierarchy['expedition_name_of_specimen'].keys()):
                        PmagSpecRec["er_expedition_name"] = self.Data_hierarchy['expedition_name_of_specimen'][specimen]
                    PmagSpecRec["er_citation_names"] = "This study"
                    if "magic_experiment_name" in self.Data[specimen]:
                        PmagSpecRec["magic_experiment_names"] = self.Data[specimen]["magic_experiment_name"]
                    if 'magic_instrument_codes' in list(self.Data[specimen].keys()):
                        PmagSpecRec["magic_instrument_codes"] = self.Data[specimen]['magic_instrument_codes']
                    PmagSpecRec['specimen_correction'] = 'u'
                    PmagSpecRec['specimen_direction_type'] = mpars["specimen_direction_type"]
                    PmagSpecRec['specimen_dec'] = "%.1f" % mpars["specimen_dec"]
                    PmagSpecRec['specimen_inc'] = "%.1f" % mpars["specimen_inc"]
                    PmagSpecRec['specimen_flag'] = "g"
                    if fit in self.bad_fits:
                        PmagSpecRec['specimen_flag'] = "b"

                    if "C" in fit.tmin or "C" in fit.tmax:
                        PmagSpecRec['measurement_step_unit'] = "K"
                    else:
                        PmagSpecRec['measurement_step_unit'] = "T"

                    if "C" in fit.tmin:
                        PmagSpecRec['measurement_step_min'] = "%.0f" % (
                            mpars["measurement_step_min"]+273.)
                    elif "mT" in fit.tmin:
                        PmagSpecRec['measurement_step_min'] = "%8.3e" % (
                            mpars["measurement_step_min"]*1e-3)
                    else:
                        if PmagSpecRec['measurement_step_unit'] == "K":
                            PmagSpecRec['measurement_step_min'] = "%.0f" % (
                                mpars["measurement_step_min"]+273.)
                        else:
                            PmagSpecRec['measurement_step_min'] = "%8.3e" % (
                                mpars["measurement_step_min"]*1e-3)

                    if "C" in fit.tmax:
                        PmagSpecRec['measurement_step_max'] = "%.0f" % (
                            mpars["measurement_step_max"]+273.)
                    elif "mT" in fit.tmax:
                        PmagSpecRec['measurement_step_max'] = "%8.3e" % (
                            mpars["measurement_step_max"]*1e-3)
                    else:
                        if PmagSpecRec['measurement_step_unit'] == "K":
                            PmagSpecRec['measurement_step_min'] = "%.0f" % (
                                mpars["measurement_step_min"]+273.)
                        else:
                            PmagSpecRec['measurement_step_min'] = "%8.3e" % (
                                mpars["measurement_step_min"]*1e-3)

                    PmagSpecRec['specimen_n'] = "%.0f" % mpars["specimen_n"]
                    calculation_type = mpars['calculation_type']
                    PmagSpecRec["magic_method_codes"] = self.Data[specimen]['magic_method_codes'] + \
                        ":"+calculation_type+":"+dirtype
                    PmagSpecRec["specimen_comp_n"] = str(
                        len(self.pmag_results_data["specimens"][specimen]))
                    PmagSpecRec["specimen_comp_name"] = fit.name
                    if fit in self.bad_fits:
                        PmagSpecRec["specimen_flag"] = "b"
                    else:
                        PmagSpecRec["specimen_flag"] = "g"
                    if calculation_type in ["DE-BFL", "DE-BFL-A", "DE-BFL-O"]:
                        PmagSpecRec['specimen_direction_type'] = 'l'
                        PmagSpecRec['specimen_mad'] = "%.1f" % float(
                            mpars["specimen_mad"])
                        PmagSpecRec['specimen_dang'] = "%.1f" % float(
                            mpars['specimen_dang'])
                        PmagSpecRec['specimen_alpha95'] = ""
                    elif calculation_type in ["DE-BFP"]:
                        PmagSpecRec['specimen_direction_type'] = 'p'
                        PmagSpecRec['specimen_mad'] = "%.1f" % float(
                            mpars['specimen_mad'])
                        PmagSpecRec['specimen_dang'] = ""
                        PmagSpecRec['specimen_alpha95'] = ""
                        if self.data_model == 3.0:
                            if 'bfv_dec' not in list(mpars.keys()) or \
                               'bfv_inc' not in list(mpars.keys()):
                                self.calculate_best_fit_vectors(
                                    high_level_type="sites", high_level_name=PmagSpecRec["er_site_name"], dirtype=dirtype)
                                mpars = fit.get(dirtype)
                            try:
                                PmagSpecRec['dir_bfv_dec'] = "%.1f" % mpars['bfv_dec']
                                PmagSpecRec['dir_bfv_inc'] = "%.1f" % mpars['bfv_inc']
                            except KeyError:
                                print("Error calculating BFV during export of interpretations for %s, %s, %s" % (
                                    fit.name, specimen, dirtype))
                    elif calculation_type in ["DE-FM"]:
                        PmagSpecRec['specimen_direction_type'] = 'l'
                        PmagSpecRec['specimen_mad'] = ""
                        PmagSpecRec['specimen_dang'] = ""
                        PmagSpecRec['specimen_alpha95'] = "%.1f" % float(
                            mpars['specimen_alpha95'])
                    if dirtype == 'DA-DIR-TILT':
                        PmagSpecRec['specimen_tilt_correction'] = "100"
                    elif dirtype == 'DA-DIR-GEO':
                        PmagSpecRec['specimen_tilt_correction'] = "0"
                    else:
                        PmagSpecRec['specimen_tilt_correction'] = "-1"
                    PmagSpecs.append(PmagSpecRec)
                    i += 1

        # add the 'old' lines with no "LP-DIR" in
        if 'pmag_specimens.txt' in list(self.PmagRecsOld.keys()):
            for rec in self.PmagRecsOld['pmag_specimens.txt']:
                PmagSpecs.append(rec)
        PmagSpecs_fixed = self.merge_pmag_recs(PmagSpecs)

        if len(PmagSpecs_fixed) == 0:
            self.user_warning(
                "No data to save to MagIC tables please create some interpretations before saving")
            print("No data to save, MagIC tables not written")
            return

        if self.data_model == 3.0:

            # translate demag_gui output to 3.0 DataFrame
            ndf2_5 = DataFrame(PmagSpecs_fixed)
            if 'specimen_direction_type' in ndf2_5.columns:
                # doesn't exist in new model
                del ndf2_5['specimen_direction_type']
            ndf3_0 = ndf2_5.rename(columns=map_magic.spec_magic2_2_magic3_map)
            if 'specimen' in ndf3_0.columns:
                ndf3_0 = ndf3_0.set_index("specimen")
                # replace the removed specimen column
                ndf3_0['specimen'] = ndf3_0.index
            # prefer keeping analyst_names in txt
            if 'analyst_names' in ndf3_0:
                del ndf3_0['analyst_names']

            # get current 3.0 DataFrame from contribution object
            if 'specimens' not in self.con.tables:
                cols = ndf3_0.columns
                self.con.add_empty_magic_table('specimens', col_names=cols)
            spmdf = self.con.tables['specimens']
            # remove translation collisions or deprecated terms
            for dc in ["dir_comp_name", "magic_method_codes"]:
                if dc in spmdf.df.columns:
                    del spmdf.df[dc]

            # merge previous df with new interpretations DataFrame
            # (do not include non-directional data in the merge or else it
            # will be overwritten)

            # fix index names
            spmdf.df.index.name = "specimen_name"
            ndf3_0.index.name = "specimen_name"
            # pull out directional/non-directional data
            if 'method_codes' not in spmdf.df:
                spmdf.df['method_codes'] = ''
            directional = spmdf.df['method_codes'].str.contains('LP-DIR').astype(bool)
            non_directional_df = spmdf.df[~directional]
            spmdf.df = spmdf.df[directional]
            # merge new interpretations with old specimen information
            directional_df = spmdf.merge_dfs(ndf3_0)
            # add any missing columns to non_directional_df
            for col in directional_df.columns:
                if col not in non_directional_df.columns:
                    non_directional_df[col] = ""
            # make sure columns are ordered the same so that we can concatenate
            non_directional_df.sort_index(axis='columns', inplace=True)
            directional_df.sort_index(axis='columns', inplace=True)
            # put directional/non-directional data back together
            merged = pd.concat([non_directional_df, directional_df])
            merged.sort_index(inplace=True)
            spmdf.df = merged

            # write to disk
            spmdf.write_magic_file(dir_path=self.WD)

            TEXT = "specimens interpretations are saved in specimens.txt.\nPress OK to save to samples/sites/locations/ages tables."
            self.dlg = wx.MessageDialog(
                self, caption="Other Tables", message=TEXT, style=wx.OK | wx.CANCEL)
            result = self.show_dlg(self.dlg)
            if result == wx.ID_OK:
                self.dlg.Destroy()
            else:
                self.dlg.Destroy()
                return

        else:
            pmag.magic_write(os.path.join(
                self.WD, "pmag_specimens.txt"), PmagSpecs_fixed, 'pmag_specimens')
            print(("specimen data stored in %s\n" %
                   os.path.join(self.WD, "pmag_specimens.txt")))

            TEXT = "specimens interpretations are saved in pmag_specimens.txt.\nPress OK for pmag_samples/pmag_sites/pmag_results tables."
            dlg = wx.MessageDialog(
                self, caption="Other Pmag Tables", message=TEXT, style=wx.OK | wx.CANCEL)
            result = self.show_dlg(dlg)
            if result == wx.ID_OK:
                dlg.Destroy()
            else:
                dlg.Destroy()
                return

        # --------------------------------

        dia = demag_dialogs.magic_pmag_tables_dialog(
            None, self.WD, self.Data, self.Data_info)

        if self.show_dlg(dia) == wx.ID_OK:  # Until the user clicks OK, show the message
            self.On_close_MagIC_dialog(dia)

Response: Creates or updates MagIC tables for later contribution to the MagIC results table.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def on_menu_import_meas_file(self, event):
        # use new measurement file and corresponding WD
        meas_file = self.choose_meas_file()
        WD = os.path.split(meas_file)[0]
        self.WD = WD
        self.magic_file = meas_file
        # reset backend with new files
        self.reset_backend()

Response: Open measurement file reset self. magic_file and self. WD reset everything.


Instruction:
Can you write a function in Python 3 where it
reads pmag_criteria. txt file and open changecriteria dialog

Response:
def on_menu_criteria_file(self, event):
        """
        read pmag_criteria.txt file
        and open changecriteria dialog
        """
        if self.data_model == 3:
            default_file = "criteria.txt"
        else:
            default_file = "pmag_criteria.txt"
        read_sucsess = False
        dlg = wx.FileDialog(
            self, message="choose pmag criteria file",
            defaultDir=self.WD,
            defaultFile=default_file,
            style=wx.FD_OPEN | wx.FD_CHANGE_DIR
        )
        if self.show_dlg(dlg) == wx.ID_OK:
            criteria_file = dlg.GetPath()
            print(("-I- Read new criteria file: %s" % criteria_file))

            # check if this is a valid pmag_criteria file
            try:
                mag_meas_data, file_type = pmag.magic_read(criteria_file)
            except:
                dlg = wx.MessageDialog(
                    self, caption="Error", message="not a valid pmag_criteria file", style=wx.OK)
                result = self.show_dlg(dlg)
                if result == wx.ID_OK:
                    dlg.Destroy()
                dlg.Destroy()
                return

            # initialize criteria
            self.acceptance_criteria = self.read_criteria_file(criteria_file)
            read_sucsess = True

        dlg.Destroy()
        if read_sucsess:
            self.on_menu_change_criteria(None)


Instruction:
Create a Python 3 function for
righting click the zijderveld on the right of the iTunes instance

Response:
def right_click_zijderveld(self, event):
        """
        toggles between zoom and pan effects for the zijderveld on right
        click

        Parameters
        ----------
        event : the wx.MouseEvent that triggered the call of this function

        Alters
        ------
        zijderveld_setting, toolbar1 setting
        """
        if event.LeftIsDown() or event.ButtonDClick():
            return
        elif self.zijderveld_setting == "Zoom":
            self.zijderveld_setting = "Pan"
            try:
                self.toolbar1.pan('off')
            except TypeError:
                pass
        elif self.zijderveld_setting == "Pan":
            self.zijderveld_setting = "Zoom"
            try:
                self.toolbar1.zoom()
            except TypeError:
                pass


Instruction:
Write a Python 3 script to
handle mouse cursor events for the zijd area

Response:
def on_change_zijd_mouse_cursor(self, event):
        """
        If mouse is over data point making it selectable change the shape of
        the cursor

        Parameters
        ----------
        event : the wx Mouseevent for that click
        """
        if not array(self.CART_rot).any():
            return
        pos = event.GetPosition()
        width, height = self.canvas1.get_width_height()
        pos[1] = height - pos[1]
        xpick_data, ypick_data = pos
        xdata_org = list(self.CART_rot[:, 0]) + list(self.CART_rot[:, 0])
        ydata_org = list(-1*self.CART_rot[:, 1]) + list(-1*self.CART_rot[:, 2])
        data_corrected = self.zijplot.transData.transform(
            vstack([xdata_org, ydata_org]).T)
        xdata, ydata = data_corrected.T
        xdata = list(map(float, xdata))
        ydata = list(map(float, ydata))
        e = 4e0

        if self.zijderveld_setting == "Zoom":
            self.canvas1.SetCursor(wx.Cursor(wx.CURSOR_CROSS))
        else:
            self.canvas1.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
        for i, (x, y) in enumerate(zip(xdata, ydata)):
            if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
                self.canvas1.SetCursor(wx.Cursor(wx.CURSOR_HAND))
                break
        event.Skip()


Instruction:
Write a Python 3 script for
selecting the nearest interpretation to the mouse position on double click.

Response:
def on_zijd_select(self, event):
        """
        Get mouse position on double click find the nearest interpretation
        to the mouse
        position then select that interpretation

        Parameters
        ----------
        event : the wx Mouseevent for that click

        Alters
        ------
        current_fit
        """
        if not array(self.CART_rot_good).any():
            return
        pos = event.GetPosition()
        width, height = self.canvas1.get_width_height()
        pos[1] = height - pos[1]
        xpick_data, ypick_data = pos
        xdata_org = list(
            self.CART_rot_good[:, 0]) + list(self.CART_rot_good[:, 0])
        ydata_org = list(-1*self.CART_rot_good[:, 1]) + \
            list(-1*self.CART_rot_good[:, 2])
        data_corrected = self.zijplot.transData.transform(
            vstack([xdata_org, ydata_org]).T)
        xdata, ydata = data_corrected.T
        xdata = list(map(float, xdata))
        ydata = list(map(float, ydata))
        e = 4.0

        index = None
        for i, (x, y) in enumerate(zip(xdata, ydata)):
            if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
                index = i
                break
        if index != None:
            steps = self.Data[self.s]['zijdblock_steps']
            bad_count = self.Data[self.s]['measurement_flag'][:index].count(
                'b')
            if index > len(steps):
                bad_count *= 2
            if not self.current_fit:
                self.on_btn_add_fit(event)
            self.select_bounds_in_logger((index+bad_count) % len(steps))


Instruction:
Write a Python 3 function for
marking the interpretation in the current interpretation for that mouse position and mark that interpretation bad or good

Response:
def on_zijd_mark(self, event):
        """
        Get mouse position on double right click find the interpretation in
        range of mouse
        position then mark that interpretation bad or good

        Parameters
        ----------
        event : the wx Mouseevent for that click

        Alters
        ------
        current_fit
        """
        if not array(self.CART_rot).any():
            return
        pos = event.GetPosition()
        width, height = self.canvas1.get_width_height()
        pos[1] = height - pos[1]
        xpick_data, ypick_data = pos
        xdata_org = list(self.CART_rot[:, 0]) + list(self.CART_rot[:, 0])
        ydata_org = list(-1*self.CART_rot[:, 1]) + list(-1*self.CART_rot[:, 2])
        data_corrected = self.zijplot.transData.transform(
            vstack([xdata_org, ydata_org]).T)
        xdata, ydata = data_corrected.T
        xdata = list(map(float, xdata))
        ydata = list(map(float, ydata))
        e = 4e0

        index = None
        for i, (x, y) in enumerate(zip(xdata, ydata)):
            if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
                index = i
                break
        if index != None:
            steps = self.Data[self.s]['zijdblock']
            if self.Data[self.s]['measurement_flag'][index % len(steps)] == "g":
                self.mark_meas_bad(index % len(steps))
            else:
                self.mark_meas_good(index % len(steps))
            pmag.magic_write(os.path.join(
                self.WD, "magic_measurements.txt"), self.mag_meas_data, "magic_measurements")

            self.recalculate_current_specimen_interpreatations()

            if self.ie_open:
                self.ie.update_current_fit_data()
            self.calculate_high_levels_data()
            self.update_selection()


Instruction:
Can you generate the documentation for the following Python 3 function
def right_click_specimen_equalarea(self, event):
        if event.LeftIsDown() or event.ButtonDClick():
            return
        elif self.specimen_EA_setting == "Zoom":
            self.specimen_EA_setting = "Pan"
            try:
                self.toolbar2.pan('off')
            except TypeError:
                pass
        elif self.specimen_EA_setting == "Pan":
            self.specimen_EA_setting = "Zoom"
            try:
                self.toolbar2.zoom()
            except TypeError:
                pass

Response: right click specimen equal area on the specimen equal area


Instruction:
Explain what the following Python 3 code does
def on_change_specimen_mouse_cursor(self, event):
        if not self.specimen_EA_xdata or not self.specimen_EA_ydata:
            return
        pos = event.GetPosition()
        width, height = self.canvas2.get_width_height()
        pos[1] = height - pos[1]
        xpick_data, ypick_data = pos
        xdata_org = self.specimen_EA_xdata
        ydata_org = self.specimen_EA_ydata
        data_corrected = self.specimen_eqarea.transData.transform(
            vstack([xdata_org, ydata_org]).T)
        xdata, ydata = data_corrected.T
        xdata = list(map(float, xdata))
        ydata = list(map(float, ydata))
        e = 4e0

        if self.specimen_EA_setting == "Zoom":
            self.canvas2.SetCursor(wx.Cursor(wx.CURSOR_CROSS))
        else:
            self.canvas2.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
        for i, (x, y) in enumerate(zip(xdata, ydata)):
            if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
                self.canvas2.SetCursor(wx.Cursor(wx.CURSOR_HAND))
                break
        event.Skip()

Response: Handles mouse cursor events for specimen related data points


Instruction:
Can you create a Python 3 function that
selects the nearest interpretation to the mouse position on double click and draw the figure.

Response:
def on_equalarea_specimen_select(self, event):
        """
        Get mouse position on double click find the nearest interpretation
        to the mouse
        position then select that interpretation

        Parameters
        ----------
        event : the wx Mouseevent for that click

        Alters
        ------
        current_fit
        """
        if not self.specimen_EA_xdata or not self.specimen_EA_ydata:
            return
        pos = event.GetPosition()
        width, height = self.canvas2.get_width_height()
        pos[1] = height - pos[1]
        xpick_data, ypick_data = pos
        xdata_org = self.specimen_EA_xdata
        ydata_org = self.specimen_EA_ydata
        data_corrected = self.specimen_eqarea.transData.transform(
            vstack([xdata_org, ydata_org]).T)
        xdata, ydata = data_corrected.T
        xdata = list(map(float, xdata))
        ydata = list(map(float, ydata))
        e = 4e0

        index = None
        for i, (x, y) in enumerate(zip(xdata, ydata)):
            if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
                index = i
                break
        if index != None:
            self.fit_box.SetSelection(index)
            self.draw_figure(self.s, True)
            self.on_select_fit(event)


Instruction:
Given the following Python 3 function, write the documentation
def right_click_high_equalarea(self, event):
        if event.LeftIsDown():
            return
        elif self.high_EA_setting == "Zoom":
            self.high_EA_setting = "Pan"
            try:
                self.toolbar4.pan('off')
            except TypeError:
                pass
        elif self.high_EA_setting == "Pan":
            self.high_EA_setting = "Zoom"
            try:
                self.toolbar4.zoom()
            except TypeError:
                pass

Response: Right click the high equal area on the event object event.


Instruction:
Write a Python 3 function that can
change the shape of the mouse cursor

Response:
def on_change_high_mouse_cursor(self, event):
        """
        If mouse is over data point making it selectable change the shape of
        the cursor

        Parameters
        ----------
        event : the wx Mouseevent for that click
        """
        if self.ie_open and self.ie.show_box.GetValue() != "specimens":
            return
        pos = event.GetPosition()
        width, height = self.canvas4.get_width_height()
        pos[1] = height - pos[1]
        xpick_data, ypick_data = pos
        xdata_org = self.high_EA_xdata
        ydata_org = self.high_EA_ydata
        data_corrected = self.high_level_eqarea.transData.transform(
            vstack([xdata_org, ydata_org]).T)
        xdata, ydata = data_corrected.T
        xdata = list(map(float, xdata))
        ydata = list(map(float, ydata))
        e = 4e0

        if self.high_EA_setting == "Zoom":
            self.canvas4.SetCursor(wx.Cursor(wx.CURSOR_CROSS))
        else:
            self.canvas4.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
        if not self.high_EA_xdata or not self.high_EA_ydata:
            return
        for i, (x, y) in enumerate(zip(xdata, ydata)):
            if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
                self.canvas4.SetCursor(wx.Cursor(wx.CURSOR_HAND))
                break
        event.Skip()


Instruction:
Write a Python 3 function for
selecting interpretation for high level interpretation

Response:
def on_equalarea_high_select(self, event, fig=None, canvas=None):
        """
        Get mouse position on double click find the nearest interpretation
        to the mouse position then select that interpretation

        Parameters
        ----------
        event : the wx Mouseevent for that click

        Alters
        ------
        current_fit, s, mean_fit, fit_box selection, mean_fit_box selection,
        specimens_box selection, tmin_box selection, tmax_box selection
        """
        if self.ie_open and self.ie.show_box.GetValue() != "specimens":
            return
        if not self.high_EA_xdata or not self.high_EA_ydata:
            return
        if fig == None:
            fig = self.high_level_eqarea
        if canvas == None:
            canvas = self.canvas4
        pos = event.GetPosition()
        width, height = canvas.get_width_height()
        pos[1] = height - pos[1]
        xpick_data, ypick_data = pos
        xdata_org = self.high_EA_xdata
        ydata_org = self.high_EA_ydata
        data_corrected = fig.transData.transform(
            vstack([xdata_org, ydata_org]).T)
        xdata, ydata = data_corrected.T
        xdata = list(map(float, xdata))
        ydata = list(map(float, ydata))
        e = 4e0

        index = None
        for i, (x, y) in enumerate(zip(xdata, ydata)):
            if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
                index = i
                break
        if index != None:
            disp_fit_name = self.mean_fit_box.GetValue()

            if self.level_box.GetValue() == 'sample':
                high_level_type = 'samples'
            if self.level_box.GetValue() == 'site':
                high_level_type = 'sites'
            if self.level_box.GetValue() == 'location':
                high_level_type = 'locations'
            if self.level_box.GetValue() == 'study':
                high_level_type = 'study'

            high_level_name = str(self.level_names.GetValue())
            calculation_type = str(self.mean_type_box.GetValue())
            elements_type = self.UPPER_LEVEL_SHOW

            elements_list = self.Data_hierarchy[high_level_type][high_level_name][elements_type]

            new_fit_index = 0
            for i, specimen in enumerate(elements_list):
                if disp_fit_name == "All" and \
                   specimen in self.pmag_results_data[elements_type]:
                    l = 0
                    for fit in self.pmag_results_data[elements_type][specimen]:
                        l += 1
                else:
                    try:
                        disp_fit_index = map(
                            lambda x: x.name, self.pmag_results_data[elements_type][specimen]).index(disp_fit_name)
                        if self.pmag_results_data[elements_type][specimen][disp_fit_index] in self.bad_fits:
                            l = 0
                        else:
                            l = 1
                    except IndexError:
                        l = 0
                    except KeyError:
                        l = 0
                    except ValueError:
                        l = 0

                if index < l:
                    self.specimens_box.SetStringSelection(specimen)
                    self.select_specimen(specimen)
                    self.draw_figure(specimen, False)
                    if disp_fit_name == "All":
                        new_fit_index = index
                    else:
                        new_fit_index = disp_fit_index
                    break

                index -= l
            self.update_fit_box()
            self.fit_box.SetSelection(new_fit_index)
            self.on_select_fit(event)
            if disp_fit_name != "All":
                self.mean_fit = self.current_fit.name
                self.mean_fit_box.SetSelection(2+new_fit_index)
                self.update_selection()
            else:
                self.Add_text()
            if self.ie_open:
                self.ie.change_selected(self.current_fit)


Instruction:
Write a Python 3 script to
add measurement data lines to the text window.

Response:
def Add_text(self):
        """
        Add measurement data lines to the text window.
        """
        self.selected_meas = []
        if self.COORDINATE_SYSTEM == 'geographic':
            zijdblock = self.Data[self.s]['zijdblock_geo']
        elif self.COORDINATE_SYSTEM == 'tilt-corrected':
            zijdblock = self.Data[self.s]['zijdblock_tilt']
        else:
            zijdblock = self.Data[self.s]['zijdblock']

        tmin_index, tmax_index = -1, -1
        if self.current_fit and self.current_fit.tmin and self.current_fit.tmax:
            tmin_index, tmax_index = self.get_indices(self.current_fit)

        TEXT = ""
        self.logger.DeleteAllItems()
        for i in range(len(zijdblock)):
            lab_treatment = self.Data[self.s]['zijdblock_lab_treatments'][i]
            Step = ""
            methods = lab_treatment.split('-')
            if "NO" in methods:
                Step = "N"
            elif "AF" in methods:
                Step = "AF"
            elif "ARM" in methods:
                Step = "ARM"
            elif "IRM" in methods:
                Step = "IRM"
            elif "T" in methods:
                Step = "T"
            elif "LT" in methods:
                Step = "LT"
            Tr = zijdblock[i][0]
            Dec = zijdblock[i][1]
            Inc = zijdblock[i][2]
            Int = zijdblock[i][3]
            csd = self.Data[self.s]['csds'][i]
            self.logger.InsertItem(i, "%i" % i)
            self.logger.SetItem(i, 1, Step)
            self.logger.SetItem(i, 2, "%.1f" % Tr)
            self.logger.SetItem(i, 3, "%.1f" % Dec)
            self.logger.SetItem(i, 4, "%.1f" % Inc)
            self.logger.SetItem(i, 5, "%.2e" % Int)
            self.logger.SetItem(i, 6, csd)
            self.logger.SetItemBackgroundColour(i, "WHITE")
            if i >= tmin_index and i <= tmax_index:
                self.logger.SetItemBackgroundColour(i, "LIGHT BLUE")
            if self.Data[self.s]['measurement_flag'][i] == 'b':
                self.logger.SetItemBackgroundColour(i, "red")


Instruction:
Can you create a Python 3 function that
selects the index in the logger based on what the other bound is and sets it in the logger.

Response:
def select_bounds_in_logger(self, index):
        """
        sets index as the upper or lower bound of a fit based on what the
        other bound is and selects it in the logger. Requires 2 calls to
        completely update a interpretation. NOTE: Requires an interpretation
        to exist before it is called.

        Parameters
        ----------
        index : index of the step to select in the logger
        """
        tmin_index, tmax_index = "", ""
        if str(self.tmin_box.GetValue()) != "":
            tmin_index = self.tmin_box.GetSelection()
        if str(self.tmax_box.GetValue()) != "":
            tmax_index = self.tmax_box.GetSelection()

        if self.list_bound_loc != 0:
            if self.list_bound_loc == 1:
                if index < tmin_index:
                    self.tmin_box.SetSelection(index)
                    self.tmax_box.SetSelection(tmin_index)
                elif index == tmin_index:
                    pass
                else:
                    self.tmax_box.SetSelection(index)
            else:
                if index > tmax_index:
                    self.tmin_box.SetSelection(tmax_index)
                    self.tmax_box.SetSelection(index)
                elif index == tmax_index:
                    pass
                else:
                    self.tmin_box.SetSelection(index)
            self.list_bound_loc = 0
        else:
            if index < tmax_index:
                self.tmin_box.SetSelection(index)
                self.list_bound_loc = 1
            else:
                self.tmax_box.SetSelection(index)
                self.list_bound_loc = 2

#        if tmin_index=="" or index<tmin_index:
#            if tmax_index=="" and tmin_index!="":
#                self.tmax_box.SetSelection(tmin_index)
#            self.tmin_box.SetSelection(index)
#        elif tmax_index=="" or index>tmax_index:
#            self.tmax_box.SetSelection(index)
#        else:
#            self.tmin_box.SetSelection(index)
#            self.tmax_box.SetValue("")

        self.logger.Select(index, on=0)
        self.get_new_PCA_parameters(-1)