Example #1
0
def spitout(line):
    dir=[]  # initialize list for  dec,inc,intensity
    dat=line.split() # split the data on a space into columns
    for element in dat: # step through dec,inc, int
        dir.append(float(element)) # append floating point variable to "dir"
    if len(dir)==2:dir.append(1.)
    cart= pmag.dir2cart(dir)  # send dir to dir2cart and spit out result
    print '%8.4e %8.4e %8.4e'%(cart[0],cart[1],cart[2])
    return cart
Example #2
0
def Rotate_zijderveld(Zdata, rot_declination):
    if len(Zdata) == 0:
        return ([])
    CART_rot = []
    for i in range(0, len(Zdata)):
        DIR = cart2dir(Zdata[i])
        DIR[0] = (DIR[0] - rot_declination) % 360.
        CART_rot.append(array(dir2cart(DIR)))
    CART_rot = array(CART_rot)
    return (CART_rot)
def Rotate_zijderveld(Zdata,rot_declination):
    if len(Zdata)==0:
        return([])
    CART_rot=[]
    for i in range(0,len(Zdata)):
        DIR=cart2dir(Zdata[i])
        DIR[0]=(DIR[0]-rot_declination)%360.
        CART_rot.append(array(dir2cart(DIR)))
    CART_rot=array(CART_rot)
    return(CART_rot)
Example #4
0
def get_bounds(DIs):
    #2sigma bounds
    bounds=[]
    #  convert to cartesian coordinates
    cart=pmag.dir2cart(DIs).transpose()
    min=int(0.025*len(cart[0]))
    max=int(0.975*len(cart[0])) 
    for i in range(3):
        comp=cart[i]
        comp.sort() 
        bounds.append([comp[min],comp[max]])
    return bounds
Example #5
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)
Example #6
0
def main():
    """
    NAME
        lowrie.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX 
        lowrie -h [command line options]
    
    INPUT 
       takes SIO formatted input files
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file
        -N do not normalize by maximum magnetization
        -fmt [svg, pdf, eps, png] specify fmt, default is svg
    """
    fmt='svg'
    FIG={} # plot dictionary
    FIG['lowrie']=1 # demag is figure 1
    pmagplotlib.plot_init(FIG['lowrie'],6,6)
    norm=1 # default is to normalize by maximum axis
    if len(sys.argv)>1:
        if '-h' in sys.argv:
            print main.__doc__
            sys.exit()
        if '-N' in sys.argv: norm=0 # don't normalize
        if '-f' in sys.argv: # sets input filename
            ind=sys.argv.index("-f")
            in_file=sys.argv[ind+1]
        else:
            print main.__doc__
            print 'you must supply a file name'
            sys.exit() 
    else:
        print main.__doc__
        print 'you must supply a file name'
        sys.exit() 
    data=open(in_file).readlines() # open the SIO format file
    PmagRecs=[] # set up a list for the results
    keys=['specimen','treatment','csd','M','dec','inc']
    for line in data:
        PmagRec={}
        rec=line.replace('\n','').split()
        for k in range(len(keys)): 
            PmagRec[keys[k]]=rec[k]
        PmagRecs.append(PmagRec)
    specs=pmag.get_dictkey(PmagRecs,'specimen','')
    sids=[]
    for spec in specs:
        if spec not in sids:sids.append(spec) # get list of unique specimen names
    for spc in sids:  # step through the specimen names
        print spc
        specdata=pmag.get_dictitem(PmagRecs,'specimen',spc,'T') # get all this one's data
        DIMs,Temps=[],[]
        for dat in specdata: # step through the data
            DIMs.append([float(dat['dec']),float(dat['inc']),float(dat['M'])*1e-3])
            Temps.append(float(dat['treatment']))
        carts=pmag.dir2cart(DIMs).transpose()
        #if norm==1: # want to normalize
        #    nrm=max(max(abs(carts[0])),max(abs(carts[1])),max(abs(carts[2]))) # by maximum of x,y,z values
        #    ylab="M/M_max"
        if norm==1: # want to normalize
            nrm=(DIMs[0][2]) # normalize by NRM
            ylab="M/M_o"
        else: 
            nrm=1. # don't normalize
            ylab="Magnetic moment (Am^2)"
        xlab="Temperature (C)"
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[0])/nrm,sym='r-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[0])/nrm,sym='ro') # X direction
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[1])/nrm,sym='c-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[1])/nrm,sym='cs') # Y direction
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[2])/nrm,sym='k-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[2])/nrm,sym='k^',title=spc,xlab=xlab,ylab=ylab) # Z direction
        pmagplotlib.drawFIGS(FIG)
        ans=raw_input('S[a]ve figure? [q]uit, <return> to continue   ')
        if ans=='a':
            files={'lowrie':'lowrie:_'+spc+'_.'+fmt}
            pmagplotlib.saveP(FIG,files)
        elif ans=='q':
            sys.exit()
        pmagplotlib.clearFIG(FIG['lowrie'])
Example #7
0
#!/usr/bin/env python
import pmag
dat=open('princ.di','rU').readlines()
x,y,z=[],[],[]
Dirs=[]
for line in dat:
    rec=line.split()
    Dirs=[float(rec[0]),float(rec[1]),float(rec[2])*1e-4]
    cart=pmag.dir2cart(Dirs)
    x.append(cart[0])
    y.append(cart[1]*1.1)
    z.append(cart[2])
from enthought.mayavi.mlab import points3d,savefig,show,outline,plot3d
from numpy import array,sum,transpose
from numpy.linalg import eig
X,Y,Z=array(x),array(y),array(z)
points3d(X,Y,Z,color=(0,0,0),scale_factor=0.25,opacity=.5)
outline(color=(.7,0,0))
T=array([[sum(X*X),sum(X*Y),sum(X*Z)],
   [sum(Y*X),sum(Y*Y),sum(Y*Z)],
   [sum(Z*X),sum(Z*Y),sum(Z*Z)]])
vals,vects=eig(T)
pv=transpose(vects)[0]*3.
plot3d([pv[0],-pv[0]],[pv[1],-pv[1]],[pv[2],-pv[2]],tube_radius=0.1,color=(0,1,0))
show()

Example #8
0
def plotELL(pars, col, lower, plot):
    """
    function to calculate points on an ellipse about Pdec,Pdip with angle beta,gamma
    """
    rad = np.pi / 180.
    Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc = pars[0], pars[1], pars[
        2], pars[3], pars[4], pars[5], pars[6], pars[7]
    if beta > 90. or gamma > 90:
        beta = 180. - beta
        gamma = 180. - beta
        Pdec = Pdec - 180.
        Pinc = -Pinc
    beta, gamma = beta * rad, gamma * rad  # convert to radians
    X_ell, Y_ell, X_up, Y_up, PTS = [], [], [], [], []
    nums = 201
    xnum = float(nums - 1.) / 2.
    # set up t matrix
    t = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    X = pmag.dir2cart((Pdec, Pinc, 1.0))  # convert to cartesian coordintes
    if lower == 1 and X[2] < 0:
        for i in range(3):
            X[i] = -X[i]
# set up rotation matrix t
    t[0][2] = X[0]
    t[1][2] = X[1]
    t[2][2] = X[2]
    X = pmag.dir2cart((Bdec, Binc, 1.0))
    if lower == 1 and X[2] < 0:
        for i in range(3):
            X[i] = -X[i]
    t[0][0] = X[0]
    t[1][0] = X[1]
    t[2][0] = X[2]
    X = pmag.dir2cart((Gdec, Ginc, 1.0))
    if lower == 1 and X[2] < 0:
        for i in range(3):
            X[i] = -X[i]
    t[0][1] = X[0]
    t[1][1] = X[1]
    t[2][1] = X[2]
    # set up v matrix
    v = [0, 0, 0]
    for i in range(nums):  # incremental point along ellipse
        psi = float(i) * np.pi / xnum
        v[0] = np.sin(beta) * np.cos(psi)
        v[1] = np.sin(gamma) * np.sin(psi)
        v[2] = np.sqrt(1. - v[0]**2 - v[1]**2)
        elli = [0, 0, 0]
        # calculate points on the ellipse
        for j in range(3):
            for k in range(3):
                elli[j] = elli[j] + t[j][k] * v[
                    k]  # cartesian coordinate j of ellipse
        PTS.append(pmag.cart2dir(elli))
        R = np.sqrt(1. - abs(elli[2])) / (np.sqrt(elli[0]**2 + elli[1]**2)
                                          )  # put on an equal area projection
        if elli[2] < 0:
            #            for i in range(3): elli[i]=-elli[i]
            X_up.append(elli[1] * R)
            Y_up.append(elli[0] * R)
            # Adding None values stops plotting of an additional straight line
            # between the points where the ellipse crosses the edge of the stereonet
            X_ell.append(None)
            Y_ell.append(None)
        else:
            X_ell.append(elli[1] * R)
            Y_ell.append(elli[0] * R)
    if plot == 1:
        if X_ell != []:
            plt.plot(X_ell, Y_ell, color=col, linewidth=2, zorder=6)
        if X_up != []:
            plt.plot(X_up, Y_up, color=col, linewidth=2, linestyle=':')
    else:
        return PTS
Example #9
0
def plotELL(pars,col,lower,plot): #Modified from PmagPy (Tauxe et al., 2016)
    """
    function to calculate points on an ellipse about Pdec,Pdip with angle beta,gamma
    """
    #pylab.figure(num=fignum)
    Pdec,Pinc,beta,Bdec,Binc,gamma,Gdec,Ginc=pars[0],pars[1],pars[2],pars[3],pars[4],pars[5],pars[6],pars[7]
    if beta > 90. or gamma>90:
        beta=180.-beta
        gamma=180.-beta
        Pdec=Pdec-180.
        Pinc=-Pinc
    beta,gamma=beta*rad,gamma*rad # convert to radians
    X_ell,Y_ell,X_up,Y_up,PTS=[],[],[],[],[]
    nums=201
    xnum=float(nums-1.)/2.
# set up t matrix
    t=[[0,0,0],[0,0,0],[0,0,0]]
    X=pmag.dir2cart((Pdec,Pinc,1.0)) # convert to cartesian coordintes
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
# set up rotation matrix t
    t[0][2]=X[0]
    t[1][2]=X[1]
    t[2][2]=X[2]
    X=pmag.dir2cart((Bdec,Binc,1.0))
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
    t[0][0]=X[0]
    t[1][0]=X[1]
    t[2][0]=X[2]
    X=pmag.dir2cart((Gdec,Ginc,1.0))
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
    t[0][1]=X[0]
    t[1][1]=X[1]
    t[2][1]=X[2]
# set up v matrix
    v=[0,0,0]
    for i in range(nums):  # incremental point along ellipse
        psi=float(i)*np.pi/xnum
        v[0]=np.sin(beta)*np.cos(psi) 
        v[1]=np.sin(gamma)*np.sin(psi) 
        v[2]=np.sqrt(1.-v[0]**2 - v[1]**2)
        elli=[0,0,0]
# calculate points on the ellipse
        for j in range(3):
            for k in range(3):
                elli[j]=elli[j] + t[j][k]*v[k]  # cartesian coordinate j of ellipse
        PTS.append(pmag.cart2dir(elli))
        R=np.sqrt( 1.-abs(elli[2]))/(np.sqrt(elli[0]**2+elli[1]**2)) # put on an equal area projection
        if elli[2]<0:
#            for i in range(3): elli[i]=-elli[i]
            X_up.append(elli[1]*R)
            Y_up.append(elli[0]*R)
        else:
            X_ell.append(elli[1]*R)
            Y_ell.append(elli[0]*R)
    if plot==1:
        if X_ell!=[]:plt.plot(X_ell,Y_ell,col,linewidth=2,zorder=5)#pylab.plot(X_ell,Y_ell,col,zorder=3)
        if X_up!=[]:plt.plot(X_up,Y_up,col,linewidth=2,zorder=5)#pylab.plot(X_up,Y_up,'g-',zorder=3)
        #pylab.draw()
    else: 
        return PTS
def bootstrap_common_mean(Data1,Data2,NumSims=1000):
    """
    Conduct a bootstrap test (Tauxe, 2010) for a common mean on two declination,
    inclination data sets
    
    This function modifies code from PmagPy for use calculating and plotting 
    bootstrap statistics. Three plots are generated (one for x, one for y and
    one for z). If the 95 percent confidence bounds for each component overlap
    each other, the two directions are not significantly different.

    Arguments
    ----------
    Data1 : a list of directional data [dec,inc]
    Data2 : a list of directional data [dec,inc]
    NumSims : number of bootstrap samples (default is 1000)
    """         
    counter=0
    BDI1=pmag.di_boot(Data1)
    BDI2=pmag.di_boot(Data2)

    cart1= pmag.dir2cart(BDI1).transpose()
    X1,Y1,Z1=cart1[0],cart1[1],cart1[2]
    cart2= pmag.dir2cart(BDI2).transpose()
    X2,Y2,Z2=cart2[0],cart2[1],cart2[2]
    
    print "Here are the results of the bootstrap test for a common mean:"
    
    fignum = 1
    fig = plt.figure(figsize=(9,3))
    fig = plt.subplot(1,3,1)
    
    minimum = int(0.025*len(X1))
    maximum = int(0.975*len(X1))
    
    X1,y=pmagplotlib.plotCDF(fignum,X1,"X component",'r',"")
    bounds1=[X1[minimum],X1[maximum]]
    pmagplotlib.plotVs(fignum,bounds1,'r','-')

    X2,y=pmagplotlib.plotCDF(fignum,X2,"X component",'b',"")
    bounds2=[X2[minimum],X2[maximum]]
    pmagplotlib.plotVs(fignum,bounds2,'b','--')
    plt.ylim(0,1)
    
    plt.subplot(1,3,2)
    
    Y1,y=pmagplotlib.plotCDF(fignum,Y1,"Y component",'r',"")
    bounds1=[Y1[minimum],Y1[maximum]]
    pmagplotlib.plotVs(fignum,bounds1,'r','-')
    
    Y2,y=pmagplotlib.plotCDF(fignum,Y2,"Y component",'b',"")
    bounds2=[Y2[minimum],Y2[maximum]]
    pmagplotlib.plotVs(fignum,bounds2,'b','--')
    plt.ylim(0,1)
    
    plt.subplot(1,3,3)
    
    Z1,y=pmagplotlib.plotCDF(fignum,Z1,"Z component",'r',"")
    bounds1=[Z1[minimum],Z1[maximum]]
    pmagplotlib.plotVs(fignum,bounds1,'r','-')
    
    Z2,y=pmagplotlib.plotCDF(fignum,Z2,"Z component",'b',"")
    bounds2=[Z2[minimum],Z2[maximum]]
    pmagplotlib.plotVs(fignum,bounds2,'b','--')
    plt.ylim(0,1)
    
    plt.tight_layout()
    plt.show()
