Instruction:
Write a Python 3 function that can
set value of selected cell to value selected from menuitem

Response:
def on_select_menuitem(self, event, grid, row, col, selection):
        """
        sets value of selected cell to value selected from menu
        """
        if self.grid.changes:  # if user selects a menuitem, that is an edit
            self.grid.changes.add(row)
        else:
            self.grid.changes = {row}

        item_id = event.GetId()
        item = event.EventObject.FindItemById(item_id)
        label = item.Label
        cell_value = grid.GetCellValue(row, col)
        if str(label) == "CLEAR cell of all values":
            label = ""

        col_label = grid.GetColLabelValue(col).strip('\nEDIT ALL').strip('**')
        if col_label in self.colon_delimited_lst and label:
            if not label.lower() in cell_value.lower():
                label += (":" + cell_value).rstrip(':')
            else:
                label = cell_value

        if self.selected_col and self.selected_col == col:
            for row in range(self.grid.GetNumberRows()):
                grid.SetCellValue(row, col, label)
                if self.grid.changes:
                    self.grid.changes.add(row)
                else:
                    self.grid.changes = {row}

                #self.selected_col = None
        else:
            grid.SetCellValue(row, col, label)

        if selection:
            for cell in selection:
                row = cell[0]
                grid.SetCellValue(row, col, label)
            return


Instruction:
Can you implement a function in Python 3 that
names plot_cdf.py DESCRIPTION makes plots of cdfs of data in input file SYNTAX plot_cdf.py [-h][command line options] OPTIONS -h prints help message and quits -f FILE -t TITLE -fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is svg -sav saves plot and quits

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

    DESCRIPTION
        makes plots of cdfs of data in input file

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

    OPTIONS
        -h prints help message and quits
        -f FILE
        -t TITLE
        -fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is svg
        -sav saves plot and quits

    """
    fmt,plot='svg',0
    title=""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-sav' in sys.argv:plot=1
    if '-f' in sys.argv:
       ind=sys.argv.index('-f')
       file=sys.argv[ind+1]
       X=numpy.loadtxt(file)
#    else:
#       X=numpy.loadtxt(sys.stdin,dtype=numpy.float)
    else:
       print('-f option required')
       print(main.__doc__)
       sys.exit()
    if '-fmt' in sys.argv:
       ind=sys.argv.index('-fmt')
       fmt=sys.argv[ind+1]
    if '-t' in sys.argv:
       ind=sys.argv.index('-t')
       title=sys.argv[ind+1]
    CDF={'X':1}
    pmagplotlib.plot_init(CDF['X'],5,5)
    pmagplotlib.plot_cdf(CDF['X'],X,title,'r','')
    files={'X':'CDF_.'+fmt}
    if plot==0:
        pmagplotlib.draw_figs(CDF)
        ans= input('S[a]ve  plot, <Return> to quit ')
        if ans=='a':
            pmagplotlib.save_plots(CDF,files)
    else:
        pmagplotlib.save_plots(CDF,files)


Instruction:
Implement a Python 3 function for
naming npar - npar - npar - npar - nnpar - nnpar - n

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

    DESCRIPTION
      calculates bootstrap statistics for tensor data

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

    OPTIONS:
        -h prints help message and quits
        -f FILE specifies input file name
        -par specifies parametric bootstrap [by whole data set]
        -n N  specifies the number of bootstrap samples, default is N=1000

    INPUT
         x11 x22 x33 x12 x23 x13

    OUTPUT
     tau_1 tau_1_sigma V1_dec V1_inc V1_eta V1_eta_dec V1_eta_inc V1_zeta V1_zeta_dec V1_zeta_inc
     tau_2 tau_2_sigma V2_dec V2_inc V2_eta V2_eta_dec V2_eta_inc V2_zeta V2_zeta_dec V2_zeta_inc
     tau_3 tau_2_sigma V3_dec V3_inc V3_eta V3_eta_dec V3_eta_inc V3_zeta V3_zeta_dec V3_zeta_inc
    """
# set options
    ipar,nb=0,5000
    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]
        Ss=np.loadtxt(file)
        #f=open(file,'r')
        #data=f.readlines()
    if '-par' in sys.argv:ipar=1
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        nb=int(sys.argv[ind+1])
# read in the data
    print("Doing bootstrap - be patient")
    #Ss=[]
    #for line in data:
    #    s=[]
    #    rec=line.split()
    #    for i in range(6):
    #        s.append(float(rec[i]))
    #    Ss.append(s)
    Tmean,Vmean,Taus,Vs=pmag.s_boot(Ss,ipar=ipar,nb=nb)
    bpars=pmag.sbootpars(Taus,Vs) # calculate kent parameters for bootstrap
    bpars["v1_dec"]=Vmean[0][0]
    bpars["v1_inc"]=Vmean[0][1]
    bpars["v2_dec"]=Vmean[1][0]
    bpars["v2_inc"]=Vmean[1][1]
    bpars["v3_dec"]=Vmean[2][0]
    bpars["v3_inc"]=Vmean[2][1]
    bpars["t1"]=Tmean[0]
    bpars["t2"]=Tmean[1]
    bpars["t3"]=Tmean[2]
    print("""
tau tau_sigma V_dec V_inc V_eta V_eta_dec V_eta_inc V_zeta V_zeta_dec V_zeta_inc
""")
    outstring='%7.5f %7.5f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f'%(bpars["t1"],bpars["t1_sigma"],bpars["v1_dec"],bpars["v1_inc"],bpars["v1_zeta"],bpars["v1_zeta_dec"],bpars["v1_zeta_inc"],bpars["v1_eta"],bpars["v1_eta_dec"],bpars["v1_eta_inc"])
    print(outstring)
    outstring='%7.5f %7.5f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f'%(bpars["t2"],bpars["t2_sigma"],bpars["v2_dec"],bpars["v2_inc"],bpars["v2_zeta"],bpars["v2_zeta_dec"],bpars["v2_zeta_inc"],bpars["v2_eta"],bpars["v2_eta_dec"],bpars["v2_eta_inc"])
    print(outstring)
    outstring='%7.5f %7.5f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f'%(bpars["t3"],bpars["t3_sigma"],bpars["v3_dec"],bpars["v3_inc"],bpars["v3_zeta"],bpars["v3_zeta_dec"],bpars["v3_zeta_inc"],bpars["v3_eta"],bpars["v3_eta_dec"],bpars["v3_eta_inc"])
    print(outstring)


Instruction:
Here you have a function in Python 3, explain what it does
def get_json_online(self, url):
        if not requests:
            return False
        try:
            req = requests.get(url, timeout=.2)
            if not req.ok:
                return []
            return req
        except (requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError,
                requests.exceptions.ReadTimeout):
            return []

Response: Get json from url.


Instruction:
Write a Python 3 script for
getting a tiered list of all er and pmag_age codes for a given method type

Response:
def get_tiered_meth_category(self, mtype, all_codes, code_types):
        """
        Get a tiered list of all er/pmag_age codes
        i.e. pmag_codes = {'anisotropy_codes': ['code1', 'code2'],
        'sample_preparation': [code1, code2], ...}
        """
        categories = Series(code_types[code_types[mtype] == True].index)
        codes = {cat: list(self.get_one_meth_type(cat, all_codes).index) for cat in categories}
        return codes


Instruction:
Can you generate the documentation for the following Python 3 function
def get_controlled_vocabularies(self, vocab_types=default_vocab_types):
        if len(VOCAB):
            self.set_vocabularies()
            return
        data = []
        controlled_vocabularies = []
        # try to get online
        if not set_env.OFFLINE:
            url = 'https://www2.earthref.org/vocabularies/controlled.json'
            try:
                raw = self.get_json_online(url)
                data = pd.DataFrame(raw.json())
                print('-I- Importing controlled vocabularies from https://earthref.org')
            except Exception as ex:
                pass
                #print(ex, type(ex))
        # used cached
        if not len(data):
            print('-I- Using cached vocabularies')
            fname = os.path.join(data_model_dir, "controlled_vocabularies_December_10_2018.json")
            data = pd.io.json.read_json(fname, encoding='utf-8-sig')
        # parse data
        possible_vocabularies = data.columns
        ## this line means, grab every single controlled vocabulary
        vocab_types = list(possible_vocabularies)

        def get_cv_from_list(lst):
            """
            Check a validations list from the data model.
            If there is a controlled vocabulary validation,
            return which category of controlled vocabulary it is.
            This will generally be applied to the validations col
            of the data model
            """
            try:
                for i in lst:
                    if "cv(" in i:
                        return i[4:-2]
            except TypeError:
                return None
            else:
                return None

        vocab_col_names = []
        data_model = self.data_model
        for dm_key in data_model.dm:
            df = data_model.dm[dm_key]
            df['vocab_name'] = df['validations'].apply(get_cv_from_list)
            lst = list(zip(df[df['vocab_name'].notnull()]['vocab_name'], df[df['vocab_name'].notnull()].index))
            # in lst, first value is the name of the controlled vocabulary
            # second value is the name of the dataframe column
            vocab_col_names.extend(lst)

        # vocab_col_names is now a list of tuples
        # consisting of the vocabulary name and the column name
        # i.e., (u'type', u'geologic_types')

        # remove duplicate col_names:
        vocab_col_names = sorted(set(vocab_col_names))

        # add in boolean category to controlled vocabularies
        bool_items = [{'item': True}, {'item': False}, {'item': 'true'},
                      {'item': 'false'}, {'item': 0}, {'item': 1},
                      {'item': 0.0}, {'item': 1.0},
                      {'item': 't'}, {'item': 'f'},
                      {'item': 'T'}, {'item': 'F'}]
        series = Series({'label': 'Boolean', 'items': bool_items})
        data['boolean'] = series
        # use vocabulary name to get possible values for the column name
        for vocab in vocab_col_names[:]:
            if vocab[0] == "magic_table_column":
                vocab_col_names.remove(("magic_table_column", "table_column"))
                continue
            items = data[vocab[0]]['items']
            stripped_list = [item['item'] for item in items]
            controlled_vocabularies.append(stripped_list)
        # create series with the column name as the index,
        # and the possible values as the values
        ind_values = [i[1] for i in vocab_col_names]
        vocabularies = pd.Series(controlled_vocabularies, index=ind_values)
        return vocabularies

Response: Get all controlled vocabularies from Earthref 10. 2018


