Example #1
0
def main():
    """
    NAME
       qqunf.py

    DESCRIPTION
       makes qq plot from input data against uniform distribution

    SYNTAX
       qqunf.py [command line options]

    OPTIONS
        -h help message
        -f FILE, specify file on command line

    """
    fmt, plot = 'svg', 0
    if '-h' in sys.argv:  # check if help is needed
        print(main.__doc__)
        sys.exit()  # graceful quit
    elif '-f' in sys.argv:  # ask for filename
        ind = sys.argv.index('-f')
        file = sys.argv[ind + 1]
        f = open(file, 'r')
        input = f.readlines()
    Data = []
    for line in input:
        line.replace('\n', '')
        if '\t' in line:  # read in the data from standard input
            rec = line.split('\t')  # split each line on space to get records
        else:
            rec = line.split()  # split each line on space to get records
        Data.append(float(rec[0]))


#
    if len(Data) >= 10:
        QQ = {'unf1': 1}
        pmagplotlib.plot_init(QQ['unf1'], 5, 5)
        pmagplotlib.plot_qq_unf(QQ['unf1'], Data, 'QQ-Uniform')  # make plot
    else:
        print('you need N> 10')
        sys.exit()
    pmagplotlib.draw_figs(QQ)
    files = {}
    for key in list(QQ.keys()):
        files[key] = key + '.' + fmt
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['eq'] = 'Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ, titles, black, purple)
        pmagplotlib.save_plots(QQ, files)
    elif plot == 1:
        files['qq'] = file + '.' + fmt
        pmagplotlib.save_plots(QQ, files)
    else:
        ans = input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans == "a": pmagplotlib.save_plots(QQ, files)
Example #2
0
def main():
    """
    NAME
       revtest_MM1990.py

    DESCRIPTION
       calculates Watson's V statistic from input files through Monte Carlo simulation in order to test whether normal and reversed populations could have been drawn from a common mean (equivalent to watsonV.py). Also provides the critical angle between the two sample mean directions and the corresponding McFadden and McElhinny (1990) classification.

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files (one file for normal directions, one file for reversed directions).

    SYNTAX
       revtest_MM1990.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE
        -f2 FILE
        -P  (don't plot the Watson V cdf)

    OUTPUT
        Watson's V between the two populations and the Monte Carlo Critical Value Vc.
        M&M1990 angle, critical angle and classification
        Plot of Watson's V CDF from Monte Carlo simulation (red line), V is solid and Vc is dashed.

    """
    D1, D2 = [], []
    plot = 1
    Flip = 1
    if '-h' in sys.argv:  # check if help is needed
        print(main.__doc__)
        sys.exit()  # graceful quit
    if '-P' in sys.argv: plot = 0
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file1 = sys.argv[ind + 1]
    f1 = open(file1, 'r')
    for line in f1.readlines():
        rec = line.split()
        Dec, Inc = float(rec[0]), float(rec[1])
        D1.append([Dec, Inc, 1.])
    f1.close()
    if '-f2' in sys.argv:
        ind = sys.argv.index('-f2')
        file2 = sys.argv[ind + 1]
        f2 = open(file2, 'r')
        print("be patient, your computer is doing 5000 simulations...")
        for line in f2.readlines():
            rec = line.split()
            Dec, Inc = float(rec[0]), float(rec[1])
            D2.append([Dec, Inc, 1.])
        f2.close()
    #take the antipode for the directions in file 2
    D2_flip = []
    for rec in D2:
        d, i = (rec[0] - 180.) % 360., -rec[1]
        D2_flip.append([d, i, 1.])

    pars_1 = pmag.fisher_mean(D1)
    pars_2 = pmag.fisher_mean(D2_flip)

    cart_1 = pmag.dir2cart([pars_1["dec"], pars_1["inc"], pars_1["r"]])
    cart_2 = pmag.dir2cart([pars_2['dec'], pars_2['inc'], pars_2["r"]])
    Sw = pars_1['k'] * pars_1['r'] + pars_2['k'] * pars_2['r']  # k1*r1+k2*r2
    xhat_1 = pars_1['k'] * cart_1[0] + pars_2['k'] * cart_2[0]  # k1*x1+k2*x2
    xhat_2 = pars_1['k'] * cart_1[1] + pars_2['k'] * cart_2[1]  # k1*y1+k2*y2
    xhat_3 = pars_1['k'] * cart_1[2] + pars_2['k'] * cart_2[2]  # k1*z1+k2*z2
    Rw = numpy.sqrt(xhat_1**2 + xhat_2**2 + xhat_3**2)
    V = 2 * (Sw - Rw)
    #
    #keep weighted sum for later when determining the "critical angle" let's save it as Sr (notation of McFadden and McElhinny, 1990)
    #
    Sr = Sw
    #
    # do monte carlo simulation of datasets with same kappas, but common mean
    #
    counter, NumSims = 0, 5000
    Vp = []  # set of Vs from simulations
    for k in range(NumSims):
        #
        # get a set of N1 fisher distributed vectors with k1, calculate fisher stats
        #
        Dirp = []
        for i in range(pars_1["n"]):
            Dirp.append(pmag.fshdev(pars_1["k"]))
        pars_p1 = pmag.fisher_mean(Dirp)
        #
        # get a set of N2 fisher distributed vectors with k2, calculate fisher stats
        #
        Dirp = []
        for i in range(pars_2["n"]):
            Dirp.append(pmag.fshdev(pars_2["k"]))
        pars_p2 = pmag.fisher_mean(Dirp)
        #
        # get the V for these
        #
        Vk = pmag.vfunc(pars_p1, pars_p2)
        Vp.append(Vk)


#
# sort the Vs, get Vcrit (95th percentile one)
#
    Vp.sort()
    k = int(.95 * NumSims)
    Vcrit = Vp[k]
    #
    # equation 18 of McFadden and McElhinny, 1990 calculates the critical value of R (Rwc)
    #
    Rwc = Sr - (old_div(Vcrit, 2))
    #
    #following equation 19 of McFadden and McElhinny (1990) the critical angle is calculated.
    #
    k1 = pars_1['k']
    k2 = pars_2['k']
    R1 = pars_1['r']
    R2 = pars_2['r']
    critical_angle = numpy.degrees(
        numpy.arccos(
            old_div(((Rwc**2) - ((k1 * R1)**2) - ((k2 * R2)**2)),
                    (2 * k1 * R1 * k2 * R2))))
    D1_mean = (pars_1['dec'], pars_1['inc'])
    D2_mean = (pars_2['dec'], pars_2['inc'])
    angle = pmag.angle(D1_mean, D2_mean)
    #
    # print the results of the test
    #
    print("")
    print("Results of Watson V test: ")
    print("")
    print("Watson's V:           " '%.1f' % (V))
    print("Critical value of V:  " '%.1f' % (Vcrit))

    if V < Vcrit:
        print(
            '"Pass": Since V is less than Vcrit, the null hypothesis that the two populations are drawn from distributions that share a common mean direction (antipodal to one another) cannot be rejected.'
        )
    elif V > Vcrit:
        print(
            '"Fail": Since V is greater than Vcrit, the two means can be distinguished at the 95% confidence level.'
        )
    print("")
    print("M&M1990 classification:")
    print("")
    print("Angle between data set means: " '%.1f' % (angle))
    print("Critical angle of M&M1990:   " '%.1f' % (critical_angle))

    if V > Vcrit:
        print("")
    elif V < Vcrit:
        if critical_angle < 5:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'A'"
            )
        elif critical_angle < 10:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'B'"
            )
        elif critical_angle < 20:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'C'"
            )
        else:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'INDETERMINATE;"
            )
    if plot == 1:
        CDF = {'cdf': 1}
        pmagplotlib.plot_init(CDF['cdf'], 5, 5)
        p1 = pmagplotlib.plot_cdf(CDF['cdf'], Vp, "Watson's V", 'r', "")
        p2 = pmagplotlib.plot_vs(CDF['cdf'], [V], 'g', '-')
        p3 = pmagplotlib.plot_vs(CDF['cdf'], [Vp[k]], 'b', '--')
        pmagplotlib.draw_figs(CDF)
        files, fmt = {}, 'svg'
        if file2 != "":
            files['cdf'] = 'WatsonsV_' + file1 + '_' + file2 + '.' + fmt
        else:
            files['cdf'] = 'WatsonsV_' + file1 + '.' + fmt
        if pmagplotlib.isServer:
            black = '#000000'
            purple = '#800080'
            titles = {}
            titles['cdf'] = 'Cumulative Distribution'
            CDF = pmagplotlib.add_borders(CDF, titles, black, purple)
            pmagplotlib.save_plots(CDF, files)
        else:
            ans = input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans == "a": pmagplotlib.save_plots(CDF, files)
Example #3
0
def main():
    """
    NAME
        eqarea_ell.py

    DESCRIPTION
       makes equal area projections from declination/inclination data
       and plot ellipses

    SYNTAX
        eqarea_ell.py -h [command line options]

    INPUT
       takes space delimited Dec/Inc data

    OPTIONS
        -h prints help message and quits
        -f FILE
        -fmt [svg,png,jpg] format for output plots
        -sav  saves figures and quits
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
    """
    FIG={} # plot dictionary
    FIG['eq']=1 # eqarea is figure 1
    fmt,dist,mode,plot='svg','F',1,0
    sym={'lower':['o','r'],'upper':['o','w'],'size':10}
    plotE=0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if not set_env.IS_WIN:
        pmagplotlib.plot_init(FIG['eq'],5,5)
    if '-sav' in sys.argv:plot=1
    if '-f' in sys.argv:
        ind=sys.argv.index("-f")
        title=sys.argv[ind+1]
        data=numpy.loadtxt(title).transpose()
    if '-ell' in sys.argv:
        plotE=1
        ind=sys.argv.index('-ell')
        ell_type=sys.argv[ind+1]
        if ell_type=='F':dist='F'
        if ell_type=='K':dist='K'
        if ell_type=='B':dist='B'
        if ell_type=='Be':dist='BE'
        if ell_type=='Bv':
            dist='BV'
            FIG['bdirs']=2
            pmagplotlib.plot_init(FIG['bdirs'],5,5)
    if '-fmt' in sys.argv:
        ind=sys.argv.index("-fmt")
        fmt=sys.argv[ind+1]
    DIblock=numpy.array([data[0],data[1]]).transpose()
    if len(DIblock)>0:
        pmagplotlib.plot_eq_sym(FIG['eq'],DIblock,title,sym)
        #if plot==0:pmagplotlib.draw_figs(FIG)
    else:
        print("no data to plot")
        sys.exit()
    if plotE==1:
        ppars=pmag.doprinc(DIblock) # get principal directions
        nDIs,rDIs,npars,rpars=[],[],[],[]
        for rec in DIblock:
            angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
            if angle>90.:
                rDIs.append(rec)
            else:
                nDIs.append(rec)
        if dist=='B': # do on whole dataset
            etitle="Bingham confidence ellipse"
            bpars=pmag.dobingham(DIblock)
            for key in list(bpars.keys()):
                if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(bpars[key]))
                if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(bpars[key]))
            npars.append(bpars['dec'])
            npars.append(bpars['inc'])
            npars.append(bpars['Zeta'])
            npars.append(bpars['Zdec'])
            npars.append(bpars['Zinc'])
            npars.append(bpars['Eta'])
            npars.append(bpars['Edec'])
            npars.append(bpars['Einc'])
        if dist=='F':
            etitle="Fisher confidence cone"
            if len(nDIs)>3:
                fpars=pmag.fisher_mean(nDIs)
                for key in list(fpars.keys()):
                    if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(fpars[key]))
                    if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(fpars[key]))
                mode+=1
                npars.append(fpars['dec'])
                npars.append(fpars['inc'])
                npars.append(fpars['alpha95']) # Beta
                npars.append(fpars['dec'])
                isign=abs(fpars['inc']) / fpars['inc']
                npars.append(fpars['inc']-isign*90.) #Beta inc
                npars.append(fpars['alpha95']) # gamma
                npars.append(fpars['dec']+90.) # Beta dec
                npars.append(0.) #Beta inc
            if len(rDIs)>3:
                fpars=pmag.fisher_mean(rDIs)
                if pmagplotlib.verbose:print("mode ",mode)
                for key in list(fpars.keys()):
                    if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(fpars[key]))
                    if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(fpars[key]))
                mode+=1
                rpars.append(fpars['dec'])
                rpars.append(fpars['inc'])
                rpars.append(fpars['alpha95']) # Beta
                rpars.append(fpars['dec'])
                isign=abs(fpars['inc']) / fpars['inc']
                rpars.append(fpars['inc']-isign*90.) #Beta inc
                rpars.append(fpars['alpha95']) # gamma
                rpars.append(fpars['dec']+90.) # Beta dec
                rpars.append(0.) #Beta inc
        if dist=='K':
            etitle="Kent confidence ellipse"
            if len(nDIs)>3:
                kpars=pmag.dokent(nDIs,len(nDIs))
                if pmagplotlib.verbose:print("mode ",mode)
                for key in list(kpars.keys()):
                    if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(kpars[key]))
                    if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(kpars[key]))
                mode+=1
                npars.append(kpars['dec'])
                npars.append(kpars['inc'])
                npars.append(kpars['Zeta'])
                npars.append(kpars['Zdec'])
                npars.append(kpars['Zinc'])
                npars.append(kpars['Eta'])
                npars.append(kpars['Edec'])
                npars.append(kpars['Einc'])
            if len(rDIs)>3:
                kpars=pmag.dokent(rDIs,len(rDIs))
                if pmagplotlib.verbose:print("mode ",mode)
                for key in list(kpars.keys()):
                    if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(kpars[key]))
                    if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(kpars[key]))
                mode+=1
                rpars.append(kpars['dec'])
                rpars.append(kpars['inc'])
                rpars.append(kpars['Zeta'])
                rpars.append(kpars['Zdec'])
                rpars.append(kpars['Zinc'])
                rpars.append(kpars['Eta'])
                rpars.append(kpars['Edec'])
                rpars.append(kpars['Einc'])
        else: # assume bootstrap
            if len(nDIs)<10 and len(rDIs)<10:
                print('too few data points for bootstrap')
                sys.exit()
            if dist=='BE':
                print('Be patient for bootstrap...')
                if len(nDIs)>=10:
                    BnDIs=pmag.di_boot(nDIs)
                    Bkpars=pmag.dokent(BnDIs,1.)
                    if pmagplotlib.verbose:print("mode ",mode)
                    for key in list(Bkpars.keys()):
                        if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(Bkpars[key]))
                        if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(Bkpars[key]))
                    mode+=1
                    npars.append(Bkpars['dec'])
                    npars.append(Bkpars['inc'])
                    npars.append(Bkpars['Zeta'])
                    npars.append(Bkpars['Zdec'])
                    npars.append(Bkpars['Zinc'])
                    npars.append(Bkpars['Eta'])
                    npars.append(Bkpars['Edec'])
                    npars.append(Bkpars['Einc'])
                if len(rDIs)>=10:
                    BrDIs=pmag.di_boot(rDIs)
                    Bkpars=pmag.dokent(BrDIs,1.)
                    if pmagplotlib.verbose:print("mode ",mode)
                    for key in list(Bkpars.keys()):
                        if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(Bkpars[key]))
                        if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(Bkpars[key]))
                    mode+=1
                    rpars.append(Bkpars['dec'])
                    rpars.append(Bkpars['inc'])
                    rpars.append(Bkpars['Zeta'])
                    rpars.append(Bkpars['Zdec'])
                    rpars.append(Bkpars['Zinc'])
                    rpars.append(Bkpars['Eta'])
                    rpars.append(Bkpars['Edec'])
                    rpars.append(Bkpars['Einc'])
                etitle="Bootstrapped confidence ellipse"
            elif dist=='BV':
                print('Be patient for bootstrap...')
                vsym={'lower':['+','k'],'upper':['x','k'],'size':5}
                if len(nDIs)>5:
                    BnDIs=pmag.di_boot(nDIs)
                    pmagplotlib.plot_eq_sym(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors',vsym)
                if len(rDIs)>5:
                    BrDIs=pmag.di_boot(rDIs)
                    if len(nDIs)>5:  # plot on existing plots
                        pmagplotlib.plot_di_sym(FIG['bdirs'],BrDIs,vsym)
                    else:
                        pmagplotlib.plot_eq(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors',vsym)
        if dist=='B':
            if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plot_conf(FIG['eq'],etitle,[],npars,0)
        elif len(nDIs)>3 and dist!='BV':
            pmagplotlib.plot_conf(FIG['eq'],etitle,[],npars,0)
            if len(rDIs)>3:
                pmagplotlib.plot_conf(FIG['eq'],etitle,[],rpars,0)
        elif len(rDIs)>3 and dist!='BV':
            pmagplotlib.plot_conf(FIG['eq'],etitle,[],rpars,0)
        #if plot==0:pmagplotlib.draw_figs(FIG)
    if plot==0:pmagplotlib.draw_figs(FIG)
        #
    files={}
    for key in list(FIG.keys()):
        files[key]=title+'_'+key+'.'+fmt
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        FIG = pmagplotlib.add_borders(FIG,titles,black,purple)
        pmagplotlib.save_plots(FIG,files)
    elif plot==0:
        ans=input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans=="q": sys.exit()
        if ans=="a":
            pmagplotlib.save_plots(FIG,files)
    else:
        pmagplotlib.save_plots(FIG,files)
Example #4
0
def main():
    """
    NAME
        vgpmap_magic.py

    DESCRIPTION
        makes a map of vgps and a95/dp,dm for site means in a pmag_results table

    SYNTAX
        vgpmap_magic.py [command line options]

    OPTIONS
        -h prints help and quits
        -eye  ELAT ELON [specify eyeball location], default is 90., 0.
        -f FILE pmag_results format file, [default is pmag_results.txt]
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -etp plot the etopo20 topographpy data (requires high resolution data set)
        -prj PROJ,  specify one of the following:
             ortho = orthographic
             lcc = lambert conformal
             moll = molweide
             merc = mercator
        -sym SYM SIZE: choose a symbol and size, examples:
            ro 5 : small red circles
            bs 10 : intermediate blue squares
            g^ 20 : large green triangles
        -ell  plot dp/dm or a95 ellipses
        -rev RSYM RSIZE : flip reverse poles to normal antipode
        -S:  plot antipodes of all poles
        -age : plot the ages next to the poles
        -crd [g,t] : choose coordinate system, default is to plot all site VGPs
        -fmt [pdf, png, eps...] specify output format, default is pdf
        -sav  save and quit
    DEFAULTS
        FILE: pmag_results.txt
        res:  c
        prj: ortho
        ELAT,ELON = 0,0
        SYM SIZE: ro 8
        RSYM RSIZE: g^ 8

    """
    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)
Example #5
0
def main():
    """
    NAME
        microwave_magic.py

    DESCRIPTION
        plots microwave paleointensity data, allowing interactive setting of bounds.
        Saves and reads interpretations
        from a pmag_specimen formatted table, default: microwave_specimens.txt

    SYNTAX
        microwave_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set magic_measurements input file
        -fsp PRIOR, set pmag_specimen prior interpretations file
        -fcr CRIT, set criteria file for grading.
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (default format)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds adn quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step for slope calculation
           END: ending step for slope calculation

    DEFAULTS
        MEAS: magic_measurements.txt
        CRIT: NONE
        PRIOR: microwave_specimens.txt

    OUTPUT
        figures:
            ALL:  numbers refer to temperature steps in command line window
            1) Arai plot:  closed circles are zero-field first/infield
                           open circles are infield first/zero-field
                           triangles are pTRM checks
                           squares are pTRM tail checks
                           VDS is vector difference sum
                           diamonds are bounds for interpretation
            2) Zijderveld plot:  closed (open) symbols are X-Y (X-Z) planes
                                 X rotated to NRM direction
            3) (De/Re)Magnetization diagram:
                           circles are NRM remaining
                           squares are pTRM gained
        command line window:
            list is: temperature step numbers, power (J), Dec, Inc, Int (units of magic_measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates .svg format files with specimen_name, plot type as name
    """
    #
    #   initializations
    #
    meas_file, critout, inspec = "magic_measurements.txt", "", "microwave_specimens.txt"
    inlt = 0
    version_num = pmag.get_version()
    Tinit, DCZ, field, first_save = 0, 0, -1, 1
    user, comment = "", ''
    ans, specimen, recnum, start, end = 0, 0, 0, 0, 0
    plots, pmag_out, samp_file, style = 0, "", "", "svg"
    fmt = '.' + style
    #
    # default acceptance criteria
    #
    accept_keys = [
        'specimen_int_ptrm_n', 'specimen_md', 'specimen_fvds',
        'specimen_b_beta', 'specimen_dang', 'specimen_drats', 'specimen_Z'
    ]
    accept = {}
    accept['specimen_int_ptrm_n'] = 2
    accept['specimen_md'] = 10
    accept['specimen_fvds'] = 0.35
    accept['specimen_b_beta'] = .1
    accept['specimen_int_mad'] = 7
    accept['specimen_dang'] = 10
    accept['specimen_drats'] = 10
    accept['specimen_Z'] = 10
    #
    # parse command line options
    #
    spc, BEG, END = "", "", ""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        meas_file = sys.argv[ind + 1]
    if '-fsp' in sys.argv:
        ind = sys.argv.index('-fsp')
        inspec = sys.argv[ind + 1]
    if '-fcr' in sys.argv:
        ind = sys.argv.index('-fcr')
        critout = sys.argv[ind + 1]
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = '.' + sys.argv[ind + 1]
    if '-spc' in sys.argv:
        ind = sys.argv.index('-spc')
        spc = sys.argv[ind + 1]
        if '-b' in sys.argv:
            ind = sys.argv.index('-b')
            BEG = int(sys.argv[ind + 1])
            END = int(sys.argv[ind + 2])
    if critout != "":
        crit_data, file_type = pmag.magic_read(critout)
        if pmagplotlib.verbose:
            print("Acceptance criteria read in from ", critout)
        accept = {}
        accept['specimen_int_ptrm_n'] = 2.0
        for critrec in crit_data:
            if critrec["pmag_criteria_code"] == "IE-SPEC":
                for key in accept_keys:
                    if key not in list(critrec.keys()):
                        accept[key] = -1
                    else:
                        accept[key] = float(critrec[key])
    try:
        open(inspec, 'r')
        PriorRecs, file_type = pmag.magic_read(inspec)
        if file_type != 'pmag_specimens':
            print(file_type)
            print(file_type, inspec, " is not a valid pmag_specimens file ")
            sys.exit()
        for rec in PriorRecs:
            if 'magic_software_packages' not in list(rec.keys()):
                rec['magic_software_packages'] = ""
    except IOError:
        PriorRecs = []
        if pmagplotlib.verbose:
            print("starting new specimen interpretation file: ", inspec)
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(file_type)
        print(file_type, "This is not a valid magic_measurements file ")
        sys.exit()
    backup = 0
    # define figure numbers for arai, zijderveld and
    #   de-,re-magization diagrams
    AZD = {}
    AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4
    pmagplotlib.plot_init(AZD['arai'], 4, 4)
    pmagplotlib.plot_init(AZD['zijd'], 4, 4)
    pmagplotlib.plot_init(AZD['deremag'], 4, 4)
    pmagplotlib.plot_init(AZD['eqarea'], 4, 4)
    #
    #
    #
    # get list of unique specimen names
    #
    CurrRec = []
    sids = pmag.get_specs(meas_data)
    # get plots for specimen s - default is just to step through arai diagrams
    #
    if spc != "": specimen = sids.index(spc)
    while specimen < len(sids):
        methcodes = []
        if pmagplotlib.verbose and spc != "":
            print(sids[specimen], specimen + 1, 'of ', len(sids))
        MeasRecs = []
        s = sids[specimen]
        datablock, trmblock = [], []
        PmagSpecRec = {}
        PmagSpecRec["er_analyst_mail_names"] = user
        PmagSpecRec["specimen_correction"] = 'u'
        #
        # find the data from the meas_data file for this specimen
        #
        for rec in meas_data:
            if rec["er_specimen_name"] == s:
                MeasRecs.append(rec)
                methods = rec["magic_method_codes"].split(":")
                meths = []
                for meth in methods:
                    meths.append(meth.strip())  # take off annoying spaces
                methods = ""
                for meth in meths:
                    if meth.strip() not in methcodes and "LP-" in meth:
                        methcodes.append(meth.strip())
                    methods = methods + meth + ":"
                methods = methods[:-1]
                rec["magic_method_codes"] = methods
                if "LP-PI-M" in meths: datablock.append(rec)
                if "LP-MRM" in meths: trmblock.append(rec)
        if len(trmblock) > 2 and inspec != "":
            if Tinit == 0:
                Tinit = 1
                AZD['MRM'] = 4
                pmagplotlib.plot_init(AZD['MRM'], 4, 4)
            elif Tinit == 1:
                pmagplotlib.clearFIG(AZD['MRM'])
        if len(datablock) < 4:
            if backup == 0:
                specimen += 1
                if pmagplotlib.verbose:
                    print('skipping specimen - moving forward ', s)
            else:
                specimen -= 1
                if pmagplotlib.verbose:
                    print('skipping specimen - moving backward ', s)
    #
    #  collect info for the PmagSpecRec dictionary
    #
        else:
            rec = datablock[0]
            PmagSpecRec["er_citation_names"] = "This study"
            PmagSpecRec["er_specimen_name"] = s
            PmagSpecRec["er_sample_name"] = rec["er_sample_name"]
            PmagSpecRec["er_site_name"] = rec["er_site_name"]
            PmagSpecRec["er_location_name"] = rec["er_location_name"]
            if "magic_instrument_codes" not in list(rec.keys()):
                rec["magic_instrument_codes"] = ""
            PmagSpecRec["magic_instrument_codes"] = rec[
                "magic_instrument_codes"]
            PmagSpecRec["measurement_step_unit"] = "J"
            if "magic_experiment_name" not in list(rec.keys()):
                rec["magic_experiment_name"] = ""
            else:
                PmagSpecRec["magic_experiment_names"] = rec[
                    "magic_experiment_name"]

            meths = rec["magic_method_codes"].split(':')
            # sort data into types
            if "LP-PI-M-D" in meths:  # this is a double heating experiment
                exp_type = "LP-PI-M-D"
            elif "LP-PI-M-S" in meths:
                exp_type = "LP-PI-M-S"
            else:
                print("experiment type not supported yet ")
                break
            araiblock, field = pmag.sortmwarai(datablock, exp_type)
            first_Z = araiblock[0]
            first_I = araiblock[1]
            GammaChecks = araiblock[-3]
            ThetaChecks = araiblock[-2]
            DeltaChecks = araiblock[-1]
            if len(first_Z) < 3:
                if backup == 0:
                    specimen += 1
                    if pmagplotlib.verbose:
                        print('skipping specimen - moving forward ', s)
                else:
                    specimen -= 1
                    if pmagplotlib.verbose:
                        print('skipping specimen - moving backward ', s)
            else:
                backup = 0
                zijdblock, units = pmag.find_dmag_rec(s, meas_data)
                if exp_type == "LP-PI-M-D":
                    recnum = 0
                    print("ZStep Watts  Dec Inc  Int")
                    for plotrec in zijdblock:
                        if pmagplotlib.verbose:
                            print('%i  %i %7.1f %7.1f %8.3e ' %
                                  (recnum, plotrec[0], plotrec[1], plotrec[2],
                                   plotrec[3]))
                            recnum += 1
                    recnum = 1
                    if GammaChecks != "":
                        print("IStep Watts  Gamma")
                        for gamma in GammaChecks:
                            if pmagplotlib.verbose:
                                print('%i %i %7.1f ' %
                                      (recnum, gamma[0], gamma[1]))
                            recnum += 1
                if exp_type == "LP-PI-M-S":
                    if pmagplotlib.verbose:
                        print("IStep Watts  Theta")
                        kk = 0
                        for theta in ThetaChecks:
                            kk += 1
                            print('%i  %i %7.1f ' % (kk, theta[0], theta[1]))
                    if pmagplotlib.verbose:
                        print("Watts  Delta")
                        for delta in DeltaChecks:
                            print('%i %7.1f ' % (delta[0], delta[1]))
                pmagplotlib.plot_arai_zij(AZD, araiblock, zijdblock, s,
                                          units[0])
                if inspec != "":
                    if pmagplotlib.verbose:
                        print('Looking up saved interpretation....')
                    found = 0
                    for k in range(len(PriorRecs)):
                        try:
                            if PriorRecs[k]["er_specimen_name"] == s:
                                found = 1
                                CurrRec.append(PriorRecs[k])
                                for j in range(len(araiblock[0])):
                                    if float(araiblock[0][j][0]) == float(
                                            PriorRecs[k]
                                        ["measurement_step_min"]):
                                        start = j
                                    if float(araiblock[0][j][0]) == float(
                                            PriorRecs[k]
                                        ["measurement_step_max"]):
                                        end = j
                                pars, errcode = pmag.PintPars(
                                    araiblock, zijdblock, start, end)
                                pars['measurement_step_unit'] = "J"
                                del PriorRecs[
                                    k]  # put in CurrRec, take out of PriorRecs
                                if errcode != 1:
                                    pars["specimen_lab_field_dc"] = field
                                    pars["specimen_int"] = -1 * field * pars[
                                        "specimen_b"]
                                    pars["er_specimen_name"] = s
                                    if pmagplotlib.verbose:
                                        print('Saved interpretation: ')
                                    pars = pmag.scoreit(
                                        pars, PmagSpecRec, accept, '', 0)
                                    pmagplotlib.plot_b(AZD, araiblock,
                                                       zijdblock, pars)
                                    if len(trmblock) > 2:
                                        blab = field
                                        best = pars["specimen_int"]
                                        Bs, TRMs = [], []
                                        for trec in trmblock:
                                            Bs.append(
                                                float(
                                                    trec['treatment_dc_field'])
                                            )
                                            TRMs.append(
                                                float(trec[
                                                    'measurement_magn_moment'])
                                            )
                                        NLpars = nlt.NLtrm(
                                            Bs, TRMs, best, blab, 0
                                        )  # calculate best fit parameters through TRM acquisition data, and get new banc
                                        Mp, Bp = [], []
                                        for k in range(int(max(Bs) * 1e6)):
                                            Bp.append(float(k) * 1e-6)
                                            npred = nlt.TRM(
                                                Bp[-1], NLpars['xopt'][0],
                                                NLpars['xopt'][1]
                                            )  # predicted NRM for this field
                                            Mp.append(npred)
                                        pmagplotlib.plot_trm(
                                            AZD['MRM'], Bs, TRMs, Bp, Mp,
                                            NLpars,
                                            trec['magic_experiment_name'])
                                        print(npred)
                                        print('Banc= ',
                                              float(NLpars['banc']) * 1e6)
                                        if pmagplotlib.verbose:
                                            print('Banc= ',
                                                  float(NLpars['banc']) * 1e6)
                                        pmagplotlib.draw_figs(AZD)
                                else:
                                    print('error on specimen ', s)
                        except:
                            pass
                    if pmagplotlib.verbose and found == 0:
                        print('    None found :(  ')
                if spc != "":
                    if BEG != "":
                        pars, errcode = pmag.PintPars(araiblock, zijdblock,
                                                      BEG, END)
                        pars['measurement_step_unit'] = "J"
                        pars["specimen_lab_field_dc"] = field
                        pars["specimen_int"] = -1 * field * pars["specimen_b"]
                        pars["er_specimen_name"] = s
                        pars['specimen_grade'] = ''  # ungraded
                        pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                        if len(trmblock) > 2:
                            if inlt == 0:
                                donlt()
                                inlt = 1
                            blab = field
                            best = pars["specimen_int"]
                            Bs, TRMs = [], []
                            for trec in trmblock:
                                Bs.append(float(trec['treatment_dc_field']))
                                TRMs.append(
                                    float(trec['measurement_magn_moment']))
                            NLpars = nlt.NLtrm(
                                Bs, TRMs, best, blab, 0
                            )  # calculate best fit parameters through TRM acquisition data, and get new banc
                            #
                            Mp, Bp = [], []
                            for k in range(int(max(Bs) * 1e6)):
                                Bp.append(float(k) * 1e-6)
                                npred = nlt.TRM(
                                    Bp[-1], NLpars['xopt'][0], NLpars['xopt']
                                    [1])  # predicted NRM for this field
                    files = {}
                    for key in list(AZD.keys()):
                        files[key] = s + '_' + key + fmt
                    pmagplotlib.save_plots(AZD, files)
                    sys.exit()
                if plots == 0:
                    ans = 'b'
                    while ans != "":
                        print("""
               s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit:
               """)
                        ans = input('Return for next specimen \n')
                        if ans == "":
                            specimen += 1
                        if ans == "d":
                            save_redo(PriorRecs, inspec)
                            CurrRec = []
                            pmagplotlib.plot_arai_zij(AZD, araiblock,
                                                      zijdblock, s, units[0])
                            pmagplotlib.draw_figs(AZD)
                        if ans == 'a':
                            files = {}
                            for key in list(AZD.keys()):
                                files[key] = s + '_' + key + fmt
                            pmagplotlib.save_plots(AZD, files)
                            ans = ""
                        if ans == 'q':
                            print("Good bye")
                            sys.exit()
                        if ans == 'p':
                            specimen = specimen - 1
                            backup = 1
                            ans = ""
                        if ans == 's':
                            keepon = 1
                            spec = input(
                                'Enter desired specimen name (or first part there of): '
                            )
                            while keepon == 1:
                                try:
                                    specimen = sids.index(spec)
                                    keepon = 0
                                except:
                                    tmplist = []
                                    for qq in range(len(sids)):
                                        if spec in sids[qq]:
                                            tmplist.append(sids[qq])
                                    print(specimen,
                                          " not found, but this was: ")
                                    print(tmplist)
                                    spec = input('Select one or try again\n ')
                            ans = ""
                        if ans == 'b':
                            if end == 0 or end >= len(araiblock[0]):
                                end = len(araiblock[0]) - 1
                            GoOn = 0
                            while GoOn == 0:
                                print(
                                    'Enter index of first point for calculation: ',
                                    '[', start, ']')
                                answer = input('return to keep default  ')
                                if answer != "": start = int(answer)
                                print(
                                    'Enter index  of last point for calculation: ',
                                    '[', end, ']')
                                answer = input('return to keep default  ')
                                if answer != "":
                                    end = int(answer)
                                if start >= 0 and start < len(araiblock[
                                        0]) - 2 and end > 0 and end < len(
                                            araiblock[0]) and start < end:
                                    GoOn = 1
                                else:
                                    print("Bad endpoints - try again! ")
                                    start, end = 0, len(araiblock)
                            s = sids[specimen]
                            pars, errcode = pmag.PintPars(
                                araiblock, zijdblock, start, end)
                            pars['measurement_step_unit'] = "J"
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1 * field * pars[
                                "specimen_b"]
                            pars["er_specimen_name"] = s
                            pars = pmag.scoreit(pars, PmagSpecRec, accept, '',
                                                0)
                            PmagSpecRec["measurement_step_min"] = '%8.3e' % (
                                pars["measurement_step_min"])
                            PmagSpecRec["measurement_step_max"] = '%8.3e' % (
                                pars["measurement_step_max"])
                            PmagSpecRec["measurement_step_unit"] = "J"
                            PmagSpecRec["specimen_int_n"] = '%i' % (
                                pars["specimen_int_n"])
                            PmagSpecRec["specimen_lab_field_dc"] = '%8.3e' % (
                                pars["specimen_lab_field_dc"])
                            PmagSpecRec["specimen_int"] = '%8.3e ' % (
                                pars["specimen_int"])
                            PmagSpecRec["specimen_b"] = '%5.3f ' % (
                                pars["specimen_b"])
                            PmagSpecRec["specimen_q"] = '%5.1f ' % (
                                pars["specimen_q"])
                            PmagSpecRec["specimen_f"] = '%5.3f ' % (
                                pars["specimen_f"])
                            PmagSpecRec["specimen_fvds"] = '%5.3f' % (
                                pars["specimen_fvds"])
                            PmagSpecRec["specimen_b_beta"] = '%5.3f' % (
                                pars["specimen_b_beta"])
                            PmagSpecRec["specimen_int_mad"] = '%7.1f' % (
                                pars["specimen_int_mad"])
                            PmagSpecRec["specimen_Z"] = '%7.1f' % (
                                pars["specimen_Z"])
                            if pars["method_codes"] != "":
                                tmpcodes = pars["method_codes"].split(":")
                                for t in tmpcodes:
                                    if t.strip() not in methcodes:
                                        methcodes.append(t.strip())
                            PmagSpecRec["specimen_dec"] = '%7.1f' % (
                                pars["specimen_dec"])
                            PmagSpecRec["specimen_inc"] = '%7.1f' % (
                                pars["specimen_inc"])
                            PmagSpecRec["specimen_tilt_correction"] = '-1'
                            PmagSpecRec["specimen_direction_type"] = 'l'
                            PmagSpecRec[
                                "direction_type"] = 'l'  # this is redudant, but helpful - won't be imported
                            PmagSpecRec["specimen_dang"] = '%7.1f ' % (
                                pars["specimen_dang"])
                            PmagSpecRec["specimen_drats"] = '%7.1f ' % (
                                pars["specimen_drats"])
                            PmagSpecRec["specimen_int_ptrm_n"] = '%i ' % (
                                pars["specimen_int_ptrm_n"])
                            PmagSpecRec["specimen_rsc"] = '%6.4f ' % (
                                pars["specimen_rsc"])
                            PmagSpecRec["specimen_md"] = '%i ' % (int(
                                pars["specimen_md"]))
                            if PmagSpecRec["specimen_md"] == '-1':
                                PmagSpecRec["specimen_md"] = ""
                            PmagSpecRec["specimen_b_sigma"] = '%5.3f ' % (
                                pars["specimen_b_sigma"])
                            if "IE-TT" not in methcodes:
                                methcodes.append("IE-TT")
                            methods = ""
                            for meth in methcodes:
                                methods = methods + meth + ":"
                            PmagSpecRec["magic_method_codes"] = methods[:-1]
                            PmagSpecRec["specimen_description"] = comment
                            PmagSpecRec[
                                "magic_software_packages"] = version_num
                            pmagplotlib.plot_arai_zij(AZD, araiblock,
                                                      zijdblock, s, units[0])
                            pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                            if len(trmblock) > 2:
                                blab = field
                                best = pars["specimen_int"]
                                Bs, TRMs = [], []
                                for trec in trmblock:
                                    Bs.append(float(
                                        trec['treatment_dc_field']))
                                    TRMs.append(
                                        float(trec['measurement_magn_moment']))
                                NLpars = nlt.NLtrm(
                                    Bs, TRMs, best, blab, 0
                                )  # calculate best fit parameters through TRM acquisition data, and get new banc
                                Mp, Bp = [], []
                                for k in range(int(max(Bs) * 1e6)):
                                    Bp.append(float(k) * 1e-6)
                                    npred = nlt.TRM(
                                        Bp[-1], NLpars['xopt'][0],
                                        NLpars['xopt']
                                        [1])  # predicted NRM for this field
                                    Mp.append(npred)
                                pmagplotlib.plot_trm(
                                    AZD['MRM'], Bs, TRMs, Bp, Mp, NLpars,
                                    trec['magic_experiment_name'])
                                print('Banc= ', float(NLpars['banc']) * 1e6)
                            pmagplotlib.draw_figs(AZD)
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1 * field * pars[
                                "specimen_b"]
                            saveit = input(
                                "Save this interpretation? [y]/n \n")
                            if saveit != 'n':
                                specimen += 1
                                PriorRecs.append(
                                    PmagSpecRec)  # put back an interpretation
                                save_redo(PriorRecs, inspec)
                            ans = ""
                else:
                    specimen += 1
                    if fmt != ".pmag":
                        basename = s + '_microwave' + fmt
                        files = {}
                        for key in list(AZD.keys()):
                            files[key] = s + '_' + key + fmt
                        if pmagplotlib.isServer:
                            black = '#000000'
                            purple = '#800080'
                            titles = {}
                            titles['deremag'] = 'DeReMag Plot'
                            titles['zijd'] = 'Zijderveld Plot'
                            titles['arai'] = 'Arai Plot'
                            AZD = pmagplotlib.add_borders(
                                AZD, titles, black, purple)
                        pmagplotlib.save_plots(AZD, files)
    #                   pmagplotlib.combineFigs(s,files,3)
        if len(CurrRec) > 0:
            for rec in CurrRec:
                PriorRecs.append(rec)
        CurrRec = []
    if plots != 1:
        ans = input(" Save last plot? 1/[0] ")
        if ans == "1":
            if fmt != ".pmag":
                files = {}
                for key in list(AZD.keys()):
                    files[key] = s + '_' + key + fmt
                pmagplotlib.save_plots(AZD, files)
        if len(CurrRec) > 0:
            PriorRecs.append(CurrRec)  # put back an interpretation
        if len(PriorRecs) > 0:
            save_redo(PriorRecs, inspec)
            print('Updated interpretations saved in ', inspec)
    if pmagplotlib.verbose:
        print("Good bye")
Example #6
0
def main():
    """
    NAME
        vgpmap_magic.py

    DESCRIPTION
        makes a map of vgps and a95/dp,dm for site means in a pmag_results table

    SYNTAX
        vgpmap_magic.py [command line options]

    OPTIONS
        -h prints help and quits
        -eye  ELAT ELON [specify eyeball location], default is 90., 0.
        -f FILE pmag_results format file, [default is pmag_results.txt]
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -etp plot the etopo20 topographpy data (requires high resolution data set)
        -prj PROJ,  specify one of the following:
             ortho = orthographic
             lcc = lambert conformal
             moll = molweide
             merc = mercator
        -sym SYM SIZE: choose a symbol and size, examples:
            ro 5 : small red circles
            bs 10 : intermediate blue squares
            g^ 20 : large green triangles
        -ell  plot dp/dm or a95 ellipses
        -rev RSYM RSIZE : flip reverse poles to normal antipode
        -S:  plot antipodes of all poles
        -age : plot the ages next to the poles
        -crd [g,t] : choose coordinate system, default is to plot all site VGPs
        -fmt [pdf, png, eps...] specify output format, default is pdf
        -sav  save and quit
    DEFAULTS
        FILE: pmag_results.txt
        res:  c
        prj: ortho
        ELAT,ELON = 0,0
        SYM SIZE: ro 8
        RSYM RSIZE: g^ 8

    """
    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)
