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

    DESCRIPTION
        generates set of Fisher distribed data from specified distribution 

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

    OPTIONS
        -h prints help message and quits
        -i for interactive  entry
        -k kappa specify kappa, default is 20
        -n N specify N, default is 100
        -D D specify mean Dec, default is 0
        -I I specify mean Inc, default is 90
        where:
            kappa:  fisher distribution concentration parameter
            N:  number of directions desired
    OUTPUT
        dec,  inc   


    """
    N,kappa,D,I=100,20.,0.,90.
    if len(sys.argv)!=0 and  '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    elif '-i' in sys.argv:
        ans=raw_input('    Kappa: ')
        kappa=float(ans)
        ans=raw_input('    N: ')
        N=int(ans)
        ans=raw_input('    Mean Dec: ')
        D=float(ans)
        ans=raw_input('    Mean Inc: ')
        I=float(ans)
    else:
        if '-k' in sys.argv:
            ind=sys.argv.index('-k')
            kappa=float(sys.argv[ind+1])
        if '-n' in sys.argv:
            ind=sys.argv.index('-n')
            N=int(sys.argv[ind+1])
        if '-D' in sys.argv:
            ind=sys.argv.index('-D')
            D=float(sys.argv[ind+1])
        if '-I' in sys.argv:
            ind=sys.argv.index('-I')
            I=float(sys.argv[ind+1])
    for k in range(N): 
        dec,inc= pmag.fshdev(kappa)  # send kappa to fshdev
        drot,irot=pmag.dodirot(dec,inc,D,I)   
        print '%7.1f %7.1f ' % (drot,irot)
Example #2
0
def get_fish(dir):
    """
    generate fisher distributed points according to the supplied parameters
    (includes dec,inc,n,k) in a pandas object.
    """
    tempD,tempI=[],[]
    for k in range(int(dir.n)):
        dec,inc=pmag.fshdev(dir.k)
        drot,irot=pmag.dodirot(dec,inc,dir.dec,dir.inc)
        tempD.append(drot)
        tempI.append(irot)
    return np.column_stack((tempD,tempI))
Example #3
0
def fishrot(kappa,N,D,I): #from Pmagpy
    """
    Description: generates set of Fisher distributed data from specified distribution 
	Input: kappa (fisher distribution concentration parameter), number of desired subsamples, Dec and Inc
	Output: list with N pairs of Dec, Inc.
    """
    out_d=[]
    out=[]

    for k in range(N): 
        dec,inc= pmag.fshdev(kappa)  # send kappa to fshdev
        drot,irot=pmag.dodirot(dec,inc,D,I)
        out_d=[drot,irot]
        out.append(out_d)
    return out
Example #4
0
def ifishrot(k=20,n=100,Dec=0,Inc=90):
    """
    Generates Fisher distributed unit vectors from a specified distribution 
    using the pmag.py fshdev and dodirot functions
    
    Parameters
    ----------
    k kappa precision parameter (default is 20) 
    n number of vectors to determine (default is 100)
    Dec mean declination of data set (default is 0)
    Inc mean inclination of data set (default is 90)
    """
    directions=[]
    for data in range(n):
        dec,inc=pmag.fshdev(k) 
        drot,irot=pmag.dodirot(dec,inc,Dec,Inc)
        directions.append([drot,irot,1.])
    return directions
Example #5
0
File: EI.py Project: jholmes/PmagPy
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) 
Example #6
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)
Example #7
0
def main():
    """
    NAME
       watsonsV.py

    DESCRIPTION
       calculates Watson's V statistic from input files

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files
   
    SYNTAX
       watsonsV.py [command line options]

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

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

    """
    Flip=0
    show,plot=1,0
    fmt='svg'
    file2=""
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    if '-ant' in  sys.argv: Flip=1
    if '-sav' in sys.argv: show,plot=0,1 # don't display, but do save plot
    if '-fmt' in sys.argv: 
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-P' in  sys.argv: show=0 # don't display or save plot
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file1=sys.argv[ind+1]
        data=numpy.loadtxt(file1).transpose()
        D1=numpy.array([data[0],data[1]]).transpose()
    else:
        print "-f is required"
        print main.__doc__
        sys.exit()
    if '-f2' in sys.argv:
        ind=sys.argv.index('-f2')
        file2=sys.argv[ind+1]
        data2=numpy.loadtxt(file2).transpose()
        D2=numpy.array([data2[0],data2[1]]).transpose()
        if Flip==1:
            D2,D=pmag.flip(D2) # D2 are now flipped
            if len(D2)!=0:
                if len(D)!=0: 
                    D2=numpy.concatenate(D,D2) # put all in D2
            elif len(D)!=0:
                D2=D
            else: 
                print 'length of second file is zero'
                sys.exit()
    elif Flip==1:D2,D1=pmag.flip(D1) # peel out antipodal directions, put in D2
#
    counter,NumSims=0,5000
#
# first calculate the fisher means and cartesian coordinates of each set of Directions
#
    pars_1=pmag.fisher_mean(D1)
    pars_2=pmag.fisher_mean(D2)
#
# get V statistic for these
#
    V=pmag.vfunc(pars_1,pars_2)
#
# do monte carlo simulation of datasets with same kappas, but common mean
# 
    Vp=[] # set of Vs from simulations
    if show==1:print "Doing ",NumSims," simulations"
    for k in range(NumSims):
        counter+=1
        if counter==50:
            if show==1:print k+1
            counter=0
        Dirp=[]
# get a set of N1 fisher distributed vectors with k1, calculate fisher stats
        for i in range(pars_1["n"]):
            Dirp.append(pmag.fshdev(pars_1["k"]))
        pars_p1=pmag.fisher_mean(Dirp)
# get a set of N2 fisher distributed vectors with k2, calculate fisher stats
        Dirp=[]
        for i in range(pars_2["n"]):
            Dirp.append(pmag.fshdev(pars_2["k"]))
        pars_p2=pmag.fisher_mean(Dirp)
# get the V for these
        Vk=pmag.vfunc(pars_p1,pars_p2)
        Vp.append(Vk)
#
# sort the Vs, get Vcrit (95th one)
#
    Vp.sort()
    k=int(.95*NumSims)
    if show==1:
        print "Watson's V,  Vcrit: " 
        print '   %10.1f %10.1f'%(V,Vp[k])
    if show==1 or plot==1:
        CDF={'cdf':1}
        pmagplotlib.plot_init(CDF['cdf'],5,5)
        pmagplotlib.plotCDF(CDF['cdf'],Vp,"Watson's V",'r',"")
        pmagplotlib.plotVs(CDF['cdf'],[V],'g','-')
        pmagplotlib.plotVs(CDF['cdf'],[Vp[k]],'b','--')
        if plot==0:pmagplotlib.drawFIGS(CDF)
        files={}
        if file2!="":
            files['cdf']='WatsonsV_'+file1+'_'+file2+'.'+fmt
        else:
            files['cdf']='WatsonsV_'+file1+'.'+fmt
        if pmagplotlib.isServer:
            black     = '#000000'
            purple    = '#800080'
            titles={}
            titles['cdf']='Cumulative Distribution'
            CDF = pmagplotlib.addBorders(CDF,titles,black,purple)
            pmagplotlib.saveP(CDF,files)
        elif plot==0:
            ans=raw_input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans=="a": pmagplotlib.saveP(CDF,files) 
        if plot==1: # save and quit silently
            pmagplotlib.saveP(CDF,files)
def watson_common_mean(Data1,Data2,NumSims=5000,plot='no'):
    """
    Conduct a Watson V test for a common mean on two declination, inclination data sets
    
    This function calculates Watson's V statistic from input files through Monte Carlo
    simulation in order to test whether two populations of directional data could have
    been drawn from a common mean. The critical angle between the two sample mean
    directions and the corresponding McFadden and McElhinny (1990) classification is printed.


    Required Arguments
    ----------
    Data1 : a list of directional data [dec,inc]
    Data2 : a list of directional data [dec,inc]
    
    Optional Arguments
    ----------
    NumSims : number of Monte Carlo simulations (default is 5000)
    plot : the default is no plot ('no'). Putting 'yes' will the plot the CDF from
    the Monte Carlo simulations.
    """   
    pars_1=pmag.fisher_mean(Data1)
    pars_2=pmag.fisher_mean(Data2)

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

    # sort the Vs, get Vcrit (95th percentile one)

    Vp.sort()
    k=int(.95*NumSims)
    Vcrit=Vp[k]

    # equation 18 of McFadden and McElhinny, 1990 calculates the critical
    # value of R (Rwc)

    Rwc=Sr-(Vcrit/2)

    # following equation 19 of McFadden and McElhinny (1990) the critical
    # angle is calculated. If the observed angle (also calculated below)
    # between the data set means exceeds the critical angle the hypothesis 
    # of a common mean direction may be rejected at the 95% confidence
    # level. The critical angle is simply a different way to present 
    # Watson's V parameter so it makes sense to use the Watson V parameter
    # in comparison with the critical value of V for considering the test
    # results. What calculating the critical angle allows for is the 
    # classification of McFadden and McElhinny (1990) to be made
    # for data sets that are consistent with sharing a common mean.

    k1=pars_1['k']
    k2=pars_2['k']
    R1=pars_1['r']
    R2=pars_2['r']
    critical_angle=np.degrees(np.arccos(((Rwc**2)-((k1*R1)**2)
                                               -((k2*R2)**2))/
                                              (2*k1*R1*k2*R2)))
    D1=(pars_1['dec'],pars_1['inc'])
    D2=(pars_2['dec'],pars_2['inc'])
    angle=pmag.angle(D1,D2)

    print "Results of Watson V test: "
    print "" 
    print "Watson's V:           " '%.1f' %(V)
    print "Critical value of V:  " '%.1f' %(Vcrit)

    if V<Vcrit:
        print '"Pass": Since V is less than Vcrit, the null hypothesis'
        print 'that the two populations are drawn from distributions'
        print 'that share a common mean direction can not be rejected.'
    elif V>Vcrit:
        print '"Fail": Since V is greater than Vcrit, the two means can'
        print 'be distinguished at the 95% confidence level.'
    print ""    
    print "M&M1990 classification:"
    print "" 
    print "Angle between data set means: " '%.1f'%(angle)
    print "Critical angle for M&M1990:   " '%.1f'%(critical_angle)
    
    if V>Vcrit:
        print ""
    elif V<Vcrit:
        if critical_angle<5:
            print "The McFadden and McElhinny (1990) classification for"
            print "this test is: 'A'"
        elif critical_angle<10:
            print "The McFadden and McElhinny (1990) classification for"
            print "this test is: 'B'"
        elif critical_angle<20:
            print "The McFadden and McElhinny (1990) classification for"
            print "this test is: 'C'"
        else:
            print "The McFadden and McElhinny (1990) classification for"
            print "this test is: 'INDETERMINATE;"

    if plot=='yes':
        CDF={'cdf':1}
        #pmagplotlib.plot_init(CDF['cdf'],5,5)
        p1 = pmagplotlib.plotCDF(CDF['cdf'],Vp,"Watson's V",'r',"")
        p2 = pmagplotlib.plotVs(CDF['cdf'],[V],'g','-')
        p3 = pmagplotlib.plotVs(CDF['cdf'],[Vp[k]],'b','--')
        pmagplotlib.drawFIGS(CDF)
Example #9
0
def main():
    """
    NAME
       revtest_MM1990.py

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

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files (one file for normal directions, one file for reversed directions).
   
    SYNTAX
       revtest_MM1990.py [command line options]

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

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

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

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

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

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

    if V > Vcrit:
        print ""
    elif V < Vcrit:
        if critical_angle < 5:
            print "The McFadden and McElhinny (1990) classification for this test is: 'A'"
        elif critical_angle < 10:
            print "The McFadden and McElhinny (1990) classification for this test is: 'B'"
        elif critical_angle < 20:
            print "The McFadden and McElhinny (1990) classification for this test is: 'C'"
        else:
            print "The McFadden and McElhinny (1990) classification for this test is: 'INDETERMINATE;"
    if plot == 1:
        CDF = {"cdf": 1}
        pmagplotlib.plot_init(CDF["cdf"], 5, 5)
        p1 = pmagplotlib.plotCDF(CDF["cdf"], Vp, "Watson's V", "r", "")
        p2 = pmagplotlib.plotVs(CDF["cdf"], [V], "g", "-")
        p3 = pmagplotlib.plotVs(CDF["cdf"], [Vp[k]], "b", "--")
        pmagplotlib.drawFIGS(CDF)
        files, fmt = {}, "svg"
        if file2 != "":
            files["cdf"] = "WatsonsV_" + file1 + "_" + file2 + "." + fmt
        else:
            files["cdf"] = "WatsonsV_" + file1 + "." + fmt
        if pmagplotlib.isServer:
            black = "#000000"
            purple = "#800080"
            titles = {}
            titles["cdf"] = "Cumulative Distribution"
            CDF = pmagplotlib.addBorders(CDF, titles, black, purple)
            pmagplotlib.saveP(CDF, files)
        else:
            ans = raw_input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans == "a":
                pmagplotlib.saveP(CDF, files)