Instruction:
Can you tell what is the following Python 3 function doing
def main():

    #==================================================================================

    meas_file="magic_measurements.txt"
    args=sys.argv
    dir_path='.'
    #
    # get name of file from command line
    #
    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")
        meas_file=sys.argv[ind+1]
    else:
        meas_file=dir_path+'/'+meas_file
    WD=dir_path

    #======================================
    # functions
    #======================================

    def get_Data(magic_file):

        #------------------------------------------------
        # Read magic measurement file and sort to blocks
        #------------------------------------------------
        Data={}
        try:
            meas_data,file_type=pmag.magic_read(magic_file)
        except:
            print("-E- ERROR: Cant read magic_measurement.txt file. File is corrupted.")
            return Data

        # get list of unique specimen names

        #sids=pmag.get_specs(meas_data) # samples ID's

        for rec in meas_data:
            s=rec["er_specimen_name"]
            method_codes= rec["magic_method_codes"].strip('\n')
            method_codes.replace(" ","")
            methods=method_codes.split(":")
            if "LP-AN-TRM" in methods:
                if s not in list(Data.keys()):
                    Data[s]={}
                if 'atrmblock' not in list(Data[s].keys()):
                    Data[s]['atrmblock']=[]
                Data[s]['atrmblock'].append(rec)

            if "LP-AN-ARM" in methods:
                if s not in list(Data.keys()):
                    Data[s]={}
                if 'aarmblock' not in list(Data[s].keys()):
                    Data[s]['aarmblock']=[]
                Data[s]['aarmblock'].append(rec)
        return (Data)

    #======================================
    # better to put this one in pmagpy
    #======================================

    def calculate_aniso_parameters(B,K):

        aniso_parameters={}
        S_bs=dot(B,K)

        # normalize by trace
        trace=S_bs[0]+S_bs[1]+S_bs[2]
        S_bs=old_div(S_bs,trace)
        s1,s2,s3,s4,s5,s6=S_bs[0],S_bs[1],S_bs[2],S_bs[3],S_bs[4],S_bs[5]
        s_matrix=[[s1,s4,s6],[s4,s2,s5],[s6,s5,s3]]

        # calculate eigen vector,
        t,evectors=eig(s_matrix)
        # sort vectors
        t=list(t)
        t1=max(t)
        ix_1=t.index(t1)
        t3=min(t)
        ix_3=t.index(t3)
        for tt in range(3):
            if t[tt]!=t1 and t[tt]!=t3:
                t2=t[tt]
                ix_2=t.index(t2)

        v1=[evectors[0][ix_1],evectors[1][ix_1],evectors[2][ix_1]]
        v2=[evectors[0][ix_2],evectors[1][ix_2],evectors[2][ix_2]]
        v3=[evectors[0][ix_3],evectors[1][ix_3],evectors[2][ix_3]]

        DIR_v1=pmag.cart2dir(v1)
        DIR_v2=pmag.cart2dir(v2)
        DIR_v3=pmag.cart2dir(v3)

        aniso_parameters['anisotropy_s1']="%f"%s1
        aniso_parameters['anisotropy_s2']="%f"%s2
        aniso_parameters['anisotropy_s3']="%f"%s3
        aniso_parameters['anisotropy_s4']="%f"%s4
        aniso_parameters['anisotropy_s5']="%f"%s5
        aniso_parameters['anisotropy_s6']="%f"%s6
        aniso_parameters['anisotropy_degree']="%f"%(old_div(t1,t3))
        aniso_parameters['anisotropy_t1']="%f"%t1
        aniso_parameters['anisotropy_t2']="%f"%t2
        aniso_parameters['anisotropy_t3']="%f"%t3
        aniso_parameters['anisotropy_v1_dec']="%.1f"%DIR_v1[0]
        aniso_parameters['anisotropy_v1_inc']="%.1f"%DIR_v1[1]
        aniso_parameters['anisotropy_v2_dec']="%.1f"%DIR_v2[0]
        aniso_parameters['anisotropy_v2_inc']="%.1f"%DIR_v2[1]
        aniso_parameters['anisotropy_v3_dec']="%.1f"%DIR_v3[0]
        aniso_parameters['anisotropy_v3_inc']="%.1f"%DIR_v3[1]

        # modified from pmagpy:
        if old_div(len(K),3)==9 or old_div(len(K),3)==6 or old_div(len(K),3)==15:
            n_pos=old_div(len(K),3)
            tmpH = Matrices[n_pos]['tmpH']
            a=s_matrix
            S=0.
            comp=zeros((n_pos*3),'f')
            for i in range(n_pos):
                for j in range(3):
                    index=i*3+j
                    compare=a[j][0]*tmpH[i][0]+a[j][1]*tmpH[i][1]+a[j][2]*tmpH[i][2]
                    comp[index]=compare
            for i in range(n_pos*3):
                d=old_div(K[i],trace) - comp[i] # del values
                S+=d*d
            nf=float(n_pos*3-6) # number of degrees of freedom
            if S >0:
                sigma=math.sqrt(old_div(S,nf))
            hpars=pmag.dohext(nf,sigma,[s1,s2,s3,s4,s5,s6])

            aniso_parameters['anisotropy_sigma']="%f"%sigma
            aniso_parameters['anisotropy_ftest']="%f"%hpars["F"]
            aniso_parameters['anisotropy_ftest12']="%f"%hpars["F12"]
            aniso_parameters['anisotropy_ftest23']="%f"%hpars["F23"]
            aniso_parameters['result_description']="Critical F: %s"%(hpars['F_crit'])
            aniso_parameters['anisotropy_F_crit']="%f"%float(hpars['F_crit'])
            aniso_parameters['anisotropy_n']=n_pos

        return(aniso_parameters)

    #======================================
    # Main
    #======================================

    aniso_logfile=open(WD+"/rmag_anisotropy.log",'w')
    aniso_logfile.write("------------------------\n")
    aniso_logfile.write( "-I- Start rmag anisrotropy script\n")
    aniso_logfile.write( "------------------------\n")

    Data=get_Data(meas_file)
    #try:
    #    Data=get_Data(meas_file)
    #except:
    #    aniso_logfile.write( "-E- Cant open measurement file %s\n" %meas_file)
    #    print "-E- Cant open measurement file %s\n exiting" %meas_file
    #    exit()

    aniso_logfile.write( "-I-  Open measurement file %s\n" %meas_file)

    Data_anisotropy={}
    specimens=list(Data.keys())
    specimens.sort()

    #-----------------------------------
    # Prepare rmag_anisotropy.txt file for writing
    #-----------------------------------

    rmag_anisotropy_file =open(WD+"/rmag_anisotropy.txt",'w')
    rmag_anisotropy_file.write("tab\trmag_anisotropy\n")

    rmag_results_file =open(WD+"/rmag_results.txt",'w')
    rmag_results_file.write("tab\trmag_results\n")

    rmag_anistropy_header=['er_specimen_name','er_sample_name','er_site_name','anisotropy_type','anisotropy_n','anisotropy_description','anisotropy_s1','anisotropy_s2','anisotropy_s3','anisotropy_s4','anisotropy_s5','anisotropy_s6','anisotropy_sigma','anisotropy_alt','magic_experiment_names','magic_method_codes']

    String=""
    for i in range (len(rmag_anistropy_header)):
        String=String+rmag_anistropy_header[i]+'\t'
    rmag_anisotropy_file.write(String[:-1]+"\n")

    rmag_results_header=['er_specimen_names','er_sample_names','er_site_names','anisotropy_type','magic_method_codes','magic_experiment_names','result_description','anisotropy_t1','anisotropy_t2','anisotropy_t3','anisotropy_ftest','anisotropy_ftest12','anisotropy_ftest23',\
                            'anisotropy_v1_dec','anisotropy_v1_inc','anisotropy_v2_dec','anisotropy_v2_inc','anisotropy_v3_dec','anisotropy_v3_inc']

    String=""
    for i in range (len(rmag_results_header)):
        String=String+rmag_results_header[i]+'\t'
    rmag_results_file.write(String[:-1]+"\n")

    #-----------------------------------
    # Matrices definitions:
    # A design matrix
    # B dot(inv(dot(A.transpose(),A)),A.transpose())
    # tmpH is used for sigma calculation (9,15 measurements only)
    #
    #  Anisotropy tensor:
    #
    # |Mx|   |s1 s4 s6|   |Bx|
    # |My| = |s4 s2 s5| . |By|
    # |Mz|   |s6 s5 s3|   |Bz|
    #
    # A matrix (measurement matrix):
    # Each mesurement yields three lines in "A" matrix
    #
    # |Mi  |   |Bx 0  0   By  0   Bz|   |s1|
    # |Mi+1| = |0  By 0   Bx  Bz  0 | . |s2|
    # |Mi+2|   |0  0  Bz  0   By  Bx|   |s3|
    #                                   |s4|
    #                                   |s5|
    #
    #-----------------------------------

    Matrices={}

    for n_pos in [6,9,15]:

        Matrices[n_pos]={}

        A=zeros((n_pos*3,6),'f')

        if n_pos==6:
            positions=[[0.,0.,1.],[90.,0.,1.],[0.,90.,1.],\
                    [180.,0.,1.],[270.,0.,1.],[0.,-90.,1.]]

        if n_pos==15:
            positions=[[315.,0.,1.],[225.,0.,1.],[180.,0.,1.],[135.,0.,1.],[45.,0.,1.],\
                    [90.,-45.,1.],[270.,-45.,1.],[270.,0.,1.],[270.,45.,1.],[90.,45.,1.],\
                    [180.,45.,1.],[180.,-45.,1.],[0.,-90.,1.],[0,-45.,1.],[0,45.,1.]]
        if n_pos==9:
            positions=[[315.,0.,1.],[225.,0.,1.],[180.,0.,1.],\
                    [90.,-45.,1.],[270.,-45.,1.],[270.,0.,1.],\
                    [180.,45.,1.],[180.,-45.,1.],[0.,-90.,1.]]

        tmpH=zeros((n_pos,3),'f') # define tmpH
        for i in range(len(positions)):
            CART=pmag.dir2cart(positions[i])
            a=CART[0];b=CART[1];c=CART[2]
            A[3*i][0]=a
            A[3*i][3]=b
            A[3*i][5]=c

            A[3*i+1][1]=b
            A[3*i+1][3]=a
            A[3*i+1][4]=c

            A[3*i+2][2]=c
            A[3*i+2][4]=b
            A[3*i+2][5]=a

            tmpH[i][0]=CART[0]
            tmpH[i][1]=CART[1]
            tmpH[i][2]=CART[2]

        B=dot(inv(dot(A.transpose(),A)),A.transpose())

        Matrices[n_pos]['A']=A
        Matrices[n_pos]['B']=B
        Matrices[n_pos]['tmpH']=tmpH

    for specimen in specimens:

        if 'atrmblock' in list(Data[specimen].keys()):

            #-----------------------------------
            # aTRM 6 positions
            #-----------------------------------

            aniso_logfile.write("-I- Start calculating ATRM tensor for specimen %s\n "%specimen)
            atrmblock=Data[specimen]['atrmblock']
            if len(atrmblock)<6:
                aniso_logfile.write("-W- specimen %s has not enough measurementf for ATRM calculation\n"%specimen)
                continue

            B=Matrices[6]['B']

            Reject_specimen = False

            # The zero field step is a "baseline"

            # Search the baseline in the ATRM measurement

            baseline=""
            Alteration_check=""
            Alteration_check_index=""
            baselines=[]

            # search for baseline in atrm blocks
            for rec in atrmblock:
                dec=float(rec['measurement_dec'])
                inc=float(rec['measurement_inc'])
                moment=float(rec['measurement_magn_moment'])
                # find the temperature of the atrm
                if float(rec['treatment_dc_field'])!=0 and float(rec['treatment_temp'])!=273:
                    atrm_temperature=float(rec['treatment_temp'])
                # find baseline
                if float(rec['treatment_dc_field'])==0 and float(rec['treatment_temp'])!=273:
                    baselines.append(array(pmag.dir2cart([dec,inc,moment])))
                # Find alteration check
                #print rec['measurement_number']

            if len(baselines)!=0:
                aniso_logfile.write( "-I- found ATRM baseline for specimen %s\n"%specimen)
                baselines=array(baselines)
                baseline=array([mean(baselines[:,0]),mean(baselines[:,1]),mean(baselines[:,2])])

            else:
                baseline=zeros(3,'f')
                aniso_logfile.write( "-I- No aTRM baseline for specimen %s\n"%specimen)

            # sort measurements

            M=zeros([6,3],'f')

            for rec in atrmblock:

                dec=float(rec['measurement_dec'])
                inc=float(rec['measurement_inc'])
                moment=float(rec['measurement_magn_moment'])
                CART=array(pmag.dir2cart([dec,inc,moment]))-baseline

                if float(rec['treatment_dc_field'])==0: # Ignore zero field steps
                    continue
                if  "LT-PTRM-I" in rec['magic_method_codes'].split(":"): #  alteration check
                    Alteration_check=CART
                    Alteration_check_dc_field_phi=float(rec['treatment_dc_field_phi'])
                    Alteration_check_dc_field_theta=float(rec['treatment_dc_field_theta'])
                    if Alteration_check_dc_field_phi==0 and Alteration_check_dc_field_theta==0 :
                        Alteration_check_index=0
                    if Alteration_check_dc_field_phi==90 and Alteration_check_dc_field_theta==0 :
                        Alteration_check_index=1
                    if Alteration_check_dc_field_phi==0 and Alteration_check_dc_field_theta==90 :
                        Alteration_check_index=2
                    if Alteration_check_dc_field_phi==180 and Alteration_check_dc_field_theta==0 :
                        Alteration_check_index=3
                    if Alteration_check_dc_field_phi==270 and Alteration_check_dc_field_theta==0 :
                        Alteration_check_index=4
                    if Alteration_check_dc_field_phi==0 and Alteration_check_dc_field_theta==-90 :
                        Alteration_check_index=5
                    aniso_logfile.write(  "-I- found alteration check  for specimen %s\n"%specimen)
                    continue

                treatment_dc_field_phi=float(rec['treatment_dc_field_phi'])
                treatment_dc_field_theta=float(rec['treatment_dc_field_theta'])
                treatment_dc_field=float(rec['treatment_dc_field'])

                #+x, M[0]
                if treatment_dc_field_phi==0 and treatment_dc_field_theta==0 :
                    M[0]=CART
                #+Y , M[1]
                if treatment_dc_field_phi==90 and treatment_dc_field_theta==0 :
                    M[1]=CART
                #+Z , M[2]
                if treatment_dc_field_phi==0 and treatment_dc_field_theta==90 :
                    M[2]=CART
                #-x, M[3]
                if treatment_dc_field_phi==180 and treatment_dc_field_theta==0 :
                    M[3]=CART
                #-Y , M[4]
                if treatment_dc_field_phi==270 and treatment_dc_field_theta==0 :
                    M[4]=CART
                #-Z , M[5]
                if treatment_dc_field_phi==0 and treatment_dc_field_theta==-90 :
                    M[5]=CART

            # check if at least one measurement in missing
            for i in range(len(M)):
                if M[i][0]==0 and M[i][1]==0 and M[i][2]==0:
                    aniso_logfile.write( "-E- ERROR: missing atrm data for specimen %s\n"%(specimen))
                    Reject_specimen=True

            # alteration check

            anisotropy_alt=0
            if Alteration_check!="":
                for i in range(len(M)):
                    if Alteration_check_index==i:
                        M_1=sqrt(sum((array(M[i])**2)))
                        M_2=sqrt(sum(Alteration_check**2))
                        diff=abs(M_1-M_2)
                        diff_ratio=old_div(diff,mean([M_1,M_2]))
                        diff_ratio_perc=100*diff_ratio
                        if diff_ratio_perc > anisotropy_alt:
                            anisotropy_alt=diff_ratio_perc
            else:
                aniso_logfile.write( "-W- Warning: no alteration check for specimen %s \n "%specimen )

            # Check for maximum difference in anti parallel directions.
            # if the difference between the two measurements is more than maximum_diff
            # The specimen is rejected

            # i.e. +x versus -x, +y versus -y, etc.s

            for i in range(3):
                M_1=sqrt(sum(array(M[i])**2))
                M_2=sqrt(sum(array(M[i+3])**2))

                diff=abs(M_1-M_2)
                diff_ratio=old_div(diff,max(M_1,M_2))
                diff_ratio_perc=100*diff_ratio

                if diff_ratio_perc>anisotropy_alt:
                    anisotropy_alt=diff_ratio_perc

            if not Reject_specimen:

                # K vector (18 elements, M1[x], M1[y], M1[z], ... etc.)
                K=zeros(18,'f')
                K[0],K[1],K[2]=M[0][0],M[0][1],M[0][2]
                K[3],K[4],K[5]=M[1][0],M[1][1],M[1][2]
                K[6],K[7],K[8]=M[2][0],M[2][1],M[2][2]
                K[9],K[10],K[11]=M[3][0],M[3][1],M[3][2]
                K[12],K[13],K[14]=M[4][0],M[4][1],M[4][2]
                K[15],K[16],K[17]=M[5][0],M[5][1],M[5][2]

                if specimen not in list(Data_anisotropy.keys()):
                    Data_anisotropy[specimen]={}
                aniso_parameters=calculate_aniso_parameters(B,K)
                Data_anisotropy[specimen]['ATRM']=aniso_parameters
                Data_anisotropy[specimen]['ATRM']['anisotropy_alt']="%.2f"%anisotropy_alt
                Data_anisotropy[specimen]['ATRM']['anisotropy_type']="ATRM"
                Data_anisotropy[specimen]['ATRM']['er_sample_name']=atrmblock[0]['er_sample_name']
                Data_anisotropy[specimen]['ATRM']['er_specimen_name']=specimen
                Data_anisotropy[specimen]['ATRM']['er_site_name']=atrmblock[0]['er_site_name']
                Data_anisotropy[specimen]['ATRM']['anisotropy_description']='Hext statistics adapted to ATRM'
                Data_anisotropy[specimen]['ATRM']['magic_experiment_names']=specimen+";ATRM"
                Data_anisotropy[specimen]['ATRM']['magic_method_codes']="LP-AN-TRM:AE-H"
                #Data_anisotropy[specimen]['ATRM']['rmag_anisotropy_name']=specimen

        if 'aarmblock' in list(Data[specimen].keys()):

            #-----------------------------------
            # AARM - 6, 9 or 15 positions
            #-----------------------------------

            aniso_logfile.write( "-I- Start calculating AARM tensors specimen %s\n"%specimen)

            aarmblock=Data[specimen]['aarmblock']
            if len(aarmblock)<12:
                aniso_logfile.write( "-W- WARNING: not enough aarm measurement for specimen %s\n"%specimen)
                continue
            elif len(aarmblock)==12:
                n_pos=6
                B=Matrices[6]['B']
                M=zeros([6,3],'f')
            elif len(aarmblock)==18:
                n_pos=9
                B=Matrices[9]['B']
                M=zeros([9,3],'f')
            # 15 positions
            elif len(aarmblock)==30:
                n_pos=15
                B=Matrices[15]['B']
                M=zeros([15,3],'f')
            else:
                aniso_logfile.write( "-E- ERROR: number of measurements in aarm block is incorrect sample %s\n"%specimen)
                continue

            Reject_specimen = False

            for i in range(n_pos):
                for rec in aarmblock:
                    if float(rec['measurement_number'])==i*2+1:
                        dec=float(rec['measurement_dec'])
                        inc=float(rec['measurement_inc'])
                        moment=float(rec['measurement_magn_moment'])
                        M_baseline=array(pmag.dir2cart([dec,inc,moment]))

                    if float(rec['measurement_number'])==i*2+2:
                        dec=float(rec['measurement_dec'])
                        inc=float(rec['measurement_inc'])
                        moment=float(rec['measurement_magn_moment'])
                        M_arm=array(pmag.dir2cart([dec,inc,moment]))
                M[i]=M_arm-M_baseline

            K=zeros(3*n_pos,'f')
            for i in range(n_pos):
                K[i*3]=M[i][0]
                K[i*3+1]=M[i][1]
                K[i*3+2]=M[i][2]

            if specimen not in list(Data_anisotropy.keys()):
                Data_anisotropy[specimen]={}
            aniso_parameters=calculate_aniso_parameters(B,K)
            Data_anisotropy[specimen]['AARM']=aniso_parameters
            Data_anisotropy[specimen]['AARM']['anisotropy_alt']=""
            Data_anisotropy[specimen]['AARM']['anisotropy_type']="AARM"
            Data_anisotropy[specimen]['AARM']['er_sample_name']=aarmblock[0]['er_sample_name']
            Data_anisotropy[specimen]['AARM']['er_site_name']=aarmblock[0]['er_site_name']
            Data_anisotropy[specimen]['AARM']['er_specimen_name']=specimen
            Data_anisotropy[specimen]['AARM']['anisotropy_description']='Hext statistics adapted to AARM'
            Data_anisotropy[specimen]['AARM']['magic_experiment_names']=specimen+";AARM"
            Data_anisotropy[specimen]['AARM']['magic_method_codes']="LP-AN-ARM:AE-H"
            #Data_anisotropy[specimen]['AARM']['rmag_anisotropy_name']=specimen

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

    specimens=list(Data_anisotropy.keys())
    specimens.sort

    # remove previous anistropy data, and replace with the new one:
    s_list=list(Data.keys())
    for sp in s_list:
        if 'AniSpec' in list(Data[sp].keys()):
            del  Data[sp]['AniSpec']
    for specimen in specimens:
        # if both AARM and ATRM axist prefer the AARM !!
        if 'AARM' in list(Data_anisotropy[specimen].keys()):
            TYPES=['AARM']
        if 'ATRM' in list(Data_anisotropy[specimen].keys()):
            TYPES=['ATRM']
        if  'AARM' in list(Data_anisotropy[specimen].keys()) and 'ATRM' in list(Data_anisotropy[specimen].keys()):
            TYPES=['ATRM','AARM']
            aniso_logfile.write( "-W- WARNING: both aarm and atrm data exist for specimen %s. using AARM by default. If you prefer using one of them, delete the other!\n"%specimen)
        for TYPE in TYPES:
            String=""
            for i in range (len(rmag_anistropy_header)):
                try:
                    String=String+Data_anisotropy[specimen][TYPE][rmag_anistropy_header[i]]+'\t'
                except:
                    String=String+"%f"%(Data_anisotropy[specimen][TYPE][rmag_anistropy_header[i]])+'\t'
            rmag_anisotropy_file.write(String[:-1]+"\n")

            String=""
            Data_anisotropy[specimen][TYPE]['er_specimen_names']=Data_anisotropy[specimen][TYPE]['er_specimen_name']
            Data_anisotropy[specimen][TYPE]['er_sample_names']=Data_anisotropy[specimen][TYPE]['er_sample_name']
            Data_anisotropy[specimen][TYPE]['er_site_names']=Data_anisotropy[specimen][TYPE]['er_site_name']
            for i in range (len(rmag_results_header)):
                try:
                    String=String+Data_anisotropy[specimen][TYPE][rmag_results_header[i]]+'\t'
                except:
                    String=String+"%f"%(Data_anisotropy[specimen][TYPE][rmag_results_header[i]])+'\t'
            rmag_results_file.write(String[:-1]+"\n")

            if 'AniSpec' not in Data[specimen]:
                Data[specimen]['AniSpec']={}
            Data[specimen]['AniSpec'][TYPE]=Data_anisotropy[specimen][TYPE]

    aniso_logfile.write("------------------------\n")
    aniso_logfile.write("-I-  remanence_aniso_magic script finished sucsessfuly\n")
    aniso_logfile.write( "------------------------\n")

    rmag_anisotropy_file.close()
    print("Anisotropy tensors elements are saved in rmag_anistropy.txt")
    print("Other anisotropy statistics are saved in rmag_results.txt")
    print("log file is  in rmag_anisotropy.log")

