Instruction:
How would you explain what the following Python 3 function does
def main():
    #
    file='magic_measurements.txt'
    methx,methy,fmt="","",'.svg'
    plot_key=''
    norm_by=""
    #plot=0
    no_plot = pmag.get_flag_arg_from_sys('-sav')
    if not no_plot:
        do_plot = True
    else:
        do_plot = False
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt='.'+sys.argv[ind+1]
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        norm_by=sys.argv[ind+1]
    xtreat_key,ytreat_key,xstep,ystep="","","",""
    if '-x' in sys.argv:
        ind=sys.argv.index('-x')
        meths=sys.argv[ind+1].split(':')
        methx=meths[0]
        if len(meths)>1:
            xtreat_key=meths[1]
            xstep=float(meths[2])
    if '-y' in sys.argv:
        ind=sys.argv.index('-y')
        meths=sys.argv[ind+1].split(':')
        methy=meths[0]
        if len(meths)>1:
            ytreat_key=meths[1]
            ystep=float(meths[2])
    if '-obj' in sys.argv:
        ind=sys.argv.index('-obj')
        plot_by=sys.argv[ind+1]
        if plot_by=='loc':plot_key='er_location_name'
        if plot_by=='sit':plot_key='er_site_name'
        if plot_by=='sam':plot_key='er_sample_name'
        if plot_by=='spc':plot_key='er_specimen_name'
    if '-h' in sys.argv:
        do_plot = False
    if '-i' in sys.argv:
    #
    # get name of file from command line
    #
        file=input("Input magic_measurments file name? [magic_measurements.txt] ")
        if file=="":file="magic_measurements.txt"
    #
    #
    FIG={'fig':1}
    pmagplotlib.plot_init(FIG['fig'],5,5)
    data,file_type=pmag.magic_read(file)
    if file_type!="magic_measurements":
        print(file_type,' not correct format for magic_measurments file')
        sys.exit()
    #
    # collect method codes
    methods,plotlist=[],[]
    for rec in  data:
        if plot_key!="":
            if rec[plot_key] not in plotlist:plotlist.append(rec[plot_key])
        elif len(plotlist)==0:
            plotlist.append('All')
        meths=rec['magic_method_codes'].split(':')
        for meth in meths:
            if meth.strip() not in methods and meth.strip()!="LP-":
                methods.append(meth.strip())
    #
    if '-i' in sys.argv:
        print(methods)
    elif methx =="" or methy=="":
        print(methods)
        sys.exit()
    GoOn=1
    while GoOn==1:
        if '-i' in sys.argv:methx=input('Select method for x axis: ')
        if methx not in methods:
            if '-i' in sys.argv:
                print('try again! method not available')
            else:
                print(main.__doc__)
                print('\n must specify X axis method\n')
                sys.exit()
        else:
            if pmagplotlib.verbose: print(methx, ' selected for X axis')
            GoOn=0
    GoOn=1
    while GoOn==1:
        if '-i' in sys.argv:methy=input('Select method for y axis: ')
        if methy not in methods:
            if '-i' in sys.argv:
                print('try again! method not available')
            else:
                print(main.__doc__)
                print('\n must specify Y axis method\n')
                sys.exit()
        else:
            if pmagplotlib.verbose: print(methy, ' selected for Y axis')
            GoOn=0
    if norm_by=="":
        measkeys=['measurement_magn_mass','measurement_magn_volume','measurement_magn_moment','measurement_magnitude','measurement_chi_volume','measurement_chi_mass','measurement_chi']
    elif norm_by=="V":
        measkeys=['measurement_magn_volume','measurement_chi_volume']
    elif norm_by=="M":
        measkeys=['measurement_magn_mass','measurement_chi_mass']
    xmeaskey,ymeaskey="",""
    plotlist.sort()
    for plot in plotlist: # go through objects
        if pmagplotlib.verbose:
            print(plot)
        X,Y=[],[]
        x,y='',''
        for rec in data:
            if plot_key!="" and rec[plot_key]!=plot:
                pass
            else:
                meths=rec['magic_method_codes'].split(':')
                for meth in meths:
                    if meth.strip()==methx:
                        if xmeaskey=="":
                            for key in measkeys:
                                if key in list(rec.keys()) and rec[key]!="":
                                    xmeaskey=key
                                    if pmagplotlib.verbose:
                                        print(xmeaskey,' being used for plotting X.')
                                    break
                    if meth.strip()==methy:
                        if ymeaskey=="":
                            for key in measkeys:
                                if key in list(rec.keys()) and rec[key]!="":
                                    ymeaskey=key
                                    if pmagplotlib.verbose:
                                        print(ymeaskey,' being used for plotting Y')
                                    break
        if ymeaskey!="" and xmeaskey!="":
            for rec in data:
                x,y='',''
                spec=rec['er_specimen_name'] # get the ydata for this specimen
                if rec[ymeaskey]!="" and methy in rec['magic_method_codes'].split(':'):
                    if ytreat_key=="" or (ytreat_key in list(rec.keys()) and float(rec[ytreat_key])==ystep):
                        y=float(rec[ymeaskey])
                        for rec in data: # now find the xdata
                            if rec['er_specimen_name']==spec and rec[xmeaskey]!="" and methx in rec['magic_method_codes'].split(':'):
                                if xtreat_key=="" or (xtreat_key in list(rec.keys()) and float(rec[xtreat_key])==xstep):
                                    x=float(rec[xmeaskey])
                if x != '' and y!= '':
                    X.append(x)
                    Y.append(y)
        if len(X)>0:
            pmagplotlib.clearFIG(FIG['fig'])
            pmagplotlib.plot_xy(FIG['fig'],X,Y,sym='ro',xlab=methx,ylab=methy,title=plot+':Biplot')
            if not pmagplotlib.isServer and do_plot:
                pmagplotlib.draw_figs(FIG)
                ans=input('S[a]ve plots, [q]uit,  Return for next plot ' )
                if ans=='a':
                    files={}
                    for key in list(FIG.keys()): files[key]=plot+'_'+key+fmt
                    pmagplotlib.save_plots(FIG,files)
                if ans=='q':
                    print("Good-bye\n")
                    sys.exit()
            else:
                files={}
                for key in list(FIG.keys()): files[key]=plot+'_'+key+fmt
                if pmagplotlib.isServer:
                    black     = '#000000'
                    purple    = '#800080'
                    titles={}
                    titles['fig']='X Y Plot'
                    FIG = pmagplotlib.add_borders(FIG,titles,black,purple)
                pmagplotlib.save_plots(FIG,files)
        else:
            print('nothing to plot for ',plot)

Response: This function is the main function for the biplot_magic. py script. It is the main function for the main function. It is used to create a new object of the same type and is used to create a new object of the same type.


Instruction:
Here you have a function in Python 3, explain what it does
def main():
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    xaxis, xplotind, yplotind = "", 0, 0  # (0 for strat pos)
    yaxis, Xinc = "", ""
    plot = 0
    obj = 'all'
    data_model_num = int(pmag.get_named_arg("-DM", 3))
    # 2.5 keys
    if data_model_num == 2:
        supported = ['pmag_specimens', 'pmag_samples',
                     'pmag_sites', 'pmag_results', 'magic_web'] # available file types
        Depth_keys = ['specimen_core_depth', 'specimen_height', 'specimen_elevation',
                      'specimen_composite_depth', 'sample_core_depth', 'sample_height',
                      'sample_elevation', 'sample_composite_depth', 'site_core_depth',
                      'site_height', 'site_elevation', 'site_composite_depth', 'average_height']
        Age_keys = ['specimen_inferred_age', 'sample_inferred_age',
                    'site_inferred_age', 'average_age']
        Unit_keys = {'specimen_inferred_age': 'specimen_inferred_age_unit',
                     'sample_inferred_age': 'sample_inferred_age_unit',
                     'site_inferred_age': 'site_inferred_age_unit', 'average_age': 'average_age_unit'}
        Dec_keys = ['measurement_dec', 'specimen_dec',
                    'sample_dec', 'site_dec', 'average_dec']
        Inc_keys = ['measurement_inc', 'specimen_inc',
                    'sample_inc', 'site_inc', 'average_inc']
        Int_keys = ['measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume',
                    'measurement_magn_mass', 'specimen_int', 'specimen_int_rel', 'sample_int',
                    'sample_int_rel', 'site_int', 'site_int_rel', 'average_int', 'average_int_rel']
        Chi_keys = ['measurement_chi_volume', 'measurement_chi_mass']
        Lat_keys = ['sample_lat', 'site_lat', 'average_lat']
        VLat_keys = ['vgp_lat']
        VLon_keys = ['vgp_lon']
        Vdm_keys = ['vdm']
        Vadm_keys = ['vadm']
        method_col_name = "magic_method_codes"
    else:
        # 3.0 keys
        supported = ["specimens", "samples", "sites", "locations"] # available file types
        Depth_keys = [ "height", "core_depth", "elevation", "composite_depth" ]
        Age_keys = [ "age" ]
        Unit_keys = { "age": "age" }
        Chi_keys = [ "susc_chi_volume", "susc_chi_mass" ]
        Int_keys = [ "magn_moment", "magn_volume", "magn_mass", "int_abs", "int_rel" ]
        Inc_keys = [ "dir_inc" ]
        Dec_keys = [ "dir_dec" ]
        Lat_Keys = [ "lat" ]
        VLat_keys = [ "vgp_lat", "pole_lat" ]
        VLon_keys = [ "vgp_lon", "pole_lon" ]
        Vdm_keys = [ "vdm", "pdm" ]
        Vadm_keys = [ "vadm", "padm" ]
        method_col_name = "method_codes"

    #
    X_keys = [Age_keys, Depth_keys]
    Y_keys = [Dec_keys, Inc_keys, Int_keys, Chi_keys,
              VLat_keys, VLon_keys, Vdm_keys, Vadm_keys]
    method, fmt = "", 'svg'
    FIG = {'strat': 1}
    plotexp, pTS = 0, 0
    dir_path = pmag.get_named_arg("-WD", ".")
    # default files
    if data_model_num == 3:
        res_file = pmag.get_named_arg("-f", "sites.txt")
    else:
        res_file = pmag.get_named_arg("-f", "pmag_results.txt")
    res_file = pmag.resolve_file_name(res_file, dir_path)
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind+1]
    if '-obj' in sys.argv:
        ind = sys.argv.index('-obj')
        obj = sys.argv[ind+1]
    if '-x' in sys.argv:
        ind = sys.argv.index('-x')
        xaxis = sys.argv[ind+1]
    if '-y' in sys.argv:
        ind = sys.argv.index('-y')
        yaxis = sys.argv[ind+1]
        if yaxis == 'dec':
            ykeys = Dec_keys
        if yaxis == 'inc':
            ykeys = Inc_keys
        if yaxis == 'int':
            ykeys = Int_keys
        if yaxis == 'chi':
            ykeys = Chi_keys
        if yaxis == 'lat':
            ykeys = VLat_keys
        if yaxis == 'lon':
            ykeys = VLon_keys
        if yaxis == 'vdm':
            ykeys = Vdm_keys
        if yaxis == 'vadm':
            ykeys = Vadm_keys
    if '-mcd' in sys.argv:
        ind = sys.argv.index('-mcd')
        method = sys.argv[ind+1]
    if '-ts' in sys.argv:
        ind = sys.argv.index('-ts')
        ts = sys.argv[ind+1]
        amin = float(sys.argv[ind+2])
        amax = float(sys.argv[ind+3])
        pTS = 1
    if '-Iex' in sys.argv:
        plotexp = 1
    if '-sav' in sys.argv:
        plot = 1
    #
    #
    # get data read in
    Results, file_type = pmag.magic_read(res_file)
    if file_type not in supported:
        print("Unsupported file type ({}), try again".format(file_type))
        sys.exit()
    PltObjs = ['all']
    if data_model_num == 2:
        if file_type == 'pmag_results':  # find out what to plot
            for rec in Results:
                resname = rec['pmag_result_name'].split()
                if 'Sample' in resname and 'sam' not in PltObjs:
                    PltObjs.append('sam')
                if 'Site' in resname and 'sit' not in PltObjs:
                    PltObjs.append('sit')

    methcodes = []
    # need to know all the measurement types from method_codes
    if "magic_method_codes" in list(Results[0].keys()):
        for rec in Results:
            meths = rec["magic_method_codes"].split(":")
            for meth in meths:
                if meth.strip() not in methcodes and 'LP' in meth:
                    # look for the lab treatments
                    methcodes.append(meth.strip())
    #
    # initialize some variables
    X_unit = ""  # Unit for age or depth plotting (meters if depth)
    Xplots, Yplots = [], []
    Xunits = []
    yplotind, xplotind = 0, 0
    #
    # step through possible plottable keys
    #
    if xaxis == "" or yaxis == "":
        for key in list(Results[0].keys()):
            for keys in X_keys:
                for xkeys in keys:
                    if key in xkeys:
                        for ResRec in Results:
                            if ResRec[key] != "":
                                # only plot something if there is something to plot!
                                Xplots.append(key)
                                break
            for keys in Y_keys:
                for pkeys in keys:
                    if key in pkeys:
                        for ResRec in Results:
                            if ResRec[key] != "":
                                Yplots.append(key)
                                break
        X, Y = [], []
        for plt in Xplots:
            if plt in Age_keys and 'age' not in X:
                X.append('age')
            if plt in Depth_keys and 'pos' not in X:
                X.append('pos')
        for plt in Yplots:
            if plt in Dec_keys and 'dec' not in Y:
                Y.append('dec')
            if plt in Inc_keys and 'inc' not in Y:
                Y.append('inc')
            if plt in Int_keys and 'int' not in Y:
                Y.append('int')
            if plt in Chi_keys and 'chi' not in Y:
                Y.append('chi')
            if plt in VLat_keys and 'lat' not in Y:
                Y.append('lat')
            if plt in VLon_keys and 'lon' not in Y:
                Y.append('lon')
            if plt in Vadm_keys and 'vadm' not in Y:
                Y.append('vadm')
            if plt in Vdm_keys and 'vdm' not in Y:
                Y.append('vdm')
        if file_type == 'pmag_results':
            print('available objects for plotting: ', PltObjs)
        print('available X plots: ', X)
        print('available Y plots: ', Y)
        print('available method codes: ', methcodes)
        f = open(dir_path+'/.striprc', 'w')
        for x in X:
            f.write('x:'+x+'\n')
        for y in Y:
            f.write('y:'+y+'\n')
        for m in methcodes:
            f.write('m:'+m+'\n')
        for obj in PltObjs:
            f.write('obj:'+obj+'\n')
        sys.exit()
    if plotexp == 1:
        for lkey in Lat_keys:
            for key in list(Results[0].keys()):
                if key == lkey:
                    lat = float(Results[0][lkey])
                    Xinc = [pmag.pinc(lat), -pmag.pinc(lat)]
                    break
        if Xinc == "":
            print('can not plot expected inc for site - lat unknown')
    if method != "" and method not in methcodes:
        print('your method not available, but these are:  ')
        print(methcodes)
        print('use ', methcodes[0], '? ^D to quit')
    if xaxis == 'age':
        for akey in Age_keys:
            for key in list(Results[0].keys()):
                if key == akey:
                    Xplots.append(key)
                    Xunits.append(Unit_keys[key])
    if xaxis == 'pos':
        for dkey in Depth_keys:
            for key in list(Results[0].keys()):
                if key == dkey:
                    Xplots.append(key)
    if len(Xplots) == 0:
        print('desired X axis  information not found')
        sys.exit()
    if xaxis == 'age':
        age_unit = Results[0][Xunits[0]]
    if len(Xplots) > 1:
        print('multiple X axis  keys found, using: ', Xplots[xplotind])
    for ykey in ykeys:
        for key in list(Results[0].keys()):
            if key == ykey:
                Yplots.append(key)
    if len(Yplots) == 0:
        print('desired Y axis  information not found')
        sys.exit()
    if len(Yplots) > 1:
        print('multiple Y axis  keys found, using: ', Yplots[yplotind])

    # check if age or depth info
    if len(Xplots) == 0:
        print("Must have either age or height info to plot ")
        sys.exit()
    #
    # check for variable to plot
    #
    #
    # determine X axis (age or depth)
    #
    if xaxis == "age":
        plotind = "1"
    if method == "":
        try:
            method = methcodes[0]
        except IndexError:
            method = ""
    if xaxis == 'pos':
        xlab = "Stratigraphic Height (meters)"
    else:
        xlab = "Age ("+age_unit+")"
    Xkey = Xplots[xplotind]
    Ykey = Yplots[yplotind]
    ylab = Ykey
    #
    # collect the data for plotting
    XY = []
    isign = 1.
