Instruction:
Can you generate the documentation for the following Python 3 function
def plot_selected_meas(self):
        self.close_warning = True
        # set hex colors for cover and size of selected meas marker
        blue_cover = "#9999FF"
        red_cover = "#FF9999"
        eqarea_outline = "#FF0000"
        MS_selected = 40

        # remove old selected points
        for a in self.selected_meas_artists:
            if a in self.zijplot.collections:
                self.zijplot.collections.remove(a)
            if a in self.specimen_eqarea.collections:
                self.specimen_eqarea.collections.remove(a)
            if a in self.mplot.collections:
                self.mplot.collections.remove(a)
            if a in self.mplot_af.collections:
                self.mplot_af.collections.remove(a)

        # do zijderveld plot
        self.selected_meas_artists = []
        x, y, z = self.CART_rot[self.selected_meas,
                                0], self.CART_rot[self.selected_meas, 1], self.CART_rot[self.selected_meas, 2]
        self.selected_meas_artists.append(self.zijplot.scatter(
            x, -1*y, c=red_cover, marker='o', s=MS_selected, zorder=2))
        self.selected_meas_artists.append(self.zijplot.scatter(
            x, -1*z, c=blue_cover, marker='s', s=MS_selected, zorder=2))

        # do down data for eqarea
        x_eq = array([row[0] for i, row in enumerate(self.zij_norm)
                      if i in self.selected_meas and row[2] > 0])
        y_eq = array([row[1] for i, row in enumerate(self.zij_norm)
                      if i in self.selected_meas and row[2] > 0])
        z_eq = abs(array([row[2] for i, row in enumerate(
            self.zij_norm) if i in self.selected_meas and row[2] > 0]))
        if len(x_eq) > 0:
            # from Collinson 1983
            R = array(sqrt(1-z_eq)/sqrt(x_eq**2+y_eq**2))
            eqarea_data_x = y_eq*R
            eqarea_data_y = x_eq*R
            self.selected_meas_artists.append(self.specimen_eqarea.scatter([eqarea_data_x], [
                                              eqarea_data_y], marker='o', edgecolor=eqarea_outline, facecolor="#808080", s=15*self.GUI_RESOLUTION, lw=1, clip_on=False))

        # do up data for eqarea
        x_eq = array([row[0] for i, row in enumerate(self.zij_norm)
                      if i in self.selected_meas and row[2] < 0])
        y_eq = array([row[1] for i, row in enumerate(self.zij_norm)
                      if i in self.selected_meas and row[2] < 0])
        z_eq = abs(array([row[2] for i, row in enumerate(
            self.zij_norm) if i in self.selected_meas and row[2] < 0]))
        if len(x_eq) > 0:
            # from Collinson 1983
            R = array(sqrt(1-z_eq)/sqrt(x_eq**2+y_eq**2))
            eqarea_data_x = y_eq*R
            eqarea_data_y = x_eq*R
            self.selected_meas_artists.append(self.specimen_eqarea.scatter([eqarea_data_x], [
                                              eqarea_data_y], marker='o', edgecolor=eqarea_outline, facecolor="#FFFFFF", s=15*self.GUI_RESOLUTION, lw=1, clip_on=False))

        # do M/M0 plot
        steps = self.Data[self.s]['zijdblock_steps']
        flags = self.Data[self.s]['measurement_flag']
        selected_af_meas = [
            i for i in self.selected_meas if "T" in steps[i] or steps[i] == "0" and flags[i] != "b"]
        selected_T_meas = [i for i in self.selected_meas if "C" in steps[i]
                           or steps[i] == "0" and flags[i] != "b"]
        data = array(self.Data[self.s]['zijdblock'])
        af_x = array(list(map(float, data[selected_af_meas, 0])))
        af_y = array(
            list(map(float, data[selected_af_meas, 3])))/float(data[0, 3])
        T_x = array(list(map(float, data[selected_T_meas, 0])))
        T_y = array(
            list(map(float, data[selected_T_meas, 3])))/float(data[0, 3])

        xmin, xmax = self.mplot.get_xlim()
        ymin, ymax = self.mplot.get_ylim()
        if T_x.astype(float).any() or T_y.astype(float).any():
            self.selected_meas_artists.append(self.mplot.scatter(
                T_x, T_y, facecolor=red_cover, edgecolor="#000000", marker='o', s=30, lw=1, clip_on=False, zorder=3))
        self.mplot.set_xlim([xmin, xmax])
        self.mplot.set_ylim([ymin, ymax])

        xmin, xmax = self.mplot_af.get_xlim()
        ymin, ymax = self.mplot_af.get_ylim()
        if af_x.astype(float).any() or af_y.astype(float).any():
            self.selected_meas_artists.append(self.mplot_af.scatter(
                af_x, af_y, facecolor=blue_cover, edgecolor="#000000", marker='o', s=30, lw=1, clip_on=False, zorder=3))
        self.mplot_af.set_xlim([xmin, xmax])
        self.mplot_af.set_ylim([ymin, ymax])

        self.canvas1.draw()
        self.canvas2.draw()
        self.canvas3.draw()

