예제 #1
0
def main():
    """
    NAME
       goprinc.py

    DESCRIPTION
       calculates Principal components from dec/iinc data

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

    SYNTAX
       goprinc.py [options]  [< filename]

    OPTIONS
        -h prints help message and quits
        -i for interactive filename entry
        -f FILE, specify input file
        -F FILE, specifies output file name
        < filename for reading from standard input

    OUTPUT
       tau_1 V1_Dec, V1_Inc, tau_2 V2_Dec V2_Inc, tau_3 V3_Dec V3_Inc, N

    """
    if len(sys.argv) > 0:
        if '-h' in sys.argv: # check if help is needed
            print main.__doc__
            sys.exit() # graceful quit
        if '-f' in sys.argv:
            ind=sys.argv.index('-f')
            file=sys.argv[ind+1]
            f=open(file,'rU')
            data=f.readlines()
        elif '-i' in sys.argv: # ask for filename
            file=raw_input("Enter file name with dec, inc data: ")
            f=open(file,'rU')
            data=f.readlines()
        else:
#
            data=sys.stdin.readlines() # read in data from standard input
    ofile = ""
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        ofile= sys.argv[ind+1]
        out = open(ofile, 'w + a')
    DIs= [] # set up list for dec inc data
    for line in data:   # read in the data from standard input
        if '\t' in line:
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        DIs.append((float(rec[0]),float(rec[1])))
#
    ppars=pmag.doprinc(DIs)
    output = '%7.5f %7.1f %7.1f %7.5f %7.1f %7.1f %7.5f %7.1f %7.1f %i' % (ppars["tau1"],ppars["dec"],ppars["inc"],ppars["tau2"],ppars["V2dec"],ppars["V2inc"],ppars["tau3"],ppars["V3dec"],ppars["V3inc"],ppars["N"])
    if ofile == "":
        print output
    else:
        out.write(output+'\n')
예제 #2
0
파일: iodp_funcs.py 프로젝트: PmagPy/PmagPy
def adj_dec(df,hole):
    cores=df.core.unique()
    adj_dec_df=pd.DataFrame(columns=df.columns)
    core_dec_corr={}
    for core in cores:
        core_df=df[df['core']==core]
        di_block=core_df[['dir_dec','dir_inc']].values
        ppars=pmag.doprinc(di_block)
        if ppars['inc']>0: # take the antipode
            ppars['dec']=ppars['dec']-180
        core_dec_corr[core]=ppars['dec']
        core_df['adj_dec']=(core_df['dir_dec']-ppars['dec'])%360
        core_df['dir_dec']=(core_df['adj_dec']+90)%360 # set mean normal to 90 for plottingh
        adj_dec_df=pd.concat([adj_dec_df,core_df])
    adj_dec_df.fillna("",inplace=True)
    adj_dec_df.drop_duplicates(inplace=True)
    adj_dec_df.to_csv(hole+'/'+hole+'_dec_adjusted.csv',index=False) 
    print ('Adjusted Declination DataFrame returned')
    return adj_dec_df,core_dec_corr
예제 #3
0
def adj_dec(df,hole):
    """
    takes an archive measurement DataFrame and adjusts the average declination by hole to 90 for "normal"

    Parameters
    __________
    df : Pandas DataFrame
        data frame of archive measurement data
    hole : str
        IODP hole

    Returns
    _______
    adj_dec_df : DataFrame
        adjusted declination  data frame
    core_dec_adj : dict
        dictionary of cores and the average declination
    """
    cores=df.core.unique()
    adj_dec_df=pd.DataFrame(columns=df.columns)
    core_dec_adj={}
    for core in cores:
        core_df=df[df['core']==core]
        di_block=core_df[['dir_dec','dir_inc']].values
        ppars=pmag.doprinc(di_block)
        if ppars['inc']>0: # take the antipode
            ppars['dec']=ppars['dec']-180
        core_dec_adj[core]=ppars['dec']
        core_df['adj_dec']=(core_df['dir_dec']-ppars['dec'])%360
        core_df['dir_dec']=(core_df['adj_dec']+90)%360 # set mean normal to 90 for plottingh
        adj_dec_df=pd.concat([adj_dec_df,core_df])
    adj_dec_df.fillna("",inplace=True)
    adj_dec_df.drop_duplicates(inplace=True)
    adj_dec_df.to_csv(hole+'/'+hole+'_dec_adjusted.csv',index=False) 
    print ('Adjusted Declination DataFrame returned')
    return adj_dec_df,core_dec_adj
예제 #4
0
def main():
    """
    NAME
       foldtest_magic.py

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

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

    SYNTAX
       foldtest_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f sites  formatted file [default for 3.0 is sites.txt, for 2.5, pmag_sites.txt]
        -fsa samples  formatted file
        -fsi sites  formatted file
        -exc use criteria to set acceptance criteria (supported only for data model 3)
        -n NB, set number of bootstraps, default is 1000
        -b MIN, MAX, set bounds for untilting, default is -10, 150
        -fmt FMT, specify format - default is svg
        -sav saves plots and quits
        -DM NUM MagIC data model number (2 or 3, default 3)

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

    """
    if '-h' in sys.argv:  # check if help is needed
        print(main.__doc__)
        sys.exit()  # graceful quit

    kappa = 0

    dir_path = pmag.get_named_arg("-WD", ".")
    nboot = int(float(pmag.get_named_arg("-n", 1000)))     # number of bootstraps
    fmt = pmag.get_named_arg("-fmt", "svg")
    data_model_num = int(float(pmag.get_named_arg("-DM", 3)))
    if data_model_num == 3:
        infile = pmag.get_named_arg("-f", 'sites.txt')
        orfile = 'samples.txt'
        site_col = 'site'
        dec_col = 'dir_dec'
        inc_col = 'dir_inc'
        tilt_col = 'dir_tilt_correction'
        dipkey, azkey = 'bed_dip', 'bed_dip_direction'
        crit_col = 'criterion'
        critfile = 'criteria.txt'
    else:
        infile = pmag.get_named_arg("-f", 'pmag_sites.txt')
        orfile = 'er_samples.txt'
        site_col = 'er_site_name'
        dec_col = 'site_dec'
        inc_col = 'site_inc'
        tilt_col = 'site_tilt_correction'
        dipkey, azkey = 'sample_bed_dip', 'sample_bed_dip_direction'
        crit_col = 'pmag_criteria_code'
        critfile = 'pmag_criteria.txt'
    if '-sav' in sys.argv:
        plot = 1
    else:
        plot = 0
    if '-b' in sys.argv:
        ind = sys.argv.index('-b')
        untilt_min = int(sys.argv[ind+1])
        untilt_max = int(sys.argv[ind+2])
    else:
        untilt_min, untilt_max = -10, 150
    if '-fsa' in sys.argv:
        orfile = pmag.get_named_arg("-fsa", "")
    elif '-fsi' in sys.argv:
        orfile = pmag.get_named_arg("-fsi", "")
        if data_model_num == 3:
            dipkey, azkey = 'bed_dip', 'bed_dip_direction'
        else:
            dipkey, azkey = 'site_bed_dip', 'site_bed_dip_direction'
    else:
        if data_model_num == 3:
            orfile = 'sites.txt'
        else:
            orfile = 'pmag_sites.txt'
    orfile = pmag.resolve_file_name(orfile, dir_path)
    infile = pmag.resolve_file_name(infile, dir_path)
    critfile = pmag.resolve_file_name(critfile, dir_path)
    df = pd.read_csv(infile, sep='\t', header=1)
    # keep only records with tilt_col
    data = df.copy()
    data = data[data[tilt_col].notnull()]
    data = data.where(data.notnull(), "")
    # turn into pmag data list
    data = list(data.T.apply(dict))
    # get orientation data
    if data_model_num == 3:
        # often orientation will be in infile (sites table)
        if os.path.split(orfile)[1] == os.path.split(infile)[1]:
            ordata = df[df[azkey].notnull()]
            ordata = ordata[ordata[dipkey].notnull()]
            ordata = list(ordata.T.apply(dict))
        # sometimes orientation might be in a sample file instead
        else:
            ordata = pd.read_csv(orfile, sep='\t', header=1)
            ordata = list(ordata.T.apply(dict))
    else:
        ordata, file_type = pmag.magic_read(orfile)

    if '-exc' in sys.argv:
        crits, file_type = pmag.magic_read(critfile)
        SiteCrits = []
        for crit in crits:
            if crit[crit_col] == "DE-SITE":
                SiteCrits.append(crit)
                #break

# get to work
#
    PLTS = {'geo': 1, 'strat': 2, 'taus': 3}  # make plot dictionary
    if not set_env.IS_WIN:
        pmagplotlib.plot_init(PLTS['geo'], 5, 5)
        pmagplotlib.plot_init(PLTS['strat'], 5, 5)
        pmagplotlib.plot_init(PLTS['taus'], 5, 5)
    if data_model_num == 2:
        GEOrecs = pmag.get_dictitem(data, tilt_col, '0', 'T')
    else:
        GEOrecs = data
    if len(GEOrecs) > 0:  # have some geographic data
        num_dropped = 0
        DIDDs = []  # set up list for dec inc  dip_direction, dip
        for rec in GEOrecs:   # parse data
            dip, dip_dir = 0, -1
            Dec = float(rec[dec_col])
            Inc = float(rec[inc_col])
            orecs = pmag.get_dictitem(
                ordata, site_col, rec[site_col], 'T')
            if len(orecs) > 0:
                if orecs[0][azkey] != "":
                    dip_dir = float(orecs[0][azkey])
                if orecs[0][dipkey] != "":
                    dip = float(orecs[0][dipkey])
            if dip != 0 and dip_dir != -1:
                if '-exc' in sys.argv:
                    keep = 1
                    for site_crit in SiteCrits:
                        crit_name = site_crit['table_column'].split('.')[1]
                        if crit_name and crit_name in rec.keys() and rec[crit_name]:
                            # get the correct operation (<, >=, =, etc.)
                            op = OPS[site_crit['criterion_operation']]
                            # then make sure the site record passes
                            if op(float(rec[crit_name]), float(site_crit['criterion_value'])):
                                keep = 0

                    if keep == 1:
                        DIDDs.append([Dec, Inc, dip_dir, dip])
                    else:
                        num_dropped += 1
                else:
                    DIDDs.append([Dec, Inc, dip_dir, dip])
        if num_dropped:
            print("-W- Dropped {} records because each failed one or more criteria".format(num_dropped))
    else:
        print('no geographic directional data found')
        sys.exit()

    pmagplotlib.plot_eq(PLTS['geo'], DIDDs, 'Geographic')
    data = np.array(DIDDs)
    D, I = pmag.dotilt_V(data)
    TCs = np.array([D, I]).transpose()
    pmagplotlib.plot_eq(PLTS['strat'], TCs, 'Stratigraphic')
    if plot == 0:
        pmagplotlib.draw_figs(PLTS)
    Percs = list(range(untilt_min, untilt_max))
    Cdf, Untilt = [], []
    plt.figure(num=PLTS['taus'])
    print('doing ', nboot, ' iterations...please be patient.....')
    for n in range(nboot):  # do bootstrap data sets - plot first 25 as dashed red line
        if n % 50 == 0:
            print(n)
        Taus = []  # set up lists for taus
        PDs = pmag.pseudo(DIDDs)
        if kappa != 0:
            for k in range(len(PDs)):
                d, i = pmag.fshdev(kappa)
                dipdir, dip = pmag.dodirot(d, i, PDs[k][2], PDs[k][3])
                PDs[k][2] = dipdir
                PDs[k][3] = dip
        for perc in Percs:
            tilt = np.array([1., 1., 1., 0.01*perc])
            D, I = pmag.dotilt_V(PDs*tilt)
            TCs = np.array([D, I]).transpose()
            ppars = pmag.doprinc(TCs)  # get principal directions
            Taus.append(ppars['tau1'])
        if n < 25:
            plt.plot(Percs, Taus, 'r--')
        # tilt that gives maximum tau
        Untilt.append(Percs[Taus.index(np.max(Taus))])
        Cdf.append(float(n) / float(nboot))
    plt.plot(Percs, Taus, 'k')
    plt.xlabel('% Untilting')
    plt.ylabel('tau_1 (red), CDF (green)')
    Untilt.sort()  # now for CDF of tilt of maximum tau
    plt.plot(Untilt, Cdf, 'g')
    lower = int(.025*nboot)
    upper = int(.975*nboot)
    plt.axvline(x=Untilt[lower], ymin=0, ymax=1, linewidth=1, linestyle='--')
    plt.axvline(x=Untilt[upper], ymin=0, ymax=1, linewidth=1, linestyle='--')
    tit = '%i - %i %s' % (Untilt[lower], Untilt[upper], 'Percent Unfolding')
    print(tit)
    plt.title(tit)
    if plot == 0:
        pmagplotlib.draw_figs(PLTS)
        ans = input('S[a]ve all figures, <Return> to quit  \n ')
        if ans != 'a':
            print("Good bye")
            sys.exit()
    files = {}
    for key in list(PLTS.keys()):
        files[key] = ('foldtest_'+'%s' % (key.strip()[:2])+'.'+fmt)
    pmagplotlib.save_plots(PLTS, files)
예제 #5
0
def main():
    """
    NAME
        find_EI.py

    DESCRIPTION
        Applies series of assumed flattening factor and "unsquishes" inclinations assuming tangent function.
        Finds flattening factor that gives elongation/inclination pair consistent with TK03.
        Finds bootstrap confidence bounds

    SYNTAX
        find_EI.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE specify input file name
        -nb N specify number of bootstraps - the more the better, but slower!, default is 1000
        -sc uses a "site-level" correction to a Fisherian distribution instead
            of a "study-level" correction to a TK03-consistent distribution.
            Note that many directions (~ 100) are needed for this correction to be reliable.
        -fmt [svg,png,eps,pdf..] change plot format, default is svg
        -sav  saves the figures and quits

    INPUT
        dec/inc pairs, delimited with space or tabs

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

    """
    fmt, nb = 'svg', 1000
    plot = 0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()  # graceful quit
    elif '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file = sys.argv[ind + 1]
    else:
        print(main.__doc__)
        sys.exit()
    if '-nb' in sys.argv:
        ind = sys.argv.index('-nb')
        nb = int(sys.argv[ind + 1])
    if '-sc' in sys.argv:
        site_correction = True
    else:
        site_correction = False
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-sav' in sys.argv: plot = 1
    data = numpy.loadtxt(file)
    upper, lower = int(round(.975 * nb)), int(round(.025 * nb))
    E, I = [], []
    PLTS = {'eq': 1, 'ei': 2, 'cdf': 3, 'v2': 4}
    pmagplotlib.plot_init(PLTS['eq'], 6, 6)
    pmagplotlib.plot_init(PLTS['ei'], 5, 5)
    pmagplotlib.plot_init(PLTS['cdf'], 5, 5)
    pmagplotlib.plot_init(PLTS['v2'], 5, 5)
    pmagplotlib.plotEQ(PLTS['eq'], data, 'Data')
    if plot == 0: pmagplotlib.drawFIGS(PLTS)
    ppars = pmag.doprinc(data)
    Io = ppars['inc']
    n = ppars["N"]
    Es, Is, Fs, V2s = pmag.find_f(data)
    if site_correction:
        Inc, Elong = Is[Es.index(min(Es))], Es[Es.index(min(Es))]
        flat_f = Fs[Es.index(min(Es))]
    else:
        Inc, Elong = Is[-1], Es[-1]
        flat_f = Fs[-1]
    pmagplotlib.plotEI(PLTS['ei'], Es, Is, flat_f)
    pmagplotlib.plotV2s(PLTS['v2'], V2s, Is, flat_f)
    b = 0
    print("Bootstrapping.... be patient")
    while b < nb:
        bdata = pmag.pseudo(data)
        Esb, Isb, Fsb, V2sb = pmag.find_f(bdata)
        if b < 25:
            pmagplotlib.plotEI(PLTS['ei'], Esb, Isb, Fsb[-1])
        if Esb[-1] != 0:
            ppars = pmag.doprinc(bdata)
            if site_correction:
                I.append(abs(Isb[Esb.index(min(Esb))]))
                E.append(Esb[Esb.index(min(Esb))])
            else:
                I.append(abs(Isb[-1]))
                E.append(Esb[-1])
            b += 1
            if b % 25 == 0: print(b, ' out of ', nb)
    I.sort()
    E.sort()
    Eexp = []
    for i in I:
        Eexp.append(pmag.EI(i))
    if Inc == 0:
        title = 'Pathological Distribution: ' + '[%7.1f, %7.1f]' % (I[lower],
                                                                    I[upper])
    else:
        title = '%7.1f [%7.1f, %7.1f]' % (Inc, I[lower], I[upper])
    pmagplotlib.plotEI(PLTS['ei'], Eexp, I, 1)
    pmagplotlib.plotCDF(PLTS['cdf'], I, 'Inclinations', 'r', title)
    pmagplotlib.plotVs(PLTS['cdf'], [I[lower], I[upper]], 'b', '--')
    pmagplotlib.plotVs(PLTS['cdf'], [Inc], 'g', '-')
    pmagplotlib.plotVs(PLTS['cdf'], [Io], 'k', '-')
    if plot == 0:
        pmagplotlib.drawFIGS(PLTS)
        print("Io Inc  I_lower, I_upper, Elon, E_lower, E_upper")
        print('%7.1f %s %7.1f _ %7.1f ^ %7.1f:  %6.4f _ %6.4f ^ %6.4f' %
              (Io, " => ", Inc, I[lower], I[upper], Elong, E[lower], E[upper]))
        ans = input("S[a]ve plots - <return> to quit:  ")
        if ans != 'a':
            print("\n Good bye\n")
            sys.exit()
    files = {}
    files['eq'] = 'findEI_eq.' + fmt
    files['ei'] = 'findEI_ei.' + fmt
    files['cdf'] = 'findEI_cdf.' + fmt
    files['v2'] = 'findEI_v2.' + fmt
    pmagplotlib.saveP(PLTS, files)
예제 #6
0
def main():
    """
    NAME
       foldtest_magic.py

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

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

    SYNTAX
       foldtest_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f sites  formatted file [default for 3.0 is sites.txt, for 2.5, pmag_sites.txt]
        -fsa samples  formatted file
        -fsi sites  formatted file
        -exc use criteria to set acceptance criteria (supported only for data model 3)
        -n NB, set number of bootstraps, default is 1000
        -b MIN, MAX, set bounds for untilting, default is -10, 150
        -fmt FMT, specify format - default is svg
        -sav saves plots and quits
        -DM NUM MagIC data model number (2 or 3, default 3)

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

    """
    if '-h' in sys.argv:  # check if help is needed
        print(main.__doc__)
        sys.exit()  # graceful quit

    kappa = 0

    dir_path = pmag.get_named_arg("-WD", ".")
    nboot = int(float(pmag.get_named_arg("-n", 1000)))  # number of bootstraps
    fmt = pmag.get_named_arg("-fmt", "svg")
    data_model_num = int(float(pmag.get_named_arg("-DM", 3)))
    if data_model_num == 3:
        infile = pmag.get_named_arg("-f", 'sites.txt')
        orfile = 'samples.txt'
        site_col = 'site'
        dec_col = 'dir_dec'
        inc_col = 'dir_inc'
        tilt_col = 'dir_tilt_correction'
        dipkey, azkey = 'bed_dip', 'bed_dip_direction'
        crit_col = 'criterion'
        critfile = 'criteria.txt'
    else:
        infile = pmag.get_named_arg("-f", 'pmag_sites.txt')
        orfile = 'er_samples.txt'
        site_col = 'er_site_name'
        dec_col = 'site_dec'
        inc_col = 'site_inc'
        tilt_col = 'site_tilt_correction'
        dipkey, azkey = 'sample_bed_dip', 'sample_bed_dip_direction'
        crit_col = 'pmag_criteria_code'
        critfile = 'pmag_criteria.txt'
    if '-sav' in sys.argv:
        plot = 1
    else:
        plot = 0
    if '-b' in sys.argv:
        ind = sys.argv.index('-b')
        untilt_min = int(sys.argv[ind + 1])
        untilt_max = int(sys.argv[ind + 2])
    else:
        untilt_min, untilt_max = -10, 150
    if '-fsa' in sys.argv:
        orfile = pmag.get_named_arg("-fsa", "")
    elif '-fsi' in sys.argv:
        orfile = pmag.get_named_arg("-fsi", "")
        if data_model_num == 3:
            dipkey, azkey = 'bed_dip', 'bed_dip_direction'
        else:
            dipkey, azkey = 'site_bed_dip', 'site_bed_dip_direction'
    else:
        if data_model_num == 3:
            orfile = 'sites.txt'
        else:
            orfile = 'pmag_sites.txt'
    orfile = pmag.resolve_file_name(orfile, dir_path)
    infile = pmag.resolve_file_name(infile, dir_path)
    critfile = pmag.resolve_file_name(critfile, dir_path)
    df = pd.read_csv(infile, sep='\t', header=1)
    # keep only records with tilt_col
    data = df.copy()
    data = data[data[tilt_col].notnull()]
    data = data.where(data.notnull(), "")
    # turn into pmag data list
    data = list(data.T.apply(dict))
    # get orientation data
    if data_model_num == 3:
        # often orientation will be in infile (sites table)
        if os.path.split(orfile)[1] == os.path.split(infile)[1]:
            ordata = df[df[azkey].notnull()]
            ordata = ordata[ordata[dipkey].notnull()]
            ordata = list(ordata.T.apply(dict))
        # sometimes orientation might be in a sample file instead
        else:
            ordata = pd.read_csv(orfile, sep='\t', header=1)
            ordata = list(ordata.T.apply(dict))
    else:
        ordata, file_type = pmag.magic_read(orfile)

    if '-exc' in sys.argv:
        crits, file_type = pmag.magic_read(critfile)
        SiteCrits = []
        for crit in crits:
            if crit[crit_col] == "DE-SITE":
                SiteCrits.append(crit)
                #break


# get to work
#
    PLTS = {'geo': 1, 'strat': 2, 'taus': 3}  # make plot dictionary
    if not set_env.IS_WIN:
        pmagplotlib.plot_init(PLTS['geo'], 5, 5)
        pmagplotlib.plot_init(PLTS['strat'], 5, 5)
        pmagplotlib.plot_init(PLTS['taus'], 5, 5)
    if data_model_num == 2:
        GEOrecs = pmag.get_dictitem(data, tilt_col, '0', 'T')
    else:
        GEOrecs = data
    if len(GEOrecs) > 0:  # have some geographic data
        num_dropped = 0
        DIDDs = []  # set up list for dec inc  dip_direction, dip
        for rec in GEOrecs:  # parse data
            dip, dip_dir = 0, -1
            Dec = float(rec[dec_col])
            Inc = float(rec[inc_col])
            orecs = pmag.get_dictitem(ordata, site_col, rec[site_col], 'T')
            if len(orecs) > 0:
                if orecs[0][azkey] != "":
                    dip_dir = float(orecs[0][azkey])
                if orecs[0][dipkey] != "":
                    dip = float(orecs[0][dipkey])
            if dip != 0 and dip_dir != -1:
                if '-exc' in sys.argv:
                    keep = 1
                    for site_crit in SiteCrits:
                        crit_name = site_crit['table_column'].split('.')[1]
                        if crit_name and crit_name in rec.keys(
                        ) and rec[crit_name]:
                            # get the correct operation (<, >=, =, etc.)
                            op = OPS[site_crit['criterion_operation']]
                            # then make sure the site record passes
                            if op(float(rec[crit_name]),
                                  float(site_crit['criterion_value'])):
                                keep = 0

                    if keep == 1:
                        DIDDs.append([Dec, Inc, dip_dir, dip])
                    else:
                        num_dropped += 1
                else:
                    DIDDs.append([Dec, Inc, dip_dir, dip])
        if num_dropped:
            print(
                "-W- Dropped {} records because each failed one or more criteria"
                .format(num_dropped))
    else:
        print('no geographic directional data found')
        sys.exit()

    pmagplotlib.plot_eq(PLTS['geo'], DIDDs, 'Geographic')
    data = np.array(DIDDs)
    D, I = pmag.dotilt_V(data)
    TCs = np.array([D, I]).transpose()
    pmagplotlib.plot_eq(PLTS['strat'], TCs, 'Stratigraphic')
    if plot == 0:
        pmagplotlib.draw_figs(PLTS)
    Percs = list(range(untilt_min, untilt_max))
    Cdf, Untilt = [], []
    plt.figure(num=PLTS['taus'])
    print('doing ', nboot, ' iterations...please be patient.....')
    for n in range(
            nboot
    ):  # do bootstrap data sets - plot first 25 as dashed red line
        if n % 50 == 0:
            print(n)
        Taus = []  # set up lists for taus
        PDs = pmag.pseudo(DIDDs)
        if kappa != 0:
            for k in range(len(PDs)):
                d, i = pmag.fshdev(kappa)
                dipdir, dip = pmag.dodirot(d, i, PDs[k][2], PDs[k][3])
                PDs[k][2] = dipdir
                PDs[k][3] = dip
        for perc in Percs:
            tilt = np.array([1., 1., 1., 0.01 * perc])
            D, I = pmag.dotilt_V(PDs * tilt)
            TCs = np.array([D, I]).transpose()
            ppars = pmag.doprinc(TCs)  # get principal directions
            Taus.append(ppars['tau1'])
        if n < 25:
            plt.plot(Percs, Taus, 'r--')
        # tilt that gives maximum tau
        Untilt.append(Percs[Taus.index(np.max(Taus))])
        Cdf.append(float(n) / float(nboot))
    plt.plot(Percs, Taus, 'k')
    plt.xlabel('% Untilting')
    plt.ylabel('tau_1 (red), CDF (green)')
    Untilt.sort()  # now for CDF of tilt of maximum tau
    plt.plot(Untilt, Cdf, 'g')
    lower = int(.025 * nboot)
    upper = int(.975 * nboot)
    plt.axvline(x=Untilt[lower], ymin=0, ymax=1, linewidth=1, linestyle='--')
    plt.axvline(x=Untilt[upper], ymin=0, ymax=1, linewidth=1, linestyle='--')
    tit = '%i - %i %s' % (Untilt[lower], Untilt[upper], 'Percent Unfolding')
    print(tit)
    plt.title(tit)
    if plot == 0:
        pmagplotlib.draw_figs(PLTS)
        ans = input('S[a]ve all figures, <Return> to quit  \n ')
        if ans != 'a':
            print("Good bye")
            sys.exit()
    files = {}
    for key in list(PLTS.keys()):
        files[key] = ('foldtest_' + '%s' % (key.strip()[:2]) + '.' + fmt)
    pmagplotlib.save_plots(PLTS, files)
