Beispiel #1
0
def main():
    """
    NAME
        EI.py [command line options]

    DESCRIPTION
        Finds bootstrap confidence bounds on Elongation and Inclination data

    SYNTAX
        EI.py  [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE specifies input file
        -p do parametric bootstrap

    INPUT
        dec/inc pairs

    OUTPUT
        makes a plot of the E/I pair and bootstrapped confidence bounds
        along with the E/I trend predicted by the TK03 field model
        prints out:
            Io (mean inclination), I_lower and I_upper are 95% confidence bounds on inclination
            Eo (elongation), E_lower and E_upper are 95% confidence bounds on elongation
            Edec,Einc are the elongation direction

    """
    par=0
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=open(sys.argv[ind+1],'rU')
    if '-p' in sys.argv: par=1
    rseed,nb,data=10,5000,[]
    upper,lower=int(round(.975*nb)),int(round(.025*nb))
    Es,Is=[],[]
    PLTS={'eq':1,'ei':2}
    pmagplotlib.plot_init(PLTS['eq'],5,5) 
    pmagplotlib.plot_init(PLTS['ei'],5,5) 
#    poly_tab= [  3.07448925e-06,  -3.49555831e-04,  -1.46990847e-02,   2.90905483e+00]
    poly_new= [  3.15976125e-06,  -3.52459817e-04,  -1.46641090e-02,   2.89538539e+00]
#    poly_cp88= [ 5.34558576e-06,  -7.70922659e-04,   5.18529685e-03,   2.90941351e+00]
#    poly_qc96= [  7.08210133e-06,  -8.79536536e-04,   1.09625547e-03,   2.92513660e+00]
#    poly_cj98=[  6.56675431e-06,  -7.91823539e-04,  -1.08211350e-03,   2.80557710e+00]
#    poly_tk03_g20= [  4.96757685e-06,  -6.02256097e-04,  -5.96103272e-03,   2.84227449e+00]
#    poly_tk03_g30= [  7.82525963e-06,  -1.39781724e-03,   4.47187092e-02,   2.54637535e+00]
#    poly_gr99_g=[  1.24362063e-07,  -1.69383384e-04,  -4.24479223e-03,   2.59257437e+00]
#    poly_gr99_e=[  1.26348154e-07,   2.01691452e-04,  -4.99142308e-02,   3.69461060e+00]
    E_EI,E_tab,E_new,E_cp88,E_cj98,E_qc96,E_tk03_g20=[],[],[],[],[],[],[]
    E_tk03_g30,E_gr99_g,E_gr99_e=[],[],[]
    I2=range(0,90,5)
    for inc in I2:
        E_new.append(EI(inc,poly_new)) # use the polynomial from Tauxe et al. (2008)
    pmagplotlib.plotEI(PLTS['ei'],E_new,I2,1)
    if '-f' in sys.argv:
        random.seed(rseed)
        for line in file.readlines():
            rec=line.split()
            dec=float(rec[0])
            inc=float(rec[1])
            if par==1:
                if  len(rec)==4:
                    N=(int(rec[2]))  # append n
                    K=float(rec[3])  # append k
                    rec=[dec,inc,N,K]
                    data.append(rec)
            else:
                rec=[dec,inc]
                data.append(rec)
        pmagplotlib.plotEQ(PLTS['eq'],data,'Data')
        ppars=pmag.doprinc(data)
        n=ppars["N"]
        Io=ppars['inc']
        Edec=ppars['Edir'][0]
        Einc=ppars['Edir'][1]
        Eo=(ppars['tau2']/ppars['tau3'])
        b=0
        print 'doing bootstrap - be patient'
        while b<nb:
            bdata=[]
            for j in range(n):
                boot=random.randint(0,n-1)
                random.jumpahead(rseed)
                if par==1:
                    DIs=[]
                    D,I,N,K=data[boot][0],data[boot][1],data[boot][2],data[boot][3]
                    for k in range(N):
                        dec,inc=pmag.fshdev(K)
                        drot,irot=pmag.dodirot(dec,inc,D,I)
                        DIs.append([drot,irot])
                    fpars=pmag.fisher_mean(DIs)
                    bdata.append([fpars['dec'],fpars['inc'],1.])  # replace data[boot] with parametric dec,inc    
                else:
                    bdata.append(data[boot])
            ppars=pmag.doprinc(bdata)
            Is.append(ppars['inc'])
            Es.append(ppars['tau2']/ppars['tau3'])
            b+=1
            if b%100==0:print b
        Is.sort()
        Es.sort()
        x,std=pmag.gausspars(Es)
        stderr=std/math.sqrt(len(data))
        pmagplotlib.plotX(PLTS['ei'],Io,Eo,Is[lower],Is[upper],Es[lower],Es[upper],'b-')
#        pmagplotlib.plotX(PLTS['ei'],Io,Eo,Is[lower],Is[upper],Eo-stderr,Eo+stderr,'b-')
        print 'Io, Eo, I_lower, I_upper, E_lower, E_upper, Edec, Einc'
        print '%7.1f %4.2f %7.1f %7.1f %4.2f %4.2f %7.1f %7.1f' %(Io,Eo,Is[lower],Is[upper],Es[lower],Es[upper], Edec,Einc)
#        print '%7.1f %4.2f %7.1f %7.1f %4.2f %4.2f' %(Io,Eo,Is[lower],Is[upper],Eo-stderr,Eo+stderr)
    pmagplotlib.drawFIGS(PLTS)
    files,fmt={},'svg'
    for key in PLTS.keys():
        files[key]=key+'.'+fmt 
    ans=raw_input(" S[a]ve to save plot, [q]uit without saving:  ")
    if ans=="a": pmagplotlib.saveP(PLTS,files) 