Response: Goes through all measurements selected in logger and draws darker and eqarea plots to display which measurements have been selected in specimen plots.


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

        problems = {}

        if self.s in self.pmag_results_data['specimens'] and \
                self.pmag_results_data['specimens'][self.s] != []:
            #            self.zijplot.collections=[] # delete fit points
            self.specimen_EA_xdata = []  # clear saved x positions on specimen equal area
            self.specimen_EA_ydata = []  # clear saved y positions on specimen equal area

        # check to see if there's a results log or not
        if not (self.s in list(self.pmag_results_data['specimens'].keys())):
            self.pmag_results_data['specimens'][self.s] = []

        for fit in self.pmag_results_data['specimens'][self.s]:

            pars = fit.get(self.COORDINATE_SYSTEM)

            if (fit.tmin == None or fit.tmax == None or not pars):
                if 'no bounds' not in list(problems.keys()):
                    problems['no bounds'] = []
                problems['no bounds'].append(fit)
                continue

            for line in fit.lines:
                if line in self.zijplot.lines:
                    self.zijplot.lines.remove(line)
            for point in fit.points:
                if point in self.zijplot.collections:
                    self.zijplot.collections.remove(point)

            PCA_type = fit.PCA_type

            tmin_index, tmax_index = self.get_indices(fit)

            marker_shape = 'o'
            SIZE = 20
            if fit == self.current_fit:
                marker_shape = 'D'
            if pars['calculation_type'] == "DE-BFP":
                marker_shape = 's'
                if "bfv" in self.plane_display_box.GetValue():
                    marker_shape = '>'
            if fit in self.bad_fits:
                marker_shape = (4, 1, 0)
                SIZE = 30*self.GUI_RESOLUTION

            # Zijderveld plot

            ymin, ymax = self.zijplot.get_ylim()
            xmin, xmax = self.zijplot.get_xlim()

            for i in range(1):
                if (len(self.CART_rot[:, i]) <= tmin_index or
                        len(self.CART_rot[:, i]) <= tmax_index):
                    self.Add_text()

            self.zijplot.scatter([self.CART_rot[:, 0][tmin_index], self.CART_rot[:, 0][tmax_index]], [-1 * self.CART_rot[:, 1][tmin_index], -
                                                                                1 * self.CART_rot[:, 1][tmax_index]], marker=marker_shape, s=40, facecolor=fit.color, edgecolor='k', zorder=100, clip_on=False)
            self.zijplot.scatter([self.CART_rot[:, 0][tmin_index], self.CART_rot[:, 0][tmax_index]], [-1 * self.CART_rot[:, 2][tmin_index], -
                                                                                1 * self.CART_rot[:, 2][tmax_index]], marker=marker_shape, s=40, facecolor=fit.color, edgecolor='k', zorder=100, clip_on=False)
            fit.points[0] = self.zijplot.collections[-1]
            fit.points[1] = self.zijplot.collections[-2]

            if pars['calculation_type'] in ['DE-BFL', 'DE-BFL-A', 'DE-BFL-O']:

                # rotated zijderveld
                if self.COORDINATE_SYSTEM == 'geographic' and len(self.Data[self.s]['zdata_geo']) > 0:
                    first_data = self.Data[self.s]['zdata_geo'][0]
                elif self.COORDINATE_SYSTEM == 'tilt-corrected' and len(self.Data[self.s]['zdata_tilt']) > 0:
                    first_data = self.Data[self.s]['zdata_tilt'][0]
                else:
                    first_data = self.Data[self.s]['zdata'][0]
                    if self.COORDINATE_SYSTEM != 'specimen':
                        self.on_menu_change_speci_coord(-1)
                        pars = fit.get(self.COORDINATE_SYSTEM)

                if self.ORTHO_PLOT_TYPE == 'N-S':
                    rotation_declination = 0.
                elif self.ORTHO_PLOT_TYPE == 'E-W':
                    rotation_declination = 90.
                elif self.ORTHO_PLOT_TYPE == 'PCA_dec':
                    if 'specimen_dec' in list(pars.keys()) and type(pars['specimen_dec']) != str:
                        rotation_declination = pars['specimen_dec']
                    else:
                        rotation_declination = pmag.cart2dir(first_data)[0]
                else:  # Zijderveld
                    rotation_declination = pmag.cart2dir(first_data)[0]

                PCA_dir = [pars['specimen_dec'], pars['specimen_inc'], 1]
                PCA_dir_rotated = [PCA_dir[0] -
                                   rotation_declination, PCA_dir[1], 1]
                PCA_CART_rotated = pmag.dir2cart(PCA_dir_rotated)

                slop_xy_PCA = -1*PCA_CART_rotated[1]/PCA_CART_rotated[0]
                slop_xz_PCA = -1*PCA_CART_rotated[2]/PCA_CART_rotated[0]

                # Center of mass rotated for plotting
                CM_x = mean(self.CART_rot_good[:, 0][tmin_index:tmax_index+1])
                CM_y = mean(self.CART_rot_good[:, 1][tmin_index:tmax_index+1])
                CM_z = mean(self.CART_rot_good[:, 2][tmin_index:tmax_index+1])

                # intercpet from the center of mass
                intercept_xy_PCA = -1*CM_y - slop_xy_PCA*CM_x
                intercept_xz_PCA = -1*CM_z - slop_xz_PCA*CM_x

                xx = array([self.CART_rot[:, 0][tmax_index],
                            self.CART_rot[:, 0][tmin_index]])
                yy = slop_xy_PCA*xx+intercept_xy_PCA
                zz = slop_xz_PCA*xx+intercept_xz_PCA

                if (pars['calculation_type'] in ['DE-BFL-A']):  # CHECK
                    xx = [0.] + xx
                    yy = [0.] + yy
                    zz = [0.] + zz

                self.zijplot.plot(xx, yy, '-', color=fit.color,
                                  lw=3, alpha=0.5, zorder=0)
                self.zijplot.plot(xx, zz, '-', color=fit.color,
                                  lw=3, alpha=0.5, zorder=0)

                fit.lines[0] = self.zijplot.lines[-2]
                fit.lines[1] = self.zijplot.lines[-1]

            # Equal Area plot
            self.toolbar2.home()

            # delete old interpretation data
            for d in fit.eqarea_data:
                if d in self.specimen_eqarea.lines:
                    self.specimen_eqarea.lines.remove(d)
                if d in self.specimen_eqarea.collections:
                    self.specimen_eqarea.collections.remove(d)

            if pars['calculation_type'] == 'DE-BFP' and \
               self.plane_display_box.GetValue() != "poles":

                # draw a best-fit plane
                ymin, ymax = self.specimen_eqarea.get_ylim()
                xmin, xmax = self.specimen_eqarea.get_xlim()

                D_c, I_c = pmag.circ(
                    pars["specimen_dec"], pars["specimen_inc"], 90)
                X_c_up, Y_c_up = [], []
                X_c_d, Y_c_d = [], []
                for k in range(len(D_c)):
                    XY = pmag.dimap(D_c[k], I_c[k])
                    if I_c[k] < 0:
                        X_c_up.append(XY[0])
                        Y_c_up.append(XY[1])
                    if I_c[k] > 0:
                        X_c_d.append(XY[0])
                        Y_c_d.append(XY[1])

                if self.plane_display_box.GetValue() == "u. hemisphere" or \
                   self.plane_display_box.GetValue() == "whole plane" or \
                   "wp" in self.plane_display_box.GetValue():
                    self.specimen_eqarea.plot(X_c_d, Y_c_d, 'b')
                if self.plane_display_box.GetValue() == "l. hemisphere" or \
                   self.plane_display_box.GetValue() == "whole plane" or \
                   "wp" in self.plane_display_box.GetValue():
                    self.specimen_eqarea.plot(X_c_up, Y_c_up, 'c')
                eqarea_x = XY[0]
                eqarea_y = XY[1]
                z = 1
                fit.eqarea_data[0] = self.specimen_eqarea.lines[-1]
                fit.eqarea_data[1] = self.specimen_eqarea.lines[-2]

                if "bfv" in self.plane_display_box.GetValue():
                    if 'bfv_dec' not in list(pars.keys()) or 'bfv_inc' not in list(pars.keys()):
                        self.calculate_best_fit_vectors()
                        pars = fit.get(self.COORDINATE_SYSTEM)
                    try:
                        CART = pmag.dir2cart(
                            [pars['bfv_dec'], pars['bfv_inc'], 1])
                        x = CART[0]
                        y = CART[1]
                        z = CART[2]
                        R = array(sqrt(1-abs(z))/sqrt(x**2+y**2))
                        eqarea_x = y*R
                        eqarea_y = x*R
                    except KeyError:
                        print(("specimen %s fit %s is marked bad or there was an error calculating bfv pole will be displayed instead" % (
                            element, fit.name)))

            else:
                CART = pmag.dir2cart(
                    [pars['specimen_dec'], pars['specimen_inc'], 1])
                x = CART[0]
                y = CART[1]
                z = CART[2]
                R = array(sqrt(1-abs(z))/sqrt(x**2+y**2))
                eqarea_x = y*R
                eqarea_y = x*R

            self.specimen_EA_xdata.append(eqarea_x)
            self.specimen_EA_ydata.append(eqarea_y)
            if z > 0:
                FC = fit.color
                EC = '0.1'
            else:
                FC = (1, 1, 1)
                EC = fit.color
            self.specimen_eqarea.scatter([eqarea_x], [
                                         eqarea_y], marker=marker_shape, edgecolor=EC, facecolor=FC, s=SIZE, lw=1, clip_on=False)
            fit.eqarea_data[0] = self.specimen_eqarea.collections[-1]

            # M/M0 plot (only if C or mT - not both)
            for d in fit.mm0_data:
                if d in self.mplot.collections:
                    self.mplot.collections.remove(d)
                elif d in self.mplot_af.collections:
                    self.mplot_af.collections.remove(d)
            temp_data_exists = any(
                ['C' in step for step in self.Data[self.s]['zijdblock_steps']])
            af_data_exists = any(
                ['T' in step for step in self.Data[self.s]['zijdblock_steps']])
            if "C" in fit.tmin and temp_data_exists:
                tmin_ax = self.mplot
            elif af_data_exists:
                tmin_ax = self.mplot_af
            else:
                tmin_ax = self.mplot
            if "C" in fit.tmax and temp_data_exists:
                tmax_ax = self.mplot
            elif af_data_exists:
                tmax_ax = self.mplot_af
            else:
                tmax_ax = self.mplot
            tmin_ymin, tmin_ymax = tmin_ax.get_ylim()
            tmin_xmin, tmin_xmax = tmin_ax.get_xlim()
            tmax_ymin, tmax_ymax = tmax_ax.get_ylim()
            tmax_xmin, tmax_xmax = tmax_ax.get_xlim()
            fit.mm0_data[0] = tmin_ax.scatter([self.Data[self.s]['zijdblock'][tmin_index][0]], [self.Data[self.s]['zijdblock'][tmin_index][3] /
                                                                                self.Data[self.s]['zijdblock'][0][3]], marker=marker_shape, s=30, facecolor=fit.color, edgecolor='k', zorder=10000, clip_on=False)
            fit.mm0_data[1] = tmax_ax.scatter([self.Data[self.s]['zijdblock'][tmax_index][0]], [self.Data[self.s]['zijdblock'][tmax_index][3] /
                                                                                self.Data[self.s]['zijdblock'][0][3]], marker=marker_shape, s=30, facecolor=fit.color, edgecolor='k', zorder=10000, clip_on=False)
            tmin_ax.set_xlim(tmin_xmin, tmin_xmax)
            tmin_ax.set_ylim(tmin_ymin, tmin_ymax)
            tmax_ax.set_xlim(tmax_xmin, tmax_xmax)
            tmax_ax.set_ylim(tmax_ymin, tmax_ymax)

            # logger
            if fit == self.current_fit:
                for item in range(self.logger.GetItemCount()):
                    if item >= tmin_index and item <= tmax_index:
                        self.logger.SetItemBackgroundColour(item, "LIGHT BLUE")
                    else:
                        self.logger.SetItemBackgroundColour(item, "WHITE")
                    try:
                        relability = self.Data[self.s]['measurement_flag'][item]
                    except IndexError:
                        relability = 'b'
                    if relability == 'b':
                        self.logger.SetItemBackgroundColour(item, "red")

        if problems != {}:
            if 'no bounds' in list(problems.keys()):
                text = "Fits "
                for problem in problems['no bounds']:
                    text += fit.name + ' '
                text += " for the current specimen are missing bounds and will not be displayed."

        self.canvas1.draw()
        self.canvas2.draw()
        self.canvas3.draw()

Response: draw the interpretations on the specimen and the M - M0 plots


Instruction:
Write a Python 3 script to
get the current level of the high level mean plot and the name of the corrisponding site study etc.

Response:
def get_levels_and_coordinates_names(self):
        """
        Get the current level of the high level mean plot and the name of
        the corrisponding site, study, etc. As well as the code for the
        current coordinate system.

        Returns
        -------
        (high_level_type,high_level_name,coordinate_system) : tuple object
            containing current high level type, name, and coordinate system
            being analyzed
        """
        if self.COORDINATE_SYSTEM == "geographic":
            dirtype = 'DA-DIR-GEO'
        elif self.COORDINATE_SYSTEM == "tilt-corrected":
            dirtype = 'DA-DIR-TILT'
        else:
            dirtype = 'DA-DIR'

        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())
        return (high_level_type, high_level_name, dirtype)


Instruction:
How would you code a function in Python 3 to
calculate and plots the sample orientation of the current specimen and checks if the sample orientation is on plots the wrong arrow wrong compass wrong compass and rotated sample error directions for the current specimen

Response:
def calc_and_plot_sample_orient_check(self):
        """
        If sample orientation is on plots the wrong arrow, wrong compass,
        and rotated sample error directions for the current specimen
        interpretation on the high level mean plot so that you can check
        sample orientation good/bad.
        """
        fit = self.current_fit
        if fit == None:
            return
        pars = fit.get('specimen')
        if 'specimen_dec' not in list(pars.keys()) or 'specimen_inc' not in list(pars.keys()):
            fit.put(self.s, 'specimen', self.get_PCA_parameters(
                self.s, fit, fit.tmin, fit.tmax, 'specimen', fit.PCA_type))
            pars = fit.get('specimen')
            if not pars:
                self.user_warning(
                    "could not calculate fit %s for specimen %s in specimen coordinate system while checking sample orientation please check data" % (fit.name, self.s))
                return
        dec, inc = pars['specimen_dec'], pars['specimen_inc']
        sample = self.Data_hierarchy['sample_of_specimen'][self.s]
        if sample not in list(self.Data_info["er_samples"].keys()) or "sample_azimuth" not in list(self.Data_info["er_samples"][sample].keys()) or "sample_dip" not in list(self.Data_info["er_samples"][sample].keys()):
            self.user_warning(
                "Could not display sample orientation checks because sample azimuth or sample dip is missing from er_samples table for sample %s" % sample)
            self.check_orient_on = False  # stop trying because this raises a ton of warnings
            return
        try:
            azimuth = float(self.Data_info["er_samples"][sample]['sample_azimuth'])
            dip = float(self.Data_info["er_samples"][sample]['sample_dip'])
        except TypeError:
            self.user_warning(
                "Could not display sample orientation checks because azimuth or dip is missing (or invalid) for sample %s" % sample)
            self.check_orient_on = False # stop trying because this raises a ton of warnings
            return

        # first test wrong direction of drill arrows (flip drill direction in opposite direction and re-calculate d,i)
        d, i = pmag.dogeo(dec, inc, azimuth-180., -dip)
        XY = pmag.dimap(d, i)
        if i > 0:
            FC = fit.color
            SIZE = 15*self.GUI_RESOLUTION
        else:
            FC = 'white'
            SIZE = 15*self.GUI_RESOLUTION
        self.high_level_eqarea.scatter([XY[0]], [
                                       XY[1]], marker='^', edgecolor=fit.color, facecolor=FC, s=SIZE, lw=1, clip_on=False)
        if self.ie_open:
            self.ie.scatter([XY[0]], [XY[1]], marker='^', edgecolor=fit.color,
                            facecolor=FC, s=SIZE, lw=1, clip_on=False)
        # Then test wrong end of compass (take az-180.)
        d, i = pmag.dogeo(dec, inc, azimuth-180., dip)
        XY = pmag.dimap(d, i)
        if i > 0:
            FC = fit.color
            SIZE = 15*self.GUI_RESOLUTION
        else:
            FC = 'white'
            SIZE = 15*self.GUI_RESOLUTION
        self.high_level_eqarea.scatter([XY[0]], [
                                       XY[1]], marker='v', edgecolor=fit.color, facecolor=FC, s=SIZE, lw=1, clip_on=False)
        if self.ie_open:
            self.ie.scatter([XY[0]], [XY[1]], marker='v', edgecolor=fit.color,
                            facecolor=FC, s=SIZE, lw=1, clip_on=False)
        # did the sample spin in the hole?
        # now spin around specimen's z
        X_up, Y_up, X_d, Y_d = [], [], [], []
        for incr in range(0, 360, 5):
            d, i = pmag.dogeo(dec+incr, inc, azimuth, dip)
            XY = pmag.dimap(d, i)
            if i >= 0:
                X_d.append(XY[0])
                Y_d.append(XY[1])
            else:
                X_up.append(XY[0])
                Y_up.append(XY[1])
        self.high_level_eqarea.scatter(
            X_d, Y_d, marker='.', color=fit.color, alpha=.5, s=SIZE/2, lw=1, clip_on=False)
        self.high_level_eqarea.scatter(
            X_up, Y_up, marker='.', color=fit.color, s=SIZE/2, lw=1, clip_on=False)
        if self.ie_open:
            self.ie.scatter(X_d, Y_d, marker='.', color=fit.color,
                            alpha=.5, s=SIZE/2, lw=1, clip_on=False)
            self.ie.scatter(X_up, Y_up, marker='.',
                            color=fit.color, s=SIZE/2, lw=1, clip_on=False)