Response: This function is the main function of the aarm_magic. py program.


Instruction:
Given the following Python 3 function, write the documentation
def main():
    FIG = {}  # plot dictionary
    FIG['eqarea'] = 1  # eqarea is figure 1
    in_file, plot_key, coord, crd = 'pmag_results.txt', 'all', "0", 'g'
    plotE, contour = 0, 0
    dir_path = '.'
    fmt = 'svg'
    verbose = pmagplotlib.verbose
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path = sys.argv[ind+1]
    pmagplotlib.plot_init(FIG['eqarea'], 5, 5)
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        in_file = dir_path+"/"+sys.argv[ind+1]
    if '-obj' in sys.argv:
        ind = sys.argv.index('-obj')
        plot_by = sys.argv[ind+1]
        if plot_by == 'all':
            plot_key = 'all'
        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 '-c' in sys.argv:
        contour = 1
    plt = 0
    if '-sav' in sys.argv:
        plt = 1
        verbose = 0
    if '-ell' in sys.argv:
        plotE = 1
        ind = sys.argv.index('-ell')
        ell_type = sys.argv[ind+1]
        if ell_type == 'F':
            dist = 'F'
        if ell_type == 'K':
            dist = 'K'
        if ell_type == 'B':
            dist = 'B'
        if ell_type == 'Be':
            dist = 'BE'
        if ell_type == 'Bv':
            dist = 'BV'
            FIG['bdirs'] = 2
            pmagplotlib.plot_init(FIG['bdirs'], 5, 5)
    if '-crd' in sys.argv:
        ind = sys.argv.index("-crd")
        crd = sys.argv[ind+1]
        if crd == 's':
            coord = "-1"
        if crd == 'g':
            coord = "0"
        if crd == 't':
            coord = "100"
    if '-fmt' in sys.argv:
        ind = sys.argv.index("-fmt")
        fmt = sys.argv[ind+1]
    Dec_keys = ['site_dec', 'sample_dec', 'specimen_dec',
                'measurement_dec', 'average_dec', 'none']
    Inc_keys = ['site_inc', 'sample_inc', 'specimen_inc',
                'measurement_inc', 'average_inc', 'none']
    Tilt_keys = ['tilt_correction', 'site_tilt_correction',
                 'sample_tilt_correction', 'specimen_tilt_correction', 'none']
    Dir_type_keys = ['', 'site_direction_type',
                     'sample_direction_type', 'specimen_direction_type']
    Name_keys = ['er_specimen_name', 'er_sample_name',
                 'er_site_name', 'pmag_result_name']
    data, file_type = pmag.magic_read(in_file)
    if file_type == 'pmag_results' and plot_key != "all":
        plot_key = plot_key+'s'  # need plural for results table
    if verbose:
        print(len(data), ' records read from ', in_file)
    #
    #
    # find desired dec,inc data:
    #
    dir_type_key = ''
    #
    # get plotlist if not plotting all records
    #
    plotlist = []
    if plot_key != "all":
        plots = pmag.get_dictitem(data, plot_key, '', 'F')
        for rec in plots:
            if rec[plot_key] not in plotlist:
                plotlist.append(rec[plot_key])
        plotlist.sort()
    else:
        plotlist.append('All')
    for plot in plotlist:
        # if verbose: print plot
        DIblock = []
        GCblock = []
        SLblock, SPblock = [], []
        title = plot
        mode = 1
        dec_key, inc_key, tilt_key, name_key, k = "", "", "", "", 0
        if plot != "All":
            odata = pmag.get_dictitem(data, plot_key, plot, 'T')
        else:
            odata = data  # data for this obj
        for dec_key in Dec_keys:
            # get all records with this dec_key not blank
            Decs = pmag.get_dictitem(odata, dec_key, '', 'F')
            if len(Decs) > 0:
                break
        for inc_key in Inc_keys:
            # get all records with this inc_key not blank
            Incs = pmag.get_dictitem(Decs, inc_key, '', 'F')
            if len(Incs) > 0:
                break
        for tilt_key in Tilt_keys:
            if tilt_key in Incs[0].keys():
                break  # find the tilt_key for these records
        if tilt_key == 'none':  # no tilt key in data, need to fix this with fake data which will be unknown tilt
            tilt_key = 'tilt_correction'
            for rec in Incs:
                rec[tilt_key] = ''
        # get all records matching specified coordinate system
        cdata = pmag.get_dictitem(Incs, tilt_key, coord, 'T')
        if coord == '0':  # geographic
            # get all the blank records - assume geographic
            udata = pmag.get_dictitem(Incs, tilt_key, '', 'T')
            if len(cdata) == 0:
                crd = ''
            if len(udata) > 0:
                for d in udata:
                    cdata.append(d)
                crd = crd+'u'
        for name_key in Name_keys:
            # get all records with this name_key not blank
            Names = pmag.get_dictitem(cdata, name_key, '', 'F')
            if len(Names) > 0:
                break
        for dir_type_key in Dir_type_keys:
            # get all records with this direction type
            Dirs = pmag.get_dictitem(cdata, dir_type_key, '', 'F')
            if len(Dirs) > 0:
                break
        if dir_type_key == "":
            dir_type_key = 'direction_type'
        locations, site, sample, specimen = "", "", "", ""
        for rec in cdata:  # pick out the data
            if 'er_location_name' in rec.keys() and rec['er_location_name'] != "" and rec['er_location_name'] not in locations:
                locations = locations + \
                    rec['er_location_name'].replace("/", "")+"_"
            if 'er_location_names' in rec.keys() and rec['er_location_names'] != "":
                locs = rec['er_location_names'].split(':')
                for loc in locs:
                    if loc not in locations:
                        locations = locations+loc.replace("/", "")+'_'
            if plot_key == 'er_site_name' or plot_key == 'er_sample_name' or plot_key == 'er_specimen_name':
                site = rec['er_site_name']
            if plot_key == 'er_sample_name' or plot_key == 'er_specimen_name':
                sample = rec['er_sample_name']
            if plot_key == 'er_specimen_name':
                specimen = rec['er_specimen_name']
            if plot_key == 'er_site_names' or plot_key == 'er_sample_names' or plot_key == 'er_specimen_names':
                site = rec['er_site_names']
            if plot_key == 'er_sample_names' or plot_key == 'er_specimen_names':
                sample = rec['er_sample_names']
            if plot_key == 'er_specimen_names':
                specimen = rec['er_specimen_names']
            if dir_type_key not in rec.keys() or rec[dir_type_key] == "":
                rec[dir_type_key] = 'l'
            if 'magic_method_codes' not in rec.keys():
                rec['magic_method_codes'] = ""
            DIblock.append([float(rec[dec_key]), float(rec[inc_key])])
            SLblock.append([rec[name_key], rec['magic_method_codes']])
            if rec[tilt_key] == coord and rec[dir_type_key] != 'l' and rec[dec_key] != "" and rec[inc_key] != "":
                GCblock.append([float(rec[dec_key]), float(rec[inc_key])])
                SPblock.append([rec[name_key], rec['magic_method_codes']])
        if len(DIblock) == 0 and len(GCblock) == 0:
            if verbose:
                print("no records for plotting")
            sys.exit()
        if verbose:
            for k in range(len(SLblock)):
                print('%s %s %7.1f %7.1f' % (
                    SLblock[k][0], SLblock[k][1], DIblock[k][0], DIblock[k][1]))
            for k in range(len(SPblock)):
                print('%s %s %7.1f %7.1f' % (
                    SPblock[k][0], SPblock[k][1], GCblock[k][0], GCblock[k][1]))
        if len(DIblock) > 0:
            if contour == 0:
                pmagplotlib.plot_eq(FIG['eqarea'], DIblock, title)
            else:
                pmagplotlib.plot_eq_cont(FIG['eqarea'], DIblock)
        else:
            pmagplotlib.plot_net(FIG['eqarea'])
        if len(GCblock) > 0:
            for rec in GCblock:
                pmagplotlib.plot_circ(FIG['eqarea'], rec, 90., 'g')
        if plotE == 1:
            ppars = pmag.doprinc(DIblock)  # get principal directions
            nDIs, rDIs, npars, rpars = [], [], [], []
            for rec in DIblock:
                angle = pmag.angle([rec[0], rec[1]], [
                                   ppars['dec'], ppars['inc']])
                if angle > 90.:
                    rDIs.append(rec)
                else:
                    nDIs.append(rec)
            if dist == 'B':  # do on whole dataset
                etitle = "Bingham confidence ellipse"
                bpars = pmag.dobingham(DIblock)
                for key in bpars.keys():
                    if key != 'n' and verbose:
                        print("    ", key, '%7.1f' % (bpars[key]))
                    if key == 'n' and verbose:
                        print("    ", key, '       %i' % (bpars[key]))
                npars.append(bpars['dec'])
                npars.append(bpars['inc'])
                npars.append(bpars['Zeta'])
                npars.append(bpars['Zdec'])
                npars.append(bpars['Zinc'])
                npars.append(bpars['Eta'])
                npars.append(bpars['Edec'])
                npars.append(bpars['Einc'])
            if dist == 'F':
                etitle = "Fisher confidence cone"
                if len(nDIs) > 2:
                    fpars = pmag.fisher_mean(nDIs)
                    for key in fpars.keys():
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (fpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (fpars[key]))
                    mode += 1
                    npars.append(fpars['dec'])
                    npars.append(fpars['inc'])
                    npars.append(fpars['alpha95'])  # Beta
                    npars.append(fpars['dec'])
                    isign = abs(fpars['inc'])/fpars['inc']
                    npars.append(fpars['inc']-isign*90.)  # Beta inc
                    npars.append(fpars['alpha95'])  # gamma
                    npars.append(fpars['dec']+90.)  # Beta dec
                    npars.append(0.)  # Beta inc
                if len(rDIs) > 2:
                    fpars = pmag.fisher_mean(rDIs)
                    if verbose:
                        print("mode ", mode)
                    for key in fpars.keys():
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (fpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (fpars[key]))
                    mode += 1
                    rpars.append(fpars['dec'])
                    rpars.append(fpars['inc'])
                    rpars.append(fpars['alpha95'])  # Beta
                    rpars.append(fpars['dec'])
                    isign = abs(fpars['inc'])/fpars['inc']
                    rpars.append(fpars['inc']-isign*90.)  # Beta inc
                    rpars.append(fpars['alpha95'])  # gamma
                    rpars.append(fpars['dec']+90.)  # Beta dec
                    rpars.append(0.)  # Beta inc
            if dist == 'K':
                etitle = "Kent confidence ellipse"
                if len(nDIs) > 3:
                    kpars = pmag.dokent(nDIs, len(nDIs))
                    if verbose:
                        print("mode ", mode)
                    for key in kpars.keys():
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (kpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (kpars[key]))
                    mode += 1
                    npars.append(kpars['dec'])
                    npars.append(kpars['inc'])
                    npars.append(kpars['Zeta'])
                    npars.append(kpars['Zdec'])
                    npars.append(kpars['Zinc'])
                    npars.append(kpars['Eta'])
                    npars.append(kpars['Edec'])
                    npars.append(kpars['Einc'])
                if len(rDIs) > 3:
                    kpars = pmag.dokent(rDIs, len(rDIs))
                    if verbose:
                        print("mode ", mode)
                    for key in kpars.keys():
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (kpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (kpars[key]))
                    mode += 1
                    rpars.append(kpars['dec'])
                    rpars.append(kpars['inc'])
                    rpars.append(kpars['Zeta'])
                    rpars.append(kpars['Zdec'])
                    rpars.append(kpars['Zinc'])
                    rpars.append(kpars['Eta'])
                    rpars.append(kpars['Edec'])
                    rpars.append(kpars['Einc'])
            else:  # assume bootstrap
                if dist == 'BE':
                    if len(nDIs) > 5:
                        BnDIs = pmag.di_boot(nDIs)
                        Bkpars = pmag.dokent(BnDIs, 1.)
                        if verbose:
                            print("mode ", mode)
                        for key in Bkpars.keys():
                            if key != 'n' and verbose:
                                print("    ", key, '%7.1f' % (Bkpars[key]))
                            if key == 'n' and verbose:
                                print("    ", key, '       %i' % (Bkpars[key]))
                        mode += 1
                        npars.append(Bkpars['dec'])
                        npars.append(Bkpars['inc'])
                        npars.append(Bkpars['Zeta'])
                        npars.append(Bkpars['Zdec'])
                        npars.append(Bkpars['Zinc'])
                        npars.append(Bkpars['Eta'])
                        npars.append(Bkpars['Edec'])
                        npars.append(Bkpars['Einc'])
                    if len(rDIs) > 5:
                        BrDIs = pmag.di_boot(rDIs)
                        Bkpars = pmag.dokent(BrDIs, 1.)
                        if verbose:
                            print("mode ", mode)
                        for key in Bkpars.keys():
                            if key != 'n' and verbose:
                                print("    ", key, '%7.1f' % (Bkpars[key]))
                            if key == 'n' and verbose:
                                print("    ", key, '       %i' % (Bkpars[key]))
                        mode += 1
                        rpars.append(Bkpars['dec'])
                        rpars.append(Bkpars['inc'])
                        rpars.append(Bkpars['Zeta'])
                        rpars.append(Bkpars['Zdec'])
                        rpars.append(Bkpars['Zinc'])
                        rpars.append(Bkpars['Eta'])
                        rpars.append(Bkpars['Edec'])
                        rpars.append(Bkpars['Einc'])
                    etitle = "Bootstrapped confidence ellipse"
                elif dist == 'BV':
                    sym = {'lower': ['o', 'c'], 'upper': [
                        'o', 'g'], 'size': 3, 'edgecolor': 'face'}
                    if len(nDIs) > 5:
                        BnDIs = pmag.di_boot(nDIs)
                        pmagplotlib.plot_eq_sym(
                            FIG['bdirs'], BnDIs, 'Bootstrapped Eigenvectors', sym)
                    if len(rDIs) > 5:
                        BrDIs = pmag.di_boot(rDIs)
                        if len(nDIs) > 5:  # plot on existing plots
                            pmagplotlib.plot_di_sym(FIG['bdirs'], BrDIs, sym)
                        else:
                            pmagplotlib.plot_eq(
                                FIG['bdirs'], BrDIs, 'Bootstrapped Eigenvectors')
            if dist == 'B':
                if len(nDIs) > 3 or len(rDIs) > 3:
                    pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], npars, 0)
            elif len(nDIs) > 3 and dist != 'BV':
                pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], npars, 0)
                if len(rDIs) > 3:
                    pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], rpars, 0)
            elif len(rDIs) > 3 and dist != 'BV':
                pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], rpars, 0)
        if verbose:
            pmagplotlib.draw_figs(FIG)
            #
        files = {}
        locations = locations[:-1]
        for key in FIG.keys():
            if pmagplotlib.isServer:  # use server plot naming convention
                filename = 'LO:_'+locations+'_SI:_'+site+'_SA:_'+sample + \
                    '_SP:_'+specimen+'_CO:_'+crd+'_TY:_'+key+'_.'+fmt
            else:  # use more readable plot naming convention
                filename = ''
                for item in [locations, site, sample, specimen, crd, key]:
                    if item:
                        item = item.replace(' ', '_')
                        filename += item + '_'
                if filename.endswith('_'):
                    filename = filename[:-1]
                filename += ".{}".format(fmt)
            files[key] = filename
        if pmagplotlib.isServer:
            black = '#000000'
            purple = '#800080'
            titles = {}
            titles['eq'] = 'Equal Area Plot'
            FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
            pmagplotlib.save_plots(FIG, files)
        elif verbose:
            ans = raw_input(
                " S[a]ve to save plot, [q]uit, Return to continue:  ")
            if ans == "q":
                sys.exit()
            if ans == "a":
                pmagplotlib.save_plots(FIG, files)
        if plt:
            pmagplotlib.save_plots(FIG, files)

