Instruction:
Explain what the following Python 3 code does
def main():
    args = sys.argv
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    verbose = pmagplotlib.verbose
    dir_path = pmag.get_named_arg("-WD", ".")
    input_dir_path = pmag.get_named_arg("-ID", "")
    num_bootstraps = pmag.get_named_arg("-n", 1000)
    ipar = pmag.get_flag_arg_from_sys("-par", true=1, false=0)
    ihext = pmag.get_flag_arg_from_sys("-x", true=1, false=0)
    ivec = pmag.get_flag_arg_from_sys("-v", true=1, false=0)
    iplot = pmag.get_flag_arg_from_sys("-P", true=0, false=1)
    isite = pmag.get_flag_arg_from_sys("-sit", true=1, false=0)
    iboot, vec = 1, 0
    infile = pmag.get_named_arg('-f', 'specimens.txt')
    samp_file = pmag.get_named_arg('-fsa', 'samples.txt')
    site_file = pmag.get_named_arg('-fsi', 'sites.txt')
    #outfile = pmag.get_named_arg("-F", "rmag_results.txt")
    fmt = pmag.get_named_arg("-fmt", "png")
    crd = pmag.get_named_arg("-crd", "s")
    comp, Dir, PDir = 0, [], []
    user = pmag.get_named_arg("-usr", "")
    if '-B' in args:
        iboot, ihext = 0, 1
    plots, verbose = 0, True
    if '-sav' in args:
        plots = 1
        verbose = 0
    if '-gtc' in args:
        ind = args.index('-gtc')
        d, i = float(args[ind+1]), float(args[ind+2])
        PDir.append(d)
        PDir.append(i)
    if '-d' in args:
        comp = 1
        ind = args.index('-d')
        vec = int(args[ind+1])-1
        Dir = [float(args[ind+2]), float(args[ind+3])]

    ipmag.aniso_magic(infile=infile, samp_file=samp_file, site_file=site_file,
                      ipar=ipar, ihext=ihext, ivec=ivec, iplot=iplot, isite=isite, iboot=iboot, vec=vec,
                      Dir=Dir, PDir=PDir, comp=comp, user=user,
                      fmt=fmt, crd=crd, verbose=verbose, plots=plots,
                      num_bootstraps=num_bootstraps, dir_path=dir_path,
                      input_dir_path=input_dir_path)

Response: NAME aniso_magic. py - h is the entry point for the anisotropy_base. py script


Instruction:
Make a summary of the following Python 3 code
def new():

    args = sys.argv
    if '-h' in args:
        print(new.__doc__)
        return
    dir_path = pmag.get_named_arg("-WD", ".")
    if '-ID' in args and dir_path == '.':
        dir_path = pmag.get_named_arg("-ID", ".")
    iboot, vec = 1, 0
    num_bootstraps = pmag.get_named_arg("-n", 1000)
    ipar = pmag.get_flag_arg_from_sys("-par", true=1, false=0)
    ihext = pmag.get_flag_arg_from_sys("-x", true=1, false=0)
    ivec = pmag.get_flag_arg_from_sys("-v", true=1, false=0)
    if ivec:
        vec = 3
    #iplot = pmag.get_flag_arg_from_sys("-P", true=0, false=1)
    isite = pmag.get_flag_arg_from_sys("-sit", true=1, false=0)
    infile = pmag.get_named_arg('-f', 'specimens.txt')
    samp_file = pmag.get_named_arg('-fsa', 'samples.txt')
    site_file = pmag.get_named_arg('-fsi', 'sites.txt')
    #outfile = pmag.get_named_arg("-F", "rmag_results.txt")
    fmt = pmag.get_named_arg("-fmt", "png")
    crd = pmag.get_named_arg("-crd", "s")
    comp, Dir, PDir = 0, [], []
    user = pmag.get_named_arg("-usr", "")
    if '-B' in args:
        iboot, ihext = 0, 1
    save_plots, verbose, interactive = False, True, True
    if '-sav' in args:
        save_plots = True
        verbose = False
        interactive = False
    if '-gtc' in args:
        ind = args.index('-gtc')
        d, i = float(args[ind+1]), float(args[ind+2])
        PDir.append(d)
        PDir.append(i)
    if '-d' in args:
        comp = 1
        ind = args.index('-d')
        vec = int(args[ind+1])-1
        Dir = [float(args[ind+2]), float(args[ind+3])]
    ipmag.aniso_magic_nb(infile, samp_file, site_file, verbose,
                         ipar, ihext, ivec, isite, False, iboot,
                         vec, Dir, PDir, crd, num_bootstraps,
                         dir_path, save_plots=save_plots, interactive=interactive,
                         fmt=fmt)

Response: A function to create a new empty set of anisotropy data structures for the current base level of the current site.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def main():
    coord, kappa, cutoff, n = 0, 0, 180., 0
    nb, anti, spin, v, boot = 1000, 0, 0, 0, 0
    data_model = 3
    rev = 0
    if '-dm' in sys.argv:
        ind = sys.argv.index("-dm")
        data_model = int(sys.argv[ind+1])
    if data_model == 2:
        coord_key = 'tilt_correction'
        in_file = 'pmag_results.txt'
        k_key, n_key, lat_key = 'average_k', 'average_nn', 'average_lat'
    else:
        coord_key = 'dir_tilt_correction'
        in_file = 'sites.txt'
        k_key, n_key, lat_key = 'dir_k', 'dir_n_samples`', 'lat'
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        in_file = sys.argv[ind + 1]
        vgp_df = pd.read_csv(in_file, sep='\t', header=1)
    else:
        vgp_df = pd.read_csv(sys.stdin, sep='\t', header=1)
    if '-c' in sys.argv:
        ind = sys.argv.index('-c')
        cutoff = float(sys.argv[ind+1])
    if '-k' in sys.argv:
        ind = sys.argv.index('-k')
        kappa = float(sys.argv[ind+1])
    if '-n' in sys.argv:
        ind = sys.argv.index('-n')
        n = float(sys.argv[ind+1])
    if '-crd' in sys.argv:
        ind = sys.argv.index("-crd")
        coord = sys.argv[ind+1]
        if coord == 's':
            coord = -1
        if coord == 'g':
            coord = 0
        if coord == 't':
            coord = 100
    if '-a' in sys.argv:
        anti = 1
    if '-r' in sys.argv:
        rev = 1
    if '-p' in sys.argv:
        spin = 1
    if '-v' in sys.argv:
        v = 1
    if '-b' in sys.argv:
        boot = 1
    if '-mm97' in sys.argv:
        mm97 = 1
    else:
        mm97 = 0
    #
    # find desired vgp lat,lon, kappa,N_site data:
    #
    vgp_df.dropna(subset=['vgp_lat', 'vgp_lon'])
    keys = [coord_key, k_key, n_key, lat_key]
    for key in keys:
        if key not in vgp_df.columns:
            vgp_df[key] = 0
    vgp_df = vgp_df[vgp_df[coord_key] == coord]
    if data_model != 3:  # convert
        vgp_df['dir_k'] = vgp_df[k_key]
        vgp_df['dir_n_samples'] = vgp_df[n_key]
        vgp_df['lat'] = vgp_df[lat_key]
    N, S_B, low, high, cutoff = pmag.scalc_vgp_df(
        vgp_df, anti=anti, rev=rev, cutoff=cutoff, kappa=kappa, n=n, spin=spin, v=v, boot=boot, mm97=mm97)
    if high != 0:
        print(N, '%7.1f %7.1f  %7.1f %7.1f ' % (S_B, low, high, cutoff))
    else:
        print(N, '%7.1f  %7.1f ' % (S_B, cutoff))

Response:
NAME
        scalc_magic.py

    DESCRIPTION
       calculates Sb from pmag_results files

    SYNTAX
        scalc_magic -h [command line options]

    INPUT
       takes magic formatted pmag_results (2.5) or sites (3.0) table
       pmag_result_name (2.5)  must start with "VGP: Site"
       must have average_lat (2.5)  or lat (3.0) if spin axis is reference

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input results file, default is 'sites.txt'
        -c cutoff:  specify VGP colatitude cutoff value, default is no cutoff
        -k cutoff: specify kappa cutoff, default is 0
        -crd [s,g,t]: specify coordinate system, default is geographic
        -v : use the VanDammme criterion
        -a: use antipodes of reverse data: default is to use only normal
        -r:  use reverse data only
        -p: do relative to principle axis
        -b: do bootstrap confidence bounds
        -n: set minimum n for samples (specimens) per site
        -dm: data model [3.0 is default, otherwise, 2.5]
        -mm97: correct for within site scatter (McElhinny & McFadden, 1997)
    NOTES
        if kappa, N_site, lat supplied, will consider within site scatter
    OUTPUT
        N Sb  Sb_lower Sb_upper Co-lat. Cutoff

     OUTPUT:
         if option -b used: N,  S_B, lower and upper bounds
         otherwise: N,  S_B, cutoff


