Instruction:
Can you create a Python 3 function that
sorts data block in to first_Z, first_I, etc.

Response:
def sortarai(self, datablock, s, Zdiff):
        """
        sorts data block in to first_Z, first_I, etc.
        """

        first_Z, first_I, zptrm_check, ptrm_check, ptrm_tail = [], [], [], [], []
        field, phi, theta = "", "", ""
        starthere = 0
        Treat_I, Treat_Z, Treat_PZ, Treat_PI, Treat_M, Treat_AC = [], [], [], [], [], []
        ISteps, ZSteps, PISteps, PZSteps, MSteps, ACSteps = [], [], [], [], [], []
        GammaChecks = []  # comparison of pTRM direction acquired and lab field
        Mkeys = ['measurement_magn_moment', 'measurement_magn_volume',
                 'measurement_magn_mass', 'measurement_magnitude']
        rec = datablock[0]
        for key in Mkeys:
            if key in list(rec.keys()) and rec[key] != "":
                momkey = key
                break
    # first find all the steps
        for k in range(len(datablock)):
            rec = datablock[k]
            if "treatment_temp" in list(rec.keys()) and rec["treatment_temp"] != "":
                temp = float(rec["treatment_temp"])
                THERMAL = True
                MICROWAVE = False
            elif "treatment_mw_power" in list(rec.keys()) and rec["treatment_mw_power"] != "":
                THERMAL = False
                MICROWAVE = True
                if "measurement_description" in list(rec.keys()):
                    MW_step = rec["measurement_description"].strip(
                        '\n').split(":")
                    for STEP in MW_step:
                        if "Number" in STEP:
                            temp = float(STEP.split("-")[-1])

            methcodes = []
            tmp = rec["magic_method_codes"].split(":")
            for meth in tmp:
                methcodes.append(meth.strip())
            # for thellier-thellier
            if 'LT-T-I' in methcodes and 'LP-PI-TRM' in methcodes and 'LP-TRM' not in methcodes:
                Treat_I.append(temp)
                ISteps.append(k)
                if field == "":
                    field = float(rec["treatment_dc_field"])
                if phi == "":
                    phi = float(rec['treatment_dc_field_phi'])
                    theta = float(rec['treatment_dc_field_theta'])

            # for Microwave
            if 'LT-M-I' in methcodes and 'LP-PI-M' in methcodes:
                Treat_I.append(temp)
                ISteps.append(k)
                if field == "":
                    field = float(rec["treatment_dc_field"])
                if phi == "":
                    phi = float(rec['treatment_dc_field_phi'])
                    theta = float(rec['treatment_dc_field_theta'])

    # stick  first zero field stuff into first_Z
            if 'LT-NO' in methcodes:
                Treat_Z.append(temp)
                ZSteps.append(k)
            if "LT-AF-Z" in methcodes and 'treatment_ac_field' in list(rec.keys()):
                if rec['treatment_ac_field'] != "":
                    AFD_after_NRM = True
                    # consider AFD before T-T experiment ONLY if it comes before
                    # the experiment
                    for i in range(len(first_I)):
                        # check if there was an infield step before the AFD
                        if float(first_I[i][3]) != 0:
                            AFD_after_NRM = False
                        if AFD_after_NRM:
                            AF_field = 0
                            if 'treatment_ac_field' in rec:
                                try:
                                    AF_field = float(rec['treatment_ac_field']) * 1000
                                except ValueError:
                                    pass

                            dec = float(rec["measurement_dec"])
                            inc = float(rec["measurement_inc"])
                            intensity = float(rec[momkey])
                            first_I.append([273. - AF_field, 0., 0., 0., 1])
                            first_Z.append(
                                [273. - AF_field, dec, inc, intensity, 1])  # NRM step
            if 'LT-T-Z' in methcodes or 'LT-M-Z' in methcodes:
                Treat_Z.append(temp)
                ZSteps.append(k)
            if 'LT-PTRM-Z':
                Treat_PZ.append(temp)
                PZSteps.append(k)
            if 'LT-PTRM-I' in methcodes or 'LT-PMRM-I' in methcodes:
                Treat_PI.append(temp)
                PISteps.append(k)
            if 'LT-PTRM-MD' in methcodes or 'LT-PMRM-MD' in methcodes:
                Treat_M.append(temp)
                MSteps.append(k)
            if 'LT-PTRM-AC' in methcodes or 'LT-PMRM-AC' in methcodes:
                Treat_AC.append(temp)
                ACSteps.append(k)
            if 'LT-NO' in methcodes:
                dec = float(rec["measurement_dec"])
                inc = float(rec["measurement_inc"])
                moment = float(rec["measurement_magn_moment"])
                if 'LP-PI-M' not in methcodes:
                    first_I.append([273, 0., 0., 0., 1])
                    first_Z.append([273, dec, inc, moment, 1])  # NRM step
                else:
                    first_I.append([0, 0., 0., 0., 1])
                    first_Z.append([0, dec, inc, moment, 1])  # NRM step

        #---------------------
        # find  IZ and ZI
        #---------------------

        for temp in Treat_I:  # look through infield steps and find matching Z step
            if temp in Treat_Z:  # found a match
                istep = ISteps[Treat_I.index(temp)]
                irec = datablock[istep]
                methcodes = []
                tmp = irec["magic_method_codes"].split(":")
                for meth in tmp:
                    methcodes.append(meth.strip())
                # take last record as baseline to subtract
                brec = datablock[istep - 1]
                zstep = ZSteps[Treat_Z.index(temp)]
                zrec = datablock[zstep]
        # sort out first_Z records
                # check if ZI/IZ in in method codes:
                ZI = ""
                if "LP-PI-TRM-IZ" in methcodes or "LP-PI-M-IZ" in methcodes or "LP-PI-IZ" in methcodes:
                    ZI = 0
                elif "LP-PI-TRM-ZI" in methcodes or "LP-PI-M-ZI" in methcodes or "LP-PI-ZI" in methcodes:
                    ZI = 1
                elif "LP-PI-BT-IZZI" in methcodes:
                    ZI == ""
                    i_intex, z_intex = 0, 0
                    foundit = False
                    for i in range(len(datablock)):
                        if THERMAL:
                            if ('treatment_temp' in list(datablock[i].keys()) and float(temp) == float(datablock[i]['treatment_temp'])):
                                foundit = True
                        if MICROWAVE:
                            if ('measurement_description' in list(datablock[i].keys())):
                                MW_step = datablock[i]["measurement_description"].strip(
                                    '\n').split(":")
                                for STEP in MW_step:
                                    if "Number" in STEP:
                                        ThisStep = float(STEP.split("-")[-1])
                                        if ThisStep == float(temp):
                                            foundit = True
                        if foundit:
                            if "LT-T-Z" in datablock[i]['magic_method_codes'].split(":") or "LT-M-Z" in datablock[i]['magic_method_codes'].split(":"):
                                z_intex = i
                            if "LT-T-I" in datablock[i]['magic_method_codes'].split(":") or "LT-M-I" in datablock[i]['magic_method_codes'].split(":"):
                                i_intex = i
                            foundit = False

                    if z_intex < i_intex:
                        ZI = 1
                    else:
                        ZI = 0
                dec = float(zrec["measurement_dec"])
                inc = float(zrec["measurement_inc"])
                str = float(zrec[momkey])
                first_Z.append([temp, dec, inc, str, ZI])
        # sort out first_I records
                idec = float(irec["measurement_dec"])
                iinc = float(irec["measurement_inc"])
                istr = float(irec[momkey])
                X = pmag.dir2cart([idec, iinc, istr])
                BL = pmag.dir2cart([dec, inc, str])
                I = []
                for c in range(3):
                    I.append((X[c] - BL[c]))
                if I[2] != 0:
                    iDir = pmag.cart2dir(I)
                    if Zdiff == 0:
                        first_I.append([temp, iDir[0], iDir[1], iDir[2], ZI])
                    else:
                        first_I.append([temp, 0., 0., I[2], ZI])
# gamma=angle([iDir[0],iDir[1]],[phi,theta])
                else:
                    first_I.append([temp, 0., 0., 0., ZI])