Response:
NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

    INPUT
       takes magic formatted pmag_results, pmag_sites, pmag_samples or pmag_specimens

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file from magic,default='pmag_results.txt'
         supported types=[magic_measurements,pmag_specimens, pmag_samples, pmag_sites, pmag_results, magic_web]
        -obj OBJ: specify  level of plot  [all, sit, sam, spc], default is all
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is geographic, unspecified assumed geographic
        -fmt [svg,png,jpg] format for output plots
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
        -c plot as colour contour
        -sav save plot and quit quietly
    NOTE
        all: entire file; sit: site; sam: sample; spc: specimen


Instruction:
Make a summary of the following Python 3 code
def main(command_line=True, **kwargs):

    #--------------------------------------
    # functions
    #--------------------------------------

    def sort_magic_file(path,ignore_lines_n,sort_by_this_name):
        '''
        reads a file with headers. Each line is stored as a dictionary following the headers.
        Lines are sorted in DATA by the sort_by_this_name header
        DATA[sort_by_this_name]=[dictionary1,dictionary2,...]
        '''
        DATA={}
        fin=open(path,'r')
        #ignore first lines
        for i in range(ignore_lines_n):
            fin.readline()
        #header
        line=fin.readline()
        header=line.strip('\n').split('\t')
        #print header
        for line in fin.readlines():
            if line[0]=="#":
                continue
            tmp_data={}
            tmp_line=line.strip('\n').split('\t')
            #print tmp_line
            for i in range(len(tmp_line)):
                if i>= len(header):
                    continue
                tmp_data[header[i]]=tmp_line[i]
            DATA[tmp_data[sort_by_this_name]]=tmp_data
        fin.close()
        return(DATA)

    def read_generic_file(path,average_replicates):
        '''
        reads a generic file format. If average_replicates==True average replicate measurements.
        Rrturns a Data dictionary with measurements line sorted by specimen
        Data[specimen_name][dict1,dict2,...]
        '''
        Data={}
        Fin=open(path,'r')
        header=Fin.readline().strip('\n').split('\t')
        duplicates=[]
        for line in Fin.readlines():
            tmp_data={}
            #found_duplicate=False
            l=line.strip('\n').split('\t')
            for i in range(min(len(header),len(l))):
                tmp_data[header[i]]=l[i]
            specimen=tmp_data['specimen']
            if specimen not in list(Data.keys()):
                Data[specimen]=[]
            Data[specimen].append(tmp_data)
        # search fro duplicates
        for specimen in list(Data.keys()):
            x=len(Data[specimen])-1
            new_data=[]
            duplicates=[]
            for i in range(1,x):
                while i< len(Data[specimen]) and Data[specimen][i]['treatment']==Data[specimen][i-1]['treatment'] and Data[specimen][i]['treatment_type']==Data[specimen][i-1]['treatment_type']:
                   duplicates.append(Data[specimen][i])
                   del(Data[specimen][i])
                if len(duplicates)>0:
                   if average_replicates:
                       duplicates.append(Data[specimen][i-1])
                       Data[specimen][i-1]=average_duplicates(duplicates)
                       print("-W- WARNING: averaging %i duplicates for specimen %s treatmant %s"%(len(duplicates),specimen,duplicates[-1]['treatment']))
                       duplicates=[]
                   else:
                       Data[specimen][i-1]=duplicates[-1]
                       print("-W- WARNING: found %i duplicates for specimen %s treatmant %s. Taking the last measurement only"%(len(duplicates),specimen,duplicates[-1]['treatment']))
                       duplicates=[]

                if i==len(Data[specimen])-1:
                    break

            #    if tmp_data['treatment']==Data[specimen][-1]['treatment'] and tmp_data['treatment_type']==Data[specimen][-1]['treatment_type']:
            #
            ## check replicates
            #if tmp_data['treatment']==Data[specimen][-1]['treatment'] and tmp_data['treatment_type']==Data[specimen][-1]['treatment_type']:
            #    #found_duplicate=True
            #    duplicates.append(Data[specimen][-1])
            #    duplicates.append(tmp_data)
            #    del(Data[specimen][-1])
            #    continue
            #else:
            #    if len(duplicates)>0:
            #        if average_replicates:
            #            Data[specimen].append(average_duplicates(duplicates))
            #            print "-W- WARNING: averaging %i duplicates for specimen %s treatmant %s"%(len(duplicates),specimen,duplicates[-1]['treatment'])
            #        else:
            #            Data[specimen].append(duplicates[-1])
            #            print "-W- WARNING: found %i duplicates for specimen %s treatmant %s. Taking the last measurement only"%(len(duplicates),specimen,duplicates[-1]['treatment'])
            #    duplicates=[]
            #    Data[specimen].append(tmp_data)

        return(Data)

    def average_duplicates(duplicates):
        '''
        avarage replicate measurements.
        '''
        carts_s,carts_g,carts_t=[],[],[]
        for rec in duplicates:
            moment=float(rec['moment'])
            if 'dec_s' in list(rec.keys()) and 'inc_s' in list(rec.keys()):
                if rec['dec_s']!="" and rec['inc_s']!="":
                    dec_s=float(rec['dec_s'])
                    inc_s=float(rec['inc_s'])
                    cart_s=pmag.dir2cart([dec_s,inc_s,moment])
                    carts_s.append(cart_s)
            if 'dec_g' in list(rec.keys()) and 'inc_g' in list(rec.keys()):
                if rec['dec_g']!="" and rec['inc_g']!="":
                    dec_g=float(rec['dec_g'])
                    inc_g=float(rec['inc_g'])
                    cart_g=pmag.dir2cart([dec_g,inc_g,moment])
                    carts_g.append(cart_g)
            if 'dec_t' in list(rec.keys()) and 'inc_t' in list(rec.keys()):
                if rec['dec_t']!="" and rec['inc_t']!="":
                    dec_t=float(rec['dec_t'])
                    inc_t=float(rec['inc_t'])
                    cart_t=pmag.dir2cart([dec_t,inc_t,moment])
                    carts_t.append(cart_t)
        if len(carts_s)>0:
            carts=scipy.array(carts_s)
            x_mean=scipy.mean(carts[:,0])
            y_mean=scipy.mean(carts[:,1])
            z_mean=scipy.mean(carts[:,2])
            mean_dir=pmag.cart2dir([x_mean,y_mean,z_mean])
            mean_dec_s="%.2f"%mean_dir[0]
            mean_inc_s="%.2f"%mean_dir[1]
            mean_moment="%10.3e"%mean_dir[2]
        else:
            mean_dec_s,mean_inc_s="",""
        if len(carts_g)>0:
            carts=scipy.array(carts_g)
            x_mean=scipy.mean(carts[:,0])
            y_mean=scipy.mean(carts[:,1])
            z_mean=scipy.mean(carts[:,2])
            mean_dir=pmag.cart2dir([x_mean,y_mean,z_mean])
            mean_dec_g="%.2f"%mean_dir[0]
            mean_inc_g="%.2f"%mean_dir[1]
            mean_moment="%10.3e"%mean_dir[2]
        else:
            mean_dec_g,mean_inc_g="",""

        if len(carts_t)>0:
            carts=scipy.array(carts_t)
            x_mean=scipy.mean(carts[:,0])
            y_mean=scipy.mean(carts[:,1])
            z_mean=scipy.mean(carts[:,2])
            mean_dir=pmag.cart2dir([x_mean,y_mean,z_mean])
            mean_dec_t="%.2f"%mean_dir[0]
            mean_inc_t="%.2f"%mean_dir[1]
            mean_moment="%10.3e"%mean_dir[2]
        else:
            mean_dec_t,mean_inc_t="",""

        meanrec={}
        for key in list(duplicates[0].keys()):
            if key in ['dec_s','inc_s','dec_g','inc_g','dec_t','inc_t','moment']:
                continue
            else:
                meanrec[key]=duplicates[0][key]
        meanrec['dec_s']=mean_dec_s
        meanrec['dec_g']=mean_dec_g
        meanrec['dec_t']=mean_dec_t
        meanrec['inc_s']=mean_inc_s
        meanrec['inc_g']=mean_inc_g
        meanrec['inc_t']=mean_inc_t
        meanrec['moment']=mean_moment
        return meanrec

    def get_upper_level_name(name,nc):
        '''
        get sample/site name from specimen/sample using naming convention
        '''
        if float(nc[0])==0:
            if float(nc[1])!=0:
                number_of_char=int(nc[1])
                high_name=name[:number_of_char]
            else:
                high_name=name
        elif float(nc[0])==1:
            if float(nc[1])!=0:
                number_of_char=int(nc[1])*-1
                high_name=name[:number_of_char]
            else:
                high_name=name
        elif float(nc[0])==2:
            d=str(nc[1])
            name_splitted=name.split(d)
            if len(name_splitted)==1:
                high_name=name_splitted[0]
            else:
                high_name=d.join(name_splitted[:-1])
        else:
            high_name=name
        return high_name

    def merge_pmag_recs(old_recs):
        recs={}
        recs=copy.deepcopy(old_recs)
        headers=[]
        for rec in recs:
            for key in list(rec.keys()):
                if key not in headers:
                    headers.append(key)
        for rec in recs:
            for header in headers:
                if header not in list(rec.keys()):
                    rec[header]=""
        return recs

    # initialize some variables
    experiment = ''
    sample_nc = [1, 0]
    site_nc = [1, 0]
    meas_file = "magic_measurements.txt"
    labfield = 0

    #--------------------------------------
    # get command line arguments
    #--------------------------------------

    if command_line:
        args=sys.argv
        user=""
        if "-h" in args:
            print(main.__doc__)
            return False
        if "-usr" in args:
            ind=args.index("-usr")
            user=args[ind+1]
        else:
            user=""
        if '-F' in args:
            ind=args.index("-F")
            meas_file=args[ind+1]
        if '-Fsa' in args:
            ind=args.index("-Fsa")
            samp_file=args[ind+1]
        else:
            samp_file="er_samples.txt"

        if '-f' in args:
            ind=args.index("-f")
            magfile=args[ind+1]

        if "-dc" in args:
            ind=args.index("-dc")
            labfield=float(args[ind+1])*1e-6
            labfield_phi=float(args[ind+2])
            labfield_theta=float(args[ind+3])
        if '-exp' in args:
            ind=args.index("-exp")
            experiment=args[ind+1]
        if "-samp" in args:
            ind=args.index("-samp")
            sample_nc=[]
            sample_nc.append(args[ind+1])
            sample_nc.append(args[ind+2])
        if "-site" in args:
            ind=args.index("-site")
            site_nc=[]
            site_nc.append(args[ind+1])
            site_nc.append(args[ind+2])
        if "-loc" in args:
            ind=args.index("-loc")
            er_location_name=args[ind+1]
        else:
            er_location_name=""
        if "-A" in args:
            noave=1
        else:
            noave=0

        if "-WD" in args:
            ind=args.index("-WD")
            WD=args[ind+1]
            os.chdir(WD)

    # unpack keyword args if using as module
    if not command_line:
        user = kwargs.get('user', '')
        meas_file = kwargs.get('meas_file', 'magic_measurements.txt')
        samp_file = kwargs.get('samp_file', 'er_samples.txt')
        magfile = kwargs.get('magfile', '')
        labfield = int(kwargs.get('labfield', 0))
        if labfield:
            labfield *= 1e-6
        labfield_phi = int(kwargs.get('labfield_phi', 0))
        labfield_theta = int(kwargs.get('labfield_theta', 0))
        experiment = kwargs.get('experiment', '')
        cooling_times = kwargs.get('cooling_times_list', '')
        sample_nc = kwargs.get('sample_nc', [1, 0])
        site_nc = kwargs.get('site_nc', [1, 0])
        er_location_name = kwargs.get('er_location_name', '')
        noave = kwargs.get('noave', 0) # 0 is default, means do average
        WD = kwargs.get('WD', '.')
        #os.chdir(WD)

    # format and validate variables
    if magfile:
        try:
            input=open(magfile,'r')
        except:
            print("bad mag file:",magfile)
            return False, "bad mag file"
    else:
        print("mag_file field is required option")
        print(main.__doc__)
        return False, "mag_file field is required option"

    if not experiment:
        print("-exp is required option. Please provide experiment type of: Demag, PI, ATRM n (n of positions), CR (see below for format), NLT")
        print(main.__doc__)
        return False, "-exp is required option"

    if experiment=='ATRM':
        if command_line:
            ind=args.index("ATRM")
            atrm_n_pos=int(args[ind+1])
        else:
            atrm_n_pos = 6

    if experiment=='AARM':
        if command_line:
            ind=args.index("AARM")
            aarm_n_pos=int(args[ind+1])
        else:
            aarm_n_pos = 6

    if  experiment=='CR':
        if command_line:
            ind=args.index("CR")
            cooling_times=args[ind+1]
        cooling_times_list=cooling_times.split(',')
        # if not command line, cooling_times_list is already set

    #--------------------------------------
    # read data from er_samples.txt
    #--------------------------------------

    #if "-fsa" in args:
    #   ind=args.index("-fsa")
    #    er_sample_file=args[ind+1]
    #else:
    #    er_sample_file="er_samples.txt"

    er_sample_data={}
    #er_sample_data=sort_magic_file(samp_file,1,'er_sample_name')
    try:
        er_sample_data=sort_magic_file(samp_file,1,'er_sample_name')
        print("-I- Found er_samples.txt")
        print('-I- sample information will be appended to existing er_samples.txt file')
    except:
        print("-I- Cant find file er_samples.txt")
        print('-I- sample information will be stored in new er_samples.txt file')

    #--------------------------------------
    # read data from generic file
    #--------------------------------------

    if  noave:
        mag_data=read_generic_file(magfile,False)
    else:
        mag_data=read_generic_file(magfile,True)

    #--------------------------------------
    # for each specimen get the data, and translate it to MagIC format
    #--------------------------------------

    ErSamplesRecs=[]
    MagRecs=[]
    specimens_list=list(mag_data.keys())
    specimens_list.sort()
    for specimen in specimens_list:
        measurement_running_number=0
        this_specimen_treatments=[] # a list of all treatments
        MagRecs_this_specimen=[]
        LP_this_specimen=[] # a list of all lab protocols
        IZ,ZI=0,0 # counter for IZ and ZI steps

        for meas_line in mag_data[specimen]:

            #------------------
            # trivial MagRec data
            #------------------

            MagRec={}
            MagRec['er_citation_names']="This study"
            MagRec["er_specimen_name"]=meas_line['specimen']
            MagRec["er_sample_name"]=get_upper_level_name(MagRec["er_specimen_name"],sample_nc)
            MagRec["er_site_name"]=get_upper_level_name(MagRec["er_sample_name"],site_nc)
            MagRec['er_location_name']=er_location_name
            MagRec['er_analyst_mail_names']=user
            MagRec["magic_instrument_codes"]=""
            MagRec["measurement_flag"]='g'
            MagRec["measurement_number"]="%i"%measurement_running_number

            MagRec["measurement_magn_moment"]='%10.3e'%(float(meas_line["moment"])*1e-3) # in Am^2
            MagRec["measurement_temp"]='273.' # room temp in kelvin

            #------------------
            #  decode treatments from treatment column in the generic file
            #------------------

            treatment=[]
            treatment_code=str(meas_line['treatment']).split(".")
            treatment.append(float(treatment_code[0]))
            if len(treatment_code)==1:
                treatment.append(0)
            else:
                treatment.append(float(treatment_code[1]))

            #------------------
            #  lab field direction
            #------------------

            if experiment in ['PI','NLT','CR']:

                if float(treatment[1])==0:
                    MagRec["treatment_dc_field"]="0"
                    MagRec["treatment_dc_field_phi"]="0"
                    MagRec["treatment_dc_field_theta"]="0"
                elif not labfield:
                    print("-W- WARNING: labfield (-dc) is a required argument for this experiment type")
                    return False, "labfield (-dc) is a required argument for this experiment type"

                else:
                    MagRec["treatment_dc_field"]='%8.3e'%(float(labfield))
                    MagRec["treatment_dc_field_phi"]="%.2f"%(float(labfield_phi))
                    MagRec["treatment_dc_field_theta"]="%.2f"%(float(labfield_theta))
            else:
                MagRec["treatment_dc_field"]=""
                MagRec["treatment_dc_field_phi"]=""
                MagRec["treatment_dc_field_theta"]=""

            #------------------
            # treatment temperature/peak field
            #------------------

            if experiment == 'Demag':
                if meas_line['treatment_type']=='A':
                    MagRec['treatment_temp']="273."
                    MagRec["treatment_ac_field"]="%.3e"%(treatment[0]*1e-3)
                elif meas_line['treatment_type']=='N':
                    MagRec['treatment_temp']="273."
                    MagRec["treatment_ac_field"]=""
                else:
                    MagRec['treatment_temp']="%.2f"%(treatment[0]+273.)
                    MagRec["treatment_ac_field"]=""
            else:
                    MagRec['treatment_temp']="%.2f"%(treatment[0]+273.)
                    MagRec["treatment_ac_field"]=""

            #---------------------
            # Lab treatment
            # Lab protocol
            #---------------------

            #---------------------
            # Lab treatment and lab protocoal for NRM:
            #---------------------

            if float(meas_line['treatment'])==0:
                LT="LT-NO"
                LP="" # will be filled later after finishing reading all measurements line

            #---------------------
            # Lab treatment and lab protocoal for paleointensity experiment
            #---------------------

            elif experiment =='PI':
                LP="LP-PI-TRM"
                if treatment[1]==0:
                    LT="LT-T-Z"
                elif  treatment[1]==1 or treatment[1]==10: # infield
                    LT="LT-T-I"
                elif treatment[1]==2 or treatment[1]==20:  # pTRM check
                    LT="LT-PTRM-I"
                    LP=LP+":"+"LP-PI-ALT-PTRM"
                elif treatment[1]==3 or treatment[1]==30: # Tail check
                    LT="LT-PTRM-MD"
                    LP=LP+":"+"LP-PI-BT-MD"
                elif treatment[1]==4 or treatment[1]==40: # Additivity check
                    LT="LT-PTRM-AC"
                    LP=LP+":"+"LP-PI-BT-MD"
                elif treatment[1]==5 or treatment[1]==50: # Thellier protocol, second infield step
                    LT="LT-T-I"
                    LP=LP+":"+"LP-PI-II"

                    # adjust field direction in thellier protocol
                    MagRec["treatment_dc_field_phi"]="%.2f"%( (float(labfield_phi) +180.0)%360.    )
                    MagRec["treatment_dc_field_theta"]="%.2f"%( float(labfield_theta)*-1 )

                else:
                    print("-E- unknown measurement code specimen %s treatmemt %s"%(meas_line['specimen'],meas_line['treatment']))
                    MagRec={}
                    continue
                # save all treatment in a list
                # we will use this later to distinguidh between ZI / IZ / and IZZI

                this_specimen_treatments.append(float(meas_line['treatment']))
                if LT=="LT-T-Z":
                    if float(treatment[0]+0.1) in this_specimen_treatments:
                        LP=LP+":"+"LP-PI-IZ"
                if LT=="LT-T-I":
                    if float(treatment[0]+0.0) in this_specimen_treatments:
                        LP=LP+":"+"LP-PI-ZI"
            #---------------------
            # Lab treatment and lab protocoal for demag experiment
            #---------------------

            elif "Demag" in experiment:
                if meas_line['treatment_type']=='A':
                    LT="LT-AF-Z"
                    LP="LP-DIR-AF"
                else:
                    LT="LT-T-Z"
                    LP="LP-DIR-T"

            #---------------------
            # Lab treatment and lab protocoal for ATRM experiment
            #---------------------

            elif experiment in ['ATRM','AARM']:

                if experiment=='ATRM':
                    LP="LP-AN-TRM"
                    n_pos=atrm_n_pos
                    if n_pos!=6:
                        print("the program does not support ATRM in %i position."%n_pos)
                        continue

                if experiment=='AARM':
                    #MagRec['treatment_temp']="273."
                    #MagRec["treatment_ac_field"]=""
                    LP="LP-AN-ARM"
                    n_pos=aarm_n_pos
                    if n_pos!=6:
                        print("the program does not support AARM in %i position."%n_pos)
                        continue

                if treatment[1]==0:
                    if experiment=='ATRM':
                        LT="LT-T-Z"
                        MagRec['treatment_temp']="%.2f"%(treatment[0]+273.)
                        MagRec["treatment_ac_field"]=""

                    else:
                        LT="LT-AF-Z"
                        MagRec['treatment_temp']="273."
                        MagRec["treatment_ac_field"]="%.3e"%(treatment[0]*1e-3)
                    MagRec["treatment_dc_field"]='0'
                    MagRec["treatment_dc_field_phi"]='0'
                    MagRec["treatment_dc_field_theta"]='0'
                else:
                    if experiment=='ATRM':
                        if float(treatment[1])==70 or float(treatment[1])==7: # alteration check as final measurement
                            LT="LT-PTRM-I"
                        else:
                            LT="LT-T-I"
                    else:
                        LT="LT-AF-I"
                    MagRec["treatment_dc_field"]='%8.3e'%(float(labfield))

                    # find the direction of the lab field in two ways:

                    # (1) using the treatment coding (XX.1=+x, XX.2=+y, XX.3=+z, XX.4=-x, XX.5=-y, XX.6=-z)
                    tdec=[0,90,0,180,270,0,0,90,0]
                    tinc=[0,0,90,0,0,-90,0,0,90]
                    if treatment[1] < 10:
                        ipos_code=int(treatment[1])-1
                    else:
                        ipos_code=int(old_div(treatment[1],10))-1

                    # (2) using the magnetization
                    if meas_line["dec_s"]!="":
                        DEC=float(meas_line["dec_s"])
                        INC=float(meas_line["inc_s"])
                    elif meas_line["dec_g"]!="":
                        DEC=float(meas_line["dec_g"])
                        INC=float(meas_line["inc_g"])
                    elif meas_line["dec_t"]!="":
                        DEC=float(meas_line["dec_t"])
                        INC=float(meas_line["inc_t"])
                    if DEC<0 and DEC>-359:
                        DEC=360.+DEC

                    if INC < 45 and INC > -45:
                        if DEC>315  or DEC<45: ipos_guess=0
                        if DEC>45 and DEC<135: ipos_guess=1
                        if DEC>135 and DEC<225: ipos_guess=3
                        if DEC>225 and DEC<315: ipos_guess=4
                    else:
                        if INC >45: ipos_guess=2
                        if INC <-45: ipos_guess=5
                    # prefer the guess over the code
                    ipos=ipos_guess
                    # check it
                    if treatment[1]!= 7 and treatment[1]!= 70:
                        if ipos_guess!=ipos_code:
                            print("-W- WARNING: check specimen %s step %s, anistropy measurements, coding does not match the direction of the lab field"%(specimen,meas_line['treatment']))
                    MagRec["treatment_dc_field_phi"]='%7.1f' %(tdec[ipos])
                    MagRec["treatment_dc_field_theta"]='%7.1f'% (tinc[ipos])

            #---------------------
            # Lab treatment and lab protocoal for cooling rate experiment
            #---------------------

            elif experiment == "CR":

                cooling_times_list
                LP="LP-CR-TRM"
                MagRec["treatment_temp"]='%8.3e' % (float(treatment[0])+273.) # temp in kelvin

                if treatment[1]==0:
                    LT="LT-T-Z"
                    MagRec["treatment_dc_field"]="0"
                    MagRec["treatment_dc_field_phi"]='0'
                    MagRec["treatment_dc_field_theta"]='0'
                else:
                    if treatment[1]==7: # alteration check as final measurement
                            LT="LT-PTRM-I"
                    else:
                            LT="LT-T-I"
                    MagRec["treatment_dc_field"]='%8.3e'%(labfield)
                    MagRec["treatment_dc_field_phi"]='%7.1f' % (labfield_phi) # labfield phi
                    MagRec["treatment_dc_field_theta"]='%7.1f' % (labfield_theta) # labfield theta

                    indx=int(treatment[1])-1
                    # alteration check matjed as 0.7 in the measurement file
                    if indx==6:
                        cooling_time= cooling_times_list[-1]
                    else:
                        cooling_time=cooling_times_list[indx]
                    MagRec["measurement_description"]="cooling_rate"+":"+cooling_time+":"+"K/min"

            #---------------------
            # Lab treatment and lab protocoal for NLT experiment
            #---------------------

            elif 'NLT' in experiment :
                print("Dont support yet NLT rate experiment file. Contact rshaar@ucsd.edu")

            #---------------------
            # magic_method_codes for this measurement only
            # LP will be fixed after all measurement lines are read
            #---------------------

            MagRec["magic_method_codes"]=LT+":"+LP

            #---------------------
            # Demag experiments only:
            # search if orientation data exists in er_samples.txt
            # if not: create one and save
            #---------------------

            # see if core azimuth and tilt-corrected data are in er_samples.txt
            sample=MagRec["er_sample_name"]
            found_sample_azimuth,found_sample_dip,found_sample_bed_dip_direction,found_sample_bed_dip=False,False,False,False
            if sample in list(er_sample_data.keys()):
                if "sample_azimuth" in list(er_sample_data[sample].keys()) and er_sample_data[sample]['sample_azimuth'] !="":
                    sample_azimuth=float(er_sample_data[sample]['sample_azimuth'])
                    found_sample_azimuth=True
                if "sample_dip" in list(er_sample_data[sample].keys()) and er_sample_data[sample]['sample_dip']!="":
                    sample_dip=float(er_sample_data[sample]['sample_dip'])
                    found_sample_dip=True
                if "sample_bed_dip_direction" in list(er_sample_data[sample].keys()) and er_sample_data[sample]['sample_bed_dip_direction']!="":
                    sample_bed_dip_direction=float(er_sample_data[sample]['sample_bed_dip_direction'])
                    found_sample_bed_dip_direction=True
                if "sample_bed_dip" in list(er_sample_data[sample].keys()) and er_sample_data[sample]['sample_bed_dip']!="":
                    sample_bed_dip=float(er_sample_data[sample]['sample_bed_dip'])
                    found_sample_bed_dip=True
            else:
                er_sample_data[sample]={}

            #--------------------
            # deal with specimen orientation and different coordinate system
            #--------------------

            found_s,found_geo,found_tilt=False,False,False
            if "dec_s" in list(meas_line.keys()) and "inc_s" in list(meas_line.keys()):
                if meas_line["dec_s"]!="" and meas_line["inc_s"]!="":
                    found_s=True
                MagRec["measurement_dec"]=meas_line["dec_s"]
                MagRec["measurement_inc"]=meas_line["inc_s"]
            if "dec_g" in list(meas_line.keys()) and "inc_g" in list(meas_line.keys()):
                if meas_line["dec_g"]!="" and meas_line["inc_g"]!="":
                    found_geo=True
            if "dec_t" in list(meas_line.keys()) and "inc_t" in list(meas_line.keys()):
                if meas_line["dec_t"]!="" and meas_line["inc_t"]!="":
                    found_tilt=True

            #-----------------------------
            # specimen coordinates: no
            # geographic coordinates: yes
            #-----------------------------

            if found_geo and not found_s:
                MagRec["measurement_dec"]=meas_line["dec_g"]
                MagRec["measurement_inc"]=meas_line["inc_g"]

                # core azimuth/plunge is not in er_samples.txt
                if not found_sample_dip or not found_sample_azimuth:
                    er_sample_data[sample]['sample_azimuth']="0"
                    er_sample_data[sample]['sample_dip']="0"

                # core azimuth/plunge is in er_samples.txt
                else:
                    sample_azimuth=float(er_sample_data[sample]['sample_azimuth'])
                    sample_dip=float(er_sample_data[sample]['sample_dip'])
                    if sample_azimuth!=0 and sample_dip!=0:
                        print("-W- WARNING: delete core azimuth/plunge in er_samples.txt\n\
                        becasue dec_s and inc_s are unavaialable")

            #-----------------------------
            # specimen coordinates: no
            # geographic coordinates: no
            #-----------------------------
            if not found_geo and not found_s:
                print("-E- ERROR: sample %s does not have dec_s/inc_s or dec_g/inc_g. Ignore specimen %s "%(sample,specimen))
                break

            #-----------------------------
            # specimen coordinates: yes
            # geographic coordinates: yes
            #
            # commant: Ron, this need to be tested !!
            #-----------------------------
            if found_geo and found_s:

                cdec,cinc=float(meas_line["dec_s"]),float(meas_line["inc_s"])
                gdec,ginc=float(meas_line["dec_g"]),float(meas_line["inc_g"])
                az,pl=pmag.get_azpl(cdec,cinc,gdec,ginc)

                # core azimuth/plunge is not in er_samples.txt:
                # calculate core az/pl and add it to er_samples.txt
                if not found_sample_dip or not found_sample_azimuth:
                    er_sample_data[sample]['sample_azimuth']="%.1f"%az
                    er_sample_data[sample]['sample_dip']="%.1f"%pl

                # core azimuth/plunge is in er_samples.txt
                else:
                    if float(er_sample_data[sample]['sample_azimuth'])!= az:
                        print("-E- ERROR in sample_azimuth sample %s. Check it! using the value in er_samples.txt"%sample)

                    if float(er_sample_data[sample]['sample_dip'])!= pl:
                        print("-E- ERROR in sample_dip sample %s. Check it! using the value in er_samples.txt"%sample)

            #-----------------------------
            # specimen coordinates: yes
            # geographic coordinates: no
            #-----------------------------
            if not found_geo and found_s:
                if found_sample_dip and found_sample_azimuth:
                    pass
                    # (nothing to do)
                else:
                    if "Demag" in experiment:
                        print("-W- WARNING: missing sample_dip or sample_azimuth for sample %s"%sample)

            #-----------------------------
            # tilt-corrected coordinates: yes
            # geographic coordinates: no
            #-----------------------------
            if found_tilt and not found_geo:
                    print("-E- ERROR: missing geographic data for sample %s. Ignoring tilt-corrected data "%sample)
            if found_tilt and found_geo:
                dec_geo,inc_geo=float(meas_line["dec_g"]),float(meas_line["inc_g"])
                dec_tilt,inc_tilt=float(meas_line["dec_t"]),float(meas_line["inc_t"])
                if dec_geo==dec_tilt and inc_geo==inc_tilt:
                    DipDir,Dip=0.,0.
                else:
                    DipDir,Dip=pmag.get_tilt(dec_geo,inc_geo,dec_tilt,inc_tilt)

                if not found_sample_bed_dip_direction or not found_sample_bed_dip:
                    print("-I- calculating dip and dip direction used for tilt correction sample %s. results are put in er_samples.txt"%sample)
                    er_sample_data[sample]['sample_bed_dip_direction']="%.1f"%DipDir
                    er_sample_data[sample]['sample_bed_dip']="%.1f"%Dip

            #-----------------------------
            # er_samples method codes
            # geographic coordinates: no
            #-----------------------------
            if found_tilt or found_geo:
                er_sample_data[sample]['magic_method_codes']="SO-NO"

            #-----------------
            # er_samples_data
            #-----------------
            if sample in list(er_sample_data.keys()):
                er_sample_data[sample]['er_sample_name']=sample
                er_sample_data[sample]['er_site_name']=MagRec["er_site_name"]
                er_sample_data[sample]['er_location_name']=MagRec["er_location_name"]

            #MagRec["magic_method_codes"]=LT
            MagRecs_this_specimen.append(MagRec)

            #if LP!="" and LP not in LP_this_specimen:
            #    LP_this_specimen.append(LP)

            measurement_running_number+=1
            #-------

        #-------
        # after reading all the measurements lines for this specimen
        # 1) add magic_experiment_name
        # 2) fix magic_method_codes with the correct lab protocol
        #-------
        LP_this_specimen=[]
        for MagRec in MagRecs_this_specimen:
            magic_method_codes=MagRec["magic_method_codes"].split(":")
            for code in magic_method_codes:
                if "LP" in code and code not in LP_this_specimen:
                    LP_this_specimen.append(code)
        # check IZ/ZI/IZZI
        if "LP-PI-ZI" in   LP_this_specimen and "LP-PI-IZ" in   LP_this_specimen:
            LP_this_specimen.remove("LP-PI-ZI")
            LP_this_specimen.remove("LP-PI-IZ")
            LP_this_specimen.append("LP-PI-BT-IZZI")

        # add the right LP codes and fix experiment name
        for MagRec in MagRecs_this_specimen:
            MagRec["magic_experiment_name"]=MagRec["er_specimen_name"]+":"+":".join(LP_this_specimen)
            magic_method_codes=MagRec["magic_method_codes"].split(":")
            LT=""
            for code in magic_method_codes:
                if code[:3]=="LT-":
                    LT=code;
                    break
            MagRec["magic_method_codes"]=LT+":"+":".join(LP_this_specimen)

            MagRecs.append(MagRec)

    #--
    # write magic_measurements.txt
    #--
    MagRecs_fixed=merge_pmag_recs(MagRecs)
    pmag.magic_write(meas_file,MagRecs_fixed,'magic_measurements')
    print("-I- MagIC file is saved in  %s"%meas_file)

    #--
    # write er_samples.txt
    #--
    ErSamplesRecs=[]
    samples=list(er_sample_data.keys())
    samples.sort()
    for sample in samples:
        ErSamplesRecs.append(er_sample_data[sample])
    ErSamplesRecs_fixed=merge_pmag_recs(ErSamplesRecs)
    pmag.magic_write(samp_file,ErSamplesRecs_fixed,'er_samples')
    return True, meas_file

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


