Esempio n. 1
0
def main():
    """
    NAME
        site_edit_magic.py

    DESCRIPTION
       makes equal area projections site by site
         from pmag_specimens.txt file with
         Fisher confidence ellipse using McFadden and McElhinny (1988)
         technique for combining lines and planes
         allows testing and reject specimens for bad orientations

    SYNTAX
        site_edit_magic.py [command line options]

    OPTIONS
       -h: prints help and quits
       -f: specify pmag_specimen format file, default is pmag_specimens.txt
       -fsa: specify er_samples.txt file
       -exc: use existing pmag_criteria.txt file
       -N: reset all sample flags to good
    
    OUPUT
       edited er_samples.txt file

    """
    dir_path='.'
    FIG={} # plot dictionary
    FIG['eqarea']=1 # eqarea is figure 1
    in_file='pmag_specimens.txt'
    sampfile='er_samples.txt'
    out_file=""
    fmt,plot='svg',1
    Crits=""
    M,N=180.,1
    repeat=''
    renew=0
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-f' in sys.argv:
        ind=sys.argv.index("-f")
        in_file=sys.argv[ind+1]
    if '-fsa' in sys.argv:
        ind=sys.argv.index("-fsa")
        sampfile=sys.argv[ind+1]
    if '-exc' in sys.argv:
        Crits,file_type=pmag.magic_read(dir_path+'/pmag_criteria.txt')
        for crit in Crits:
            if crit['pmag_criteria_code']=='DE-SPEC':
                M=float(crit['specimen_mad'])
                N=float(crit['specimen_n'])
    if '-fmt' in sys.argv:
        ind=sys.argv.index("-fmt")
        fmt=sys.argv[ind+1]
    if '-N' in sys.argv: renew=1
# 
    if in_file[0]!="/":in_file=dir_path+'/'+in_file
    if sampfile[0]!="/":sampfile=dir_path+'/'+sampfile
    crd='s'
    Specs,file_type=pmag.magic_read(in_file)
    if file_type!='pmag_specimens':
        print ' bad pmag_specimen input file'
        sys.exit()
    Samps,file_type=pmag.magic_read(sampfile)
    if file_type!='er_samples':
        print ' bad er_samples input file'
        sys.exit()
    SO_methods=[]
    for rec in Samps:
       if 'sample_orientation_flag' not in rec.keys(): rec['sample_orientation_flag']='g'
       if 'sample_description' not in rec.keys(): rec['sample_description']=''
       if renew==1:
          rec['sample_orientation_flag']='g'
          description=rec['sample_description']
          if '#' in description:
               newdesc=""
               c=0
               while description[c]!='#' and c<len(description)-1: # look for first pound sign
                   newdesc=newdesc+description[c]
                   c+=1
               while description[c]=='#': 
                   c+=1# skip first set of pound signs
               while description[c]!='#':c+=1 # find second set of pound signs
               while description[c]=='#' and c<len(description)-1:c+=1 # skip second set of pound signs
               while c<len(description)-1: # look for first pound sign
                   newdesc=newdesc+description[c]
                   c+=1
               rec['sample_description']=newdesc # edit out old comment about orientations
       if "magic_method_codes" in rec:
           methlist=rec["magic_method_codes"]
           for meth in methlist.split(":"):
               if "SO" in meth.strip() and "SO-POM" not in meth.strip():
                   if meth.strip() not in SO_methods: SO_methods.append(meth.strip())
    pmag.magic_write(sampfile,Samps,'er_samples')
    SO_priorities=pmag.set_priorities(SO_methods,0)
    sitelist=[]
    for rec in Specs:
        if rec['er_site_name'] not in sitelist: sitelist.append(rec['er_site_name'])
    sitelist.sort()
    EQ={} 
    EQ['eqarea']=1
    pmagplotlib.plot_init(EQ['eqarea'],5,5)
    k=0
    while k<len(sitelist):
        site=sitelist[k]
        print site
        data=[]
        ThisSiteSpecs=pmag.get_dictitem(Specs,'er_site_name',site,'T')
        ThisSiteSpecs=pmag.get_dictitem(ThisSiteSpecs,'specimen_tilt_correction','-1','T') # get all the unoriented data
        for spec in ThisSiteSpecs:
                if spec['specimen_mad']!="" and spec['specimen_n']!="" and float(spec['specimen_mad'])<=M and float(spec['specimen_n'])>=N: 