def main():
    """
    NAME
        remanence_aniso_magic.py

    DESCRIPTION
        This program is similar to aarm_magic.py and atrm_magic.py with minor modifications.

        Converts magic measurement file with ATRM/AARM data to best-fit tensor (6 elements plus sigma)
        following Hext (1963), and calculates F-test statistics.
        
        Comments:
        - infield steps are marked with method codes LT-T-I:LP-AN-TRM; LT-AF-I:LP-AN-ARM
        - zerofield steps are marked with method codes LT-T-Z:LP-AN-TRM; LT-AF-Z:LP-AN-ARM
        - alteration check is marked with method codes LT-PTRM-I:LP-AN-TRM
        please notice;
        - ATRM: The program uses treatment_dc_field_phi/treatment_dc_field_theta columns to infer the direction of the applied field
                 (this is a change from atrm_magic.py)
        - ATRM: zerofield (baseline) magnetization is subtructed from all infield measurements
        - AARM: The program uses measurement number (running number) to to infer the direction of the applied field
                assuming the SIO protocol for 6,9,15 measurements scheme.
                See cookbook for diagram and details.
        - AARM: zerofield (baseline) are assumed to be before any infield, and the baseline is subtructed from the 
                subsequent infield magnetization.
      
    SYNTAX 
        remanence_aniso_magic.py [-h] [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is magic_measurements.txt

    INPUT  
        magic measurement file with ATRM and/or AARM data.
        if both types of measurements exist then the program calculates both.
        
    OUTPUT  
        rmag_anisotropy.log
                -I- information
                -W- Warning
                -E- Error
        rmag_anistropy.txt:
            This file contains in addition to some some magic information the following:
                - anistropy tensor s1 to s6 normalized by the trace:
                    |Mx|   |s1 s4 s6|   |Bx|
                    |My| = |s4 s2 s5| . |By|
                    |Mz|   |s6 s5 s3|   |Bz|
                - anisotropy_sigma (Hext, 1963)
                - anisotropy_alt (altertion check for ATRM in units of %):
                    100* [abs(M_first-Mlast)/max(M_first,M_last)]
                -                     
        rmag_results.txt:
            This file contains in addition to some  magic information the follow(ing:
                - anisotropy_t1,anisotropy_t2,anisotropy_t3 : eigenvalues
                - anisotropy_v*_dec,anisotropy_v*_inc: declination/inclination of the eigenvectors
                - anisotropy_ftest,anisotropy_ftest12,anisotropy_ftest13 
                - (the crtical F for 95% confidence level of anistropy is given in result_description column).
                
                
    """


    #==================================================================================
    
    meas_file="magic_measurements.txt"
    args=sys.argv
    dir_path='.'
    #
    # get name of file from command line
    #
    if '-WD' in args:
        ind=args.index('-WD')
        dir_path=args[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-f" in args:
        ind=args.index("-f")
        meas_file=sys.argv[ind+1]
    else:
        meas_file=dir_path+'/'+meas_file
    WD=dir_path

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

    def get_Data(magic_file):
    
        #------------------------------------------------
        # Read magic measurement file and sort to blocks
        #------------------------------------------------
        Data={}
        try:
            meas_data,file_type=pmag.magic_read(magic_file)
        except:
            print "-E- ERROR: Cant read magic_measurement.txt file. File is corrupted."
            return Data
            
        # get list of unique specimen names
        
        #sids=pmag.get_specs(meas_data) # samples ID's
        
        for rec in meas_data:
            s=rec["er_specimen_name"]
            method_codes= rec["magic_method_codes"].strip('\n')
            method_codes.replace(" ","")
            methods=method_codes.split(":")
            if "LP-AN-TRM" in methods:
                if s not in Data.keys():
                    Data[s]={}
                if 'atrmblock' not in Data[s].keys():
                    Data[s]['atrmblock']=[]
                Data[s]['atrmblock'].append(rec)
            
            
            if "LP-AN-ARM" in methods:
                if s not in Data.keys():
                    Data[s]={}
                if 'aarmblock' not in Data[s].keys():
                    Data[s]['aarmblock']=[]
                Data[s]['aarmblock'].append(rec)
        return (Data)        

    #======================================
    # better to put this one in pmagpy
    #======================================
        
    def calculate_aniso_parameters(B,K):
    
        aniso_parameters={}
        S_bs=dot(B,K)
        
        # normalize by trace
        trace=S_bs[0]+S_bs[1]+S_bs[2]
        S_bs=S_bs/trace
        s1,s2,s3,s4,s5,s6=S_bs[0],S_bs[1],S_bs[2],S_bs[3],S_bs[4],S_bs[5]
        s_matrix=[[s1,s4,s6],[s4,s2,s5],[s6,s5,s3]]
        
        # calculate eigen vector,
        t,evectors=eig(s_matrix)
        # sort vectors
        t=list(t)
        t1=max(t)
        ix_1=t.index(t1)
        t3=min(t)
        ix_3=t.index(t3)
        for tt in range(3):
            if t[tt]!=t1 and t[tt]!=t3:
                t2=t[tt]
                ix_2=t.index(t2)
                
        v1=[evectors[0][ix_1],evectors[1][ix_1],evectors[2][ix_1]]
        v2=[evectors[0][ix_2],evectors[1][ix_2],evectors[2][ix_2]]
        v3=[evectors[0][ix_3],evectors[1][ix_3],evectors[2][ix_3]]
    
    
        DIR_v1=pmag.cart2dir(v1)
        DIR_v2=pmag.cart2dir(v2)
        DIR_v3=pmag.cart2dir(v3)
    
                            
        aniso_parameters['anisotropy_s1']="%f"%s1
        aniso_parameters['anisotropy_s2']="%f"%s2
        aniso_parameters['anisotropy_s3']="%f"%s3
        aniso_parameters['anisotropy_s4']="%f"%s4
        aniso_parameters['anisotropy_s5']="%f"%s5
        aniso_parameters['anisotropy_s6']="%f"%s6
        aniso_parameters['anisotropy_degree']="%f"%(t1/t3)
        aniso_parameters['anisotropy_t1']="%f"%t1
        aniso_parameters['anisotropy_t2']="%f"%t2
        aniso_parameters['anisotropy_t3']="%f"%t3
        aniso_parameters['anisotropy_v1_dec']="%.1f"%DIR_v1[0]
        aniso_parameters['anisotropy_v1_inc']="%.1f"%DIR_v1[1]
        aniso_parameters['anisotropy_v2_dec']="%.1f"%DIR_v2[0]
        aniso_parameters['anisotropy_v2_inc']="%.1f"%DIR_v2[1]
        aniso_parameters['anisotropy_v3_dec']="%.1f"%DIR_v3[0]
        aniso_parameters['anisotropy_v3_inc']="%.1f"%DIR_v3[1]
    
        # modified from pmagpy:
        if len(K)/3==9 or len(K)/3==6 or len(K)/3==15:
            n_pos=len(K)/3
            tmpH = Matrices[n_pos]['tmpH']
            a=s_matrix
            S=0.
            comp=zeros((n_pos*3),'f')
            for i in range(n_pos):
                for j in range(3):
                    index=i*3+j
                    compare=a[j][0]*tmpH[i][0]+a[j][1]*tmpH[i][1]+a[j][2]*tmpH[i][2]
                    comp[index]=compare
            for i in range(n_pos*3):
                d=K[i]/trace - comp[i] # del values
                S+=d*d
            nf=float(n_pos*3-6) # number of degrees of freedom
            if S >0: 
                sigma=math.sqrt(S/nf)
            hpars=pmag.dohext(nf,sigma,[s1,s2,s3,s4,s5,s6])
            
            aniso_parameters['anisotropy_sigma']="%f"%sigma
            aniso_parameters['anisotropy_ftest']="%f"%hpars["F"]
            aniso_parameters['anisotropy_ftest12']="%f"%hpars["F12"]
            aniso_parameters['anisotropy_ftest23']="%f"%hpars["F23"]
            aniso_parameters['result_description']="Critical F: %s"%(hpars['F_crit'])
            aniso_parameters['anisotropy_F_crit']="%f"%float(hpars['F_crit'])
            aniso_parameters['anisotropy_n']=n_pos
            
        return(aniso_parameters)
    
    
    #======================================
    # Main
    #======================================
          
    
        
    aniso_logfile=open(WD+"/rmag_anisotropy.log",'w')
    aniso_logfile.write("------------------------\n")
    aniso_logfile.write( "-I- Start rmag anisrotropy script\n")
    aniso_logfile.write( "------------------------\n")

    Data=get_Data(meas_file)
    #try:    
    #    Data=get_Data(meas_file)
    #except:
    #    aniso_logfile.write( "-E- Cant open measurement file %s\n" %meas_file)
    #    print "-E- Cant open measurement file %s\n exiting" %meas_file
    #    exit()
        
    aniso_logfile.write( "-I-  Open measurement file %s\n" %meas_file)
    
        
    Data_anisotropy={}                
    specimens=Data.keys()
    specimens.sort()
    
    
    
    #-----------------------------------
    # Prepare rmag_anisotropy.txt file for writing
    #-----------------------------------
    
    rmag_anisotropy_file =open(WD+"/rmag_anisotropy.txt",'w')
    rmag_anisotropy_file.write("tab\trmag_anisotropy\n")
    
    rmag_results_file =open(WD+"/rmag_results.txt",'w')
    rmag_results_file.write("tab\trmag_results\n")
    
    rmag_anistropy_header=['er_specimen_name','er_sample_name','er_site_name','anisotropy_type','anisotropy_n','anisotropy_description','anisotropy_s1','anisotropy_s2','anisotropy_s3','anisotropy_s4','anisotropy_s5','anisotropy_s6','anisotropy_sigma','anisotropy_alt','magic_experiment_names','magic_method_codes','rmag_anisotropy_name']
    
    String=""
    for i in range (len(rmag_anistropy_header)):
        String=String+rmag_anistropy_header[i]+'\t'
    rmag_anisotropy_file.write(String[:-1]+"\n")
    
    
    
    rmag_results_header=['er_specimen_names','er_sample_names','er_site_names','anisotropy_type','magic_method_codes','magic_experiment_names','result_description','anisotropy_t1','anisotropy_t2','anisotropy_t3','anisotropy_ftest','anisotropy_ftest12','anisotropy_ftest23',\
                            'anisotropy_v1_dec','anisotropy_v1_inc','anisotropy_v2_dec','anisotropy_v2_inc','anisotropy_v3_dec','anisotropy_v3_inc']
    
    
    String=""
    for i in range (len(rmag_results_header)):
        String=String+rmag_results_header[i]+'\t'
    rmag_results_file.write(String[:-1]+"\n")
    
    #-----------------------------------
    # Matrices definitions:
    # A design matrix
    # B dot(inv(dot(A.transpose(),A)),A.transpose())
    # tmpH is used for sigma calculation (9,15 measurements only)
    # 
    #  Anisotropy tensor:
    #
    # |Mx|   |s1 s4 s6|   |Bx|
    # |My| = |s4 s2 s5| . |By|
    # |Mz|   |s6 s5 s3|   |Bz|
    #
    # A matrix (measurement matrix):
    # Each mesurement yields three lines in "A" matrix
    #
    # |Mi  |   |Bx 0  0   By  0   Bz|   |s1|
    # |Mi+1| = |0  By 0   Bx  Bz  0 | . |s2|
    # |Mi+2|   |0  0  Bz  0   By  Bx|   |s3|
    #                                   |s4|
    #                                   |s5|
    #
    #-----------------------------------
    
    Matrices={}
    
    for n_pos in [6,9,15]:
    
        Matrices[n_pos]={}
        
        A=zeros((n_pos*3,6),'f')
    
        if n_pos==6:
            positions=[[0.,0.,1.],[90.,0.,1.],[0.,90.,1.],\
                    [180.,0.,1.],[270.,0.,1.],[0.,-90.,1.]]
    
        if n_pos==15:
            positions=[[315.,0.,1.],[225.,0.,1.],[180.,0.,1.],[135.,0.,1.],[45.,0.,1.],\
                    [90.,-45.,1.],[270.,-45.,1.],[270.,0.,1.],[270.,45.,1.],[90.,45.,1.],\
                    [180.,45.,1.],[180.,-45.,1.],[0.,-90.,1.],[0,-45.,1.],[0,45.,1.]]
        if n_pos==9:
            positions=[[315.,0.,1.],[225.,0.,1.],[180.,0.,1.],\
                    [90.,-45.,1.],[270.,-45.,1.],[270.,0.,1.],\
                    [180.,45.,1.],[180.,-45.,1.],[0.,-90.,1.]]
    
        
        tmpH=zeros((n_pos,3),'f') # define tmpH
        for i in range(len(positions)):
            CART=pmag.dir2cart(positions[i])
            a=CART[0];b=CART[1];c=CART[2]
            A[3*i][0]=a
            A[3*i][3]=b
            A[3*i][5]=c
    
            A[3*i+1][1]=b
            A[3*i+1][3]=a
            A[3*i+1][4]=c
    
            A[3*i+2][2]=c
            A[3*i+2][4]=b
            A[3*i+2][5]=a
            
            tmpH[i][0]=CART[0]
            tmpH[i][1]=CART[1]
            tmpH[i][2]=CART[2]
    
        B=dot(inv(dot(A.transpose(),A)),A.transpose())
    
        Matrices[n_pos]['A']=A
        Matrices[n_pos]['B']=B
        Matrices[n_pos]['tmpH']=tmpH
    
    
    
    
    
    for specimen in specimens:
    
        if 'atrmblock' in Data[specimen].keys():
            
            #-----------------------------------
            # aTRM 6 positions
            #-----------------------------------
                
            aniso_logfile.write("-I- Start calculating ATRM tensor for specimen %s\n "%specimen)
            atrmblock=Data[specimen]['atrmblock']
            if len(atrmblock)<6:
                aniso_logfile.write("-W- specimen %s has not enough measurementf for ATRM calculation\n"%specimen)
                continue
            
            B=Matrices[6]['B']
                                
            Reject_specimen = False
    
            # The zero field step is a "baseline"
    
            # Search the baseline in the ATRM measurement
            
            baseline=""
            Alteration_check=""
            Alteration_check_index=""
            baselines=[]
    
            # search for baseline in atrm blocks
            for rec in atrmblock:
                dec=float(rec['measurement_dec'])
                inc=float(rec['measurement_inc'])
                moment=float(rec['measurement_magn_moment'])
                # find the temperature of the atrm
                if float(rec['treatment_dc_field'])!=0 and float(rec['treatment_temp'])!=273:
                    atrm_temperature=float(rec['treatment_temp'])
                # find baseline
                if float(rec['treatment_dc_field'])==0 and float(rec['treatment_temp'])!=273:
                    baselines.append(array(pmag.dir2cart([dec,inc,moment])))
                # Find alteration check
                #print rec['measurement_number']
            
            if len(baselines)!=0:
                aniso_logfile.write( "-I- found ATRM baseline for specimen %s\n"%specimen)
                baselines=array(baselines)
                baseline=array([mean(baselines[:,0]),mean(baselines[:,1]),mean(baselines[:,2])])                                 
                
            else:
                baseline=zeros(3,'f')
                aniso_logfile.write( "-I- No aTRM baseline for specimen %s\n"%specimen)
                        
            # sort measurements
            
            M=zeros([6,3],'f')
            
            for rec in atrmblock:
    
                dec=float(rec['measurement_dec'])
                inc=float(rec['measurement_inc'])
                moment=float(rec['measurement_magn_moment'])
                CART=array(pmag.dir2cart([dec,inc,moment]))-baseline
                
                if float(rec['treatment_dc_field'])==0: # Ignore zero field steps
                    continue
                if  "LT-PTRM-I" in rec['magic_method_codes'].split(":"): #  alteration check
                    Alteration_check=CART
                    Alteration_check_dc_field_phi=float(rec['treatment_dc_field_phi'])
                    Alteration_check_dc_field_theta=float(rec['treatment_dc_field_theta'])
                    if Alteration_check_dc_field_phi==0 and Alteration_check_dc_field_theta==0 :
                        Alteration_check_index=0
                    if Alteration_check_dc_field_phi==90 and Alteration_check_dc_field_theta==0 :
                        Alteration_check_index=1
                    if Alteration_check_dc_field_phi==0 and Alteration_check_dc_field_theta==90 :
                        Alteration_check_index=2
                    if Alteration_check_dc_field_phi==180 and Alteration_check_dc_field_theta==0 :
                        Alteration_check_index=3
                    if Alteration_check_dc_field_phi==270 and Alteration_check_dc_field_theta==0 :
                        Alteration_check_index=4
                    if Alteration_check_dc_field_phi==0 and Alteration_check_dc_field_theta==-90 :
                        Alteration_check_index=5
                    aniso_logfile.write(  "-I- found alteration check  for specimen %s\n"%specimen)
                    continue
                
                treatment_dc_field_phi=float(rec['treatment_dc_field_phi'])
                treatment_dc_field_theta=float(rec['treatment_dc_field_theta'])
                treatment_dc_field=float(rec['treatment_dc_field'])
                
                #+x, M[0]
                if treatment_dc_field_phi==0 and treatment_dc_field_theta==0 :
                    M[0]=CART
                #+Y , M[1]
                if treatment_dc_field_phi==90 and treatment_dc_field_theta==0 :
                    M[1]=CART
                #+Z , M[2]
                if treatment_dc_field_phi==0 and treatment_dc_field_theta==90 :
                    M[2]=CART
                #-x, M[3]
                if treatment_dc_field_phi==180 and treatment_dc_field_theta==0 :
                    M[3]=CART
                #-Y , M[4]
                if treatment_dc_field_phi==270 and treatment_dc_field_theta==0 :
                    M[4]=CART
                #-Z , M[5]
                if treatment_dc_field_phi==0 and treatment_dc_field_theta==-90 :
                    M[5]=CART
        
            # check if at least one measurement in missing
            for i in range(len(M)):
                if M[i][0]==0 and M[i][1]==0 and M[i][2]==0: 
                    aniso_logfile.write( "-E- ERROR: missing atrm data for specimen %s\n"%(specimen))
                    Reject_specimen=True
    
            # alteration check        
    
            anisotropy_alt=0
            if Alteration_check!="":
                for i in range(len(M)):
                    if Alteration_check_index==i:
                        M_1=sqrt(sum((array(M[i])**2)))
                        M_2=sqrt(sum(Alteration_check**2))
                        diff=abs(M_1-M_2)
                        diff_ratio=diff/max(M_1,M_2)
                        diff_ratio_perc=100*diff_ratio
                        if diff_ratio_perc > anisotropy_alt:
                            anisotropy_alt=diff_ratio_perc
            else:
                aniso_logfile.write( "-W- Warning: no alteration check for specimen %s \n "%specimen )
    
            # Check for maximum difference in anti parallel directions.
            # if the difference between the two measurements is more than maximum_diff
            # The specimen is rejected
            
            # i.e. +x versus -x, +y versus -y, etc.s
    
            for i in range(3):
                M_1=sqrt(sum(array(M[i])**2))
                M_2=sqrt(sum(array(M[i+3])**2))
                
                diff=abs(M_1-M_2)
                diff_ratio=diff/max(M_1,M_2)
                diff_ratio_perc=100*diff_ratio
                
                if diff_ratio_perc>anisotropy_alt:
                    anisotropy_alt=diff_ratio_perc
                    
            if not Reject_specimen:
            
                # K vector (18 elements, M1[x], M1[y], M1[z], ... etc.) 
                K=zeros(18,'f')
                K[0],K[1],K[2]=M[0][0],M[0][1],M[0][2]
                K[3],K[4],K[5]=M[1][0],M[1][1],M[1][2]
                K[6],K[7],K[8]=M[2][0],M[2][1],M[2][2]
                K[9],K[10],K[11]=M[3][0],M[3][1],M[3][2]
                K[12],K[13],K[14]=M[4][0],M[4][1],M[4][2]
                K[15],K[16],K[17]=M[5][0],M[5][1],M[5][2]
    
                if specimen not in Data_anisotropy.keys():
                    Data_anisotropy[specimen]={}
                aniso_parameters=calculate_aniso_parameters(B,K)
                Data_anisotropy[specimen]['ATRM']=aniso_parameters
                Data_anisotropy[specimen]['ATRM']['anisotropy_alt']="%.2f"%anisotropy_alt               
                Data_anisotropy[specimen]['ATRM']['anisotropy_type']="ATRM"
                Data_anisotropy[specimen]['ATRM']['er_sample_name']=atrmblock[0]['er_sample_name']
                Data_anisotropy[specimen]['ATRM']['er_specimen_name']=specimen
                Data_anisotropy[specimen]['ATRM']['er_site_name']=atrmblock[0]['er_site_name']
                Data_anisotropy[specimen]['ATRM']['anisotropy_description']='Hext statistics adapted to ATRM'
                Data_anisotropy[specimen]['ATRM']['magic_experiment_names']=specimen+";ATRM"
                Data_anisotropy[specimen]['ATRM']['magic_method_codes']="LP-AN-TRM:AE-H"
                Data_anisotropy[specimen]['ATRM']['rmag_anisotropy_name']=specimen
    
    
        if 'aarmblock' in Data[specimen].keys():    
    
            #-----------------------------------
            # AARM - 6, 9 or 15 positions
            #-----------------------------------
                
            aniso_logfile.write( "-I- Start calculating AARM tensors specimen %s\n"%specimen)
    
            aarmblock=Data[specimen]['aarmblock']
            if len(aarmblock)<12:
                aniso_logfile.write( "-W- WARNING: not enough aarm measurement for specimen %s\n"%specimen)
                continue
            elif len(aarmblock)==12:
                n_pos=6
                B=Matrices[6]['B']
                M=zeros([6,3],'f')
            elif len(aarmblock)==18:
                n_pos=9
                B=Matrices[9]['B']
                M=zeros([9,3],'f')
            # 15 positions
            elif len(aarmblock)==30:
                n_pos=15
                B=Matrices[15]['B']
                M=zeros([15,3],'f')
            else:
                aniso_logfile.write( "-E- ERROR: number of measurements in aarm block is incorrect sample %s\n"%specimen)
                continue
                
            Reject_specimen = False
    
            for i in range(n_pos):
                for rec in aarmblock:
                    if float(rec['measurement_number'])==i*2+1:
                        dec=float(rec['measurement_dec'])
                        inc=float(rec['measurement_inc'])
                        moment=float(rec['measurement_magn_moment'])                    
                        M_baseline=array(pmag.dir2cart([dec,inc,moment]))
                        
                    if float(rec['measurement_number'])==i*2+2:
                        dec=float(rec['measurement_dec'])
                        inc=float(rec['measurement_inc'])
                        moment=float(rec['measurement_magn_moment'])                    
                        M_arm=array(pmag.dir2cart([dec,inc,moment]))
                M[i]=M_arm-M_baseline
    
                
            K=zeros(3*n_pos,'f')
            for i in range(n_pos):
                K[i*3]=M[i][0]
                K[i*3+1]=M[i][1]
                K[i*3+2]=M[i][2]            
    
            if specimen not in Data_anisotropy.keys():
                Data_anisotropy[specimen]={}
            aniso_parameters=calculate_aniso_parameters(B,K)
            Data_anisotropy[specimen]['AARM']=aniso_parameters
            Data_anisotropy[specimen]['AARM']['anisotropy_alt']=""               
            Data_anisotropy[specimen]['AARM']['anisotropy_type']="AARM"
            Data_anisotropy[specimen]['AARM']['er_sample_name']=aarmblock[0]['er_sample_name']
            Data_anisotropy[specimen]['AARM']['er_site_name']=aarmblock[0]['er_site_name']
            Data_anisotropy[specimen]['AARM']['er_specimen_name']=specimen
            Data_anisotropy[specimen]['AARM']['anisotropy_description']='Hext statistics adapted to AARM'
            Data_anisotropy[specimen]['AARM']['magic_experiment_names']=specimen+";AARM"
            Data_anisotropy[specimen]['AARM']['magic_method_codes']="LP-AN-ARM:AE-H"
            Data_anisotropy[specimen]['AARM']['rmag_anisotropy_name']=specimen
            
    
    #-----------------------------------   
    
    specimens=Data_anisotropy.keys()
    specimens.sort
    
    # remove previous anistropy data, and replace with the new one:
    s_list=Data.keys()
    for sp in s_list:
        if 'AniSpec' in Data[sp].keys():
            del  Data[sp]['AniSpec']
    for specimen in specimens:
        # if both AARM and ATRM axist prefer the AARM !!
        if 'AARM' in Data_anisotropy[specimen].keys():
            TYPES=['AARM']
        if 'ATRM' in Data_anisotropy[specimen].keys():
            TYPES=['ATRM']
        if  'AARM' in Data_anisotropy[specimen].keys() and 'ATRM' in Data_anisotropy[specimen].keys():
            TYPES=['ATRM','AARM']
            aniso_logfile.write( "-W- WARNING: both aarm and atrm data exist for specimen %s. using AARM by default. If you prefer using one of them, delete the other!\n"%specimen)
        for TYPE in TYPES:
            String=""
            for i in range (len(rmag_anistropy_header)):
                try:
                    String=String+Data_anisotropy[specimen][TYPE][rmag_anistropy_header[i]]+'\t'
                except:
                    String=String+"%f"%(Data_anisotropy[specimen][TYPE][rmag_anistropy_header[i]])+'\t'
            rmag_anisotropy_file.write(String[:-1]+"\n")
    
            String=""
            Data_anisotropy[specimen][TYPE]['er_specimen_names']=Data_anisotropy[specimen][TYPE]['er_specimen_name']
            Data_anisotropy[specimen][TYPE]['er_sample_names']=Data_anisotropy[specimen][TYPE]['er_sample_name']
            Data_anisotropy[specimen][TYPE]['er_site_names']=Data_anisotropy[specimen][TYPE]['er_site_name']
            for i in range (len(rmag_results_header)):
                try:
                    String=String+Data_anisotropy[specimen][TYPE][rmag_results_header[i]]+'\t'
                except:
                    String=String+"%f"%(Data_anisotropy[specimen][TYPE][rmag_results_header[i]])+'\t'
            rmag_results_file.write(String[:-1]+"\n")
    
            if 'AniSpec' not in Data[specimen]:
                Data[specimen]['AniSpec']={}
            Data[specimen]['AniSpec'][TYPE]=Data_anisotropy[specimen][TYPE]
    
    aniso_logfile.write("------------------------\n")
    aniso_logfile.write("-I-  remanence_aniso_magic script finished sucsessfuly\n")
    aniso_logfile.write( "------------------------\n")
    
    rmag_anisotropy_file.close()
    print "Anisotropy tensors elements are saved in rmag_anistropy.txt"
    print "Other anisotropy statistics are saved in rmag_results.txt"
    print "log file is  in rmag_anisotropy.log"
Example #12
0
def dokent(data, NN):  #From PmagPy (Tauxe et al., 2016)
    """
    gets Kent  parameters for data ([D,I],N)
    """
    X, kpars = [], {}
    N = len(data)
    if N < 2:
        return kpars
#
#  get fisher mean and convert to co-inclination (theta)/dec (phi) in radians
#
    fpars = pmag.fisher_mean(data)
    pbar = fpars["dec"] * np.pi / 180.
    tbar = (90. - fpars["inc"]) * np.pi / 180.
    #
    #   initialize matrices
    #
    H = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]
    w = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]
    b = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]
    gam = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]
    xg = []
    #
    #  set up rotation matrix H
    #
    H = [[
        np.cos(tbar) * np.cos(pbar), -np.sin(pbar),
        np.sin(tbar) * np.cos(pbar)
    ], [
        np.cos(tbar) * np.sin(pbar),
        np.cos(pbar),
        np.sin(pbar) * np.sin(tbar)
    ], [-np.sin(tbar), 0., np.cos(tbar)]]
    #
    #  get cartesian coordinates of data
    #
    for rec in data:
        X.append(pmag.dir2cart([rec[0], rec[1], 1.]))