Instruction:
How would you explain what the following Python 3 function does
def plot_high_level_equalarea(self, element):
        if self.ie_open:
            high_level = self.ie.show_box.GetValue()
        else:
            high_level = self.UPPER_LEVEL_SHOW
        fits = []
        if high_level not in self.pmag_results_data:
            print(("no level: " + str(high_level)))
            return
        if element not in self.pmag_results_data[high_level]:
            print(("no element: " + str(element)))
            return
        if self.mean_fit == 'All':
            fits = self.pmag_results_data[high_level][element]
        elif self.mean_fit != 'None' and self.mean_fit != None:
            fits = [fit for fit in self.pmag_results_data[high_level]
                    [element] if fit.name == self.mean_fit]
        else:
            fits = []
        fig = self.high_level_eqarea
        if fits:
            for fit in fits:
                pars = fit.get(self.COORDINATE_SYSTEM)
                if not pars:
                    if element in self.specimens:
                        fit.put(element, self.COORDINATE_SYSTEM, self.get_PCA_parameters(
                            element, fit, fit.tmin, fit.tmax, self.COORDINATE_SYSTEM, self.PCA_type_box.GetValue()))
                    pars = fit.get(self.COORDINATE_SYSTEM)
                    if not pars:
                        print(("No data for %s on element %s" %
                               (fit.name, element)))
                        return
                if "specimen_dec" in list(pars.keys()) and "specimen_inc" in list(pars.keys()):
                    dec = pars["specimen_dec"]
                    inc = pars["specimen_inc"]
                elif "dec" in list(pars.keys()) and "inc" in list(pars.keys()):
                    dec = pars["dec"]
                    inc = pars["inc"]
                else:
                    print(("-E- no dec and inc values for:\n" + str(fit)))
                XY = pmag.dimap(dec, inc)
                if inc > 0:
                    FC = fit.color
                    SIZE = 15*self.GUI_RESOLUTION
                else:
                    FC = 'white'
                    SIZE = 15*self.GUI_RESOLUTION
                marker_shape = 'o'
                if pars['calculation_type'] == "DE-BFP":
                    marker_shape = 's'
                    if 'bfv' in self.plane_display_box.GetValue():
                        marker_shape = '>'
                        SIZE = 25*self.GUI_RESOLUTION
                if fit == self.current_fit:
                    marker_shape = 'D'
                if fit in self.bad_fits:
                    marker_shape = (4, 1, 0)
                    SIZE = 25*self.GUI_RESOLUTION

                # draw a best-fit plane
                if pars['calculation_type'] == 'DE-BFP' and \
                   self.plane_display_box.GetValue() != "poles":

                    if "plane" in self.plane_display_box.GetValue() or "hemisphere" in self.plane_display_box.GetValue() or "wp" in self.plane_display_box.GetValue():

                        ymin, ymax = self.specimen_eqarea.get_ylim()
                        xmin, xmax = self.specimen_eqarea.get_xlim()

                        D_c, I_c = pmag.circ(
                            pars["specimen_dec"], pars["specimen_inc"], 90)
                        X_c_up, Y_c_up = [], []
                        X_c_d, Y_c_d = [], []
                        for k in range(len(D_c)):
                            XY = pmag.dimap(D_c[k], I_c[k])
                            if I_c[k] < 0:
                                X_c_up.append(XY[0])
                                Y_c_up.append(XY[1])
                            if I_c[k] > 0:
                                X_c_d.append(XY[0])
                                Y_c_d.append(XY[1])

                        if self.plane_display_box.GetValue() == "u. hemisphere" or \
                           self.plane_display_box.GetValue() == "whole plane" or \
                           self.plane_display_box.GetValue() == "wp + bfv":
                            fig.plot(X_c_d, Y_c_d, 'b')
                            if self.ie_open:
                                self.ie.plot(X_c_d, Y_c_d, 'b')
                        if self.plane_display_box.GetValue() == "l. hemisphere" or \
                           self.plane_display_box.GetValue() == "whole plane" or \
                           self.plane_display_box.GetValue() == "wp + bfv":
                            fig.plot(X_c_up, Y_c_up, 'c')
                            if self.ie_open:
                                self.ie.plot(X_c_up, Y_c_up, 'c')

                    if "bfv" in self.plane_display_box.GetValue():
                        if 'bfv_dec' not in list(pars.keys()) or 'bfv_inc' not in list(pars.keys()):
                            self.calculate_best_fit_vectors()
                            pars = fit.get(self.COORDINATE_SYSTEM)
                        try:
                            XY = pmag.dimap(pars['bfv_dec'], pars['bfv_inc'])
                        except KeyError:
                            print(("specimen %s fit %s is marked bad or there was an error calculating bfv pole will be displayed instead" % (
                                element, fit.name)))
#                            self.user_warning("There was an error calculating bfv for %s of %s, please raise an issue on github and/or contact a dev about this problem and restart the GUI"%(fit.name,element))
                        if inc > 0:
                            FC = fit.color
                        else:
                            FC = 'white'

                self.high_EA_xdata.append(XY[0])
                self.high_EA_ydata.append(XY[1])
                fig.scatter([XY[0]], [XY[1]], marker=marker_shape,
                            edgecolor=fit.color, facecolor=FC, s=SIZE, lw=1, clip_on=False)
                if self.ie_open:
                    self.ie.scatter([XY[0]], [XY[1]], marker=marker_shape,
                                    edgecolor=fit.color, facecolor=FC, s=SIZE, lw=1, clip_on=False)

Response: Given an element in the GUI plot to the high level mean plot


Instruction:
Here you have a function in Python 3, explain what it does
def plot_eqarea_pars(self, pars, fig):
        if pars == {}:
            pass
        elif 'calculation_type' in list(pars.keys()) and pars['calculation_type'] == 'DE-BFP':
            ymin, ymax = fig.get_ylim()
            xmin, xmax = fig.get_xlim()

            D_c, I_c = pmag.circ(pars["specimen_dec"],
                                 pars["specimen_inc"], 90)
            X_c_up, Y_c_up = [], []
            X_c_d, Y_c_d = [], []
            for k in range(len(D_c)):
                XY = pmag.dimap(D_c[k], I_c[k])
                if I_c[k] < 0:
                    X_c_up.append(XY[0])
                    Y_c_up.append(XY[1])
                if I_c[k] > 0:
                    X_c_d.append(XY[0])
                    Y_c_d.append(XY[1])
            fig.plot(X_c_d, Y_c_d, 'b', lw=0.5)
            fig.plot(X_c_up, Y_c_up, 'c', lw=0.5)
            if self.ie_open:
                self.ie.plot(X_c_d, Y_c_d, 'b', lw=0.5)
                self.ie.plot(X_c_up, Y_c_up, 'c', lw=0.5)

            fig.set_xlim(xmin, xmax)
            fig.set_ylim(ymin, ymax)
        # plot best-fit direction
        else:
            if "specimen_dec" in list(pars.keys()) and "specimen_inc" in list(pars.keys()):
                dec = pars["specimen_dec"]
                inc = pars["specimen_inc"]
            elif "dec" in list(pars.keys()) and "inc" in list(pars.keys()):
                dec = pars["dec"]
                inc = pars["inc"]
            else:
                print(("either dec or inc missing from values recived for high level plot, was given %s, aborting" % (
                    str(pars))))
                return
            XY = pmag.dimap(float(dec), float(inc))
            if inc > 0:
                if 'color' in list(pars.keys()):
                    FC = pars['color']
                    EC = pars['color']
                    SIZE = 15*self.GUI_RESOLUTION
                else:
                    FC = 'grey'
                    EC = 'grey'
                    SIZE = 15*self.GUI_RESOLUTION
            else:
                if 'color' in list(pars.keys()):
                    FC = 'white'
                    EC = pars['color']
                    SIZE = 15*self.GUI_RESOLUTION
                else:
                    FC = 'white'
                    EC = 'grey'
                    SIZE = 15*self.GUI_RESOLUTION
            fig.scatter([XY[0]], [XY[1]], marker='o', edgecolor=EC,
                        facecolor=FC, s=SIZE, lw=1, clip_on=False)
            if self.ie_open:
                self.ie.scatter([XY[0]], [XY[1]], marker='o', edgecolor=EC,
                                facecolor=FC, s=SIZE, lw=1, clip_on=False)

Response: Plots the parameters that are returned from pmag. domean and returns the corresponding plot of the species in the given figure.


Instruction:
How would you explain what the following Python 3 function does
def plot_eqarea_mean(self, meanpars, fig):
        mpars_to_plot = []
        if meanpars == {}:
            return
        if meanpars['calculation_type'] == 'Fisher by polarity':
            for mode in list(meanpars.keys()):
                if type(meanpars[mode]) == dict and meanpars[mode] != {}:
                    mpars_to_plot.append(meanpars[mode])
        else:
            mpars_to_plot.append(meanpars)
        ymin, ymax = fig.get_ylim()
        xmin, xmax = fig.get_xlim()
        if 'color' in meanpars:
            color = meanpars['color']
        else:
            color = 'black'
        size, alpha = 30, 1.
        # put on the mean direction
        for mpars in mpars_to_plot:
            XYM = pmag.dimap(float(mpars["dec"]), float(mpars["inc"]))
            if float(mpars["inc"]) > 0:
                FC = color
                EC = 'black'
            else:
                FC = 'white'
                EC = color
            self.displayed_means.append(fig.scatter([XYM[0]], [
                                        XYM[1]], marker='o', edgecolor=EC, facecolor=FC, s=size, lw=1, clip_on=False, alpha=alpha))

            if "alpha95" in list(mpars.keys()):
                # get the alpha95
                Xcirc, Ycirc = [], []
                Da95, Ia95 = pmag.circ(float(mpars["dec"]), float(
                    mpars["inc"]), float(mpars["alpha95"]))
                for k in range(len(Da95)):
                    XY = pmag.dimap(Da95[k], Ia95[k])
                    Xcirc.append(XY[0])
                    Ycirc.append(XY[1])
                self.displayed_means.append(
                    fig.plot(Xcirc, Ycirc, color, alpha=alpha))

            if self.ie_open:
                self.displayed_means.append(self.ie.scatter([XYM[0]], [
                                            XYM[1]], marker='o', edgecolor=EC, facecolor=FC, s=size, lw=1, clip_on=False, alpha=alpha))
                if "alpha95" in list(mpars.keys()):
                    self.displayed_means.append(
                        self.ie.plot(Xcirc, Ycirc, color, alpha=alpha))
                self.ie.eqarea.set_xlim(xmin, xmax)
                self.ie.eqarea.set_ylim(ymin, ymax)

        fig.set_xlim(xmin, xmax)
        fig.set_ylim(ymin, ymax)