Example #7
0
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]

    """
    fname, fmt = "", 'svg'
    plot = 0
    if '-sav' in sys.argv:
        plot = 1
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind+1]
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        fname = sys.argv[ind+1]
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        outfile = sys.argv[ind+1]
        fmt = ""
    else:
        outfile = 'hist.'+fmt
    if '-N' in sys.argv:
        norm = 0
        ylab = 'Number'
    else:
        norm = 1
        ylab = 'Frequency'
    if '-twin' in sys.argv:
        norm=-1
    binsize = 0
    if '-b' in sys.argv:
        ind = sys.argv.index('-b')
        binsize = int(sys.argv[ind+1])
    if '-xlab' in sys.argv:
        ind = sys.argv.index('-xlab')
        xlab = sys.argv[ind+1]
    else:
        xlab = 'x'
    if fname != "":
        D = np.loadtxt(fname)
    else:
        print('-I- Trying to read from stdin... <ctrl>-c to quit')
        D = np.loadtxt(sys.stdin, dtype=np.float)
    # read in data
    #
    try:
        if not D:
            print('-W- No data found')
            return
    except ValueError:
        pass
    fig = pmagplotlib.plot_init(1, 8, 7)
    try:
        len(D)
    except TypeError:
        D = np.array([D])
    if len(D) < 5:
        print("-W- Not enough points to plot histogram ({} point(s) provided, 5 required)".format(len(D)))
        return
    # if binsize not provided, calculate reasonable binsize
    if not binsize:
        binsize = int(np.around(1 + 3.22 * np.log(len(D))))
    Nbins = int(len(D) / binsize)
    ax = fig.add_subplot(111)
    if norm==1:
        print ('normalizing')
        n, bins, patches = ax.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=True)
        ax.set_ylabel(ylab)
    elif norm==0:
        print ('not normalizing')
        n, bins, patches = ax.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=False)
        ax.set_ylabel(ylab)
    elif norm==-1:
        print ('trying twin')
        n, bins, patches = ax.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=True)
        ax.set_ylabel('Frequency')
        ax2=ax.twinx()
        n, bins, patches = ax2.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=False)
        ax2.set_ylabel('Number',rotation=-90)
    plt.axis([D.min(), D.max(), 0, n.max()+.1*n.max()])
    ax.set_xlabel(xlab)
    name = 'N = ' + str(len(D))
    plt.title(name)
    if plot == 0:
        pmagplotlib.draw_figs({1: 'hist'})
        p = input('s[a]ve to save plot, [q]uit to exit without saving  ')
        if p != 'a':
            sys.exit()
    if pmagplotlib.isServer:
        pmagplotlib.add_borders({'hist': 1}, {'hist': 'Intensity Histogram'})
    plt.savefig(outfile)
    print('plot saved in ', outfile)
Example #8
0
def main():
    """
    NAME
       qqplot.py

    DESCRIPTION
       makes qq plot of input data  against a Normal distribution.  
       

    INPUT FORMAT
       takes real numbers in single column
   
    SYNTAX
       qqplot.py [-h][-i][-f FILE]

    OPTIONS
        -f FILE, specify file on command line
        -fmt [png,svg,jpg,eps] set plot output format [default is svg]
        -sav saves and quits

    OUTPUT
         calculates the K-S D and the D expected for a normal distribution 
         when D<Dc,  distribution is normal (at 95% level of confidence).

    """
    fmt,plot='svg',0
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    if '-sav' in sys.argv: plot=1
    if '-fmt' in sys.argv: 
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        data=f.readlines()
    X= [] # set up list for data
    for line in data:   # read in the data from standard input
        rec=line.split() # split each line on space to get records
        X.append(float(rec[0])) # append data to X
#
    QQ={'qq':1}
    pmagplotlib.plot_init(QQ['qq'],5,5)
    pmagplotlib.plot_qq_norm(QQ['qq'],X,'Q-Q Plot') # make plot
    if plot==0:
        pmagplotlib.draw_figs(QQ)
    files={}
    for key in list(QQ.keys()):
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Q-Q Plot'
        QQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==0:
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": 
            pmagplotlib.save_plots(QQ,files) 
    else:
        pmagplotlib.save_plots(QQ,files) 
Example #9
0
def main():
    """
    NAME
        vgpmap_magic.py

    DESCRIPTION
        makes a map of vgps and a95/dp,dm for site means in a sites table

    SYNTAX
        vgpmap_magic.py [command line options]

    OPTIONS
        -h prints help and quits
        -eye  ELAT ELON [specify eyeball location], default is 90., 0.
        -f FILE sites format file, [default is sites.txt]
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -etp plot the etopo20 topographpy data (requires high resolution data set)
        -prj PROJ,  specify one of the following:
             ortho = orthographic
             lcc = lambert conformal
             moll = molweide
             merc = mercator
        -sym SYM SIZE: choose a symbol and size, examples:
            ro 5 : small red circles
            bs 10 : intermediate blue squares
            g^ 20 : large green triangles
        -ell  plot dp/dm or a95 ellipses
        -rev RSYM RSIZE : flip reverse poles to normal antipode
        -S:  plot antipodes of all poles
        -age : plot the ages next to the poles
        -crd [g,t] : choose coordinate system, default is to plot all site VGPs
        -fmt [pdf, png, eps...] specify output format, default is pdf
        -sav  save and quit
    DEFAULTS
        FILE: sites.txt
        res:  c
        prj: ortho
        ELAT,ELON = 0,0
        SYM SIZE: ro 8
        RSYM RSIZE: g^ 8

    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", ".")
    # plot: default is 0, if -sav in sys.argv should be 1
    plot = pmag.get_flag_arg_from_sys("-sav", true=1, false=0)
    fmt = pmag.get_named_arg("-fmt", "pdf")
    res = pmag.get_named_arg("-res", "c")
    proj = pmag.get_named_arg("-prj", "ortho")
    anti = pmag.get_flag_arg_from_sys("-S", true=1, false=0)
    fancy = pmag.get_flag_arg_from_sys("-etp", true=1, false=0)
    ell = pmag.get_flag_arg_from_sys("-ell", true=1, false=0)
    ages = pmag.get_flag_arg_from_sys("-age", true=1, false=0)
    if '-rev' in sys.argv:
        flip = 1
        ind = sys.argv.index('-rev')
        rsym = (sys.argv[ind + 1])
        rsize = int(sys.argv[ind + 2])
    else:
        flip, rsym, rsize = 0, "g^", 8
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym = (sys.argv[ind + 1])
        size = int(sys.argv[ind + 2])
    else:
        sym, size = 'ro', 8
    if '-eye' in sys.argv:
        ind = sys.argv.index('-eye')
        lat_0 = float(sys.argv[ind + 1])
        lon_0 = float(sys.argv[ind + 2])
    else:
        lat_0, lon_0 = 90., 0.
    crd = pmag.get_named_arg("-crd", "")
    coord_dict = {'g': 0, 't': 100}
    coord = coord_dict[crd] if crd else ""
    results_file = pmag.get_named_arg("-f", "sites.txt")

    con = cb.Contribution(dir_path, single_file=results_file)
    if not list(con.tables.keys()):
        print("-W - Couldn't read in data")
        return

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

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

    # go through rows and extract data
    for ind, row in Results.iterrows():
        lat, lon = float(row['vgp_lat']), float(row['vgp_lon'])
        if anti == 1:
            lats.append(-lat)
            lon = lon + 180.
            if lon > 360:
                lon = lon - 360.
            lons.append(lon)
        elif flip == 0:
            lats.append(lat)
            lons.append(lon)
        elif flip == 1:
            if lat < 0:
                rlats.append(-lat)
                lon = lon + 180.
                if lon > 360:
                    lon = lon - 360
                rlons.append(lon)
            else:
                lats.append(lat)
                lons.append(lon)

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

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

    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['map'] = location + ' VGP map'
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    elif 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)
Example #10
0
def main():
    """
    NAME
        thellier_magic.py

    DESCRIPTION
        plots Thellier-Thellier data in version 3.0 format
        Reads saved interpretations from a specimen formatted table, default: specimens.txt

    SYNTAX
        thellier_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set measurements input file, default is 'measurements.txt'
        -fsp PRIOR, set specimens.txt prior interpretations file, default is 'specimens.txt'
        -fcr CRIT, set criteria file for grading.  # not yet implemented
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (in format specified by -fmt key or default)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds and quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step number for slope calculation
           END: ending step number for slope calculation
        -z use only z component difference for pTRM calculation

    OUTPUT
        figures:
            ALL:  numbers refer to temperature steps in command line window
            1) Arai plot:  closed circles are zero-field first/infield
                           open circles are infield first/zero-field
                           triangles are pTRM checks
                           squares are pTRM tail checks
                           VDS is vector difference sum
                           diamonds are bounds for interpretation
            2) Zijderveld plot:  closed (open) symbols are X-Y (X-Z) planes
                                 X rotated to NRM direction
            3) (De/Re)Magnetization diagram:
                           circles are NRM remaining
                           squares are pTRM gained
            4) equal area projections:
               green triangles are pTRM gained direction
                           red (purple) circles are lower(upper) hemisphere of ZI step directions
                           blue (cyan) squares are lower(upper) hemisphere IZ step directions
            5) Optional:  TRM acquisition
            6) Optional: TDS normalization
        command line window:
            list is: temperature step numbers, temperatures (C), Dec, Inc, Int (units of measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates image files with specimen, plot type as name
    """
    #
    #   initializations
    #
    version_num = pmag.get_version()
    verbose = pmagplotlib.verbose
    #
    # default acceptance criteria
    #
    accept = pmag.default_criteria(0)[0]  # set the default criteria
    #
    # parse command line options
    #
    plots, fmt, Zdiff = 0, 'svg', 0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", default_val=os.getcwd())
    meas_file = pmag.get_named_arg("-f", default_val="measurements.txt")
    spec_file = pmag.get_named_arg("-fsp", default_val="specimens.txt")
    crit_file = pmag.get_named_arg("-fcr", default_val="criteria.txt")
    spec_file = os.path.join(dir_path, spec_file)
    meas_file = os.path.join(dir_path, meas_file)
    crit_file = os.path.join(dir_path, crit_file)
    fmt = pmag.get_named_arg("-fmt", "svg")
    if '-sav' in sys.argv:
        plots, verbose = 1, 0
    if '-z' in sys.argv:
        Zdiff = 1
    specimen = pmag.get_named_arg("-spc", default_val="")
    if '-b' in sys.argv:
        ind = sys.argv.index('-b')
        start = int(sys.argv[ind + 1])
        end = int(sys.argv[ind + 2])
    else:
        start, end = "", ""
    fnames = {
        'measurements': meas_file,
        'specimens': spec_file,
        'criteria': crit_file
    }
    contribution = cb.Contribution(
        dir_path,
        custom_filenames=fnames,
        read_tables=['measurements', 'specimens', 'criteria'])
    #
    #   import  prior interpretations  from specimen file
    #
    specimen_cols = [
        'analysts', 'aniso_ftest', 'aniso_ftest12', 'aniso_ftest23', 'aniso_s',
        'aniso_s_mean', 'aniso_s_n_measurements', 'aniso_s_sigma',
        'aniso_s_unit', 'aniso_tilt_correction', 'aniso_type', 'aniso_v1',
        'aniso_v2', 'aniso_v3', 'citations', 'description', 'dir_alpha95',
        'dir_comp', 'dir_dec', 'dir_inc', 'dir_mad_free', 'dir_n_measurements',
        'dir_tilt_correction', 'experiments', 'geologic_classes',
        'geologic_types', 'hyst_bc', 'hyst_bcr', 'hyst_mr_moment',
        'hyst_ms_moment', 'int_abs', 'int_b', 'int_b_beta', 'int_b_sigma',
        'int_corr', 'int_dang', 'int_drats', 'int_f', 'int_fvds', 'int_gamma',
        'int_mad_free', 'int_md', 'int_n_measurements', 'int_n_ptrm', 'int_q',
        'int_rsc', 'int_treat_dc_field', 'lithologies', 'meas_step_max',
        'meas_step_min', 'meas_step_unit', 'method_codes', 'sample',
        'software_packages', 'specimen'
    ]
    spec_container, prior_spec_data = None, []
    if 'specimens' in contribution.tables:
        spec_container = contribution.tables['specimens']
        if 'method_codes' in spec_container.df.columns:
            # look up all prior intensity interpretations
            prior_spec_data = spec_container.get_records_for_code(
                'LP-PI-TRM', strict_match=False)
    backup = 0
    #
    Mkeys = ['magn_moment', 'magn_volume', 'magn_mass']
    #
    #   create measurement dataframe
    #
    if pmagplotlib.isServer:
        contribution.propagate_location_to_measurements()

    meas_container = contribution.tables['measurements']
    meas_data = meas_container.df
    #
    meas_data['method_codes'] = meas_data['method_codes'].str.replace(
        " ", "")  # get rid of nasty spaces
    meas_data = meas_data[meas_data['method_codes'].str.contains(
        'LP-PI-TRM|LP-TRM|LP-TRM-TD') ==
                          True]  # fish out zero field steps for plotting
    intensity_types = [
        col_name for col_name in meas_data.columns if col_name in Mkeys
    ]
    # plot first intensity method found - normalized to initial value anyway -
    # doesn't matter which used

    int_key = meas_container.find_filled_col(intensity_types)
    if not int_key:
        print("-W- No intensity data found, thellier_magic cannot run")
        return

    # get all the non-null intensity records of the same type
    meas_data = meas_data[meas_data[int_key].notnull()]

    if not len(meas_data):
        print("-W- No intensity data found, thellier_magic cannot run")
        return
    if 'flag' not in meas_data.columns:
        meas_data['flag'] = 'g'  # set the default flag to good
    meas_data = meas_data[meas_data['flag'].str.contains('g') ==
                          True]  # only the 'good' measurements
    thel_data = meas_data[meas_data['method_codes'].str.contains('LP-PI-TRM')
                          == True]  # get all the Thellier data
    trm_data = meas_data[meas_data['method_codes'].str.contains('LP-TRM') ==
                         True]  # get all the TRM acquisition data
    td_data = meas_data[meas_data['method_codes'].str.contains('LP-TRM-TD') ==
                        True]  # get all the TD data
    anis_data = meas_data[meas_data['method_codes'].str.contains('LP-AN') ==
                          True]  # get all the anisotropy data
    #
    # get list of unique specimen names from measurement data
    #
    # this is a Series of all the specimen names
    specimen_names = meas_data.specimen.unique()
    specimen_names = specimen_names.tolist()  # turns it into a list
    specimen_names.sort()  # sorts by specimen name
    #
    # set up new DataFrame for this sessions specimen interpretations
    #
    spec_container = cb.MagicDataFrame(dtype='specimens',
                                       columns=specimen_cols)
    # this is for interpretations from this session
    current_spec_data = spec_container.df
    if specimen == "":  # do all specimens
        k = 0
    else:
        k = specimen_names.index(specimen)  # just do this one
    # define figure numbers for arai, zijderveld and
    #   de-,re-magnetization diagrams
    AZD = {}
    AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4
    pmagplotlib.plot_init(AZD['arai'], 5, 5)
    pmagplotlib.plot_init(AZD['zijd'], 5, 5)
    pmagplotlib.plot_init(AZD['deremag'], 5, 5)
    pmagplotlib.plot_init(AZD['eqarea'], 5, 5)
    if len(trm_data) > 0:
        AZD['TRM'] = 5
        pmagplotlib.plot_init(AZD['TRM'], 5, 5)
    if len(td_data) > 0:
        AZD['TDS'] = 6
        pmagplotlib.plot_init(AZD['TDS'], 5, 5)
    #
    while k < len(specimen_names):
        # set the current specimen for plotting
        this_specimen = specimen_names[k]
        if verbose and this_specimen != "":
            print(this_specimen, k + 1, 'out of ', len(specimen_names))
        if pmagplotlib.isServer:
            this_specimen_measurements = meas_data[meas_data['specimen'] ==
                                                   this_specimen]
            try:
                loc = this_specimen_measurements.loc[:, 'location'].values[0]
            except:
                loc = ""
            try:
                site = this_specimen_measurements.loc[:, 'site'].values[0]
            except:
                site = ""
            try:
                samp = this_specimen_measurements.loc[:, 'sample'].values[0]
            except:
                samp = ""