#
#   put in T matrix
#
    T = pmag.Tmatrix(X)
    for i in range(3):
        for j in range(3):
            T[i][j] = old_div(T[i][j], float(NN))
#
# compute B=H'TH
#
    for i in range(3):
        for j in range(3):
            for k in range(3):
                w[i][j] += T[i][k] * H[k][j]
    for i in range(3):
        for j in range(3):
            for k in range(3):
                b[i][j] += H[k][i] * w[k][j]
#
# choose a rotation w about North pole to diagonalize upper part of B
#
    psi = 0.5 * np.arctan(2. * b[0][1] / (b[0][0] - b[1][1]))
    w = [[np.cos(psi), -np.sin(psi), 0], [np.sin(psi),
                                          np.cos(psi), 0], [0., 0., 1.]]
    for i in range(3):
        for j in range(3):
            gamtmp = 0.
            for k in range(3):
                gamtmp += H[i][k] * w[k][j]
            gam[i][j] = gamtmp
    for i in range(N):
        xg.append([0., 0., 0.])
        for k in range(3):
            xgtmp = 0.
            for j in range(3):
                xgtmp += gam[j][k] * X[i][j]
            xg[i][k] = xgtmp
# compute asymptotic ellipse parameters
#
    xmu, sigma1, sigma2 = 0., 0., 0.
    for i in range(N):
        xmu += xg[i][2]
        sigma1 = sigma1 + xg[i][0]**2
        sigma2 = sigma2 + xg[i][1]**2
    xmu = old_div(xmu, float(N))
    sigma1 = old_div(sigma1, float(N))
    sigma2 = old_div(sigma2, float(N))
    g = -2.0 * np.log(0.05) / (float(NN) * xmu**2)
    if np.sqrt(sigma1 * g) < 1:
        eta = np.arcsin(np.sqrt(sigma1 * g))
    if np.sqrt(sigma2 * g) < 1:
        zeta = np.arcsin(np.sqrt(sigma2 * g))
    if np.sqrt(sigma1 * g) >= 1.:
        eta = old_div(np.pi, 2.)
    if np.sqrt(sigma2 * g) >= 1.:
        zeta = old_div(np.pi, 2.)