예제 #7
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

    INPUT
       takes magic formatted sites, samples, specimens, or measurements

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file from magic, default='sites.txt'
         supported types=[measurements, specimens, samples, sites]
        -fsp FILE: specify specimen file name, (required if you want to plot measurements by sample)
                default='specimens.txt'
        -fsa FILE: specify sample file name, (required if you want to plot specimens by site)
                default='samples.txt'
        -fsi FILE: specify site file name, default='sites.txt'

        -obj OBJ: specify  level of plot  [all, sit, sam, spc], default is all
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is geographic, unspecified assumed geographic
        -fmt [svg,png,jpg] format for output plots
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
        -c plot as colour contour
        -sav save plot and quit quietly
    NOTE
        all: entire file; sit: site; sam: sample; spc: specimen
    """
    # initialize some default variables
    FIG = {} # plot dictionary
    FIG['eqarea'] = 1 # eqarea is figure 1
    plotE = 0
    plt = 0  # default to not plotting
    verbose = pmagplotlib.verbose
    # extract arguments from sys.argv
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg_from_sys("-WD", default_val=os.getcwd())
    pmagplotlib.plot_init(FIG['eqarea'],5,5)
    in_file = pmag.get_named_arg_from_sys("-f", default_val="sites.txt")
    full_in_file = os.path.join(dir_path, in_file)
    plot_by = pmag.get_named_arg_from_sys("-obj", default_val="all").lower()
    spec_file = pmag.get_named_arg_from_sys("-fsp", default_val="specimens.txt")
    samp_file = pmag.get_named_arg_from_sys("-fsa", default_val="samples.txt")
    site_file = pmag.get_named_arg_from_sys("-fsi", default_val="sites.txt")
    if plot_by == 'all':
        plot_key = 'all'
    elif plot_by == 'sit':
        plot_key = 'site'
    elif plot_by == 'sam':
        plot_key = 'sample'
    elif plot_by == 'spc':
        plot_key = 'specimen'
    else:
        plot_key = 'all'
    if '-c' in sys.argv:
        contour = 1
    else:
        contour = 0
    if '-sav' in sys.argv:
        plt = 1
        verbose = 0
    if '-ell' in sys.argv:
        plotE = 1
        ind = sys.argv.index('-ell')
        ell_type = sys.argv[ind+1]
        ell_type = pmag.get_named_arg_from_sys("-ell", "F")
        dist = ell_type.upper()
        # if dist type is unrecognized, use Fisher
        if dist not in ['F', 'K', 'B', 'BE', 'BV']:
            dist = 'F'
        if dist == "BV":
            FIG['bdirs'] = 2
            pmagplotlib.plot_init(FIG['bdirs'],5,5)
    crd = pmag.get_named_arg_from_sys("-crd", default_val="g")
    if crd == "s":
        coord = "-1"
    elif crd == "t":
        coord = "100"
    else:
        coord = "0"

    fmt = pmag.get_named_arg_from_sys("-fmt", "svg")

    dec_key = 'dir_dec'
    inc_key = 'dir_inc'
    tilt_key = 'dir_tilt_correction'
    #Dir_type_keys=['','site_direction_type','sample_direction_type','specimen_direction_type']

    #
    fnames = {"specimens": spec_file, "samples": samp_file, 'sites': site_file}
    contribution = nb.Contribution(dir_path, custom_filenames=fnames,
                                   single_file=in_file)
    # the object that contains the DataFrame + useful helper methods:
    table_name = list(contribution.tables.keys())[0]
    data_container = contribution.tables[table_name]
    # the actual DataFrame:
    data = data_container.df

    # uses sample infile to add temporary site_name
    # column to the specimen table



    data_container = contribution.tables[table_name]
    data = data_container.df

    if (plot_key != "all") and (plot_key not in data.columns):
        contribution.propagate_location_to_measurements()
        contribution.propagate_location_to_specimens()

    # add tilt key into DataFrame columns if it isn't there already
    if tilt_key not in data.columns:
        data.loc[:, tilt_key] = None

    if verbose:
        print(len(data), ' records read from ', in_file)

    # find desired dec,inc data:
    dir_type_key = ''
    #
    # get plotlist if not plotting all records
    #
    plotlist=[]
    if plot_key != "all":
        # return all where plot_key is not blank
        if plot_key not in data.columns:
            print('Can\'t plot by "{}".  That header is not in infile: {}'.format(plot_key, in_file))
            return
        plots = data[data[plot_key].notnull()]
        plotlist = plots[plot_key].unique() # grab unique values
    else:
        plotlist.append('All')

    for plot in plotlist:
        if verbose:
            print(plot)
        if plot == 'All':
            # plot everything at once
            plot_data = data
        else:
            # pull out only partial data
            plot_data = data[data[plot_key] == plot]

        DIblock = []
        GCblock = []
        # SLblock, SPblock = [], []
        title = plot
        mode = 1
        k = 0


        if dec_key not in plot_data.columns:
            print("-W- No dec/inc data")
            continue
        # get all records where dec & inc values exist
        plot_data = plot_data[plot_data[dec_key].notnull() & plot_data[inc_key].notnull()]
        if plot_data.empty:
            continue
        # this sorting out is done in get_di_bock
        #if coord == '0':  # geographic, use records with no tilt key (or tilt_key 0)
        #    cond1 = plot_data[tilt_key].fillna('') == coord
        #    cond2 = plot_data[tilt_key].isnull()
        #    plot_data = plot_data[cond1 | cond2]
        #else:  # not geographic coordinates, use only records with correct tilt_key
        #    plot_data = plot_data[plot_data[tilt_key] == coord]

        # get metadata for naming the plot file
        locations = data_container.get_name('location', df_slice=plot_data)
        site = data_container.get_name('site', df_slice=plot_data)
        sample = data_container.get_name('sample', df_slice=plot_data)
        specimen = data_container.get_name('specimen', df_slice=plot_data)

        # make sure method_codes is in plot_data
        if 'method_codes' not in plot_data.columns:
            plot_data['method_codes'] = ''

        # get data blocks
        DIblock = data_container.get_di_block(df_slice=plot_data,
                                              tilt_corr=coord, excl=['DE-BFP'])
        #SLblock = [[ind, row['method_codes']] for ind, row in plot_data.iterrows()]
        # get great circles
        great_circle_data = data_container.get_records_for_code('DE-BFP', incl=True,
                                                                use_slice=True, sli=plot_data)

        if len(great_circle_data) > 0:
            gc_cond = great_circle_data[tilt_key] == coord
            GCblock = [[float(row[dec_key]), float(row[inc_key])] for ind, row in great_circle_data[gc_cond].iterrows()]
            #SPblock = [[ind, row['method_codes']] for ind, row in great_circle_data[gc_cond].iterrows()]

        if len(DIblock) > 0:
            if contour == 0:
                pmagplotlib.plotEQ(FIG['eqarea'], DIblock, title)
            else:
                pmagplotlib.plotEQcont(FIG['eqarea'], DIblock)
        else:
            pmagplotlib.plotNET(FIG['eqarea'])
        if len(GCblock)>0:
            for rec in GCblock:
                pmagplotlib.plotC(FIG['eqarea'], rec, 90., 'g')
        if len(DIblock) == 0 and len(GCblock) == 0:
            if verbose:
                print("no records for plotting")
            continue
            #sys.exit()
        if plotE == 1:
            ppars = pmag.doprinc(DIblock) # get principal directions
            nDIs, rDIs, npars, rpars = [], [], [], []
            for rec in DIblock:
                angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
                if angle>90.:
                    rDIs.append(rec)
                else:
                    nDIs.append(rec)
            if dist=='B': # do on whole dataset
                etitle="Bingham confidence ellipse"
                bpars=pmag.dobingham(DIblock)
                for key in list(bpars.keys()):
                    if key!='n' and verbose: print("    ",key, '%7.1f'%(bpars[key]))
                    if key=='n' and verbose: print("    ",key, '       %i'%(bpars[key]))
                npars.append(bpars['dec'])
                npars.append(bpars['inc'])
                npars.append(bpars['Zeta'])
                npars.append(bpars['Zdec'])
                npars.append(bpars['Zinc'])
                npars.append(bpars['Eta'])
                npars.append(bpars['Edec'])
                npars.append(bpars['Einc'])
            if dist=='F':
                etitle="Fisher confidence cone"
                if len(nDIs)>2:
                    fpars=pmag.fisher_mean(nDIs)
                    for key in list(fpars.keys()):
                        if key!='n' and verbose: print("    ",key, '%7.1f'%(fpars[key]))
                        if key=='n' and verbose: print("    ",key, '       %i'%(fpars[key]))
                    mode+=1
                    npars.append(fpars['dec'])
                    npars.append(fpars['inc'])
                    npars.append(fpars['alpha95']) # Beta
                    npars.append(fpars['dec'])
                    isign=old_div(abs(fpars['inc']),fpars['inc'])
                    npars.append(fpars['inc']-isign*90.) #Beta inc
                    npars.append(fpars['alpha95']) # gamma
                    npars.append(fpars['dec']+90.) # Beta dec
                    npars.append(0.) #Beta inc
                if len(rDIs)>2:
                    fpars=pmag.fisher_mean(rDIs)
                    if verbose: print("mode ",mode)
                    for key in list(fpars.keys()):
                        if key!='n' and verbose: print("    ",key, '%7.1f'%(fpars[key]))
                        if key=='n' and verbose: print("    ",key, '       %i'%(fpars[key]))
                    mode+=1
                    rpars.append(fpars['dec'])
                    rpars.append(fpars['inc'])
                    rpars.append(fpars['alpha95']) # Beta
                    rpars.append(fpars['dec'])
                    isign=old_div(abs(fpars['inc']),fpars['inc'])
                    rpars.append(fpars['inc']-isign*90.) #Beta inc
                    rpars.append(fpars['alpha95']) # gamma
                    rpars.append(fpars['dec']+90.) # Beta dec
                    rpars.append(0.) #Beta inc
            if dist=='K':
                etitle="Kent confidence ellipse"
                if len(nDIs)>3:
                    kpars=pmag.dokent(nDIs,len(nDIs))
                    if verbose: print("mode ",mode)
                    for key in list(kpars.keys()):
                        if key!='n' and verbose: print("    ",key, '%7.1f'%(kpars[key]))
                        if key=='n' and verbose: print("    ",key, '       %i'%(kpars[key]))
                    mode+=1
                    npars.append(kpars['dec'])
                    npars.append(kpars['inc'])
                    npars.append(kpars['Zeta'])
                    npars.append(kpars['Zdec'])
                    npars.append(kpars['Zinc'])
                    npars.append(kpars['Eta'])
                    npars.append(kpars['Edec'])
                    npars.append(kpars['Einc'])
                if len(rDIs)>3:
                    kpars=pmag.dokent(rDIs,len(rDIs))
                    if verbose: print("mode ",mode)
                    for key in list(kpars.keys()):
                        if key!='n' and verbose: print("    ",key, '%7.1f'%(kpars[key]))
                        if key=='n' and verbose: print("    ",key, '       %i'%(kpars[key]))
                    mode+=1
                    rpars.append(kpars['dec'])
                    rpars.append(kpars['inc'])
                    rpars.append(kpars['Zeta'])
                    rpars.append(kpars['Zdec'])
                    rpars.append(kpars['Zinc'])
                    rpars.append(kpars['Eta'])
                    rpars.append(kpars['Edec'])
                    rpars.append(kpars['Einc'])
            else: # assume bootstrap
                if dist=='BE':
                    if len(nDIs)>5:
                        BnDIs=pmag.di_boot(nDIs)
                        Bkpars=pmag.dokent(BnDIs,1.)
                        if verbose: print("mode ",mode)
                        for key in list(Bkpars.keys()):
                            if key!='n' and verbose: print("    ",key, '%7.1f'%(Bkpars[key]))
                            if key=='n' and verbose: print("    ",key, '       %i'%(Bkpars[key]))
                        mode+=1
                        npars.append(Bkpars['dec'])
                        npars.append(Bkpars['inc'])
                        npars.append(Bkpars['Zeta'])
                        npars.append(Bkpars['Zdec'])
                        npars.append(Bkpars['Zinc'])
                        npars.append(Bkpars['Eta'])
                        npars.append(Bkpars['Edec'])
                        npars.append(Bkpars['Einc'])
                    if len(rDIs)>5:
                        BrDIs=pmag.di_boot(rDIs)
                        Bkpars=pmag.dokent(BrDIs,1.)
                        if verbose: print("mode ",mode)
                        for key in list(Bkpars.keys()):
                            if key!='n' and verbose: print("    ",key, '%7.1f'%(Bkpars[key]))
                            if key=='n' and verbose: print("    ",key, '       %i'%(Bkpars[key]))
                        mode+=1
                        rpars.append(Bkpars['dec'])
                        rpars.append(Bkpars['inc'])
                        rpars.append(Bkpars['Zeta'])
                        rpars.append(Bkpars['Zdec'])
                        rpars.append(Bkpars['Zinc'])
                        rpars.append(Bkpars['Eta'])
                        rpars.append(Bkpars['Edec'])
                        rpars.append(Bkpars['Einc'])
                    etitle="Bootstrapped confidence ellipse"
                elif dist=='BV':
                    sym={'lower':['o','c'],'upper':['o','g'],'size':3,'edgecolor':'face'}
                    if len(nDIs)>5:
                        BnDIs=pmag.di_boot(nDIs)
                        pmagplotlib.plotEQsym(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors', sym)
                    if len(rDIs)>5:
                        BrDIs=pmag.di_boot(rDIs)
                        if len(nDIs)>5:  # plot on existing plots
                            pmagplotlib.plotDIsym(FIG['bdirs'],BrDIs,sym)
                        else:
                            pmagplotlib.plotEQ(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors')
            if dist=='B':
                if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],npars,0)
            elif len(nDIs)>3 and dist!='BV':
                pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],npars,0)
                if len(rDIs)>3:
                    pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],rpars,0)
            elif len(rDIs)>3 and dist!='BV':
                pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],rpars,0)

        for key in list(FIG.keys()):
            files = {}
            filename = pmag.get_named_arg_from_sys('-fname')
            if filename: # use provided filename
                filename+= '.' + fmt
            elif pmagplotlib.isServer: # use server plot naming convention
                filename='LO:_'+locations+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+specimen+'_CO:_'+crd+'_TY:_'+key+'_.'+fmt
            else: # use more readable naming convention
                filename = ''
                for item in [locations, site, sample, specimen, crd, key]:
                    if item:
                        item = item.replace(' ', '_')
                        filename += item + '_'
                if filename.endswith('_'):
                    filename = filename[:-1]
                filename += ".{}".format(fmt)

            files[key]=filename

        if pmagplotlib.isServer:
            black     = '#000000'
            purple    = '#800080'
            titles={}
            titles['eq']='Equal Area Plot'
            FIG = pmagplotlib.addBorders(FIG,titles,black,purple)
            pmagplotlib.saveP(FIG,files)

        if plt:
            pmagplotlib.saveP(FIG,files)
            continue
        if verbose:
            pmagplotlib.drawFIGS(FIG)
            ans=input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
            if ans == "q":
                sys.exit()
            if ans == "a":
                pmagplotlib.saveP(FIG,files)
        continue
예제 #8
0
def main():
    """
    NAME
       foldtest.py

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

    INPUT FORMAT
       dec inc dip_direction dip

    SYNTAX
       foldtest.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE file with input data
        -F FILE for confidence bounds on fold test
        -u ANGLE (circular standard deviation) for uncertainty on bedding poles
        -b MIN MAX bounds for quick search of percent untilting [default is -10 to 150%]
        -n NB  number of bootstrap samples [default is 1000]
        -fmt FMT, specify format - default is svg
        -sav  save figures and quit
    INPUT FILE
	Dec Inc Dip_Direction Dip  in space delimited file

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

    OPTIONAL OUTPUT FILE:
       The output file has the % untilting within the 95% confidence bounds
nd the number of bootstrap samples
    """
    kappa = 0
    fmt, plot = 'svg', 0
    nb = 1000  # number of bootstraps
    min, max = -10, 150
    if '-h' in sys.argv:  # check if help is needed
        print main.__doc__
        sys.exit()  # graceful quit
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        outfile = open(sys.argv[ind + 1], 'w')
    else:
        outfile = ""
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file = sys.argv[ind + 1]
        DIDDs = numpy.loadtxt(file)
    else:
        print main.__doc__
        sys.exit()
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-sav' in sys.argv: plot = 1
    if '-b' in sys.argv:
        ind = sys.argv.index('-b')
        min = int(sys.argv[ind + 1])
        max = int(sys.argv[ind + 2])
    if '-n' in sys.argv:
        ind = sys.argv.index('-n')
        nb = int(sys.argv[ind + 1])
    if '-u' in sys.argv:
        ind = sys.argv.index('-u')
        csd = float(sys.argv[ind + 1])
        kappa = (81. / csd)**2
    #
    # get to work
    #
    PLTS = {'geo': 1, 'strat': 2, 'taus': 3}  # make plot dictionary
    pmagplotlib.plot_init(PLTS['geo'], 5, 5)
    pmagplotlib.plot_init(PLTS['strat'], 5, 5)
    pmagplotlib.plot_init(PLTS['taus'], 5, 5)
    pmagplotlib.plotEQ(PLTS['geo'], DIDDs, 'Geographic')
    D, I = pmag.dotilt_V(DIDDs)
    TCs = numpy.array([D, I]).transpose()
    pmagplotlib.plotEQ(PLTS['strat'], TCs, 'Stratigraphic')
    if plot == 0: pmagplotlib.drawFIGS(PLTS)
    Percs = range(min, max)
    Cdf, Untilt = [], []
    pylab.figure(num=PLTS['taus'])
    print 'doing ', nb, ' iterations...please be patient.....'
    for n in range(
            nb):  # do bootstrap data sets - plot first 25 as dashed red line
        if n % 50 == 0: print n
        Taus = []  # set up lists for taus
        PDs = pmag.pseudo(DIDDs)
        if kappa != 0:
            for k in range(len(PDs)):
                d, i = pmag.fshdev(kappa)
                dipdir, dip = pmag.dodirot(d, i, PDs[k][2], PDs[k][3])
                PDs[k][2] = dipdir
                PDs[k][3] = dip
        for perc in Percs:
            tilt = numpy.array([1., 1., 1., 0.01 * perc])
            D, I = pmag.dotilt_V(PDs * tilt)
            TCs = numpy.array([D, I]).transpose()
            ppars = pmag.doprinc(TCs)  # get principal directions
            Taus.append(ppars['tau1'])
        if n < 25: pylab.plot(Percs, Taus, 'r--')
        Untilt.append(Percs[Taus.index(
            numpy.max(Taus))])  # tilt that gives maximum tau
        Cdf.append(float(n) / float(nb))
    pylab.plot(Percs, Taus, 'k')
    pylab.xlabel('% Untilting')
    pylab.ylabel('tau_1 (red), CDF (green)')
    Untilt.sort()  # now for CDF of tilt of maximum tau
    pylab.plot(Untilt, Cdf, 'g')
    lower = int(.025 * nb)
    upper = int(.975 * nb)
    pylab.axvline(x=Untilt[lower], ymin=0, ymax=1, linewidth=1, linestyle='--')
    pylab.axvline(x=Untilt[upper], ymin=0, ymax=1, linewidth=1, linestyle='--')
    tit = '%i - %i %s' % (Untilt[lower], Untilt[upper], 'Percent Unfolding')
    print tit
    print 'range of all bootstrap samples: ', Untilt[0], ' - ', Untilt[-1]
    pylab.title(tit)
    outstring = '%i - %i; %i\n' % (Untilt[lower], Untilt[upper], nb)
    if outfile != "": outfile.write(outstring)
    files = {}
    for key in PLTS.keys():
        files[key] = ('foldtest_' + '%s' % (key.strip()[:2]) + '.' + fmt)
    if plot == 0:
        pmagplotlib.drawFIGS(PLTS)
        ans = raw_input('S[a]ve all figures, <Return> to quit   ')
        if ans != 'a':
            print "Good bye"
            sys.exit()
    pmagplotlib.saveP(PLTS, files)
예제 #9
0
def main():
    """
    NAME
       foldtest.py

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

    INPUT FORMAT
       dec inc dip_direction dip

    SYNTAX
       foldtest.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE file with input data
        -F FILE for confidence bounds on fold test
        -u ANGLE (circular standard deviation) for uncertainty on bedding poles
        -b MIN MAX bounds for quick search of percent untilting [default is -10 to 150%]
        -n NB  number of bootstrap samples [default is 1000]
        -fmt FMT, specify format - default is svg
        -sav  save figures and quit
    INPUT FILE
    Dec Inc Dip_Direction Dip  in space delimited file

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

    OPTIONAL OUTPUT FILE:
       The output file has the % untilting within the 95% confidence bounds