# good spec, now get orientation....
                    redo,p=1,0
                    if len(SO_methods)<=1:
                        az_type=SO_methods[0]
                        orient=pmag.find_samp_rec(spec["er_sample_name"],Samps,az_type)
                        redo=0
                    while redo==1:
                        if p>=len(SO_priorities):
                            print "no orientation data for ",spec['er_sample_name']
                            orient["sample_azimuth"]=""
                            orient["sample_dip"]=""
                            redo=0
                        else:
                            az_type=SO_methods[SO_methods.index(SO_priorities[p])]
                            orient=pmag.find_samp_rec(spec["er_sample_name"],Samps,az_type)
                            if orient["sample_azimuth"]  !="":
                                redo=0
                        p+=1
                    if orient['sample_azimuth']!="":
                        rec={}
                        for key in spec.keys():rec[key]=spec[key]
                        rec['dec'],rec['inc']=pmag.dogeo(float(spec['specimen_dec']),float(spec['specimen_inc']),float(orient['sample_azimuth']),float(orient['sample_dip']))
                        rec["tilt_correction"]='1'
                        crd='g'
                        rec['sample_azimuth']=orient['sample_azimuth']
                        rec['sample_dip']=orient['sample_dip']
                        data.append(rec)
        if len(data)>2:
            print 'specimen, dec, inc, n_meas/MAD,| method codes '
            for i  in range(len(data)):
                print '%s: %7.1f %7.1f %s / %s | %s' % (data[i]['er_specimen_name'], data[i]['dec'], data[i]['inc'], data[i]['specimen_n'], data[i]['specimen_mad'], data[i]['magic_method_codes'])

            fpars=pmag.dolnp(data,'specimen_direction_type')
            print "\n Site lines planes  kappa   a95   dec   inc"
            print site, fpars["n_lines"], fpars["n_planes"], fpars["K"], fpars["alpha95"], fpars["dec"], fpars["inc"], fpars["R"]
            if out_file!="":
                if float(fpars["alpha95"])<=acutoff and float(fpars["K"])>=kcutoff:
                    out.write('%s %s %s\n'%(fpars["dec"],fpars['inc'],fpars['alpha95']))
            pmagplotlib.plotLNP(EQ['eqarea'],site,data,fpars,'specimen_direction_type')
            pmagplotlib.drawFIGS(EQ)
            if k!=0 and repeat!='y':
                ans=raw_input("s[a]ve plot, [q]uit, [e]dit specimens, [p]revious site, <return> to continue:\n ")
            elif k==0 and repeat!='y':
                ans=raw_input("s[a]ve plot, [q]uit, [e]dit specimens, <return> to continue:\n ")
            if ans=="p": k-=2
            if ans=="a":
                files={}
                files['eqarea']=site+'_'+crd+'_eqarea'+'.'+fmt
                pmagplotlib.saveP(EQ,files)
            if ans=="q": sys.exit()
            if ans=="e" and Samps==[]:
                print "can't edit samples without orientation file, sorry"
            elif ans=="e": 
#                k-=1
                testspec=raw_input("Enter name of specimen to check: ")
                for spec in data:
                    if spec['er_specimen_name']==testspec:
# first test wrong direction of drill arrows (flip drill direction in opposite direction and re-calculate d,i
                        d,i=pmag.dogeo(float(spec['specimen_dec']),float(spec['specimen_inc']),float(spec['sample_azimuth'])-180.,-float(spec['sample_dip']))
                        XY=pmag.dimap(d,i)
                        pmagplotlib.plotXY(EQ['eqarea'],[XY[0]],[XY[1]],sym='g^')
# first test wrong end of compass (take az-180.)
                        d,i=pmag.dogeo(float(spec['specimen_dec']),float(spec['specimen_inc']),float(spec['sample_azimuth'])-180.,float(spec['sample_dip']))
                        XY=pmag.dimap(d,i)
                        pmagplotlib.plotXY(EQ['eqarea'],[XY[0]],[XY[1]],sym='kv')
# did the sample spin in the hole?  
# now spin around specimen's z
                        X_up,Y_up,X_d,Y_d=[],[],[],[]
                        for incr in range(0,360,5):
                            d,i=pmag.dogeo(float(spec['specimen_dec'])+incr,float(spec['specimen_inc']),float(spec['sample_azimuth']),float(spec['sample_dip']))
                            XY=pmag.dimap(d,i)
                            if i>=0:
                                X_d.append(XY[0])
                                Y_d.append(XY[1])
                            else:
                                X_up.append(XY[0])
                                Y_up.append(XY[1])
                        pmagplotlib.plotXY(EQ['eqarea'],X_d,Y_d,sym='b.')
                        pmagplotlib.plotXY(EQ['eqarea'],X_up,Y_up,sym='c.')
                        pmagplotlib.drawFIGS(EQ)
                        break
                print "Triangle: wrong arrow for drill direction."
                print "Delta: wrong end of compass."
                print "Small circle:  wrong mark on sample. [cyan upper hemisphere]"
                deleteme=raw_input("Mark this sample as bad? y/[n]  ")
                if deleteme=='y':
                    reason=raw_input("Reason: [1] broke, [2] wrong drill direction, [3] wrong compass direction, [4] bad mark, [5] displaced block [6] other ")
                    if reason=='1':
                       description=' sample broke while drilling'
                    if reason=='2':
                       description=' wrong drill direction '
                    if reason=='3':
                       description=' wrong compass direction '
                    if reason=='4':
                       description=' bad mark in field'
                    if reason=='5':
                       description=' displaced block'
                    if reason=='6':
                       description=raw_input('Enter brief reason for deletion:   ')
                    for samp in Samps:
                        if samp['er_sample_name']==spec['er_sample_name']:
                            samp['sample_orientation_flag']='b'
                            samp['sample_description']=samp['sample_description']+' ## direction deleted because: '+description+'##' # mark description
                    pmag.magic_write(sampfile,Samps,'er_samples')
                repeat=raw_input("Mark another sample, this site? y/[n]  ")
                if repeat=='y': k-=1
        else:
            print 'skipping site - not enough data with specified coordinate system'
        k+=1 
    print "sample flags stored in ",sampfile