#    if float(Results[0][Xkey])/float(Results[-1][Xkey])>0 and float(Results[0][Xkey])<0:
#        isign=-1. # x axis all same sign and negative, take positive (e.g.,for depth in core)
#        xlab="Stratigraphic Position (meters)"
#    else:
#        isign=1.
    for rec in Results:
        if "magic_method_codes" in list(rec.keys()):
            meths = rec["magic_method_codes"].split(":")
            if method in meths:  # make sure it is desired lab treatment step
                if obj == 'all' and rec[Xkey].strip() != "":
                    XY.append([isign*float(rec[Xkey]), float(rec[Ykey])])
                elif rec[Xkey].strip() != "":
                    name = rec['pmag_result_name'].split()
                    if obj == 'sit' and "Site" in name:
                        XY.append([isign*float(rec[Xkey]), float(rec[Ykey])])
                    if obj == 'sam' and "Sample" in name:
                        XY.append([isign*float(rec[Xkey]), float(rec[Ykey])])
        elif method == "":
            if obj == 'all' and rec[Xkey].strip() != "":
                XY.append([isign*float(rec[Xkey]), float(rec[Ykey])])
            elif rec[Xkey].strip() != "":
                name = rec['pmag_result_name'].split()
                if obj == 'sit' and "Site" in name:
                    XY.append([isign*float(rec[Xkey]), float(rec[Ykey])])
                if obj == 'sam' and "Sample" in name:
                    XY.append([isign*float(rec[Xkey]), float(rec[Ykey])])
        else:
            print("Something wrong with your plotting choices")
            break
    XY.sort()
    title = ""
    if "er_locations_names" in list(Results[0].keys()):
        title = Results[0]["er_location_names"]
    if "er_locations_name" in list(Results[0].keys()):
        title = Results[0]["er_location_name"]
    labels = [xlab, ylab, title]
    pmagplotlib.plot_init(FIG['strat'], 10, 5)
    pmagplotlib.plot_strat(FIG['strat'], XY, labels)  # plot them
    if plotexp == 1:
        pmagplotlib.plot_hs(FIG['strat'], Xinc, 'b', '--')
    if yaxis == 'inc' or yaxis == 'lat':
        pmagplotlib.plot_hs(FIG['strat'], [0], 'b', '-')
        pmagplotlib.plot_hs(FIG['strat'], [-90, 90], 'g', '-')
    if pTS == 1:
        FIG['ts'] = 2
        pmagplotlib.plot_init(FIG['ts'], 10, 5)
        pmagplotlib.plot_ts(FIG['ts'], [amin, amax], ts)
    files = {}
    for key in list(FIG.keys()):
        files[key] = key+'.'+fmt
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        files = {}
        files['strat'] = xaxis+'_'+yaxis+'_.'+fmt
        files['ts'] = 'ts.'+fmt
        titles = {}
        titles['strat'] = 'Depth/Time Series Plot'
        titles['ts'] = 'Time Series Plot'
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    elif plot == 1:
        pmagplotlib.save_plots(FIG, files)
    else:
        pmagplotlib.draw_figs(FIG)
        ans = input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans == "a":
            pmagplotlib.save_plots(FIG, files)

Response: NAME strip_magic. py is the entry point for the magic file strip_magic. py is the main function for the magic file strip_magic. py


Instruction:
Explain what the following Python 3 code does
def main():
    import numpy
    X=arange(.1,10.1,.2) #make a list of numbers
    Y=myfunc(X) # calls myfunc with argument X
    for i in range(len(X)):
        print(X[i],Y[i])

Response: This program prints doubled values!


Instruction:
Make a summary of the following Python 3 code
def main():
    d,i,file2="","",""
    fmt,plot='svg',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 '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file1=sys.argv[ind+1]
    if '-f2' in sys.argv:
        ind=sys.argv.index('-f2')
        file2=sys.argv[ind+1]
    if '-dir' in sys.argv:
        ind=sys.argv.index('-dir')
        d=float(sys.argv[ind+1])
        i=float(sys.argv[ind+2])
    D1=numpy.loadtxt(file1,dtype=numpy.float)
    if file2!="": D2=numpy.loadtxt(file2,dtype=numpy.float)
#
    counter,NumSims=0,1000
#
# get bootstrapped means for first data set
#
    print("Doing first set of directions, please be patient..")
    BDI1=pmag.di_boot(D1)
#
#   convert to cartesian coordinates X1,X2, Y1,Y2 and Z1, Z2
#
    if d=="": # repeat for second data set
        print("Doing second  set of directions, please be patient..")
        BDI2=pmag.di_boot(D2)
    else:
        BDI2=[]
# set up plots
    CDF={'X':1,'Y':2,'Z':3}
    pmagplotlib.plot_init(CDF['X'],4,4)
    pmagplotlib.plot_init(CDF['Y'],4,4)
    pmagplotlib.plot_init(CDF['Z'],4,4)
# draw the cdfs
    pmagplotlib.plot_com(CDF,BDI1,BDI2,[d,i])
    files={}
    files['X']='CD_X.'+fmt
    files['Y']='CD_Y.'+fmt
    files['Z']='CD_Z.'+fmt
    if plot==0:
        pmagplotlib.draw_figs(CDF)
        ans=input("S[a]ve plots, <Return> to quit ")
        if ans=="a":
            pmagplotlib.save_plots(CDF,files)
        else:
            sys.exit()

    else:
        pmagplotlib.save_plots(CDF,files)
        sys.exit()

Response:
NAME
       common_mean.py

    DESCRIPTION
       calculates bootstrap statistics to test for common mean

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

    SYNTAX
       common_mean.py [command line options]

    OPTIONS
       -h prints help message and quits
       -f FILE, input file
       -f2 FILE, optional second file to compare with first file
       -dir D I, optional direction to compare with input file
       -fmt [svg,jpg,pnd,pdf] set figure format [default is svg]
    NOTES
       must have either F2 OR dir but not both


Instruction:
Write a Python 3 function that can
input list of x points, list of y points output: k, a, b, SSE. curvature, circle center, and SSE Function for calculating the radius of the best fit circle to a set of x-y coordinates. Paterson, G. A., (2011), A simple test for the presence of multidomain behaviour during paleointensity experiments, J. Geophys. Res., in press, doi: 10.1029/2011JB008369

Response:
def AraiCurvature(x=x,y=y):
    """
    input: list of x points, list of y points
    output: k, a, b, SSE.  curvature, circle center, and SSE
    Function for calculating the radius of the best fit circle to a set of
    x-y coordinates.
    Paterson, G. A., (2011), A simple test for the presence of multidomain
    behaviour during paleointensity experiments, J. Geophys. Res., in press,
    doi: 10.1029/2011JB008369

    """
    # makes sure all values are floats, then norms them by largest value
    X = numpy.array(list(map(float, x)))
    X = old_div(X, max(X))
    Y = numpy.array(list(map(float, y)))
    Y = old_div(Y, max(Y))
    XY = numpy.array(list(zip(X, Y)))

    #Provide the intitial estimate
    E1=TaubinSVD(XY);

    #Determine the iterative solution
    E2=LMA(XY, E1);

    estimates=[E2[2], E2[0], E2[1]];

    best_a = E2[0]
    best_b = E2[1]
    best_r = E2[2]

    if best_a <= numpy.mean(X) and best_b <= numpy.mean(Y):
        k = old_div(-1.,best_r)
    else:
        k = old_div(1.,best_r)

    SSE = get_SSE(best_a, best_b, best_r, X, Y)
    return k, best_a, best_b, SSE