nd the number of bootstrap samples
    """
    kappa=0
    fmt,plot='svg',0
    nb=1000 # number of bootstraps
    min,max=-10,150
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        outfile=open(sys.argv[ind+1],'w')
    else:
        outfile=""
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        DIDDs=numpy.loadtxt(file)
    else:
        print(main.__doc__)
        sys.exit()
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-sav' in sys.argv:plot=1
    if '-b' in sys.argv:
        ind=sys.argv.index('-b')
        min=int(sys.argv[ind+1])
        max=int(sys.argv[ind+2])
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        nb=int(sys.argv[ind+1])
    if '-u' in sys.argv:
        ind=sys.argv.index('-u')
        csd=float(sys.argv[ind+1])
        kappa=(81. / csd)**2
    #
    # get to work
    #
    PLTS={'geo':1,'strat':2,'taus':3} # make plot dictionary
    pmagplotlib.plot_init(PLTS['geo'],5,5)
    pmagplotlib.plot_init(PLTS['strat'],5,5)
    pmagplotlib.plot_init(PLTS['taus'],5,5)
    pmagplotlib.plot_eq(PLTS['geo'],DIDDs,'Geographic')
    D,I=pmag.dotilt_V(DIDDs)
    TCs=numpy.array([D,I]).transpose()
    pmagplotlib.plot_eq(PLTS['strat'],TCs,'Stratigraphic')
    if not set_env.IS_WIN:
        if plot==0:pmagplotlib.draw_figs(PLTS)
    Percs=list(range(min,max))
    Cdf,Untilt=[],[]
    pylab.figure(num=PLTS['taus'])
    print('doing ',nb,' iterations...please be patient.....')
    for n in range(nb): # do bootstrap data sets - plot first 25 as dashed red line
            if n%50==0:print(n)
            Taus=[] # set up lists for taus
            PDs=pmag.pseudo(DIDDs)
            if kappa!=0:
                for k in range(len(PDs)):
                    d,i=pmag.fshdev(kappa)
                    dipdir,dip=pmag.dodirot(d,i,PDs[k][2],PDs[k][3])
                    PDs[k][2]=dipdir
                    PDs[k][3]=dip
            for perc in Percs:
                tilt=numpy.array([1.,1.,1.,0.01*perc])
                D,I=pmag.dotilt_V(PDs*tilt)
                TCs=numpy.array([D,I]).transpose()
                ppars=pmag.doprinc(TCs) # get principal directions
                Taus.append(ppars['tau1'])
            if n<25:pylab.plot(Percs,Taus,'r--')
            Untilt.append(Percs[Taus.index(numpy.max(Taus))]) # tilt that gives maximum tau
            Cdf.append(float(n) / float(nb))
    pylab.plot(Percs,Taus,'k')
    pylab.xlabel('% Untilting')
    pylab.ylabel('tau_1 (red), CDF (green)')
    Untilt.sort() # now for CDF of tilt of maximum tau
    pylab.plot(Untilt,Cdf,'g')
    lower=int(.025*nb)
    upper=int(.975*nb)
    pylab.axvline(x=Untilt[lower],ymin=0,ymax=1,linewidth=1,linestyle='--')
    pylab.axvline(x=Untilt[upper],ymin=0,ymax=1,linewidth=1,linestyle='--')
    tit= '%i - %i %s'%(Untilt[lower],Untilt[upper],'Percent Unfolding')
    print(tit)
    print('range of all bootstrap samples: ', Untilt[0], ' - ', Untilt[-1])
    pylab.title(tit)
    outstring= '%i - %i; %i\n'%(Untilt[lower],Untilt[upper],nb)
    if outfile!="":outfile.write(outstring)
    files={}
    for key in list(PLTS.keys()):
        files[key]=('foldtest_'+'%s'%(key.strip()[:2])+'.'+fmt)
    if plot==0:
        pmagplotlib.draw_figs(PLTS)
        ans= input('S[a]ve all figures, <Return> to quit   ')
        if ans!='a':
            print("Good bye")
            sys.exit()
    pmagplotlib.save_plots(PLTS,files)
def main():
    """
    NAME
       foldtest_magic.py

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

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

    SYNTAX
       foldtest_magic.py [command line options]

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

    """
    kappa=0
    nb=1000 # number of bootstraps
    min,max=-10,150
    dir_path='.'
    infile,orfile='pmag_sites.txt','er_samples.txt'
    critfile='pmag_criteria.txt'
    dipkey,azkey='sample_bed_dip','sample_bed_dip_direction'
    fmt='svg'
    plot=0
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        nb=int(sys.argv[ind+1])
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-sav' in sys.argv:plot=1
    if '-b' in sys.argv:
        ind=sys.argv.index('-b')
        min=int(sys.argv[ind+1])
        max=int(sys.argv[ind+2])
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        infile=sys.argv[ind+1] 
    if '-fsa' in sys.argv:
        ind=sys.argv.index('-fsa')
        orfile=sys.argv[ind+1] 
    elif '-fsi' in sys.argv:
        ind=sys.argv.index('-fsi')
        orfile=sys.argv[ind+1] 
        dipkey,azkey='site_bed_dip','site_bed_dip_direction'
    orfile=dir_path+'/'+orfile
    infile=dir_path+'/'+infile
    critfile=dir_path+'/'+critfile
    data,file_type=pmag.magic_read(infile)
    ordata,file_type=pmag.magic_read(orfile)
    if '-exc' in sys.argv:
        crits,file_type=pmag.magic_read(critfile)
        for crit in crits:
             if crit['pmag_criteria_code']=="DE-SITE":
                 SiteCrit=crit
                 break
# get to work
#
    PLTS={'geo':1,'strat':2,'taus':3} # make plot dictionary
    pmagplotlib.plot_init(PLTS['geo'],5,5)
    pmagplotlib.plot_init(PLTS['strat'],5,5)
    pmagplotlib.plot_init(PLTS['taus'],5,5)
    GEOrecs=pmag.get_dictitem(data,'site_tilt_correction','0','T')
    if len(GEOrecs)>0: # have some geographic data
        DIDDs= [] # set up list for dec inc  dip_direction, dip
        for rec in GEOrecs:   # parse data
            dip,dip_dir=0,-1
            Dec=float(rec['site_dec'])
            Inc=float(rec['site_inc'])
            orecs=pmag.get_dictitem(ordata,'er_site_name',rec['er_site_name'],'T')
            if len(orecs)>0:
                    if orecs[0][azkey]!="":dip_dir=float(orecs[0][azkey])
                    if orecs[0][dipkey]!="":dip=float(orecs[0][dipkey])
            if dip!=0 and dip_dir!=-1:
                if  '-exc' in  sys.argv:
                    keep=1
                    for key in SiteCrit.keys():
                        if 'site' in key  and SiteCrit[key]!="" and rec[key]!="" and key!='site_alpha95':
                            if float(rec[key])<float(SiteCrit[key]): 
                                keep=0
                                print rec['er_site_name'],key,rec[key]
                        if key=='site_alpha95'  and SiteCrit[key]!="" and rec[key]!="":
                            if float(rec[key])>float(SiteCrit[key]): 
                                keep=0
                    if keep==1:  DIDDs.append([Dec,Inc,dip_dir,dip])
                else:
                                DIDDs.append([Dec,Inc,dip_dir,dip])
    else:
        print 'no geographic directional data found'
        sys.exit()
    pmagplotlib.plotEQ(PLTS['geo'],DIDDs,'Geographic')
    data=numpy.array(DIDDs)
    D,I=pmag.dotilt_V(data)
    TCs=numpy.array([D,I]).transpose()
    pmagplotlib.plotEQ(PLTS['strat'],TCs,'Stratigraphic')
    if plot==0:pmagplotlib.drawFIGS(PLTS)
    Percs=range(min,max)
    Cdf,Untilt=[],[]
    pylab.figure(num=PLTS['taus'])
    print 'doing ',nb,' iterations...please be patient.....'
    for n in range(nb): # do bootstrap data sets - plot first 25 as dashed red line
            if n%50==0:print n
            Taus=[] # set up lists for taus
            PDs=pmag.pseudo(DIDDs)
            if kappa!=0:
                for k in range(len(PDs)):
                    d,i=pmag.fshdev(kappa)
                    dipdir,dip=pmag.dodirot(d,i,PDs[k][2],PDs[k][3])
                    PDs[k][2]=dipdir
                    PDs[k][3]=dip
            for perc in Percs:
                tilt=numpy.array([1.,1.,1.,0.01*perc])
                D,I=pmag.dotilt_V(PDs*tilt)
                TCs=numpy.array([D,I]).transpose()
                ppars=pmag.doprinc(TCs) # get principal directions
                Taus.append(ppars['tau1'])
            if n<25:pylab.plot(Percs,Taus,'r--')
            Untilt.append(Percs[Taus.index(numpy.max(Taus))]) # tilt that gives maximum tau
            Cdf.append(float(n)/float(nb))
    pylab.plot(Percs,Taus,'k')
    pylab.xlabel('% Untilting')
    pylab.ylabel('tau_1 (red), CDF (green)')
    Untilt.sort() # now for CDF of tilt of maximum tau
    pylab.plot(Untilt,Cdf,'g')
    lower=int(.025*nb)     
    upper=int(.975*nb)
    pylab.axvline(x=Untilt[lower],ymin=0,ymax=1,linewidth=1,linestyle='--')
    pylab.axvline(x=Untilt[upper],ymin=0,ymax=1,linewidth=1,linestyle='--')
    tit= '%i - %i %s'%(Untilt[lower],Untilt[upper],'Percent Unfolding')
    print tit
    pylab.title(tit)
    if plot==0:
        pmagplotlib.drawFIGS(PLTS)
        ans= raw_input('S[a]ve all figures, <Return> to quit  \n ')
        if ans!='a':
            print "Good bye"
            sys.exit()
    files={}
    for key in PLTS.keys():
        files[key]=('foldtest_'+'%s'%(key.strip()[:2])+'.'+fmt)
    pmagplotlib.saveP(PLTS,files)
예제 #11
0
def main():
    """
    NAME
        eqarea_ell.py

    DESCRIPTION
       makes equal area projections from declination/inclination data
       and plot ellipses

    SYNTAX
        eqarea_ell.py -h [command line options]

    INPUT
       takes space delimited Dec/Inc data

    OPTIONS
        -h prints help message and quits
        -f FILE
        -fmt [svg,png,jpg] format for output plots
        -sav  saves figures and quits
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
    """
    FIG={} # plot dictionary
    FIG['eq']=1 # eqarea is figure 1
    fmt,dist,mode,plot='svg','F',1,0
    sym={'lower':['o','r'],'upper':['o','w'],'size':10}
    plotE=0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if not set_env.IS_WIN:
        pmagplotlib.plot_init(FIG['eq'],5,5)
    if '-sav' in sys.argv:plot=1
    if '-f' in sys.argv:
        ind=sys.argv.index("-f")
        title=sys.argv[ind+1]
        data=numpy.loadtxt(title).transpose()
    if '-ell' in sys.argv:
        plotE=1
        ind=sys.argv.index('-ell')
        ell_type=sys.argv[ind+1]
        if ell_type=='F':dist='F'
        if ell_type=='K':dist='K'
        if ell_type=='B':dist='B'
        if ell_type=='Be':dist='BE'
        if ell_type=='Bv':
            dist='BV'
            FIG['bdirs']=2
            pmagplotlib.plot_init(FIG['bdirs'],5,5)
    if '-fmt' in sys.argv:
        ind=sys.argv.index("-fmt")
        fmt=sys.argv[ind+1]
    DIblock=numpy.array([data[0],data[1]]).transpose()
    if len(DIblock)>0:
        pmagplotlib.plot_eq_sym(FIG['eq'],DIblock,title,sym)
        #if plot==0:pmagplotlib.draw_figs(FIG)
    else:
        print("no data to plot")
        sys.exit()
    if plotE==1:
        ppars=pmag.doprinc(DIblock) # get principal directions
        nDIs,rDIs,npars,rpars=[],[],[],[]
        for rec in DIblock:
            angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
            if angle>90.:
                rDIs.append(rec)
            else:
                nDIs.append(rec)
        if dist=='B': # do on whole dataset
            etitle="Bingham confidence ellipse"
            bpars=pmag.dobingham(DIblock)
            for key in list(bpars.keys()):
                if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(bpars[key]))
                if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(bpars[key]))
            npars.append(bpars['dec'])
            npars.append(bpars['inc'])
            npars.append(bpars['Zeta'])
            npars.append(bpars['Zdec'])
            npars.append(bpars['Zinc'])
            npars.append(bpars['Eta'])
            npars.append(bpars['Edec'])
            npars.append(bpars['Einc'])
        if dist=='F':
            etitle="Fisher confidence cone"
            if len(nDIs)>3:
                fpars=pmag.fisher_mean(nDIs)
                for key in list(fpars.keys()):
                    if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(fpars[key]))
                    if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(fpars[key]))
                mode+=1
                npars.append(fpars['dec'])
                npars.append(fpars['inc'])
                npars.append(fpars['alpha95']) # Beta
                npars.append(fpars['dec'])
                isign=abs(fpars['inc']) / fpars['inc']
                npars.append(fpars['inc']-isign*90.) #Beta inc
                npars.append(fpars['alpha95']) # gamma
                npars.append(fpars['dec']+90.) # Beta dec
                npars.append(0.) #Beta inc
            if len(rDIs)>3:
                fpars=pmag.fisher_mean(rDIs)
                if pmagplotlib.verbose:print("mode ",mode)
                for key in list(fpars.keys()):
                    if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(fpars[key]))
                    if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(fpars[key]))
                mode+=1
                rpars.append(fpars['dec'])
                rpars.append(fpars['inc'])
                rpars.append(fpars['alpha95']) # Beta
                rpars.append(fpars['dec'])
                isign=abs(fpars['inc']) / fpars['inc']
                rpars.append(fpars['inc']-isign*90.) #Beta inc
                rpars.append(fpars['alpha95']) # gamma
                rpars.append(fpars['dec']+90.) # Beta dec
                rpars.append(0.) #Beta inc
        if dist=='K':
            etitle="Kent confidence ellipse"
            if len(nDIs)>3:
                kpars=pmag.dokent(nDIs,len(nDIs))
                if pmagplotlib.verbose:print("mode ",mode)
                for key in list(kpars.keys()):
                    if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(kpars[key]))
                    if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(kpars[key]))
                mode+=1
                npars.append(kpars['dec'])
                npars.append(kpars['inc'])
                npars.append(kpars['Zeta'])
                npars.append(kpars['Zdec'])
                npars.append(kpars['Zinc'])
                npars.append(kpars['Eta'])
                npars.append(kpars['Edec'])
                npars.append(kpars['Einc'])
            if len(rDIs)>3:
                kpars=pmag.dokent(rDIs,len(rDIs))
                if pmagplotlib.verbose:print("mode ",mode)
                for key in list(kpars.keys()):
                    if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(kpars[key]))
                    if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(kpars[key]))
                mode+=1
                rpars.append(kpars['dec'])
                rpars.append(kpars['inc'])
                rpars.append(kpars['Zeta'])
                rpars.append(kpars['Zdec'])
                rpars.append(kpars['Zinc'])
                rpars.append(kpars['Eta'])
                rpars.append(kpars['Edec'])
                rpars.append(kpars['Einc'])
        else: # assume bootstrap
            if len(nDIs)<10 and len(rDIs)<10:
                print('too few data points for bootstrap')
                sys.exit()
            if dist=='BE':
                print('Be patient for bootstrap...')
                if len(nDIs)>=10:
                    BnDIs=pmag.di_boot(nDIs)
                    Bkpars=pmag.dokent(BnDIs,1.)
                    if pmagplotlib.verbose:print("mode ",mode)
                    for key in list(Bkpars.keys()):
                        if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(Bkpars[key]))
                        if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(Bkpars[key]))
                    mode+=1
                    npars.append(Bkpars['dec'])
                    npars.append(Bkpars['inc'])
                    npars.append(Bkpars['Zeta'])
                    npars.append(Bkpars['Zdec'])
                    npars.append(Bkpars['Zinc'])
                    npars.append(Bkpars['Eta'])
                    npars.append(Bkpars['Edec'])
                    npars.append(Bkpars['Einc'])
                if len(rDIs)>=10:
                    BrDIs=pmag.di_boot(rDIs)
                    Bkpars=pmag.dokent(BrDIs,1.)
                    if pmagplotlib.verbose:print("mode ",mode)
                    for key in list(Bkpars.keys()):
                        if key!='n' and pmagplotlib.verbose:print("    ",key, '%7.1f'%(Bkpars[key]))
                        if key=='n' and pmagplotlib.verbose:print("    ",key, '       %i'%(Bkpars[key]))
                    mode+=1
                    rpars.append(Bkpars['dec'])
                    rpars.append(Bkpars['inc'])
                    rpars.append(Bkpars['Zeta'])
                    rpars.append(Bkpars['Zdec'])
                    rpars.append(Bkpars['Zinc'])
                    rpars.append(Bkpars['Eta'])
                    rpars.append(Bkpars['Edec'])
                    rpars.append(Bkpars['Einc'])
                etitle="Bootstrapped confidence ellipse"
            elif dist=='BV':
                print('Be patient for bootstrap...')
                vsym={'lower':['+','k'],'upper':['x','k'],'size':5}
                if len(nDIs)>5:
                    BnDIs=pmag.di_boot(nDIs)
                    pmagplotlib.plot_eq_sym(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors',vsym)
                if len(rDIs)>5:
                    BrDIs=pmag.di_boot(rDIs)
                    if len(nDIs)>5:  # plot on existing plots
                        pmagplotlib.plot_di_sym(FIG['bdirs'],BrDIs,vsym)
                    else:
                        pmagplotlib.plot_eq(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors',vsym)
        if dist=='B':
            if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plot_conf(FIG['eq'],etitle,[],npars,0)
        elif len(nDIs)>3 and dist!='BV':
            pmagplotlib.plot_conf(FIG['eq'],etitle,[],npars,0)
            if len(rDIs)>3:
                pmagplotlib.plot_conf(FIG['eq'],etitle,[],rpars,0)
        elif len(rDIs)>3 and dist!='BV':
            pmagplotlib.plot_conf(FIG['eq'],etitle,[],rpars,0)
        #if plot==0:pmagplotlib.draw_figs(FIG)
    if plot==0:pmagplotlib.draw_figs(FIG)
        #
    files={}
    for key in list(FIG.keys()):
        files[key]=title+'_'+key+'.'+fmt
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        FIG = pmagplotlib.add_borders(FIG,titles,black,purple)
        pmagplotlib.save_plots(FIG,files)
    elif plot==0:
        ans=input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans=="q": sys.exit()
        if ans=="a":
            pmagplotlib.save_plots(FIG,files)
    else:
        pmagplotlib.save_plots(FIG,files)
예제 #12
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

    INPUT
       takes magic formatted sites, samples, specimens, or measurements

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file from magic, default='sites.txt'
         supported types=[measurements, specimens, samples, sites]
        -fsp FILE: specify specimen file name, (required if you want to plot measurements by sample)
                default='specimens.txt'
        -fsa FILE: specify sample file name, (required if you want to plot specimens by site)
                default='samples.txt'
        -fsi FILE: specify site file name, default='sites.txt'

        -obj OBJ: specify  level of plot  [all, sit, sam, spc], default is all
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is geographic, unspecified assumed geographic
        -fmt [svg,png,jpg] format for output plots
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
        -c plot as colour contour
        -sav save plot and quit quietly
    NOTE
        all: entire file; sit: site; sam: sample; spc: specimen
    """
    # initialize some default variables
    FIG = {}  # plot dictionary
    FIG["eqarea"] = 1  # eqarea is figure 1
    plotE = 0
    plt = 0  # default to not plotting
    verbose = pmagplotlib.verbose
    # extract arguments from sys.argv
    if "-h" in sys.argv:
        print main.__doc__
        sys.exit()
    dir_path = pmag.get_named_arg_from_sys("-WD", default_val=os.getcwd())
    pmagplotlib.plot_init(FIG["eqarea"], 5, 5)
    in_file = pmag.get_named_arg_from_sys("-f", default_val="sites.txt")
    full_in_file = os.path.join(dir_path, in_file)
    plot_by = pmag.get_named_arg_from_sys("-obj", default_val="all").lower()
    spec_file = pmag.get_named_arg_from_sys("-fsp", default_val="specimens.txt")
    samp_file = pmag.get_named_arg_from_sys("-fsa", default_val="samples.txt")
    site_file = pmag.get_named_arg_from_sys("-fsi", default_val="sites.txt")
    if plot_by == "all":
        plot_key = "all"
    elif plot_by == "sit":
        plot_key = "site"
    elif plot_by == "sam":
        plot_key = "sample"
    elif plot_by == "spc":
        plot_key = "specimen"
    else:
        plot_key = "all"
    if "-c" in sys.argv:
        contour = 1
    else:
        contour = 0
    if "-sav" in sys.argv:
        plt = 1
        verbose = 0
    if "-ell" in sys.argv:
        plotE = 1
        ind = sys.argv.index("-ell")
        ell_type = sys.argv[ind + 1]
        ell_type = pmag.get_named_arg_from_sys("-ell", "F")
        dist = ell_type.upper()
        # if dist type is unrecognized, use Fisher
        if dist not in ["F", "K", "B", "BE", "BV"]:
            dist = "F"
        if dist == "BV":
            FIG["bdirs"] = 2
            pmagplotlib.plot_init(FIG["bdirs"], 5, 5)
    crd = pmag.get_named_arg_from_sys("-crd", default_val="g")
    if crd == "s":
        coord = "-1"
    elif crd == "t":
        coord = "100"
    else:
        coord = "0"

    fmt = pmag.get_named_arg_from_sys("-fmt", "svg")

    dec_key = "dir_dec"
    inc_key = "dir_inc"
    tilt_key = "dir_tilt_correction"
    # Dir_type_keys=['','site_direction_type','sample_direction_type','specimen_direction_type']

    #
    fnames = {"specimens": spec_file, "samples": samp_file, "sites": site_file}
    contribution = nb.Contribution(dir_path, custom_filenames=fnames, single_file=in_file)
    # the object that contains the DataFrame + useful helper methods:
    table_name = contribution.tables.keys()[0]
    data_container = contribution.tables[table_name]
    # the actual DataFrame:
    data = data_container.df

    # uses sample infile to add temporary site_name
    # column to the specimen table

    data_container = contribution.tables[table_name]
    data = data_container.df

    if (plot_key != "all") and (plot_key not in data.columns):
        data = contribution.propagate_name_down(plot_key, table_name)

    # add tilt key into DataFrame columns if it isn't there already
    if tilt_key not in data.columns:
        data.loc[:, tilt_key] = None

    if verbose:
        print len(data), " records read from ", in_file

    # find desired dec,inc data:
    dir_type_key = ""
    #
    # get plotlist if not plotting all records
    #
    plotlist = []
    if plot_key != "all":
        # return all where plot_key is not blank
        if plot_key not in data.columns:
            print 'Can\'t plot by "{}".  That header is not in infile: {}'.format(plot_key, in_file)
            return
        plots = data[data[plot_key].notnull()]
        plotlist = plots[plot_key].unique()  # grab unique values
    else:
        plotlist.append("All")

    for plot in plotlist:
        if verbose:
            print plot
        if plot == "All":
            # plot everything at once
            plot_data = data
        else:
            # pull out only partial data
            plot_data = data[data[plot_key] == plot]

        DIblock = []
        GCblock = []
        # SLblock, SPblock = [], []
        title = plot
        mode = 1
        k = 0

        if dec_key not in plot_data.columns:
            print "-W- No dec/inc data"
            continue
        # get all records where dec & inc values exist
        plot_data = plot_data[plot_data[dec_key].notnull() & plot_data[inc_key].notnull()]
        if plot_data.empty:
            continue
        # this sorting out is done in get_di_bock
        # if coord == '0':  # geographic, use records with no tilt key (or tilt_key 0)
        #    cond1 = plot_data[tilt_key].fillna('') == coord
        #    cond2 = plot_data[tilt_key].isnull()
        #    plot_data = plot_data[cond1 | cond2]
        # else:  # not geographic coordinates, use only records with correct tilt_key
        #    plot_data = plot_data[plot_data[tilt_key] == coord]

        # get metadata for naming the plot file
        locations = data_container.get_name("location", df_slice=plot_data)
        site = data_container.get_name("site", df_slice=plot_data)
        sample = data_container.get_name("sample", df_slice=plot_data)
        specimen = data_container.get_name("specimen", df_slice=plot_data)

        # make sure method_codes is in plot_data
        if "method_codes" not in plot_data.columns:
            plot_data["method_codes"] = ""

        # get data blocks
        DIblock = data_container.get_di_block(df_slice=plot_data, tilt_corr=coord, excl=["DE-BFP"])
        # SLblock = [[ind, row['method_codes']] for ind, row in plot_data.iterrows()]
        # get great circles
        great_circle_data = data_container.get_records_for_code("DE-BFP", incl=True, use_slice=True, sli=plot_data)

        if len(great_circle_data) > 0:
            gc_cond = great_circle_data[tilt_key] == coord
            GCblock = [[float(row[dec_key]), float(row[inc_key])] for ind, row in great_circle_data[gc_cond].iterrows()]
            # SPblock = [[ind, row['method_codes']] for ind, row in great_circle_data[gc_cond].iterrows()]

        if len(DIblock) > 0:
            if contour == 0:
                pmagplotlib.plotEQ(FIG["eqarea"], DIblock, title)
            else:
                pmagplotlib.plotEQcont(FIG["eqarea"], DIblock)
        else:
            pmagplotlib.plotNET(FIG["eqarea"])
        if len(GCblock) > 0:
            for rec in GCblock:
                pmagplotlib.plotC(FIG["eqarea"], rec, 90.0, "g")
        if len(DIblock) == 0 and len(GCblock) == 0:
            if verbose:
                print "no records for plotting"
            continue
            # sys.exit()
        if plotE == 1:
            ppars = pmag.doprinc(DIblock)  # get principal directions
            nDIs, rDIs, npars, rpars = [], [], [], []
            for rec in DIblock:
                angle = pmag.angle([rec[0], rec[1]], [ppars["dec"], ppars["inc"]])
                if angle > 90.0:
                    rDIs.append(rec)
                else:
                    nDIs.append(rec)
            if dist == "B":  # do on whole dataset
                etitle = "Bingham confidence ellipse"
                bpars = pmag.dobingham(DIblock)
                for key in bpars.keys():
                    if key != "n" and verbose:
                        print "    ", key, "%7.1f" % (bpars[key])
                    if key == "n" and verbose:
                        print "    ", key, "       %i" % (bpars[key])
                npars.append(bpars["dec"])
                npars.append(bpars["inc"])
                npars.append(bpars["Zeta"])
                npars.append(bpars["Zdec"])
                npars.append(bpars["Zinc"])
                npars.append(bpars["Eta"])
                npars.append(bpars["Edec"])
                npars.append(bpars["Einc"])
            if dist == "F":
                etitle = "Fisher confidence cone"
                if len(nDIs) > 2:
                    fpars = pmag.fisher_mean(nDIs)
                    for key in fpars.keys():
                        if key != "n" and verbose:
                            print "    ", key, "%7.1f" % (fpars[key])
                        if key == "n" and verbose:
                            print "    ", key, "       %i" % (fpars[key])
                    mode += 1
                    npars.append(fpars["dec"])
                    npars.append(fpars["inc"])
                    npars.append(fpars["alpha95"])  # Beta
                    npars.append(fpars["dec"])
                    isign = abs(fpars["inc"]) / fpars["inc"]
                    npars.append(fpars["inc"] - isign * 90.0)  # Beta inc
                    npars.append(fpars["alpha95"])  # gamma
                    npars.append(fpars["dec"] + 90.0)  # Beta dec
                    npars.append(0.0)  # Beta inc
                if len(rDIs) > 2:
                    fpars = pmag.fisher_mean(rDIs)
                    if verbose:
                        print "mode ", mode
                    for key in fpars.keys():
                        if key != "n" and verbose:
                            print "    ", key, "%7.1f" % (fpars[key])
                        if key == "n" and verbose:
                            print "    ", key, "       %i" % (fpars[key])
                    mode += 1
                    rpars.append(fpars["dec"])
                    rpars.append(fpars["inc"])
                    rpars.append(fpars["alpha95"])  # Beta
                    rpars.append(fpars["dec"])
                    isign = abs(fpars["inc"]) / fpars["inc"]
                    rpars.append(fpars["inc"] - isign * 90.0)  # Beta inc
                    rpars.append(fpars["alpha95"])  # gamma
                    rpars.append(fpars["dec"] + 90.0)  # Beta dec
                    rpars.append(0.0)  # Beta inc
            if dist == "K":
                etitle = "Kent confidence ellipse"
                if len(nDIs) > 3:
                    kpars = pmag.dokent(nDIs, len(nDIs))
                    if verbose:
                        print "mode ", mode
                    for key in kpars.keys():
                        if key != "n" and verbose:
                            print "    ", key, "%7.1f" % (kpars[key])
                        if key == "n" and verbose:
                            print "    ", key, "       %i" % (kpars[key])
                    mode += 1
                    npars.append(kpars["dec"])
                    npars.append(kpars["inc"])
                    npars.append(kpars["Zeta"])
                    npars.append(kpars["Zdec"])
                    npars.append(kpars["Zinc"])
                    npars.append(kpars["Eta"])
                    npars.append(kpars["Edec"])
                    npars.append(kpars["Einc"])
                if len(rDIs) > 3:
                    kpars = pmag.dokent(rDIs, len(rDIs))
                    if verbose:
                        print "mode ", mode
                    for key in kpars.keys():
                        if key != "n" and verbose:
                            print "    ", key, "%7.1f" % (kpars[key])
                        if key == "n" and verbose:
                            print "    ", key, "       %i" % (kpars[key])
                    mode += 1
                    rpars.append(kpars["dec"])
                    rpars.append(kpars["inc"])
                    rpars.append(kpars["Zeta"])
                    rpars.append(kpars["Zdec"])
                    rpars.append(kpars["Zinc"])
                    rpars.append(kpars["Eta"])
                    rpars.append(kpars["Edec"])
                    rpars.append(kpars["Einc"])
            else:  # assume bootstrap
                if dist == "BE":
                    if len(nDIs) > 5:
                        BnDIs = pmag.di_boot(nDIs)
                        Bkpars = pmag.dokent(BnDIs, 1.0)
                        if verbose:
                            print "mode ", mode
                        for key in Bkpars.keys():
                            if key != "n" and verbose:
                                print "    ", key, "%7.1f" % (Bkpars[key])
                            if key == "n" and verbose:
                                print "    ", key, "       %i" % (Bkpars[key])
                        mode += 1
                        npars.append(Bkpars["dec"])
                        npars.append(Bkpars["inc"])
                        npars.append(Bkpars["Zeta"])
                        npars.append(Bkpars["Zdec"])
                        npars.append(Bkpars["Zinc"])
                        npars.append(Bkpars["Eta"])
                        npars.append(Bkpars["Edec"])
                        npars.append(Bkpars["Einc"])
                    if len(rDIs) > 5:
                        BrDIs = pmag.di_boot(rDIs)
                        Bkpars = pmag.dokent(BrDIs, 1.0)
                        if verbose:
                            print "mode ", mode
                        for key in Bkpars.keys():
                            if key != "n" and verbose:
                                print "    ", key, "%7.1f" % (Bkpars[key])
                            if key == "n" and verbose:
                                print "    ", key, "       %i" % (Bkpars[key])
                        mode += 1
                        rpars.append(Bkpars["dec"])
                        rpars.append(Bkpars["inc"])
                        rpars.append(Bkpars["Zeta"])
                        rpars.append(Bkpars["Zdec"])
                        rpars.append(Bkpars["Zinc"])
                        rpars.append(Bkpars["Eta"])
                        rpars.append(Bkpars["Edec"])
                        rpars.append(Bkpars["Einc"])
                    etitle = "Bootstrapped confidence ellipse"
                elif dist == "BV":
                    sym = {"lower": ["o", "c"], "upper": ["o", "g"], "size": 3, "edgecolor": "face"}
                    if len(nDIs) > 5:
                        BnDIs = pmag.di_boot(nDIs)
                        pmagplotlib.plotEQsym(FIG["bdirs"], BnDIs, "Bootstrapped Eigenvectors", sym)
                    if len(rDIs) > 5:
                        BrDIs = pmag.di_boot(rDIs)
                        if len(nDIs) > 5:  # plot on existing plots
                            pmagplotlib.plotDIsym(FIG["bdirs"], BrDIs, sym)
                        else:
                            pmagplotlib.plotEQ(FIG["bdirs"], BrDIs, "Bootstrapped Eigenvectors")
            if dist == "B":
                if len(nDIs) > 3 or len(rDIs) > 3:
                    pmagplotlib.plotCONF(FIG["eqarea"], etitle, [], npars, 0)
            elif len(nDIs) > 3 and dist != "BV":
                pmagplotlib.plotCONF(FIG["eqarea"], etitle, [], npars, 0)
                if len(rDIs) > 3:
                    pmagplotlib.plotCONF(FIG["eqarea"], etitle, [], rpars, 0)
            elif len(rDIs) > 3 and dist != "BV":
                pmagplotlib.plotCONF(FIG["eqarea"], etitle, [], rpars, 0)

        for key in FIG.keys():
            files = {}
            filename = pmag.get_named_arg_from_sys("-fname")
            if filename:
                filename += "." + fmt
            else:
                filename = (
                    "LO:_"
                    + locations
                    + "_SI:_"
                    + site
                    + "_SA:_"
                    + sample
                    + "_SP:_"
                    + specimen
                    + "_CO:_"
                    + crd
                    + "_TY:_"
                    + key
                    + "_."
                    + fmt
                )
            files[key] = filename

        if pmagplotlib.isServer:
            black = "#000000"
            purple = "#800080"
            titles = {}
            titles["eq"] = "Equal Area Plot"
            FIG = pmagplotlib.addBorders(FIG, titles, black, purple)
            pmagplotlib.saveP(FIG, files)

        if plt:
            pmagplotlib.saveP(FIG, files)
            continue
        if verbose:
            pmagplotlib.drawFIGS(FIG)
            ans = raw_input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
            if ans == "q":
                sys.exit()
            if ans == "a":
                pmagplotlib.saveP(FIG, files)
        continue