Beispiel #2
0
def main():
    """
    NAME
       foldtest.py

    DESCRIPTION
       does a fold test (Tauxe, 2010) on data

    INPUT FORMAT
       dec inc dip_direction dip

    SYNTAX
       foldtest.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE file with input data
        -F FILE for confidence bounds on fold test
        -u ANGLE (circular standard deviation) for uncertainty on bedding poles
        -b MIN MAX bounds for quick search of percent untilting [default is -10 to 150%]
        -n NB  number of bootstrap samples [default is 1000]
        -fmt FMT, specify format - default is svg
    
    OUTPUT PLOTS
        Geographic: is an equal area projection of the input data in 
                    original coordinates
        Stratigraphic: is an equal area projection of the input data in 
                    tilt adjusted coordinates
        % Untilting: The dashed (red) curves are representative plots of 
                    maximum eigenvalue (tau_1) as a function of untilting
                    The solid line is the cumulative distribution of the
                    % Untilting required to maximize tau for all the 
                    bootstrapped data sets.  The dashed vertical lines
                    are 95% confidence bounds on the % untilting that yields 
                   the most clustered result (maximum tau_1).  
        Command line: prints out the bootstrapped iterations and
                   finally the confidence bounds on optimum untilting.
        If the 95% conf bounds include 0, then a pre-tilt magnetization is indicated
        If the 95% conf bounds include 100, then a post-tilt magnetization is indicated
        If the 95% conf bounds exclude both 0 and 100, syn-tilt magnetization is
                possible as is vertical axis rotation or other pathologies
        Geographic: is an equal area projection of the input data in 
    
    OPTIONAL OUTPUT FILE:
       The output file has the % untilting within the 95% confidence bounds
nd the number of bootstrap samples
    """
    kappa=0
    fmt='svg'
    nb=1000 # number of bootstraps
    min,max=-10,150
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        outfile=open(sys.argv[ind+1],'w')
    else:
        outfile=""
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1] 
        DIDDs=numpy.loadtxt(file)
    else:
        print main.__doc__
        sys.exit()
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-b' in sys.argv:
        ind=sys.argv.index('-b')
        min=float(sys.argv[ind+1])
        max=float(sys.argv[ind+2])
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        nb=int(sys.argv[ind+1])
    if '-u' in sys.argv:
        ind=sys.argv.index('-u')
        csd=float(sys.argv[ind+1])
        kappa=(81./csd)**2
    #
    # get to work
    #
    PLTS={'geo':1,'strat':2,'taus':3} # make plot dictionary
    pmagplotlib.plot_init(PLTS['geo'],5,5)
    pmagplotlib.plot_init(PLTS['strat'],5,5)
    pmagplotlib.plot_init(PLTS['taus'],5,5)
    pmagplotlib.plotEQ(PLTS['geo'],DIDDs,'Geographic')
    D,I=pmag.dotilt_V(DIDDs)
    TCs=numpy.array([D,I]).transpose()
    pmagplotlib.plotEQ(PLTS['strat'],TCs,'Stratigraphic')
    pmagplotlib.drawFIGS(PLTS)
    Percs=range(min,max)
    Cdf,Untilt=[],[]
    pylab.figure(num=PLTS['taus'])
    print 'doing ',nb,' iterations...please be patient.....'
    for n in range(nb): # do bootstrap data sets - plot first 25 as dashed red line
            if n%50==0:print n
            Taus=[] # set up lists for taus
            PDs=pmag.pseudo(DIDDs)
            if kappa!=0:
                for k in range(len(PDs)):
                    d,i=pmag.fshdev(kappa)
                    dipdir,dip=pmag.dodirot(d,i,PDs[k][2],PDs[k][3])
                    PDs[k][2]=dipdir            
                    PDs[k][3]=dip
            for perc in Percs:
                tilt=numpy.array([1.,1.,1.,0.01*perc])
                D,I=pmag.dotilt_V(PDs*tilt)
                TCs=numpy.array([D,I]).transpose()
                ppars=pmag.doprinc(TCs) # get principal directions
                Taus.append(ppars['tau1'])
            if n<25:pylab.plot(Percs,Taus,'r--')
            Untilt.append(Percs[Taus.index(numpy.max(Taus))]) # tilt that gives maximum tau
            Cdf.append(float(n)/float(nb))
    pylab.plot(Percs,Taus,'k')
    pylab.xlabel('% Untilting')
    pylab.ylabel('tau_1 (red), CDF (green)')
    Untilt.sort() # now for CDF of tilt of maximum tau
    pylab.plot(Untilt,Cdf,'g')
    lower=int(.025*nb)     
    upper=int(.975*nb)
    pylab.axvline(x=Untilt[lower],ymin=0,ymax=1,linewidth=1,linestyle='--')
    pylab.axvline(x=Untilt[upper],ymin=0,ymax=1,linewidth=1,linestyle='--')
    tit= '%i - %i %s'%(Untilt[lower],Untilt[upper],'Percent Unfolding')
    print tit
    print 'range of all bootstrap samples: ', Untilt[0], ' - ', Untilt[-1]
    pylab.title(tit)
    outstring= '%i - %i; %i\n'%(Untilt[lower],Untilt[upper],nb)
    if outfile!="":outfile.write(outstring)
    pmagplotlib.drawFIGS(PLTS)
    ans= raw_input('S[a]ve all figures, <Return> to quit   ')
    if ans!='a':
        print "Good bye"
        sys.exit()
    else:
        files={}
        for key in PLTS.keys():
            files[key]=('foldtest_'+'%s'%(key.strip()[:2])+'.'+fmt)
        pmagplotlib.saveP(PLTS,files)
Beispiel #3
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
    plots = 0
    if '-sav' in sys.argv:
        plots = 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:
            Decs = pmag.get_dictitem(odata, dec_key, '', 'F') # get all records with this dec_key not blank
            if len(Decs) > 0: break
        for inc_key in Inc_keys:
            Incs = pmag.get_dictitem(Decs, inc_key, '', 'F') # get all records with this inc_key not blank
            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] = ''
        cdata = pmag.get_dictitem(Incs, tilt_key, coord, 'T') # get all records matching specified coordinate system
        if coord == '0': # geographic
            udata = pmag.get_dictitem(Incs, tilt_key, '', 'T') # get all the blank records - assume geographic
            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:
            Names = pmag.get_dictitem(cdata, name_key, '', 'F') # get all records with this name_key not blank
            if len(Names) > 0: break
        for dir_type_key in Dir_type_keys:
            Dirs = pmag.get_dictitem(cdata, dir_type_key, '', 'F') # get all records with this direction type
            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.plotEQ(FIG['eqarea'], DIblock, title)
            else:
                pmagplotlib.plotEQcont(FIG['eqarea'], DIblock)
        else:
            pmagplotlib.plotNET(FIG['eqarea'])
        if len(GCblock) > 0:
            for rec in GCblock: pmagplotlib.plotC(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.plotEQsym(FIG['bdirs'], BnDIs, 'Bootstrapped Eigenvectors', sym)
                    if len(rDIs) > 5:
                        BrDIs = pmag.di_boot(rDIs)
                        if len(nDIs) > 5:  # plot on existing plots
                            pmagplotlib.plotDIsym(FIG['bdirs'], BrDIs, sym)
                        else:
                            pmagplotlib.plotEQ(FIG['bdirs'], BrDIs, 'Bootstrapped Eigenvectors')
            if dist == 'B':
                if len(nDIs) > 3 or len(rDIs) > 3: pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], npars, 0)
            elif len(nDIs) > 3 and dist != 'BV':
                pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], npars, 0)
                if len(rDIs) > 3:
                    pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], rpars, 0)
            elif len(rDIs) > 3 and dist != 'BV':
                pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], rpars, 0)
        if verbose: pmagplotlib.drawFIGS(FIG)
        #
        files = {}
        locations = locations[:-1]
        for key in FIG.keys():
            filename = 'LO:_' + locations + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + specimen + '_CO:_' + crd + '_TY:_' + key + '_.' + fmt
            files[key] = filename
        if pmagplotlib.isServer:
            black = '#000000'
            purple = '#800080'
            titles = {}
            titles['eq'] = 'Equal Area Plot'
            FIG = pmagplotlib.addBorders(FIG, titles, black, purple)
            pmagplotlib.saveP(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.saveP(FIG, files)
        if plots:
            pmagplotlib.saveP(FIG, files)
Beispiel #4
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
        -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 = "svg", "F", 1
    plotE = 0
    if "-h" in sys.argv:
        print main.__doc__
        sys.exit()
    pmagplotlib.plot_init(FIG["eq"], 5, 5)
    if "-f" in sys.argv:
        ind = sys.argv.index("-f")
        title = sys.argv[ind + 1]
        f = open(title, "rU")
        data = f.readlines()
    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 = []
    for line in data:
        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
        DIblock.append([float(rec[0]), float(rec[1])])
    if len(DIblock) > 0:
        pmagplotlib.plotEQ(FIG["eq"], DIblock, title)
    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.0:
                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 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 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.0)  # Beta inc
                npars.append(fpars["alpha95"])  # gamma
                npars.append(fpars["dec"] + 90.0)  # Beta dec
                npars.append(0.0)  # Beta inc
            if len(rDIs) > 3:
                fpars = pmag.fisher_mean(rDIs)
                if pmagplotlib.verbose:
                    print "mode ", mode
                for key in 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.0)  # Beta inc
                rpars.append(fpars["alpha95"])  # gamma
                rpars.append(fpars["dec"] + 90.0)  # Beta dec
                rpars.append(0.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 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 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":
                if len(nDIs) >= 10:
                    BnDIs = pmag.di_boot(nDIs)
                    Bkpars = pmag.dokent(BnDIs, 1.0)
                    if pmagplotlib.verbose:
                        print "mode ", mode
                    for key in 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.0)
                    if pmagplotlib.verbose:
                        print "mode ", mode
                    for key in 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":
                vsym = {"lower": ["+", "k"], "upper": ["x", "k"], "size": 5}
                if len(nDIs) > 5:
                    BnDIs = pmag.di_boot(nDIs)
                    pmagplotlib.plotEQsym(FIG["bdirs"], BnDIs, "Bootstrapped Eigenvectors", vsym)
                if len(rDIs) > 5:
                    BrDIs = pmag.di_boot(rDIs)
                    if len(nDIs) > 5:  # plot on existing plots
                        pmagplotlib.plotDIsym(FIG["bdirs"], BrDIs, vsym)
                    else:
                        pmagplotlib.plotEQ(FIG["bdirs"], BrDIs, "Bootstrapped Eigenvectors", vsym)
        if dist == "B":
            if len(nDIs) > 3 or len(rDIs) > 3:
                pmagplotlib.plotCONF(FIG["eq"], etitle, [], npars, 0)
        elif len(nDIs) > 3 and dist != "BV":
            pmagplotlib.plotCONF(FIG["eq"], etitle, [], npars, 0)
            if len(rDIs) > 3:
                pmagplotlib.plotCONF(FIG["eq"], etitle, [], rpars, 0)
        elif len(rDIs) > 3 and dist != "BV":
            pmagplotlib.plotCONF(FIG["eq"], etitle, [], rpars, 0)
    pmagplotlib.drawFIGS(FIG)
    #
    files = {}
    for key in FIG.keys():
        files[key] = title + "_" + key + "." + fmt
    if pmagplotlib.isServer:
        black = "#000000"
        purple = "#800080"
        titles = {}
        titles["eq"] = "Equal Area Plot"
        FIG = pmagplotlib.addBorders(FIG, titles, black, purple)
        pmagplotlib.saveP(FIG, files)
    else:
        ans = raw_input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans == "q":
            sys.exit()
        if ans == "a":
            pmagplotlib.saveP(FIG, files)