def watson_common_mean(Data1, Data2, NumSims=5000, plot='no'):
    """
    Conduct a Watson V test for a common mean on two declination, inclination data sets
    
    This function calculates Watson's V statistic from input files through Monte Carlo
    simulation in order to test whether two populations of directional data could have
    been drawn from a common mean. The critical angle between the two sample mean
    directions and the corresponding McFadden and McElhinny (1990) classification is printed.


    Required Arguments
    ----------
    Data1 : a list of directional data [dec,inc]
    Data2 : a list of directional data [dec,inc]
    
    Optional Arguments
    ----------
    NumSims : number of Monte Carlo simulations (default is 5000)
    plot : the default is no plot ('no'). Putting 'yes' will the plot the CDF from
    the Monte Carlo simulations.
    """
    pars_1 = pmag.fisher_mean(Data1)
    pars_2 = pmag.fisher_mean(Data2)

    cart_1 = pmag.dir2cart([pars_1["dec"], pars_1["inc"], pars_1["r"]])
    cart_2 = pmag.dir2cart([pars_2['dec'], pars_2['inc'], pars_2["r"]])
    Sw = pars_1['k'] * pars_1['r'] + pars_2['k'] * pars_2['r']  # k1*r1+k2*r2
    xhat_1 = pars_1['k'] * cart_1[0] + pars_2['k'] * cart_2[0]  # k1*x1+k2*x2
    xhat_2 = pars_1['k'] * cart_1[1] + pars_2['k'] * cart_2[1]  # k1*y1+k2*y2
    xhat_3 = pars_1['k'] * cart_1[2] + pars_2['k'] * cart_2[2]  # k1*z1+k2*z2
    Rw = np.sqrt(xhat_1**2 + xhat_2**2 + xhat_3**2)
    V = 2 * (Sw - Rw)
    # keep weighted sum for later when determining the "critical angle"
    # let's save it as Sr (notation of McFadden and McElhinny, 1990)
    Sr = Sw

    # do monte carlo simulation of datasets with same kappas as data,
    # but a common mean
    counter = 0
    Vp = []  # set of Vs from simulations
    for k in range(NumSims):

        # get a set of N1 fisher distributed vectors with k1,
        # calculate fisher stats
        Dirp = []
        for i in range(pars_1["n"]):
            Dirp.append(pmag.fshdev(pars_1["k"]))
        pars_p1 = pmag.fisher_mean(Dirp)
        # get a set of N2 fisher distributed vectors with k2,
        # calculate fisher stats
        Dirp = []
        for i in range(pars_2["n"]):
            Dirp.append(pmag.fshdev(pars_2["k"]))
        pars_p2 = pmag.fisher_mean(Dirp)
        # get the V for these
        Vk = pmag.vfunc(pars_p1, pars_p2)
        Vp.append(Vk)

    # sort the Vs, get Vcrit (95th percentile one)

    Vp.sort()
    k = int(.95 * NumSims)
    Vcrit = Vp[k]

    # equation 18 of McFadden and McElhinny, 1990 calculates the critical
    # value of R (Rwc)

    Rwc = Sr - (Vcrit / 2)

    # following equation 19 of McFadden and McElhinny (1990) the critical
    # angle is calculated. If the observed angle (also calculated below)
    # between the data set means exceeds the critical angle the hypothesis
    # of a common mean direction may be rejected at the 95% confidence
    # level. The critical angle is simply a different way to present
    # Watson's V parameter so it makes sense to use the Watson V parameter
    # in comparison with the critical value of V for considering the test
    # results. What calculating the critical angle allows for is the
    # classification of McFadden and McElhinny (1990) to be made
    # for data sets that are consistent with sharing a common mean.

    k1 = pars_1['k']
    k2 = pars_2['k']
    R1 = pars_1['r']
    R2 = pars_2['r']
    critical_angle = np.degrees(
        np.arccos(((Rwc**2) - ((k1 * R1)**2) - ((k2 * R2)**2)) /
                  (2 * k1 * R1 * k2 * R2)))
    D1 = (pars_1['dec'], pars_1['inc'])
    D2 = (pars_2['dec'], pars_2['inc'])
    angle = pmag.angle(D1, D2)

    print "Results of Watson V test: "
    print ""
    print "Watson's V:           " '%.1f' % (V)
    print "Critical value of V:  " '%.1f' % (Vcrit)

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

    if V > Vcrit:
        print ""
    elif V < Vcrit:
        if critical_angle < 5:
            print "The McFadden and McElhinny (1990) classification for"
            print "this test is: 'A'"
        elif critical_angle < 10:
            print "The McFadden and McElhinny (1990) classification for"
            print "this test is: 'B'"
        elif critical_angle < 20:
            print "The McFadden and McElhinny (1990) classification for"
            print "this test is: 'C'"
        else:
            print "The McFadden and McElhinny (1990) classification for"
            print "this test is: 'INDETERMINATE;"

    if plot == 'yes':
        CDF = {'cdf': 1}
        #pmagplotlib.plot_init(CDF['cdf'],5,5)
        p1 = pmagplotlib.plotCDF(CDF['cdf'], Vp, "Watson's V", 'r', "")
        p2 = pmagplotlib.plotVs(CDF['cdf'], [V], 'g', '-')
        p3 = pmagplotlib.plotVs(CDF['cdf'], [Vp[k]], 'b', '--')
        pmagplotlib.drawFIGS(CDF)