Instruction:
Make a summary of the following Python 3 code
def TaubinSVD(XY):
    XY = numpy.array(XY)
    X = XY[:,0] - numpy.mean(XY[:,0]) # norming points by x avg
    Y = XY[:,1] - numpy.mean(XY[:,1]) # norming points by y avg
    centroid = [numpy.mean(XY[:,0]), numpy.mean(XY[:,1])]
    Z = X * X + Y * Y
    Zmean = numpy.mean(Z)
    Z0 = old_div((Z - Zmean), (2. * numpy.sqrt(Zmean)))
    ZXY = numpy.array([Z0, X, Y]).T
    U, S, V = numpy.linalg.svd(ZXY, full_matrices=False) #
    V = V.transpose()
    A = V[:,2]
    A[0] = old_div(A[0], (2. * numpy.sqrt(Zmean)))
    A = numpy.concatenate([A, [(-1. * Zmean * A[0])]], axis=0)
    a, b = (-1 * A[1:3]) / A[0] / 2 + centroid
    r = numpy.sqrt(A[1]*A[1]+A[2]*A[2]-4*A[0]*A[3])/abs(A[0])/2;
    return a,b,r

Response: TaubinSVD is a simple algorithm for calculating the center of the fitting circle and the radius of the fitting circle.


Instruction:
Here you have a function in Python 3, explain what it does
def VarCircle(XY, Par):  # must have at least 4 sets of xy points or else division by zero occurs
    if type(XY) != numpy.ndarray:
        XY = numpy.array(XY)
    n = len(XY)
    if n < 4:
        raise Warning("Circle cannot be calculated with less than 4 data points.  Please include more data")
    Dx = XY[:,0] - Par[0]
    Dy = XY[:,1] - Par[1]
    D = numpy.sqrt(Dx * Dx + Dy * Dy) - Par[2]
    result = old_div(numpy.dot(D, D),(n-3))
    return result

Response: Calculates the sample variance of distances from data points XY to the circle Par is a list of numpy arrays.


Instruction:
Make a summary of the following Python 3 code
def LMA(XY,ParIni):
    factorUp=10
    factorDown=0.04
    lambda0=0.01
    epsilon=0.000001
    IterMAX = 50
    AdjustMax = 20
    Xshift=0
    Yshift=0
    dX=1
    dY=0;
    n = len(XY);      # number of data points

    anew = ParIni[0] + Xshift
    bnew = ParIni[1] + Yshift
    Anew = old_div(1.,(2.*ParIni[2]))
    aabb = anew*anew + bnew*bnew
    Fnew = (aabb - ParIni[2]*ParIni[2])*Anew
    Tnew = numpy.arccos(old_div(-anew,numpy.sqrt(aabb)))
    if bnew > 0:
        Tnew = 2*numpy.pi - Tnew
    VarNew = VarCircle(XY,ParIni)

    VarLambda = lambda0;
    finish = 0;

    for it in range(0,IterMAX):

        Aold = Anew
        Fold = Fnew
        Told = Tnew
        VarOld = VarNew

        H = numpy.sqrt(1+4*Aold*Fold);
        aold = -H*numpy.cos(Told)/(Aold+Aold) - Xshift;
        bold = -H*numpy.sin(Told)/(Aold+Aold) - Yshift;
        Rold = old_div(1,abs(Aold+Aold));

        DD = 1 + 4*Aold*Fold;
        D = numpy.sqrt(DD);
        CT = numpy.cos(Told);
        ST = numpy.sin(Told);
        H11=0;
        H12=0;
        H13=0;
        H22=0;
        H23=0;
        H33=0;
        F1=0;
        F2=0;
        F3=0;

        for i in range(0,n):
            Xi = XY[i,0] + Xshift;
            Yi = XY[i,1] + Yshift;
            Zi = Xi*Xi + Yi*Yi;
            Ui = Xi*CT + Yi*ST;
            Vi =-Xi*ST + Yi*CT;

            ADF = Aold*Zi + D*Ui + Fold;
            SQ = numpy.sqrt(4*Aold*ADF + 1);
            DEN = SQ + 1;
            Gi = 2*ADF/DEN;
            FACT = 2/DEN*(1 - Aold*Gi/SQ);
            DGDAi = FACT*(Zi + 2*Fold*Ui/D) - Gi*Gi/SQ;
            DGDFi = FACT*(2*Aold*Ui/D + 1);
            DGDTi = FACT*D*Vi;

            H11 = H11 + DGDAi*DGDAi;
            H12 = H12 + DGDAi*DGDFi;
            H13 = H13 + DGDAi*DGDTi;
            H22 = H22 + DGDFi*DGDFi;
            H23 = H23 + DGDFi*DGDTi;
            H33 = H33 + DGDTi*DGDTi;

            F1 = F1 + Gi*DGDAi;
            F2 = F2 + Gi*DGDFi;
            F3 = F3 + Gi*DGDTi;

        for adjust in range(1,AdjustMax):

#             Cholesly decomposition

            G11 = numpy.sqrt(H11 + VarLambda);
            G12 = old_div(H12,G11)
            G13 = old_div(H13,G11)
            G22 = numpy.sqrt(H22 + VarLambda - G12*G12);
            G23 = old_div((H23 - G12*G13),G22);
            G33 = numpy.sqrt(H33 + VarLambda - G13*G13 - G23*G23);

            D1 = old_div(F1,G11);
            D2 = old_div((F2 - G12*D1),G22);
            D3 = old_div((F3 - G13*D1 - G23*D2),G33);

            dT = old_div(D3,G33);
            dF = old_div((D2 - G23*dT),G22)
            dA = old_div((D1 - G12*dF - G13*dT),G11)

#            updating the parameters

            Anew = Aold - dA;
            Fnew = Fold - dF;
            Tnew = Told - dT;

            if 1+4*Anew*Fnew < epsilon and VarLambda>1:
                Xshift = Xshift + dX;
                Yshift = Yshift + dY;

                H = numpy.sqrt(1+4*Aold*Fold);
                aTemp = -H*numpy.cos(Told)/(Aold+Aold) + dX;
                bTemp = -H*numpy.sin(Told)/(Aold+Aold) + dY;
                rTemp = old_div(1,abs(Aold+Aold));

                Anew = old_div(1,(rTemp + rTemp));
                aabb = aTemp*aTemp + bTemp*bTemp;
                Fnew = (aabb - rTemp*rTemp)*Anew;
                Tnew = numpy.arccos(old_div(-aTemp,numpy.sqrt(aabb)));
                if bTemp > 0:
                    Tnew = 2*numpy.pi - Tnew;
                VarNew = VarOld;
                break;

            if 1+4*Anew*Fnew < epsilon:
                VarLambda = VarLambda * factorUp;
                continue;

            DD = 1 + 4*Anew*Fnew;
            D = numpy.sqrt(DD);
            CT = numpy.cos(Tnew);
            ST = numpy.sin(Tnew);

            GG = 0;

            for i in range(0, n):
                Xi = XY[i,0] + Xshift;
                Yi = XY[i,1] + Yshift;
                Zi = Xi*Xi + Yi*Yi;
                Ui = Xi*CT + Yi*ST;

                ADF = Anew*Zi + D*Ui + Fnew;
                SQ = numpy.sqrt(4*Anew*ADF + 1);
                DEN = SQ + 1;
                Gi = 2*ADF/DEN;
                GG = GG + Gi*Gi;

            VarNew = old_div(GG,(n-3));

            H = numpy.sqrt(1+4*Anew*Fnew);
            anew = -H*numpy.cos(Tnew)/(Anew+Anew) - Xshift;
            bnew = -H*numpy.sin(Tnew)/(Anew+Anew) - Yshift;
            Rnew = old_div(1,abs(Anew+Anew));

            if VarNew <= VarOld:
                progress = old_div((abs(anew-aold) + abs(bnew-bold) + abs(Rnew-Rold)),(Rnew+Rold));
                if progress < epsilon:
                    Aold = Anew;
                    Fold = Fnew;
                    Told = Tnew;
                    VarOld = VarNew # %#ok<NASGU>
                    finish = 1;
                    break;

                VarLambda = VarLambda * factorDown
                break
            else:                 #    %   no improvement
                VarLambda = VarLambda * factorUp;
                continue;

        if finish == 1:
            break

    H = numpy.sqrt(1+4*Aold*Fold);
    result_a = -H*numpy.cos(Told)/(Aold+Aold) - Xshift;
    result_b = -H*numpy.sin(Told)/(Aold+Aold) - Yshift;
    result_r = old_div(1,abs(Aold+Aold));

    return result_a, result_b, result_r

Response: A function to compute the least squares fitting of circles.


Instruction:
Write a Python 3 function that can
calculate the SSE of a set of pages

Response:
def get_SSE(a,b,r,x,y):
    """
    input: a, b, r, x, y.  circle center, radius, xpts, ypts
    output: SSE
    """
    SSE = 0
    X = numpy.array(x)
    Y = numpy.array(y)
    for i in range(len(X)):
        x = X[i]
        y = Y[i]
        v = (numpy.sqrt( (x -a)**2 + (y - b)**2 ) - r )**2
        SSE += v
    return SSE


Instruction:
Can you tell what is the following Python 3 function doing
def main():
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        data=f.readlines() # read in data from standard input
        for line in data: # step through line by line
            dec=spitout(line)
        sys.exit()
    if '-i' in sys.argv:
        while 1: # repeat this block until program killed
            sundata={}  # dictionary with sundata in it
            print ("Time difference between Greenwich Mean Time (hrs to subtract from local time to get GMT): ")
            try:
                sundata["delta_u"]=input("<cntl-D> to quit ")
            except:
                print("\n Good-bye\n")
                sys.exit()
            date=""
            date=date+input("Year:  <cntl-D to quit> ")
            date=date+":"+input("Month:  ")
            date=date+":"+input("Day:  ")
            date=date+":"+input("hour:  ")
            date=date+":"+input("minute:  ")
            sundata["date"]=date
            sundata["lat"]=input("Latitude of sampling site (negative in southern hemisphere): ")
            sundata["lon"]=input("Longitude of sampling site (negative for western hemisphere): ")
            sundata["shadow_angle"]=input("Shadow angle: ")
            print('%7.1f'%(pmag.dosundec(sundata))) # call sundec function from pmag module and print
    else:
        data=sys.stdin.readlines() # read in data from standard input
    for line in data: # step through line by line
        dec=spitout(line)

Response: This function is the entry point for sun. py.