Instruction:
Can you create a Python 3 function that
names picks out keys and makes and xy plot_magic_keys. py

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

    DESCRIPTION
        picks out keys and makes and xy plot

    SYNTAX
        plot_magic_keys.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file
        -xkey KEY: specify key for X
        -ykey KEY: specify key  for Y
        -b xmin xmax ymin ymax, sets bounds

    """
    dir_path="./"
    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')
        magic_file=dir_path+'/'+sys.argv[ind+1]
    else:
        print(main.__doc__)
        sys.exit()
    if '-xkey' in sys.argv:
        ind=sys.argv.index('-xkey')
        xkey=sys.argv[ind+1]
        if '-ykey' in sys.argv:
            ind=sys.argv.index('-ykey')
            ykey=sys.argv[ind+1]
    else:
        print(main.__doc__)
        sys.exit()
    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])
    #
    #
    # get data read in
    X,Y=[],[]
    Data,file_type=pmag.magic_read(magic_file)
    if len(Data)>0:
        for rec in Data:
            if xkey in list(rec.keys()) and rec[xkey]!="" and ykey in list(rec.keys()) and rec[ykey]!="":
                try:
                    X.append(float(rec[xkey]))
                    Y.append(float(rec[ykey]))
                except:
                    pass
        FIG={'fig':1}
        pmagplotlib.plot_init(FIG['fig'],5,5)
        if '-b' in sys.argv:
            pmagplotlib.plot_xy(FIG['fig'],X,Y,sym='ro',xlab=xkey,ylab=ykey,xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax )
        else:
            pmagplotlib.plot_xy(FIG['fig'],X,Y,sym='ro',xlab=xkey,ylab=ykey)
        pmagplotlib.draw_figs(FIG)
        ans=input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans=="q": sys.exit()
        if ans=="a":
            files = {}
            for key in list(FIG.keys()):
                files[key]=str(key) + ".svg"
                pmagplotlib.save_plots(FIG,files)
        sys.exit()
    else:
        print('no data to plot')


Instruction:
Make a summary of the following Python 3 code
def main():
    title = ""
    files, fmt = {}, 'svg'
    sym = {'lower': ['o', 'r'], 'upper': ['o', 'w']}
    plot = 0
    if '-h' in sys.argv:  # check if help is needed
        print(main.__doc__)
        sys.exit()  # graceful quit
    if '-sav' in sys.argv:
        plot = 1
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-s' in sys.argv:
        ind = sys.argv.index('-s')
        sym['size'] = int(sys.argv[ind + 1])
    else:
        sym['size'] = 20
    if '-Lsym' in sys.argv:
        ind = sys.argv.index('-Lsym')
        sym['lower'][0] = sys.argv[ind + 1]
        sym['lower'][1] = sys.argv[ind + 2]
    if '-Usym' in sys.argv:
        ind = sys.argv.index('-Usym')
        sym['upper'][0] = sys.argv[ind + 1]
        sym['upper'][1] = sys.argv[ind + 2]
    if '-f' in sys.argv:  # ask for filename
        ind = sys.argv.index('-f')
        fname = sys.argv[ind + 1]
    else:
        print(main.__doc__)
        print(' \n   -f option required')
        sys.exit()  # graceful quit
    DI = numpy.loadtxt(fname)
    EQ = {'eq': 1}
    pmagplotlib.plot_init(EQ['eq'], 5, 5)
    pmagplotlib.plot_eq_sym(EQ['eq'], DI, 'Equal Area Plot', sym)  # make plot
    if plot == 0:
        pmagplotlib.draw_figs(EQ)  # make it visible
    for key in list(EQ.keys()):
        files[key] = key + '.' + fmt
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['eq'] = 'Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ, titles, black, purple)
        pmagplotlib.save_plots(EQ, files)
    elif plot == 1:
        fname = os.path.split(fname)[1].split('.')[0]
        files['eq'] = fname + '_eq.' + fmt
        pmagplotlib.save_plots(EQ, files)
    else:
        ans = input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans == "a":
            pmagplotlib.save_plots(EQ, files)

Response:
NAME eqarea. py
    DESCRIPTION
       makes equal area projections from declination and inclination data


Instruction:
Given the following Python 3 function, write the documentation
def main():
    fmt,nb='svg',1000
    plot=0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
    else:
        print(main.__doc__)
        sys.exit()
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        nb=int(sys.argv[ind+1])
    if '-sc' in sys.argv:
        site_correction = True
    else:
        site_correction = False
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-sav' in sys.argv:plot=1
    data=numpy.loadtxt(file)
    upper,lower=int(round(.975*nb)),int(round(.025*nb))
    E,I=[],[]
    PLTS={'eq':1,'ei':2,'cdf':3,'v2':4}
    pmagplotlib.plot_init(PLTS['eq'],6,6)
    pmagplotlib.plot_init(PLTS['ei'],5,5)
    pmagplotlib.plot_init(PLTS['cdf'],5,5)
    pmagplotlib.plot_init(PLTS['v2'],5,5)
    pmagplotlib.plot_eq(PLTS['eq'],data,'Data')
    # this is a problem
    #if plot==0:pmagplotlib.draw_figs(PLTS)
    ppars=pmag.doprinc(data)
    Io=ppars['inc']
    n=ppars["N"]
    Es,Is,Fs,V2s=pmag.find_f(data)
    if site_correction:
        Inc,Elong=Is[Es.index(min(Es))],Es[Es.index(min(Es))]
        flat_f = Fs[Es.index(min(Es))]
    else:
        Inc,Elong=Is[-1],Es[-1]
        flat_f = Fs[-1]
    pmagplotlib.plot_ei(PLTS['ei'],Es,Is,flat_f)
    pmagplotlib.plot_v2s(PLTS['v2'],V2s,Is,flat_f)
    b=0
    print("Bootstrapping.... be patient")
    while b<nb:
        bdata=pmag.pseudo(data)
        Esb,Isb,Fsb,V2sb=pmag.find_f(bdata)
        if b<25:
            pmagplotlib.plot_ei(PLTS['ei'],Esb,Isb,Fsb[-1])
        if Esb[-1]!=0:
            ppars=pmag.doprinc(bdata)
            if site_correction:
                I.append(abs(Isb[Esb.index(min(Esb))]))
                E.append(Esb[Esb.index(min(Esb))])
            else:
                I.append(abs(Isb[-1]))
                E.append(Esb[-1])
            b+=1
            if b%25==0:print(b,' out of ',nb)
    I.sort()
    E.sort()
    Eexp=[]
    for i in I:
       Eexp.append(pmag.EI(i))
    if Inc==0:
        title= 'Pathological Distribution: '+'[%7.1f, %7.1f]' %(I[lower],I[upper])
    else:
        title= '%7.1f [%7.1f, %7.1f]' %( Inc, I[lower],I[upper])
    pmagplotlib.plot_ei(PLTS['ei'],Eexp,I,1)
    pmagplotlib.plot_cdf(PLTS['cdf'],I,'Inclinations','r',title)
    pmagplotlib.plot_vs(PLTS['cdf'],[I[lower],I[upper]],'b','--')
    pmagplotlib.plot_vs(PLTS['cdf'],[Inc],'g','-')
    pmagplotlib.plot_vs(PLTS['cdf'],[Io],'k','-')
    if plot==0:
        print('%7.1f %s %7.1f _ %7.1f ^ %7.1f:  %6.4f _ %6.4f ^ %6.4f' %(Io, " => ", Inc, I[lower],I[upper], Elong, E[lower],E[upper]))
        print("Io Inc  I_lower, I_upper, Elon, E_lower, E_upper")
        pmagplotlib.draw_figs(PLTS)
        ans = ""
        while ans not in ['q', 'a']:
            ans= input("S[a]ve plots - <q> to quit:  ")
        if ans=='q':
           print("\n Good bye\n")
           sys.exit()

    files={}
    files['eq']='findEI_eq.'+fmt
    files['ei']='findEI_ei.'+fmt
    files['cdf']='findEI_cdf.'+fmt
    files['v2']='findEI_v2.'+fmt
    pmagplotlib.save_plots(PLTS,files)

Response: This is the main function for the unflattening_EI_tangent function. It is used to find the unflattening_EI_tangent function that is used to calculate the unflattening_EI_tangent function. It is used to calculate the unflattening_EI_tangent function and the unflattening_EI_tangent function.


Instruction:
Here you have a function in Python 3, explain what it does
def on_change_dir_button(self, event):
        currentDirectory = self.WD #os.getcwd()
        change_dir_dialog = wx.DirDialog(self.panel,
                                         "Choose your working directory to create or edit a MagIC contribution:",
                                         defaultPath=currentDirectory,
                                         style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON | wx.DD_CHANGE_DIR)
        result = change_dir_dialog.ShowModal()
        if result == wx.ID_CANCEL:
            return
        if result == wx.ID_OK:
            self.WD = change_dir_dialog.GetPath()
            self.dir_path.SetValue(self.WD)
        change_dir_dialog.Destroy()
        wait = wx.BusyInfo('Initializing data object in new directory, please wait...')
        wx.SafeYield()
        print('-I- Initializing magic data object')
        # make new builder object, but reuse old data_model
        self.er_magic = builder.ErMagicBuilder(self.WD, self.er_magic.data_model)
        print('-I- Read in any available data from working directory')
        self.er_magic.get_all_magic_info()
        print('-I- Initializing headers')
        self.er_magic.init_default_headers()
        self.er_magic.init_actual_headers()
        del wait

Response: Create a new directory dialog and initialize the data object


Instruction:
Explain what the following Python 3 code does
def make_grid_frame(self, event):
        if self.grid_frame:
            print('-I- You already have a grid frame open')
            pw.simple_warning("You already have a grid open")
            return

        try:
            grid_type = event.GetButtonObj().Name[:-4] # remove '_btn'
        except AttributeError:
            grid_type = self.FindWindowById(event.Id).Name[:-4] # remove ('_btn')
        wait = wx.BusyInfo('Making {} grid, please wait...'.format(grid_type))
        wx.SafeYield()
        # hide mainframe
        self.on_open_grid_frame()
        self.grid_frame = grid_frame.GridFrame(self.er_magic, self.WD, grid_type, grid_type, self.panel)
        if self.validation_mode:
            if grid_type in self.validation_mode:
                self.grid_frame.grid.paint_invalid_cells(self.warn_dict[grid_type])
                #self.grid_frame.msg_boxsizer
                current_label = self.grid_frame.msg_text.GetLabel()
                add_text = """\n\nColumns and rows with problem data have been highlighted in blue.
Cells with problem data are highlighted with different colors according to the type of problem.
Red: missing required data
Green: missing or invalid parent
Blue: non-numeric data provided in a numeric field
Gray: unrecognized column
Purple: invalid result child
Yellow: Out-of-range latitude (should be -90 - 90) or longitude (should be 0-360)
Light gray: Unrecognized term in controlled vocabulary