Beispiel #5
0
def main():
    """
    NAME
       plotdi_e.py

    DESCRIPTION
       plots equal area projection  from dec inc data and cones of confidence 
           (Fisher, kent or Bingham or bootstrap).

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

    SYNTAX
       plotdi_e.py [command line options]

    OPTIONS
        -h prints help message and quits
        -i for interactive parameter entry
        -f FILE, sets input filename on command line 
        -Fish plots unit vector mean direction, alpha95
        -Bing plots Principal direction, Bingham confidence ellipse
        -Kent plots unit vector mean direction, confidence ellipse
        -Boot E plots unit vector mean direction, bootstrapped confidence ellipse
        -Boot V plots  unit vector mean direction, distribution of bootstrapped means

    """
    dist='F' # default distribution is Fisherian
    mode=1
    EQ={'eq':1}
    if len(sys.argv) > 0:
        if '-h' in sys.argv: # check if help is needed
            print main.__doc__
            sys.exit() # graceful quit
        if '-i' in sys.argv: # ask for filename
            file=raw_input("Enter file name with dec, inc data: ")
            dist=raw_input("Enter desired distrubution: [Fish]er, [Bing]ham, [Kent] [Boot] [default is Fisher]: ")
            if dist=="":dist="F"
            if dist=="Boot":
                 type=raw_input(" Ellipses or distribution of vectors? [E]/V ")
                 if type=="" or type=="E":
                     dist="BE"
                 else:
                     dist="BE"
        else:
#
            if '-f' in sys.argv:
                ind=sys.argv.index('-f')
                file=sys.argv[ind+1]
            else:
                print 'you must specify a file name'
                print main.__doc__
                sys.exit()
            if '-Bing' in sys.argv:dist='B'
            if '-Kent' in sys.argv:dist='K'
            if '-Boot' in sys.argv:
                ind=sys.argv.index('-Boot')
                type=sys.argv[ind+1]
                if type=='E': 
                    dist='BE'
                elif type=='V': 
                    dist='BV'
                    EQ['bdirs']=2
                    pmagplotlib.plot_init(EQ['bdirs'],5,5)
                else:
                    print main.__doc__
                    sys.exit()
    pmagplotlib.plot_init(EQ['eq'],5,5)
#
# get to work
    f=open(file,'r')
    data=f.readlines()