Instruction:
Can you write a function in Python 3 where it
gets the names locations and bounds of locations

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

    DESCRIPTION
        reads in er_sites.txt file and finds all locations and bounds of locations
        outputs er_locations.txt file

    SYNTAX
        sites_locations.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f: specimen input er_sites format file, default is "er_sites.txt"
        -F: locations table: default is "er_locations.txt"
    """
# set defaults
    site_file="er_sites.txt"
    loc_file="er_locations.txt"
    Names,user=[],"unknown"
    Done=[]
    version_num=pmag.get_version()
    args=sys.argv
    dir_path='.'
# get command line stuff
    if '-WD' in args:
        ind=args.index("-WD")
        dir_path=args[ind+1]
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if '-f' in args:
        ind=args.index("-f")
        site_file=args[ind+1]
    if '-F' in args:
        ind=args.index("-F")
        loc_file=args[ind+1]
    #
    site_file=dir_path+'/'+site_file
    loc_file=dir_path+'/'+loc_file
    Sites,file_type=pmag.magic_read(site_file)
    if file_type != 'er_sites':
        print(file_type)
        print(file_type,"This is not a valid er_sites file ")
        sys.exit()
    # read in site data
    #
    LocNames,Locations=[],[]
    for site in Sites:
        if site['er_location_name'] not in LocNames: # new location name
            LocNames.append(site['er_location_name'])
            sites_locs=pmag.get_dictitem(Sites,'er_location_name',site['er_location_name'],'T') # get all sites for this loc
            lats=pmag.get_dictkey(sites_locs,'site_lat','f') # get all the latitudes as floats
            lons=pmag.get_dictkey(sites_locs,'site_lon','f') # get all the longitudes as floats
            LocRec={'er_citation_names':'This study','er_location_name':site['er_location_name'],'location_type':''}
            LocRec['location_begin_lat']=str(min(lats))
            LocRec['location_end_lat']=str(max(lats))
            LocRec['location_begin_lon']=str(min(lons))
            LocRec['location_end_lon']=str(max(lons))
            Locations.append(LocRec)
    if len(Locations)>0:
        pmag.magic_write(loc_file,Locations,"er_locations")
        print("Locations written to: ",loc_file)


Instruction:
Create a Python 3 function to
get all codes of one type

Response:
def get_one_meth_type(self, mtype, method_list):
        """
        Get all codes of one type (i.e., 'anisotropy_estimation')
        """
        cond = method_list['dtype'] == mtype
        codes = method_list[cond]
        return codes


Instruction:
Make a summary of the following Python 3 code
def get_one_meth_category(self, category, all_codes, code_types):
        categories = Series(code_types[code_types[category] == True].index)
        cond = all_codes['dtype'].isin(categories)
        codes = all_codes[cond]
        return codes

Response: Get all codes in one category


Instruction:
Can you generate a brief explanation for the following Python 3 code
def main():

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

    dataframe = extractor.command_line_dataframe([['f', False, 'orient.txt'], ['Fsa', False, 'samples.txt'], ['ncn', False, "1"], ['mcd', False, 'FS-FD'], ['loc', False, 'unknown'], ['app', False, False], ['WD', False, '.'], ['ID', False, '.'], ['DM', False, 3]])
    checked_args = extractor.extract_and_check_args(args, dataframe)
    #print('checked_args:', checked_args)
    orient_file, samp_file, samp_con, method_codes, location_name, append, output_dir, input_dir, data_model = extractor.get_vars(['f', 'Fsa', 'ncn', 'mcd', 'loc', 'app', 'WD', 'ID', 'DM'], checked_args)

    if len(str(samp_con)) > 1:
        samp_con, Z = samp_con.split('-')
        Z = float(Z)
    else:
        Z = 1

    ipmag.azdip_magic(orient_file, samp_file, samp_con, Z, method_codes, location_name, append, output_dir, input_dir, data_model)

Response: This function is the main function of the AzDip Magic module. It takes space delimited AzDip file and converts to MagIC formatted tables and returns the base function.


Instruction:
Given the following Python 3 function, write the documentation
def main():
    dir_path='.'
    names,res,proj,locs,padlon,padlat,fancy,gridspace,details=[],'l','lcc','',0,0,0,15,1
    Age_bounds=[-5000,2000]
    Lat_bounds=[20,45]
    Lon_bounds=[15,55]
    fmt='pdf'
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        sites_file=sys.argv[ind+1]
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res=sys.argv[ind+1]
    if '-etp' in sys.argv:fancy=1
    if '-o' in sys.argv:ocean=1
    if '-d' in sys.argv:details=1
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    verbose=pmagplotlib.verbose
    if '-sav' in sys.argv:
        verbose=0
    if '-pad' in sys.argv:
        ind = sys.argv.index('-pad')
        padlat=float(sys.argv[ind+1])
        padlon=float(sys.argv[ind+2])
    if '-grd' in sys.argv:
        ind = sys.argv.index('-grd')
        gridspace=float(sys.argv[ind+1])
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    sites_file=dir_path+'/'+sites_file
    geo_in=open(sites_file,'r').readlines()
    Age,AgeErr,Vadm,VadmErr,slats,slons=[],[],[],[],[],[]
    for line in geo_in[2:]: # skip top two rows`
        rec=line.split()
        if float(rec[0])>Age_bounds[0] and float(rec[0])<Age_bounds[1] \
           and float(rec[12])>Lat_bounds[0] and float(rec[12]) < Lat_bounds[1]\
            and float(rec[13])>Lon_bounds[0] and float(rec[13])<Lon_bounds[1]:
            Age.append(float(rec[0]))
            AgeErr.append(float(rec[1]))
            Vadm.append(10.*float(rec[6]))
            VadmErr.append(10.*float(rec[7]))
            slats.append(float(rec[12]))
            slons.append(float(rec[13]))
    FIGS={'map':1,'vadms':2}
    pmagplotlib.plot_init(FIGS['map'],6,6)
    pmagplotlib.plot_init(FIGS['vadms'],6,6)
    Opts={'res':res,'proj':proj,'loc_name':locs,'padlon':padlon,'padlat':padlat,'latmin':numpy.min(slats)-padlat,'latmax':numpy.max(slats)+padlat,'lonmin':numpy.min(slons)-padlon,'lonmax':numpy.max(slons)+padlon,'sym':'ro','boundinglat':0.,'pltgrid':1}
    Opts['lon_0']=int(0.5*(numpy.min(slons)+numpy.max(slons)))
    Opts['lat_0']=int(0.5*(numpy.min(slats)+numpy.max(slats)))
    Opts['gridspace']=gridspace
    if details==1:
        Opts['details']={'coasts':1,'rivers':0,'states':1,'countries':1,'ocean':1}
    else:
        Opts['details']={'coasts':1,'rivers':0,'states':0,'countries':0,'ocean':1}
    Opts['details']['fancy']=fancy
    pmagplotlib.plot_map(FIGS['map'],slats,slons,Opts)
    pmagplotlib.plot_xy(FIGS['vadms'],Age,Vadm,sym='bo',xlab='Age (Years CE)',ylab=r'VADM (ZAm$^2$)')
    if verbose:pmagplotlib.draw_figs(FIGS)
    files={}
    for key in list(FIGS.keys()):
        files[key]=key+'.'+fmt
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['map']='Map'
        titles['vadms']='VADMs'
        FIG = pmagplotlib.add_borders(FIGS,titles,black,purple)
        pmagplotlib.save_plots(FIGS,files)
    elif verbose:
        ans=input(" S[a]ve to save plot, Return to quit:  ")
        if ans=="a":
            pmagplotlib.save_plots(FIGS,files)
    else:
        pmagplotlib.save_plots(FIGS,files)

Response: This function is the main function for the main function of the main function. It is the main function for the main function. It is the main function for the main function.


Instruction:
How would you explain what the following Python 3 function does
def main():
    args = sys.argv
    if '-h' in args:
        print(do_help())
        sys.exit()

    # def k15_magic(k15file, specnum=0, sample_naming_con='1', er_location_name="unknown", measfile='magic_measurements.txt', sampfile="er_samples.txt", aniso_outfile='rmag_anisotropy.txt', result_file="rmag_results.txt", input_dir_path='.', output_dir_path='.'):

    dataframe = extractor.command_line_dataframe([['f', True, ''], ['F', False, 'measurements.txt'], ['Fsa', False, 'samples.txt'], ['Fa', False, 'specimens.txt'], [
                                                 'Fr', False, 'rmag_results.txt'], ['spc', False, 0], ['ncn', False, '1'], ['loc', False, 'unknown'], ['WD', False, '.'], ['ID', False, '.'], ['DM', False, 3]])
    checked_args = extractor.extract_and_check_args(args, dataframe)
    k15file, measfile, sampfile, aniso_outfile, result_file, specnum, sample_naming_con, location_name, output_dir_path, input_dir_path, data_model_num = extractor.get_vars(
        ['f', 'F', 'Fsa', 'Fa', 'Fr', 'spc', 'ncn', 'loc', 'WD', 'ID', 'DM'], checked_args)
    program_ran, error_message = convert.k15(k15file, specnum=specnum, sample_naming_con=sample_naming_con, location=location_name, meas_file=measfile,
                                                 samp_file=sampfile, aniso_outfile=aniso_outfile, result_file=result_file, input_dir_path=input_dir_path, dir_path=output_dir_path, data_model_num=data_model_num)

Response: This function is the main entry point for the k15_magic. py script.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def main(command_line=True, **kwargs):

#
#              NB: use PHI, THETA = -1 -1 to signal that it changes, i.e. in anisotropy experiment
#        -ac B : peak AF field (in mT) for ARM acquisition, default is none
    #
    #initialize variables
    norm='cc'
    samp_con,Z='3',1
    meas_file='magic_measurements.txt'
    spec_file='er_specimens.txt'
    samp_file='er_samples.txt'
    site_file='er_sites.txt'
    ErSpecs,ErSamps,ErSites,ErLocs,ErCits=[],[],[],[],[]
    MeasRecs=[]
    specnum,units,locname=0,"1","unknown"
    citation="This study"
    dir_path='.'
    args=sys.argv
    if command_line:
        if '-WD' in args:
            ind=args.index("-WD")
            dir_path=args[ind+1]
        if "-h" in args:
            print(main.__doc__)
            return False
        if "-usr" in args:
            ind=args.index("-usr")
            user=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 '-Fsa' in args:
            ind=args.index("-Fsa")
            samp_file=args[ind+1]
        if '-Fsi' in args:   # LORI addition
            ind=args.index("-Fsi")
            site_file=args[ind+1]
        if '-loc' in args:
            ind=args.index("-loc")
            locname=args[ind+1]
        if '-mcd' in args:
            ind=args.index("-mcd")
            methods=args[ind+1]
        else:
            methods='SO-MAG'
        if '-spc' in args:
            ind=args.index("-spc")
            specnum=-int(args[ind+1])
        if '-n' in args:
            ind=args.index("-n")
            norm=args[ind+1]
        if "-A" in args:
            avg=1
        else:
            avg=0
        if '-dc' in args:
            ind=args.index('-dc')
            DC_FIELD,DC_PHI,DC_THETA=list(map(float,args[ind+1].strip('( ) [ ]').split(',')))
            DC_FIELD *= 1e-6
            yn=''
            GET_DC_PARAMS=False
        else: GET_DC_PARAMS,DC_FIELD,DC_PHI,DC_THETA,yn=True,0,0,-90,''
        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")
                    return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
                else:
                    Z=samp_con.split("-")[1]
                    samp_con="4"
            elif "7" in samp_con:
                if "-" not in samp_con:
                    print("option [7] must be in form 7-Z where Z is an integer")
                    return False, "naming convention option [7] must be in form 7-Z where Z is an integer"
                else:
                    Z=samp_con.split("-")[1]
                    samp_con="7"
        if '-f' in args:
            ind=args.index("-f")
            magfile=args[ind+1]
        if '-ID' in args:
            ind = args.index('-ID')
            input_dir_path = args[ind+1]
        else:
            input_dir_path = os.path.split(magfile)[0]
        output_dir_path = dir_path
        # LJ

    # if you are running as a module:
    elif not command_line:
        dir_path = kwargs.get('dir_path', '.')
        user = kwargs.get('user', '')
        meas_file = kwargs.get('meas_file', 'magic_measurements.txt') # outfile
        spec_file = kwargs.get('spec_file', 'er_specimens.txt') # specimen outfile
        samp_file = kwargs.get('samp_file', 'er_samples.txt') # sample outfile
        site_file = kwargs.get('site_file', 'er_sites.txt') # site outfile
        locname = kwargs.get('locname', '')
        methods = kwargs.get('methods', ['SO-MAG'])
        specnum = -int(kwargs.get('specnum', 0))
        norm = kwargs.get('norm', 'cc')
        avg = kwargs.get('avg', 0)  # 0 means do average, 1 means don't
        samp_con = kwargs.get('samp_con', '3')
        magfile = kwargs.get('magfile', '')
        input_dir_path = kwargs.get('input_dir_path', os.path.split(magfile)[0])
        output_dir_path = dir_path
        DC_FIELD,DC_PHI,DC_THETA = list(map(float, kwargs.get('dc_params', (0,0,-90))))
        DC_FIELD *= 1e-6
        yn = ''
        if DC_FIELD==0 and DC_PHI==0 and DC_THETA==-90: GET_DC_PARAMS=True
        else: GET_DC_PARAMS=False
        # done with module-specific stuff

        # formatting and checking variables
        if "4" in samp_con:
            if "-" not in samp_con:
                print("option [4] must be in form 4-Z where Z is an integer")
                return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        elif "7" in samp_con:
            if "-" not in samp_con:
                print("option [7] must be in form 7-Z where Z is an integer")
                return False, "naming convention option [7] must be in form 7-Z where Z is an integer"
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"

    magfile = os.path.join(input_dir_path, magfile)
    spec_file = os.path.join(output_dir_path, spec_file)
    samp_file = os.path.join(output_dir_path, samp_file)
    site_file = os.path.join(output_dir_path, site_file)
    meas_file= os.path.join(output_dir_path, meas_file)
    FIRST_GET_DC=True
    try:
        with open(magfile,'r') as file_input:
            File = file_input.readlines()
    except Exception as ex:
        print("bad sam file name: ", magfile)
        return False, "bad sam file name"
    if len(File) == 1: File = File[0].split('\r'); File = [x+"\r\n" for x in File]
    sids,ln,format=[],0,'CIT'
    formats=['CIT','2G','APP','JRA']
    if File[ln].strip()=='CIT': ln+=1
    ErLocRec={}
    ErLocRec["er_location_name"]=locname
    ErLocRec["er_citation_names"]=citation
    comment=File[ln]
    if comment=='CIT':
       format=comment
       ln+=1
    comment=File[ln]
    print(comment)
    ln+=1
    specimens,samples,sites=[],[],[]
    if format=='CIT':
        line=File[ln].split()
        site_lat=line[0]
        site_lon=line[1]
        ErLocRec["location_begin_lat"]=site_lat
        ErLocRec["location_begin_lon"]=site_lon
        ErLocRec["location_end_lat"]=site_lat
        ErLocRec["location_end_lon"]=site_lon
        ErLocs.append(ErLocRec)
        try: Cdec=float(line[2])
        except ValueError: pdb.set_trace()
        for k in range(ln+1,len(File)):
            line=File[k]
            rec=line.split()
            if rec == []: continue
            specimen=rec[0]
            specimens.append(specimen)
    for specimen in specimens:
        ErSpecRec,ErSampRec,ErSiteRec={},{},{}
        if specnum!=0:
            sample=specimen[:specnum]
        else: sample=specimen
        site=pmag.parse_site(sample,samp_con,Z)
        ErSpecRec['er_specimen_name']=specimen
        ErSpecRec['er_sample_name']=sample
        ErSpecRec['er_site_name']=site
        ErSpecRec['er_location_name']=locname
        ErSpecRec['er_citation_names']=citation
        ErSampRec['er_sample_name']=sample
        ErSampRec['er_site_name']=site
        ErSampRec['er_location_name']=locname
        ErSampRec['er_citation_names']=citation
        ErSampRec['magic_method_codes']=methods
        ErSampRec['sample_declination_correction']='%7.1f'%(Cdec)
        ErSiteRec['er_site_name']=site
        ErSiteRec['er_location_name']=locname
        ErSiteRec['er_citation_names']=citation
        ErSiteRec['site_lat']=site_lat
        ErSiteRec['site_lon']=site_lon
        with open(os.path.join(input_dir_path,specimen),'r') as finput:
            Lines = list(finput.readlines())
        comment = ""
        line=Lines[0].split()
        if len(line)>2:
            comment=line[2]
        info=Lines[1].split()
        vol=float(info[-1])
        if vol!=1.0:
            if norm=='cc':units="1"
            if norm=='m3':units="2"
            ErSpecRec['specimen_weight']=""
            if units=="1" or "":
                ErSpecRec['specimen_volume']='%10.3e'%(vol*1e-6)
            else:
                ErSpecRec['specimen_volume']='%10.3e'%(vol)
        else:
            if norm=='cc':units="1"
            if norm=='m3':units="2"
            ErSpecRec['specimen_volume']=""
            if units=="1" or "":
                ErSpecRec['specimen_weight']='%10.3e'%(vol*1e-3)
            else:
                ErSpecRec['specimen_weight']='%10.3e'%(vol)
        dip=float(info[-2])
        dip_direction=float(info[-3])+Cdec+90.
        sample_dip=-float(info[-4])
        sample_azimuth=float(info[-5])+Cdec-90.
        if len(info)>5:
            ErSampRec['sample_height']=info[-6]
        else:
            ErSampRec['sample_height']='0'
        ErSampRec['sample_azimuth']='%7.1f'%(sample_azimuth)
        ErSampRec['sample_dip']='%7.1f'%(sample_dip)
        ErSampRec['sample_bed_dip']='%7.1f'%(dip)
        ErSampRec['sample_bed_dip_direction']='%7.1f'%(dip_direction)
        ErSampRec['sample_class']=''
        ErSampRec['sample_type']=''
        ErSampRec['sample_lithology']=''
        if Cdec!=0 or Cdec!="":
            ErSampRec['magic_method_codes']='SO-CMD-NORTH'
        else:
            ErSampRec['magic_method_codes']='SO-MAG'
        for line in Lines[2:len(Lines)]:
            if line == '\n': continue
            MeasRec=ErSpecRec.copy()
#           Remove specimen_volume and specimen_weight as they do not exits in the magic_measurement table
            del MeasRec["specimen_volume"]
            del MeasRec["specimen_weight"]
            treat_type=line[0:3]
            if treat_type[1] == '.':
                treat_type = 'NRM'
            treat=line[2:6]
            try: float(treat)
            except ValueError: treat = line[3:6]
            if treat_type.startswith('NRM'):
                MeasRec['magic_method_codes']='LT-NO'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']='273'
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_dc_field_phi'] = '%1.2f'%DC_PHI
                MeasRec['treatment_dc_field_theta'] = '%1.2f'%DC_THETA
                MeasRec['treatment_ac_field']='0'
            elif treat_type.startswith('AF'):
                MeasRec['magic_method_codes']='LT-AF-Z'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']='273'
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_dc_field_phi'] = '%1.2f'%DC_PHI
                MeasRec['treatment_dc_field_theta'] = '%1.2f'%DC_THETA
                if treat.strip() == '':
                    MeasRec['treatment_ac_field']='0'
                else:
                    MeasRec['treatment_ac_field']='%10.3e'%(float(treat)*1e-3)
            elif treat_type.startswith('ARM'):
                MeasRec['magic_method_codes']="LP-ARM"
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']='273'
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_dc_field_phi'] = '%1.2f'%DC_PHI
                MeasRec['treatment_dc_field_theta'] = '%1.2f'%DC_THETA
                if treat.strip() == '':
                    MeasRec['treatment_ac_field']='0'
                else:
                    MeasRec['magic_method_codes']="LP-ARM-AFD"
                    MeasRec['treatment_ac_field']='%10.3e'%(float(treat)*1e-3)
            elif treat_type.startswith('TT'):
                MeasRec['magic_method_codes']='LT-T-Z'
                MeasRec['measurement_temp']='273'
                if treat.strip() == '':
                    MeasRec['treatment_temp']='273'
                else:
                    MeasRec['treatment_temp']='%7.1f'%(float(treat)+273)
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_dc_field_phi'] = '%1.2f'%DC_PHI
                MeasRec['treatment_dc_field_theta'] = '%1.2f'%DC_THETA
                MeasRec['treatment_ac_field']='0'
            elif treat_type.startswith('LT') or treat_type.startswith('LN2'):
                MeasRec['magic_method_codes']='LT-LT-Z'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']='77'
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_dc_field_phi'] = '%1.2f'%DC_PHI
                MeasRec['treatment_dc_field_theta'] = '%1.2f'%DC_THETA
                MeasRec['treatment_ac_field']='0'
            elif line[4] == '0': #assume decimal IZZI format 0 field thus can hardcode the dc fields
                MeasRec['magic_method_codes']='LT-T-Z'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']=str(int(treat_type) + 273)
                MeasRec['treatment_dc_field']='0'
                MeasRec['treatment_dc_field_phi'] = '%1.2f'%DC_PHI
                MeasRec['treatment_dc_field_theta'] = '%1.2f'%DC_THETA
                MeasRec['treatment_ac_field']='0'
            elif line[4] == '1': #assume decimal IZZI format in constant field
                if GET_DC_PARAMS: GET_DC_PARAMS, FIRST_GET_DC, yn, DC_FIELD, DC_PHI, DC_THETA = get_dc_params(FIRST_GET_DC,specimen,treat_type,yn)
                MeasRec['magic_method_codes']='LT-T-I'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']=str(int(treat_type) + 273)
                MeasRec['treatment_dc_field']='%1.2e'%DC_FIELD
                MeasRec['treatment_dc_field_phi'] = '%1.2f'%DC_PHI
                MeasRec['treatment_dc_field_theta'] = '%1.2f'%DC_THETA
                MeasRec['treatment_ac_field']='0'
            elif line[4] == '2': #assume decimal IZZI format PTRM step
                if GET_DC_PARAMS: GET_DC_PARAMS, FIRST_GET_DC, yn, DC_FIELD, DC_PHI, DC_THETA = get_dc_params(FIRST_GET_DC,specimen,treat_type,yn)
                MeasRec['magic_method_codes']='LT-PTRM-I'
                MeasRec['measurement_temp']='273'
                MeasRec['treatment_temp']=str(int(treat_type) + 273)
                MeasRec['treatment_dc_field']='%1.2e'%DC_FIELD
                MeasRec['treatment_dc_field_phi'] = '%1.2f'%DC_PHI
                MeasRec['treatment_dc_field_theta'] = '%1.2f'%DC_THETA
                MeasRec['treatment_ac_field']='0'
            else:
                print("trouble with your treatment steps")
            MeasRec['measurement_dec']=line[46:51]
            MeasRec['measurement_inc']=line[52:58]
            M='%8.2e'%(float(line[31:39])*vol*1e-3) # convert to Am2
            MeasRec['measurement_magn_moment']=M
            MeasRec['measurement_csd']='%7.1f'%(eval(line[41:46]))
            MeasRec["measurement_positions"]='1'
            MeasRec['measurement_standard']='u'
            if len(line)>60:
                MeasRec['magic_instrument_codes']=line[85:]
                MeasRec['measurement_sd_x']='%8.2e'%(float(line[58:67])*1e-8) #(convert e-5emu to Am2)
                MeasRec['measurement_sd_y']='%8.2e'%(float(line[67:76])*1e-8)
                MeasRec['measurement_sd_z']='%8.2e'%(float(line[76:85])*1e-8)
            MeasRecs.append(MeasRec)
        ErSpecs.append(ErSpecRec)
        if sample not in samples:
            samples.append(sample)
            ErSamps.append(ErSampRec)
        site=pmag.parse_site(sample,samp_con,Z)
        if site not in sites:
            sites.append(site)
            ErSites.append(ErSiteRec)
    pmag.magic_write(spec_file,ErSpecs,'er_specimens')
    print('specimens stored in ',spec_file)
    pmag.magic_write(samp_file,ErSamps,'er_samples')
    print('samples stored in ',samp_file)
    pmag.magic_write(site_file,ErSites,'er_sites')
    print('sites stored in ', site_file)
    Fixed=pmag.measurements_methods(MeasRecs,avg)
    pmag.magic_write(meas_file,Fixed,'magic_measurements')
    print('data stored in ',meas_file)
    return True, meas_file

Response: This function is the main entry point for the cit_magic. py script.


Instruction:
Create a Python 3 function for
naming nac_util. py is the main function of the demagnetization diagram.

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

    DESCRIPTION
       plots demagnetization data. The equal area projection has the X direction (usually North in geographic coordinates)
          to the top.  The red line is the X axis of the Zijderveld diagram.  Solid symbols are lower hemisphere.
          The solid (open) symbols in the Zijderveld diagram are X,Y (X,Z) pairs.  The demagnetization diagram plots the
          fractional remanence remaining after each step. The green line is the fraction of the total remaence removed
          between each step.

    INPUT FORMAT
       takes specimen_name treatment intensity declination inclination  in space
 delimited file

    SYNTAX
        zeq.py [command line options

    OPTIONS
        -f FILE for reading from command line
        -u [mT,C] specify units of mT OR C, default is unscaled
        -sav save figure and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
        -beg [step number] treatment step for beginning of PCA calculation, 0 is default
        -end [step number] treatment step for end of PCA calculation, last step is default
        -ct [l,p,f] Calculation Type: best-fit line,  plane or fisher mean; line is default

    """
    files,fmt,plot={},'svg',0
    end_pca,beg_pca="",""
    calculation_type='DE-BFL'
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    else:
        if '-f' in sys.argv:
            ind=sys.argv.index('-f')
            file=sys.argv[ind+1]
        else:
            print(main.__doc__)
            sys.exit()
        if '-u' in sys.argv:
            ind=sys.argv.index('-u')
            units=sys.argv[ind+1]
            if units=="C":SIunits="K"
            if units=="mT":SIunits="T"
        else:
            units="U"
            SIunits="U"
    if '-sav' in sys.argv:plot=1
    if '-ct' in sys.argv:
        ind=sys.argv.index('-ct')
        ct=sys.argv[ind+1]
        if ct=='f':calculation_type='DE-FM'
        if ct=='p':calculation_type='DE-BFP'
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-beg' in sys.argv:
        ind=sys.argv.index('-beg')
        beg_pca=int(sys.argv[ind+1])
    if '-end' in sys.argv:
        ind=sys.argv.index('-end')
        end_pca=int(sys.argv[ind+1])
    f=open(file,'r')
    data=f.readlines()