Note: It is possible to have a row highlighted that has no highlighted column.
This means that you are missing information higher up in the data.
For example: a specimen could be missing a site name.
However, you need to fix this in the sample grid, not the specimen grid.
Once each item in the data has its proper parent, validations will be correct.
"""
                self.grid_frame.msg_text.SetLabel(add_text)
        #self.on_finish_change_dir(self.change_dir_dialog)
        del wait

Response: Create a grid frame for the data type of the button that was clicked


Instruction:
Write a Python 3 script for
writing all data to appropriate er_* and pmag_* files. Then use those files to create a MagIC upload format file. Validate the upload file.

Response:
def on_upload_file(self, event):
        """
        Write all data to appropriate er_* and pmag_* files.
        Then use those files to create a MagIC upload format file.
        Validate the upload file.
        """
        # coherence validations
        wait = wx.BusyInfo('Validating data, please wait...')
        wx.SafeYield()
        spec_warnings, samp_warnings, site_warnings, loc_warnings = self.er_magic.validate_data()
        result_warnings = self.er_magic.validate_results(self.er_magic.results)
        meas_warnings = self.er_magic.validate_measurements(self.er_magic.measurements)
        self.warn_dict = {'specimen': spec_warnings, 'sample': samp_warnings,
                          'site': site_warnings, 'location': loc_warnings,
                          'result': result_warnings, 'age': {}, 'measurement': meas_warnings}
        # done coherence validations
        del wait
        # write upload file and perform data validations
        wait = wx.BusyInfo('Making upload file, please wait...')
        wx.SafeYield()
        self.er_magic.write_files()
        upfile, error_message, errors = ipmag.upload_magic(dir_path=self.WD,
                                                           data_model=self.data_model)
        del wait
        if upfile:
            text = "You are ready to upload.\nYour file:\n{}\nwas generated in directory: \n{}\nDrag and drop this file in the MagIC database.".format(os.path.split(upfile)[1], self.WD)
            dlg = wx.MessageDialog(self, caption="Saved", message=text, style=wx.OK)
        else:
            text = "There were some problems with the creation of your upload file.\nError message: {}\nSee Terminal/Command Prompt for details".format(error_message)
            dlg = wx.MessageDialog(self, caption="Error", message=text, style=wx.OK)
        result = dlg.ShowModal()
        if result == wx.ID_OK:
            dlg.Destroy()
        self.edited = False
        ## add together data & coherence errors into one dictionary
        if errors:
            for item_type in errors:
                for item_name in errors[item_type]:
                    if item_name in self.warn_dict[item_type]:
                        self.warn_dict[item_type][item_name].update(errors[item_type][item_name])
                    else:
                        self.warn_dict[item_type][item_name] = errors[item_type][item_name]

        has_problems = []
        for item_type, warnings in list(self.warn_dict.items()):
            if warnings:
                has_problems.append(item_type)
        # for any dtypes with validation problems (data or coherence),
        # highlight the button to the corresponding grid
        # skip this step for Windows
        if sys.platform in ['win32', 'win62']:
            pass
        else:
            for dtype in self.warn_dict:
                wind = self.FindWindowByName(dtype + '_btn')
                if wind:
                    if dtype in has_problems:
                        wind.Bind(wx.EVT_PAINT, self.highlight_button)
                    else:
                        wind.Unbind(wx.EVT_PAINT, handler=self.highlight_button)
            self.Refresh()
        if has_problems:
            self.validation_mode = set(has_problems)
            if sys.platform in ['win32', 'win62']:
                self.message.SetLabel('The following grid(s) have incorrect or incomplete data:\n{}'.format(', '.join(self.validation_mode)))
            else:
                self.message.SetLabel('Highlighted grids have incorrect or incomplete data')
            self.bSizer_msg.ShowItems(True)
            self.hbox.Fit(self)
        if not has_problems:
            self.validation_mode = set()
            self.message.SetLabel('')
            self.bSizer_msg.ShowItems(False)
            self.hbox.Fit(self)


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:
            print('-I- Clear data object')
            self.parent.er_magic = builder.ErMagicBuilder(self.parent.WD, self.parent.data_model)
            print('-I- Initializing headers')
            self.parent.er_magic.init_default_headers()
            self.parent.er_magic.init_actual_headers()

Response: Clear the data object


Instruction:
How would you explain what the following Python 3 function does
def main():
    #
    # initialize variables
    #
    version_num=pmag.get_version()
    orient_file,samp_file = "orient","er_samples.txt"
    args=sys.argv
    dir_path,out_path='.','.'
    default_outfile = True
    #
    #
    if '-WD' in args:
        ind=args.index('-WD')
        dir_path=args[ind+1]
    if '-OD' in args:
        ind=args.index('-OD')
        out_path=args[ind+1]
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if "-F" in args:
        ind=args.index("-F")
        orient_file=sys.argv[ind+1]
        default_outfile = False
    if "-f" in args:
        ind=args.index("-f")
        samp_file=sys.argv[ind+1]
    orient_file=out_path+'/'+orient_file
    samp_file=dir_path+'/'+samp_file
    #
    # read in file to convert
    #
    ErSamples=[]
    Required=['sample_class','sample_type','sample_lithology','lat','long']
    Samps,file_type=pmag.magic_read(samp_file)
    Locs=[]
    OrKeys=['sample_name','site_name','mag_azimuth','field_dip','sample_class','sample_type','sample_lithology','lat','long','stratigraphic_height','method_codes','site_description']
    print("file_type", file_type) # LJ
    if file_type.lower()=='er_samples':
        SampKeys=['er_sample_name','er_site_name','sample_azimuth','sample_dip','sample_class','sample_type','sample_lithology','sample_lat','sample_lon','sample_height','magic_method_codes','er_sample_description']
    elif file_type.lower()=='magic_measurements':
        SampKeys=['er_sample_name','er_site_name']
    else:
        print('wrong file format; must be er_samples or magic_measurements only')
    for samp in Samps:
            if samp['er_location_name'] not in Locs:Locs.append(samp['er_location_name']) # get all the location names
    for location_name in Locs:
        loc_samps=pmag.get_dictitem(Samps,'er_location_name',location_name,'T')
        OrOut=[]
        for samp in loc_samps:
            if samp['er_sample_name'] not in ErSamples:
                ErSamples.append(samp['er_sample_name'])
                OrRec={}
                if 'sample_date' in list(samp.keys()) and samp['sample_date'].strip()!="":
                    date=samp['sample_date'].split(':')
                    OrRec['date']=date[1]+'/'+date[2]+'/'+date[0][2:4]
                for i in range(len(SampKeys)):
                    if SampKeys[i] in list(samp.keys()):OrRec[OrKeys[i]]=samp[SampKeys[i]]
                for key in Required:
                    if key not in list(OrRec.keys()):OrRec[key]="" # fill in blank required keys
                OrOut.append(OrRec)
        loc=location_name.replace(" ","_")
        if default_outfile:
            outfile=orient_file+'_'+loc+'.txt'
        else:
            outfile=orient_file
        pmag.magic_write(outfile,OrOut,location_name)
        print("Data saved in: ", outfile)

Response: A function that takes an er_samples or magic_measurements format file and creates an orient. txt file for the new sample set and returns a template for the new sample set.


Instruction:
Given the following Python 3 function, write the documentation
def main():
    if len(sys.argv) > 0:
        if '-h' in sys.argv: # check if help is needed
            print(main.__doc__)
            sys.exit() # graceful quit
        if '-f' in sys.argv: # ask for filename
            ind=sys.argv.index('-f')
            file=sys.argv[ind+1]
            f=open(file,'r')
            data=f.readlines()
        else:
            data=sys.stdin.readlines() # read in data from standard input
    DIs= [] # set up list for dec inc data
    ofile = ""
    if '-F' in sys.argv: # set up output file
        ind = sys.argv.index('-F')
        ofile= sys.argv[ind+1]
        out = open(ofile, 'w + a')
    for line in data:   # read in the data from standard input
        if '\t' in line:
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        DIs.append((float(rec[0]),float(rec[1])))
#
    bpars=pmag.dobingham(DIs)
    output = '%7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %i' % (bpars["dec"],bpars["inc"],bpars["Eta"],bpars["Edec"],bpars["Einc"],bpars["Zeta"],bpars["Zdec"],bpars["Zinc"],bpars["n"])
    if ofile == "":
        print(output)
    else:
        out.write(output+'\n')

Response:
NAME
ATTRIBS get_n_record_from_dec_inc_file DESCRIPTION get_n_record_from_dec_inc_file DESCRIPTION get_n_record_from_dec_inc_file DESCRIPTION get_n_record_from_dec_inc_file DESCRIPTION get_n_record_from_dec_inc_file DESCRIPTION get_n_record_from_dec_file DESCRIPTION get_n_record_from_dec_file DESCRIPTION get_n


Instruction:
Can you write a function in Python 3 where it
names atrm_magic.py DESCRIPTION Converts ATRM data to best-fit tensor (6 elements plus sigma) Original program ARMcrunch written to accomodate ARM anisotropy data collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the off-axis remanence terms to construct the tensor. A better way to do the anisotropy of ARMs is to use 9,12 or 15 measurements in the Hext rotational scheme. SYNTAX atrm_magic.py [-h][command line options] OPTIONS -h prints help message and quits -f FILE: specify input file, default is atrm_measurements.txt -fsp FILE: specimen input file, default is specimens.txt (optional) -Fsp FILE: specify output file, default is specimens.txt (MagIC 3 only) -DM DATA_MODEL: specify MagIC 2 or MagIC 3, default is 3 INPUT Input for the present program is a TRM acquisition data with an optional baseline. The order of the measurements is: Decs=[0,90,0,180,270,0,0,90,0] Incs=[0,0,90,0,0,-90,0,0,90] The last two measurements are optional

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

    DESCRIPTION
        Converts ATRM  data to best-fit tensor (6 elements plus sigma)
         Original program ARMcrunch written to accomodate ARM anisotropy data
          collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the
          off-axis remanence terms to construct the tensor. A better way to
          do the anisotropy of ARMs is to use 9,12 or 15 measurements in
          the Hext rotational scheme.

    SYNTAX
        atrm_magic.py [-h][command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is atrm_measurements.txt
        -fsp FILE: specimen input file, default is specimens.txt (optional)
        -Fsp FILE: specify output file, default is specimens.txt (MagIC 3 only)
        -DM DATA_MODEL: specify MagIC 2 or MagIC 3, default is 3

    INPUT
        Input for the present program is a TRM acquisition data with an optional baseline.
      The order of the measurements is:
    Decs=[0,90,0,180,270,0,0,90,0]
    Incs=[0,0,90,0,0,-90,0,0,90]
     The last two measurements are optional

    """
    # initialize some parameters
    args = sys.argv
    if "-h" in args:
        print(main.__doc__)
        sys.exit()

    #if "-Fa" in args:
    #    ind = args.index("-Fa")
    #    rmag_anis = args[ind + 1]
    #if "-Fr" in args:
    #    ind = args.index("-Fr")
    #    rmag_res = args[ind + 1]

    #meas_file = "atrm_measurements.txt"
    #rmag_anis = "trm_anisotropy.txt"
    #rmag_res = "atrm_results.txt"

    dir_path = pmag.get_named_arg("-WD", ".")
    input_dir_path = pmag.get_named_arg("-ID", "")
    meas_file = pmag.get_named_arg("-f", "measurements.txt")
    data_model_num = int(pmag.get_named_arg("-DM", 3))
    spec_outfile = pmag.get_named_arg("-Fsp", "specimens.txt")
    spec_infile = pmag.get_named_arg("-fsp", "specimens.txt")

    ipmag.atrm_magic(meas_file, dir_path, input_dir_path,
                     spec_infile, spec_outfile, data_model_num)