#
#    set up datablocks
#
        thelblock = thel_data[thel_data['specimen'].str.contains(this_specimen)
                              == True]  # fish out this specimen
        trmblock = trm_data[trm_data['specimen'].str.contains(this_specimen) ==
                            True]  # fish out this specimen
        tdsrecs = td_data[td_data['specimen'].str.contains(this_specimen) ==
                          True]  # fish out this specimen
        anisblock = anis_data[anis_data['specimen'].str.contains(this_specimen)
                              == True]  # fish out the anisotropy data
        if len(prior_spec_data):
            prior_specimen_interpretations = prior_spec_data[
                prior_spec_data['specimen'].str.contains(
                    this_specimen) == True]  # fish out prior interpretation
        else:
            prior_specimen_interpretations = []

#
# sort data into types
#
        araiblock, field = pmag.sortarai(thelblock,
                                         this_specimen,
                                         Zdiff,
                                         version=3)
        first_Z = araiblock[0]
        GammaChecks = araiblock[5]
        if len(first_Z) < 3:
            if backup == 0:
                k += 1
                if verbose:
                    print('skipping specimen - moving forward ', this_specimen)
            else:
                k -= 1
                if verbose:
                    print('skipping specimen - moving backward ',
                          this_specimen)
        else:
            backup = 0
            zijdblock, units = pmag.find_dmag_rec(this_specimen,
                                                  thelblock,
                                                  version=3)
            if start == "" and len(prior_specimen_interpretations) > 0:
                if verbose:
                    print('Looking up saved interpretation....')
#
# get prior interpretation steps
#
                beg_int = pd.to_numeric(prior_specimen_interpretations.
                                        meas_step_min.values).tolist()[0]
                end_int = pd.to_numeric(prior_specimen_interpretations.
                                        meas_step_max.values).tolist()[0]
            else:
                beg_int, end_int = "", ""
            recnum = 0
            if verbose:
                print("index step Dec   Inc  Int       Gamma")
            for plotrec in zijdblock:
                if plotrec[0] == beg_int:
                    start = recnum  # while we are at it, collect these bounds
                if plotrec[0] == end_int:
                    end = recnum
                if verbose:
                    if GammaChecks != "":
                        gamma = ""
                        for g in GammaChecks:
                            if g[0] == plotrec[0] - 273:
                                gamma = g[1]
                                break
                    if gamma is not "":
                        print('%i     %i %7.1f %7.1f %8.3e %7.1f' %
                              (recnum, plotrec[0] - 273, plotrec[1],
                               plotrec[2], plotrec[3], gamma))
                    else:
                        print('%i     %i %7.1f %7.1f %8.3e ' %
                              (recnum, plotrec[0] - 273, plotrec[1],
                               plotrec[2], plotrec[3]))
                recnum += 1
            for fig in list(AZD.keys()):
                pmagplotlib.clearFIG(AZD[fig])  # clear all figures
            if 'K' in units:
                u = 'K'
            elif 'J' in units:
                u = 'J'
            pmagplotlib.plot_arai_zij(AZD, araiblock, zijdblock, this_specimen,
                                      u)
            if verbose:
                pmagplotlib.draw_figs(AZD)
            if cb.is_null(start, False) or cb.is_null(end, False):
                if verbose:
                    ans = input('Return for next specimen, q to quit:  ')
                    if ans == 'q':
                        sys.exit()
                k += 1  # moving on
                start, end = "", ""
                continue

            pars, errcode = pmag.PintPars(thelblock,
                                          araiblock,
                                          zijdblock,
                                          start,
                                          end,
                                          accept,
                                          version=3)
            pars['measurement_step_unit'] = "K"
            pars['experiment_type'] = 'LP-PI-TRM'
            #
            # work on saving interpretations stuff later
            #
            if errcode != 1:  # no problem in PintPars
                pars["specimen_lab_field_dc"] = field
                pars["specimen_int"] = -1 * field * pars["specimen_b"]
                pars["er_specimen_name"] = this_specimen
                # pars,kill=pmag.scoreit(pars,this_specimen_interpretation,accept,'',verbose)
                # # deal with this later
                pars["specimen_grade"] = 'None'
                pars['measurement_step_min'] = pars['meas_step_min']
                pars['measurement_step_max'] = pars['meas_step_max']
                if pars['measurement_step_unit'] == 'K':
                    outstr = "specimen     Tmin  Tmax  N  lab_field  B_anc  b  q  f(coe)  Fvds  beta  MAD  Dang  Drats  Nptrm  Grade  R  MD%  sigma  Gamma_max \n"
                    pars_out = (this_specimen, (pars["meas_step_min"] - 273),
                                (pars["meas_step_max"] -
                                 273), (pars["specimen_int_n"]),
                                1e6 * (pars["specimen_lab_field_dc"]),
                                1e6 * (pars["specimen_int"]),
                                pars["specimen_b"], pars["specimen_q"],
                                pars["specimen_f"], pars["specimen_fvds"],
                                pars["specimen_b_beta"], pars["int_mad_free"],
                                pars["int_dang"], pars["int_drats"],
                                pars["int_n_ptrm"], pars["specimen_grade"],
                                np.sqrt(pars["specimen_rsc"]),
                                int(pars["int_md"]), pars["specimen_b_sigma"],
                                pars['specimen_gamma'])
                    outstring = '%s %4.0f %4.0f %i %4.1f %4.1f %5.3f %5.1f %5.3f %5.3f %5.3f  %7.1f %7.1f %7.1f %s %s %6.3f %i %5.3f %7.1f' % pars_out + '\n'
                elif pars['measurement_step_unit'] == 'J':
                    outstr = "specimen     Wmin  Wmax  N  lab_field  B_anc  b  q  f(coe)  Fvds  beta  MAD  Dang  Drats  Nptrm  Grade  R  MD%  sigma  ThetaMax DeltaMax GammaMax\n"
                    pars_out = (
                        this_specimen, (pars["meas_step_min"]),
                        (pars["meas_step_max"]), (pars["specimen_int_n"]),
                        1e6 * (pars["specimen_lab_field_dc"]),
                        1e6 * (pars["specimen_int"]), pars["specimen_b"],
                        pars["specimen_q"], pars["specimen_f"],
                        pars["specimen_fvds"], pars["specimen_b_beta"],
                        pars["specimen_int_mad"], pars["specimen_int_dang"],
                        pars["specimen_drats"], pars["specimen_int_ptrm_n"],
                        pars["specimen_grade"], np.sqrt(pars["specimen_rsc"]),
                        int(pars["specimen_md"]), pars["specimen_b_sigma"],
                        pars["specimen_theta"], pars["specimen_delta"],
                        pars["specimen_gamma"])
                    outstring = '%s %4.0f %4.0f %i %4.1f %4.1f %5.3f %5.1f %5.3f %5.3f %5.3f  %7.1f %7.1f %7.1f %s %s %6.3f %i %5.3f %7.1f %7.1f %7.1f' % pars_out + '\n'
                print(outstr)
                print(outstring)
                pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                mpars = pmag.domean(araiblock[1], start, end, 'DE-BFL')
                if verbose:
                    pmagplotlib.draw_figs(AZD)
                    print('pTRM direction= ',
                          '%7.1f' % (mpars['specimen_dec']),
                          ' %7.1f' % (mpars['specimen_inc']), ' MAD:',
                          '%7.1f' % (mpars['specimen_mad']))
            if len(anisblock) > 0:  # this specimen has anisotropy data
                if verbose:
                    print('Found anisotropy record... but ignoring for now ')
            if plots == 1:
                if fmt != "pmag":
                    files = {}
                    for key in list(AZD.keys()):
                        if pmagplotlib.isServer:
                            files[
                                key] = "LO:_{}_SI:_{}_SA:_{}_SP:_{}_TY:_{}_.{}".format(
                                    loc, site, samp, this_specimen, key, fmt)
                        else:
                            files[key] = 'SP:_' + this_specimen + \
                              '_TY:_' + key + '_' + '.' + fmt
                    if pmagplotlib.isServer:
                        black = '#000000'
                        purple = '#800080'
                        titles = {}
                        titles['deremag'] = 'DeReMag Plot'
                        titles['zijd'] = 'Zijderveld Plot'
                        titles['arai'] = 'Arai Plot'
                        titles['TRM'] = 'TRM Acquisition data'
                        titles['eqarea'] = 'Equal Area Plot'
                        AZD = pmagplotlib.add_borders(AZD, titles, black,
                                                      purple)
                    pmagplotlib.save_plots(AZD, files)
                else:  # save in pmag format
                    print('pmag format no longer supported')
                    #script="grep "+this_specimen+" output.mag | thellier -mfsi"
                    #script=script+' %8.4e'%(field)
                    # min='%i'%((pars["measurement_step_min"]-273))
                    # Max='%i'%((pars["measurement_step_max"]-273))
                    #script=script+" "+min+" "+Max
                    #script=script+" |plotxy;cat mypost >>thellier.ps\n"
                    # pltf.write(script)
                    # pmag.domagicmag(outf,MeasRecs)
            if specimen != "":
                sys.exit()  # syonara
            if verbose:
                ans = input('Return for next specimen, q to quit:  ')
                if ans == 'q':
                    sys.exit()
            start, end = "", ""
            k += 1  # moving on
Example #11
0
def main():
    """
    NAME
       plotdi_a.py

    DESCRIPTION
       plots equal area projection  from dec inc data and fisher mean, cone of confidence

    INPUT FORMAT
       takes dec, inc, alpha95 as first three columns in space delimited file

    SYNTAX
       plotdi_a.py [-i][-f FILE]

    OPTIONS
        -f FILE to read file name from command line
        -fmt [png,jpg,eps,pdf,svg] set plot file format ['svg' is default]
        -sav save plot and quit

    """
    fmt, plot = 'svg', 0
    if len(sys.argv) > 0:
        if '-h' in sys.argv:  # check if help is needed
            print(main.__doc__)
            sys.exit()  # graceful quit
        if '-fmt' in sys.argv:
            ind = sys.argv.index('-fmt')
            fmt = sys.argv[ind + 1]
        if '-sav' in sys.argv: plot = 1
        if '-f' in sys.argv:
            ind = sys.argv.index('-f')
            file = sys.argv[ind + 1]
            f = open(file, 'r')
            data = f.readlines()
        else:
            data = sys.stdin.readlines()  # read in data from standard input
    DIs, Pars = [], []
    for line in data:  # read in the data from standard input
        pars = []
        rec = line.split()  # split each line on space to get records
        DIs.append([float(rec[0]), float(rec[1])])
        pars.append(float(rec[0]))
        pars.append(float(rec[1]))
        pars.append(float(rec[2]))
        pars.append(float(rec[0]))
        isign = abs(float(rec[1])) / float(rec[1])
        pars.append(float(rec[1]) - isign * 90.)  #Beta inc
        pars.append(float(rec[2]))  # gamma
        pars.append(float(rec[0]) + 90.)  # Beta dec
        pars.append(0.)  #Beta inc
        Pars.append(pars)


#
    EQ = {'eq': 1}  # make plot dictionary
    pmagplotlib.plot_init(EQ['eq'], 5, 5)
    title = 'Equal area projection'
    pmagplotlib.plot_eq(EQ['eq'], DIs, title)  # plot directions
    for k in range(len(Pars)):
        pmagplotlib.plot_ell(EQ['eq'], Pars[k], 'b', 0, 1)  # plot ellipses
    files = {}
    for key in list(EQ.keys()):
        files[key] = key + '.' + fmt
    titles = {}
    titles['eq'] = 'Equal Area Plot'
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        EQ = pmagplotlib.add_borders(EQ, titles, black, purple)
        pmagplotlib.save_plots(EQ, files)
    elif plot == 0:
        pmagplotlib.draw_figs(EQ)
        ans = input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans == "q": sys.exit()
        if ans == "a":
            pmagplotlib.save_plots(EQ, files)
    else:
        pmagplotlib.save_plots(EQ, files)