Esempio n. 2
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
Esempio n. 3
0
def main():
    """
        NAME
            nrm_specimens_magic.py
    
        DESCRIPTION
            converts NRM data in a magic_measurements type file to 
            geographic and tilt corrected data in a pmag_specimens type file
    
        SYNTAX
           nrm_specimens_magic.py [-h][command line options]
        
        OPTIONS:
            -h prints the help message and quits
            -f MFILE: specify input file
            -fsa SFILE: specify er_samples format file [with orientations]
            -F PFILE: specify output file
            -A  do not average replicate measurements
            -crd [g, t]: specify coordinate system ([g]eographic or [t]ilt adjusted)
                 NB: you must have the  SFILE in this directory

        DEFAULTS
            MFILE: magic_measurements.txt
            PFILE: nrm_specimens.txt
            SFILE: er_samples.txt
            coord: specimen
            average replicate measurements?: YES

        
    """
#
#   define some variables
#
    beg,end,pole,geo,tilt,askave,save=0,0,[],0,0,0,0
    samp_file=1
    args=sys.argv
    geo,tilt,orient=0,0,0
    doave=1
    user,comment,doave,coord="","",1,""
    dir_path='.'
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    meas_file=dir_path+"/magic_measurements.txt"
    pmag_file=dir_path+"/nrm_specimens.txt"
    samp_file=dir_path+"/er_samples.txt"
    if "-A" in args: doave=0
    if "-f" in args:
        ind=args.index("-f")
        meas_file=sys.argv[ind+1]
    if "-F" in args:
        ind=args.index("-F")
        pmag_file=dir_path+'/'+sys.argv[ind+1]
    speclist=[]
    if "-fsa" in args:
        ind=args.index("-fsa")
        samp_file=dir_path+'/'+sys.argv[ind+1]
    if "-crd" in args:
        ind=args.index("-crd")
        coord=sys.argv[ind+1]
        if coord=="g":
            geo,orient=1,1
        if coord=="t":
            tilt,orient,geo=1,1,1