Response: Plots the mean parameters of the eqarea of the current object.


Instruction:
How would you explain what the following Python 3 function does
def initialize_CART_rot(self, s):
        self.s = s  # only place in code where self.s is to be set directly
        if self.orthogonal_box.GetValue() == "X=East":
            self.ORTHO_PLOT_TYPE = 'E-W'
        elif self.orthogonal_box.GetValue() == "X=North":
            self.ORTHO_PLOT_TYPE = 'N-S'
        elif self.orthogonal_box.GetValue() == "X=best fit line dec":
            self.ORTHO_PLOT_TYPE = 'PCA_dec'
        else:
            self.ORTHO_PLOT_TYPE = 'ZIJ'
        if self.COORDINATE_SYSTEM == 'geographic':
            # self.CART_rot=self.Data[self.s]['zij_rotated_geo']
            self.zij = array(self.Data[self.s]['zdata_geo'])
            self.zijblock = self.Data[self.s]['zijdblock_geo']
        elif self.COORDINATE_SYSTEM == 'tilt-corrected':
            # self.CART_rot=self.Data[self.s]['zij_rotated_tilt']
            self.zij = array(self.Data[self.s]['zdata_tilt'])
            self.zijblock = self.Data[self.s]['zijdblock_tilt']
        else:
            # self.CART_rot=self.Data[self.s]['zij_rotated']
            self.zij = array(self.Data[self.s]['zdata'])
            self.zijblock = self.Data[self.s]['zijdblock']

        if self.COORDINATE_SYSTEM == 'geographic':
            if self.ORTHO_PLOT_TYPE == 'N-S':
                self.CART_rot = Rotate_zijderveld(
                    self.Data[self.s]['zdata_geo'], 0.)
            elif self.ORTHO_PLOT_TYPE == 'E-W':
                self.CART_rot = Rotate_zijderveld(
                    self.Data[self.s]['zdata_geo'], 90.)
            elif self.ORTHO_PLOT_TYPE == 'PCA_dec':
                if 'specimen_dec' in list(self.current_fit.pars.keys()) and type(self.current_fit.pars['specimen_dec']) != str:
                    self.CART_rot = Rotate_zijderveld(
                        self.Data[self.s]['zdata_geo'], self.current_fit.pars['specimen_dec'])
                else:
                    self.CART_rot = Rotate_zijderveld(self.Data[self.s]['zdata_geo'], pmag.cart2dir(
                        self.Data[self.s]['zdata_geo'][0])[0])
            else:
                self.CART_rot = Rotate_zijderveld(self.Data[self.s]['zdata_geo'], pmag.cart2dir(
                    self.Data[self.s]['zdata_geo'][0])[0])

        elif self.COORDINATE_SYSTEM == 'tilt-corrected':
            if self.ORTHO_PLOT_TYPE == 'N-S':
                self.CART_rot = Rotate_zijderveld(
                    self.Data[self.s]['zdata_tilt'], 0.)
            elif self.ORTHO_PLOT_TYPE == 'E-W':
                self.CART_rot = Rotate_zijderveld(
                    self.Data[self.s]['zdata_tilt'], 90)
            elif self.ORTHO_PLOT_TYPE == 'PCA_dec':
                if 'specimen_dec' in list(self.current_fit.pars.keys()) and type(self.current_fit.pars['specimen_dec']) != str:
                    self.CART_rot = Rotate_zijderveld(
                        self.Data[self.s]['zdata_tilt'], self.current_fit.pars['specimen_dec'])
                else:
                    self.CART_rot = Rotate_zijderveld(self.Data[self.s]['zdata_tilt'], pmag.cart2dir(
                        self.Data[self.s]['zdata_tilt'][0])[0])
            else:
                self.CART_rot = Rotate_zijderveld(self.Data[self.s]['zdata_tilt'], pmag.cart2dir(
                    self.Data[self.s]['zdata_tilt'][0])[0])
        else:
            if self.ORTHO_PLOT_TYPE == 'N-S':
                self.CART_rot = Rotate_zijderveld(
                    self.Data[self.s]['zdata'], 0.)
            elif self.ORTHO_PLOT_TYPE == 'E-W':
                self.CART_rot = Rotate_zijderveld(
                    self.Data[self.s]['zdata'], 90)
            elif self.ORTHO_PLOT_TYPE == 'PCA_dec':
                if 'specimen_dec' in list(self.current_fit.pars.keys()) and type(self.current_fit.pars['specimen_dec']) != str:
                    self.CART_rot = Rotate_zijderveld(
                        self.Data[self.s]['zdata'], self.current_fit.pars['specimen_dec'])
                else:  # Zijderveld
                    self.CART_rot = Rotate_zijderveld(
                        self.Data[self.s]['zdata'], pmag.cart2dir(self.Data[self.s]['zdata'][0])[0])

            else:  # Zijderveld
                self.CART_rot = Rotate_zijderveld(
                    self.Data[self.s]['zdata'], pmag.cart2dir(self.Data[self.s]['zdata'][0])[0])

        self.zij_norm = array([row/sqrt(sum(row**2)) for row in self.zij])

        # remove bad data from plotting:
        self.CART_rot_good = []
        self.CART_rot_bad = []
        for i in range(len(self.CART_rot)):
            if self.Data[self.s]['measurement_flag'][i] == 'g':
                self.CART_rot_good.append(list(self.CART_rot[i]))
            else:
                self.CART_rot_bad.append(list(self.CART_rot[i]))

        self.CART_rot = array(self.CART_rot)
        self.CART_rot_good = array(self.CART_rot_good)
        self.CART_rot_bad = array(self.CART_rot_bad)

Response: Initializes the internal structure of the current specimen and calculates the data necessary to plot the specimen plots.


Instruction:
Can you create a Python 3 function that
adds a new fit to the current fit.

Response:
def add_fit(self, specimen, name, fmin, fmax, PCA_type="DE-BFL", color=None, suppress_warnings=False, saved=True):
        """
        Goes through the data checks required to add an interpretation to
        the param specimen with the name param name, the bounds param fmin
        and param fmax, and calculation type param PCA_type.

        Parameters
        ----------
        specimen : specimen with measurement data to add the
        interpretation to
        name : name of the new interpretation
        fmin : lower bound of new interpretation
        fmax : upper bound of new interpretation
        PCA_type : type of regression or mean for new interpretaion
        (default: DE-BFL or line)
        color : color to plot the new interpretation in

        Returns
        -------
        new Fit object or None if fit could not be added
        """
        if specimen not in list(self.Data.keys()) and not suppress_warnings:
            self.user_warning(
                "there is no measurement data for %s and therefore no interpretation can be created for this specimen" % (specimen))
            return
        if fmax != None and fmax not in self.Data[specimen]['zijdblock_steps'] or fmin != None and fmin not in self.Data[specimen]['zijdblock_steps']:
            return
        if not (specimen in list(self.pmag_results_data['specimens'].keys())):
            self.pmag_results_data['specimens'][specimen] = []
        next_fit = str(len(self.pmag_results_data['specimens'][specimen]) + 1)
        if name == None or name in [x.name for x in self.pmag_results_data['specimens'][specimen]] or name == "" or name.replace(" ", "") == "":
            name = ('Fit ' + next_fit)
            if name in [x.name for x in self.pmag_results_data['specimens'][specimen]]:
                print('bad name')
                return
        if color == None:
            color = self.colors[(int(next_fit)-1) % len(self.colors)]
        new_fit = Fit(name, fmax, fmin, color, self, PCA_type, saved)
        if fmin != None and fmax != None:
            new_fit.put(specimen, self.COORDINATE_SYSTEM, self.get_PCA_parameters(
                specimen, new_fit, fmin, fmax, self.COORDINATE_SYSTEM, PCA_type))
            if ('specimen_dec' not in list(new_fit.get(self.COORDINATE_SYSTEM).keys())
                    or 'specimen_inc' not in list(new_fit.get(self.COORDINATE_SYSTEM).keys()))\
                    and not suppress_warnings:
                TEXT = "Could not calculate dec or inc for specimen %s component %s with bounds %s and %s in coordinate_system %s, component not added" % (
                    specimen, name, fmin, fmax, self.COORDINATE_SYSTEM)
                self.user_warning(TEXT)
                print(TEXT)
                return
        self.pmag_results_data['specimens'][specimen].append(new_fit)
        samp = self.Data_hierarchy['sample_of_specimen'][specimen]
        if samp in list(self.Data_info['er_samples'].keys()):
            if 'sample_orientation_flag' not in self.Data_info['er_samples'][samp]:
                self.Data_info['er_samples'][samp]['sample_orientation_flag'] = 'g'
            samp_flag = self.Data_info['er_samples'][samp]['sample_orientation_flag']
            if samp_flag == 'b':
                self.mark_fit_bad(new_fit)
        self.close_warning = True
        return new_fit


Instruction:
Create a Python 3 function to
remove fit from GUI results data

Response:
def delete_fit(self, fit, specimen=None):
        """
        removes fit from GUI results data

        Parameters
        ----------
        fit : fit to remove
        specimen : specimen of fit to remove, if not provided and
        set to None then the function will find the specimen itself
        """
        if specimen == None:
            for spec in self.pmag_results_data['specimens']:
                if fit in self.pmag_results_data['specimens'][spec]:
                    specimen = spec
                    break
        if specimen not in self.pmag_results_data['specimens']:
            return
        if fit in self.pmag_results_data['specimens'][specimen]:
            self.pmag_results_data['specimens'][specimen].remove(fit)
        if fit == self.current_fit:
            if self.pmag_results_data['specimens'][specimen]:
                self.pmag_results_data['specimens'][specimen][-1].select()
            else:
                self.current_fit = None
        self.close_warning = True
        self.calculate_high_levels_data()
        if self.ie_open:
            self.ie.update_editor()
        self.update_selection()