#
    DIs= [] # set up list for dec inc data
    DiRecs=[]
    pars=[]
    nDIs,rDIs,npars,rpars=[],[],[],[]
    mode =1
    for line in data:   # read in the data from standard input
        DiRec={}
        rec=line.split() # split each line on space to get records
        DIs.append((float(rec[0]),float(rec[1]),1.))
        DiRec['dec']=rec[0]
        DiRec['inc']=rec[1]
        DiRec['direction_type']='l'
        DiRecs.append(DiRec)
    # 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 dist=='B': # do on whole dataset
        title="Bingham confidence ellipse"
        bpars=pmag.dobingham(DIs)
        for key in bpars.keys():
            if key!='n':print "    ",key, '%7.1f'%(bpars[key])
            if key=='n':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':
        title="Fisher confidence cone"
        if len(nDIs)>3:
            fpars=pmag.fisher_mean(nDIs)
            print "mode ",mode
            for key in fpars.keys():
                if key!='n':print "    ",key, '%7.1f'%(fpars[key])
                if key=='n':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)
            print "mode ",mode
            for key in fpars.keys():
                if key!='n':print "    ",key, '%7.1f'%(fpars[key])
                if key=='n':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':
        title="Kent confidence ellipse"
        if len(nDIs)>3:
            kpars=pmag.dokent(nDIs,len(nDIs))
            print "mode ",mode
            for key in kpars.keys():
                if key!='n':print "    ",key, '%7.1f'%(kpars[key])
                if key=='n':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))
            print "mode ",mode
            for key in kpars.keys():
                if key!='n':print "    ",key, '%7.1f'%(kpars[key])
                if key=='n':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.)
                print "mode ",mode
                for key in Bkpars.keys():
                    if key!='n':print "    ",key, '%7.1f'%(Bkpars[key])
                    if key=='n':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.)
                print "mode ",mode
                for key in Bkpars.keys():
                    if key!='n':print "    ",key, '%7.1f'%(Bkpars[key])
                    if key=='n':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'])
            title="Bootstrapped confidence ellipse"
        elif dist=='BV':
            if len(nDIs)>5:
                pmagplotlib.plotEQ(EQ['eq'],nDIs,'Data')
                BnDIs=pmag.di_boot(nDIs)
                pmagplotlib.plotEQ(EQ['bdirs'],BnDIs,'Bootstrapped Eigenvectors')
            if len(rDIs)>5:
                BrDIs=pmag.di_boot(rDIs)
                if len(nDIs)>5:  # plot on existing plots
                    pmagplotlib.plotDI(EQ['eq'],rDIs)
                    pmagplotlib.plotDI(EQ['bdirs'],BrDIs)
                else:
                    pmagplotlib.plotEQ(EQ['eq'],rDIs,'Data')
                    pmagplotlib.plotEQ(EQ['bdirs'],BrDIs,'Bootstrapped Eigenvectors')
            pmagplotlib.drawFIGS(EQ)
            ans=raw_input('s[a]ve, [q]uit ')
            if ans=='q':sys.exit()
            if ans=='a':
                files={}
                for key in EQ.keys():
                    files[key]='BE_'+key+'.svg'
                pmagplotlib.saveP(EQ,files)
            sys.exit() 
    if len(nDIs)>5:
        pmagplotlib.plotCONF(EQ['eq'],title,DiRecs,npars,1)
        if len(rDIs)>5 and dist!='B': 
            pmagplotlib.plotCONF(EQ['eq'],title,[],rpars,0)
    elif len(rDIs)>5 and dist!='B': 
        pmagplotlib.plotCONF(EQ['eq'],title,DiRecs,rpars,1)
    pmagplotlib.drawFIGS(EQ)
    ans=raw_input('s[a]ve, [q]uit ')
    if ans=='q':sys.exit()
    if ans=='a':
        files={}
        for key in EQ.keys():
            files[key]=key+'.svg'
        pmagplotlib.saveP(EQ,files)
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()
    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.plotEQsym(FIG['eq'],DIblock,title,sym)
        if plot==0:pmagplotlib.drawFIGS(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 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 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 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 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 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 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 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.plotEQsym(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors',vsym)
                if len(rDIs)>5:
                    BrDIs=pmag.di_boot(rDIs)
                    if len(nDIs)>5:  # plot on existing plots
                        pmagplotlib.plotDIsym(FIG['bdirs'],BrDIs,vsym)
                    else:
                        pmagplotlib.plotEQ(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors',vsym)
        if dist=='B':
            if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plotCONF(FIG['eq'],etitle,[],npars,0)
        elif len(nDIs)>3 and dist!='BV':
            pmagplotlib.plotCONF(FIG['eq'],etitle,[],npars,0)
            if len(rDIs)>3:
                pmagplotlib.plotCONF(FIG['eq'],etitle,[],rpars,0)
        elif len(rDIs)>3 and dist!='BV':
            pmagplotlib.plotCONF(FIG['eq'],etitle,[],rpars,0)
        if plot==0:pmagplotlib.drawFIGS(FIG)
    if plot==0:pmagplotlib.drawFIGS(FIG)
        #
    files={}
    for key in FIG.keys():
        files[key]=title+'_'+key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        FIG = pmagplotlib.addBorders(FIG,titles,black,purple)
        pmagplotlib.saveP(FIG,files)
    elif plot==0:
        ans=raw_input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans=="q": sys.exit()
        if ans=="a": 
            pmagplotlib.saveP(FIG,files) 
    else:
        pmagplotlib.saveP(FIG,files)
Beispiel #7
0
def main():
    """
    NAME
        find_EI.py
 
    DESCRIPTION
        Applies series of assumed flattening factor and "unsquishes" inclinations assuming tangent function.
        Finds flattening factor that gives elongation/inclination pair consistent with TK03.  
        Finds bootstrap confidence bounds

    SYNTAX
        find_EI.py [command line options]

    OPTIONS
        -h prints help message and quits
        -i allows interactive input of file name
        -f FILE specify input file name
        -nb N specify number of bootstraps - the more the better, but slower!, default is 1000
        -fmt [svg,png,eps,pdf..] change plot format, default is svg

    INPUT
        dec/inc pairs, delimited with space or tabs

    OUTPUT
        four plots:  1) equal area plot of original directions
                      2) Elongation/inclination pairs as a function of f,  data plus 25 bootstrap samples
                      3) Cumulative distribution of bootstrapped optimal inclinations plus uncertainties.
                         Estimate from original data set plotted as solid line
                      4) Orientation of principle direction through unflattening
    NOTE: If distribution does not have a solution, plot labeled: Pathological.  Some bootstrap samples may have
       valid solutions and those are plotted in the CDFs and E/I plot.

    """
    fmt,nb='svg',1000
    if '-i' in sys.argv:
        file=raw_input("Enter file name for processing: ")
    elif '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
    else:
        print main.__doc__
        sys.exit()
    if '-nb' in sys.argv:
        ind=sys.argv.index('-nb')
        nb=int(sys.argv[ind+1])
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    data=numpy.loadtxt(file)
    upper,lower=int(round(.975*nb)),int(round(.025*nb))
    E,I=[],[]
    PLTS={'eq':1,'ei':2,'cdf':3,'v2':4}
    pmagplotlib.plot_init(PLTS['eq'],6,6) 
    pmagplotlib.plot_init(PLTS['ei'],5,5) 
    pmagplotlib.plot_init(PLTS['cdf'],5,5) 
    pmagplotlib.plot_init(PLTS['v2'],5,5) 
    pmagplotlib.plotEQ(PLTS['eq'],data,'Data')
    pmagplotlib.drawFIGS(PLTS)
    ppars=pmag.doprinc(data)
    Io=ppars['inc']
    n=ppars["N"]
    Es,Is,Fs,V2s=find_f(data)
    Inc,Elong=Is[-1],Es[-1]
    pmagplotlib.plotEI(PLTS['ei'],Es,Is,Fs[-1])
    pmagplotlib.plotV2s(PLTS['v2'],V2s,Is,Fs[-1])
    b=0
    print "Bootstrapping.... be patient"
    while b<nb:
        bdata=pmag.pseudo(data)
        Es,Is,Fs,V2s=find_f(bdata)
        if b<25:
            pmagplotlib.plotEI(PLTS['ei'],Es,Is,Fs[-1])
        if Es[-1]!=0:
            ppars=pmag.doprinc(bdata)
            I.append(abs(Is[-1]))
            E.append(Es[-1])
            b+=1
            if b%25==0:print b,' out of ',nb
    I.sort()
    E.sort()
    Eexp=[]
    for i in I:
       Eexp.append(EI(i)) 
    if Inc==0:
        title= 'Pathological Distribution: '+'[%7.1f, %7.1f]' %(I[lower],I[upper])
    else:
        title= '%7.1f [%7.1f, %7.1f]' %( Inc, I[lower],I[upper])
    pmagplotlib.plotEI(PLTS['ei'],Eexp,I,1)
    pmagplotlib.plotCDF(PLTS['cdf'],I,'Inclinations','r',title)
    pmagplotlib.plotVs(PLTS['cdf'],[I[lower],I[upper]],'b','--')
    pmagplotlib.plotVs(PLTS['cdf'],[Inc],'g','-')
    pmagplotlib.plotVs(PLTS['cdf'],[Io],'k','-')
    pmagplotlib.drawFIGS(PLTS)
    print "Io Inc  I_lower, I_upper, Elon, E_lower, E_upper"
    print '%7.1f %s %7.1f _ %7.1f ^ %7.1f:  %6.4f _ %6.4f ^ %6.4f' %(Io, " => ", Inc, I[lower],I[upper], Elong, E[lower],E[upper])
    ans= raw_input("S[a]ve plots - <return> to quit:  ")
    if ans!='a':
       print "\n Good bye\n"
       sys.exit()
    files={}
    files['eq']='findEI_eq.'+fmt
    files['ei']='findEI_ei.'+fmt
    files['cdf']='findEI_cdf.'+fmt
    files['v2']='findEI_v2.'+fmt
    pmagplotlib.saveP(PLTS,files)
Beispiel #8
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
        -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 
    NOTE
        all: entire file; sit: site; sam: sample; spc: specimen
    """
    FIG={} # plot dictionary
    FIG['eq']=1 # eqarea is figure 1
    in_file,plot_key,coord,crd='pmag_results.txt','all',"-1",'g'
    fmt,dist,mode='svg','F',1
    plotE,contour=0,0
    dir_path='.'
    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['eq'],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
    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")
        coord=sys.argv[ind+1]
        if coord=='g':coord="0"
        if coord=='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']
    Inc_keys=['site_inc','sample_inc','specimen_inc','measurement_inc','average_inc']
    Tilt_keys=['tilt_correction','site_tilt_correction','sample_tilt_correction','specimen_tilt_correction']
    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 pmagplotlib.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":
        for  rec in data:
            if rec[plot_key] not in plotlist:
                plotlist.append(rec[plot_key])
        plotlist.sort()
    else:
        plotlist.append('Whole file')
    for plot in plotlist:
        DIblock=[]
        GCblock=[]
        SLblock,SPblock=[],[]
        tilt_key=""
        mode=1
        for rec in data: # find what data are available
            if plot_key=='all' or rec[plot_key]==plot:
                if plot_key!="all":
                    title=rec[plot_key]
                else:
                    title=plot
                if coord=='-1':title=title+' Specimen Coordinates'
                if coord=='0':title=title+' Geographic Coordinates'
                if coord=='100':title=title+' Tilt corrected Coordinates'
                dec_key,inc_key,tilt_key,name_key,k="","","","",0
                while dec_key==""  and k<len(Dec_keys):
                    if Dec_keys[k]  in rec.keys() and rec[Dec_keys[k]]!="" and Inc_keys[k] in rec.keys() and rec[Inc_keys[k]]!="": 
                        dec_key,inc_key =Dec_keys[k],Inc_keys[k]
                    k+=1
                k=0
                while tilt_key==""  and k<len(Tilt_keys):
                    if Tilt_keys[k]  in rec.keys():tilt_key=Tilt_keys[k]
                    k+=1
                k=0
                while name_key==""  and k<len(Name_keys):
                    if Name_keys[k]  in rec.keys():name_key=Name_keys[k]
                    k+=1
                k=1
                while dir_type_key==""  and k<len(Dir_type_keys):
                    if Dir_type_keys[k]  in rec.keys():dir_type_key=Dir_type_keys[k]
                    k+=1
                if  dec_key!="":break 
        if tilt_key=="":tilt_key='-1'
        if dir_type_key=="":dir_type_key='direction_type'
        for rec in data: # pick out the data
          if (plot_key=='all' or rec[plot_key]==plot)  and rec[dec_key].strip()!="" and rec[inc_key].strip()!="":
            if dir_type_key not in rec.keys() or rec[dir_type_key]=="":rec[dir_type_key]='l'
            if tilt_key not in rec.keys():rec[tilt_key]='-1' # assume specimen coordinates unless otherwise specified
            if coord=='-1':
                    DIblock.append([float(rec[dec_key]),float(rec[inc_key])])
                    SLblock.append([rec[name_key],rec['magic_method_codes']])
            elif rec[tilt_key]==coord and rec[dir_type_key]=='l' and rec[dec_key]!="" and rec[inc_key]!="":
                if rec[tilt_key]==coord and rec[dir_type_key]=='l' and rec[dec_key]!="" and rec[inc_key]!="":
                    DIblock.append([float(rec[dec_key]),float(rec[inc_key])])
                    SLblock.append([rec[name_key],rec['magic_method_codes']])
            elif 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 pmagplotlib.verbose: print "no records for plotting"
            sys.exit()
        if pmagplotlib.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.plotEQ(FIG['eq'],DIblock,title)
            else:
                pmagplotlib.plotEQcont(FIG['eq'],DIblock)
        else:   pmagplotlib.plotNET(FIG['eq'])
        if len(GCblock)>0:
            for rec in GCblock: pmagplotlib.plotC(FIG['eq'],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 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)>2:
                    fpars=pmag.fisher_mean(nDIs)
                    for key in 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)>2:
                    fpars=pmag.fisher_mean(rDIs)
                    if pmagplotlib.verbose:print "mode ",mode
                    for key in 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 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 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 dist=='BE':
                    if len(nDIs)>5:
                        BnDIs=pmag.di_boot(nDIs)
                        Bkpars=pmag.dokent(BnDIs,1.)
                        if pmagplotlib.verbose:print "mode ",mode
                        for key in 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)>5:
                        BrDIs=pmag.di_boot(rDIs)
                        Bkpars=pmag.dokent(BrDIs,1.)
                        if pmagplotlib.verbose:print "mode ",mode
                        for key in 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':
                    if len(nDIs)>5:
                        BnDIs=pmag.di_boot(nDIs)
                        pmagplotlib.plotEQ(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors')
                    if len(rDIs)>5:
                        BrDIs=pmag.di_boot(rDIs)
                        if len(nDIs)>5:  # plot on existing plots
                            pmagplotlib.plotDI(FIG['bdirs'],BrDIs)
                        else:
                            pmagplotlib.plotEQ(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors')
            if dist=='B':
                if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plotCONF(FIG['eq'],etitle,[],npars,0)
            elif len(nDIs)>3 and dist!='BV':
                pmagplotlib.plotCONF(FIG['eq'],etitle,[],npars,0)
                if len(rDIs)>3:
                    pmagplotlib.plotCONF(FIG['eq'],etitle,[],rpars,0)
            elif len(rDIs)>3 and dist!='BV':
                pmagplotlib.plotCONF(FIG['eq'],etitle,[],rpars,0)
        pmagplotlib.drawFIGS(FIG)
            #
        files={}
        for key in FIG.keys():
            files[key]=title.replace(" ","_")+'_'+'eqarea'+'.'+fmt 
        if pmagplotlib.isServer:
            black     = '#000000'
            purple    = '#800080'
            titles={}
            titles['eq']='Equal Area Plot'
            FIG = pmagplotlib.addBorders(FIG,titles,black,purple)
            pmagplotlib.saveP(FIG,files)
        else:
            ans=raw_input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
            if ans=="q": sys.exit()
            if ans=="a": 
                pmagplotlib.saveP(FIG,files) 
Beispiel #9
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
        -i for interactive filename entry
        -f FILE to read file name from command line

    """
    fmt='svg'
    if len(sys.argv) > 0:
        if '-h' in sys.argv: # check if help is needed
            print main.__doc__
            sys.exit() # graceful quit
        if '-i' in sys.argv: # ask for filename
            file=raw_input("Enter file name with dec, inc data: ")
            f=open(file,'rU')
            data=f.readlines()
        elif '-f' in sys.argv:
            ind=sys.argv.index('-f')
            file=sys.argv[ind+1]
            f=open(file,'rU')
            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.plotEQ(EQ['eq'],DIs,title)# plot directions
    for k in range(len(Pars)):
        pmagplotlib.plotELL(EQ['eq'],Pars[k],'b',0,1) # plot ellipses
    pmagplotlib.drawFIGS(EQ)
    files={}
    for key in EQ.keys():
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.addBorders(EQ,titles,black,purple)
        pmagplotlib.saveP(EQ,files)
    else:
        ans=raw_input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans=="q": sys.exit()
        if ans=="a": 
            pmagplotlib.saveP(EQ,files) 
Beispiel #10
0
def main():
    """
    NAME
        find_EI.py
 
    DESCRIPTION
        Applies assumed flattening factor and "unsquishes" inclinations assuming tangent function.
        Finds flattening factor that gives elongation/inclination pair consistent with TK03.  
        Finds bootstrap confidence bounds

    SYNTAX
        find_EI.py [-h][-i] [-f FILE] 

    INPUT
        dec/inc pairs

    OUTPUT
        three plots:  1) equal area plot of original directions
                      2) Elongation/inclination pairs as a function of f,  data plus 25 bootstrap samples
                      3) Cumulative distribution of bootstrapped optimal inclinations plus uncertainties.
                         Estimate from original data set plotted as solid line

    """
    if '-i' in sys.argv:
        file=raw_input("Enter file name for processing: ")
        f=open(file,'rU') 
    elif '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'rU') 
    else:
        print main.__doc__
        sys.exit()
    rseed,nb,data=10,5000,[]
    upper,lower=int(round(.975*nb)),int(round(.025*nb))
    E,I=[],[]
    PLTS={'eq':1,'ei':2,'cdf':3,'v2':4}
    pmagplotlib.plot_init(PLTS['eq'],6,6) 
    pmagplotlib.plot_init(PLTS['ei'],5,5) 
    pmagplotlib.plot_init(PLTS['cdf'],5,5) 
    pmagplotlib.plot_init(PLTS['v2'],5,5) 
    random.seed(rseed)
    for line in f.readlines():
        rec=line.split()
        dec=float(rec[0])
        inc=float(rec[1])
        rec=[dec,inc,1.]
        data.append(rec)
    pmagplotlib.plotEQ(PLTS['eq'],data,'Data')
    ppars=pmag.doprinc(data)
    Io=ppars['inc']
    n=ppars["N"]
    Es,Is,Fs,V2s=find_f(data)
    Inc,Elong=Is[-1],Es[-1]
    pmagplotlib.plotEI(PLTS['ei'],Es,Is,Fs[-1])
    pmagplotlib.plotV2s(PLTS['v2'],V2s,Is,Fs[-1])
    b=0
    print "Bootstrapping.... be patient"
    while b<nb:
        bdata=[]
        for j in range(n):
            boot=random.randint(0,n-1)
            random.jumpahead(rseed)
            bdata.append(data[boot])
        Es,Is,Fs,V2s=find_f(bdata)
        if b<25:
            pmagplotlib.plotEI(PLTS['ei'],Es,Is,Fs[-1])
        if Es[-1]!=0:
            ppars=pmag.doprinc(bdata)
            I.append(abs(Is[-1]))
            E.append(Es[-1])
            b+=1
            if b%25==0:print b,' out of ',nb
    I.sort()
    E.sort()
    Eexp=[]
    for i in I:
       Eexp.append(EI(i)) 
    title= '%7.1f [%7.1f, %7.1f]' %( Inc, I[lower],I[upper])
    pmagplotlib.plotEI(PLTS['ei'],Eexp,I,1)
    pmagplotlib.plotCDF(PLTS['cdf'],I,'Inclinations','r',title)
    pmagplotlib.plotVs(PLTS['cdf'],[I[lower],I[upper]],'b','--')
    pmagplotlib.plotVs(PLTS['cdf'],[Inc],'g','-')
    pmagplotlib.plotVs(PLTS['cdf'],[Io],'k','-')
    print "Io Inc  I_lower, I_upper, Elon, E_lower, E_upper"
    print '%7.1f %s %7.1f _ %7.1f ^ %7.1f:  %6.4f _ %6.4f ^ %6.4f' %(Io, " => ", Inc, I[lower],I[upper], Elong, E[lower],E[upper])
    try:
        raw_input("Return to save plots - <return> to quit:  ")
    except EOFError:
       print "\n Good bye\n"
       sys.exit()
    files={}
    files['eq']='findEI_eq.svg'
    files['ei']='findEI_ei.svg'
    files['cdf']='findEI_cdf.svg'
    files['v2']='findEI_v2.svg'
    pmagplotlib.saveP(PLTS,files)
Beispiel #11
0
def main():
    """
    NAME
       foldtest.py

    DESCRIPTION
       does a fold test (Tauxe, 2007) on data

    INPUT FORMAT
       dec inc dip_direction dip

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

    OPTIONS
        -h prints help message and quits
        -i for interactive parameter entry
        -f FILE
    
    OUTPUT
        Geographic: is an equal area projection of the input data in 
                    original coordinates
        Stratigraphic: is an equal area projection of the input data in 
                    tilt adjusted coordinates
        % Untilting: The dashed (red) curves are representative plots of 
                    maximum eigenvalue (tau_1) as a function of untilting
                    The solid line is the cumulative distribution of the
                    % Untilting required to maximize tau for all the 
                    bootstrapped data sets.  The dashed vertical lines
                    are 95% confidence bounds on the % untilting that yields 
                   the most clustered result (maximum tau_1).  
        Command line: prints out the bootstrapped iterations and
                   finally the confidence bounds on optimum untilting.
        If the 95% conf bounds include 0, then a pre-tilt magnetization is indicated
        If the 95% conf bounds include 100, then a post-tilt magnetization is indicated
        If the 95% conf bounds exclude both 0 and 100, syn-tilt magnetization is
                possible as is vertical axis rotation or other pathologies

    """
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    if '-i' in sys.argv: # ask for filename
        file=raw_input("Enter file name with dec, inc dip_direction and dip data: ")
        f=open(file,'rU')
        data=f.readlines()
    elif '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1] 
        f=open(file,'rU')
        data=f.readlines()
    else:
        print main.__doc__
        sys.exit()
#
# get to work
#
    PLTS={'geo':1,'strat':2,'taus':3,'ei':4} # make plot dictionary
    pmagplotlib.plot_init(PLTS['geo'],5,5)
    pmagplotlib.plot_init(PLTS['strat'],5,5)
    pmagplotlib.plot_init(PLTS['taus'],5,5)
    pmagplotlib.plot_init(PLTS['ei'],5,5)
    DIDDs= [] # set up list for dec inc  dip_direction, dip
    nb=100 # number of bootstraps
    for line in data:   # read in the data from standard input
        rec=line.split() # split each line on space to get records
        DIDDs.append([float(rec[0]),float(rec[1]),float(rec[2]),float(rec[3])])
    pmagplotlib.plotEQ(PLTS['geo'],DIDDs,'Geographic')
    TCs,Ps,Taus,Es,Is=[],[],[],[],[]
    for k in range(len(DIDDs)):
        drot,irot=pmag.dotilt(DIDDs[k][0],DIDDs[k][1],DIDDs[k][2],DIDDs[k][3])
        TCs.append([drot,irot,1.])
    pmagplotlib.plotEQ(PLTS['strat'],TCs,'Stratigraphic')
    Percs=range(-10,110)
    for perc in Percs:
        tilt=0.01*perc
        TCs=[]
        for k in range(len(DIDDs)):
            drot,irot=pmag.dotilt(DIDDs[k][0],DIDDs[k][1],DIDDs[k][2],tilt*DIDDs[k][3])
            TCs.append([drot,irot,1.])
        ppars=pmag.doprinc(TCs) # get principal directions
        Taus.append(ppars['tau1'])
        Es.append(ppars["tau2"]/ppars["tau3"])
        Is.append(ppars["inc"])
        if int(10*(EI(ppars["inc"])))==int(10*Es[-1]): 
            print EI(ppars["inc"]),Es[-1],perc
            Ps.append(perc)
    pylab.figure(num=PLTS['taus'])
    pylab.plot(Percs,Taus,'b-')
    pylab.figure(num=PLTS['ei'])
    pylab.plot(Es,Is,'b-')
    Is.sort()
    Eexp=[] 
    for i in Is: Eexp.append(EI(i))
    pylab.plot(Eexp,Is,'g-')
    Cdf,Untilt=[],[]
    print 'doing ',nb,' iterations...please be patient.....'
    for n in range(nb): # do bootstrap data sets - plot first 25 as dashed red line
        Es,Is=[],[]
        if n%50==0:print n
        Taus=[] # set up lists for taus
        PDs=pmag.pseudo(DIDDs)
        for perc in Percs:
            tilt=0.01*perc
            TCs=[]
            for k in range(len(PDs)):
                drot,irot=pmag.dotilt(PDs[k][0],PDs[k][1],PDs[k][2],tilt*PDs[k][3])
                TCs.append([drot,irot,1.])
            ppars=pmag.doprinc(TCs) # get principal directions
            Taus.append(ppars['tau1'])
            Es.append(ppars["tau2"]/ppars["tau3"])
            Is.append(ppars["inc"])
            if int(10*(EI(ppars["inc"])))==int(10*Es[-1]): 
                Ps.append(perc)
        if n<25:
            pylab.figure(num=PLTS['taus'])
            pylab.plot(Percs,Taus,'r--')
            pylab.figure(num=PLTS['ei'])
            pylab.plot(Es,Is,'r--')
        Untilt.append(Percs[Taus.index(pylab.max(Taus))]) # tilt that gives maximum tau
        Cdf.append(float(n)/float(nb))
    pylab.figure(num=PLTS['taus'])
    pylab.plot(Percs,Taus,'k')
    pylab.xlabel('% Untilting')
    pylab.ylabel('tau_1 (red), CDF (green)')
    Untilt.sort() # now for CDF of tilt of maximum tau
    Ps.sort()
    pylab.plot(Untilt,Cdf,'g')
    lower=int(.025*nb)     
    upper=int(.975*nb)
    pylab.axvline(x=Untilt[lower],ymin=0,ymax=1,linewidth=1,linestyle='--')
    pylab.axvline(x=Untilt[upper],ymin=0,ymax=1,linewidth=1,linestyle='--')
    tit= '%i - %i %s'%(Untilt[lower],Untilt[upper],'Percent Unfolding')
    pylab.title(tit)
    print Ps[lower],Ps[upper]
    pmagplotlib.drawFIGS(PLTS)
    try:
        raw_input('Return to save all figures, cntl-d to quit\n')
    except EOFError:
        print "Good bye"
        sys.exit()
    files={}
    for key in PLTS.keys():
        files[key]=('fold_'+'%s'%(key.strip()[:2])+'.svg')
    pmagplotlib.saveP(PLTS,files)
Beispiel #12
0
def main():
    """
    NAME
       foldtest_magic.py

    DESCRIPTION
       does a fold test (Tauxe, 2007) on data

    INPUT FORMAT
       pmag_specimens format file, er_samples.txt format file (for bedding)

    SYNTAX
       foldtest_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f pmag_sites  formatted file [default is pmag_sites.txt]
        -fsa er_samples  formatted file [default is er_samples.txt]
        -exc use pmag_criteria.txt to set acceptance criteria
        -n NB, set number of bootstraps, default is 500
        -b MIN, MAX, set bounds for untilting, default is -10, 150
    
    OUTPUT
        Geographic: is an equal area projection of the input data in 
                    original coordinates
        Stratigraphic: is an equal area projection of the input data in 
                    tilt adjusted coordinates
        % Untilting: The dashed (red) curves are representative plots of 
                    maximum eigenvalue (tau_1) as a function of untilting
                    The solid line is the cumulative distribution of the
                    % Untilting required to maximize tau for all the 
                    bootstrapped data sets.  The dashed vertical lines
                    are 95% confidence bounds on the % untilting that yields 
                   the most clustered result (maximum tau_1).  
        Command line: prints out the bootstrapped iterations and
                   finally the confidence bounds on optimum untilting.
        If the 95% conf bounds include 0, then a pre-tilt magnetization is indicated
        If the 95% conf bounds include 100, then a post-tilt magnetization is indicated
        If the 95% conf bounds exclude both 0 and 100, syn-tilt magnetization is
                possible as is vertical axis rotation or other pathologies

    """
    kappa=0
    nb=500 # number of bootstraps
    min,max=-10,150
    dir_path='.'
    infile,orfile='pmag_sites.txt','er_samples.txt'
    critfile='pmag_criteria.txt'
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        nb=int(sys.argv[ind+1])
    if '-b' in sys.argv:
        ind=sys.argv.index('-b')
        min=int(sys.argv[ind+1])
        max=int(sys.argv[ind+2])
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        infile=sys.argv[ind+1] 
    if '-fsa' in sys.argv:
        ind=sys.argv.index('-fsa')
        orfile=sys.argv[ind+1] 
    orfile=dir_path+'/'+orfile
    infile=dir_path+'/'+infile
    critfile=dir_path+'/'+critfile
    data,file_type=pmag.magic_read(infile)
    ordata,file_type=pmag.magic_read(orfile)
    if '-exc' in sys.argv:
        crits,file_type=pmag.magic_read(critfile)
        for crit in crits:
             if crit['pmag_criteria_code']=="DE-SITE":
                 SiteCrit=crit
                 break
# get to work
#
    PLTS={'geo':1,'strat':2,'taus':3} # make plot dictionary
    pmagplotlib.plot_init(PLTS['geo'],5,5)
    pmagplotlib.plot_init(PLTS['strat'],5,5)
    pmagplotlib.plot_init(PLTS['taus'],5,5)
    DIDDs= [] # set up list for dec inc  dip_direction, dip
    for rec in data:   # read in the data from standard input
        if eval(rec['site_tilt_correction'])==0:
            dip,dip_dir=0,-1
            Dec=float(rec['site_dec'])
            Inc=float(rec['site_inc'])
            for orec in ordata:
                if orec['er_site_name']==rec['er_site_name']:
                    if orec['sample_bed_dip_direction']!="":dip_dir=float(orec['sample_bed_dip_direction'])
                    if orec['sample_bed_dip']!="":dip=float(orec['sample_bed_dip'])
                    break
            if dip!=0 and dip_dir!=-1:
                if  '-exc' in  sys.argv:
                    keep=1
                    for key in SiteCrit.keys():
                        if 'site' in key  and SiteCrit[key]!="" and rec[key]!="" and key!='site_alpha95':
                            if float(rec[key])<float(SiteCrit[key]): 
                                keep=0
                                print rec['er_site_name'],key,rec[key]
                        if key=='site_alpha95'  and SiteCrit[key]!="" and rec[key]!="":
                            if float(rec[key])>float(SiteCrit[key]): 
                                keep=0
                    if keep==1:  DIDDs.append([Dec,Inc,dip_dir,dip])
                else:
                                DIDDs.append([Dec,Inc,dip_dir,dip])

    pmagplotlib.plotEQ(PLTS['geo'],DIDDs,'Geographic')
    TCs=[]
    for k in range(len(DIDDs)):
        drot,irot=pmag.dotilt(DIDDs[k][0],DIDDs[k][1],DIDDs[k][2],DIDDs[k][3])
        TCs.append([drot,irot,1.])
    pmagplotlib.plotEQ(PLTS['strat'],TCs,'Stratigraphic')
    Percs=range(min,max)
    Cdf,Untilt=[],[]
    pylab.figure(num=PLTS['taus'])
    print 'doing ',nb,' iterations...please be patient.....'
    for n in range(nb): # do bootstrap data sets - plot first 25 as dashed red line
        if n%50==0:print n
        Taus=[] # set up lists for taus
        PDs=pmag.pseudo(DIDDs)
        for perc in Percs:
            tilt=0.01*perc
            TCs=[]
            for k in range(len(PDs)):
                drot,irot=pmag.dotilt(PDs[k][0],PDs[k][1],PDs[k][2],tilt*PDs[k][3])
                TCs.append([drot,irot,1.])
            ppars=pmag.doprinc(TCs) # get principal directions
            Taus.append(ppars['tau1'])
        if n<25:pylab.plot(Percs,Taus,'r--')
        Untilt.append(Percs[Taus.index(numpy.max(Taus))]) # tilt that gives maximum tau
        Cdf.append(float(n)/float(nb))
    pylab.plot(Percs,Taus,'k')
    pylab.xlabel('% Untilting')
    pylab.ylabel('tau_1 (red), CDF (green)')
    Untilt.sort() # now for CDF of tilt of maximum tau
    pylab.plot(Untilt,Cdf,'g')
    lower=int(.025*nb)     
    upper=int(.975*nb)
    pylab.axvline(x=Untilt[lower],ymin=0,ymax=1,linewidth=1,linestyle='--')
    pylab.axvline(x=Untilt[upper],ymin=0,ymax=1,linewidth=1,linestyle='--')
    tit= '%i - %i %s'%(Untilt[lower],Untilt[upper],'Percent Unfolding')
    print tit
    pylab.title(tit)
    try:
        raw_input('Return to save all figures, cntl-d to quit\n')
    except EOFError:
        print "Good bye"
        sys.exit()
    files={}
    for key in PLTS.keys():
        files[key]=('fold_'+'%s'%(key.strip()[:2])+'.svg')
    pmagplotlib.saveP(PLTS,files)
Beispiel #13
0
def main():
    """
    NAME
       foldtest.py

    DESCRIPTION
       does a fold test (Tauxe, 2008) on data

    INPUT FORMAT
       dec inc dip_direction dip

    SYNTAX
       foldtest.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE
        -u ANGLE (circular standard deviation) for uncertainty on bedding poles
        -b MIN MAX bounds for quick search of percent untilting [default is -10 to 150%]
        -n NB  number of bootstrap samples [default is 1000]
    
    OUTPUT
        Geographic: is an equal area projection of the input data in 
                    original coordinates
        Stratigraphic: is an equal area projection of the input data in 
                    tilt adjusted coordinates
        % Untilting: The dashed (red) curves are representative plots of 
                    maximum eigenvalue (tau_1) as a function of untilting
                    The solid line is the cumulative distribution of the
                    % Untilting required to maximize tau for all the 
                    bootstrapped data sets.  The dashed vertical lines
                    are 95% confidence bounds on the % untilting that yields 
                   the most clustered result (maximum tau_1).  
        Command line: prints out the bootstrapped iterations and
                   finally the confidence bounds on optimum untilting.
        If the 95% conf bounds include 0, then a pre-tilt magnetization is indicated
        If the 95% conf bounds include 100, then a post-tilt magnetization is indicated
        If the 95% conf bounds exclude both 0 and 100, syn-tilt magnetization is
                possible as is vertical axis rotation or other pathologies

    """
    kappa=0
    nb=1000 # number of bootstraps
    min,max=-10,150
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1] 
        f=open(file,'rU')
        data=f.readlines()
    else:
        print main.__doc__
        sys.exit()
    if '-b' in sys.argv:
        ind=sys.argv.index('-b')
        min=float(sys.argv[ind+1])
        max=float(sys.argv[ind+2])
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        nb=int(sys.argv[ind+1])
    if '-u' in sys.argv:
        ind=sys.argv.index('-u')
        csd=float(sys.argv[ind+1])
        kappa=(81./csd)**2
#
# get to work
#
    PLTS={'geo':1,'strat':2,'taus':3} # make plot dictionary
    pmagplotlib.plot_init(PLTS['geo'],5,5)
    pmagplotlib.plot_init(PLTS['strat'],5,5)
    pmagplotlib.plot_init(PLTS['taus'],5,5)
    DIDDs= [] # set up list for dec inc  dip_direction, dip
    for line in data:   # read in the data from standard input
        rec=line.split() # split each line on space to get records
        DIDDs.append([float(rec[0]),float(rec[1]),float(rec[2]),float(rec[3])])
    pmagplotlib.plotEQ(PLTS['geo'],DIDDs,'Geographic')
    TCs=[]
    for k in range(len(DIDDs)):
        drot,irot=pmag.dotilt(DIDDs[k][0],DIDDs[k][1],DIDDs[k][2],DIDDs[k][3])
        TCs.append([drot,irot,1.])
    pmagplotlib.plotEQ(PLTS['strat'],TCs,'Stratigraphic')
    Percs=range(min,max)
    Cdf,Untilt=[],[]
    pylab.figure(num=PLTS['taus'])
    print 'doing ',nb,' iterations...please be patient.....'
    for n in range(nb): # do bootstrap data sets - plot first 25 as dashed red line
        if n%50==0:print n
        Taus=[] # set up lists for taus
        PDs=pmag.pseudo(DIDDs)
        if kappa!=0:
            for k in range(len(PDs)):
                d,i=pmag.fshdev(kappa)
                dipdir,dip=pmag.dodirot(d,i,PDs[k][2],PDs[k][3])
                PDs[k][2]=dipdir            
                PDs[k][3]=dip
        for perc in Percs:
            tilt=0.01*perc
            TCs=[]
            for k in range(len(PDs)):
                drot,irot=pmag.dotilt(PDs[k][0],PDs[k][1],PDs[k][2],tilt*PDs[k][3])
                TCs.append([drot,irot,1.])
            ppars=pmag.doprinc(TCs) # get principal directions
            Taus.append(ppars['tau1'])
        if n<25:pylab.plot(Percs,Taus,'r--')
        Untilt.append(Percs[Taus.index(numpy.max(Taus))]) # tilt that gives maximum tau
        Cdf.append(float(n)/float(nb))
    pylab.plot(Percs,Taus,'k')
    pylab.xlabel('% Untilting')
    pylab.ylabel('tau_1 (red), CDF (green)')
    Untilt.sort() # now for CDF of tilt of maximum tau
    pylab.plot(Untilt,Cdf,'g')
    lower=int(.025*nb)     
    upper=int(.975*nb)
    pylab.axvline(x=Untilt[lower],ymin=0,ymax=1,linewidth=1,linestyle='--')
    pylab.axvline(x=Untilt[upper],ymin=0,ymax=1,linewidth=1,linestyle='--')
    tit= '%i - %i %s'%(Untilt[lower],Untilt[upper],'Percent Unfolding')
    print tit
    print 'range of all bootstrap samples: ', Untilt[0], ' - ', Untilt[-1]
    pylab.title(tit)
    try:
        raw_input('Return to save all figures, cntl-d to quit\n')
    except:
        print "Good bye"
        sys.exit()
    files={}
    for key in PLTS.keys():
        files[key]=('fold_'+'%s'%(key.strip()[:2])+'.svg')
    pmagplotlib.saveP(PLTS,files)
Beispiel #14
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()
    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.plotEQsym(FIG['eq'], DIblock, title, sym)
        if plot == 0: pmagplotlib.drawFIGS(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 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 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 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 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 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 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 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.plotEQsym(FIG['bdirs'], BnDIs,
                                          'Bootstrapped Eigenvectors', vsym)
                if len(rDIs) > 5:
                    BrDIs = pmag.di_boot(rDIs)
                    if len(nDIs) > 5:  # plot on existing plots
                        pmagplotlib.plotDIsym(FIG['bdirs'], BrDIs, vsym)
                    else:
                        pmagplotlib.plotEQ(FIG['bdirs'], BrDIs,
                                           'Bootstrapped Eigenvectors', vsym)
        if dist == 'B':
            if len(nDIs) > 3 or len(rDIs) > 3:
                pmagplotlib.plotCONF(FIG['eq'], etitle, [], npars, 0)
        elif len(nDIs) > 3 and dist != 'BV':
            pmagplotlib.plotCONF(FIG['eq'], etitle, [], npars, 0)
            if len(rDIs) > 3:
                pmagplotlib.plotCONF(FIG['eq'], etitle, [], rpars, 0)
        elif len(rDIs) > 3 and dist != 'BV':
            pmagplotlib.plotCONF(FIG['eq'], etitle, [], rpars, 0)
        if plot == 0: pmagplotlib.drawFIGS(FIG)
    if plot == 0: pmagplotlib.drawFIGS(FIG)
    #
    files = {}
    for key in FIG.keys():
        files[key] = title + '_' + key + '.' + fmt
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['eq'] = 'Equal Area Plot'
        FIG = pmagplotlib.addBorders(FIG, titles, black, purple)
        pmagplotlib.saveP(FIG, files)
    elif plot == 0:
        ans = raw_input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans == "q": sys.exit()
        if ans == "a":
            pmagplotlib.saveP(FIG, files)
    else:
        pmagplotlib.saveP(FIG, files)