#
#  convert Kent parameters to directions,angles
#
    kpars["dec"] = fpars["dec"]
    kpars["inc"] = fpars["inc"]
    kpars["n"] = NN
    ZDir = pmag.cart2dir([gam[0][1], gam[1][1], gam[2][1]])
    EDir = pmag.cart2dir([gam[0][0], gam[1][0], gam[2][0]])
    kpars["Zdec"] = ZDir[0]
    kpars["Zinc"] = ZDir[1]
    kpars["Edec"] = EDir[0]
    kpars["Einc"] = EDir[1]
    if kpars["Zinc"] < 0:
        kpars["Zinc"] = -kpars["Zinc"]
        kpars["Zdec"] = (kpars["Zdec"] + 180.) % 360.
    if kpars["Einc"] < 0:
        kpars["Einc"] = -kpars["Einc"]
        kpars["Edec"] = (kpars["Edec"] + 180.) % 360.
    kpars["Zeta"] = zeta * 180. / np.pi
    kpars["Eta"] = eta * 180. / np.pi
    return kpars
Example #13
0
    Ps.append(P*4*math.pi*rr**2)
#pylab.plot(Rs,Ps)
Xs,Ys,Zs=[],[],[]
for k in range(len(Rs)):
    N=int(Ps[k]*20)
    for n in range(N):
        ran=random.random()
        random.jumpahead(int(ran*1000)) 
        ran2=random.random()
        theta=2.*math.pi*ran
        phi=2.*math.pi*ran2
        if n%2==0:
            sign=10.
        else:
            sign=-10.
        offset=pmag.dir2cart([45.,45.,sign])
        Xs.append(offset[0]+math.cos(theta)*math.cos(phi)*Rs[k])
        Ys.append(offset[1]+math.cos(theta)*math.sin(phi)*Rs[k])
        Zs.append(offset[2]+math.sin(theta)*Rs[k])
X=numpy.array(Xs)
Y=numpy.array(Ys)
Z=numpy.array(Zs)
points3d(X,Y,Z,color=(1.,0.,0.))
line=[-15.,15.]
zline=[0.,0.]
Line=numpy.array(line)
ZLine=numpy.array(zline)
plot3d(Line,ZLine,ZLine,tube_radius=.1)
plot3d(ZLine,Line,ZLine,tube_radius=.1)
plot3d(ZLine,ZLine,Line,tube_radius=.1)
view(azimuth=125., elevation=0.)
Example #14
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
Example #15
0
def get_PI_parameters(Data,acceptance_criteria,preferences,s,tmin,tmax,GUI_log,THERMAL,MICROWAVE):
        
    datablock = Data[s]['datablock']
    pars=copy.deepcopy(Data[s]['pars']) # assignments to pars are assiging to Data[s]['pars']
    # get MagIC mothod codes:

    #pars['magic_method_codes']="LP-PI-TRM" # thellier Method
    import SPD
    import SPD.spd as spd
    Pint_pars = spd.PintPars(Data, str(s), tmin, tmax, 'magic', preferences['show_statistics_on_gui'])
    Pint_pars.reqd_stats() # calculate only statistics indicated in preferences
    if not Pint_pars.pars:
        print "Could not get any parameters for {}".format(Pint_pars)
        return 0
    #Pint_pars.calculate_all_statistics() # calculate every statistic available
    #print "-D- Debag"
    #print Pint_pars.keys()
    pars.update(Pint_pars.pars) # 

    t_Arai=Data[s]['t_Arai']
    x_Arai=Data[s]['x_Arai']
    y_Arai=Data[s]['y_Arai']
    x_tail_check=Data[s]['x_tail_check']
    y_tail_check=Data[s]['y_tail_check']

    zijdblock=Data[s]['zijdblock']        
    z_temperatures=Data[s]['z_temp']

    #print tmin,tmax,z_temperatures
    # check tmin
    if tmin not in t_Arai or tmin not in z_temperatures:
        return(pars)
    
    # check tmax
    if tmax not in t_Arai or tmin not in z_temperatures:
        return(pars)

    start=t_Arai.index(tmin)
    end=t_Arai.index(tmax)

    zstart=z_temperatures.index(tmin)
    zend=z_temperatures.index(tmax)

    zdata_segment=Data[s]['zdata'][zstart:zend+1]


    # replacing PCA for zdata and for ptrms here
    

## removed a bunch of Ron's commented out old code        

#lj
    #-------------------------------------------------
    # York regresssion (York, 1967) following Coe (1978)
    # calculate f,fvds,
    # modified from pmag.py
    #-------------------------------------------------               

    x_Arai_segment= x_Arai[start:end+1]
    y_Arai_segment= y_Arai[start:end+1]
    # replace thellier_gui code for york regression here

    pars["specimen_int"]=-1*pars['lab_dc_field']*pars["specimen_b"]


    # replace thellier_gui code for ptrm checks, DRAT etc. here
    # also tail checks and SCAT




    #-------------------------------------------------                     
    # Add missing parts of code from old get_PI
    #-------------------------------------------------                     

    if MICROWAVE==True:
        LP_code="LP-PI-M"
    else:
        LP_code="LP-PI-TRM"
                
        
    count_IZ= Data[s]['steps_Arai'].count('IZ')
    count_ZI= Data[s]['steps_Arai'].count('ZI')
    if count_IZ >1 and count_ZI >1:
        pars['magic_method_codes']=LP_code+":"+"LP-PI-BT-IZZI"
    elif count_IZ <1 and count_ZI >1:
        pars['magic_method_codes']=LP_code+":"+"LP-PI-ZI"
    elif count_IZ >1 and count_ZI <1:
        pars['magic_method_codes']=LP_code+":"+"LP-PI-IZ"            
    else:
        pars['magic_method_codes']=LP_code

    if 'ptrm_checks_temperatures' in Data[s].keys() and len(Data[s]['ptrm_checks_temperatures'])>0:
        if MICROWAVE==True:
            pars['magic_method_codes']+=":LP-PI-ALT-PMRM"
        else:
            pars['magic_method_codes']+=":LP-PI-ALT-PTRM"
            
    if 'tail_check_temperatures' in Data[s].keys() and len(Data[s]['tail_check_temperatures'])>0:
        pars['magic_method_codes']+=":LP-PI-BT-MD"

    if 'additivity_check_temperatures' in Data[s].keys() and len(Data[s]['additivity_check_temperatures'])>0:
        pars['magic_method_codes']+=":LP-PI-BT"
                    
    #-------------------------------------------------            
    # Calculate anistropy correction factor
    #-------------------------------------------------            

    if "AniSpec" in Data[s].keys():
        pars["AC_WARNING"]=""
        # if both aarm and atrm tensor axist, try first the aarm. if it fails use the atrm.
        if 'AARM' in Data[s]["AniSpec"].keys() and 'ATRM' in Data[s]["AniSpec"].keys():
            TYPES=['AARM','ATRM']
        else:
            TYPES=Data[s]["AniSpec"].keys()
        for TYPE in TYPES:
            red_flag=False
            S_matrix=zeros((3,3),'f')
            S_matrix[0,0]=Data[s]['AniSpec'][TYPE]['anisotropy_s1']
            S_matrix[1,1]=Data[s]['AniSpec'][TYPE]['anisotropy_s2']
            S_matrix[2,2]=Data[s]['AniSpec'][TYPE]['anisotropy_s3']
            S_matrix[0,1]=Data[s]['AniSpec'][TYPE]['anisotropy_s4']
            S_matrix[1,0]=Data[s]['AniSpec'][TYPE]['anisotropy_s4']
            S_matrix[1,2]=Data[s]['AniSpec'][TYPE]['anisotropy_s5']
            S_matrix[2,1]=Data[s]['AniSpec'][TYPE]['anisotropy_s5']
            S_matrix[0,2]=Data[s]['AniSpec'][TYPE]['anisotropy_s6']
            S_matrix[2,0]=Data[s]['AniSpec'][TYPE]['anisotropy_s6']

            #Data[s]['AniSpec']['anisotropy_type']=Data[s]['AniSpec']['anisotropy_type']
            Data[s]['AniSpec'][TYPE]['anisotropy_n']=int(float(Data[s]['AniSpec'][TYPE]['anisotropy_n']))

            this_specimen_f_type=Data[s]['AniSpec'][TYPE]['anisotropy_type']+"_"+"%i"%(int(Data[s]['AniSpec'][TYPE]['anisotropy_n']))
            
            Ftest_crit={} 
            Ftest_crit['ATRM_6']=  3.1059
            Ftest_crit['AARM_6']=  3.1059
            Ftest_crit['AARM_9']= 2.6848
            Ftest_crit['AARM_15']= 2.4558

            # threshold value for Ftest:
            
            if 'AniSpec' in Data[s].keys() and TYPE in Data[s]['AniSpec'].keys()\
                and 'anisotropy_sigma' in  Data[s]['AniSpec'][TYPE].keys() \
                and Data[s]['AniSpec'][TYPE]['anisotropy_sigma']!="":
                # Calculate Ftest. If Ftest exceeds threshold value: set anistropy tensor to identity matrix
                sigma=float(Data[s]['AniSpec'][TYPE]['anisotropy_sigma'])             
                nf = 3*int(Data[s]['AniSpec'][TYPE]['anisotropy_n'])-6
                F=calculate_ftest(S_matrix,sigma,nf)
                #print s,"F",F
                Data[s]['AniSpec'][TYPE]['ftest']=F
                #print "s,sigma,nf,F,Ftest_crit[this_specimen_f_type]"
                #print s,sigma,nf,F,Ftest_crit[this_specimen_f_type]
                if acceptance_criteria['anisotropy_ftest_flag']['value'] in ['g','1',1,True,'TRUE','True'] :
                    Ftest_threshold=Ftest_crit[this_specimen_f_type]
                    if Data[s]['AniSpec'][TYPE]['ftest'] < Ftest_crit[this_specimen_f_type]:
                        S_matrix=identity(3,'f')
                        pars["AC_WARNING"]=pars["AC_WARNING"]+"%s tensor fails F-test; "%(TYPE)
                        red_flag=True
                        
            else:
                Data[s]['AniSpec'][TYPE]['anisotropy_sigma']=""
                Data[s]['AniSpec'][TYPE]['ftest']=99999
    
            
            if 'anisotropy_alt' in Data[s]['AniSpec'][TYPE].keys() and Data[s]['AniSpec'][TYPE]['anisotropy_alt']!="":
                if acceptance_criteria['anisotropy_alt']['value'] != -999 and \
                (float(Data[s]['AniSpec'][TYPE]['anisotropy_alt']) > float(acceptance_criteria['anisotropy_alt']['value'])):
                    S_matrix=identity(3,'f')
                    pars["AC_WARNING"]=pars["AC_WARNING"]+"%s tensor fails alteration check: %.1f > %.1f; "%(TYPE,float(Data[s]['AniSpec'][TYPE]['anisotropy_alt']),float(acceptance_criteria['anisotropy_alt']['value']))
                    red_flag=True
            else:
                Data[s]['AniSpec'][TYPE]['anisotropy_alt']=""

            Data[s]['AniSpec'][TYPE]['S_matrix']=S_matrix 
        #--------------------------  
        # if AARM passes all, use the AARM.
        # if ATRM fail alteration use the AARM
        # if both fail F-test: use AARM
        if len(TYPES)>1:
            if "ATRM tensor fails alteration check" in pars["AC_WARNING"]:
                TYPE='AARM'
            elif "ATRM tensor fails F-test" in pars["AC_WARNING"]:
                TYPE='AARM'
            else: 
                TYPE=='AARM'
        S_matrix= Data[s]['AniSpec'][TYPE]['S_matrix']
        #---------------------------        
        TRM_anc_unit=array(pars['specimen_PCA_v1'])/sqrt(pars['specimen_PCA_v1'][0]**2+pars['specimen_PCA_v1'][1]**2+pars['specimen_PCA_v1'][2]**2)
        B_lab_unit=pmag.dir2cart([ Data[s]['Thellier_dc_field_phi'], Data[s]['Thellier_dc_field_theta'],1])
        #B_lab_unit=array([0,0,-1])
        Anisotropy_correction_factor=linalg.norm(dot(inv(S_matrix),TRM_anc_unit.transpose()))*norm(dot(S_matrix,B_lab_unit))
        pars["Anisotropy_correction_factor"]=Anisotropy_correction_factor
        pars["AC_specimen_int"]= pars["Anisotropy_correction_factor"] * float(pars["specimen_int"])
        
        pars["AC_anisotropy_type"]=Data[s]['AniSpec'][TYPE]["anisotropy_type"]
        pars["specimen_int_uT"]=float(pars["AC_specimen_int"])*1e6
        if TYPE=='AARM':
            if ":LP-AN-ARM" not in pars['magic_method_codes']:
                pars['magic_method_codes']+=":LP-AN-ARM:AE-H:DA-AC-AARM"
                pars['specimen_correction']='c'
                pars['specimen_int_corr_anisotropy']=Anisotropy_correction_factor
        if TYPE=='ATRM':
            if ":LP-AN-TRM" not in pars['magic_method_codes']:
                pars['magic_method_codes']+=":LP-AN-TRM:AE-H:DA-AC-ATRM"
                pars['specimen_correction']='c' 
                pars['specimen_int_corr_anisotropy']=Anisotropy_correction_factor


    else:
        pars["Anisotropy_correction_factor"]=1.0
        pars["specimen_int_uT"]=float(pars["specimen_int"])*1e6
        pars["AC_WARNING"]="No anistropy correction"
        pars['specimen_correction']='u' 

    pars["specimen_int_corr_anisotropy"]=pars["Anisotropy_correction_factor"]   
    #-------------------------------------------------                    
    # NLT and anisotropy correction together in one equation
    # See Shaar et al (2010), Equation (3)
    #-------------------------------------------------

    if 'NLT_parameters' in Data[s].keys():

        alpha=Data[s]['NLT_parameters']['tanh_parameters'][0][0]
        beta=Data[s]['NLT_parameters']['tanh_parameters'][0][1]
        b=float(pars["specimen_b"])
        Fa=pars["Anisotropy_correction_factor"]

        if ((abs(b)*Fa)/alpha) <1.0:
            Banc_NLT=math.atanh( ((abs(b)*Fa)/alpha) ) / beta
            pars["NLTC_specimen_int"]=Banc_NLT
            pars["specimen_int_uT"]=Banc_NLT*1e6

            if "AC_specimen_int" in pars.keys():
                pars["NLT_specimen_correction_factor"]=Banc_NLT/float(pars["AC_specimen_int"])
            else:                       
                pars["NLT_specimen_correction_factor"]=Banc_NLT/float(pars["specimen_int"])
            if ":LP-TRM" not in pars['magic_method_codes']:
                pars['magic_method_codes']+=":LP-TRM:DA-NL"
            pars['specimen_correction']='c' 

        else:
            GUI_log.write ("-W- WARNING: problematic NLT mesurements for specimens %s. Cant do NLT calculation. check data\n"%s)
            pars["NLT_specimen_correction_factor"]=-1
    else:
        pars["NLT_specimen_correction_factor"]=-1

    #-------------------------------------------------                    
    # Calculate the final result with cooling rate correction
    #-------------------------------------------------

    pars["specimen_int_corr_cooling_rate"]=-999
    if 'cooling_rate_data' in Data[s].keys():
        if 'CR_correction_factor' in Data[s]['cooling_rate_data'].keys():
            if Data[s]['cooling_rate_data']['CR_correction_factor'] != -1 and Data[s]['cooling_rate_data']['CR_correction_factor'] !=-999:
                pars["specimen_int_corr_cooling_rate"]=Data[s]['cooling_rate_data']['CR_correction_factor']
                pars['specimen_correction']='c'
                pars["specimen_int_uT"]=pars["specimen_int_uT"]*pars["specimen_int_corr_cooling_rate"]
                if ":DA-CR" not in pars['magic_method_codes']:
                    pars['magic_method_codes']+=":DA-CR"
                if   'CR_correction_factor_flag' in Data[s]['cooling_rate_data'].keys():
                    if Data[s]['cooling_rate_data']['CR_correction_factor_flag']=="calculated":
                        pars['CR_flag']="calculated"
                    else:
                        pars['CR_flag']=""
                if 'CR_correction_factor_flag' in Data[s]['cooling_rate_data'].keys() \
                    and Data[s]['cooling_rate_data']['CR_correction_factor_flag']!="calculated":
                    pars["CR_WARNING"]="inferred cooling rate correction"
                
            
    else:
        pars["CR_WARNING"]="no cooling rate correction"
        



    def combine_dictionaries(d1, d2):
        """
        combines dict1 and dict2 into a new dict.  
        if dict1 and dict2 share a key, the value from dict1 is used
        """
        for key, value in d2.iteritems():
            if key not in d1.keys():
                d1[key] = value
        return d1

    
    Data[s]['pars'] = pars
    #print pars.keys()

    return(pars)