예제 #13
0
def main():
    """
    NAME
       foldtest_magic.py

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

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

    SYNTAX
       foldtest_magic.py [command line options]

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

    """
    kappa = 0
    nb = 1000  # number of bootstraps
    min, max = -10, 150
    dir_path = '.'
    infile, orfile = 'pmag_sites.txt', 'er_samples.txt'
    critfile = 'pmag_criteria.txt'
    dipkey, azkey = 'sample_bed_dip', 'sample_bed_dip_direction'
    fmt = 'svg'
    plot = 0
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path = sys.argv[ind + 1]
    if '-h' in sys.argv:  # check if help is needed
        print(main.__doc__)
        sys.exit()  # graceful quit
    if '-n' in sys.argv:
        ind = sys.argv.index('-n')
        nb = int(sys.argv[ind + 1])
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-sav' in sys.argv: plot = 1
    if '-b' in sys.argv:
        ind = sys.argv.index('-b')
        min = int(sys.argv[ind + 1])
        max = int(sys.argv[ind + 2])
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        infile = sys.argv[ind + 1]
    if '-fsa' in sys.argv:
        ind = sys.argv.index('-fsa')
        orfile = sys.argv[ind + 1]
    elif '-fsi' in sys.argv:
        ind = sys.argv.index('-fsi')
        orfile = sys.argv[ind + 1]
        dipkey, azkey = 'site_bed_dip', 'site_bed_dip_direction'
    orfile = dir_path + '/' + orfile
    infile = dir_path + '/' + infile
    critfile = dir_path + '/' + critfile
    data, file_type = pmag.magic_read(infile)
    ordata, file_type = pmag.magic_read(orfile)
    if '-exc' in sys.argv:
        crits, file_type = pmag.magic_read(critfile)
        for crit in crits:
            if crit['pmag_criteria_code'] == "DE-SITE":
                SiteCrit = crit
                break


# get to work
#
    PLTS = {'geo': 1, 'strat': 2, 'taus': 3}  # make plot dictionary
    pmagplotlib.plot_init(PLTS['geo'], 5, 5)
    pmagplotlib.plot_init(PLTS['strat'], 5, 5)
    pmagplotlib.plot_init(PLTS['taus'], 5, 5)
    GEOrecs = pmag.get_dictitem(data, 'site_tilt_correction', '0', 'T')
    if len(GEOrecs) > 0:  # have some geographic data
        DIDDs = []  # set up list for dec inc  dip_direction, dip
        for rec in GEOrecs:  # parse data
            dip, dip_dir = 0, -1
            Dec = float(rec['site_dec'])
            Inc = float(rec['site_inc'])
            orecs = pmag.get_dictitem(ordata, 'er_site_name',
                                      rec['er_site_name'], 'T')
            if len(orecs) > 0:
                if orecs[0][azkey] != "": dip_dir = float(orecs[0][azkey])
                if orecs[0][dipkey] != "": dip = float(orecs[0][dipkey])
            if dip != 0 and dip_dir != -1:
                if '-exc' in sys.argv:
                    keep = 1
                    for key in list(SiteCrit.keys()):
                        if 'site' in key and SiteCrit[key] != "" and rec[
                                key] != "" and key != 'site_alpha95':
                            if float(rec[key]) < float(SiteCrit[key]):
                                keep = 0
                                print(rec['er_site_name'], key, rec[key])
                        if key == 'site_alpha95' and SiteCrit[
                                key] != "" and rec[key] != "":
                            if float(rec[key]) > float(SiteCrit[key]):
                                keep = 0
                    if keep == 1: DIDDs.append([Dec, Inc, dip_dir, dip])
                else:
                    DIDDs.append([Dec, Inc, dip_dir, dip])
    else:
        print('no geographic directional data found')
        sys.exit()
    pmagplotlib.plotEQ(PLTS['geo'], DIDDs, 'Geographic')
    data = numpy.array(DIDDs)
    D, I = pmag.dotilt_V(data)
    TCs = numpy.array([D, I]).transpose()
    pmagplotlib.plotEQ(PLTS['strat'], TCs, 'Stratigraphic')
    if plot == 0: pmagplotlib.drawFIGS(PLTS)
    Percs = list(range(min, max))
    Cdf, Untilt = [], []
    pylab.figure(num=PLTS['taus'])
    print('doing ', nb, ' iterations...please be patient.....')
    for n in range(
            nb):  # do bootstrap data sets - plot first 25 as dashed red line
        if n % 50 == 0: print(n)
        Taus = []  # set up lists for taus
        PDs = pmag.pseudo(DIDDs)
        if kappa != 0:
            for k in range(len(PDs)):
                d, i = pmag.fshdev(kappa)
                dipdir, dip = pmag.dodirot(d, i, PDs[k][2], PDs[k][3])
                PDs[k][2] = dipdir
                PDs[k][3] = dip
        for perc in Percs:
            tilt = numpy.array([1., 1., 1., 0.01 * perc])
            D, I = pmag.dotilt_V(PDs * tilt)
            TCs = numpy.array([D, I]).transpose()
            ppars = pmag.doprinc(TCs)  # get principal directions
            Taus.append(ppars['tau1'])
        if n < 25: pylab.plot(Percs, Taus, 'r--')
        Untilt.append(Percs[Taus.index(
            numpy.max(Taus))])  # tilt that gives maximum tau
        Cdf.append(old_div(float(n), float(nb)))
    pylab.plot(Percs, Taus, 'k')
    pylab.xlabel('% Untilting')
    pylab.ylabel('tau_1 (red), CDF (green)')
    Untilt.sort()  # now for CDF of tilt of maximum tau
    pylab.plot(Untilt, Cdf, 'g')
    lower = int(.025 * nb)
    upper = int(.975 * nb)
    pylab.axvline(x=Untilt[lower], ymin=0, ymax=1, linewidth=1, linestyle='--')
    pylab.axvline(x=Untilt[upper], ymin=0, ymax=1, linewidth=1, linestyle='--')
    tit = '%i - %i %s' % (Untilt[lower], Untilt[upper], 'Percent Unfolding')
    print(tit)
    pylab.title(tit)
    if plot == 0:
        pmagplotlib.drawFIGS(PLTS)
        ans = input('S[a]ve all figures, <Return> to quit  \n ')
        if ans != 'a':
            print("Good bye")
            sys.exit()
    files = {}
    for key in list(PLTS.keys()):
        files[key] = ('foldtest_' + '%s' % (key.strip()[:2]) + '.' + fmt)
    pmagplotlib.saveP(PLTS, files)
예제 #14
0
def main():
    """
    NAME
        find_EI.py

    DESCRIPTION
        Applies series of assumed flattening factor and "unsquishes" inclinations assuming tangent function.
        Finds flattening factor that gives elongation/inclination pair consistent with TK03.
        Finds bootstrap confidence bounds

    SYNTAX
        find_EI.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE specify input file name
        -n N specify number of bootstraps - the more the better, but slower!, default is 1000
        -sc uses a "site-level" correction to a Fisherian distribution instead
            of a "study-level" correction to a TK03-consistent distribution.
            Note that many directions (~ 100) are needed for this correction to be reliable.
        -fmt [svg,png,eps,pdf..] change plot format, default is svg
        -sav  saves the figures and quits

    INPUT
        dec/inc pairs, delimited with space or tabs

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

    """
    fmt,nb='svg',1000
    plot=0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
    else:
        print(main.__doc__)
        sys.exit()
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        nb=int(sys.argv[ind+1])
    if '-sc' in sys.argv:
        site_correction = True
    else:
        site_correction = False
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-sav' in sys.argv:plot=1
    data=numpy.loadtxt(file)
    upper,lower=int(round(.975*nb)),int(round(.025*nb))
    E,I=[],[]
    PLTS={'eq':1,'ei':2,'cdf':3,'v2':4}
    pmagplotlib.plot_init(PLTS['eq'],6,6)
    pmagplotlib.plot_init(PLTS['ei'],5,5)
    pmagplotlib.plot_init(PLTS['cdf'],5,5)
    pmagplotlib.plot_init(PLTS['v2'],5,5)
    pmagplotlib.plot_eq(PLTS['eq'],data,'Data')
    # this is a problem
    #if plot==0:pmagplotlib.draw_figs(PLTS)
    ppars=pmag.doprinc(data)
    Io=ppars['inc']
    n=ppars["N"]
    Es,Is,Fs,V2s=pmag.find_f(data)
    if site_correction:
        Inc,Elong=Is[Es.index(min(Es))],Es[Es.index(min(Es))]
        flat_f = Fs[Es.index(min(Es))]
    else:
        Inc,Elong=Is[-1],Es[-1]
        flat_f = Fs[-1]
    pmagplotlib.plot_ei(PLTS['ei'],Es,Is,flat_f)
    pmagplotlib.plot_v2s(PLTS['v2'],V2s,Is,flat_f)
    b=0
    print("Bootstrapping.... be patient")
    while b<nb:
        bdata=pmag.pseudo(data)
        Esb,Isb,Fsb,V2sb=pmag.find_f(bdata)
        if b<25:
            pmagplotlib.plot_ei(PLTS['ei'],Esb,Isb,Fsb[-1])
        if Esb[-1]!=0:
            ppars=pmag.doprinc(bdata)
            if site_correction:
                I.append(abs(Isb[Esb.index(min(Esb))]))
                E.append(Esb[Esb.index(min(Esb))])
            else:
                I.append(abs(Isb[-1]))
                E.append(Esb[-1])
            b+=1
            if b%25==0:print(b,' out of ',nb)
    I.sort()
    E.sort()
    Eexp=[]
    for i in I:
       Eexp.append(pmag.EI(i))
    if Inc==0:
        title= 'Pathological Distribution: '+'[%7.1f, %7.1f]' %(I[lower],I[upper])
    else:
        title= '%7.1f [%7.1f, %7.1f]' %( Inc, I[lower],I[upper])
    pmagplotlib.plot_ei(PLTS['ei'],Eexp,I,1)
    pmagplotlib.plot_cdf(PLTS['cdf'],I,'Inclinations','r',title)
    pmagplotlib.plot_vs(PLTS['cdf'],[I[lower],I[upper]],'b','--')
    pmagplotlib.plot_vs(PLTS['cdf'],[Inc],'g','-')
    pmagplotlib.plot_vs(PLTS['cdf'],[Io],'k','-')
    if plot==0:
        print('%7.1f %s %7.1f _ %7.1f ^ %7.1f:  %6.4f _ %6.4f ^ %6.4f' %(Io, " => ", Inc, I[lower],I[upper], Elong, E[lower],E[upper]))
        print("Io Inc  I_lower, I_upper, Elon, E_lower, E_upper")
        pmagplotlib.draw_figs(PLTS)
        ans = ""
        while ans not in ['q', 'a']:
            ans= input("S[a]ve plots - <q> to quit:  ")
        if ans=='q':
           print("\n Good bye\n")
           sys.exit()

    files={}
    files['eq']='findEI_eq.'+fmt
    files['ei']='findEI_ei.'+fmt
    files['cdf']='findEI_cdf.'+fmt
    files['v2']='findEI_v2.'+fmt
    pmagplotlib.save_plots(PLTS,files)
