Instruction:
How would you code a function in Python 3 to
make a map of vgps and a95/dp,dm for site means in a sites table Parameters ---------- dir_path : str, default "." input directory path results_file : str, default "sites.txt" name of MagIC format sites file crd : str, default "" coordinate system [g, t] (geographic, tilt_corrected) sym : str, default "ro" symbol color and shape, default red circles (see matplotlib documentation for more color/shape options) size : int, default 8 symbol size rsym : str, default "g^" symbol for plotting reverse poles (see matplotlib documentation for more color/shape options) rsize : int, default 8 symbol size for reverse poles fmt : str, default "pdf" format for figures, ["svg", "jpg", "pdf", "png"] res : str, default "c" resolution [c, l, i, h] (crude, low, intermediate, high) proj : str, default "ortho" ortho = orthographic lcc = lambert conformal moll = molweide merc = mercator flip : bool, default False if True, flip reverse poles to normal antipode anti : bool, default False if True, plot antipodes for each pole fancy : bool, default False if True, plot topography (not yet implemented) ell : bool, default False if True, plot ellipses ages : bool, default False if True, plot ages lat_0 : float, default 0. eyeball latitude lon_0 : float, default 0. eyeball longitude save_plots : bool, default True if True, create and save all requested plots interactive : bool, default False if True, interactively plot and display (this is best used on the command line only) Returns --------- (status, output_files) - Tuple : (True or False indicating if conversion was sucessful, file name(s) written)

Response:
def vgpmap_magic(dir_path=".", results_file="sites.txt", crd="",
                 sym='ro', size=8, rsym="g^", rsize=8,
                 fmt="pdf", res="c", proj="ortho",
                 flip=False, anti=False, fancy=False,
                 ell=False, ages=False, lat_0=0, lon_0=0,
                 save_plots=True, interactive=False, contribution=None):
    """
    makes a map of vgps and a95/dp,dm for site means in a sites table

    Parameters
    ----------
    dir_path : str, default "."
        input directory path
    results_file : str, default "sites.txt"
        name of MagIC format sites file
    crd : str, default ""
       coordinate system [g, t] (geographic, tilt_corrected)
    sym : str, default "ro"
        symbol color and shape, default red circles
        (see matplotlib documentation for more color/shape options)
    size : int, default 8
        symbol size
    rsym : str, default "g^"
        symbol for plotting reverse poles
        (see matplotlib documentation for more color/shape options)
    rsize : int, default 8
        symbol size for reverse poles
    fmt : str, default "pdf"
        format for figures, ["svg", "jpg", "pdf", "png"]
    res : str, default "c"
        resolution [c, l, i, h] (crude, low, intermediate, high)
    proj : str, default "ortho"
        ortho = orthographic
        lcc = lambert conformal
        moll = molweide
        merc = mercator
    flip : bool, default False
        if True, flip reverse poles to normal antipode
    anti : bool, default False
        if True, plot antipodes for each pole
    fancy : bool, default False
        if True, plot topography (not yet implemented)
    ell : bool, default False
        if True, plot ellipses
    ages : bool, default False
        if True, plot ages
    lat_0 : float, default 0.
        eyeball latitude
    lon_0 : float, default 0.
        eyeball longitude
    save_plots : bool, default True
        if True, create and save all requested plots
    interactive : bool, default False
       if True, interactively plot and display
        (this is best used on the command line only)

    Returns
    ---------
    (status, output_files) - Tuple : (True or False indicating if conversion was sucessful, file name(s) written)

    """
    coord_dict = {'g': 0, 't': 100}
    coord = coord_dict[crd] if crd else ""
    if contribution is None:
        con = cb.Contribution(dir_path, single_file=results_file)
    else:
        con = contribution
    if not list(con.tables.keys()):
        print("-W - Couldn't read in data")
        return False, []
    if 'sites' not in con.tables:
        print("-W - No sites data")
        return False, []

    FIG = {'map': 1}
    pmagplotlib.plot_init(FIG['map'], 6, 6)
    # read in sites file
    lats, lons = [], []
    Pars = []
    dates, rlats, rlons = [], [], []

    site_container = con.tables['sites']
    site_container.front_and_backfill(['location'])
    site_df = site_container.df
    # use records with vgp_lat and vgp_lon
    if 'vgp_lat' in site_df.columns and 'vgp_lon' in site_df.columns:
        cond1, cond2 = site_df['vgp_lat'].notnull(), site_df['vgp_lon'].notnull()
    else:
        print ('nothing to plot')
        sys.exit()
    Results = site_df[cond1 & cond2]
    # use tilt correction
    if coord and 'dir_tilt_correction' in Results.columns:
        Results = Results[Results['dir_tilt_correction'] == coord]
    # get location name and average ages
    locs = Results['location'].dropna().unique()
    if len(locs):
        location = ":".join(Results['location'].unique())
    else:
        location = ""
    if 'age' in Results.columns and ages == 1:
        dates = Results['age'].unique()

    # go through rows and extract data
    for ind, row in Results.iterrows():
        try:
            lat, lon = float(row['vgp_lat']), float(row['vgp_lon'])
        except ValueError:
            lat = float(str(row['vgp_lat']).replace(' ', '').translate({0x2c: '.', 0xa0: None, 0x2212: '-'}))
            lon = float(str(row['vgp_lon']).replace(' ', '').translate({0x2c: '.', 0xa0: None, 0x2212: '-'}))
        if anti == 1:
            lats.append(-lat)
            lon = lon + 180.
            if lon > 360:
                lon = lon - 360.
            lons.append(lon)
        elif flip == 0:
            lats.append(lat)
            lons.append(lon)
        elif flip == 1:
            if lat < 0:
                rlats.append(-lat)
                lon = lon + 180.
                if lon > 360:
                    lon = lon - 360
                rlons.append(lon)
            else:
                lats.append(lat)
                lons.append(lon)

        ppars = []
        ppars.append(lon)
        ppars.append(lat)
        ell1, ell2 = "", ""
        if 'vgp_dm' in list(row.keys()) and row['vgp_dm']:
            ell1 = float(row['vgp_dm'])
        if 'vgp_dp' in list(row.keys()) and row['vgp_dp']:
            ell2 = float(row['vgp_dp'])
        if 'vgp_alpha95' in list(row.keys()) and (row['vgp_alpha95'] or row['vgp_alpha95'] == 0):
            ell1, ell2 = float(row['vgp_alpha95']), float(row['vgp_alpha95'])
        if ell1 and ell2:
            ppars = []
            ppars.append(lons[-1])
            ppars.append(lats[-1])
            ppars.append(ell1)
            ppars.append(lons[-1])
            try:
                isign = abs(lats[-1]) / lats[-1]
            except ZeroDivisionError:
                isign = 1
            ppars.append(lats[-1] - isign * 90.)
            ppars.append(ell2)
            ppars.append(lons[-1] + 90.)
            ppars.append(0.)
            Pars.append(ppars)

    location = location.strip(':')
    Opts = {'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360.,
            'lat_0': lat_0, 'lon_0': lon_0, 'proj': proj, 'sym': 'bs',
            'symsize': 3, 'pltgrid': 0, 'res': res, 'boundinglat': 0.}
    Opts['details'] = {'coasts': 1, 'rivers': 0, 'states': 0,
                       'countries': 0, 'ocean': 1, 'fancy': fancy}
    # make the base map with a blue triangle at the pole
    pmagplotlib.plot_map(FIG['map'], [90.], [0.], Opts)
    Opts['pltgrid'] = -1
    Opts['sym'] = sym
    Opts['symsize'] = size
    if len(dates) > 0:
        Opts['names'] = dates
    if len(lats) > 0:
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], lats, lons, Opts)
    Opts['names'] = []
    if len(rlats) > 0:
        Opts['sym'] = rsym
        Opts['symsize'] = rsize
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], rlats, rlons, Opts)
    if not save_plots and not set_env.IS_WIN:
        pmagplotlib.draw_figs(FIG)
    if ell == 1:  # add ellipses if desired.
        Opts['details'] = {'coasts': 0, 'rivers': 0, 'states': 0,
                           'countries': 0, 'ocean': 0, 'fancy': fancy}
        Opts['pltgrid'] = -1  # turn off meridian replotting
        Opts['symsize'] = 2
        Opts['sym'] = 'g-'
        for ppars in Pars:
            if ppars[2] != 0:
                PTS = pmagplotlib.plot_ell(FIG['map'], ppars, 'g.', 0, 0)
                elats, elons = [], []
                for pt in PTS:
                    elons.append(pt[0])
                    elats.append(pt[1])
                # make the base map with a blue triangle at the pole
                pmagplotlib.plot_map(FIG['map'], elats, elons, Opts)
                if not save_plots and not set_env.IS_WIN:
                    pmagplotlib.draw_figs(FIG)
    files = {}
    for key in list(FIG.keys()):
        if pmagplotlib.isServer:  # use server plot naming convention
            files[key] = 'LO:_' + location + '_TY:_VGP_map.' + fmt
            con.add_magic_table('contribution')
            con_id = con.get_con_id()
            if con_id:
                files[key] = 'MC:_' + str(con_id) + '_' + files[key]
        else:  # use more readable naming convention
            files[key] = '{}_VGP_map.{}'.format(location, fmt)

    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['map'] = location + ' VGP map'
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    elif interactive:
        pmagplotlib.draw_figs(FIG)
        ans = input(" S[a]ve to save plot, Return to quit:  ")
        if ans == "a":
            pmagplotlib.save_plots(FIG, files)
            return True, files.values()
        else:
            print("Good bye")
            return True, []
    elif save_plots:
        pmagplotlib.save_plots(FIG, files)
        return True, files.values()


Instruction:
Write a Python 3 script to
function that plots a histogram of the data in infile.

Response:
def histplot(infile="", data=(), outfile="",
             xlab='x', binsize=False, norm=1,
             fmt='svg', save_plots=True, interactive=False):
    """
    makes histograms for data

    Parameters
    ----------
    infile : str, default ""
        input file name
        format: single variable
    data : list-like, default ()
        list/array of values to plot if infile is not provided
    outfile : str, default ""
        name for plot, if not provided defaults to hist.FMT
    xlab : str, default 'x'
        label for x axis
    binsize : int, default False
        desired binsize.  if not specified, an appropriate binsize will be calculated.
    norm : int, default 1
        1: norm, 0: don't norm, -1: show normed and non-normed axes
    fmt : str, default "svg"
        format for figures, ["svg", "jpg", "pdf", "png"]
    save_plots : bool, default True
        if True, create and save all requested plots
    interactive : bool, default False
        interactively plot and display
        (this is best used on the command line only)
    """
    # set outfile name
    if outfile:
        fmt = ""
    else:
        outfile = 'hist.'+fmt
    # read in data from infile or use data argument
    if os.path.exists(infile):
        D = np.loadtxt(infile)
    else:
        D = np.array(data)
    try:
        if not len(D):
            print('-W- No data found')
            return False, []
    except ValueError:
        pass
    fig = pmagplotlib.plot_init(1, 8, 7)
    try:
        len(D)
    except TypeError:
        D = np.array([D])
    if len(D) < 5:
        print("-W- Not enough points to plot histogram ({} point(s) provided, 5 required)".format(len(D)))
        return False, []

    # if binsize not provided, calculate reasonable binsize
    if not binsize:
        binsize = int(np.around(1 + 3.22 * np.log(len(D))))
    binsize = int(binsize)
    Nbins = int(len(D) / binsize)
    ax = fig.add_subplot(111)
    if norm == 1:
        print('normalizing')
        n, bins, patches = ax.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=True)
        ax.set_ylabel('Frequency')
    elif norm == 0:
        print('not normalizing')
        n, bins, patches = ax.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=False)
        ax.set_ylabel('Number')
    elif norm == -1:
        #print('trying twin')
        n, bins, patches = ax.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=True)
        ax.set_ylabel('Frequency')
        ax2 = ax.twinx()
        n, bins, patches = ax2.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=False)
        ax2.set_ylabel('Number', rotation=-90)
    plt.axis([D.min(), D.max(), 0, n.max()+.1*n.max()])
    ax.set_xlabel(xlab)
    name = 'N = ' + str(len(D))
    plt.title(name)
    if interactive:
        pmagplotlib.draw_figs({1: 'hist'})
        p = input('s[a]ve to save plot, [q]uit to exit without saving  ')
        if p != 'a':
            return True, []
        plt.savefig(outfile)
        print('plot saved in ', outfile)
        return True, [outfile]
    if pmagplotlib.isServer:
        pmagplotlib.add_borders({'hist': 1}, {'hist': 'Intensity Histogram'})
    if save_plots:
        plt.savefig(outfile)
        print('plot saved in ', outfile)
        return True, [outfile]