#
    datablock= [] # set up list for data
    s="" # initialize specimen name
    angle=0.
    for line in data:   # read in the data from standard input
        rec=line.split() # split each line on space to get records
        if angle=="":angle=float(rec[3])
        if s=="":s=rec[0]
        if units=='mT':datablock.append([float(rec[1])*1e-3,float(rec[3]),float(rec[4]),1e-3*float(rec[2]),'','g']) # treatment, dec, inc, int # convert to T and Am^2 (assume emu)
        if units=='C':datablock.append([float(rec[1])+273.,float(rec[3]),float(rec[4]),1e-3*float(rec[2]),'','g']) # treatment, dec, inc, int, convert to K and Am^2, assume emu
        if units=='U':datablock.append([float(rec[1]),float(rec[3]),float(rec[4]),float(rec[2]),'','g']) # treatment, dec, inc, int, using unscaled units
# define figure numbers in a dictionary for equal area, zijderveld,
#  and intensity vs. demagnetiztion step respectively
    ZED={}
    ZED['eqarea'],ZED['zijd'],  ZED['demag']=1,2,3
    pmagplotlib.plot_init(ZED['eqarea'],5,5) # initialize plots
    pmagplotlib.plot_init(ZED['zijd'],5,5)
    pmagplotlib.plot_init(ZED['demag'],5,5)