# gamma=0.0
# put in Gamma check (infield trm versus lab field)
# if 180.-gamma<gamma:
# gamma=180.-gamma
# GammaChecks.append([temp-273.,gamma])

        #---------------------
        # find Thellier Thellier protocol
        #---------------------
        if 'LP-PI-II'in methcodes or 'LP-PI-T-II' in methcodes or 'LP-PI-M-II' in methcodes:
            # look through infield steps and find matching Z step
            for i in range(1, len(Treat_I)):
                if Treat_I[i] == Treat_I[i - 1]:
                    # ignore, if there are more than
                    temp = Treat_I[i]
                    irec1 = datablock[ISteps[i - 1]]
                    dec1 = float(irec1["measurement_dec"])
                    inc1 = float(irec1["measurement_inc"])
                    moment1 = float(irec1["measurement_magn_moment"])
                    if len(first_I) < 2:
                        dec_initial = dec1
                        inc_initial = inc1
                    cart1 = np.array(pmag.dir2cart([dec1, inc1, moment1]))
                    irec2 = datablock[ISteps[i]]
                    dec2 = float(irec2["measurement_dec"])
                    inc2 = float(irec2["measurement_inc"])
                    moment2 = float(irec2["measurement_magn_moment"])
                    cart2 = np.array(pmag.dir2cart([dec2, inc2, moment2]))

                    # check if its in the same treatment
                    if Treat_I[i] == Treat_I[i - 2] and dec2 != dec_initial and inc2 != inc_initial:
                        continue
                    if dec1 != dec2 and inc1 != inc2:
                        zerofield = (cart2 + cart1) / 2
                        infield = (cart2 - cart1) / 2

                        DIR_zerofield = pmag.cart2dir(zerofield)
                        DIR_infield = pmag.cart2dir(infield)

                        first_Z.append(
                            [temp, DIR_zerofield[0], DIR_zerofield[1], DIR_zerofield[2], 0])
                        first_I.append(
                            [temp, DIR_infield[0], DIR_infield[1], DIR_infield[2], 0])

        #---------------------
        # find  pTRM checks
        #---------------------

        for i in range(len(Treat_PI)):  # look through infield steps and find matching Z step

            temp = Treat_PI[i]
            k = PISteps[i]
            rec = datablock[k]
            dec = float(rec["measurement_dec"])
            inc = float(rec["measurement_inc"])
            moment = float(rec["measurement_magn_moment"])
            phi = float(rec["treatment_dc_field_phi"])
            theta = float(rec["treatment_dc_field_theta"])
            M = np.array(pmag.dir2cart([dec, inc, moment]))

            foundit = False
            if 'LP-PI-II' not in methcodes:
                    # Important: suport several pTRM checks in a row, but
                    # does not support pTRM checks after infield step
                for j in range(k, 1, -1):
                    if "LT-M-I" in datablock[j]['magic_method_codes'] or "LT-T-I" in datablock[j]['magic_method_codes']:
                        after_zerofield = 0.
                        foundit = True
                        prev_rec = datablock[j]
                        zerofield_index = j
                        break
                    if float(datablock[j]['treatment_dc_field']) == 0:
                        after_zerofield = 1.
                        foundit = True
                        prev_rec = datablock[j]
                        zerofield_index = j
                        break
            else:  # Thellier-Thellier protocol
                foundit = True
                prev_rec = datablock[k - 1]
                zerofield_index = k - 1

            if foundit:
                prev_dec = float(prev_rec["measurement_dec"])
                prev_inc = float(prev_rec["measurement_inc"])
                prev_moment = float(prev_rec["measurement_magn_moment"])
                prev_phi = float(prev_rec["treatment_dc_field_phi"])
                prev_theta = float(prev_rec["treatment_dc_field_theta"])
                prev_M = np.array(pmag.dir2cart(
                    [prev_dec, prev_inc, prev_moment]))

                if 'LP-PI-II' not in methcodes:
                    diff_cart = M - prev_M
                    diff_dir = pmag.cart2dir(diff_cart)
                    if after_zerofield == 0:
                        ptrm_check.append(
                            [temp, diff_dir[0], diff_dir[1], diff_dir[2], zerofield_index, after_zerofield])
                    else:
                        ptrm_check.append(
                            [temp, diff_dir[0], diff_dir[1], diff_dir[2], zerofield_index, after_zerofield])
                else:
                    # health check for T-T protocol:
                    if theta != prev_theta:
                        diff = (M - prev_M) / 2
                        diff_dir = pmag.cart2dir(diff)
                        ptrm_check.append(
                            [temp, diff_dir[0], diff_dir[1], diff_dir[2], zerofield_index, ""])
                    else:
                        print(
                            "-W- WARNING: specimen. pTRM check not in place in Thellier Thellier protocol. step please check")

        #---------------------
        # find Tail checks
        #---------------------

        for temp in Treat_M:
            # print temp
            step = MSteps[Treat_M.index(temp)]
            rec = datablock[step]
            dec = float(rec["measurement_dec"])
            inc = float(rec["measurement_inc"])
            moment = float(rec["measurement_magn_moment"])
            foundit = False
            for i in range(1, len(datablock)):
                if 'LT-T-Z' in datablock[i]['magic_method_codes'] or 'LT-M-Z' in datablock[i]['magic_method_codes']:
                    if (THERMAL and "treatment_temp" in list(datablock[i].keys()) and float(datablock[i]["treatment_temp"]) == float(temp))\
                       or (MICROWAVE and "measurement_description" in list(datablock[i].keys()) and "Step Number-%.0f" % float(temp) in datablock[i]["measurement_description"]):
                        prev_rec = datablock[i]
                        prev_dec = float(prev_rec["measurement_dec"])
                        prev_inc = float(prev_rec["measurement_inc"])
                        prev_moment = float(
                            prev_rec["measurement_magn_moment"])
                        foundit = True
                        break

            if foundit:
                ptrm_tail.append([temp, 0, 0, moment - prev_moment])

    #
    # final check
    #
        if len(first_Z) != len(first_I):
            print(len(first_Z), len(first_I))
            print(" Something wrong with this specimen! Better fix it or delete it ")
            input(" press return to acknowledge message")

        #---------------------
        # find  Additivity (patch by rshaar)
        #---------------------

        additivity_check = []
        for i in range(len(Treat_AC)):
            step_0 = ACSteps[i]
            temp = Treat_AC[i]
            dec0 = float(datablock[step_0]["measurement_dec"])
            inc0 = float(datablock[step_0]["measurement_inc"])
            moment0 = float(datablock[step_0]['measurement_magn_moment'])
            V0 = pmag.dir2cart([dec0, inc0, moment0])
            # find the infield step that comes before the additivity check
            foundit = False
            for j in range(step_0, 1, -1):
                if "LT-T-I" in datablock[j]['magic_method_codes']:
                    foundit = True
                    break
            if foundit:
                dec1 = float(datablock[j]["measurement_dec"])
                inc1 = float(datablock[j]["measurement_inc"])
                moment1 = float(datablock[j]['measurement_magn_moment'])
                V1 = pmag.dir2cart([dec1, inc1, moment1])
                # print "additivity check: ",s
                # print j
                # print "ACC=V1-V0:"
                # print "V1=",[dec1,inc1,moment1],pmag.dir2cart([dec1,inc1,moment1])/float(datablock[0]["measurement_magn_moment"])
                # print "V1=",pmag.dir2cart([dec1,inc1,moment1])/float(datablock[0]["measurement_magn_moment"])
                # print "V0=",[dec0,inc0,moment0],pmag.dir2cart([dec0,inc0,moment0])/float(datablock[0]["measurement_magn_moment"])
                # print "NRM=",float(datablock[0]["measurement_magn_moment"])
                # print "-------"

                I = []
                for c in range(3):
                    I.append(V1[c] - V0[c])
                dir1 = pmag.cart2dir(I)
                additivity_check.append([temp, dir1[0], dir1[1], dir1[2]])
                # print
                # "I",np.array(I)/float(datablock[0]["measurement_magn_moment"]),dir1,"(dir1
                # unnormalized)"
                X = np.array(I) / \
                    float(datablock[0]["measurement_magn_moment"])
                # print "I",np.sqrt(sum(X**2))
        araiblock = (first_Z, first_I, ptrm_check, ptrm_tail,
                     zptrm_check, GammaChecks, additivity_check)

        return araiblock, field


Instruction:
Can you tell what is the following Python 3 function doing
def main():
    ofile=""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        ofile=sys.argv[ind+1]
        outfile=open(ofile,'w')
    if '-i' in sys.argv:
        cont=1
        while cont==1:
            cart=[]
            try:
                ans=input('X: [ctrl-D  to quit] ')
                cart.append(float(ans))
                ans=input('Y: ')
                cart.append(float(ans))
                ans=input('Z: ')
                cart.append(float(ans))
            except:
                print("\n Good-bye \n")
                sys.exit()
            dir= pmag.cart2dir(cart)  # send dir to dir2cart and spit out result
            print('%7.1f %7.1f %10.3e'%(dir[0],dir[1],dir[2]))
    elif '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        inp=numpy.loadtxt(file) # read from a file
    else:
        inp = numpy.loadtxt(sys.stdin,dtype=numpy.float)  # read from standard input
    dir=pmag.cart2dir(inp)
    if len(dir.shape)==1:
        line=dir
        print('%7.1f %7.1f %10.3e'%(line[0],line[1],line[2]))
        if ofile!="":
           outstring='%7.1f %7.1f %10.8e\n' %(line[0],line[1],line[2])
           outfile.write(outstring)
    else:
        for line in dir:
            print('%7.1f %7.1f %10.3e'%(line[0],line[1],line[2]))
            if ofile!="":
               outstring='%7.1f %7.1f %10.8e\n' %(line[0],line[1],line[2])
               outfile.write(outstring)

Response: NAME get_internal_cart_file is the main function of pmag. get_internal_cart_file.


Instruction:
How would you explain what the following Python 3 function does
def main():
    citation='This study'
    cont=0
    samp_con,Z="1",1
    AniRecSs,AniRecs,SpecRecs,SampRecs,SiteRecs,MeasRecs=[],[],[],[],[],[]
    user,locname,specfile="","unknown","er_specimens.txt"
    isspec,inst,specnum='0',"",0
    spin,new=1,0
    dir_path='.'
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    aoutput,routput,moutput=dir_path+'/rmag_anisotropy.txt',dir_path+'/rmag_results.txt',dir_path+'/magic_measurements.txt'
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-usr' in sys.argv:
        ind=sys.argv.index('-usr')
        user=sys.argv[ind+1]
    if "-ncn" in sys.argv:
        ind=sys.argv.index("-ncn")
        samp_con=sys.argv[ind+1]
        if "4" in samp_con:
            if "-" not in samp_con:
                print("option [4] must be in form 4-Z where Z is an integer")
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="4"
        if "7" in samp_con:
            if "-" not in samp_con:
                print("option [7] must be in form 7-Z where Z is an integer")
                sys.exit()
            else:
                Z=samp_con.split("-")[1]
                samp_con="7"
    if '-k15' in sys.argv:spin=0
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        ascfile=dir_path+'/'+sys.argv[ind+1]
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        moutput=dir_path+'/'+sys.argv[ind+1]
    if '-Fa' in sys.argv:
        ind=sys.argv.index('-Fa')
        aoutput=dir_path+'/'+sys.argv[ind+1]
    if '-Fr' in sys.argv:
        ind=sys.argv.index('-Fr')
        routput=dir_path+'/'+sys.argv[ind+1]
    if '-Fs' in sys.argv:
        ind=sys.argv.index('-Fs')
        specfile=dir_path+'/'+sys.argv[ind+1]
        isspec='1'
    elif '-loc' in sys.argv:
        ind=sys.argv.index('-loc')
        locname=sys.argv[ind+1]
    if '-spc' in sys.argv:
        ind=sys.argv.index('-spc')
        specnum=-(int(sys.argv[ind+1]))
        if specnum!=0:specnum=-specnum
    if isspec=="1":
        specs,file_type=pmag.magic_read(specfile)
    specnames,sampnames,sitenames=[],[],[]
    if '-new' not in sys.argv: # see if there are already specimen,sample, site files lying around
        try:
            SpecRecs,file_type=pmag.magic_read(dir_path+'/er_specimens.txt')
            for spec in SpecRecs:
                if spec['er_specimen_name'] not in specnames:specnames.append(samp['er_specimen_name'])
        except:
            SpecRecs,specs=[],[]
        try:
            SampRecs,file_type=pmag.magic_read(dir_path+'/er_samples.txt')
            for samp in SampRecs:
                if samp['er_sample_name'] not in sampnames:sampnames.append(samp['er_sample_name'])
        except:
            sampnames,SampRecs=[],[]
        try:
            SiteRecs,file_type=pmag.magic_read(dir_path+'/er_sites.txt')
            for site in SiteRecs:
                if site['er_site_names'] not in sitenames:sitenames.append(site['er_site_name'])
        except:
            sitenames,SiteRecs=[],[]
    try:
        input=open(ascfile,'r')
    except:
        print('Error opening file: ', ascfile)
    Data=input.readlines()
    k=0
    while k<len(Data):
        line = Data[k]
        words=line.split()
        if "ANISOTROPY" in words: # first line of data for the spec
            MeasRec,AniRec,SpecRec,SampRec,SiteRec={},{},{},{},{}
            specname=words[0]
            AniRec['er_specimen_name']=specname
            if isspec=="1":
                for spec in specs:
                    if spec['er_specimen_name']==specname:
                        AniRec['er_sample_name']=spec['er_sample_name']
                        AniRec['er_site_name']=spec['er_site_name']
                        AniRec['er_location_name']=spec['er_location_name']
                        break
            elif isspec=="0":
                if specnum!=0:
                    sampname=specname[:specnum]
                else:
                    sampname=specname
                AniRec['er_sample_name']=sampname
                SpecRec['er_specimen_name']=specname
                SpecRec['er_sample_name']=sampname
                SampRec['er_sample_name']=sampname
                SiteRec['er_sample_name']=sampname
                SiteRec['site_description']='s'
                AniRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
                SpecRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
                SampRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
                SiteRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
                AniRec['er_location_name']=locname
                SpecRec['er_location_name']=locname
                SampRec['er_location_name']=locname
                SiteRec['er_location_name']=locname
                AniRec['er_citation_names']="This study"
                SpecRec['er_citation_names']="This study"
                SampRec['er_citation_names']="This study"
                SiteRec['er_citation_names']="This study"
            AniRec['er_citation_names']="This study"
            AniRec['magic_instrument_codes']=inst
            AniRec['magic_method_codes']="LP-X:AE-H:LP-AN-MS"
            AniRec['magic_experiment_names']=specname+":"+"LP-AN-MS"
            AniRec['er_analyst_mail_names']=user
            for key in list(AniRec.keys()):MeasRec[key]=AniRec[key]
            MeasRec['measurement_flag']='g'
            AniRec['anisotropy_flag']='g'
            MeasRec['measurement_standard']='u'
            MeasRec['measurement_description']='Bulk sucsecptibility measurement'
            AniRec['anisotropy_type']="AMS"
            AniRec['anisotropy_unit']="Normalized by trace"
            if spin==1:
                AniRec['anisotropy_n']="192"
            else:
                AniRec['anisotropy_n']="15"
        if 'Azi' in words and isspec=='0':
            SampRec['sample_azimuth']=words[1]
            labaz=float(words[1])
        if 'Dip' in words:
            SampRec['sample_dip']='%7.1f'%(-float(words[1]))
            SpecRec['specimen_vol']='%8.3e'%(float(words[10])*1e-6) # convert actual volume to m^3 from cm^3
            labdip=float(words[1])
        if 'T1' in words and 'F1' in words:
            k+=2 # read in fourth line down
            line=Data[k]
            rec=line.split()
            dd=rec[1].split('/')
            dip_direction=int(dd[0])+90
            SampRec['sample_bed_dip_direction']='%i'%(dip_direction)
            SampRec['sample_bed_dip']=dd[1]
            bed_dip=float(dd[1])
        if "Mean" in words:
            k+=4 # read in fourth line down
            line=Data[k]
            rec=line.split()
            MeasRec['measurement_chi_volume']=rec[1]
            sigma=.01*float(rec[2])/3.
            AniRec['anisotropy_sigma']='%7.4f'%(sigma)
            AniRec['anisotropy_unit']='SI'
        if "factors" in words:
            k+=4 # read in second line down
            line=Data[k]
            rec=line.split()
        if "Specimen" in words:  # first part of specimen data
            AniRec['anisotropy_s1']='%7.4f'%(old_div(float(words[5]),3.)) # eigenvalues sum to unity - not 3
            AniRec['anisotropy_s2']='%7.4f'%(old_div(float(words[6]),3.))
            AniRec['anisotropy_s3']='%7.4f'%(old_div(float(words[7]),3.))
            k+=1
            line=Data[k]
            rec=line.split()
            AniRec['anisotropy_s4']='%7.4f'%(old_div(float(rec[5]),3.)) # eigenvalues sum to unity - not 3
            AniRec['anisotropy_s5']='%7.4f'%(old_div(float(rec[6]),3.))
            AniRec['anisotropy_s6']='%7.4f'%(old_div(float(rec[7]),3.))
            AniRec['anisotropy_tilt_correction']='-1'
            AniRecs.append(AniRec)
            AniRecG,AniRecT={},{}
            for key in list(AniRec.keys()):AniRecG[key]=AniRec[key]
            for key in list(AniRec.keys()):AniRecT[key]=AniRec[key]
            sbar=[]
            sbar.append(float(AniRec['anisotropy_s1']))
            sbar.append(float(AniRec['anisotropy_s2']))
            sbar.append(float(AniRec['anisotropy_s3']))
            sbar.append(float(AniRec['anisotropy_s4']))
            sbar.append(float(AniRec['anisotropy_s5']))
            sbar.append(float(AniRec['anisotropy_s6']))
            sbarg=pmag.dosgeo(sbar,labaz,labdip)
            AniRecG["anisotropy_s1"]='%12.10f'%(sbarg[0])
            AniRecG["anisotropy_s2"]='%12.10f'%(sbarg[1])
            AniRecG["anisotropy_s3"]='%12.10f'%(sbarg[2])
            AniRecG["anisotropy_s4"]='%12.10f'%(sbarg[3])
            AniRecG["anisotropy_s5"]='%12.10f'%(sbarg[4])
            AniRecG["anisotropy_s6"]='%12.10f'%(sbarg[5])
            AniRecG["anisotropy_tilt_correction"]='0'
            AniRecs.append(AniRecG)
            if bed_dip!="" and bed_dip!=0: # have tilt correction
                sbart=pmag.dostilt(sbarg,dip_direction,bed_dip)
                AniRecT["anisotropy_s1"]='%12.10f'%(sbart[0])
                AniRecT["anisotropy_s2"]='%12.10f'%(sbart[1])
                AniRecT["anisotropy_s3"]='%12.10f'%(sbart[2])
                AniRecT["anisotropy_s4"]='%12.10f'%(sbart[3])
                AniRecT["anisotropy_s5"]='%12.10f'%(sbart[4])
                AniRecT["anisotropy_s6"]='%12.10f'%(sbart[5])
                AniRecT["anisotropy_tilt_correction"]='100'
                AniRecs.append(AniRecT)
            MeasRecs.append(MeasRec)
            if SpecRec['er_specimen_name'] not in specnames:
                SpecRecs.append(SpecRec)
                specnames.append(SpecRec['er_specimen_name'])
            if SampRec['er_sample_name'] not in sampnames:
                SampRecs.append(SampRec)
                sampnames.append(SampRec['er_sample_name'])
            if SiteRec['er_site_name'] not in sitenames:
                SiteRecs.append(SiteRec)
                sitenames.append(SiteRec['er_site_name'])
        k+=1 # skip to next specimen
    pmag.magic_write(aoutput,AniRecs,'rmag_anisotropy')
    print("anisotropy tensors put in ",aoutput)
    pmag.magic_write(moutput,MeasRecs,'magic_measurements')
    print("bulk measurements put in ",moutput)
    if isspec=="0":
        SpecOut,keys=pmag.fillkeys(SpecRecs)
        output=dir_path+"/er_specimens.txt"
        pmag.magic_write(output,SpecOut,'er_specimens')
        print("specimen info put in ",output)
        output=dir_path+"/er_samples.txt"
        SampOut,keys=pmag.fillkeys(SampRecs)
        pmag.magic_write(output,SampOut,'er_samples')
        print("sample info put in ",output)
        output=dir_path+"/er_sites.txt"
        SiteOut,keys=pmag.fillkeys(SiteRecs)
        pmag.magic_write(output,SiteOut,'er_sites')
        print("site info put in ",output)
    print(""""
         You can now import your data into the Magic Console and complete data entry,
         for example the site locations, lithologies, etc. plotting can be done with aniso_magic.py
    """)