Example #12
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

    INPUT
       takes magic formatted pmag_results, pmag_sites, pmag_samples or pmag_specimens

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

    DESCRIPTION
       makes equal area projections from declination/inclination data

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

    SYNTAX
       eqarea.py [options]

    OPTIONS
        -f FILE, specify file on command line
        -sav save figure and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
        -s  SIZE specify symbol size - default is 20
        -Lsym  SHAPE  COLOR specify shape and color for lower hemisphere
        -Usym  SHAPE  COLOR specify shape and color for upper hemisphere
          shapes:  's': square,'o': circle,'^,>,v,<': [up,right,down,left] triangle, 'd': diamond,
                   'p': pentagram, 'h': hexagon, '8': octagon, '+': plus, 'x': cross
          colors:  [b]lue,[g]reen,[r]ed,[c]yan,[m]agenta,[y]ellow,blac[k],[w]hite

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

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

    INPUT
       takes magic formatted sites, samples, specimens, or measurements

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file from magic, default='sites.txt'
         supported types=[measurements, specimens, samples, sites]
        -fsp FILE: specify specimen file name, (required if you want to plot measurements by sample)
                default='specimens.txt'
        -fsa FILE: specify sample file name, (required if you want to plot specimens by site)
                default='samples.txt'
        -fsi FILE: specify site file name, default='sites.txt'
        -flo FILE: specify location file name, default='locations.txt'

        -obj OBJ: specify  level of plot  [all, sit, sam, spc], default is all
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is geographic, unspecified assumed geographic
        -fmt [svg,png,jpg] format for output plots
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
        -c plot as colour contour
        -cm CM use color map CM [default is coolwarm]
        -sav save plot and quit quietly
        -no-tilt data are unoriented, allows plotting of measurement dec/inc
    NOTE
        all: entire file; sit: site; sam: sample; spc: specimen
    """
    # initialize some default variables
    FIG = {}  # plot dictionary
    FIG['eqarea'] = 1  # eqarea is figure 1
    plotE = 0
    plt = 0  # default to not plotting
    verbose = pmagplotlib.verbose
    # extract arguments from sys.argv
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", default_val=".")
    pmagplotlib.plot_init(FIG['eqarea'], 5, 5)
    in_file = pmag.get_named_arg("-f", default_val="sites.txt")
    in_file = pmag.resolve_file_name(in_file, dir_path)
    if "-WD" not in sys.argv:
        dir_path = os.path.split(in_file)[0]
    #full_in_file = os.path.join(dir_path, in_file)
    plot_by = pmag.get_named_arg("-obj", default_val="all").lower()
    spec_file = pmag.get_named_arg("-fsp", default_val="specimens.txt")
    samp_file = pmag.get_named_arg("-fsa", default_val="samples.txt")
    site_file = pmag.get_named_arg("-fsi", default_val="sites.txt")
    loc_file = pmag.get_named_arg("-flo", default_val="locations.txt")
    ignore_tilt = False
    if '-no-tilt' in sys.argv:
        ignore_tilt = True
    if plot_by == 'all':
        plot_key = 'all'
    elif plot_by == 'sit':
        plot_key = 'site'
    elif plot_by == 'sam':
        plot_key = 'sample'
    elif plot_by == 'spc':
        plot_key = 'specimen'
    else:
        plot_by = 'all'
        plot_key = 'all'
    if '-c' in sys.argv:
        contour = 1
        if '-cm' in sys.argv:
            ind = sys.argv.index('-cm')
            color_map = sys.argv[ind + 1]
        else:
            color_map = 'coolwarm'
    else:
        contour = 0
    if '-sav' in sys.argv:
        plt = 1
        verbose = 0
    if '-ell' in sys.argv:
        plotE = 1
        ind = sys.argv.index('-ell')
        ell_type = sys.argv[ind + 1]
        ell_type = pmag.get_named_arg("-ell", "F")
        dist = ell_type.upper()
        # if dist type is unrecognized, use Fisher
        if dist not in ['F', 'K', 'B', 'BE', 'BV']:
            dist = 'F'
        if dist == "BV":
            FIG['bdirs'] = 2
            pmagplotlib.plot_init(FIG['bdirs'], 5, 5)
    crd = pmag.get_named_arg("-crd", default_val="g")
    if crd == "s":
        coord = "-1"
    elif crd == "t":
        coord = "100"
    else:
        coord = "0"

    fmt = pmag.get_named_arg("-fmt", "svg")

    dec_key = 'dir_dec'
    inc_key = 'dir_inc'
    tilt_key = 'dir_tilt_correction'
    # Dir_type_keys=['','site_direction_type','sample_direction_type','specimen_direction_type']

    #
    fnames = {
        "specimens": spec_file,
        "samples": samp_file,
        'sites': site_file,
        'locations': loc_file
    }
    contribution = cb.Contribution(dir_path,
                                   custom_filenames=fnames,
                                   single_file=in_file)

    try:
        contribution.propagate_location_to_samples()
        contribution.propagate_location_to_specimens()
        contribution.propagate_location_to_measurements()
    except KeyError as ex:
        pass

    # the object that contains the DataFrame + useful helper methods:
    table_name = list(contribution.tables.keys())[0]
    data_container = contribution.tables[table_name]
    # the actual DataFrame:
    data = data_container.df

    if plot_key != "all" and plot_key not in data.columns:
        print(
            "-E- You can't plot by {} with the data provided".format(plot_key))
        return

    # add tilt key into DataFrame columns if it isn't there already
    if tilt_key not in data.columns:
        data.loc[:, tilt_key] = None

    if verbose:
        print(len(data), ' records read from ', in_file)

    # find desired dec,inc data:
    dir_type_key = ''
    #
    # get plotlist if not plotting all records
    #
    plotlist = []
    if plot_key != "all":
        # return all where plot_key is not blank
        if plot_key not in data.columns:
            print('Can\'t plot by "{}".  That header is not in infile: {}'.
                  format(plot_key, in_file))
            return
        plots = data[data[plot_key].notnull()]
        plotlist = plots[plot_key].unique()  # grab unique values
    else:
        plotlist.append('All')

    for plot in plotlist:
        if verbose:
            print(plot)
        if plot == 'All':
            # plot everything at once
            plot_data = data
        else:
            # pull out only partial data
            plot_data = data[data[plot_key] == plot]

        DIblock = []
        GCblock = []
        # SLblock, SPblock = [], []
        title = plot
        mode = 1
        k = 0

        if dec_key not in plot_data.columns:
            print("-W- No dec/inc data")
            continue
        # get all records where dec & inc values exist
        plot_data = plot_data[plot_data[dec_key].notnull()
                              & plot_data[inc_key].notnull()]
        if plot_data.empty:
            continue
        # this sorting out is done in get_di_bock
        # if coord == '0':  # geographic, use records with no tilt key (or tilt_key 0)
        #    cond1 = plot_data[tilt_key].fillna('') == coord
        #    cond2 = plot_data[tilt_key].isnull()
        #    plot_data = plot_data[cond1 | cond2]
        # else:  # not geographic coordinates, use only records with correct tilt_key
        #    plot_data = plot_data[plot_data[tilt_key] == coord]

        # get metadata for naming the plot file
        locations = data_container.get_name('location', df_slice=plot_data)
        site = data_container.get_name('site', df_slice=plot_data)
        sample = data_container.get_name('sample', df_slice=plot_data)
        specimen = data_container.get_name('specimen', df_slice=plot_data)

        # make sure method_codes is in plot_data
        if 'method_codes' not in plot_data.columns:
            plot_data['method_codes'] = ''

        # get data blocks
        # would have to ignore tilt to use measurement level data
        DIblock = data_container.get_di_block(df_slice=plot_data,
                                              tilt_corr=coord,
                                              excl=['DE-BFP'],
                                              ignore_tilt=ignore_tilt)
        #SLblock = [[ind, row['method_codes']] for ind, row in plot_data.iterrows()]
        # get great circles
        great_circle_data = data_container.get_records_for_code('DE-BFP',
                                                                incl=True,
                                                                use_slice=True,
                                                                sli=plot_data)

        if len(great_circle_data) > 0:
            gc_cond = great_circle_data[tilt_key] == coord
            GCblock = [[float(row[dec_key]),
                        float(row[inc_key])]
                       for ind, row in great_circle_data[gc_cond].iterrows()]
            #SPblock = [[ind, row['method_codes']] for ind, row in great_circle_data[gc_cond].iterrows()]

        if len(DIblock) > 0:
            if contour == 0:
                pmagplotlib.plot_eq(FIG['eqarea'], DIblock, title)
            else:
                pmagplotlib.plot_eq_cont(FIG['eqarea'],
                                         DIblock,
                                         color_map=color_map)
        else:
            pmagplotlib.plot_net(FIG['eqarea'])
        if len(GCblock) > 0:
            for rec in GCblock:
                pmagplotlib.plot_circ(FIG['eqarea'], rec, 90., 'g')
        if len(DIblock) == 0 and len(GCblock) == 0:
            if verbose:
                print("no records for plotting")
            continue
            # sys.exit()
        if plotE == 1:
            ppars = pmag.doprinc(DIblock)  # get principal directions
            nDIs, rDIs, npars, rpars = [], [], [], []
            for rec in DIblock:
                angle = pmag.angle([rec[0], rec[1]],
                                   [ppars['dec'], ppars['inc']])
                if angle > 90.:
                    rDIs.append(rec)
                else:
                    nDIs.append(rec)
            if dist == 'B':  # do on whole dataset
                etitle = "Bingham confidence ellipse"
                bpars = pmag.dobingham(DIblock)
                for key in list(bpars.keys()):
                    if key != 'n' and verbose:
                        print("    ", key, '%7.1f' % (bpars[key]))
                    if key == 'n' and verbose:
                        print("    ", key, '       %i' % (bpars[key]))
                npars.append(bpars['dec'])
                npars.append(bpars['inc'])
                npars.append(bpars['Zeta'])
                npars.append(bpars['Zdec'])
                npars.append(bpars['Zinc'])
                npars.append(bpars['Eta'])
                npars.append(bpars['Edec'])
                npars.append(bpars['Einc'])
            if dist == 'F':
                etitle = "Fisher confidence cone"
                if len(nDIs) > 2:
                    fpars = pmag.fisher_mean(nDIs)
                    for key in list(fpars.keys()):
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (fpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (fpars[key]))
                    mode += 1
                    npars.append(fpars['dec'])
                    npars.append(fpars['inc'])
                    npars.append(fpars['alpha95'])  # Beta
                    npars.append(fpars['dec'])
                    isign = abs(fpars['inc']) / fpars['inc']
                    npars.append(fpars['inc'] - isign * 90.)  # Beta inc
                    npars.append(fpars['alpha95'])  # gamma
                    npars.append(fpars['dec'] + 90.)  # Beta dec
                    npars.append(0.)  # Beta inc
                if len(rDIs) > 2:
                    fpars = pmag.fisher_mean(rDIs)
                    if verbose:
                        print("mode ", mode)
                    for key in list(fpars.keys()):
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (fpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (fpars[key]))
                    mode += 1
                    rpars.append(fpars['dec'])
                    rpars.append(fpars['inc'])
                    rpars.append(fpars['alpha95'])  # Beta
                    rpars.append(fpars['dec'])
                    isign = abs(fpars['inc']) / fpars['inc']
                    rpars.append(fpars['inc'] - isign * 90.)  # Beta inc
                    rpars.append(fpars['alpha95'])  # gamma
                    rpars.append(fpars['dec'] + 90.)  # Beta dec
                    rpars.append(0.)  # Beta inc
            if dist == 'K':
                etitle = "Kent confidence ellipse"
                if len(nDIs) > 3:
                    kpars = pmag.dokent(nDIs, len(nDIs))
                    if verbose:
                        print("mode ", mode)
                    for key in list(kpars.keys()):
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (kpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (kpars[key]))
                    mode += 1
                    npars.append(kpars['dec'])
                    npars.append(kpars['inc'])
                    npars.append(kpars['Zeta'])
                    npars.append(kpars['Zdec'])
                    npars.append(kpars['Zinc'])
                    npars.append(kpars['Eta'])
                    npars.append(kpars['Edec'])
                    npars.append(kpars['Einc'])
                if len(rDIs) > 3:
                    kpars = pmag.dokent(rDIs, len(rDIs))
                    if verbose:
                        print("mode ", mode)
                    for key in list(kpars.keys()):
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (kpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (kpars[key]))
                    mode += 1
                    rpars.append(kpars['dec'])
                    rpars.append(kpars['inc'])
                    rpars.append(kpars['Zeta'])
                    rpars.append(kpars['Zdec'])
                    rpars.append(kpars['Zinc'])
                    rpars.append(kpars['Eta'])
                    rpars.append(kpars['Edec'])
                    rpars.append(kpars['Einc'])
            else:  # assume bootstrap
                if dist == 'BE':
                    if len(nDIs) > 5:
                        BnDIs = pmag.di_boot(nDIs)
                        Bkpars = pmag.dokent(BnDIs, 1.)
                        if verbose:
                            print("mode ", mode)
                        for key in list(Bkpars.keys()):
                            if key != 'n' and verbose:
                                print("    ", key, '%7.1f' % (Bkpars[key]))
                            if key == 'n' and verbose:
                                print("    ", key, '       %i' % (Bkpars[key]))
                        mode += 1
                        npars.append(Bkpars['dec'])
                        npars.append(Bkpars['inc'])
                        npars.append(Bkpars['Zeta'])
                        npars.append(Bkpars['Zdec'])
                        npars.append(Bkpars['Zinc'])
                        npars.append(Bkpars['Eta'])
                        npars.append(Bkpars['Edec'])
                        npars.append(Bkpars['Einc'])
                    if len(rDIs) > 5:
                        BrDIs = pmag.di_boot(rDIs)
                        Bkpars = pmag.dokent(BrDIs, 1.)
                        if verbose:
                            print("mode ", mode)
                        for key in list(Bkpars.keys()):
                            if key != 'n' and verbose:
                                print("    ", key, '%7.1f' % (Bkpars[key]))
                            if key == 'n' and verbose:
                                print("    ", key, '       %i' % (Bkpars[key]))
                        mode += 1
                        rpars.append(Bkpars['dec'])
                        rpars.append(Bkpars['inc'])
                        rpars.append(Bkpars['Zeta'])
                        rpars.append(Bkpars['Zdec'])
                        rpars.append(Bkpars['Zinc'])
                        rpars.append(Bkpars['Eta'])
                        rpars.append(Bkpars['Edec'])
                        rpars.append(Bkpars['Einc'])
                    etitle = "Bootstrapped confidence ellipse"
                elif dist == 'BV':
                    sym = {
                        'lower': ['o', 'c'],
                        'upper': ['o', 'g'],
                        'size': 3,
                        'edgecolor': 'face'
                    }
                    if len(nDIs) > 5:
                        BnDIs = pmag.di_boot(nDIs)
                        pmagplotlib.plot_eq_sym(FIG['bdirs'], BnDIs,
                                                'Bootstrapped Eigenvectors',
                                                sym)
                    if len(rDIs) > 5:
                        BrDIs = pmag.di_boot(rDIs)
                        if len(nDIs) > 5:  # plot on existing plots
                            pmagplotlib.plot_di_sym(FIG['bdirs'], BrDIs, sym)
                        else:
                            pmagplotlib.plot_eq(FIG['bdirs'], BrDIs,
                                                'Bootstrapped Eigenvectors')
            if dist == 'B':
                if len(nDIs) > 3 or len(rDIs) > 3:
                    pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], npars, 0)
            elif len(nDIs) > 3 and dist != 'BV':
                pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], npars, 0)
                if len(rDIs) > 3:
                    pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], rpars, 0)
            elif len(rDIs) > 3 and dist != 'BV':
                pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], rpars, 0)

        for key in list(FIG.keys()):
            files = {}
            filename = pmag.get_named_arg('-fname')
            if filename:  # use provided filename
                filename += '.' + fmt
            elif pmagplotlib.isServer:  # use server plot naming convention
                filename = 'LO:_'+locations+'_SI:_'+site+'_SA:_'+sample + \
                    '_SP:_'+specimen+'_CO:_'+crd+'_TY:_'+key+'_.'+fmt
            elif plot_key == 'all':
                filename = 'all'
                if 'location' in plot_data.columns:
                    locs = plot_data['location'].unique()
                    loc_string = "_".join(
                        [str(loc).replace(' ', '_') for loc in locs])
                    filename += "_" + loc_string
                filename += "_" + crd + "_" + key
                filename += ".{}".format(fmt)
            else:  # use more readable naming convention
                filename = ''
                # fix this if plot_by is location , for example
                use_names = {
                    'location': [locations],
                    'site': [locations, site],
                    'sample': [locations, site, sample],
                    'specimen': [locations, site, sample, specimen]
                }
                use = use_names[plot_key]
                use.extend([crd, key])
                # [locations, site, sample, specimen, crd, key]:
                for item in use:
                    if item:
                        item = item.replace(' ', '_')
                        filename += item + '_'
                if filename.endswith('_'):
                    filename = filename[:-1]
                filename += ".{}".format(fmt)

            files[key] = filename

        if pmagplotlib.isServer:
            black = '#000000'
            purple = '#800080'
            titles = {}
            titles['eqarea'] = 'Equal Area Plot'
            FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
            pmagplotlib.save_plots(FIG, files)

        elif plt:
            pmagplotlib.save_plots(FIG, files)
            continue
        if verbose:
            pmagplotlib.draw_figs(FIG)
            ans = input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
            if ans == "q":
                sys.exit()
            if ans == "a":
                pmagplotlib.save_plots(FIG, files)
        continue
Example #15
0
def main():
    """
    NAME
        cont_rot.py

    DESCRIPTION
        rotates continental fragments according to specified Euler pole

    SYNTAX
        cont_rot.py [command line options]

    OPTIONS
        -h prints help and quits
        -con [af, congo, kala, aus, balt, eur, ind, sam, ant, grn, lau, nam, gond] , specify colon delimited list of continents to be displayed, e.g., af, af:aus], etc
        -age use finite rotations of Torsvik et al. 2008 for specific age (5 Ma increments <325Ma)
             rotates to paleomagnetic reference frame
             available conts: [congo kala aus eur ind sam ant grn nam]
        -sac include rotation of south african craton to pmag reference
        -sym [ro, bs, g^, r., b-, etc.] [1,5,10] symbol and size for continent
           colors are r=red,b=blue,g=green, etc.
           symbols are '.' for points, ^, for triangle, s for square, etc.
            -, for lines, -- for dotted lines, see matplotlib online documentation for plot()
        -eye  ELAT ELON [specify eyeball location]
        -pfr  PLAT PLON OMEGA  [specify pole of finite rotation lat,lon and degrees]
        -ffr FFILE, specifies series of finite rotations
           vector in tab delimited file
        -sr treat poles as sequential rotations
        -fpp PFILE, specifies series of paleopoles from which
           euler poles can be calculated: vector in tab delimited file
        -pt LAT LON,  specify a point to rotate along with continent
        -fpt PTFILE, specifies file with a series of points to be plotted
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -fmt [png,jpg,svg,pdf] format for saved figure - pdf is default
        -sav saves plots and quits
        -prj PROJ,  specify one of the supported projections: (see basemap.py online documentation)
            aeqd = Azimuthal Equidistant
            poly = Polyconic
            gnom = Gnomonic
            moll = Mollweide
            tmerc = Transverse Mercator
            nplaea = North-Polar Lambert Azimuthal
            mill = Miller Cylindrical
            merc = Mercator
            stere = Stereographic
            npstere = North-Polar Stereographic
            geos = Geostationary
            laea = Lambert Azimuthal Equal Area
            sinu = Sinusoidal
            spstere = South-Polar Stereographic
            lcc = Lambert Conformal
            npaeqd = North-Polar Azimuthal Equidistant
            eqdc = Equidistant Conic
            cyl = Cylindrical Equidistant
            omerc = Oblique Mercator
            aea = Albers Equal Area
            spaeqd = South-Polar Azimuthal Equidistant
            ortho = Orthographic
            cass= Cassini-Soldner
            splaea = South-Polar Lambert Azimuthal
            robin = Robinson

    DEFAULTS
        con: nam
        res:  c
        prj: mollweide
        ELAT,ELON = 0,0
        NB: high resolution or lines can be very slow

    """
    dir_path = '.'
    ocean = 0
    res = 'c'
    proj = 'moll'
    euler_file = ''
    Conts = []
    Poles = []
    PTS = []
    lat_0, lon_0 = 0., 0.
    fmt = 'pdf'
    sym = 'r.'
    symsize = 5
    plot = 0
    SEQ, age, SAC = 0, 0, 0
    rconts = [
        'af', 'congo', 'kala', 'aus', 'eur', 'ind', 'sam', 'ant', 'grn', 'nam'
    ]
    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 '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-con' in sys.argv:
        ind = sys.argv.index('-con')
        Conts = sys.argv[ind + 1].split(':')
    if '-age' in sys.argv:
        ind = sys.argv.index('-age')
        age = int(sys.argv[ind + 1])
        if age % 5 != 0 and age > 320:
            print(main.__doc__)
            print('age must be multiple of 5 less than 325')
            sys.exit()
        import pmagpy.frp as frp
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res = sys.argv[ind + 1]
        if res != 'c' and res != 'l':
            print('this resolution will take a while - be patient')
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj = sys.argv[ind + 1]
    if '-sav' in sys.argv:
        plot = 1
    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 '-pt' in sys.argv:
        ind = sys.argv.index('-pt')
        pt_lat = float(sys.argv[ind + 1])
        pt_lon = float(sys.argv[ind + 2])
        PTS.append([pt_lat, pt_lon])
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym = sys.argv[ind + 1]
        symsize = int(sys.argv[ind + 2])


#    if '-rsym' in sys.argv:
#        ind = sys.argv.index('-rsym')
#        rsym=sys.argv[ind+1]
#        rsymsize=int(sys.argv[ind+2])
    if '-sr' in sys.argv:
        SEQ = 1
    if '-sac' in sys.argv:
        SAC = 1
    if '-pfr' in sys.argv:
        ind = sys.argv.index('-pfr')
        Poles.append([
            float(sys.argv[ind + 1]),
            float(sys.argv[ind + 2]),
            float(sys.argv[ind + 3])
        ])
    elif '-ffr' in sys.argv:
        ind = sys.argv.index('-ffr')
        file = dir_path + '/' + sys.argv[ind + 1]
        f = open(file, 'r')
        edata = f.readlines()
        for line in edata:
            rec = line.split()
            Poles.append([float(rec[0]), float(rec[1]), float(rec[2])])
    elif '-fpp' in sys.argv:
        ind = sys.argv.index('-fpp')
        file = dir_path + '/' + sys.argv[ind + 1]
        f = open(file, 'r')
        pdata = f.readlines()
        for line in pdata:
            rec = line.split()
            # transform paleopole to Euler pole taking shortest route
            Poles.append([0., float(rec[1]) - 90., 90. - float(rec[0])])
    if '-fpt' in sys.argv:
        ind = sys.argv.index('-fpt')
        file = dir_path + '/' + sys.argv[ind + 1]
        f = open(file, 'r')
        ptdata = f.readlines()
        for line in ptdata:
            rec = line.split()
            PTS.append([float(rec[0]), float(rec[1])])
    FIG = {'map': 1}
    pmagplotlib.plot_init(FIG['map'], 6, 6)
    # read in er_sites file
    if res == 'c':
        skip = 8
    if res == 'l':
        skip = 5
    if res == 'i':
        skip = 2
    if res == 'h':
        skip = 1
    cnt = 0
    Opts = {
        'latmin': -90,
        'latmax': 90,
        'lonmin': 0.,
        'lonmax': 360.,
        'lat_0': lat_0,
        'lon_0': lon_0,
        'proj': proj,
        'sym': sym,
        'symsize': 3,
        'pltgrid': 0,
        'res': res,
        'boundinglat': 0.
    }
    if proj == 'merc':
        Opts['latmin'] = -70
        Opts['latmax'] = 70
        Opts['lonmin'] = -180
        Opts['lonmax'] = 180
    pmagplotlib.plot_map(FIG['map'], [], [], Opts)  # plot the basemap
    Opts['pltgrid'] = -1  # turn off replotting of gridlines
    if '-pt' in sys.argv:
        Opts['sym'] = sym
        Opts['symsize'] = symsize
        pmagplotlib.plot_map(FIG['map'], [pt_lat], [pt_lon], Opts)
        if plot == 0 and not IS_WIN:
            pmagplotlib.draw_figs(FIG)
    for cont in Conts:
        Opts['sym'] = sym
        lats, lons = [], []
        if age != 0:
            Poles = []
            rcont = cont
            if rcont not in rconts:
                print(main.__doc__)
                print(rcont)
                print('continents  must be one of following: ')
                print(rconts)
                sys.exit()
            if rcont == 'congo':
                rcont = 'nwaf'
            if rcont == 'kala':
                rcont = 'neaf'
            if rcont == 'sam':
                rcont = 'sac'
            if rcont == 'ant':
                rcont = 'eant'
            if rcont != 'af':
                Poles.append(frp.get_pole(rcont, age))
            else:
                Poles.append([0, 0, 0])
            if SAC == 1:
                Poles.append(frp.get_pole('saf', age))
            SEQ = 1
            if Poles[-1] == 'NONE':
                print('continent does not exist for rotation, try again ')
                sys.exit()
        data = continents.get_continent(cont + '.asc')
        for line in data:
            if float(line[0]) == 0 and float(line[1]) == 0:
                line[
                    0] = '100.'  # change stupid 0,0s to delimeters with lat=100
            if float(line[0]) > 90:
                lats.append(float(line[0]))
                lons.append(float(line[1]))
            elif cnt % skip == 0:
                lats.append(float(line[0]))
                lons.append(float(line[1]))
            cnt += 1
        if len(lats) > 0 and len(Poles) == 0:
            pmagplotlib.plot_map(FIG['map'], lats, lons, Opts)
            if plot == 0 and not IS_WIN:
                pmagplotlib.draw_figs(FIG)
        newlats, newlons = [], []
        for lat in lats:
            newlats.append(lat)
        for lon in lons:
            newlons.append(lon)
        Opts['pltgrid'] = -1  # turns off replotting of meridians and parallels
        for pole in Poles:
            Rlats, Rlons = pmag.pt_rot(pole, newlats, newlons)
            Opts['sym'] = sym
            Opts['symsize'] = 3
            if SEQ == 0:
                pmagplotlib.plot_map(FIG['map'], Rlats, Rlons, Opts)
            elif pole == Poles[
                    -1]:  # plot only last pole for sequential rotations
                pmagplotlib.plot_map(FIG['map'], Rlats, Rlons, Opts)
            if plot == 0 and not IS_WIN:
                pmagplotlib.draw_figs(FIG)
            if SEQ == 1:  # treat poles as sequential rotations
                newlats, newlons = [], []
                for lat in Rlats:
                    newlats.append(lat)
                for lon in Rlons:
                    newlons.append(lon)
    for pt in PTS:
        pt_lat = pt[0]
        pt_lon = pt[1]
        Opts['sym'] = 'r*'
        Opts['symsize'] = 5
        pmagplotlib.plot_map(FIG['map'], [pt[0]], [pt[1]], Opts)
        if plot == 0 and not IS_WIN:
            pmagplotlib.draw_figs(FIG)
        Opts['pltgrid'] = -1  # turns off replotting of meridians and parallels
        for pole in Poles:
            Opts['sym'] = sym
            Opts['symsize'] = symsize
            Rlats, Rlons = pmag.pt_rot(pole, [pt_lat], [pt_lon])
            print(Rlats, Rlons)
            pmagplotlib.plot_map(FIG['map'], Rlats, Rlons, Opts)
            if plot == 0 and not IS_WIN:
                pmagplotlib.draw_figs(FIG)
        Opts['sym'] = 'g^'
        Opts['symsize'] = 5
        pmagplotlib.plot_map(FIG['map'], [pole[0]], [pole[1]], Opts)
        if plot == 0 and not IS_WIN:
            pmagplotlib.draw_figs(FIG)
    files = {}
    for key in list(FIG.keys()):
        files[key] = 'Cont_rot' + '.' + fmt
    if plot == 0 and not IS_WIN:
        pmagplotlib.draw_figs(FIG)
    if plot == 1:
        pmagplotlib.save_plots(FIG, files)
        sys.exit()
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['eq'] = 'Site Map'
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    else:
        pmagplotlib.draw_figs(FIG)
        ans = pmagplotlib.save_or_quit()
        if ans == "a":
            pmagplotlib.save_plots(FIG, files)
Example #16
0
def main():
    """
    NAME
        biplot_magic.py

    DESCRIPTION
        makes a biplot of specified variables from magic_measurements.txt format file

    SYNTAX
        biplot_magic.py [-h] [-i] [command line options]

    INPUT
        takes magic formated magic_measurments file

    OPTIONS
        -h prints help message and quits
        -i interactively set filename and axes for plotting
        -f FILE: specifies file name, default: magic_measurements.txt
        -fmt [svg,png,jpg], format for images - default is svg
        -sav figure and quit
        -x XMETH:key:step, specify method code for X axis (optional key and treatment values)
        -y YMETH:key:step, specify method code for X axis
        -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is whole file
        -n [V,M] plot volume or mass normalized data only
    NOTES
        if nothing is specified for x and y, the user will be presented with options
        key = ['treatment_ac_field','treatment_dc_field',treatment_temp']
        step in mT for fields, K for temperatures
           """
    #
    file='magic_measurements.txt'
    methx,methy,fmt="","",'.svg'
    plot_key=''
    norm_by=""
    #plot=0
    no_plot = pmag.get_flag_arg_from_sys('-sav')
    if not no_plot:
        do_plot = True
    else:
        do_plot = False
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt='.'+sys.argv[ind+1]
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        norm_by=sys.argv[ind+1]
    xtreat_key,ytreat_key,xstep,ystep="","","",""
    if '-x' in sys.argv:
        ind=sys.argv.index('-x')
        meths=sys.argv[ind+1].split(':')
        methx=meths[0]
        if len(meths)>1:
            xtreat_key=meths[1]
            xstep=float(meths[2])
    if '-y' in sys.argv:
        ind=sys.argv.index('-y')
        meths=sys.argv[ind+1].split(':')
        methy=meths[0]
        if len(meths)>1:
            ytreat_key=meths[1]
            ystep=float(meths[2])
    if '-obj' in sys.argv:
        ind=sys.argv.index('-obj')
        plot_by=sys.argv[ind+1]
        if plot_by=='loc':plot_key='er_location_name'
        if plot_by=='sit':plot_key='er_site_name'
        if plot_by=='sam':plot_key='er_sample_name'
        if plot_by=='spc':plot_key='er_specimen_name'
    if '-h' in sys.argv:
        do_plot = False
    if '-i' in sys.argv:
    #
    # get name of file from command line
    #
        file=input("Input magic_measurments file name? [magic_measurements.txt] ")
        if file=="":file="magic_measurements.txt"
    #
    #
    FIG={'fig':1}
    pmagplotlib.plot_init(FIG['fig'],5,5)
    data,file_type=pmag.magic_read(file)
    if file_type!="magic_measurements":
        print(file_type,' not correct format for magic_measurments file')
        sys.exit()
    #
    # collect method codes
    methods,plotlist=[],[]
    for rec in  data:
        if plot_key!="":
            if rec[plot_key] not in plotlist:plotlist.append(rec[plot_key])
        elif len(plotlist)==0:
            plotlist.append('All')
        meths=rec['magic_method_codes'].split(':')
        for meth in meths:
            if meth.strip() not in methods and meth.strip()!="LP-":
                methods.append(meth.strip())
    #
    if '-i' in sys.argv:
        print(methods)
    elif methx =="" or methy=="":
        print(methods)
        sys.exit()
    GoOn=1
    while GoOn==1:
        if '-i' in sys.argv:methx=input('Select method for x axis: ')
        if methx not in methods:
            if '-i' in sys.argv:
                print('try again! method not available')
            else:
                print(main.__doc__)
                print('\n must specify X axis method\n')
                sys.exit()
        else:
            if pmagplotlib.verbose: print(methx, ' selected for X axis')
            GoOn=0
    GoOn=1
    while GoOn==1:
        if '-i' in sys.argv:methy=input('Select method for y axis: ')
        if methy not in methods:
            if '-i' in sys.argv:
                print('try again! method not available')
            else:
                print(main.__doc__)
                print('\n must specify Y axis method\n')
                sys.exit()
        else:
            if pmagplotlib.verbose: print(methy, ' selected for Y axis')
            GoOn=0
    if norm_by=="":
        measkeys=['measurement_magn_mass','measurement_magn_volume','measurement_magn_moment','measurement_magnitude','measurement_chi_volume','measurement_chi_mass','measurement_chi']
    elif norm_by=="V":
        measkeys=['measurement_magn_volume','measurement_chi_volume']
    elif norm_by=="M":
        measkeys=['measurement_magn_mass','measurement_chi_mass']
    xmeaskey,ymeaskey="",""
    plotlist.sort()
    for plot in plotlist: # go through objects
        if pmagplotlib.verbose:
            print(plot)
        X,Y=[],[]
        x,y='',''
        for rec in data:
            if plot_key!="" and rec[plot_key]!=plot:
                pass
            else:
                meths=rec['magic_method_codes'].split(':')
                for meth in meths:
                    if meth.strip()==methx:
                        if xmeaskey=="":
                            for key in measkeys:
                                if key in list(rec.keys()) and rec[key]!="":
                                    xmeaskey=key
                                    if pmagplotlib.verbose:
                                        print(xmeaskey,' being used for plotting X.')
                                    break
                    if meth.strip()==methy:
                        if ymeaskey=="":
                            for key in measkeys:
                                if key in list(rec.keys()) and rec[key]!="":
                                    ymeaskey=key
                                    if pmagplotlib.verbose:
                                        print(ymeaskey,' being used for plotting Y')
                                    break
        if ymeaskey!="" and xmeaskey!="":
            for rec in data:
                x,y='',''
                spec=rec['er_specimen_name'] # get the ydata for this specimen
                if rec[ymeaskey]!="" and methy in rec['magic_method_codes'].split(':'):
                    if ytreat_key=="" or (ytreat_key in list(rec.keys()) and float(rec[ytreat_key])==ystep):
                        y=float(rec[ymeaskey])
                        for rec in data: # now find the xdata
                            if rec['er_specimen_name']==spec and rec[xmeaskey]!="" and methx in rec['magic_method_codes'].split(':'):
                                if xtreat_key=="" or (xtreat_key in list(rec.keys()) and float(rec[xtreat_key])==xstep):
                                    x=float(rec[xmeaskey])
                if x != '' and y!= '':
                    X.append(x)
                    Y.append(y)
        if len(X)>0:
            pmagplotlib.clearFIG(FIG['fig'])
            pmagplotlib.plot_xy(FIG['fig'],X,Y,sym='ro',xlab=methx,ylab=methy,title=plot+':Biplot')
            if not pmagplotlib.isServer and do_plot:
                pmagplotlib.draw_figs(FIG)
                ans=input('S[a]ve plots, [q]uit,  Return for next plot ' )
                if ans=='a':
                    files={}
                    for key in list(FIG.keys()): files[key]=plot+'_'+key+fmt
                    pmagplotlib.save_plots(FIG,files)
                if ans=='q':
                    print("Good-bye\n")
                    sys.exit()
            else:
                files={}
                for key in list(FIG.keys()): files[key]=plot+'_'+key+fmt
                if pmagplotlib.isServer:
                    black     = '#000000'
                    purple    = '#800080'
                    titles={}
                    titles['fig']='X Y Plot'
                    FIG = pmagplotlib.add_borders(FIG,titles,black,purple)
                pmagplotlib.save_plots(FIG,files)
        else:
            print('nothing to plot for ',plot)
Example #17
0
def main():
    """
    NAME
        thellier_magic.py

    DESCRIPTION
        plots Thellier-Thellier, allowing interactive setting of bounds
        and customizing of selection criteria.  Saves and reads interpretations
        from a pmag_specimen formatted table, default: thellier_specimens.txt

    SYNTAX
        thellier_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set magic_measurements input file
        -fsp PRIOR, set pmag_specimen prior interpretations file
        -fan ANIS, set rmag_anisotropy file for doing the anisotropy corrections
        -fcr CRIT, set criteria file for grading.
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (default format)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds adn quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step for slope calculation
           END: ending step for slope calculation
        -z use only z component difference for pTRM calculation

    DEFAULTS
        MEAS: magic_measurements.txt
        REDO: thellier_redo
        CRIT: NONE
        PRIOR: NONE

    OUTPUT
        figures:
            ALL:  numbers refer to temperature steps in command line window
            1) Arai plot:  closed circles are zero-field first/infield
                           open circles are infield first/zero-field
                           triangles are pTRM checks
                           squares are pTRM tail checks
                           VDS is vector difference sum
                           diamonds are bounds for interpretation
            2) Zijderveld plot:  closed (open) symbols are X-Y (X-Z) planes
                                 X rotated to NRM direction
            3) (De/Re)Magnetization diagram:
                           circles are NRM remaining
                           squares are pTRM gained
            4) equal area projections:
               green triangles are pTRM gained direction
                           red (purple) circles are lower(upper) hemisphere of ZI step directions
                           blue (cyan) squares are lower(upper) hemisphere IZ step directions
            5) Optional:  TRM acquisition
            6) Optional: TDS normalization
        command line window:
            list is: temperature step numbers, temperatures (C), Dec, Inc, Int (units of magic_measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates .svg format files with specimen_name, plot type as name
    """
#
#   initializations
#
    meas_file, critout, inspec = "magic_measurements.txt", "", "thellier_specimens.txt"
    first = 1
    inlt = 0
    version_num = pmag.get_version()
    TDinit, Tinit, field, first_save = 0, 0, -1, 1
    user, comment, AniSpec, locname = "", '', "", ""
    ans, specimen, recnum, start, end = 0, 0, 0, 0, 0
    plots, pmag_out, samp_file, style = 0, "", "", "svg"
    verbose = pmagplotlib.verbose
    fmt = '.'+style
#
# default acceptance criteria
#
    accept = pmag.default_criteria(0)[0]  # set the default criteria
#
# parse command line options
#
    Zdiff, anis = 0, 0
    spc, BEG, END = "", "", ""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        meas_file = sys.argv[ind+1]
    if '-fsp' in sys.argv:
        ind = sys.argv.index('-fsp')
        inspec = sys.argv[ind+1]
    if '-fan' in sys.argv:
        ind = sys.argv.index('-fan')
        anisfile = sys.argv[ind+1]
        anis = 1
        anis_data, file_type = pmag.magic_read(anisfile)
        if verbose:
            print("Anisotropy data read in from ", anisfile)
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = '.'+sys.argv[ind+1]
    if '-dpi' in sys.argv:
        ind = sys.argv.index('-dpi')
        dpi = '.'+sys.argv[ind+1]
    else:
        dpi = 100
    if '-sav' in sys.argv:
        plots = 1
        verbose = 0
    if '-z' in sys.argv:
        Zdiff = 1
    if '-spc' in sys.argv:
        ind = sys.argv.index('-spc')
        spc = sys.argv[ind+1]
        if '-b' in sys.argv:
            ind = sys.argv.index('-b')
            BEG = int(sys.argv[ind+1])
            END = int(sys.argv[ind+2])
    if '-fcr' in sys.argv:
        ind = sys.argv.index('-fcr')
        critout = sys.argv[ind+1]
        crit_data, file_type = pmag.magic_read(critout)
        if file_type != 'pmag_criteria':
            if verbose:
                print('bad pmag_criteria file, using no acceptance criteria')
            accept = pmag.default_criteria(1)[0]
        else:
            if verbose:
                print("Acceptance criteria read in from ", critout)
            accept = {'pmag_criteria_code': 'ACCEPTANCE',
                      'er_citation_names': 'This study'}
            for critrec in crit_data:
                if 'sample_int_sigma_uT' in critrec.keys():  # accommodate Shaar's new criterion
                    critrec['sample_int_sigma'] = '%10.3e' % (
                        eval(critrec['sample_int_sigma_uT'])*1e-6)
                for key in critrec.keys():
                    if key not in accept.keys() and critrec[key] != '':
                        accept[key] = critrec[key]
    try:
        open(inspec, 'rU')
        PriorRecs, file_type = pmag.magic_read(inspec)
        if file_type != 'pmag_specimens':
            print(file_type)
            print(file_type, inspec, " is not a valid pmag_specimens file ")
            sys.exit()
        for rec in PriorRecs:
            if 'magic_software_packages' not in rec.keys():
                rec['magic_software_packages'] = ""
    except IOError:
        PriorRecs = []
        if verbose:
            print("starting new specimen interpretation file: ", inspec)
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(file_type)
        print(file_type, "This is not a valid magic_measurements file ")
        sys.exit()
    backup = 0
    # define figure numbers for arai, zijderveld and
    #   de-,re-magization diagrams
    AZD = {}
    AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4
    pmagplotlib.plot_init(AZD['arai'], 5, 5)
    pmagplotlib.plot_init(AZD['zijd'], 5, 5)
    pmagplotlib.plot_init(AZD['deremag'], 5, 5)
    pmagplotlib.plot_init(AZD['eqarea'], 5, 5)
    #
    #
    #
    # get list of unique specimen names
    #
    CurrRec = []
    sids = pmag.get_specs(meas_data)
    # get plots for specimen s - default is just to step through arai diagrams
    #
    if spc != "":
        specimen = sids.index(spc)
    while specimen < len(sids):
        methcodes = []

        if verbose:
            print(sids[specimen], specimen+1, 'of ', len(sids))
        MeasRecs = []
        s = sids[specimen]
        datablock, trmblock, tdsrecs = [], [], []
        PmagSpecRec = {}
        if first == 0:
            for key in keys:
                # make sure all new records have same set of keys
                PmagSpecRec[key] = ""
        PmagSpecRec["er_analyst_mail_names"] = user
        PmagSpecRec["specimen_correction"] = 'u'
    #
    # find the data from the meas_data file for this specimen
    #
        for rec in meas_data:
            if rec["er_specimen_name"] == s:
                MeasRecs.append(rec)
                if "magic_method_codes" not in rec.keys():
                    rec["magic_method_codes"] = ""
                methods = rec["magic_method_codes"].split(":")
                meths = []
                for meth in methods:
                    meths.append(meth.strip())  # take off annoying spaces
                methods = ""
                for meth in meths:
                    if meth.strip() not in methcodes and "LP-" in meth:
                        methcodes.append(meth.strip())
                    methods = methods+meth+":"
                methods = methods[:-1]
                rec["magic_method_codes"] = methods
                if "LP-PI-TRM" in meths:
                    datablock.append(rec)
                if "LP-TRM" in meths:
                    trmblock.append(rec)
                if "LP-TRM-TD" in meths:
                    tdsrecs.append(rec)
        if len(trmblock) > 2 and inspec != "":
            if Tinit == 0:
                Tinit = 1
                AZD['TRM'] = 5
                pmagplotlib.plot_init(AZD['TRM'], 5, 5)
        elif Tinit == 1:  # clear the TRM figure if not needed
            pmagplotlib.clearFIG(AZD['TRM'])
        if len(tdsrecs) > 2:
            if TDinit == 0:
                TDinit = 1
                AZD['TDS'] = 6
                pmagplotlib.plot_init(AZD['TDS'], 5, 5)
        elif TDinit == 1:  # clear the TDS figure if not needed
            pmagplotlib.clearFIG(AZD['TDS'])
        if len(datablock) < 4:
            if backup == 0:
                specimen += 1
                if verbose:
                    print('skipping specimen - moving forward ', s)
            else:
                specimen -= 1
                if verbose:
                    print('skipping specimen - moving backward ', s)
    #
    #  collect info for the PmagSpecRec dictionary
    #
        else:
            rec = datablock[0]
            PmagSpecRec["er_citation_names"] = "This study"
            PmagSpecRec["er_specimen_name"] = s
            PmagSpecRec["er_sample_name"] = rec["er_sample_name"]
            PmagSpecRec["er_site_name"] = rec["er_site_name"]
            PmagSpecRec["er_location_name"] = rec["er_location_name"]
            locname = rec['er_location_name'].replace('/', '-')
            if "er_expedition_name" in rec.keys():
                PmagSpecRec["er_expedition_name"] = rec["er_expedition_name"]
            if "magic_instrument_codes" not in rec.keys():
                rec["magic_instrument_codes"] = ""
            PmagSpecRec["magic_instrument_codes"] = rec["magic_instrument_codes"]
            PmagSpecRec["measurement_step_unit"] = "K"
            if "magic_experiment_name" not in rec.keys():
                rec["magic_experiment_name"] = ""
            else:
                PmagSpecRec["magic_experiment_names"] = rec["magic_experiment_name"]

            meths = rec["magic_method_codes"].split()
        # sort data into types
            araiblock, field = pmag.sortarai(datablock, s, Zdiff)
            first_Z = araiblock[0]
            GammaChecks = araiblock[5]
            if len(first_Z) < 3:
                if backup == 0:
                    specimen += 1
                    if verbose:
                        print('skipping specimen - moving forward ', s)
                else:
                    specimen -= 1
                    if verbose:
                        print('skipping specimen - moving backward ', s)
            else:
                backup = 0
                zijdblock, units = pmag.find_dmag_rec(s, meas_data)
                recnum = 0
                if verbose:
                    print("index step Dec   Inc  Int       Gamma")
                    for plotrec in zijdblock:
                        if GammaChecks != "":
                            gamma = ""
                            for g in GammaChecks:
                                if g[0] == plotrec[0]-273:
                                    gamma = g[1]
                                    break
                        if gamma != "":
                            print('%i     %i %7.1f %7.1f %8.3e %7.1f' % (
                                recnum, plotrec[0]-273, plotrec[1], plotrec[2], plotrec[3], gamma))
                        else:
                            print('%i     %i %7.1f %7.1f %8.3e ' % (
                                recnum, plotrec[0]-273, plotrec[1], plotrec[2], plotrec[3]))
                        recnum += 1
                pmagplotlib.plot_arai_zij(AZD, araiblock, zijdblock, s, units[0])
                if verbose:
                    pmagplotlib.draw_figs(AZD)
                if len(tdsrecs) > 2:  # a TDS experiment
                    tdsblock = []  # make a list for the TDS  data
                    Mkeys = ['measurement_magnitude', 'measurement_magn_moment',
                             'measurement_magn_volume', 'measuruement_magn_mass']
                    mkey, k = "", 0
                    # find which type of intensity
                    while mkey == "" and k < len(Mkeys)-1:
                        key = Mkeys[k]
                        if key in tdsrecs[0].keys() and tdsrecs[0][key] != "":
                            mkey = key
                        k += 1
                    if mkey == "":
                        break  # get outta here
                    Tnorm = ""
                    for tdrec in tdsrecs:
                        meths = tdrec['magic_method_codes'].split(":")
                        for meth in meths:
                            # strip off potential nasty spaces
                            meth.replace(" ", "")
                        if 'LT-T-I' in meths and Tnorm == "":  # found first total TRM
                            # normalize by total TRM
                            Tnorm = float(tdrec[mkey])
                            # put in the zero step
                            tdsblock.append([273, zijdblock[0][3]/Tnorm, 1.])
                        # found a LP-TRM-TD demag step, now need complementary LT-T-Z from zijdblock
                        if 'LT-T-Z' in meths and Tnorm != "":
                            step = float(tdrec['treatment_temp'])
                            Tint = ""
                            if mkey != "":
                                Tint = float(tdrec[mkey])
                            if Tint != "":
                                for zrec in zijdblock:
                                    if zrec[0] == step:  # found matching
                                        tdsblock.append(
                                            [step, zrec[3]/Tnorm, Tint/Tnorm])
                                        break
                    if len(tdsblock) > 2:
                        pmagplotlib.plot_tds(
                            AZD['TDS'], tdsblock, s+':LP-PI-TDS:')
                        if verbose:
                            pmagplotlib(draw_figs(AZD))
                    else:
                        print("Something wrong here")
                if anis == 1:   # look up anisotropy data for this specimen
                    AniSpec = ""
                    for aspec in anis_data:
                        if aspec["er_specimen_name"] == PmagSpecRec["er_specimen_name"]:
                            AniSpec = aspec
                            if verbose:
                                print('Found anisotropy record...')
                            break
                if inspec != "":
                    if verbose:
                        print('Looking up saved interpretation....')
                    found = 0
                    for k in range(len(PriorRecs)):
                        try:
                            if PriorRecs[k]["er_specimen_name"] == s:
                                found = 1
                                CurrRec.append(PriorRecs[k])
                                for j in range(len(zijdblock)):
                                    if float(zijdblock[j][0]) == float(PriorRecs[k]["measurement_step_min"]):
                                        start = j
                                    if float(zijdblock[j][0]) == float(PriorRecs[k]["measurement_step_max"]):
                                        end = j
                                pars, errcode = pmag.PintPars(
                                    datablock, araiblock, zijdblock, start, end, accept)
                                pars['measurement_step_unit'] = "K"
                                pars['experiment_type'] = 'LP-PI-TRM'
                                # put in CurrRec, take out of PriorRecs
                                del PriorRecs[k]
                                if errcode != 1:
                                    pars["specimen_lab_field_dc"] = field
                                    pars["specimen_int"] = -1 * \
                                        field*pars["specimen_b"]
                                    pars["er_specimen_name"] = s
                                    if verbose:
                                        print('Saved interpretation: ')
                                    pars, kill = pmag.scoreit(
                                        pars, PmagSpecRec, accept, '', verbose)
                                    pmagplotlib.plot_b(
                                        AZD, araiblock, zijdblock, pars)
                                    if verbose:
                                        pmagplotlib.draw_figs(AZD)
                                    if len(trmblock) > 2:
                                        blab = field
                                        best = pars["specimen_int"]
                                        Bs, TRMs = [], []
                                        for trec in trmblock:
                                            Bs.append(
                                                float(trec['treatment_dc_field']))
                                            TRMs.append(
                                                float(trec['measurement_magn_moment']))
                                        # calculate best fit parameters through TRM acquisition data, and get new banc
                                        NLpars = nlt.NLtrm(
                                            Bs, TRMs, best, blab, 0)
                                        Mp, Bp = [], []
                                        for k in range(int(max(Bs)*1e6)):
                                            Bp.append(float(k)*1e-6)
                                            # predicted NRM for this field
                                            npred = nlt.TRM(
                                                Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1])
                                            Mp.append(npred)
                                        pmagplotlib.plot_trm(
                                            AZD['TRM'], Bs, TRMs, Bp, Mp, NLpars, trec['magic_experiment_name'])
                                        PmagSpecRec['specimen_int'] = NLpars['banc']
                                        if verbose:
                                            print('Banc= ', float(
                                                NLpars['banc'])*1e6)
                                            pmagplotlib.draw_figs(AZD)
                                    mpars = pmag.domean(
                                        araiblock[1], start, end, 'DE-BFL')
                                    if verbose:
                                        print('pTRM direction= ', '%7.1f' % (mpars['specimen_dec']), ' %7.1f' % (
                                            mpars['specimen_inc']), ' MAD:', '%7.1f' % (mpars['specimen_mad']))
                                    if AniSpec != "":
                                        CpTRM = pmag.Dir_anis_corr(
                                            [mpars['specimen_dec'], mpars['specimen_inc']], AniSpec)
                                        AniSpecRec = pmag.doaniscorr(
                                            PmagSpecRec, AniSpec)
                                        if verbose:
                                            print('Anisotropy corrected TRM direction= ', '%7.1f' % (
                                                CpTRM[0]), ' %7.1f' % (CpTRM[1]))
                                            print('Anisotropy corrected intensity= ', float(
                                                AniSpecRec['specimen_int'])*1e6)
                                else:
                                    print('error on specimen ', s)
                        except:
                            pass
                    if verbose and found == 0:
                        print('    None found :(  ')
                if spc != "":
                    if BEG != "":
                        pars, errcode = pmag.PintPars(
                            datablock, araiblock, zijdblock, BEG, END, accept)
                        pars['measurement_step_unit'] = "K"
                        pars["specimen_lab_field_dc"] = field
                        pars["specimen_int"] = -1*field*pars["specimen_b"]
                        pars["er_specimen_name"] = s
                        pars['specimen_grade'] = ''  # ungraded
                        pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                        if verbose:
                            pmagplotlib.draw_figs(AZD)
                        if len(trmblock) > 2:
                            if inlt == 0:
                                inlt = 1
                            blab = field
                            best = pars["specimen_int"]
                            Bs, TRMs = [], []
                            for trec in trmblock:
                                Bs.append(float(trec['treatment_dc_field']))
                                TRMs.append(
                                    float(trec['measurement_magn_moment']))
                            # calculate best fit parameters through TRM acquisition data, and get new banc
                            NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0)
    #
                            Mp, Bp = [], []
                            for k in range(int(max(Bs)*1e6)):
                                Bp.append(float(k)*1e-6)
                                # predicted NRM for this field
                                npred = nlt.TRM(
                                    Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1])
                    files = {}
                    for key in AZD.keys():
                        files[key] = s+'_'+key+fmt
                    pmagplotlib.save_plots(AZD, files, dpi=dpi)
                    sys.exit()
                if verbose:
                    ans = 'b'
                    while ans != "":
                        print("""
               s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit:
               """)
                        ans = input('Return for next specimen \n')
                        if ans == "":
                            specimen += 1
                        if ans == "d":
                            save_redo(PriorRecs, inspec)
                            CurrRec = []
                            pmagplotlib.plot_arai_zij(
                                AZD, araiblock, zijdblock, s, units[0])
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                        if ans == 'a':
                            files = {}
                            for key in AZD.keys():
                                files[key] = "LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name'] + \
                                    '_SA:_' + \
                                    PmagSpecRec['er_sample_name'] + \
                                    '_SP:_'+s+'_CO:_s_TY:_'+key+fmt
                            pmagplotlib.save_plots(AZD, files)
                            ans = ""
                        if ans == 'q':
                            print("Good bye")
                            sys.exit()
                        if ans == 'p':
                            specimen = specimen - 1
                            backup = 1
                            ans = ""
                        if ans == 's':
                            keepon = 1
                            spec = input(
                                'Enter desired specimen name (or first part there of): ')
                            while keepon == 1:
                                try:
                                    specimen = sids.index(spec)
                                    keepon = 0
                                except:
                                    tmplist = []
                                    for qq in range(len(sids)):
                                        if spec in sids[qq]:
                                            tmplist.append(sids[qq])
                                    print(specimen, " not found, but this was: ")
                                    print(tmplist)
                                    spec = input('Select one or try again\n ')
                            ans = ""
                        if ans == 'b':
                            if end == 0 or end >= len(zijdblock):
                                end = len(zijdblock)-1
                            GoOn = 0
                            while GoOn == 0:
                                answer = input(
                                    'Enter index of first point for calculation: ['+str(start)+']  ')
                                try:
                                    start = int(answer)
                                    answer = input(
                                        'Enter index  of last point for calculation: ['+str(end)+']  ')
                                    end = int(answer)
                                    if start >= 0 and start < len(zijdblock)-2 and end > 0 and end < len(zijdblock) or start >= end:
                                        GoOn = 1
                                    else:
                                        print("Bad endpoints - try again! ")
                                        start, end = 0, len(zijdblock)
                                except ValueError:
                                    print("Bad endpoints - try again! ")
                                    start, end = 0, len(zijdblock)
                            s = sids[specimen]
                            pars, errcode = pmag.PintPars(
                                datablock, araiblock, zijdblock, start, end, accept)
                            pars['measurement_step_unit'] = "K"
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1*field*pars["specimen_b"]
                            pars["er_specimen_name"] = s
                            pars, kill = pmag.scoreit(
                                pars, PmagSpecRec, accept, '', 0)
                            PmagSpecRec['specimen_scat'] = pars['specimen_scat']
                            PmagSpecRec['specimen_frac'] = '%5.3f' % (
                                pars['specimen_frac'])
                            PmagSpecRec['specimen_gmax'] = '%5.3f' % (
                                pars['specimen_gmax'])
                            PmagSpecRec["measurement_step_min"] = '%8.3e' % (
                                pars["measurement_step_min"])
                            PmagSpecRec["measurement_step_max"] = '%8.3e' % (
                                pars["measurement_step_max"])
                            PmagSpecRec["measurement_step_unit"] = "K"
                            PmagSpecRec["specimen_int_n"] = '%i' % (
                                pars["specimen_int_n"])
                            PmagSpecRec["specimen_lab_field_dc"] = '%8.3e' % (
                                pars["specimen_lab_field_dc"])
                            PmagSpecRec["specimen_int"] = '%9.4e ' % (
                                pars["specimen_int"])
                            PmagSpecRec["specimen_b"] = '%5.3f ' % (
                                pars["specimen_b"])
                            PmagSpecRec["specimen_q"] = '%5.1f ' % (
                                pars["specimen_q"])
                            PmagSpecRec["specimen_f"] = '%5.3f ' % (
                                pars["specimen_f"])
                            PmagSpecRec["specimen_fvds"] = '%5.3f' % (
                                pars["specimen_fvds"])
                            PmagSpecRec["specimen_b_beta"] = '%5.3f' % (
                                pars["specimen_b_beta"])
                            PmagSpecRec["specimen_int_mad"] = '%7.1f' % (
                                pars["specimen_int_mad"])
                            PmagSpecRec["specimen_Z"] = '%7.1f' % (
                                pars["specimen_Z"])
                            PmagSpecRec["specimen_gamma"] = '%7.1f' % (
                                pars["specimen_gamma"])
                            PmagSpecRec["specimen_grade"] = pars["specimen_grade"]
                            if pars["method_codes"] != "":
                                tmpcodes = pars["method_codes"].split(":")
                                for t in tmpcodes:
                                    if t.strip() not in methcodes:
                                        methcodes.append(t.strip())
                            PmagSpecRec["specimen_dec"] = '%7.1f' % (
                                pars["specimen_dec"])
                            PmagSpecRec["specimen_inc"] = '%7.1f' % (
                                pars["specimen_inc"])
                            PmagSpecRec["specimen_tilt_correction"] = '-1'
                            PmagSpecRec["specimen_direction_type"] = 'l'
                            # this is redundant, but helpful - won't be imported
                            PmagSpecRec["direction_type"] = 'l'
                            PmagSpecRec["specimen_int_dang"] = '%7.1f ' % (
                                pars["specimen_int_dang"])
                            PmagSpecRec["specimen_drats"] = '%7.1f ' % (
                                pars["specimen_drats"])
                            PmagSpecRec["specimen_drat"] = '%7.1f ' % (
                                pars["specimen_drat"])
                            PmagSpecRec["specimen_int_ptrm_n"] = '%i ' % (
                                pars["specimen_int_ptrm_n"])
                            PmagSpecRec["specimen_rsc"] = '%6.4f ' % (
                                pars["specimen_rsc"])
                            PmagSpecRec["specimen_md"] = '%i ' % (
                                int(pars["specimen_md"]))
                            if PmagSpecRec["specimen_md"] == '-1':
                                PmagSpecRec["specimen_md"] = ""
                            PmagSpecRec["specimen_b_sigma"] = '%5.3f ' % (
                                pars["specimen_b_sigma"])
                            if "IE-TT" not in methcodes:
                                methcodes.append("IE-TT")
                            methods = ""
                            for meth in methcodes:
                                methods = methods+meth+":"
                            PmagSpecRec["magic_method_codes"] = methods[:-1]
                            PmagSpecRec["specimen_description"] = comment
                            PmagSpecRec["magic_software_packages"] = version_num
                            pmagplotlib.plot_arai_zij(
                                AZD, araiblock, zijdblock, s, units[0])
                            pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                            if len(trmblock) > 2:
                                blab = field
                                best = pars["specimen_int"]
                                Bs, TRMs = [], []
                                for trec in trmblock:
                                    Bs.append(
                                        float(trec['treatment_dc_field']))
                                    TRMs.append(
                                        float(trec['measurement_magn_moment']))
                                # calculate best fit parameters through TRM acquisition data, and get new banc
                                NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0)
                                Mp, Bp = [], []
                                for k in range(int(max(Bs)*1e6)):
                                    Bp.append(float(k)*1e-6)
                                    # predicted NRM for this field
                                    npred = nlt.TRM(
                                        Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1])
                                    Mp.append(npred)
                                pmagplotlib.plot_trm(
                                    AZD['TRM'], Bs, TRMs, Bp, Mp, NLpars, trec['magic_experiment_name'])
                                if verbose:
                                    print(
                                        'Non-linear TRM corrected intensity= ', float(NLpars['banc'])*1e6)
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1*field*pars["specimen_b"]
                            pars, kill = pmag.scoreit(
                                pars, PmagSpecRec, accept, '', verbose)
                            saveit = input(
                                "Save this interpretation? [y]/n \n")
                            if saveit != 'n':
                                # put back an interpretation
                                PriorRecs.append(PmagSpecRec)
                                specimen += 1
                                save_redo(PriorRecs, inspec)
                            ans = ""
                elif plots == 1:
                    specimen += 1
                    if fmt != ".pmag":
                        files = {}
                        for key in AZD.keys():
                            files[key] = "LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name']+'_SA:_' + \
                                PmagSpecRec['er_sample_name'] + \
                                '_SP:_'+s+'_CO:_s_TY:_'+key+'_'+fmt
                        if pmagplotlib.isServer:
                            black = '#000000'
                            purple = '#800080'
                            titles = {}
                            titles['deremag'] = 'DeReMag Plot'
                            titles['zijd'] = 'Zijderveld Plot'
                            titles['arai'] = 'Arai Plot'
                            AZD = pmagplotlib.add_borders(
                                AZD, titles, black, purple)
                        pmagplotlib.save_plots(AZD, files, dpi=dpi)
    #                   pmagplotlib.combineFigs(s,files,3)
                    else:  # save in pmag format
                        script = "grep "+s+" output.mag | thellier -mfsi"
                        script = script+' %8.4e' % (field)
                        min = '%i' % ((pars["measurement_step_min"]-273))
                        Max = '%i' % ((pars["measurement_step_max"]-273))
                        script = script+" "+min+" "+Max
                        script = script+" |plotxy;cat mypost >>thellier.ps\n"
                        pltf.write(script)
                        pmag.domagicmag(outf, MeasRecs)
        if len(CurrRec) > 0:
            for rec in CurrRec:
                PriorRecs.append(rec)
        CurrRec = []
    if plots != 1 and verbose:
        ans = input(" Save last plot? 1/[0] ")
        if ans == "1":
            if fmt != ".pmag":
                files = {}
                for key in AZD.keys():
                    files[key] = s+'_'+key+fmt
                pmagplotlib.save_plots(AZD, files, dpi=dpi)
        else:
            print("\n Good bye\n")
            sys.exit()
        if len(CurrRec) > 0:
            PriorRecs.append(CurrRec)  # put back an interpretation
        if len(PriorRecs) > 0:
            save_redo(PriorRecs, inspec)
            print('Updated interpretations saved in ', inspec)
    if verbose:
        print("Good bye")
Example #18
0
def main():
    """
    NAME
        vgpmap_magic.py

    DESCRIPTION
        makes a map of vgps and a95/dp,dm for site means in a sites table

    SYNTAX
        vgpmap_magic.py [command line options]

    OPTIONS
        -h prints help and quits
        -eye  ELAT ELON [specify eyeball location], default is 90., 0.
        -f FILE sites format file, [default is sites.txt]
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -etp plot the etopo20 topographpy data (requires high resolution data set)
        -prj PROJ,  specify one of the following:
             ortho = orthographic
             lcc = lambert conformal
             moll = molweide
             merc = mercator
        -sym SYM SIZE: choose a symbol and size, examples:
            ro 5 : small red circles
            bs 10 : intermediate blue squares
            g^ 20 : large green triangles
        -ell  plot dp/dm or a95 ellipses
        -rev RSYM RSIZE : flip reverse poles to normal antipode
        -S:  plot antipodes of all poles
        -age : plot the ages next to the poles
        -crd [g,t] : choose coordinate system, default is to plot all site VGPs
        -fmt [pdf, png, eps...] specify output format, default is pdf
        -sav  save and quit
    DEFAULTS
        FILE: sites.txt
        res:  c
        prj: ortho
        ELAT,ELON = 0,0
        SYM SIZE: ro 8
        RSYM RSIZE: g^ 8

    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", ".")
    # plot: default is 0, if -sav in sys.argv should be 1
    plot = pmag.get_flag_arg_from_sys("-sav", true=1, false=0)
    fmt = pmag.get_named_arg("-fmt", "pdf")
    res = pmag.get_named_arg("-res", "c")
    proj = pmag.get_named_arg("-prj", "ortho")
    anti = pmag.get_flag_arg_from_sys("-S", true=1, false=0)
    fancy = pmag.get_flag_arg_from_sys("-etp", true=1, false=0)
    ell = pmag.get_flag_arg_from_sys("-ell", true=1, false=0)
    ages = pmag.get_flag_arg_from_sys("-age", true=1, false=0)
    if '-rev' in sys.argv:
        flip = 1
        ind = sys.argv.index('-rev')
        rsym = (sys.argv[ind + 1])
        rsize = int(sys.argv[ind + 2])
    else:
        flip, rsym, rsize = 0, "g^", 8
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym = (sys.argv[ind + 1])
        size = int(sys.argv[ind + 2])
    else:
        sym, size = 'ro', 8
    if '-eye' in sys.argv:
        ind = sys.argv.index('-eye')
        lat_0 = float(sys.argv[ind + 1])
        lon_0 = float(sys.argv[ind + 2])
    else:
        lat_0, lon_0 = 90., 0.
    crd = pmag.get_named_arg("-crd", "")
    coord_dict = {'g': 0, 't': 100}
    coord = coord_dict[crd] if crd else ""
    results_file = pmag.get_named_arg("-f", "sites.txt")

    con = cb.Contribution(dir_path, single_file=results_file)
    if not list(con.tables.keys()):
        print("-W - Couldn't read in data")
        return

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

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

    # go through rows and extract data
    for ind, row in Results.iterrows():
        lat, lon = float(row['vgp_lat']), float(row['vgp_lon'])
        if anti == 1:
            lats.append(-lat)
            lon = lon + 180.
            if lon > 360:
                lon = lon - 360.
            lons.append(lon)
        elif flip == 0:
            lats.append(lat)
            lons.append(lon)
        elif flip == 1:
            if lat < 0:
                rlats.append(-lat)
                lon = lon + 180.
                if lon > 360:
                    lon = lon - 360
                rlons.append(lon)
            else:
                lats.append(lat)
                lons.append(lon)

        ppars = []
        ppars.append(lon)
        ppars.append(lat)
        ell1, ell2 = "", ""
        if 'vgp_dm' in list(row.keys()) and row['vgp_dm']:
            ell1 = float(row['vgp_dm'])
        if 'vgp_dp' in list(row.keys()) and row['vgp_dp']:
            ell2 = float(row['vgp_dp'])
        if 'vgp_alpha95' in list(row.keys()) and row['vgp_alpha95'].notnull():
            ell1, ell2 = float(row['vgp_alpha95']), float(row['vgp_alpha95'])
        if ell1 and ell2:
            ppars = []
            ppars.append(lons[-1])
            ppars.append(lats[-1])
            ppars.append(ell1)
            ppars.append(lons[-1])
            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 and not set_env.IS_WIN:
        pmagplotlib.draw_figs(FIG)
    if ell == 1:  # add ellipses if desired.
        Opts['details'] = {
            'coasts': 0,
            'rivers': 0,
            'states': 0,
            'countries': 0,
            'ocean': 0,
            'fancy': fancy
        }
        Opts['pltgrid'] = -1  # turn off meridian replotting
        Opts['symsize'] = 2
        Opts['sym'] = 'g-'
        for ppars in Pars:
            if ppars[2] != 0:
                PTS = pmagplotlib.plot_ell(FIG['map'], ppars, 'g.', 0, 0)
                elats, elons = [], []
                for pt in PTS:
                    elons.append(pt[0])
                    elats.append(pt[1])
                # make the base map with a blue triangle at the pole
                pmagplotlib.plot_map(FIG['map'], elats, elons, Opts)
                if plot == 0 and not set_env.IS_WIN:
                    pmagplotlib.draw_figs(FIG)
    files = {}
    for key in list(FIG.keys()):
        if pmagplotlib.isServer:  # use server plot naming convention
            files[key] = 'LO:_' + location + '_VGP_map.' + fmt
        else:  # use more readable naming convention
            files[key] = '{}_VGP_map.{}'.format(location, fmt)

    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['map'] = '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)
Example #19
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

    INPUT
       takes magic formatted pmag_results, pmag_sites, pmag_samples or pmag_specimens

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

    DESCRIPTION
       calculates Watson's V statistic from input files

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

    SYNTAX
       watsons_v.py [command line options]

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

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

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

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

    DESCRIPTION
       plots equal area projection  from dec inc data and fisher mean, cone of confidence

    INPUT FORMAT
       takes dec, inc, alpha95 as first three columns in space delimited file

    SYNTAX
       plotdi_a.py [-i][-f FILE]

    OPTIONS
        -f FILE to read file name from command line
        -fmt [png,jpg,eps,pdf,svg] set plot file format ['svg' is default]
        -sav save plot and quit

    """
    fmt,plot='svg',0
    if len(sys.argv) > 0:
        if '-h' in sys.argv: # check if help is needed
            print(main.__doc__)
            sys.exit() # graceful quit
        if '-fmt' in sys.argv:
            ind=sys.argv.index('-fmt')
            fmt=sys.argv[ind+1]
        if '-sav' in sys.argv:plot=1
        if '-f' in sys.argv:
            ind=sys.argv.index('-f')
            file=sys.argv[ind+1]
            f=open(file,'r')
            data=f.readlines()
        else:
            data=sys.stdin.readlines() # read in data from standard input
    DIs,Pars=[],[]
    for line in data:   # read in the data from standard input
        pars=[]
        rec=line.split() # split each line on space to get records
        DIs.append([float(rec[0]),float(rec[1])])
        pars.append(float(rec[0]))
        pars.append(float(rec[1]))
        pars.append(float(rec[2]))
        pars.append(float(rec[0]))
        isign=abs(float(rec[1])) / float(rec[1])
        pars.append(float(rec[1])-isign*90.) #Beta inc
        pars.append(float(rec[2])) # gamma
        pars.append(float(rec[0])+90.) # Beta dec
        pars.append(0.) #Beta inc
        Pars.append(pars)
#
    EQ={'eq':1} # make plot dictionary
    pmagplotlib.plot_init(EQ['eq'],5,5)
    title='Equal area projection'
    pmagplotlib.plot_eq(EQ['eq'],DIs,title)# plot directions
    for k in range(len(Pars)):
        pmagplotlib.plot_ell(EQ['eq'],Pars[k],'b',0,1) # plot ellipses
    files={}
    for key in list(EQ.keys()):
        files[key]=key+'.'+fmt
    titles={}
    titles['eq']='Equal Area Plot'
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(EQ,files)
    elif plot==0:
        pmagplotlib.draw_figs(EQ)
        ans=input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans=="q": sys.exit()
        if ans=="a":
            pmagplotlib.save_plots(EQ,files)
    else:
        pmagplotlib.save_plots(EQ,files)
Example #22
0
def main():
    """
    NAME
        strip_magic.py

    DESCRIPTION
        plots various parameters versus depth or age

    SYNTAX
        strip_magic.py [command line optins]

    OPTIONS
        -h prints help message and quits
        -DM NUM: specify data model num, options 2 (legacy) or 3 (default)
        -f FILE: specify input magic format file from magic,default='pmag_results.txt'
         supported types=[pmag_specimens, pmag_samples, pmag_sites, pmag_results, magic_web]
        -obj [sit,sam,all]: specify object to site,sample,all for pmag_result table, default is all
        -fmt [svg,png,jpg], format for images - default is svg
        -x [age,pos]:  specify whether age or stratigraphic position
        -y [dec,inc,int,chi,lat,lon,vdm,vadm]
           (lat and lon are VGP lat and lon)
        -Iex: plot the expected inc at lat - only available for results with lat info in file
        -ts TS amin amax: plot the GPTS for the time interval between amin and amax (numbers in Ma)
           TS: [ck95, gts04]
        -mcd method_code, specify method code, default is first one encountered
        -sav  save plot and quit
    NOTES
        when x and/or y are not specified, a list of possibilities will be presented to the user for choosing

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

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


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

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

    DESCRIPTION
        plots points on map
 
    SYNTAX
        plot_map_pts.py [command line options]

    OPTIONS
        -h prints help and quits
        -sym [ro, bs, g^, r., b-, etc.] [1,5,10] symbol and size for points
           colors are r=red,b=blue,g=green, etc.
           symbols are '.' for points, ^, for triangle, s for square, etc.
            -, for lines, -- for dotted lines, see matplotlib online documentation for plot()
        -eye  ELAT ELON [specify eyeball location]
        -etp  put on topography
        -cmap color map [default is jet]
        -f FILE, specify input file
        -o color ocean blue/land green (default is not)
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -fmt [pdf,eps, png] specify output format (default is pdf)
        -R don't plot details of rivers
        -B don't plot national/state boundaries, etc.
        -pad [LAT LON] pad bounding box by LAT/LON (default is not)
        -grd SPACE specify grid spacing
        -sav  save plot and quit
        -prj PROJ,  specify one of the supported projections: 
            pc = Plate Carree
            aea = Albers Equal Area
            aeqd = Azimuthal Equidistant
            lcc = Lambert Conformal
            lcyl = Lambert Cylindrical
            merc = Mercator
            mill = Miller Cylindrical
            moll = Mollweide [default]
            ortho = Orthographic
            robin = Robinson
            sinu = Sinusoidal
            stere = Stereographic
            tmerc = Transverse Mercator
            utm = UTM
            laea = Lambert Azimuthal Equal Area
            geos = Geostationary
            npstere = North-Polar Stereographic
            spstere = South-Polar Stereographic
        Special codes for MagIC formatted input files:
            -n
            -l
    
    INPUTS
        space or tab delimited LON LAT data
        OR: 
           standard MagIC formatted er_sites or pmag_results table
    DEFAULTS
        res:  c
        prj: mollweide;  lcc for MagIC format files 
        ELAT,ELON = 0,0
        pad LAT,LON=0,0
        NB: high resolution or lines can be very slow
    
    """
    dir_path='.'
    plot=0
    ocean=0
    res='c'
    proj='moll'
    Lats,Lons=[],[]
    fmt='pdf'
    sym='ro'
    symsize=5
    fancy=0
    rivers,boundaries,ocean=1,1,0
    latmin,latmax,lonmin,lonmax,lat_0,lon_0=-90,90,0.,360.,0.,0.
    padlat,padlon,gridspace=0,0,30
    lat_0,lon_0="",""
    basemap=1
    prn_name,prn_loc,names,locs=0,0,[],[]
    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 '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res=sys.argv[ind+1]
        if res!= 'c' and res!='l':
            print('this resolution will take a while - be patient')
    if '-etp' in sys.argv: 
        fancy=1
        print ('-W- plotting will require patience!')
    if '-ctp' in sys.argv: basemap=0
    if '-sav' in sys.argv: plot=1
    if '-R' in sys.argv:rivers=0
    if '-B' in sys.argv:boundaries=0
    if '-o' in sys.argv:ocean=1
    if '-cmap' in sys.argv:
        ind = sys.argv.index('-cmap')
        cmap=float(sys.argv[ind+1])
    else:
        cmap='jet'
    if '-grd' in sys.argv:
        ind = sys.argv.index('-grd')
        gridspace=float(sys.argv[ind+1])
    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 '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym=sys.argv[ind+1]
        symsize=int(sys.argv[ind+2])
    if '-pad' in sys.argv:
        ind = sys.argv.index('-pad')
        padlat=float(sys.argv[ind+1])
        padlon=float(sys.argv[ind+2])
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file=dir_path+'/'+sys.argv[ind+1]
        header=open(file,'r').readlines()[0].split('\t')
        if 'tab' in header[0]:
            proj='lcc'
            if 'sites' in header[1]:
                latkey='lat'
                lonkey='lon'
                namekey='site'
                lockey=''
            else:  
                print('file type not supported')
                print(main.__doc__)
                sys.exit()
            Sites,file_type=pmag.magic_read(file)
            Lats=pmag.get_dictkey(Sites,latkey,'f')
            Lons=pmag.get_dictkey(Sites,lonkey,'f')
            if prn_name==1:names=pmag.get_dictkey(Sites,namekey,'')
            if prn_loc==1:names=pmag.get_dictkey(Sites,lockey,'')
        else:
            ptdata=numpy.loadtxt(file)
            Lons=ptdata.transpose()[0]
            Lats=ptdata.transpose()[1]
        latmin=numpy.min(Lats)-padlat
        lonmin=numpy.min(Lons)-padlon
        latmax=numpy.max(Lats)+padlat
        lonmax=numpy.max(Lons)+padlon
        if lon_0=="":
            lon_0=0.5*(lonmin+lonmax)
            lat_0=0.5*(latmin+latmax)
    else:
        print("input file must be specified")
        sys.exit()
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj=sys.argv[ind+1]
    FIG={'map':1}
    pmagplotlib.plot_init(FIG['map'],6,6)
    cnt=0
    Opts={'latmin':latmin,'latmax':latmax,'lonmin':lonmin,'lonmax':lonmax,'lat_0':lat_0,'lon_0':lon_0,'proj':proj,'sym':sym,'symsize':3,'pltgrid':1,'res':res,'boundinglat':0.,'padlon':padlon,'padlat':padlat,'gridspace':gridspace,'cmap':cmap}
    Opts['details']={}
    Opts['details']['coasts']=1
    Opts['details']['rivers']=rivers
    Opts['details']['states']=boundaries
    Opts['details']['countries']=boundaries
    Opts['details']['ocean']=ocean
    Opts['details']['fancy']=fancy
    if len(names)>0:Opts['names']=names
    if len(locs)>0:Opts['loc_name']=locs
    if proj=='merc':
        Opts['latmin']=-70
        Opts['latmax']=70
        Opts['lonmin']=-180
        Opts['lonmax']=180
    print('please wait to draw points')
    Opts['sym']=sym
    Opts['symsize']=symsize
    if basemap: 
        pmagplotlib.plot_map(FIG['map'],Lats,Lons,Opts)
    else:
        pmagplotlib.plot_map(FIG['map'],Lats,Lons,Opts)
    files={}
    titles={}
    titles['map']='PT Map'
    for key in list(FIG.keys()):
        files[key]='map_pts'+'.'+fmt
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        FIG = pmagplotlib.add_borders(FIG,titles,black,purple)
        pmagplotlib.save_plots(FIG,files)
    if plot==1:
        pmagplotlib.save_plots(FIG,files)
    else:
        pmagplotlib.draw_figs(FIG)
        ans=input(" S[a]ve to save plot, Return to quit:  ")
        if ans=="a": pmagplotlib.save_plots(FIG,files)
Example #24
0
def main():
    """
    NAME
       fishqq.py

    DESCRIPTION
       makes qq plot from dec,inc input data

    INPUT FORMAT
       takes dec/inc pairs in space delimited file

    SYNTAX
       fishqq.py [command line options]

    OPTIONS
        -h help message
        -f FILE, specify file on command line
        -F FILE, specify output file for statistics
        -sav save and quit [saves as input file name plus fmt extension]
        -fmt specify format for output [png, eps, svg, pdf] 

    OUTPUT:
        Dec Inc N Mu Mu_crit Me Me_crit Y/N
     where direction is the principal component and Y/N is Fisherian or not
     separate lines for each mode with N >=10 (N and R)
    """
    fmt, plot = 'svg', 0
    outfile = ""
    if '-h' in sys.argv:  # check if help is needed
        print(main.__doc__)
        sys.exit()  # graceful quit
    elif '-f' in sys.argv:  # ask for filename
        ind = sys.argv.index('-f')
        file = sys.argv[ind + 1]
        f = open(file, 'r')
        data = f.readlines()
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        outfile = open(sys.argv[ind + 1], 'w')  # open output file
    if '-sav' in sys.argv: plot = 1
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    DIs, nDIs, rDIs = [], [], []  # set up list for 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])])  # append data to Inc
# split into two modes
    ppars = pmag.doprinc(DIs)  # get principal directions
    for rec in DIs:
        angle = pmag.angle([rec[0], rec[1]], [ppars['dec'], ppars['inc']])
        if angle > 90.:
            rDIs.append(rec)
        else:
            nDIs.append(rec)


#
    if len(rDIs) >= 10 or len(nDIs) >= 10:
        D1, I1 = [], []
        QQ = {'unf1': 1, 'exp1': 2}
        pmagplotlib.plot_init(QQ['unf1'], 5, 5)
        pmagplotlib.plot_init(QQ['exp1'], 5, 5)
        if len(nDIs) < 10:
            ppars = pmag.doprinc(rDIs)  # get principal directions
            Drbar, Irbar = ppars['dec'] - 180., -ppars['inc']
            Nr = len(rDIs)
            for di in rDIs:
                d, irot = pmag.dotilt(di[0], di[1], Drbar - 180.,
                                      90. - Irbar)  # rotate to mean
                drot = d - 180.
                if drot < 0: drot = drot + 360.
                D1.append(drot)
                I1.append(irot)
                Dtit = 'Mode 2 Declinations'
                Itit = 'Mode 2 Inclinations'
        else:
            ppars = pmag.doprinc(nDIs)  # get principal directions
            Dnbar, Inbar = ppars['dec'], ppars['inc']
            Nn = len(nDIs)
            for di in nDIs:

                d, irot = pmag.dotilt(di[0], di[1], Dnbar - 180.,
                                      90. - Inbar)  # rotate to mean
                drot = d - 180.
                if drot < 0: drot = drot + 360.
                D1.append(drot)
                I1.append(irot)
                Dtit = 'Mode 1 Declinations'
                Itit = 'Mode 1 Inclinations'
        Mu_n, Mu_ncr = pmagplotlib.plot_qq_unf(QQ['unf1'], D1,
                                               Dtit)  # make plot
        Me_n, Me_ncr = pmagplotlib.plot_qq_exp(QQ['exp1'], I1,
                                               Itit)  # make plot
        #print Mu_n,Mu_ncr,Me_n, Me_ncr
        if outfile != "":
            #        Dec Inc N Mu Mu_crit Me Me_crit Y/N
            if Mu_n <= Mu_ncr and Me_n <= Me_ncr:
                F = 'Y'
            else:
                F = 'N'
            outstring = '%7.1f %7.1f %i %5.3f %5.3f %5.3f %5.3f %s \n' % (
                Dnbar, Inbar, Nn, Mu_n, Mu_ncr, Me_n, Me_ncr, F)
            outfile.write(outstring)
    else:
        print('you need N> 10 for at least one mode')
        sys.exit()
    if len(rDIs) > 10 and len(nDIs) > 10:
        D2, I2 = [], []
        QQ['unf2'] = 3
        QQ['exp2'] = 4
        pmagplotlib.plot_init(QQ['unf2'], 5, 5)
        pmagplotlib.plot_init(QQ['exp2'], 5, 5)
        ppars = pmag.doprinc(rDIs)  # get principal directions
        Drbar, Irbar = ppars['dec'] - 180., -ppars['inc']
        Nr = len(rDIs)
        for di in rDIs:
            d, irot = pmag.dotilt(di[0], di[1], Drbar - 180.,
                                  90. - Irbar)  # rotate to mean
            drot = d - 180.
            if drot < 0: drot = drot + 360.
            D2.append(drot)
            I2.append(irot)
            Dtit = 'Mode 2 Declinations'
            Itit = 'Mode 2 Inclinations'
        Mu_r, Mu_rcr = pmagplotlib.plot_qq_unf(QQ['unf2'], D2,
                                               Dtit)  # make plot
        Me_r, Me_rcr = pmagplotlib.plot_qq_exp(QQ['exp2'], I2,
                                               Itit)  # make plot
        if outfile != "":
            #        Dec Inc N Mu Mu_crit Me Me_crit Y/N
            if Mu_r <= Mu_rcr and Me_r <= Me_rcr:
                F = 'Y'
            else:
                F = 'N'
            outstring = '%7.1f %7.1f %i %5.3f %5.3f %5.3f %5.3f %s \n' % (
                Drbar, Irbar, Nr, Mu_r, Mu_rcr, Me_r, Me_rcr, F)
            outfile.write(outstring)
    files = {}
    for key in list(QQ.keys()):
        files[key] = file + '_' + key + '.' + fmt
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['eq'] = 'Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ, titles, black, purple)
        pmagplotlib.save_plots(QQ, files)
    elif plot == 1:
        pmagplotlib.save_plots(QQ, files)
    else:
        pmagplotlib.draw_figs(QQ)
        ans = input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans == "a": pmagplotlib.save_plots(QQ, files)
Example #25
0
def main():
    """
    NAME
       revtest_MM1990.py

    DESCRIPTION
       calculates Watson's V statistic from input files through Monte Carlo simulation in order to test whether normal and reversed populations could have been drawn from a common mean (equivalent to watsonV.py). Also provides the critical angle between the two sample mean directions and the corresponding McFadden and McElhinny (1990) classification.

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files (one file for normal directions, one file for reversed directions).

    SYNTAX
       revtest_MM1990.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE
        -f2 FILE
        -P  (don't plot the Watson V cdf)

    OUTPUT
        Watson's V between the two populations and the Monte Carlo Critical Value Vc.
        M&M1990 angle, critical angle and classification
        Plot of Watson's V CDF from Monte Carlo simulation (red line), V is solid and Vc is dashed.

    """
    D1,D2=[],[]
    plot=1
    Flip=1
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    if '-P' in  sys.argv: plot=0
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file1=sys.argv[ind+1]
    f1=open(file1,'r')
    for line in f1.readlines():
        rec=line.split()
        Dec,Inc=float(rec[0]),float(rec[1])
        D1.append([Dec,Inc,1.])
    f1.close()
    if '-f2' in sys.argv:
        ind=sys.argv.index('-f2')
        file2=sys.argv[ind+1]
        f2=open(file2,'r')
        print("be patient, your computer is doing 5000 simulations...")
        for line in f2.readlines():
            rec=line.split()
            Dec,Inc=float(rec[0]),float(rec[1])
            D2.append([Dec,Inc,1.])
        f2.close()
    #take the antipode for the directions in file 2
    D2_flip=[]
    for rec in D2:
        d,i=(rec[0]-180.)%360.,-rec[1]
        D2_flip.append([d,i,1.])

    pars_1=pmag.fisher_mean(D1)
    pars_2=pmag.fisher_mean(D2_flip)

    cart_1=pmag.dir2cart([pars_1["dec"],pars_1["inc"],pars_1["r"]])
    cart_2=pmag.dir2cart([pars_2['dec'],pars_2['inc'],pars_2["r"]])
    Sw=pars_1['k']*pars_1['r']+pars_2['k']*pars_2['r'] # k1*r1+k2*r2
    xhat_1=pars_1['k']*cart_1[0]+pars_2['k']*cart_2[0] # k1*x1+k2*x2
    xhat_2=pars_1['k']*cart_1[1]+pars_2['k']*cart_2[1] # k1*y1+k2*y2
    xhat_3=pars_1['k']*cart_1[2]+pars_2['k']*cart_2[2] # k1*z1+k2*z2
    Rw=numpy.sqrt(xhat_1**2+xhat_2**2+xhat_3**2)
    V=2*(Sw-Rw)
#
#keep weighted sum for later when determining the "critical angle" let's save it as Sr (notation of McFadden and McElhinny, 1990)
#
    Sr=Sw
#
# do monte carlo simulation of datasets with same kappas, but common mean
#
    counter,NumSims=0,5000
    Vp=[] # set of Vs from simulations
    for k in range(NumSims):
#
# get a set of N1 fisher distributed vectors with k1, calculate fisher stats
#
        Dirp=[]
        for i in range(pars_1["n"]):
            Dirp.append(pmag.fshdev(pars_1["k"]))
        pars_p1=pmag.fisher_mean(Dirp)
#
# get a set of N2 fisher distributed vectors with k2, calculate fisher stats
#
        Dirp=[]
        for i in range(pars_2["n"]):
            Dirp.append(pmag.fshdev(pars_2["k"]))
        pars_p2=pmag.fisher_mean(Dirp)
#
# get the V for these
#
        Vk=pmag.vfunc(pars_p1,pars_p2)
        Vp.append(Vk)
#
# sort the Vs, get Vcrit (95th percentile one)
#
    Vp.sort()
    k=int(.95*NumSims)
    Vcrit=Vp[k]
#
# equation 18 of McFadden and McElhinny, 1990 calculates the critical value of R (Rwc)
#
    Rwc=Sr-(old_div(Vcrit,2))
#
#following equation 19 of McFadden and McElhinny (1990) the critical angle is calculated.
#
    k1=pars_1['k']
    k2=pars_2['k']
    R1=pars_1['r']
    R2=pars_2['r']
    critical_angle=numpy.degrees(numpy.arccos(old_div(((Rwc**2)-((k1*R1)**2)-((k2*R2)**2)),(2*k1*R1*k2*R2))))
    D1_mean=(pars_1['dec'],pars_1['inc'])
    D2_mean=(pars_2['dec'],pars_2['inc'])
    angle=pmag.angle(D1_mean,D2_mean)
#
# print the results of the test
#
    print("")
    print("Results of Watson V test: ")
    print("")
    print("Watson's V:           " '%.1f' %(V))
    print("Critical value of V:  " '%.1f' %(Vcrit))

    if V<Vcrit:
        print('"Pass": Since V is less than Vcrit, the null hypothesis that the two populations are drawn from distributions that share a common mean direction (antipodal to one another) cannot be rejected.')
    elif V>Vcrit:
        print('"Fail": Since V is greater than Vcrit, the two means can be distinguished at the 95% confidence level.')
    print("")
    print("M&M1990 classification:")
    print("")
    print("Angle between data set means: " '%.1f'%(angle))
    print("Critical angle of M&M1990:   " '%.1f'%(critical_angle))

    if V>Vcrit:
        print("")
    elif V<Vcrit:
        if critical_angle<5:
            print("The McFadden and McElhinny (1990) classification for this test is: 'A'")
        elif critical_angle<10:
            print("The McFadden and McElhinny (1990) classification for this test is: 'B'")
        elif critical_angle<20:
            print("The McFadden and McElhinny (1990) classification for this test is: 'C'")
        else:
            print("The McFadden and McElhinny (1990) classification for this test is: 'INDETERMINATE;")
    if plot==1:
        CDF={'cdf':1}
        pmagplotlib.plot_init(CDF['cdf'],5,5)
        p1 = pmagplotlib.plot_cdf(CDF['cdf'],Vp,"Watson's V",'r',"")
        p2 = pmagplotlib.plot_vs(CDF['cdf'],[V],'g','-')
        p3 = pmagplotlib.plot_vs(CDF['cdf'],[Vp[k]],'b','--')
        pmagplotlib.draw_figs(CDF)
        files,fmt={},'svg'
        if file2!="":
            files['cdf']='WatsonsV_'+file1+'_'+file2+'.'+fmt
        else:
            files['cdf']='WatsonsV_'+file1+'.'+fmt
        if pmagplotlib.isServer:
            black     = '#000000'
            purple    = '#800080'
            titles={}
            titles['cdf']='Cumulative Distribution'
            CDF = pmagplotlib.add_borders(CDF,titles,black,purple)
            pmagplotlib.save_plots(CDF,files)
        else:
            ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans=="a": pmagplotlib.save_plots(CDF,files)
Example #26
0
def main():
    """
    NAME
        polemap_magic.py

    DESCRIPTION
        makes a map of paleomagnetic poles and a95/dp,dm for pole  in a locations table

    SYNTAX
        polemap_magic.py [command line options]

    OPTIONS
        -h prints help and quits
        -eye  ELAT ELON [specify eyeball location], default is 90., 0.
        -f FILE location format file, [default is locations.txt]
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -etp plot the etopo20 topographpy data (requires high resolution data set)
        -prj PROJ,  specify one of the following:
             ortho = orthographic
             lcc = lambert conformal
             moll = molweide
             merc = mercator
        -sym SYM SIZE: choose a symbol and size, examples:
            ro 5 : small red circles
            bs 10 : intermediate blue squares
            g^ 20 : large green triangles
        -ell  plot dp/dm or a95 ellipses
        -rev RSYM RSIZE : flip reverse poles to normal antipode
        -S:  plot antipodes of all poles
        -age : plot the ages next to the poles
        -crd [g,t] : choose coordinate system, default is to plot all location poles
        -fmt [pdf, png, eps...] specify output format, default is pdf
        -sav  save and quit
    DEFAULTS
        FILE: locations.txt
        res:  c
        prj: ortho
        ELAT,ELON = 0,0
        SYM SIZE: ro 8
        RSYM RSIZE: g^ 8

    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", ".")
    # plot: default is 0, if -sav in sys.argv should be 1
    plot = pmag.get_flag_arg_from_sys("-sav", true=1, false=0)
    fmt = pmag.get_named_arg("-fmt", "pdf")
    res = pmag.get_named_arg("-res", "c")
    proj = pmag.get_named_arg("-prj", "ortho")
    anti = pmag.get_flag_arg_from_sys("-S", true=1, false=0)
    fancy = pmag.get_flag_arg_from_sys("-etp", true=1, false=0)
    ell = pmag.get_flag_arg_from_sys("-ell", true=1, false=0)
    ages = pmag.get_flag_arg_from_sys("-age", true=1, false=0)
    if '-rev' in sys.argv:
        flip = 1
        ind = sys.argv.index('-rev')
        rsym = (sys.argv[ind + 1])
        rsize = int(sys.argv[ind + 2])
    else:
        flip, rsym, rsize = 0, "g^", 8
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym = (sys.argv[ind + 1])
        size = int(sys.argv[ind + 2])
    else:
        sym, size = 'ro', 8
    if '-eye' in sys.argv:
        ind = sys.argv.index('-eye')
        lat_0 = float(sys.argv[ind + 1])
        lon_0 = float(sys.argv[ind + 2])
    else:
        lat_0, lon_0 = 90., 0.
    crd = pmag.get_named_arg("-crd", "")
    coord_dict = {'g': 0, 't': 100}
    coord = coord_dict[crd] if crd else ""
    results_file = pmag.get_named_arg("-f", "locations.txt")

    con = cb.Contribution(dir_path, single_file=results_file)
    if not list(con.tables.keys()):
        print("-W - Couldn't read in data")
        return False, "Couldn't read in data"

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

    pole_container = con.tables['locations']
    pole_df = pole_container.df
    # use individual results
    if not pmagplotlib.isServer:
        if 'result_type' in pole_df.columns:
            pole_df = pole_df[pole_df['result_type'] == 'a']
    if 'pole_lat' not in pole_df.columns or 'pole_lon' not in pole_df.columns:
        print(
            "-W- pole_lat and pole_lon are required columns to run polemap_magic.py"
        )
        return False, "pole_lat and pole_lon are required columns to run polemap_magic.py"
    # use records with pole_lat and pole_lon
    cond1, cond2 = pole_df['pole_lat'].notnull(), pole_df['pole_lon'].notnull()
    Results = pole_df[cond1 & cond2]
    # use tilt correction
    if coord and 'dir_tilt_correction' in Results.columns:
        Results = Results[Results['dir_tilt_correction'] == coord]
    # get location name and average ages
    loc_list = Results['location'].values
    locations = ":".join(Results['location'].unique())
    if 'age' not in Results.columns and 'age_low' in Results.columns and 'age_high' in Results.columns:
        Results['age'] = Results['age_low']+0.5 * \
            (Results['age_high']-Results['age_low'])
    if 'age' in Results.columns and ages == 1:
        dates = Results['age'].unique()

    if not any(Results.index):
        print("-W- No poles could be plotted")
        return False, "No poles could be plotted"

    # go through rows and extract data
    for ind, row in Results.iterrows():
        lat, lon = float(row['pole_lat']), float(row['pole_lon'])
        if 'dir_polarity' in row:
            polarities.append(row['dir_polarity'])
        if anti == 1:
            lats.append(-lat)
            lon = lon + 180.
            if lon > 360:
                lon = lon - 360.
            lons.append(lon)
        elif flip == 0:
            lats.append(lat)
            lons.append(lon)
        elif flip == 1:
            if lat < 0:
                rlats.append(-lat)
                lon = lon + 180.
                if lon > 360:
                    lon = lon - 360
                rlons.append(lon)
            else:
                lats.append(lat)
                lons.append(lon)

        ppars = []
        ppars.append(lon)
        ppars.append(lat)
        ell1, ell2 = "", ""
        if 'pole_dm' in list(row.keys()) and row['pole_dm']:
            ell1 = float(row['pole_dm'])
        if 'pole_dp' in list(row.keys()) and row['pole_dp']:
            ell2 = float(row['pole_dp'])
        if 'pole_alpha95' in list(row.keys()) and row['pole_alpha95']:
            ell1, ell2 = float(row['pole_alpha95']), float(row['pole_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)

    locations = locations.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
    }
    base_Opts = Opts.copy()

    # 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'] = []

    titles = {}
    files = {}

    if pmagplotlib.isServer:
        # plot each indvidual pole for the server
        for ind in range(len(lats)):
            lat = lats[ind]
            lon = lons[ind]
            polarity = ""
            if 'polarites' in locals():
                polarity = polarities[ind]
            polarity = "_" + polarity if polarity else ""
            location = loc_list[ind]
            FIG["map_{}".format(ind)] = ind + 2
            pmagplotlib.plot_init(FIG['map'], 6, 6)
            # if with baseOpts, lat/lon don't show
            # if with Opts, grid lines don't show
            pmagplotlib.plot_map(ind + 2, [90], [0.], base_Opts)
            pmagplotlib.plot_map(ind + 2, [lat], [lon], Opts)
            titles["map_{}".format(ind)] = location
            files["map_{}".format(ind)] = "LO:_{}{}_TY:_POLE_map_.{}".format(
                location, polarity, fmt)

    # truncate location names so that ultra long filenames are not created
    if len(locations) > 50:
        locations = locations[:50]
    if pmagplotlib.isServer:
        # use server plot naming convention
        if 'contribution' in con.tables:
            # try to get contribution id
            con_id = con.tables['contribution'].df.iloc[0].id
            files['map'] = 'MC:_{}_TY:_POLE_map.{}'.format(con_id, fmt)
        else:
            # no contribution id available
            files['map'] = 'LO:_' + locations + '_TY:_POLE_map.' + fmt
    else:
        # use readable naming convention for non-database use
        files['map'] = '{}_POLE_map.{}'.format(locations, fmt)

    #
    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 and not set_env.IS_WIN:
        pmagplotlib.draw_figs(FIG)
    if ell == 1:  # add ellipses if desired.
        Opts['details'] = {
            'coasts': 0,
            'rivers': 0,
            'states': 0,
            'countries': 0,
            'ocean': 0,
            'fancy': fancy
        }
        Opts['pltgrid'] = -1  # turn off meridian replotting
        Opts['symsize'] = 2
        Opts['sym'] = 'g-'
        for ppars in Pars:
            if ppars[2] != 0:
                PTS = pmagplotlib.plot_ell(FIG['map'], ppars, 'g.', 0, 0)
                elats, elons = [], []
                for pt in PTS:
                    elons.append(pt[0])
                    elats.append(pt[1])
                # make the base map with a blue triangle at the pole
                pmagplotlib.plot_map(FIG['map'], elats, elons, Opts)
                if plot == 0 and not set_env.IS_WIN:
                    pmagplotlib.draw_figs(FIG)

    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles['map'] = 'LO:_' + locations + '_POLE_map'
        if 'contribution' in con.tables:
            con_id = con.tables['contribution'].df.iloc[0].id
            titles['map'] = "MagIC contribution {} all locations".format(
                con_id)
        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")
    else:
        pmagplotlib.save_plots(FIG, files)

    return True, files
Example #27
0
def main():
    """
    NAME
        strip_magic.py

    DESCRIPTION
        plots various parameters versus depth or age

    SYNTAX
        strip_magic.py [command line optins]

    OPTIONS
        -h prints help message and quits
        -DM NUM: specify data model num, options 2 (legacy) or 3 (default)
        -f FILE: specify input magic format file from magic,default='pmag_results.txt'
         supported types=[pmag_specimens, pmag_samples, pmag_sites, pmag_results, magic_web]
        -obj [sit,sam,all]: specify object to site,sample,all for pmag_result table, default is all
        -fmt [svg,png,jpg], format for images - default is svg
        -x [age,pos]:  specify whether age or stratigraphic position
        -y [dec,inc,int,chi,lat,lon,vdm,vadm]
           (lat and lon are VGP lat and lon)
        -Iex: plot the expected inc at lat - only available for results with lat info in file
        -ts TS amin amax: plot the GPTS for the time interval between amin and amax (numbers in Ma)
           TS: [ck95, gts04]
        -mcd method_code, specify method code, default is first one encountered
        -sav  save plot and quit
    NOTES
        when x and/or y are not specified, a list of possibilities will be presented to the user for choosing

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

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

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

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

    DESCRIPTION
        makes a map of locations in er_sites.txt

    SYNTAX
        basemap_magic.py  [command line options]

    OPTIONS
        -h prints help message and quits
        -f SFILE, specify er_sites.txt or pmag_results.txt format file
        -res [c,l,i,h] specify resolution (crude,low,intermediate,high)
        -etp plot the etopo20 topographic mesh
        -pad [LAT LON]  pad bounding box by LAT/LON  (default is [.5 .5] degrees)
        -grd SPACE specify grid spacing
        -prj [lcc] , specify projection (lcc=lambert conic conformable), default is mercator
        -n print site names (default is not)
        -l print location names (default is not)
        -o color ocean blue/land green (default is not)
        -R don't plot details of rivers
        -B don't plot national/state  boundaries, etc.
        -sav save plot and quit quietly
        -fmt [png,svg,eps,jpg,pdf] specify format for output, default is pdf
    DEFAULTS
        SFILE: 'er_sites.txt'
        resolution: intermediate
        saved images are in pdf
    """
    dir_path = '.'
    sites_file = 'er_sites.txt'
    ocean = 0
    res = 'i'
    proj = 'merc'
    prn_name = 0
    prn_loc = 0
    fancy = 0
    rivers, boundaries = 0, 0
    padlon, padlat, gridspace, details = .5, .5, .5, 1
    fmt = 'pdf'
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        sites_file = sys.argv[ind+1]
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res = sys.argv[ind+1]
    if '-etp' in sys.argv:
        fancy = 1
    if '-n' in sys.argv:
        prn_name = 1
    if '-l' in sys.argv:
        prn_loc = 1
    if '-o' in sys.argv:
        ocean = 1
    if '-R' in sys.argv:
        rivers = 0
    if '-B' in sys.argv:
        boundaries = 0
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj = sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind+1]
    verbose = pmagplotlib.verbose
    if '-sav' in sys.argv:
        verbose = 0
    if '-pad' in sys.argv:
        ind = sys.argv.index('-pad')
        padlat = float(sys.argv[ind+1])
        padlon = float(sys.argv[ind+2])
    if '-grd' in sys.argv:
        ind = sys.argv.index('-grd')
        gridspace = float(sys.argv[ind+1])
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path = sys.argv[ind+1]
    sites_file = dir_path+'/'+sites_file
    location = ""
    FIG = {'map': 1}
    pmagplotlib.plot_init(FIG['map'], 6, 6)
    # read in er_sites file
    Sites, file_type = pmag.magic_read(sites_file)
    if 'results' in file_type:
        latkey = 'average_lat'
        lonkey = 'average_lon'
        namekey = 'pmag_result_name'
        lockey = 'er_location_names'
    else:
        latkey = 'site_lat'
        lonkey = 'site_lon'
        namekey = 'er_site_name'
        lockey = 'er_location_name'
    lats, lons = [], []
    slats, slons = [], []
    names, locs = [], []
    for site in Sites:
        if prn_loc == 1 and location == "":
            location = site['er_location_name']
        lats.append(float(site[latkey]))
        l = float(site[lonkey])
        if l < 0:
            l = l+360.  # make positive
        lons.append(l)
        if prn_name == 1:
            names.append(site[namekey])
        if prn_loc == 1:
            locs.append(site[lockey])
    for lat in lats:
        slats.append(lat)
    for lon in lons:
        slons.append(lon)
    Opts = {'res': res, 'proj': proj, 'loc_name': locs, 'padlon': padlon, 'padlat': padlat, 'latmin': numpy.min(slats)-padlat, 'latmax': numpy.max(
        slats)+padlat, 'lonmin': numpy.min(slons)-padlon, 'lonmax': numpy.max(slons)+padlon, 'sym': 'ro', 'boundinglat': 0., 'pltgrid': 1.}
    Opts['lon_0'] = 0.5*(numpy.min(slons)+numpy.max(slons))
    Opts['lat_0'] = 0.5*(numpy.min(slats)+numpy.max(slats))
    Opts['names'] = names
    Opts['gridspace'] = gridspace
    Opts['details'] = {'coasts': 1, 'rivers': 1,
                       'states': 1, 'countries': 1, 'ocean': 0}
    if ocean == 1:
        Opts['details']['ocean'] = 1
    if rivers == 1:
        Opts['details']['rivers'] = 0
    if boundaries == 1:
        Opts['details']['states'] = 0
        Opts['details']['countries'] = 0
    Opts['details']['fancy'] = fancy
    pmagplotlib.plot_map(FIG['map'], lats, lons, Opts)
    if verbose:
        pmagplotlib.draw_figs(FIG)
    files = {}
    for key in list(FIG.keys()):
        files[key] = 'Site_map'+'.'+fmt
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['map'] = 'Site Map'
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    elif verbose:
        ans = input(" S[a]ve to save plot, Return to quit:  ")
        if ans == "a":
            pmagplotlib.save_plots(FIG, files)
    else:
        pmagplotlib.save_plots(FIG, files)
Example #29
0
def main():
    """
    NAME
        thellier_magic.py

    DESCRIPTION
        plots Thellier-Thellier, allowing interactive setting of bounds
        and customizing of selection criteria.  Saves and reads interpretations
        from a pmag_specimen formatted table, default: thellier_specimens.txt

    SYNTAX
        thellier_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set magic_measurements input file
        -fsp PRIOR, set pmag_specimen prior interpretations file
        -fan ANIS, set rmag_anisotropy file for doing the anisotropy corrections
        -fcr CRIT, set criteria file for grading.
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (default format)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds adn quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step for slope calculation
           END: ending step for slope calculation
        -z use only z component difference for pTRM calculation

    DEFAULTS
        MEAS: magic_measurements.txt
        REDO: thellier_redo
        CRIT: NONE
        PRIOR: NONE

    OUTPUT
        figures:
            ALL:  numbers refer to temperature steps in command line window
            1) Arai plot:  closed circles are zero-field first/infield
                           open circles are infield first/zero-field
                           triangles are pTRM checks
                           squares are pTRM tail checks
                           VDS is vector difference sum
                           diamonds are bounds for interpretation
            2) Zijderveld plot:  closed (open) symbols are X-Y (X-Z) planes
                                 X rotated to NRM direction
            3) (De/Re)Magnetization diagram:
                           circles are NRM remaining
                           squares are pTRM gained
            4) equal area projections:
               green triangles are pTRM gained direction
                           red (purple) circles are lower(upper) hemisphere of ZI step directions
                           blue (cyan) squares are lower(upper) hemisphere IZ step directions
            5) Optional:  TRM acquisition
            6) Optional: TDS normalization
        command line window:
            list is: temperature step numbers, temperatures (C), Dec, Inc, Int (units of magic_measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates .svg format files with specimen_name, plot type as name
    """
    #
    #   initializations
    #
    meas_file, critout, inspec = "magic_measurements.txt", "", "thellier_specimens.txt"
    first = 1
    inlt = 0
    version_num = pmag.get_version()
    TDinit, Tinit, field, first_save = 0, 0, -1, 1
    user, comment, AniSpec, locname = "", '', "", ""
    ans, specimen, recnum, start, end = 0, 0, 0, 0, 0
    plots, pmag_out, samp_file, style = 0, "", "", "svg"
    verbose = pmagplotlib.verbose
    fmt = '.' + style
    #
    # default acceptance criteria
    #
    accept = pmag.default_criteria(0)[0]  # set the default criteria
    #
    # parse command line options
    #
    Zdiff, anis = 0, 0
    spc, BEG, END = "", "", ""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        meas_file = sys.argv[ind + 1]
    if '-fsp' in sys.argv:
        ind = sys.argv.index('-fsp')
        inspec = sys.argv[ind + 1]
    if '-fan' in sys.argv:
        ind = sys.argv.index('-fan')
        anisfile = sys.argv[ind + 1]
        anis = 1
        anis_data, file_type = pmag.magic_read(anisfile)
        if verbose:
            print("Anisotropy data read in from ", anisfile)
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = '.' + sys.argv[ind + 1]
    if '-dpi' in sys.argv:
        ind = sys.argv.index('-dpi')
        dpi = '.' + sys.argv[ind + 1]
    else:
        dpi = 100
    if '-sav' in sys.argv:
        plots = 1
        verbose = 0
    if '-z' in sys.argv:
        Zdiff = 1
    if '-spc' in sys.argv:
        ind = sys.argv.index('-spc')
        spc = sys.argv[ind + 1]
        if '-b' in sys.argv:
            ind = sys.argv.index('-b')
            BEG = int(sys.argv[ind + 1])
            END = int(sys.argv[ind + 2])
    if '-fcr' in sys.argv:
        ind = sys.argv.index('-fcr')
        critout = sys.argv[ind + 1]
        crit_data, file_type = pmag.magic_read(critout)
        if file_type != 'pmag_criteria':
            if verbose:
                print('bad pmag_criteria file, using no acceptance criteria')
            accept = pmag.default_criteria(1)[0]
        else:
            if verbose:
                print("Acceptance criteria read in from ", critout)
            accept = {
                'pmag_criteria_code': 'ACCEPTANCE',
                'er_citation_names': 'This study'
            }
            for critrec in crit_data:
                if 'sample_int_sigma_uT' in critrec.keys(
                ):  # accommodate Shaar's new criterion
                    critrec['sample_int_sigma'] = '%10.3e' % (
                        eval(critrec['sample_int_sigma_uT']) * 1e-6)
                for key in critrec.keys():
                    if key not in accept.keys() and critrec[key] != '':
                        accept[key] = critrec[key]
    try:
        open(inspec, 'rU')
        PriorRecs, file_type = pmag.magic_read(inspec)
        if file_type != 'pmag_specimens':
            print(file_type)
            print(file_type, inspec, " is not a valid pmag_specimens file ")
            sys.exit()
        for rec in PriorRecs:
            if 'magic_software_packages' not in rec.keys():
                rec['magic_software_packages'] = ""
    except IOError:
        PriorRecs = []
        if verbose:
            print("starting new specimen interpretation file: ", inspec)
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(file_type)
        print(file_type, "This is not a valid magic_measurements file ")
        sys.exit()
    backup = 0
    # define figure numbers for arai, zijderveld and
    #   de-,re-magization diagrams
    AZD = {}
    AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4
    pmagplotlib.plot_init(AZD['arai'], 5, 5)
    pmagplotlib.plot_init(AZD['zijd'], 5, 5)
    pmagplotlib.plot_init(AZD['deremag'], 5, 5)
    pmagplotlib.plot_init(AZD['eqarea'], 5, 5)
    #
    #
    #
    # get list of unique specimen names
    #
    CurrRec = []
    sids = pmag.get_specs(meas_data)
    # get plots for specimen s - default is just to step through arai diagrams
    #
    if spc != "":
        specimen = sids.index(spc)
    while specimen < len(sids):
        methcodes = []

        if verbose:
            print(sids[specimen], specimen + 1, 'of ', len(sids))
        MeasRecs = []
        s = sids[specimen]
        datablock, trmblock, tdsrecs = [], [], []
        PmagSpecRec = {}
        if first == 0:
            for key in keys:
                # make sure all new records have same set of keys
                PmagSpecRec[key] = ""
        PmagSpecRec["er_analyst_mail_names"] = user
        PmagSpecRec["specimen_correction"] = 'u'
        #
        # find the data from the meas_data file for this specimen
        #
        for rec in meas_data:
            if rec["er_specimen_name"] == s:
                MeasRecs.append(rec)
                if "magic_method_codes" not in rec.keys():
                    rec["magic_method_codes"] = ""
                methods = rec["magic_method_codes"].split(":")
                meths = []
                for meth in methods:
                    meths.append(meth.strip())  # take off annoying spaces
                methods = ""
                for meth in meths:
                    if meth.strip() not in methcodes and "LP-" in meth:
                        methcodes.append(meth.strip())
                    methods = methods + meth + ":"
                methods = methods[:-1]
                rec["magic_method_codes"] = methods
                if "LP-PI-TRM" in meths:
                    datablock.append(rec)
                if "LP-TRM" in meths:
                    trmblock.append(rec)
                if "LP-TRM-TD" in meths:
                    tdsrecs.append(rec)
        if len(trmblock) > 2 and inspec != "":
            if Tinit == 0:
                Tinit = 1
                AZD['TRM'] = 5
                pmagplotlib.plot_init(AZD['TRM'], 5, 5)
        elif Tinit == 1:  # clear the TRM figure if not needed
            pmagplotlib.clearFIG(AZD['TRM'])
        if len(tdsrecs) > 2:
            if TDinit == 0:
                TDinit = 1
                AZD['TDS'] = 6
                pmagplotlib.plot_init(AZD['TDS'], 5, 5)
        elif TDinit == 1:  # clear the TDS figure if not needed
            pmagplotlib.clearFIG(AZD['TDS'])
        if len(datablock) < 4:
            if backup == 0:
                specimen += 1
                if verbose:
                    print('skipping specimen - moving forward ', s)
            else:
                specimen -= 1
                if verbose:
                    print('skipping specimen - moving backward ', s)
    #
    #  collect info for the PmagSpecRec dictionary
    #
        else:
            rec = datablock[0]
            PmagSpecRec["er_citation_names"] = "This study"
            PmagSpecRec["er_specimen_name"] = s
            PmagSpecRec["er_sample_name"] = rec["er_sample_name"]
            PmagSpecRec["er_site_name"] = rec["er_site_name"]
            PmagSpecRec["er_location_name"] = rec["er_location_name"]
            locname = rec['er_location_name'].replace('/', '-')
            if "er_expedition_name" in rec.keys():
                PmagSpecRec["er_expedition_name"] = rec["er_expedition_name"]
            if "magic_instrument_codes" not in rec.keys():
                rec["magic_instrument_codes"] = ""
            PmagSpecRec["magic_instrument_codes"] = rec[
                "magic_instrument_codes"]
            PmagSpecRec["measurement_step_unit"] = "K"
            if "magic_experiment_name" not in rec.keys():
                rec["magic_experiment_name"] = ""
            else:
                PmagSpecRec["magic_experiment_names"] = rec[
                    "magic_experiment_name"]

            meths = rec["magic_method_codes"].split()
            # sort data into types
            araiblock, field = pmag.sortarai(datablock, s, Zdiff)
            first_Z = araiblock[0]
            GammaChecks = araiblock[5]
            if len(first_Z) < 3:
                if backup == 0:
                    specimen += 1
                    if verbose:
                        print('skipping specimen - moving forward ', s)
                else:
                    specimen -= 1
                    if verbose:
                        print('skipping specimen - moving backward ', s)
            else:
                backup = 0
                zijdblock, units = pmag.find_dmag_rec(s, meas_data)
                recnum = 0
                if verbose:
                    print("index step Dec   Inc  Int       Gamma")
                    for plotrec in zijdblock:
                        if GammaChecks != "":
                            gamma = ""
                            for g in GammaChecks:
                                if g[0] == plotrec[0] - 273:
                                    gamma = g[1]
                                    break
                        if gamma != "":
                            print('%i     %i %7.1f %7.1f %8.3e %7.1f' %
                                  (recnum, plotrec[0] - 273, plotrec[1],
                                   plotrec[2], plotrec[3], gamma))
                        else:
                            print('%i     %i %7.1f %7.1f %8.3e ' %
                                  (recnum, plotrec[0] - 273, plotrec[1],
                                   plotrec[2], plotrec[3]))
                        recnum += 1
                pmagplotlib.plot_arai_zij(AZD, araiblock, zijdblock, s,
                                          units[0])
                if verbose:
                    pmagplotlib.draw_figs(AZD)
                if len(tdsrecs) > 2:  # a TDS experiment
                    tdsblock = []  # make a list for the TDS  data
                    Mkeys = [
                        'measurement_magnitude', 'measurement_magn_moment',
                        'measurement_magn_volume', 'measuruement_magn_mass'
                    ]
                    mkey, k = "", 0
                    # find which type of intensity
                    while mkey == "" and k < len(Mkeys) - 1:
                        key = Mkeys[k]
                        if key in tdsrecs[0].keys() and tdsrecs[0][key] != "":
                            mkey = key
                        k += 1
                    if mkey == "":
                        break  # get outta here
                    Tnorm = ""
                    for tdrec in tdsrecs:
                        meths = tdrec['magic_method_codes'].split(":")
                        for meth in meths:
                            # strip off potential nasty spaces
                            meth.replace(" ", "")
                        if 'LT-T-I' in meths and Tnorm == "":  # found first total TRM
                            # normalize by total TRM
                            Tnorm = float(tdrec[mkey])
                            # put in the zero step
                            tdsblock.append([273, zijdblock[0][3] / Tnorm, 1.])
                        # found a LP-TRM-TD demag step, now need complementary LT-T-Z from zijdblock
                        if 'LT-T-Z' in meths and Tnorm != "":
                            step = float(tdrec['treatment_temp'])
                            Tint = ""
                            if mkey != "":
                                Tint = float(tdrec[mkey])
                            if Tint != "":
                                for zrec in zijdblock:
                                    if zrec[0] == step:  # found matching
                                        tdsblock.append([
                                            step, zrec[3] / Tnorm, Tint / Tnorm
                                        ])
                                        break
                    if len(tdsblock) > 2:
                        pmagplotlib.plot_tds(AZD['TDS'], tdsblock,
                                             s + ':LP-PI-TDS:')
                        if verbose:
                            pmagplotlib(draw_figs(AZD))
                    else:
                        print("Something wrong here")
                if anis == 1:  # look up anisotropy data for this specimen
                    AniSpec = ""
                    for aspec in anis_data:
                        if aspec["er_specimen_name"] == PmagSpecRec[
                                "er_specimen_name"]:
                            AniSpec = aspec
                            if verbose:
                                print('Found anisotropy record...')
                            break
                if inspec != "":
                    if verbose:
                        print('Looking up saved interpretation....')
                    found = 0
                    for k in range(len(PriorRecs)):
                        try:
                            if PriorRecs[k]["er_specimen_name"] == s:
                                found = 1
                                CurrRec.append(PriorRecs[k])
                                for j in range(len(zijdblock)):
                                    if float(zijdblock[j][0]) == float(
                                            PriorRecs[k]
                                        ["measurement_step_min"]):
                                        start = j
                                    if float(zijdblock[j][0]) == float(
                                            PriorRecs[k]
                                        ["measurement_step_max"]):
                                        end = j
                                pars, errcode = pmag.PintPars(
                                    datablock, araiblock, zijdblock, start,
                                    end, accept)
                                pars['measurement_step_unit'] = "K"
                                pars['experiment_type'] = 'LP-PI-TRM'
                                # put in CurrRec, take out of PriorRecs
                                del PriorRecs[k]
                                if errcode != 1:
                                    pars["specimen_lab_field_dc"] = field
                                    pars["specimen_int"] = -1 * \
                                        field*pars["specimen_b"]
                                    pars["er_specimen_name"] = s
                                    if verbose:
                                        print('Saved interpretation: ')
                                    pars, kill = pmag.scoreit(
                                        pars, PmagSpecRec, accept, '', verbose)
                                    pmagplotlib.plot_b(AZD, araiblock,
                                                       zijdblock, pars)
                                    if verbose:
                                        pmagplotlib.draw_figs(AZD)
                                    if len(trmblock) > 2:
                                        blab = field
                                        best = pars["specimen_int"]
                                        Bs, TRMs = [], []
                                        for trec in trmblock:
                                            Bs.append(
                                                float(
                                                    trec['treatment_dc_field'])
                                            )
                                            TRMs.append(
                                                float(trec[
                                                    'measurement_magn_moment'])
                                            )
                                        # calculate best fit parameters through TRM acquisition data, and get new banc
                                        NLpars = nlt.NLtrm(
                                            Bs, TRMs, best, blab, 0)
                                        Mp, Bp = [], []
                                        for k in range(int(max(Bs) * 1e6)):
                                            Bp.append(float(k) * 1e-6)
                                            # predicted NRM for this field
                                            npred = nlt.TRM(
                                                Bp[-1], NLpars['xopt'][0],
                                                NLpars['xopt'][1])
                                            Mp.append(npred)
                                        pmagplotlib.plot_trm(
                                            AZD['TRM'], Bs, TRMs, Bp, Mp,
                                            NLpars,
                                            trec['magic_experiment_name'])
                                        PmagSpecRec['specimen_int'] = NLpars[
                                            'banc']
                                        if verbose:
                                            print('Banc= ',
                                                  float(NLpars['banc']) * 1e6)
                                            pmagplotlib.draw_figs(AZD)
                                    mpars = pmag.domean(
                                        araiblock[1], start, end, 'DE-BFL')
                                    if verbose:
                                        print(
                                            'pTRM direction= ',
                                            '%7.1f' % (mpars['specimen_dec']),
                                            ' %7.1f' % (mpars['specimen_inc']),
                                            ' MAD:',
                                            '%7.1f' % (mpars['specimen_mad']))
                                    if AniSpec != "":
                                        CpTRM = pmag.Dir_anis_corr([
                                            mpars['specimen_dec'],
                                            mpars['specimen_inc']
                                        ], AniSpec)
                                        AniSpecRec = pmag.doaniscorr(
                                            PmagSpecRec, AniSpec)
                                        if verbose:
                                            print(
                                                'Anisotropy corrected TRM direction= ',
                                                '%7.1f' % (CpTRM[0]),
                                                ' %7.1f' % (CpTRM[1]))
                                            print(
                                                'Anisotropy corrected intensity= ',
                                                float(
                                                    AniSpecRec['specimen_int'])
                                                * 1e6)
                                else:
                                    print('error on specimen ', s)
                        except:
                            pass
                    if verbose and found == 0:
                        print('    None found :(  ')
                if spc != "":
                    if BEG != "":
                        pars, errcode = pmag.PintPars(datablock, araiblock,
                                                      zijdblock, BEG, END,
                                                      accept)
                        pars['measurement_step_unit'] = "K"
                        pars["specimen_lab_field_dc"] = field
                        pars["specimen_int"] = -1 * field * pars["specimen_b"]
                        pars["er_specimen_name"] = s
                        pars['specimen_grade'] = ''  # ungraded
                        pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                        if verbose:
                            pmagplotlib.draw_figs(AZD)
                        if len(trmblock) > 2:
                            if inlt == 0:
                                inlt = 1
                            blab = field
                            best = pars["specimen_int"]
                            Bs, TRMs = [], []
                            for trec in trmblock:
                                Bs.append(float(trec['treatment_dc_field']))
                                TRMs.append(
                                    float(trec['measurement_magn_moment']))
                            # calculate best fit parameters through TRM acquisition data, and get new banc
                            NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0)
                            #
                            Mp, Bp = [], []
                            for k in range(int(max(Bs) * 1e6)):
                                Bp.append(float(k) * 1e-6)
                                # predicted NRM for this field
                                npred = nlt.TRM(Bp[-1], NLpars['xopt'][0],
                                                NLpars['xopt'][1])
                    files = {}
                    for key in AZD.keys():
                        files[key] = s + '_' + key + fmt
                    pmagplotlib.save_plots(AZD, files, dpi=dpi)
                    sys.exit()
                if verbose:
                    ans = 'b'
                    while ans != "":
                        print("""
               s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit:
               """)
                        ans = input('Return for next specimen \n')
                        if ans == "":
                            specimen += 1
                        if ans == "d":
                            save_redo(PriorRecs, inspec)
                            CurrRec = []
                            pmagplotlib.plot_arai_zij(AZD, araiblock,
                                                      zijdblock, s, units[0])
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                        if ans == 'a':
                            files = {}
                            for key in AZD.keys():
                                files[key] = "LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name'] + \
                                    '_SA:_' + \
                                    PmagSpecRec['er_sample_name'] + \
                                    '_SP:_'+s+'_CO:_s_TY:_'+key+fmt
                            pmagplotlib.save_plots(AZD, files)
                            ans = ""
                        if ans == 'q':
                            print("Good bye")
                            sys.exit()
                        if ans == 'p':
                            specimen = specimen - 1
                            backup = 1
                            ans = ""
                        if ans == 's':
                            keepon = 1
                            spec = input(
                                'Enter desired specimen name (or first part there of): '
                            )
                            while keepon == 1:
                                try:
                                    specimen = sids.index(spec)
                                    keepon = 0
                                except:
                                    tmplist = []
                                    for qq in range(len(sids)):
                                        if spec in sids[qq]:
                                            tmplist.append(sids[qq])
                                    print(specimen,
                                          " not found, but this was: ")
                                    print(tmplist)
                                    spec = input('Select one or try again\n ')
                            ans = ""
                        if ans == 'b':
                            if end == 0 or end >= len(zijdblock):
                                end = len(zijdblock) - 1
                            GoOn = 0
                            while GoOn == 0:
                                answer = input(
                                    'Enter index of first point for calculation: ['
                                    + str(start) + ']  ')
                                try:
                                    start = int(answer)
                                    answer = input(
                                        'Enter index  of last point for calculation: ['
                                        + str(end) + ']  ')
                                    end = int(answer)
                                    if start >= 0 and start < len(
                                            zijdblock
                                    ) - 2 and end > 0 and end < len(
                                            zijdblock) or start >= end:
                                        GoOn = 1
                                    else:
                                        print("Bad endpoints - try again! ")
                                        start, end = 0, len(zijdblock)
                                except ValueError:
                                    print("Bad endpoints - try again! ")
                                    start, end = 0, len(zijdblock)
                            s = sids[specimen]
                            pars, errcode = pmag.PintPars(
                                datablock, araiblock, zijdblock, start, end,
                                accept)
                            pars['measurement_step_unit'] = "K"
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1 * field * pars[
                                "specimen_b"]
                            pars["er_specimen_name"] = s
                            pars, kill = pmag.scoreit(pars, PmagSpecRec,
                                                      accept, '', 0)
                            PmagSpecRec['specimen_scat'] = pars[
                                'specimen_scat']
                            PmagSpecRec['specimen_frac'] = '%5.3f' % (
                                pars['specimen_frac'])
                            PmagSpecRec['specimen_gmax'] = '%5.3f' % (
                                pars['specimen_gmax'])
                            PmagSpecRec["measurement_step_min"] = '%8.3e' % (
                                pars["measurement_step_min"])
                            PmagSpecRec["measurement_step_max"] = '%8.3e' % (
                                pars["measurement_step_max"])
                            PmagSpecRec["measurement_step_unit"] = "K"
                            PmagSpecRec["specimen_int_n"] = '%i' % (
                                pars["specimen_int_n"])
                            PmagSpecRec["specimen_lab_field_dc"] = '%8.3e' % (
                                pars["specimen_lab_field_dc"])
                            PmagSpecRec["specimen_int"] = '%9.4e ' % (
                                pars["specimen_int"])
                            PmagSpecRec["specimen_b"] = '%5.3f ' % (
                                pars["specimen_b"])
                            PmagSpecRec["specimen_q"] = '%5.1f ' % (
                                pars["specimen_q"])
                            PmagSpecRec["specimen_f"] = '%5.3f ' % (
                                pars["specimen_f"])
                            PmagSpecRec["specimen_fvds"] = '%5.3f' % (
                                pars["specimen_fvds"])
                            PmagSpecRec["specimen_b_beta"] = '%5.3f' % (
                                pars["specimen_b_beta"])
                            PmagSpecRec["specimen_int_mad"] = '%7.1f' % (
                                pars["specimen_int_mad"])
                            PmagSpecRec["specimen_Z"] = '%7.1f' % (
                                pars["specimen_Z"])
                            PmagSpecRec["specimen_gamma"] = '%7.1f' % (
                                pars["specimen_gamma"])
                            PmagSpecRec["specimen_grade"] = pars[
                                "specimen_grade"]
                            if pars["method_codes"] != "":
                                tmpcodes = pars["method_codes"].split(":")
                                for t in tmpcodes:
                                    if t.strip() not in methcodes:
                                        methcodes.append(t.strip())
                            PmagSpecRec["specimen_dec"] = '%7.1f' % (
                                pars["specimen_dec"])
                            PmagSpecRec["specimen_inc"] = '%7.1f' % (
                                pars["specimen_inc"])
                            PmagSpecRec["specimen_tilt_correction"] = '-1'
                            PmagSpecRec["specimen_direction_type"] = 'l'
                            # this is redundant, but helpful - won't be imported
                            PmagSpecRec["direction_type"] = 'l'
                            PmagSpecRec["specimen_int_dang"] = '%7.1f ' % (
                                pars["specimen_int_dang"])
                            PmagSpecRec["specimen_drats"] = '%7.1f ' % (
                                pars["specimen_drats"])
                            PmagSpecRec["specimen_drat"] = '%7.1f ' % (
                                pars["specimen_drat"])
                            PmagSpecRec["specimen_int_ptrm_n"] = '%i ' % (
                                pars["specimen_int_ptrm_n"])
                            PmagSpecRec["specimen_rsc"] = '%6.4f ' % (
                                pars["specimen_rsc"])
                            PmagSpecRec["specimen_md"] = '%i ' % (int(
                                pars["specimen_md"]))
                            if PmagSpecRec["specimen_md"] == '-1':
                                PmagSpecRec["specimen_md"] = ""
                            PmagSpecRec["specimen_b_sigma"] = '%5.3f ' % (
                                pars["specimen_b_sigma"])
                            if "IE-TT" not in methcodes:
                                methcodes.append("IE-TT")
                            methods = ""
                            for meth in methcodes:
                                methods = methods + meth + ":"
                            PmagSpecRec["magic_method_codes"] = methods[:-1]
                            PmagSpecRec["specimen_description"] = comment
                            PmagSpecRec[
                                "magic_software_packages"] = version_num
                            pmagplotlib.plot_arai_zij(AZD, araiblock,
                                                      zijdblock, s, units[0])
                            pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                            if len(trmblock) > 2:
                                blab = field
                                best = pars["specimen_int"]
                                Bs, TRMs = [], []
                                for trec in trmblock:
                                    Bs.append(float(
                                        trec['treatment_dc_field']))
                                    TRMs.append(
                                        float(trec['measurement_magn_moment']))
                                # calculate best fit parameters through TRM acquisition data, and get new banc
                                NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0)
                                Mp, Bp = [], []
                                for k in range(int(max(Bs) * 1e6)):
                                    Bp.append(float(k) * 1e-6)
                                    # predicted NRM for this field
                                    npred = nlt.TRM(Bp[-1], NLpars['xopt'][0],
                                                    NLpars['xopt'][1])
                                    Mp.append(npred)
                                pmagplotlib.plot_trm(
                                    AZD['TRM'], Bs, TRMs, Bp, Mp, NLpars,
                                    trec['magic_experiment_name'])
                                if verbose:
                                    print(
                                        'Non-linear TRM corrected intensity= ',
                                        float(NLpars['banc']) * 1e6)
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1 * field * pars[
                                "specimen_b"]
                            pars, kill = pmag.scoreit(pars, PmagSpecRec,
                                                      accept, '', verbose)
                            saveit = input(
                                "Save this interpretation? [y]/n \n")
                            if saveit != 'n':
                                # put back an interpretation
                                PriorRecs.append(PmagSpecRec)
                                specimen += 1
                                save_redo(PriorRecs, inspec)
                            ans = ""
                elif plots == 1:
                    specimen += 1
                    if fmt != ".pmag":
                        files = {}
                        for key in AZD.keys():
                            files[key] = "LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name']+'_SA:_' + \
                                PmagSpecRec['er_sample_name'] + \
                                '_SP:_'+s+'_CO:_s_TY:_'+key+'_'+fmt
                        if pmagplotlib.isServer:
                            black = '#000000'
                            purple = '#800080'
                            titles = {}
                            titles['deremag'] = 'DeReMag Plot'
                            titles['zijd'] = 'Zijderveld Plot'
                            titles['arai'] = 'Arai Plot'
                            AZD = pmagplotlib.add_borders(
                                AZD, titles, black, purple)
                        pmagplotlib.save_plots(AZD, files, dpi=dpi)
    #                   pmagplotlib.combineFigs(s,files,3)
                    else:  # save in pmag format
                        script = "grep " + s + " output.mag | thellier -mfsi"
                        script = script + ' %8.4e' % (field)
                        min = '%i' % ((pars["measurement_step_min"] - 273))
                        Max = '%i' % ((pars["measurement_step_max"] - 273))
                        script = script + " " + min + " " + Max
                        script = script + " |plotxy;cat mypost >>thellier.ps\n"
                        pltf.write(script)
                        pmag.domagicmag(outf, MeasRecs)
        if len(CurrRec) > 0:
            for rec in CurrRec:
                PriorRecs.append(rec)
        CurrRec = []
    if plots != 1 and verbose:
        ans = input(" Save last plot? 1/[0] ")
        if ans == "1":
            if fmt != ".pmag":
                files = {}
                for key in AZD.keys():
                    files[key] = s + '_' + key + fmt
                pmagplotlib.save_plots(AZD, files, dpi=dpi)
        else:
            print("\n Good bye\n")
            sys.exit()
        if len(CurrRec) > 0:
            PriorRecs.append(CurrRec)  # put back an interpretation
        if len(PriorRecs) > 0:
            save_redo(PriorRecs, inspec)
            print('Updated interpretations saved in ', inspec)
    if verbose:
        print("Good bye")