Example #11
0
def spitout(kappa):
    dec,inc= pmag.fshdev(kappa)  # send kappa to fshdev
    print '%7.1f %7.1f ' % (dec,inc)
    return 
Example #12
0
def main():
    """
    NAME
       watsonsV.py

    DESCRIPTION
       calculates Watson's V statistic from input files

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files
   
    SYNTAX
       watsonsV.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE (with optional second)
        -f2 FILE (second file) 
        -ant,  flip antipodal directions in FILE to opposite direction
        -P  (don't plot)

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

    """
    D1,D2=[],[]
    Flip=0
    plot=1
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    if '-ant' in  sys.argv: Flip=1
    if '-P' in  sys.argv: plot=0
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file1=sys.argv[ind+1]
    f=open(file1,'rU')
    for line in f.readlines():
        rec=line.split()
        Dec,Inc=float(rec[0]),float(rec[1]) 
        D1.append([Dec,Inc,1.])
    f.close()
    if '-f2' in sys.argv:
        ind=sys.argv.index('-f2')
        file2=sys.argv[ind+1]
        f=open(file2,'rU')
        for line in f.readlines():
            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
            Dec,Inc=float(rec[0]),float(rec[1]) 
            if Flip==0:
                D2.append([Dec,Inc,1.])
            else:
                D1.append([Dec,Inc,1.])
        f.close()
        if Flip==1:
            D1,D2=pmag.flip(D1)