Example #16
0
def main():
    """
    NAME
        aarm_magic.py

    DESCRIPTION
        Converts AARM  data to best-fit tensor (6 elements plus sigma)
         Original program ARMcrunch written to accomodate ARM anisotropy data
          collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the
          off-axis remanence terms to construct the tensor. A better way to
          do the anisotropy of ARMs is to use 9,12 or 15 measurements in
          the Hext rotational scheme.
    
    SYNTAX 
        aarm_magic.py [-h][command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f FILE: specify input file, default is aarm_measurements.txt
        -crd [s,g,t] specify coordinate system, requires er_samples.txt file
        -fsa  FILE: specify er_samples.txt file, default is er_samples.txt
        -Fa FILE: specify anisotropy output file, default is arm_anisotropy.txt
        -Fr FILE: specify results output file, default is aarm_results.txt

    INPUT  
        Input for the present program is a series of baseline, ARM pairs.
      The baseline should be the AF demagnetized state (3 axis demag is
      preferable) for the following ARM acquisition. The order of the
      measurements is:
    
           positions 1,2,3, 6,7,8, 11,12,13 (for 9 positions)
           positions 1,2,3,4, 6,7,8,9, 11,12,13,14 (for 12 positions)
           positions 1-15 (for 15 positions)
    """
    # initialize some parameters
    args=sys.argv
    user=""
    meas_file="aarm_measurements.txt"
    samp_file="er_samples.txt"
    rmag_anis="arm_anisotropy.txt"
    rmag_res="aarm_results.txt"
    dir_path='.'
    #
    # get name of file from command line
    #
    if '-WD' in args:
        ind=args.index('-WD')
        dir_path=args[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=sys.argv[ind+1]
    if "-f" in args:
        ind=args.index("-f")
        meas_file=sys.argv[ind+1]
    coord='-1'
    if "-crd" in sys.argv:
        ind=sys.argv.index("-crd")
        coord=sys.argv[ind+1]
        if coord=='s':coord='-1'
        if coord=='g':coord='0'
        if coord=='t':coord='100'
        if "-fsa" in args:
            ind=args.index("-fsa")
            samp_file=sys.argv[ind+1]
    if "-Fa" in args:
        ind=args.index("-Fa")
        rmag_anis=args[ind+1]
    if "-Fr" in args:
        ind=args.index("-Fr")
        rmag_res=args[ind+1]
    meas_file=dir_path+'/'+meas_file
    samp_file=dir_path+'/'+samp_file
    rmag_anis=dir_path+'/'+rmag_anis
    rmag_res=dir_path+'/'+rmag_res
    # read in data
    meas_data,file_type=pmag.magic_read(meas_file)
    meas_data=pmag.get_dictitem(meas_data,'magic_method_codes','LP-AN-ARM','has')
    if file_type != 'magic_measurements':
        print file_type
        print file_type,"This is not a valid magic_measurements file " 
        sys.exit()
    if coord!='-1': # need to read in sample data
        samp_data,file_type=pmag.magic_read(samp_file)
        if file_type != 'er_samples':
            print file_type
            print file_type,"This is not a valid er_samples file " 
            print "Only specimen coordinates will be calculated"
            coord='-1'
    #
    # sort the specimen names
    #
    ssort=[]
    for rec in meas_data:
      spec=rec["er_specimen_name"]
      if spec not in ssort: ssort.append(spec)
    if len(ssort)>1:
        sids=sorted(ssort)
    else:
        sids=ssort
    #
    # work on each specimen
    #
    specimen=0
    RmagSpecRecs,RmagResRecs=[],[]
    while specimen < len(sids):
        s=sids[specimen]
        data=[]
        RmagSpecRec={}
        RmagResRec={}
        method_codes=[]
    #
    # find the data from the meas_data file for this sample
    #
        data=pmag.get_dictitem(meas_data,'er_specimen_name',s,'T')
    #
    # find out the number of measurements (9, 12 or 15)
    #
        npos=len(data)/2
        if npos==9:
        #
        # get dec, inc, int and convert to x,y,z
        #
            B,H,tmpH=pmag.designAARM(npos)  # B matrix made from design matrix for positions
            X=[]
            for rec in data:
                Dir=[]
                Dir.append(float(rec["measurement_dec"]))
                Dir.append(float(rec["measurement_inc"]))
                Dir.append(float(rec["measurement_magn_moment"]))
                X.append(pmag.dir2cart(Dir))
        #
        # subtract baseline and put in a work array
        #
            work=numpy.zeros((npos,3),'f')
            for i in range(npos):
                for j in range(3):
                    work[i][j]=X[2*i+1][j]-X[2*i][j]
        #
        # calculate tensor elements
        # first put ARM components in w vector
        #
            w=numpy.zeros((npos*3),'f')
            index=0
            for i in range(npos):
                for j in range(3):
                    w[index]=work[i][j] 
                    index+=1
            s=numpy.zeros((6),'f') # initialize the s matrix
            for i in range(6):
                for j in range(len(w)):
                    s[i]+=B[i][j]*w[j] 
            trace=s[0]+s[1]+s[2]   # normalize by the trace
            for i in range(6):
                s[i]=s[i]/trace
            a=pmag.s2a(s)
        #------------------------------------------------------------
        #  Calculating dels is different than in the Kappabridge
        #  routine. Use trace normalized tensor (a) and the applied
        #  unit field directions (tmpH) to generate model X,Y,Z
        #  components. Then compare these with the measured values.
        #------------------------------------------------------------
            S=0.
            comp=numpy.zeros((npos*3),'f')
            for i in range(npos):
                for j in range(3):
                    index=i*3+j
                    compare=a[j][0]*tmpH[i][0]+a[j][1]*tmpH[i][1]+a[j][2]*tmpH[i][2]
                    comp[index]=compare
            for i in range(npos*3):
                d=w[i]/trace - comp[i] # del values
                S+=d*d
            nf=float(npos*3-6) # number of degrees of freedom
            if S >0: 
                sigma=numpy.sqrt(S/nf)
            else: sigma=0
            RmagSpecRec["rmag_anisotropy_name"]=data[0]["er_specimen_name"]
            RmagSpecRec["er_location_name"]=data[0]["er_location_name"]
            RmagSpecRec["er_specimen_name"]=data[0]["er_specimen_name"]
            RmagSpecRec["er_sample_name"]=data[0]["er_sample_name"]
            RmagSpecRec["er_site_name"]=data[0]["er_site_name"]
            RmagSpecRec["magic_experiment_names"]=RmagSpecRec["rmag_anisotropy_name"]+":AARM"
            RmagSpecRec["er_citation_names"]="This study"
            RmagResRec["rmag_result_name"]=data[0]["er_specimen_name"]+":AARM"
            RmagResRec["er_location_names"]=data[0]["er_location_name"]
            RmagResRec["er_specimen_names"]=data[0]["er_specimen_name"]
            RmagResRec["er_sample_names"]=data[0]["er_sample_name"]
            RmagResRec["er_site_names"]=data[0]["er_site_name"]
            RmagResRec["magic_experiment_names"]=RmagSpecRec["rmag_anisotropy_name"]+":AARM"
            RmagResRec["er_citation_names"]="This study"
            if "magic_instrument_codes" in data[0].keys():
                RmagSpecRec["magic_instrument_codes"]=data[0]["magic_instrument_codes"]
            else:  
                RmagSpecRec["magic_instrument_codes"]=""
            RmagSpecRec["anisotropy_type"]="AARM"
            RmagSpecRec["anisotropy_description"]="Hext statistics adapted to AARM"
            if coord!='-1': # need to rotate s
    # set orientation priorities
                SO_methods=[]
                for rec in samp_data:
                   if "magic_method_codes" not in rec:
                       rec['magic_method_codes']='SO-NO'
                   if "magic_method_codes" in rec:
                       methlist=rec["magic_method_codes"]
                       for meth in methlist.split(":"):
                           if "SO" in meth and "SO-POM" not in meth.strip():
                               if meth.strip() not in SO_methods: SO_methods.append(meth.strip())
                SO_priorities=pmag.set_priorities(SO_methods,0)
# continue here
                redo,p=1,0
                if len(SO_methods)<=1:
                    az_type=SO_methods[0]
                    orient=pmag.find_samp_rec(RmagSpecRec["er_sample_name"],samp_data,az_type)
                    if orient["sample_azimuth"]  !="": method_codes.append(az_type)
                    redo=0
                while redo==1:
                    if p>=len(SO_priorities):
                        print "no orientation data for ",s
                        orient["sample_azimuth"]=""
                        orient["sample_dip"]=""
                        method_codes.append("SO-NO")
                        redo=0
                    else:
                        az_type=SO_methods[SO_methods.index(SO_priorities[p])]
                        orient=pmag.find_samp_rec(PmagSpecRec["er_sample_name"],samp_data,az_type)
                        if orient["sample_azimuth"]  !="":
                            method_codes.append(az_type)
                            redo=0
                    p+=1
                az,pl=orient['sample_azimuth'],orient['sample_dip']
                s=pmag.dosgeo(s,az,pl) # rotate to geographic coordinates
                if coord=='100': 
                    sampe_bed_dir,sample_bed_dip=orient['sample_bed_dip_direction'],orient['sample_bed_dip']
                    s=pmag.dostilt(s,bed_dir,bed_dip) # rotate to geographic coordinates
            hpars=pmag.dohext(nf,sigma,s)
        #
        # prepare for output
        #
            RmagSpecRec["anisotropy_s1"]='%8.6f'%(s[0])
            RmagSpecRec["anisotropy_s2"]='%8.6f'%(s[1])
            RmagSpecRec["anisotropy_s3"]='%8.6f'%(s[2])
            RmagSpecRec["anisotropy_s4"]='%8.6f'%(s[3])
            RmagSpecRec["anisotropy_s5"]='%8.6f'%(s[4])
            RmagSpecRec["anisotropy_s6"]='%8.6f'%(s[5])
            RmagSpecRec["anisotropy_mean"]='%8.3e'%(trace/3)
            RmagSpecRec["anisotropy_sigma"]='%8.6f'%(sigma)
            RmagSpecRec["anisotropy_unit"]="Am^2"
            RmagSpecRec["anisotropy_n"]='%i'%(npos)
            RmagSpecRec["anisotropy_tilt_correction"]=coord
            RmagSpecRec["anisotropy_F"]='%7.1f '%(hpars["F"]) # used by thellier_gui - must be taken out for uploading
            RmagSpecRec["anisotropy_F_crit"]=hpars["F_crit"] # used by thellier_gui - must be taken out for uploading
            RmagResRec["anisotropy_t1"]='%8.6f '%(hpars["t1"])
            RmagResRec["anisotropy_t2"]='%8.6f '%(hpars["t2"])
            RmagResRec["anisotropy_t3"]='%8.6f '%(hpars["t3"])
            RmagResRec["anisotropy_v1_dec"]='%7.1f '%(hpars["v1_dec"])
            RmagResRec["anisotropy_v2_dec"]='%7.1f '%(hpars["v2_dec"])
            RmagResRec["anisotropy_v3_dec"]='%7.1f '%(hpars["v3_dec"])
            RmagResRec["anisotropy_v1_inc"]='%7.1f '%(hpars["v1_inc"])
            RmagResRec["anisotropy_v2_inc"]='%7.1f '%(hpars["v2_inc"])
            RmagResRec["anisotropy_v3_inc"]='%7.1f '%(hpars["v3_inc"])
            RmagResRec["anisotropy_ftest"]='%7.1f '%(hpars["F"])
            RmagResRec["anisotropy_ftest12"]='%7.1f '%(hpars["F12"])
            RmagResRec["anisotropy_ftest23"]='%7.1f '%(hpars["F23"])
            RmagResRec["result_description"]='Critical F: '+hpars["F_crit"]+';Critical F12/F13: '+hpars["F12_crit"]
            if hpars["e12"]>hpars["e13"]:
                RmagResRec["anisotropy_v1_zeta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v1_zeta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v1_zeta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v2_zeta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v1_eta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v1_eta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v1_eta_inc"]='%7.1f '%(hpars['v3_inc'])
                RmagResRec["anisotropy_v3_eta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_eta_inc"]='%7.1f '%(hpars['v1_inc'])
            else:
                RmagResRec["anisotropy_v1_zeta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v1_zeta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v1_zeta_inc"]='%7.1f '%(hpars['v3_inc'])
                RmagResRec["anisotropy_v3_zeta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v1_eta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v1_eta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v1_eta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v2_eta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_eta_inc"]='%7.1f '%(hpars['v1_inc'])
            if hpars["e23"]>hpars['e12']:
                RmagResRec["anisotropy_v2_zeta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v2_zeta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v2_zeta_inc"]='%7.1f '%(hpars['v3_inc'])
                RmagResRec["anisotropy_v3_zeta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v3_zeta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v3_zeta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v3_eta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_eta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v2_eta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_eta_inc"]='%7.1f '%(hpars['v1_inc'])
            else:
                RmagResRec["anisotropy_v2_zeta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v3_eta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v3_eta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v3_eta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v3_zeta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v2_eta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v2_eta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v2_eta_inc"]='%7.1f '%(hpars['v3_inc'])
            RmagResRec["tilt_correction"]='-1'
            RmagResRec["anisotropy_type"]='AARM'
            RmagResRec["magic_method_codes"]='LP-AN-ARM:AE-H'
            RmagSpecRec["magic_method_codes"]='LP-AN-ARM:AE-H'
            RmagResRec["magic_software_packages"]=pmag.get_version()
            RmagSpecRec["magic_software_packages"]=pmag.get_version()
            specimen+=1
            RmagSpecRecs.append(RmagSpecRec)
            RmagResRecs.append(RmagResRec)
        else:
            print 'skipping specimen ',s,' only 9 positions supported','; this has ',npos
            specimen+=1
    if rmag_anis=="":rmag_anis="rmag_anisotropy.txt"
    pmag.magic_write(rmag_anis,RmagSpecRecs,'rmag_anisotropy')
    print "specimen tensor elements stored in ",rmag_anis
    if rmag_res=="":rmag_res="rmag_results.txt"
    pmag.magic_write(rmag_res,RmagResRecs,'rmag_results')
    print "specimen statistics and eigenparameters stored in ",rmag_res
Example #17
0
def main():
    """
    NAME
        aarm_magic.py

    DESCRIPTION
        Converts AARM  data to best-fit tensor (6 elements plus sigma)
         Original program ARMcrunch written to accomodate ARM anisotropy data
          collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the
          off-axis remanence terms to construct the tensor. A better way to
          do the anisotropy of ARMs is to use 9,12 or 15 measurements in
          the Hext rotational scheme.
    
    SYNTAX 
        aarm_magic.py [-h][command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f FILE: specify input file, default is aarm_measurements.txt
        -Fa FILE: specify anisotropy output file, default is rmag_anisotropy.txt
        -Fr FILE: specify results output file, default is rmag_results.txt

    INPUT  
        Input for the present program is a series of baseline, ARM pairs.
      The baseline should be the AF demagnetized state (3 axis demag is
      preferable) for the following ARM acquisition. The order of the
      measurements is:
    
           positions 1,2,3, 6,7,8, 11,12,13 (for 9 positions)
           positions 1,2,3,4, 6,7,8,9, 11,12,13,14 (for 12 positions)
           positions 1-15 (for 15 positions)
    """
    # initialize some parameters
    args=sys.argv
    user=""
    meas_file="aarm_measurements.txt"
    rmag_anis="rmag_anisotropy.txt"
    rmag_res="rmag_results.txt"
    dir_path='.'
    #
    # get name of file from command line
    #
    if '-WD' in args:
        ind=args.index('-WD')
        dir_path=args[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=sys.argv[ind+1]
    if "-f" in args:
        ind=args.index("-f")
        meas_file=sys.argv[ind+1]
    if "-Fa" in args:
        ind=args.index("-Fa")
        rmag_anis=args[ind+1]
    if "-Fr" in args:
        ind=args.index("-Fr")
        rmag_res=args[ind+1]
    meas_file=dir_path+'/'+meas_file
    rmag_anis=dir_path+'/'+rmag_anis
    rmag_res=dir_path+'/'+rmag_res
    # read in data
    meas_data,file_type=pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print file_type
        print file_type,"This is not a valid magic_measurements file " 
        sys.exit()
    #
    # sort the specimen names
    #
    ssort=[]
    for rec in meas_data:
      spec=rec["er_specimen_name"]
      ssort.append(spec)
    ssort.sort()
    bak=ssort[0]
    #
    # get list of unique specimen names
    #
    sids=[bak]
    for s in ssort:
       if s !=  bak: 
          sids.append(s)
          bak=s
    #
    # work on each specimen
    #
    specimen=0
    RmagSpecRecs,RmagResRecs=[],[]
    while specimen < len(sids):
        s=sids[specimen]
        data=[]
        RmagSpecRec={}
        RmagResRec={}
        method_codes=[]
    #
    # find the data from the meas_data file for this sample
    #
        for rec in meas_data:
            if rec["er_specimen_name"]==s: 
                data.append(rec)
    #
    # find out the number of measurements (9, 12 or 15)
    #
        npos=len(data)/2
        if npos==9:
            print 'Processing: ',s, ' Number of positions: ',npos
        #
        # get dec, inc, int and convert to x,y,z
        #
            B,H,tmpH=pmag.designAARM(npos)  # B matrix made from design matrix for positions
            X=[]
            for rec in data:
                Dir=[]
                Dir.append(float(rec["measurement_dec"]))
                Dir.append(float(rec["measurement_inc"]))
                Dir.append(float(rec["measurement_magn_moment"]))
                X.append(pmag.dir2cart(Dir))
        #
        # subtract baseline and put in a work array
        #
            work=numpy.zeros((npos,3),'f')
            for i in range(npos):
                for j in range(3):
                    work[i][j]=X[2*i+1][j]-X[2*i][j]
        #
        # calculate tensor elements
        # first put ARM components in w vector
        #
            w=numpy.zeros((npos*3),'f')
            index=0
            for i in range(npos):
                for j in range(3):
                    w[index]=work[i][j] 
                    index+=1
            s=numpy.zeros((6),'f') # initialize the s matrix
            for i in range(6):
                for j in range(len(w)):
                    s[i]+=B[i][j]*w[j] 
            trace=s[0]+s[1]+s[2]   # normalize by the trace
            for i in range(6):
                s[i]=s[i]/trace
            a=pmag.s2a(s)
        #------------------------------------------------------------
        #  Calculating dels is different than in the Kappabridge
        #  routine. Use trace normalized tensor (a) and the applied
        #  unit field directions (tmpH) to generate model X,Y,Z
        #  components. Then compare these with the measured values.
        #------------------------------------------------------------
            S=0.
            comp=numpy.zeros((npos*3),'f')
            for i in range(npos):
                for j in range(3):
                    index=i*3+j
                    compare=a[j][0]*tmpH[i][0]+a[j][1]*tmpH[i][1]+a[j][2]*tmpH[i][2]
                    comp[index]=compare
            for i in range(npos*3):
                d=w[i]/trace - comp[i] # del values
                S+=d*d
            nf=float(npos*3-6) # number of degrees of freedom
            if S >0: 
                sigma=math.sqrt(S/nf)
            else: sigma=0
            hpars=pmag.dohext(nf,sigma,s)
        #
        # prepare for output
        #
            RmagSpecRec["rmag_anisotropy_name"]=data[0]["er_specimen_name"]
            RmagSpecRec["er_location_name"]=data[0]["er_location_name"]
            RmagSpecRec["er_specimen_name"]=data[0]["er_specimen_name"]
            RmagSpecRec["er_sample_name"]=data[0]["er_sample_name"]
            RmagSpecRec["er_site_name"]=data[0]["er_site_name"]
            RmagSpecRec["magic_experiment_names"]=RmagSpecRec["rmag_anisotropy_name"]+":AARM"
            RmagSpecRec["er_citation_names"]="This study"
            RmagResRec["rmag_result_name"]=data[0]["er_specimen_name"]
            RmagResRec["er_location_names"]=data[0]["er_location_name"]
            RmagResRec["er_specimen_names"]=data[0]["er_specimen_name"]
            RmagResRec["er_sample_names"]=data[0]["er_sample_name"]
            RmagResRec["er_site_names"]=data[0]["er_site_name"]
            RmagResRec["magic_experiment_names"]=RmagSpecRec["rmag_anisotropy_name"]+":AARM"
            RmagResRec["er_citation_names"]="This study"
            if "magic_instrument_codes" in data[0].keys():
                RmagSpecRec["magic_instrument_codes"]=data[0]["magic_instrument_codes"]
            else:  
                RmagSpecRec["magic_instrument_codes"]=""
            RmagSpecRec["anisotropy_type"]="AARM"
            RmagSpecRec["anisotropy_description"]="Hext statistics adapted to AARM"
            RmagSpecRec["anisotropy_s1"]='%8.6f'%(s[0])
            RmagSpecRec["anisotropy_s2"]='%8.6f'%(s[1])
            RmagSpecRec["anisotropy_s3"]='%8.6f'%(s[2])
            RmagSpecRec["anisotropy_s4"]='%8.6f'%(s[3])
            RmagSpecRec["anisotropy_s5"]='%8.6f'%(s[4])
            RmagSpecRec["anisotropy_s6"]='%8.6f'%(s[5])
            RmagSpecRec["anisotropy_mean"]='%8.3e'%(trace/3)
            RmagSpecRec["anisotropy_sigma"]='%8.6f'%(sigma)
            RmagSpecRec["anisotropy_unit"]="Am^2"
            RmagSpecRec["anisotropy_n"]='%i'%(npos)
            RmagSpecRec["anisotropy_tilt_correction"]='-1'
            RmagResRec["anisotropy_t1"]='%8.6f '%(hpars["t1"])
            RmagResRec["anisotropy_t2"]='%8.6f '%(hpars["t2"])
            RmagResRec["anisotropy_t3"]='%8.6f '%(hpars["t3"])
            RmagResRec["anisotropy_v1_dec"]='%7.1f '%(hpars["v1_dec"])
            RmagResRec["anisotropy_v2_dec"]='%7.1f '%(hpars["v2_dec"])
            RmagResRec["anisotropy_v3_dec"]='%7.1f '%(hpars["v3_dec"])
            RmagResRec["anisotropy_v1_inc"]='%7.1f '%(hpars["v1_inc"])
            RmagResRec["anisotropy_v2_inc"]='%7.1f '%(hpars["v2_inc"])
            RmagResRec["anisotropy_v3_inc"]='%7.1f '%(hpars["v3_inc"])
            RmagResRec["anisotropy_ftest"]='%7.1f '%(hpars["F"])
            RmagResRec["anisotropy_ftest12"]='%7.1f '%(hpars["F12"])
            RmagResRec["anisotropy_ftest23"]='%7.1f '%(hpars["F23"])
            if hpars["e12"]>hpars["e13"]:
                RmagResRec["anisotropy_v1_zeta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v1_zeta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v1_zeta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v2_zeta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v1_eta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v1_eta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v1_eta_inc"]='%7.1f '%(hpars['v3_inc'])
                RmagResRec["anisotropy_v3_eta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_eta_inc"]='%7.1f '%(hpars['v1_inc'])
            else:
                RmagResRec["anisotropy_v1_zeta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v1_zeta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v1_zeta_inc"]='%7.1f '%(hpars['v3_inc'])
                RmagResRec["anisotropy_v3_zeta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v1_eta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v1_eta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v1_eta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v2_eta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_eta_inc"]='%7.1f '%(hpars['v1_inc'])
            if hpars["e23"]>hpars['e12']:
                RmagResRec["anisotropy_v2_zeta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v2_zeta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v2_zeta_inc"]='%7.1f '%(hpars['v3_inc'])
                RmagResRec["anisotropy_v3_zeta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v3_zeta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v3_zeta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v3_eta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_eta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v2_eta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_eta_inc"]='%7.1f '%(hpars['v1_inc'])
            else:
                RmagResRec["anisotropy_v2_zeta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v3_eta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v3_eta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v3_eta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v3_zeta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v2_eta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v2_eta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v2_eta_inc"]='%7.1f '%(hpars['v3_inc'])
            RmagResRec["tilt_correction"]='-1'
            RmagResRec["anisotropy_type"]='AARM'
            RmagResRec["magic_method_codes"]='LP-AN-ARM:AE-H'
            RmagSpecRec["magic_method_codes"]='LP-AN-ARM:AE-H'
            RmagResRec["magic_software_packages"]=pmag.get_version()
            RmagSpecRec["magic_software_packages"]=pmag.get_version()
            specimen+=1
            RmagSpecRecs.append(RmagSpecRec)
            RmagResRecs.append(RmagResRec)
        else:
            print npos
            print 'skipping specimen ',s,' only 9 positions supported'
            specimen+=1
    if rmag_anis=="":rmag_anis="rmag_anisotropy.txt"
    pmag.magic_write(rmag_anis,RmagSpecRecs,'rmag_anisotropy')
    print "specimen tensor elements stored in ",rmag_anis
    if rmag_res=="":rmag_res="rmag_results.txt"
    pmag.magic_write(rmag_res,RmagResRecs,'rmag_results')
    print "specimen statistics and eigenparameters stored in ",rmag_res
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 #19
0
def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX 
        lowrie -h [command line options]
    
    INPUT 
       takes magic_measurements formatted input files
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is magic_measurements.txt
        -N do not normalize by maximum magnetization
        -fmt [svg, pdf, eps, png] specify fmt, default is svg
    """
    fmt='svg'
    FIG={} # plot dictionary
    FIG['lowrie']=1 # demag is figure 1
    pmagplotlib.plot_init(FIG['lowrie'],6,6)
    norm=1 # default is to normalize by maximum axis
    in_file,dir_path='magic_measurements.txt','.'
    if len(sys.argv)>1:
        if '-WD' in sys.argv:
            ind=sys.argv.index('-WD')
            dir_path=sys.argv[ind+1]
        if '-h' in sys.argv:
            print main.__doc__
            sys.exit()
        if '-N' in sys.argv: norm=0 # don't normalize
        if '-f' in sys.argv: # sets input filename
            ind=sys.argv.index("-f")
            in_file=sys.argv[ind+1]
    else:
        print main.__doc__
        print 'you must supply a file name'
        sys.exit() 
    in_file=dir_path+'/'+in_file
    print in_file
    PmagRecs,file_type=pmag.magic_read(in_file)
    if file_type!="magic_measurements":
         print 'bad input file'
         sys.exit()
    PmagRecs=pmag.get_dictitem(PmagRecs,'magic_method_codes','LP-IRM-3D','has') # get all 3D IRM records
    if len(PmagRecs)==0:
        print 'no records found'
        sys.exit()
    specs=pmag.get_dictkey(PmagRecs,'er_specimen_name','')
    sids=[]
    for spec in specs:
        if spec not in sids:sids.append(spec) # get list of unique specimen names
    for spc in sids:  # step through the specimen names
        print spc
        specdata=pmag.get_dictitem(PmagRecs,'er_specimen_name',spc,'T') # get all this one's data
        DIMs,Temps=[],[]
        for dat in specdata: # step through the data
            DIMs.append([float(dat['measurement_dec']),float(dat['measurement_inc']),float(dat['measurement_magn_moment'])])
            Temps.append(float(dat['treatment_temp'])-273.)
        carts=pmag.dir2cart(DIMs).transpose()
        if norm==1: # want to normalize
            nrm=(DIMs[0][2]) # normalize by NRM
            ylab="M/M_o"
        else: 
            nrm=1. # don't normalize
            ylab="Magnetic moment (Am^2)"
        xlab="Temperature (C)"
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[0])/nrm,sym='r-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[0])/nrm,sym='ro') # X direction
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[1])/nrm,sym='c-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[1])/nrm,sym='cs') # Y direction
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[2])/nrm,sym='k-')
        pmagplotlib.plotXY(FIG['lowrie'],Temps,abs(carts[2])/nrm,sym='k^',title=spc,xlab=xlab,ylab=ylab) # Z direction
        pmagplotlib.drawFIGS(FIG)
        ans=raw_input('S[a]ve figure? [q]uit, <return> to continue   ')
        if ans=='a':
            files={'lowrie':'lowrie:_'+spc+'_.'+fmt}
            pmagplotlib.saveP(FIG,files)
        elif ans=='q':
            sys.exit()
        pmagplotlib.clearFIG(FIG['lowrie'])
Example #20
0
def plotELL(pars,col,lower,plot):
    """
    function to calculate points on an ellipse about Pdec,Pdip with angle beta,gamma
    """
    rad=np.pi/180.
    Pdec,Pinc,beta,Bdec,Binc,gamma,Gdec,Ginc=pars[0],pars[1],pars[2],pars[3],pars[4],pars[5],pars[6],pars[7]
    if beta > 90. or gamma>90:
        beta=180.-beta
        gamma=180.-beta
        Pdec=Pdec-180.
        Pinc=-Pinc
    beta,gamma=beta*rad,gamma*rad # convert to radians
    X_ell,Y_ell,X_up,Y_up,PTS=[],[],[],[],[]
    nums=201
    xnum=float(nums-1.)/2.
# set up t matrix
    t=[[0,0,0],[0,0,0],[0,0,0]]
    X=pmag.dir2cart((Pdec,Pinc,1.0)) # convert to cartesian coordintes
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
# set up rotation matrix t
    t[0][2]=X[0]
    t[1][2]=X[1]
    t[2][2]=X[2]
    X=pmag.dir2cart((Bdec,Binc,1.0))
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
    t[0][0]=X[0]
    t[1][0]=X[1]
    t[2][0]=X[2]
    X=pmag.dir2cart((Gdec,Ginc,1.0))
    if lower==1 and X[2]<0:
       for i in range(3):
           X[i]=-X[i]
    t[0][1]=X[0]
    t[1][1]=X[1]
    t[2][1]=X[2]
# set up v matrix
    v=[0,0,0]
    for i in range(nums):  # incremental point along ellipse
        psi=float(i)*np.pi/xnum
        v[0]=np.sin(beta)*np.cos(psi)
        v[1]=np.sin(gamma)*np.sin(psi)
        v[2]=np.sqrt(1.-v[0]**2 - v[1]**2)
        elli=[0,0,0]
# calculate points on the ellipse
        for j in range(3):
            for k in range(3):
                elli[j]=elli[j] + t[j][k]*v[k]  # cartesian coordinate j of ellipse
        PTS.append(pmag.cart2dir(elli))
        R=np.sqrt( 1.-abs(elli[2]))/(np.sqrt(elli[0]**2+elli[1]**2)) # put on an equal area projection
        if elli[2]<0:
#            for i in range(3): elli[i]=-elli[i]
            X_up.append(elli[1]*R)
            Y_up.append(elli[0]*R)
            # Adding None values stops plotting of an additional straight line 
            # between the points where the ellipse crosses the edge of the stereonet
            X_ell.append(None)
            Y_ell.append(None)            
        else:
            X_ell.append(elli[1]*R)
            Y_ell.append(elli[0]*R)
    if plot==1:
        if X_ell!=[]:plt.plot(X_ell,Y_ell,color=col, linewidth=2, zorder=6)
        if X_up!=[]:plt.plot(X_up,Y_up,color=col,linewidth=2,linestyle=':')
    else:
        return PTS
def bootstrap_common_mean(Data1, Data2, NumSims=1000):
    """
    Conduct a bootstrap test (Tauxe, 2010) for a common mean on two declination,
    inclination data sets
    
    This function modifies code from PmagPy for use calculating and plotting 
    bootstrap statistics. Three plots are generated (one for x, one for y and
    one for z). If the 95 percent confidence bounds for each component overlap
    each other, the two directions are not significantly different.

    Arguments
    ----------
    Data1 : a list of directional data [dec,inc]
    Data2 : a list of directional data [dec,inc]
    NumSims : number of bootstrap samples (default is 1000)
    """
    counter = 0
    BDI1 = pmag.di_boot(Data1)
    BDI2 = pmag.di_boot(Data2)

    cart1 = pmag.dir2cart(BDI1).transpose()
    X1, Y1, Z1 = cart1[0], cart1[1], cart1[2]
    cart2 = pmag.dir2cart(BDI2).transpose()
    X2, Y2, Z2 = cart2[0], cart2[1], cart2[2]

    print "Here are the results of the bootstrap test for a common mean:"

    fignum = 1
    fig = plt.figure(figsize=(9, 3))
    fig = plt.subplot(1, 3, 1)

    minimum = int(0.025 * len(X1))
    maximum = int(0.975 * len(X1))

    X1, y = pmagplotlib.plotCDF(fignum, X1, "X component", 'r', "")
    bounds1 = [X1[minimum], X1[maximum]]
    pmagplotlib.plotVs(fignum, bounds1, 'r', '-')

    X2, y = pmagplotlib.plotCDF(fignum, X2, "X component", 'b', "")
    bounds2 = [X2[minimum], X2[maximum]]
    pmagplotlib.plotVs(fignum, bounds2, 'b', '--')
    plt.ylim(0, 1)

    plt.subplot(1, 3, 2)

    Y1, y = pmagplotlib.plotCDF(fignum, Y1, "Y component", 'r', "")
    bounds1 = [Y1[minimum], Y1[maximum]]
    pmagplotlib.plotVs(fignum, bounds1, 'r', '-')

    Y2, y = pmagplotlib.plotCDF(fignum, Y2, "Y component", 'b', "")
    bounds2 = [Y2[minimum], Y2[maximum]]
    pmagplotlib.plotVs(fignum, bounds2, 'b', '--')
    plt.ylim(0, 1)

    plt.subplot(1, 3, 3)

    Z1, y = pmagplotlib.plotCDF(fignum, Z1, "Z component", 'r', "")
    bounds1 = [Z1[minimum], Z1[maximum]]
    pmagplotlib.plotVs(fignum, bounds1, 'r', '-')

    Z2, y = pmagplotlib.plotCDF(fignum, Z2, "Z component", 'b', "")
    bounds2 = [Z2[minimum], Z2[maximum]]
    pmagplotlib.plotVs(fignum, bounds2, 'b', '--')
    plt.ylim(0, 1)

    plt.tight_layout()
    plt.show()
Example #22
0
 def average_duplicates(duplicates):
     '''
     avarage replicate measurements.
     '''
     carts_s,carts_g,carts_t=[],[],[]   
     for rec in duplicates:
         moment=float(rec['moment'])
         if 'dec_s' in rec.keys() and 'inc_s' in rec.keys():
             if rec['dec_s']!="" and rec['inc_s']!="":
                 dec_s=float(rec['dec_s'])
                 inc_s=float(rec['inc_s'])
                 cart_s=pmag.dir2cart([dec_s,inc_s,moment])
                 carts_s.append(cart_s)
         if 'dec_g' in rec.keys() and 'inc_g' in rec.keys():
             if rec['dec_g']!="" and rec['inc_g']!="":
                 dec_g=float(rec['dec_g'])
                 inc_g=float(rec['inc_g'])
                 cart_g=pmag.dir2cart([dec_g,inc_g,moment])
                 carts_g.append(cart_g)
         if 'dec_t' in rec.keys() and 'inc_t' in rec.keys():
             if rec['dec_t']!="" and rec['inc_t']!="":
                 dec_t=float(rec['dec_t'])
                 inc_t=float(rec['inc_t'])
                 cart_t=pmag.dir2cart([dec_t,inc_t,moment])
                 carts_t.append(cart_t)
     if len(carts_s)>0:                               
         carts=scipy.array(carts_s)
         x_mean=scipy.mean(carts[:,0])
         y_mean=scipy.mean(carts[:,1])
         z_mean=scipy.mean(carts[:,2])
         mean_dir=pmag.cart2dir([x_mean,y_mean,z_mean])
         mean_dec_s="%.2f"%mean_dir[0]
         mean_inc_s="%.2f"%mean_dir[1]
         mean_moment="%10.3e"%mean_dir[2]
     else:
         mean_dec_s,mean_inc_s="",""
     if len(carts_g)>0:                               
         carts=scipy.array(carts_g)
         x_mean=scipy.mean(carts[:,0])
         y_mean=scipy.mean(carts[:,1])
         z_mean=scipy.mean(carts[:,2])
         mean_dir=pmag.cart2dir([x_mean,y_mean,z_mean])
         mean_dec_g="%.2f"%mean_dir[0]
         mean_inc_g="%.2f"%mean_dir[1]
         mean_moment="%10.3e"%mean_dir[2]
     else:
         mean_dec_g,mean_inc_g="",""
         
     if len(carts_t)>0:                               
         carts=scipy.array(carts_t)
         x_mean=scipy.mean(carts[:,0])
         y_mean=scipy.mean(carts[:,1])
         z_mean=scipy.mean(carts[:,2])
         mean_dir=pmag.cart2dir([x_mean,y_mean,z_mean])
         mean_dec_t="%.2f"%mean_dir[0]
         mean_inc_t="%.2f"%mean_dir[1]
         mean_moment="%10.3e"%mean_dir[2]
     else:
         mean_dec_t,mean_inc_t="",""
                                                                     
     meanrec={}
     for key in duplicates[0].keys():
         if key in ['dec_s','inc_s','dec_g','inc_g','dec_t','inc_t','moment']:
             continue
         else:
             meanrec[key]=duplicates[0][key]
     meanrec['dec_s']=mean_dec_s
     meanrec['dec_g']=mean_dec_g
     meanrec['dec_t']=mean_dec_t
     meanrec['inc_s']=mean_inc_s
     meanrec['inc_g']=mean_inc_g
     meanrec['inc_t']=mean_inc_t
     meanrec['moment']=mean_moment
     return meanrec
def 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 #24
0
def main():
    """
    NAME
        dir_cart.py
    
    DESCRIPTION
      converts geomagnetic elements to cartesian coordinates
    
    INPUT (COMMAND LINE ENTRY) 
           declination inclination [magnitude]
          or
           longitude latitude
        if only two columns, assumes magnitude of unity
    OUTPUT
           x1 x2  x3
    
    SYNTAX
        dir_cart.py [command line options] [< filename]
    
    OPTIONS
        -h print help and quit
        -i for interactive data entry
        -f FILE, input file
        -F FILE, output file
    
    """
    out=""
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        ofile=sys.argv[ind+1]  
        out=open(ofile,'w')
    if '-i' in sys.argv:
        cont=1
        while cont==1:
            try:
                dir=[]
                ans=raw_input('Declination: [cntrl-D  to quit] ')
                dir.append(float(ans))
                ans=raw_input('Inclination: ')
                dir.append(float(ans))
                ans=raw_input('Intensity [return for unity]: ')
                if ans=='':ans='1'
                dir.append(float(ans))
                cart= pmag.dir2cart(dir)  # send dir to dir2cart and spit out result
                print '%8.4e %8.4e %8.4e'%(cart[0],cart[1],cart[2])
            except:
                print '\n Good-bye \n'
                sys.exit()
    elif '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]  
        input=numpy.loadtxt(file)
    else:
        input=numpy.loadtxt(sys.stdin,dtype=numpy.float)
    cart= pmag.dir2cart(input)
    if len(cart.shape)==1:
        line=cart
        print '%8.4e %8.4e %8.4e'%(line[0],line[1],line[2])
        if out!="":out.write('%8.4e %8.4e %8.4e\n'%(line[0],line[1],line[2]))
    else:
        for line in cart:
            print '%8.4e %8.4e %8.4e'%(line[0],line[1],line[2])
            if out!="":out.write('%8.4e %8.4e %8.4e\n'%(line[0],line[1],line[2]))
Example #25
0
def main():
    """
    NAME
        atrm_magic.py

    DESCRIPTION
        Converts ATRM  data to best-fit tensor (6 elements plus sigma)
         Original program ARMcrunch written to accomodate ARM anisotropy data
          collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the
          off-axis remanence terms to construct the tensor. A better way to
          do the anisotropy of ARMs is to use 9,12 or 15 measurements in
          the Hext rotational scheme.
    
    SYNTAX 
        atrm_magic.py [-h][command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f FILE: specify input file, default is atrm_measurements.txt
        -Fa FILE: specify anisotropy output file, default is trm_anisotropy.txt
        -Fr FILE: specify results output file, default is atrm_results.txt

    INPUT  
        Input for the present program is a TRM acquisition data with an optional baseline.
      The order of the measurements is:
    Decs=[0,90,0,180,270,0,0,90,0]
    Incs=[0,0,90,0,0,-90,0,0,90]
     The last two measurements are optional
    
    """
    # initialize some parameters
    args=sys.argv
    user=""
    meas_file="atrm_measurements.txt"
    rmag_anis="trm_anisotropy.txt"
    rmag_res="atrm_results.txt"
    dir_path='.'
    #
    # get name of file from command line
    #
    if '-WD' in args:
        ind=args.index('-WD')
        dir_path=args[ind+1]
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-usr" in args:
        ind=args.index("-usr")
        user=sys.argv[ind+1]
    if "-f" in args:
        ind=args.index("-f")
        meas_file=sys.argv[ind+1]
    if "-Fa" in args:
        ind=args.index("-Fa")
        rmag_anis=args[ind+1]
    if "-Fr" in args:
        ind=args.index("-Fr")
        rmag_res=args[ind+1]
    meas_file=dir_path+'/'+meas_file
    rmag_anis=dir_path+'/'+rmag_anis
    rmag_res=dir_path+'/'+rmag_res
    # read in data
    meas_data,file_type=pmag.magic_read(meas_file)
    meas_data=pmag.get_dictitem(meas_data,'magic_method_codes','LP-AN-TRM','has')
    if file_type != 'magic_measurements':
        print file_type
        print file_type,"This is not a valid magic_measurements file " 
        sys.exit()
    #
    #
    # get sorted list of unique specimen names
    ssort=[]
    for rec in meas_data:
      spec=rec["er_specimen_name"]
      if spec not in ssort:ssort.append(spec)
    sids=sorted(ssort)
    #
    #
    # work on each specimen
    #
    specimen,npos=0,6
    RmagSpecRecs,RmagResRecs=[],[]
    while specimen < len(sids):
        nmeas=0 
        s=sids[specimen]
        RmagSpecRec={}
        RmagResRec={}
        BX,X=[],[]
        method_codes=[]
        Spec0=""
    #
    # find the data from the meas_data file for this sample
        # and get dec, inc, int and convert to x,y,z
        #
        data=pmag.get_dictitem(meas_data,'er_specimen_name',s,'T') # fish out data for this specimen name
        if len(data)>5:
            RmagSpecRec["rmag_anisotropy_name"]=data[0]["er_specimen_name"]
            RmagSpecRec["er_location_name"]=data[0]["er_location_name"]
            RmagSpecRec["er_specimen_name"]=data[0]["er_specimen_name"]
            RmagSpecRec["er_sample_name"]=data[0]["er_sample_name"]
            RmagSpecRec["er_site_name"]=data[0]["er_site_name"]
            RmagSpecRec["magic_experiment_names"]=RmagSpecRec["rmag_anisotropy_name"]+":ATRM"
            RmagSpecRec["er_citation_names"]="This study"
            RmagResRec["rmag_result_name"]=data[0]["er_specimen_name"]+":ATRM"
            RmagResRec["er_location_names"]=data[0]["er_location_name"]
            RmagResRec["er_specimen_names"]=data[0]["er_specimen_name"]
            RmagResRec["er_sample_names"]=data[0]["er_sample_name"]
            RmagResRec["er_site_names"]=data[0]["er_site_name"]
            RmagResRec["magic_experiment_names"]=RmagSpecRec["rmag_anisotropy_name"]+":ATRM"
            RmagResRec["er_citation_names"]="This study"
            RmagSpecRec["anisotropy_type"]="ATRM"
            if "magic_instrument_codes" in data[0].keys():
                RmagSpecRec["magic_instrument_codes"]=data[0]["magic_instrument_codes"]
            else:  
                RmagSpecRec["magic_instrument_codes"]=""
                RmagSpecRec["anisotropy_description"]="Hext statistics adapted to ATRM"
            for rec in data:
                meths=rec['magic_method_codes'].strip().split(':')
                Dir=[]
                Dir.append(float(rec["measurement_dec"]))
                Dir.append(float(rec["measurement_inc"]))
                Dir.append(float(rec["measurement_magn_moment"]))
                if "LT-T-Z" in meths:
                    BX.append(pmag.dir2cart(Dir)) # append baseline steps
                elif "LT-T-I" in meths: 
                    X.append(pmag.dir2cart(Dir))
                    nmeas+=1
    #
        if len(BX)==1:
            for i in range(len(X)-1):BX.append(BX[0]) # assume first 0 field step as baseline
        elif len(BX)== 0: # assume baseline is zero
            for i in range(len(X)):BX.append([0.,0.,0.]) # assume baseline of 0
        elif len(BX)!= len(X): # if BX isn't just one measurement or one in between every infield step, just assume it is zero
            print 'something odd about the baselines - just assuming zero'
            for i in range(len(X)):BX.append([0.,0.,0.]) # assume baseline of 0
        if nmeas<6: # must have at least 6 measurements right now - 
            print 'skipping specimen ',s,' too few measurements'
            specimen+=1
        else:
            B,H,tmpH=pmag.designATRM(npos)  # B matrix made from design matrix for positions
        #
        # subtract optional baseline and put in a work array
        #
            work=numpy.zeros((nmeas,3),'f')
            for i in range(nmeas):
                for j in range(3):
                    work[i][j]=X[i][j]-BX[i][j] # subtract baseline, if available
        #
        # calculate tensor elements
        # first put ARM components in w vector
        #
            w=numpy.zeros((npos*3),'f')
            index=0
            for i in range(npos):
                for j in range(3):
                    w[index]=work[i][j] 
                    index+=1
            s=numpy.zeros((6),'f') # initialize the s matrix
            for i in range(6):
                for j in range(len(w)):
                    s[i]+=B[i][j]*w[j] 
            trace=s[0]+s[1]+s[2]   # normalize by the trace
            for i in range(6):
                s[i]=s[i]/trace
            a=pmag.s2a(s)
            
        #------------------------------------------------------------
        #  Calculating dels is different than in the Kappabridge
        #  routine. Use trace normalized tensor (a) and the applied
        #  unit field directions (tmpH) to generate model X,Y,Z
        #  components. Then compare these with the measured values.
        #------------------------------------------------------------
            S=0.
            comp=numpy.zeros((npos*3),'f')
            for i in range(npos):
                for j in range(3):
                    index=i*3+j
                    compare=a[j][0]*tmpH[i][0]+a[j][1]*tmpH[i][1]+a[j][2]*tmpH[i][2]
                    comp[index]=compare
            for i in range(npos*3):
                d=w[i]/trace - comp[i] # del values
                S+=d*d
            nf=float(npos*3.-6.) # number of degrees of freedom
            if S >0: 
                sigma=numpy.sqrt(S/nf)
            else: sigma=0
            hpars=pmag.dohext(nf,sigma,s)
        #
        # prepare for output
        #
            RmagSpecRec["anisotropy_s1"]='%8.6f'%(s[0])
            RmagSpecRec["anisotropy_s2"]='%8.6f'%(s[1])
            RmagSpecRec["anisotropy_s3"]='%8.6f'%(s[2])
            RmagSpecRec["anisotropy_s4"]='%8.6f'%(s[3])
            RmagSpecRec["anisotropy_s5"]='%8.6f'%(s[4])
            RmagSpecRec["anisotropy_s6"]='%8.6f'%(s[5])
            RmagSpecRec["anisotropy_mean"]='%8.3e'%(trace/3)
            RmagSpecRec["anisotropy_sigma"]='%8.6f'%(sigma)
            RmagSpecRec["anisotropy_unit"]="Am^2"
            RmagSpecRec["anisotropy_n"]='%i'%(npos)
            RmagSpecRec["anisotropy_tilt_correction"]='-1'
            RmagSpecRec["anisotropy_F"]='%7.1f '%(hpars["F"]) # used by thellier_gui - must be taken out for uploading
            RmagSpecRec["anisotropy_F_crit"]=hpars["F_crit"] # used by thellier_gui - must be taken out for uploading
            RmagResRec["anisotropy_t1"]='%8.6f '%(hpars["t1"])
            RmagResRec["anisotropy_t2"]='%8.6f '%(hpars["t2"])
            RmagResRec["anisotropy_t3"]='%8.6f '%(hpars["t3"])
            RmagResRec["anisotropy_v1_dec"]='%7.1f '%(hpars["v1_dec"])
            RmagResRec["anisotropy_v2_dec"]='%7.1f '%(hpars["v2_dec"])
            RmagResRec["anisotropy_v3_dec"]='%7.1f '%(hpars["v3_dec"])
            RmagResRec["anisotropy_v1_inc"]='%7.1f '%(hpars["v1_inc"])
            RmagResRec["anisotropy_v2_inc"]='%7.1f '%(hpars["v2_inc"])
            RmagResRec["anisotropy_v3_inc"]='%7.1f '%(hpars["v3_inc"])
            RmagResRec["anisotropy_ftest"]='%7.1f '%(hpars["F"])
            RmagResRec["anisotropy_ftest12"]='%7.1f '%(hpars["F12"])
            RmagResRec["anisotropy_ftest23"]='%7.1f '%(hpars["F23"])
            RmagResRec["result_description"]='Critical F: '+hpars["F_crit"]+';Critical F12/F13: '+hpars["F12_crit"]
            if hpars["e12"]>hpars["e13"]:
                RmagResRec["anisotropy_v1_zeta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v1_zeta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v1_zeta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v2_zeta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v1_eta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v1_eta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v1_eta_inc"]='%7.1f '%(hpars['v3_inc'])
                RmagResRec["anisotropy_v3_eta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_eta_inc"]='%7.1f '%(hpars['v1_inc'])
            else:
                RmagResRec["anisotropy_v1_zeta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v1_zeta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v1_zeta_inc"]='%7.1f '%(hpars['v3_inc'])
                RmagResRec["anisotropy_v3_zeta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v1_eta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v1_eta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v1_eta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v2_eta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_eta_inc"]='%7.1f '%(hpars['v1_inc'])
            if hpars["e23"]>hpars['e12']:
                RmagResRec["anisotropy_v2_zeta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v2_zeta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v2_zeta_inc"]='%7.1f '%(hpars['v3_inc'])
                RmagResRec["anisotropy_v3_zeta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v3_zeta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v3_zeta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v3_eta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_eta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v2_eta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_eta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_eta_inc"]='%7.1f '%(hpars['v1_inc'])
            else:
                RmagResRec["anisotropy_v2_zeta_semi_angle"]='%7.1f '%(hpars['e12'])
                RmagResRec["anisotropy_v2_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v2_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v3_eta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v3_eta_dec"]='%7.1f '%(hpars['v2_dec'])
                RmagResRec["anisotropy_v3_eta_inc"]='%7.1f '%(hpars['v2_inc'])
                RmagResRec["anisotropy_v3_zeta_semi_angle"]='%7.1f '%(hpars['e13'])
                RmagResRec["anisotropy_v3_zeta_dec"]='%7.1f '%(hpars['v1_dec'])
                RmagResRec["anisotropy_v3_zeta_inc"]='%7.1f '%(hpars['v1_inc'])
                RmagResRec["anisotropy_v2_eta_semi_angle"]='%7.1f '%(hpars['e23'])
                RmagResRec["anisotropy_v2_eta_dec"]='%7.1f '%(hpars['v3_dec'])
                RmagResRec["anisotropy_v2_eta_inc"]='%7.1f '%(hpars['v3_inc'])
            RmagResRec["tilt_correction"]='-1'
            RmagResRec["anisotropy_type"]='ATRM'
            RmagResRec["magic_method_codes"]='LP-AN-TRM:AE-H'
            RmagSpecRec["magic_method_codes"]='LP-AN-TRM:AE-H'
            RmagResRec["magic_software_packages"]=pmag.get_version()
            RmagSpecRec["magic_software_packages"]=pmag.get_version()
            RmagSpecRecs.append(RmagSpecRec)
            RmagResRecs.append(RmagResRec)
            specimen+=1
    pmag.magic_write(rmag_anis,RmagSpecRecs,'rmag_anisotropy')
    print "specimen tensor elements stored in ",rmag_anis
    pmag.magic_write(rmag_res,RmagResRecs,'rmag_results')
    print "specimen statistics and eigenparameters stored in ",rmag_res