#
#
    pmagplotlib.plot_zed(ZED,datablock,angle,s,SIunits) # plot the data
    if plot==0:pmagplotlib.draw_figs(ZED)
#
# print out data for this sample to screen
#
    recnum=0
    for plotrec in datablock:
        if units=='mT':print('%i  %7.1f %8.3e %7.1f %7.1f ' % (recnum,plotrec[0]*1e3,plotrec[3],plotrec[1],plotrec[2]))
        if units=='C':print('%i  %7.1f %8.3e %7.1f %7.1f ' % (recnum,plotrec[0]-273.,plotrec[3],plotrec[1],plotrec[2]))
        if units=='U':print('%i  %7.1f %8.3e %7.1f %7.1f ' % (recnum,plotrec[0],plotrec[3],plotrec[1],plotrec[2]))
        recnum += 1
    if plot==0:
      while 1:
        if beg_pca!="" and end_pca!="" and calculation_type!="":
                pmagplotlib.plot_zed(ZED,datablock,angle,s,SIunits) # plot the data
                mpars=pmag.domean(datablock,beg_pca,end_pca,calculation_type) # get best-fit direction/great circle
                pmagplotlib.plot_dir(ZED,mpars,datablock,angle) # plot the best-fit direction/great circle
                print('Specimen, calc_type, N, min, max, MAD, dec, inc')
                if units=='mT':print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s,calculation_type,mpars["specimen_n"],mpars["measurement_step_min"]*1e3,mpars["measurement_step_max"]*1e3,mpars["specimen_mad"],mpars["specimen_dec"],mpars["specimen_inc"]))
                if units=='C':print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s,calculation_type,mpars["specimen_n"],mpars["measurement_step_min"]-273,mpars["measurement_step_max"]-273,mpars["specimen_mad"],mpars["specimen_dec"],mpars["specimen_inc"]))
                if units=='U':print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s,calculation_type,mpars["specimen_n"],mpars["measurement_step_min"],mpars["measurement_step_max"],mpars["specimen_mad"],mpars["specimen_dec"],mpars["specimen_inc"]))
        if end_pca=="":end_pca=len(datablock)-1 # initialize end_pca, beg_pca to first and last measurement
        if beg_pca=="":beg_pca=0
        ans=input(" s[a]ve plot, [b]ounds for pca and calculate, change [h]orizontal projection angle, [q]uit:   ")
        if ans =='q':
            sys.exit()
        if  ans=='a':
            files={}
            for key in list(ZED.keys()):
                files[key]=s+'_'+key+'.'+fmt
            pmagplotlib.save_plots(ZED,files)
        if ans=='h':
            angle=float(input(" Declination to project onto horizontal axis? "))
            pmagplotlib.plot_zed(ZED,datablock,angle,s,SIunits) # plot the data

        if ans=='b':
            GoOn=0
            while GoOn==0: # keep going until reasonable bounds are set
                print('Enter index of first point for pca: ','[',beg_pca,']')
                answer=input('return to keep default  ')
                if answer != "":beg_pca=int(answer)
                print('Enter index  of last point for pca: ','[',end_pca,']')
                answer=input('return to keep default  ')
                if answer != "":
                    end_pca=int(answer)
                if beg_pca >=0 and beg_pca<=len(datablock)-2 and end_pca>0 and end_pca<len(datablock):
                    GoOn=1
                else:
                    print("Bad entry of indices - try again")
                    end_pca=len(datablock)-1
                    beg_pca=0
            GoOn=0
            while GoOn==0:
                ct=input('Enter Calculation Type: best-fit line,  plane or fisher mean [l]/p/f :  ' )
                if ct=="" or ct=="l":
                    calculation_type="DE-BFL"
                    GoOn=1 # all good
                elif ct=='p':
                    calculation_type="DE-BFP"
                    GoOn=1 # all good
                elif ct=='f':
                    calculation_type="DE-FM"
                    GoOn=1 # all good
                else:
                    print("bad entry of calculation type: try again. ") # keep going
                pmagplotlib.plot_zed(ZED,datablock,angle,s,SIunits) # plot the data
                mpars=pmag.domean(datablock,beg_pca,end_pca,calculation_type) # get best-fit direction/great circle
                pmagplotlib.plot_dir(ZED,mpars,datablock,angle) # plot the best-fit direction/great circle
                print('Specimen, calc_type, N, min, max, MAD, dec, inc')
                if units=='mT':print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s,calculation_type,mpars["specimen_n"],mpars["measurement_step_min"]*1e3,mpars["measurement_step_max"]*1e3,mpars["specimen_mad"],mpars["specimen_dec"],mpars["specimen_inc"]))
                if units=='C':print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s,calculation_type,mpars["specimen_n"],mpars["measurement_step_min"]-273,mpars["measurement_step_max"]-273,mpars["specimen_mad"],mpars["specimen_dec"],mpars["specimen_inc"]))
                if units=='U':print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s,calculation_type,mpars["specimen_n"],mpars["measurement_step_min"],mpars["measurement_step_max"],mpars["specimen_mad"],mpars["specimen_dec"],mpars["specimen_inc"]))
        pmagplotlib.draw_figs(ZED)
    else:
        print(beg_pca,end_pca)
        if beg_pca!="" and end_pca!="":
            pmagplotlib.plot_zed(ZED,datablock,angle,s,SIunits) # plot the data
            mpars=pmag.domean(datablock,beg_pca,end_pca,calculation_type) # get best-fit direction/great circle
            pmagplotlib.plot_dir(ZED,mpars,datablock,angle) # plot the best-fit direction/great circle
            print('Specimen, calc_type, N, min, max, MAD, dec, inc')
            if units=='mT':print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s,calculation_type,mpars["specimen_n"],mpars["measurement_step_min"]*1e3,mpars["measurement_step_max"]*1e3,mpars["specimen_mad"],mpars["specimen_dec"],mpars["specimen_inc"]))
            if units=='C':print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s,calculation_type,mpars["specimen_n"],mpars["measurement_step_min"]-273,mpars["measurement_step_max"]-273,mpars["specimen_mad"],mpars["specimen_dec"],mpars["specimen_inc"]))
            if units=='U':print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' % (s,calculation_type,mpars["specimen_n"],mpars["measurement_step_min"],mpars["measurement_step_max"],mpars["specimen_mad"],mpars["specimen_dec"],mpars["specimen_inc"]))
        files={}
        for key in list(ZED.keys()):
            files[key]=s+'_'+key+'.'+fmt
        pmagplotlib.save_plots(ZED,files)


Instruction:
Here you have a function in Python 3, explain what it does
def check_for_reqd_cols(data, reqd_cols):
    missing = []
    for col in reqd_cols:
        if col not in data[0]:
            missing.append(col)
    return missing

Response: Check data for required columns