Example #30
0
def main():
    """
    NAME
        plot_geomagia.py

    DESCRIPTION
        makes a map  and VADM plot of geomagia download file 

    SYNTAX
        plot_geomagia.py  [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE, specify geomagia download file
        -res [c,l,i,h] specify resolution (crude,low,intermediate,high)
        -etp plot the etopo20 topographic mesh
        -pad [LAT LON]  pad bounding box by LAT/LON  (default is [.5 .5] degrees)
        -grd SPACE specify grid spacing
        -prj [lcc] , specify projection (lcc=lambert conic conformable), default is mercator
        -o color ocean blue/land green (default is not)
        -d plot details of rivers, boundaries, etc.
        -sav save plot and quit quietly
        -fmt [png,svg,eps,jpg,pdf] specify format for output, default is pdf
    DEFAULTS
        resolution: intermediate
        saved images are in pdf
    """
    dir_path='.'
    names,res,proj,locs,padlon,padlat,fancy,gridspace,details=[],'l','lcc','',0,0,0,15,1
    Age_bounds=[-5000,2000]
    Lat_bounds=[20,45]
    Lon_bounds=[15,55]
    fmt='pdf'
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        sites_file=sys.argv[ind+1]
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res=sys.argv[ind+1]
    if '-etp' in sys.argv:fancy=1
    if '-o' in sys.argv:ocean=1
    if '-d' in sys.argv:details=1
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    verbose=pmagplotlib.verbose
    if '-sav' in sys.argv:
        verbose=0
    if '-pad' in sys.argv:
        ind = sys.argv.index('-pad')
        padlat=float(sys.argv[ind+1])
        padlon=float(sys.argv[ind+2])
    if '-grd' in sys.argv:
        ind = sys.argv.index('-grd')
        gridspace=float(sys.argv[ind+1])
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    sites_file=dir_path+'/'+sites_file
    geo_in=open(sites_file,'r').readlines()
    Age,AgeErr,Vadm,VadmErr,slats,slons=[],[],[],[],[],[]
    for line in geo_in[2:]: # skip top two rows`
        rec=line.split()
        if float(rec[0])>Age_bounds[0] and float(rec[0])<Age_bounds[1] \
           and float(rec[12])>Lat_bounds[0] and float(rec[12]) < Lat_bounds[1]\
            and float(rec[13])>Lon_bounds[0] and float(rec[13])<Lon_bounds[1]:
            Age.append(float(rec[0]))
            AgeErr.append(float(rec[1]))
            Vadm.append(10.*float(rec[6]))
            VadmErr.append(10.*float(rec[7]))
            slats.append(float(rec[12]))
            slons.append(float(rec[13]))
    FIGS={'map':1,'vadms':2}
    pmagplotlib.plot_init(FIGS['map'],6,6)
    pmagplotlib.plot_init(FIGS['vadms'],6,6)
    Opts={'res':res,'proj':proj,'loc_name':locs,'padlon':padlon,'padlat':padlat,'latmin':numpy.min(slats)-padlat,'latmax':numpy.max(slats)+padlat,'lonmin':numpy.min(slons)-padlon,'lonmax':numpy.max(slons)+padlon,'sym':'ro','boundinglat':0.,'pltgrid':1}
    Opts['lon_0']=int(0.5*(numpy.min(slons)+numpy.max(slons)))
    Opts['lat_0']=int(0.5*(numpy.min(slats)+numpy.max(slats)))
    Opts['gridspace']=gridspace
    if details==1:
        Opts['details']={'coasts':1,'rivers':0,'states':1,'countries':1,'ocean':1}
    else:
        Opts['details']={'coasts':1,'rivers':0,'states':0,'countries':0,'ocean':1}
    Opts['details']['fancy']=fancy
    pmagplotlib.plot_map(FIGS['map'],slats,slons,Opts)
    pmagplotlib.plot_xy(FIGS['vadms'],Age,Vadm,sym='bo',xlab='Age (Years CE)',ylab=r'VADM (ZAm$^2$)')
    if verbose:pmagplotlib.draw_figs(FIGS)
    files={}
    for key in list(FIGS.keys()):
        files[key]=key+'.'+fmt
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['map']='Map'
        titles['vadms']='VADMs'
        FIG = pmagplotlib.add_borders(FIGS,titles,black,purple)
        pmagplotlib.save_plots(FIGS,files)
    elif verbose:
        ans=input(" S[a]ve to save plot, Return to quit:  ")
        if ans=="a":
            pmagplotlib.save_plots(FIGS,files)
    else:
        pmagplotlib.save_plots(FIGS,files)