#
    counter,NumSims=0,5000
#
# first calculate the fisher means and cartesian coordinates of each set of Directions
#
    pars_1=pmag.fisher_mean(D1)
    pars_2=pmag.fisher_mean(D2)
#
# get V statistic for these
#
    V=pmag.vfunc(pars_1,pars_2)
#
# do monte carlo simulation of datasets with same kappas, but common mean
# 
    Vp=[] # set of Vs from simulations
    if plot==1:print "Doing ",NumSims," simulations"
    for k in range(NumSims):
        counter+=1
        if counter==50:
            if plot==1:print k+1
            counter=0
        Dirp=[]
# get a set of N1 fisher distributed vectors with k1, calculate fisher stats
        for i in range(pars_1["n"]):
            Dirp.append(pmag.fshdev(pars_1["k"]))
        pars_p1=pmag.fisher_mean(Dirp)
# get a set of N2 fisher distributed vectors with k2, calculate fisher stats
        Dirp=[]
        for i in range(pars_2["n"]):
            Dirp.append(pmag.fshdev(pars_2["k"]))
        pars_p2=pmag.fisher_mean(Dirp)
# get the V for these
        Vk=pmag.vfunc(pars_p1,pars_p2)
        Vp.append(Vk)
#
# sort the Vs, get Vcrit (95th one)
#
    Vp.sort()
    k=int(.95*NumSims)
    print "Watson's V,  Vcrit: " 
    print '   %10.1f %10.1f'%(V,Vp[k])
    if plot==1:
        CDF={'cdf':1}
        pmagplotlib.plot_init(CDF['cdf'],5,5)
        pmagplotlib.plotCDF(CDF['cdf'],Vp,"Watson's V",'r',"")
        pmagplotlib.plotVs(CDF['cdf'],[V],'g','-')
        pmagplotlib.plotVs(CDF['cdf'],[Vp[k]],'b','--')
        pmagplotlib.drawFIGS(CDF)
        files,fmt={},'svg'
        if file2!="":
            files['cdf']='WatsonsV_'+file1+'_'+file2+'.'+fmt
        else:
            files['cdf']='WatsonsV_'+file1+'.'+fmt
        if pmagplotlib.isServer:
            black     = '#000000'
            purple    = '#800080'
            titles={}
            titles['cdf']='Cumulative Distribution'
            CDF = pmagplotlib.addBorders(CDF,titles,black,purple)
            pmagplotlib.saveP(CDF,files)
        else:
            ans=raw_input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans=="a": pmagplotlib.saveP(CDF,files) 