Instruction:
Given the following Python 3 function, write the documentation
def main():
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    # reset log files
    for fname in ['log.txt', 'errors.txt']:
        f = os.path.join(os.getcwd(), fname)
        if os.path.exists(f):
            os.remove(f)
    dirlist = ['./']
    dir_path = os.getcwd()
    #
    if '-fmt' in sys.argv:
        ind = sys.argv.index("-fmt")
        fmt = sys.argv[ind + 1]
    else:
        fmt = 'png'
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        filelist = [sys.argv[ind + 1]]
    else:
        filelist = os.listdir(dir_path)
    ## initialize some variables
    samp_file = 'samples.txt'
    azimuth_key = 'azimuth'
    meas_file = 'measurements.txt'
    loc_key = 'location'
    loc_file = 'locations.txt'
    method_key = 'method_codes'
    dec_key = 'dir_dec'
    inc_key = 'dir_inc'
    tilt_corr_key = "dir_tilt_correction"
    aniso_tilt_corr_key = "aniso_tilt_correction"
    hyst_bcr_key = "hyst_bcr"
    hyst_mr_key = "hyst_mr_moment"
    hyst_ms_key = "hyst_ms_moment"
    hyst_bc_key = "hyst_bc"
    Mkeys = ['magnitude', 'magn_moment', 'magn_volume', 'magn_mass']
    results_file = 'sites.txt'
    hyst_file = 'specimens.txt'
    aniso_file = 'specimens.txt'
    # create contribution and propagate data throughout
    con = cb.Contribution()
    con.propagate_location_to_measurements()
    con.propagate_location_to_specimens()
    con.propagate_location_to_samples()
    if not con.tables:
        print('-E- No MagIC tables could be found in this directory')
        error_log("No MagIC tables found")
        return
    # try to get the contribution id for error logging
    con_id = ""
    if 'contribution' in con.tables:
        if 'id' in con.tables['contribution'].df.columns:
            con_id = con.tables['contribution'].df.iloc[0]['id']
    # check to see if propagation worked, otherwise you can't plot by location
    lowest_table = None
    for table in con.ancestry:
        if table in con.tables:
            lowest_table = table
            break

    do_full_directory = False
    # check that locations propagated down to the lowest table in the contribution
    if 'location' in con.tables[lowest_table].df.columns:
        if 'locations' not in con.tables:
            info_log('location names propagated to {}, but could not be validated'.format(lowest_table))
        # are there any locations in the lowest table?
        elif not all(con.tables[lowest_table].df['location'].isnull()):
            locs = con.tables['locations'].df.index.unique()
            lowest_locs = con.tables[lowest_table].df['location'].unique()
            incorrect_locs = set(lowest_locs).difference(set(locs))
            # are they actual locations?
            if not incorrect_locs:
                info_log('location names propagated to {}'.format(lowest_table))
            else:
                do_full_directory = True
                error_log('location names did not propagate fully to {} table (looks like there are some naming inconsistencies between tables)'.format(lowest_table), con_id=con_id)
        else:
            do_full_directory = True
            error_log('could not propagate location names down to {} table'.format(lowest_table), con_id=con_id)
    else:
        do_full_directory = True
        error_log('could not propagate location names down to {} table'.format(lowest_table), con_id=con_id)

    all_data = {}
    all_data['measurements'] = con.tables.get('measurements', None)
    all_data['specimens'] = con.tables.get('specimens', None)
    all_data['samples'] = con.tables.get('samples', None)
    all_data['sites'] = con.tables.get('sites', None)
    all_data['locations'] = con.tables.get('locations', None)
    if 'locations' in con.tables:
        locations = con.tables['locations'].df.index.unique()
    else:
        locations = ['']
    dirlist = [loc for loc in locations if cb.not_null(loc, False) and loc != 'nan']
    if not dirlist:
        dirlist = ["./"]
    if do_full_directory:
        dirlist = ["./"]

    # plot the whole contribution as one location
    if dirlist == ["./"]:
        error_log('plotting the entire contribution as one location', con_id=con_id)
        for fname in os.listdir("."):
            if fname.endswith(".txt"):
                shutil.copy(fname, "tmp_" + fname)

    # if possible, go through all data by location
    # use tmp_*.txt files to separate out by location

    for loc in dirlist:
        print('\nworking on: ', loc)

        def get_data(dtype, loc_name):
            """
            Extract data of type dtype for location loc_name.
            Write tmp_dtype.txt files if possible.
            """
            if cb.not_null(all_data[dtype], False):
                data_container = all_data[dtype]
                if loc_name == "./":
                    data_df = data_container.df
                else:
                    # awkward workaround for chars like "(" and "?" that break in regex
                    try:
                        data_df = data_container.df[data_container.df['location'].astype(str).str.contains(loc_name, na=False)]
                    except: #sre_constants.error:
                        data_df = data_container.df[data_container.df['location'] == loc_name]

                data = data_container.convert_to_pmag_data_list(df=data_df)
                res = data_container.write_magic_file('tmp_{}.txt'.format(dtype), df=data_df)
                if not res:
                    return []
                return data

        meas_data = get_data('measurements', loc)
        spec_data = get_data('specimens', loc)
        samp_data = get_data('samples', loc)
        site_data = get_data('sites', loc)
        loc_data = get_data('locations', loc)

        if loc == "./":  # if you can't sort by location, do everything together
            try:
                meas_data = con.tables['measurements'].convert_to_pmag_data_list()
            except KeyError:
                meas_data = None
            try:
                spec_data = con.tables['specimens'].convert_to_pmag_data_list()
            except KeyError:
                spec_data = None
            try:
                samp_data = con.tables['samples'].convert_to_pmag_data_list()
            except KeyError:
                samp_data = None
            try:
                site_data = con.tables['sites'].convert_to_pmag_data_list()
            except KeyError:
                site_data = None

        crd = 's'
        if samp_file in filelist and samp_data:  # find coordinate systems
            samps = samp_data
            file_type = "samples"
            # get all non blank sample orientations
            Srecs = pmag.get_dictitem(samps, azimuth_key, '', 'F')
            if len(Srecs) > 0:
                crd = 'g'
                print('using geographic coordinates')
            else:
                print('using specimen coordinates')
        else:
            if VERBOSE:
                print('-I- No sample data found')
        if meas_file in filelist and meas_data:  # start with measurement data
            print('working on measurements data')
            data = meas_data
            file_type = 'measurements'
            # looking for  zeq_magic possibilities
            # get all non blank method codes
            AFZrecs = pmag.get_dictitem(data, method_key, 'LT-AF-Z', 'has')
            # get all non blank method codes
            TZrecs = pmag.get_dictitem(data, method_key, 'LT-T-Z', 'has')
            # get all non blank method codes
            MZrecs = pmag.get_dictitem(data, method_key, 'LT-M-Z', 'has')
            # get all dec measurements
            Drecs = pmag.get_dictitem(data, dec_key, '', 'F')
            # get all inc measurements
            Irecs = pmag.get_dictitem(data, inc_key, '', 'F')
            for key in Mkeys:
                Mrecs = pmag.get_dictitem(
                    data, key, '', 'F')  # get intensity data
                if len(Mrecs) > 0:
                    break
            # potential for stepwise demag curves
            if len(AFZrecs) > 0 or len(TZrecs) > 0 or len(MZrecs) > 0 and len(Drecs) > 0 and len(Irecs) > 0 and len(Mrecs) > 0:
                CMD = 'zeq_magic.py -f tmp_measurements.txt -fsp tmp_specimens.txt -fsa tmp_samples.txt -fsi tmp_sites.txt -sav -fmt ' + fmt + ' -crd ' + crd + " -new"
                print(CMD)
                info_log(CMD, loc)
                os.system(CMD)
            # looking for  thellier_magic possibilities
            if len(pmag.get_dictitem(data, method_key, 'LP-PI-TRM', 'has')) > 0:
                CMD = 'thellier_magic.py -f tmp_measurements.txt -fsp tmp_specimens.txt -sav -fmt ' + fmt
                print(CMD)
                info_log(CMD, loc)
                os.system(CMD)
            # looking for hysteresis possibilities
            if len(pmag.get_dictitem(data, method_key, 'LP-HYS', 'has')) > 0:  # find hyst experiments
                # check for reqd columns
                missing = check_for_reqd_cols(data, ['treat_temp'])
                if missing:
                    error_log('LP-HYS method code present, but required column(s) [{}] missing'.format(", ".join(missing)), loc, "quick_hyst.py", con_id=con_id)
                else:
                    CMD = 'quick_hyst.py -f tmp_measurements.txt -sav -fmt ' + fmt
                    print(CMD)
                    info_log(CMD, loc)
                    os.system(CMD)
            # equal area plots of directional data
            # at measurment level (by specimen)

            if data:
                missing = check_for_reqd_cols(data, ['dir_dec', 'dir_inc'])
                if not missing:
                    CMD = "eqarea_magic.py -f tmp_measurements.txt -obj spc -sav -no-tilt -fmt " + fmt
                    print(CMD)
                    os.system(CMD)
                    info_log(CMD, loc, "eqarea_magic.py")

        else:
            if VERBOSE:
                print('-I- No measurement data found')

        # site data
        if results_file in filelist and site_data:
            print('-I- result file found', results_file)
            data = site_data
            file_type = 'sites'
            print('-I- working on site directions')
            print('number of datapoints: ', len(data), loc)
            dec_key = 'dir_dec'
            inc_key = 'dir_inc'
            int_key = 'int_abs'
            SiteDIs = pmag.get_dictitem(data, dec_key, "", 'F')  # find decs
            SiteDIs = pmag.get_dictitem(
                SiteDIs, inc_key, "", 'F')  # find decs and incs
            dir_data_found = len(SiteDIs)
            print('{} Dec/inc pairs found'.format(dir_data_found))
            if SiteDIs:
                # then convert tilt_corr_key to correct format
                old_SiteDIs = SiteDIs
                SiteDIs = []
                for rec in old_SiteDIs:
                    if tilt_corr_key not in rec:
                        rec[tilt_corr_key] = "0"
                    # make sure tilt_corr_key is a correct format
                    try:
                        rec[tilt_corr_key] = str(int(float(rec[tilt_corr_key])))
                    except ValueError:
                        rec[tilt_corr_key] = "0"
                    SiteDIs.append(rec)

                print('number of individual directions: ', len(SiteDIs))
                # tilt corrected coordinates
                SiteDIs_t = pmag.get_dictitem(SiteDIs, tilt_corr_key, '100',
                                              'T', float_to_int=True)
                print('number of tilt corrected directions: ', len(SiteDIs_t))
                SiteDIs_g = pmag.get_dictitem(
                    SiteDIs, tilt_corr_key, '0', 'T', float_to_int=True)  # geographic coordinates
                print('number of geographic  directions: ', len(SiteDIs_g))
                SiteDIs_s = pmag.get_dictitem(
                    SiteDIs, tilt_corr_key, '-1', 'T', float_to_int=True)  # sample coordinates
                print('number of sample  directions: ', len(SiteDIs_s))
                SiteDIs_x = pmag.get_dictitem(
                    SiteDIs, tilt_corr_key, '', 'T')  # no coordinates
                print('number of no coordinates  directions: ', len(SiteDIs_x))
                if len(SiteDIs_t) > 0 or len(SiteDIs_g) > 0 or len(SiteDIs_s) > 0 or len(SiteDIs_x) > 0:
                    CRD = ""
                    if len(SiteDIs_t) > 0:
                        CRD = ' -crd t'
                    elif len(SiteDIs_g) > 0:
                        CRD = ' -crd g'
                    elif len(SiteDIs_s) > 0:
                        CRD = ' -crd s'
                    CMD = 'eqarea_magic.py -f tmp_sites.txt -fsp tmp_specimens.txt -fsa tmp_samples.txt -flo tmp_locations.txt -sav -fmt ' + fmt + CRD
                    print(CMD)
                    info_log(CMD, loc)
                    os.system(CMD)
                else:
                    if dir_data_found:
                        error_log('{} dec/inc pairs found, but no equal area plots were made'.format(dir_data_found), loc, "equarea_magic.py", con_id=con_id)
            #
            print('-I- working on VGP map')
            VGPs = pmag.get_dictitem(
                SiteDIs, 'vgp_lat', "", 'F')  # are there any VGPs?
            if len(VGPs) > 0:  # YES!
                CMD = 'vgpmap_magic.py -f tmp_sites.txt -prj moll -res c -sym ro 5 -sav -fmt png'
                print(CMD)
                info_log(CMD, loc, 'vgpmap_magic.py')
                os.system(CMD)
            else:
                print('-I- No vgps found')

            print('-I- Look for intensities')
            # is there any intensity data?
            if site_data:
                if int_key in site_data[0].keys():
                    # old way, wasn't working right:
                    #CMD = 'magic_select.py  -key ' + int_key + ' 0. has -F tmp1.txt -f tmp_sites.txt'
                    Selection = pmag.get_dictkey(site_data, int_key, dtype="f")
                    with open('intensities.txt', 'w') as out:
                        for rec in Selection:
                            if rec != 0:
                                out.write(str(rec * 1e6) + "\n")

                    loc = loc.replace(" ", "_")
                    if loc == "./":
                        loc_name = ""
                    else:
                        loc_name = loc
                    histfile = 'LO:_' + loc_name + \
                        '_TY:_intensities_histogram:_.' + fmt
                    # maybe run histplot.main here instead, so you can return an error message
                    CMD = "histplot.py -twin -b 1 -xlab 'Intensity (uT)' -sav -f intensities.txt -F " + histfile
                    os.system(CMD)
                    info_log(CMD, loc)
                    print(CMD)
                else:
                    print('-I- No intensities found')
            else:
                print('-I- No intensities found')

        ##
        if hyst_file in filelist and spec_data:
            print('working on hysteresis', hyst_file)
            data = spec_data
            file_type = 'specimens'
            hdata = pmag.get_dictitem(data, hyst_bcr_key, '', 'F')
            hdata = pmag.get_dictitem(hdata, hyst_mr_key, '', 'F')
            hdata = pmag.get_dictitem(hdata, hyst_ms_key, '', 'F')
            # there are data for a dayplot
            hdata = pmag.get_dictitem(hdata, hyst_bc_key, '', 'F')
            if len(hdata) > 0:
                CMD = 'dayplot_magic.py -f tmp_specimens.txt -sav -fmt ' + fmt
                info_log(CMD, loc)
                print(CMD)
            else:
                print('no hysteresis data found')
        if aniso_file in filelist and spec_data:  # do anisotropy plots if possible
            print('working on anisotropy', aniso_file)
            data = spec_data
            file_type = 'specimens'

            # make sure there is some anisotropy data
            if not data:
                print('No anisotropy data found')
            elif 'aniso_s' not in data[0]:
                print('No anisotropy data found')
            else:
                # get specimen coordinates
                if aniso_tilt_corr_key not in data[0]:
                    sdata = data
                else:
                    sdata = pmag.get_dictitem(
                        data, aniso_tilt_corr_key, '-1', 'T', float_to_int=True)
                # get specimen coordinates
                gdata = pmag.get_dictitem(
                    data, aniso_tilt_corr_key, '0', 'T', float_to_int=True)
                # get specimen coordinates
                tdata = pmag.get_dictitem(
                    data, aniso_tilt_corr_key, '100', 'T', float_to_int=True)
                CRD = ""
                CMD = 'aniso_magic.py -x -B -sav -fmt ' + fmt + " -new"
                if len(sdata) > 3:
                    CMD = CMD + ' -crd s'
                    print(CMD)
                    info_log(CMD, loc)
                    os.system(CMD)
                if len(gdata) > 3:
                    CMD = CMD + ' -crd g'
                    print(CMD)
                    info_log(CMD, loc)
                    os.system(CMD)
                if len(tdata) > 3:
                    CMD = CMD + ' -crd t'
                    print(CMD)
                    info_log(CMD, loc)
                    os.system(CMD)
        # remove temporary files
        for fname in glob.glob('tmp*.txt'):
            os.remove(fname)
        try:
            os.remove('intensities.txt')
        except FileNotFoundError:
            pass
    if loc_file in filelist and loc_data:
        #data, file_type = pmag.magic_read(loc_file)  # read in location data
        data = loc_data
        print('-I- working on pole map')
        poles = pmag.get_dictitem(
            data, 'pole_lat', "", 'F')  # are there any poles?
        poles = pmag.get_dictitem(
            poles, 'pole_lon', "", 'F')  # are there any poles?
        if len(poles) > 0:  # YES!
            CMD = 'polemap_magic.py -sav -fmt png -rev gv 40'
            print(CMD)
            info_log(CMD, "all locations", "polemap_magic.py")
            os.system(CMD)
        else:
            print('-I- No poles found')
    thumbnails.make_thumbnails(dir_path)