Instruction:
Make a summary of the following Python 3 code
def calculate_vgp_data(self):
        # get criteria if it exists else use default
        crit_data = self.read_criteria_file()
        if crit_data == None:
            crit_data = pmag.default_criteria(0)
        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
                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]

        Ns = []
        # retrieve specimen data to calculate VGPS with
        for s in list(self.pmag_results_data['specimens'].keys()):
            for fit in self.pmag_results_data['specimens'][s]:
                if fit in self.bad_fits:
                    continue
                pars = fit.get(self.COORDINATE_SYSTEM)
                # check for interpretation data for fit
                if not pars:
                    pars = self.get_PCA_parameters(
                        s, fit, fit.tmin, fit.tmax, self.COORDINATE_SYSTEM, fit.PCA_type)
                    if not pars or 'specimen_dec' not in list(pars.keys()) or 'specimen_inc' not in list(pars.keys()):
                        print(("Could not calculate interpretation for specimen %s and fit %s while calculating VGP data, skipping this component" % (
                            s, fit.name)))
                        continue
                    pars['er_specimen_name'] = s
                    pars['specimen_comp_name'] = fit.name
                Ns.append(pars)

        SpecDirs = []
        if crit_data != None:  # 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=2.5)
                if len(kill) == 0:  # nothing killed it
                    SpecDirs.append(rec)
        else:  # no criteria
            SpecDirs = Ns[:]  # take them all

        for i in range(len(SpecDirs)):
            if SpecDirs[i] == {}:
                continue
            specimen = SpecDirs[i]['er_specimen_name']
            SpecDirs[i]['er_sample_name'] = self.Data_hierarchy['sample_of_specimen'][specimen]
            SpecDirs[i]['er_site_name'] = self.Data_hierarchy['site_of_specimen'][specimen]
            SpecDirs[i]['er_location_name'] = self.Data_hierarchy['location_of_specimen'][specimen]

        # init VGP data
        VGP_Data = {'samples': [], 'sites': [], 'locations': []}

        # obtain lat lon data
        SiteNFO = list(self.Data_info['er_sites'].values())
        for val in SiteNFO:
            site = val['er_site_name']
            not_found = []
            # check that lat/lon columns are present and non-null
            if 'site_lat' not in val:
                not_found.append('latitude')
            elif not val['site_lat'] and val['site_lat'] is not 0:
                not_found.append('latitude')
            if 'site_lon' not in val:
                not_found.append('longitude')
            elif not val['site_lon'] and val['site_lon'] is not 0:
                not_found.append('longitude')
            if not_found == []:
                continue
            TEXT = "%s not found for site %s. Select 'yes' to enter the values now or 'no' to skip this site and all samples contained in it." % (
                str(not_found), val['er_site_name'])
            dlg = wx.MessageDialog(
                self, caption="Missing Data", message=TEXT, style=wx.YES_NO | wx.ICON_QUESTION)
            result = self.show_dlg(dlg)
            dlg.Destroy()
            if result == wx.ID_YES:
                ui_dialog = demag_dialogs.user_input(self, ['Latitude', 'Longitude'], parse_funcs=[
                                                     float, float], heading="Missing Latitude or Longitude data for site: %s" % val['er_site_name'])
                self.show_dlg(ui_dialog)
                ui_data = ui_dialog.get_values()
                if ui_data[0]:
                    self.Data_info['er_sites'][site]['site_lat'] = ui_data[1]['Latitude']
                    self.Data_info['er_sites'][site]['site_lon'] = ui_data[1]['Longitude']
                    val['site_lat'] = ui_data[1]['Latitude']
                    val['site_lon'] = ui_data[1]['Longitude']

        # calculate sample vgps
        for samp in self.samples:
            SampDir = pmag.get_dictitem(SpecDirs, 'er_sample_name', samp, 'T')
            if len(SampDir) <= 0:
                continue
            for comp in self.all_fits_list:
                CompDir = pmag.get_dictitem(
                    SampDir, 'specimen_comp_name', comp, 'T')
                if len(CompDir) <= 0:
                    continue  # no data for comp
                samp_mean = pmag.lnpbykey(CompDir, 'sample', 'specimen')
                site = pmag.get_dictitem(
                    SiteNFO, 'er_site_name', CompDir[0]['er_site_name'], 'T')
                dec = float(samp_mean['sample_dec'])
                inc = float(samp_mean['sample_inc'])
                if 'sample_alpha95' in samp_mean and samp_mean['sample_alpha95'] != "":
                    a95 = float(samp_mean['sample_alpha95'])
                else:
                    a95 = 180.
                try:
                    lat = float(site[0]['site_lat'])
                    lon = float(site[0]['site_lon'])
                except (KeyError, IndexError, ValueError, TypeError) as e:
                    continue
                plong, plat, dp, dm = pmag.dia_vgp(dec, inc, a95, lat, lon)
                PmagResRec = {}
                PmagResRec['name'] = samp
                PmagResRec['comp_name'] = comp
                PmagResRec['n'] = len(CompDir)
                PmagResRec['color'] = [e.color for sl in list(self.pmag_results_data['specimens'].values(
                )) for e in sl if e not in self.bad_fits and e.name == comp][0]
                PmagResRec['vgp_lon'] = plong
                PmagResRec['vgp_lat'] = plat
                PmagResRec['lon'] = lon
                PmagResRec['lat'] = lat
                PmagResRec['vgp_dp'] = dp
                PmagResRec['vgp_dm'] = dm
                VGP_Data['samples'].append(PmagResRec)

        for site in self.sites:
            SiteDir = pmag.get_dictitem(SpecDirs, 'er_site_name', site, 'T')
            erSite = pmag.get_dictitem(SiteNFO, 'er_site_name', site, 'T')
            for comp in self.all_fits_list:
                siteD = pmag.get_dictitem(
                    SiteDir, 'specimen_comp_name', comp, 'T')
                if len(siteD) <= 0:
                    print(("no data for comp %s and site %s" % (comp, site)))
                    continue
                SiteData = pmag.lnpbykey(siteD, 'site', 'specimen')
                dec = float(SiteData['site_dec'])
                inc = float(SiteData['site_inc'])
                if 'site_alpha95' in SiteData and SiteData['site_alpha95'] != "":
                    a95 = float(SiteData['site_alpha95'])
                else:
                    a95 = 180.
                try:
                    lat = float(erSite[0]['site_lat'])
                    lon = float(erSite[0]['site_lon'])
                except (KeyError, IndexError, TypeError) as e:
                    continue
                plong, plat, dp, dm = pmag.dia_vgp(dec, inc, a95, lat, lon)
                SiteData['name'] = site
                SiteData['comp_name'] = comp
                SiteData['n'] = len(siteD)
                SiteData['vgp_lon'] = plong
                SiteData['vgp_lat'] = plat
                SiteData['lon'] = lon
                SiteData['lat'] = lat
                SiteData['vgp_dp'] = dp
                SiteData['vgp_dm'] = dm
                SiteData['color'] = [e.color for sl in list(self.pmag_results_data['specimens'].values(
                )) for e in sl if e not in self.bad_fits and e.name == comp][0]
                VGP_Data['sites'].append(SiteData)

        for loc in self.locations:
            LocDir = pmag.get_dictitem(SpecDirs, 'er_location_name', loc, 'T')
            for comp in self.all_fits_list:
                LocCompData = pmag.get_dictitem(
                    LocDir, 'specimen_comp_name', comp, 'T')
                if len(LocCompData) < 3:
                    print(("insufficient data for comp %s" % comp))
                    continue
                precs = []
                for rec in LocCompData:
                    prec = {'dec': rec['specimen_dec'], 'inc': rec['specimen_inc'],
                            'name': rec['er_site_name'], 'loc': rec['er_location_name']}
                    prec = {k: v if v != None else '' for k,
                            v in list(prec.items())}
                    precs.append(prec)
                # you need at least 3 records to get anything back from pmag.fisher_by_pol
                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['name'] = polpars[mode]['locs']
                    PolRes["comp_name"] = comp+':'+mode
                    PolRes["dec"] = '%7.1f' % (polpars[mode]['dec'])
                    PolRes["inc"] = '%7.1f' % (polpars[mode]['inc'])
                    PolRes["n"] = '%i' % (polpars[mode]['n'])
                    PolRes["r"] = '%5.4f' % (polpars[mode]['r'])
                    PolRes["k"] = '%6.0f' % (polpars[mode]['k'])
                    PolRes['a95'] = '%7.1f' % (polpars[mode]['alpha95'])
                    dec, inc, a95 = PolRes["dec"], PolRes["inc"], PolRes["a95"]
                    lat, lon, loc_data = "", "", self.Data_info['er_locations']
                    if loc in loc_data and 'location_begin_lat' in loc_data[loc]:
                        lat = loc_data[loc]['location_begin_lat']
                    elif loc in loc_data and 'location_end_lat' in loc_data[loc]:
                        lat = loc_data[loc]['location_end_lat']
                    if loc in loc_data and 'location_begin_lon' in loc_data[loc]:
                        lon = loc_data[loc]['location_begin_lon']
                    elif loc in loc_data and 'location_end_lon' in loc_data[loc]:
                        lon = loc_data[loc]['location_end_lon']
                    if lat == "" or lon == "" or lat == None or lon == None:
                        ui_dialog = demag_dialogs.user_input(self, ['Latitude', 'Longitude'], parse_funcs=[
                                                             float, float], heading="Missing Latitude or Longitude data for location: %s" % loc)
                        self.show_dlg(ui_dialog)
                        ui_data = ui_dialog.get_values()
                        if ui_data[0]:
                            lat = ui_data[1]['Latitude']
                            lon = ui_data[1]['Longitude']
                            if loc not in loc_data:
                                loc_data[loc] = {}
                            if len(loc_data) > 0:
                                loc_data[loc]['location_begin_lat'] = lat
                                loc_data[loc]['location_begin_lon'] = lon
                        else:
                            continue
                    try:
                        plong, plat, dp, dm = pmag.dia_vgp(
                            *list(map(float, [dec, inc, a95, lat, lon])))
                    except TypeError:
                        print(("Not valid parameters for vgp calculation on location: %s" %
                               loc, dec, inc, a95, lat, lon))
                        continue
                    PolRes['vgp_lon'] = plong
                    PolRes['vgp_lat'] = plat
                    PolRes['lon'] = lon
                    PolRes['lat'] = lat
                    PolRes['vgp_dp'] = dp
                    PolRes['vgp_dm'] = dm
                    PolRes['color'] = [e.color for sl in list(self.pmag_results_data['specimens'].values(
                    )) for e in sl if e not in self.bad_fits and e.name == comp][0]
                    VGP_Data['locations'].append(PolRes)

        return VGP_Data

Response: Calculates VGPS for all samples sites and locations