Example #31
0
def main():
    """
    NAME
       fishqq.py

    DESCRIPTION
       makes qq plot from dec,inc input data

    INPUT FORMAT
       takes dec/inc pairs in space delimited file

    SYNTAX
       fishqq.py [command line options]

    OPTIONS
        -h help message
        -f FILE, specify file on command line
        -F FILE, specify output file for statistics
        -sav save and quit [saves as input file name plus fmt extension]
        -fmt specify format for output [png, eps, svg, pdf] 

    OUTPUT:
        Dec Inc N Mu Mu_crit Me Me_crit Y/N
     where direction is the principal component and Y/N is Fisherian or not
     separate lines for each mode with N >=10 (N and R)
    """
    fmt,plot='svg',0
    outfile=""
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        data=f.readlines()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        outfile=open(sys.argv[ind+1],'w') # open output file
    if '-sav' in sys.argv: plot=1
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    DIs,nDIs,rDIs= [],[],[] # set up list for 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])]) # append data to Inc
# split into two modes
    ppars=pmag.doprinc(DIs) # get principal directions
    for rec in DIs:
        angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
        if angle>90.:
            rDIs.append(rec)
        else:
            nDIs.append(rec)
    
#
    if len(rDIs) >=10 or len(nDIs) >=10:
        D1,I1=[],[]
        QQ={'unf1':1,'exp1':2}
        pmagplotlib.plot_init(QQ['unf1'],5,5)
        pmagplotlib.plot_init(QQ['exp1'],5,5)
        if len(nDIs) < 10: 
            ppars=pmag.doprinc(rDIs) # get principal directions
            Drbar,Irbar=ppars['dec']-180.,-ppars['inc']
            Nr=len(rDIs)
            for di in rDIs:
                d,irot=pmag.dotilt(di[0],di[1],Drbar-180.,90.-Irbar) # rotate to mean
                drot=d-180.
                if drot<0:drot=drot+360.
                D1.append(drot)           
                I1.append(irot) 
                Dtit='Mode 2 Declinations'
                Itit='Mode 2 Inclinations'
        else:          
            ppars=pmag.doprinc(nDIs) # get principal directions
            Dnbar,Inbar=ppars['dec'],ppars['inc']
            Nn=len(nDIs)
            for di in nDIs:
                d,irot=pmag.dotilt(di[0],di[1],Dnbar-180.,90.-Inbar) # rotate to mean
                drot=d-180.
                if drot<0:drot=drot+360.
                D1.append(drot)
                I1.append(irot)
                Dtit='Mode 1 Declinations'
                Itit='Mode 1 Inclinations'
        Mu_n,Mu_ncr=pmagplotlib.plot_qq_unf(QQ['unf1'],D1,Dtit) # make plot
        Me_n,Me_ncr=pmagplotlib.plot_qq_exp(QQ['exp1'],I1,Itit) # make plot
        #print Mu_n,Mu_ncr,Me_n, Me_ncr
        if outfile!="":