Response: This function is the main function for the make_magic_plots. py script. It will take the magic directory and make plots and returns a dictionary of all the available data.


Instruction:
Create a Python 3 function for
naming core_depthplot.py DESCRIPTION plots various measurements versus core_depth or age. plots data flagged as 'FS-SS-C' as discrete samples. SYNTAX core_depthplot.py [command line options] # or, for Anaconda users: core_depthplot_anaconda [command line options] OPTIONS -h prints help message and quits -f FILE: specify input measurments format file -fsum FILE: specify input LIMS database (IODP) core summary csv file -fwig FILE: specify input depth,wiggle to plot, in magic format with sample_core_depth key for depth -fsa FILE: specify input er_samples format file from magic for depth -fa FILE: specify input ages format file from magic for age NB: must have either -fsa OR -fa (not both) -fsp FILE sym size: specify input zeq_specimen format file from magic, sym and size NB: PCAs will have specified color, while fisher means will be white with specified color as the edgecolor -fres FILE specify input pmag_results file from magic, sym and size -LP [AF,T,ARM,IRM, X] step [in mT,C,mT,mT, mass/vol] to plot -S do not plot blanket treatment data (if this is set, you don't need the -LP) -sym SYM SIZE, symbol, size for continuous points (e.g., ro 5, bs 10, g^ 10 for red dot, blue square, green triangle), default is blue dot at 5 pt -D do not plot declination -M do not plot magnetization -log plot magnetization on a log scale -L do not connect dots with a line -I do not plot inclination -d min max [in m] depth range to plot -n normalize by weight in er_specimen table -Iex: plot the expected inc at lat - only available for results with lat info in file -ts TS amin amax: plot the GPTS for the time interval between amin and amax (numbers in Ma) TS: [ck95, gts04, gts12] -ds [mbsf,mcd] specify depth scale, mbsf default -fmt [svg, eps, pdf, png] specify output format for plot (default: svg) -sav save plot silently DEFAULTS: Measurements file: measurements.txt Samples file: samples.txt NRM step Summary file: none

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

    DESCRIPTION
        plots various measurements versus core_depth or age.  plots data flagged as 'FS-SS-C' as discrete samples.

    SYNTAX
        core_depthplot.py [command line options]
        # or, for Anaconda users:
        core_depthplot_anaconda [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input measurments format file
        -fsum FILE: specify input LIMS database (IODP) core summary csv file
        -fwig FILE: specify input depth,wiggle to plot, in magic format with sample_core_depth key for depth
        -fsa FILE: specify input er_samples format file from magic for depth
        -fa FILE: specify input ages format file from magic for age
              NB: must have either -fsa OR -fa (not both)
        -fsp FILE sym size: specify input zeq_specimen format file from magic, sym and size
              NB: PCAs will have specified color, while fisher means will be white with specified color as the edgecolor
        -fres FILE specify input pmag_results file from magic, sym and size
        -LP [AF,T,ARM,IRM, X] step [in mT,C,mT,mT, mass/vol] to plot
        -S do not plot blanket treatment data (if this is set, you don't need the -LP)
        -sym SYM SIZE, symbol, size for continuous points (e.g., ro 5, bs 10, g^ 10 for red dot, blue square, green triangle), default is blue dot at 5 pt
        -D do not plot declination
        -M do not plot magnetization
        -log  plot magnetization  on a log scale
        -L do not connect dots with a line
        -I do not plot inclination
        -d min max [in m] depth range to plot
        -n normalize by weight in er_specimen table
        -Iex: plot the expected inc at lat - only available for results with lat info in file
        -ts TS amin amax: plot the GPTS for the time interval between amin and amax (numbers in Ma)
           TS: [ck95, gts04, gts12]
        -ds [mbsf,mcd] specify depth scale, mbsf default
        -fmt [svg, eps, pdf, png] specify output format for plot (default: svg)
        -sav save plot silently

     DEFAULTS:
         Measurements file: measurements.txt
         Samples file: samples.txt
         NRM step
         Summary file: none
    """

    args = sys.argv
    if '-h' in args:
        print(main.__doc__)
        sys.exit()

    dataframe = extractor.command_line_dataframe([ ['f', False, 'measurements.txt'], ['fsum', False, ''],
                                                   ['fwig', False, ''], ['fsa', False, ''],
                                                   ['fa', False, ''], ['fsp', False, ''],
                                                   ['fres', False, '' ],  ['fmt', False, 'svg'],
                                                   ['LP', False,  ''], ['n', False, False],
                                                   ['d', False, '-1 -1'], ['ts', False, ''],
                                                   ['WD', False, '.'], ['L', False, True],
                                                   ['S', False, True], ['D', False, True],
                                                   ['I', False, True], ['M', False, True],
                                                   ['log', False,  0],
                                                   ['ds', False, 'sample_core_depth'],
                                                   ['sym', False, 'bo 5'], ['ID', False, '.'],
                                                   ['sav', False, False], ['DM', False, 3]])

    checked_args = extractor.extract_and_check_args(args, dataframe)
    meas_file, sum_file, wig_file, samp_file, age_file, spc_file, res_file, fmt, meth, norm, depth, timescale, dir_path, pltLine, pltSus, pltDec, pltInc, pltMag, logit, depth_scale, symbol, input_dir, save, data_model_num = extractor.get_vars(
        ['f', 'fsum', 'fwig', 'fsa', 'fa', 'fsp', 'fres', 'fmt',  'LP', 'n', 'd', 'ts', 'WD', 'L', 'S', 'D', 'I', 'M', 'log', 'ds', 'sym', 'ID', 'sav', 'DM'], checked_args)

    # format some variables
    # format symbol/size
    try:
        sym, size = symbol.split()
        size = int(size)
    except:
        print('you should provide -sym in this format: ro 5')
        print('using defaults instead')
        sym, size = 'ro', 5

    # format result file, symbol, size
    if res_file:
        try:
            res_file, res_sym, res_size = res_file.split()
        except:
            print('you must provide -fres in this format: -fres filename symbol size')
            print(
                'could not parse {}, defaulting to using no result file'.format(res_file))
            res_file, res_sym, res_size = '', '', 0
    else:
        res_file, res_sym, res_size = '', '', 0

    # format specimen file, symbol, size
    if spc_file:
        try:
            spc_file, spc_sym, spc_size = spc_file.split()
        except:
            print('you must provide -fsp in this format: -fsp filename symbol size')
            print(
                'could not parse {}, defaulting to using no specimen file'.format(spc_file))
            spc_file, spc_sym, spc_size = '', '', 0
    else:
        spc_file, spc_sym, spc_size = '', '', 0

    # format min/max depth
    try:
        dmin, dmax = depth.split()
    except:
        print('you must provide -d in this format: -d dmin dmax')
        print('could not parse {}, defaulting to plotting all depths'.format(depth))
        dmin, dmax = -1, -1

    # format timescale, min/max time
    if timescale:
        try:
            timescale, amin, amax = timescale.split()
            pltTime = True
        except:
            print(
                'you must provide -ts in this format: -ts timescale minimum_age maximum_age')
            print(
                'could not parse {}, defaulting to using no timescale'.format(timescale))
            timescale, amin, amax = None, -1, -1
            pltTime = False
    else:
        timescale, amin, amax = None, -1, -1
        pltTime = False

    # format norm and wt_file
    if norm and not isinstance(norm, bool):
        wt_file = norm
        norm = True
    else:
        norm = False
        wt_file = ''

    # format list of protcols and step
    try:
        method, step = meth.split()
    except:
        print(
            'To use the -LP flag you must provide both the protocol and the step in this format:\n-LP [AF,T,ARM,IRM, X] step [in mT,C,mT,mT, mass/vol] to plot')
        print('Defaulting to using no protocol')
        method, step = 'LT-NO', 0

    # list of varnames
    #['f', 'fsum', 'fwig', 'fsa', 'fa', 'fsp', 'fres', 'fmt',  'LP', 'n', 'd', 'ts', 'WD', 'L', 'S', 'D', 'I', 'M', 'log', 'ds', 'sym' ]
    #meas_file, sum_file, wig_file, samp_file, age_file, spc_file, res_file, fmt, meth, norm, depth, timescale, dir_path, pltLine, pltSus, pltDec, pltInc, pltMag, logit, depth_scale, symbol

    fig, figname = ipmag.core_depthplot(input_dir, meas_file, spc_file, samp_file, age_file, sum_file, wt_file, depth_scale, dmin, dmax, sym, size,
                                        spc_sym, spc_size, method, step, fmt, pltDec, pltInc, pltMag, pltLine, pltSus, logit, pltTime, timescale, amin, amax, norm, data_model_num)

    if not pmagplotlib.isServer:
        figname = figname.replace(':', '_')

    if fig and save:
        print('-I- Created plot: {}'.format(figname))
        plt.savefig(figname)
        return

    app = wx.App(redirect=False)
    if not fig:
        pw.simple_warning(
            'No plot was able to be created with the data you provided.\nMake sure you have given all the required information and try again')
        return False

    dpi = fig.get_dpi()
    pixel_width = dpi * fig.get_figwidth()
    pixel_height = dpi * fig.get_figheight()
    figname = os.path.join(dir_path, figname)
    plot_frame = pmag_menu_dialogs.PlotFrame((int(pixel_width), int(pixel_height + 50)),
                                             fig, figname, standalone=True)

    app.MainLoop()