Instruction:
Here you have a function in Python 3, explain what it does
def convert_ages_to_calendar_year(self, er_ages_rec):
        if "age" not in list(er_ages_rec.keys()):
            return(er_ages_rec)
        if "age_unit" not in list(er_ages_rec.keys()):
            return(er_ages_rec)
        if er_ages_rec["age_unit"] == "":
            return(er_ages_rec)

        if er_ages_rec["age"] == "":
            if "age_range_high" in list(er_ages_rec.keys()) and "age_range_low" in list(er_ages_rec.keys()):
                if er_ages_rec["age_range_high"] != "" and er_ages_rec["age_range_low"] != "":
                    er_ages_rec["age"] = scipy.mean(
                        [float(er_ages_rec["age_range_high"]), float(er_ages_rec["age_range_low"])])
        if er_ages_rec["age"] == "":
            return(er_ages_rec)

        age_unit = er_ages_rec["age_unit"]

        # Fix 'age':
        mutliplier = 1
        if age_unit == "Ga":
            mutliplier = -1e9
        if age_unit == "Ma":
            mutliplier = -1e6
        if age_unit == "Ka":
            mutliplier = -1e3
        if age_unit == "Years AD (+/-)" or age_unit == "Years Cal AD (+/-)":
            mutliplier = 1
        if age_unit == "Years BP" or age_unit == "Years Cal BP":
            mutliplier = 1
        age = float(er_ages_rec["age"])*mutliplier
        if age_unit == "Years BP" or age_unit == "Years Cal BP":
            age = 1950-age
        er_ages_rec['age_cal_year'] = age

        # Fix 'age_range_low':
        age_range_low = age
        age_range_high = age
        age_sigma = 0

        if "age_sigma" in list(er_ages_rec.keys()) and er_ages_rec["age_sigma"] != "":
            age_sigma = float(er_ages_rec["age_sigma"])*mutliplier
            if age_unit == "Years BP" or age_unit == "Years Cal BP":
                age_sigma = 1950-age_sigma
            age_range_low = age-age_sigma
            age_range_high = age+age_sigma

        if "age_range_high" in list(er_ages_rec.keys()) and "age_range_low" in list(er_ages_rec.keys()):
            if er_ages_rec["age_range_high"] != "" and er_ages_rec["age_range_low"] != "":
                age_range_high = float(
                    er_ages_rec["age_range_high"])*mutliplier
                if age_unit == "Years BP" or age_unit == "Years Cal BP":
                    age_range_high = 1950-age_range_high
                age_range_low = float(er_ages_rec["age_range_low"])*mutliplier
                if age_unit == "Years BP" or age_unit == "Years Cal BP":
                    age_range_low = 1950-age_range_low
        er_ages_rec['age_cal_year_range_low'] = age_range_low
        er_ages_rec['age_cal_year_range_high'] = age_range_high

        return(er_ages_rec)

Response: Convert all age units to calendar year


Instruction:
Implement a function in Python 3 to
generate the warning text for the current specimen and adds them to the warning_text attribute of the GUI.

Response:
def generate_warning_text(self):
        """
        generates warnings for the current specimen then adds them to the
        current warning text for the GUI which will be rendered on a call to
        update_warning_box.
        """
        self.warning_text = ""
        if self.s in list(self.pmag_results_data['specimens'].keys()):
            for fit in self.pmag_results_data['specimens'][self.s]:
                beg_pca, end_pca = self.get_indices(
                    fit, fit.tmin, fit.tmax, self.s)
                if beg_pca == None or end_pca == None:
                    self.warning_text += "%s to %s are invalid bounds, to fit %s.\n" % (
                        fit.tmin, fit.tmax, fit.name)
                elif end_pca - beg_pca < 2:
                    self.warning_text += "there are not enough points between %s to %s, on fit %s.\n" % (
                        fit.tmin, fit.tmax, fit.name)
                else:
                    check_duplicates = []
                    warning_issued = []  # keep track of warnings issued to avoid redundant warnings

                    # if within range, attempt to go one additional step beyond
                    # tmax so that duplicates at the upper bound are caught
                    if (end_pca + 2) < len(self.Data[self.s]['zijdblock_steps']):
                        check_endpoint = end_pca + 2
                    else:
                        check_endpoint = end_pca + 1

                    for s, f in zip(self.Data[self.s]['zijdblock_steps'][beg_pca:check_endpoint],
                                    self.Data[self.s]['measurement_flag'][beg_pca:check_endpoint]):
                        if f == 'g' and [s, 'g'] in check_duplicates:
                            if s == fit.tmin and s not in warning_issued:
                                self.warning_text += ("There are multiple good %s " +
                                                      "steps at the upper bound of Fit %s. The first " +
                                                      "measurement will be used as the lower bound.\n") % (
                                                          s, fit.name)
                                # warning_issued_low.append(s)
                                warning_issued.append(s)
                            elif s == fit.tmax and s not in warning_issued:
                                self.warning_text += ("There are multiple good %s " +
                                                      "steps at the upper bound of Fit %s. The first " +
                                                      "measurement will be used as the upper bound.\n") % (
                                                          s, fit.name)
                                # warning_issued_high.append(s)
                                warning_issued.append(s)
                            elif s not in warning_issued:
                                self.warning_text += ("Within Fit %s, there are " +
                                                      "multiple good measurements at the %s step. All " +
                                                      "good measurements are included in the fit.\n") % (
                                                          fit.name, s)
                                warning_issued.append(s)
                            else:
                                pass
                        else:
                            check_duplicates.append([s, f])
        if self.s in list(self.Data.keys()):
            if not self.Data[self.s]['zijdblock_geo']:
                self.warning_text += "There is no geographic data for this specimen.\n"
            if not self.Data[self.s]['zijdblock_tilt']:
                self.warning_text += "There is no tilt-corrected data for this specimen.\n"


Instruction:
Given the following Python 3 function, write the documentation
def read_criteria_file(self, criteria_file_name=None):
#        import pdb; pdb.set_trace()
        acceptance_criteria = pmag.initialize_acceptance_criteria()
        if self.data_model == 3:
            if criteria_file_name == None:
                criteria_file_name = "criteria.txt"
            contribution = cb.Contribution(self.WD, read_tables=[
                                           'criteria'], custom_filenames={'criteria': criteria_file_name})
            if 'criteria' in contribution.tables:
                crit_container = contribution.tables['criteria']
                crit_data = crit_container.df
                crit_data = crit_data.to_dict('records')
                for crit in crit_data:
                    m2_name = map_magic.convert_direction_criteria(
                        'magic2', crit['table_column'])
                    if m2_name != "":
                        try:
                            if crit['criterion_value'] == 'True':
                                acceptance_criteria[m2_name]['value'] = 1
                            else:
                                acceptance_criteria[m2_name]['value'] = 0
                            acceptance_criteria[m2_name]['value'] = float(
                                crit['criterion_value'])
                        except ValueError:
                            self.user_warning("%s is not a valid comparitor for %s, skipping this criteria" % (
                                str(crit['criterion_value']), m2_name))
                            continue
                        acceptance_criteria[m2_name]['pmag_criteria_code'] = crit['criterion']
            return acceptance_criteria
        else:
            if criteria_file_name == None:
                criteria_file_name = "pmag_criteria.txt"
            try:
                acceptance_criteria = pmag.read_criteria_from_file(
                    os.path.join(self.WD, criteria_file_name), acceptance_criteria)
            except (IOError, OSError) as e:
                self.user_warning("File %s not found in directory %s aborting opperation" % (
                    criteria_file_name, self.WD))
            return acceptance_criteria

Response: Reads the pmag_criteria. txt file and returns a set of dicts that can be passed into pmag. grade to filter data.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_PCA_parameters(self, specimen, fit, tmin, tmax, coordinate_system, calculation_type):
        if tmin == '' or tmax == '':
            return
        beg_pca, end_pca = self.get_indices(fit, tmin, tmax, specimen)

        if coordinate_system == 'geographic' or coordinate_system == 'DA-DIR-GEO':
            block = self.Data[specimen]['zijdblock_geo']
        elif coordinate_system == 'tilt-corrected' or coordinate_system == 'DA-DIR-TILT':
            block = self.Data[specimen]['zijdblock_tilt']
        else:
            block = self.Data[specimen]['zijdblock']
        if block == []:
            print(("-E- no measurement data for specimen %s in coordinate system %s" %
                   (specimen, coordinate_system)))
            mpars = {}
        elif end_pca > beg_pca and end_pca - beg_pca > 1:

            try:
                # preformes regression
                mpars = pmag.domean(block, beg_pca, end_pca, calculation_type)
            except:
                print((block, beg_pca, end_pca, calculation_type,
                       specimen, fit.name, tmin, tmax, coordinate_system))
                return

            if 'specimen_direction_type' in mpars and mpars['specimen_direction_type'] == 'Error':
                print(("-E- no measurement data for specimen %s in coordinate system %s" %
                       (specimen, coordinate_system)))
                return {}
        else:
            mpars = {}
        for k in list(mpars.keys()):
            try:
                if math.isnan(float(mpars[k])):
                    mpars[k] = 0
            except:
                pass
        if "DE-BFL" in calculation_type and 'specimen_dang' not in list(mpars.keys()):
            mpars['specimen_dang'] = 0

        if 'best fit vector' in self.plane_display_box.GetValue():
            self.calculate_best_fit_vectors()

        return(mpars)

Response: Returns a dictionary of specimen record parameters for the specified specimen and fit.


Instruction:
Can you generate the documentation for the following Python 3 function
def autointerpret(self, event, step_size=None, calculation_type="DE-BFL"):
        if not self.user_warning("This feature is in ALPHA and still in development and testing. It is subject to bugs and will often create a LOT of new interpretations. This feature should only be used to get a general idea of the trend of the data before actually mannuely interpreting the data and the output of this function should certainly not be trusted as 100% accurate and useable for publication. Would you like to continue?"):
            return
        if not self.clear_interpretations():
            return

        print("Autointerpretation Start")

        self.set_test_mode(True)
        for specimen in self.specimens:
            self.autointerpret_specimen(specimen, step_size, calculation_type)
        self.set_test_mode(False)

        if self.pmag_results_data['specimens'][self.s] != []:
            self.current_fit = self.pmag_results_data['specimens'][self.s][-1]
        else:
            self.current_fit = None
        print("Autointerpretation Complete")
        self.update_selection()
        if self.ie_open:
            self.ie.update_editor()

Response: Autointerprets the current interpretations for all the specimen in the current specimen and adds interpretations to every specimen in the current specimen.


Instruction:
Can you write a function in Python 3 where it
gets the Parameters of a specific high level mean of the specimen interpretations