Instruction:
Given the following Python 3 function, write the documentation
def parse_fits(self, fit_name):
        '''USE PARSE_ALL_FITS unless otherwise necessary
        Isolate fits by the name of the fit; we also set 'specimen_tilt_correction' to zero in order
        to only include data in geographic coordinates - THIS NEEDS TO BE GENERALIZED
        '''
        fits = self.fits.loc[self.fits.specimen_comp_name ==
                             fit_name].loc[self.fits.specimen_tilt_correction == 0]
        fits.reset_index(inplace=True)
        means = self.means.loc[self.means.site_comp_name ==
                               fit_name].loc[self.means.site_tilt_correction == 0]
        means.reset_index(inplace=True)
        mean_name = str(fit_name) + "_mean"
        setattr(self, fit_name, fits)
        setattr(self, mean_name, means)

Response:
USE PARSE_ALL_FITS unless otherwise necessary
        Isolate fits by the name of the fit ; we also set specimen_tilt_correction to zero in order


Instruction:
Make a summary of the following Python 3 code
def main():
    #
    # initialize variables
    #
    #
    #
    dir_path='.'
    if "-WD" in sys.argv:
        ind=sys.argv.index("-WD")
        dir_path=sys.argv[ind+1]
    meas_file,spec_file= dir_path+"/magic_measurements.txt",dir_path+"/er_specimens.txt"
    out_file=meas_file
    MeasRecs,SpecRecs=[],[]
    OutRecs=[]
    if "-h" in sys.argv:
        print(main.__doc__)
        sys.exit()
    if "-f" in sys.argv:
        ind=sys.argv.index("-f")
        meas_file=dir_path+'/'+sys.argv[ind+1]
    if "-fsp" in sys.argv:
        ind=sys.argv.index("-fsp")
        spec_file=dir_path+'/'+sys.argv[ind+1]
    if "-F" in sys.argv:
        ind=sys.argv.index("-F")
        out_file=dir_path+'/'+sys.argv[ind+1]
    MeasRecs,file_type=pmag.magic_read(meas_file)
    Specs,file_type=pmag.magic_read(spec_file)
    for rec in MeasRecs:
        if 'measurement_magn_moment' in list(rec.keys()) and rec['measurement_magn_moment'] != "":
            for spec in Specs:
                if spec['er_specimen_name']==rec['er_specimen_name']:
                    if 'specimen_weight' in list(spec.keys()) and spec['specimen_weight']!="":
                        rec['measurement_magn_mass']='%e'%(old_div(float(rec['measurement_magn_moment']),float(spec['specimen_weight'])))
                    if 'specimen_volume' in list(spec.keys()) and spec['specimen_volume']!="":
                        rec['measurement_magn_volume']='%e'%(old_div(float(rec['measurement_magn_moment']),float(spec['specimen_volume'])))
                    break
        if 'measurement_magn_volume' not in list(rec.keys()): rec['measurement_magn_volume']=''
        if 'measurement_magn_mass' not in list(rec.keys()): rec['measurement_magn_mass']=''
        OutRecs.append(rec)
    pmag.magic_write(out_file,OutRecs,"magic_measurements")
    print("Data saved in ", out_file)

Response:
NAME measurements_normalize. py DESCRIPTION

    takes magic_measurements file and normalized moment by sample weight and sample volume in the er_specimens table

    returns a list of dicts each containing the name of the unique item in the table that contains the unique item in the order they appear in the measurements file.


Instruction:
Write a Python 3 script for
shutting down application if in the main frame. otherwise, destroy the top window (wind) and restore the main frame.

Response:
def on_quit(self, event, wind=None):
        """
        shut down application if in the main frame.
        otherwise, destroy the top window (wind) and restore
        the main frame.
        """
        if wind:
            wind.Destroy()
        if not self.parent.IsShown():
            self.on_show_mainframe(None)
            # re-do the quit binding
            self.parent.Bind(wx.EVT_MENU, self.on_quit, self.file_quit)
        else:
            self.parent.Close()


Instruction:
Given the following Python 3 function, write the documentation
def on_clear(self, event):
        dia = pmag_menu_dialogs.ClearWD(self.parent, self.parent.WD)
        clear = dia.do_clear()
        if clear:
            # clear directory, but use previously acquired data_model
            if self.data_model_num == 2.5:
                self.parent.er_magic = builder.ErMagicBuilder(self.parent.WD, self.parent.er_magic.data_model)
            elif self.data_model_num == 3:
                self.parent.contribution = cb.Contribution(self.parent.WD,
                                                           dmodel=self.parent.contribution.data_model)

Response: clear the working directory


Instruction:
How would you code a function in Python 3 to
name plotxy_magic.py DESCRIPTION Makes simple X,Y plots INPUT FORMAT Any MagIC formatted file SYNTAX plotxy_magic.py [command line options] OPTIONS -h prints this help message -f FILE to set file name on command rec -c col1 col2 specify columns names to plot -sym SYM SIZE specify symbol and size to plot: default is red dots -S don't plot symbols -xlab XLAB -ylab YLAB -l connect symbols with lines -b xmin xmax ymin ymax, sets bounds # -b [key:max:min,key:max:min,etc.] leave or min blank for no cutoff

Response:
def main():
    """
    NAME
       plotxy_magic.py

    DESCRIPTION
       Makes simple X,Y plots

    INPUT FORMAT
       Any MagIC formatted file

    SYNTAX
       plotxy_magic.py [command line options]

    OPTIONS
        -h prints this help message
        -f FILE to set file name on command rec
        -c col1 col2 specify columns names to plot
        -sym SYM SIZE specify symbol and size to plot: default is red dots
        -S   don't plot symbols
        -xlab XLAB
        -ylab YLAB
        -l  connect symbols with lines
        -b xmin xmax ymin ymax, sets bounds
#        -b [key:max:min,key:max:min,etc.] leave or min blank for no cutoff
    """
    col1,col2=0,1
    sym,size = 'ro',20
    xlab,ylab='',''
    lines=0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
    else:
        '-f option is a required field'
        print(main.__doc__)
        sys.exit()
    if '-c' in sys.argv:
        ind=sys.argv.index('-c')
        col1=sys.argv[ind+1]
        col2=sys.argv[ind+2]
    else:
        'Column headers a required field'
        print(main.__doc__)
        sys.exit()
    if '-xlab' in sys.argv:
        ind=sys.argv.index('-xlab')
        xlab=sys.argv[ind+1]
    if '-ylab' in sys.argv:
        ind=sys.argv.index('-ylab')
        ylab=sys.argv[ind+1]
#    if '-b' in sys.argv:
#        ind=sys.argv.index('-b')
#        bounds=sys.argv[ind+1].split(',')
    if '-b' in sys.argv:
        ind=sys.argv.index('-b')
        xmin=float(sys.argv[ind+1])
        xmax=float(sys.argv[ind+2])
        ymin=float(sys.argv[ind+3])
        ymax=float(sys.argv[ind+4])
    if '-sym' in sys.argv:
        ind=sys.argv.index('-sym')
        sym=sys.argv[ind+1]
        size=int(sys.argv[ind+2])
    if '-l' in sys.argv: lines=1
    if '-S' in sys.argv: sym=''
    X,Y=[],[]
    data,file_type=pmag.magic_read(file)
    print(file_type)
    for rec in data:
        if col1 not in list(rec.keys()) or col2 not in list(rec.keys()):
            print(col1,' and/or ',col2, ' not in file headers')
            print('try again')
            sys.exit()
        if rec[col1]!='' and rec[col2]!='':
            skip=0
            if '-crit' in sys.argv:
                for crit in bounds:
                    crits=crit.split(':')
                    crit_key=crits[0]
                    crit_min=crits[1]
                    crit_max=crits[2]
                    if rec[crit_key]=="":
                        skip=1
                    else:
                        if crit_min!="" and float(rec[crit_key])<float(crit_min):skip=1
                        if crit_max!="" and float(rec[crit_key])>float(crit_min):skip=1
            if skip==0:
                X.append(float(rec[col1]))
                Y.append(float(rec[col2]))
    if len(X)==0:
            print(col1,' and/or ',col2, ' have no data ')
            print('try again')
            sys.exit()
    else:
        print(len(X),' data points')
    if sym!='':pylab.scatter(X,Y,c=sym[0],marker=sym[1],s=size)
    if xlab!='':pylab.xlabel(xlab)
    if ylab!='':pylab.ylabel(ylab)
    if lines==1:pylab.plot(X,Y,'k-')
    if '-b' in sys.argv:pylab.axis([xmin,xmax,ymin,ymax])
    pylab.draw()
    ans=input("Press return to quit  ")
    sys.exit()