#        Dec Inc N Mu Mu_crit Me Me_crit Y/N
            if Mu_n<=Mu_ncr and Me_n<=Me_ncr:
               F='Y'
            else:
               F='N'
            outstring='%7.1f %7.1f %i %5.3f %5.3f %5.3f %5.3f %s \n'%(Dnbar,Inbar,Nn,Mu_n,Mu_ncr,Me_n,Me_ncr,F)
            outfile.write(outstring)
    else:
        print('you need N> 10 for at least one mode')
        sys.exit()
    if len(rDIs)>10 and len(nDIs)>10:
        D2,I2=[],[]
        QQ['unf2']=3
        QQ['exp2']=4
        pmagplotlib.plot_init(QQ['unf2'],5,5)
        pmagplotlib.plot_init(QQ['exp2'],5,5)
        ppars=pmag.doprinc(rDIs) # get principal directions
        Drbar,Irbar=ppars['dec']-180.,-ppars['inc']
        Nr=len(rDIs)
        for di in rDIs:
            d,irot=pmag.dotilt(di[0],di[1],Drbar-180.,90.-Irbar) # rotate to mean
            drot=d-180.
            if drot<0:drot=drot+360.
            D2.append(drot)           
            I2.append(irot) 
            Dtit='Mode 2 Declinations'
            Itit='Mode 2 Inclinations'
        Mu_r,Mu_rcr=pmagplotlib.plot_qq_unf(QQ['unf2'],D2,Dtit) # make plot
        Me_r,Me_rcr=pmagplotlib.plot_qq_exp(QQ['exp2'],I2,Itit) # make plot
        if outfile!="":