Example #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)
Example #14
0
def main():
    """
    NAME
       foldtest_magic.py

    DESCRIPTION
       does a fold test (Tauxe, 2010) 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 1000
        -b MIN, MAX, set bounds for untilting, default is -10, 150
        -fmt FMT, specify format - default is svg
    
    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
    dir_path='.'
    infile,orfile='pmag_sites.txt','er_samples.txt'
    critfile='pmag_criteria.txt'
    fmt='svg'
    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 '-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=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)
    GEOrecs=pmag.get_dictitem(data,'site_tilt_correction','0','T')
    if len(GEOrecs)>0: # have some geographic data
        DIDDs= [] # set up list for dec inc  dip_direction, dip
        for rec in GEOrecs:   # parse data
            dip,dip_dir=0,-1
            Dec=float(rec['site_dec'])
            Inc=float(rec['site_inc'])
            orecs=pmag.get_dictitem(ordata,'er_site_name',rec['er_site_name'],'T')
            if len(orecs)>0:
                    if orecs[0]['sample_bed_dip_direction']!="":dip_dir=float(orecs[0]['sample_bed_dip_direction'])
                    if orecs[0]['sample_bed_dip']!="":dip=float(orecs[0]['sample_bed_dip'])
            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])
    else:
        print 'no geographic directional data found'
        sys.exit()
    pmagplotlib.plotEQ(PLTS['geo'],DIDDs,'Geographic')
    data=numpy.array(DIDDs)
    D,I=pmag.dotilt_V(data)
    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
    pylab.title(tit)
    pmagplotlib.drawFIGS(PLTS)
    ans= raw_input('S[a]ve all figures, <Return> to quit  \n ')
    if ans!='a':
        print "Good bye"
        sys.exit()
    files={}
    for key in PLTS.keys():
        files[key]=('foldtest_'+'%s'%(key.strip()[:2])+'.'+fmt)
    pmagplotlib.saveP(PLTS,files)
Example #15
0
#!/usr/bin/env python
import pmag, matplotlib, math
matplotlib.use("TkAgg")
import pylab
k = 29.2
Dels, A95s, CSDs, Ns = [], [], [], range(4, 31)
DIs = []
for i in range(31):
    dec, inc = pmag.fshdev(k)
    DIs.append([dec, inc])
pars = pmag.fisher_mean(DIs)
pDIs = []
for i in range(3):
    pDIs.append(DIs[i])
for n in Ns:
    pDIs.append(DIs[n])
    fpars = pmag.fisher_mean(pDIs)
    A95s.append(fpars['alpha95'])
    CSDs.append(fpars['csd'])
    Dels.append((180. / math.pi) * math.acos(fpars['r'] / float(n)))
pylab.plot(Ns, A95s, 'ro')
pylab.plot(Ns, A95s, 'r-')
pylab.plot(Ns, CSDs, 'bs')
pylab.plot(Ns, CSDs, 'b-')
pylab.plot(Ns, Dels, 'g^')
pylab.plot(Ns, Dels, 'g-')
pylab.axhline(pars['csd'], color='k')
pylab.show()
raw_input()
Example #16
0
def common_dir_MM90(dir1,dir2,NumSims=5000,plot='no'):
    dir1['r']=get_R(dir1)
    dir2['r']=get_R(dir2)
    #largely based on iWatsonV routine of Swanson-Hyell in IPMag    
    cart_1=pmag.dir2cart([dir1["dec"],dir1["inc"],dir1["r"]])
    cart_2=pmag.dir2cart([dir2['dec'],dir2['inc'],dir2["r"]])
    Sw=dir1['k']*dir1['r']+dir2['k']*dir2['r'] # k1*r1+k2*r2
    xhat_1=dir1['k']*cart_1[0]+dir2['k']*cart_2[0] # k1*x1+k2*x2
    xhat_2=dir1['k']*cart_1[1]+dir2['k']*cart_2[1] # k1*y1+k2*y2
    xhat_3=dir1['k']*cart_1[2]+dir2['k']*cart_2[2] # k1*z1+k2*z2
    Rw=np.sqrt(xhat_1**2+xhat_2**2+xhat_3**2)
    V=2*(Sw-Rw)
    # keep weighted sum for later when determining the "critical angle" 
    # let's save it as Sr (notation of McFadden and McElhinny, 1990)
    Sr=Sw 
    
    # do monte carlo simulation of datasets with same kappas as data, 
    # but a common mean
    counter=0
    Vp=[] # set of Vs from simulations
    for k in range(NumSims): 
       
    # get a set of N1 fisher distributed vectors with k1,
    # calculate fisher stats
        Dirp=[]
        for i in range(int(dir1["n"])):
            Dirp.append(pmag.fshdev(dir1["k"]))
        pars_p1=pmag.fisher_mean(Dirp)
    # get a set of N2 fisher distributed vectors with k2, 
    # calculate fisher stats
        Dirp=[]
        for i in range(int(dir2["n"])):
            Dirp.append(pmag.fshdev(dir2["k"]))
        pars_p2=pmag.fisher_mean(Dirp)
    # get the V for these
        Vk=pmag.vfunc(pars_p1,pars_p2)
        Vp.append(Vk)

    # sort the Vs, get Vcrit (95th percentile one)

    Vp.sort()
    k=int(.95*NumSims)
    Vcrit=Vp[k]

    # equation 18 of McFadden and McElhinny, 1990 calculates the critical
    # value of R (Rwc)

    Rwc=Sr-(Vcrit/2)

    # following equation 19 of McFadden and McElhinny (1990) the critical
    # angle is calculated. If the observed angle (also calculated below)
    # between the data set means exceeds the critical angle the hypothesis 
    # of a common mean direction may be rejected at the 95% confidence
    # level. The critical angle is simply a different way to present 
    # Watson's V parameter so it makes sense to use the Watson V parameter
    # in comparison with the critical value of V for considering the test
    # results. What calculating the critical angle allows for is the 
    # classification of McFadden and McElhinny (1990) to be made
    # for data sets that are consistent with sharing a common mean.

    k1=dir1['k']
    k2=dir2['k']
    R1=dir1['r']
    R2=dir2['r']
    critical_angle=np.degrees(np.arccos(((Rwc**2)-((k1*R1)**2)
                                               -((k2*R2)**2))/
                                              (2*k1*R1*k2*R2)))
    D1=(dir1['dec'],dir1['inc'])
    D2=(dir2['dec'],dir2['inc'])
    angle=pmag.angle(D1,D2)

    if V<Vcrit: 
        outcome='Pass'
        if critical_angle<5: MM90class='A'
        elif critical_angle<10: MM90class='B'
        elif critical_angle<20: MM90class='C'
        else: MM90class='INDETERMINATE'
    else:
        outcome='Fail'
        MM90class='FAIL'
        
    result=pd.Series([outcome,V,Vcrit,angle[0],critical_angle,MM90class], index=['Outcome','VWatson','Vcrit','angle','critangle','MM90class'])

    if plot=='yes':
        CDF={'cdf':1}
        #pmagplotlib.plot_init(CDF['cdf'],5,5)
        p1 = pmagplotlib.plotCDF(CDF['cdf'],Vp,"Watson's V",'r',"")
        p2 = pmagplotlib.plotVs(CDF['cdf'],[V],'g','-')
        p3 = pmagplotlib.plotVs(CDF['cdf'],[Vp[k]],'b','--')
        pmagplotlib.drawFIGS(CDF)
    
    return result