Response:
def get_high_level_mean_pars(self, high_level_type, high_level_name, calculation_type, elements_type, mean_fit, dirtype):
        """
        Gets the Parameters of a mean of lower level data such as a Site
        level Fisher mean of Specimen interpretations

        Parameters
        ----------
        high_level_type : 'samples','sites','locations','study'
        high_level_name : sample, site, location, or study whose
            data to which to apply the mean
        calculation_type : 'Bingham','Fisher','Fisher by polarity'
        elements_type : what to average: 'specimens', 'samples',
            'sites' (Ron. ToDo allow VGP and maybe locations?)
        mean_fit : name of interpretation to average if All uses all
            figure out what level to average,and what elements to average
            (specimen, samples, sites, vgp)
        """

        elements_list = self.Data_hierarchy[high_level_type][high_level_name][elements_type]
        pars_for_mean = {}
        pars_for_mean["All"] = []

        for element in elements_list:
            if elements_type == 'specimens' and element in self.pmag_results_data['specimens']:
                for fit in self.pmag_results_data['specimens'][element]:
                    if fit in self.bad_fits:
                        continue
                    if fit.name not in list(pars_for_mean.keys()):
                        pars_for_mean[fit.name] = []
                    try:
                        # is this fit to be included in mean
                        if mean_fit == 'All' or mean_fit == fit.name:
                            pars = fit.get(dirtype)
                            if pars == {} or pars == None:
                                pars = self.get_PCA_parameters(
                                    element, fit, fit.tmin, fit.tmax, dirtype, fit.PCA_type)
                                if pars == {} or pars == None:
                                    print(("cannot calculate parameters for element %s and fit %s in calculate_high_level_mean leaving out of fisher mean, please check this value." % (
                                        element, fit.name)))
                                    continue
                                fit.put(element, dirtype, pars)
                        else:
                            continue
                        if "calculation_type" in list(pars.keys()) and pars["calculation_type"] == 'DE-BFP':
                            dec, inc, direction_type = pars["specimen_dec"], pars["specimen_inc"], 'p'
                        elif "specimen_dec" in list(pars.keys()) and "specimen_inc" in list(pars.keys()):
                            dec, inc, direction_type = pars["specimen_dec"], pars["specimen_inc"], 'l'
                        elif "dec" in list(pars.keys()) and "inc" in list(pars.keys()):
                            dec, inc, direction_type = pars["dec"], pars["inc"], 'l'
                        else:
                            print(
                                ("-E- ERROR: can't find mean for specimen interpertation: %s , %s" % (element, fit.name)))
                            print(pars)
                            continue
                        # add for calculation
                        pars_for_mean[fit.name].append({'dec': float(dec), 'inc': float(
                            inc), 'direction_type': direction_type, 'element_name': element})
                        pars_for_mean["All"].append({'dec': float(dec), 'inc': float(
                            inc), 'direction_type': direction_type, 'element_name': element})
                    except KeyError:
                        print(
                            ("KeyError in calculate_high_level_mean for element: " + str(element)))
                        continue
            else:
                try:
                    pars = self.high_level_means[elements_type][element][mean_fit][dirtype]
                    if "dec" in list(pars.keys()) and "inc" in list(pars.keys()):
                        dec, inc, direction_type = pars["dec"], pars["inc"], 'l'
                    else:
                        #                            print "-E- ERROR: can't find mean for element %s"%element
                        continue
                except KeyError:
                    #                        print("KeyError in calculate_high_level_mean for element: " + str(element) + " please report to a dev")
                    continue

        return pars_for_mean


Instruction:
Can you tell what is the following Python 3 function doing
def calculate_mean(self, pars_for_mean, calculation_type):

        if len(pars_for_mean) == 0:
            return({})

        elif len(pars_for_mean) == 1:
            return ({"dec": float(pars_for_mean[0]['dec']), "inc": float(pars_for_mean[0]['inc']), "calculation_type": calculation_type, "n": 1})

#        elif calculation_type =='Bingham':
#            data=[]
#            for pars in pars_for_mean:
#                # ignore great circle
#                if 'direction_type' in pars.keys() and 'direction_type'=='p':
#                    continue
#                else:
#                    data.append([pars['dec'],pars['inc']])
#            mpars=pmag.dobingham(data)

        elif calculation_type == 'Fisher':
            mpars = pmag.dolnp(pars_for_mean, 'direction_type')

        elif calculation_type == 'Fisher by polarity':
            mpars = pmag.fisher_by_pol(pars_for_mean)
            for key in list(mpars.keys()):
                mpars[key]['n_planes'] = 0
                mpars[key]['calculation_type'] = 'Fisher'

        mpars['calculation_type'] = calculation_type

        return mpars

Response: Calculates the mean of the in - memory data for a given set of parameters.


Instruction:
Implement a Python 3 function for
calculating the high level mean data for the high level mean plot using the information in level_box level_names mean_type_box and mean_fit_box.

Response:
def calculate_high_levels_data(self):
        """
        calculates high level mean data for the high level mean plot using
        information in level_box, level_names, mean_type_box, and
        mean_fit_box also updates the information in the ie to match high
        level mean data in main GUI.
        """
        high_level_type = str(self.level_box.GetValue())
        if high_level_type == 'sample':
            high_level_type = 'samples'
        if high_level_type == 'site':
            high_level_type = 'sites'
        if high_level_type == 'location':
            high_level_type = 'locations'
        high_level_name = str(self.level_names.GetValue())
        calculation_type = str(self.mean_type_box.GetValue())
        elements_type = self.UPPER_LEVEL_SHOW
        if self.ie_open:
            self.ie.mean_type_box.SetStringSelection(calculation_type)
        self.calculate_high_level_mean(
            high_level_type, high_level_name, calculation_type, elements_type, self.mean_fit)


Instruction:
Explain what the following Python 3 code does
def quiet_reset_backend(self, reset_interps=True):
        new_Data_info = self.get_data_info()
        new_Data, new_Data_hierarchy = self.get_data()

        if not new_Data:
            print("Data read in failed when reseting, aborting reset")
            return
        else:
            self.Data, self.Data_hierarchy, self.Data_info = new_Data, new_Data_hierarchy, new_Data_info

        if reset_interps:
            self.pmag_results_data = {}
            for level in ['specimens', 'samples', 'sites', 'locations', 'study']:
                self.pmag_results_data[level] = {}
            self.high_level_means = {}

            high_level_means = {}
            for high_level in ['samples', 'sites', 'locations', 'study']:
                if high_level not in list(self.high_level_means.keys()):
                    self.high_level_means[high_level] = {}

        # get list of sites
        self.locations = list(self.Data_hierarchy['locations'].keys())
        self.locations.sort()  # get list of sites
        # get list of sites
        self.sites = list(self.Data_hierarchy['sites'].keys())
        self.sites.sort(key=spec_key_func)  # get list of sites
        self.samples = []  # sort the samples within each site
        for site in self.sites:
            self.samples.extend(
                sorted(self.Data_hierarchy['sites'][site]['samples'], key=spec_key_func))
        self.specimens = []  # sort the specimens within each sample
        for samp in self.samples:
            self.specimens.extend(
                sorted(self.Data_hierarchy['samples'][samp]['specimens'], key=spec_key_func))

        # --------------------------------------------------------------------
        # initialize first specimen in list as current specimen
        # --------------------------------------------------------------------
        if self.s in self.specimens:
            pass
        elif len(self.specimens) > 0:
            self.select_specimen(str(self.specimens[0]))
        else:
            self.select_specimen("")
        try:
            self.sample = self.Data_hierarchy['sample_of_specimen'][self.s]
        except KeyError:
            self.sample = ""
        try:
            self.site = self.Data_hierarchy['site_of_specimen'][self.s]
        except KeyError:
            self.site = ""

        if self.Data and reset_interps:
            self.update_pmag_tables()

        if self.ie_open:
            self.ie.specimens_list = self.specimens

Response: Resets all the data in the backend to the original data and returns the new data and the new data_info.


Instruction:
Can you tell what is the following Python 3 function doing
def reset_backend(self, warn_user=True, reset_interps=True):
        if warn_user and not self.data_loss_warning():
            return False

        # reset backend, including get_data(), get_data_info()
        self.quiet_reset_backend(reset_interps=reset_interps)

        # reset specimens box
        self.specimens_box.SetItems(self.specimens)
        self.specimens_box.SetStringSelection(str(self.s))

        # reset site level means box
        self.level_names.Clear()
        self.level_names.AppendItems(self.sites)
        if self.sites:
            self.level_names.SetSelection(0)

        # reset coordinate system
        self.COORDINATE_SYSTEM, self.coordinate_list = self.get_coordinate_system()
        self.coordinates_box.Clear()
        self.coordinates_box.AppendItems(self.coordinate_list)
        self.coordinates_box.SetStringSelection(self.COORDINATE_SYSTEM)

        # get cart rot
        self.initialize_CART_rot(str(self.s))

        # draw everything
        if self.Data:
            if not self.current_fit:
                self.draw_figure(self.s)
                self.update_selection()
            else:
                self.Add_text()
                self.update_fit_boxes()

        if self.ie_open:
            self.ie.update_editor()

Response: Resets the current backend and updates GUI displays such as plots boxes and GUI displays.


Instruction:
Make a summary of the following Python 3 code
def recalculate_current_specimen_interpreatations(self):
        self.initialize_CART_rot(self.s)
        if str(self.s) in self.pmag_results_data['specimens']:
            for fit in self.pmag_results_data['specimens'][self.s]:
                if fit.get('specimen') and 'calculation_type' in fit.get('specimen'):
                    fit.put(self.s, 'specimen', self.get_PCA_parameters(
                        self.s, fit, fit.tmin, fit.tmax, 'specimen', fit.get('specimen')['calculation_type']))
                if len(self.Data[self.s]['zijdblock_geo']) > 0 and fit.get('geographic') and 'calculation_type' in fit.get('geographic'):
                    fit.put(self.s, 'geographic', self.get_PCA_parameters(
                        self.s, fit, fit.tmin, fit.tmax, 'geographic', fit.get('geographic')['calculation_type']))
                if len(self.Data[self.s]['zijdblock_tilt']) > 0 and fit.get('tilt-corrected') and 'calculation_type' in fit.get('tilt-corrected'):
                    fit.put(self.s, 'tilt-corrected', self.get_PCA_parameters(self.s, fit, fit.tmin,
                                                                              fit.tmax, 'tilt-corrected', fit.get('tilt-corrected')['calculation_type']))

Response: recalculates all interpretations on all coordinate systems for all coordinate systems. Does not display recalcuated data.


Instruction:
How would you explain what the following Python 3 function does
def parse_bound_data(self, tmin0, tmax0, specimen):
        if specimen not in self.Data:
            print(
                ("no measurement data found loaded for specimen %s and will be ignored" % (specimen)))
            return (None, None)
        if self.Data[specimen]['measurement_step_unit'] == "C":
            if float(tmin0) == 0 or float(tmin0) == 273:
                tmin = "0"
            else:
                tmin = "%.0fC" % (float(tmin0)-273)
            if float(tmax0) == 0 or float(tmax0) == 273:
                tmax = "0"
            else:
                tmax = "%.0fC" % (float(tmax0)-273)
        elif self.Data[specimen]['measurement_step_unit'] == "mT":
            if float(tmin0) == 0:
                tmin = "0"
            else:
                tmin = "%.1fmT" % (float(tmin0)*1000)
            if float(tmax0) == 0:
                tmax = "0"
            else:
                tmax = "%.1fmT" % (float(tmax0)*1000)
        else:  # combimned experiment T:AF
            if float(tmin0) == 0:
                tmin = "0"
            elif "%.0fC" % (float(tmin0)-273) in self.Data[specimen]['zijdblock_steps']:
                tmin = "%.0fC" % (float(tmin0)-273)
            elif "%.1fmT" % (float(tmin0)*1000) in self.Data[specimen]['zijdblock_steps']:
                tmin = "%.1fmT" % (float(tmin0)*1000)
            else:
                tmin = None
            if float(tmax0) == 0:
                tmax = "0"
            elif "%.0fC" % (float(tmax0)-273) in self.Data[specimen]['zijdblock_steps']:
                tmax = "%.0fC" % (float(tmax0)-273)
            elif "%.1fmT" % (float(tmax0)*1000) in self.Data[specimen]['zijdblock_steps']:
                tmax = "%.1fmT" % (float(tmax0)*1000)
            else:
                tmax = None
        return tmin, tmax