Instruction:
Explain what the following Python 3 code does
def main(command_line=True, **kwargs):
    #
    # initialize defaults
    version_num=pmag.get_version()
    meas_file='magic_measurements.txt'
    spec_file='er_specimens.txt'
    samp_file='er_samples.txt'
    site_file='er_sites.txt'
    csv_file=''
    ErSpecs,ErSamps,ErSites,ErLocs,ErCits=[],[],[],[],[]
    MagRecs=[]
    citation="This study"
    dir_path,demag='.','NRM'
    args=sys.argv
    noave=0
    depth_method='a'
    # get command line args
    if command_line:
        if '-WD' in args:
            ind=args.index("-WD")
            dir_path=args[ind+1]
        if '-ID' in args:
            ind = args.index('-ID')
            input_dir_path = args[ind+1]
        else:
            input_dir_path = dir_path
        output_dir_path = dir_path
        if "-h" in args:
            print(main.__doc__)
            return False
        if "-A" in args: noave=1
        if '-f' in args:
            ind=args.index("-f")
            csv_file=args[ind+1]
        if '-F' in args:
            ind=args.index("-F")
            meas_file=args[ind+1]
        if '-Fsp' in args:
            ind=args.index("-Fsp")
            spec_file = args[ind+1]
        if '-Fsi' in args:
            ind=args.index("-Fsi")
            site_file=args[ind+1]
        if '-Fsa' in args:
            ind=args.index("-Fsa")
            samp_file = args[ind+1]

    if not command_line:
        dir_path = kwargs.get('dir_path', '.')
        input_dir_path = kwargs.get('input_dir_path', dir_path)
        output_dir_path = dir_path # rename dir_path after input_dir_path is set
        noave = kwargs.get('noave', 0) # default (0) is DO average
        csv_file = kwargs.get('csv_file', '')
        meas_file = kwargs.get('meas_file', 'magic_measurements.txt')
        spec_file = kwargs.get('spec_file', 'er_specimens.txt')
        samp_file = kwargs.get('samp_file', 'er_samples.txt')
        site_file = kwargs.get('site_file', 'er_sites.txt')

    # format variables

    meas_file = os.path.join(output_dir_path, meas_file)
    spec_file = os.path.join(output_dir_path, spec_file)
    Specs,file_type = pmag.magic_read(spec_file)
    samp_file = os.path.join(output_dir_path, samp_file)
    ErSamps,file_type = pmag.magic_read(samp_file)
    site_file = os.path.join(output_dir_path, site_file)
    if csv_file=="":
        filelist=os.listdir(input_dir_path) # read in list of files to import
    else:
        csv_file = os.path.join(input_dir_path, csv_file)
        filelist=[csv_file]

    # parsing the data
    specimens,samples,sites=[],[],[]
    MagRecs,SpecRecs,SampRecs,SiteRecs=[],[],[],[]
    for samp in ErSamps:
        if samp['er_sample_name'] not in samples:
            samples.append(samp['er_sample_name'])
            SampRecs.append(samp)
    file_found = False
    for f in filelist: # parse each file
        if f[-3:].lower()=='csv':
            file_found = True
            print('processing: ',f)
            full_file = os.path.join(input_dir_path, f)
            with open(full_file, 'r') as fin:
                file_input = fin.readlines()
            keys=file_input[0].replace('\n','').split(',') # splits on underscores
            if "Interval Top (cm) on SHLF" in keys:interval_key="Interval Top (cm) on SHLF"
            if " Interval Bot (cm) on SECT" in keys:interval_key=" Interval Bot (cm) on SECT"
            if "Offset (cm)" in keys: interval_key="Offset (cm)"
            if "Top Depth (m)" in keys:depth_key="Top Depth (m)"
            if "CSF-A Top (m)" in keys:depth_key="CSF-A Top (m)"
            if "Depth CSF-A (m)" in keys:depth_key="Depth CSF-A (m)"
            if "CSF-B Top (m)" in keys:
                comp_depth_key="CSF-B Top (m)" # use this model if available
            elif "Depth CSF-B (m)" in keys:
                comp_depth_key="Depth CSF-B (m)"
            else:
                comp_depth_key=""
            if "Demag level (mT)" in keys:demag_key="Demag level (mT)"
            if "Demag Level (mT)" in keys: demag_key="Demag Level (mT)"
            if "Inclination (Tray- and Bkgrd-Corrected) (deg)" in keys:inc_key="Inclination (Tray- and Bkgrd-Corrected) (deg)"
            if "Inclination background + tray corrected  (deg)" in keys:inc_key="Inclination background + tray corrected  (deg)"
            if "Inclination background + tray corrected  (\xc2\xb0)" in keys:inc_key="Inclination background + tray corrected  (\xc2\xb0)"
            if "Inclination background & tray corrected (deg)" in keys:inc_key="Inclination background & tray corrected (deg)"
            if "Declination (Tray- and Bkgrd-Corrected) (deg)" in keys:dec_key="Declination (Tray- and Bkgrd-Corrected) (deg)"
            if "Declination background + tray corrected (deg)" in keys:dec_key="Declination background + tray corrected (deg)"
            if "Declination background + tray corrected (\xc2\xb0)" in keys:dec_key="Declination background + tray corrected (\xc2\xb0)"
            if "Declination background & tray corrected (deg)" in keys:dec_key="Declination background & tray corrected (deg)"
            if "Intensity (Tray- and Bkgrd-Corrected) (A/m)" in keys:int_key="Intensity (Tray- and Bkgrd-Corrected) (A/m)"
            if "Intensity background + tray corrected  (A/m)" in keys:int_key="Intensity background + tray corrected  (A/m)"
            if "Intensity background & tray corrected (A/m)" in keys:int_key="Intensity background & tray corrected (A/m)"
            if "Core Type" in keys:
                core_type="Core Type"
            else: core_type="Type"
            if 'Run Number' in keys: run_number_key='Run Number'
            if 'Test No.' in keys: run_number_key='Test No.'
            if 'Test Changed On' in keys: date_key='Test Changed On'
            if "Timestamp (UTC)" in keys: date_key="Timestamp (UTC)"
            if "Section" in keys: sect_key="Section"
            if "Sect" in keys: sect_key="Sect"
            if 'Section Half' in keys: half_key='Section Half'
            if "A/W" in keys: half_key="A/W"
            if "Text ID" in keys: text_id="Text ID"
            if "Text Id" in keys: text_id="Text Id"
            for line in file_input[1:]:
              InRec={}
              test=0
              recs=line.split(',')
              for k in range(len(keys)):
                  if len(recs)==len(keys):
                      InRec[keys[k]]=line.split(',')[k]
              if InRec['Exp']!="": test=1 # get rid of pesky blank lines
              if test==1:
                run_number=""
                inst="IODP-SRM"
                volume='15.59' # set default volume to this
                MagRec,SpecRec,SampRec,SiteRec={},{},{},{}
                expedition=InRec['Exp']
                location=InRec['Site']+InRec['Hole']
# Maintain backward compatibility for the ever-changing LIMS format (Argh!)
                while len(InRec['Core'])<3:
                    InRec['Core']='0'+InRec['Core']
                if "Last Tray Measurment" in list(InRec.keys()) and "SHLF" not in InRec[text_id] or 'dscr' in csv_file :  # assume discrete sample
                    specimen=expedition+'-'+location+'-'+InRec['Core']+InRec[core_type]+"-"+InRec[sect_key]+'-'+InRec[half_key]+'-'+str(InRec[interval_key])
                else: # mark as continuous measurements
                    specimen=expedition+'-'+location+'-'+InRec['Core']+InRec[core_type]+"_"+InRec[sect_key]+InRec[half_key]+'-'+str(InRec[interval_key])
                SpecRec['er_expedition_name']=expedition
                SpecRec['er_location_name']=location
                SpecRec['er_site_name']=specimen
                SpecRec['er_citation_names']=citation
                for key in list(SpecRec.keys()):SampRec[key]=SpecRec[key]
                for key in list(SpecRec.keys()):SiteRec[key]=SpecRec[key]
                SampRec['sample_azimuth']='0'
                SampRec['sample_dip']='0'
                SampRec['sample_core_depth']=InRec[depth_key]
                if comp_depth_key!='':
                    SampRec['sample_composite_depth']=InRec[comp_depth_key]
                if "SHLF" not in InRec[text_id]:
                    SampRec['magic_method_codes']='FS-C-DRILL-IODP:SP-SS-C:SO-V'
                else:
                    SampRec['magic_method_codes']='FS-C-DRILL-IODP:SO-V'
                SpecRec['er_specimen_name']=specimen
                SpecRec['er_sample_name']=specimen
                SampRec['er_sample_name']=specimen
                SampRec['er_specimen_names']=specimen
                SiteRec['er_specimen_names']=specimen

                for key in list(SpecRec.keys()):MagRec[key]=SpecRec[key]
# set up measurement record - default is NRM
                #MagRec['er_analyst_mail_names']=InRec['Test Entered By']
                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"
                SpecRec['er_specimen_alternatives']=InRec[text_id]
                if 'Sample Area (cm?)' in list(InRec.keys()) and  InRec['Sample Area (cm?)']!= "": volume=InRec['Sample Area (cm?)']
                if InRec[run_number_key]!= "": run_number=InRec[run_number_key]
                datestamp=InRec[date_key].split() # date time is second line of file
                if '/' in datestamp[0]:
                    mmddyy=datestamp[0].split('/') # break into month day year
                    if len(mmddyy[0])==1: mmddyy[0]='0'+mmddyy[0] # make 2 characters
                    if len(mmddyy[1])==1: mmddyy[1]='0'+mmddyy[1] # make 2 characters
                    if len(datestamp[1])==1: datestamp[1]='0'+datestamp[1] # make 2 characters
                    date='20'+mmddyy[2]+':'+mmddyy[0]+":"+mmddyy[1] +':' +datestamp[1]+":00.00"
                if '-' in datestamp[0]:
                    mmddyy=datestamp[0].split('-') # break into month day year
                    date=mmddyy[0]+':'+mmddyy[1]+":"+mmddyy[2] +':' +datestamp[1]+":00.00"
                MagRec["measurement_date"]=date
                MagRec["magic_method_codes"]='LT-NO'
                if InRec[demag_key]!="0":
                    MagRec['magic_method_codes'] = 'LT-AF-Z'
                    inst=inst+':IODP-SRM-AF' # measured on shipboard in-line 2G AF
                    treatment_value=float(InRec[demag_key].strip('"'))*1e-3 # convert mT => T
                    MagRec["treatment_ac_field"]=treatment_value # AF demag in treat mT => T
                if 'Treatment Type' in list(InRec.keys()) and InRec['Treatment Type']!="":
                    if 'Alternating Frequency' in InRec['Treatment Type']:
                        MagRec['magic_method_codes'] = 'LT-AF-Z'
                        inst=inst+':I`ODP-DTECH' # measured on shipboard Dtech D2000
                        treatment_value=float(InRec['Treatment Value'])*1e-3 # convert mT => T
                        MagRec["treatment_ac_field"]=treatment_value # AF demag in treat mT => T
                    elif 'Thermal' in InRec['Treatment Type']:
                        MagRec['magic_method_codes'] = 'LT-T-Z'
                        inst=inst+':IODP-TDS' # measured on shipboard Schonstedt thermal demagnetizer
                        treatment_value=float(InRec['Treatment Value'])+273 # convert C => K
                        MagRec["treatment_temp"]='%8.3e'%(treatment_value) #
                MagRec["measurement_standard"]='u' # assume all data are "good"
                vol=float(volume)*1e-6 # convert from cc to m^3
                if run_number!="":
                    MagRec['external_database_ids']=run_number
                    MagRec['external_database_names']='LIMS'
                else:
                    MagRec['external_database_ids']=""
                    MagRec['external_database_names']=''
                MagRec['measurement_inc']=InRec[inc_key].strip('"')
                MagRec['measurement_dec']=InRec[dec_key].strip('"')
                intens= InRec[int_key].strip('"')
                MagRec['measurement_magn_moment']='%8.3e'%(float(intens)*vol) # convert intensity from A/m to Am^2 using vol
                MagRec['magic_instrument_codes']=inst
                MagRec['measurement_number']='1'
                MagRec['measurement_csd']=''
                MagRec['measurement_positions']=''
                MagRecs.append(MagRec)
                if specimen not in specimens:
                    specimens.append(specimen)
                    SpecRecs.append(SpecRec)
                if MagRec['er_sample_name']  not in samples:
                    samples.append(MagRec['er_sample_name'])
                    SampRecs.append(SampRec)
                if MagRec['er_site_name']  not in sites:
                    sites.append(MagRec['er_site_name'])
                    SiteRecs.append(SiteRec)
              #except:
              #   print 'Boo-boo somewhere - no idea where'
    if not file_found:
        print("No .csv files were found")
        return False, "No .csv files were found"
    if len(SpecRecs)>0:
        print('spec_file', spec_file)
        pmag.magic_write(spec_file,SpecRecs,'er_specimens')
        #print 'specimens stored in ',spec_file
    if len(SampRecs)>0:
        SampOut,keys=pmag.fillkeys(SampRecs)
        pmag.magic_write(samp_file,SampOut,'er_samples')
        #print 'samples stored in ',samp_file
    if len(SiteRecs)>0:
        pmag.magic_write(site_file,SiteRecs,'er_sites')
        #print 'sites stored in ',site_file
    MagSort=pmag.sortbykeys(MagRecs,["er_specimen_name","treatment_ac_field"])
    MagOuts=[]
    for MagRec in MagSort:
       MagRec["treatment_ac_field"]='%8.3e'%(MagRec['treatment_ac_field']) # convert to string
       MagOuts.append(MagRec)
    Fixed=pmag.measurements_methods(MagOuts,noave)
    if pmag.magic_write(meas_file,Fixed,'magic_measurements'):
        print('data stored in ',meas_file)
        return True, meas_file
    else:
        print('no data found.  bad magfile?')
        return False, 'no data found.  bad magfile?'

Response: This function is the main function for the iodp_srm_magic. py script.