#
# read in data
    if samp_file!="":
        samp_data,file_type=pmag.magic_read(samp_file)
        if file_type != 'er_samples':
           print file_type
           print "This is not a valid er_samples file " 
           sys.exit()
        else: print samp_file,' read in with ',len(samp_data),' records'
    else:
        print 'no orientations - will create file in specimen coordinates'
        geo,tilt,orient=0,0,0
    #
    #
    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()
    #
    if orient==1:
    # set orientation priorities
        SO_methods=[]
        orientation_priorities={'0':'SO-SUN','1':'SO-GPS-DIFF','2':'SO-SIGHT-BACK','3':'SO-CMD-NORTH','4':'SO-MAG'}
        for rec in samp_data:
           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())
    #
    # sort the sample names
    #
    sids=pmag.get_specs(meas_data)
    #
    #
    PmagSpecRecs=[]
    for s in sids:
        skip=0
        recnum=0
        PmagSpecRec={}
        PmagSpecRec["er_analyst_mail_names"]=user
        method_codes,inst_code=[],""
    # find the data from the meas_data file for this sample
    #
    #  collect info for the PmagSpecRec dictionary
    #
        meas_meth=[]
        for rec in  meas_data: # copy of vital stats to PmagSpecRec from first spec record
           if rec["er_specimen_name"]==s: 
               PmagSpecRec["er_specimen_name"]=s
               PmagSpecRec["er_sample_name"]=rec["er_sample_name"]
               PmagSpecRec["er_site_name"]=rec["er_site_name"]
               PmagSpecRec["er_location_name"]=rec["er_location_name"]
               PmagSpecRec["er_citation_names"]="This study"
               PmagSpecRec["magic_instrument_codes"]=""
               if "magic_experiment_name" not in rec.keys():
                   rec["magic_experiment_name"]=""
               if "magic_instrument_codes" not in rec.keys():
                   rec["magic_instrument_codes"]=""
               else:
                   PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"]
               if len(rec["magic_instrument_codes"]) > len(inst_code):
                   inst_code=rec["magic_instrument_codes"]
                   PmagSpecRec["magic_instrument_codes"]=inst_code  # copy over instruments
               break
    #
    # now check for correct method labels for all measurements
    #
        nrm_data=[]
        for meas_rec in meas_data:
            if meas_rec['er_specimen_name']==PmagSpecRec['er_specimen_name']:
                meths=meas_rec["magic_method_codes"].split(":")
                for meth in meths:
                    if meth.strip() not in meas_meth:meas_meth.append(meth)
                if "LT-NO" in meas_meth:nrm_data.append(meas_rec)
    #
        data,units=pmag.find_dmag_rec(s,nrm_data)
    #
        datablock=data
        #
        # find replicate measurements at NRM step and average them
        #
        Specs=[]
        if doave==1:
            step_meth,avedata=pmag.vspec(data)
            if len(avedata) != len(datablock):
                method_codes.append("DE-VM")
                SpecRec=avedata[0]
                print 'averaging data '
            else: SpecRec=data[0]
            Specs.append(SpecRec)
        else:
            for spec in data:Specs.append(spec)
        for SpecRec in Specs:
        #
        # do geo or stratigraphic correction now
        #
            if geo==1:
        #
        # find top priority orientation method
                redo,p=1,0
                if len(SO_methods)<=1: 
                    az_type=SO_methods[0] 
                    orient=pmag.find_samp_rec(PmagSpecRec["er_sample_name"],samp_data,az_type)
                    if orient["sample_azimuth"]  !="": method_codes.append(az_type)
                    redo=0
                while redo==1:
                    if p>=len(orientation_priorities):
                        print "no orientation data for ",s 
                        skip,redo=1,0
                        break
                    az_type=orientation_priorities[str(p)]
                    orient=pmag.find_samp_rec(PmagSpecRec["er_sample_name"],samp_data,az_type)
                    if orient["sample_azimuth"]  !="":
                        method_codes.append(az_type.strip())
                        redo=0
                    elif orient["sample_azimuth"]  =="":
                        p+=1
            #
            #  if stratigraphic selected,  get stratigraphic correction
            #
                if skip==0 and orient["sample_azimuth"]!="" and orient["sample_dip"]!="":
                    d_geo,i_geo=pmag.dogeo(SpecRec[1],SpecRec[2],orient["sample_azimuth"],orient["sample_dip"])
                    SpecRec[1]=d_geo
                    SpecRec[2]=i_geo
                    if tilt==1 and "sample_bed_dip" in orient.keys() and orient['sample_bed_dip']!="": 
                        d_tilt,i_tilt=pmag.dotilt(d_geo,i_geo,orient["sample_bed_dip_direction"],orient["sample_bed_dip"])
                        SpecRec[1]=d_tilt
                        SpecRec[2]=i_tilt
            if skip==0:
                PmagSpecRec["specimen_dec"]='%7.1f ' %(SpecRec[1])
                PmagSpecRec["specimen_inc"]='%7.1f ' %(SpecRec[2])
                if geo==1 and tilt==0:PmagSpecRec["specimen_tilt_correction"]='0'
                if geo==1 and tilt==1: PmagSpecRec["specimen_tilt_correction"]='100'
                if geo==0 and tilt==0: PmagSpecRec["specimen_tilt_correction"]='-1'
                PmagSpecRec["specimen_direction_type"]='l'
                PmagSpecRec["magic_method_codes"]="LT-NO"
                if len(method_codes) != 0:
                    methstring=""
                    for meth in method_codes:
                        methstring=methstring+ ":" +meth
                    PmagSpecRec["magic_method_codes"]=methstring[1:]
                PmagSpecRec["specimen_description"]="NRM data"
                PmagSpecRecs.append(PmagSpecRec)
    pmag.magic_write(pmag_file,PmagSpecRecs,'pmag_specimens')
    print "Data saved in ",pmag_file