예제 #15
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX 
        eqarea_magic.py [command line options]
    
    INPUT 
       takes magic formatted pmag_results, pmag_sites, pmag_samples or pmag_specimens
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file from magic,default='pmag_results.txt'
         supported types=[magic_measurements,pmag_specimens, pmag_samples, pmag_sites, pmag_results, magic_web]
        -obj OBJ: specify  level of plot  [all, sit, sam, spc], default is all
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is geographic, unspecified assumed geographic
        -fmt [svg,png,jpg] format for output plots
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
        -c plot as colour contour 
        -sav save plot and quit quietly
    NOTE
        all: entire file; sit: site; sam: sample; spc: specimen
    """
    FIG={} # plot dictionary
    FIG['eqarea']=1 # eqarea is figure 1
    in_file,plot_key,coord,crd='pmag_results.txt','all',"0",'g'
    plotE,contour=0,0
    dir_path='.'
    fmt='svg'
    verbose=pmagplotlib.verbose
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    pmagplotlib.plot_init(FIG['eqarea'],5,5)
    if '-f' in sys.argv:
        ind=sys.argv.index("-f")
        in_file=dir_path+"/"+sys.argv[ind+1]
    if '-obj' in sys.argv:
        ind=sys.argv.index('-obj')
        plot_by=sys.argv[ind+1]
        if plot_by=='all':plot_key='all'
        if plot_by=='sit':plot_key='er_site_name'
        if plot_by=='sam':plot_key='er_sample_name'
        if plot_by=='spc':plot_key='er_specimen_name'
    if '-c' in sys.argv: contour=1
    plt=0
    if '-sav' in sys.argv: 
        plt=1
        verbose=0
    if '-ell' in sys.argv:
        plotE=1
        ind=sys.argv.index('-ell')
        ell_type=sys.argv[ind+1]
        if ell_type=='F':dist='F' 
        if ell_type=='K':dist='K' 
        if ell_type=='B':dist='B' 
        if ell_type=='Be':dist='BE' 
        if ell_type=='Bv':
            dist='BV' 
            FIG['bdirs']=2
            pmagplotlib.plot_init(FIG['bdirs'],5,5)
    if '-crd' in sys.argv:
        ind=sys.argv.index("-crd")
        crd=sys.argv[ind+1]
        if crd=='s':coord="-1"
        if crd=='g':coord="0"
        if crd=='t':coord="100"
    if '-fmt' in sys.argv:
        ind=sys.argv.index("-fmt")
        fmt=sys.argv[ind+1]
    Dec_keys=['site_dec','sample_dec','specimen_dec','measurement_dec','average_dec','none']
    Inc_keys=['site_inc','sample_inc','specimen_inc','measurement_inc','average_inc','none']
    Tilt_keys=['tilt_correction','site_tilt_correction','sample_tilt_correction','specimen_tilt_correction','none']
    Dir_type_keys=['','site_direction_type','sample_direction_type','specimen_direction_type']
    Name_keys=['er_specimen_name','er_sample_name','er_site_name','pmag_result_name']
    data,file_type=pmag.magic_read(in_file)
    if file_type=='pmag_results' and plot_key!="all":plot_key=plot_key+'s' # need plural for results table
    if verbose:    
        print len(data),' records read from ',in_file
    #
    #
    # find desired dec,inc data:
    #
    dir_type_key=''
    #
    # get plotlist if not plotting all records
    #
    plotlist=[]
    if plot_key!="all":
        plots=pmag.get_dictitem(data,plot_key,'','F')
        for  rec in plots:
            if rec[plot_key] not in plotlist:
                plotlist.append(rec[plot_key])
        plotlist.sort()
    else:
        plotlist.append('All')
    for plot in plotlist:
        #if verbose: print plot
        DIblock=[]
        GCblock=[]
        SLblock,SPblock=[],[]
        title=plot
        mode=1
        dec_key,inc_key,tilt_key,name_key,k="","","","",0
        if plot!="All": 
            odata=pmag.get_dictitem(data,plot_key,plot,'T')
        else: odata=data # data for this obj
        for dec_key in Dec_keys:
            Decs=pmag.get_dictitem(odata,dec_key,'','F') # get all records with this dec_key not blank 
            if len(Decs)>0: break
        for inc_key in Inc_keys:
            Incs=pmag.get_dictitem(Decs,inc_key,'','F') # get all records with this inc_key not blank 
            if len(Incs)>0: break
        for tilt_key in Tilt_keys:
            if tilt_key in Incs[0].keys(): break # find the tilt_key for these records
        if tilt_key=='none': # no tilt key in data, need to fix this with fake data which will be unknown tilt
            tilt_key='tilt_correction'
            for rec in Incs:rec[tilt_key]=''
        cdata=pmag.get_dictitem(Incs,tilt_key,coord,'T') # get all records matching specified coordinate system
        if coord=='0': # geographic
            udata=pmag.get_dictitem(Incs,tilt_key,'','T') # get all the blank records - assume geographic
            if len(cdata)==0: crd='' 
            if len(udata)>0:
                for d in udata:cdata.append(d)  
                crd=crd+'u'
        for name_key in Name_keys:
            Names=pmag.get_dictitem(cdata,name_key,'','F') # get all records with this name_key not blank 
            if len(Names)>0: break
        for dir_type_key in Dir_type_keys:
            Dirs=pmag.get_dictitem(cdata,dir_type_key,'','F') # get all records with this direction type
            if len(Dirs)>0: break
        if dir_type_key=="":dir_type_key='direction_type'
        locations,site,sample,specimen="","","",""
        for rec in cdata: # pick out the data
            if 'er_location_name' in rec.keys() and rec['er_location_name']!="" and rec['er_location_name'] not in locations:locations=locations+rec['er_location_name'].replace("/","")+"_"
            if 'er_location_names' in rec.keys() and rec['er_location_names']!="":
               locs=rec['er_location_names'].split(':')
               for loc in locs:
                   if loc not in locations:locations=locations+loc.replace("/","")+'_'
            if plot_key=='er_site_name' or plot_key=='er_sample_name' or plot_key=='er_specimen_name':
                site=rec['er_site_name']
            if plot_key=='er_sample_name' or plot_key=='er_specimen_name':
                sample=rec['er_sample_name']
            if plot_key=='er_specimen_name':
                specimen=rec['er_specimen_name']
            if plot_key=='er_site_names' or plot_key=='er_sample_names' or plot_key=='er_specimen_names':
                site=rec['er_site_names']
            if plot_key=='er_sample_names' or plot_key=='er_specimen_names':
                sample=rec['er_sample_names']
            if plot_key=='er_specimen_names':
                specimen=rec['er_specimen_names']
            if dir_type_key not in rec.keys() or rec[dir_type_key]=="":rec[dir_type_key]='l'
            if 'magic_method_codes' not in rec.keys():rec['magic_method_codes']=""
            DIblock.append([float(rec[dec_key]),float(rec[inc_key])])
            SLblock.append([rec[name_key],rec['magic_method_codes']])
            if rec[tilt_key]==coord and rec[dir_type_key]!='l' and rec[dec_key]!="" and rec[inc_key]!="":
                GCblock.append([float(rec[dec_key]),float(rec[inc_key])])
                SPblock.append([rec[name_key],rec['magic_method_codes']])
        if len(DIblock)==0 and len(GCblock)==0:
            if verbose: print "no records for plotting"
            sys.exit()
        if verbose:
          for k in range(len(SLblock)):
            print '%s %s %7.1f %7.1f'%(SLblock[k][0],SLblock[k][1],DIblock[k][0],DIblock[k][1])
          for k in range(len(SPblock)):
            print '%s %s %7.1f %7.1f'%(SPblock[k][0],SPblock[k][1],GCblock[k][0],GCblock[k][1])
        if len(DIblock)>0: 
            if contour==0:
                pmagplotlib.plotEQ(FIG['eqarea'],DIblock,title)
            else:
                pmagplotlib.plotEQcont(FIG['eqarea'],DIblock)
        else:   pmagplotlib.plotNET(FIG['eqarea'])
        if len(GCblock)>0:
            for rec in GCblock: pmagplotlib.plotC(FIG['eqarea'],rec,90.,'g')
        if plotE==1:
            ppars=pmag.doprinc(DIblock) # get principal directions
            nDIs,rDIs,npars,rpars=[],[],[],[]
            for rec in DIblock:
                angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
                if angle>90.:
                    rDIs.append(rec)
                else:
                    nDIs.append(rec)
            if dist=='B': # do on whole dataset
                etitle="Bingham confidence ellipse"
                bpars=pmag.dobingham(DIblock)
                for key in bpars.keys():
                    if key!='n' and verbose:print "    ",key, '%7.1f'%(bpars[key])
                    if key=='n' and verbose:print "    ",key, '       %i'%(bpars[key])
                npars.append(bpars['dec']) 
                npars.append(bpars['inc'])
                npars.append(bpars['Zeta']) 
                npars.append(bpars['Zdec']) 
                npars.append(bpars['Zinc'])
                npars.append(bpars['Eta']) 
                npars.append(bpars['Edec']) 
                npars.append(bpars['Einc'])
            if dist=='F':
                etitle="Fisher confidence cone"
                if len(nDIs)>2:
                    fpars=pmag.fisher_mean(nDIs)
                    for key in fpars.keys():
                        if key!='n' and verbose:print "    ",key, '%7.1f'%(fpars[key])
                        if key=='n' and verbose:print "    ",key, '       %i'%(fpars[key])
                    mode+=1
                    npars.append(fpars['dec']) 
                    npars.append(fpars['inc'])
                    npars.append(fpars['alpha95']) # Beta
                    npars.append(fpars['dec']) 
                    isign=abs(fpars['inc'])/fpars['inc'] 
                    npars.append(fpars['inc']-isign*90.) #Beta inc
                    npars.append(fpars['alpha95']) # gamma 
                    npars.append(fpars['dec']+90.) # Beta dec
                    npars.append(0.) #Beta inc
                if len(rDIs)>2:
                    fpars=pmag.fisher_mean(rDIs)
                    if verbose:print "mode ",mode
                    for key in fpars.keys():
                        if key!='n' and verbose:print "    ",key, '%7.1f'%(fpars[key])
                        if key=='n' and verbose:print "    ",key, '       %i'%(fpars[key])
                    mode+=1
                    rpars.append(fpars['dec']) 
                    rpars.append(fpars['inc'])
                    rpars.append(fpars['alpha95']) # Beta
                    rpars.append(fpars['dec']) 
                    isign=abs(fpars['inc'])/fpars['inc'] 
                    rpars.append(fpars['inc']-isign*90.) #Beta inc
                    rpars.append(fpars['alpha95']) # gamma 
                    rpars.append(fpars['dec']+90.) # Beta dec
                    rpars.append(0.) #Beta inc
            if dist=='K':
                etitle="Kent confidence ellipse"
                if len(nDIs)>3:
                    kpars=pmag.dokent(nDIs,len(nDIs))
                    if verbose:print "mode ",mode
                    for key in kpars.keys():
                        if key!='n' and verbose:print "    ",key, '%7.1f'%(kpars[key])
                        if key=='n' and verbose:print "    ",key, '       %i'%(kpars[key])
                    mode+=1
                    npars.append(kpars['dec']) 
                    npars.append(kpars['inc'])
                    npars.append(kpars['Zeta']) 
                    npars.append(kpars['Zdec']) 
                    npars.append(kpars['Zinc'])
                    npars.append(kpars['Eta']) 
                    npars.append(kpars['Edec']) 
                    npars.append(kpars['Einc'])
                if len(rDIs)>3:
                    kpars=pmag.dokent(rDIs,len(rDIs))
                    if verbose:print "mode ",mode
                    for key in kpars.keys():
                        if key!='n' and verbose:print "    ",key, '%7.1f'%(kpars[key])
                        if key=='n' and verbose:print "    ",key, '       %i'%(kpars[key])
                    mode+=1
                    rpars.append(kpars['dec']) 
                    rpars.append(kpars['inc'])
                    rpars.append(kpars['Zeta']) 
                    rpars.append(kpars['Zdec']) 
                    rpars.append(kpars['Zinc'])
                    rpars.append(kpars['Eta']) 
                    rpars.append(kpars['Edec']) 
                    rpars.append(kpars['Einc'])
            else: # assume bootstrap
                if dist=='BE':
                    if len(nDIs)>5:
                        BnDIs=pmag.di_boot(nDIs)
                        Bkpars=pmag.dokent(BnDIs,1.)
                        if verbose:print "mode ",mode
                        for key in Bkpars.keys():
                            if key!='n' and verbose:print "    ",key, '%7.1f'%(Bkpars[key])
                            if key=='n' and verbose:print "    ",key, '       %i'%(Bkpars[key])
                        mode+=1
                        npars.append(Bkpars['dec']) 
                        npars.append(Bkpars['inc'])
                        npars.append(Bkpars['Zeta']) 
                        npars.append(Bkpars['Zdec']) 
                        npars.append(Bkpars['Zinc'])
                        npars.append(Bkpars['Eta']) 
                        npars.append(Bkpars['Edec']) 
                        npars.append(Bkpars['Einc'])
                    if len(rDIs)>5:
                        BrDIs=pmag.di_boot(rDIs)
                        Bkpars=pmag.dokent(BrDIs,1.)
                        if verbose:print "mode ",mode
                        for key in Bkpars.keys():
                            if key!='n' and verbose:print "    ",key, '%7.1f'%(Bkpars[key])
                            if key=='n' and verbose:print "    ",key, '       %i'%(Bkpars[key])
                        mode+=1
                        rpars.append(Bkpars['dec']) 
                        rpars.append(Bkpars['inc'])
                        rpars.append(Bkpars['Zeta']) 
                        rpars.append(Bkpars['Zdec']) 
                        rpars.append(Bkpars['Zinc'])
                        rpars.append(Bkpars['Eta']) 
                        rpars.append(Bkpars['Edec']) 
                        rpars.append(Bkpars['Einc'])
                    etitle="Bootstrapped confidence ellipse"
                elif dist=='BV':
                    sym={'lower':['o','c'],'upper':['o','g'],'size':3,'edgecolor':'face'}
                    if len(nDIs)>5:
                        BnDIs=pmag.di_boot(nDIs)
                        pmagplotlib.plotEQsym(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors', sym)
                    if len(rDIs)>5:
                        BrDIs=pmag.di_boot(rDIs)
                        if len(nDIs)>5:  # plot on existing plots
                            pmagplotlib.plotDIsym(FIG['bdirs'],BrDIs,sym)
                        else:
                            pmagplotlib.plotEQ(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors')
            if dist=='B':
                if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],npars,0)
            elif len(nDIs)>3 and dist!='BV':
                pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],npars,0)
                if len(rDIs)>3:
                    pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],rpars,0)
            elif len(rDIs)>3 and dist!='BV':
                pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],rpars,0)
        if verbose:pmagplotlib.drawFIGS(FIG)
            #
        files={}
        locations=locations[:-1]
        for key in FIG.keys():
            filename='LO:_'+locations+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+specimen+'_CO:_'+crd+'_TY:_'+key+'_.'+fmt
            files[key]=filename 
        if pmagplotlib.isServer:
            black     = '#000000'
            purple    = '#800080'
            titles={}
            titles['eq']='Equal Area Plot'
            FIG = pmagplotlib.addBorders(FIG,titles,black,purple)
            pmagplotlib.saveP(FIG,files)
        elif verbose:
            ans=raw_input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
            if ans=="q": sys.exit()
            if ans=="a": pmagplotlib.saveP(FIG,files) 
        if plt:
           pmagplotlib.saveP(FIG,files) 
예제 #16
0
def main():
    """
    NAME
       fishqq.py

    DESCRIPTION
       makes qq plot from dec,inc input data

    INPUT FORMAT
       takes dec/inc pairs in space delimited file

    SYNTAX
       fishqq.py [command line options]

    OPTIONS
        -h help message
        -f FILE, specify file on command line
        -F FILE, specify output file for statistics
        -sav save and quit [saves as input file name plus fmt extension]
        -fmt specify format for output [png, eps, svg, pdf] 

    OUTPUT:
        Dec Inc N Mu Mu_crit Me Me_crit Y/N
     where direction is the principal component and Y/N is Fisherian or not
     separate lines for each mode with N >=10 (N and R)
    """
    fmt,plot='svg',0
    outfile=""
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    elif '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'rU')
        data=f.readlines()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        outfile=open(sys.argv[ind+1],'w') # open output file
    if '-sav' in sys.argv: plot=1
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    DIs,nDIs,rDIs= [],[],[] # set up list for data
    for line in data:   # read in the data from standard input
        if '\t' in line:
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        DIs.append([float(rec[0]),float(rec[1])]) # append data to Inc
# split into two modes
    ppars=pmag.doprinc(DIs) # get principal directions
    for rec in DIs:
        angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
        if angle>90.:
            rDIs.append(rec)
        else:
            nDIs.append(rec)
    
#
    if len(rDIs) >=10 or len(nDIs) >=10:
        D1,I1=[],[]
        QQ={'unf1':1,'exp1':2}
        pmagplotlib.plot_init(QQ['unf1'],5,5)
        pmagplotlib.plot_init(QQ['exp1'],5,5)
        if len(nDIs) < 10: 
            ppars=pmag.doprinc(rDIs) # get principal directions
            Drbar,Irbar=ppars['dec']-180.,-ppars['inc']
            Nr=len(rDIs)
            for di in rDIs:
                d,irot=pmag.dotilt(di[0],di[1],Drbar-180.,90.-Irbar) # rotate to mean
                drot=d-180.
                if drot<0:drot=drot+360.
                D1.append(drot)           
                I1.append(irot) 
                Dtit='Mode 2 Declinations'
                Itit='Mode 2 Inclinations'
        else:          
            ppars=pmag.doprinc(nDIs) # get principal directions
            Dnbar,Inbar=ppars['dec'],ppars['inc']
            Nn=len(nDIs)
            for di in nDIs:
                d,irot=pmag.dotilt(di[0],di[1],Dnbar-180.,90.-Inbar) # rotate to mean
                drot=d-180.
                if drot<0:drot=drot+360.
                D1.append(drot)
                I1.append(irot)
                Dtit='Mode 1 Declinations'
                Itit='Mode 1 Inclinations'
        Mu_n,Mu_ncr=pmagplotlib.plotQQunf(QQ['unf1'],D1,Dtit) # make plot
        Me_n,Me_ncr=pmagplotlib.plotQQexp(QQ['exp1'],I1,Itit) # make plot
        #print Mu_n,Mu_ncr,Me_n, Me_ncr
        if outfile!="":
#        Dec Inc N Mu Mu_crit Me Me_crit Y/N
            if Mu_n<=Mu_ncr and Me_n<=Me_ncr:
               F='Y'
            else:
               F='N'
            outstring='%7.1f %7.1f %i %5.3f %5.3f %5.3f %5.3f %s \n'%(Dnbar,Inbar,Nn,Mu_n,Mu_ncr,Me_n,Me_ncr,F)
            outfile.write(outstring)
    else:
        print 'you need N> 10 for at least one mode'
        sys.exit()
    if len(rDIs)>10 and len(nDIs)>10:
        D2,I2=[],[]
        QQ['unf2']=3
        QQ['exp2']=4
        pmagplotlib.plot_init(QQ['unf2'],5,5)
        pmagplotlib.plot_init(QQ['exp2'],5,5)
        ppars=pmag.doprinc(rDIs) # get principal directions
        Drbar,Irbar=ppars['dec']-180.,-ppars['inc']
        Nr=len(rDIs)
        for di in rDIs:
            d,irot=pmag.dotilt(di[0],di[1],Drbar-180.,90.-Irbar) # rotate to mean
            drot=d-180.
            if drot<0:drot=drot+360.
            D2.append(drot)           
            I2.append(irot) 
            Dtit='Mode 2 Declinations'
            Itit='Mode 2 Inclinations'
        Mu_r,Mu_rcr=pmagplotlib.plotQQunf(QQ['unf2'],D2,Dtit) # make plot
        Me_r,Me_rcr=pmagplotlib.plotQQexp(QQ['exp2'],I2,Itit) # make plot
        if outfile!="":
#        Dec Inc N Mu Mu_crit Me Me_crit Y/N
            if Mu_r<=Mu_rcr and Me_r<=Me_rcr:
               F='Y'
            else:
               F='N'
            outstring='%7.1f %7.1f %i %5.3f %5.3f %5.3f %5.3f %s \n'%(Drbar,Irbar,Nr,Mu_r,Mu_rcr,Me_r,Me_rcr,F)
            outfile.write(outstring)
    files={}
    for key in QQ.keys():
        files[key]=file+'_'+key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.addBorders(EQ,titles,black,purple)
        pmagplotlib.saveP(QQ,files)
    elif plot==1:
        pmagplotlib.saveP(QQ,files)
    else:
        pmagplotlib.drawFIGS(QQ) 
        ans=raw_input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.saveP(QQ,files)
예제 #17
0
def main():
    """
    NAME
        eqarea_ell.py

    DESCRIPTION
       makes equal area projections from declination/inclination data
       and plot ellipses

    SYNTAX 
        eqarea_ell.py -h [command line options]
    
    INPUT 
       takes space delimited Dec/Inc data
    
    OPTIONS
        -h prints help message and quits
        -f FILE
        -fmt [svg,png,jpg] format for output plots
        -sav  saves figures and quits
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
    """
    FIG = {}  # plot dictionary
    FIG['eq'] = 1  # eqarea is figure 1
    fmt, dist, mode, plot = 'svg', 'F', 1, 0
    sym = {'lower': ['o', 'r'], 'upper': ['o', 'w'], 'size': 10}
    plotE = 0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    pmagplotlib.plot_init(FIG['eq'], 5, 5)
    if '-sav' in sys.argv: plot = 1
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        title = sys.argv[ind + 1]
        data = numpy.loadtxt(title).transpose()
    if '-ell' in sys.argv:
        plotE = 1
        ind = sys.argv.index('-ell')
        ell_type = sys.argv[ind + 1]
        if ell_type == 'F': dist = 'F'
        if ell_type == 'K': dist = 'K'
        if ell_type == 'B': dist = 'B'
        if ell_type == 'Be': dist = 'BE'
        if ell_type == 'Bv':
            dist = 'BV'
            FIG['bdirs'] = 2
            pmagplotlib.plot_init(FIG['bdirs'], 5, 5)
    if '-fmt' in sys.argv:
        ind = sys.argv.index("-fmt")
        fmt = sys.argv[ind + 1]
    DIblock = numpy.array([data[0], data[1]]).transpose()
    if len(DIblock) > 0:
        pmagplotlib.plotEQsym(FIG['eq'], DIblock, title, sym)
        if plot == 0: pmagplotlib.drawFIGS(FIG)
    else:
        print("no data to plot")
        sys.exit()
    if plotE == 1:
        ppars = pmag.doprinc(DIblock)  # get principal directions
        nDIs, rDIs, npars, rpars = [], [], [], []
        for rec in DIblock:
            angle = pmag.angle([rec[0], rec[1]], [ppars['dec'], ppars['inc']])
            if angle > 90.:
                rDIs.append(rec)
            else:
                nDIs.append(rec)
        if dist == 'B':  # do on whole dataset
            etitle = "Bingham confidence ellipse"
            bpars = pmag.dobingham(DIblock)
            for key in list(bpars.keys()):
                if key != 'n' and pmagplotlib.verbose:
                    print("    ", key, '%7.1f' % (bpars[key]))
                if key == 'n' and pmagplotlib.verbose:
                    print("    ", key, '       %i' % (bpars[key]))
            npars.append(bpars['dec'])
            npars.append(bpars['inc'])
            npars.append(bpars['Zeta'])
            npars.append(bpars['Zdec'])
            npars.append(bpars['Zinc'])
            npars.append(bpars['Eta'])
            npars.append(bpars['Edec'])
            npars.append(bpars['Einc'])
        if dist == 'F':
            etitle = "Fisher confidence cone"
            if len(nDIs) > 3:
                fpars = pmag.fisher_mean(nDIs)
                for key in list(fpars.keys()):
                    if key != 'n' and pmagplotlib.verbose:
                        print("    ", key, '%7.1f' % (fpars[key]))
                    if key == 'n' and pmagplotlib.verbose:
                        print("    ", key, '       %i' % (fpars[key]))
                mode += 1
                npars.append(fpars['dec'])
                npars.append(fpars['inc'])
                npars.append(fpars['alpha95'])  # Beta
                npars.append(fpars['dec'])
                isign = old_div(abs(fpars['inc']), fpars['inc'])
                npars.append(fpars['inc'] - isign * 90.)  #Beta inc
                npars.append(fpars['alpha95'])  # gamma
                npars.append(fpars['dec'] + 90.)  # Beta dec
                npars.append(0.)  #Beta inc
            if len(rDIs) > 3:
                fpars = pmag.fisher_mean(rDIs)
                if pmagplotlib.verbose: print("mode ", mode)
                for key in list(fpars.keys()):
                    if key != 'n' and pmagplotlib.verbose:
                        print("    ", key, '%7.1f' % (fpars[key]))
                    if key == 'n' and pmagplotlib.verbose:
                        print("    ", key, '       %i' % (fpars[key]))
                mode += 1
                rpars.append(fpars['dec'])
                rpars.append(fpars['inc'])
                rpars.append(fpars['alpha95'])  # Beta
                rpars.append(fpars['dec'])
                isign = old_div(abs(fpars['inc']), fpars['inc'])
                rpars.append(fpars['inc'] - isign * 90.)  #Beta inc
                rpars.append(fpars['alpha95'])  # gamma
                rpars.append(fpars['dec'] + 90.)  # Beta dec
                rpars.append(0.)  #Beta inc
        if dist == 'K':
            etitle = "Kent confidence ellipse"
            if len(nDIs) > 3:
                kpars = pmag.dokent(nDIs, len(nDIs))
                if pmagplotlib.verbose: print("mode ", mode)
                for key in list(kpars.keys()):
                    if key != 'n' and pmagplotlib.verbose:
                        print("    ", key, '%7.1f' % (kpars[key]))
                    if key == 'n' and pmagplotlib.verbose:
                        print("    ", key, '       %i' % (kpars[key]))
                mode += 1
                npars.append(kpars['dec'])
                npars.append(kpars['inc'])
                npars.append(kpars['Zeta'])
                npars.append(kpars['Zdec'])
                npars.append(kpars['Zinc'])
                npars.append(kpars['Eta'])
                npars.append(kpars['Edec'])
                npars.append(kpars['Einc'])
            if len(rDIs) > 3:
                kpars = pmag.dokent(rDIs, len(rDIs))
                if pmagplotlib.verbose: print("mode ", mode)
                for key in list(kpars.keys()):
                    if key != 'n' and pmagplotlib.verbose:
                        print("    ", key, '%7.1f' % (kpars[key]))
                    if key == 'n' and pmagplotlib.verbose:
                        print("    ", key, '       %i' % (kpars[key]))
                mode += 1
                rpars.append(kpars['dec'])
                rpars.append(kpars['inc'])
                rpars.append(kpars['Zeta'])
                rpars.append(kpars['Zdec'])
                rpars.append(kpars['Zinc'])
                rpars.append(kpars['Eta'])
                rpars.append(kpars['Edec'])
                rpars.append(kpars['Einc'])
        else:  # assume bootstrap
            if len(nDIs) < 10 and len(rDIs) < 10:
                print('too few data points for bootstrap')
                sys.exit()
            if dist == 'BE':
                print('Be patient for bootstrap...')
                if len(nDIs) >= 10:
                    BnDIs = pmag.di_boot(nDIs)
                    Bkpars = pmag.dokent(BnDIs, 1.)
                    if pmagplotlib.verbose: print("mode ", mode)
                    for key in list(Bkpars.keys()):
                        if key != 'n' and pmagplotlib.verbose:
                            print("    ", key, '%7.1f' % (Bkpars[key]))
                        if key == 'n' and pmagplotlib.verbose:
                            print("    ", key, '       %i' % (Bkpars[key]))
                    mode += 1
                    npars.append(Bkpars['dec'])
                    npars.append(Bkpars['inc'])
                    npars.append(Bkpars['Zeta'])
                    npars.append(Bkpars['Zdec'])
                    npars.append(Bkpars['Zinc'])
                    npars.append(Bkpars['Eta'])
                    npars.append(Bkpars['Edec'])
                    npars.append(Bkpars['Einc'])
                if len(rDIs) >= 10:
                    BrDIs = pmag.di_boot(rDIs)
                    Bkpars = pmag.dokent(BrDIs, 1.)
                    if pmagplotlib.verbose: print("mode ", mode)
                    for key in list(Bkpars.keys()):
                        if key != 'n' and pmagplotlib.verbose:
                            print("    ", key, '%7.1f' % (Bkpars[key]))
                        if key == 'n' and pmagplotlib.verbose:
                            print("    ", key, '       %i' % (Bkpars[key]))
                    mode += 1
                    rpars.append(Bkpars['dec'])
                    rpars.append(Bkpars['inc'])
                    rpars.append(Bkpars['Zeta'])
                    rpars.append(Bkpars['Zdec'])
                    rpars.append(Bkpars['Zinc'])
                    rpars.append(Bkpars['Eta'])
                    rpars.append(Bkpars['Edec'])
                    rpars.append(Bkpars['Einc'])
                etitle = "Bootstrapped confidence ellipse"
            elif dist == 'BV':
                print('Be patient for bootstrap...')
                vsym = {'lower': ['+', 'k'], 'upper': ['x', 'k'], 'size': 5}
                if len(nDIs) > 5:
                    BnDIs = pmag.di_boot(nDIs)
                    pmagplotlib.plotEQsym(FIG['bdirs'], BnDIs,
                                          'Bootstrapped Eigenvectors', vsym)
                if len(rDIs) > 5:
                    BrDIs = pmag.di_boot(rDIs)
                    if len(nDIs) > 5:  # plot on existing plots
                        pmagplotlib.plotDIsym(FIG['bdirs'], BrDIs, vsym)
                    else:
                        pmagplotlib.plotEQ(FIG['bdirs'], BrDIs,
                                           'Bootstrapped Eigenvectors', vsym)
        if dist == 'B':
            if len(nDIs) > 3 or len(rDIs) > 3:
                pmagplotlib.plotCONF(FIG['eq'], etitle, [], npars, 0)
        elif len(nDIs) > 3 and dist != 'BV':
            pmagplotlib.plotCONF(FIG['eq'], etitle, [], npars, 0)
            if len(rDIs) > 3:
                pmagplotlib.plotCONF(FIG['eq'], etitle, [], rpars, 0)
        elif len(rDIs) > 3 and dist != 'BV':
            pmagplotlib.plotCONF(FIG['eq'], etitle, [], rpars, 0)
        if plot == 0: pmagplotlib.drawFIGS(FIG)
    if plot == 0: pmagplotlib.drawFIGS(FIG)
    #
    files = {}
    for key in list(FIG.keys()):
        files[key] = title + '_' + key + '.' + fmt
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['eq'] = 'Equal Area Plot'
        FIG = pmagplotlib.addBorders(FIG, titles, black, purple)
        pmagplotlib.saveP(FIG, files)
    elif plot == 0:
        ans = input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans == "q": sys.exit()
        if ans == "a":
            pmagplotlib.saveP(FIG, files)
    else:
        pmagplotlib.saveP(FIG, files)
예제 #18
0
def main():
    """
    NAME
        scalc.py

    DESCRIPTION
       calculates Sb from VGP Long,VGP Lat,Directional kappa,Site latitude data

    SYNTAX 
        scalc -h [command line options] [< standard input]
    
    INPUT 
       takes space delimited files with PLong, PLat,[kappa, N_site, slat]
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file
        -c cutoff:  specify VGP colatitude cutoff value
        -k cutoff: specify kappa cutoff
        -v : use the VanDammme criterion 
        -a: use antipodes of reverse data: default is to use only normal
        -C:  use all data without regard to polarity
        -b: do a bootstrap for confidence
        -p: do relative to principle axis
    NOTES
        if kappa, N_site, lat supplied, will consider within site scatter
    OUTPUT
        N Sb  Sb_lower Sb_upper Co-lat. Cutoff
    """
    coord,kappa,cutoff="0",0,90.
    nb,anti,boot=1000,0,0
    all=0
    n=0
    v=0
    spin=1
    coord_key='tilt_correction'
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index("-f")
        in_file=sys.argv[ind+1]
        f=open(in_file,'rU')
        lines=f.readlines()
    else:
        lines=sys.stdin.readlines()
    if '-c' in sys.argv:
        ind=sys.argv.index('-c')
        cutoff=float(sys.argv[ind+1])
    if '-k' in sys.argv:
        ind=sys.argv.index('-k')
        kappa=float(sys.argv[ind+1])
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        n=int(sys.argv[ind+1])
    if '-a' in sys.argv: anti=1
    if '-C' in sys.argv: cutoff=180. # no cutoff
    if '-b' in sys.argv: boot=1
    if '-v' in sys.argv: v=1
    if '-p' in sys.argv: spin=0
    #
    #
    # find desired vgp lat,lon, kappa,N_site data:
    #
    A,Vgps,slats,Pvgps=180.,[],[],[]
    for line in lines:
        if '\t' in line:
            rec=line.replace('\n','').split('\t') # split each line on space to get records
        else:
            rec=line.replace('\n','').split() # split each line on space to get records
        vgp={}
        vgp['vgp_lon'],vgp['vgp_lat']=rec[0],rec[1]
        Pvgps.append([float(rec[0]),float(rec[1])])
        if anti==1:
            if float(vgp['vgp_lat'])<0:
                vgp['vgp_lat']='%7.1f'%(-1*float(vgp['vgp_lat']))
                vgp['vgp_lon']='%7.1f'%(float(vgp['vgp_lon'])-180.)
        if len(rec)==5:
            vgp['average_k'],vgp['average_nn'],vgp['average_lat']=rec[2],rec[3],rec[4]
            slats.append(float(rec[4]))
        else: 
            vgp['average_k'],vgp['average_nn'],vgp['average_lat']="0","0","0"
        if 90.-(float(vgp['vgp_lat']))<=cutoff and float(vgp['average_k'])>=kappa and int(vgp['average_nn'])>=n: Vgps.append(vgp) 
    if spin==0: # do transformation to pole
        ppars=pmag.doprinc(Pvgps)
        for vgp in Vgps:
	    vlon,vlat=pmag.dotilt(float(vgp['vgp_lon']),float(vgp['vgp_lat']),ppars['dec']-180.,90.-ppars['inc'])
            vgp['vgp_lon']=vlon  
            vgp['vgp_lat']=vlat  
            vgp['average_k']="0"
    S_B= pmag.get_Sb(Vgps)
    A=cutoff
    if v==1:
        thetamax,A=181.,180.
        vVgps,cnt=[],0
        for vgp in Vgps:vVgps.append(vgp) # make a copy of Vgps
        while thetamax>A:
            thetas=[]
            A=1.8*S_B+5
            cnt+=1
            for vgp in vVgps:thetas.append(90.-(float(vgp['vgp_lat'])))
            thetas.sort()
            thetamax=thetas[-1]
            if thetamax<A:break
            nVgps=[]
            for  vgp in vVgps:
                if 90.-(float(vgp['vgp_lat']))<thetamax:nVgps.append(vgp)
            vVgps=[]
            for vgp in nVgps:vVgps.append(vgp) 
            S_B= pmag.get_Sb(vVgps)
        Vgps=[]
        for vgp in vVgps:Vgps.append(vgp) # make a new Vgp list
    SBs,Ns=[],[]
    if boot==1:
      print 'please be patient...   bootstrapping'
      for i in range(nb): # now do bootstrap 
        BVgps=[]
        for k in range(len(Vgps)):
            ind=random.randint(0,len(Vgps)-1)
            random.jumpahead(int(ind*1000))
            BVgps.append(Vgps[ind])
        SBs.append(pmag.get_Sb(BVgps))
      SBs.sort()
      low=int(.025*nb)
      high=int(.975*nb)
      print len(Vgps),'%7.1f %7.1f  %7.1f %7.1f '%(S_B,SBs[low],SBs[high],A)
    else:
      print len(Vgps),'%7.1f  %7.1f '%(S_B,A)
    if  len(slats)>2:
        stats= pmag.gausspars(slats)
        print 'mean lat = ','%7.1f'%(stats[0])
예제 #19
0
def main():
    """
    NAME
        scalc_magic.py

    DESCRIPTION
       calculates Sb from pmag_results files

    SYNTAX 
        scalc_magic -h [command line options]
    
    INPUT 
       takes magic formatted pmag_results table
       pmag_result_name must start with "VGP: Site"
       must have average_lat if spin axis is reference
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input results file, default is 'pmag_results.txt'
        -c cutoff:  specify VGP colatitude cutoff value
        -k cutoff: specify kappa cutoff
        -crd [s,g,t]: specify coordinate system, default is geographic
        -v : use the VanDammme criterion 
        -a: use antipodes of reverse data: default is to use only normal
        -C: use all data without regard to polarity
        -r:  use reverse data only
        -p: do relative to principle axis
        -b: do bootstrap confidence bounds

     OUTPUT:
         if option -b used: N,  S_B, lower and upper bounds
         otherwise: N,  S_B, cutoff
    """
    in_file='pmag_results.txt'
    coord,kappa,cutoff="0",1.,90.
    nb,anti,spin,v,boot=1000,0,1,0,0
    coord_key='tilt_correction'
    rev=0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index("-f")
        in_file=sys.argv[ind+1]
    if '-c' in sys.argv:
        ind=sys.argv.index('-c')
        cutoff=float(sys.argv[ind+1])
    if '-k' in sys.argv:
        ind=sys.argv.index('-k')
        kappa=float(sys.argv[ind+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 '-a' in sys.argv: anti=1
    if '-C' in sys.argv: cutoff=180. # no cutoff
    if '-r' in sys.argv: rev=1
    if '-p' in sys.argv: spin=0
    if '-v' in sys.argv: v=1
    if '-b' in sys.argv: boot=1
    data,file_type=pmag.magic_read(in_file)
    #
    #
    # find desired vgp lat,lon, kappa,N_site data:
    #
    #
    #
    A,Vgps,Pvgps=180.,[],[]
    VgpRecs=pmag.get_dictitem(data,'vgp_lat','','F') # get all non-blank vgp latitudes
    VgpRecs=pmag.get_dictitem(VgpRecs,'vgp_lon','','F') # get all non-blank vgp longitudes
    SiteRecs=pmag.get_dictitem(VgpRecs,'data_type','i','T') # get VGPs (as opposed to averaged)
    SiteRecs=pmag.get_dictitem(SiteRecs,coord_key,coord,'T') # get right coordinate system
    for rec in SiteRecs:
        if anti==1:
            if 90.-abs(float(rec['vgp_lat']))<=cutoff and float(rec['average_k'])>=kappa: 
                if float(rec['vgp_lat'])<0:
                    rec['vgp_lat']='%7.1f'%(-1*float(rec['vgp_lat']))
                    rec['vgp_lon']='%7.1f'%(float(rec['vgp_lon'])-180.)
                Vgps.append(rec)
                Pvgps.append([float(rec['vgp_lon']),float(rec['vgp_lat'])])
        elif rev==0: # exclude normals
            if 90.-(float(rec['vgp_lat']))<=cutoff and float(rec['average_k'])>=kappa: 
                Vgps.append(rec)
                Pvgps.append([float(rec['vgp_lon']),float(rec['vgp_lat'])])
        else: # include normals
            if 90.-abs(float(rec['vgp_lat']))<=cutoff and float(rec['average_k'])>=kappa: 
                if float(rec['vgp_lat'])<0:
                    rec['vgp_lat']='%7.1f'%(-1*float(rec['vgp_lat']))
                    rec['vgp_lon']='%7.1f'%(float(rec['vgp_lon'])-180.)
                    Vgps.append(rec)
                    Pvgps.append([float(rec['vgp_lon']),float(rec['vgp_lat'])])
    if spin==0: # do transformation to pole
        ppars=pmag.doprinc(Pvgps)
        for vgp in Vgps:
            vlon,vlat=pmag.dotilt(float(vgp['vgp_lon']),float(vgp['vgp_lat']),ppars['dec']-180.,90.-ppars['inc'])
            vgp['vgp_lon']=vlon
            vgp['vgp_lat']=vlat
            vgp['average_k']="0"
    S_B= pmag.get_Sb(Vgps)
    A=cutoff
    if v==1:
        thetamax,A=181.,180.
        vVgps,cnt=[],0
        for vgp in Vgps:vVgps.append(vgp) # make a copy of Vgps
        while thetamax>A:
            thetas=[]
            A=1.8*S_B+5
            cnt+=1
            for vgp in vVgps:thetas.append(90.-(float(vgp['vgp_lat'])))
            thetas.sort()
            thetamax=thetas[-1]
            if thetamax<A:break
            nVgps=[]
            for  vgp in vVgps:
                if 90.-(float(vgp['vgp_lat']))<thetamax:nVgps.append(vgp)
            vVgps=[]
            for vgp in nVgps:vVgps.append(vgp)
            S_B= pmag.get_Sb(vVgps)
        Vgps=[]
        for vgp in vVgps:Vgps.append(vgp) # make a new Vgp list
    SBs=[]
    if boot==1:
        for i in range(nb): # now do bootstrap 
            BVgps=[]
            if i%100==0: print(i,' out of ',nb)
            for k in range(len(Vgps)):
                random.seed()
                ind=random.randint(0,len(Vgps)-1)
                BVgps.append(Vgps[ind])
            SBs.append(pmag.get_Sb(BVgps))
        SBs.sort()
        low=int(.025*nb)
        high=int(.975*nb)
        print(len(Vgps),'%7.1f _ %7.1f ^ %7.1f %7.1f'%(S_B,SBs[low],SBs[high],A))
    else:
        print(len(Vgps),'%7.1f  %7.1f '%(S_B,A))
예제 #20
0
def main():
    """
    NAME
       plotdi_e.py

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

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

    SYNTAX
       plotdi_e.py [command line options]

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

    """
    dist = 'F'  # default distribution is Fisherian
    mode = 1
    EQ = {'eq': 1}
    if len(sys.argv) > 0:
        if '-h' in sys.argv:  # check if help is needed
            print main.__doc__
            sys.exit()  # graceful quit
        if '-i' in sys.argv:  # ask for filename
            file = raw_input("Enter file name with dec, inc data: ")
            dist = raw_input(
                "Enter desired distrubution: [Fish]er, [Bing]ham, [Kent] [Boot] [default is Fisher]: "
            )
            if dist == "": dist = "F"
            if dist == "Boot":
                type = raw_input(
                    " Ellipses or distribution of vectors? [E]/V ")
                if type == "" or type == "E":
                    dist = "BE"
                else:
                    dist = "BE"
        else:
            #
            if '-f' in sys.argv:
                ind = sys.argv.index('-f')
                file = sys.argv[ind + 1]
            else:
                print 'you must specify a file name'
                print main.__doc__
                sys.exit()
            if '-Bing' in sys.argv: dist = 'B'
            if '-Kent' in sys.argv: dist = 'K'
            if '-Boot' in sys.argv:
                ind = sys.argv.index('-Boot')
                type = sys.argv[ind + 1]
                if type == 'E':
                    dist = 'BE'
                elif type == 'V':
                    dist = 'BV'
                    EQ['bdirs'] = 2
                    pmagplotlib.plot_init(EQ['bdirs'], 5, 5)
                else:
                    print main.__doc__
                    sys.exit()
    pmagplotlib.plot_init(EQ['eq'], 5, 5)
    #
    # get to work
    f = open(file, 'r')
    data = f.readlines()
    #
    DIs = []  # set up list for dec inc data
    DiRecs = []
    pars = []
    nDIs, rDIs, npars, rpars = [], [], [], []
    mode = 1
    for line in data:  # read in the data from standard input
        DiRec = {}
        rec = line.split()  # split each line on space to get records
        DIs.append((float(rec[0]), float(rec[1]), 1.))
        DiRec['dec'] = rec[0]
        DiRec['inc'] = rec[1]
        DiRec['direction_type'] = 'l'
        DiRecs.append(DiRec)
    # split into two modes
    ppars = pmag.doprinc(DIs)  # get principal directions
    for rec in DIs:
        angle = pmag.angle([rec[0], rec[1]], [ppars['dec'], ppars['inc']])
        if angle > 90.:
            rDIs.append(rec)
        else:
            nDIs.append(rec)
    if dist == 'B':  # do on whole dataset
        title = "Bingham confidence ellipse"
        bpars = pmag.dobingham(DIs)
        for key in bpars.keys():
            if key != 'n': print "    ", key, '%7.1f' % (bpars[key])
            if key == 'n': print "    ", key, '       %i' % (bpars[key])
        npars.append(bpars['dec'])
        npars.append(bpars['inc'])
        npars.append(bpars['Zeta'])
        npars.append(bpars['Zdec'])
        npars.append(bpars['Zinc'])
        npars.append(bpars['Eta'])
        npars.append(bpars['Edec'])
        npars.append(bpars['Einc'])
    if dist == 'F':
        title = "Fisher confidence cone"
        if len(nDIs) > 3:
            fpars = pmag.fisher_mean(nDIs)
            print "mode ", mode
            for key in fpars.keys():
                if key != 'n': print "    ", key, '%7.1f' % (fpars[key])
                if key == 'n': print "    ", key, '       %i' % (fpars[key])
            mode += 1
            npars.append(fpars['dec'])
            npars.append(fpars['inc'])
            npars.append(fpars['alpha95'])  # Beta
            npars.append(fpars['dec'])
            isign = abs(fpars['inc']) / fpars['inc']
            npars.append(fpars['inc'] - isign * 90.)  #Beta inc
            npars.append(fpars['alpha95'])  # gamma
            npars.append(fpars['dec'] + 90.)  # Beta dec
            npars.append(0.)  #Beta inc
        if len(rDIs) > 3:
            fpars = pmag.fisher_mean(rDIs)
            print "mode ", mode
            for key in fpars.keys():
                if key != 'n': print "    ", key, '%7.1f' % (fpars[key])
                if key == 'n': print "    ", key, '       %i' % (fpars[key])
            mode += 1
            rpars.append(fpars['dec'])
            rpars.append(fpars['inc'])
            rpars.append(fpars['alpha95'])  # Beta
            rpars.append(fpars['dec'])
            isign = abs(fpars['inc']) / fpars['inc']
            rpars.append(fpars['inc'] - isign * 90.)  #Beta inc
            rpars.append(fpars['alpha95'])  # gamma
            rpars.append(fpars['dec'] + 90.)  # Beta dec
            rpars.append(0.)  #Beta inc
    if dist == 'K':
        title = "Kent confidence ellipse"
        if len(nDIs) > 3:
            kpars = pmag.dokent(nDIs, len(nDIs))
            print "mode ", mode
            for key in kpars.keys():
                if key != 'n': print "    ", key, '%7.1f' % (kpars[key])
                if key == 'n': print "    ", key, '       %i' % (kpars[key])
            mode += 1
            npars.append(kpars['dec'])
            npars.append(kpars['inc'])
            npars.append(kpars['Zeta'])
            npars.append(kpars['Zdec'])
            npars.append(kpars['Zinc'])
            npars.append(kpars['Eta'])
            npars.append(kpars['Edec'])
            npars.append(kpars['Einc'])
        if len(rDIs) > 3:
            kpars = pmag.dokent(rDIs, len(rDIs))
            print "mode ", mode
            for key in kpars.keys():
                if key != 'n': print "    ", key, '%7.1f' % (kpars[key])
                if key == 'n': print "    ", key, '       %i' % (kpars[key])
            mode += 1
            rpars.append(kpars['dec'])
            rpars.append(kpars['inc'])
            rpars.append(kpars['Zeta'])
            rpars.append(kpars['Zdec'])
            rpars.append(kpars['Zinc'])
            rpars.append(kpars['Eta'])
            rpars.append(kpars['Edec'])
            rpars.append(kpars['Einc'])
    else:  # assume bootstrap
        if dist == 'BE':
            if len(nDIs) > 5:
                BnDIs = pmag.di_boot(nDIs)
                Bkpars = pmag.dokent(BnDIs, 1.)
                print "mode ", mode
                for key in Bkpars.keys():
                    if key != 'n': print "    ", key, '%7.1f' % (Bkpars[key])
                    if key == 'n':
                        print "    ", key, '       %i' % (Bkpars[key])
                mode += 1
                npars.append(Bkpars['dec'])
                npars.append(Bkpars['inc'])
                npars.append(Bkpars['Zeta'])
                npars.append(Bkpars['Zdec'])
                npars.append(Bkpars['Zinc'])
                npars.append(Bkpars['Eta'])
                npars.append(Bkpars['Edec'])
                npars.append(Bkpars['Einc'])
            if len(rDIs) > 5:
                BrDIs = pmag.di_boot(rDIs)
                Bkpars = pmag.dokent(BrDIs, 1.)
                print "mode ", mode
                for key in Bkpars.keys():
                    if key != 'n': print "    ", key, '%7.1f' % (Bkpars[key])
                    if key == 'n':
                        print "    ", key, '       %i' % (Bkpars[key])
                mode += 1
                rpars.append(Bkpars['dec'])
                rpars.append(Bkpars['inc'])
                rpars.append(Bkpars['Zeta'])
                rpars.append(Bkpars['Zdec'])
                rpars.append(Bkpars['Zinc'])
                rpars.append(Bkpars['Eta'])
                rpars.append(Bkpars['Edec'])
                rpars.append(Bkpars['Einc'])
            title = "Bootstrapped confidence ellipse"
        elif dist == 'BV':
            if len(nDIs) > 5:
                pmagplotlib.plotEQ(EQ['eq'], nDIs, 'Data')
                BnDIs = pmag.di_boot(nDIs)
                pmagplotlib.plotEQ(EQ['bdirs'], BnDIs,
                                   'Bootstrapped Eigenvectors')
            if len(rDIs) > 5:
                BrDIs = pmag.di_boot(rDIs)
                if len(nDIs) > 5:  # plot on existing plots
                    pmagplotlib.plotDI(EQ['eq'], rDIs)
                    pmagplotlib.plotDI(EQ['bdirs'], BrDIs)
                else:
                    pmagplotlib.plotEQ(EQ['eq'], rDIs, 'Data')
                    pmagplotlib.plotEQ(EQ['bdirs'], BrDIs,
                                       'Bootstrapped Eigenvectors')
            pmagplotlib.drawFIGS(EQ)
            ans = raw_input('s[a]ve, [q]uit ')
            if ans == 'q': sys.exit()
            if ans == 'a':
                files = {}
                for key in EQ.keys():
                    files[key] = 'BE_' + key + '.svg'
                pmagplotlib.saveP(EQ, files)
            sys.exit()
    if len(nDIs) > 5:
        pmagplotlib.plotCONF(EQ['eq'], title, DiRecs, npars, 1)
        if len(rDIs) > 5 and dist != 'B':
            pmagplotlib.plotCONF(EQ['eq'], title, [], rpars, 0)
    elif len(rDIs) > 5 and dist != 'B':
        pmagplotlib.plotCONF(EQ['eq'], title, DiRecs, rpars, 1)
    pmagplotlib.drawFIGS(EQ)
    ans = raw_input('s[a]ve, [q]uit ')
    if ans == 'q': sys.exit()
    if ans == 'a':
        files = {}
        for key in EQ.keys():
            files[key] = key + '.svg'
        pmagplotlib.saveP(EQ, files)
예제 #21
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

    INPUT
       takes magic formatted pmag_results, pmag_sites, pmag_samples or pmag_specimens

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file from magic,default='pmag_results.txt'
         supported types=[magic_measurements,pmag_specimens, pmag_samples, pmag_sites, pmag_results, magic_web]
        -obj OBJ: specify  level of plot  [all, sit, sam, spc], default is all
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is geographic, unspecified assumed geographic
        -fmt [svg,png,jpg] format for output plots
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
        -c plot as colour contour
        -sav save plot and quit quietly
    NOTE
        all: entire file; sit: site; sam: sample; spc: specimen
    """
    FIG = {}  # plot dictionary
    FIG['eqarea'] = 1  # eqarea is figure 1
    in_file, plot_key, coord, crd = 'pmag_results.txt', 'all', "0", 'g'
    plotE, contour = 0, 0
    dir_path = '.'
    fmt = 'svg'
    verbose = pmagplotlib.verbose
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path = sys.argv[ind+1]
    pmagplotlib.plot_init(FIG['eqarea'], 5, 5)
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        in_file = dir_path+"/"+sys.argv[ind+1]
    if '-obj' in sys.argv:
        ind = sys.argv.index('-obj')
        plot_by = sys.argv[ind+1]
        if plot_by == 'all':
            plot_key = 'all'
        if plot_by == 'sit':
            plot_key = 'er_site_name'
        if plot_by == 'sam':
            plot_key = 'er_sample_name'
        if plot_by == 'spc':
            plot_key = 'er_specimen_name'
    if '-c' in sys.argv:
        contour = 1
    plt = 0
    if '-sav' in sys.argv:
        plt = 1
        verbose = 0
    if '-ell' in sys.argv:
        plotE = 1
        ind = sys.argv.index('-ell')
        ell_type = sys.argv[ind+1]
        if ell_type == 'F':
            dist = 'F'
        if ell_type == 'K':
            dist = 'K'
        if ell_type == 'B':
            dist = 'B'
        if ell_type == 'Be':
            dist = 'BE'
        if ell_type == 'Bv':
            dist = 'BV'
            FIG['bdirs'] = 2
            pmagplotlib.plot_init(FIG['bdirs'], 5, 5)
    if '-crd' in sys.argv:
        ind = sys.argv.index("-crd")
        crd = sys.argv[ind+1]
        if crd == 's':
            coord = "-1"
        if crd == 'g':
            coord = "0"
        if crd == 't':
            coord = "100"
    if '-fmt' in sys.argv:
        ind = sys.argv.index("-fmt")
        fmt = sys.argv[ind+1]
    Dec_keys = ['site_dec', 'sample_dec', 'specimen_dec',
                'measurement_dec', 'average_dec', 'none']
    Inc_keys = ['site_inc', 'sample_inc', 'specimen_inc',
                'measurement_inc', 'average_inc', 'none']
    Tilt_keys = ['tilt_correction', 'site_tilt_correction',
                 'sample_tilt_correction', 'specimen_tilt_correction', 'none']
    Dir_type_keys = ['', 'site_direction_type',
                     'sample_direction_type', 'specimen_direction_type']
    Name_keys = ['er_specimen_name', 'er_sample_name',
                 'er_site_name', 'pmag_result_name']
    data, file_type = pmag.magic_read(in_file)
    if file_type == 'pmag_results' and plot_key != "all":
        plot_key = plot_key+'s'  # need plural for results table
    if verbose:
        print(len(data), ' records read from ', in_file)
    #
    #
    # find desired dec,inc data:
    #
    dir_type_key = ''
    #
    # get plotlist if not plotting all records
    #
    plotlist = []
    if plot_key != "all":
        plots = pmag.get_dictitem(data, plot_key, '', 'F')
        for rec in plots:
            if rec[plot_key] not in plotlist:
                plotlist.append(rec[plot_key])
        plotlist.sort()
    else:
        plotlist.append('All')
    for plot in plotlist:
        # if verbose: print plot
        DIblock = []
        GCblock = []
        SLblock, SPblock = [], []
        title = plot
        mode = 1
        dec_key, inc_key, tilt_key, name_key, k = "", "", "", "", 0
        if plot != "All":
            odata = pmag.get_dictitem(data, plot_key, plot, 'T')
        else:
            odata = data  # data for this obj
        for dec_key in Dec_keys:
            # get all records with this dec_key not blank
            Decs = pmag.get_dictitem(odata, dec_key, '', 'F')
            if len(Decs) > 0:
                break
        for inc_key in Inc_keys:
            # get all records with this inc_key not blank
            Incs = pmag.get_dictitem(Decs, inc_key, '', 'F')
            if len(Incs) > 0:
                break
        for tilt_key in Tilt_keys:
            if tilt_key in Incs[0].keys():
                break  # find the tilt_key for these records
        if tilt_key == 'none':  # no tilt key in data, need to fix this with fake data which will be unknown tilt
            tilt_key = 'tilt_correction'
            for rec in Incs:
                rec[tilt_key] = ''
        # get all records matching specified coordinate system
        cdata = pmag.get_dictitem(Incs, tilt_key, coord, 'T')
        if coord == '0':  # geographic
            # get all the blank records - assume geographic
            udata = pmag.get_dictitem(Incs, tilt_key, '', 'T')
            if len(cdata) == 0:
                crd = ''
            if len(udata) > 0:
                for d in udata:
                    cdata.append(d)
                crd = crd+'u'
        for name_key in Name_keys:
            # get all records with this name_key not blank
            Names = pmag.get_dictitem(cdata, name_key, '', 'F')
            if len(Names) > 0:
                break
        for dir_type_key in Dir_type_keys:
            # get all records with this direction type
            Dirs = pmag.get_dictitem(cdata, dir_type_key, '', 'F')
            if len(Dirs) > 0:
                break
        if dir_type_key == "":
            dir_type_key = 'direction_type'
        locations, site, sample, specimen = "", "", "", ""
        for rec in cdata:  # pick out the data
            if 'er_location_name' in rec.keys() and rec['er_location_name'] != "" and rec['er_location_name'] not in locations:
                locations = locations + \
                    rec['er_location_name'].replace("/", "")+"_"
            if 'er_location_names' in rec.keys() and rec['er_location_names'] != "":
                locs = rec['er_location_names'].split(':')
                for loc in locs:
                    if loc not in locations:
                        locations = locations+loc.replace("/", "")+'_'
            if plot_key == 'er_site_name' or plot_key == 'er_sample_name' or plot_key == 'er_specimen_name':
                site = rec['er_site_name']
            if plot_key == 'er_sample_name' or plot_key == 'er_specimen_name':
                sample = rec['er_sample_name']
            if plot_key == 'er_specimen_name':
                specimen = rec['er_specimen_name']
            if plot_key == 'er_site_names' or plot_key == 'er_sample_names' or plot_key == 'er_specimen_names':
                site = rec['er_site_names']
            if plot_key == 'er_sample_names' or plot_key == 'er_specimen_names':
                sample = rec['er_sample_names']
            if plot_key == 'er_specimen_names':
                specimen = rec['er_specimen_names']
            if dir_type_key not in rec.keys() or rec[dir_type_key] == "":
                rec[dir_type_key] = 'l'
            if 'magic_method_codes' not in rec.keys():
                rec['magic_method_codes'] = ""
            DIblock.append([float(rec[dec_key]), float(rec[inc_key])])
            SLblock.append([rec[name_key], rec['magic_method_codes']])
            if rec[tilt_key] == coord and rec[dir_type_key] != 'l' and rec[dec_key] != "" and rec[inc_key] != "":
                GCblock.append([float(rec[dec_key]), float(rec[inc_key])])
                SPblock.append([rec[name_key], rec['magic_method_codes']])
        if len(DIblock) == 0 and len(GCblock) == 0:
            if verbose:
                print("no records for plotting")
            sys.exit()
        if verbose:
            for k in range(len(SLblock)):
                print('%s %s %7.1f %7.1f' % (
                    SLblock[k][0], SLblock[k][1], DIblock[k][0], DIblock[k][1]))
            for k in range(len(SPblock)):
                print('%s %s %7.1f %7.1f' % (
                    SPblock[k][0], SPblock[k][1], GCblock[k][0], GCblock[k][1]))
        if len(DIblock) > 0:
            if contour == 0:
                pmagplotlib.plot_eq(FIG['eqarea'], DIblock, title)
            else:
                pmagplotlib.plot_eq_cont(FIG['eqarea'], DIblock)
        else:
            pmagplotlib.plot_net(FIG['eqarea'])
        if len(GCblock) > 0:
            for rec in GCblock:
                pmagplotlib.plot_circ(FIG['eqarea'], rec, 90., 'g')
        if plotE == 1:
            ppars = pmag.doprinc(DIblock)  # get principal directions
            nDIs, rDIs, npars, rpars = [], [], [], []
            for rec in DIblock:
                angle = pmag.angle([rec[0], rec[1]], [
                                   ppars['dec'], ppars['inc']])
                if angle > 90.:
                    rDIs.append(rec)
                else:
                    nDIs.append(rec)
            if dist == 'B':  # do on whole dataset
                etitle = "Bingham confidence ellipse"
                bpars = pmag.dobingham(DIblock)
                for key in bpars.keys():
                    if key != 'n' and verbose:
                        print("    ", key, '%7.1f' % (bpars[key]))
                    if key == 'n' and verbose:
                        print("    ", key, '       %i' % (bpars[key]))
                npars.append(bpars['dec'])
                npars.append(bpars['inc'])
                npars.append(bpars['Zeta'])
                npars.append(bpars['Zdec'])
                npars.append(bpars['Zinc'])
                npars.append(bpars['Eta'])
                npars.append(bpars['Edec'])
                npars.append(bpars['Einc'])
            if dist == 'F':
                etitle = "Fisher confidence cone"
                if len(nDIs) > 2:
                    fpars = pmag.fisher_mean(nDIs)
                    for key in fpars.keys():
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (fpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (fpars[key]))
                    mode += 1
                    npars.append(fpars['dec'])
                    npars.append(fpars['inc'])
                    npars.append(fpars['alpha95'])  # Beta
                    npars.append(fpars['dec'])
                    isign = abs(fpars['inc'])/fpars['inc']
                    npars.append(fpars['inc']-isign*90.)  # Beta inc
                    npars.append(fpars['alpha95'])  # gamma
                    npars.append(fpars['dec']+90.)  # Beta dec
                    npars.append(0.)  # Beta inc
                if len(rDIs) > 2:
                    fpars = pmag.fisher_mean(rDIs)
                    if verbose:
                        print("mode ", mode)
                    for key in fpars.keys():
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (fpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (fpars[key]))
                    mode += 1
                    rpars.append(fpars['dec'])
                    rpars.append(fpars['inc'])
                    rpars.append(fpars['alpha95'])  # Beta
                    rpars.append(fpars['dec'])
                    isign = abs(fpars['inc'])/fpars['inc']
                    rpars.append(fpars['inc']-isign*90.)  # Beta inc
                    rpars.append(fpars['alpha95'])  # gamma
                    rpars.append(fpars['dec']+90.)  # Beta dec
                    rpars.append(0.)  # Beta inc
            if dist == 'K':
                etitle = "Kent confidence ellipse"
                if len(nDIs) > 3:
                    kpars = pmag.dokent(nDIs, len(nDIs))
                    if verbose:
                        print("mode ", mode)
                    for key in kpars.keys():
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (kpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (kpars[key]))
                    mode += 1
                    npars.append(kpars['dec'])
                    npars.append(kpars['inc'])
                    npars.append(kpars['Zeta'])
                    npars.append(kpars['Zdec'])
                    npars.append(kpars['Zinc'])
                    npars.append(kpars['Eta'])
                    npars.append(kpars['Edec'])
                    npars.append(kpars['Einc'])
                if len(rDIs) > 3:
                    kpars = pmag.dokent(rDIs, len(rDIs))
                    if verbose:
                        print("mode ", mode)
                    for key in kpars.keys():
                        if key != 'n' and verbose:
                            print("    ", key, '%7.1f' % (kpars[key]))
                        if key == 'n' and verbose:
                            print("    ", key, '       %i' % (kpars[key]))
                    mode += 1
                    rpars.append(kpars['dec'])
                    rpars.append(kpars['inc'])
                    rpars.append(kpars['Zeta'])
                    rpars.append(kpars['Zdec'])
                    rpars.append(kpars['Zinc'])
                    rpars.append(kpars['Eta'])
                    rpars.append(kpars['Edec'])
                    rpars.append(kpars['Einc'])
            else:  # assume bootstrap
                if dist == 'BE':
                    if len(nDIs) > 5:
                        BnDIs = pmag.di_boot(nDIs)
                        Bkpars = pmag.dokent(BnDIs, 1.)
                        if verbose:
                            print("mode ", mode)
                        for key in Bkpars.keys():
                            if key != 'n' and verbose:
                                print("    ", key, '%7.1f' % (Bkpars[key]))
                            if key == 'n' and verbose:
                                print("    ", key, '       %i' % (Bkpars[key]))
                        mode += 1
                        npars.append(Bkpars['dec'])
                        npars.append(Bkpars['inc'])
                        npars.append(Bkpars['Zeta'])
                        npars.append(Bkpars['Zdec'])
                        npars.append(Bkpars['Zinc'])
                        npars.append(Bkpars['Eta'])
                        npars.append(Bkpars['Edec'])
                        npars.append(Bkpars['Einc'])
                    if len(rDIs) > 5:
                        BrDIs = pmag.di_boot(rDIs)
                        Bkpars = pmag.dokent(BrDIs, 1.)
                        if verbose:
                            print("mode ", mode)
                        for key in Bkpars.keys():
                            if key != 'n' and verbose:
                                print("    ", key, '%7.1f' % (Bkpars[key]))
                            if key == 'n' and verbose:
                                print("    ", key, '       %i' % (Bkpars[key]))
                        mode += 1
                        rpars.append(Bkpars['dec'])
                        rpars.append(Bkpars['inc'])
                        rpars.append(Bkpars['Zeta'])
                        rpars.append(Bkpars['Zdec'])
                        rpars.append(Bkpars['Zinc'])
                        rpars.append(Bkpars['Eta'])
                        rpars.append(Bkpars['Edec'])
                        rpars.append(Bkpars['Einc'])
                    etitle = "Bootstrapped confidence ellipse"
                elif dist == 'BV':
                    sym = {'lower': ['o', 'c'], 'upper': [
                        'o', 'g'], 'size': 3, 'edgecolor': 'face'}
                    if len(nDIs) > 5:
                        BnDIs = pmag.di_boot(nDIs)
                        pmagplotlib.plot_eq_sym(
                            FIG['bdirs'], BnDIs, 'Bootstrapped Eigenvectors', sym)
                    if len(rDIs) > 5:
                        BrDIs = pmag.di_boot(rDIs)
                        if len(nDIs) > 5:  # plot on existing plots
                            pmagplotlib.plot_di_sym(FIG['bdirs'], BrDIs, sym)
                        else:
                            pmagplotlib.plot_eq(
                                FIG['bdirs'], BrDIs, 'Bootstrapped Eigenvectors')
            if dist == 'B':
                if len(nDIs) > 3 or len(rDIs) > 3:
                    pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], npars, 0)
            elif len(nDIs) > 3 and dist != 'BV':
                pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], npars, 0)
                if len(rDIs) > 3:
                    pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], rpars, 0)
            elif len(rDIs) > 3 and dist != 'BV':
                pmagplotlib.plot_conf(FIG['eqarea'], etitle, [], rpars, 0)
        if verbose:
            pmagplotlib.draw_figs(FIG)
            #
        files = {}
        locations = locations[:-1]
        for key in FIG.keys():
            if pmagplotlib.isServer:  # use server plot naming convention
                filename = 'LO:_'+locations+'_SI:_'+site+'_SA:_'+sample + \
                    '_SP:_'+specimen+'_CO:_'+crd+'_TY:_'+key+'_.'+fmt
            else:  # use more readable plot naming convention
                filename = ''
                for item in [locations, site, sample, specimen, crd, key]:
                    if item:
                        item = item.replace(' ', '_')
                        filename += item + '_'
                if filename.endswith('_'):
                    filename = filename[:-1]
                filename += ".{}".format(fmt)
            files[key] = filename
        if pmagplotlib.isServer:
            black = '#000000'
            purple = '#800080'
            titles = {}
            titles['eq'] = 'Equal Area Plot'
            FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
            pmagplotlib.save_plots(FIG, files)
        elif verbose:
            ans = raw_input(
                " S[a]ve to save plot, [q]uit, Return to continue:  ")
            if ans == "q":
                sys.exit()
            if ans == "a":
                pmagplotlib.save_plots(FIG, files)
        if plt:
            pmagplotlib.save_plots(FIG, files)