Response:
This function converts the input temperature and upper bound values from the MagIC and Redo format to that of Celsius and MilliTesla which is often more intuitive and returns the minimum and maximum values for the current is
           .


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_indices(self, fit=None, tmin=None, tmax=None, specimen=None):
        if specimen == None:
            specimen = self.s
        if fit and not tmin and not tmax:
            tmin = fit.tmin
            tmax = fit.tmax
        if specimen not in list(self.Data.keys()):
            self.user_warning("No data for specimen " + specimen)
        if tmin in self.Data[specimen]['zijdblock_steps']:
            tmin_index = self.Data[specimen]['zijdblock_steps'].index(tmin)
        elif type(tmin) == str or type(tmin) == str and tmin != '':
            int_steps = [float(x.strip("C mT"))
                         for x in self.Data[specimen]['zijdblock_steps']]
            if tmin == '':
                tmin = self.Data[specimen]['zijdblock_steps'][0]
                print(("No lower bound for %s on specimen %s using lowest step (%s) for lower bound" % (
                    fit.name, specimen, tmin)))
                if fit != None:
                    fit.tmin = tmin
            int_tmin = float(tmin.strip("C mT"))
            diffs = [abs(x-int_tmin) for x in int_steps]
            tmin_index = diffs.index(min(diffs))
        else:
            tmin_index = self.tmin_box.GetSelection()
        if tmax in self.Data[specimen]['zijdblock_steps']:
            tmax_index = self.Data[specimen]['zijdblock_steps'].index(tmax)
        elif type(tmax) == str or type(tmax) == str and tmax != '':
            int_steps = [float(x.strip("C mT"))
                         for x in self.Data[specimen]['zijdblock_steps']]
            if tmax == '':
                tmax = self.Data[specimen]['zijdblock_steps'][-1]
                print(("No upper bound for fit %s on specimen %s using last step (%s) for upper bound" % (
                    fit.name, specimen, tmax)))
                if fit != None:
                    fit.tmax = tmax
            int_tmax = float(tmax.strip("C mT"))
            diffs = [abs(x-int_tmax) for x in int_steps]
            tmax_index = diffs.index(min(diffs))
        else:
            tmax_index = self.tmin_box.GetSelection()

        max_index = len(self.Data[specimen]['zijdblock_steps'])-1
        while (self.Data[specimen]['measurement_flag'][max_index] == 'b' and max_index-1 > 0):
            max_index -= 1

        if tmin_index >= max_index:
            print(("lower bound is greater or equal to max step cannot determine bounds for specimen: " + specimen))
            return (None, None)

        if (tmin_index >= 0):
            while (self.Data[specimen]['measurement_flag'][tmin_index] == 'b' and
                   tmin_index+1 < len(self.Data[specimen]['zijdblock_steps'])):
                if (self.Data[specimen]['zijdblock_steps'][tmin_index+1] == tmin):
                    tmin_index += 1
                else:
                    tmin_old = tmin
                    while (self.Data[specimen]['measurement_flag'][tmin_index] == 'b' and
                           tmin_index+1 < len(self.Data[specimen]['zijdblock_steps'])):
                        tmin_index += 1
                    tmin = self.Data[specimen]['zijdblock_steps'][tmin_index]
                    if fit != None:
                        fit.tmin = tmin
                    self.tmin_box.SetStringSelection(tmin)
                    print(("For specimen " + str(specimen) + " there are no good measurement steps with value - " +
                           str(tmin_old) + " using step " + str(tmin) + " as lower bound instead"))
                    break

        if (tmax_index < max_index):
            while (self.Data[specimen]['measurement_flag'][tmax_index] == 'b' and
                   tmax_index+1 < len(self.Data[specimen]['zijdblock_steps'])):
                if (self.Data[specimen]['zijdblock_steps'][tmax_index+1] == tmax):
                    tmax_index += 1
                else:
                    tmax_old = tmax
                    while (self.Data[specimen]['measurement_flag'][tmax_index] == 'b' and
                           tmax_index >= 0):
                        tmax_index -= 1
                    tmax = self.Data[specimen]['zijdblock_steps'][tmax_index]
                    if fit != None:
                        fit.tmax = tmax
                    self.tmax_box.SetStringSelection(tmax)
                    print(("For specimen " + str(specimen) + " there are no good measurement steps with value - " +
                           str(tmax_old) + " using step " + str(tmax) + " as upper bound instead"))
                    break

        if (tmin_index < 0):
            tmin_index = 0
        if (tmax_index > max_index):
            tmax_index = max_index

        return (tmin_index, tmax_index)

Response: Finds the appropriate indices in the order of the indecies in the given order of the indecies in the given specimen.


Instruction:
Implement a function in Python 3 to
merge a list of dictionaries with the keys in the old_recs and returns a list of dictionaries with the same keys as all the others.

Response:
def merge_pmag_recs(self, old_recs):
        """
        Takes in a list of dictionaries old_recs and returns a list of
        dictionaries where every dictionary in the returned list has the
        same keys as all the others.

        Parameters
        ----------
        old_recs : list of dictionaries to fix

        Returns
        -------
        recs : list of dictionaries with same keys
        """
        recs = {}
        recs = deepcopy(old_recs)
        headers = []
        for rec in recs:
            for key in list(rec.keys()):
                if key not in headers:
                    headers.append(key)
        for rec in recs:
            for header in headers:
                if header not in list(rec.keys()):
                    rec[header] = ""
        return recs


Instruction:
Implement a Python 3 function for
selecting the specimen and sets the current GUI specimen to the specimen.

Response:
def select_specimen(self, specimen):
        """
        Goes through the calculations necessary to plot measurement data for
        specimen and sets specimen as current GUI specimen, also attempts to
        handle changing current fit.
        """
        try:
            fit_index = self.pmag_results_data['specimens'][self.s].index(
                self.current_fit)
        except KeyError:
            fit_index = None
        except ValueError:
            fit_index = None
        # sets self.s to specimen calculates params etc.
        self.initialize_CART_rot(specimen)
        self.list_bound_loc = 0
        if fit_index != None and self.s in self.pmag_results_data['specimens']:
            try:
                self.current_fit = self.pmag_results_data['specimens'][self.s][fit_index]
            except IndexError:
                self.current_fit = None
        else:
            self.current_fit = None
        if self.s != self.specimens_box.GetValue():
            self.specimens_box.SetValue(self.s)


Instruction:
Create a Python 3 function for
clearing all interpretations in the current directory

Response:
def clear_interpretations(self, message=None):
        """
        Clears all specimen interpretations

        Parameters
        ----------
        message : message to display when warning the user that all
        fits will be deleted. If None default message is used (None is
        default)
        """
        if self.total_num_of_interpertations() == 0:
            print("There are no interpretations")
            return True

        if message == None:
            message = "All interpretations will be deleted all unsaved data will be irretrievable, continue?"
        dlg = wx.MessageDialog(self, caption="Delete?",
                               message=message, style=wx.OK | wx.CANCEL)
        result = self.show_dlg(dlg)
        dlg.Destroy()
        if result != wx.ID_OK:
            return False

        for specimen in list(self.pmag_results_data['specimens'].keys()):
            self.pmag_results_data['specimens'][specimen] = []
            # later on when high level means are fixed remove the bellow loop and loop over pmag_results_data
            for high_level_type in ['samples', 'sites', 'locations', 'study']:
                self.high_level_means[high_level_type] = {}
        self.current_fit = None
        if self.ie_open:
            self.ie.update_editor()
        return True


Instruction:
Implement a function in Python 3 to
mark the g_index'th measuremnt of current specimen good

Response:
def mark_meas_good(self, g_index):
        """
        Marks the g_index'th measuremnt of current specimen good

        Parameters
        ----------
        g_index : int that gives the index of the measurement to mark good,
            indexed from 0
        """
        meas_index, ind_data = 0, []
        for i, meas_data in enumerate(self.mag_meas_data):
            if meas_data['er_specimen_name'] == self.s:
                ind_data.append(i)
        meas_index = ind_data[g_index]

        self.Data[self.s]['measurement_flag'][g_index] = 'g'
        if len(self.Data[self.s]['zijdblock'][g_index]) < 6:
            self.Data[self.s]['zijdblock'][g_index].append('g')
        self.Data[self.s]['zijdblock'][g_index][5] = 'g'
        if 'zijdblock_geo' in self.Data[self.s] and g_index < len(self.Data[self.s]['zijdblock_geo']):
            if len(self.Data[self.s]['zijdblock_geo'][g_index]) < 6:
                self.Data[self.s]['zijdblock_geo'][g_index].append('g')
            self.Data[self.s]['zijdblock_geo'][g_index][5] = 'g'
        if 'zijdblock_tilt' in self.Data[self.s] and g_index < len(self.Data[self.s]['zijdblock_tilt']):
            if len(self.Data[self.s]['zijdblock_tilt'][g_index]) < 6:
                self.Data[self.s]['zijdblock_tilt'][g_index].append('g')
            self.Data[self.s]['zijdblock_tilt'][g_index][5] = 'g'
        self.mag_meas_data[meas_index]['measurement_flag'] = 'g'

        if self.data_model == 3.0:
            meas_name = str(self.Data[self.s]['measurement_names'][g_index])
            mdf = self.con.tables['measurements'].df
            # check for multiple measurements with the same name
            if not isinstance(mdf.loc[meas_name], pd.Series):
                res = self.user_warning("Your measurements table has non-unique measurement names.\nYou may end up marking more than one measurement as good.\nRight click this measurement again to undo.")
            # mark measurement as good
            mdf.loc[meas_name, 'quality'] = 'g'


Instruction:
Here you have a function in Python 3, explain what it does
def mark_fit_good(self, fit, spec=None):
        if spec == None:
            for spec, fits in list(self.pmag_results_data['specimens'].items()):
                if fit in fits:
                    break
        samp = self.Data_hierarchy['sample_of_specimen'][spec]
        if 'sample_orientation_flag' not in self.Data_info['er_samples'][samp]:
            self.Data_info['er_samples'][samp]['sample_orientation_flag'] = 'g'
        samp_flag = self.Data_info['er_samples'][samp]['sample_orientation_flag']
        if samp_flag == 'g':
            self.bad_fits.remove(fit)
            return True
        else:
            self.user_warning(
                "Cannot mark this interpretation good its sample orientation has been marked bad")
            return False

Response: Mark a fit good so it is used in high level means


Instruction:
Given the following Python 3 function, write the documentation
def mark_fit_bad(self, fit):
        if fit not in self.bad_fits:
            self.bad_fits.append(fit)
            return True
        else:
            return False

Response: Mark a fit bad so it is excluded from high level means