Esempio n. 4
0
def main():
    """
    NAME
        site_edit_magic.py

    DESCRIPTION
       makes equal area projections site by site
         from pmag_specimens.txt file with
         Fisher confidence ellipse using McFadden and McElhinny (1988)
         technique for combining lines and planes
         allows testing and reject specimens for bad orientations

    SYNTAX
        site_edit_magic.py [command line options]

    OPTIONS
       -h: prints help and quits
       -f: specify pmag_specimen format file, default is pmag_specimens.txt
       -fsa: specify er_samples.txt file
       -exc: use existing pmag_criteria.txt file
       -N: reset all sample flags to good
    
    OUPUT
       edited er_samples.txt file

    """
    dir_path = '.'
    FIG = {}  # plot dictionary
    FIG['eqarea'] = 1  # eqarea is figure 1
    in_file = 'pmag_specimens.txt'
    sampfile = 'er_samples.txt'
    out_file = ""
    fmt, plot = 'svg', 1
    Crits = ""
    M, N = 180., 1
    repeat = ''
    renew = 0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path = sys.argv[ind + 1]
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        in_file = sys.argv[ind + 1]
    if '-fsa' in sys.argv:
        ind = sys.argv.index("-fsa")
        sampfile = sys.argv[ind + 1]
    if '-exc' in sys.argv:
        Crits, file_type = pmag.magic_read(dir_path + '/pmag_criteria.txt')
        for crit in Crits:
            if crit['pmag_criteria_code'] == 'DE-SPEC':
                M = float(crit['specimen_mad'])
                N = float(crit['specimen_n'])
    if '-fmt' in sys.argv:
        ind = sys.argv.index("-fmt")
        fmt = sys.argv[ind + 1]
    if '-N' in sys.argv: renew = 1
    #
    if in_file[0] != "/": in_file = dir_path + '/' + in_file
    if sampfile[0] != "/": sampfile = dir_path + '/' + sampfile
    crd = 's'
    Specs, file_type = pmag.magic_read(in_file)
    if file_type != 'pmag_specimens':
        print(' bad pmag_specimen input file')
        sys.exit()
    Samps, file_type = pmag.magic_read(sampfile)
    if file_type != 'er_samples':
        print(' bad er_samples input file')
        sys.exit()
    SO_methods = []
    for rec in Samps:
        if 'sample_orientation_flag' not in list(rec.keys()):
            rec['sample_orientation_flag'] = 'g'
        if 'sample_description' not in list(rec.keys()):
            rec['sample_description'] = ''
        if renew == 1:
            rec['sample_orientation_flag'] = 'g'
            description = rec['sample_description']
            if '#' in description:
                newdesc = ""
                c = 0
                while description[c] != '#' and c < len(
                        description) - 1:  # look for first pound sign
                    newdesc = newdesc + description[c]
                    c += 1
                while description[c] == '#':
                    c += 1  # skip first set of pound signs
                while description[c] != '#':
                    c += 1  # find second set of pound signs
                while description[c] == '#' and c < len(description) - 1:
                    c += 1  # skip second set of pound signs
                while c < len(description) - 1:  # look for first pound sign
                    newdesc = newdesc + description[c]
                    c += 1
                rec['sample_description'] = newdesc  # edit out old comment about orientations
        if "magic_method_codes" in rec:
            methlist = rec["magic_method_codes"]
            for meth in methlist.split(":"):
                if "SO" in meth.strip() and "SO-POM" not in meth.strip():
                    if meth.strip() not in SO_methods:
                        SO_methods.append(meth.strip())
    pmag.magic_write(sampfile, Samps, 'er_samples')
    SO_priorities = pmag.set_priorities(SO_methods, 0)
    sitelist = []
    for rec in Specs:
        if rec['er_site_name'] not in sitelist:
            sitelist.append(rec['er_site_name'])
    sitelist.sort()
    EQ = {}
    EQ['eqarea'] = 1
    pmagplotlib.plot_init(EQ['eqarea'], 5, 5)
    k = 0
    while k < len(sitelist):
        site = sitelist[k]
        print(site)
        data = []
        ThisSiteSpecs = pmag.get_dictitem(Specs, 'er_site_name', site, 'T')
        ThisSiteSpecs = pmag.get_dictitem(ThisSiteSpecs,
                                          'specimen_tilt_correction', '-1',
                                          'T')  # get all the unoriented data
        for spec in ThisSiteSpecs:
            if spec['specimen_mad'] != "" and spec[
                    'specimen_n'] != "" and float(
                        spec['specimen_mad']) <= M and float(
                            spec['specimen_n']) >= N:
                # good spec, now get orientation....
                redo, p = 1, 0
                if len(SO_methods) <= 1:
                    az_type = SO_methods[0]
                    orient = pmag.find_samp_rec(spec["er_sample_name"], Samps,
                                                az_type)
                    redo = 0
                while redo == 1:
                    if p >= len(SO_priorities):
                        print("no orientation data for ",
                              spec['er_sample_name'])
                        orient["sample_azimuth"] = ""
                        orient["sample_dip"] = ""
                        redo = 0
                    else:
                        az_type = SO_methods[SO_methods.index(
                            SO_priorities[p])]
                        orient = pmag.find_samp_rec(spec["er_sample_name"],
                                                    Samps, az_type)
                        if orient["sample_azimuth"] != "":
                            redo = 0
                    p += 1
                if orient['sample_azimuth'] != "":
                    rec = {}
                    for key in list(spec.keys()):
                        rec[key] = spec[key]
                    rec['dec'], rec['inc'] = pmag.dogeo(
                        float(spec['specimen_dec']),
                        float(spec['specimen_inc']),
                        float(orient['sample_azimuth']),
                        float(orient['sample_dip']))
                    rec["tilt_correction"] = '1'
                    crd = 'g'
                    rec['sample_azimuth'] = orient['sample_azimuth']
                    rec['sample_dip'] = orient['sample_dip']
                    data.append(rec)
        if len(data) > 2:
            print('specimen, dec, inc, n_meas/MAD,| method codes ')
            for i in range(len(data)):
                print('%s: %7.1f %7.1f %s / %s | %s' %
                      (data[i]['er_specimen_name'], data[i]['dec'],
                       data[i]['inc'], data[i]['specimen_n'],
                       data[i]['specimen_mad'], data[i]['magic_method_codes']))

            fpars = pmag.dolnp(data, 'specimen_direction_type')
            print("\n Site lines planes  kappa   a95   dec   inc")
            print(site, fpars["n_lines"], fpars["n_planes"], fpars["K"],
                  fpars["alpha95"], fpars["dec"], fpars["inc"], fpars["R"])
            if out_file != "":
                if float(fpars["alpha95"]) <= acutoff and float(
                        fpars["K"]) >= kcutoff:
                    out.write('%s %s %s\n' %
                              (fpars["dec"], fpars['inc'], fpars['alpha95']))
            pmagplotlib.plot_lnp(EQ['eqarea'], site, data, fpars,
                                 'specimen_direction_type')
            pmagplotlib.draw_figs(EQ)
            if k != 0 and repeat != 'y':
                ans = input(
                    "s[a]ve plot, [q]uit, [e]dit specimens, [p]revious site, <return> to continue:\n "
                )
            elif k == 0 and repeat != 'y':
                ans = input(
                    "s[a]ve plot, [q]uit, [e]dit specimens, <return> to continue:\n "
                )
            if ans == "p": k -= 2
            if ans == "a":
                files = {}
                files['eqarea'] = site + '_' + crd + '_eqarea' + '.' + fmt
                pmagplotlib.save_plots(EQ, files)
            if ans == "q": sys.exit()
            if ans == "e" and Samps == []:
                print("can't edit samples without orientation file, sorry")
            elif ans == "e":
                #                k-=1
                testspec = input("Enter name of specimen to check: ")
                for spec in data:
                    if spec['er_specimen_name'] == testspec:
                        # first test wrong direction of drill arrows (flip drill direction in opposite direction and re-calculate d,i
                        d, i = pmag.dogeo(float(spec['specimen_dec']),
                                          float(spec['specimen_inc']),
                                          float(spec['sample_azimuth']) - 180.,
                                          -float(spec['sample_dip']))
                        XY = pmag.dimap(d, i)
                        pmagplotlib.plot_xy(EQ['eqarea'], [XY[0]], [XY[1]],
                                            sym='g^')
                        # first test wrong end of compass (take az-180.)
                        d, i = pmag.dogeo(float(spec['specimen_dec']),
                                          float(spec['specimen_inc']),
                                          float(spec['sample_azimuth']) - 180.,
                                          float(spec['sample_dip']))
                        XY = pmag.dimap(d, i)
                        pmagplotlib.plot_xy(EQ['eqarea'], [XY[0]], [XY[1]],
                                            sym='kv')
                        # did the sample spin in the hole?
                        # now spin around specimen's z
                        X_up, Y_up, X_d, Y_d = [], [], [], []
                        for incr in range(0, 360, 5):
                            d, i = pmag.dogeo(
                                float(spec['specimen_dec']) + incr,
                                float(spec['specimen_inc']),
                                float(spec['sample_azimuth']),
                                float(spec['sample_dip']))
                            XY = pmag.dimap(d, i)
                            if i >= 0:
                                X_d.append(XY[0])
                                Y_d.append(XY[1])
                            else:
                                X_up.append(XY[0])
                                Y_up.append(XY[1])
                        pmagplotlib.plot_xy(EQ['eqarea'], X_d, Y_d, sym='b.')
                        pmagplotlib.plot_xy(EQ['eqarea'], X_up, Y_up, sym='c.')
                        pmagplotlib.draw_figs(EQ)
                        break
                print("Triangle: wrong arrow for drill direction.")
                print("Delta: wrong end of compass.")
                print(
                    "Small circle:  wrong mark on sample. [cyan upper hemisphere]"
                )
                deleteme = input("Mark this sample as bad? y/[n]  ")
                if deleteme == 'y':
                    reason = input(
                        "Reason: [1] broke, [2] wrong drill direction, [3] wrong compass direction, [4] bad mark, [5] displaced block [6] other "
                    )
                    if reason == '1':
                        description = ' sample broke while drilling'
                    if reason == '2':
                        description = ' wrong drill direction '
                    if reason == '3':
                        description = ' wrong compass direction '
                    if reason == '4':
                        description = ' bad mark in field'
                    if reason == '5':
                        description = ' displaced block'
                    if reason == '6':
                        description = input(
                            'Enter brief reason for deletion:   ')
                    for samp in Samps:
                        if samp['er_sample_name'] == spec['er_sample_name']:
                            samp['sample_orientation_flag'] = 'b'
                            samp['sample_description'] = samp[
                                'sample_description'] + ' ## direction deleted because: ' + description + '##'  # mark description
                    pmag.magic_write(sampfile, Samps, 'er_samples')
                repeat = input("Mark another sample, this site? y/[n]  ")
                if repeat == 'y': k -= 1
        else:
            print(
                'skipping site - not enough data with specified coordinate system'
            )
        k += 1
    print("sample flags stored in ", sampfile)