Response: This function is the main entry point for the magic file system. It is the main entry point for the magic file system.


Instruction:
Write a Python 3 script for
naming is the main function for the histplot. py script.

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

    DESCRIPTION
       makes histograms for data

    OPTIONS
       -h prints help message and quits
       -f input file name
       -b binsize
       -fmt [svg,png,pdf,eps,jpg] specify format for image, default is svg
       -sav save figure and quit
       -F output file name, default is hist.fmt
       -N don't normalize
       -twin plot both normalized and un-normalized y axes
       -xlab Label of X axis
       -ylab Label of Y axis

    INPUT FORMAT
        single variable

    SYNTAX
       histplot.py [command line options] [<file]

    """
    save_plots = False
    if '-sav' in sys.argv:
        save_plots = True
        interactive = False

    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    fmt = pmag.get_named_arg('-fmt', 'svg')
    fname = pmag.get_named_arg('-f', '')
    outfile = pmag.get_named_arg("-F", "")
    norm = 1
    if '-N' in sys.argv:
        norm = 0
    if '-twin' in sys.argv:
        norm = - 1
    binsize = pmag.get_named_arg('-b', 0)
    if '-xlab' in sys.argv:
        ind = sys.argv.index('-xlab')
        xlab = sys.argv[ind+1]
    else:
        xlab = 'x'
    data = []
    if not fname:
        print('-I- Trying to read from stdin... <ctrl>-c to quit')
        data = np.loadtxt(sys.stdin, dtype=np.float)

    ipmag.histplot(fname, data, outfile, xlab, binsize, norm,
             fmt, save_plots, interactive)


Instruction:
How would you implement a function in Python 3 that
extracts the arguments from sys. argv that is used to call a command - line script and returns a correctly split list of arguments

Response:
def extract_args(argv):
    """
    take sys.argv that is used to call a command-line script and return a correctly split list of arguments
    for example, this input: ["eqarea.py", "-f", "infile", "-F", "outfile", "-A"]
    will return this output: [['f', 'infile'], ['F', 'outfile'], ['A']]
    """
    string = " ".join(argv)
    string = string.split(' -')
    program = string[0]
    arguments = [s.split() for s in string[1:]]
    return arguments


Instruction:
Make a summary of the following Python 3 code
def check_args(arguments, data_frame):
    stripped_args = [a[0] for a in arguments]
    df = data_frame.df
    # first make sure all args are valid
    for a in arguments:
        if a[0] not in df.index:
            print("-I- ignoring invalid argument: {}".format(a[0]))
            print("-")
    # next make sure required arguments are present
    condition = df['reqd']
    reqd_args = df[condition]
    for arg in reqd_args['arg_name']:
        if arg not in stripped_args:
            raise pmag.MissingCommandLineArgException("-"+arg)
    #next, assign any default values as needed

    #condition = df['default'] != '' # don't need this, and sometimes the correct default argument IS ''
    default_args = df #[condition]
    using_defaults = []
    for arg_name, row in default_args.iterrows():
        default = row['default']
        if arg_name not in stripped_args:
            using_defaults.append(arg_name)
            arguments.append([arg_name, default])
    using_defaults = ["-" + arg for arg in using_defaults]
    print('Using default arguments for: {}'.format(', '.join(using_defaults)))
    return arguments

Response: checks that all arguments are valid and assign any required arguments to the passed in list of available objects


Instruction:
How would you explain what the following Python 3 function does
def InitUI(self):
        if self.data_type in ['orient', 'ages']:
            belongs_to = []
        else:
            parent_table_name = self.parent_type + "s"
            if parent_table_name in self.contribution.tables:
                belongs_to = sorted(self.contribution.tables[parent_table_name].df.index.unique())
            else:
                belongs_to = []

        self.choices = {}
        if self.data_type in ['specimens', 'samples', 'sites']:
            self.choices = {1: (belongs_to, False)}
        if self.data_type == 'orient':
            self.choices = {1: (['g', 'b'], False)}
        if self.data_type == 'ages':
            for level in ['specimen', 'sample', 'site', 'location']:
                if level in self.grid.col_labels:
                    level_names = []
                    if level + "s" in self.contribution.tables:
                        level_names = list(self.contribution.tables[level+"s"].df.index.unique())
                    num = self.grid.col_labels.index(level)
                    self.choices[num] = (level_names, False)
        # Bind left click to drop-down menu popping out
        self.grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK,
                       lambda event: self.on_left_click(event, self.grid, self.choices))

        cols = self.grid.GetNumberCols()
        col_labels = [self.grid.GetColLabelValue(col) for col in range(cols)]

        # check if any additional columns have controlled vocabularies
        # if so, get the vocabulary list
        for col_number, label in enumerate(col_labels):
            self.add_drop_down(col_number, label)

Response: Initialize the UI for the current object.


Instruction:
Write a Python 3 function for
adding a correctly formatted drop - down menu for given col_label.

Response:
def add_drop_down(self, col_number, col_label):
        """
        Add a correctly formatted drop-down-menu for given col_label,
        if required or suggested.
        Otherwise do nothing.

        Parameters
        ----------
        col_number : int
                grid position at which to add a drop down menu
        col_label : str
                column name
        """
        if col_label.endswith('**') or col_label.endswith('^^'):
            col_label = col_label[:-2]
        # add drop-down for experiments
        if col_label == "experiments":
            if 'measurements' in self.contribution.tables:
                meas_table = self.contribution.tables['measurements'].df
                if 'experiment' in meas_table.columns:
                    exps = meas_table['experiment'].unique()
                    self.choices[col_number] = (sorted(exps), False)
                    self.grid.SetColLabelValue(col_number, col_label + "**")
            return
        #
        if col_label == 'method_codes':
            self.add_method_drop_down(col_number, col_label)
        elif col_label == 'magic_method_codes':
            self.add_method_drop_down(col_number, 'method_codes')
        elif col_label in ['specimens', 'samples', 'sites', 'locations']:
            if col_label in self.contribution.tables:
                item_df = self.contribution.tables[col_label].df
                item_names = item_df.index.unique() #[col_label[:-1]].unique()
                self.choices[col_number] = (sorted(item_names), False)
        elif col_label in ['specimen', 'sample', 'site', 'location']:
            if col_label + "s" in self.contribution.tables:
                item_df = self.contribution.tables[col_label + "s"].df
                item_names = item_df.index.unique() #[col_label[:-1]].unique()
                self.choices[col_number] = (sorted(item_names), False)
        # add vocabularies
        if col_label in self.contribution.vocab.suggested:
            typ = 'suggested'
        elif col_label in self.contribution.vocab.vocabularies:
            typ = 'controlled'
        else:
            return

        # add menu, if not already set
        if col_number not in list(self.choices.keys()):
            if typ == 'suggested':
                self.grid.SetColLabelValue(col_number, col_label + "^^")
                controlled_vocabulary = self.contribution.vocab.suggested[col_label]
            else:
                self.grid.SetColLabelValue(col_number, col_label + "**")
                controlled_vocabulary = self.contribution.vocab.vocabularies[col_label]
            #
            stripped_list = []
            for item in controlled_vocabulary:
                try:
                    stripped_list.append(str(item))
                except UnicodeEncodeError:
                    # skips items with non ASCII characters
                    pass

            if len(stripped_list) > 100:
            # split out the list alphabetically, into a dict of lists {'A': ['alpha', 'artist'], 'B': ['beta', 'beggar']...}
                dictionary = {}
                for item in stripped_list:
                    letter = item[0].upper()
                    if letter not in list(dictionary.keys()):
                        dictionary[letter] = []
                    dictionary[letter].append(item)
                stripped_list = dictionary

            two_tiered = True if isinstance(stripped_list, dict) else False
            self.choices[col_number] = (stripped_list, two_tiered)
        return


Instruction:
Write a Python 3 function for
adding drop - down - menu options for magic_method_codes columns

Response:
def add_method_drop_down(self, col_number, col_label):
        """
        Add drop-down-menu options for magic_method_codes columns
        """
        if self.data_type == 'ages':
            method_list = self.contribution.vocab.age_methods
        else:
            method_list = self.contribution.vocab.age_methods.copy()
            method_list.update(self.contribution.vocab.methods)
        self.choices[col_number] = (method_list, True)


Instruction:
Make a summary of the following Python 3 code
def on_left_click(self, event, grid, choices):
        row, col = event.GetRow(), event.GetCol()
        if col == 0 and self.grid.name != 'ages':
            default_val = self.grid.GetCellValue(row, col)
            msg = "Choose a new name for {}.\nThe new value will propagate throughout the contribution.".format(default_val)
            dia = wx.TextEntryDialog(self.grid, msg,
                                     "Rename {}".format(self.grid.name, default_val),
                                     default_val)
            res = dia.ShowModal()
            if res == wx.ID_OK:
                new_val = dia.GetValue()
                # update the contribution with new name
                self.contribution.rename_item(self.grid.name,
                                              default_val, new_val)
                # don't propagate changes if we are just assigning a new name
                # and not really renaming
                # (i.e., if a blank row was added then named)
                if default_val == '':
                    self.grid.SetCellValue(row, 0, new_val)
                    return

                # update the current grid with new name
                for row in range(self.grid.GetNumberRows()):
                    cell_value = self.grid.GetCellValue(row, 0)
                    if cell_value == default_val:
                        self.grid.SetCellValue(row, 0, new_val)
                    else:
                        continue
            return
        color = self.grid.GetCellBackgroundColour(event.GetRow(), event.GetCol())
        # allow user to cherry-pick cells for editing.
        # gets selection of meta key for mac, ctrl key for pc
        if event.ControlDown() or event.MetaDown():
            row, col = event.GetRow(), event.GetCol()
            if (row, col) not in self.dispersed_selection:
                self.dispersed_selection.append((row, col))
                self.grid.SetCellBackgroundColour(row, col, 'light blue')
            else:
                self.dispersed_selection.remove((row, col))
                self.grid.SetCellBackgroundColour(row, col, color)# 'white'
            self.grid.ForceRefresh()
            return
        if event.ShiftDown(): # allow user to highlight multiple consecutive cells in a column
            previous_col = self.grid.GetGridCursorCol()
            previous_row = self.grid.GetGridCursorRow()
            col = event.GetCol()
            row = event.GetRow()
            if col != previous_col:
                return
            else:
                if row > previous_row:
                    row_range = list(range(previous_row, row+1))
                else:
                    row_range = list(range(row, previous_row+1))
            for r in row_range:
                self.grid.SetCellBackgroundColour(r, col, 'light blue')
                self.selection.append((r, col))
            self.grid.ForceRefresh()
            return

        selection = False

        if self.dispersed_selection:
            is_dispersed = True
            selection = self.dispersed_selection

        if self.selection:
            is_dispersed = False
            selection = self.selection

        try:
            col = event.GetCol()
            row = event.GetRow()
        except AttributeError:
            row, col = selection[0][0], selection[0][1]

        self.grid.SetGridCursor(row, col)

        if col in list(choices.keys()): # column should have a pop-up menu
            menu = wx.Menu()
            two_tiered = choices[col][1]
            choices = choices[col][0]
            if not two_tiered: # menu is one tiered
                if 'CLEAR cell of all values' not in choices:
                    choices.insert(0, 'CLEAR cell of all values')
                for choice in choices:
                    if not choice:
                        choice = " " # prevents error if choice is an empty string
                    menuitem = menu.Append(wx.ID_ANY, str(choice))
                    self.window.Bind(wx.EVT_MENU, lambda event: self.on_select_menuitem(event, grid, row, col, selection), menuitem)
                self.show_menu(event, menu)
            else: # menu is two_tiered
                clear = menu.Append(-1, 'CLEAR cell of all values')
                self.window.Bind(wx.EVT_MENU, lambda event: self.on_select_menuitem(event, grid, row, col, selection), clear)
                for choice in sorted(choices.items()):
                    submenu = wx.Menu()
                    for item in choice[1]:
                        menuitem = submenu.Append(-1, str(item))
                        self.window.Bind(wx.EVT_MENU, lambda event: self.on_select_menuitem(event, grid, row, col, selection), menuitem)
                    menu.Append(-1, choice[0], submenu)
                self.show_menu(event, menu)

        if selection:
            # re-whiten the cells that were previously highlighted
            for row, col in selection:
                self.grid.SetCellBackgroundColour(row, col, self.col_color)
            self.dispersed_selection = []
            self.selection = []
            self.grid.ForceRefresh()

Response: Creates a popup menu when user clicks on the column


Instruction:
Can you tell what is the following Python 3 function doing
def main():
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        ofile=sys.argv[ind+1]
        out=open(ofile,'w')
        print(ofile, ' opened for output')
    else: ofile=""
    if '-i' in sys.argv: # interactive flag
        while 1:
            try:
                Dec=float(input("Declination: <cntl-D> to quit "))
            except:
                print("\n Good-bye\n")
                sys.exit()
            Inc=float(input("Inclination: "))
            Dip_dir=float(input("Dip direction: "))
            Dip=float(input("Dip: "))
            print('%7.1f %7.1f'%(pmag.dotilt(Dec,Inc,Dip_dir,Dip)))
    elif '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        data=numpy.loadtxt(file)
    else:
        data=numpy.loadtxt(sys.stdin,dtype=numpy.float) # read in the data from the datafile
    D,I=pmag.dotilt_V(data)
    for k in range(len(D)):
        if ofile=="":
            print('%7.1f %7.1f'%(D[k],I[k]))
        else:
            out.write('%7.1f %7.1f\n'%(D[k],I[k]))

Response: NAME di_tilt. py entry.


Instruction:
Can you implement a function in Python 3 that
names convert2unix.py DESCRIPTION converts mac or dos formatted file to unix file in place SYNTAX convert2unix.py FILE OPTIONS -h prints help and quits

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

    DESCRIPTION
      converts mac or dos formatted file to unix file in place

    SYNTAX
        convert2unix.py FILE

    OPTIONS
        -h prints help and quits

    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    file=sys.argv[1]
    f=open(file,'r')
    Input=f.readlines()
    f.close()
    out=open(file,'w')
    for line in Input:
        out.write(line)
    out.close()


Instruction:
Explain what the following Python 3 code does
def main():
    plot, fmt = 0, 'svg'
    mod, alt, make_plot, lat, lon = 'cals10k', 0, 0, 0, 0
    if '-loc' in sys.argv:
        ind = sys.argv.index('-loc')
        lat = float(sys.argv[ind+1])
        lon = float(sys.argv[ind+2])
    if '-alt' in sys.argv:
        ind = sys.argv.index('-alt')
        alt = float(sys.argv[ind+1])
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind+1]
    if len(sys.argv) != 0 and '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-mod' in sys.argv:
        ind = sys.argv.index('-mod')
        mod = sys.argv[ind+1]
    if '-fgh' in sys.argv:
        ind = sys.argv.index('-fgh')
        ghfile = sys.argv[ind+1]
        lmgh = numpy.loadtxt(ghfile)
        gh = []
        lmgh = numpy.loadtxt(ghfile).transpose()
        gh.append(lmgh[2][0])
        for i in range(1, lmgh.shape[1]):
            gh.append(lmgh[2][i])
            gh.append(lmgh[3][i])
        mod = 'custom'
        inp = [[0, alt, lat, lon]]
    elif '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file = sys.argv[ind+1]
        inp = numpy.loadtxt(file)
    elif '-i' in sys.argv:
        while 1:
            try:
                line = []
                if mod != 'custom':
                    line.append(
                        float(input("Decimal year: <cntrl-D to quit> ")))
                else:
                    line.append(0)
                alt = input("Elevation in km [0] ")
                if alt == "":
                    alt = "0"
                line.append(float(alt))
                line.append(float(input("Latitude (positive north) ")))
                line.append(float(input("Longitude (positive east) ")))
                if mod == '':
                    x, y, z, f = pmag.doigrf(
                        line[3] % 360., line[2], line[1], line[0])
                elif mod == 'custom':
                    x, y, z, f = pmag.docustom(
                        line[3] % 360., line[2], line[1], gh)
                else:
                    x, y, z, f = pmag.doigrf(
                        line[3] % 360., line[2], line[1], line[0], mod=mod)
                Dir = pmag.cart2dir((x, y, z))
                print('%8.2f %8.2f %8.0f' % (Dir[0], Dir[1], f))
            except EOFError:
                print("\n Good-bye\n")
                sys.exit()
    elif '-ages' in sys.argv:
        ind = sys.argv.index('-ages')
        agemin = float(sys.argv[ind+1])
        agemax = float(sys.argv[ind+2])
        ageincr = float(sys.argv[ind+3])
        ages = numpy.arange(agemin, agemax, ageincr)
        lats = numpy.ones(len(ages))*lat
        lons = numpy.ones(len(ages))*lon
        alts = numpy.ones(len(ages))*alt
        inp = numpy.array([ages, alts, lats, lons]).transpose()
    else:
        inp = numpy.loadtxt(sys.stdin, dtype=numpy.float)
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        outfile = sys.argv[ind+1]
        out = open(outfile, 'w')
    else:
        outfile = ""
    if '-sav' in sys.argv:
        plot = 1
    if '-plt' in sys.argv:
        make_plot = 1
        Ages, Decs, Incs, Ints, VADMs = [], [], [], [], []
    for line in inp:
        if mod != 'custom':
            x, y, z, f = pmag.doigrf(
                line[3] % 360., line[2], line[1], line[0], mod=mod)
        else:
            x, y, z, f = pmag.docustom(line[3] % 360., line[2], line[1], gh)
        Dir = pmag.cart2dir((x, y, z))
        if outfile != "":
            out.write('%8.2f %8.2f %8.0f %7.1f %7.1f %7.1f %7.1f\n' %
                      (Dir[0], Dir[1], f, line[0], line[1], line[2], line[3]))
        elif make_plot:
            Ages.append(line[0])
            if Dir[0] > 180:
                Dir[0] = Dir[0]-360.0
            Decs.append(Dir[0])
            Incs.append(Dir[1])
            Ints.append(f*1e-3)
            VADMs.append(pmag.b_vdm(f*1e-9, line[2])*1e-21)
        else:
            print('%8.2f %8.2f %8.0f %7.1f %7.1f %7.1f %7.1f' %
                  (Dir[0], Dir[1], f, line[0], line[1], line[2], line[3]))
    if make_plot:
        pmagplotlib.plot_init(1, 7, 9)
        fig = plt.figure(num=1, figsize=(7, 9))
        fig.add_subplot(411)
        plt.plot(Ages, Decs)
        plt.ylabel('Declination ($^{\circ}$)')
        fig.add_subplot(412)
        plt.plot(Ages, Incs)
        plt.ylabel('Inclination ($^{\circ}$)')
        fig.add_subplot(413)
        plt.plot(Ages, Ints)
        plt.ylabel('Intensity ($\mu$T)')
        fig.add_subplot(414)
        plt.plot(Ages, VADMs)
        plt.ylabel('VADMs (ZAm$^2$)')
        plt.xlabel('Ages')
        # show plot
        if plot == 0:
            pmagplotlib.draw_figs({'time series': 1})
            ans = input("S[a]ve to save figure, <Return>  to quit  ")
            if ans == 'a':
                plt.savefig('igrf.'+fmt)
                print('Figure saved as: ', 'igrf.'+fmt)
        # save plot without showing
        else:
            plt.savefig('igrf.'+fmt)
            print('Figure saved as: ', 'igrf.'+fmt)
        sys.exit()

Response: This function is used to generate the igrf field vector for the given file entry. It uses the routine of Malin and Barraclough and CALS10k - 4bce.


Instruction:
Make a summary of the following Python 3 code
def main():
    dir_path = '.'
    res, ages = 'c', 0
    plot = 0
    proj = 'ortho'
    results_file = 'pmag_results.txt'
    ell, flip = 0, 0
    lat_0, lon_0 = 90., 0.
    fmt = 'pdf'
    sym, size = 'ro', 8
    rsym, rsize = 'g^', 8
    anti = 0
    fancy = 0
    coord = ""
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path = sys.argv[ind+1]
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-S' in sys.argv:
        anti = 1
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind+1]
    if '-sav' in sys.argv:
        plot = 1
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res = sys.argv[ind+1]
    if '-etp' in sys.argv:
        fancy = 1
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj = sys.argv[ind+1]
    if '-rev' in sys.argv:
        flip = 1
        ind = sys.argv.index('-rev')
        rsym = (sys.argv[ind+1])
        rsize = int(sys.argv[ind+2])
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym = (sys.argv[ind+1])
        size = int(sys.argv[ind+2])
    if '-eye' in sys.argv:
        ind = sys.argv.index('-eye')
        lat_0 = float(sys.argv[ind+1])
        lon_0 = float(sys.argv[ind+2])
    if '-ell' in sys.argv:
        ell = 1
    if '-age' in sys.argv:
        ages = 1
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        results_file = sys.argv[ind+1]
    if '-crd' in sys.argv:
        ind = sys.argv.index('-crd')
        crd = sys.argv[ind+1]
        if crd == 'g':
            coord = '0'
        if crd == 't':
            coord = '100'
    results_file = dir_path+'/'+results_file
    data, file_type = pmag.magic_read(results_file)
    if file_type != 'pmag_results':
        print("bad results file")
        sys.exit()
    FIG = {'map': 1}
    pmagplotlib.plot_init(FIG['map'], 6, 6)
    # read in er_sites file
    lats, lons, dp, dm, a95 = [], [], [], [], []
    Pars = []
    dates, rlats, rlons = [], [], []
    if 'data_type' in data[0].keys():
        # get all site level data
        Results = pmag.get_dictitem(data, 'data_type', 'i', 'T')
    else:
        Results = data
    # get all non-blank latitudes
    Results = pmag.get_dictitem(Results, 'vgp_lat', '', 'F')
    # get all non-blank longitudes
    Results = pmag.get_dictitem(Results, 'vgp_lon', '', 'F')
    if coord != "":
        # get specified coordinate system
        Results = pmag.get_dictitem(Results, 'tilt_correction', coord, 'T')
    location = ""
    for rec in Results:
        if rec['er_location_names'] not in location:
            location = location+':'+rec['er_location_names']
        if 'average_age' in rec.keys() and rec['average_age'] != "" and ages == 1:
            dates.append(rec['average_age'])
        lat = float(rec['vgp_lat'])
        lon = float(rec['vgp_lon'])
        if flip == 0:
            lats.append(lat)
            lons.append(lon)
        elif flip == 1:
            if lat < 0:
                rlats.append(-lat)
                lon = lon+180.
                if lon > 360:
                    lon = lon-360.
                rlons.append(lon)
            else:
                lats.append(lat)
                lons.append(lon)
        elif anti == 1:
            lats.append(-lat)
            lon = lon+180.
            if lon > 360:
                lon = lon-360.
            lons.append(lon)
        ppars = []
        ppars.append(lon)
        ppars.append(lat)
        ell1, ell2 = "", ""
        if 'vgp_dm' in rec.keys() and rec['vgp_dm'] != "":
            ell1 = float(rec['vgp_dm'])
        if 'vgp_dp' in rec.keys() and rec['vgp_dp'] != "":
            ell2 = float(rec['vgp_dp'])
        if 'vgp_alpha95' in rec.keys() and rec['vgp_alpha95'] != "":
            ell1, ell2 = float(rec['vgp_alpha95']), float(rec['vgp_alpha95'])
        if ell1 != "" and ell2 != "":
            ppars = []
            ppars.append(lons[-1])
            ppars.append(lats[-1])
            ppars.append(ell1)
            ppars.append(lons[-1])
            isign = abs(lats[-1])/lats[-1]
            ppars.append(lats[-1]-isign*90.)
            ppars.append(ell2)
            ppars.append(lons[-1]+90.)
            ppars.append(0.)
            Pars.append(ppars)
    location = location.strip(':')
    Opts = {'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360., 'lat_0': lat_0, 'lon_0': lon_0,
            'proj': proj, 'sym': 'bs', 'symsize': 3, 'pltgrid': 0, 'res': res, 'boundinglat': 0.}
    Opts['details'] = {'coasts': 1, 'rivers': 0, 'states': 0,
                       'countries': 0, 'ocean': 1, 'fancy': fancy}
    # make the base map with a blue triangle at the pole`
    pmagplotlib.plot_map(FIG['map'], [90.], [0.], Opts)
    Opts['pltgrid'] = -1
    Opts['sym'] = sym
    Opts['symsize'] = size
    if len(dates) > 0:
        Opts['names'] = dates
    if len(lats) > 0:
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], lats, lons, Opts)
    Opts['names'] = []
    if len(rlats) > 0:
        Opts['sym'] = rsym
        Opts['symsize'] = rsize
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], rlats, rlons, Opts)
    if plot == 0:
        pmagplotlib.draw_figs(FIG)
    if ell == 1:  # add ellipses if desired.
        Opts['details'] = {'coasts': 0, 'rivers': 0,
                           'states': 0, 'countries': 0, 'ocean': 0}
        Opts['pltgrid'] = -1  # turn off meridian replotting
        Opts['symsize'] = 2
        Opts['sym'] = 'g-'
        for ppars in Pars:
            if ppars[2] != 0:
                PTS = pmagplotlib.plot_ell(FIG['map'], ppars, 'g.', 0, 0)
                elats, elons = [], []
                for pt in PTS:
                    elons.append(pt[0])
                    elats.append(pt[1])
                # make the base map with a blue triangle at the pole`
                pmagplotlib.plot_map(FIG['map'], elats, elons, Opts)
                if plot == 0:
                    pmagplotlib.draw_figs(FIG)
    files = {}
    for key in FIG.keys():
        if pmagplotlib.isServer:  # use server plot naming convention
            files[key] = 'LO:_'+location+'_VGP_map.'+fmt
        else:  # use more readable plot naming convention
            files[key] = '{}_VGP_map.{}'.format(
                location.replace(' ', '_'), fmt)
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['eq'] = 'LO:_'+location+'_VGP_map'
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    elif plot == 0:
        pmagplotlib.draw_figs(FIG)
        ans = input(" S[a]ve to save plot, Return to quit:  ")
        if ans == "a":
            pmagplotlib.save_plots(FIG, files)
        else:
            print("Good bye")
            sys.exit()
    else:
        pmagplotlib.save_plots(FIG, files)

Response: This function is the main function of the vgpmap_magic. py script. It is the main function of the vgpmap_magic. py script.


Instruction:
How would you implement a function in Python 3 that
names gokent.py DESCRIPTION calculates Kent parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX gokent.py [options] OPTIONS -h prints help message and quits -i for interactive filename entry -f FILE, specify filename -F FILE, specifies output file name < filename for reading from standard input OUTPUT mean dec, mean inc, Eta, Deta, Ieta, Zeta, Zdec, Zinc, N

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

    DESCRIPTION
       calculates Kent parameters from dec inc data

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

    SYNTAX
       gokent.py [options]

    OPTIONS
        -h prints help message and quits
        -i for interactive filename entry
        -f FILE, specify filename
        -F FILE, specifies output file name
        < filename for reading from standard input

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


Instruction:
Can you tell what is the following Python 3 function doing
def draw_figs(FIGS):
    is_win = True if sys.platform in ['win32', 'win64'] else False
    if not is_win:
        plt.ion()
        for fig in list(FIGS.keys()):
            plt.draw()
            plt.show()
        plt.ioff()
    if is_win:
        # this style basically works for Windows
        plt.draw()
        print("You must manually close all plots to continue")
        plt.show()

Response: Draw all the figures in the TKAgg


Instruction:
Can you generate a brief explanation for the following Python 3 code
def delticks(fig):
    locs = fig.xaxis.get_ticklocs()
    nlocs = np.delete(locs, list(range(0, len(locs), 2)))
    fig.set_xticks(nlocs)

Response: Delete half the x - axis tick marks in the matplotlib figure.


Instruction:
Explain what the following Python 3 code does
def plot_init(fignum, w, h):
    global fig_x_pos, fig_y_pos, plt_num
    dpi = 80
    if isServer:
        dpi = 240
    # plt.ion()
    plt_num += 1
    fig = plt.figure(num=fignum, figsize=(w, h), dpi=dpi)
    if (not isServer) and (not set_env.IS_NOTEBOOK):
        plt.get_current_fig_manager().show()
        # plt.get_current_fig_manager().window.wm_geometry('+%d+%d' %
        # (fig_x_pos,fig_y_pos)) # this only works with matplotlib.use('TKAgg')
        fig_x_pos = fig_x_pos + dpi * (w) + 25
        if plt_num == 3:
            plt_num = 0
            fig_x_pos = 25
            fig_y_pos = fig_y_pos + dpi * (h) + 25
        plt.figtext(.02, .01, version_num)
# plt.connect('button_press_event',click)
#
    # plt.ioff()
    return fig

Response: Initializes the matplotlib figure with the given width w and height h.


Instruction:
Write a Python 3 script for
returning the cumulative normal distribution function of the variable y with mean ybar and standard deviation sigma

Response:
def gaussfunc(y, ybar, sigma):
    """
    cumulative normal distribution function of the variable y
    with mean ybar,standard deviation sigma
    uses expression 7.1.26 from Abramowitz & Stegun
    accuracy better than 1.5e-7 absolute
    Parameters
    _________
    y : input variable
    ybar : mean
    sigma : standard deviation

    """
    x = old_div((y - ybar), (np.sqrt(2.) * sigma))
    t = old_div(1.0, (1.0 + .3275911 * abs(x)))
    erf = 1.0 - np.exp(-x * x) * t * (.254829592 - t * (.284496736 -
                                                        t * (1.421413741 - t * (1.453152027 - t * 1.061405429))))
    erf = abs(erf)
    sign = old_div(x, abs(x))
    return 0.5 * (1.0 + sign * erf)


Instruction:
How would you explain what the following Python 3 function does
def k_s(X):
    xbar, sigma = pmag.gausspars(X)
    d, f = 0, 0.
    for i in range(1, len(X) + 1):
        b = old_div(float(i), float(len(X)))
        a = gaussfunc(X[i - 1], xbar, sigma)
        if abs(f - a) > abs(b - a):
            delta = abs(f - a)
        else:
            delta = abs(b - a)
        if delta > d:
            d = delta
        f = b
    return d, xbar, sigma

Response: Kolmorgorov - Smirnov statistic.


Instruction:
Given the following Python 3 function, write the documentation
def plot_xy(fignum, X, Y, **kwargs):
    plt.figure(num=fignum)
#    if 'poly' in kwargs.keys():
#          coeffs=np.polyfit(X,Y,kwargs['poly'])
#          polynomial=np.poly1d(coeffs)
#          xs=np.arange(np.min(X),np.max(X))
#          ys=polynomial(xs)
#          plt.plot(xs,ys)
#          print coefs
#          print polynomial
    if 'sym' in list(kwargs.keys()):
        sym = kwargs['sym']
    else:
        sym = 'ro'
    if 'lw' in list(kwargs.keys()):
        lw = kwargs['lw']
    else:
        lw = 1
    if 'xerr' in list(kwargs.keys()):
        plt.errorbar(X, Y, fmt=sym, xerr=kwargs['xerr'])
    if 'yerr' in list(kwargs.keys()):
        plt.errorbar(X, Y, fmt=sym, yerr=kwargs['yerr'])
    if 'axis' in list(kwargs.keys()):
        if kwargs['axis'] == 'semilogx':
            plt.semilogx(X, Y, marker=sym[1], markerfacecolor=sym[0])
        if kwargs['axis'] == 'semilogy':
            plt.semilogy(X, Y, marker=sym[1], markerfacecolor=sym[0])
        if kwargs['axis'] == 'loglog':
            plt.loglog(X, Y, marker=sym[1], markerfacecolor=sym[0])
    else:
        plt.plot(X, Y, sym, linewidth=lw)
    if 'xlab' in list(kwargs.keys()):
        plt.xlabel(kwargs['xlab'])
    if 'ylab' in list(kwargs.keys()):
        plt.ylabel(kwargs['ylab'])
    if 'title' in list(kwargs.keys()):
        plt.title(kwargs['title'])
    if 'xmin' in list(kwargs.keys()):
        plt.axis([kwargs['xmin'], kwargs['xmax'],
                  kwargs['ymin'], kwargs['ymax']])
    if 'notes' in list(kwargs.keys()):
        for note in kwargs['notes']:
            plt.text(note[0], note[1], note[2])

Response: This function plots the X and Y of a curie.


Instruction:
Write a Python 3 script for
plotting the site mean data

Response:
def plot_site(fignum, SiteRec, data, key):
    """
    deprecated (used in ipmag)
    """
    print('Site mean data: ')
    print('   dec    inc n_lines n_planes kappa R alpha_95 comp coord')
    print(SiteRec['site_dec'], SiteRec['site_inc'], SiteRec['site_n_lines'], SiteRec['site_n_planes'], SiteRec['site_k'],
          SiteRec['site_r'], SiteRec['site_alpha95'], SiteRec['site_comp_name'], SiteRec['site_tilt_correction'])
    print('sample/specimen, dec, inc, n_specs/a95,| method codes ')
    for i in range(len(data)):
        print('%s: %s %s %s / %s | %s' % (data[i]['er_' + key + '_name'], data[i][key + '_dec'], data[i]
                                          [key + '_inc'], data[i][key + '_n'], data[i][key + '_alpha95'], data[i]['magic_method_codes']))
    plot_slnp(fignum, SiteRec, data, key)
    plot = input("s[a]ve plot, [q]uit or <return> to continue:   ")
    if plot == 'q':
        print("CUL8R")
        sys.exit()
    if plot == 'a':
        files = {}
        for key in list(EQ.keys()):
            files[key] = site + '_' + key + '.' + fmt
        save_plots(EQ, files)


Instruction:
Explain what the following Python 3 code does
def plot_qq_norm(fignum, Y, title):
    plt.figure(num=fignum)
    if type(Y) == list:
        Y = np.array(Y)
    Y = np.sort(Y)  # sort the data
    n = len(Y)
    d, mean, sigma = k_s(Y)
    dc = old_div(0.886, np.sqrt(float(n)))
    X = []  # list for normal quantile
    for i in range(1, n + 1):
        p = old_div(float(i), float(n + 1))
        X.append(qsnorm(p))
    plt.plot(X, Y, 'ro')
    plt.title(title)
    plt.xlabel('Normal Quantile')
    plt.ylabel('Data Quantile')
    bounds = plt.axis()
    notestr = 'N: ' + '%i' % (n)
    plt.text(-.9 * bounds[1], .9 * bounds[3], notestr)
    notestr = 'mean: ' + '%8.3e' % (mean)
    plt.text(-.9 * bounds[1], .8 * bounds[3], notestr)
    notestr = 'std dev: ' + '%8.3e' % (sigma)
    plt.text(-.9 * bounds[1], .7 * bounds[3], notestr)
    notestr = 'D: ' + '%8.3e' % (d)
    plt.text(-.9 * bounds[1], .6 * bounds[3], notestr)
    notestr = 'Dc: ' + '%8.3e' % (dc)
    plt.text(-.9 * bounds[1], .5 * bounds[3], notestr)
    return d, dc

Response: Function that makes a Quantile - Quantile - Normal plot for the data Y


Instruction:
How would you implement a function in Python 3 that
functions to plot a Quantile plot of data against a uniform distribution in 0 => 360.

Response:
def plot_qq_unf(fignum, D, title, subplot=False, degrees=True):
    """
    plots data against a uniform distribution in 0=>360.
    Parameters
    _________
    fignum : matplotlib figure number
    D : data
    title : title for plot
    subplot : if True, make this number one of two subplots
    degrees : if True, assume that these are degrees

    Return
    Mu : Mu statistic (Fisher et al., 1987)
    Mu_crit : critical value of Mu for uniform distribution

    Effect
    ______
    makes a Quantile Quantile plot of data
    """
    if subplot == True:
        plt.subplot(1, 2, fignum)
    else:
        plt.figure(num=fignum)
    X, Y, dpos, dneg = [], [], 0., 0.
    if degrees:
        D = (np.array(D)) % 360
    X = D/D.max()
    X = np.sort(X)
    n = float(len(D))
    i = np.arange(0, len(D))
    Y = (i-0.5)/n
    ds = (i/n)-X
    dpos = ds.max()
    dneg = ds.min()
    plt.plot(Y, X, 'ro')
    v = dneg + dpos  # kuiper's v
    # Mu of fisher et al. equation 5.16
    Mu = v * (np.sqrt(n) - 0.567 + (old_div(1.623, (np.sqrt(n)))))
    plt.axis([0, 1., 0., 1.])
    bounds = plt.axis()
    notestr = 'N: ' + '%i' % (n)
    plt.text(.1 * bounds[1], .9 * bounds[3], notestr)
    notestr = 'Mu: ' + '%7.3f' % (Mu)
    plt.text(.1 * bounds[1], .8 * bounds[3], notestr)
    if Mu > 1.347:
        notestr = "Non-uniform (99%)"
    elif Mu < 1.207:
        notestr = "Uniform (95%)"
    elif Mu > 1.207:
        notestr = "Uniform (99%)"
    plt.text(.1 * bounds[1], .7 * bounds[3], notestr)
    plt.text(.1 * bounds[1], .7 * bounds[3], notestr)
    plt.title(title)
    plt.xlabel('Uniform Quantile')
    plt.ylabel('Data Quantile')
    return Mu, 1.207


Instruction:
Implement a Python 3 function for
plotting data against an exponential distribution in 0=>90.

Response:
def plot_qq_exp(fignum, I, title, subplot=False):
    """
    plots data against an exponential distribution in 0=>90.

    Parameters
    _________
    fignum : matplotlib figure number
    I : data
    title : plot title
    subplot : boolean, if True plot as subplot with 1 row, two columns with fignum the plot number
    """
    if subplot == True:
        plt.subplot(1, 2, fignum)
    else:
        plt.figure(num=fignum)
    X, Y, dpos, dneg = [], [], 0., 0.
    rad = old_div(np.pi, 180.)
    xsum = 0
    for i in I:
        theta = (90. - i) * rad
        X.append(1. - np.cos(theta))
        xsum += X[-1]
    X.sort()
    n = float(len(X))
    kappa = old_div((n - 1.), xsum)
    for i in range(len(X)):
        p = old_div((float(i) - 0.5), n)
        Y.append(-np.log(1. - p))
        f = 1. - np.exp(-kappa * X[i])
        ds = old_div(float(i), n) - f
        if dpos < ds:
            dpos = ds
        ds = f - old_div((float(i) - 1.), n)
        if dneg < ds:
            dneg = ds
    if dneg > dpos:
        ds = dneg
    else:
        ds = dpos
    Me = (ds - (old_div(0.2, n))) * (np.sqrt(n) + 0.26 +
                                     (old_div(0.5, (np.sqrt(n)))))  # Eq. 5.15 from Fisher et al. (1987)

    plt.plot(Y, X, 'ro')
    bounds = plt.axis()
    plt.axis([0, bounds[1], 0., bounds[3]])
    notestr = 'N: ' + '%i' % (n)
    plt.text(.1 * bounds[1], .9 * bounds[3], notestr)
    notestr = 'Me: ' + '%7.3f' % (Me)
    plt.text(.1 * bounds[1], .8 * bounds[3], notestr)
    if Me > 1.094:
        notestr = "Not Exponential"
    else:
        notestr = "Exponential (95%)"
    plt.text(.1 * bounds[1], .7 * bounds[3], notestr)
    plt.title(title)
    plt.xlabel('Exponential Quantile')
    plt.ylabel('Data Quantile')
    return Me, 1.094


Instruction:
Explain what the following Python 3 code does
def plot_di(fignum, DIblock):
    global globals
    """
    plots directions on equal area net
    Parameters
    _________
    fignum : matplotlib figure number
    DIblock : nested list of dec, inc pairs
    """
    X_down, X_up, Y_down, Y_up = [], [], [], []  # initialize some variables
    plt.figure(num=fignum)
#
#   plot the data - separate upper and lower hemispheres
#
    for rec in DIblock:
        Up, Down = 0, 0
        XY = pmag.dimap(rec[0], rec[1])
        if rec[1] >= 0:
            X_down.append(XY[0])
            Y_down.append(XY[1])
        else:
            X_up.append(XY[0])
            Y_up.append(XY[1])
#
    if len(X_down) > 0:
        #        plt.scatter(X_down,Y_down,marker='s',c='r')
        plt.scatter(X_down, Y_down, marker='o', c='blue')
        if globals != 0:
            globals.DIlist = X_down
            globals.DIlisty = Y_down
    if len(X_up) > 0:
        #        plt.scatter(X_up,Y_up,marker='s',facecolor='none',edgecolor='black')
        plt.scatter(X_up, Y_up, marker='o',
                    facecolor='white', edgecolor='blue')
        if globals != 0:
            globals.DIlist = X_up
            globals.DIlisty = Y_up

Response: Plots the DIblock in the same direction as the current net.


Instruction:
Can you create a Python 3 function that
functions to plot the DIblock and the corresponding symbol

Response:
def plot_di_sym(fignum, DIblock, sym):
    global globals
    """
    plots directions on equal area net
    Parameters
    _________
    fignum : matplotlib figure number
    DIblock : nested list of dec, inc pairs
    sym : set matplotlib symbol (e.g., 'bo' for blue circles)
    """
    X_down, X_up, Y_down, Y_up = [], [], [], []  # initialize some variables
    plt.figure(num=fignum)
#
#   plot the data - separate upper and lower hemispheres
#
    for rec in DIblock:
        Up, Down = 0, 0
        XY = pmag.dimap(rec[0], rec[1])
        if rec[1] >= 0:
            X_down.append(XY[0])
            Y_down.append(XY[1])
        else:
            X_up.append(XY[0])
            Y_up.append(XY[1])
#
    if 'size' not in list(sym.keys()):
        size = 50
    else:
        size = sym['size']
    if 'edgecolor' not in list(sym.keys()):
        sym['edgecolor'] = 'k'
    if len(X_down) > 0:
        plt.scatter(X_down, Y_down, marker=sym['lower'][0],
                    c=sym['lower'][1], s=size, edgecolor=sym['edgecolor'])
        if globals != 0:
            globals.DIlist = X_down
            globals.DIlisty = Y_down
    if len(X_up) > 0:
        plt.scatter(X_up, Y_up, marker=sym['upper'][0],
                    c=sym['upper'][1], s=size, edgecolor=sym['edgecolor'])
        if globals != 0:
            globals.DIlist = X_up
            globals.DIlisty = Y_up


Instruction:
Explain what the following Python 3 code does
def plot_circ(fignum, pole, ang, col):
    plt.figure(num=fignum)
    D_c, I_c = pmag.circ(pole[0], pole[1], ang)
    X_c_up, Y_c_up = [], []
    X_c_d, Y_c_d = [], []
    for k in range(len(D_c)):
        XY = pmag.dimap(D_c[k], I_c[k])
        if I_c[k] < 0:
            X_c_up.append(XY[0])
            Y_c_up.append(XY[1])
        else:
            X_c_d.append(XY[0])
            Y_c_d.append(XY[1])
    plt.plot(X_c_d, Y_c_d, col + '.', ms=5)
    plt.plot(X_c_up, Y_c_up, 'c.', ms=2)

Response: function to plot a small circle on an equal area projection plot


Instruction:
Create a Python 3 function to
function to make a Zijderveld diagrams for a given site.

Response:
def plot_zij(fignum, datablock, angle, s, norm=True):
    """
    function to make Zijderveld diagrams

    Parameters
    __________
    fignum : matplotlib figure number
    datablock : nested list of [step, dec, inc, M (Am2), type, quality]
                where type is a string, either 'ZI' or 'IZ' for IZZI experiments
    angle : desired rotation in the horizontal plane (0 puts X on X axis)
    s : specimen name
    norm : if True, normalize to initial magnetization = unity

    Effects
    _______
    makes a zijderveld plot

    """
    global globals
    plt.figure(num=fignum)
    plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    amin, amax = 0., -100.
    if norm == 0:
        fact = 1.
    else:
        fact = (1./datablock[0][3])   # normalize to NRM=1
    # convert datablock to DataFrame data with  dec,inc, int
    data = pd.DataFrame(datablock)
    if len(data.columns) == 5:
        data.columns = ['treat', 'dec', 'inc', 'int', 'quality']
    if len(data.columns) == 6:
        data.columns = ['treat', 'dec', 'inc', 'int', 'type', 'quality']
    elif len(data.columns) == 7:
        data.columns = ['treat', 'dec', 'inc', 'int', 'type', 'quality', 'y']
    #print (len(data.columns))
    data['int'] = data['int']*fact  # normalize
    data['dec'] = (data['dec']-angle) % 360  # adjust X axis angle
    gdata = data[data['quality'].str.contains('g')]
    bdata = data[data['quality'].str.contains('b')]
    forVDS = gdata[['dec', 'inc', 'int']].values
    gXYZ = pd.DataFrame(pmag.dir2cart(forVDS))
    gXYZ.columns = ['X', 'Y', 'Z']
    amax = np.maximum(gXYZ.X.max(), gXYZ.Z.max())
    amin = np.minimum(gXYZ.X.min(), gXYZ.Z.min())
    if amin > 0:
        amin = 0
    bXYZ = pmag.dir2cart(bdata[['dec', 'inc', 'int']].values).transpose()
# plotting stuff
    if angle != 0:
        tempstr = "\n Declination rotated by: " + str(angle) + '\n'
    if globals != 0:
        globals.text.insert(globals.END, tempstr)
        globals.Zlist = gXYZ['x'].tolist()
        globals.Zlisty = gXYZ['y'].tolist()
        globals.Zlistz = gXYZ['z'].tolist()
    if len(bXYZ) > 0:
        plt.scatter(bXYZ[0], bXYZ[1], marker='d', c='y', s=30)
        plt.scatter(bXYZ[0], bXYZ[2], marker='d', c='y', s=30)
    plt.plot(gXYZ['X'], gXYZ['Y'], 'ro')
    plt.plot(gXYZ['X'], gXYZ['Z'], 'ws', markeredgecolor='blue')
    plt.plot(gXYZ['X'], gXYZ['Y'], 'r-')
    plt.plot(gXYZ['X'], gXYZ['Z'], 'b-')
    for k in range(len(gXYZ)):
        plt.annotate(str(k), (gXYZ['X'][k], gXYZ['Z']
                              [k]), ha='left', va='bottom')
    if amin > 0 and amax >0:amin=0 # complete the line
    if amin < 0 and amax <0:amax=0 # complete the line
    xline = [amin, amax]
   # yline=[-amax,-amin]
    yline = [amax, amin]
    zline = [0, 0]
    plt.plot(xline, zline, 'k-')
    plt.plot(zline, xline, 'k-')
    if angle != 0:
        xlab = "X: rotated to Dec = " + '%7.1f' % (angle)
    if angle == 0:
        xlab = "X: rotated to Dec = " + '%7.1f' % (angle)
    plt.xlabel(xlab)
    plt.ylabel("Circles: Y; Squares: Z")
    tstring = s + ': NRM = ' + '%9.2e' % (datablock[0][3])
    plt.axis([amin, amax, amax, amin])
    plt.axis("equal")
    plt.title(tstring)


Instruction:
Can you implement a function in Python 3 that
plots the magnetization against the current state of the object.

Response:
def plot_mag(fignum, datablock, s, num, units, norm):
    """
    plots magnetization against (de)magnetizing temperature or field

    Parameters
    _________________
    fignum : matplotlib figure number for plotting
    datablock : nested list of [step, 0, 0, magnetization, 1,quality]
    s : string for title
    num : matplotlib figure number, can set to 1
    units : [T,K,U] for tesla, kelvin or arbitrary
    norm : [True,False] if True, normalize

    Effects
    ______
        plots figure
    """
    global globals, graphmenu
    Ints = []
    for plotrec in datablock:
        Ints.append(plotrec[3])
    Ints.sort()
    plt.figure(num=fignum)
    T, M, Tv, recnum = [], [], [], 0
    Mex, Tex, Vdif = [], [], []
    recbak = []
    for rec in datablock:
        if rec[5] == 'g':
            if units == "T":
                T.append(rec[0] * 1e3)
                Tv.append(rec[0] * 1e3)
                if recnum > 0:
                    Tv.append(rec[0] * 1e3)
            elif units == "U":
                T.append(rec[0])
                Tv.append(rec[0])
                if recnum > 0:
                    Tv.append(rec[0])
            elif units == "K":
                T.append(rec[0] - 273)
                Tv.append(rec[0] - 273)
                if recnum > 0:
                    Tv.append(rec[0] - 273)
            elif "T" in units and "K" in units:
                if rec[0] < 1.:
                    T.append(rec[0] * 1e3)
                    Tv.append(rec[0] * 1e3)
                else:
                    T.append(rec[0] - 273)
                    Tv.append(rec[0] - 273)
                    if recnum > 0:
                        Tv.append(rec[0] - 273)
            else:
                T.append(rec[0])
                Tv.append(rec[0])
                if recnum > 0:
                    Tv.append(rec[0])
            if norm:
                M.append(old_div(rec[3], Ints[-1]))
            else:
                M.append(rec[3])
            if recnum > 0 and len(rec) > 0 and len(recbak) > 0:
                v = []
                if recbak[0] != rec[0]:
                    V0 = pmag.dir2cart([recbak[1], recbak[2], recbak[3]])
                    V1 = pmag.dir2cart([rec[1], rec[2], rec[3]])
                    for el in range(3):
                        v.append(abs(V1[el] - V0[el]))
                    vdir = pmag.cart2dir(v)
                    # append vector difference
                    Vdif.append(old_div(vdir[2], Ints[-1]))
                    Vdif.append(old_div(vdir[2], Ints[-1]))
            recbak = []
            for el in rec:
                recbak.append(el)
            delta = .005 * M[0]
            if num == 1:
                if recnum % 2 == 0:
                    plt.text(T[-1] + delta, M[-1],
                             (' ' + str(recnum)), fontsize=9)
            recnum += 1
        else:
            if rec[0] < 200:
                Tex.append(rec[0] * 1e3)
            if rec[0] >= 200:
                Tex.append(rec[0] - 273)
            Mex.append(old_div(rec[3], Ints[-1]))
            recnum += 1
    if globals != 0:
        globals.MTlist = T
        globals.MTlisty = M
    if len(Mex) > 0 and len(Tex) > 0:
        plt.scatter(Tex, Mex, marker='d', color='k')
    if len(Vdif) > 0:
        Vdif.append(old_div(vdir[2], Ints[-1]))
        Vdif.append(0)
    if Tv:
        Tv.append(Tv[-1])
    plt.plot(T, M)
    plt.plot(T, M, 'ro')
    if len(Tv) == len(Vdif) and norm:
        plt.plot(Tv, Vdif, 'g-')
    if units == "T":
        plt.xlabel("Step (mT)")
    elif units == "K":
        plt.xlabel("Step (C)")
    elif units == "J":
        plt.xlabel("Step (J)")
    else:
        plt.xlabel("Step [mT,C]")
    if norm == 1:
        plt.ylabel("Fractional Magnetization")
    if norm == 0:
        plt.ylabel("Magnetization")
    plt.axvline(0, color='k')
    plt.axhline(0, color='k')
    tstring = s
    plt.title(tstring)
    plt.draw()


Instruction:
Can you generate the documentation for the following Python 3 function
def plot_zed(ZED, datablock, angle, s, units):
    for fignum in list(ZED.keys()):
        fig = plt.figure(num=ZED[fignum])
        plt.clf()
        if not isServer:
            plt.figtext(.02, .01, version_num)
    DIbad, DIgood = [], []
    for rec in datablock:
        if cb.is_null(rec[1],zero_as_null=False):
            print('-W- You are missing a declination for specimen', s, ', skipping this row')
            continue
        if cb.is_null(rec[2],zero_as_null=False):
            print('-W- You are missing an inclination for specimen', s, ', skipping this row')
            continue
        if rec[5] == 'b':
            DIbad.append((rec[1], rec[2]))
        else:
            DIgood.append((rec[1], rec[2]))
    badsym = {'lower': ['+', 'g'], 'upper': ['x', 'c']}
    if len(DIgood) > 0:
        plot_eq(ZED['eqarea'], DIgood, s)
        if len(DIbad) > 0:
            plot_di_sym(ZED['eqarea'], DIbad, badsym)
    elif len(DIbad) > 0:
        plot_eq_sym(ZED['eqarea'], DIbad, s, badsym)
    AngleX, AngleY = [], []
    XY = pmag.dimap(angle, 90.)
    AngleX.append(XY[0])
    AngleY.append(XY[1])
    XY = pmag.dimap(angle, 0.)
    AngleX.append(XY[0])
    AngleY.append(XY[1])
    plt.figure(num=ZED['eqarea'])
    # Draw a line for Zijderveld horizontal axis
    plt.plot(AngleX, AngleY, 'r-')
    if AngleX[-1] == 0:
        AngleX[-1] = 0.01
    plt.text(AngleX[-1] + (old_div(AngleX[-1], abs(AngleX[-1]))) * .1,
             AngleY[-1] + (old_div(AngleY[-1], abs(AngleY[-1]))) * .1, 'X')
    norm = 1
    #if units=="U": norm=0
    # if there are NO good points, don't try to plot
    if DIgood:
        plot_mag(ZED['demag'], datablock, s, 1, units, norm)
        plot_zij(ZED['zijd'], datablock, angle, s, norm)
    else:
        ZED.pop('demag')
        ZED.pop('zijd')
    return ZED

Response: function to make a zijderveld plot and a demag


Instruction:
Write a Python 3 function that can
function to plot the great circle on the equal area projection and plot start and end points of the current object

Response:
def plot_dir(ZED, pars, datablock, angle):
    """
    function to put the great circle on the equal area projection
    and plot start and end points of calculation

    DEPRECATED (used in zeq_magic)
    """
#
# find start and end points from datablock
#
    if pars["calculation_type"] == 'DE-FM':
        x, y = [], []
        plt.figure(num=ZED['eqarea'])
        XY = pmag.dimap(pars["specimen_dec"], pars["specimen_inc"])
        x.append(XY[0])
        y.append(XY[1])
        plt.scatter(x, y, marker='^', s=80, c='r')
        plt.show()
        return
    StartDir, EndDir = [0, 0, 1.], [0, 0, 1.]
    for rec in datablock:
        if rec[0] == pars["measurement_step_min"]:
            StartDir[0] = rec[1]
            StartDir[1] = rec[2]
            if pars["specimen_direction_type"] == 'l':
                StartDir[2] = rec[3]/datablock[0][3]
        if rec[0] == pars["measurement_step_max"]:
            EndDir[0] = rec[1]
            EndDir[1] = rec[2]
            if pars["specimen_direction_type"] == 'l':
                EndDir[2] = rec[3]/datablock[0][3]

#
#  put them on the plots
#
    x, y, z, pole = [], [], [], []
    if pars["calculation_type"] != 'DE-BFP':
        plt.figure(num=ZED['eqarea'])
        XY = pmag.dimap(pars["specimen_dec"], pars["specimen_inc"])
        x.append(XY[0])
        y.append(XY[1])
        plt.scatter(x, y, marker='d', s=80, c='b')
        x, y, z = [], [], []
        StartDir[0] = StartDir[0] - angle
        EndDir[0] = EndDir[0] - angle
        XYZs = pmag.dir2cart(StartDir)
        x.append(XYZs[0])
        y.append(XYZs[1])
        z.append(XYZs[2])
        XYZe = pmag.dir2cart(EndDir)
        x.append(XYZe[0])
        y.append(XYZe[1])
        z.append(XYZe[2])
        plt.figure(num=ZED['zijd'])
        plt.scatter(x, y, marker='d', s=80, c='g')
        plt.scatter(x, z, marker='d', s=80, c='g')
        plt.scatter(x, y, marker='o', c='r', s=20)
        plt.scatter(x, z, marker='s', c='w', s=20)
#
# put on best fit line
# new way (from Jeff Gee's favorite website http://GET THIS):
#      P1=pmag.dir2cart([(pars["specimen_dec"]-angle),pars["specimen_inc"],1.]) #  princ comp.
#      P2=pmag.dir2cart([(pars["specimen_dec"]-angle-180.),-pars["specimen_inc"],1.]) # antipode of princ comp.
#      P21,Ps,Pe,Xs,Xe=[],[],[],[],[]
#      for i in range(3):
#          P21.append(P2[i]-P1[i])
#          Ps.append(XYZs[i]-P1[i])
#          Pe.append(XYZe[i]-P1[i])
#      norm=pmag.cart2dir(P21)[2]
#      us=(Ps[0]*P21[0]+Ps[1]*P21[1]+Ps[2]*P21[2])/(norm**2)
#      ue=(Pe[0]*P21[0]+Pe[1]*P21[1]+Pe[2]*P21[2])/(norm**2)
#      px,py,pz=[],[],[]
#      for i in range(3):
#          Xs.append(P1[i]+us*(P2[i]-P1[i]))
#          Xe.append(P1[i]+ue*(P2[i]-P1[i]))
#   old way:
        cm = pars["center_of_mass"]
        if cm != [0., 0., 0.]:
            cm = np.array(pars["center_of_mass"])/datablock[0][3]
            cmDir = pmag.cart2dir(cm)
            cmDir[0] = cmDir[0] - angle
            cm = pmag.dir2cart(cmDir)
            diff = []
            for i in range(3):
                diff.append(XYZe[i] - XYZs[i])
            R = np.sqrt(diff[0]**2 + diff[1]**2 + diff[2]**2)
            P = pmag.dir2cart(
                ((pars["specimen_dec"] - angle), pars["specimen_inc"], R/2.5))
            px, py, pz = [], [], []
            px.append((cm[0] + P[0]))
            py.append((cm[1] + P[1]))
            pz.append((cm[2] + P[2]))
            px.append((cm[0] - P[0]))
            py.append((cm[1] - P[1]))
            pz.append((cm[2] - P[2]))

        plt.plot(px, py, 'g', linewidth=2)
        plt.plot(px, pz, 'g', linewidth=2)
        plt.axis("equal")
    else:
        plt.figure(num=ZED['eqarea'])
        XY = pmag.dimap(StartDir[0], StartDir[1])
        x.append(XY[0])
        y.append(XY[1])
        XY = pmag.dimap(EndDir[0], EndDir[1])
        x.append(XY[0])
        y.append(XY[1])
        plt.scatter(x, y, marker='d', s=80, c='b')
        pole.append(pars["specimen_dec"])
        pole.append(pars["specimen_inc"])
        plot_circ(ZED['eqarea'], pole, 90., 'g')
        plt.xlim((-1., 1.))
        plt.ylim((-1., 1.))
        plt.axis("equal")


Instruction:
Create a Python 3 function for
making Arai plots for Thellier-Thellier type experiments Parameters __________ fignum : figure number of matplotlib plot object indata : nested list of data for Arai plots: the araiblock of data prepared by pmag.sortarai() s : specimen name units : [K, J, ""] (kelvin, joules, unknown) Effects _______ makes the Arai plot

Response:
def plot_arai(fignum, indata, s, units):
    """
    makes Arai plots for Thellier-Thellier type experiments

    Parameters
    __________
    fignum : figure number of matplotlib plot object
    indata : nested list of data for Arai plots:
        the araiblock of data prepared by pmag.sortarai()
    s : specimen name
    units : [K, J, ""] (kelvin, joules, unknown)
    Effects
    _______
    makes the Arai plot
    """
    global globals
    plt.figure(num=fignum)
    plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    x, y, x_zi, y_zi, x_iz, y_iz, xptrm, yptrm, xptrmt, yptrmt = [
    ], [], [], [], [], [], [], [], [], []
    xzptrm, yzptrm = [], []  # zero field ptrm checks
    zptrm_check = []
    first_Z, first_I, ptrm_check, ptrm_tail, zptrm_check = indata[
        0], indata[1], indata[2], indata[3], indata[4]
    if len(indata) > 6:
        if len(indata[-1]) > 1:
            s = s + ":PERP"  # there are Delta checks, must be a LP-PI-M-S perp experiment
    recnum, yes, Nptrm, Nptrmt, diffcum = 0, 0, 0, 0, 0
# plot the NRM-pTRM data
    forVDS = []
    for zrec in first_Z:
        forVDS.append([zrec[1], zrec[2], old_div(zrec[3], first_Z[0][3])])
        ZI = zrec[4]
        if zrec[0] == '0':
            irec = ['0', 0, 0, 0]
        if zrec[0] == '273' and units == 'K':
            irec = ['273', 0, 0, 0]
        else:
            for irec in first_I:
                if irec[0] == zrec[0]:
                    break
# save the NRM data used for calculation in Vi
        x.append(old_div(irec[3], first_Z[0][3]))
        y.append(old_div(zrec[3], first_Z[0][3]))
        if ZI == 1:
            x_zi.append(old_div(irec[3], first_Z[0][3]))
            y_zi.append(old_div(zrec[3], first_Z[0][3]))
        else:
            x_iz.append(old_div(irec[3], first_Z[0][3]))
            y_iz.append(old_div(zrec[3], first_Z[0][3]))
        plt.text(x[-1], y[-1], (' ' + str(recnum)), fontsize=9)
        recnum += 1
# now deal with ptrm checks.
    if len(ptrm_check) != 0:
        for prec in ptrm_check:
            step = prec[0]
            for zrec in first_Z:
                if zrec[0] == step:
                    break
            xptrm.append(old_div(prec[3], first_Z[0][3]))
            yptrm.append(old_div(zrec[3], first_Z[0][3]))
# now deal with zptrm checks.
    if len(zptrm_check) != 0:
        for prec in zptrm_check:
            step = prec[0]
            for zrec in first_Z:
                if zrec[0] == step:
                    break
            xzptrm.append(old_div(prec[3], first_Z[0][3]))
            yzptrm.append(old_div(zrec[3], first_Z[0][3]))
# and the pTRM tails
    if len(ptrm_tail) != 0:
        for trec in ptrm_tail:
            step = trec[0]
            for irec in first_I:
                if irec[0] == step:
                    break
            xptrmt.append(old_div(irec[3], first_Z[0][3]))
            yptrmt.append((old_div(trec[3], first_Z[0][3])))
# now plot stuff
    if len(x) == 0:
        print("Can't do nuttin for ya")
        return
    try:
        if len(x_zi) > 0:
            plt.scatter(x_zi, y_zi, marker='o', c='r',
                        edgecolors="none")  # zero field-infield
        if len(x_iz) > 0:
            plt.scatter(x_iz, y_iz, marker='s', c='b',
                        faceted="True")  # infield-zerofield
    except:
        if len(x_zi) > 0:
            plt.scatter(x_zi, y_zi, marker='o', c='r')  # zero field-infield
        if len(x_iz) > 0:
            plt.scatter(x_iz, y_iz, marker='s', c='b')  # infield-zerofield
    plt.plot(x, y, 'r')
    if globals != 0:
        globals.MTlist = x
        globals.MTlisty = y
    if len(xptrm) > 0:
        plt.scatter(xptrm, yptrm, marker='^', c='g', s=80)
    if len(xzptrm) > 0:
        plt.scatter(xzptrm, yzptrm, marker='v', c='c', s=80)
    if len(xptrmt) > 0:
        plt.scatter(xptrmt, yptrmt, marker='s', c='b', s=80)
    try:
        plt.axhline(0, color='k')
        plt.axvline(0, color='k')
    except:
        pass
    plt.xlabel("pTRM gained")
    plt.ylabel("NRM remaining")
    tstring = s + ': NRM = ' + '%9.2e' % (first_Z[0][3])
    plt.title(tstring)
# put on VDS
    vds = pmag.dovds(forVDS)
    plt.axhline(vds, color='b')
    plt.text(1., vds - .1, ('VDS '), fontsize=9)


Instruction:
Explain what the following Python 3 code does
def plot_np(fignum, indata, s, units):
    global globals
    first_Z, first_I, ptrm_check, ptrm_tail = indata[0], indata[1], indata[2], indata[3]
    plt.figure(num=fignum)
    plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    X, Y, recnum = [], [], 0
#
    for rec in first_Z:
        if units == "K":
            if rec[0] != 0:
                X.append(rec[0] - 273.)
            else:
                X.append(rec[0])
        if (units == "J") or (not units) or (units == "T"):
            X.append(rec[0])
        Y.append(old_div(rec[3], first_Z[0][3]))
        delta = .02 * Y[0]
        if recnum % 2 == 0:
            plt.text(X[-1] - delta, Y[-1] + delta,
                     (' ' + str(recnum)), fontsize=9)
        recnum += 1
    plt.plot(X, Y)
    plt.scatter(X, Y, marker='o', color='b')
    X, Y = [], []
    for rec in first_I:
        if units == "K":
            if rec[0] != 0:
                X.append(rec[0] - 273)
            else:
                X.append(rec[0])
        if (units == "J") or (not units) or (units == "T"):
            X.append(rec[0])
        Y.append(old_div(rec[3], first_Z[0][3]))
    if globals != 0:
        globals.DIlist = X
        globals.DIlisty = Y
    plt.plot(X, Y)
    plt.scatter(X, Y, marker='s', color='r')
    plt.ylabel("Circles: NRM; Squares: pTRM")
    if units == "K":
        plt.xlabel("Temperature (C)")
    elif units == "J":
        plt.xlabel("Microwave Energy (J)")
    else:
        plt.xlabel("")
    title = s + ": NRM = " + '%9.2e' % (first_Z[0][3])
    plt.title(title)
    plt.axhline(y=0, xmin=0, xmax=1, color='k')
    plt.axvline(x=0, ymin=0, ymax=1, color='k')

Response: This function plots the data for a specific Thellier - Thellier type experiment.


Instruction:
Given the following Python 3 function, write the documentation
def plot_arai_zij(ZED, araiblock, zijdblock, s, units):
    angle = zijdblock[0][1]
    norm = 1
    if units == "U":
        norm = 0
    plot_arai(ZED['arai'], araiblock, s, units)
    plot_teq(ZED['eqarea'], araiblock, s, "")
    plot_zij(ZED['zijd'], zijdblock, angle, s, norm)
    plot_np(ZED['deremag'], araiblock, s, units)
    return ZED

Response: Plots the Arai and Zijderveld diagrams for Thellier - Thellier experiments.