예제 #22
0
def main():
    """
    NAME
        scalc.py

    DESCRIPTION
       calculates Sb from VGP Long,VGP Lat,Directional kappa,Site latitude data

    SYNTAX 
        scalc -h [command line options] [< standard input]
    
    INPUT 
       takes space delimited files with PLong, PLat,[kappa, N_site, slat]
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file
        -c cutoff:  specify VGP colatitude cutoff value
        -k cutoff: specify kappa cutoff
        -v : use the VanDammme criterion 
        -a: use antipodes of reverse data: default is to use only normal
        -C:  use all data without regard to polarity
        -b: do a bootstrap for confidence
        -p: do relative to principle axis
    NOTES
        if kappa, N_site, lat supplied, will consider within site scatter
    OUTPUT
        N Sb  Sb_lower Sb_upper Co-lat. Cutoff
    """
    coord, kappa, cutoff = "0", 0, 90.
    nb, anti, boot = 1000, 0, 0
    all = 0
    n = 0
    v = 0
    spin = 1
    coord_key = 'tilt_correction'
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        in_file = sys.argv[ind + 1]
        f = open(in_file, 'rU')
        lines = f.readlines()
    else:
        lines = sys.stdin.readlines()
    if '-c' in sys.argv:
        ind = sys.argv.index('-c')
        cutoff = float(sys.argv[ind + 1])
    if '-k' in sys.argv:
        ind = sys.argv.index('-k')
        kappa = float(sys.argv[ind + 1])
    if '-n' in sys.argv:
        ind = sys.argv.index('-n')
        n = int(sys.argv[ind + 1])
    if '-a' in sys.argv: anti = 1
    if '-C' in sys.argv: cutoff = 180.  # no cutoff
    if '-b' in sys.argv: boot = 1
    if '-v' in sys.argv: v = 1
    if '-p' in sys.argv: spin = 0
    #
    #
    # find desired vgp lat,lon, kappa,N_site data:
    #
    A, Vgps, slats, Pvgps = 180., [], [], []
    for line in lines:
        if '\t' in line:
            rec = line.replace('\n', '').split(
                '\t')  # split each line on space to get records
        else:
            rec = line.replace(
                '\n', '').split()  # split each line on space to get records
        vgp = {}
        vgp['vgp_lon'], vgp['vgp_lat'] = rec[0], rec[1]
        Pvgps.append([float(rec[0]), float(rec[1])])
        if anti == 1:
            if float(vgp['vgp_lat']) < 0:
                vgp['vgp_lat'] = '%7.1f' % (-1 * float(vgp['vgp_lat']))
                vgp['vgp_lon'] = '%7.1f' % (float(vgp['vgp_lon']) - 180.)
        if len(rec) == 5:
            vgp['average_k'], vgp['average_nn'], vgp['average_lat'] = rec[
                2], rec[3], rec[4]
            slats.append(float(rec[4]))
        else:
            vgp['average_k'], vgp['average_nn'], vgp[
                'average_lat'] = "0", "0", "0"
        if 90. - (float(vgp['vgp_lat'])) <= cutoff and float(
                vgp['average_k']) >= kappa and int(vgp['average_nn']) >= n:
            Vgps.append(vgp)
    if spin == 0:  # do transformation to pole
        ppars = pmag.doprinc(Pvgps)
        for vgp in Vgps:
            vlon, vlat = pmag.dotilt(float(vgp['vgp_lon']),
                                     float(vgp['vgp_lat']),
                                     ppars['dec'] - 180., 90. - ppars['inc'])
            vgp['vgp_lon'] = vlon
            vgp['vgp_lat'] = vlat
            vgp['average_k'] = "0"
    S_B = pmag.get_Sb(Vgps)
    A = cutoff
    if v == 1:
        thetamax, A = 181., 180.
        vVgps, cnt = [], 0
        for vgp in Vgps:
            vVgps.append(vgp)  # make a copy of Vgps
        while thetamax > A:
            thetas = []
            A = 1.8 * S_B + 5
            cnt += 1
            for vgp in vVgps:
                thetas.append(90. - (float(vgp['vgp_lat'])))
            thetas.sort()
            thetamax = thetas[-1]
            if thetamax < A: break
            nVgps = []
            for vgp in vVgps:
                if 90. - (float(vgp['vgp_lat'])) < thetamax: nVgps.append(vgp)
            vVgps = []
            for vgp in nVgps:
                vVgps.append(vgp)
            S_B = pmag.get_Sb(vVgps)
        Vgps = []
        for vgp in vVgps:
            Vgps.append(vgp)  # make a new Vgp list
    SBs, Ns = [], []
    if boot == 1:
        print 'please be patient...   bootstrapping'
        for i in range(nb):  # now do bootstrap
            BVgps = []
            for k in range(len(Vgps)):
                ind = random.randint(0, len(Vgps) - 1)
                random.jumpahead(int(ind * 1000))
                BVgps.append(Vgps[ind])
            SBs.append(pmag.get_Sb(BVgps))
        SBs.sort()
        low = int(.025 * nb)
        high = int(.975 * nb)
        print len(Vgps), '%7.1f %7.1f  %7.1f %7.1f ' % (S_B, SBs[low],
                                                        SBs[high], A)
    else:
        print len(Vgps), '%7.1f  %7.1f ' % (S_B, A)
    if len(slats) > 2:
        stats = pmag.gausspars(slats)
        print 'mean lat = ', '%7.1f' % (stats[0])