Instruction:
Implement a Python 3 function for
loading the data from a file.

Response:
def loadData(filePath=None):
    '''
    #====================================================================
    in:
    read measured raw data file,
    search the line ['    Field       Remanence  '] in measured data file,
    skip all the rows above and the last line,
    otherwise, load data as two columns.
    #
    out:
    rawDf,fitDf are the pandas dataframe of measured raw data, and the
    log10 interploted data
    #====================================================================
    '''
    skip_from = '    Field       Remanence  '
    with open(filePath,'rb') as fr:
        #f = fr.read()
        for i,line in enumerate(fr,1):
            #print(line)
            if skip_from in str(line):
                skiprows=i+2
                break
            else:
                skiprows=None
    skiprows = skiprows if isinstance(skiprows,int) else 1
    rawDf = pd.read_csv(filePath, sep='\s+', delimiter=',', names=['field','remanance'],
                        dtype=np.float64, skiprows=skiprows, skipfooter=1,engine='python')
    rawDf = rawDf[(rawDf['field']>0)]
    rawDf = rawDf.sort_values(by=['field'])
    rawDf['field'] = rawDf['field']*10**3 # mT to # T
    y_measure=rawDf['remanance']
    rawDf = rawDf[(rawDf['field']>=2)]
    rawDf['field_log'] = np.log10(rawDf['field'])
    rawDf['rem_gradient'] = np.gradient(rawDf['remanance'])
    rawDf['rem_grad_norm'] = rawDf['rem_gradient']/rawDf['rem_gradient'].max()
    field_fit = np.linspace(np.log10(rawDf['field'].min()),
                            np.log10(rawDf['field'].max()), 100)
    y_gradient = interpolate.splev(field_fit,
                                   interpolate.splrep(np.log10(rawDf['field']),
                                   np.gradient(rawDf['remanance'])))
    fitDf = pd.DataFrame({'field':field_fit,'remanance':y_gradient})
    fitDf.remanance[fitDf.remanance<=0] = 10**-15
    return rawDf,fitDf