Esempio n. 5
0
def main():
    """
        NAME
            nrm_specimens_magic.py
    
        DESCRIPTION
            converts NRM data in a magic_measurements type file to 
            geographic and tilt corrected data in a pmag_specimens type file
    
        SYNTAX
           nrm_specimens_magic.py [-h][command line options]
        
        OPTIONS:
            -h prints the help message and quits
            -f MFILE: specify input file
            -fsa SFILE: specify er_samples format file [with orientations]
            -F PFILE: specify output file
            -A  do not average replicate measurements
            -crd [g, t]: specify coordinate system ([g]eographic or [t]ilt adjusted)
                 NB: you must have the  SFILE in this directory

        DEFAULTS
            MFILE: magic_measurements.txt
            PFILE: nrm_specimens.txt
            SFILE: er_samples.txt
            coord: specimen
            average replicate measurements?: YES

        
    """
    #
    #   define some variables
    #
    beg, end, pole, geo, tilt, askave, save = 0, 0, [], 0, 0, 0, 0
    samp_file = 1
    args = sys.argv
    geo, tilt, orient = 0, 0, 0
    doave = 1
    user, comment, doave, coord = "", "", 1, ""
    dir_path = "."
    if "-h" in args:
        print main.__doc__
        sys.exit()
    if "-WD" in sys.argv:
        ind = sys.argv.index("-WD")
        dir_path = sys.argv[ind + 1]
    meas_file = dir_path + "/magic_measurements.txt"
    pmag_file = dir_path + "/nrm_specimens.txt"
    samp_file = dir_path + "/er_samples.txt"
    if "-A" in args:
        doave = 0
    if "-f" in args:
        ind = args.index("-f")
        meas_file = sys.argv[ind + 1]
    if "-F" in args:
        ind = args.index("-F")
        pmag_file = dir_path + "/" + sys.argv[ind + 1]
    speclist = []
    if "-fsa" in args:
        ind = args.index("-fsa")
        samp_file = dir_path + "/" + sys.argv[ind + 1]
    if "-crd" in args:
        ind = args.index("-crd")
        coord = sys.argv[ind + 1]
        if coord == "g":
            geo, orient = 1, 1
        if coord == "t":
            tilt, orient, geo = 1, 1, 1
    #
    # read in data
    if samp_file != "":
        samp_data, file_type = pmag.magic_read(samp_file)
        if file_type != "er_samples":
            print file_type
            print "This is not a valid er_samples file "
            sys.exit()
        else:
            print samp_file, " read in with ", len(samp_data), " records"
    else:
        print "no orientations - will create file in specimen coordinates"
        geo, tilt, orient = 0, 0, 0
    #
    #
    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()
    #
    if orient == 1:
        # set orientation priorities
        SO_methods = []
        orientation_priorities = {
            "0": "SO-SUN",
            "1": "SO-GPS-DIFF",
            "2": "SO-SIGHT-BACK",
            "3": "SO-CMD-NORTH",
            "4": "SO-MAG",
        }
        for rec in samp_data:
            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())
    #
    # sort the sample names
    #
    sids = pmag.get_specs(meas_data)
    #
    #
    PmagSpecRecs = []
    for s in sids:
        skip = 0
        recnum = 0
        PmagSpecRec = {}
        PmagSpecRec["er_analyst_mail_names"] = user
        method_codes, inst_code = [], ""
        # find the data from the meas_data file for this sample
        #
        #  collect info for the PmagSpecRec dictionary
        #
        meas_meth = []
        for rec in meas_data:  # copy of vital stats to PmagSpecRec from first spec record
            if rec["er_specimen_name"] == s:
                PmagSpecRec["er_specimen_name"] = s
                PmagSpecRec["er_sample_name"] = rec["er_sample_name"]
                PmagSpecRec["er_site_name"] = rec["er_site_name"]
                PmagSpecRec["er_location_name"] = rec["er_location_name"]
                PmagSpecRec["er_citation_names"] = "This study"
                PmagSpecRec["magic_instrument_codes"] = ""
                if "magic_experiment_name" not in rec.keys():
                    rec["magic_experiment_name"] = ""
                if "magic_instrument_codes" not in rec.keys():
                    rec["magic_instrument_codes"] = ""
                else:
                    PmagSpecRec["magic_experiment_names"] = rec["magic_experiment_name"]
                if len(rec["magic_instrument_codes"]) > len(inst_code):
                    inst_code = rec["magic_instrument_codes"]
                    PmagSpecRec["magic_instrument_codes"] = inst_code  # copy over instruments
                break
        #
        # now check for correct method labels for all measurements
        #
        nrm_data = []
        for meas_rec in meas_data:
            if meas_rec["er_specimen_name"] == PmagSpecRec["er_specimen_name"]:
                meths = meas_rec["magic_method_codes"].split(":")
                for meth in meths:
                    if meth.strip() not in meas_meth:
                        meas_meth.append(meth)
                if "LT-NO" in meas_meth:
                    nrm_data.append(meas_rec)
        #
        data, units = pmag.find_dmag_rec(s, nrm_data)
        #
        datablock = data
        #
        # find replicate measurements at NRM step and average them
        #
        Specs = []
        if doave == 1:
            step_meth, avedata = pmag.vspec(data)
            if len(avedata) != len(datablock):
                method_codes.append("DE-VM")
                SpecRec = avedata[0]
                print "averaging data "
            else:
                SpecRec = data[0]
            Specs.append(SpecRec)
        else:
            for spec in data:
                Specs.append(spec)
        for SpecRec in Specs:
            #
            # do geo or stratigraphic correction now
            #
            if geo == 1:
                #
                # find top priority orientation method
                redo, p = 1, 0
                if len(SO_methods) <= 1:
                    az_type = SO_methods[0]
                    orient = pmag.find_samp_rec(PmagSpecRec["er_sample_name"], samp_data, az_type)
                    if orient["sample_azimuth"] != "":
                        method_codes.append(az_type)
                    redo = 0
                while redo == 1:
                    if p >= len(orientation_priorities):
                        print "no orientation data for ", s
                        skip, redo = 1, 0
                        break
                    az_type = orientation_priorities[str(p)]
                    orient = pmag.find_samp_rec(PmagSpecRec["er_sample_name"], samp_data, az_type)
                    if orient["sample_azimuth"] != "":
                        method_codes.append(az_type.strip())
                        redo = 0
                    elif orient["sample_azimuth"] == "":
                        p += 1
                #
                #  if stratigraphic selected,  get stratigraphic correction
                #
                if skip == 0 and orient["sample_azimuth"] != "" and orient["sample_dip"] != "":
                    d_geo, i_geo = pmag.dogeo(SpecRec[1], SpecRec[2], orient["sample_azimuth"], orient["sample_dip"])
                    SpecRec[1] = d_geo
                    SpecRec[2] = i_geo
                    if tilt == 1 and "sample_bed_dip" in orient.keys() and orient["sample_bed_dip"] != "":
                        d_tilt, i_tilt = pmag.dotilt(
                            d_geo, i_geo, orient["sample_bed_dip_direction"], orient["sample_bed_dip"]
                        )
                        SpecRec[1] = d_tilt
                        SpecRec[2] = i_tilt
            if skip == 0:
                PmagSpecRec["specimen_dec"] = "%7.1f " % (SpecRec[1])
                PmagSpecRec["specimen_inc"] = "%7.1f " % (SpecRec[2])
                if geo == 1 and tilt == 0:
                    PmagSpecRec["specimen_tilt_correction"] = "0"
                if geo == 1 and tilt == 1:
                    PmagSpecRec["specimen_tilt_correction"] = "100"
                if geo == 0 and tilt == 0:
                    PmagSpecRec["specimen_tilt_correction"] = "-1"
                PmagSpecRec["specimen_direction_type"] = "l"
                PmagSpecRec["magic_method_codes"] = "LT-NO"
                if len(method_codes) != 0:
                    methstring = ""
                    for meth in method_codes:
                        methstring = methstring + ":" + meth
                    PmagSpecRec["magic_method_codes"] = methstring[1:]
                PmagSpecRec["specimen_description"] = "NRM data"
                PmagSpecRecs.append(PmagSpecRec)
    pmag.magic_write(pmag_file, PmagSpecRecs, "pmag_specimens")
    print "Data saved in ", pmag_file
Esempio n. 6
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