Instruction:
How would you explain what the following Python 3 function does
def main():
    citation='This study'
    MeasRecs=[]
    units='cgs'
    meth="LP-HYS"
    version_num=pmag.get_version()
    args=sys.argv
    fmt='old'
    er_sample_name,er_site_name,er_location_name="","",""
    inst=""
    er_location_name="unknown"
    er_synthetic_name=""
    user=""
    er_site_name=""
    dir_path='.'
    dm=3
    if "-WD" in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    if "-ID" in args:
        ind = args.index("-ID")
        input_dir_path = args[ind+1]
    else:
        input_dir_path = dir_path
    output_dir_path = dir_path
    specfile = output_dir_path+'/er_specimens.txt'
    output = output_dir_path+"/agm_measurements.txt"
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if "-bak" in args:
        meth="LP-IRM-DCD"
        output = output_dir_path+"/irm_measurements.txt"
    if "-new" in args: fmt='new'
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        output = output_dir_path+'/'+args[ind+1]
    if '-f' in args:
        ind=args.index("-f")
        agm_file= input_dir_path+'/'+args[ind+1]
        er_specimen_name=args[ind+1].split('.')[0]
    else:
        print("agm_file field is required option")
        print(main.__doc__)
        sys.exit()
    if '-Fsp' in args:
        ind=args.index("-Fsp")
        specfile= output_dir_path+'/'+args[ind+1]
    specnum,samp_con,Z=0,'1',1
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if "-spn" in args:
        ind=args.index("-spn")
        er_specimen_name=args[ind+1]
    #elif "-syn" not in args:
    #    print "you must specify a specimen name"
    #    sys.exit()
    if "-syn" in args:
        ind=args.index("-syn")
        er_synthetic_name=args[ind+1]
        er_specimen_name=""
    if "-loc" in args:
        ind=args.index("-loc")
        er_location_name=args[ind+1]
    if "-fsa" in args:
        ind=args.index("-fsa")
        sampfile = input_dir_path+'/'+args[ind+1]
        Samps,file_type=pmag.magic_read(sampfile)
        print('sample_file successfully read in')
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print("option [4] must be in form 4-Z where Z is an integer")
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print("option [7] must be in form 7-Z where Z is an integer")
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    if "-ins" in args:
        ind=args.index("-ins")
        inst=args[ind+1]
    if "-u" in args:
        ind=args.index("-u")
        units=args[ind+1]
    dm = pmag.get_named_arg("-DM", 2)
    ErSpecRecs,filetype=pmag.magic_read(specfile)
    ErSpecRec,MeasRec={},{}
    ErSpecRec['er_citation_names']="This study"
    ErSpecRec['er_specimen_name']=er_specimen_name
    ErSpecRec['er_synthetic_name']=er_synthetic_name
    if specnum!=0:
        ErSpecRec["er_sample_name"]=er_specimen_name[:specnum]
    else:
        ErSpecRec["er_sample_name"]=er_specimen_name
    if "-fsa" in args and er_synthetic_name=="":
        for samp in Samps:
            if samp["er_sample_name"] == ErSpecRec["er_sample_name"]:
                ErSpecRec["er_location_name"]=samp["er_location_name"]
                ErSpecRec["er_site_name"]=samp["er_site_name"]
                break
    elif int(samp_con)!=6 and int(samp_con)!=8:
        site=pmag.parse_site(ErSpecRec['er_sample_name'],samp_con,Z)
        ErSpecRec["er_site_name"]=site
        ErSpecRec["er_location_name"]=er_location_name
    ErSpecRec['er_scientist_mail_names']=user.strip()
    insert=1
    for rec in ErSpecRecs:
        if rec['er_specimen_name']==er_specimen_name:
            insert=0
            break
    if insert==1:
        ErSpecRecs.append(ErSpecRec)
        ErSpecRecs,keylist=pmag.fillkeys(ErSpecRecs)
        pmag.magic_write(specfile,ErSpecRecs,'er_specimens')
        print("specimen name put in ",specfile)
    f=open(agm_file,'r')
    Data=f.readlines()
    if "ASCII" not in Data[0]:fmt='new'
    measnum,start=1,""
    if fmt=='new': # new Micromag formatted file
        end=2
        for skip in range(len(Data)):
            line=Data[skip]
            rec=line.split()
            if 'Units' in line:units=rec[-1]
            if "Raw" in rec:
                start=skip+2
            if "Field" in rec and "Moment" in rec and start=="":
                start=skip+2
                break
    else:
        start = 2
        end=1
    for i in range(start,len(Data)-end): # skip header stuff

        MeasRec={}
        for key in list(ErSpecRec.keys()):
            MeasRec[key]=ErSpecRec[key]
        MeasRec['magic_instrument_codes']=inst
        MeasRec['magic_method_codes']=meth
        if 'er_synthetic_name' in list(MeasRec.keys()) and MeasRec['er_synthetic_name']!="":
            MeasRec['magic_experiment_name']=er_synthetic_name+':'+meth
        else:
            MeasRec['magic_experiment_name']=er_specimen_name+':'+meth
        line=Data[i]
        rec=line.split(',') # data comma delimited
        if rec[0]!='\n':
            if units=='cgs':
                field =float(rec[0])*1e-4 # convert from oe to tesla
            else:
                field =float(rec[0]) # field in tesla
            if meth=="LP-HYS":
                MeasRec['measurement_lab_field_dc']='%10.3e'%(field)
                MeasRec['treatment_dc_field']=''
            else:
                MeasRec['measurement_lab_field_dc']=''
                MeasRec['treatment_dc_field']='%10.3e'%(field)
            if units=='cgs':
                MeasRec['measurement_magn_moment']='%10.3e'%(float(rec[1])*1e-3) # convert from emu to Am^2
            else:
                MeasRec['measurement_magn_moment']='%10.3e'%(float(rec[1])) # Am^2
            MeasRec['treatment_temp']='273' # temp in kelvin
            MeasRec['measurement_temp']='273' # temp in kelvin
            MeasRec['measurement_flag']='g'
            MeasRec['measurement_standard']='u'
            MeasRec['measurement_number']='%i'%(measnum)
            measnum+=1
            MeasRec['magic_software_packages']=version_num
            MeasRecs.append(MeasRec)
# now we have to relabel LP-HYS method codes.  initial loop is LP-IMT, minor loops are LP-M  - do this in measurements_methods function
    if meth=='LP-HYS':
        recnum=0
        while float(MeasRecs[recnum]['measurement_lab_field_dc'])<float(MeasRecs[recnum+1]['measurement_lab_field_dc']) and recnum+1<len(MeasRecs): # this is LP-IMAG
            MeasRecs[recnum]['magic_method_codes']='LP-IMAG'
            MeasRecs[recnum]['magic_experiment_name']=MeasRecs[recnum]['er_specimen_name']+":"+'LP-IMAG'
            recnum+=1
#
    if int(dm)==2:
        pmag.magic_write(output,MeasRecs,'magic_measurements')
    else:
        print ('MagIC 3 is not supported yet')
        sys.exit()
        pmag.magic_write(output,MeasRecs,'measurements')

    print("results put in ", output)

Response: This function is the main entry point for the magic command line tool. It is used to convert Micromag agm files to IRM backfield curves and return the resulting IRM backfield curves.


Instruction:
Can you generate the documentation for the following Python 3 function
def on_okButton(self, event):
        os.chdir(self.WD)
        options = {}
        HUJI_file = self.bSizer0.return_value()
        if not HUJI_file:
            pw.simple_warning("You must select a HUJI format file")
            return False
        options['magfile'] = HUJI_file
        dat_file = self.bSizer0A.return_value()
        if os.path.isfile(dat_file): options['datafile'] = dat_file
        else: dat_file=""
        magicoutfile=os.path.split(HUJI_file)[1]+".magic"
        outfile=os.path.join(self.WD, magicoutfile)
        options['meas_file'] = outfile
        magicoutfile=os.path.split(HUJI_file)[1]+"_specimens.txt"
        spec_outfile=os.path.join(self.WD, magicoutfile)
        options['spec_file'] = spec_outfile
        magicoutfile=os.path.split(HUJI_file)[1]+"_samples.txt"
        samp_outfile=os.path.join(self.WD, magicoutfile)
        options['samp_file'] = samp_outfile
        magicoutfile=os.path.split(HUJI_file)[1]+"_sites.txt"
        site_outfile=os.path.join(self.WD, magicoutfile)
        options['site_file'] = site_outfile
        magicoutfile=os.path.split(HUJI_file)[1]+"_locations.txt"
        loc_outfile=os.path.join(self.WD, magicoutfile)
        options['loc_file'] = loc_outfile
        user = self.bSizer1.return_value()
        options['user'] = user
        if user:
            user = '-usr ' + user
        experiment_type = self.bSizer2.return_value()
        options['codelist'] = experiment_type
        if not experiment_type:
            pw.simple_warning("You must select an experiment type")
            return False
        cooling_rate = self.cooling_rate.GetValue() or 0
        if cooling_rate:
            experiment_type = experiment_type + " " + cooling_rate
        lab_field = self.bSizer3.return_value()
        if not lab_field:
            lab_field = "0 0 0"
        lab_field_list = lab_field.split()
        options['labfield'] = lab_field_list[0]
        options['phi'] = lab_field_list[1]
        options['theta'] = lab_field_list[2]
        lab_field = '-dc ' + lab_field
        spc = self.bSizer4.return_value()
        options['specnum'] = spc or 0
        if not spc:
            spc = '-spc 0'
        else:
            spc = '-spc ' + spc
        ncn = self.bSizer5.return_value()
        options['samp_con'] = ncn
        loc_name = self.bSizer6.return_value()
        options['location'] = loc_name
        if loc_name:
            loc_name = '-loc ' + loc_name
        #peak_AF = self.bSizer7.return_value()
        #options['peakfield'] = peak_AF

        replicate = self.bSizer8.return_value()
        if replicate:
            options['noave'] = 0
            replicate = ''
        else:
            options['noave'] = 1
            replicate = '-A'

        COMMAND = "huji_magic_new.py -f {} -fd {} -F {} -Fsp {} -Fsa {} -Fsi {} -Flo {} {} -LP {} {} -ncn {} {} {} {}".format(HUJI_file, dat_file, outfile, spec_outfile, samp_outfile, site_outfile, loc_outfile, user, experiment_type, loc_name, ncn, lab_field, spc, replicate)
        program_ran, error_message = convert.huji(**options)
        if program_ran:
            pw.close_window(self, COMMAND, outfile)
        else:
            pw.simple_warning(error_message)

Response: This method is called when the user selects a new HUJI file and runs huji_magic. py with the appropriate flags.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_sheet(self):
        '''
        create an editable grid showing demag_orient.txt
        '''
        #--------------------------------
        # orient.txt supports many other headers
        # but we will only initialize with
        # the essential headers for
        # sample orientation and headers present
        # in existing demag_orient.txt file
        #--------------------------------

        #--------------------------------
        # create the grid
        #--------------------------------

        samples_list = list(self.orient_data.keys())
        samples_list.sort()
        self.samples_list = [ sample for sample in samples_list if sample is not "" ]
        #self.headers.extend(self.add_extra_headers(samples_list))
        display_headers = [header[1] for header in self.headers]
        self.grid = magic_grid.MagicGrid(self.panel, 'orient grid',
                                         self.samples_list, display_headers)
        self.grid.InitUI()

        #--------------------------------
        # color the columns by groups
        #--------------------------------

        for i in range(len(self.samples_list)):
            self.grid.SetCellBackgroundColour(i, 0, "LIGHT GREY")
            self.grid.SetCellBackgroundColour(i, 1, "LIGHT STEEL BLUE")
            self.grid.SetCellBackgroundColour(i, 2, "YELLOW")
            self.grid.SetCellBackgroundColour(i, 3, "YELLOW")
            self.grid.SetCellBackgroundColour(i, 4, "PALE GREEN")
            self.grid.SetCellBackgroundColour(i, 5, "PALE GREEN")
            self.grid.SetCellBackgroundColour(i, 6, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 7, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 8, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 9, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 10, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 11, "LIGHT MAGENTA")
            self.grid.SetCellBackgroundColour(i, 12, "LIGHT MAGENTA")

        #--------------------------------
        # fill data from self.orient_data
        #--------------------------------

        headers = [header[0] for header in self.headers]
        for sample in self.samples_list:
            for key in list(self.orient_data[sample].keys()):
                if key in headers:
                    sample_index = self.samples_list.index(sample)
                    i = headers.index(key)
                    val = str(self.orient_data[sample][key])
                    # if it's a pmag_object, use its name
                    try:
                        val = val.name
                    except AttributeError:
                        pass
                    if val and val != "None":
                        self.grid.SetCellValue(sample_index, i, val)

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

        #--------------------------------
        # fill in some default values
        #--------------------------------
        for row in range(self.grid.GetNumberRows()):
            col = 1
            if not self.grid.GetCellValue(row, col):
                self.grid.SetCellValue(row, col, 'g')

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

        # temporary trick to get drop-down-menus to work
        self.grid.changes = {'a'}

        self.grid.AutoSize()
        #self.drop_down_menu = drop_down_menus.Menus("orient", self, self.grid, '')
        self.drop_down_menu = drop_down_menus3.Menus("orient", self.contribution, self.grid)
        self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid)