Instruction:
Explain what the following Python 3 code does
def main():
    fmt, plot = 'svg', 0
    FIG = {}  # plot dictionary
    FIG['lowrie'] = 1  # demag is figure 1
    pmagplotlib.plot_init(FIG['lowrie'], 6, 6)
    norm = 1  # default is to normalize by maximum axis
    if len(sys.argv) > 1:
        if '-h' in sys.argv:
            print(main.__doc__)
            sys.exit()
        if '-N' in sys.argv:
            norm = 0  # don't normalize
        if '-sav' in sys.argv:
            plot = 1  # don't normalize
        if '-fmt' in sys.argv:  # sets input filename
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        if '-f' in sys.argv:  # sets input filename
            ind = sys.argv.index("-f")
            in_file = sys.argv[ind + 1]
        else:
            print(main.__doc__)
            print('you must supply a file name')
            sys.exit()
    else:
        print(main.__doc__)
        print('you must supply a file name')
        sys.exit()
    data = pmag.open_file(in_file)
    PmagRecs = []  # set up a list for the results
    keys = ['specimen', 'treatment', 'csd', 'M', 'dec', 'inc']
    for line in data:
        PmagRec = {}
        rec = line.replace('\n', '').split()
        for k in range(len(keys)):
            PmagRec[keys[k]] = rec[k]
        PmagRecs.append(PmagRec)
    specs = pmag.get_dictkey(PmagRecs, 'specimen', '')
    sids = []
    for spec in specs:
        if spec not in sids:
            sids.append(spec)  # get list of unique specimen names
    for spc in sids:  # step through the specimen names
        pmagplotlib.plot_init(FIG['lowrie'], 6, 6)
        print(spc)
        specdata = pmag.get_dictitem(
            PmagRecs, 'specimen', spc, 'T')  # get all this one's data
        DIMs, Temps = [], []
        for dat in specdata:  # step through the data
            DIMs.append([float(dat['dec']), float(
                dat['inc']), float(dat['M']) * 1e-3])
            Temps.append(float(dat['treatment']))
        carts = pmag.dir2cart(DIMs).transpose()
        # if norm==1: # want to normalize
        #    nrm=max(max(abs(carts[0])),max(abs(carts[1])),max(abs(carts[2]))) # by maximum of x,y,z values
        #    ylab="M/M_max"
        if norm == 1:  # want to normalize
            nrm = (DIMs[0][2])  # normalize by NRM
            ylab = "M/M_o"
        else:
            nrm = 1.  # don't normalize
            ylab = "Magnetic moment (Am^2)"
        xlab = "Temperature (C)"
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[0]), nrm), sym='r-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[0]), nrm), sym='ro')  # X direction
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[1]), nrm), sym='c-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[1]), nrm), sym='cs')  # Y direction
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[2]), nrm), sym='k-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[2]), nrm), sym='k^', title=spc, xlab=xlab, ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt}
        if plot == 0:
            pmagplotlib.draw_figs(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.save_plots(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.save_plots(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])

Response:
NAME
aptcha. py is the main function for the Lowrie experiment.


Instruction:
Write a Python 3 script for
naming apwp.py DESCRIPTION returns predicted paleolatitudes, directions and pole latitude/longitude from apparent polar wander paths of Besse and Courtillot (2002). SYNTAX apwp.py [command line options][< filename] OPTIONS -h prints help message and quits -i allows interactive data entry f file: read plate, lat, lon, age data from file -F output_file: write output to output_file -P [NA, SA, AF, IN, EU, AU, ANT, GL] plate -lat LAT specify present latitude (positive = North; negative=South) -lon LON specify present longitude (positive = East, negative=West) -age AGE specify Age in Ma Note: must have all -P, -lat, -lon, -age or none. OUTPUT Age Paleolat. Dec. Inc. Pole_lat. Pole_Long.

Response:
def main():
    """
    NAME
        apwp.py

    DESCRIPTION
        returns predicted paleolatitudes, directions and pole latitude/longitude
        from apparent polar wander paths of Besse and Courtillot (2002).

    SYNTAX
        apwp.py [command line options][< filename]

    OPTIONS
        -h prints help message and quits
        -i allows interactive data entry
        f file: read plate, lat, lon, age data from file
        -F output_file: write output to output_file
        -P [NA, SA, AF, IN, EU, AU, ANT, GL] plate
        -lat LAT specify present latitude (positive = North; negative=South)
        -lon LON specify present longitude (positive = East, negative=West)
        -age AGE specify Age in Ma

     Note:  must have all -P, -lat, -lon, -age or none.

     OUTPUT
        Age  Paleolat.  Dec.  Inc.  Pole_lat.  Pole_Long.

    """
    infile,outfile,data,indata="","",[],[]
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        outfile=sys.argv[ind+1]
        out=open(outfile,'w')
    if '-i' in sys.argv:
        print("Welcome to paleolatitude calculator\n")
        while 1:
            data=[]
            print("pick a plate: NA, SA, AF, IN, EU, AU, ANT, GL \n   cntl-D to quit")
            try:
                plate=input("Plate\n").upper()
            except:
                print("Goodbye \n")
                sys.exit()
            lat=float(input( "Site latitude\n"))
            lon=float(input(" Site longitude\n"))
            age=float(input(" Age\n"))
            data=[plate,lat,lon,age]
            print("Age  Paleolat.  Dec.  Inc.  Pole_lat.  Pole_Long.")
            print(spitout(data))
    elif '-f' in sys.argv:
        ind=sys.argv.index('-f')
        infile=sys.argv[ind+1]
        f=open(infile,'r')
        inp=f.readlines()
    elif '-P' in sys.argv:
        ind=sys.argv.index('-P')
        plate=sys.argv[ind+1].upper()
        if '-lat' in sys.argv:
            ind=sys.argv.index('-lat')
            lat=float(sys.argv[ind+1])
        else:
            print(main.__doc__)
            sys.exit()
        if '-lon' in sys.argv:
            ind=sys.argv.index('-lon')
            lon=float(sys.argv[ind+1])
        else:
            print(main.__doc__)
            sys.exit()
        if '-age' in sys.argv:
            ind=sys.argv.index('-age')
            age=float(sys.argv[ind+1])
        else:
            print(main.__doc__)
            sys.exit()
        data=[plate,lat,lon,age]
        outstring=spitout(data)
        if outfile=="":
            print("Age  Paleolat.  Dec.  Inc.  Pole_lat.  Pole_Long.")
            print(outstring)
        else:
            out.write(outstring)
        sys.exit()
    else:
        inp=sys.stdin.readlines() # read from standard input
    if len(inp)>0:
      for line in inp:
        data=[]
        rec=line.split()
        data.append(rec[0])
        for k in range(1,4): data.append(float(rec[k]))
        indata.append(data)
      if len(indata)>0:
        for line in indata:
            outstring=spitout(line)
            if outfile=="":
                print(outstring)
            else:
                out.write(outstring)
    else:
       print('no input data')
       sys.exit()


Instruction:
How would you implement a function in Python 3 that
gets the eigenvalues and eigenvectors of a single object from a matrix T

Response:
def tauV(T):
    """
    gets the eigenvalues (tau) and eigenvectors (V) from matrix T
    """
    t,V,tr=[],[],0.
    ind1,ind2,ind3=0,1,2
    evalues,evectmps=numpy.linalg.eig(T)
    evectors=numpy.transpose(evectmps)  # to make compatible with Numeric convention
    for tau in evalues:
        tr += tau  # tr totals tau values
    if tr != 0:
        for i in range(3):
            evalues[i]=old_div(evalues[i], tr)  # convention is norming eigenvalues so they sum to 1.
    else:
        return t,V  # if eigenvalues add up to zero, no sorting is needed
# sort evalues,evectors
    t1, t2, t3 = 0., 0., 1.
    for k in range(3):
        if evalues[k] > t1:
            t1,ind1 = evalues[k],k
        if evalues[k] < t3:
            t3,ind3 = evalues[k],k
    for k in range(3):
        if evalues[k] != t1 and evalues[k] != t3:
            t2,ind2=evalues[k],k
    V.append(evectors[ind1])
    V.append(evectors[ind2])
    V.append(evectors[ind3])
    t.append(t1)
    t.append(t2)
    t.append(t3)
    return t,V


Instruction:
Can you create a Python 3 function that
takes arrays of X1_prime X2_prime X3_prime and the PD. checks that the PD vector direction is correct

Response:
def get_PD_direction(X1_prime, X2_prime, X3_prime, PD):
    """takes arrays of X1_prime, X2_prime, X3_prime, and the PD.
    checks that the PD vector direction is correct"""
    n = len(X1_prime) - 1
    X1 = X1_prime[0] - X1_prime[n]
    X2 = X2_prime[0] - X2_prime[n]
    X3 = X3_prime[0] - X3_prime[n]
    R= numpy.array([X1, X2, X3])
    #print 'R (reference vector for PD direction)', R
    dot = numpy.dot(PD, R) # dot product of reference vector and the principal axis of the V matrix
    #print 'dot (dot of PD and R)', dot
    if dot < -1:
        dot = -1
    elif dot > 1:
        dot = 1
    if numpy.arccos(dot) > old_div(numpy.pi, 2.):
        #print 'numpy.arccos(dot) {} > numpy.pi / 2. {}'.format(numpy.arccos(dot), numpy.pi / 2)
        #print 'correcting PD direction'
        PD = -1. * numpy.array(PD)
    #print 'PD after get PD direction', PD
    return PD


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_MAD(tau):
    # tau is ordered so that tau[0] > tau[1] > tau[2]
    for t in tau:
        if isinstance(t, complex):
            return -999
    MAD = math.degrees(numpy.arctan(numpy.sqrt(old_div((tau[1] + tau[2]), tau[0]))) )
    return MAD

Response: Calculates the maximum angular deviation of a PCA matrix


Instruction:
How would you explain what the following Python 3 function does
def dir2cart(d): # from pmag.py
    ints = numpy.ones(len(d)).transpose() # get an array of ones to plug into dec,inc pairs
    d = numpy.array(d)
    rad = old_div(numpy.pi, 180.)
    if len(d.shape) > 1: # array of vectors
        decs, incs = d[:,0] * rad, d[:,1] * rad
        if d.shape[1] == 3: ints = d[:,2] # take the given lengths
    else: # single vector
        decs, incs = numpy.array(d[0]) * rad, numpy.array(d[1]) * rad
        if len(d) == 3:
            ints = numpy.array(d[2])
        else:
            ints = numpy.array([1.])
    cart = numpy.array([ints * numpy.cos(decs) * numpy.cos(incs),
                       ints * numpy.sin(decs) * numpy.cos(incs),
                       ints * numpy.sin(incs)
                     ]).transpose()
    return cart

Response: converts list or array of vector directions in degrees to array of cartesian coordinates in x y z form


Instruction:
Can you tell what is the following Python 3 function doing
def pmag_angle(D1,D2): # use this
    D1 = numpy.array(D1)
    if len(D1.shape) > 1:
        D1 = D1[:,0:2] # strip off intensity
    else: D1 = D1[:2]
    D2 = numpy.array(D2)
    if len(D2.shape) > 1:
        D2 = D2[:,0:2] # strip off intensity
    else: D2 = D2[:2]
    X1 = dir2cart(D1) # convert to cartesian from polar
    X2 = dir2cart(D2)
    angles = [] # set up a list for angles
    for k in range(X1.shape[0]): # single vector
        angle = numpy.arccos(numpy.dot(X1[k],X2[k]))*180./numpy.pi # take the dot product
        angle = angle%360.
        angles.append(angle)
    return numpy.array(angles)

Response: returns the angle between two lists of two directions D1 D2


Instruction:
Given the following Python 3 function, write the documentation
def new_get_angle_diff(v1,v2):
    v1 = numpy.array(v1)
    v2 = numpy.array(v2)
    angle = numpy.arctan2(numpy.linalg.norm(numpy.cross(v1, v2)), numpy.dot(v1, v2))
    return math.degrees(angle)

Response: returns angular difference in degrees between two vectors. may be more precise in certain cases.


Instruction:
Here you have a function in Python 3, explain what it does
def get_angle_difference(v1, v2):
    v1 = numpy.array(v1)
    v2 = numpy.array(v2)
    angle=numpy.arccos(old_div((numpy.dot(v1, v2) ), (numpy.sqrt(math.fsum(v1**2)) * numpy.sqrt(math.fsum(v2**2)))))
    return math.degrees(angle)

Response: returns angular difference in degrees between two vectors. takes in cartesian coordinates


Instruction:
Can you implement a function in Python 3 that
gives angle between principal direction of the ptrm data and the b_lab vector. this is NOT in SPD, but taken from Ron Shaar's old thellier_gui.py code. see PmagPy on github

Response:
def get_ptrms_angle(ptrms_best_fit_vector, B_lab_vector):
    """
    gives angle between principal direction of the ptrm data and the b_lab vector.  this is NOT in SPD, but taken from Ron Shaar's old thellier_gui.py code.  see PmagPy on github
    """
    ptrms_angle = math.degrees(math.acos(old_div(numpy.dot(ptrms_best_fit_vector,B_lab_vector),(numpy.sqrt(sum(ptrms_best_fit_vector**2)) * numpy.sqrt(sum(B_lab_vector**2))))))  # from old thellier_gui.py code
    return ptrms_angle


Instruction:
Write a Python 3 function for
taking out dos problem characters from any file

Response:
def main():
    """
    Take out dos problem characters from any file
    """
    filename = pmag.get_named_arg('-f')
    if not filename:
        return
    with open(filename, 'rb+') as f:
        content = f.read()
        f.seek(0)
        f.write(content.replace(b'\r', b''))
        f.truncate()


Instruction:
Write a Python 3 script for
adding criteria used only in thellier gui only

Response:
def add_thellier_gui_criteria(acceptance_criteria):
    '''criteria used only in thellier gui
    these criteria are not written to pmag_criteria.txt
    '''
    category="thellier_gui"
    for crit in ['sample_int_n_outlier_check','site_int_n_outlier_check']:
        acceptance_criteria[crit]={}
        acceptance_criteria[crit]['category']=category
        acceptance_criteria[crit]['criterion_name']=crit
        acceptance_criteria[crit]['value']=-999
        acceptance_criteria[crit]['threshold_type']="low"
        acceptance_criteria[crit]['decimal_points']=0

    for crit in ['sample_int_interval_uT','sample_int_interval_perc',\
    'site_int_interval_uT','site_int_interval_perc',\
    'sample_int_BS_68_uT','sample_int_BS_95_uT','sample_int_BS_68_perc','sample_int_BS_95_perc','specimen_int_max_slope_diff']:
        acceptance_criteria[crit]={}
        acceptance_criteria[crit]['category']=category
        acceptance_criteria[crit]['criterion_name']=crit
        acceptance_criteria[crit]['value']=-999
        acceptance_criteria[crit]['threshold_type']="high"
        if crit in ['specimen_int_max_slope_diff']:
            acceptance_criteria[crit]['decimal_points']=-999
        else:
            acceptance_criteria[crit]['decimal_points']=1
        acceptance_criteria[crit]['comments']="thellier_gui_only"

    for crit in ['average_by_sample_or_site','interpreter_method']:
        acceptance_criteria[crit]={}
        acceptance_criteria[crit]['category']=category
        acceptance_criteria[crit]['criterion_name']=crit
        if crit in ['average_by_sample_or_site']:
            acceptance_criteria[crit]['value']='sample'
        if crit in ['interpreter_method']:
            acceptance_criteria[crit]['value']='stdev_opt'
        acceptance_criteria[crit]['threshold_type']="flag"
        acceptance_criteria[crit]['decimal_points']=-999

    for crit in ['include_nrm']:
        acceptance_criteria[crit]={}
        acceptance_criteria[crit]['category']=category
        acceptance_criteria[crit]['criterion_name']=crit
        acceptance_criteria[crit]['value']=True
        acceptance_criteria[crit]['threshold_type']="bool"
        acceptance_criteria[crit]['decimal_points']=-999


Instruction:
Given the following Python 3 function, write the documentation
def on_okButton(self, event):
        def check_input_dir_path(input_dir_path, new_dir_path):
            if input_dir_path and input_dir_path != new_dir_path:
                pw.simple_warning("Please make sure that all input files come from the same directory")
                return False
            if not input_dir_path and new_dir_path:
                return new_dir_path
            elif input_dir_path == new_dir_path:
                return input_dir_path

        wait = wx.BusyInfo('Making plots, please wait...')
        wx.SafeYield()

        os.chdir(self.WD)
        input_dir_path = None
        meas_file = self.bSizer0.return_value()
        if meas_file:
            input_dir_path, meas_file = os.path.split(meas_file)
        pmag_spec_file = self.bSizer0a.return_value()
        if pmag_spec_file:
            new_dir_path, pmag_spec_file = os.path.split(pmag_spec_file)
            input_dir_path = check_input_dir_path(input_dir_path, new_dir_path)
            if not input_dir_path:
                del wait
                return False
        sum_file = self.bSizer2.return_value()
        if sum_file:
            new_dir_path, sum_file = os.path.split(sum_file)
            input_dir_path = check_input_dir_path(input_dir_path, new_dir_path)
            if not input_dir_path:
                del wait
                return False

        spec_sym, spec_sym_shape, spec_sym_color, spec_sym_size = "", "", "", ""

        if pmag_spec_file:
            # get symbol/size for dots
            spec_sym_shape = self.shape_choices_dict[self.bSizer0a2.return_value()]
            spec_sym_color = self.bSizer0a1.return_value()[0]
            spec_sym_size = self.bSizer0a3.return_value()
            spec_sym = str(spec_sym_color) + str(spec_sym_shape)

        use_sampfile = self.bSizer1a.return_value()
        if use_sampfile:
            new_dir_path, samp_file = os.path.split(str(self.bSizer1.return_value()))
            age_file = ''
            input_dir_path = check_input_dir_path(input_dir_path, new_dir_path)
            if not input_dir_path:
                del wait
                return False
        else:
            samp_file = ''
            new_dir_path, age_file = os.path.split(self.bSizer1.return_value())
            input_dir_path = check_input_dir_path(input_dir_path, new_dir_path)
            if not input_dir_path:
                del wait
                return False

        depth_scale = self.bSizer8.return_value()
        if age_file:
            depth_scale='age'
        elif depth_scale:
            depth_scale = 'sample_core_depth' #'mbsf'
        else:
            depth_scale = 'sample_composite_depth' #'mcd'
        dmin = self.bSizer6.return_value()
        dmax = self.bSizer7.return_value()
        if self.bSizer9.return_value(): # if plot GPTS is checked
            pltTime = 1
            timescale = self.bSizer10.return_value()
            amin = self.bSizer11.return_value()
            amax = self.bSizer12.return_value()
            if not amin or not amax:
                del wait
                pw.simple_warning("If plotting timescale, you must provide both a lower and an upper bound.\nIf you don't want to plot timescale, uncheck the 'Plot GPTS' checkbox")
                return False
        else: # if plot GPTS is not checked
            pltTime, timescale, amin, amax = 0, '', -1, -1
        sym_shape = self.shape_choices_dict[self.bSizer5.return_value()]
        sym_color = self.bSizer4.return_value()[0]
        sym = sym_color + sym_shape
        size = self.bSizer5a.return_value()
        pltLine = self.bSizer5b.return_value()
        if pltLine:
            pltLine = 1
        else:
            pltLine = 0
        method = str(self.bSizer13.return_value())
        step = self.bSizer14.return_value()
        if not step:
            step = 0
            method = 'LT-NO'
        #if not step:
        #    #-LP [AF,T,ARM,IRM, X] step [in mT,C,mT,mT, mass/vol] to plot
        #    units_dict = {'AF': 'millitesla', 'T': 'degrees C', 'ARM': 'millitesla', 'IRM': 'millitesla', 'X': 'mass/vol'}
            #unit = units_dict[method]
            #pw.simple_warning("You must provide the experiment step in {}".format(unit))
            #return False
        pltDec, pltInc, pltMag, logit = 0, 0, 0, 0
        for val in self.bSizer3.return_value():
            if 'declination' in val:
                pltDec = 1
            if 'inclination' in val:
                pltInc = 1
            if 'magnetization' in val:
                pltMag = 1
            if 'log' in val:
                logit = 1

        #pltSus = self.bSizer15.return_value()
        #if pltSus:
        #    pltSus = 0
        #else:
        #    pltSus = 1

        fmt = self.bSizer16.return_value()
        #print "meas_file", meas_file, "pmag_spec_file", pmag_spec_file, "spec_sym_shape", spec_sym_shape, "spec_sym_color", spec_sym_color, "spec_sym_size", spec_sym_size, "samp_file", samp_file, "age_file", age_file, "depth_scale", depth_scale, "dmin", dmin, "dmax", dmax, "timescale", timescale, "amin", amin, "amax", amax, "sym", sym, "size", size, "method", method, "step", step, "pltDec", pltDec, "pltInc", pltInc, "pltMag", pltMag, "pltTime", pltTime, "logit", logit, "fmt", fmt

        # for use as module:
        #print "pltLine:", pltLine
        #print "pltSus:", pltSus

        fig, figname = ipmag.core_depthplot(input_dir_path or self.WD, meas_file, pmag_spec_file, samp_file, age_file, sum_file, '', depth_scale, dmin, dmax, sym, size, spec_sym, spec_sym_size, method, step, fmt, pltDec, pltInc, pltMag, pltLine, 1, logit, pltTime, timescale, amin, amax)
        if fig:
            self.Destroy()
            dpi = fig.get_dpi()
            pixel_width = dpi * fig.get_figwidth()
            pixel_height = dpi * fig.get_figheight()
            plot_frame = PlotFrame((pixel_width, pixel_height + 50), fig, figname)
            del wait
            return plot_frame
        else:
            del wait
            pw.simple_warning("No data points met your criteria - try again\nError message: {}".format(figname))
            return False

        # for use as command_line:
        if meas_file:
            meas_file = os.path.split(meas_file)[1]
        meas_file = pmag.add_flag(meas_file, '-f')
        if pmag_spec_file:
            pmag_spec_file = os.path.split(pmag_spec_file)[1]
        pmag_spec_file = pmag.add_flag(pmag_spec_file, '-fsp')
        pmag_spec_file = pmag_spec_file + ' ' + spec_sym_color + spec_sym_shape + ' ' + str(spec_sym_size)
        sym = '-sym ' + sym + ' ' + str(size)
        if samp_file:
            samp_file = os.path.split(samp_file)[1]
        samp_file = pmag.add_flag(samp_file, '-fsa')
        if age_file:
            age_file = os.path.split(age_file)[1]
        age_file = pmag.add_flag(age_file, '-fa')
        depth_scale = pmag.add_flag(depth_scale, '-ds')
        depth_range = ''
        if dmin and dmax:
            depth_range = '-d ' + str(dmin) + ' ' + str(dmax)
        if pltTime and amin and amax:
            timescale = '-ts ' + timescale + ' ' + str(amin) + ' ' + str(amax)
        else:
            timescale = ''
        method = pmag.add_flag(method, '-LP') + ' ' + str(step)
        #if not pltSus:
        #    pltSus = "-L"
        #else:
        #    pltSus = ''
        if not pltDec:
            pltDec = "-D"
        else:
            pltDec = ''
        if not pltInc:
            pltInc = "-I"
        else:
            pltInc = ''
        if not pltMag:
            pltMag = "-M"
        else:
            pltMag = ''
        if pltLine:
            pltLine = ""
        else:
            pltLine = '-L' # suppress line
        if logit:
            logit = "-log"
        else:
            logit = ''
        fmt = pmag.add_flag(fmt, '-fmt')

        COMMAND = "core_depthplot.py {meas_file} {pmag_spec_file} {sym} {samp_file} {age_file} {depth_scale} {depth_range} {timescale} {method} {pltDec} {pltInc} {pltMag} {logit} {fmt} {pltLine} -WD {WD}".format(meas_file=meas_file, pmag_spec_file=pmag_spec_file, sym=sym, samp_file=samp_file, age_file=age_file, depth_scale=depth_scale, depth_range=depth_range, timescale=timescale, method=method, pltDec=pltDec, pltInc=pltInc, pltMag=pltMag, logit=logit, fmt=fmt, pltLine=pltLine, WD=self.WD)
        print(COMMAND)
        #os.system(COMMAND)

        """
        haven't done these options yet
        wt_file (also sets norm)# -n specimen_filename
        spc_file, spc_sym, spc_size # -fsp spec_file symbol_shape symbol_size
        res_file, res_sym, res_size # -fres pmag_results_file symbol_shape symbol_size
        wig_file (also sets pcol, width) # -fwig wiggle_file(???)
        sum_file # -fsum IODP_core_summary_csv_file

        (sets plots & verbose) # -sav
        """

Response: Function called when OK button is clicked


Instruction:
Can you implement a function in Python 3 that
names odp_srm_magic.py DESCRIPTION converts ODP measurement format files to magic_measurements format files SYNTAX odp_srm_magic.py [command line options] OPTIONS -h: prints the help message and quits. -F FILE: specify output measurements file, default is magic_measurements.txt -Fsa FILE: specify output er_sample.txt file, default is er_sample.txt -A : don't average replicate measurements INPUT put data from a single core into a directory. depths will be below core top

Response:
def main():
    """
    NAME
        odp_srm_magic.py

    DESCRIPTION
        converts ODP measurement format files to magic_measurements format files

    SYNTAX
        odp_srm_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -F FILE: specify output  measurements file, default is magic_measurements.txt
        -Fsa FILE: specify output er_sample.txt file, default is er_sample.txt
        -A : don't average replicate measurements
    INPUT
        put data from a single core into a directory. depths will be below core top

    """
#
#
    version_num=pmag.get_version()
    meas_file='magic_measurements.txt'
    samp_file='er_samples.txt'
    ErSpecs,ErSamps,ErSites,ErLocs,ErCits=[],[],[],[],[]
    MagRecs=[]
    citation="This study"
    dir_path,demag='.','NRM'
    args=sys.argv
    noave=0,
    if '-WD' in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if "-A" in args: noave=1
    if '-F' in args:
        ind=args.index("-F")
        meas_file=args[ind+1]
    if '-Fsa' in args:
        ind=args.index("-Fsa")
        samp_file=args[ind+1]
    if '-LP' in args:
        ind=args.index("-LP")
        codelist=args[ind+1]
        codes=codelist.split(':')
        if "AF" in codes:
            demag='AF'
            if'-dc' not in args: methcode="LT-AF-Z"
            if'-dc' in args: methcode="LT-AF-I"
        if "T" in codes:
            demag="T"
            if '-dc' not in args: methcode="LT-T-Z"
            if '-dc' in args: methcode="LT-T-I"
        if "I" in codes:
            methcode="LP-IRM"
        if "S" in codes:
            demag="S"
            methcode="LP-PI-TRM:LP-PI-ALT-AFARM"
            trm_labfield=labfield
            ans=input("DC lab field for ARM step: [50uT] ")
            if ans=="":
                arm_labfield=50e-6
            else:
                arm_labfield=float(ans)*1e-6
            ans=input("temperature for total trm step: [600 C] ")
            if ans=="":
                trm_peakT=600+273 # convert to kelvin
            else:
                trm_peakT=float(ans)+273 # convert to kelvin
        if "G" in codes: methcode="LT-AF-G"
    if "D" in codes: methcode="LT-AF-D"
    if "TRM" in codes:
        demag="T"
        trm=1
    if demag=="T" and "ANI" in codes:
        methcode="LP-AN-TRM"
    if demag=="AF" and "ANI" in codes:
        methcode="LP-AN-ARM"
        if labfield==0: labfield=50e-6
        if peakfield==0: peakfield=.180
    samp_file=dir_path+'/'+samp_file
    meas_file=dir_path+'/'+meas_file
    filelist=os.listdir(dir_path) # read in list of files to import
    specimens,samples,sites=[],[],[]
    MagRecs,SpecRecs,SampRecs=[],[],[]
    for file in filelist: # parse each file
        if file[-3:].lower()=='srm':
            print('processing: ',file)
            Nfo=file.split('_')[0].split('-')
            try:
                sect=int(Nfo[3][:-1])
            except:
                sect=1
            input=open(file,'r').readlines()
            MagRec,SpecRec,SampRec={},{},{}
            alt_spec,treatment_type,treatment_value,user="","","",""
            inst="ODP-SRM"
            SampRec['sample_azimuth']='0'
            SampRec['sample_dip']='0'
            SampRec['magic_method_code']='FS-C-DRILL-IODP:SP-SS-C'
            MagRec['er_analyst_mail_names']=user
            MagRec['magic_method_codes']='LT-NO'
            MagRec['magic_software_packages']=version_num
            MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
            MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
            MagRec["treatment_ac_field"]='0'
            MagRec["treatment_dc_field"]='0'
            MagRec["treatment_dc_field_phi"]='0'
            MagRec["treatment_dc_field_theta"]='0'
            MagRec["measurement_flag"]='g' # assume all data are "good"
            MagRec["measurement_standard"]='u' # assume all data are "good"
            MagRec["measurement_csd"]='' # set csd to blank
            SpecRec['er_specimen_alternatives']=alt_spec
            vol=7e-6 # assume 7 cc samples
            datestamp=input[1].split() # date time is second line of file
            mmddyy=datestamp[0].split('/') # break into month day year
            date=mmddyy[2]+':'+mmddyy[0]+":"+mmddyy[1] +':' +datestamp[1]
            MagRec["measurement_date"]=date
            treatment_value,inst="","ODP-SRM"
            k=0
            while 1:
                fields= input[k].replace('\n','').split("=")
                if 'treatment_type' in fields[0]:
                    if "Alternating Frequency Demagnetization" in fields[1]:
                        MagRec['magic_method_codes'] = 'LT-AF-Z'
                        inst=inst+':ODP-DTECH' # measured on shipboard AF DTECH D2000
                if "treatment_value" in fields[0]:
                    value=fields[1]
                    if value!=" ":
                        treatment_value=float(value)*1e-3
                        MagRec["treatment_ac_field"]='%8.3e'%(treatment_value) # AF demag in treat mT => T
                if 'user' in fields[0]:
                    user=fields[-1]
                    MagRec["er_analyst_mail_names"]=user
                MagRec["measurement_standard"]='u' # assume all data are "good"
                if 'sample_area' in fields[0]:  vol=float(fields[1])*1e-6 # takes volume (cc) and converts to m^3
                if 'run_number' in fields[0]:
                    MagRec['external_database_ids']=fields[1] # run number is the LIMS measurement number
                    MagRec['external_database_names']='LIMS'
                k+=1
                if input[k][0:7]=='<MULTI>':
                    break
            while 1:
                k+=1
                line = input[k]
                if line[0:5]=='<RAW>':
                    break
                treatment_value=""
                rec=line.replace('\n','').split(',') # list of data
                if len(rec)>2:
                    MeasRec,SampRec={},{'core_depth':'0','er_sample_name':'0','er_site_name':'0','er_location_name':'location'}
                    for key in list(MagRec.keys()):MeasRec[key]=MagRec[key]
                    for item in rec:
                             items=item.split('=')
                             if 'demag_level' in items[0]:
                                treat= float(items[1])
                                if treat!=0:
                                    MeasRec['magic_method_codes']='LT-AF-Z'
                                    inst=inst+':ODP-SRM-AF'
                                    MeasRec["treatment_ac_field"]='%8.3e'%(treat*1e-3) # AF demag in treat mT => T
                             if 'inclination_w_tray_w_bkgrd' in items[0]: MeasRec['measurement_inc']=items[1]
                             if 'declination_w_tray_w_bkgrd' in items[0]: MeasRec['measurement_dec']=items[1]
                             if 'intensity_w_tray_w_bkgrd' in items[0]: MeasRec['measurement_magn_moment']='%8.3e'%(float(items[1])*vol) # convert intensity from A/m to Am^2 using vol
                             MeasRec['magic_instrument_codes']=inst
                             if 'offset' in items[0]:
                                 depth='%7.3f'%(float(sect-1)*1.5+float(items[1]))
                                 SampRec['core_depth']=depth
                                 MeasRec['er_specimen_name']=depth
                                 MeasRec['er_sample_name']=depth
                                 MeasRec['er_site_name']=depth
                                 MeasRec['er_location_name']='location'
                                 SampRec['er_sample_name']=depth
                                 SampRec['er_site_name']=depth
                                 SampRec['er_location_name']='location'
                                 MeasRec['measurement_number']='1'
                    SampRecs.append(SampRec)
                    MagRecs.append(MeasRec)
    pmag.magic_write(samp_file,SampRecs,'er_samples')
    print('samples stored in ',samp_file)
    Fixed=pmag.measurements_methods(MagRecs,noave)
    pmag.magic_write(meas_file,Fixed,'magic_measurements')
    print('data stored in ',meas_file)


Instruction:
Create a Python 3 function for
naming kly4s_magic.py DESCRIPTION converts files generated by SIO kly4S labview program to MagIC formated files for use with PmagPy plotting software SYNTAX kly4s_magic.py -h [command line options] OPTIONS -h: prints the help message and quits -f FILE: specify .ams input file name -fad AZDIP: specify AZDIP file with orientations, will create er_samples.txt file -fsa SFILE: specify existing er_samples.txt file with orientation information -fsp SPFILE: specify existing er_specimens.txt file for appending -F MFILE: specify magic_measurements output file -Fa AFILE: specify rmag_anisotropy output file -ocn ORCON: specify orientation convention: default is #3 below -only with AZDIP file -usr USER: specify who made the measurements -loc LOC: specify location name for study -ins INST: specify instrument used -spc SPEC: specify number of characters to specify specimen from sample -ncn NCON: specify naming convention: default is #1 below DEFAULTS MFILE: magic_measurements.txt AFILE: rmag_anisotropy.txt SPFILE: create new er_specimens.txt file USER: "" LOC: "unknown" INST: "SIO-KLY4S" SPEC: 1 specimen name is same as sample (if SPEC is 1, sample is all but last character) NOTES: Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXXYYY: YYY is sample designation with Z characters from site XXX [5] site name = sample name [6] site name entered in site_name column in the orient.txt format input file -- NOT CURRENTLY SUPPORTED [7-Z] [XXX]YYY: XXX is site designation with Z characters from samples XXXYYY NB: all others you will have to either customize your self or e-mail ltauxe@ucsd.edu for help. Orientation convention: [1] Lab arrow azimuth= azimuth; Lab arrow dip=-dip i.e., dip is degrees from vertical down - the hade [default] [2] Lab arrow azimuth = azimuth-90; Lab arrow dip = -dip i.e., azimuth is strike and dip is hade [3] Lab arrow azimuth = azimuth; Lab arrow dip = dip-90 e.g. dip is degrees from horizontal of drill direction [4] Lab arrow azimuth = azimuth; Lab arrow dip = dip [5] Lab arrow azimuth = azimuth; Lab arrow dip = 90-dip [6] all others you will have to either customize your self or e-mail ltauxe@ucsd.edu for help.

Response:
def main():
    """
    NAME
        kly4s_magic.py

    DESCRIPTION
        converts files generated by SIO kly4S labview program to MagIC formated
        files for use with PmagPy plotting software

    SYNTAX
        kly4s_magic.py -h [command line options]

    OPTIONS
        -h: prints the help message and quits
        -f FILE: specify .ams input file name
        -fad AZDIP: specify AZDIP file with orientations, will create er_samples.txt file
        -fsa SFILE: specify existing er_samples.txt file with orientation information
        -fsp SPFILE: specify existing er_specimens.txt file for appending
        -F MFILE: specify magic_measurements output file
        -Fa AFILE: specify rmag_anisotropy output file
        -ocn ORCON:  specify orientation convention: default is #3 below -only with AZDIP file
        -usr USER: specify who made the measurements
        -loc LOC: specify location name for study
        -ins INST: specify instrument used
        -spc SPEC: specify number of characters to specify specimen from sample
        -ncn NCON:  specify naming convention: default is #1 below

    DEFAULTS
        MFILE: magic_measurements.txt
        AFILE: rmag_anisotropy.txt
        SPFILE: create new er_specimens.txt file
        USER: ""
        LOC: "unknown"
        INST: "SIO-KLY4S"
        SPEC: 1  specimen name is same as sample (if SPEC is 1, sample is all but last character)
    NOTES:
        Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXXYYY:  YYY is sample designation with Z characters from site XXX
            [5] site name = sample name
            [6] site name entered in site_name column in the orient.txt format input file  -- NOT CURRENTLY SUPPORTED
            [7-Z] [XXX]YYY:  XXX is site designation with Z characters from samples  XXXYYY
            NB: all others you will have to either customize your
                self or e-mail ltauxe@ucsd.edu for help.

       Orientation convention:
            [1] Lab arrow azimuth= azimuth; Lab arrow dip=-dip
                i.e., dip is degrees from vertical down - the hade [default]
            [2] Lab arrow azimuth = azimuth-90; Lab arrow dip = -dip
                i.e., azimuth is strike and dip is hade
            [3] Lab arrow azimuth = azimuth; Lab arrow dip = dip-90
                e.g. dip is degrees from horizontal of drill direction
            [4] Lab arrow azimuth = azimuth; Lab arrow dip = dip
            [5] Lab arrow azimuth = azimuth; Lab arrow dip = 90-dip
            [6] all others you will have to either customize your
                self or e-mail ltauxe@ucsd.edu for help.

    """

    args = sys.argv
    if '-h' in args:
        print(main.__doc__)
        sys.exit()
    dataframe = extractor.command_line_dataframe([['f', True, ''], ['fad', False, ''],
                                                  ['fsa', False, ''], ['fsp', False, ''],
                                                  ['Fsp', False, 'specimens.txt'], ['F', False, 'measurements.txt'],
                                                  ['Fa', False, 'rmag_anisotropy.txt'], ['ocn', False, '3'],
                                                  ['usr', False, ''], ['loc', False, ''],
                                                  ['ins', False, 'SIO-KLY4S'], ['spc', False, 0],
                                                  ['ncn', False, '1'], ['WD', False, '.'],
                                                  ['ID', False, '.'], ['DM', False, 3 ]])
    checked_args = extractor.extract_and_check_args(args, dataframe)
    infile, azdip_infile, samp_infile, spec_infile, spec_outfile, measfile, aniso_outfile, or_con, user, locname, inst, specnum, samp_con, output_dir_path, input_dir_path, data_model_num = extractor.get_vars(['f', 'fad', 'fsa', 'fsp', 'Fsp', 'F', 'Fa', 'ocn', 'usr', 'loc', 'ins', 'spc', 'ncn', 'WD', 'ID', 'DM'], checked_args)
    convert.kly4s(infile, specnum=specnum, locname=locname, inst=inst,
                  user=user, measfile=measfile,or_con=or_con,
                      samp_con=samp_con, aniso_outfile=aniso_outfile,
                      samp_infile=samp_infile, spec_infile=spec_infile,
                      spec_outfile=spec_outfile, azdip_infile=azdip_infile,
                      dir_path=output_dir_path, input_dir_path=input_dir_path,
                      data_model_num=data_model_num)


Instruction:
Write a Python 3 function for
naming plotXY.py DESCRIPTION Makes simple X,Y plots INPUT FORMAT X,Y data in columns SYNTAX plotxy.py [command line options] OPTIONS -h prints this help message -f FILE to set file name on command line -c col1 col2 specify columns to plot -xsig col3 specify xsigma if desired -ysig col4 specify xsigma if desired -b xmin xmax ymin ymax, sets bounds -sym SYM SIZE specify symbol to plot: default is red dots, 10 pt -S don't plot the symbols -xlab XLAB -ylab YLAB -l connect symbols with lines -fmt [svg,png,pdf,eps] specify output format, default is svg -sav saves plot and quits -poly X plot a degree X polynomial through the data -skip n Number of lines to skip before reading in data

Response:
def main():
    """
    NAME
       plotXY.py

    DESCRIPTION
       Makes simple X,Y plots

    INPUT FORMAT
       X,Y data in columns

    SYNTAX
       plotxy.py [command line options]

    OPTIONS
        -h prints this help message
        -f FILE to set file name on command line
        -c col1 col2 specify columns to plot
        -xsig col3  specify xsigma if desired
        -ysig col4  specify xsigma if desired
        -b xmin xmax ymin ymax, sets bounds
        -sym SYM SIZE specify symbol to plot: default is red dots, 10 pt
        -S   don't plot the symbols
        -xlab XLAB
        -ylab YLAB
        -l  connect symbols with lines
        -fmt [svg,png,pdf,eps] specify output format, default is svg
        -sav saves plot and quits
        -poly X   plot a degree X polynomial through the data
        -skip n   Number of lines to skip before reading in data
    """
    fmt,plot='svg',0
    col1,col2=0,1
    sym,size = 'ro',50
    xlab,ylab='',''
    lines=0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-sav' in sys.argv:plot=1
    if '-c' in sys.argv:
        ind=sys.argv.index('-c')
        col1=int(sys.argv[ind+1])-1
        col2=int(sys.argv[ind+2])-1
    if '-xsig' in sys.argv:
        ind=sys.argv.index('-xsig')
        col3=int(sys.argv[ind+1])-1
    if '-ysig' in sys.argv:
        ind=sys.argv.index('-ysig')
        col4=int(sys.argv[ind+1])-1
    if '-xlab' in sys.argv:
        ind=sys.argv.index('-xlab')
        xlab=sys.argv[ind+1]
    if '-ylab' in sys.argv:
        ind=sys.argv.index('-ylab')
        ylab=sys.argv[ind+1]
    if '-b' in sys.argv:
        ind=sys.argv.index('-b')
        xmin=float(sys.argv[ind+1])
        xmax=float(sys.argv[ind+2])
        ymin=float(sys.argv[ind+3])
        ymax=float(sys.argv[ind+4])
    if '-poly' in sys.argv:
        ind=sys.argv.index('-poly')
        degr=sys.argv[ind+1]
    if '-sym' in sys.argv:
        ind=sys.argv.index('-sym')
        sym=sys.argv[ind+1]
        size=int(sys.argv[ind+2])
    if '-l' in sys.argv: lines=1
    if '-S' in sys.argv: sym=''
    skip = int(pmag.get_named_arg('-skip', default_val=0))
    X,Y=[],[]
    Xerrs,Yerrs=[],[]
    f=open(file,'r')
    for num in range(skip):
        f.readline()
    data=f.readlines()
    for line in data:
        line.replace('\n','')
        line.replace('\t',' ')
        rec=line.split()
        X.append(float(rec[col1]))
        Y.append(float(rec[col2]))
        if '-xsig' in sys.argv:Xerrs.append(float(rec[col3]))
        if '-ysig' in sys.argv:Yerrs.append(float(rec[col4]))
    if '-poly' in sys.argv:
          pylab.plot(xs,ys)
          coeffs=numpy.polyfit(X,Y,degr)
          correl=numpy.corrcoef(X,Y)**2
          polynomial=numpy.poly1d(coeffs)
          xs=numpy.linspace(numpy.min(X),numpy.max(X),10)
          ys=polynomial(xs)
          pylab.plot(xs,ys)
          print(polynomial)
          if degr=='1': print('R-square value =', '%5.4f'%(correl[0,1]))
    if sym!='':
       pylab.scatter(X,Y,marker=sym[1],c=sym[0],s=size)
    else:
       pylab.plot(X,Y)
    if '-xsig' in sys.argv and '-ysig' in sys.argv:
        pylab.errorbar(X,Y,xerr=Xerrs,yerr=Yerrs,fmt=None)
    if '-xsig' in sys.argv and '-ysig' not in sys.argv:
        pylab.errorbar(X,Y,xerr=Xerrs,fmt=None)
    if '-xsig' not in sys.argv and '-ysig' in sys.argv:
        pylab.errorbar(X,Y,yerr=Yerrs,fmt=None)
    if xlab!='':pylab.xlabel(xlab)
    if ylab!='':pylab.ylabel(ylab)
    if lines==1:pylab.plot(X,Y,'k-')
    if '-b' in sys.argv:pylab.axis([xmin,xmax,ymin,ymax])
    if plot==0:
        pylab.show()
    else:
        pylab.savefig('plotXY.'+fmt)
        print('Figure saved as ','plotXY.'+fmt)
    sys.exit()


Instruction:
Make a summary of the following Python 3 code
def main():
    dir_path='.'
    inspec="pmag_specimens.txt"
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        inspec=sys.argv[ind+1]
    basename=inspec.split('.')[:-1]
    inspec=dir_path+"/"+inspec
    ofile_base=dir_path+"/"+basename[0]
#
# read in data
#
    prior_spec_data,file_type=pmag.magic_read(inspec)
    if file_type != 'pmag_specimens':
        print(file_type, " this is not a valid pmag_specimens file")
        sys.exit()
# get list of specimens in file, components, coordinate systems available
    specs,comps,coords=[],[],[]
    for spec in prior_spec_data:
        if spec['er_specimen_name'] not in specs:specs.append(spec['er_specimen_name'])
        if 'specimen_comp_name' not in list(spec.keys()):spec['specimen_comp_name']='A'
        if 'specimen_tilt_correction'  not in list(spec.keys()):spec['tilt_correction']='-1' # assume specimen coordinates
        if spec['specimen_comp_name'] not in comps:comps.append(spec['specimen_comp_name'])
        if spec['specimen_tilt_correction'] not in coords:coords.append(spec['specimen_tilt_correction'])
# work on separating out components, coordinate systems by specimen
    for coord in coords:
        print(coord)
        for comp in comps:
            print(comp)
            speclist=[]
            for spec in prior_spec_data:
                if spec['specimen_tilt_correction']==coord and spec['specimen_comp_name']==comp:speclist.append(spec)
            ofile=ofile_base+'_'+coord+'_'+comp+'.txt'
            pmag.magic_write(ofile,speclist,'pmag_specimens')
            print('coordinate system: ',coord,' component name: ',comp,' saved in ',ofile)

Response: NAME sort_specimens. py DESCRIPTION Reads in a pmag_specimen formatted file and separates it into different components and coordinate systems


Instruction:
Explain what the following Python 3 code does
def InitSpecCheck(self):
        #wait = wx.BusyInfo("Please wait, working...")
        #wx.SafeYield()
        self.contribution.propagate_lithology_cols()
        spec_df = self.contribution.tables['specimens'].df
        self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        self.grid_frame = grid_frame3.GridFrame(self.contribution, self.WD,
                                                'specimens', 'specimens', self.panel,
                                                 main_frame=self.main_frame)
        # redefine default 'save & exit grid' button to go to next dialog instead
        self.grid_frame.exitButton.SetLabel('Save and continue')
        grid = self.grid_frame.grid
        self.grid_frame.Bind(wx.EVT_BUTTON,
                             lambda event: self.onContinue(event, grid, self.InitSampCheck),
                             self.grid_frame.exitButton)

            # add back button
        self.backButton = wx.Button(self.grid_frame.panel, id=-1, label='Back',
                                      name='back_btn')
        self.backButton.Disable()
        self.grid_frame.main_btn_vbox.Add(self.backButton, flag=wx.ALL, border=5)
        # re-do fit
        self.grid_frame.do_fit(None, self.min_size)
        # center
        self.grid_frame.Centre()
        return

Response: Initialize the specimen names and grids for the current specimen


Instruction:
Explain what the following Python 3 code does
def InitSiteCheck(self):
        # propagate average lat/lon info from samples table if
        # available in samples and missing in sites
        self.contribution.propagate_average_up(cols=['lat', 'lon', 'height'],
                                       target_df_name='sites',
                                       source_df_name='samples')
        # propagate lithology columns
        self.contribution.propagate_lithology_cols()

        site_df = self.contribution.tables['sites'].df
        self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        self.grid_frame = grid_frame3.GridFrame(self.contribution, self.WD,
                                                'sites', 'sites', self.panel,
                                                 main_frame=self.main_frame)
        # redefine default 'save & exit grid' button to go to next dialog instead
        self.grid_frame.exitButton.SetLabel('Save and continue')
        grid = self.grid_frame.grid
        self.grid_frame.Bind(wx.EVT_BUTTON,
                             lambda event: self.onContinue(event, grid, self.InitLocCheck),
                             self.grid_frame.exitButton)
        # add back button
        self.backButton = wx.Button(self.grid_frame.panel, id=-1, label='Back',
                                      name='back_btn')
        self.Bind(wx.EVT_BUTTON,
                  lambda event: self.onbackButton(event, self.InitSampCheck),
                  self.backButton)
        self.grid_frame.main_btn_vbox.Add(self.backButton, flag=wx.ALL, border=5)
        # re-do fit
        self.grid_frame.do_fit(None, self.min_size)
        # center
        self.grid_frame.Centre()
        return

Response: This method creates an interactive grid in which users can edit site names and locations a site belongs to.


Instruction:
How would you implement a function in Python 3 that
initializes the locations grid

Response:
def InitLocCheck(self):
        """
        make an interactive grid in which users can edit locations
        """
        # if there is a location without a name, name it 'unknown'
        self.contribution.rename_item('locations', 'nan', 'unknown')
        # propagate lat/lon values from sites table
        self.contribution.get_min_max_lat_lon()
        # propagate lithologies & geologic classes from sites table
        self.contribution.propagate_cols_up(['lithologies',
                                             'geologic_classes'], 'locations', 'sites')
        res = self.contribution.propagate_min_max_up()
        if cb.not_null(res):
            self.contribution.propagate_cols_up(['age_unit'], 'locations', 'sites')

        # set up frame
        self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        self.grid_frame = grid_frame3.GridFrame(self.contribution, self.WD,
                                                'locations', 'locations', self.panel,
                                                main_frame=self.main_frame)
        # redefine default 'save & exit grid' button to go to next dialog instead
        self.grid_frame.exitButton.SetLabel('Save and continue')
        grid = self.grid_frame.grid
        self.grid_frame.Bind(wx.EVT_BUTTON,
                             lambda event: self.onContinue(event, grid, self.InitAgeCheck),
                             self.grid_frame.exitButton)
        # add back button
        self.backButton = wx.Button(self.grid_frame.panel, id=-1, label='Back',
                                      name='back_btn')
        self.Bind(wx.EVT_BUTTON,
                  lambda event: self.onbackButton(event, self.InitSiteCheck),
                  self.backButton)
        self.grid_frame.main_btn_vbox.Add(self.backButton, flag=wx.ALL, border=5)
        # re-do fit
        self.grid_frame.do_fit(None, min_size=self.min_size)
        # center
        self.grid_frame.Centre()
        return


Instruction:
Given the following Python 3 function, write the documentation
def InitAgeCheck(self):
        age_df = self.contribution.tables['ages'].df
        self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        self.grid_frame = grid_frame3.GridFrame(self.contribution, self.WD,
                                                'ages', 'ages', self.panel,
                                                 main_frame=self.main_frame)
        self.grid_frame.exitButton.SetLabel('Save and continue')
        grid = self.grid_frame.grid
        self.grid_frame.Bind(wx.EVT_BUTTON, lambda event: self.onContinue(event, grid, None),
                             self.grid_frame.exitButton)
        # add back button
        self.backButton = wx.Button(self.grid_frame.panel, id=-1, label='Back',
                                      name='back_btn')
        self.Bind(wx.EVT_BUTTON,
                  lambda event: self.onbackButton(event, self.InitLocCheck),
                  self.backButton)
        self.grid_frame.main_btn_vbox.Add(self.backButton, flag=wx.ALL, border=5)
        # re-do fit
        self.grid_frame.do_fit(None, self.min_size)
        # center
        self.grid_frame.Centre()
        return

Response: make an interactive grid in which users can edit ages


Instruction:
Can you tell what is the following Python 3 function doing
def onContinue(self, event, grid, next_dia=None):#, age_data_type='site'):
        # deselect column, including remove 'EDIT ALL' label
        if self.grid_frame.drop_down_menu:
            self.grid_frame.drop_down_menu.clean_up()

        # remove '**' and '^^' from col names
        #self.remove_starred_labels(grid)
        grid.remove_starred_labels()

        grid.SaveEditControlValue() # locks in value in cell currently edited
        grid_name = str(grid.GetName())

        # save all changes to data object and write to file
        self.grid_frame.grid_builder.save_grid_data()

        # check that all required data are present
        validation_errors = self.validate(grid)
        if validation_errors:
            warn_string = ""
            for error_name, error_cols in list(validation_errors.items()):
                if error_cols:
                    warn_string += "You have {}: {}.\n\n".format(error_name, ", ".join(error_cols))
            warn_string += "Are you sure you want to continue?"
            result = pw.warning_with_override(warn_string)
            if result == wx.ID_YES:
                pass
            else:
                return False
        else:
            wx.MessageBox('Saved!', 'Info',
                          style=wx.OK | wx.ICON_INFORMATION)

        self.panel.Destroy()
        if next_dia:
            next_dia()
        else:
            # propagate any type/lithology/class data from sites to samples table
            # will only overwrite if sample values are blank or "Not Specified"
            self.contribution.propagate_lithology_cols()
            wx.MessageBox('Done!', 'Info',
                          style=wx.OK | wx.ICON_INFORMATION)

Response: Save grid data in the data object and save it to file


Instruction:
Make a summary of the following Python 3 code
def validate(self, grid):
        grid_name = str(grid.GetName())
        dmodel = self.contribution.dmodel
        reqd_headers = dmodel.get_reqd_headers(grid_name)
        df = self.contribution.tables[grid_name].df
        df = df.replace('', np.nan) # python does not view empty strings as null
        if df.empty:
            return {}
        col_names = set(df.columns)
        missing_headers = set(reqd_headers) - col_names
        present_headers = set(reqd_headers) - set(missing_headers)
        non_null_headers = df.dropna(how='all', axis='columns').columns
        null_reqd_headers = present_headers - set(non_null_headers)
        if any(missing_headers) or any (null_reqd_headers):
            warnings = {'missing required column(s)': sorted(missing_headers),
                        'no data in required column(s)': sorted(null_reqd_headers)}
        else:
            warnings = {}
        return warnings

Response: Validate the MagIC data model for a specific MagIC grid.


Instruction:
How would you code a function in Python 3 to
save any editing of the grid but does not continue to the next window

Response:
def on_saveButton(self, event, grid):
        """saves any editing of the grid but does not continue to the next window"""
        wait = wx.BusyInfo("Please wait, working...")
        wx.SafeYield()

        if self.grid_frame.drop_down_menu:  # unhighlight selected columns, etc.
            self.grid_frame.drop_down_menu.clean_up()

        # remove '**' and '^^' from col labels
        starred_cols, hatted_cols = grid.remove_starred_labels()

        grid.SaveEditControlValue() # locks in value in cell currently edited
        grid.HideCellEditControl() # removes focus from cell that was being edited

        if grid.changes:
            self.onSave(grid)

        for col in starred_cols:
            label = grid.GetColLabelValue(col)
            grid.SetColLabelValue(col, label + '**')
        for col in hatted_cols:
            label = grid.GetColLabelValue(col)
            grid.SetColLabelValue(col, label + '^^')
        del wait


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

        self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        #import wx.lib.scrolledpanel as libpanel # does not work well
        #self.panel = libpanel.ScrolledPanel(self, style=wx.SIMPLE_BORDER)

        text = """Step 1:
Check that all specimens belong to the correct sample
(if sample name is simply wrong, that will be fixed in step 2)"""
        label = wx.StaticText(self.panel, label=text)
        self.grid_builder = grid_frame2.GridBuilder(self.er_magic_data, 'specimen',
                                                   self.er_magic_data.headers, self.panel,
                                                   'sample')
        self.spec_grid = self.grid_builder.make_grid(incl_pmag=False)
        self.grid = self.spec_grid

        self.spec_grid.InitUI()

        self.grid_builder.add_data_to_grid(self.spec_grid, 'specimen', incl_pmag=False)

        samples = self.er_magic_data.make_name_list(self.er_magic_data.samples)
        self.drop_down_menu = drop_down_menus.Menus("specimen", self, self.spec_grid, samples)

        #### Create Buttons ####
        hbox_one = wx.BoxSizer(wx.HORIZONTAL)
        self.addSampleButton = wx.Button(self.panel, label="Add a new sample")
        self.samples = [name for name in self.er_magic_data.samples]
        self.Bind(wx.EVT_BUTTON, self.on_addSampleButton, self.addSampleButton)
        self.helpButton = wx.Button(self.panel, label="Help")
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_helpButton(event, "ErMagicSpecimenHelp.html"), self.helpButton)
        hbox_one.Add(self.addSampleButton, flag=wx.ALIGN_LEFT|wx.RIGHT, border=10)
        hbox_one.Add(self.helpButton)

        #
        hboxok = wx.BoxSizer(wx.HORIZONTAL)
        self.saveButton = wx.Button(self.panel, id=-1, label='Save')
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_saveButton(event, self.spec_grid), self.saveButton)
        self.cancelButton = wx.Button(self.panel, wx.ID_CANCEL, '&Cancel')
        self.Bind(wx.EVT_BUTTON, self.on_cancelButton, self.cancelButton)
        self.continueButton = wx.Button(self.panel, id=-1, label='Save and continue')
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_continueButton(event, self.spec_grid, next_dia=self.InitSampCheck), self.continueButton)

        hboxok.Add(self.saveButton, flag=wx.ALIGN_LEFT|wx.RIGHT, border=10)
        hboxok.Add(self.cancelButton, flag=wx.ALIGN_LEFT|wx.RIGHT, border=10)
        hboxok.Add(self.continueButton, flag=wx.ALIGN_LEFT)

        #
        hboxgrid = pw.hbox_grid(self.panel, self.onDeleteRow, 'specimen', self.grid)
        self.deleteRowButton = hboxgrid.deleteRowButton

        self.panel.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid)

        ### Create Containers ###
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.AddSpacer(10)
        vbox.Add(label, flag=wx.ALIGN_CENTER|wx.TOP|wx.BOTTOM, border=10)

        vbox.Add(hbox_one, flag=wx.TOP|wx.LEFT|wx.BOTTOM, border=10)
        vbox.Add(hboxok, flag=wx.BOTTOM|wx.LEFT, border=10)
        vbox.Add(hboxgrid, flag=wx.BOTTOM|wx.LEFT, border=10)
        vbox.Add(self.spec_grid, flag=wx.ALL, border=10)#|wx.EXPAND, border=30)
        vbox.AddSpacer(20)

        self.hbox_all = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox_all.AddSpacer(20)
        self.hbox_all.Add(vbox)
        self.hbox_all.AddSpacer(20)

        self.panel.SetSizer(self.hbox_all)
        #self.panel.SetScrollbars(20, 20, 50, 50)
        self.hbox_all.Fit(self)
        self.Centre()
        self.Show()
        self.Hide()
        self.Show()