#        Dec Inc N Mu Mu_crit Me Me_crit Y/N
            if Mu_r<=Mu_rcr and Me_r<=Me_rcr:
               F='Y'
            else:
               F='N'
            outstring='%7.1f %7.1f %i %5.3f %5.3f %5.3f %5.3f %s \n'%(Drbar,Irbar,Nr,Mu_r,Mu_rcr,Me_r,Me_rcr,F)
            outfile.write(outstring)
    files={}
    for key in list(QQ.keys()):
        files[key]=file+'_'+key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==1:
        pmagplotlib.save_plots(QQ,files)
    else:
        pmagplotlib.draw_figs(QQ) 
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.save_plots(QQ,files)
Example #32
0
def main():
    """
    NAME
       watsons_v.py

    DESCRIPTION
       calculates Watson's V statistic from input files

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

    SYNTAX
       watsons_v.py [command line options]

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

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

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


#
# sort the Vs, get Vcrit (95th one)
#
    Vp.sort()
    k = int(.95 * NumSims)
    if show == 1:
        print("Watson's V,  Vcrit: ")
        print('   %10.1f %10.1f' % (V, Vp[k]))
    if show == 1 or plot == 1:
        print("Watson's V,  Vcrit: ")
        print('   %10.1f %10.1f' % (V, Vp[k]))
        CDF = {'cdf': 1}
        pmagplotlib.plot_init(CDF['cdf'], 5, 5)
        pmagplotlib.plot_cdf(CDF['cdf'], Vp, "Watson's V", 'r', "")
        pmagplotlib.plot_vs(CDF['cdf'], [V], 'g', '-')
        pmagplotlib.plot_vs(CDF['cdf'], [Vp[k]], 'b', '--')
        if plot == 0: pmagplotlib.draw_figs(CDF)
        files = {}
        if pmagplotlib.isServer:  # use server plot naming convention
            if file2 != "":
                files['cdf'] = 'watsons_v_' + file1 + '_' + file2 + '.' + fmt
            else:
                files['cdf'] = 'watsons_v_' + file1 + '.' + fmt
        else:  # use more readable plot naming convention
            if file2 != "":
                files[
                    'cdf'] = 'watsons_v_' + file1_name + '_' + file2_name + '.' + fmt
            else:
                files['cdf'] = 'watsons_v_' + file1_name + '.' + fmt

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