Response: create an editable grid showing the demag_orient. txt file and the headers present in the file


Instruction:
Here you have a function in Python 3, explain what it does
def on_m_open_file(self,event):
        '''
        open orient.txt
        read the data
        display the data from the file in a new grid
        '''
        dlg = wx.FileDialog(
            self, message="choose orient file",
            defaultDir=self.WD,
            defaultFile="",
            style=wx.FD_OPEN | wx.FD_CHANGE_DIR
            )
        if dlg.ShowModal() == wx.ID_OK:
            orient_file = dlg.GetPath()
            dlg.Destroy()
            new_data, dtype, keys = pmag.magic_read_dict(orient_file,
                                                         sort_by_this_name="sample_name",
                                                         return_keys=True)

            if len(new_data) > 0:
                self.orient_data={}
                self.orient_data=new_data
            #self.create_sheet()
            self.update_sheet()
            print("-I- If you don't see a change in the spreadsheet, you may need to manually re-size the window")

Response: open the file in the current working directory read the data from the file in a new grid


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_extra_headers(self, sample_names):
        if not sample_names:
            return []
        full_headers = list(self.orient_data[sample_names[0]].keys())
        add_ons = []
        for head in full_headers:
            if head not in self.header_names:
                add_ons.append((head, head))
        return add_ons

Response: Add any additional headers that are not in the default headers.


Instruction:
Can you implement a function in Python 3 that
opens the file in the current working directory read the data from the file display the data in a new grid

Response:
def on_m_open_file(self,event):
        '''
        open orient.txt
        read the data
        display the data from the file in a new grid
        '''
        dlg = wx.FileDialog(
            self, message="choose orient file",
            defaultDir=self.WD,
            defaultFile="",
            style=wx.FD_OPEN | wx.FD_CHANGE_DIR
            )
        if dlg.ShowModal() == wx.ID_OK:
            orient_file = dlg.GetPath()
            dlg.Destroy()
            new_data = self.er_magic_data.read_magic_file(orient_file, "sample_name")[0]
            if len(new_data) > 0:
                self.orient_data={}
                self.orient_data=new_data
            #self.create_sheet()
            self.update_sheet()
            print("-I- If you don't see a change in the spreadsheet, you may need to manually re-size the window")


Instruction:
Can you tell what is the following Python 3 function doing
def on_m_save_file(self,event):

        '''
        save demag_orient.txt
        (only the columns that appear on the grid frame)
        '''
        fout = open(os.path.join(self.WD, "demag_orient.txt"), 'w')
        STR = "tab\tdemag_orient\n"
        fout.write(STR)
        headers = [header[0] for header in self.headers]
        STR = "\t".join(headers) + "\n"
        fout.write(STR)
        for sample in self.samples_list:
            STR = ""
            for header in headers:
                sample_index = self.samples_list.index(sample)
                i = headers.index(header)
                value = self.grid.GetCellValue(sample_index, i)
                STR = STR + value + "\t"
            fout.write(STR[:-1] + "\n")
        if event != None:
            dlg1 = wx.MessageDialog(None,caption="Message:", message="data saved in file demag_orient.txt" ,style=wx.OK|wx.ICON_INFORMATION)
            dlg1.ShowModal()
            dlg1.Destroy()

Response:
save demag_orient.txt
        (only the columns that appear on the grid frame)


Instruction:
Create a Python 3 function to
name mk_redo. py - h prints help message and quits countryCode prints a zeq_redo format file

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

    DESCRIPTION
        Makes thellier_redo and zeq_redo files from existing pmag_specimens format file

    SYNTAX
        mk_redo.py [-h] [command line options]

    INPUT
        takes specimens.txt formatted input file

    OPTIONS
        -h: prints help message and quits
        -f FILE: specify input file, default is 'specimens.txt'
        -F REDO: specify output file suffix, default is redo so that
            output filenames are 'thellier_redo' for thellier data and 'zeq_redo' for direction only data

    OUTPUT
        makes a thellier_redo or a zeq_redo format file
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    zfile, tfile = 'zeq_redo', 'thellier_redo'
    zredo, tredo = "", ""
    dir_path = pmag.get_named_arg('-WD', '.')
    inspec = pmag.get_named_arg('-f', 'specimens.txt')
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        redo = sys.argv[ind + 1]
        tfile = redo
        zfile = redo
    inspec = pmag.resolve_file_name(inspec, dir_path)
    zfile = pmag.resolve_file_name(zfile, dir_path)
    tfile = pmag.resolve_file_name(tfile, dir_path)
#
# read in data
#
    specs = []
    prior_spec_data, file_type = pmag.magic_read(inspec)
    if file_type != 'specimens':
        print(file_type, " this is not a valid pmag_specimens file")
        sys.exit()
    outstrings = []
    for spec in prior_spec_data:
        tmp = spec["method_codes"].split(":")
        meths = []
        for meth in tmp:
            methods = meth.strip().split('-')
            for m in methods:
                if m not in meths:
                    meths.append(m)
        if 'DIR' in meths:  # DE-BFL, DE-BFP or DE-FM
            specs.append(spec['specimen'])
            if 'dir_comp' in list(spec.keys()) and spec['dir_comp'] != "" and spec['dir_comp'] != " ":
                comp_name = spec['dir_comp']
            else:
                comp_name = string.ascii_uppercase[specs.count(
                    spec['specimen']) - 1]
            calculation_type = "DE-BFL"  # assume default calculation type is best-fit line
            if "BFP" in meths:
                calculation_type = 'DE-BFP'
            elif "FM" in meths:
                calculation_type = 'DE-FM'
            if zredo == "":
                zredo = open(zfile, "w")
            outstring = '%s %s %s %s %s \n' % (
                spec["specimen"], calculation_type, spec["meas_step_min"], spec["meas_step_max"], comp_name)
            if outstring not in outstrings:
                zredo.write(outstring)
            outstrings.append(outstring)  # only writes unique interpretions
        elif "PI" in meths and "TRM" in meths:   # thellier record
            if tredo == "":
                tredo = open(tfile, "w")
            outstring = '%s %i %i \n' % (spec["specimen"], float(
                spec["meas_step_min"]), float(spec["meas_step_max"]))
            if outstring not in outstrings:
                tredo.write(outstring)
            outstrings.append(outstring)  # only writes unique interpretions
    print('Redo files saved to: ', zfile, tfile)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def find_side(ls, side):
    minx, miny, maxx, maxy = ls.bounds
    points = {'left': [(minx, miny), (minx, maxy)],
              'right': [(maxx, miny), (maxx, maxy)],
              'bottom': [(minx, miny), (maxx, miny)],
              'top': [(minx, maxy), (maxx, maxy)],}
    return sgeom.LineString(points[side])

Response:
Given a shapely LineString which is assumed to be rectangular return the
    line corresponding to a given side of the rectangle.


Instruction:
Implement a function in Python 3 to
draw ticks on the bottom x - axis of a Lambert Conformal projection.

Response:
def lambert_xticks(ax, ticks):
    """Draw ticks on the bottom x-axis of a Lambert Conformal projection."""
    te = lambda xy: xy[0]
    lc = lambda t, n, b: np.vstack((np.zeros(n) + t, np.linspace(b[2], b[3], n))).T
    xticks, xticklabels = _lambert_ticks(ax, ticks, 'bottom', lc, te)
    ax.xaxis.tick_bottom()
    ax.set_xticks(xticks)
    ax.set_xticklabels([ax.xaxis.get_major_formatter()(xtick) for xtick in xticklabels])


Instruction:
Here you have a function in Python 3, explain what it does
def lambert_yticks(ax, ticks):
    te = lambda xy: xy[1]
    lc = lambda t, n, b: np.vstack((np.linspace(b[0], b[1], n), np.zeros(n) + t)).T
    yticks, yticklabels = _lambert_ticks(ax, ticks, 'left', lc, te)
    ax.yaxis.tick_left()
    ax.set_yticks(yticks)
    ax.set_yticklabels([ax.yaxis.get_major_formatter()(ytick) for ytick in yticklabels])

Response: Draw ricks on the left y - axis of a Lamber Conformal projection.


Instruction:
How would you implement a function in Python 3 that
gets the tick locations and labels for an axis of a Lambert Conformal projection.

Response:
def _lambert_ticks(ax, ticks, tick_location, line_constructor, tick_extractor):
    """Get the tick locations and labels for an axis of a Lambert Conformal projection."""
    outline_patch = sgeom.LineString(ax.outline_patch.get_path().vertices.tolist())
    axis = find_side(outline_patch, tick_location)
    n_steps = 30
    extent = ax.get_extent(ccrs.PlateCarree())
    _ticks = []
    for t in ticks:
        xy = line_constructor(t, n_steps, extent)
        proj_xyz = ax.projection.transform_points(ccrs.Geodetic(), xy[:, 0], xy[:, 1])
        xyt = proj_xyz[..., :2]
        ls = sgeom.LineString(xyt.tolist())
        locs = axis.intersection(ls)
        if not locs:
            tick = [None]
        else:
            tick = tick_extractor(locs.xy)
        _ticks.append(tick[0])
    # Remove ticks that aren't visible:
    ticklabels = copy(ticks)
    while True:
        try:
            index = _ticks.index(None)
        except ValueError:
            break
        _ticks.pop(index)
        ticklabels.pop(index)
    return _ticks, ticklabels