Response: Initialize the specimen check dialog


Instruction:
Explain what the following Python 3 code does
def InitSampCheck(self):
        self.sample_window += 1
        self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER)

        if self.sample_window == 1:
            text = """Step 2:
Check that all samples are correctly named,
and that they belong to the correct site
(if site name is simply wrong, that will be fixed in step 3)"""
            step_label = wx.StaticText(self.panel, label=text)#, size=(900, 100))
        else:
            text = """Step 4:
Some of the data from the er_sites table has propogated into er_samples.
Check that these data are correct, and fill in missing cells using controlled vocabularies.
The columns for class, lithology, and type can take multiple values in the form of a colon-delimited list.
You may use the drop-down menus to add as many values as needed in these columns.
(see Help button for more details)\n\n** Denotes controlled vocabulary"""
            step_label = wx.StaticText(self.panel, label=text)#, size=(900, 100))

        if self.sample_window == 1:
            # provide no extra headers
            headers = {'sample': {'er': [[], [], []],
                                  'pmag': [[], [], []]}}
            self.grid_builder = grid_frame2.GridBuilder(self.er_magic_data, 'sample',
                                                       headers, self.panel,
                                                       'site')

        if self.sample_window > 1:
            self.grid_builder = grid_frame2.GridBuilder(self.er_magic_data, 'sample',
                                           self.er_magic_data.headers, self.panel,
                                           'site')

        self.samp_grid = self.grid_builder.make_grid(incl_pmag=False)
        self.samp_grid.InitUI()
        self.grid_builder.add_data_to_grid(self.samp_grid, 'sample', incl_pmag=False)
        self.grid = self.samp_grid

        sites = sorted(self.er_magic_data.make_name_list(self.er_magic_data.sites))
        self.drop_down_menu = drop_down_menus.Menus("sample", self, self.samp_grid, sites) # initialize all needed drop-down menus

        ### Create Buttons ###
        hbox_one = wx.BoxSizer(wx.HORIZONTAL)
        self.addSiteButton = wx.Button(self.panel, label="Add a new site")
        self.Bind(wx.EVT_BUTTON, self.on_addSiteButton, self.addSiteButton)
        hbox_one.Add(self.addSiteButton, flag=wx.RIGHT, border=10)
        if self.sample_window == 1:
            html_help = "ErMagicSampleHelp1.html"
        if self.sample_window > 1:
            html_help = "ErMagicSampleHelp.html"
        self.helpButton = wx.Button(self.panel, label="Help")
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_helpButton(event, html_help), self.helpButton)
        hbox_one.Add(self.helpButton)

        hboxok = wx.BoxSizer(wx.HORIZONTAL)
        self.saveButton = wx.Button(self.panel, id=-1, label='Save')
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_saveButton(event, self.samp_grid), self.saveButton)
        self.cancelButton = wx.Button(self.panel, wx.ID_CANCEL, '&Cancel')
        self.Bind(wx.EVT_BUTTON, self.on_cancelButton, self.cancelButton)
        self.continueButton = wx.Button(self.panel, id=-1, label='Save and continue')
        next_dia = self.InitSiteCheck if self.sample_window < 2 else self.InitLocCheck
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_continueButton(event, self.samp_grid, next_dia=next_dia), self.continueButton)
        self.backButton = wx.Button(self.panel, wx.ID_ANY, "&Back")
        previous_dia = self.InitSpecCheck if self.sample_window < 2 else self.InitSiteCheck
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_backButton(event, previous_dia=previous_dia), self.backButton)

        hboxok.Add(self.saveButton, flag=wx.RIGHT, border=10)
        hboxok.Add(self.cancelButton, flag=wx.RIGHT, border=10)
        hboxok.Add(self.continueButton, flag=wx.RIGHT, border=10)
        hboxok.Add(self.backButton)

        hboxgrid = pw.hbox_grid(self.panel, self.onDeleteRow, 'sample', self.grid)
        self.deleteRowButton = hboxgrid.deleteRowButton

        self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid)

        ### Make Containers ###
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(step_label, flag=wx.ALIGN_LEFT|wx.TOP|wx.BOTTOM, border=20)

        vbox.Add(hbox_one, flag=wx.BOTTOM|wx.LEFT, border=10)
        vbox.Add(hboxok, flag=wx.BOTTOM|wx.LEFT, border=10)
        vbox.Add(hboxgrid, flag=wx.BOTTOM|wx.LEFT, border=10)
        vbox.Add(self.samp_grid, flag=wx.ALL, border=10) # using wx.EXPAND or not does not affect re-size problem
        vbox.AddSpacer(20)

        self.hbox_all = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox_all.AddSpacer(20)
        self.hbox_all.Add(vbox)
        self.hbox_all.AddSpacer(20)

        self.panel.SetSizer(self.hbox_all)
        #if sys.platform in ['win32', 'win64']:
        #    self.panel.SetScrollbars(20, 20, 50, 50)
        self.hbox_all.Fit(self)

        self.Centre()
        self.Show()

        ## this combination may prevent a display error that (without the fix) only resolves on manually resizing the window
        self.panel.Refresh()
        self.samp_grid.ForceRefresh()
        self.panel.Refresh()
        self.Refresh()

        # this prevents display errors
        self.Hide()
        self.Show()