예제 #23
0
def main():
    """
    NAME
        scalc_magic.py

    DESCRIPTION
       calculates Sb from pmag_results files

    SYNTAX 
        scalc_magic -h [command line options]
    
    INPUT 
       takes magic formatted pmag_results table
       pmag_result_name must start with "VGP: Site"
       must have average_lat if spin axis is reference
    
    OPTIONS
        -h prints help message and quits
        -f FILE: specify input results file, default is 'pmag_results.txt'
        -c cutoff:  specify VGP colatitude cutoff value
        -k cutoff: specify kappa cutoff
        -crd [s,g,t]: specify coordinate system, default is geographic
        -v : use the VanDammme criterion 
        -a: use antipodes of reverse data: default is to use only normal
        -C: use all data without regard to polarity
        -r:  use reverse data only
        -p: do relative to principle axis
        -b: do bootstrap confidence bounds

     OUTPUT:
         if option -b used: N,  S_B, lower and upper bounds
         otherwise: N,  S_B, cutoff
    """
    in_file = 'pmag_results.txt'
    coord, kappa, cutoff = "0", 1., 90.
    nb, anti, spin, v, boot = 1000, 0, 1, 0, 0
    coord_key = 'tilt_correction'
    rev = 0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index("-f")
        in_file = sys.argv[ind + 1]
    if '-c' in sys.argv:
        ind = sys.argv.index('-c')
        cutoff = float(sys.argv[ind + 1])
    if '-k' in sys.argv:
        ind = sys.argv.index('-k')
        kappa = float(sys.argv[ind + 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 '-a' in sys.argv: anti = 1
    if '-C' in sys.argv: cutoff = 180.  # no cutoff
    if '-r' in sys.argv: rev = 1
    if '-p' in sys.argv: spin = 0
    if '-v' in sys.argv: v = 1
    if '-b' in sys.argv: boot = 1
    data, file_type = pmag.magic_read(in_file)
    #
    #
    # find desired vgp lat,lon, kappa,N_site data:
    #
    #
    #
    A, Vgps, Pvgps = 180., [], []
    VgpRecs = pmag.get_dictitem(data, 'vgp_lat', '',
                                'F')  # get all non-blank vgp latitudes
    VgpRecs = pmag.get_dictitem(VgpRecs, 'vgp_lon', '',
                                'F')  # get all non-blank vgp longitudes
    SiteRecs = pmag.get_dictitem(VgpRecs, 'data_type', 'i',
                                 'T')  # get VGPs (as opposed to averaged)
    SiteRecs = pmag.get_dictitem(SiteRecs, coord_key, coord,
                                 'T')  # get right coordinate system
    for rec in SiteRecs:
        if anti == 1:
            if 90. - abs(float(rec['vgp_lat'])) <= cutoff and float(
                    rec['average_k']) >= kappa:
                if float(rec['vgp_lat']) < 0:
                    rec['vgp_lat'] = '%7.1f' % (-1 * float(rec['vgp_lat']))
                    rec['vgp_lon'] = '%7.1f' % (float(rec['vgp_lon']) - 180.)
                Vgps.append(rec)
                Pvgps.append([float(rec['vgp_lon']), float(rec['vgp_lat'])])
        elif rev == 0:  # exclude normals
            if 90. - (float(rec['vgp_lat'])) <= cutoff and float(
                    rec['average_k']) >= kappa:
                Vgps.append(rec)
                Pvgps.append([float(rec['vgp_lon']), float(rec['vgp_lat'])])
        else:  # include normals
            if 90. - abs(float(rec['vgp_lat'])) <= cutoff and float(
                    rec['average_k']) >= kappa:
                if float(rec['vgp_lat']) < 0:
                    rec['vgp_lat'] = '%7.1f' % (-1 * float(rec['vgp_lat']))
                    rec['vgp_lon'] = '%7.1f' % (float(rec['vgp_lon']) - 180.)
                    Vgps.append(rec)
                    Pvgps.append(
                        [float(rec['vgp_lon']),
                         float(rec['vgp_lat'])])
    if spin == 0:  # do transformation to pole
        ppars = pmag.doprinc(Pvgps)
        for vgp in Vgps:
            vlon, vlat = pmag.dotilt(float(vgp['vgp_lon']),
                                     float(vgp['vgp_lat']),
                                     ppars['dec'] - 180., 90. - ppars['inc'])
            vgp['vgp_lon'] = vlon
            vgp['vgp_lat'] = vlat
            vgp['average_k'] = "0"
    S_B = pmag.get_Sb(Vgps)
    A = cutoff
    if v == 1:
        thetamax, A = 181., 180.
        vVgps, cnt = [], 0
        for vgp in Vgps:
            vVgps.append(vgp)  # make a copy of Vgps
        while thetamax > A:
            thetas = []
            A = 1.8 * S_B + 5
            cnt += 1
            for vgp in vVgps:
                thetas.append(90. - (float(vgp['vgp_lat'])))
            thetas.sort()
            thetamax = thetas[-1]
            if thetamax < A: break
            nVgps = []
            for vgp in vVgps:
                if 90. - (float(vgp['vgp_lat'])) < thetamax: nVgps.append(vgp)
            vVgps = []
            for vgp in nVgps:
                vVgps.append(vgp)
            S_B = pmag.get_Sb(vVgps)
        Vgps = []
        for vgp in vVgps:
            Vgps.append(vgp)  # make a new Vgp list
    SBs = []
    if boot == 1:
        for i in range(nb):  # now do bootstrap
            BVgps = []
            if i % 100 == 0: print(i, ' out of ', nb)
            for k in range(len(Vgps)):
                random.seed()
                ind = random.randint(0, len(Vgps) - 1)
                BVgps.append(Vgps[ind])
            SBs.append(pmag.get_Sb(BVgps))
        SBs.sort()
        low = int(.025 * nb)
        high = int(.975 * nb)
        print(len(Vgps),
              '%7.1f _ %7.1f ^ %7.1f %7.1f' % (S_B, SBs[low], SBs[high], A))
    else:
        print(len(Vgps), '%7.1f  %7.1f ' % (S_B, A))
예제 #24
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

    INPUT
       takes magic formatted sites, samples, specimens, or measurements

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file from magic, default='sites.txt'
         supported types=[measurements, specimens, samples, sites]
        -fsp FILE: specify specimen file name, (required if you want to plot measurements by sample)
                default='specimens.txt'
        -fsa FILE: specify sample file name, (required if you want to plot specimens by site)
                default='samples.txt'
        -fsi FILE: specify site file name, default='sites.txt'

        -obj OBJ: specify  level of plot  [all, sit, sam, spc], default is all
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is geographic, unspecified assumed geographic
        -fmt [svg,png,jpg] format for output plots
        -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
        -c plot as colour contour
        -sav save plot and quit quietly
    NOTE
        all: entire file; sit: site; sam: sample; spc: specimen
    """
    # initialize some default variables
    FIG = {} # plot dictionary
    FIG['eqarea'] = 1 # eqarea is figure 1
    plotE = 0
    plt = 0  # default to not plotting
    verbose = pmagplotlib.verbose
    # extract arguments from sys.argv
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg_from_sys("-WD", default_val=".")
    pmagplotlib.plot_init(FIG['eqarea'],5,5)
    in_file = pmag.get_named_arg_from_sys("-f", default_val="sites.txt")
    in_file = pmag.resolve_file_name(in_file, dir_path)
    if "-WD" not in sys.argv:
        dir_path = os.path.split(in_file)[0]
    #full_in_file = os.path.join(dir_path, in_file)
    plot_by = pmag.get_named_arg_from_sys("-obj", default_val="all").lower()
    spec_file = pmag.get_named_arg_from_sys("-fsp", default_val="specimens.txt")
    samp_file = pmag.get_named_arg_from_sys("-fsa", default_val="samples.txt")
    site_file = pmag.get_named_arg_from_sys("-fsi", default_val="sites.txt")
    if plot_by == 'all':
        plot_key = 'all'
    elif plot_by == 'sit':
        plot_key = 'site'
    elif plot_by == 'sam':
        plot_key = 'sample'
    elif plot_by == 'spc':
        plot_key = 'specimen'
    else:
        plot_by = 'all'
        plot_key = 'all'
    if '-c' in sys.argv:
        contour = 1
    else:
        contour = 0
    if '-sav' in sys.argv:
        plt = 1
        verbose = 0
    if '-ell' in sys.argv:
        plotE = 1
        ind = sys.argv.index('-ell')
        ell_type = sys.argv[ind+1]
        ell_type = pmag.get_named_arg_from_sys("-ell", "F")
        dist = ell_type.upper()
        # if dist type is unrecognized, use Fisher
        if dist not in ['F', 'K', 'B', 'BE', 'BV']:
            dist = 'F'
        if dist == "BV":
            FIG['bdirs'] = 2
            pmagplotlib.plot_init(FIG['bdirs'],5,5)
    crd = pmag.get_named_arg_from_sys("-crd", default_val="g")
    if crd == "s":
        coord = "-1"
    elif crd == "t":
        coord = "100"
    else:
        coord = "0"

    fmt = pmag.get_named_arg_from_sys("-fmt", "svg")

    dec_key = 'dir_dec'
    inc_key = 'dir_inc'
    tilt_key = 'dir_tilt_correction'
    #Dir_type_keys=['','site_direction_type','sample_direction_type','specimen_direction_type']

    #
    fnames = {"specimens": spec_file, "samples": samp_file, 'sites': site_file}
    contribution = nb.Contribution(dir_path, custom_filenames=fnames,
                                   single_file=in_file)

    try:
        contribution.propagate_location_to_samples()
        contribution.propagate_location_to_specimens()
        contribution.propagate_location_to_measurements()
    except KeyError as ex:
        pass

    # the object that contains the DataFrame + useful helper methods:
    table_name = list(contribution.tables.keys())[0]
    data_container = contribution.tables[table_name]
    # the actual DataFrame:
    data = data_container.df

    if plot_key != "all" and plot_key not in data.columns:
        print("-E- You can't plot by {} with the data provided".format(plot_key))
        return

    # add tilt key into DataFrame columns if it isn't there already
    if tilt_key not in data.columns:
        data.loc[:, tilt_key] = None

    if verbose:
        print(len(data), ' records read from ', in_file)

    # find desired dec,inc data:
    dir_type_key = ''
    #
    # get plotlist if not plotting all records
    #
    plotlist=[]
    if plot_key != "all":
        # return all where plot_key is not blank
        if plot_key not in data.columns:
            print('Can\'t plot by "{}".  That header is not in infile: {}'.format(plot_key, in_file))
            return
        plots = data[data[plot_key].notnull()]
        plotlist = plots[plot_key].unique() # grab unique values
    else:
        plotlist.append('All')

    for plot in plotlist:
        if verbose:
            print(plot)
        if plot == 'All':
            # plot everything at once
            plot_data = data
        else:
            # pull out only partial data
            plot_data = data[data[plot_key] == plot]

        DIblock = []
        GCblock = []
        # SLblock, SPblock = [], []
        title = plot
        mode = 1
        k = 0


        if dec_key not in plot_data.columns:
            print("-W- No dec/inc data")
            continue
        # get all records where dec & inc values exist
        plot_data = plot_data[plot_data[dec_key].notnull() & plot_data[inc_key].notnull()]
        if plot_data.empty:
            continue
        # this sorting out is done in get_di_bock
        #if coord == '0':  # geographic, use records with no tilt key (or tilt_key 0)
        #    cond1 = plot_data[tilt_key].fillna('') == coord
        #    cond2 = plot_data[tilt_key].isnull()
        #    plot_data = plot_data[cond1 | cond2]
        #else:  # not geographic coordinates, use only records with correct tilt_key
        #    plot_data = plot_data[plot_data[tilt_key] == coord]

        # get metadata for naming the plot file
        locations = data_container.get_name('location', df_slice=plot_data)
        site = data_container.get_name('site', df_slice=plot_data)
        sample = data_container.get_name('sample', df_slice=plot_data)
        specimen = data_container.get_name('specimen', df_slice=plot_data)

        # make sure method_codes is in plot_data
        if 'method_codes' not in plot_data.columns:
            plot_data['method_codes'] = ''

        # get data blocks
        DIblock = data_container.get_di_block(df_slice=plot_data,
                                              tilt_corr=coord, excl=['DE-BFP'])
        #SLblock = [[ind, row['method_codes']] for ind, row in plot_data.iterrows()]
        # get great circles
        great_circle_data = data_container.get_records_for_code('DE-BFP', incl=True,
                                                                use_slice=True, sli=plot_data)

        if len(great_circle_data) > 0:
            gc_cond = great_circle_data[tilt_key] == coord
            GCblock = [[float(row[dec_key]), float(row[inc_key])] for ind, row in great_circle_data[gc_cond].iterrows()]
            #SPblock = [[ind, row['method_codes']] for ind, row in great_circle_data[gc_cond].iterrows()]

        if len(DIblock) > 0:
            if contour == 0:
                pmagplotlib.plotEQ(FIG['eqarea'], DIblock, title)
            else:
                pmagplotlib.plotEQcont(FIG['eqarea'], DIblock)
        else:
            pmagplotlib.plotNET(FIG['eqarea'])
        if len(GCblock)>0:
            for rec in GCblock:
                pmagplotlib.plotC(FIG['eqarea'], rec, 90., 'g')
        if len(DIblock) == 0 and len(GCblock) == 0:
            if verbose:
                print("no records for plotting")
            continue
            #sys.exit()
        if plotE == 1:
            ppars = pmag.doprinc(DIblock) # get principal directions
            nDIs, rDIs, npars, rpars = [], [], [], []
            for rec in DIblock:
                angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
                if angle>90.:
                    rDIs.append(rec)
                else:
                    nDIs.append(rec)
            if dist=='B': # do on whole dataset
                etitle="Bingham confidence ellipse"
                bpars=pmag.dobingham(DIblock)
                for key in list(bpars.keys()):
                    if key!='n' and verbose: print("    ",key, '%7.1f'%(bpars[key]))
                    if key=='n' and verbose: print("    ",key, '       %i'%(bpars[key]))
                npars.append(bpars['dec'])
                npars.append(bpars['inc'])
                npars.append(bpars['Zeta'])
                npars.append(bpars['Zdec'])
                npars.append(bpars['Zinc'])
                npars.append(bpars['Eta'])
                npars.append(bpars['Edec'])
                npars.append(bpars['Einc'])
            if dist=='F':
                etitle="Fisher confidence cone"
                if len(nDIs)>2:
                    fpars=pmag.fisher_mean(nDIs)
                    for key in list(fpars.keys()):
                        if key!='n' and verbose: print("    ",key, '%7.1f'%(fpars[key]))
                        if key=='n' and verbose: print("    ",key, '       %i'%(fpars[key]))
                    mode+=1
                    npars.append(fpars['dec'])
                    npars.append(fpars['inc'])
                    npars.append(fpars['alpha95']) # Beta
                    npars.append(fpars['dec'])
                    isign=old_div(abs(fpars['inc']),fpars['inc'])
                    npars.append(fpars['inc']-isign*90.) #Beta inc
                    npars.append(fpars['alpha95']) # gamma
                    npars.append(fpars['dec']+90.) # Beta dec
                    npars.append(0.) #Beta inc
                if len(rDIs)>2:
                    fpars=pmag.fisher_mean(rDIs)
                    if verbose: print("mode ",mode)
                    for key in list(fpars.keys()):
                        if key!='n' and verbose: print("    ",key, '%7.1f'%(fpars[key]))
                        if key=='n' and verbose: print("    ",key, '       %i'%(fpars[key]))
                    mode+=1
                    rpars.append(fpars['dec'])
                    rpars.append(fpars['inc'])
                    rpars.append(fpars['alpha95']) # Beta
                    rpars.append(fpars['dec'])
                    isign=old_div(abs(fpars['inc']),fpars['inc'])
                    rpars.append(fpars['inc']-isign*90.) #Beta inc
                    rpars.append(fpars['alpha95']) # gamma
                    rpars.append(fpars['dec']+90.) # Beta dec
                    rpars.append(0.) #Beta inc
            if dist=='K':
                etitle="Kent confidence ellipse"
                if len(nDIs)>3:
                    kpars=pmag.dokent(nDIs,len(nDIs))
                    if verbose: print("mode ",mode)
                    for key in list(kpars.keys()):
                        if key!='n' and verbose: print("    ",key, '%7.1f'%(kpars[key]))
                        if key=='n' and verbose: print("    ",key, '       %i'%(kpars[key]))
                    mode+=1
                    npars.append(kpars['dec'])
                    npars.append(kpars['inc'])
                    npars.append(kpars['Zeta'])
                    npars.append(kpars['Zdec'])
                    npars.append(kpars['Zinc'])
                    npars.append(kpars['Eta'])
                    npars.append(kpars['Edec'])
                    npars.append(kpars['Einc'])
                if len(rDIs)>3:
                    kpars=pmag.dokent(rDIs,len(rDIs))
                    if verbose: print("mode ",mode)
                    for key in list(kpars.keys()):
                        if key!='n' and verbose: print("    ",key, '%7.1f'%(kpars[key]))
                        if key=='n' and verbose: print("    ",key, '       %i'%(kpars[key]))
                    mode+=1
                    rpars.append(kpars['dec'])
                    rpars.append(kpars['inc'])
                    rpars.append(kpars['Zeta'])
                    rpars.append(kpars['Zdec'])
                    rpars.append(kpars['Zinc'])
                    rpars.append(kpars['Eta'])
                    rpars.append(kpars['Edec'])
                    rpars.append(kpars['Einc'])
            else: # assume bootstrap
                if dist=='BE':
                    if len(nDIs)>5:
                        BnDIs=pmag.di_boot(nDIs)
                        Bkpars=pmag.dokent(BnDIs,1.)
                        if verbose: print("mode ",mode)
                        for key in list(Bkpars.keys()):
                            if key!='n' and verbose: print("    ",key, '%7.1f'%(Bkpars[key]))
                            if key=='n' and verbose: print("    ",key, '       %i'%(Bkpars[key]))
                        mode+=1
                        npars.append(Bkpars['dec'])
                        npars.append(Bkpars['inc'])
                        npars.append(Bkpars['Zeta'])
                        npars.append(Bkpars['Zdec'])
                        npars.append(Bkpars['Zinc'])
                        npars.append(Bkpars['Eta'])
                        npars.append(Bkpars['Edec'])
                        npars.append(Bkpars['Einc'])
                    if len(rDIs)>5:
                        BrDIs=pmag.di_boot(rDIs)
                        Bkpars=pmag.dokent(BrDIs,1.)
                        if verbose: print("mode ",mode)
                        for key in list(Bkpars.keys()):
                            if key!='n' and verbose: print("    ",key, '%7.1f'%(Bkpars[key]))
                            if key=='n' and verbose: print("    ",key, '       %i'%(Bkpars[key]))
                        mode+=1
                        rpars.append(Bkpars['dec'])
                        rpars.append(Bkpars['inc'])
                        rpars.append(Bkpars['Zeta'])
                        rpars.append(Bkpars['Zdec'])
                        rpars.append(Bkpars['Zinc'])
                        rpars.append(Bkpars['Eta'])
                        rpars.append(Bkpars['Edec'])
                        rpars.append(Bkpars['Einc'])
                    etitle="Bootstrapped confidence ellipse"
                elif dist=='BV':
                    sym={'lower':['o','c'],'upper':['o','g'],'size':3,'edgecolor':'face'}
                    if len(nDIs)>5:
                        BnDIs=pmag.di_boot(nDIs)
                        pmagplotlib.plotEQsym(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors', sym)
                    if len(rDIs)>5:
                        BrDIs=pmag.di_boot(rDIs)
                        if len(nDIs)>5:  # plot on existing plots
                            pmagplotlib.plotDIsym(FIG['bdirs'],BrDIs,sym)
                        else:
                            pmagplotlib.plotEQ(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors')
            if dist=='B':
                if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],npars,0)
            elif len(nDIs)>3 and dist!='BV':
                pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],npars,0)
                if len(rDIs)>3:
                    pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],rpars,0)
            elif len(rDIs)>3 and dist!='BV':
                pmagplotlib.plotCONF(FIG['eqarea'],etitle,[],rpars,0)

        for key in list(FIG.keys()):
            files = {}
            filename = pmag.get_named_arg_from_sys('-fname')
            if filename: # use provided filename
                filename+= '.' + fmt
            elif pmagplotlib.isServer: # use server plot naming convention
                filename='LO:_'+locations+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+specimen+'_CO:_'+crd+'_TY:_'+key+'_.'+fmt
            elif plot_key == 'all':
                filename = 'all'
                if 'location' in plot_data.columns:
                    locs = plot_data['location'].unique()
                    loc_string = "_".join([loc.replace(' ', '_') for loc in locs])
                    filename += "_" + loc_string
                filename += "_" + crd + "_" + key
                filename += ".{}".format(fmt)
            else: # use more readable naming convention
                filename = ''
                # fix this if plot_by is location , for example
                use_names = {'location': [locations], 'site': [locations, site],
                             'sample': [locations, site, sample],
                             'specimen': [locations, site, sample, specimen]}
                use = use_names[plot_key]
                use.extend([crd, key])
                for item in use: #[locations, site, sample, specimen, crd, key]:
                    if item:
                        item = item.replace(' ', '_')
                        filename += item + '_'
                if filename.endswith('_'):
                    filename = filename[:-1]
                filename += ".{}".format(fmt)

            files[key]=filename

        if pmagplotlib.isServer:
            black     = '#000000'
            purple    = '#800080'
            titles={}
            titles['eq']='Equal Area Plot'
            FIG = pmagplotlib.addBorders(FIG,titles,black,purple)
            pmagplotlib.saveP(FIG,files)

        if plt:
            pmagplotlib.saveP(FIG,files)
            continue
        if verbose:
            pmagplotlib.drawFIGS(FIG)
            ans=input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
            if ans == "q":
                sys.exit()
            if ans == "a":
                pmagplotlib.saveP(FIG,files)
        continue
예제 #25
0
def main():
    """
    NAME
       plotdi_e.py

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

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

    SYNTAX
       plotdi_e.py [command line options]

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

    """
    dist='F' # default distribution is Fisherian
    mode=1
    EQ={'eq':1}
    if len(sys.argv) > 0:
        if '-h' in sys.argv: # check if help is needed
            print main.__doc__
            sys.exit() # graceful quit
        if '-i' in sys.argv: # ask for filename
            file=raw_input("Enter file name with dec, inc data: ")
            dist=raw_input("Enter desired distrubution: [Fish]er, [Bing]ham, [Kent] [Boot] [default is Fisher]: ")
            if dist=="":dist="F"
            if dist=="Boot":
                 type=raw_input(" Ellipses or distribution of vectors? [E]/V ")
                 if type=="" or type=="E":
                     dist="BE"
                 else:
                     dist="BE"
        else:
#
            if '-f' in sys.argv:
                ind=sys.argv.index('-f')
                file=sys.argv[ind+1]
            else:
                print 'you must specify a file name'
                print main.__doc__
                sys.exit()
            if '-Bing' in sys.argv:dist='B'
            if '-Kent' in sys.argv:dist='K'
            if '-Boot' in sys.argv:
                ind=sys.argv.index('-Boot')
                type=sys.argv[ind+1]
                if type=='E': 
                    dist='BE'
                elif type=='V': 
                    dist='BV'
                    EQ['bdirs']=2
                    pmagplotlib.plot_init(EQ['bdirs'],5,5)
                else:
                    print main.__doc__
                    sys.exit()
    pmagplotlib.plot_init(EQ['eq'],5,5)
#
# get to work
    f=open(file,'r')
    data=f.readlines()
#
    DIs= [] # set up list for dec inc data
    DiRecs=[]
    pars=[]
    nDIs,rDIs,npars,rpars=[],[],[],[]
    mode =1
    for line in data:   # read in the data from standard input
        DiRec={}
        rec=line.split() # split each line on space to get records
        DIs.append((float(rec[0]),float(rec[1]),1.))
        DiRec['dec']=rec[0]
        DiRec['inc']=rec[1]
        DiRec['direction_type']='l'
        DiRecs.append(DiRec)
    # split into two modes
    ppars=pmag.doprinc(DIs) # get principal directions
    for rec in DIs:
        angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
        if angle>90.:
            rDIs.append(rec)
        else:
            nDIs.append(rec)
    if dist=='B': # do on whole dataset
        title="Bingham confidence ellipse"
        bpars=pmag.dobingham(DIs)
        for key in bpars.keys():
            if key!='n':print "    ",key, '%7.1f'%(bpars[key])
            if key=='n':print "    ",key, '       %i'%(bpars[key])
        npars.append(bpars['dec']) 
        npars.append(bpars['inc'])
        npars.append(bpars['Zeta']) 
        npars.append(bpars['Zdec']) 
        npars.append(bpars['Zinc'])
        npars.append(bpars['Eta']) 
        npars.append(bpars['Edec']) 
        npars.append(bpars['Einc'])
    if dist=='F':
        title="Fisher confidence cone"
        if len(nDIs)>3:
            fpars=pmag.fisher_mean(nDIs)
            print "mode ",mode
            for key in fpars.keys():
                if key!='n':print "    ",key, '%7.1f'%(fpars[key])
                if key=='n':print "    ",key, '       %i'%(fpars[key])
            mode+=1
            npars.append(fpars['dec']) 
            npars.append(fpars['inc'])
            npars.append(fpars['alpha95']) # Beta
            npars.append(fpars['dec']) 
            isign=abs(fpars['inc'])/fpars['inc'] 
            npars.append(fpars['inc']-isign*90.) #Beta inc
            npars.append(fpars['alpha95']) # gamma 
            npars.append(fpars['dec']+90.) # Beta dec
            npars.append(0.) #Beta inc
        if len(rDIs)>3:
            fpars=pmag.fisher_mean(rDIs)
            print "mode ",mode
            for key in fpars.keys():
                if key!='n':print "    ",key, '%7.1f'%(fpars[key])
                if key=='n':print "    ",key, '       %i'%(fpars[key])
            mode+=1
            rpars.append(fpars['dec']) 
            rpars.append(fpars['inc'])
            rpars.append(fpars['alpha95']) # Beta
            rpars.append(fpars['dec']) 
            isign=abs(fpars['inc'])/fpars['inc'] 
            rpars.append(fpars['inc']-isign*90.) #Beta inc
            rpars.append(fpars['alpha95']) # gamma 
            rpars.append(fpars['dec']+90.) # Beta dec
            rpars.append(0.) #Beta inc
    if dist=='K':
        title="Kent confidence ellipse"
        if len(nDIs)>3:
            kpars=pmag.dokent(nDIs,len(nDIs))
            print "mode ",mode
            for key in kpars.keys():
                if key!='n':print "    ",key, '%7.1f'%(kpars[key])
                if key=='n':print "    ",key, '       %i'%(kpars[key])
            mode+=1
            npars.append(kpars['dec']) 
            npars.append(kpars['inc'])
            npars.append(kpars['Zeta']) 
            npars.append(kpars['Zdec']) 
            npars.append(kpars['Zinc'])
            npars.append(kpars['Eta']) 
            npars.append(kpars['Edec']) 
            npars.append(kpars['Einc'])
        if len(rDIs)>3:
            kpars=pmag.dokent(rDIs,len(rDIs))
            print "mode ",mode
            for key in kpars.keys():
                if key!='n':print "    ",key, '%7.1f'%(kpars[key])
                if key=='n':print "    ",key, '       %i'%(kpars[key])
            mode+=1
            rpars.append(kpars['dec']) 
            rpars.append(kpars['inc'])
            rpars.append(kpars['Zeta']) 
            rpars.append(kpars['Zdec']) 
            rpars.append(kpars['Zinc'])
            rpars.append(kpars['Eta']) 
            rpars.append(kpars['Edec']) 
            rpars.append(kpars['Einc'])
    else: # assume bootstrap
        if dist=='BE':
            if len(nDIs)>5:
                BnDIs=pmag.di_boot(nDIs)
                Bkpars=pmag.dokent(BnDIs,1.)
                print "mode ",mode
                for key in Bkpars.keys():
                    if key!='n':print "    ",key, '%7.1f'%(Bkpars[key])
                    if key=='n':print "    ",key, '       %i'%(Bkpars[key])
                mode+=1
                npars.append(Bkpars['dec']) 
                npars.append(Bkpars['inc'])
                npars.append(Bkpars['Zeta']) 
                npars.append(Bkpars['Zdec']) 
                npars.append(Bkpars['Zinc'])
                npars.append(Bkpars['Eta']) 
                npars.append(Bkpars['Edec']) 
                npars.append(Bkpars['Einc'])
            if len(rDIs)>5:
                BrDIs=pmag.di_boot(rDIs)
                Bkpars=pmag.dokent(BrDIs,1.)
                print "mode ",mode
                for key in Bkpars.keys():
                    if key!='n':print "    ",key, '%7.1f'%(Bkpars[key])
                    if key=='n':print "    ",key, '       %i'%(Bkpars[key])
                mode+=1
                rpars.append(Bkpars['dec']) 
                rpars.append(Bkpars['inc'])
                rpars.append(Bkpars['Zeta']) 
                rpars.append(Bkpars['Zdec']) 
                rpars.append(Bkpars['Zinc'])
                rpars.append(Bkpars['Eta']) 
                rpars.append(Bkpars['Edec']) 
                rpars.append(Bkpars['Einc'])
            title="Bootstrapped confidence ellipse"
        elif dist=='BV':
            if len(nDIs)>5:
                pmagplotlib.plotEQ(EQ['eq'],nDIs,'Data')
                BnDIs=pmag.di_boot(nDIs)
                pmagplotlib.plotEQ(EQ['bdirs'],BnDIs,'Bootstrapped Eigenvectors')
            if len(rDIs)>5:
                BrDIs=pmag.di_boot(rDIs)
                if len(nDIs)>5:  # plot on existing plots
                    pmagplotlib.plotDI(EQ['eq'],rDIs)
                    pmagplotlib.plotDI(EQ['bdirs'],BrDIs)
                else:
                    pmagplotlib.plotEQ(EQ['eq'],rDIs,'Data')
                    pmagplotlib.plotEQ(EQ['bdirs'],BrDIs,'Bootstrapped Eigenvectors')
            pmagplotlib.drawFIGS(EQ)
            ans=raw_input('s[a]ve, [q]uit ')
            if ans=='q':sys.exit()
            if ans=='a':
                files={}
                for key in EQ.keys():
                    files[key]='BE_'+key+'.svg'
                pmagplotlib.saveP(EQ,files)
            sys.exit() 
    if len(nDIs)>5:
        pmagplotlib.plotCONF(EQ['eq'],title,DiRecs,npars,1)
        if len(rDIs)>5 and dist!='B': 
            pmagplotlib.plotCONF(EQ['eq'],title,[],rpars,0)
    elif len(rDIs)>5 and dist!='B': 
        pmagplotlib.plotCONF(EQ['eq'],title,DiRecs,rpars,1)
    pmagplotlib.drawFIGS(EQ)
    ans=raw_input('s[a]ve, [q]uit ')
    if ans=='q':sys.exit()
    if ans=='a':
        files={}
        for key in EQ.keys():
            files[key]=key+'.svg'
        pmagplotlib.saveP(EQ,files)
예제 #26
0
파일: fishqq.py 프로젝트: CrabGit334/PmagPy
def main():
    """
    NAME
       fishqq.py

    DESCRIPTION
       makes qq plot from dec,inc input data

    INPUT FORMAT
       takes dec/inc pairs in space delimited file

    SYNTAX
       fishqq.py [command line options]

    OPTIONS
        -h help message
        -f FILE, specify file on command line
        -F FILE, specify output file for statistics
        -sav save and quit [saves as input file name plus fmt extension]
        -fmt specify format for output [png, eps, svg, pdf] 

    OUTPUT:
        Dec Inc N Mu Mu_crit Me Me_crit Y/N
     where direction is the principal component and Y/N is Fisherian or not
     separate lines for each mode with N >=10 (N and R)
    """
    fmt,plot='svg',0
    outfile=""
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        data=f.readlines()
    if '-F' in sys.argv:
        ind=sys.argv.index('-F')
        outfile=open(sys.argv[ind+1],'w') # open output file
    if '-sav' in sys.argv: plot=1
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    DIs,nDIs,rDIs= [],[],[] # set up list for data
    for line in data:   # read in the data from standard input
        if '\t' in line:
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        DIs.append([float(rec[0]),float(rec[1])]) # append data to Inc
# split into two modes
    ppars=pmag.doprinc(DIs) # get principal directions
    for rec in DIs:
        angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
        if angle>90.:
            rDIs.append(rec)
        else:
            nDIs.append(rec)
    
#
    if len(rDIs) >=10 or len(nDIs) >=10:
        D1,I1=[],[]
        QQ={'unf1':1,'exp1':2}
        pmagplotlib.plot_init(QQ['unf1'],5,5)
        pmagplotlib.plot_init(QQ['exp1'],5,5)
        if len(nDIs) < 10: 
            ppars=pmag.doprinc(rDIs) # get principal directions
            Drbar,Irbar=ppars['dec']-180.,-ppars['inc']
            Nr=len(rDIs)
            for di in rDIs:
                d,irot=pmag.dotilt(di[0],di[1],Drbar-180.,90.-Irbar) # rotate to mean
                drot=d-180.
                if drot<0:drot=drot+360.
                D1.append(drot)           
                I1.append(irot) 
                Dtit='Mode 2 Declinations'
                Itit='Mode 2 Inclinations'
        else:          
            ppars=pmag.doprinc(nDIs) # get principal directions
            Dnbar,Inbar=ppars['dec'],ppars['inc']
            Nn=len(nDIs)
            for di in nDIs:
                d,irot=pmag.dotilt(di[0],di[1],Dnbar-180.,90.-Inbar) # rotate to mean
                drot=d-180.
                if drot<0:drot=drot+360.
                D1.append(drot)
                I1.append(irot)
                Dtit='Mode 1 Declinations'
                Itit='Mode 1 Inclinations'
        Mu_n,Mu_ncr=pmagplotlib.plot_qq_unf(QQ['unf1'],D1,Dtit) # make plot
        Me_n,Me_ncr=pmagplotlib.plot_qq_exp(QQ['exp1'],I1,Itit) # make plot
        #print Mu_n,Mu_ncr,Me_n, Me_ncr
        if outfile!="":
#        Dec Inc N Mu Mu_crit Me Me_crit Y/N
            if Mu_n<=Mu_ncr and Me_n<=Me_ncr:
               F='Y'
            else:
               F='N'
            outstring='%7.1f %7.1f %i %5.3f %5.3f %5.3f %5.3f %s \n'%(Dnbar,Inbar,Nn,Mu_n,Mu_ncr,Me_n,Me_ncr,F)
            outfile.write(outstring)
    else:
        print('you need N> 10 for at least one mode')
        sys.exit()
    if len(rDIs)>10 and len(nDIs)>10:
        D2,I2=[],[]
        QQ['unf2']=3
        QQ['exp2']=4
        pmagplotlib.plot_init(QQ['unf2'],5,5)
        pmagplotlib.plot_init(QQ['exp2'],5,5)
        ppars=pmag.doprinc(rDIs) # get principal directions
        Drbar,Irbar=ppars['dec']-180.,-ppars['inc']
        Nr=len(rDIs)
        for di in rDIs:
            d,irot=pmag.dotilt(di[0],di[1],Drbar-180.,90.-Irbar) # rotate to mean
            drot=d-180.
            if drot<0:drot=drot+360.
            D2.append(drot)           
            I2.append(irot) 
            Dtit='Mode 2 Declinations'
            Itit='Mode 2 Inclinations'
        Mu_r,Mu_rcr=pmagplotlib.plot_qq_unf(QQ['unf2'],D2,Dtit) # make plot
        Me_r,Me_rcr=pmagplotlib.plot_qq_exp(QQ['exp2'],I2,Itit) # make plot
        if outfile!="":
#        Dec Inc N Mu Mu_crit Me Me_crit Y/N
            if Mu_r<=Mu_rcr and Me_r<=Me_rcr:
               F='Y'
            else:
               F='N'
            outstring='%7.1f %7.1f %i %5.3f %5.3f %5.3f %5.3f %s \n'%(Drbar,Irbar,Nr,Mu_r,Mu_rcr,Me_r,Me_rcr,F)
            outfile.write(outstring)
    files={}
    for key in list(QQ.keys()):
        files[key]=file+'_'+key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==1:
        pmagplotlib.save_plots(QQ,files)
    else:
        pmagplotlib.draw_figs(QQ) 
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.save_plots(QQ,files)
예제 #27
0
def main():
    """
    NAME
       goprinc.py

    DESCRIPTION
       calculates Principal components from dec/iinc data

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

    SYNTAX
       goprinc.py [options]  [< filename]

    OPTIONS
        -h prints help message and quits
        -i for interactive filename entry
        -f FILE, specify input file
        -F FILE, specifies output file name
        < filename for reading from standard input

    OUTPUT
       tau_1 V1_Dec, V1_Inc, tau_2 V2_Dec V2_Inc, tau_3 V3_Dec V3_Inc, N

    """
    if len(sys.argv) > 0:
        if '-h' in sys.argv:  # check if help is needed
            print main.__doc__
            sys.exit()  # graceful quit
        if '-f' in sys.argv:
            ind = sys.argv.index('-f')
            file = sys.argv[ind + 1]
            f = open(file, 'rU')
            data = f.readlines()
        elif '-i' in sys.argv:  # ask for filename
            file = raw_input("Enter file name with dec, inc data: ")
            f = open(file, 'rU')
            data = f.readlines()
        else:
            #
            data = sys.stdin.readlines()  # read in data from standard input
    ofile = ""
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        ofile = sys.argv[ind + 1]
        out = open(ofile, 'w + a')
    DIs = []  # set up list for dec inc data
    for line in data:  # read in the data from standard input
        if '\t' in line:
            rec = line.split('\t')  # split each line on space to get records
        else:
            rec = line.split()  # split each line on space to get records
        DIs.append((float(rec[0]), float(rec[1])))


#
    ppars = pmag.doprinc(DIs)
    output = '%7.5f %7.1f %7.1f %7.5f %7.1f %7.1f %7.5f %7.1f %7.1f %i' % (
        ppars["tau1"], ppars["dec"], ppars["inc"], ppars["tau2"],
        ppars["V2dec"], ppars["V2inc"], ppars["tau3"], ppars["V3dec"],
        ppars["V3inc"], ppars["N"])
    if ofile == "":
        print output
    else:
        out.write(output + '\n')