Instruction:
Explain what the following Python 3 code does
def fit_plots(ax,xfit,xraw,yfit,yraw):
    '''
    #====================================================================
    plot the fitted results for data fit and refit
    #====================================================================
    '''
    global _yfits_
    _yfits_ = yfit
    ax.plot(xfit, yfit)
    ax.plot(xfit, np.sum(yfit,axis=1))
    ax.scatter(xraw, yraw)
    ax.set_xlabel('Field (log10(mT))')
    ax.set_ylabel('IRM normalization')

Response:
Plots fitted data fit and refit
    plots


Instruction:
How would you code a function in Python 3 to
name VIRTUAL_BASENAME DESCRIPTION draws N directions from uniform distribution on a sphere SYNTAX - h prints help message and quits VIRTUAL_BASENAME default is 100

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

    DESCRIPTION
        draws N directions from uniform distribution on a sphere

    SYNTAX
        uniform.py [-h][command line options]
        -h prints help message and quits
        -n N, specify N on the command line (default is 100)
        -F file, specify output file name, default is standard output
    """
    outf=""
    N=100
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        outf=sys.argv[ind+1]
    if outf!="": out=open(outf,'w')
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        N=int(sys.argv[ind+1])
    dirs=pmag.get_unf(N)
    if outf=='':
        for dir in dirs:
            print('%7.1f %7.1f'%(dir[0],dir[1]))
    else:
        numpy.savetxt(outf,dirs,fmt='%7.1f %7.1f')