Response: Initialize the main sample check dialog


Instruction:
Explain what the following Python 3 code does
def InitSiteCheck(self):
        self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER)

        text = """Step 3:
Check that all sites are correctly named, and that they belong to the correct location.
Fill in the additional columns with controlled vocabularies.
The columns for class, lithology, and type can take multiple values in the form of a colon-delimited list.
You may use the drop-down menus to add as many values as needed in these columns.
(see the help button for more details)
note: Changes to site_class, site_lithology, or site_type will overwrite er_samples.txt
However, you will be able to edit sample_class, sample_lithology, and sample_type in step 4

**Denotes controlled vocabulary"""
        label = wx.StaticText(self.panel, label=text)
        #self.Data_hierarchy = self.ErMagic.Data_hierarchy
        self.sites = sorted(self.er_magic_data.make_name_list(self.er_magic_data.sites))

        #for val in ['er_citation_names', 'er_location_name', 'er_site_name', 'site_class', 'site_lithology', 'site_type', 'site_definition', 'site_lat', 'site_lon']: #
        #    try:
        #        self.er_magic_data.headers['site']['er'][0].remove(val)
        #    except ValueError:
        #        pass

        self.grid_builder = grid_frame2.GridBuilder(self.er_magic_data, 'site',
                               self.er_magic_data.headers, self.panel,
                               'location')

        self.site_grid = self.grid_builder.make_grid(incl_pmag=False)
        self.site_grid.InitUI()
        self.grid_builder.add_data_to_grid(self.site_grid, 'site', incl_pmag=False)
        self.grid = self.site_grid

        # populate site_definition as 's' by default if no value is provided (indicates that site is single, not composite)
        rows = self.site_grid.GetNumberRows()
        col = 6
        for row in range(rows):
            cell = self.site_grid.GetCellValue(row, col)
            if not cell:
                self.site_grid.SetCellValue(row, col, 's')

        # initialize all needed drop-down menus
        locations = sorted(self.er_magic_data.make_name_list(self.er_magic_data.locations))
        self.drop_down_menu = drop_down_menus.Menus("site", self, self.site_grid, locations)

        ### Create Buttons ###
        hbox_one = wx.BoxSizer(wx.HORIZONTAL)
        self.addLocButton = wx.Button(self.panel, label="Add a new location")

        self.Bind(wx.EVT_BUTTON, self.on_addLocButton, self.addLocButton)
        hbox_one.Add(self.addLocButton, flag=wx.RIGHT, border=10)

        self.helpButton = wx.Button(self.panel, label="Help")
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_helpButton(event, "ErMagicSiteHelp.html"), self.helpButton)
        hbox_one.Add(self.helpButton)

        hboxok = wx.BoxSizer(wx.HORIZONTAL)
        self.saveButton = wx.Button(self.panel, id=-1, label='Save')
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_saveButton(event, self.site_grid), self.saveButton)
        self.cancelButton = wx.Button(self.panel, wx.ID_CANCEL, '&Cancel')
        self.Bind(wx.EVT_BUTTON, self.on_cancelButton, self.cancelButton)
        self.continueButton = wx.Button(self.panel, id=-1, label='Save and continue')
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_continueButton(event, self.site_grid, next_dia=self.InitSampCheck), self.continueButton)
        self.backButton = wx.Button(self.panel, wx.ID_ANY, "&Back")
        previous_dia = self.InitSampCheck
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_backButton(event, previous_dia=previous_dia), self.backButton)

        hboxok.Add(self.saveButton, flag=wx.RIGHT, border=10)
        hboxok.Add(self.cancelButton, flag=wx.RIGHT, border=10)
        hboxok.Add(self.continueButton, flag=wx.RIGHT, border=10)
        hboxok.Add(self.backButton)

        #
        hboxgrid = pw.hbox_grid(self.panel, self.onDeleteRow, 'site', self.grid)
        self.deleteRowButton = hboxgrid.deleteRowButton

        self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid)

        ### Make Containers ###
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(label, flag=wx.ALIGN_CENTER|wx.BOTTOM|wx.TOP, border=20)
        vbox.Add(hbox_one, flag=wx.BOTTOM|wx.LEFT, border=10)
        vbox.Add(hboxok, flag=wx.BOTTOM|wx.LEFT, border=10)
        vbox.Add(hboxgrid, flag=wx.BOTTOM|wx.LEFT, border=10)
        vbox.Add(self.site_grid, flag=wx.ALL|wx.EXPAND, border=10) # EXPAND ??
        vbox.AddSpacer(20)

        self.hbox_all = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox_all.AddSpacer(20)
        self.hbox_all.Add(vbox)
        self.hbox_all.AddSpacer(20)

        self.panel.SetSizer(self.hbox_all)
        #if sys.platform in ['win32', 'win64']:
        #    self.panel.SetScrollbars(20, 20, 50, 50)
        self.hbox_all.Fit(self)
        self.Centre()
        self.Show()
        # this combination prevents a display error that (without the fix) only resolves on manually resizing the window
        self.site_grid.ForceRefresh()
        self.panel.Refresh()
        self.Hide()
        self.Show()

Response: Initialize the site check dialog