Beispiel #1
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 list(rec.keys()) and 'inc_s' in list(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 list(rec.keys()) and 'inc_g' in list(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 list(rec.keys()) and 'inc_t' in list(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 list(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
Beispiel #2
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 list(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] = old_div(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 = old_div(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(old_div(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' % (old_div(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)
Beispiel #3
0
def plotMT(datablock, s, num, units, norm):
    Ints = []
    for plotrec in datablock:
        Ints.append(plotrec[3])
    Ints.sort()
    T, M, Tv, recnum = [], [], [], 0
    Mex, Tex, Vdif = [], [], []
    recbak = []
    for rec in datablock:
        if rec[5] == 'g':
            if units == "T":
                T.append(rec[0] * 1e3)
                Tv.append(rec[0] * 1e3)
                if recnum > 0: Tv.append(rec[0] * 1e3)
            elif units == "U":
                T.append(rec[0])
                Tv.append(rec[0])
                if recnum > 0: Tv.append(rec[0])
            elif units == "K":
                T.append(rec[0] - 273)
                Tv.append(rec[0] - 273)
                if recnum > 0: Tv.append(rec[0] - 273)
            elif "T" in units and "K" in units:
                if rec[0] < 1.:
                    T.append(rec[0] * 1e3)
                    Tv.append(rec[0] * 1e3)
                else:
                    T.append(rec[0] - 273)
                    Tv.append(rec[0] - 273)
                    if recnum > 0: Tv.append(rec[0] - 273)
            else:
                T.append(rec[0])
                Tv.append(rec[0])
                if recnum > 0: Tv.append(rec[0])
            if norm == 1:
                M.append(rec[3] / Ints[-1])
            else:
                M.append(rec[3])
            if recnum > 0 and len(rec) > 0 and len(recbak) > 0:
                v = []
                if recbak[0] != rec[0]:
                    V0 = pmag.dir2cart([recbak[1], recbak[2], recbak[3]])
                    V1 = pmag.dir2cart([rec[1], rec[2], rec[3]])
                    for el in range(3):
                        v.append(abs(V1[el] - V0[el]))
                    vdir = pmag.cart2dir(v)
                    Vdif.append(vdir[2] / Ints[-1])  # append vector difference
                    Vdif.append(vdir[2] / Ints[-1])  #
            recbak = []
            for el in rec:
                recbak.append(el)
            delta = .02 * M[0]
            if num == 1:
                if recnum % 2 == 0:
                    plt.text(T[-1] + delta,
                             M[-1],
                             ' ' * 3 + str(int(datablock[recnum][0] - 273)) +
                             '$\degree$C',
                             fontsize=9)
            recnum += 1
        else:
            if rec[0] < 200: Tex.append(rec[0] * 1e3)
            if rec[0] >= 200: Tex.append(rec[0] - 273)
            Mex.append(rec[3] / Ints[-1])
            recnum += 1
        MTlist = T
        MTlisty = M
    if len(Mex) > 0 and len(Tex) > 0:
        plt.scatter(Tex, Mex, marker='d', color='k')
    if len(Vdif) > 0:
        Vdif.append(vdir[2] / Ints[-1])  #
        Vdif.append(0)
    Tv.append(Tv[-1])
    plt.plot(T, M)
    plt.plot(T, M, 'ro')
    if len(Tv) == len(Vdif) and norm == 1: plt.plot(Tv, Vdif, 'g-')
    if units == "T":
        plt.xlabel("Step (mT)")
    elif units == "K":
        plt.xlabel("Step (C)")
    elif units == "J":
        plt.xlabel("Step (J)")
    else:
        plt.xlabel("Step [mT,C]")
    if norm == 1: plt.ylabel("Fractional Magnetization")
    if norm == 0: plt.ylabel("Magnetization")
    plt.axvline(0, color='k')
    plt.axhline(0, color='k')
    tstring = s
    plt.title(tstring)
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']
    Pint_pars = spd.PintPars(Data, str(s), tmin, tmax, 'magic', preferences['show_statistics_on_gui'],acceptance_criteria)
    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
    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

    #-------------------------------------------------
    # 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 list(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 list(Data[s].keys()) and len(Data[s]['tail_check_temperatures'])>0:
        pars['magic_method_codes']+=":LP-PI-BT-MD"

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

    #-------------------------------------------------
    # Calculate anisotropy correction factor
    #-------------------------------------------------

    if "AniSpec" in list(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 list(Data[s]["AniSpec"].keys()) and 'ATRM' in list(Data[s]["AniSpec"].keys()):
            TYPES=['AARM','ATRM']
        else:
            TYPES=list(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 list(Data[s].keys()) and TYPE in list(Data[s]['AniSpec'].keys())\
                and 'anisotropy_sigma' in  list(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['specimen_aniso_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 list(Data[s]['AniSpec'][TYPE].keys()) and Data[s]['AniSpec'][TYPE]['anisotropy_alt']!="" and Data[s]['AniSpec'][TYPE]['anisotropy_alt']!=None: # added 3/5/20 LT
                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 list(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 list(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 list(Data[s].keys()):
        if 'CR_correction_factor' in list(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 list(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 list(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.items():
            if key not in list(d1.keys()):
                d1[key] = value
        return d1

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

    return(pars)
Beispiel #5
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 list(rec.keys()) and 'inc_s' in list(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 list(rec.keys()) and 'inc_g' in list(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 list(rec.keys()) and 'inc_t' in list(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 list(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
Beispiel #6
0
def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX 
        lowrie_magic.py -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
        -sav saves plots and quits
    """
    fmt, plot = 'svg', 0
    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 '-sav' in sys.argv: plot = 1  # don't normalize
        if '-fmt' in sys.argv:  # sets input filename
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        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,
                           old_div(abs(carts[0]), nrm),
                           sym='r-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[0]), nrm),
                           sym='ro')  # X direction
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[1]), nrm),
                           sym='c-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[1]), nrm),
                           sym='cs')  # Y direction
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[2]), nrm),
                           sym='k-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[2]), nrm),
                           sym='k^',
                           title=spc,
                           xlab=xlab,
                           ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt}
        if plot == 0:
            pmagplotlib.drawFIGS(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.saveP(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.saveP(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Beispiel #7
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
Beispiel #8
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
        -sav save plots and quit
    """
    fmt, plot = "svg", 0
    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 "-sav" in sys.argv:
            plot = 1  # don't normalize
        if "-fmt" in sys.argv:  # sets input filename
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        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.0  # 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
        files = {"lowrie": "lowrie:_" + spc + "_." + fmt}
        if plot == 0:
            pmagplotlib.drawFIGS(FIG)
            ans = raw_input("S[a]ve figure? [q]uit, <return> to continue   ")
            if ans == "a":
                pmagplotlib.saveP(FIG, files)
            elif ans == "q":
                sys.exit()
        else:
            pmagplotlib.saveP(FIG, files)
        pmagplotlib.clearFIG(FIG["lowrie"])
Beispiel #9
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
        -sav save plots and quit
    """
    fmt, plot = 'svg', 0
    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 '-sav' in sys.argv:
            plot = 1  # don't normalize
        if '-fmt' in sys.argv:  # sets input filename
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        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 = pmag.open_file(in_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, old_div(
            abs(carts[0]), nrm), sym='r-')
        pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(
            abs(carts[0]), nrm), sym='ro')  # X direction
        pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(
            abs(carts[1]), nrm), sym='c-')
        pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(
            abs(carts[1]), nrm), sym='cs')  # Y direction
        pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(
            abs(carts[2]), nrm), sym='k-')
        pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(
            abs(carts[2]), nrm), sym='k^', title=spc, xlab=xlab, ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt}
        if plot == 0:
            pmagplotlib.drawFIGS(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.saveP(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.saveP(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Beispiel #10
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]))
Beispiel #11
0
def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX
        lowrie_magic.py -h [command line options]

    INPUT
       takes 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
        -sav saves plots and quits
        -DM [2, 3] MagIC data model number
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if len(sys.argv) <= 1:
        print(main.__doc__)
        print('you must supply a file name')
        sys.exit()
    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 = pmag.get_named_arg("-f", "measurements.txt")
    dir_path = pmag.get_named_arg("-WD", ".")
    in_file = pmag.resolve_file_name(in_file, dir_path)
    data_model = pmag.get_named_arg("-DM", 3)
    data_model = int(float(data_model))
    fmt = pmag.get_named_arg("-fmt", "svg")
    if '-N' in sys.argv:
        norm = 0  # don't normalize
    if '-sav' in sys.argv:
        plot = 1  # silently save and quit
    else:
        plot = 0 # generate plots
    print(in_file)
    # read in data
    PmagRecs, file_type = pmag.magic_read(in_file)
    if data_model == 2 and file_type != "magic_measurements":
        print('bad input file', file_type)
        sys.exit()
    if data_model == 3 and file_type != "measurements":
        print('bad input file', file_type)
        sys.exit()

    if data_model == 2:
        meth_code_col = 'magic_method_codes'
        spec_col = 'er_specimen_name'
        dec_col = "measurement_dec"
        inc_col = 'measurement_inc'
        moment_col = 'measurement_magn_moment'
        temp_col = 'treatment_temp'
    else:
        meth_code_col = 'method_codes'
        spec_col = 'specimen'
        dec_col = 'dir_dec'
        inc_col = 'dir_inc'
        moment_col = 'magn_moment'
        temp_col = "treat_temp"

    PmagRecs = pmag.get_dictitem(
        PmagRecs, meth_code_col, 'LP-IRM-3D', 'has')  # get all 3D IRM records

    if len(PmagRecs) == 0:
        print('no records found with the method code LP-IRM-3D')
        sys.exit()

    specs = pmag.get_dictkey(PmagRecs, spec_col, '')
    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, spec_col, spc, 'T')  # get all this one's data

        DIMs, Temps = [], []
        for dat in specdata:  # step through the data
            DIMs.append([float(dat[dec_col]), float(
                dat[inc_col]), float(dat[moment_col])])
            Temps.append(float(dat[temp_col])-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.plot_xy(FIG['lowrie'], Temps, abs(carts[0]) / nrm, sym='r-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, abs(carts[0]) / nrm, sym='ro')  # X direction
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, abs(carts[1]) / nrm, sym='c-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, abs(carts[1]) / nrm, sym='cs')  # Y direction
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, abs(carts[2]) / nrm, sym='k-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, abs(carts[2]) / nrm, sym='k^', title=spc, xlab=xlab, ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_'+spc+'_.'+fmt}
        if plot == 0:
            pmagplotlib.draw_figs(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.save_plots(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.save_plots(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Beispiel #12
0
def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX
        lowrie_magic.py -h [command line options]

    INPUT
       takes 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
        -sav saves plots and quits
        -DM [2, 3] MagIC data model number
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if len(sys.argv) <= 1:
        print(main.__doc__)
        print('you must supply a file name')
        sys.exit()
    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 = pmag.get_named_arg("-f", "measurements.txt")
    dir_path = pmag.get_named_arg("-WD", ".")
    in_file = pmag.resolve_file_name(in_file, dir_path)
    data_model = pmag.get_named_arg("-DM", 3)
    data_model = int(float(data_model))
    fmt = pmag.get_named_arg("-fmt", "svg")
    if '-N' in sys.argv:
        norm = 0  # don't normalize
    if '-sav' in sys.argv:
        plot = 1  # silently save and quit
    else:
        plot = 0  # generate plots
    print(in_file)
    # read in data
    PmagRecs, file_type = pmag.magic_read(in_file)
    if data_model == 2 and file_type != "magic_measurements":
        print('bad input file', file_type)
        sys.exit()
    if data_model == 3 and file_type != "measurements":
        print('bad input file', file_type)
        sys.exit()

    if data_model == 2:
        meth_code_col = 'magic_method_codes'
        spec_col = 'er_specimen_name'
        dec_col = "measurement_dec"
        inc_col = 'measurement_inc'
        moment_col = 'measurement_magn_moment'
        temp_col = 'treatment_temp'
    else:
        meth_code_col = 'method_codes'
        spec_col = 'specimen'
        dec_col = 'dir_dec'
        inc_col = 'dir_inc'
        moment_col = 'magn_moment'
        temp_col = "treat_temp"

    PmagRecs = pmag.get_dictitem(PmagRecs, meth_code_col, 'LP-IRM-3D',
                                 'has')  # get all 3D IRM records

    if len(PmagRecs) == 0:
        print('no records found with the method code LP-IRM-3D')
        sys.exit()

    specs = pmag.get_dictkey(PmagRecs, spec_col, '')
    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, spec_col, spc,
                                     'T')  # get all this one's data

        DIMs, Temps = [], []
        for dat in specdata:  # step through the data
            DIMs.append([
                float(dat[dec_col]),
                float(dat[inc_col]),
                float(dat[moment_col])
            ])
            Temps.append(float(dat[temp_col]) - 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.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[0]) / nrm,
                            sym='r-')
        pmagplotlib.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[0]) / nrm,
                            sym='ro')  # X direction
        pmagplotlib.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[1]) / nrm,
                            sym='c-')
        pmagplotlib.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[1]) / nrm,
                            sym='cs')  # Y direction
        pmagplotlib.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[2]) / nrm,
                            sym='k-')
        pmagplotlib.plot_xy(FIG['lowrie'],
                            Temps,
                            abs(carts[2]) / nrm,
                            sym='k^',
                            title=spc,
                            xlab=xlab,
                            ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt}
        if plot == 0:
            pmagplotlib.draw_figs(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.save_plots(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.save_plots(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Beispiel #13
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
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['jmethod_codes']="LP-PI-TRM" # thellier Method
    import SPD
    import SPD.spd3_0 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
    #print 'LIB1: ',Pint_pars
    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) # 
    #print 'LIB2: ',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["int_abs"]=-1*pars['treat_dc_field']*pars["int_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['method_codes']=LP_code+":"+"LP-PI-BT-IZZI"
    elif count_IZ <1 and count_ZI >1:
        pars['method_codes']=LP_code+":"+"LP-PI-ZI"
    elif count_IZ >1 and count_ZI <1:
        pars['method_codes']=LP_code+":"+"LP-PI-IZ"            
    else:
        pars['method_codes']=LP_code

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

    if 'additivity_check_temperatures' in Data[s].keys() and len(Data[s]['additivity_check_temperatures'])>0:
        pars['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]['aniso_s1']
            S_matrix[1,1]=Data[s]['AniSpec'][TYPE]['aniso_s2']
            S_matrix[2,2]=Data[s]['AniSpec'][TYPE]['aniso_s3']
            S_matrix[0,1]=Data[s]['AniSpec'][TYPE]['aniso_s4']
            S_matrix[1,0]=Data[s]['AniSpec'][TYPE]['aniso_s4']
            S_matrix[1,2]=Data[s]['AniSpec'][TYPE]['aniso_s5']
            S_matrix[2,1]=Data[s]['AniSpec'][TYPE]['aniso_s5']
            S_matrix[0,2]=Data[s]['AniSpec'][TYPE]['aniso_s6']
            S_matrix[2,0]=Data[s]['AniSpec'][TYPE]['aniso_s6']

            #Data[s]['AniSpec']['aniso_type']=Data[s]['AniSpec']['aniso_type']
            Data[s]['AniSpec'][TYPE]['aniso_n']=int(float(Data[s]['AniSpec'][TYPE]['aniso_n']))

            this_specimen_f_type=Data[s]['AniSpec'][TYPE]['aniso_type']+"_"+"%i"%(int(Data[s]['AniSpec'][TYPE]['aniso_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 'aniso_sigma' in  Data[s]['AniSpec'][TYPE].keys() \
                and Data[s]['AniSpec'][TYPE]['aniso_sigma']!="":
                # Calculate Ftest. If Ftest exceeds threshold value: set anistropy tensor to identity matrix
                sigma=float(Data[s]['AniSpec'][TYPE]['aniso_sigma'])             
                nf = 3*int(Data[s]['AniSpec'][TYPE]['aniso_n'])-6
                F=calculate_ftest(S_matrix,sigma,nf)
                #print s,"F",F
                Data[s]['AniSpec'][TYPE]['aniso_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]['aniso_sigma']=""
                Data[s]['AniSpec'][TYPE]['aniso_ftest']=99999
    
            
            if 'aniso_alt' in Data[s]['AniSpec'][TYPE].keys() and Data[s]['AniSpec'][TYPE]['aniso_alt']!="":
                if acceptance_criteria['aniso_alt']['value'] != -999 and \
                (float(Data[s]['AniSpec'][TYPE]['aniso_alt']) > float(acceptance_criteria['aniso_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]['aniso_alt']),float(acceptance_criteria['anisotropy_alt']['value']))
                    red_flag=True
            else:
                Data[s]['AniSpec'][TYPE]['aniso_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]['treat_dc_field_phi'], Data[s]['treat_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["int_abs"])
        
        pars["AC_anisotropy_type"]=Data[s]['AniSpec'][TYPE]["aniso_type"]
        pars["specimen_int_uT"]=float(pars["AC_specimen_int"])*1e6
        if TYPE=='AARM':
            if ":LP-AN-ARM" not in pars['method_codes']:
                pars['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['jmethod_codes']:
                pars['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["int_abs"])*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["int__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["int_abs"])
            if ":LP-TRM" not in pars['method_codes']:
                pars['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['method_codes']:
                    pars['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)
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']
    
    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/mean([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"
Beispiel #16
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
        -sav save plots and quit
    """
    fmt, plot = 'svg', 0
    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 '-sav' in sys.argv:
            plot = 1  # don't normalize
        if '-fmt' in sys.argv:  # sets input filename
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        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 = pmag.open_file(in_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,
                           old_div(abs(carts[0]), nrm),
                           sym='r-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[0]), nrm),
                           sym='ro')  # X direction
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[1]), nrm),
                           sym='c-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[1]), nrm),
                           sym='cs')  # Y direction
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[2]), nrm),
                           sym='k-')
        pmagplotlib.plotXY(FIG['lowrie'],
                           Temps,
                           old_div(abs(carts[2]), nrm),
                           sym='k^',
                           title=spc,
                           xlab=xlab,
                           ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt}
        if plot == 0:
            pmagplotlib.drawFIGS(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.saveP(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.saveP(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Beispiel #17
0
def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX 
        lowrie_magic.py -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
        -sav saves plots and quits
    """
    fmt,plot='svg',0
    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 '-sav' in sys.argv: plot=1 # don't normalize
        if '-fmt' in sys.argv: # sets input filename
            ind=sys.argv.index("-fmt")
            fmt=sys.argv[ind+1]
        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
        files={'lowrie':'lowrie:_'+spc+'_.'+fmt}
        if plot==0:
            pmagplotlib.drawFIGS(FIG)
            ans=raw_input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans=='a':
                pmagplotlib.saveP(FIG,files)
            elif ans=='q':
                sys.exit()
        else:
            pmagplotlib.saveP(FIG,files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Beispiel #18
0
def main():
    """
    NAME
       revtest_MM1990.py

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

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

    SYNTAX
       revtest_MM1990.py [command line options]

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

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

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

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

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

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

    if V>Vcrit:
        print("")
    elif V<Vcrit:
        if critical_angle<5:
            print("The McFadden and McElhinny (1990) classification for this test is: 'A'")
        elif critical_angle<10:
            print("The McFadden and McElhinny (1990) classification for this test is: 'B'")
        elif critical_angle<20:
            print("The McFadden and McElhinny (1990) classification for this test is: 'C'")
        else:
            print("The McFadden and McElhinny (1990) classification for this test is: 'INDETERMINATE;")
    if plot==1:
        CDF={'cdf':1}
        pmagplotlib.plot_init(CDF['cdf'],5,5)
        p1 = pmagplotlib.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=input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans=="a": pmagplotlib.saveP(CDF,files)
Beispiel #19
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 = input('Declination: [cntrl-D  to quit] ')
                dir.append(float(ans))
                ans = input('Inclination: ')
                dir.append(float(ans))
                ans = 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]))
Beispiel #20
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
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'
    ]

    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 / mean([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"
Beispiel #22
0
def main():
    """
    NAME
       revtest_MM1990.py

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

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

    SYNTAX
       revtest_MM1990.py [command line options]

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

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

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

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

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


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

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

    if V > Vcrit:
        print("")
    elif V < Vcrit:
        if critical_angle < 5:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'A'"
            )
        elif critical_angle < 10:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'B'"
            )
        elif critical_angle < 20:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'C'"
            )
        else:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'INDETERMINATE;"
            )
    if plot == 1:
        CDF = {'cdf': 1}
        pmagplotlib.plot_init(CDF['cdf'], 5, 5)
        p1 = pmagplotlib.plot_cdf(CDF['cdf'], Vp, "Watson's V", 'r', "")
        p2 = pmagplotlib.plot_vs(CDF['cdf'], [V], 'g', '-')
        p3 = pmagplotlib.plot_vs(CDF['cdf'], [Vp[k]], 'b', '--')
        pmagplotlib.draw_figs(CDF)
        files, fmt = {}, 'svg'
        if file2 != "":
            files['cdf'] = 'WatsonsV_' + file1 + '_' + file2 + '.' + fmt
        else:
            files['cdf'] = 'WatsonsV_' + file1 + '.' + fmt
        if pmagplotlib.isServer:
            black = '#000000'
            purple = '#800080'
            titles = {}
            titles['cdf'] = 'Cumulative Distribution'
            CDF = pmagplotlib.add_borders(CDF, titles, black, purple)
            pmagplotlib.save_plots(CDF, files)
        else:
            ans = input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans == "a": pmagplotlib.save_plots(CDF, files)
Beispiel #23
0
def plotZ(datablock, angle, s, norm):
    """
    function to make Zijderveld diagrams
    """
    amin, amax = 0., -100.
    fact = 1. / (datablock[0][3])  # normalize to NRM=1
    if norm == 0: fact = 1.
    x, y, z = [], [], []
    xb, yb, zb = [], [], []
    forVDS = []
    labels = []
    # convert to cartesian
    recnum, delta = 0, ""
    for plotrec in datablock:
        forVDS.append([plotrec[1], plotrec[2], plotrec[3] / datablock[0][3]])
        rec = pmag.dir2cart([(plotrec[1] - angle), plotrec[2],
                             plotrec[3] * fact])
        if len(plotrec) == 4:
            plotrec.append('0')  # fake the ZI,IZ step for old data
        if len(plotrec) == 5:
            plotrec.append('g')  # assume good measurement if not specified
        if plotrec[5] == 'g':
            #  z.append(-rec[2])
            z.append(rec[2])
            x.append(rec[0])
            #  y.append(-rec[1])
            y.append(rec[1])
            if x[-1] > amax: amax = x[-1]
            if y[-1] > amax: amax = y[-1]
            if z[-1] > amax: amax = z[-1]
            if x[-1] < amin: amin = x[-1]
            if y[-1] < amin: amin = y[-1]
            if z[-1] < amin: amin = z[-1]
            if delta == "": delta = .02 * x[-1]
            if recnum % 2 == 0 and len(x) > 0:
                # labels.append(' '*3 +str(int(datablock[recnum][0] - 273))+'$\degree$C')
                plt.text(x[-1] - delta,
                         z[-1] + delta,
                         ' ' * 3 + str(int(datablock[recnum][0] - 273)) +
                         '$\degree$C',
                         fontsize=9)
            recnum += 1
        elif len(plotrec) >= 6 and plotrec[5] == 'b':
            #  zb.append(-rec[2])
            zb.append(rec[2])
            xb.append(rec[0])
            #  yb.append(-rec[1])
            yb.append(rec[1])
            if xb[-1] > amax: amax = xb[-1]
            if yb[-1] > amax: amax = yb[-1]
            if zb[-1] > amax: amax = zb[-1]
            if xb[-1] < amin: amin = xb[-1]
            if yb[-1] < amin: amin = yb[-1]
            if zb[-1] < amin: amin = zb[-1]
            if delta == "": delta = .02 * xb[-1]
            # labels.append(' '*3 +str(int(datablock[recnum][0] - 273))+'$\degree$C')
            plt.text(xb[-1] - delta,
                     zb[-1] + delta,
                     ' ' * 3 + str(int(datablock[recnum][0] - 273)) +
                     '$\degree$C',
                     fontsize=9)
            recnum += 1


# plotting stuff
    if angle != 0: tempstr = "\n Declination rotated by: " + str(angle) + '\n'
    #         globals.text.insert(globals.END,tempstr)
    Zlist = x
    Zlisty = y
    Zlistz = z
    if len(xb) > 0:
        plt.scatter(xb, yb, marker='d', c='w', s=30)
        plt.scatter(xb, zb, marker='d', c='w', s=30)
    plt.plot(x, y, 'r')
    plt.plot(x, z, 'b')
    dec_points = plt.scatter(x, y, marker='o', c='r')
    inc_points = plt.scatter(x, z, marker='s', c='w')
    xline = [amin, amax]
    # yline=[-amax,-amin]
    yline = [amax, amin]
    zline = [0, 0]
    plt.plot(xline, zline, c='k')
    plt.plot(zline, xline, c='k')
    # if angle!=0:xlab="X: rotated to Dec = "+'%7.1f'%(angle)
    # if angle==0:xlab="X: rotated to Dec = "+'%7.1f'%(angle)
    # plt.xlabel(xlab)
    # plt.ylabel("Circles: Y; Squares: Z")
    tstring = s + ': NRM = ' + '%9.2e' % (datablock[0][3])
    plt.axis([amin, amax, amax, amin])
    plt.axis("equal")
    plt.axis('off')
    plt.tight_layout()
    plt.title(tstring)