Instruction:
Create a Python 3 function for
naming umich_magic.py DESCRIPTION converts UMICH .mag format files to magic_measurements format files SYNTAX umich_magic.py [command line options] OPTIONS -h: prints the help message and quits. -usr USER: identify user, default is "" -f FILE: specify .mag format input file, required -fsa SAMPFILE : specify er_samples.txt file relating samples, site and locations names,default is none -F FILE: specify output file, default is magic_measurements.txt -spc NUM : specify number of characters to designate a specimen, default = 0 -loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic -ncn NCON: specify naming convention: default is #1 below -A: don't average replicate measurements 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] XXXX[YYY]: YYY is sample designation with Z characters from site XXX [5] site name same as sample [6] site is entered under a separate column -- NOT CURRENTLY SUPPORTED [7-Z] [XXXX]YYY: XXXX is site designation with Z characters with sample name XXXXYYYY NB: all others you will have to customize your self or e-mail ltauxe@ucsd.edu for help. Format of UMICH .mag files: Spec Treat CSD Intensity Declination Inclination metadata string Spec: specimen name Treat: treatment step XXX T in Centigrade XXX AF in mT Intensity assumed to be total moment in 10^3 Am^2 (emu) Declination: Declination in specimen coordinate system Inclination: Declination in specimen coordinate system metatdata string: mm/dd/yy;hh:mm;[dC,mT];xx.xx;UNITS;USER;INST;NMEAS hh in 24 hours. dC or mT units of treatment XXX (see Treat above) for thermal or AF respectively xx.xxx DC field UNITS of DC field (microT, mT) INST: instrument code, number of axes, number of positions (e.g., G34 is 2G, three axes, measured in four positions) NMEAS: number of measurements in a single position (1,3,200...)

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

    DESCRIPTION
        converts UMICH .mag format files to magic_measurements format files

    SYNTAX
        umich_magic.py [command line options]

    OPTIONS
        -h: prints the help message and quits.
        -usr USER:   identify user, default is ""
        -f FILE: specify .mag format input file, required
        -fsa SAMPFILE : specify er_samples.txt file relating samples, site and locations names,default is none
        -F FILE: specify output file, default is magic_measurements.txt
        -spc NUM : specify number of characters to designate a  specimen, default = 0
        -loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic
        -ncn NCON:  specify naming convention: default is #1 below
        -A: don't average replicate measurements
       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] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            [5] site name same as sample
            [6] site is entered under a separate column -- NOT CURRENTLY SUPPORTED
            [7-Z] [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail ltauxe@ucsd.edu for help.

        Format of UMICH .mag files:
        Spec Treat CSD Intensity Declination Inclination metadata string
        Spec: specimen name
        Treat:  treatment step
            XXX T in Centigrade
            XXX AF in mT
         Intensity assumed to be total moment in 10^3 Am^2 (emu)
         Declination:  Declination in specimen coordinate system
         Inclination:  Declination in specimen coordinate system

         metatdata string:  mm/dd/yy;hh:mm;[dC,mT];xx.xx;UNITS;USER;INST;NMEAS
             hh in 24 hours.
             dC or mT units of treatment XXX (see Treat above) for thermal or AF respectively
             xx.xxx   DC field
             UNITS of DC field (microT, mT)
             INST:  instrument code, number of axes, number of positions (e.g., G34 is 2G, three axes,
                    measured in four positions)
             NMEAS: number of measurements in a single position (1,3,200...)
    """
# initialize some stuff
    dir_path='.'
    infile_type="mag"
    noave=0
    methcode,inst="",""
    phi,theta,peakfield,labfield=0,0,0,0
    pTRM,MD,samp_con,Z=0,0,'1',1
    missing=1
    demag="N"
    er_location_name=""
    citation='This study'
    args=sys.argv
    methcode="LP-NO"
    samp_file,ErSamps='',[]
    specnum=0
#
# get command line arguments
#
    meas_file="magic_measurements.txt"
    user=""
    if '-WD' in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        meas_file=dir_path+'/'+args[ind+1]
    if '-f' in args:
        ind=args.index("-f")
        magfile=dir_path+'/'+args[ind+1]
        try:
            input=open(magfile,'r')
        except:
            print("bad mag file name")
            sys.exit()
    else:
        print("mag_file field is required option")
        print(main.__doc__)
        sys.exit()
    if "-spc" in args:
        ind=args.index("-spc")
        specnum=int(args[ind+1])
        if specnum!=0:specnum=-specnum
    if "-loc" in args:
        ind=args.index("-loc")
        er_location_name=args[ind+1]
    if "-fsa" in args:
        ind=args.index("-fsa")
        samp_file=dir_path+'/'+args[ind+1]
        Samps,file_type=pmag.magic_read(samp_file)
    if "-A" in args: noave=1
    if "-ncn" in args:
        ind=args.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print("option [4] must be in form 4-Z where Z is an integer")
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
            samp_con=sys.argv[ind+1]
        if "7" in samp_con:
            if "-" not in samp_con:
                print("option [7] must be in form 7-Z where Z is an integer")
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    MagRecs,specs=[],[]
    version_num=pmag.get_version()
    if infile_type=="mag":
        for line in input.readlines():
            instcode=""
            if len(line)>2:
                MagRec={}
                MagRec['er_location_name']=er_location_name
                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'
                meas_type="LT-NO"
                rec=line.split()
                labfield=0
                code1=rec[6].split(';')
                date=code1[0].split('/') # break date into mon/day/year
                yy=int(date[2])
                if yy <90:
                    yyyy=str(2000+yy)
                else: yyyy=str(1900+yy)
                mm=int(date[0])
                if mm<10:
                    mm="0"+str(mm)
                else: mm=str(mm)
                dd=int(date[1])
                if dd<10:
                    dd="0"+str(dd)
                else: dd=str(dd)
                time=code1[1].split(':')
                hh=int(time[0])
                if hh<10:
                    hh="0"+str(hh)
                else: hh=str(hh)
                min=int(time[1])
                if min<10:
                   min= "0"+str(min)
                else: min=str(min)
                MagRec["measurement_date"]=yyyy+":"+mm+":"+dd+":"+hh+":"+min+":00.00"
                MagRec["measurement_time_zone"]=''
                instcode=''
                if len(code1)>1:
                    MagRec["measurement_positions"]=code1[6][2]
                else:
                    MagRec["measurement_positions"]=code1[7]   # takes care of awkward format with bubba and flo being different
                if user=="":user=code1[5]
                if code1[2][-1]=='C': demag="T"
                if code1[2]=='mT': demag="AF"
                treat=rec[1].split('.')
                if len(treat)==1:treat.append('0')
                if demag=='T' and treat!=0:
                    meas_type="LT-T-Z"
                    MagRec["treatment_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin
                if demag=="AF":
                    meas_type="LT-AF-Z"
                    MagRec["treatment_ac_field"]='%8.3e' % (float(treat[0])*1e-3) # Af field in T
                MagRec["treatment_dc_field"]='0'
                MagRec["er_specimen_name"]=rec[0]
                if rec[0] not in specs:specs.append(rec[0]) # get a list of specimen names
                experiment=rec[0]+":"
                MagRec["er_site_name"]=""
                if specnum!=0:
                    MagRec["er_sample_name"]=rec[0][:specnum]
                else:
                    MagRec["er_sample_name"]=rec[0]
                if "-fsa" in args:
                    for samp in Samps:
                        if samp["er_sample_name"] == MagRec["er_sample_name"]:
                            MagRec["er_location_name"]=samp["er_location_name"]
                            MagRec["er_site_name"]=samp["er_site_name"]
                            break
                elif int(samp_con)!=6:
                    site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z)
                    MagRec["er_site_name"]=site
                if MagRec['er_site_name']=="":
                    print('No site name found for: ',MagRec['er_specimen_name'],MagRec['er_sample_name'])
                if MagRec["er_location_name"]=="":
                    print('no location name for: ',MagRec["er_specimen_name"])
                if rec[1]==".00":rec[1]="0.00"
                MagRec["measurement_csd"]=rec[2]
                MagRec["measurement_magn_moment"]='%10.3e'% (float(rec[3])*1e-3) # moment in Am^2 (from emu)
                MagRec["measurement_dec"]=rec[4]
                MagRec["measurement_inc"]=rec[5]
                MagRec["magic_instrument_codes"]=instcode
                MagRec["er_analyst_mail_names"]=user
                MagRec["er_citation_names"]=citation
                MagRec["magic_method_codes"]=meas_type
                MagRec["measurement_flag"]='g'
                MagRec["er_specimen_name"]=rec[0]
                MagRec["measurement_number"]='1'
                MagRecs.append(MagRec)
    MagOuts=[]
    for spec in specs:  # gather all demag types for this specimen
        SpecRecs,meths,measnum=[],[],1
        for rec in MagRecs:
            if rec['er_specimen_name']==spec:
                rec['measurement_number']=str(measnum)
                measnum+=1
                if rec['magic_method_codes'] not in meths:meths.append(rec['magic_method_codes'])
                SpecRecs.append(rec)
        expname=spec
        if "LT-AF-Z" in meths:expname=expname+ ':LP-DIR-AF'
        if "LT-T-Z" in meths:expname=expname+ ':LP-DIR-T'
        for rec in SpecRecs:
            rec['magic_experiment_name']=expname
            MagOuts.append(rec)
    pmag.magic_write(meas_file,MagOuts,'magic_measurements')
    print("results put in ",meas_file)


Instruction:
Implement a function in Python 3 to
plot intensity decay curves for demagnetization experiments Parameters ---------- in_file : str, default "measurements.txt" dir_path : str output directory, default "." input_dir_path : str input file directory (if different from dir_path), default "" spec_file : str input specimen file name, default "specimens.txt" samp_file: str input sample file name, default "samples.txt" site_file : str input site file name, default "sites.txt" loc_file : str input location file name, default "locations.txt" plot_by : str [spc, sam, sit, loc] (specimen, sample, site, location), default "loc" LT : str lab treatment [T, AF, M], default AF norm : bool normalize by NRM magnetization, default True XLP : str exclude specific lab protocols, (for example, method codes like LP-PI) default "" save_plots : bool plot and save non-interactively, default True fmt : str ["png", "svg", "pdf", "jpg"], default "svg" Returns --------- type - Tuple : (True or False indicating if conversion was sucessful, file name(s) written)

Response:
def dmag_magic(in_file="measurements.txt", dir_path=".", input_dir_path="",
         spec_file="specimens.txt", samp_file="samples.txt",
         site_file="sites.txt", loc_file="locations.txt",
         plot_by="loc", LT="AF", norm=True, XLP="",
         save_plots=True, fmt="svg"):

    """
    plots intensity decay curves for demagnetization experiments

    Parameters
    ----------
    in_file : str, default "measurements.txt"
    dir_path : str
        output directory, default "."
    input_dir_path : str
        input file directory (if different from dir_path), default ""
    spec_file : str
        input specimen file name, default "specimens.txt"
    samp_file: str
        input sample file name, default "samples.txt"
    site_file : str
        input site file name, default "sites.txt"
    loc_file : str
        input location file name, default "locations.txt"
    plot_by : str
        [spc, sam, sit, loc] (specimen, sample, site, location), default "loc"
    LT : str
        lab treatment [T, AF, M], default AF
    norm : bool
        normalize by NRM magnetization, default True
    XLP : str
        exclude specific  lab protocols, (for example, method codes like LP-PI)
        default ""
    save_plots : bool
        plot and save non-interactively, default True
    fmt : str
        ["png", "svg", "pdf", "jpg"], default "svg"

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

    """
    dir_path = os.path.realpath(dir_path)
    if not input_dir_path:
        input_dir_path = dir_path
    input_dir_path = os.path.realpath(input_dir_path)

    # format plot_key
    name_dict = {'loc': 'location', 'sit': 'site',
                 'sam': 'sample', 'spc': 'specimen'}
    if plot_by not in name_dict.values():
        try:
            plot_key = name_dict[plot_by]
        except KeyError:
            print('Unrecognized plot_by {}, falling back to plot by location'.format(plot_by))
            plot_key = "loc"
    else:
        plot_key = plot_by

    # figure out what kind of experiment
    LT = "LT-" + LT + "-Z"
    print('LT', LT)
    if LT == "LT-T-Z":
        units, dmag_key = 'K', 'treat_temp'
    elif LT == "LT-AF-Z":
        units, dmag_key = 'T', 'treat_ac_field'
    elif LT == 'LT-M-Z':
        units, dmag_key = 'J', 'treat_mw_energy'
    else:
        units = 'U'

    # init
    FIG = {}  # plot dictionary
    FIG['demag'] = 1  # demag is figure 1
    # create contribution and add required headers
    fnames = {"specimens": spec_file, "samples": samp_file,
              'sites': site_file, 'locations': loc_file}
    if not os.path.exists(pmag.resolve_file_name(in_file, input_dir_path)):
        print('-E- Could not find {}'.format(in_file))
        return False, []
    contribution = cb.Contribution(input_dir_path, single_file=in_file,
                                   custom_filenames=fnames)
    file_type = list(contribution.tables.keys())[0]
    print(len(contribution.tables['measurements'].df), ' records read from ', in_file)
    # add plot_key into measurements table
    if plot_key not in contribution.tables['measurements'].df.columns:
        #contribution.propagate_name_down(plot_key, 'measurements')
        contribution.propagate_location_to_measurements()
    data_container = contribution.tables[file_type]
    # pare down to only records with useful data
    # grab records that have the requested code
    data_slice = data_container.get_records_for_code(LT)
    # and don't have the offending code
    data = data_container.get_records_for_code(XLP, incl=False, use_slice=True,
                                               sli=data_slice, strict_match=False)

    # make sure quality is in the dataframe
    if 'quality' not in data.columns:
        data['quality'] = 'g'
    # get intensity key and make sure intensity data is not blank
    intlist = ['magn_moment', 'magn_volume', 'magn_mass']
    IntMeths = [col_name for col_name in data.columns if col_name in intlist]
    # get rid of any entirely blank intensity columns
    for col_name in IntMeths:
        if not data[col_name].any():
            data.drop(col_name, axis=1, inplace=True)
    IntMeths = [col_name for col_name in data.columns if col_name in intlist]
    if len(IntMeths) == 0:
        print('-E- No intensity headers found')
        return False, []

    int_key = IntMeths[0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    data = data[data[int_key].notnull()]
    # make list of individual plots
    # by default, will be by location_name
    plotlist = data[plot_key].unique()
    plotlist.sort()
    pmagplotlib.plot_init(FIG['demag'], 5, 5)
    last_plot = False
    # iterate through and plot the data
    for plot in plotlist:
        if plot == plotlist[-1]:
            last_plot = True
        plot_data = data[data[plot_key] == plot].copy()
        if not save_plots:
            print(plot, 'plotting by: ', plot_key)
        if len(plot_data) > 2:
            title = plot
            spcs = []
            spcs = plot_data['specimen'].unique()
            for spc in spcs:
                INTblock = []
                spec_data = plot_data[plot_data['specimen'] == spc]
                for ind, rec in spec_data.iterrows():
                    INTblock.append([float(rec[dmag_key]), 0, 0, float(rec[int_key]), 1, rec['quality']])
                if len(INTblock) > 2:
                    pmagplotlib.plot_mag(FIG['demag'], INTblock,
                                       title, 0, units, norm)

            if save_plots:
                files = {}
                for key in list(FIG.keys()):
                    if pmagplotlib.isServer:
                        files[key] = title + '_' + LT + '.' + fmt
                        incl_dir = False
                    else: # if not server, include directory in output path
                        files[key] = os.path.join(dir_path, title + '_' + LT + '.' + fmt)
                        incl_dir = True

                pmagplotlib.save_plots(FIG, files, incl_directory=incl_dir)
            else:
                pmagplotlib.draw_figs(FIG)
                prompt = " S[a]ve to save plot, [q]uit,  Return to continue:  "
                ans = input(prompt)
                if ans == 'q':
                    return True, []
                if ans == "a":
                    files = {}
                    for key in list(FIG.keys()):
                        if pmagplotlib.isServer:
                            files[key] = title + '_' + LT + '.' + fmt
                            incl_dir = False
                        else: # if not server, include directory in output path
                            files[key] = os.path.join(dir_path, title + '_' + LT + '.' + fmt)
                            incl_dir = True
                    pmagplotlib.save_plots(FIG, files, incl_directory=incl_dir)
            pmagplotlib.clearFIG(FIG['demag'])
    if last_plot:
        return True, []


Instruction:
How would you implement a function in Python 3 that
names dmag_magic.py DESCRIPTION plots intensity decay curves for demagnetization experiments SYNTAX dmag_magic -h [command line options] INPUT takes magic formatted measurements.txt files OPTIONS -h prints help message and quits -f FILE: specify input file, default is: measurements.txt -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is by location -LT [AF,T,M]: specify lab treatment type, default AF -XLP [PI]: exclude specific lab protocols, (for example, method codes like LP-PI) -N do not normalize by NRM magnetization -sav save plots silently and quit -fmt [svg,jpg,png,pdf] set figure format [default is svg] NOTE loc: location (study); sit: site; sam: sample; spc: specimen

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

    DESCRIPTION
       plots intensity decay curves for demagnetization experiments

    SYNTAX
        dmag_magic -h [command line options]

    INPUT
       takes magic formatted measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot,
               default is by location
        -LT [AF,T,M]: specify lab treatment type, default AF
        -XLP [PI]: exclude specific  lab protocols,
               (for example, method codes like LP-PI)
        -N do not normalize by NRM magnetization
        -sav save plots silently and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    # initialize variables from command line + defaults
    dir_path = pmag.get_named_arg("-WD", default_val=".")
    input_dir_path = pmag.get_named_arg('-ID', '')
    if not input_dir_path:
        input_dir_path = dir_path
    in_file = pmag.get_named_arg("-f", default_val="measurements.txt")
    in_file = pmag.resolve_file_name(in_file, input_dir_path)
    if "-ID" not in sys.argv:
        input_dir_path = os.path.split(in_file)[0]
    plot_by = pmag.get_named_arg("-obj", default_val="loc")
    LT = pmag.get_named_arg("-LT", "AF")
    no_norm = pmag.get_flag_arg_from_sys("-N")
    norm = False if no_norm else True
    save_plots = pmag.get_flag_arg_from_sys("-sav")
    fmt = pmag.get_named_arg("-fmt", "svg")
    XLP = pmag.get_named_arg("-XLP", "")
    spec_file = pmag.get_named_arg("-fsp", default_val="specimens.txt")
    samp_file = pmag.get_named_arg("-fsa", default_val="samples.txt")
    site_file = pmag.get_named_arg("-fsi", default_val="sites.txt")
    loc_file = pmag.get_named_arg("-flo", default_val="locations.txt")
    dmag_magic(in_file, dir_path, input_dir_path, spec_file, samp_file,
         site_file, loc_file, plot_by, LT, norm, XLP,
         save_plots, fmt)


Instruction:
Can you implement a function in Python 3 that
names watsons_v.py DESCRIPTION calculates Watson's V statistic from input files INPUT FORMAT takes dec/inc as first two columns in two space delimited files SYNTAX watsons_v.py [command line options] OPTIONS -h prints help message and quits -f FILE (with optional second) -f2 FILE (second file) -ant, flip antipodal directions to opposite direction in first file if only one file or flip all in second, if two files -P (don't save or show plot) -sav save figure and quit silently -fmt [png,svg,eps,pdf,jpg] format for saved figure OUTPUT Watson's V and the Monte Carlo Critical Value Vc. in plot, V is solid and Vc is dashed.

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

    DESCRIPTION
       calculates Watson's V statistic from input files

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files

    SYNTAX
       watsons_v.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE (with optional second)
        -f2 FILE (second file)
        -ant,  flip antipodal directions to opposite direction
           in first file if only one file or flip all in second, if two files
        -P  (don't save or show plot)
        -sav save figure and quit silently
        -fmt [png,svg,eps,pdf,jpg] format for saved figure

    OUTPUT
        Watson's V and the Monte Carlo Critical Value Vc.
        in plot, V is solid and Vc is dashed.

    """
    Flip=0
    show,plot=1,0
    fmt='svg'
    file2=""
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    if '-ant' in  sys.argv: Flip=1
    if '-sav' in sys.argv: show,plot=0,1 # don't display, but do save plot
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-P' in  sys.argv: show=0 # don't display or save plot
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file1=sys.argv[ind+1]
        data=numpy.loadtxt(file1).transpose()
        D1=numpy.array([data[0],data[1]]).transpose()
        file1_name=os.path.split(file1)[1].split('.')[0]
    else:
        print("-f is required")
        print(main.__doc__)
        sys.exit()
    if '-f2' in sys.argv:
        ind=sys.argv.index('-f2')
        file2=sys.argv[ind+1]
        data2=numpy.loadtxt(file2).transpose()
        D2=numpy.array([data2[0],data2[1]]).transpose()
        file2_name=os.path.split(file2)[1].split('.')[0]
        if Flip==1:
            D2,D=pmag.flip(D2) # D2 are now flipped
            if len(D2)!=0:
                if len(D)!=0:
                    D2=numpy.concatenate(D,D2) # put all in D2
            elif len(D)!=0:
                D2=D
            else:
                print('length of second file is zero')
                sys.exit()
    elif Flip==1:D2,D1=pmag.flip(D1) # peel out antipodal directions, put in D2
#
    counter,NumSims=0,5000
#
# first calculate the fisher means and cartesian coordinates of each set of Directions
#
    pars_1=pmag.fisher_mean(D1)
    pars_2=pmag.fisher_mean(D2)
#
# get V statistic for these
#
    V=pmag.vfunc(pars_1,pars_2)
#
# do monte carlo simulation of datasets with same kappas, but common mean
#
    Vp=[] # set of Vs from simulations
    if show==1:print("Doing ",NumSims," simulations")
    for k in range(NumSims):
        counter+=1
        if counter==50:
            if show==1:print(k+1)
            counter=0
        Dirp=[]
# get a set of N1 fisher distributed vectors with k1, calculate fisher stats
        for i in range(pars_1["n"]):
            Dirp.append(pmag.fshdev(pars_1["k"]))
        pars_p1=pmag.fisher_mean(Dirp)
# get a set of N2 fisher distributed vectors with k2, calculate fisher stats
        Dirp=[]
        for i in range(pars_2["n"]):
            Dirp.append(pmag.fshdev(pars_2["k"]))
        pars_p2=pmag.fisher_mean(Dirp)
# get the V for these
        Vk=pmag.vfunc(pars_p1,pars_p2)
        Vp.append(Vk)
#
# sort the Vs, get Vcrit (95th one)
#
    Vp.sort()
    k=int(.95*NumSims)
    if show==1:
        print("Watson's V,  Vcrit: ")
        print('   %10.1f %10.1f'%(V,Vp[k]))
    if show==1 or plot==1:
        print("Watson's V,  Vcrit: ")
        print('   %10.1f %10.1f'%(V,Vp[k]))
        CDF={'cdf':1}
        pmagplotlib.plot_init(CDF['cdf'],5,5)
        pmagplotlib.plot_cdf(CDF['cdf'],Vp,"Watson's V",'r',"")
        pmagplotlib.plot_vs(CDF['cdf'],[V],'g','-')
        pmagplotlib.plot_vs(CDF['cdf'],[Vp[k]],'b','--')
        if plot==0:pmagplotlib.draw_figs(CDF)
        files={}
        if pmagplotlib.isServer: # use server plot naming convention
            if file2!="":
                files['cdf']='watsons_v_'+file1+'_'+file2+'.'+fmt
            else:
                files['cdf']='watsons_v_'+file1+'.'+fmt
        else: # use more readable plot naming convention
            if file2!="":
                files['cdf']='watsons_v_'+file1_name+'_'+file2_name+'.'+fmt
            else:
                files['cdf']='watsons_v_'+file1_name+'.'+fmt

        if pmagplotlib.isServer:
            black     = '#000000'
            purple    = '#800080'
            titles={}
            titles['cdf']='Cumulative Distribution'
            CDF = pmagplotlib.add_borders(CDF,titles,black,purple)
            pmagplotlib.save_plots(CDF,files)
        elif plot==0:
            ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans=="a": pmagplotlib.save_plots(CDF,files)
        if plot==1: # save and quit silently
            pmagplotlib.save_plots(CDF,files)