Ejemplo n.º 1
0
def main():
    """
    NAME
       qqunf.py

    DESCRIPTION
       makes qq plot from input data against uniform distribution

    SYNTAX
       qqunf.py [command line options]

    OPTIONS
        -h help message
        -f FILE, specify file on command line

    """
    fmt, plot = 'svg', 0
    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')
        input = f.readlines()
    Data = []
    for line in input:
        line.replace('\n', '')
        if '\t' in line:  # read in the data from standard input
            rec = line.split('\t')  # split each line on space to get records
        else:
            rec = line.split()  # split each line on space to get records
        Data.append(float(rec[0]))


#
    if len(Data) >= 10:
        QQ = {'unf1': 1}
        pmagplotlib.plot_init(QQ['unf1'], 5, 5)
        pmagplotlib.plot_qq_unf(QQ['unf1'], Data, 'QQ-Uniform')  # make plot
    else:
        print('you need N> 10')
        sys.exit()
    pmagplotlib.draw_figs(QQ)
    files = {}
    for key in list(QQ.keys()):
        files[key] = 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:
        files['qq'] = file + '.' + fmt
        pmagplotlib.save_plots(QQ, files)
    else:
        ans = input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans == "a": pmagplotlib.save_plots(QQ, files)
Ejemplo n.º 2
0
def main():
    """
    NAME
        plot_2cdfs.py

    DESCRIPTION
        makes plots of cdfs of data in input file 

    SYNTAX
        plot_2cdfs.py [-h][command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE1 FILE2
        -t TITLE
        -fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is svg
        
    """
    fmt = 'svg'
    title = ""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file = sys.argv[ind + 1]
        X = numpy.loadtxt(file)
        file = sys.argv[ind + 2]
        X2 = numpy.loadtxt(file)


#    else:
#       X=numpy.loadtxt(sys.stdin,dtype=numpy.float)
    else:
        print('-f option required')
        print(main.__doc__)
        sys.exit()
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-t' in sys.argv:
        ind = sys.argv.index('-t')
        title = sys.argv[ind + 1]
    CDF = {'X': 1}
    pmagplotlib.plot_init(CDF['X'], 5, 5)
    pmagplotlib.plot_cdf(CDF['X'], X, '', 'r', '')
    pmagplotlib.plot_cdf(CDF['X'], X2, title, 'b', '')
    D, p = scipy.stats.ks_2samp(X, X2)
    if p >= .05:
        print(D, p, ' not rejected at 95%')
    else:
        print(D, p, ' rejected at 95%')
    pmagplotlib.draw_figs(CDF)
    ans = input('S[a]ve  plot, <Return> to quit ')
    if ans == 'a':
        files = {'X': 'CDF_.' + fmt}
        pmagplotlib.save_plots(CDF, files)
Ejemplo n.º 3
0
def main():
    """
    NAME
        plot_2cdfs.py

    DESCRIPTION
        makes plots of cdfs of data in input file 

    SYNTAX
        plot_2cdfs.py [-h][command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE1 FILE2
        -t TITLE
        -fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is svg
        
    """
    fmt='svg'
    title=""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
       ind=sys.argv.index('-f')
       file=sys.argv[ind+1] 
       X=numpy.loadtxt(file)
       file=sys.argv[ind+2] 
       X2=numpy.loadtxt(file)
#    else:
#       X=numpy.loadtxt(sys.stdin,dtype=numpy.float)
    else:
       print('-f option required')
       print(main.__doc__)
       sys.exit()
    if '-fmt' in sys.argv:
       ind=sys.argv.index('-fmt')
       fmt=sys.argv[ind+1] 
    if '-t' in sys.argv:
       ind=sys.argv.index('-t')
       title=sys.argv[ind+1] 
    CDF={'X':1}
    pmagplotlib.plot_init(CDF['X'],5,5)
    pmagplotlib.plot_cdf(CDF['X'],X,'','r','')
    pmagplotlib.plot_cdf(CDF['X'],X2,title,'b','')
    D,p=scipy.stats.ks_2samp(X,X2)
    if p>=.05:
        print(D,p,' not rejected at 95%')
    else:
        print(D,p,' rejected at 95%')
    pmagplotlib.draw_figs(CDF)
    ans= input('S[a]ve  plot, <Return> to quit ')
    if ans=='a':
        files={'X':'CDF_.'+fmt}
        pmagplotlib.save_plots(CDF,files)
Ejemplo n.º 4
0
def main():
    """
    NAME
        plot_cdf.py

    DESCRIPTION
        makes plots of cdfs of data in input file 

    SYNTAX
        plot_cdf.py [-h][command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE
        -t TITLE
        -fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is svg
        -sav saves plot and quits
        
    """
    fmt, plot = 'svg', 0
    title = ""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-sav' in sys.argv: plot = 1
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file = sys.argv[ind + 1]
        X = numpy.loadtxt(file)


#    else:
#       X=numpy.loadtxt(sys.stdin,dtype=numpy.float)
    else:
        print('-f option required')
        print(main.__doc__)
        sys.exit()
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-t' in sys.argv:
        ind = sys.argv.index('-t')
        title = sys.argv[ind + 1]
    CDF = {'X': 1}
    pmagplotlib.plot_init(CDF['X'], 5, 5)
    pmagplotlib.plot_cdf(CDF['X'], X, title, 'r', '')
    files = {'X': 'CDF_.' + fmt}
    if plot == 0:
        pmagplotlib.draw_figs(CDF)
        ans = input('S[a]ve  plot, <Return> to quit ')
        if ans == 'a':
            pmagplotlib.save_plots(CDF, files)
    else:
        pmagplotlib.save_plots(CDF, files)
Ejemplo n.º 5
0
def main():
    """
    NAME
        plot_cdf.py

    DESCRIPTION
        makes plots of cdfs of data in input file 

    SYNTAX
        plot_cdf.py [-h][command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE
        -t TITLE
        -fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is svg
        -sav saves plot and quits
        
    """
    fmt,plot='svg',0
    title=""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-sav' in sys.argv:plot=1
    if '-f' in sys.argv:
       ind=sys.argv.index('-f')
       file=sys.argv[ind+1] 
       X=numpy.loadtxt(file)
#    else:
#       X=numpy.loadtxt(sys.stdin,dtype=numpy.float)
    else:
       print('-f option required')
       print(main.__doc__)
       sys.exit()
    if '-fmt' in sys.argv:
       ind=sys.argv.index('-fmt')
       fmt=sys.argv[ind+1] 
    if '-t' in sys.argv:
       ind=sys.argv.index('-t')
       title=sys.argv[ind+1] 
    CDF={'X':1}
    pmagplotlib.plot_init(CDF['X'],5,5)
    pmagplotlib.plot_cdf(CDF['X'],X,title,'r','')
    files={'X':'CDF_.'+fmt}
    if plot==0:
        pmagplotlib.draw_figs(CDF)
        ans= input('S[a]ve  plot, <Return> to quit ')
        if ans=='a':
            pmagplotlib.save_plots(CDF,files)
    else:
        pmagplotlib.save_plots(CDF,files)
Ejemplo n.º 6
0
    def plot(self, save=False, fmt="svg"):
        fig = plt.figure(figsize=(6, 5), facecolor='white')
        fig.subplots_adjust(left=0.18,
                            right=0.97,
                            bottom=0.18,
                            top=0.9,
                            wspace=0.5,
                            hspace=0.5)
        #ax = fig.add_subplot(1,1,1)
        plt.contour(self.xi * 1000,
                    self.yi * 1000,
                    self.zi,
                    9,
                    colors='k',
                    linewidths=0.5)  # mt to T
        # plt.pcolormesh(X,Y,Z_a,cmap=plt.get_cmap('rainbow'))#vmin=np.min(rho)-0.2)
        plt.pcolormesh(self.xi * 1000,
                       self.yi * 1000,
                       self.zi,
                       cmap=plt.get_cmap('rainbow'))  # vmin=np.min(rho)-0.2)
        plt.colorbar()
        # plt.xlim(0,0.15)
        # plt.ylim(-0.1,0.1)
        plt.xlabel('B$_{c}$ (mT)', fontsize=12)
        plt.ylabel('B$_{i}$ (mT)', fontsize=12)

        from pmagpy import pmagplotlib
        if save:
            pmagplotlib.save_plots({'forc': 1},
                                   {'forc': 'forc.{}'.format(fmt)})
            return
        else:
            pmagplotlib.draw_figs({'forc': 1})
            res = pmagplotlib.save_or_quit()
            if res == 'a':
                pmagplotlib.save_plots({'forc': 1},
                                       {'forc': 'forc.{}'.format(fmt)})
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
def main():
    """
    NAME
       common_mean.py

    DESCRIPTION
       calculates bootstrap statistics to test for common mean

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files
   
    SYNTAX
       common_mean.py [command line options]
    
    OPTIONS
       -h prints help message and quits
       -f FILE, input file 
       -f2 FILE, optional second file to compare with first file
       -dir D I, optional direction to compare with input file
       -fmt [svg,jpg,pnd,pdf] set figure format [default is svg]
    NOTES
       must have either F2 OR dir but not both
     

    """
    d, i, file2 = "", "", ""
    fmt, plot = 'svg', 0
    if '-h' in sys.argv:  # check if help is needed
        print(main.__doc__)
        sys.exit()  # graceful quit
    if '-sav' in sys.argv: plot = 1
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file1 = sys.argv[ind + 1]
    if '-f2' in sys.argv:
        ind = sys.argv.index('-f2')
        file2 = sys.argv[ind + 1]
    if '-dir' in sys.argv:
        ind = sys.argv.index('-dir')
        d = float(sys.argv[ind + 1])
        i = float(sys.argv[ind + 2])
    D1 = numpy.loadtxt(file1, dtype=numpy.float)
    if file2 != "": D2 = numpy.loadtxt(file2, dtype=numpy.float)
    #
    counter, NumSims = 0, 1000
    #
    # get bootstrapped means for first data set
    #
    print("Doing first set of directions, please be patient..")
    BDI1 = pmag.di_boot(D1)
    #
    #   convert to cartesian coordinates X1,X2, Y1,Y2 and Z1, Z2
    #
    if d == "":  # repeat for second data set
        print("Doing second  set of directions, please be patient..")
        BDI2 = pmag.di_boot(D2)
    else:
        BDI2 = []


# set up plots
    CDF = {'X': 1, 'Y': 2, 'Z': 3}
    pmagplotlib.plot_init(CDF['X'], 4, 4)
    pmagplotlib.plot_init(CDF['Y'], 4, 4)
    pmagplotlib.plot_init(CDF['Z'], 4, 4)
    # draw the cdfs
    pmagplotlib.plot_com(CDF, BDI1, BDI2, [d, i])
    files = {}
    files['X'] = 'CD_X.' + fmt
    files['Y'] = 'CD_Y.' + fmt
    files['Z'] = 'CD_Z.' + fmt
    if plot == 0:
        pmagplotlib.draw_figs(CDF)
        ans = input("S[a]ve plots, <Return> to quit ")
        if ans == "a":
            pmagplotlib.save_plots(CDF, files)
        else:
            sys.exit()

    else:
        pmagplotlib.save_plots(CDF, files)
        sys.exit()
Ejemplo n.º 9
0
def main():
    """
    NAME
        dmag_magic2.py

    DESCRIPTION
       plots intensity decay curves for demagnetization experiments

    SYNTAX
        dmag_magic -h [command line options]

    INPUT
       takes magic formatted magic_measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot, default is by location
        -LT [AF,T,M]: specify lab treatment type, default AF
        -XLP [PI]: exclude specific  lab protocols (for example, method codes like LP-PI)
        -N do not normalize by NRM magnetization
        -sav save plots silently and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    FIG = {}  # plot dictionary
    FIG['demag'] = 1  # demag is figure 1
    in_file, plot_key, LT = 'magic_measurements.txt', 'er_location_name', "LT-AF-Z"
    XLP = ""
    norm = 1
    LT = 'LT-AF-Z'
    units, dmag_key = 'T', 'treatment_ac_field'
    plot = 0
    fmt = 'svg'
    if len(sys.argv) > 1:
        if '-h' in sys.argv:
            print(main.__doc__)
            sys.exit()
        if '-N' in sys.argv:
            norm = 0
        if '-sav' in sys.argv:
            plot = 1
        if '-f' in sys.argv:
            ind = sys.argv.index("-f")
            in_file = sys.argv[ind+1]
        if '-fmt' in sys.argv:
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind+1]
        if '-obj' in sys.argv:
            ind = sys.argv.index('-obj')
            plot_by = sys.argv[ind+1]
            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 '-XLP' in sys.argv:
            ind = sys.argv.index("-XLP")
            XLP = sys.argv[ind+1]  # get lab protocol for excluding
        if '-LT' in sys.argv:
            ind = sys.argv.index("-LT")
            LT = 'LT-'+sys.argv[ind+1]+'-Z'  # get lab treatment for plotting
            if LT == 'LT-T-Z':
                units, dmag_key = 'K', 'treatment_temp'
            elif LT == 'LT-AF-Z':
                units, dmag_key = 'T', 'treatment_ac_field'
            elif LT == 'LT-M-Z':
                units, dmag_key = 'J', 'treatment_mw_energy'
            else:
                units = 'U'
    data, file_type = pmag.magic_read(in_file)
    sids = pmag.get_specs(data)
    pmagplotlib.plot_init(FIG['demag'], 5, 5)
    print(len(data), ' records read from ', in_file)
    #
    #
    # find desired intensity data
    #
    #
    plotlist, intlist = [], ['measurement_magnitude', 'measurement_magn_moment',
                             'measurement_magn_volume', 'measurement_magn_mass']
    IntMeths = []
    FixData = []
    for rec in data:
        meths = []
        methcodes = rec['magic_method_codes'].split(':')
        for meth in methcodes:
            meths.append(meth.strip())
        for key in rec.keys():
            if key in intlist and rec[key] != "":
                if key not in IntMeths:
                    IntMeths.append(key)
                if rec[plot_key] not in plotlist and LT in meths:
                    plotlist.append(rec[plot_key])
                if 'measurement_flag' not in rec.keys():
                    rec['measurement_flag'] = 'g'
                FixData.append(rec)
        plotlist.sort()
    if len(IntMeths) == 0:
        print('No intensity information found')
        sys.exit()
    data = FixData
    # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    int_key = IntMeths[0]
    for plt in plotlist:
        if plot == 0:
            print(plt, 'plotting by: ', plot_key)
        # fish out all the data for this type of plot
        PLTblock = pmag.get_dictitem(data, plot_key, plt, 'T')
        # fish out all the dmag for this experiment type
        PLTblock = pmag.get_dictitem(PLTblock, 'magic_method_codes', LT, 'has')
        # get all with this intensity key non-blank
        PLTblock = pmag.get_dictitem(PLTblock, int_key, '', 'F')
        if XLP != "":
            # reject data with XLP in method_code
            PLTblock = pmag.get_dictitem(
                PLTblock, 'magic_method_codes', XLP, 'not')
        if len(PLTblock) > 2:
            title = PLTblock[0][plot_key]
            spcs = []
            for rec in PLTblock:
                if rec['er_specimen_name'] not in spcs:
                    spcs.append(rec['er_specimen_name'])
            for spc in spcs:
                # plot specimen by specimen
                SPCblock = pmag.get_dictitem(
                    PLTblock, 'er_specimen_name', spc, 'T')
                INTblock = []
                for rec in SPCblock:
                    INTblock.append([float(rec[dmag_key]), 0, 0, float(
                        rec[int_key]), 1, rec['measurement_flag']])
                if len(INTblock) > 2:
                    pmagplotlib.plot_mag(
                        FIG['demag'], INTblock, title, 0, units, norm)
            if plot == 1:
                files = {}
                for key in FIG.keys():
                    files[key] = title+'_'+LT+'.'+fmt
                pmagplotlib.save_plots(FIG, files)
                sys.exit()
            else:
                pmagplotlib.draw_figs(FIG)
                ans = input(
                    " S[a]ve to save plot, [q]uit,  Return to continue:  ")
                if ans == 'q':
                    sys.exit()
                if ans == "a":
                    files = {}
                    for key in FIG.keys():
                        files[key] = title+'_'+LT+'.'+fmt
                    pmagplotlib.save_plots(FIG, files)
            pmagplotlib.clearFIG(FIG['demag'])
Ejemplo n.º 10
0
def main():
    """
    NAME
       histplot.py

    DESCRIPTION
       makes histograms for data

    OPTIONS
       -h prints help message and quits
       -f input file name
       -b binsize
       -fmt [svg,png,pdf,eps,jpg] specify format for image, default is svg
       -sav save figure and quit
       -F output file name, default is hist.fmt
       -N don't normalize
       -xlab Label of X axis
       -ylab Label of Y axis

    INPUT FORMAT
        single variable

    SYNTAX
       histplot.py [command line options] [<file]

    """
    fname, fmt = "", 'svg'
    plot = 0
    if '-sav' in sys.argv:
        plot = 1
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        fname = sys.argv[ind + 1]
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        outfile = sys.argv[ind + 1]
        fmt = ""
    else:
        outfile = 'hist.' + fmt
    print(outfile)
    if '-N' in sys.argv:
        norm = 0
        ylab = 'Number'
    else:
        norm = 1
        ylab = 'Frequency'
    if '-b' in sys.argv:
        ind = sys.argv.index('-b')
        binsize = int(sys.argv[ind + 1])
    else:
        binsize = 5
    if '-xlab' in sys.argv:
        ind = sys.argv.index('-xlab')
        xlab = sys.argv[ind + 1]
    else:
        xlab = 'x'
    if fname != "":
        D = numpy.loadtxt(fname)
    else:
        print('-I- Trying to read from stdin... <ctrl>-c to quit')
        D = numpy.loadtxt(sys.stdin, dtype=numpy.float)
    # read in data
    #
    try:
        if not D:
            print('-W- No data found')
            return
    except ValueError:
        pass
    pmagplotlib.plot_init(1, 8, 7)
    Nbins = old_div(len(D), binsize)
    # n,bins,patches=plt.hist(D,bins=Nbins,facecolor='white',histtype='step',color='black',normed=norm)
    n, bins, patches = plt.hist(D,
                                bins=Nbins,
                                facecolor='white',
                                histtype='step',
                                color='black',
                                density=norm)
    plt.axis([D.min(), D.max(), 0, n.max() + .1 * n.max()])
    plt.xlabel(xlab)
    plt.ylabel(ylab)
    name = 'N = ' + str(len(D))
    plt.title(name)
    if plot == 0:
        # plt.draw()
        # plt.show()
        pmagplotlib.draw_figs({1: 'hist'})
        p = input('s[a]ve to save plot, [q]uit to exit without saving  ')
        if p != 'a':
            sys.exit()
    plt.savefig(outfile)
    print('plot saved in ', outfile)
Ejemplo n.º 11
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)
Ejemplo n.º 12
0
def main():
    """
    NAME
        plot_magmap.py

    DESCRIPTION
        makes a color contour map of desired field model

    SYNTAX
        plot_magmap.py [command line options]

    OPTIONS
        -h prints help and quits
        -f FILE  specify field model file with format:  l m g h
        -fmt [pdf,eps,svg,png]  specify format for output figure  (default is png)
        -mod [arch3k,cals3k,pfm9k,hfm10k,cals10k.2,shadif14k,cals10k.1b] specify model for 3ka to 1900 CE, default is  cals10k
        -alt ALT;  specify altitude in km, default is sealevel (0)
        -age specify date in decimal year, default is 2016
        -lon0: 0 longitude for map, default is 0
        -el: [D,I,B,Br]  specify element for plotting
        -cm: [see https://matplotlib.org/users/colormaps.html] specify color map for plotting (default is RdYlBu)

    """
    cmap = 'RdYlBu'
    date = 2016.
    if not Basemap:
        print("-W- You must intstall the Basemap module to run plot_magmap.py")
        sys.exit()
    dir_path = '.'
    lincr = 1  # level increment for contours
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path = sys.argv[ind + 1]
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
        if fmt == 'jpg':
            print('jpg not a supported option')
            print(main.__doc__)
            sys.exit()
    else:
        fmt = 'png'
    if '-cm' in sys.argv:
        ind = sys.argv.index('-cm')
        cmap = sys.argv[ind + 1]
    if '-el' in sys.argv:
        ind = sys.argv.index('-el')
        el = sys.argv[ind + 1]
    else:
        el = 'B'
    if '-alt' in sys.argv:
        ind = sys.argv.index('-alt')
        alt = sys.argv[ind + 1]
    else:
        alt = 0
    if '-lon0' in sys.argv:
        ind = sys.argv.index('-lon0')
        lon_0 = float(sys.argv[ind + 1])
    else:
        lon_0 = 0
    if '-mod' in sys.argv:
        ind = sys.argv.index('-mod')
        mod = sys.argv[ind + 1]
        ghfile = ''
    elif '-f' in sys.argv:
        ind = sys.argv.index('-f')
        ghfile = sys.argv[ind + 1]
        mod = 'custom'
        date = ''
    else:
        mod, ghfile = 'cals10k', ''
    if '-age' in sys.argv:
        ind = sys.argv.index('-age')
        date = float(sys.argv[ind + 1])
    if '-alt' in sys.argv:
        ind = sys.argv.index('-alt')
        alt = float(sys.argv[ind + 1])
    else:
        alt = 0
    save = pmag.get_flag_arg_from_sys("-sav")
    if mod == 'custom':
        d = 'Custom'
    else:
        d = str(date)
    Ds, Is, Bs, Brs, lons, lats = pmag.do_mag_map(date,
                                                  mod=mod,
                                                  lon_0=lon_0,
                                                  alt=alt,
                                                  file=ghfile)
    if el == 'D':
        element = Ds
    elif el == 'I':
        element = Is
    elif el == 'B':
        element = Bs
    elif el == 'Br':
        element = Brs
    elif el == 'I':
        element = Is
    else:
        print(main.__doc__)
        sys.exit()
    pmagplotlib.plot_mag_map(1, element, lons, lats, el, lon_0=0, date=date)
    if not save:
        pmagplotlib.draw_figs({'map': 1})
        res = pmagplotlib.save_or_quit()
        if res == 'a':
            figname = 'igrf' + d + '.' + fmt
            print("1 saved in ", figname)
            plt.savefig('igrf' + d + '.' + fmt)
        sys.exit()
    plt.savefig('igrf' + d + '.' + fmt)
    print('Figure saved as: ', 'igrf' + d + '.' + fmt)
Ejemplo n.º 13
0
def main():
    """
    NAME
        thellier_magic.py

    DESCRIPTION
        plots Thellier-Thellier, allowing interactive setting of bounds
        and customizing of selection criteria.  Saves and reads interpretations
        from a pmag_specimen formatted table, default: thellier_specimens.txt

    SYNTAX
        thellier_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set magic_measurements input file
        -fsp PRIOR, set pmag_specimen prior interpretations file
        -fan ANIS, set rmag_anisotropy file for doing the anisotropy corrections
        -fcr CRIT, set criteria file for grading.
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (default format)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds adn quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step for slope calculation
           END: ending step for slope calculation
        -z use only z component difference for pTRM calculation

    DEFAULTS
        MEAS: magic_measurements.txt
        REDO: thellier_redo
        CRIT: NONE
        PRIOR: NONE

    OUTPUT
        figures:
            ALL:  numbers refer to temperature steps in command line window
            1) Arai plot:  closed circles are zero-field first/infield
                           open circles are infield first/zero-field
                           triangles are pTRM checks
                           squares are pTRM tail checks
                           VDS is vector difference sum
                           diamonds are bounds for interpretation
            2) Zijderveld plot:  closed (open) symbols are X-Y (X-Z) planes
                                 X rotated to NRM direction
            3) (De/Re)Magnetization diagram:
                           circles are NRM remaining
                           squares are pTRM gained
            4) equal area projections:
               green triangles are pTRM gained direction
                           red (purple) circles are lower(upper) hemisphere of ZI step directions
                           blue (cyan) squares are lower(upper) hemisphere IZ step directions
            5) Optional:  TRM acquisition
            6) Optional: TDS normalization
        command line window:
            list is: temperature step numbers, temperatures (C), Dec, Inc, Int (units of magic_measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates .svg format files with specimen_name, plot type as name
    """
    #
    #   initializations
    #
    meas_file, critout, inspec = "magic_measurements.txt", "", "thellier_specimens.txt"
    first = 1
    inlt = 0
    version_num = pmag.get_version()
    TDinit, Tinit, field, first_save = 0, 0, -1, 1
    user, comment, AniSpec, locname = "", '', "", ""
    ans, specimen, recnum, start, end = 0, 0, 0, 0, 0
    plots, pmag_out, samp_file, style = 0, "", "", "svg"
    verbose = pmagplotlib.verbose
    fmt = '.' + style
    #
    # default acceptance criteria
    #
    accept = pmag.default_criteria(0)[0]  # set the default criteria
    #
    # parse command line options
    #
    Zdiff, anis = 0, 0
    spc, BEG, END = "", "", ""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        meas_file = sys.argv[ind + 1]
    if '-fsp' in sys.argv:
        ind = sys.argv.index('-fsp')
        inspec = sys.argv[ind + 1]
    if '-fan' in sys.argv:
        ind = sys.argv.index('-fan')
        anisfile = sys.argv[ind + 1]
        anis = 1
        anis_data, file_type = pmag.magic_read(anisfile)
        if verbose:
            print("Anisotropy data read in from ", anisfile)
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = '.' + sys.argv[ind + 1]
    if '-dpi' in sys.argv:
        ind = sys.argv.index('-dpi')
        dpi = '.' + sys.argv[ind + 1]
    else:
        dpi = 100
    if '-sav' in sys.argv:
        plots = 1
        verbose = 0
    if '-z' in sys.argv:
        Zdiff = 1
    if '-spc' in sys.argv:
        ind = sys.argv.index('-spc')
        spc = sys.argv[ind + 1]
        if '-b' in sys.argv:
            ind = sys.argv.index('-b')
            BEG = int(sys.argv[ind + 1])
            END = int(sys.argv[ind + 2])
    if '-fcr' in sys.argv:
        ind = sys.argv.index('-fcr')
        critout = sys.argv[ind + 1]
        crit_data, file_type = pmag.magic_read(critout)
        if file_type != 'pmag_criteria':
            if verbose:
                print('bad pmag_criteria file, using no acceptance criteria')
            accept = pmag.default_criteria(1)[0]
        else:
            if verbose:
                print("Acceptance criteria read in from ", critout)
            accept = {
                'pmag_criteria_code': 'ACCEPTANCE',
                'er_citation_names': 'This study'
            }
            for critrec in crit_data:
                if 'sample_int_sigma_uT' in critrec.keys(
                ):  # accommodate Shaar's new criterion
                    critrec['sample_int_sigma'] = '%10.3e' % (
                        eval(critrec['sample_int_sigma_uT']) * 1e-6)
                for key in critrec.keys():
                    if key not in accept.keys() and critrec[key] != '':
                        accept[key] = critrec[key]
    try:
        open(inspec, 'rU')
        PriorRecs, file_type = pmag.magic_read(inspec)
        if file_type != 'pmag_specimens':
            print(file_type)
            print(file_type, inspec, " is not a valid pmag_specimens file ")
            sys.exit()
        for rec in PriorRecs:
            if 'magic_software_packages' not in rec.keys():
                rec['magic_software_packages'] = ""
    except IOError:
        PriorRecs = []
        if verbose:
            print("starting new specimen interpretation file: ", inspec)
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(file_type)
        print(file_type, "This is not a valid magic_measurements file ")
        sys.exit()
    backup = 0
    # define figure numbers for arai, zijderveld and
    #   de-,re-magization diagrams
    AZD = {}
    AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4
    pmagplotlib.plot_init(AZD['arai'], 5, 5)
    pmagplotlib.plot_init(AZD['zijd'], 5, 5)
    pmagplotlib.plot_init(AZD['deremag'], 5, 5)
    pmagplotlib.plot_init(AZD['eqarea'], 5, 5)
    #
    #
    #
    # get list of unique specimen names
    #
    CurrRec = []
    sids = pmag.get_specs(meas_data)
    # get plots for specimen s - default is just to step through arai diagrams
    #
    if spc != "":
        specimen = sids.index(spc)
    while specimen < len(sids):
        methcodes = []

        if verbose:
            print(sids[specimen], specimen + 1, 'of ', len(sids))
        MeasRecs = []
        s = sids[specimen]
        datablock, trmblock, tdsrecs = [], [], []
        PmagSpecRec = {}
        if first == 0:
            for key in keys:
                # make sure all new records have same set of keys
                PmagSpecRec[key] = ""
        PmagSpecRec["er_analyst_mail_names"] = user
        PmagSpecRec["specimen_correction"] = 'u'
        #
        # find the data from the meas_data file for this specimen
        #
        for rec in meas_data:
            if rec["er_specimen_name"] == s:
                MeasRecs.append(rec)
                if "magic_method_codes" not in rec.keys():
                    rec["magic_method_codes"] = ""
                methods = rec["magic_method_codes"].split(":")
                meths = []
                for meth in methods:
                    meths.append(meth.strip())  # take off annoying spaces
                methods = ""
                for meth in meths:
                    if meth.strip() not in methcodes and "LP-" in meth:
                        methcodes.append(meth.strip())
                    methods = methods + meth + ":"
                methods = methods[:-1]
                rec["magic_method_codes"] = methods
                if "LP-PI-TRM" in meths:
                    datablock.append(rec)
                if "LP-TRM" in meths:
                    trmblock.append(rec)
                if "LP-TRM-TD" in meths:
                    tdsrecs.append(rec)
        if len(trmblock) > 2 and inspec != "":
            if Tinit == 0:
                Tinit = 1
                AZD['TRM'] = 5
                pmagplotlib.plot_init(AZD['TRM'], 5, 5)
        elif Tinit == 1:  # clear the TRM figure if not needed
            pmagplotlib.clearFIG(AZD['TRM'])
        if len(tdsrecs) > 2:
            if TDinit == 0:
                TDinit = 1
                AZD['TDS'] = 6
                pmagplotlib.plot_init(AZD['TDS'], 5, 5)
        elif TDinit == 1:  # clear the TDS figure if not needed
            pmagplotlib.clearFIG(AZD['TDS'])
        if len(datablock) < 4:
            if backup == 0:
                specimen += 1
                if verbose:
                    print('skipping specimen - moving forward ', s)
            else:
                specimen -= 1
                if verbose:
                    print('skipping specimen - moving backward ', s)
    #
    #  collect info for the PmagSpecRec dictionary
    #
        else:
            rec = datablock[0]
            PmagSpecRec["er_citation_names"] = "This study"
            PmagSpecRec["er_specimen_name"] = s
            PmagSpecRec["er_sample_name"] = rec["er_sample_name"]
            PmagSpecRec["er_site_name"] = rec["er_site_name"]
            PmagSpecRec["er_location_name"] = rec["er_location_name"]
            locname = rec['er_location_name'].replace('/', '-')
            if "er_expedition_name" in rec.keys():
                PmagSpecRec["er_expedition_name"] = rec["er_expedition_name"]
            if "magic_instrument_codes" not in rec.keys():
                rec["magic_instrument_codes"] = ""
            PmagSpecRec["magic_instrument_codes"] = rec[
                "magic_instrument_codes"]
            PmagSpecRec["measurement_step_unit"] = "K"
            if "magic_experiment_name" not in rec.keys():
                rec["magic_experiment_name"] = ""
            else:
                PmagSpecRec["magic_experiment_names"] = rec[
                    "magic_experiment_name"]

            meths = rec["magic_method_codes"].split()
            # sort data into types
            araiblock, field = pmag.sortarai(datablock, s, Zdiff)
            first_Z = araiblock[0]
            GammaChecks = araiblock[5]
            if len(first_Z) < 3:
                if backup == 0:
                    specimen += 1
                    if verbose:
                        print('skipping specimen - moving forward ', s)
                else:
                    specimen -= 1
                    if verbose:
                        print('skipping specimen - moving backward ', s)
            else:
                backup = 0
                zijdblock, units = pmag.find_dmag_rec(s, meas_data)
                recnum = 0
                if verbose:
                    print("index step Dec   Inc  Int       Gamma")
                    for plotrec in zijdblock:
                        if GammaChecks != "":
                            gamma = ""
                            for g in GammaChecks:
                                if g[0] == plotrec[0] - 273:
                                    gamma = g[1]
                                    break
                        if gamma != "":
                            print('%i     %i %7.1f %7.1f %8.3e %7.1f' %
                                  (recnum, plotrec[0] - 273, plotrec[1],
                                   plotrec[2], plotrec[3], gamma))
                        else:
                            print('%i     %i %7.1f %7.1f %8.3e ' %
                                  (recnum, plotrec[0] - 273, plotrec[1],
                                   plotrec[2], plotrec[3]))
                        recnum += 1
                pmagplotlib.plot_arai_zij(AZD, araiblock, zijdblock, s,
                                          units[0])
                if verbose:
                    pmagplotlib.draw_figs(AZD)
                if len(tdsrecs) > 2:  # a TDS experiment
                    tdsblock = []  # make a list for the TDS  data
                    Mkeys = [
                        'measurement_magnitude', 'measurement_magn_moment',
                        'measurement_magn_volume', 'measuruement_magn_mass'
                    ]
                    mkey, k = "", 0
                    # find which type of intensity
                    while mkey == "" and k < len(Mkeys) - 1:
                        key = Mkeys[k]
                        if key in tdsrecs[0].keys() and tdsrecs[0][key] != "":
                            mkey = key
                        k += 1
                    if mkey == "":
                        break  # get outta here
                    Tnorm = ""
                    for tdrec in tdsrecs:
                        meths = tdrec['magic_method_codes'].split(":")
                        for meth in meths:
                            # strip off potential nasty spaces
                            meth.replace(" ", "")
                        if 'LT-T-I' in meths and Tnorm == "":  # found first total TRM
                            # normalize by total TRM
                            Tnorm = float(tdrec[mkey])
                            # put in the zero step
                            tdsblock.append([273, zijdblock[0][3] / Tnorm, 1.])
                        # found a LP-TRM-TD demag step, now need complementary LT-T-Z from zijdblock
                        if 'LT-T-Z' in meths and Tnorm != "":
                            step = float(tdrec['treatment_temp'])
                            Tint = ""
                            if mkey != "":
                                Tint = float(tdrec[mkey])
                            if Tint != "":
                                for zrec in zijdblock:
                                    if zrec[0] == step:  # found matching
                                        tdsblock.append([
                                            step, zrec[3] / Tnorm, Tint / Tnorm
                                        ])
                                        break
                    if len(tdsblock) > 2:
                        pmagplotlib.plot_tds(AZD['TDS'], tdsblock,
                                             s + ':LP-PI-TDS:')
                        if verbose:
                            pmagplotlib(draw_figs(AZD))
                    else:
                        print("Something wrong here")
                if anis == 1:  # look up anisotropy data for this specimen
                    AniSpec = ""
                    for aspec in anis_data:
                        if aspec["er_specimen_name"] == PmagSpecRec[
                                "er_specimen_name"]:
                            AniSpec = aspec
                            if verbose:
                                print('Found anisotropy record...')
                            break
                if inspec != "":
                    if verbose:
                        print('Looking up saved interpretation....')
                    found = 0
                    for k in range(len(PriorRecs)):
                        try:
                            if PriorRecs[k]["er_specimen_name"] == s:
                                found = 1
                                CurrRec.append(PriorRecs[k])
                                for j in range(len(zijdblock)):
                                    if float(zijdblock[j][0]) == float(
                                            PriorRecs[k]
                                        ["measurement_step_min"]):
                                        start = j
                                    if float(zijdblock[j][0]) == float(
                                            PriorRecs[k]
                                        ["measurement_step_max"]):
                                        end = j
                                pars, errcode = pmag.PintPars(
                                    datablock, araiblock, zijdblock, start,
                                    end, accept)
                                pars['measurement_step_unit'] = "K"
                                pars['experiment_type'] = 'LP-PI-TRM'
                                # put in CurrRec, take out of PriorRecs
                                del PriorRecs[k]
                                if errcode != 1:
                                    pars["specimen_lab_field_dc"] = field
                                    pars["specimen_int"] = -1 * \
                                        field*pars["specimen_b"]
                                    pars["er_specimen_name"] = s
                                    if verbose:
                                        print('Saved interpretation: ')
                                    pars, kill = pmag.scoreit(
                                        pars, PmagSpecRec, accept, '', verbose)
                                    pmagplotlib.plot_b(AZD, araiblock,
                                                       zijdblock, pars)
                                    if verbose:
                                        pmagplotlib.draw_figs(AZD)
                                    if len(trmblock) > 2:
                                        blab = field
                                        best = pars["specimen_int"]
                                        Bs, TRMs = [], []
                                        for trec in trmblock:
                                            Bs.append(
                                                float(
                                                    trec['treatment_dc_field'])
                                            )
                                            TRMs.append(
                                                float(trec[
                                                    'measurement_magn_moment'])
                                            )
                                        # calculate best fit parameters through TRM acquisition data, and get new banc
                                        NLpars = nlt.NLtrm(
                                            Bs, TRMs, best, blab, 0)
                                        Mp, Bp = [], []
                                        for k in range(int(max(Bs) * 1e6)):
                                            Bp.append(float(k) * 1e-6)
                                            # predicted NRM for this field
                                            npred = nlt.TRM(
                                                Bp[-1], NLpars['xopt'][0],
                                                NLpars['xopt'][1])
                                            Mp.append(npred)
                                        pmagplotlib.plot_trm(
                                            AZD['TRM'], Bs, TRMs, Bp, Mp,
                                            NLpars,
                                            trec['magic_experiment_name'])
                                        PmagSpecRec['specimen_int'] = NLpars[
                                            'banc']
                                        if verbose:
                                            print('Banc= ',
                                                  float(NLpars['banc']) * 1e6)
                                            pmagplotlib.draw_figs(AZD)
                                    mpars = pmag.domean(
                                        araiblock[1], start, end, 'DE-BFL')
                                    if verbose:
                                        print(
                                            'pTRM direction= ',
                                            '%7.1f' % (mpars['specimen_dec']),
                                            ' %7.1f' % (mpars['specimen_inc']),
                                            ' MAD:',
                                            '%7.1f' % (mpars['specimen_mad']))
                                    if AniSpec != "":
                                        CpTRM = pmag.Dir_anis_corr([
                                            mpars['specimen_dec'],
                                            mpars['specimen_inc']
                                        ], AniSpec)
                                        AniSpecRec = pmag.doaniscorr(
                                            PmagSpecRec, AniSpec)
                                        if verbose:
                                            print(
                                                'Anisotropy corrected TRM direction= ',
                                                '%7.1f' % (CpTRM[0]),
                                                ' %7.1f' % (CpTRM[1]))
                                            print(
                                                'Anisotropy corrected intensity= ',
                                                float(
                                                    AniSpecRec['specimen_int'])
                                                * 1e6)
                                else:
                                    print('error on specimen ', s)
                        except:
                            pass
                    if verbose and found == 0:
                        print('    None found :(  ')
                if spc != "":
                    if BEG != "":
                        pars, errcode = pmag.PintPars(datablock, araiblock,
                                                      zijdblock, BEG, END,
                                                      accept)
                        pars['measurement_step_unit'] = "K"
                        pars["specimen_lab_field_dc"] = field
                        pars["specimen_int"] = -1 * field * pars["specimen_b"]
                        pars["er_specimen_name"] = s
                        pars['specimen_grade'] = ''  # ungraded
                        pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                        if verbose:
                            pmagplotlib.draw_figs(AZD)
                        if len(trmblock) > 2:
                            if inlt == 0:
                                inlt = 1
                            blab = field
                            best = pars["specimen_int"]
                            Bs, TRMs = [], []
                            for trec in trmblock:
                                Bs.append(float(trec['treatment_dc_field']))
                                TRMs.append(
                                    float(trec['measurement_magn_moment']))
                            # calculate best fit parameters through TRM acquisition data, and get new banc
                            NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0)
                            #
                            Mp, Bp = [], []
                            for k in range(int(max(Bs) * 1e6)):
                                Bp.append(float(k) * 1e-6)
                                # predicted NRM for this field
                                npred = nlt.TRM(Bp[-1], NLpars['xopt'][0],
                                                NLpars['xopt'][1])
                    files = {}
                    for key in AZD.keys():
                        files[key] = s + '_' + key + fmt
                    pmagplotlib.save_plots(AZD, files, dpi=dpi)
                    sys.exit()
                if verbose:
                    ans = 'b'
                    while ans != "":
                        print("""
               s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit:
               """)
                        ans = input('Return for next specimen \n')
                        if ans == "":
                            specimen += 1
                        if ans == "d":
                            save_redo(PriorRecs, inspec)
                            CurrRec = []
                            pmagplotlib.plot_arai_zij(AZD, araiblock,
                                                      zijdblock, s, units[0])
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                        if ans == 'a':
                            files = {}
                            for key in AZD.keys():
                                files[key] = "LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name'] + \
                                    '_SA:_' + \
                                    PmagSpecRec['er_sample_name'] + \
                                    '_SP:_'+s+'_CO:_s_TY:_'+key+fmt
                            pmagplotlib.save_plots(AZD, files)
                            ans = ""
                        if ans == 'q':
                            print("Good bye")
                            sys.exit()
                        if ans == 'p':
                            specimen = specimen - 1
                            backup = 1
                            ans = ""
                        if ans == 's':
                            keepon = 1
                            spec = input(
                                'Enter desired specimen name (or first part there of): '
                            )
                            while keepon == 1:
                                try:
                                    specimen = sids.index(spec)
                                    keepon = 0
                                except:
                                    tmplist = []
                                    for qq in range(len(sids)):
                                        if spec in sids[qq]:
                                            tmplist.append(sids[qq])
                                    print(specimen,
                                          " not found, but this was: ")
                                    print(tmplist)
                                    spec = input('Select one or try again\n ')
                            ans = ""
                        if ans == 'b':
                            if end == 0 or end >= len(zijdblock):
                                end = len(zijdblock) - 1
                            GoOn = 0
                            while GoOn == 0:
                                answer = input(
                                    'Enter index of first point for calculation: ['
                                    + str(start) + ']  ')
                                try:
                                    start = int(answer)
                                    answer = input(
                                        'Enter index  of last point for calculation: ['
                                        + str(end) + ']  ')
                                    end = int(answer)
                                    if start >= 0 and start < len(
                                            zijdblock
                                    ) - 2 and end > 0 and end < len(
                                            zijdblock) or start >= end:
                                        GoOn = 1
                                    else:
                                        print("Bad endpoints - try again! ")
                                        start, end = 0, len(zijdblock)
                                except ValueError:
                                    print("Bad endpoints - try again! ")
                                    start, end = 0, len(zijdblock)
                            s = sids[specimen]
                            pars, errcode = pmag.PintPars(
                                datablock, araiblock, zijdblock, start, end,
                                accept)
                            pars['measurement_step_unit'] = "K"
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1 * field * pars[
                                "specimen_b"]
                            pars["er_specimen_name"] = s
                            pars, kill = pmag.scoreit(pars, PmagSpecRec,
                                                      accept, '', 0)
                            PmagSpecRec['specimen_scat'] = pars[
                                'specimen_scat']
                            PmagSpecRec['specimen_frac'] = '%5.3f' % (
                                pars['specimen_frac'])
                            PmagSpecRec['specimen_gmax'] = '%5.3f' % (
                                pars['specimen_gmax'])
                            PmagSpecRec["measurement_step_min"] = '%8.3e' % (
                                pars["measurement_step_min"])
                            PmagSpecRec["measurement_step_max"] = '%8.3e' % (
                                pars["measurement_step_max"])
                            PmagSpecRec["measurement_step_unit"] = "K"
                            PmagSpecRec["specimen_int_n"] = '%i' % (
                                pars["specimen_int_n"])
                            PmagSpecRec["specimen_lab_field_dc"] = '%8.3e' % (
                                pars["specimen_lab_field_dc"])
                            PmagSpecRec["specimen_int"] = '%9.4e ' % (
                                pars["specimen_int"])
                            PmagSpecRec["specimen_b"] = '%5.3f ' % (
                                pars["specimen_b"])
                            PmagSpecRec["specimen_q"] = '%5.1f ' % (
                                pars["specimen_q"])
                            PmagSpecRec["specimen_f"] = '%5.3f ' % (
                                pars["specimen_f"])
                            PmagSpecRec["specimen_fvds"] = '%5.3f' % (
                                pars["specimen_fvds"])
                            PmagSpecRec["specimen_b_beta"] = '%5.3f' % (
                                pars["specimen_b_beta"])
                            PmagSpecRec["specimen_int_mad"] = '%7.1f' % (
                                pars["specimen_int_mad"])
                            PmagSpecRec["specimen_Z"] = '%7.1f' % (
                                pars["specimen_Z"])
                            PmagSpecRec["specimen_gamma"] = '%7.1f' % (
                                pars["specimen_gamma"])
                            PmagSpecRec["specimen_grade"] = pars[
                                "specimen_grade"]
                            if pars["method_codes"] != "":
                                tmpcodes = pars["method_codes"].split(":")
                                for t in tmpcodes:
                                    if t.strip() not in methcodes:
                                        methcodes.append(t.strip())
                            PmagSpecRec["specimen_dec"] = '%7.1f' % (
                                pars["specimen_dec"])
                            PmagSpecRec["specimen_inc"] = '%7.1f' % (
                                pars["specimen_inc"])
                            PmagSpecRec["specimen_tilt_correction"] = '-1'
                            PmagSpecRec["specimen_direction_type"] = 'l'
                            # this is redundant, but helpful - won't be imported
                            PmagSpecRec["direction_type"] = 'l'
                            PmagSpecRec["specimen_int_dang"] = '%7.1f ' % (
                                pars["specimen_int_dang"])
                            PmagSpecRec["specimen_drats"] = '%7.1f ' % (
                                pars["specimen_drats"])
                            PmagSpecRec["specimen_drat"] = '%7.1f ' % (
                                pars["specimen_drat"])
                            PmagSpecRec["specimen_int_ptrm_n"] = '%i ' % (
                                pars["specimen_int_ptrm_n"])
                            PmagSpecRec["specimen_rsc"] = '%6.4f ' % (
                                pars["specimen_rsc"])
                            PmagSpecRec["specimen_md"] = '%i ' % (int(
                                pars["specimen_md"]))
                            if PmagSpecRec["specimen_md"] == '-1':
                                PmagSpecRec["specimen_md"] = ""
                            PmagSpecRec["specimen_b_sigma"] = '%5.3f ' % (
                                pars["specimen_b_sigma"])
                            if "IE-TT" not in methcodes:
                                methcodes.append("IE-TT")
                            methods = ""
                            for meth in methcodes:
                                methods = methods + meth + ":"
                            PmagSpecRec["magic_method_codes"] = methods[:-1]
                            PmagSpecRec["specimen_description"] = comment
                            PmagSpecRec[
                                "magic_software_packages"] = version_num
                            pmagplotlib.plot_arai_zij(AZD, araiblock,
                                                      zijdblock, s, units[0])
                            pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                            if len(trmblock) > 2:
                                blab = field
                                best = pars["specimen_int"]
                                Bs, TRMs = [], []
                                for trec in trmblock:
                                    Bs.append(float(
                                        trec['treatment_dc_field']))
                                    TRMs.append(
                                        float(trec['measurement_magn_moment']))
                                # calculate best fit parameters through TRM acquisition data, and get new banc
                                NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0)
                                Mp, Bp = [], []
                                for k in range(int(max(Bs) * 1e6)):
                                    Bp.append(float(k) * 1e-6)
                                    # predicted NRM for this field
                                    npred = nlt.TRM(Bp[-1], NLpars['xopt'][0],
                                                    NLpars['xopt'][1])
                                    Mp.append(npred)
                                pmagplotlib.plot_trm(
                                    AZD['TRM'], Bs, TRMs, Bp, Mp, NLpars,
                                    trec['magic_experiment_name'])
                                if verbose:
                                    print(
                                        'Non-linear TRM corrected intensity= ',
                                        float(NLpars['banc']) * 1e6)
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1 * field * pars[
                                "specimen_b"]
                            pars, kill = pmag.scoreit(pars, PmagSpecRec,
                                                      accept, '', verbose)
                            saveit = input(
                                "Save this interpretation? [y]/n \n")
                            if saveit != 'n':
                                # put back an interpretation
                                PriorRecs.append(PmagSpecRec)
                                specimen += 1
                                save_redo(PriorRecs, inspec)
                            ans = ""
                elif plots == 1:
                    specimen += 1
                    if fmt != ".pmag":
                        files = {}
                        for key in AZD.keys():
                            files[key] = "LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name']+'_SA:_' + \
                                PmagSpecRec['er_sample_name'] + \
                                '_SP:_'+s+'_CO:_s_TY:_'+key+'_'+fmt
                        if pmagplotlib.isServer:
                            black = '#000000'
                            purple = '#800080'
                            titles = {}
                            titles['deremag'] = 'DeReMag Plot'
                            titles['zijd'] = 'Zijderveld Plot'
                            titles['arai'] = 'Arai Plot'
                            AZD = pmagplotlib.add_borders(
                                AZD, titles, black, purple)
                        pmagplotlib.save_plots(AZD, files, dpi=dpi)
    #                   pmagplotlib.combineFigs(s,files,3)
                    else:  # save in pmag format
                        script = "grep " + s + " output.mag | thellier -mfsi"
                        script = script + ' %8.4e' % (field)
                        min = '%i' % ((pars["measurement_step_min"] - 273))
                        Max = '%i' % ((pars["measurement_step_max"] - 273))
                        script = script + " " + min + " " + Max
                        script = script + " |plotxy;cat mypost >>thellier.ps\n"
                        pltf.write(script)
                        pmag.domagicmag(outf, MeasRecs)
        if len(CurrRec) > 0:
            for rec in CurrRec:
                PriorRecs.append(rec)
        CurrRec = []
    if plots != 1 and verbose:
        ans = input(" Save last plot? 1/[0] ")
        if ans == "1":
            if fmt != ".pmag":
                files = {}
                for key in AZD.keys():
                    files[key] = s + '_' + key + fmt
                pmagplotlib.save_plots(AZD, files, dpi=dpi)
        else:
            print("\n Good bye\n")
            sys.exit()
        if len(CurrRec) > 0:
            PriorRecs.append(CurrRec)  # put back an interpretation
        if len(PriorRecs) > 0:
            save_redo(PriorRecs, inspec)
            print('Updated interpretations saved in ', inspec)
    if verbose:
        print("Good bye")
Ejemplo n.º 14
0
def main():
    """
    NAME
        chi_magic.py

    DESCRIPTION
        plots magnetic susceptibility as a function of frequency and temperature and AC field

    SYNTAX
        chi_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -i allows interactive setting of FILE and temperature step
        -f FILE, specify magic_measurements format file
        -T IND, specify temperature step to plot
        -e EXP, specify experiment name to plot
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
        -sav save figure and quit

    DEFAULTS
         FILE: magic_measurements.txt
         IND: first
         SPEC: step through one by one
    """
    cont, FTinit, BTinit, k = "", 0, 0, 0
    meas_file = "magic_measurements.txt"
    spec = ""
    Tind, cont = 0, ""
    EXP = ""
    fmt = 'svg'  # default image type for saving
    plot = 0
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-i' in sys.argv:
        fname = input(
            "Input magic_measurements file name? [magic_measurements.txt]  ")
        if fname != "":
            meas_file = fname
    if '-e' in sys.argv:
        ind = sys.argv.index('-e')
        EXP = sys.argv[ind+1]
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        meas_file = sys.argv[ind+1]
    if '-T' in sys.argv:
        ind = sys.argv.index('-T')
        Tind = 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
    #
    meas_data, file_type = pmag.magic_read(meas_file)
    #
    # get list of unique experiment names
    #
    # initialize some variables (a continuation flag, plot initialization flags and the experiment counter
    experiment_names = []
    for rec in meas_data:
        if rec['magic_experiment_name'] not in experiment_names:
            experiment_names.append(rec['magic_experiment_name'])
    #
    # hunt through by experiment name
    if EXP != "":
        try:
            k = experiment_names.index(EXP)
        except:
            print("Bad experiment name")
            sys.exit()
    while k < len(experiment_names):
        e = experiment_names[k]
        if EXP == "":
            print(e, k+1, 'out of ', len(experiment_names))
    #
    #  initialize lists of data, susceptibility, temperature, frequency and field
        X, T, F, B = [], [], [], []
        for rec in meas_data:
            methcodes = rec['magic_method_codes']
            meths = methcodes.strip().split(':')
            if rec['magic_experiment_name'] == e and "LP-X" in meths:  # looking for chi measurement
                if 'measurement_temp' not in list(rec.keys()):
                    rec['measurement_temp'] = '300'  # set defaults
                if 'measurement_freq' not in list(rec.keys()):
                    rec['measurement_freq'] = '0'  # set defaults
                if 'measurement_lab_field_ac' not in list(rec.keys()):
                    rec['measurement_lab_field_ac'] = '0'  # set default
                if 'measurement_x' in rec.keys():
                    # backward compatibility
                    X.append(float(rec['measurement_x']))
                else:
                    # data model 2.5
                    X.append(float(rec['measurement_chi_volume']))
                T.append(float(rec['measurement_temp']))
                F.append(float(rec['measurement_freq']))
                B.append(float(rec['measurement_lab_field_ac']))
    #
    # get unique list of Ts,Fs, and Bs
    #
        Ts, Fs, Bs = [], [], []
        for k in range(len(X)):   # hunt through all the measurements
            if T[k] not in Ts:
                Ts.append(T[k])  # append if not in list
            if F[k] not in Fs:
                Fs.append(F[k])
            if B[k] not in Bs:
                Bs.append(B[k])
        Ts.sort()  # sort list of temperatures, frequencies and fields
        Fs.sort()
        Bs.sort()
        if '-x' in sys.argv:
            k = len(experiment_names)+1  # just plot the one
        else:
            k += 1  # increment experiment number
    #
    # plot chi versus T and F holding B constant
    #
        plotnum = 1  # initialize plot number to 1
        if len(X) > 2:  # if there are any data to plot, continue
            b = Bs[-1]  # keeping field constant and at maximum
            XTF = []  # initialize list of chi versus Temp and freq
            for f in Fs:   # step through frequencies sequentially
                XT = []  # initialize list of chi versus temp
                for kk in range(len(X)):  # hunt through all the data
                    if F[kk] == f and B[kk] == b:  # select data with given freq and field
                        XT.append([X[kk], T[kk]])  # append to list
                XTF.append(XT)  # append list to list of frequencies
            if len(XT) > 1:  # if there are any temperature dependent data
                pmagplotlib.plot_init(plotnum, 5, 5)  # initialize plot
                # call the plotting function
                pmagplotlib.plot_xtf(plotnum, XTF, Fs, e, b)
                if plot == 0:
                    pmagplotlib.draw_figs({'fig': plotnum})  # make it visible
                plotnum += 1  # increment plot number
            f = Fs[0]  # set frequency to minimum
            XTB = []  # initialize list if chi versus Temp and field
            for b in Bs:  # step through field values
                XT = []  # initial chi versus temp list for this field
                for kk in range(len(X)):  # hunt through all the data
                    if F[kk] == f and B[kk] == b:  # select data with given freq and field
                        XT.append([X[kk], T[kk]])  # append to list
                XTB.append(XT)
            if len(XT) > 1:  # if there are any temperature dependent data
                pmagplotlib.plot_init(plotnum, 5, 5)  # set up plot
                # call the plotting function
                pmagplotlib.plot_xtb(plotnum, XTB, Bs, e, f)
                if plot == 0:
                    pmagplotlib.draw_figs({'fig': plotnum})
                plotnum += 1  # increment plot number
            if '-i' in sys.argv:
                for ind in range(len(Ts)):  # print list of temperatures available
                    print(ind, int(Ts[ind]))
                cont = input(
                    "Enter index of desired temperature step, s[a]ve plots, [return] to quit ")
                if cont == 'a':
                    files = {}
                    PLTS = {}
                    for p in range(1, plotnum):
                        key = str(p)
                        files[key] = e+'_'+key+'.'+fmt
                        PLTS[key] = key
                    pmagplotlib.save_plots(PLTS, files)
                    cont = input(
                        "Enter index of desired temperature step, s[a]ve plots, [return] to quit ")
                if cont == "":
                    cont = 'q'
            while cont != "q":
                if '-i' in sys.argv:
                    Tind = int(cont)  # set temperature index
                b = Bs[-1]  # set field to max available
                XF = []  # initial chi versus frequency list
                for kk in range(len(X)):  # hunt through the data
                    if T[kk] == Ts[Tind] and B[kk] == b:  # if temperature and field match,
                        XF.append([X[kk], F[kk]])  # append the data
                if len(XF) > 1:  # if there are any data to plot
                    if FTinit == 0:  # if not already initialized, initialize plot
                        # print 'initializing ',plotnum
                        pmagplotlib.plot_init(plotnum, 5, 5)
                        FTinit = 1
                        XFplot = plotnum
                        plotnum += 1  # increment plotnum
                    pmagplotlib.plot_xft(XFplot, XF, Ts[Tind], e, b)
                    if plot == 0:
                        pmagplotlib.draw_figs({'fig': plotnum})
                else:
                    print(
                        '\n *** Skipping susceptibitily-frequency plot as a function of temperature *** \n')
                f = Fs[0]  # set frequency to minimum available
                XB = []  # initialize chi versus field list
                for kk in range(len(X)):  # hunt through the data
                    # if temperature and field match those desired
                    if T[kk] == Ts[Tind] and F[kk] == f:
                        XB.append([X[kk], B[kk]])  # append the data to list
                if len(XB) > 4:  # if there are any data
                    if BTinit == 0:  # if plot not already initialized
                        pmagplotlib.plot_init(plotnum, 5, 5)  # do it
                        BTinit = 1
                    # and call plotting function
                    pmagplotlib.plot_xbt(plotnum, XB, Ts[Tind], e, f)
                    if plot == 0:
                        pmagplotlib.draw_figs({'fig': plotnum})
                else:
                    print(
                        'Skipping susceptibitily - AC field plot as a function of temperature')
                files = {}
                PLTS = {}
                for p in range(1, plotnum):
                    key = str(p)
                    files[key] = e+'_'+key+'.'+fmt
                    PLTS[key] = p
                if '-i' in sys.argv:
                    # just in case you forgot, print out a new list of temperatures
                    for ind in range(len(Ts)):
                        print(ind, int(Ts[ind]))
                    # ask for new temp
                    cont = input(
                        "Enter index of next temperature step, s[a]ve plots,  [return] to quit ")
                    if cont == "":
                        sys.exit()
                    if cont == 'a':
                        pmagplotlib.save_plots(PLTS, files)
                        cont = input(
                            "Enter index of desired temperature step, s[a]ve plots, [return] to quit ")
                        if cont == "":
                            sys.exit()
                elif plot == 0:
                    ans = input(
                        "enter s[a]ve to save files,  [return] to quit ")
                    if ans == 'a':
                        pmagplotlib.save_plots(PLTS, files)
                        sys.exit()
                    else:
                        sys.exit()
                else:
                    pmagplotlib.save_plots(PLTS, files)
                    sys.exit()
Ejemplo n.º 15
0
def main():
    """
    NAME
        irmaq_magic.py

    DESCRIPTION
       plots IRM acquisition curves from measurements file

    SYNTAX
        irmaq_magic [command line options]

    INPUT
       takes magic formatted magic_measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt/measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot, default is by location
        -N ; do not normalize by last point - use original units
        -fmt [png,jpg,eps,pdf] set plot file format [default is svg]
        -sav save plot[s] and quit
        -DM MagIC data model number, default is 3
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    FIG = {}  # plot dictionary
    FIG['exp'] = 1  # exp is figure 1
    dir_path = './'
    plot, fmt = 0, 'svg'
    units = 'T',
    XLP = []
    norm = 1
    LP = "LP-IRM"
    if len(sys.argv) > 1:
        if '-h' in sys.argv:
            print(main.__doc__)
            sys.exit()
        data_model = int(pmag.get_named_arg("-DM", 3))
        if '-N' in sys.argv:
            norm = 0
        if '-sav' in sys.argv:
            plot = 1
        if '-fmt' in sys.argv:
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        if data_model == 3:
            in_file = pmag.get_named_arg("-f", 'measurements.txt')
        else:
            in_file = pmag.get_named_arg("-f", 'magic_measurements.txt')
        if '-WD' in sys.argv:
            ind = sys.argv.index('-WD')
            dir_path = sys.argv[ind + 1]
        dir_path = os.path.realpath(dir_path)
        in_file = pmag.resolve_file_name(in_file, dir_path)
        if '-WD' not in sys.argv:
            dir_path = os.path.split(in_file)[0]
        plot_by = pmag.get_named_arg("-obj", "loc")
        if data_model == 3:
            plot_key = 'location'
            if plot_by == 'sit':
                plot_key = 'site'
            if plot_by == 'sam':
                plot_key = 'sample'
            if plot_by == 'spc':
                plot_key = 'specimen'
        else:
            plot_key = 'er_location_name'
            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'

    # set defaults and get more information if needed
    if data_model == 3:
        dmag_key = 'treat_dc_field'
    else:
        dmag_key = 'treatment_dc_field'
    #
    if data_model == 3 and plot_key != 'specimen':
        # gonna need to read in more files
        print('-W- You are trying to plot measurements by {}'.format(plot_key))
        print(
            '    By default, this information is not available in your measurement file.'
        )
        print(
            '    Trying to acquire this information from {}'.format(dir_path))
        con = cb.Contribution(dir_path)
        meas_df = con.propagate_location_to_measurements()
        if meas_df is None:
            print('-W- No data found in {}'.format(dir_path))
            return
        if plot_key not in meas_df.columns:
            print('-W- Could not find required data.')
            print('    Try a different plot key.')
            return
        else:
            print('-I- Found {} information, continuing with plotting'.format(
                plot_key))
        # need to take the data directly from the contribution here, to keep
        # location/site/sample columns in the measurements table
        data = con.tables['measurements'].convert_to_pmag_data_list()
        file_type = "measurements"
    else:
        data, file_type = pmag.magic_read(in_file)
    # read in data
    sids = pmag.get_specs(data)
    pmagplotlib.plot_init(FIG['exp'], 6, 6)
    #
    #
    # find desired intensity data
    #
    # get plotlist
    #
    plotlist = []
    if data_model == 3:
        intlist = ['magn_moment', 'magn_volume', 'magn_mass', 'magnitude']
    else:
        intlist = [
            'measurement_magnitude', 'measurement_magn_moment',
            'measurement_magn_volume', 'measurement_magn_mass'
        ]
    IntMeths = []
    # get all the records with this lab protocol
    #print('data', len(data))
    #print('data[0]', data[0])
    if data_model == 3:
        data = pmag.get_dictitem(data, 'method_codes', LP, 'has')
    else:
        data = pmag.get_dictitem(data, 'magic_method_codes', LP, 'has')
    Ints = {}
    NoInts, int_key = 1, ""
    for key in intlist:
        # get all non-blank data for intensity type
        Ints[key] = pmag.get_dictitem(data, key, '', 'F')
        if len(Ints[key]) > 0:
            NoInts = 0
            if int_key == "":
                int_key = key
    if NoInts == 1:
        print('No intensity information found')
        sys.exit()
    for rec in Ints[int_key]:
        if rec[plot_key] not in plotlist:
            plotlist.append(rec[plot_key])
    plotlist.sort()
    for plt in plotlist:
        print(plt)
        INTblock = []
        # get data with right intensity info whose plot_key matches plot
        data = pmag.get_dictitem(Ints[int_key], plot_key, plt, 'T')
        # get a list of specimens with appropriate data
        sids = pmag.get_specs(data)
        if len(sids) > 0:
            title = data[0][plot_key]
        for s in sids:
            INTblock = []
            # get data for each specimen
            if data_model == 3:
                sdata = pmag.get_dictitem(data, 'specimen', s, 'T')
            else:
                sdata = pmag.get_dictitem(data, 'er_specimen_name', s, 'T')
            for rec in sdata:
                INTblock.append(
                    [float(rec[dmag_key]), 0, 0,
                     float(rec[int_key]), 1, 'g'])
            pmagplotlib.plot_mag(FIG['exp'], INTblock, title, 0, units, norm)
        files = {}
        for key in list(FIG.keys()):
            files[key] = title + '_' + LP + '.' + fmt
        if plot == 0:
            pmagplotlib.draw_figs(FIG)
            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)
            if plt != plotlist[
                    -1]:  # if it isn't the last plot, init the next one
                pmagplotlib.plot_init(FIG['exp'], 6, 6)
        else:
            pmagplotlib.save_plots(FIG, files)
        pmagplotlib.clearFIG(FIG['exp'])
Ejemplo n.º 16
0
def main():
    """
    NAME
        plot_geomagia.py

    DESCRIPTION
        makes a map  and VADM plot of geomagia download file 

    SYNTAX
        plot_geomagia.py  [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE, specify geomagia download file
        -res [c,l,i,h] specify resolution (crude,low,intermediate,high)
        -etp plot the etopo20 topographic mesh
        -pad [LAT LON]  pad bounding box by LAT/LON  (default is [.5 .5] degrees)
        -grd SPACE specify grid spacing
        -prj [lcc] , specify projection (lcc=lambert conic conformable), default is mercator
        -o color ocean blue/land green (default is not)
        -d plot details of rivers, boundaries, etc.
        -sav save plot and quit quietly
        -fmt [png,svg,eps,jpg,pdf] specify format for output, default is pdf
    DEFAULTS
        resolution: intermediate
        saved images are in pdf
    """
    dir_path='.'
    names,res,proj,locs,padlon,padlat,fancy,gridspace,details=[],'l','lcc','',0,0,0,15,1
    Age_bounds=[-5000,2000]
    Lat_bounds=[20,45]
    Lon_bounds=[15,55]
    fmt='pdf'
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        sites_file=sys.argv[ind+1]
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res=sys.argv[ind+1]
    if '-etp' in sys.argv:fancy=1
    if '-o' in sys.argv:ocean=1
    if '-d' in sys.argv:details=1
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    verbose=pmagplotlib.verbose
    if '-sav' in sys.argv:
        verbose=0
    if '-pad' in sys.argv:
        ind = sys.argv.index('-pad')
        padlat=float(sys.argv[ind+1])
        padlon=float(sys.argv[ind+2])
    if '-grd' in sys.argv:
        ind = sys.argv.index('-grd')
        gridspace=float(sys.argv[ind+1])
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    sites_file=dir_path+'/'+sites_file
    geo_in=open(sites_file,'r').readlines()
    Age,AgeErr,Vadm,VadmErr,slats,slons=[],[],[],[],[],[]
    for line in geo_in[2:]: # skip top two rows`
        rec=line.split()
        if float(rec[0])>Age_bounds[0] and float(rec[0])<Age_bounds[1] \
           and float(rec[12])>Lat_bounds[0] and float(rec[12]) < Lat_bounds[1]\
            and float(rec[13])>Lon_bounds[0] and float(rec[13])<Lon_bounds[1]:
            Age.append(float(rec[0]))
            AgeErr.append(float(rec[1]))
            Vadm.append(10.*float(rec[6]))
            VadmErr.append(10.*float(rec[7]))
            slats.append(float(rec[12]))
            slons.append(float(rec[13]))
    FIGS={'map':1,'vadms':2}
    pmagplotlib.plot_init(FIGS['map'],6,6)
    pmagplotlib.plot_init(FIGS['vadms'],6,6)
    Opts={'res':res,'proj':proj,'loc_name':locs,'padlon':padlon,'padlat':padlat,'latmin':numpy.min(slats)-padlat,'latmax':numpy.max(slats)+padlat,'lonmin':numpy.min(slons)-padlon,'lonmax':numpy.max(slons)+padlon,'sym':'ro','boundinglat':0.,'pltgrid':1}
    Opts['lon_0']=int(0.5*(numpy.min(slons)+numpy.max(slons)))
    Opts['lat_0']=int(0.5*(numpy.min(slats)+numpy.max(slats)))
    Opts['gridspace']=gridspace
    if details==1:
        Opts['details']={'coasts':1,'rivers':0,'states':1,'countries':1,'ocean':1}
    else:
        Opts['details']={'coasts':1,'rivers':0,'states':0,'countries':0,'ocean':1}
    Opts['details']['fancy']=fancy
    pmagplotlib.plot_map(FIGS['map'],slats,slons,Opts)
    pmagplotlib.plot_xy(FIGS['vadms'],Age,Vadm,sym='bo',xlab='Age (Years CE)',ylab=r'VADM (ZAm$^2$)')
    if verbose:pmagplotlib.draw_figs(FIGS)
    files={}
    for key in list(FIGS.keys()):
        files[key]=key+'.'+fmt
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['map']='Map'
        titles['vadms']='VADMs'
        FIG = pmagplotlib.add_borders(FIGS,titles,black,purple)
        pmagplotlib.save_plots(FIGS,files)
    elif verbose:
        ans=input(" S[a]ve to save plot, Return to quit:  ")
        if ans=="a":
            pmagplotlib.save_plots(FIGS,files)
    else:
        pmagplotlib.save_plots(FIGS,files)
Ejemplo n.º 17
0
def main():
    """
    NAME
       zeq.py
  
    DESCRIPTION
       plots demagnetization data. The equal area projection has the X direction (usually North in geographic coordinates)
          to the top.  The red line is the X axis of the Zijderveld diagram.  Solid symbols are lower hemisphere. 
          The solid (open) symbols in the Zijderveld diagram are X,Y (X,Z) pairs.  The demagnetization diagram plots the
          fractional remanence remaining after each step. The green line is the fraction of the total remaence removed 
          between each step.        

    INPUT FORMAT
       takes specimen_name treatment intensity declination inclination  in space
 delimited file

    SYNTAX
        zeq.py [command line options

    OPTIONS
        -f FILE for reading from command line
        -u [mT,C] specify units of mT OR C, default is unscaled
        -sav save figure and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
        -beg [step number] treatment step for beginning of PCA calculation, 0 is default
        -end [step number] treatment step for end of PCA calculation, last step is default
        -ct [l,p,f] Calculation Type: best-fit line,  plane or fisher mean; line is default

    """
    files, fmt, plot = {}, 'svg', 0
    end_pca, beg_pca = "", ""
    calculation_type = 'DE-BFL'
    if '-h' in sys.argv:  # check if help is needed
        print(main.__doc__)
        sys.exit()  # graceful quit
    else:
        if '-f' in sys.argv:
            ind = sys.argv.index('-f')
            file = sys.argv[ind + 1]
        else:
            print(main.__doc__)
            sys.exit()
        if '-u' in sys.argv:
            ind = sys.argv.index('-u')
            units = sys.argv[ind + 1]
            if units == "C": SIunits = "K"
            if units == "mT": SIunits = "T"
        else:
            units = "U"
            SIunits = "U"
    if '-sav' in sys.argv: plot = 1
    if '-ct' in sys.argv:
        ind = sys.argv.index('-ct')
        ct = sys.argv[ind + 1]
        if ct == 'f': calculation_type = 'DE-FM'
        if ct == 'p': calculation_type = 'DE-BFP'
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-beg' in sys.argv:
        ind = sys.argv.index('-beg')
        beg_pca = int(sys.argv[ind + 1])
    if '-end' in sys.argv:
        ind = sys.argv.index('-end')
        end_pca = int(sys.argv[ind + 1])
    f = open(file, 'r')
    data = f.readlines()
    #
    datablock = []  # set up list for data
    s = ""  # initialize specimen name
    angle = 0.
    for line in data:  # read in the data from standard input
        rec = line.split()  # split each line on space to get records
        if angle == "": angle = float(rec[3])
        if s == "": s = rec[0]
        if units == 'mT':
            datablock.append([
                float(rec[1]) * 1e-3,
                float(rec[3]),
                float(rec[4]), 1e-3 * float(rec[2]), '', 'g'
            ])  # treatment, dec, inc, int # convert to T and Am^2 (assume emu)
        if units == 'C':
            datablock.append([
                float(rec[1]) + 273.,
                float(rec[3]),
                float(rec[4]), 1e-3 * float(rec[2]), '', 'g'
            ])  # treatment, dec, inc, int, convert to K and Am^2, assume emu
        if units == 'U':
            datablock.append([
                float(rec[1]),
                float(rec[3]),
                float(rec[4]),
                float(rec[2]), '', 'g'
            ])  # treatment, dec, inc, int, using unscaled units


# define figure numbers in a dictionary for equal area, zijderveld,
#  and intensity vs. demagnetiztion step respectively
    ZED = {}
    ZED['eqarea'], ZED['zijd'], ZED['demag'] = 1, 2, 3
    pmagplotlib.plot_init(ZED['eqarea'], 5, 5)  # initialize plots
    pmagplotlib.plot_init(ZED['zijd'], 5, 5)
    pmagplotlib.plot_init(ZED['demag'], 5, 5)
    #
    #
    pmagplotlib.plot_zed(ZED, datablock, angle, s, SIunits)  # plot the data
    if plot == 0: pmagplotlib.draw_figs(ZED)
    #
    # print out data for this sample to screen
    #
    recnum = 0
    for plotrec in datablock:
        if units == 'mT':
            print(
                '%i  %7.1f %8.3e %7.1f %7.1f ' %
                (recnum, plotrec[0] * 1e3, plotrec[3], plotrec[1], plotrec[2]))
        if units == 'C':
            print('%i  %7.1f %8.3e %7.1f %7.1f ' %
                  (recnum, plotrec[0] - 273., plotrec[3], plotrec[1],
                   plotrec[2]))
        if units == 'U':
            print('%i  %7.1f %8.3e %7.1f %7.1f ' %
                  (recnum, plotrec[0], plotrec[3], plotrec[1], plotrec[2]))
        recnum += 1
    if plot == 0:
        while 1:
            if beg_pca != "" and end_pca != "" and calculation_type != "":
                pmagplotlib.plot_zed(ZED, datablock, angle, s,
                                     SIunits)  # plot the data
                mpars = pmag.domean(
                    datablock, beg_pca, end_pca,
                    calculation_type)  # get best-fit direction/great circle
                pmagplotlib.plot_dir(
                    ZED, mpars, datablock,
                    angle)  # plot the best-fit direction/great circle
                print('Specimen, calc_type, N, min, max, MAD, dec, inc')
                if units == 'mT':
                    print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' %
                          (s, calculation_type, mpars["specimen_n"],
                           mpars["measurement_step_min"] * 1e3,
                           mpars["measurement_step_max"] * 1e3,
                           mpars["specimen_mad"], mpars["specimen_dec"],
                           mpars["specimen_inc"]))
                if units == 'C':
                    print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' %
                          (s, calculation_type, mpars["specimen_n"],
                           mpars["measurement_step_min"] - 273,
                           mpars["measurement_step_max"] - 273,
                           mpars["specimen_mad"], mpars["specimen_dec"],
                           mpars["specimen_inc"]))
                if units == 'U':
                    print(
                        '%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' %
                        (s, calculation_type, mpars["specimen_n"],
                         mpars["measurement_step_min"],
                         mpars["measurement_step_max"], mpars["specimen_mad"],
                         mpars["specimen_dec"], mpars["specimen_inc"]))
            if end_pca == "":
                end_pca = len(
                    datablock
                ) - 1  # initialize end_pca, beg_pca to first and last measurement
            if beg_pca == "": beg_pca = 0
            ans = input(
                " s[a]ve plot, [b]ounds for pca and calculate, change [h]orizontal projection angle, [q]uit:   "
            )
            if ans == 'q':
                sys.exit()
            if ans == 'a':
                files = {}
                for key in list(ZED.keys()):
                    files[key] = s + '_' + key + '.' + fmt
                pmagplotlib.save_plots(ZED, files)
            if ans == 'h':
                angle = float(
                    input(" Declination to project onto horizontal axis? "))
                pmagplotlib.plot_zed(ZED, datablock, angle, s,
                                     SIunits)  # plot the data

            if ans == 'b':
                GoOn = 0
                while GoOn == 0:  # keep going until reasonable bounds are set
                    print('Enter index of first point for pca: ', '[', beg_pca,
                          ']')
                    answer = input('return to keep default  ')
                    if answer != "": beg_pca = int(answer)
                    print('Enter index  of last point for pca: ', '[', end_pca,
                          ']')
                    answer = input('return to keep default  ')
                    if answer != "":
                        end_pca = int(answer)
                    if beg_pca >= 0 and beg_pca <= len(
                            datablock) - 2 and end_pca > 0 and end_pca < len(
                                datablock):
                        GoOn = 1
                    else:
                        print("Bad entry of indices - try again")
                        end_pca = len(datablock) - 1
                        beg_pca = 0
                GoOn = 0
                while GoOn == 0:
                    ct = input(
                        'Enter Calculation Type: best-fit line,  plane or fisher mean [l]/p/f :  '
                    )
                    if ct == "" or ct == "l":
                        calculation_type = "DE-BFL"
                        GoOn = 1  # all good
                    elif ct == 'p':
                        calculation_type = "DE-BFP"
                        GoOn = 1  # all good
                    elif ct == 'f':
                        calculation_type = "DE-FM"
                        GoOn = 1  # all good
                    else:
                        print("bad entry of calculation type: try again. "
                              )  # keep going
                    pmagplotlib.plot_zed(ZED, datablock, angle, s,
                                         SIunits)  # plot the data
                    mpars = pmag.domean(
                        datablock, beg_pca, end_pca, calculation_type
                    )  # get best-fit direction/great circle
                    pmagplotlib.plot_dir(
                        ZED, mpars, datablock,
                        angle)  # plot the best-fit direction/great circle
                    print('Specimen, calc_type, N, min, max, MAD, dec, inc')
                    if units == 'mT':
                        print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' %
                              (s, calculation_type, mpars["specimen_n"],
                               mpars["measurement_step_min"] * 1e3,
                               mpars["measurement_step_max"] * 1e3,
                               mpars["specimen_mad"], mpars["specimen_dec"],
                               mpars["specimen_inc"]))
                    if units == 'C':
                        print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' %
                              (s, calculation_type, mpars["specimen_n"],
                               mpars["measurement_step_min"] - 273,
                               mpars["measurement_step_max"] - 273,
                               mpars["specimen_mad"], mpars["specimen_dec"],
                               mpars["specimen_inc"]))
                    if units == 'U':
                        print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' %
                              (s, calculation_type, mpars["specimen_n"],
                               mpars["measurement_step_min"],
                               mpars["measurement_step_max"],
                               mpars["specimen_mad"], mpars["specimen_dec"],
                               mpars["specimen_inc"]))
            pmagplotlib.draw_figs(ZED)
    else:
        print(beg_pca, end_pca)
        if beg_pca != "" and end_pca != "":
            pmagplotlib.plot_zed(ZED, datablock, angle, s,
                                 SIunits)  # plot the data
            mpars = pmag.domean(
                datablock, beg_pca, end_pca,
                calculation_type)  # get best-fit direction/great circle
            pmagplotlib.plot_dir(
                ZED, mpars, datablock,
                angle)  # plot the best-fit direction/great circle
            print('Specimen, calc_type, N, min, max, MAD, dec, inc')
            if units == 'mT':
                print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' %
                      (s, calculation_type, mpars["specimen_n"],
                       mpars["measurement_step_min"] * 1e3,
                       mpars["measurement_step_max"] * 1e3,
                       mpars["specimen_mad"], mpars["specimen_dec"],
                       mpars["specimen_inc"]))
            if units == 'C':
                print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' %
                      (s, calculation_type, mpars["specimen_n"],
                       mpars["measurement_step_min"] - 273,
                       mpars["measurement_step_max"] - 273,
                       mpars["specimen_mad"], mpars["specimen_dec"],
                       mpars["specimen_inc"]))
            if units == 'U':
                print('%s %s %i  %6.2f %6.2f %6.1f %7.1f %7.1f' %
                      (s, calculation_type, mpars["specimen_n"],
                       mpars["measurement_step_min"],
                       mpars["measurement_step_max"], mpars["specimen_mad"],
                       mpars["specimen_dec"], mpars["specimen_inc"]))
        files = {}
        for key in list(ZED.keys()):
            files[key] = s + '_' + key + '.' + fmt
        pmagplotlib.save_plots(ZED, files)
Ejemplo n.º 18
0
def main():
    """
    NAME
        basemap_magic.py
        NB:  this program no longer maintained - use plot_map_pts.py for greater functionality

    DESCRIPTION
        makes a map of locations in er_sites.txt

    SYNTAX
        basemap_magic.py  [command line options]

    OPTIONS
        -h prints help message and quits
        -f SFILE, specify er_sites.txt or pmag_results.txt format file
        -res [c,l,i,h] specify resolution (crude,low,intermediate,high)
        -etp plot the etopo20 topographic mesh
        -pad [LAT LON]  pad bounding box by LAT/LON  (default is [.5 .5] degrees)
        -grd SPACE specify grid spacing
        -prj [lcc] , specify projection (lcc=lambert conic conformable), default is mercator
        -n print site names (default is not)
        -l print location names (default is not)
        -o color ocean blue/land green (default is not)
        -R don't plot details of rivers
        -B don't plot national/state  boundaries, etc.
        -sav save plot and quit quietly
        -fmt [png,svg,eps,jpg,pdf] specify format for output, default is pdf
    DEFAULTS
        SFILE: 'er_sites.txt'
        resolution: intermediate
        saved images are in pdf
    """
    dir_path = '.'
    sites_file = 'er_sites.txt'
    ocean = 0
    res = 'i'
    proj = 'merc'
    prn_name = 0
    prn_loc = 0
    fancy = 0
    rivers, boundaries = 0, 0
    padlon, padlat, gridspace, details = .5, .5, .5, 1
    fmt = 'pdf'
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        sites_file = sys.argv[ind+1]
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res = sys.argv[ind+1]
    if '-etp' in sys.argv:
        fancy = 1
    if '-n' in sys.argv:
        prn_name = 1
    if '-l' in sys.argv:
        prn_loc = 1
    if '-o' in sys.argv:
        ocean = 1
    if '-R' in sys.argv:
        rivers = 0
    if '-B' in sys.argv:
        boundaries = 0
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj = sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind+1]
    verbose = pmagplotlib.verbose
    if '-sav' in sys.argv:
        verbose = 0
    if '-pad' in sys.argv:
        ind = sys.argv.index('-pad')
        padlat = float(sys.argv[ind+1])
        padlon = float(sys.argv[ind+2])
    if '-grd' in sys.argv:
        ind = sys.argv.index('-grd')
        gridspace = float(sys.argv[ind+1])
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path = sys.argv[ind+1]
    sites_file = dir_path+'/'+sites_file
    location = ""
    FIG = {'map': 1}
    pmagplotlib.plot_init(FIG['map'], 6, 6)
    # read in er_sites file
    Sites, file_type = pmag.magic_read(sites_file)
    if 'results' in file_type:
        latkey = 'average_lat'
        lonkey = 'average_lon'
        namekey = 'pmag_result_name'
        lockey = 'er_location_names'
    else:
        latkey = 'site_lat'
        lonkey = 'site_lon'
        namekey = 'er_site_name'
        lockey = 'er_location_name'
    lats, lons = [], []
    slats, slons = [], []
    names, locs = [], []
    for site in Sites:
        if prn_loc == 1 and location == "":
            location = site['er_location_name']
        lats.append(float(site[latkey]))
        l = float(site[lonkey])
        if l < 0:
            l = l+360.  # make positive
        lons.append(l)
        if prn_name == 1:
            names.append(site[namekey])
        if prn_loc == 1:
            locs.append(site[lockey])
    for lat in lats:
        slats.append(lat)
    for lon in lons:
        slons.append(lon)
    Opts = {'res': res, 'proj': proj, 'loc_name': locs, 'padlon': padlon, 'padlat': padlat, 'latmin': numpy.min(slats)-padlat, 'latmax': numpy.max(
        slats)+padlat, 'lonmin': numpy.min(slons)-padlon, 'lonmax': numpy.max(slons)+padlon, 'sym': 'ro', 'boundinglat': 0., 'pltgrid': 1.}
    Opts['lon_0'] = 0.5*(numpy.min(slons)+numpy.max(slons))
    Opts['lat_0'] = 0.5*(numpy.min(slats)+numpy.max(slats))
    Opts['names'] = names
    Opts['gridspace'] = gridspace
    Opts['details'] = {'coasts': 1, 'rivers': 1,
                       'states': 1, 'countries': 1, 'ocean': 0}
    if ocean == 1:
        Opts['details']['ocean'] = 1
    if rivers == 1:
        Opts['details']['rivers'] = 0
    if boundaries == 1:
        Opts['details']['states'] = 0
        Opts['details']['countries'] = 0
    Opts['details']['fancy'] = fancy
    pmagplotlib.plot_map(FIG['map'], lats, lons, Opts)
    if verbose:
        pmagplotlib.draw_figs(FIG)
    files = {}
    for key in list(FIG.keys()):
        files[key] = 'Site_map'+'.'+fmt
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['map'] = 'Site Map'
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    elif verbose:
        ans = input(" S[a]ve to save plot, Return to quit:  ")
        if ans == "a":
            pmagplotlib.save_plots(FIG, files)
    else:
        pmagplotlib.save_plots(FIG, files)
Ejemplo n.º 19
0
def main():
    """
    NAME
        lnp_magic.py

    DESCRIPTION
       makes equal area projections site by site
         from specimen formatted file with
         Fisher confidence ellipse using McFadden and McElhinny (1988)
         technique for combining lines and planes

    SYNTAX
        lnp_magic [command line options]

    INPUT
       takes magic formatted specimens file

    OUPUT
        prints site_name n_lines n_planes K alpha95 dec inc R

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is 'specimens.txt', ('pmag_specimens.txt' for legacy data model 2)
        -fsa FILE: specify samples file, required to plot by site for data model 3 (otherwise will plot by sample)
                default is 'samples.txt'
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is specimen
        -fmt [svg,png,jpg] format for plots, default is svg
        -sav save plots and quit
        -P: do not plot
        -F FILE, specify output file of dec, inc, alpha95 data for plotting with plotdi_a and plotdi_e
        -exc use criteria in criteria table # NOT IMPLEMENTED
        -DM NUMBER MagIC data model (2 or 3, default 3)
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", ".")
    data_model = int(float(pmag.get_named_arg("-DM", 3)))
    fmt = pmag.get_named_arg("-fmt", 'svg')
    if data_model == 2:
        in_file = pmag.get_named_arg('-f', 'pmag_specimens.txt')
        crit_file = "pmag_criteria.txt"
    else:
        in_file = pmag.get_named_arg('-f', 'specimens.txt')
        samp_file = pmag.get_named_arg('-fsa', 'samples.txt')
        crit_file = "criteria.txt"
    in_file = pmag.resolve_file_name(in_file, dir_path)
    dir_path = os.path.split(in_file)[0]
    if data_model == 3:
        samp_file = pmag.resolve_file_name(samp_file, dir_path)
    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"
    else:
        coord = "-1"

    out_file = pmag.get_named_arg('-F', '')
    if out_file:
        out = open(dir_path + '/' + out_file, 'w')
    if '-P' in sys.argv:
        make_plots = 0  # do not plot
    else:
        make_plots = 1  # do plot
    if '-sav' in sys.argv:
        plot = 1  # save plots and quit
    else:
        plot = 0  # show plots intereactively (if make_plots)


#

    if data_model == 2:
        Specs, file_type = pmag.magic_read(in_file)
        if 'specimens' not in file_type:
            print('Error opening ', in_file, file_type)
            sys.exit()
    else:
        fnames = {'specimens': in_file, 'samples': samp_file}
        con = cb.Contribution(dir_path,
                              read_tables=['samples', 'specimens'],
                              custom_filenames=fnames)
        con.propagate_name_down('site', 'specimens')
        if 'site' in con.tables['specimens'].df.columns:
            site_col = 'site'
        else:
            site_col = 'sample'
        tilt_corr_col = "dir_tilt_correction"
        mad_col = "dir_mad_free"
        alpha95_col = "dir_alpha95"
        site_alpha95_col = "dir_alpha95"
        dec_col = "dir_dec"
        inc_col = "dir_inc"
        num_meas_col = "dir_n_measurements"
        k_col = "dir_k"
        cols = [
            site_col, tilt_corr_col, mad_col, alpha95_col, dec_col, inc_col
        ]
        con.tables['specimens'].front_and_backfill(cols)
        con.tables['specimens'].df = con.tables['specimens'].df.where(
            con.tables['specimens'].df.notnull(), "")
        Specs = con.tables['specimens'].convert_to_pmag_data_list()

    ## using criteria file was never fully implemented
    #if '-exc' in sys.argv:
    #    Crits, file_type = pmag.magic_read(pmag.resolve_file_name(crit_file, dir_path))
    #    for crit in Crits:
    #        if mad_col in crit:
    #            M = float(crit['specimen_mad'])
    #        if num_meas_col in crit:
    #            N = float(crit['specimen_n'])
    #        if site_alpha95_col in crit and 'site' in crit:
    #            acutoff = float(crit['site_alpha95'])
    #        if k_col in crit:
    #            kcutoff = float(crit['site_k'])
    #else:
    #    Crits = ""

    sitelist = []

    # initialize some variables
    FIG = {}  # plot dictionary
    FIG['eqarea'] = 1  # eqarea is figure 1
    M, N, acutoff, kcutoff = 180., 1, 180., 0.

    if data_model == 2:
        site_col = 'er_site_name'
        tilt_corr_col = "specimen_tilt_correction"
        mad_col = "specimen_mad"
        alpha95_col = 'specimen_alpha95'
        dec_col = "specimen_dec"
        inc_col = "specimen_inc"
        num_meas_col = "specimen_n"
        site_alpha95_col = "site_alpha95"
    else:  # data model 3
        pass

    for rec in Specs:
        if rec[site_col] not in sitelist:
            sitelist.append(rec[site_col])
    sitelist.sort()
    if make_plots == 1:
        EQ = {}
        EQ['eqarea'] = 1
    for site in sitelist:
        pmagplotlib.plot_init(EQ['eqarea'], 4, 4)
        print(site)
        data = []
        for spec in Specs:
            if tilt_corr_col not in list(spec.keys()):
                spec[tilt_corr_col] = '-1'  # assume unoriented
            if spec[site_col] == site:
                if mad_col not in list(spec.keys()) or spec[mad_col] == "":
                    if alpha95_col in list(
                            spec.keys()) and spec[alpha95_col] != "":
                        spec[mad_col] = spec[alpha95_col]
                    else:
                        spec[mad_col] = '180'
                if not spec[num_meas_col]:
                    continue
                if (float(spec[tilt_corr_col])
                        == float(coord)) and (float(spec[mad_col]) <= M) and (
                            float(spec[num_meas_col]) >= N):
                    rec = {}
                    for key in list(spec.keys()):
                        rec[key] = spec[key]
                    rec["dec"] = float(spec[dec_col])
                    rec["inc"] = float(spec[inc_col])
                    rec["tilt_correction"] = spec[tilt_corr_col]
                    data.append(rec)
        if len(data) > 2:
            fpars = pmag.dolnp(data, 'specimen_direction_type')
            print("Site lines planes  kappa   a95   dec   inc")
            print(site, fpars["n_lines"], fpars["n_planes"], fpars["K"],
                  fpars["alpha95"], fpars["dec"], fpars["inc"], fpars["R"])
            if out_file != "":
                if float(fpars["alpha95"]) <= acutoff and float(
                        fpars["K"]) >= kcutoff:
                    out.write('%s %s %s\n' %
                              (fpars["dec"], fpars['inc'], fpars['alpha95']))
            print('% tilt correction: ', coord)
            if make_plots == 1:
                files = {}
                files['eqarea'] = site + '_' + crd + '_' + 'eqarea' + '.' + fmt
                pmagplotlib.plot_lnp(EQ['eqarea'], site, data, fpars,
                                     'specimen_direction_type')
                if plot == 0:
                    pmagplotlib.draw_figs(EQ)
                    ans = input(
                        "s[a]ve plot, [q]uit, <return> to continue:\n ")
                    if ans == "a":
                        pmagplotlib.save_plots(EQ, files)
                    if ans == "q":
                        sys.exit()
                else:
                    pmagplotlib.save_plots(EQ, files)
        else:
            print(
                'skipping site - not enough data with specified coordinate system'
            )
Ejemplo n.º 20
0
def main():
    """
    NAME
        polemap_magic.py

    DESCRIPTION
        makes a map of paleomagnetic poles and a95/dp,dm for pole  in a locations table

    SYNTAX
        polemap_magic.py [command line options]

    OPTIONS
        -h prints help and quits
        -eye  ELAT ELON [specify eyeball location], default is 90., 0.
        -f FILE location format file, [default is locations.txt]
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -etp plot the etopo20 topographpy data (requires high resolution data set)
        -prj PROJ,  specify one of the following:
             ortho = orthographic
             lcc = lambert conformal
             moll = molweide
             merc = mercator
        -sym SYM SIZE: choose a symbol and size, examples:
            ro 5 : small red circles
            bs 10 : intermediate blue squares
            g^ 20 : large green triangles
        -ell  plot dp/dm or a95 ellipses
        -rev RSYM RSIZE : flip reverse poles to normal antipode
        -S:  plot antipodes of all poles
        -age : plot the ages next to the poles
        -crd [g,t] : choose coordinate system, default is to plot all location poles
        -fmt [pdf, png, eps...] specify output format, default is pdf
        -sav  save and quit
    DEFAULTS
        FILE: locations.txt
        res:  c
        prj: ortho
        ELAT,ELON = 0,0
        SYM SIZE: ro 8
        RSYM RSIZE: g^ 8

    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", ".")
    # plot: default is 0, if -sav in sys.argv should be 1
    plot = pmag.get_flag_arg_from_sys("-sav", true=1, false=0)
    fmt = pmag.get_named_arg("-fmt", "pdf")
    res = pmag.get_named_arg("-res", "c")
    proj = pmag.get_named_arg("-prj", "ortho")
    anti = pmag.get_flag_arg_from_sys("-S", true=1, false=0)
    fancy = pmag.get_flag_arg_from_sys("-etp", true=1, false=0)
    ell = pmag.get_flag_arg_from_sys("-ell", true=1, false=0)
    ages = pmag.get_flag_arg_from_sys("-age", true=1, false=0)
    if '-rev' in sys.argv:
        flip = 1
        ind = sys.argv.index('-rev')
        rsym = (sys.argv[ind + 1])
        rsize = int(sys.argv[ind + 2])
    else:
        flip, rsym, rsize = 0, "g^", 8
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym = (sys.argv[ind + 1])
        size = int(sys.argv[ind + 2])
    else:
        sym, size = 'ro', 8
    if '-eye' in sys.argv:
        ind = sys.argv.index('-eye')
        lat_0 = float(sys.argv[ind + 1])
        lon_0 = float(sys.argv[ind + 2])
    else:
        lat_0, lon_0 = 90., 0.
    crd = pmag.get_named_arg("-crd", "")
    coord_dict = {'g': 0, 't': 100}
    coord = coord_dict[crd] if crd else ""
    results_file = pmag.get_named_arg("-f", "locations.txt")

    con = cb.Contribution(dir_path, single_file=results_file)
    if not list(con.tables.keys()):
        print("-W - Couldn't read in data")
        return False, "Couldn't read in data"

    FIG = {'map': 1}
    pmagplotlib.plot_init(FIG['map'], 6, 6)
    # read in location file
    lats, lons = [], []
    Pars = []
    dates, rlats, rlons = [], [], []
    polarities = []

    pole_container = con.tables['locations']
    pole_df = pole_container.df
    # use individual results
    if not pmagplotlib.isServer:
        if 'result_type' in pole_df.columns:
            pole_df = pole_df[pole_df['result_type'] == 'a']
    if 'pole_lat' not in pole_df.columns or 'pole_lon' not in pole_df.columns:
        print(
            "-W- pole_lat and pole_lon are required columns to run polemap_magic.py"
        )
        return False, "pole_lat and pole_lon are required columns to run polemap_magic.py"
    # use records with pole_lat and pole_lon
    cond1, cond2 = pole_df['pole_lat'].notnull(), pole_df['pole_lon'].notnull()
    Results = pole_df[cond1 & cond2]
    # use tilt correction
    if coord and 'dir_tilt_correction' in Results.columns:
        Results = Results[Results['dir_tilt_correction'] == coord]
    # get location name and average ages
    loc_list = Results['location'].values
    locations = ":".join(Results['location'].unique())
    if 'age' not in Results.columns and 'age_low' in Results.columns and 'age_high' in Results.columns:
        Results['age'] = Results['age_low']+0.5 * \
            (Results['age_high']-Results['age_low'])
    if 'age' in Results.columns and ages == 1:
        dates = Results['age'].unique()

    if not any(Results.index):
        print("-W- No poles could be plotted")
        return False, "No poles could be plotted"

    # go through rows and extract data
    for ind, row in Results.iterrows():
        lat, lon = float(row['pole_lat']), float(row['pole_lon'])
        if 'dir_polarity' in row:
            polarities.append(row['dir_polarity'])
        if anti == 1:
            lats.append(-lat)
            lon = lon + 180.
            if lon > 360:
                lon = lon - 360.
            lons.append(lon)
        elif flip == 0:
            lats.append(lat)
            lons.append(lon)
        elif flip == 1:
            if lat < 0:
                rlats.append(-lat)
                lon = lon + 180.
                if lon > 360:
                    lon = lon - 360
                rlons.append(lon)
            else:
                lats.append(lat)
                lons.append(lon)

        ppars = []
        ppars.append(lon)
        ppars.append(lat)
        ell1, ell2 = "", ""
        if 'pole_dm' in list(row.keys()) and row['pole_dm']:
            ell1 = float(row['pole_dm'])
        if 'pole_dp' in list(row.keys()) and row['pole_dp']:
            ell2 = float(row['pole_dp'])
        if 'pole_alpha95' in list(row.keys()) and row['pole_alpha95']:
            ell1, ell2 = float(row['pole_alpha95']), float(row['pole_alpha95'])
        if ell1 and ell2:
            ppars = []
            ppars.append(lons[-1])
            ppars.append(lats[-1])
            ppars.append(ell1)
            ppars.append(lons[-1])
            isign = abs(lats[-1]) / lats[-1]
            ppars.append(lats[-1] - isign * 90.)
            ppars.append(ell2)
            ppars.append(lons[-1] + 90.)
            ppars.append(0.)
            Pars.append(ppars)

    locations = locations.strip(':')
    Opts = {
        'latmin': -90,
        'latmax': 90,
        'lonmin': 0.,
        'lonmax': 360.,
        'lat_0': lat_0,
        'lon_0': lon_0,
        'proj': proj,
        'sym': 'bs',
        'symsize': 3,
        'pltgrid': 0,
        'res': res,
        'boundinglat': 0.
    }
    Opts['details'] = {
        'coasts': 1,
        'rivers': 0,
        'states': 0,
        'countries': 0,
        'ocean': 1,
        'fancy': fancy
    }
    base_Opts = Opts.copy()

    # make the base map with a blue triangle at the pole
    pmagplotlib.plot_map(FIG['map'], [90.], [0.], Opts)

    Opts['pltgrid'] = -1
    Opts['sym'] = sym
    Opts['symsize'] = size
    if len(dates) > 0:
        Opts['names'] = dates
    if len(lats) > 0:
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], lats, lons, Opts)
    Opts['names'] = []

    titles = {}
    files = {}

    if pmagplotlib.isServer:
        # plot each indvidual pole for the server
        for ind in range(len(lats)):
            lat = lats[ind]
            lon = lons[ind]
            polarity = ""
            if 'polarites' in locals():
                polarity = polarities[ind]
            polarity = "_" + polarity if polarity else ""
            location = loc_list[ind]
            FIG["map_{}".format(ind)] = ind + 2
            pmagplotlib.plot_init(FIG['map'], 6, 6)
            # if with baseOpts, lat/lon don't show
            # if with Opts, grid lines don't show
            pmagplotlib.plot_map(ind + 2, [90], [0.], base_Opts)
            pmagplotlib.plot_map(ind + 2, [lat], [lon], Opts)
            titles["map_{}".format(ind)] = location
            files["map_{}".format(ind)] = "LO:_{}{}_TY:_POLE_map_.{}".format(
                location, polarity, fmt)

    # truncate location names so that ultra long filenames are not created
    if len(locations) > 50:
        locations = locations[:50]
    if pmagplotlib.isServer:
        # use server plot naming convention
        if 'contribution' in con.tables:
            # try to get contribution id
            con_id = con.tables['contribution'].df.iloc[0].id
            files['map'] = 'MC:_{}_TY:_POLE_map.{}'.format(con_id, fmt)
        else:
            # no contribution id available
            files['map'] = 'LO:_' + locations + '_TY:_POLE_map.' + fmt
    else:
        # use readable naming convention for non-database use
        files['map'] = '{}_POLE_map.{}'.format(locations, fmt)

    #
    if len(rlats) > 0:
        Opts['sym'] = rsym
        Opts['symsize'] = rsize
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], rlats, rlons, Opts)
    if plot == 0 and not set_env.IS_WIN:
        pmagplotlib.draw_figs(FIG)
    if ell == 1:  # add ellipses if desired.
        Opts['details'] = {
            'coasts': 0,
            'rivers': 0,
            'states': 0,
            'countries': 0,
            'ocean': 0,
            'fancy': fancy
        }
        Opts['pltgrid'] = -1  # turn off meridian replotting
        Opts['symsize'] = 2
        Opts['sym'] = 'g-'
        for ppars in Pars:
            if ppars[2] != 0:
                PTS = pmagplotlib.plot_ell(FIG['map'], ppars, 'g.', 0, 0)
                elats, elons = [], []
                for pt in PTS:
                    elons.append(pt[0])
                    elats.append(pt[1])
                # make the base map with a blue triangle at the pole
                pmagplotlib.plot_map(FIG['map'], elats, elons, Opts)
                if plot == 0 and not set_env.IS_WIN:
                    pmagplotlib.draw_figs(FIG)

    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles['map'] = 'LO:_' + locations + '_POLE_map'
        if 'contribution' in con.tables:
            con_id = con.tables['contribution'].df.iloc[0].id
            titles['map'] = "MagIC contribution {} all locations".format(
                con_id)
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    elif plot == 0:
        pmagplotlib.draw_figs(FIG)
        ans = input(" S[a]ve to save plot, Return to quit:  ")
        if ans == "a":
            pmagplotlib.save_plots(FIG, files)
        else:
            print("Good bye")
    else:
        pmagplotlib.save_plots(FIG, files)

    return True, files
Ejemplo n.º 21
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)
Ejemplo n.º 22
0
def main():
    """
    NAME
        irmaq_magic.py

    DESCRIPTION
       plots IRM acquisition curves from measurements file

    SYNTAX
        irmaq_magic [command line options]

    INPUT
       takes magic formatted magic_measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt/measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot, default is by location
        -N ; do not normalize by last point - use original units
        -fmt [png,jpg,eps,pdf] set plot file format [default is svg]
        -sav save plot[s] and quit
        -DM MagIC data model number, default is 3
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    FIG = {}  # plot dictionary
    FIG['exp'] = 1  # exp is figure 1
    dir_path = './'
    plot, fmt = 0, 'svg'
    units = 'T',
    XLP = []
    norm = 1
    LP = "LP-IRM"
    if len(sys.argv) > 1:
        if '-h' in sys.argv:
            print(main.__doc__)
            sys.exit()
        data_model = int(pmag.get_named_arg("-DM", 3))
        if '-N' in sys.argv:
            norm = 0
        if '-sav' in sys.argv:
            plot = 1
        if '-fmt' in sys.argv:
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        if data_model == 3:
            in_file = pmag.get_named_arg("-f", 'measurements.txt')
        else:
            in_file = pmag.get_named_arg("-f", 'magic_measurements.txt')
        if '-WD' in sys.argv:
            ind = sys.argv.index('-WD')
            dir_path = sys.argv[ind + 1]
        dir_path = os.path.realpath(dir_path)
        in_file = pmag.resolve_file_name(in_file, dir_path)
        if '-WD' not in sys.argv:
            dir_path = os.path.split(in_file)[0]
        plot_by = pmag.get_named_arg("-obj", "loc")
        if data_model == 3:
            plot_key = 'location'
            if plot_by == 'sit':
                plot_key = 'site'
            if plot_by == 'sam':
                plot_key = 'sample'
            if plot_by == 'spc':
                plot_key = 'specimen'
        else:
            plot_key = 'er_location_name'
            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'

    # set defaults and get more information if needed
    if data_model == 3:
        dmag_key = 'treat_dc_field'
    else:
        dmag_key = 'treatment_dc_field'
    #
    if data_model == 3 and plot_key != 'specimen':
        # gonna need to read in more files
        print('-W- You are trying to plot measurements by {}'.format(plot_key))
        print('    By default, this information is not available in your measurement file.')
        print('    Trying to acquire this information from {}'.format(dir_path))
        con = cb.Contribution(dir_path)
        meas_df = con.propagate_location_to_measurements()
        if meas_df is None:
            print('-W- No data found in {}'.format(dir_path))
            return
        if plot_key not in meas_df.columns:
            print('-W- Could not find required data.')
            print('    Try a different plot key.')
            return
        else:
            print('-I- Found {} information, continuing with plotting'.format(plot_key))
        # need to take the data directly from the contribution here, to keep
        # location/site/sample columns in the measurements table
        data = con.tables['measurements'].convert_to_pmag_data_list()
        file_type = "measurements"
    else:
        data, file_type = pmag.magic_read(in_file)
    # read in data
    sids = pmag.get_specs(data)
    pmagplotlib.plot_init(FIG['exp'], 6, 6)
    #
    #
    # find desired intensity data
    #
    # get plotlist
    #
    plotlist = []
    if data_model == 3:
        intlist = ['magn_moment', 'magn_volume', 'magn_mass', 'magnitude']
    else:
        intlist = ['measurement_magnitude', 'measurement_magn_moment',
                    'measurement_magn_volume', 'measurement_magn_mass']
    IntMeths = []
    # get all the records with this lab protocol
    #print('data', len(data))
    #print('data[0]', data[0])
    if data_model == 3:
        data = pmag.get_dictitem(data, 'method_codes', LP, 'has')
    else:
        data = pmag.get_dictitem(data, 'magic_method_codes', LP, 'has')
    Ints = {}
    NoInts, int_key = 1, ""
    for key in intlist:
        # get all non-blank data for intensity type
        Ints[key] = pmag.get_dictitem(data, key, '', 'F')
        if len(Ints[key]) > 0:
            NoInts = 0
            if int_key == "":
                int_key = key
    if NoInts == 1:
        print('No intensity information found')
        sys.exit()
    for rec in Ints[int_key]:
        if rec[plot_key] not in plotlist:
            plotlist.append(rec[plot_key])
    plotlist.sort()
    for plt in plotlist:
        print(plt)
        INTblock = []
        # get data with right intensity info whose plot_key matches plot
        data = pmag.get_dictitem(Ints[int_key], plot_key, plt, 'T')
        # get a list of specimens with appropriate data
        sids = pmag.get_specs(data)
        if len(sids) > 0:
            title = data[0][plot_key]
        for s in sids:
            INTblock = []
            # get data for each specimen
            if data_model == 3:
                sdata = pmag.get_dictitem(data, 'specimen', s, 'T')
            else:
                sdata = pmag.get_dictitem(data, 'er_specimen_name', s, 'T')
            for rec in sdata:
                INTblock.append([float(rec[dmag_key]), 0, 0,
                                 float(rec[int_key]), 1, 'g'])
            pmagplotlib.plot_mag(FIG['exp'], INTblock, title, 0, units, norm)
        files = {}
        for key in list(FIG.keys()):
            files[key] = title + '_' + LP + '.' + fmt
        if plot == 0:
            pmagplotlib.draw_figs(FIG)
            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)
            if plt != plotlist[-1]: # if it isn't the last plot, init the next one
                pmagplotlib.plot_init(FIG['exp'], 6, 6)
        else:
            pmagplotlib.save_plots(FIG, files)
        pmagplotlib.clearFIG(FIG['exp'])
Ejemplo n.º 23
0
def main():
    """
    NAME
        vgpmap_magic.py

    DESCRIPTION
        makes a map of vgps and a95/dp,dm for site means in a pmag_results table

    SYNTAX
        vgpmap_magic.py [command line options]

    OPTIONS
        -h prints help and quits
        -eye  ELAT ELON [specify eyeball location], default is 90., 0.
        -f FILE pmag_results format file, [default is pmag_results.txt]
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -etp plot the etopo20 topographpy data (requires high resolution data set)
        -prj PROJ,  specify one of the following:
             ortho = orthographic
             lcc = lambert conformal
             moll = molweide
             merc = mercator
        -sym SYM SIZE: choose a symbol and size, examples:
            ro 5 : small red circles
            bs 10 : intermediate blue squares
            g^ 20 : large green triangles
        -ell  plot dp/dm or a95 ellipses
        -rev RSYM RSIZE : flip reverse poles to normal antipode
        -S:  plot antipodes of all poles
        -age : plot the ages next to the poles
        -crd [g,t] : choose coordinate system, default is to plot all site VGPs
        -fmt [pdf, png, eps...] specify output format, default is pdf
        -sav  save and quit
    DEFAULTS
        FILE: pmag_results.txt
        res:  c
        prj: ortho
        ELAT,ELON = 0,0
        SYM SIZE: ro 8
        RSYM RSIZE: g^ 8

    """
    dir_path = '.'
    res, ages = 'c', 0
    plot = 0
    proj = 'ortho'
    results_file = 'pmag_results.txt'
    ell, flip = 0, 0
    lat_0, lon_0 = 90., 0.
    fmt = 'pdf'
    sym, size = 'ro', 8
    rsym, rsize = 'g^', 8
    anti = 0
    fancy = 0
    coord = ""
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path = sys.argv[ind+1]
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-S' in sys.argv:
        anti = 1
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind+1]
    if '-sav' in sys.argv:
        plot = 1
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res = sys.argv[ind+1]
    if '-etp' in sys.argv:
        fancy = 1
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj = sys.argv[ind+1]
    if '-rev' in sys.argv:
        flip = 1
        ind = sys.argv.index('-rev')
        rsym = (sys.argv[ind+1])
        rsize = int(sys.argv[ind+2])
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym = (sys.argv[ind+1])
        size = int(sys.argv[ind+2])
    if '-eye' in sys.argv:
        ind = sys.argv.index('-eye')
        lat_0 = float(sys.argv[ind+1])
        lon_0 = float(sys.argv[ind+2])
    if '-ell' in sys.argv:
        ell = 1
    if '-age' in sys.argv:
        ages = 1
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        results_file = sys.argv[ind+1]
    if '-crd' in sys.argv:
        ind = sys.argv.index('-crd')
        crd = sys.argv[ind+1]
        if crd == 'g':
            coord = '0'
        if crd == 't':
            coord = '100'
    results_file = dir_path+'/'+results_file
    data, file_type = pmag.magic_read(results_file)
    if file_type != 'pmag_results':
        print("bad results file")
        sys.exit()
    FIG = {'map': 1}
    pmagplotlib.plot_init(FIG['map'], 6, 6)
    # read in er_sites file
    lats, lons, dp, dm, a95 = [], [], [], [], []
    Pars = []
    dates, rlats, rlons = [], [], []
    if 'data_type' in data[0].keys():
        # get all site level data
        Results = pmag.get_dictitem(data, 'data_type', 'i', 'T')
    else:
        Results = data
    # get all non-blank latitudes
    Results = pmag.get_dictitem(Results, 'vgp_lat', '', 'F')
    # get all non-blank longitudes
    Results = pmag.get_dictitem(Results, 'vgp_lon', '', 'F')
    if coord != "":
        # get specified coordinate system
        Results = pmag.get_dictitem(Results, 'tilt_correction', coord, 'T')
    location = ""
    for rec in Results:
        if rec['er_location_names'] not in location:
            location = location+':'+rec['er_location_names']
        if 'average_age' in rec.keys() and rec['average_age'] != "" and ages == 1:
            dates.append(rec['average_age'])
        lat = float(rec['vgp_lat'])
        lon = float(rec['vgp_lon'])
        if flip == 0:
            lats.append(lat)
            lons.append(lon)
        elif flip == 1:
            if lat < 0:
                rlats.append(-lat)
                lon = lon+180.
                if lon > 360:
                    lon = lon-360.
                rlons.append(lon)
            else:
                lats.append(lat)
                lons.append(lon)
        elif anti == 1:
            lats.append(-lat)
            lon = lon+180.
            if lon > 360:
                lon = lon-360.
            lons.append(lon)
        ppars = []
        ppars.append(lon)
        ppars.append(lat)
        ell1, ell2 = "", ""
        if 'vgp_dm' in rec.keys() and rec['vgp_dm'] != "":
            ell1 = float(rec['vgp_dm'])
        if 'vgp_dp' in rec.keys() and rec['vgp_dp'] != "":
            ell2 = float(rec['vgp_dp'])
        if 'vgp_alpha95' in rec.keys() and rec['vgp_alpha95'] != "":
            ell1, ell2 = float(rec['vgp_alpha95']), float(rec['vgp_alpha95'])
        if ell1 != "" and ell2 != "":
            ppars = []
            ppars.append(lons[-1])
            ppars.append(lats[-1])
            ppars.append(ell1)
            ppars.append(lons[-1])
            isign = abs(lats[-1])/lats[-1]
            ppars.append(lats[-1]-isign*90.)
            ppars.append(ell2)
            ppars.append(lons[-1]+90.)
            ppars.append(0.)
            Pars.append(ppars)
    location = location.strip(':')
    Opts = {'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360., 'lat_0': lat_0, 'lon_0': lon_0,
            'proj': proj, 'sym': 'bs', 'symsize': 3, 'pltgrid': 0, 'res': res, 'boundinglat': 0.}
    Opts['details'] = {'coasts': 1, 'rivers': 0, 'states': 0,
                       'countries': 0, 'ocean': 1, 'fancy': fancy}
    # make the base map with a blue triangle at the pole`
    pmagplotlib.plot_map(FIG['map'], [90.], [0.], Opts)
    Opts['pltgrid'] = -1
    Opts['sym'] = sym
    Opts['symsize'] = size
    if len(dates) > 0:
        Opts['names'] = dates
    if len(lats) > 0:
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], lats, lons, Opts)
    Opts['names'] = []
    if len(rlats) > 0:
        Opts['sym'] = rsym
        Opts['symsize'] = rsize
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], rlats, rlons, Opts)
    if plot == 0:
        pmagplotlib.draw_figs(FIG)
    if ell == 1:  # add ellipses if desired.
        Opts['details'] = {'coasts': 0, 'rivers': 0,
                           'states': 0, 'countries': 0, 'ocean': 0}
        Opts['pltgrid'] = -1  # turn off meridian replotting
        Opts['symsize'] = 2
        Opts['sym'] = 'g-'
        for ppars in Pars:
            if ppars[2] != 0:
                PTS = pmagplotlib.plot_ell(FIG['map'], ppars, 'g.', 0, 0)
                elats, elons = [], []
                for pt in PTS:
                    elons.append(pt[0])
                    elats.append(pt[1])
                # make the base map with a blue triangle at the pole`
                pmagplotlib.plot_map(FIG['map'], elats, elons, Opts)
                if plot == 0:
                    pmagplotlib.draw_figs(FIG)
    files = {}
    for key in FIG.keys():
        if pmagplotlib.isServer:  # use server plot naming convention
            files[key] = 'LO:_'+location+'_VGP_map.'+fmt
        else:  # use more readable plot naming convention
            files[key] = '{}_VGP_map.{}'.format(
                location.replace(' ', '_'), fmt)
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['eq'] = 'LO:_'+location+'_VGP_map'
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    elif plot == 0:
        pmagplotlib.draw_figs(FIG)
        ans = input(" S[a]ve to save plot, Return to quit:  ")
        if ans == "a":
            pmagplotlib.save_plots(FIG, files)
        else:
            print("Good bye")
            sys.exit()
    else:
        pmagplotlib.save_plots(FIG, files)
Ejemplo n.º 24
0
def main():
    """
    NAME
        thellier_magic.py

    DESCRIPTION
        plots Thellier-Thellier, allowing interactive setting of bounds
        and customizing of selection criteria.  Saves and reads interpretations
        from a pmag_specimen formatted table, default: thellier_specimens.txt

    SYNTAX
        thellier_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set magic_measurements input file
        -fsp PRIOR, set pmag_specimen prior interpretations file
        -fan ANIS, set rmag_anisotropy file for doing the anisotropy corrections
        -fcr CRIT, set criteria file for grading.
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (default format)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds adn quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step for slope calculation
           END: ending step for slope calculation
        -z use only z component difference for pTRM calculation

    DEFAULTS
        MEAS: magic_measurements.txt
        REDO: thellier_redo
        CRIT: NONE
        PRIOR: NONE

    OUTPUT
        figures:
            ALL:  numbers refer to temperature steps in command line window
            1) Arai plot:  closed circles are zero-field first/infield
                           open circles are infield first/zero-field
                           triangles are pTRM checks
                           squares are pTRM tail checks
                           VDS is vector difference sum
                           diamonds are bounds for interpretation
            2) Zijderveld plot:  closed (open) symbols are X-Y (X-Z) planes
                                 X rotated to NRM direction
            3) (De/Re)Magnetization diagram:
                           circles are NRM remaining
                           squares are pTRM gained
            4) equal area projections:
               green triangles are pTRM gained direction
                           red (purple) circles are lower(upper) hemisphere of ZI step directions
                           blue (cyan) squares are lower(upper) hemisphere IZ step directions
            5) Optional:  TRM acquisition
            6) Optional: TDS normalization
        command line window:
            list is: temperature step numbers, temperatures (C), Dec, Inc, Int (units of magic_measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates .svg format files with specimen_name, plot type as name
    """
#
#   initializations
#
    meas_file, critout, inspec = "magic_measurements.txt", "", "thellier_specimens.txt"
    first = 1
    inlt = 0
    version_num = pmag.get_version()
    TDinit, Tinit, field, first_save = 0, 0, -1, 1
    user, comment, AniSpec, locname = "", '', "", ""
    ans, specimen, recnum, start, end = 0, 0, 0, 0, 0
    plots, pmag_out, samp_file, style = 0, "", "", "svg"
    verbose = pmagplotlib.verbose
    fmt = '.'+style
#
# default acceptance criteria
#
    accept = pmag.default_criteria(0)[0]  # set the default criteria
#
# parse command line options
#
    Zdiff, anis = 0, 0
    spc, BEG, END = "", "", ""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        meas_file = sys.argv[ind+1]
    if '-fsp' in sys.argv:
        ind = sys.argv.index('-fsp')
        inspec = sys.argv[ind+1]
    if '-fan' in sys.argv:
        ind = sys.argv.index('-fan')
        anisfile = sys.argv[ind+1]
        anis = 1
        anis_data, file_type = pmag.magic_read(anisfile)
        if verbose:
            print("Anisotropy data read in from ", anisfile)
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = '.'+sys.argv[ind+1]
    if '-dpi' in sys.argv:
        ind = sys.argv.index('-dpi')
        dpi = '.'+sys.argv[ind+1]
    else:
        dpi = 100
    if '-sav' in sys.argv:
        plots = 1
        verbose = 0
    if '-z' in sys.argv:
        Zdiff = 1
    if '-spc' in sys.argv:
        ind = sys.argv.index('-spc')
        spc = sys.argv[ind+1]
        if '-b' in sys.argv:
            ind = sys.argv.index('-b')
            BEG = int(sys.argv[ind+1])
            END = int(sys.argv[ind+2])
    if '-fcr' in sys.argv:
        ind = sys.argv.index('-fcr')
        critout = sys.argv[ind+1]
        crit_data, file_type = pmag.magic_read(critout)
        if file_type != 'pmag_criteria':
            if verbose:
                print('bad pmag_criteria file, using no acceptance criteria')
            accept = pmag.default_criteria(1)[0]
        else:
            if verbose:
                print("Acceptance criteria read in from ", critout)
            accept = {'pmag_criteria_code': 'ACCEPTANCE',
                      'er_citation_names': 'This study'}
            for critrec in crit_data:
                if 'sample_int_sigma_uT' in critrec.keys():  # accommodate Shaar's new criterion
                    critrec['sample_int_sigma'] = '%10.3e' % (
                        eval(critrec['sample_int_sigma_uT'])*1e-6)
                for key in critrec.keys():
                    if key not in accept.keys() and critrec[key] != '':
                        accept[key] = critrec[key]
    try:
        open(inspec, 'rU')
        PriorRecs, file_type = pmag.magic_read(inspec)
        if file_type != 'pmag_specimens':
            print(file_type)
            print(file_type, inspec, " is not a valid pmag_specimens file ")
            sys.exit()
        for rec in PriorRecs:
            if 'magic_software_packages' not in rec.keys():
                rec['magic_software_packages'] = ""
    except IOError:
        PriorRecs = []
        if verbose:
            print("starting new specimen interpretation file: ", inspec)
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(file_type)
        print(file_type, "This is not a valid magic_measurements file ")
        sys.exit()
    backup = 0
    # define figure numbers for arai, zijderveld and
    #   de-,re-magization diagrams
    AZD = {}
    AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4
    pmagplotlib.plot_init(AZD['arai'], 5, 5)
    pmagplotlib.plot_init(AZD['zijd'], 5, 5)
    pmagplotlib.plot_init(AZD['deremag'], 5, 5)
    pmagplotlib.plot_init(AZD['eqarea'], 5, 5)
    #
    #
    #
    # get list of unique specimen names
    #
    CurrRec = []
    sids = pmag.get_specs(meas_data)
    # get plots for specimen s - default is just to step through arai diagrams
    #
    if spc != "":
        specimen = sids.index(spc)
    while specimen < len(sids):
        methcodes = []

        if verbose:
            print(sids[specimen], specimen+1, 'of ', len(sids))
        MeasRecs = []
        s = sids[specimen]
        datablock, trmblock, tdsrecs = [], [], []
        PmagSpecRec = {}
        if first == 0:
            for key in keys:
                # make sure all new records have same set of keys
                PmagSpecRec[key] = ""
        PmagSpecRec["er_analyst_mail_names"] = user
        PmagSpecRec["specimen_correction"] = 'u'
    #
    # find the data from the meas_data file for this specimen
    #
        for rec in meas_data:
            if rec["er_specimen_name"] == s:
                MeasRecs.append(rec)
                if "magic_method_codes" not in rec.keys():
                    rec["magic_method_codes"] = ""
                methods = rec["magic_method_codes"].split(":")
                meths = []
                for meth in methods:
                    meths.append(meth.strip())  # take off annoying spaces
                methods = ""
                for meth in meths:
                    if meth.strip() not in methcodes and "LP-" in meth:
                        methcodes.append(meth.strip())
                    methods = methods+meth+":"
                methods = methods[:-1]
                rec["magic_method_codes"] = methods
                if "LP-PI-TRM" in meths:
                    datablock.append(rec)
                if "LP-TRM" in meths:
                    trmblock.append(rec)
                if "LP-TRM-TD" in meths:
                    tdsrecs.append(rec)
        if len(trmblock) > 2 and inspec != "":
            if Tinit == 0:
                Tinit = 1
                AZD['TRM'] = 5
                pmagplotlib.plot_init(AZD['TRM'], 5, 5)
        elif Tinit == 1:  # clear the TRM figure if not needed
            pmagplotlib.clearFIG(AZD['TRM'])
        if len(tdsrecs) > 2:
            if TDinit == 0:
                TDinit = 1
                AZD['TDS'] = 6
                pmagplotlib.plot_init(AZD['TDS'], 5, 5)
        elif TDinit == 1:  # clear the TDS figure if not needed
            pmagplotlib.clearFIG(AZD['TDS'])
        if len(datablock) < 4:
            if backup == 0:
                specimen += 1
                if verbose:
                    print('skipping specimen - moving forward ', s)
            else:
                specimen -= 1
                if verbose:
                    print('skipping specimen - moving backward ', s)
    #
    #  collect info for the PmagSpecRec dictionary
    #
        else:
            rec = datablock[0]
            PmagSpecRec["er_citation_names"] = "This study"
            PmagSpecRec["er_specimen_name"] = s
            PmagSpecRec["er_sample_name"] = rec["er_sample_name"]
            PmagSpecRec["er_site_name"] = rec["er_site_name"]
            PmagSpecRec["er_location_name"] = rec["er_location_name"]
            locname = rec['er_location_name'].replace('/', '-')
            if "er_expedition_name" in rec.keys():
                PmagSpecRec["er_expedition_name"] = rec["er_expedition_name"]
            if "magic_instrument_codes" not in rec.keys():
                rec["magic_instrument_codes"] = ""
            PmagSpecRec["magic_instrument_codes"] = rec["magic_instrument_codes"]
            PmagSpecRec["measurement_step_unit"] = "K"
            if "magic_experiment_name" not in rec.keys():
                rec["magic_experiment_name"] = ""
            else:
                PmagSpecRec["magic_experiment_names"] = rec["magic_experiment_name"]

            meths = rec["magic_method_codes"].split()
        # sort data into types
            araiblock, field = pmag.sortarai(datablock, s, Zdiff)
            first_Z = araiblock[0]
            GammaChecks = araiblock[5]
            if len(first_Z) < 3:
                if backup == 0:
                    specimen += 1
                    if verbose:
                        print('skipping specimen - moving forward ', s)
                else:
                    specimen -= 1
                    if verbose:
                        print('skipping specimen - moving backward ', s)
            else:
                backup = 0
                zijdblock, units = pmag.find_dmag_rec(s, meas_data)
                recnum = 0
                if verbose:
                    print("index step Dec   Inc  Int       Gamma")
                    for plotrec in zijdblock:
                        if GammaChecks != "":
                            gamma = ""
                            for g in GammaChecks:
                                if g[0] == plotrec[0]-273:
                                    gamma = g[1]
                                    break
                        if gamma != "":
                            print('%i     %i %7.1f %7.1f %8.3e %7.1f' % (
                                recnum, plotrec[0]-273, plotrec[1], plotrec[2], plotrec[3], gamma))
                        else:
                            print('%i     %i %7.1f %7.1f %8.3e ' % (
                                recnum, plotrec[0]-273, plotrec[1], plotrec[2], plotrec[3]))
                        recnum += 1
                pmagplotlib.plot_arai_zij(AZD, araiblock, zijdblock, s, units[0])
                if verbose:
                    pmagplotlib.draw_figs(AZD)
                if len(tdsrecs) > 2:  # a TDS experiment
                    tdsblock = []  # make a list for the TDS  data
                    Mkeys = ['measurement_magnitude', 'measurement_magn_moment',
                             'measurement_magn_volume', 'measuruement_magn_mass']
                    mkey, k = "", 0
                    # find which type of intensity
                    while mkey == "" and k < len(Mkeys)-1:
                        key = Mkeys[k]
                        if key in tdsrecs[0].keys() and tdsrecs[0][key] != "":
                            mkey = key
                        k += 1
                    if mkey == "":
                        break  # get outta here
                    Tnorm = ""
                    for tdrec in tdsrecs:
                        meths = tdrec['magic_method_codes'].split(":")
                        for meth in meths:
                            # strip off potential nasty spaces
                            meth.replace(" ", "")
                        if 'LT-T-I' in meths and Tnorm == "":  # found first total TRM
                            # normalize by total TRM
                            Tnorm = float(tdrec[mkey])
                            # put in the zero step
                            tdsblock.append([273, zijdblock[0][3]/Tnorm, 1.])
                        # found a LP-TRM-TD demag step, now need complementary LT-T-Z from zijdblock
                        if 'LT-T-Z' in meths and Tnorm != "":
                            step = float(tdrec['treatment_temp'])
                            Tint = ""
                            if mkey != "":
                                Tint = float(tdrec[mkey])
                            if Tint != "":
                                for zrec in zijdblock:
                                    if zrec[0] == step:  # found matching
                                        tdsblock.append(
                                            [step, zrec[3]/Tnorm, Tint/Tnorm])
                                        break
                    if len(tdsblock) > 2:
                        pmagplotlib.plot_tds(
                            AZD['TDS'], tdsblock, s+':LP-PI-TDS:')
                        if verbose:
                            pmagplotlib(draw_figs(AZD))
                    else:
                        print("Something wrong here")
                if anis == 1:   # look up anisotropy data for this specimen
                    AniSpec = ""
                    for aspec in anis_data:
                        if aspec["er_specimen_name"] == PmagSpecRec["er_specimen_name"]:
                            AniSpec = aspec
                            if verbose:
                                print('Found anisotropy record...')
                            break
                if inspec != "":
                    if verbose:
                        print('Looking up saved interpretation....')
                    found = 0
                    for k in range(len(PriorRecs)):
                        try:
                            if PriorRecs[k]["er_specimen_name"] == s:
                                found = 1
                                CurrRec.append(PriorRecs[k])
                                for j in range(len(zijdblock)):
                                    if float(zijdblock[j][0]) == float(PriorRecs[k]["measurement_step_min"]):
                                        start = j
                                    if float(zijdblock[j][0]) == float(PriorRecs[k]["measurement_step_max"]):
                                        end = j
                                pars, errcode = pmag.PintPars(
                                    datablock, araiblock, zijdblock, start, end, accept)
                                pars['measurement_step_unit'] = "K"
                                pars['experiment_type'] = 'LP-PI-TRM'
                                # put in CurrRec, take out of PriorRecs
                                del PriorRecs[k]
                                if errcode != 1:
                                    pars["specimen_lab_field_dc"] = field
                                    pars["specimen_int"] = -1 * \
                                        field*pars["specimen_b"]
                                    pars["er_specimen_name"] = s
                                    if verbose:
                                        print('Saved interpretation: ')
                                    pars, kill = pmag.scoreit(
                                        pars, PmagSpecRec, accept, '', verbose)
                                    pmagplotlib.plot_b(
                                        AZD, araiblock, zijdblock, pars)
                                    if verbose:
                                        pmagplotlib.draw_figs(AZD)
                                    if len(trmblock) > 2:
                                        blab = field
                                        best = pars["specimen_int"]
                                        Bs, TRMs = [], []
                                        for trec in trmblock:
                                            Bs.append(
                                                float(trec['treatment_dc_field']))
                                            TRMs.append(
                                                float(trec['measurement_magn_moment']))
                                        # calculate best fit parameters through TRM acquisition data, and get new banc
                                        NLpars = nlt.NLtrm(
                                            Bs, TRMs, best, blab, 0)
                                        Mp, Bp = [], []
                                        for k in range(int(max(Bs)*1e6)):
                                            Bp.append(float(k)*1e-6)
                                            # predicted NRM for this field
                                            npred = nlt.TRM(
                                                Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1])
                                            Mp.append(npred)
                                        pmagplotlib.plot_trm(
                                            AZD['TRM'], Bs, TRMs, Bp, Mp, NLpars, trec['magic_experiment_name'])
                                        PmagSpecRec['specimen_int'] = NLpars['banc']
                                        if verbose:
                                            print('Banc= ', float(
                                                NLpars['banc'])*1e6)
                                            pmagplotlib.draw_figs(AZD)
                                    mpars = pmag.domean(
                                        araiblock[1], start, end, 'DE-BFL')
                                    if verbose:
                                        print('pTRM direction= ', '%7.1f' % (mpars['specimen_dec']), ' %7.1f' % (
                                            mpars['specimen_inc']), ' MAD:', '%7.1f' % (mpars['specimen_mad']))
                                    if AniSpec != "":
                                        CpTRM = pmag.Dir_anis_corr(
                                            [mpars['specimen_dec'], mpars['specimen_inc']], AniSpec)
                                        AniSpecRec = pmag.doaniscorr(
                                            PmagSpecRec, AniSpec)
                                        if verbose:
                                            print('Anisotropy corrected TRM direction= ', '%7.1f' % (
                                                CpTRM[0]), ' %7.1f' % (CpTRM[1]))
                                            print('Anisotropy corrected intensity= ', float(
                                                AniSpecRec['specimen_int'])*1e6)
                                else:
                                    print('error on specimen ', s)
                        except:
                            pass
                    if verbose and found == 0:
                        print('    None found :(  ')
                if spc != "":
                    if BEG != "":
                        pars, errcode = pmag.PintPars(
                            datablock, araiblock, zijdblock, BEG, END, accept)
                        pars['measurement_step_unit'] = "K"
                        pars["specimen_lab_field_dc"] = field
                        pars["specimen_int"] = -1*field*pars["specimen_b"]
                        pars["er_specimen_name"] = s
                        pars['specimen_grade'] = ''  # ungraded
                        pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                        if verbose:
                            pmagplotlib.draw_figs(AZD)
                        if len(trmblock) > 2:
                            if inlt == 0:
                                inlt = 1
                            blab = field
                            best = pars["specimen_int"]
                            Bs, TRMs = [], []
                            for trec in trmblock:
                                Bs.append(float(trec['treatment_dc_field']))
                                TRMs.append(
                                    float(trec['measurement_magn_moment']))
                            # calculate best fit parameters through TRM acquisition data, and get new banc
                            NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0)
    #
                            Mp, Bp = [], []
                            for k in range(int(max(Bs)*1e6)):
                                Bp.append(float(k)*1e-6)
                                # predicted NRM for this field
                                npred = nlt.TRM(
                                    Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1])
                    files = {}
                    for key in AZD.keys():
                        files[key] = s+'_'+key+fmt
                    pmagplotlib.save_plots(AZD, files, dpi=dpi)
                    sys.exit()
                if verbose:
                    ans = 'b'
                    while ans != "":
                        print("""
               s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit:
               """)
                        ans = input('Return for next specimen \n')
                        if ans == "":
                            specimen += 1
                        if ans == "d":
                            save_redo(PriorRecs, inspec)
                            CurrRec = []
                            pmagplotlib.plot_arai_zij(
                                AZD, araiblock, zijdblock, s, units[0])
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                        if ans == 'a':
                            files = {}
                            for key in AZD.keys():
                                files[key] = "LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name'] + \
                                    '_SA:_' + \
                                    PmagSpecRec['er_sample_name'] + \
                                    '_SP:_'+s+'_CO:_s_TY:_'+key+fmt
                            pmagplotlib.save_plots(AZD, files)
                            ans = ""
                        if ans == 'q':
                            print("Good bye")
                            sys.exit()
                        if ans == 'p':
                            specimen = specimen - 1
                            backup = 1
                            ans = ""
                        if ans == 's':
                            keepon = 1
                            spec = input(
                                'Enter desired specimen name (or first part there of): ')
                            while keepon == 1:
                                try:
                                    specimen = sids.index(spec)
                                    keepon = 0
                                except:
                                    tmplist = []
                                    for qq in range(len(sids)):
                                        if spec in sids[qq]:
                                            tmplist.append(sids[qq])
                                    print(specimen, " not found, but this was: ")
                                    print(tmplist)
                                    spec = input('Select one or try again\n ')
                            ans = ""
                        if ans == 'b':
                            if end == 0 or end >= len(zijdblock):
                                end = len(zijdblock)-1
                            GoOn = 0
                            while GoOn == 0:
                                answer = input(
                                    'Enter index of first point for calculation: ['+str(start)+']  ')
                                try:
                                    start = int(answer)
                                    answer = input(
                                        'Enter index  of last point for calculation: ['+str(end)+']  ')
                                    end = int(answer)
                                    if start >= 0 and start < len(zijdblock)-2 and end > 0 and end < len(zijdblock) or start >= end:
                                        GoOn = 1
                                    else:
                                        print("Bad endpoints - try again! ")
                                        start, end = 0, len(zijdblock)
                                except ValueError:
                                    print("Bad endpoints - try again! ")
                                    start, end = 0, len(zijdblock)
                            s = sids[specimen]
                            pars, errcode = pmag.PintPars(
                                datablock, araiblock, zijdblock, start, end, accept)
                            pars['measurement_step_unit'] = "K"
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1*field*pars["specimen_b"]
                            pars["er_specimen_name"] = s
                            pars, kill = pmag.scoreit(
                                pars, PmagSpecRec, accept, '', 0)
                            PmagSpecRec['specimen_scat'] = pars['specimen_scat']
                            PmagSpecRec['specimen_frac'] = '%5.3f' % (
                                pars['specimen_frac'])
                            PmagSpecRec['specimen_gmax'] = '%5.3f' % (
                                pars['specimen_gmax'])
                            PmagSpecRec["measurement_step_min"] = '%8.3e' % (
                                pars["measurement_step_min"])
                            PmagSpecRec["measurement_step_max"] = '%8.3e' % (
                                pars["measurement_step_max"])
                            PmagSpecRec["measurement_step_unit"] = "K"
                            PmagSpecRec["specimen_int_n"] = '%i' % (
                                pars["specimen_int_n"])
                            PmagSpecRec["specimen_lab_field_dc"] = '%8.3e' % (
                                pars["specimen_lab_field_dc"])
                            PmagSpecRec["specimen_int"] = '%9.4e ' % (
                                pars["specimen_int"])
                            PmagSpecRec["specimen_b"] = '%5.3f ' % (
                                pars["specimen_b"])
                            PmagSpecRec["specimen_q"] = '%5.1f ' % (
                                pars["specimen_q"])
                            PmagSpecRec["specimen_f"] = '%5.3f ' % (
                                pars["specimen_f"])
                            PmagSpecRec["specimen_fvds"] = '%5.3f' % (
                                pars["specimen_fvds"])
                            PmagSpecRec["specimen_b_beta"] = '%5.3f' % (
                                pars["specimen_b_beta"])
                            PmagSpecRec["specimen_int_mad"] = '%7.1f' % (
                                pars["specimen_int_mad"])
                            PmagSpecRec["specimen_Z"] = '%7.1f' % (
                                pars["specimen_Z"])
                            PmagSpecRec["specimen_gamma"] = '%7.1f' % (
                                pars["specimen_gamma"])
                            PmagSpecRec["specimen_grade"] = pars["specimen_grade"]
                            if pars["method_codes"] != "":
                                tmpcodes = pars["method_codes"].split(":")
                                for t in tmpcodes:
                                    if t.strip() not in methcodes:
                                        methcodes.append(t.strip())
                            PmagSpecRec["specimen_dec"] = '%7.1f' % (
                                pars["specimen_dec"])
                            PmagSpecRec["specimen_inc"] = '%7.1f' % (
                                pars["specimen_inc"])
                            PmagSpecRec["specimen_tilt_correction"] = '-1'
                            PmagSpecRec["specimen_direction_type"] = 'l'
                            # this is redundant, but helpful - won't be imported
                            PmagSpecRec["direction_type"] = 'l'
                            PmagSpecRec["specimen_int_dang"] = '%7.1f ' % (
                                pars["specimen_int_dang"])
                            PmagSpecRec["specimen_drats"] = '%7.1f ' % (
                                pars["specimen_drats"])
                            PmagSpecRec["specimen_drat"] = '%7.1f ' % (
                                pars["specimen_drat"])
                            PmagSpecRec["specimen_int_ptrm_n"] = '%i ' % (
                                pars["specimen_int_ptrm_n"])
                            PmagSpecRec["specimen_rsc"] = '%6.4f ' % (
                                pars["specimen_rsc"])
                            PmagSpecRec["specimen_md"] = '%i ' % (
                                int(pars["specimen_md"]))
                            if PmagSpecRec["specimen_md"] == '-1':
                                PmagSpecRec["specimen_md"] = ""
                            PmagSpecRec["specimen_b_sigma"] = '%5.3f ' % (
                                pars["specimen_b_sigma"])
                            if "IE-TT" not in methcodes:
                                methcodes.append("IE-TT")
                            methods = ""
                            for meth in methcodes:
                                methods = methods+meth+":"
                            PmagSpecRec["magic_method_codes"] = methods[:-1]
                            PmagSpecRec["specimen_description"] = comment
                            PmagSpecRec["magic_software_packages"] = version_num
                            pmagplotlib.plot_arai_zij(
                                AZD, araiblock, zijdblock, s, units[0])
                            pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                            if len(trmblock) > 2:
                                blab = field
                                best = pars["specimen_int"]
                                Bs, TRMs = [], []
                                for trec in trmblock:
                                    Bs.append(
                                        float(trec['treatment_dc_field']))
                                    TRMs.append(
                                        float(trec['measurement_magn_moment']))
                                # calculate best fit parameters through TRM acquisition data, and get new banc
                                NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0)
                                Mp, Bp = [], []
                                for k in range(int(max(Bs)*1e6)):
                                    Bp.append(float(k)*1e-6)
                                    # predicted NRM for this field
                                    npred = nlt.TRM(
                                        Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1])
                                    Mp.append(npred)
                                pmagplotlib.plot_trm(
                                    AZD['TRM'], Bs, TRMs, Bp, Mp, NLpars, trec['magic_experiment_name'])
                                if verbose:
                                    print(
                                        'Non-linear TRM corrected intensity= ', float(NLpars['banc'])*1e6)
                            if verbose:
                                pmagplotlib.draw_figs(AZD)
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1*field*pars["specimen_b"]
                            pars, kill = pmag.scoreit(
                                pars, PmagSpecRec, accept, '', verbose)
                            saveit = input(
                                "Save this interpretation? [y]/n \n")
                            if saveit != 'n':
                                # put back an interpretation
                                PriorRecs.append(PmagSpecRec)
                                specimen += 1
                                save_redo(PriorRecs, inspec)
                            ans = ""
                elif plots == 1:
                    specimen += 1
                    if fmt != ".pmag":
                        files = {}
                        for key in AZD.keys():
                            files[key] = "LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name']+'_SA:_' + \
                                PmagSpecRec['er_sample_name'] + \
                                '_SP:_'+s+'_CO:_s_TY:_'+key+'_'+fmt
                        if pmagplotlib.isServer:
                            black = '#000000'
                            purple = '#800080'
                            titles = {}
                            titles['deremag'] = 'DeReMag Plot'
                            titles['zijd'] = 'Zijderveld Plot'
                            titles['arai'] = 'Arai Plot'
                            AZD = pmagplotlib.add_borders(
                                AZD, titles, black, purple)
                        pmagplotlib.save_plots(AZD, files, dpi=dpi)
    #                   pmagplotlib.combineFigs(s,files,3)
                    else:  # save in pmag format
                        script = "grep "+s+" output.mag | thellier -mfsi"
                        script = script+' %8.4e' % (field)
                        min = '%i' % ((pars["measurement_step_min"]-273))
                        Max = '%i' % ((pars["measurement_step_max"]-273))
                        script = script+" "+min+" "+Max
                        script = script+" |plotxy;cat mypost >>thellier.ps\n"
                        pltf.write(script)
                        pmag.domagicmag(outf, MeasRecs)
        if len(CurrRec) > 0:
            for rec in CurrRec:
                PriorRecs.append(rec)
        CurrRec = []
    if plots != 1 and verbose:
        ans = input(" Save last plot? 1/[0] ")
        if ans == "1":
            if fmt != ".pmag":
                files = {}
                for key in AZD.keys():
                    files[key] = s+'_'+key+fmt
                pmagplotlib.save_plots(AZD, files, dpi=dpi)
        else:
            print("\n Good bye\n")
            sys.exit()
        if len(CurrRec) > 0:
            PriorRecs.append(CurrRec)  # put back an interpretation
        if len(PriorRecs) > 0:
            save_redo(PriorRecs, inspec)
            print('Updated interpretations saved in ', inspec)
    if verbose:
        print("Good bye")
Ejemplo n.º 25
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)
Ejemplo n.º 26
0
def main():
    """
    NAME
        quick_hyst.py

    DESCRIPTION
        makes plots of hysteresis data

    SYNTAX
        quick_hyst.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f: specify input file, default is measurements.txt
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args = sys.argv
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    plots = 0
    pltspec = ""
    verbose = pmagplotlib.verbose
    #version_num = pmag.get_version()
    dir_path = pmag.get_named_arg('-WD', '.')
    dir_path = os.path.realpath(dir_path)
    meas_file = pmag.get_named_arg('-f', 'measurements.txt')
    fmt = pmag.get_named_arg('-fmt', 'png')
    if '-sav' in args:
        verbose = 0
        plots = 1
    if '-spc' in args:
        ind = args.index("-spc")
        pltspec = args[ind + 1]
        verbose = 0
        plots = 1
    #
    con = cb.Contribution(dir_path,
                          read_tables=['measurements'],
                          custom_filenames={'measurements': meas_file})
    # get as much name data as possible (used for naming plots)
    if not 'measurements' in con.tables:
        print("-W- No measurement file found")
        return
    con.propagate_location_to_measurements()

    if 'measurements' not in con.tables:
        print(main.__doc__)
        print('bad file')
        sys.exit()
    meas_container = con.tables['measurements']
    #meas_df = meas_container.df

    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs = []
    HDD = {}
    HDD['hyst'] = 1
    pmagplotlib.plot_init(HDD['hyst'], 5, 5)
    #
    # get list of unique experiment names and specimen names
    #
    sids = []
    hyst_data = meas_container.get_records_for_code('LP-HYS')
    #experiment_names = hyst_data['experiment_name'].unique()
    if not len(hyst_data):
        print("-W- No hysteresis data found")
        return
    sids = hyst_data['specimen'].unique()

    # if 'treat_temp' is provided, use that value, otherwise assume 300
    hyst_data['treat_temp'].where(hyst_data['treat_temp'].notnull(),
                                  '300',
                                  inplace=True)
    # start at first specimen, or at provided specimen ('-spc')
    k = 0
    if pltspec != "":
        try:
            print(sids)
            k = list(sids).index(pltspec)
        except ValueError:
            print('-W- No specimen named: {}.'.format(pltspec))
            print('-W- Please provide a valid specimen name')
            return
    intlist = ['magn_moment', 'magn_volume', 'magn_mass']

    while k < len(sids):
        locname, site, sample, synth = '', '', '', ''
        s = sids[k]
        if verbose:
            print(s, k + 1, 'out of ', len(sids))
        # B, M for hysteresis, Bdcd,Mdcd for irm-dcd data
        B, M = [], []
        # get all measurements for this specimen
        spec = hyst_data[hyst_data['specimen'] == s]
        # get names
        if 'location' in spec:
            locname = spec['location'].iloc[0]
        if 'site' in spec:
            site = spec['sample'].iloc[0]
        if 'sample' in spec:
            sample = spec['sample'].iloc[0]
        # get all records with non-blank values in any intlist column
        # find intensity data
        for int_column in intlist:
            if int_column in spec.columns:
                int_col = int_column
                break
        meas_data = spec[spec[int_column].notnull()]
        if len(meas_data) == 0:
            break
        #
        c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-']
        cnum = 0
        Temps = []
        xlab, ylab, title = '', '', ''
        Temps = meas_data['treat_temp'].unique()
        for t in Temps:
            print('working on t: ', t)
            t_data = meas_data[meas_data['treat_temp'] == t]
            m = int_col
            B = t_data['meas_field_dc'].astype(float).values
            M = t_data[m].astype(float).values
            # now plot the hysteresis curve(s)
            #
            if len(B) > 0:
                B = numpy.array(B)
                M = numpy.array(M)
                if t == Temps[-1]:
                    xlab = 'Field (T)'
                    ylab = m
                    title = 'Hysteresis: ' + s
                if t == Temps[0]:
                    pmagplotlib.clearFIG(HDD['hyst'])
                pmagplotlib.plot_xy(HDD['hyst'],
                                    B,
                                    M,
                                    sym=c[cnum],
                                    xlab=xlab,
                                    ylab=ylab,
                                    title=title)
                pmagplotlib.plot_xy(HDD['hyst'],
                                    [1.1 * B.min(), 1.1 * B.max()], [0, 0],
                                    sym='k-',
                                    xlab=xlab,
                                    ylab=ylab,
                                    title=title)
                pmagplotlib.plot_xy(HDD['hyst'], [0, 0],
                                    [1.1 * M.min(), 1.1 * M.max()],
                                    sym='k-',
                                    xlab=xlab,
                                    ylab=ylab,
                                    title=title)
                if verbose and not set_env.IS_WIN:
                    pmagplotlib.draw_figs(HDD)
                cnum += 1
                if cnum == len(c):
                    cnum = 0

#
        files = {}
        if plots:
            if pltspec != "":
                s = pltspec
            for key in list(HDD.keys()):
                if pmagplotlib.isServer:
                    if synth == '':
                        files[
                            key] = "LO:_" + locname + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + s + '_TY:_' + key + '_.' + fmt
                    else:
                        files[
                            key] = 'SY:_' + synth + '_TY:_' + key + '_.' + fmt
                else:
                    if synth == '':
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename
                    else:
                        files[key] = "{}_{}.{}".format(synth, key, fmt)

            pmagplotlib.save_plots(HDD, files)
            if pltspec != "":
                sys.exit()
        if verbose:
            pmagplotlib.draw_figs(HDD)
            ans = input(
                "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n "
            )
            if ans == "a":
                files = {}
                for key in list(HDD.keys()):
                    if pmagplotlib.isServer:  # use server plot naming convention
                        files[
                            key] = "LO:_" + locname + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + s + '_TY:_' + key + '_.' + fmt
                    else:  # use more readable plot naming convention
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename

                pmagplotlib.save_plots(HDD, files)
            if ans == '':
                k += 1
            if ans == "p":
                del HystRecs[-1]
                k -= 1
            if ans == 'q':
                print("Good bye")
                sys.exit()
            if ans == 's':
                keepon = 1
                specimen = input(
                    'Enter desired specimen name (or first part there of): ')
                while keepon == 1:
                    try:
                        k = sids.index(specimen)
                        keepon = 0
                    except:
                        tmplist = []
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:
                                tmplist.append(sids[qq])
                        print(specimen, " not found, but this was: ")
                        print(tmplist)
                        specimen = input('Select one or try again\n ')
                        k = sids.index(specimen)
        else:
            k += 1
        if len(B) == 0:
            if verbose:
                print('skipping this one - no hysteresis data')
            k += 1
Ejemplo n.º 27
0
def main():
    """
    NAME
        lnp_magic.py

    DESCRIPTION
       makes equal area projections site by site
         from specimen formatted file with
         Fisher confidence ellipse using McFadden and McElhinny (1988)
         technique for combining lines and planes

    SYNTAX
        lnp_magic [command line options]

    INPUT
       takes magic formatted specimens file

    OUPUT
        prints site_name n_lines n_planes K alpha95 dec inc R

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is 'specimens.txt', ('pmag_specimens.txt' for legacy data model 2)
        -fsa FILE: specify samples file, required to plot by site for data model 3 (otherwise will plot by sample)
                default is 'samples.txt'
        -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted
                default is specimen
        -fmt [svg,png,jpg] format for plots, default is svg
        -sav save plots and quit
        -P: do not plot
        -F FILE, specify output file of dec, inc, alpha95 data for plotting with plotdi_a and plotdi_e
        -exc use criteria in criteria table # NOT IMPLEMENTED
        -DM NUMBER MagIC data model (2 or 3, default 3)
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", ".")
    data_model = int(float(pmag.get_named_arg("-DM", 3)))
    fmt = pmag.get_named_arg("-fmt", 'svg')
    if data_model == 2:
        in_file = pmag.get_named_arg('-f', 'pmag_specimens.txt')
        crit_file = "pmag_criteria.txt"
    else:
        in_file = pmag.get_named_arg('-f', 'specimens.txt')
        samp_file = pmag.get_named_arg('-fsa', 'samples.txt')
        crit_file = "criteria.txt"
    in_file = pmag.resolve_file_name(in_file, dir_path)
    dir_path = os.path.split(in_file)[0]
    if data_model == 3:
        samp_file = pmag.resolve_file_name(samp_file, dir_path)
    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"
    else:
        coord = "-1"


    out_file = pmag.get_named_arg('-F', '')
    if out_file:
        out = open(dir_path+'/'+out_file, 'w')
    if '-P' in sys.argv:
        make_plots = 0  # do not plot
    else:
        make_plots = 1  # do plot
    if '-sav' in sys.argv:
        plot = 1  # save plots and quit
    else:
        plot = 0 # show plots intereactively (if make_plots)
#


    if data_model == 2:
        Specs, file_type = pmag.magic_read(in_file)
        if 'specimens' not in file_type:
            print('Error opening ', in_file, file_type)
            sys.exit()
    else:
        fnames = {'specimens': in_file, 'samples': samp_file}
        con = cb.Contribution(dir_path, read_tables=['samples', 'specimens'],
                              custom_filenames=fnames)
        con.propagate_name_down('site', 'specimens')
        if 'site' in con.tables['specimens'].df.columns:
            site_col = 'site'
        else:
            site_col = 'sample'
        tilt_corr_col = "dir_tilt_correction"
        mad_col = "dir_mad_free"
        alpha95_col = "dir_alpha95"
        site_alpha95_col = "dir_alpha95"
        dec_col = "dir_dec"
        inc_col = "dir_inc"
        num_meas_col = "dir_n_measurements"
        k_col = "dir_k"
        cols = [site_col, tilt_corr_col, mad_col, alpha95_col, dec_col, inc_col]
        con.tables['specimens'].front_and_backfill(cols)
        con.tables['specimens'].df = con.tables['specimens'].df.where(con.tables['specimens'].df.notnull(), "")
        Specs = con.tables['specimens'].convert_to_pmag_data_list()


    ## using criteria file was never fully implemented
    #if '-exc' in sys.argv:
    #    Crits, file_type = pmag.magic_read(pmag.resolve_file_name(crit_file, dir_path))
    #    for crit in Crits:
    #        if mad_col in crit:
    #            M = float(crit['specimen_mad'])
    #        if num_meas_col in crit:
    #            N = float(crit['specimen_n'])
    #        if site_alpha95_col in crit and 'site' in crit:
    #            acutoff = float(crit['site_alpha95'])
    #        if k_col in crit:
    #            kcutoff = float(crit['site_k'])
    #else:
    #    Crits = ""

    sitelist = []

    # initialize some variables
    FIG = {}  # plot dictionary
    FIG['eqarea'] = 1  # eqarea is figure 1
    M, N, acutoff, kcutoff = 180., 1, 180., 0.

    if data_model == 2:
        site_col = 'er_site_name'
        tilt_corr_col = "specimen_tilt_correction"
        mad_col = "specimen_mad"
        alpha95_col = 'specimen_alpha95'
        dec_col = "specimen_dec"
        inc_col = "specimen_inc"
        num_meas_col = "specimen_n"
        site_alpha95_col = "site_alpha95"
    else: # data model 3
        pass

    for rec in Specs:
        if rec[site_col] not in sitelist:
            sitelist.append(rec[site_col])
    sitelist.sort()
    if make_plots == 1:
        EQ = {}
        EQ['eqarea'] = 1
    for site in sitelist:
        pmagplotlib.plot_init(EQ['eqarea'], 4, 4)
        print(site)
        data = []
        for spec in Specs:
            if tilt_corr_col not in list(spec.keys()):
                spec[tilt_corr_col] = '-1'  # assume unoriented
            if spec[site_col] == site:
                if mad_col not in list(spec.keys()) or spec[mad_col] == "":
                    if alpha95_col in list(spec.keys()) and spec[alpha95_col] != "":
                        spec[mad_col] = spec[alpha95_col]
                    else:
                        spec[mad_col] = '180'
                if not spec[num_meas_col]:
                    continue
                if (float(spec[tilt_corr_col]) == float(coord)) and (float(spec[mad_col]) <= M) and (float(spec[num_meas_col]) >= N):
                    rec = {}
                    for key in list(spec.keys()):
                        rec[key] = spec[key]
                    rec["dec"] = float(spec[dec_col])
                    rec["inc"] = float(spec[inc_col])
                    rec["tilt_correction"] = spec[tilt_corr_col]
                    data.append(rec)
        if len(data) > 2:
            fpars = pmag.dolnp(data, 'specimen_direction_type')
            print("Site lines planes  kappa   a95   dec   inc")
            print(site, fpars["n_lines"], fpars["n_planes"], fpars["K"],
                  fpars["alpha95"], fpars["dec"], fpars["inc"], fpars["R"])
            if out_file != "":
                if float(fpars["alpha95"]) <= acutoff and float(fpars["K"]) >= kcutoff:
                    out.write('%s %s %s\n' %
                              (fpars["dec"], fpars['inc'], fpars['alpha95']))
            print('% tilt correction: ', coord)
            if make_plots == 1:
                files = {}
                files['eqarea'] = site+'_'+crd+'_'+'eqarea'+'.'+fmt
                pmagplotlib.plot_lnp(EQ['eqarea'], site,
                                    data, fpars, 'specimen_direction_type')
                if plot == 0:
                    pmagplotlib.draw_figs(EQ)
                    ans = input(
                        "s[a]ve plot, [q]uit, <return> to continue:\n ")
                    if ans == "a":
                        pmagplotlib.save_plots(EQ, files)
                    if ans == "q":
                        sys.exit()
                else:
                    pmagplotlib.save_plots(EQ, files)
        else:
            print('skipping site - not enough data with specified coordinate system')
Ejemplo n.º 28
0
def main():
    """
    NAME
       common_mean.py

    DESCRIPTION
       calculates bootstrap statistics to test for common mean

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files
   
    SYNTAX
       common_mean.py [command line options]
    
    OPTIONS
       -h prints help message and quits
       -f FILE, input file 
       -f2 FILE, optional second file to compare with first file
       -dir D I, optional direction to compare with input file
       -fmt [svg,jpg,pnd,pdf] set figure format [default is svg]
    NOTES
       must have either F2 OR dir but not both
     

    """
    d,i,file2="","",""
    fmt,plot='svg',0
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    if '-sav' in sys.argv: plot=1
    if '-fmt'  in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file1=sys.argv[ind+1]
    if '-f2' in sys.argv:
        ind=sys.argv.index('-f2')
        file2=sys.argv[ind+1]
    if '-dir' in sys.argv:
        ind=sys.argv.index('-dir')
        d=float(sys.argv[ind+1])
        i=float(sys.argv[ind+2])
    D1=numpy.loadtxt(file1,dtype=numpy.float)
    if file2!="": D2=numpy.loadtxt(file2,dtype=numpy.float)
#
    counter,NumSims=0,1000
#
# get bootstrapped means for first data set
#
    print("Doing first set of directions, please be patient..")
    BDI1=pmag.di_boot(D1)
#
#   convert to cartesian coordinates X1,X2, Y1,Y2 and Z1, Z2
#
    if d=="": # repeat for second data set
        print("Doing second  set of directions, please be patient..")
        BDI2=pmag.di_boot(D2)
    else:
        BDI2=[]
# set up plots
    CDF={'X':1,'Y':2,'Z':3}
    pmagplotlib.plot_init(CDF['X'],4,4)
    pmagplotlib.plot_init(CDF['Y'],4,4)
    pmagplotlib.plot_init(CDF['Z'],4,4)
# draw the cdfs
    pmagplotlib.plot_com(CDF,BDI1,BDI2,[d,i])
    files={}
    files['X']='CD_X.'+fmt
    files['Y']='CD_Y.'+fmt
    files['Z']='CD_Z.'+fmt
    if plot==0:
        pmagplotlib.draw_figs(CDF)
        ans=input("S[a]ve plots, <Return> to quit ")
        if ans=="a":
            pmagplotlib.save_plots(CDF,files)
        else:
            sys.exit()
        
    else: 
        pmagplotlib.save_plots(CDF,files)
        sys.exit()
Ejemplo n.º 29
0
def main():
    """
    NAME
        vgpmap_magic.py

    DESCRIPTION
        makes a map of vgps and a95/dp,dm for site means in a pmag_results table

    SYNTAX
        vgpmap_magic.py [command line options]

    OPTIONS
        -h prints help and quits
        -eye  ELAT ELON [specify eyeball location], default is 90., 0.
        -f FILE pmag_results format file, [default is pmag_results.txt]
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -etp plot the etopo20 topographpy data (requires high resolution data set)
        -prj PROJ,  specify one of the following:
             ortho = orthographic
             lcc = lambert conformal
             moll = molweide
             merc = mercator
        -sym SYM SIZE: choose a symbol and size, examples:
            ro 5 : small red circles
            bs 10 : intermediate blue squares
            g^ 20 : large green triangles
        -ell  plot dp/dm or a95 ellipses
        -rev RSYM RSIZE : flip reverse poles to normal antipode
        -S:  plot antipodes of all poles
        -age : plot the ages next to the poles
        -crd [g,t] : choose coordinate system, default is to plot all site VGPs
        -fmt [pdf, png, eps...] specify output format, default is pdf
        -sav  save and quit
    DEFAULTS
        FILE: pmag_results.txt
        res:  c
        prj: ortho
        ELAT,ELON = 0,0
        SYM SIZE: ro 8
        RSYM RSIZE: g^ 8

    """
    dir_path = '.'
    res, ages = 'c', 0
    plot = 0
    proj = 'ortho'
    results_file = 'pmag_results.txt'
    ell, flip = 0, 0
    lat_0, lon_0 = 90., 0.
    fmt = 'pdf'
    sym, size = 'ro', 8
    rsym, rsize = 'g^', 8
    anti = 0
    fancy = 0
    coord = ""
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path = sys.argv[ind + 1]
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-S' in sys.argv:
        anti = 1
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-sav' in sys.argv:
        plot = 1
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res = sys.argv[ind + 1]
    if '-etp' in sys.argv:
        fancy = 1
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj = sys.argv[ind + 1]
    if '-rev' in sys.argv:
        flip = 1
        ind = sys.argv.index('-rev')
        rsym = (sys.argv[ind + 1])
        rsize = int(sys.argv[ind + 2])
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym = (sys.argv[ind + 1])
        size = int(sys.argv[ind + 2])
    if '-eye' in sys.argv:
        ind = sys.argv.index('-eye')
        lat_0 = float(sys.argv[ind + 1])
        lon_0 = float(sys.argv[ind + 2])
    if '-ell' in sys.argv:
        ell = 1
    if '-age' in sys.argv:
        ages = 1
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        results_file = sys.argv[ind + 1]
    if '-crd' in sys.argv:
        ind = sys.argv.index('-crd')
        crd = sys.argv[ind + 1]
        if crd == 'g':
            coord = '0'
        if crd == 't':
            coord = '100'
    results_file = dir_path + '/' + results_file
    data, file_type = pmag.magic_read(results_file)
    if file_type != 'pmag_results':
        print("bad results file")
        sys.exit()
    FIG = {'map': 1}
    pmagplotlib.plot_init(FIG['map'], 6, 6)
    # read in er_sites file
    lats, lons, dp, dm, a95 = [], [], [], [], []
    Pars = []
    dates, rlats, rlons = [], [], []
    if 'data_type' in data[0].keys():
        # get all site level data
        Results = pmag.get_dictitem(data, 'data_type', 'i', 'T')
    else:
        Results = data
    # get all non-blank latitudes
    Results = pmag.get_dictitem(Results, 'vgp_lat', '', 'F')
    # get all non-blank longitudes
    Results = pmag.get_dictitem(Results, 'vgp_lon', '', 'F')
    if coord != "":
        # get specified coordinate system
        Results = pmag.get_dictitem(Results, 'tilt_correction', coord, 'T')
    location = ""
    for rec in Results:
        if rec['er_location_names'] not in location:
            location = location + ':' + rec['er_location_names']
        if 'average_age' in rec.keys(
        ) and rec['average_age'] != "" and ages == 1:
            dates.append(rec['average_age'])
        lat = float(rec['vgp_lat'])
        lon = float(rec['vgp_lon'])
        if flip == 0:
            lats.append(lat)
            lons.append(lon)
        elif flip == 1:
            if lat < 0:
                rlats.append(-lat)
                lon = lon + 180.
                if lon > 360:
                    lon = lon - 360.
                rlons.append(lon)
            else:
                lats.append(lat)
                lons.append(lon)
        elif anti == 1:
            lats.append(-lat)
            lon = lon + 180.
            if lon > 360:
                lon = lon - 360.
            lons.append(lon)
        ppars = []
        ppars.append(lon)
        ppars.append(lat)
        ell1, ell2 = "", ""
        if 'vgp_dm' in rec.keys() and rec['vgp_dm'] != "":
            ell1 = float(rec['vgp_dm'])
        if 'vgp_dp' in rec.keys() and rec['vgp_dp'] != "":
            ell2 = float(rec['vgp_dp'])
        if 'vgp_alpha95' in rec.keys() and rec['vgp_alpha95'] != "":
            ell1, ell2 = float(rec['vgp_alpha95']), float(rec['vgp_alpha95'])
        if ell1 != "" and ell2 != "":
            ppars = []
            ppars.append(lons[-1])
            ppars.append(lats[-1])
            ppars.append(ell1)
            ppars.append(lons[-1])
            isign = abs(lats[-1]) / lats[-1]
            ppars.append(lats[-1] - isign * 90.)
            ppars.append(ell2)
            ppars.append(lons[-1] + 90.)
            ppars.append(0.)
            Pars.append(ppars)
    location = location.strip(':')
    Opts = {
        'latmin': -90,
        'latmax': 90,
        'lonmin': 0.,
        'lonmax': 360.,
        'lat_0': lat_0,
        'lon_0': lon_0,
        'proj': proj,
        'sym': 'bs',
        'symsize': 3,
        'pltgrid': 0,
        'res': res,
        'boundinglat': 0.
    }
    Opts['details'] = {
        'coasts': 1,
        'rivers': 0,
        'states': 0,
        'countries': 0,
        'ocean': 1,
        'fancy': fancy
    }
    # make the base map with a blue triangle at the pole`
    pmagplotlib.plot_map(FIG['map'], [90.], [0.], Opts)
    Opts['pltgrid'] = -1
    Opts['sym'] = sym
    Opts['symsize'] = size
    if len(dates) > 0:
        Opts['names'] = dates
    if len(lats) > 0:
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], lats, lons, Opts)
    Opts['names'] = []
    if len(rlats) > 0:
        Opts['sym'] = rsym
        Opts['symsize'] = rsize
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], rlats, rlons, Opts)
    if plot == 0:
        pmagplotlib.draw_figs(FIG)
    if ell == 1:  # add ellipses if desired.
        Opts['details'] = {
            'coasts': 0,
            'rivers': 0,
            'states': 0,
            'countries': 0,
            'ocean': 0
        }
        Opts['pltgrid'] = -1  # turn off meridian replotting
        Opts['symsize'] = 2
        Opts['sym'] = 'g-'
        for ppars in Pars:
            if ppars[2] != 0:
                PTS = pmagplotlib.plot_ell(FIG['map'], ppars, 'g.', 0, 0)
                elats, elons = [], []
                for pt in PTS:
                    elons.append(pt[0])
                    elats.append(pt[1])
                # make the base map with a blue triangle at the pole`
                pmagplotlib.plot_map(FIG['map'], elats, elons, Opts)
                if plot == 0:
                    pmagplotlib.draw_figs(FIG)
    files = {}
    for key in FIG.keys():
        if pmagplotlib.isServer:  # use server plot naming convention
            files[key] = 'LO:_' + location + '_VGP_map.' + fmt
        else:  # use more readable plot naming convention
            files[key] = '{}_VGP_map.{}'.format(location.replace(' ', '_'),
                                                fmt)
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['eq'] = 'LO:_' + location + '_VGP_map'
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    elif plot == 0:
        pmagplotlib.draw_figs(FIG)
        ans = input(" S[a]ve to save plot, Return to quit:  ")
        if ans == "a":
            pmagplotlib.save_plots(FIG, files)
        else:
            print("Good bye")
            sys.exit()
    else:
        pmagplotlib.save_plots(FIG, files)
Ejemplo n.º 30
0
def main():
    """
    NAME
       revtest_magic.py

    DESCRIPTION
       calculates bootstrap statistics to test for antipodality

    INPUT FORMAT
       takes dec/inc data from sites table

    SYNTAX
       revtest_magic.py [command line options]

    OPTION
       -h prints help message and quits
       -f FILE, sets pmag_sites filename on command line
       -crd [s,g,t], set coordinate system, default is geographic
       -exc use criteria file to set acceptance criteria (only available for data model 3)
       -fmt [svg,png,jpg], sets format for image output
       -sav saves plot and quits
       -DM [2, 3] MagIC data model num, default is 3

    """
    if '-h' in sys.argv:  # check if help is needed
        print(main.__doc__)
        sys.exit()  # graceful quit
    dir_path = pmag.get_named_arg("-WD", ".")
    coord = pmag.get_named_arg("-crd",
                               "0")  # default to geographic coordinates
    if coord == 's':
        coord = '-1'
    elif coord == 'g':
        coord = '0'
    elif coord == 't':
        coord = '100'
    fmt = pmag.get_named_arg("-fmt", "svg")
    if '-sav' in sys.argv:
        plot = 1
    data_model = int(float(pmag.get_named_arg("-DM")))
    if data_model == 2:
        infile = pmag.get_named_arg("-f", "pmag_sites.txt")
        critfile = "pmag_criteria.txt"
        tilt_corr_col = 'site_tilt_correction'
        dec_col = "site_dec"
        inc_col = "site_inc"
        crit_code_col = "pmag_criteria_code"
    else:
        infile = pmag.get_named_arg("-f", "sites.txt")
        critfile = "criteria.txt"
        tilt_corr_col = "dir_tilt_correction"
        dec_col = "dir_dec"
        inc_col = "dir_inc"
        crit_code_col = "criterion"
    D = []

    #
    infile = pmag.resolve_file_name(infile, dir_path)
    dir_path = os.path.split(infile)[0]
    critfile = pmag.resolve_file_name(critfile, dir_path)
    #
    if data_model == 2:
        Accept = ['site_k', 'site_alpha95', 'site_n', 'site_n_lines']
    else:
        Accept = [
            'dir_k', 'dir_alpha95', 'dir_n_samples', 'dir_n_specimens_line'
        ]
    data, file_type = pmag.magic_read(infile)
    if 'sites' not in file_type:
        print("Error opening file", file_type)
        sys.exit()
#    ordata,file_type=pmag.magic_read(orfile)
    SiteCrits = []
    if '-exc' in sys.argv and data_model != 2:
        crits, file_type = pmag.magic_read(critfile)
        for crit in crits:
            if crit[crit_code_col] == "DE-SITE":
                SiteCrit = crit
                SiteCrits.append(SiteCrit)
    elif '-exc' in sys.argv and data_model == 2:
        print(
            '-W- You have selected the -exc option, which is not available with MagIC data model 2.'
        )
    for rec in data:
        if rec[tilt_corr_col] == coord:
            Dec = float(rec[dec_col])
            Inc = float(rec[inc_col])
            if '-exc' in sys.argv and data_model != 2:
                fail = False
                for SiteCrit in SiteCrits:
                    for key in Accept:
                        if key not in SiteCrit['table_column']:
                            continue
                        if key not in rec:
                            continue
                        if SiteCrit['criterion_value'] != "":
                            op = OPS[SiteCrit['criterion_operation']]
                            if not op(float(rec[key]),
                                      float(SiteCrit['criterion_value'])):
                                fail = True
                if not fail:
                    D.append([Dec, Inc, 1.])
            else:
                D.append([Dec, Inc, 1.])


# set up plots

    CDF = {'X': 1, 'Y': 2, 'Z': 3}
    pmagplotlib.plot_init(CDF['X'], 5, 5)
    pmagplotlib.plot_init(CDF['Y'], 5, 5)
    pmagplotlib.plot_init(CDF['Z'], 5, 5)
    #
    # flip reverse mode
    #
    D1, D2 = pmag.flip(D)
    counter, NumSims = 0, 500
    #
    # get bootstrapped means for each data set
    #
    if len(D1) < 5 or len(D2) < 5:
        print('not enough data in two different modes for reversals test')
        sys.exit()
    print('doing first mode, be patient')
    BDI1 = pmag.di_boot(D1)
    print('doing second mode, be patient')
    BDI2 = pmag.di_boot(D2)
    pmagplotlib.plot_com(CDF, BDI1, BDI2, [""])
    files = {}
    for key in list(CDF.keys()):
        files[key] = 'REV' + '_' + key + '.' + fmt
    if plot == 0:
        pmagplotlib.draw_figs(CDF)
        ans = input("s[a]ve plots, [q]uit: ")
        if ans == 'a':
            pmagplotlib.save_plots(CDF, files)
    else:
        pmagplotlib.save_plots(CDF, files)
        sys.exit()
Ejemplo n.º 31
0
def main():
    """
    NAME
        site_edit_magic.py

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

    SYNTAX
        site_edit_magic.py [command line options]

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

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

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

    DESCRIPTION
        plots microwave paleointensity data, allowing interactive setting of bounds.
        Saves and reads interpretations
        from a pmag_specimen formatted table, default: microwave_specimens.txt

    SYNTAX
        microwave_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f MEAS, set magic_measurements input file
        -fsp PRIOR, set pmag_specimen prior interpretations file
        -fcr CRIT, set criteria file for grading.
        -fmt [svg,png,jpg], format for images - default is svg
        -sav,  saves plots with out review (default format)
        -spc SPEC, plots single specimen SPEC, saves plot with specified format
            with optional -b bounds adn quits
        -b BEG END: sets  bounds for calculation
           BEG: starting step for slope calculation
           END: ending step for slope calculation

    DEFAULTS
        MEAS: magic_measurements.txt
        CRIT: NONE
        PRIOR: microwave_specimens.txt

    OUTPUT
        figures:
            ALL:  numbers refer to temperature steps in command line window
            1) Arai plot:  closed circles are zero-field first/infield
                           open circles are infield first/zero-field
                           triangles are pTRM checks
                           squares are pTRM tail checks
                           VDS is vector difference sum
                           diamonds are bounds for interpretation
            2) Zijderveld plot:  closed (open) symbols are X-Y (X-Z) planes
                                 X rotated to NRM direction
            3) (De/Re)Magnetization diagram:
                           circles are NRM remaining
                           squares are pTRM gained
        command line window:
            list is: temperature step numbers, power (J), Dec, Inc, Int (units of magic_measuements)
                     list of possible commands: type letter followed by return to select option
                     saving of plots creates .svg format files with specimen_name, plot type as name
    """
    #
    #   initializations
    #
    meas_file, critout, inspec = "magic_measurements.txt", "", "microwave_specimens.txt"
    inlt = 0
    version_num = pmag.get_version()
    Tinit, DCZ, field, first_save = 0, 0, -1, 1
    user, comment = "", ''
    ans, specimen, recnum, start, end = 0, 0, 0, 0, 0
    plots, pmag_out, samp_file, style = 0, "", "", "svg"
    fmt = '.' + style
    #
    # default acceptance criteria
    #
    accept_keys = [
        'specimen_int_ptrm_n', 'specimen_md', 'specimen_fvds',
        'specimen_b_beta', 'specimen_dang', 'specimen_drats', 'specimen_Z'
    ]
    accept = {}
    accept['specimen_int_ptrm_n'] = 2
    accept['specimen_md'] = 10
    accept['specimen_fvds'] = 0.35
    accept['specimen_b_beta'] = .1
    accept['specimen_int_mad'] = 7
    accept['specimen_dang'] = 10
    accept['specimen_drats'] = 10
    accept['specimen_Z'] = 10
    #
    # parse command line options
    #
    spc, BEG, END = "", "", ""
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        meas_file = sys.argv[ind + 1]
    if '-fsp' in sys.argv:
        ind = sys.argv.index('-fsp')
        inspec = sys.argv[ind + 1]
    if '-fcr' in sys.argv:
        ind = sys.argv.index('-fcr')
        critout = sys.argv[ind + 1]
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = '.' + sys.argv[ind + 1]
    if '-spc' in sys.argv:
        ind = sys.argv.index('-spc')
        spc = sys.argv[ind + 1]
        if '-b' in sys.argv:
            ind = sys.argv.index('-b')
            BEG = int(sys.argv[ind + 1])
            END = int(sys.argv[ind + 2])
    if critout != "":
        crit_data, file_type = pmag.magic_read(critout)
        if pmagplotlib.verbose:
            print("Acceptance criteria read in from ", critout)
        accept = {}
        accept['specimen_int_ptrm_n'] = 2.0
        for critrec in crit_data:
            if critrec["pmag_criteria_code"] == "IE-SPEC":
                for key in accept_keys:
                    if key not in list(critrec.keys()):
                        accept[key] = -1
                    else:
                        accept[key] = float(critrec[key])
    try:
        open(inspec, 'r')
        PriorRecs, file_type = pmag.magic_read(inspec)
        if file_type != 'pmag_specimens':
            print(file_type)
            print(file_type, inspec, " is not a valid pmag_specimens file ")
            sys.exit()
        for rec in PriorRecs:
            if 'magic_software_packages' not in list(rec.keys()):
                rec['magic_software_packages'] = ""
    except IOError:
        PriorRecs = []
        if pmagplotlib.verbose:
            print("starting new specimen interpretation file: ", inspec)
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(file_type)
        print(file_type, "This is not a valid magic_measurements file ")
        sys.exit()
    backup = 0
    # define figure numbers for arai, zijderveld and
    #   de-,re-magization diagrams
    AZD = {}
    AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4
    pmagplotlib.plot_init(AZD['arai'], 4, 4)
    pmagplotlib.plot_init(AZD['zijd'], 4, 4)
    pmagplotlib.plot_init(AZD['deremag'], 4, 4)
    pmagplotlib.plot_init(AZD['eqarea'], 4, 4)
    #
    #
    #
    # get list of unique specimen names
    #
    CurrRec = []
    sids = pmag.get_specs(meas_data)
    # get plots for specimen s - default is just to step through arai diagrams
    #
    if spc != "": specimen = sids.index(spc)
    while specimen < len(sids):
        methcodes = []
        if pmagplotlib.verbose and spc != "":
            print(sids[specimen], specimen + 1, 'of ', len(sids))
        MeasRecs = []
        s = sids[specimen]
        datablock, trmblock = [], []
        PmagSpecRec = {}
        PmagSpecRec["er_analyst_mail_names"] = user
        PmagSpecRec["specimen_correction"] = 'u'
        #
        # find the data from the meas_data file for this specimen
        #
        for rec in meas_data:
            if rec["er_specimen_name"] == s:
                MeasRecs.append(rec)
                methods = rec["magic_method_codes"].split(":")
                meths = []
                for meth in methods:
                    meths.append(meth.strip())  # take off annoying spaces
                methods = ""
                for meth in meths:
                    if meth.strip() not in methcodes and "LP-" in meth:
                        methcodes.append(meth.strip())
                    methods = methods + meth + ":"
                methods = methods[:-1]
                rec["magic_method_codes"] = methods
                if "LP-PI-M" in meths: datablock.append(rec)
                if "LP-MRM" in meths: trmblock.append(rec)
        if len(trmblock) > 2 and inspec != "":
            if Tinit == 0:
                Tinit = 1
                AZD['MRM'] = 4
                pmagplotlib.plot_init(AZD['MRM'], 4, 4)
            elif Tinit == 1:
                pmagplotlib.clearFIG(AZD['MRM'])
        if len(datablock) < 4:
            if backup == 0:
                specimen += 1
                if pmagplotlib.verbose:
                    print('skipping specimen - moving forward ', s)
            else:
                specimen -= 1
                if pmagplotlib.verbose:
                    print('skipping specimen - moving backward ', s)
    #
    #  collect info for the PmagSpecRec dictionary
    #
        else:
            rec = datablock[0]
            PmagSpecRec["er_citation_names"] = "This study"
            PmagSpecRec["er_specimen_name"] = s
            PmagSpecRec["er_sample_name"] = rec["er_sample_name"]
            PmagSpecRec["er_site_name"] = rec["er_site_name"]
            PmagSpecRec["er_location_name"] = rec["er_location_name"]
            if "magic_instrument_codes" not in list(rec.keys()):
                rec["magic_instrument_codes"] = ""
            PmagSpecRec["magic_instrument_codes"] = rec[
                "magic_instrument_codes"]
            PmagSpecRec["measurement_step_unit"] = "J"
            if "magic_experiment_name" not in list(rec.keys()):
                rec["magic_experiment_name"] = ""
            else:
                PmagSpecRec["magic_experiment_names"] = rec[
                    "magic_experiment_name"]

            meths = rec["magic_method_codes"].split(':')
            # sort data into types
            if "LP-PI-M-D" in meths:  # this is a double heating experiment
                exp_type = "LP-PI-M-D"
            elif "LP-PI-M-S" in meths:
                exp_type = "LP-PI-M-S"
            else:
                print("experiment type not supported yet ")
                break
            araiblock, field = pmag.sortmwarai(datablock, exp_type)
            first_Z = araiblock[0]
            first_I = araiblock[1]
            GammaChecks = araiblock[-3]
            ThetaChecks = araiblock[-2]
            DeltaChecks = araiblock[-1]
            if len(first_Z) < 3:
                if backup == 0:
                    specimen += 1
                    if pmagplotlib.verbose:
                        print('skipping specimen - moving forward ', s)
                else:
                    specimen -= 1
                    if pmagplotlib.verbose:
                        print('skipping specimen - moving backward ', s)
            else:
                backup = 0
                zijdblock, units = pmag.find_dmag_rec(s, meas_data)
                if exp_type == "LP-PI-M-D":
                    recnum = 0
                    print("ZStep Watts  Dec Inc  Int")
                    for plotrec in zijdblock:
                        if pmagplotlib.verbose:
                            print('%i  %i %7.1f %7.1f %8.3e ' %
                                  (recnum, plotrec[0], plotrec[1], plotrec[2],
                                   plotrec[3]))
                            recnum += 1
                    recnum = 1
                    if GammaChecks != "":
                        print("IStep Watts  Gamma")
                        for gamma in GammaChecks:
                            if pmagplotlib.verbose:
                                print('%i %i %7.1f ' %
                                      (recnum, gamma[0], gamma[1]))
                            recnum += 1
                if exp_type == "LP-PI-M-S":
                    if pmagplotlib.verbose:
                        print("IStep Watts  Theta")
                        kk = 0
                        for theta in ThetaChecks:
                            kk += 1
                            print('%i  %i %7.1f ' % (kk, theta[0], theta[1]))
                    if pmagplotlib.verbose:
                        print("Watts  Delta")
                        for delta in DeltaChecks:
                            print('%i %7.1f ' % (delta[0], delta[1]))
                pmagplotlib.plot_arai_zij(AZD, araiblock, zijdblock, s,
                                          units[0])
                if inspec != "":
                    if pmagplotlib.verbose:
                        print('Looking up saved interpretation....')
                    found = 0
                    for k in range(len(PriorRecs)):
                        try:
                            if PriorRecs[k]["er_specimen_name"] == s:
                                found = 1
                                CurrRec.append(PriorRecs[k])
                                for j in range(len(araiblock[0])):
                                    if float(araiblock[0][j][0]) == float(
                                            PriorRecs[k]
                                        ["measurement_step_min"]):
                                        start = j
                                    if float(araiblock[0][j][0]) == float(
                                            PriorRecs[k]
                                        ["measurement_step_max"]):
                                        end = j
                                pars, errcode = pmag.PintPars(
                                    araiblock, zijdblock, start, end)
                                pars['measurement_step_unit'] = "J"
                                del PriorRecs[
                                    k]  # put in CurrRec, take out of PriorRecs
                                if errcode != 1:
                                    pars["specimen_lab_field_dc"] = field
                                    pars["specimen_int"] = -1 * field * pars[
                                        "specimen_b"]
                                    pars["er_specimen_name"] = s
                                    if pmagplotlib.verbose:
                                        print('Saved interpretation: ')
                                    pars = pmag.scoreit(
                                        pars, PmagSpecRec, accept, '', 0)
                                    pmagplotlib.plot_b(AZD, araiblock,
                                                       zijdblock, pars)
                                    if len(trmblock) > 2:
                                        blab = field
                                        best = pars["specimen_int"]
                                        Bs, TRMs = [], []
                                        for trec in trmblock:
                                            Bs.append(
                                                float(
                                                    trec['treatment_dc_field'])
                                            )
                                            TRMs.append(
                                                float(trec[
                                                    'measurement_magn_moment'])
                                            )
                                        NLpars = nlt.NLtrm(
                                            Bs, TRMs, best, blab, 0
                                        )  # calculate best fit parameters through TRM acquisition data, and get new banc
                                        Mp, Bp = [], []
                                        for k in range(int(max(Bs) * 1e6)):
                                            Bp.append(float(k) * 1e-6)
                                            npred = nlt.TRM(
                                                Bp[-1], NLpars['xopt'][0],
                                                NLpars['xopt'][1]
                                            )  # predicted NRM for this field
                                            Mp.append(npred)
                                        pmagplotlib.plot_trm(
                                            AZD['MRM'], Bs, TRMs, Bp, Mp,
                                            NLpars,
                                            trec['magic_experiment_name'])
                                        print(npred)
                                        print('Banc= ',
                                              float(NLpars['banc']) * 1e6)
                                        if pmagplotlib.verbose:
                                            print('Banc= ',
                                                  float(NLpars['banc']) * 1e6)
                                        pmagplotlib.draw_figs(AZD)
                                else:
                                    print('error on specimen ', s)
                        except:
                            pass
                    if pmagplotlib.verbose and found == 0:
                        print('    None found :(  ')
                if spc != "":
                    if BEG != "":
                        pars, errcode = pmag.PintPars(araiblock, zijdblock,
                                                      BEG, END)
                        pars['measurement_step_unit'] = "J"
                        pars["specimen_lab_field_dc"] = field
                        pars["specimen_int"] = -1 * field * pars["specimen_b"]
                        pars["er_specimen_name"] = s
                        pars['specimen_grade'] = ''  # ungraded
                        pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                        if len(trmblock) > 2:
                            if inlt == 0:
                                donlt()
                                inlt = 1
                            blab = field
                            best = pars["specimen_int"]
                            Bs, TRMs = [], []
                            for trec in trmblock:
                                Bs.append(float(trec['treatment_dc_field']))
                                TRMs.append(
                                    float(trec['measurement_magn_moment']))
                            NLpars = nlt.NLtrm(
                                Bs, TRMs, best, blab, 0
                            )  # calculate best fit parameters through TRM acquisition data, and get new banc
                            #
                            Mp, Bp = [], []
                            for k in range(int(max(Bs) * 1e6)):
                                Bp.append(float(k) * 1e-6)
                                npred = nlt.TRM(
                                    Bp[-1], NLpars['xopt'][0], NLpars['xopt']
                                    [1])  # predicted NRM for this field
                    files = {}
                    for key in list(AZD.keys()):
                        files[key] = s + '_' + key + fmt
                    pmagplotlib.save_plots(AZD, files)
                    sys.exit()
                if plots == 0:
                    ans = 'b'
                    while ans != "":
                        print("""
               s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit:
               """)
                        ans = input('Return for next specimen \n')
                        if ans == "":
                            specimen += 1
                        if ans == "d":
                            save_redo(PriorRecs, inspec)
                            CurrRec = []
                            pmagplotlib.plot_arai_zij(AZD, araiblock,
                                                      zijdblock, s, units[0])
                            pmagplotlib.draw_figs(AZD)
                        if ans == 'a':
                            files = {}
                            for key in list(AZD.keys()):
                                files[key] = s + '_' + key + fmt
                            pmagplotlib.save_plots(AZD, files)
                            ans = ""
                        if ans == 'q':
                            print("Good bye")
                            sys.exit()
                        if ans == 'p':
                            specimen = specimen - 1
                            backup = 1
                            ans = ""
                        if ans == 's':
                            keepon = 1
                            spec = input(
                                'Enter desired specimen name (or first part there of): '
                            )
                            while keepon == 1:
                                try:
                                    specimen = sids.index(spec)
                                    keepon = 0
                                except:
                                    tmplist = []
                                    for qq in range(len(sids)):
                                        if spec in sids[qq]:
                                            tmplist.append(sids[qq])
                                    print(specimen,
                                          " not found, but this was: ")
                                    print(tmplist)
                                    spec = input('Select one or try again\n ')
                            ans = ""
                        if ans == 'b':
                            if end == 0 or end >= len(araiblock[0]):
                                end = len(araiblock[0]) - 1
                            GoOn = 0
                            while GoOn == 0:
                                print(
                                    'Enter index of first point for calculation: ',
                                    '[', start, ']')
                                answer = input('return to keep default  ')
                                if answer != "": start = int(answer)
                                print(
                                    'Enter index  of last point for calculation: ',
                                    '[', end, ']')
                                answer = input('return to keep default  ')
                                if answer != "":
                                    end = int(answer)
                                if start >= 0 and start < len(araiblock[
                                        0]) - 2 and end > 0 and end < len(
                                            araiblock[0]) and start < end:
                                    GoOn = 1
                                else:
                                    print("Bad endpoints - try again! ")
                                    start, end = 0, len(araiblock)
                            s = sids[specimen]
                            pars, errcode = pmag.PintPars(
                                araiblock, zijdblock, start, end)
                            pars['measurement_step_unit'] = "J"
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1 * field * pars[
                                "specimen_b"]
                            pars["er_specimen_name"] = s
                            pars = pmag.scoreit(pars, PmagSpecRec, accept, '',
                                                0)
                            PmagSpecRec["measurement_step_min"] = '%8.3e' % (
                                pars["measurement_step_min"])
                            PmagSpecRec["measurement_step_max"] = '%8.3e' % (
                                pars["measurement_step_max"])
                            PmagSpecRec["measurement_step_unit"] = "J"
                            PmagSpecRec["specimen_int_n"] = '%i' % (
                                pars["specimen_int_n"])
                            PmagSpecRec["specimen_lab_field_dc"] = '%8.3e' % (
                                pars["specimen_lab_field_dc"])
                            PmagSpecRec["specimen_int"] = '%8.3e ' % (
                                pars["specimen_int"])
                            PmagSpecRec["specimen_b"] = '%5.3f ' % (
                                pars["specimen_b"])
                            PmagSpecRec["specimen_q"] = '%5.1f ' % (
                                pars["specimen_q"])
                            PmagSpecRec["specimen_f"] = '%5.3f ' % (
                                pars["specimen_f"])
                            PmagSpecRec["specimen_fvds"] = '%5.3f' % (
                                pars["specimen_fvds"])
                            PmagSpecRec["specimen_b_beta"] = '%5.3f' % (
                                pars["specimen_b_beta"])
                            PmagSpecRec["specimen_int_mad"] = '%7.1f' % (
                                pars["specimen_int_mad"])
                            PmagSpecRec["specimen_Z"] = '%7.1f' % (
                                pars["specimen_Z"])
                            if pars["method_codes"] != "":
                                tmpcodes = pars["method_codes"].split(":")
                                for t in tmpcodes:
                                    if t.strip() not in methcodes:
                                        methcodes.append(t.strip())
                            PmagSpecRec["specimen_dec"] = '%7.1f' % (
                                pars["specimen_dec"])
                            PmagSpecRec["specimen_inc"] = '%7.1f' % (
                                pars["specimen_inc"])
                            PmagSpecRec["specimen_tilt_correction"] = '-1'
                            PmagSpecRec["specimen_direction_type"] = 'l'
                            PmagSpecRec[
                                "direction_type"] = 'l'  # this is redudant, but helpful - won't be imported
                            PmagSpecRec["specimen_dang"] = '%7.1f ' % (
                                pars["specimen_dang"])
                            PmagSpecRec["specimen_drats"] = '%7.1f ' % (
                                pars["specimen_drats"])
                            PmagSpecRec["specimen_int_ptrm_n"] = '%i ' % (
                                pars["specimen_int_ptrm_n"])
                            PmagSpecRec["specimen_rsc"] = '%6.4f ' % (
                                pars["specimen_rsc"])
                            PmagSpecRec["specimen_md"] = '%i ' % (int(
                                pars["specimen_md"]))
                            if PmagSpecRec["specimen_md"] == '-1':
                                PmagSpecRec["specimen_md"] = ""
                            PmagSpecRec["specimen_b_sigma"] = '%5.3f ' % (
                                pars["specimen_b_sigma"])
                            if "IE-TT" not in methcodes:
                                methcodes.append("IE-TT")
                            methods = ""
                            for meth in methcodes:
                                methods = methods + meth + ":"
                            PmagSpecRec["magic_method_codes"] = methods[:-1]
                            PmagSpecRec["specimen_description"] = comment
                            PmagSpecRec[
                                "magic_software_packages"] = version_num
                            pmagplotlib.plot_arai_zij(AZD, araiblock,
                                                      zijdblock, s, units[0])
                            pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars)
                            if len(trmblock) > 2:
                                blab = field
                                best = pars["specimen_int"]
                                Bs, TRMs = [], []
                                for trec in trmblock:
                                    Bs.append(float(
                                        trec['treatment_dc_field']))
                                    TRMs.append(
                                        float(trec['measurement_magn_moment']))
                                NLpars = nlt.NLtrm(
                                    Bs, TRMs, best, blab, 0
                                )  # calculate best fit parameters through TRM acquisition data, and get new banc
                                Mp, Bp = [], []
                                for k in range(int(max(Bs) * 1e6)):
                                    Bp.append(float(k) * 1e-6)
                                    npred = nlt.TRM(
                                        Bp[-1], NLpars['xopt'][0],
                                        NLpars['xopt']
                                        [1])  # predicted NRM for this field
                                    Mp.append(npred)
                                pmagplotlib.plot_trm(
                                    AZD['MRM'], Bs, TRMs, Bp, Mp, NLpars,
                                    trec['magic_experiment_name'])
                                print('Banc= ', float(NLpars['banc']) * 1e6)
                            pmagplotlib.draw_figs(AZD)
                            pars["specimen_lab_field_dc"] = field
                            pars["specimen_int"] = -1 * field * pars[
                                "specimen_b"]
                            saveit = input(
                                "Save this interpretation? [y]/n \n")
                            if saveit != 'n':
                                specimen += 1
                                PriorRecs.append(
                                    PmagSpecRec)  # put back an interpretation
                                save_redo(PriorRecs, inspec)
                            ans = ""
                else:
                    specimen += 1
                    if fmt != ".pmag":
                        basename = s + '_microwave' + fmt
                        files = {}
                        for key in list(AZD.keys()):
                            files[key] = s + '_' + key + fmt
                        if pmagplotlib.isServer:
                            black = '#000000'
                            purple = '#800080'
                            titles = {}
                            titles['deremag'] = 'DeReMag Plot'
                            titles['zijd'] = 'Zijderveld Plot'
                            titles['arai'] = 'Arai Plot'
                            AZD = pmagplotlib.add_borders(
                                AZD, titles, black, purple)
                        pmagplotlib.save_plots(AZD, files)
    #                   pmagplotlib.combineFigs(s,files,3)
        if len(CurrRec) > 0:
            for rec in CurrRec:
                PriorRecs.append(rec)
        CurrRec = []
    if plots != 1:
        ans = input(" Save last plot? 1/[0] ")
        if ans == "1":
            if fmt != ".pmag":
                files = {}
                for key in list(AZD.keys()):
                    files[key] = s + '_' + key + fmt
                pmagplotlib.save_plots(AZD, files)
        if len(CurrRec) > 0:
            PriorRecs.append(CurrRec)  # put back an interpretation
        if len(PriorRecs) > 0:
            save_redo(PriorRecs, inspec)
            print('Updated interpretations saved in ', inspec)
    if pmagplotlib.verbose:
        print("Good bye")
Ejemplo n.º 33
0
def main():
    """
    NAME
        trmaq_magic.py

    DESCTIPTION
        does non-linear trm acquisisiton correction

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

    OPTIONS
        -h prints help message and quits
        -i allows interactive setting of file names
        -f MFILE, sets magic_measurements input file
        -ft TSPEC, sets thellier_specimens input file
        -F OUT, sets output for non-linear TRM acquisition corrected data
        -sav save figures and quit
        -fmt [png, svg, pdf]
        -DM [2, 3] MagIC data model, default 3


    DEFAULTS
        MFILE: trmaq_measurements.txt
        TSPEC: thellier_specimens.txt
        OUT: NLT_specimens.txt
    """
    meas_file = 'trmaq_measurements.txt'
    tspec = "thellier_specimens.txt"
    output = 'NLT_specimens.txt'
    data_model_num = int(float(pmag.get_named_arg("-DM", 3)))
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-i' in sys.argv:
        meas_file = input(
            "Input magic_measurements file name? [trmaq_measurements.txt] ")
        if meas_file == "":
            meas_file = "trmaq_measurements.txt"
        tspec = input(
            " thellier_specimens file name? [thellier_specimens.txt] ")
        if tspec == "":
            tspec = "thellier_specimens.txt"
        output = input(
            "File for non-linear TRM adjusted specimen data: [NLTspecimens.txt] ")
        if output == "":
            output = "NLT_specimens.txt"
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        meas_file = sys.argv[ind+1]
    if '-ft' in sys.argv:
        ind = sys.argv.index('-ft')
        tspec = sys.argv[ind+1]
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        output = sys.argv[ind+1]
    if '-sav' in sys.argv:
        save_plots = True
    else:
        save_plots = False
    fmt = pmag.get_named_arg("-fmt", "svg")
    #
    PLT = {'aq': 1}
    if not save_plots:
        pmagplotlib.plot_init(PLT['aq'], 5, 5)
    #
    # get name of file from command line
    #
    comment = ""
    #
    #
    meas_data, file_type = pmag.magic_read(meas_file)
    if 'measurements' not in file_type:
        print(file_type, "This is not a valid measurements file ")
        sys.exit()

    if data_model_num == 2:
        spec_col = "er_specimen_name"
        lab_field_dc_col = "specimen_lab_field_dc"
        int_col = "specimen_int"
        meth_col = "magic_method_codes"
        treat_dc_col = "treatment_dc_field"
        magn_moment_col = "measurement_magn_moment"
        experiment_col = "magic_experiment_name"
        outfile_type = "pmag_specimens"
    else:
        spec_col = "specimen"
        lab_field_dc_col = "int_treat_dc_field"
        int_col = "int_abs"
        meth_col = "method_codes"
        treat_dc_col = "treat_dc_field"
        magn_moment_col = "magn_moment"
        experiment_col = "experiment"
        outfile_type = "specimens"

    sids = pmag.get_specs(meas_data)
    specimen = 0
    #
    # read in thellier_specimen data
    #
    nrm, file_type = pmag.magic_read(tspec)
    PmagSpecRecs= []
    while specimen < len(sids):
        #
        # find corresoponding paleointensity data for this specimen
        #
        s = sids[specimen]
        blab, best = "", ""
        for nrec in nrm:   # pick out the Banc data for this spec
            if nrec[spec_col] == s:
                try:
                    blab = float(nrec[lab_field_dc_col])
                except ValueError:
                    continue
                best = float(nrec[int_col])
                TrmRec = nrec
                break
        if blab == "":
            print("skipping ", s, " : no best ")
            specimen += 1
        else:
            print(sids[specimen], specimen+1, 'of ',
                  len(sids), 'Best = ', best*1e6)
            MeasRecs = []
    #
    # find the data from the meas_data file for this specimen
    #
            for rec in meas_data:
                if rec[spec_col] == s:
                    meths = rec[meth_col].split(":")
                    methcodes = []
                    for meth in meths:
                        methcodes.append(meth.strip())
                    if "LP-TRM" in methcodes:
                        MeasRecs.append(rec)
            if len(MeasRecs) < 2:
                specimen += 1
                print('skipping specimen -  no trm acquisition data ', s)
    #
    #  collect info for the PmagSpecRec dictionary
    #
            else:
                TRMs, Bs = [], []
                for rec in MeasRecs:
                    Bs.append(float(rec[treat_dc_col]))
                    TRMs.append(float(rec[magn_moment_col]))
                # calculate best fit parameters through TRM acquisition data, and get new banc
                NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0)
    #
                Mp, Bp = [], []
                for k in range(int(max(Bs)*1e6)):
                    Bp.append(float(k)*1e-6)
                    # predicted NRM for this field
                    npred = nlt.TRM(Bp[-1], NLpars['xopt']
                                    [0], NLpars['xopt'][1])
                    Mp.append(npred)
                pmagplotlib.plot_trm(
                    PLT['aq'], Bs, TRMs, Bp, Mp, NLpars, rec[experiment_col])
                if not save_plots:
                    pmagplotlib.draw_figs(PLT)
                print('Banc= ', float(NLpars['banc'])*1e6)
                trmTC = {}
                for key in list(TrmRec.keys()):
                    # copy of info from thellier_specimens record
                    trmTC[key] = TrmRec[key]
                trmTC[int_col] = '%8.3e' % (NLpars['banc'])
                trmTC[meth_col] = TrmRec[meth_col]+":DA-NL"
                PmagSpecRecs.append(trmTC)
                if not save_plots:
                    ans = input("Return for next specimen, s[a]ve plot  ")
                    if ans == 'a':
                        Name = {'aq': rec[spec_col]+'_TRM.{}'.format(fmt)}
                        pmagplotlib.save_plots(PLT, Name)
                else:
                    Name = {'aq': rec[spec_col]+'_TRM.{}'.format(fmt)}
                    pmagplotlib.save_plots(PLT, Name)

                specimen += 1

    pmag.magic_write(output, PmagSpecRecs, outfile_type)
Ejemplo n.º 34
0
def main():
    """
    NAME
        plot_magic_keys.py

    DESCRIPTION
        picks out keys and makes and xy plot

    SYNTAX
        plot_magic_keys.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input magic format file
        -xkey KEY: specify key for X
        -ykey KEY: specify key  for Y
        -b xmin xmax ymin ymax, sets bounds

    """
    dir_path="./"
    if '-WD' in sys.argv:
        ind=sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        magic_file=dir_path+'/'+sys.argv[ind+1]
    else:
        print(main.__doc__)
        sys.exit()
    if '-xkey' in sys.argv:
        ind=sys.argv.index('-xkey')
        xkey=sys.argv[ind+1]
        if '-ykey' in sys.argv:
            ind=sys.argv.index('-ykey')
            ykey=sys.argv[ind+1]
    else:
        print(main.__doc__)
        sys.exit()
    if '-b' in sys.argv:
        ind=sys.argv.index('-b')
        xmin=float(sys.argv[ind+1])
        xmax=float(sys.argv[ind+2])
        ymin=float(sys.argv[ind+3])
        ymax=float(sys.argv[ind+4])
    #
    #
    # get data read in
    X,Y=[],[]
    Data,file_type=pmag.magic_read(magic_file)
    if len(Data)>0:
        for rec in Data:
            if xkey in list(rec.keys()) and rec[xkey]!="" and ykey in list(rec.keys()) and rec[ykey]!="":
                try:
                    X.append(float(rec[xkey]))
                    Y.append(float(rec[ykey]))
                except:
                    pass
        FIG={'fig':1}
        pmagplotlib.plot_init(FIG['fig'],5,5)
        if '-b' in sys.argv:
            pmagplotlib.plot_xy(FIG['fig'],X,Y,sym='ro',xlab=xkey,ylab=ykey,xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax )
        else:
            pmagplotlib.plot_xy(FIG['fig'],X,Y,sym='ro',xlab=xkey,ylab=ykey)
        pmagplotlib.draw_figs(FIG)
        ans=input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans=="q": sys.exit()
        if ans=="a":
            files = {}
            for key in list(FIG.keys()):
                files[key]=str(key) + ".svg"
                pmagplotlib.save_plots(FIG,files)
        sys.exit()
    else:
        print('no data to plot')
Ejemplo n.º 35
0
def main():
    """
    NAME
        chi_magic.py

    DESCRIPTION
        plots magnetic susceptibility as a function of frequency and temperature and AC field

    SYNTAX
        chi_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE, specify measurements format file, default "measurements.txt"
        -T IND, specify temperature step to plot
        -e EXP, specify experiment name to plot
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
        -sav save figure and quit

    """
    if "-h" in sys.argv:
        print(main.__doc__)
        return
    infile = pmag.get_named_arg("-f", "measurements.txt")
    dir_path = pmag.get_named_arg("-WD", ".")
    infile = pmag.resolve_file_name(infile, dir_path)
    fmt = pmag.get_named_arg("-fmt", "svg")
    show_plots = True
    if "-sav" in sys.argv:
        show_plots = False
    experiments = pmag.get_named_arg("-e", "")
    # read in data from data model 3 example file
    chi_data_all = pd.read_csv(infile, sep='\t', header=1)

    if not experiments:
        try:
            experiments = chi_data_all.experiment.unique()
        except Exception as ex:
            print(ex)
            experiments = ["all"]
    else:
        experiments = [experiments]

    plotnum = 0
    figs = {}
    fnames = {}
    for exp in experiments:
        if exp == "all":
            chi_data = chi_data_all
        chi_data = chi_data_all[chi_data_all.experiment == exp]
        if len(chi_data) <= 1:
            print('Not enough data to plot {}'.format(exp))
            continue

        plotnum += 1
        pmagplotlib.plot_init(plotnum, 5, 5)  # set up plot
        figs[str(plotnum)] = plotnum
        fnames[str(plotnum)] = exp + '_temperature.{}'.format(fmt)

        # get arrays of available temps, frequencies and fields
        Ts = np.sort(chi_data.meas_temp.unique())
        Fs = np.sort(chi_data.meas_freq.unique())
        Bs = np.sort(chi_data.meas_field_ac.unique())

        # plot chi versus temperature at constant field
        b = Bs.max()
        for num, f in enumerate(Fs):
            this_f = chi_data[chi_data.meas_freq == f]
            this_f = this_f[this_f.meas_field_ac == b]
            plt.plot(this_f.meas_temp,
                     1e6 * this_f.susc_chi_volume,
                     label='%i' % (f) + ' Hz')
        plt.legend()
        plt.xlabel('Temperature (K)')
        plt.ylabel('$\chi$ ($\mu$SI)')
        plt.title('B = ' + '%7.2e' % (b) + ' T')

        plotnum += 1
        figs[str(plotnum)] = plotnum
        fnames[str(plotnum)] = exp + '_frequency.{}'.format(fmt)

        pmagplotlib.plot_init(plotnum, 5, 5)  # set up plot
        ## plot chi versus frequency at constant B
        b = Bs.max()
        t = Ts.min()
        this_t = chi_data[chi_data.meas_temp == t]
        this_t = this_t[this_t.meas_field_ac == b]
        plt.semilogx(this_t.meas_freq,
                     1e6 * this_t.susc_chi_volume,
                     label='%i' % (t) + ' K')
        plt.legend()
        plt.xlabel('Frequency (Hz)')
        plt.ylabel('$\chi$ ($\mu$SI)')
        plt.title('B = ' + '%7.2e' % (b) + ' T')

    if show_plots:
        pmagplotlib.draw_figs(figs)
        ans = input("enter s[a]ve to save files,  [return] to quit ")
        if ans == 'a':
            pmagplotlib.save_plots(figs, fnames)
            sys.exit()
        else:
            sys.exit()

    else:
        pmagplotlib.save_plots(figs, fnames)
Ejemplo n.º 36
0
def main():
    """
    NAME
       qqplot.py

    DESCRIPTION
       makes qq plot of input data  against a Normal distribution.  
       

    INPUT FORMAT
       takes real numbers in single column
   
    SYNTAX
       qqplot.py [-h][-i][-f FILE]

    OPTIONS
        -f FILE, specify file on command line
        -fmt [png,svg,jpg,eps] set plot output format [default is svg]
        -sav saves and quits

    OUTPUT
         calculates the K-S D and the D expected for a normal distribution 
         when D<Dc,  distribution is normal (at 95% level of confidence).

    """
    fmt,plot='svg',0
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    if '-sav' in sys.argv: plot=1
    if '-fmt' in sys.argv: 
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        data=f.readlines()
    X= [] # set up list for data
    for line in data:   # read in the data from standard input
        rec=line.split() # split each line on space to get records
        X.append(float(rec[0])) # append data to X
#
    QQ={'qq':1}
    pmagplotlib.plot_init(QQ['qq'],5,5)
    pmagplotlib.plot_qq_norm(QQ['qq'],X,'Q-Q Plot') # make plot
    if plot==0:
        pmagplotlib.draw_figs(QQ)
    files={}
    for key in list(QQ.keys()):
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Q-Q Plot'
        QQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==0:
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": 
            pmagplotlib.save_plots(QQ,files) 
    else:
        pmagplotlib.save_plots(QQ,files) 
Ejemplo n.º 37
0
def main():
    """
    NAME 
        plot_map_pts.py 

    DESCRIPTION
        plots points on map
 
    SYNTAX
        plot_map_pts.py [command line options]

    OPTIONS
        -h prints help and quits
        -sym [ro, bs, g^, r., b-, etc.] [1,5,10] symbol and size for points
           colors are r=red,b=blue,g=green, etc.
           symbols are '.' for points, ^, for triangle, s for square, etc.
            -, for lines, -- for dotted lines, see matplotlib online documentation for plot()
        -eye  ELAT ELON [specify eyeball location]
        -etp  put on topography
        -cmap color map [default is jet]
        -f FILE, specify input file
        -o color ocean blue/land green (default is not)
        -res [c,l,i,h] specify resolution (crude, low, intermediate, high]
        -fmt [pdf,eps, png] specify output format (default is pdf)
        -R don't plot details of rivers
        -B don't plot national/state boundaries, etc.
        -pad [LAT LON] pad bounding box by LAT/LON (default is not)
        -grd SPACE specify grid spacing
        -sav  save plot and quit
        -prj PROJ,  specify one of the supported projections: 
            pc = Plate Carree
            aea = Albers Equal Area
            aeqd = Azimuthal Equidistant
            lcc = Lambert Conformal
            lcyl = Lambert Cylindrical
            merc = Mercator
            mill = Miller Cylindrical
            moll = Mollweide [default]
            ortho = Orthographic
            robin = Robinson
            sinu = Sinusoidal
            stere = Stereographic
            tmerc = Transverse Mercator
            utm = UTM
            laea = Lambert Azimuthal Equal Area
            geos = Geostationary
            npstere = North-Polar Stereographic
            spstere = South-Polar Stereographic
        Special codes for MagIC formatted input files:
            -n
            -l
    
    INPUTS
        space or tab delimited LON LAT data
        OR: 
           standard MagIC formatted er_sites or pmag_results table
    DEFAULTS
        res:  c
        prj: mollweide;  lcc for MagIC format files 
        ELAT,ELON = 0,0
        pad LAT,LON=0,0
        NB: high resolution or lines can be very slow
    
    """
    dir_path='.'
    plot=0
    ocean=0
    res='c'
    proj='moll'
    Lats,Lons=[],[]
    fmt='pdf'
    sym='ro'
    symsize=5
    fancy=0
    rivers,boundaries,ocean=1,1,0
    latmin,latmax,lonmin,lonmax,lat_0,lon_0=-90,90,0.,360.,0.,0.
    padlat,padlon,gridspace=0,0,30
    lat_0,lon_0="",""
    basemap=1
    prn_name,prn_loc,names,locs=0,0,[],[]
    if '-WD' in sys.argv:
        ind = sys.argv.index('-WD')
        dir_path=sys.argv[ind+1]
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-res' in sys.argv:
        ind = sys.argv.index('-res')
        res=sys.argv[ind+1]
        if res!= 'c' and res!='l':
            print('this resolution will take a while - be patient')
    if '-etp' in sys.argv: 
        fancy=1
        print ('-W- plotting will require patience!')
    if '-ctp' in sys.argv: basemap=0
    if '-sav' in sys.argv: plot=1
    if '-R' in sys.argv:rivers=0
    if '-B' in sys.argv:boundaries=0
    if '-o' in sys.argv:ocean=1
    if '-cmap' in sys.argv:
        ind = sys.argv.index('-cmap')
        cmap=float(sys.argv[ind+1])
    else:
        cmap='jet'
    if '-grd' in sys.argv:
        ind = sys.argv.index('-grd')
        gridspace=float(sys.argv[ind+1])
    if '-eye' in sys.argv:
        ind = sys.argv.index('-eye')
        lat_0=float(sys.argv[ind+1])
        lon_0=float(sys.argv[ind+2])
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym=sys.argv[ind+1]
        symsize=int(sys.argv[ind+2])
    if '-pad' in sys.argv:
        ind = sys.argv.index('-pad')
        padlat=float(sys.argv[ind+1])
        padlon=float(sys.argv[ind+2])
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file=dir_path+'/'+sys.argv[ind+1]
        header=open(file,'r').readlines()[0].split('\t')
        if 'tab' in header[0]:
            proj='lcc'
            if 'sites' in header[1]:
                latkey='lat'
                lonkey='lon'
                namekey='site'
                lockey=''
            else:  
                print('file type not supported')
                print(main.__doc__)
                sys.exit()
            Sites,file_type=pmag.magic_read(file)
            Lats=pmag.get_dictkey(Sites,latkey,'f')
            Lons=pmag.get_dictkey(Sites,lonkey,'f')
            if prn_name==1:names=pmag.get_dictkey(Sites,namekey,'')
            if prn_loc==1:names=pmag.get_dictkey(Sites,lockey,'')
        else:
            ptdata=numpy.loadtxt(file)
            Lons=ptdata.transpose()[0]
            Lats=ptdata.transpose()[1]
        latmin=numpy.min(Lats)-padlat
        lonmin=numpy.min(Lons)-padlon
        latmax=numpy.max(Lats)+padlat
        lonmax=numpy.max(Lons)+padlon
        if lon_0=="":
            lon_0=0.5*(lonmin+lonmax)
            lat_0=0.5*(latmin+latmax)
    else:
        print("input file must be specified")
        sys.exit()
    if '-prj' in sys.argv:
        ind = sys.argv.index('-prj')
        proj=sys.argv[ind+1]
    FIG={'map':1}
    pmagplotlib.plot_init(FIG['map'],6,6)
    cnt=0
    Opts={'latmin':latmin,'latmax':latmax,'lonmin':lonmin,'lonmax':lonmax,'lat_0':lat_0,'lon_0':lon_0,'proj':proj,'sym':sym,'symsize':3,'pltgrid':1,'res':res,'boundinglat':0.,'padlon':padlon,'padlat':padlat,'gridspace':gridspace,'cmap':cmap}
    Opts['details']={}
    Opts['details']['coasts']=1
    Opts['details']['rivers']=rivers
    Opts['details']['states']=boundaries
    Opts['details']['countries']=boundaries
    Opts['details']['ocean']=ocean
    Opts['details']['fancy']=fancy
    if len(names)>0:Opts['names']=names
    if len(locs)>0:Opts['loc_name']=locs
    if proj=='merc':
        Opts['latmin']=-70
        Opts['latmax']=70
        Opts['lonmin']=-180
        Opts['lonmax']=180
    print('please wait to draw points')
    Opts['sym']=sym
    Opts['symsize']=symsize
    if basemap: 
        pmagplotlib.plot_map(FIG['map'],Lats,Lons,Opts)
    else:
        pmagplotlib.plot_map(FIG['map'],Lats,Lons,Opts)
    files={}
    titles={}
    titles['map']='PT Map'
    for key in list(FIG.keys()):
        files[key]='map_pts'+'.'+fmt
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        FIG = pmagplotlib.add_borders(FIG,titles,black,purple)
        pmagplotlib.save_plots(FIG,files)
    if plot==1:
        pmagplotlib.save_plots(FIG,files)
    else:
        pmagplotlib.draw_figs(FIG)
        ans=input(" S[a]ve to save plot, Return to quit:  ")
        if ans=="a": pmagplotlib.save_plots(FIG,files)
Ejemplo n.º 38
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)
Ejemplo n.º 39
0
def main():
    """
    NAME
        aniso_magic.py

    DESCRIPTION
        plots anisotropy data with either bootstrap or hext ellipses

    SYNTAX
        aniso_magic.py [-h] [command line options]
    OPTIONS
        -h plots help message and quits
        -usr USER: set the user name
        -f AFILE, specify rmag_anisotropy formatted file for input
        -F RFILE, specify rmag_results formatted file for output
        -x Hext [1963] and bootstrap
        -B DON'T do bootstrap, do Hext
        -par Tauxe [1998] parametric bootstrap
        -v plot bootstrap eigenvectors instead of ellipses
        -sit plot by site instead of entire file
        -crd [s,g,t] coordinate system, default is specimen (g=geographic, t=tilt corrected)
        -P don't make any plots - just make rmag_results table
        -sav don't make the rmag_results table - just save all the plots
        -fmt [svg, jpg, eps] format for output images, pdf default
        -gtc DEC INC  dec,inc of pole to great circle [down(up) in green (cyan)
        -d Vi DEC INC; Vi (1,2,3) to compare to direction DEC INC
        -n N; specifies the number of bootstraps - default is 1000
    DEFAULTS
       AFILE:  rmag_anisotropy.txt
       RFILE:  rmag_results.txt
       plot bootstrap ellipses of Constable & Tauxe [1987]
    NOTES
       minor axis: circles
       major axis: triangles
       principal axis: squares
       directions are plotted on the lower hemisphere
       for bootstrapped eigenvector components: Xs: blue, Ys: red, Zs: black
"""
#
    dir_path = "."
    version_num = pmag.get_version()
    verbose = pmagplotlib.verbose
    args = sys.argv
    ipar, ihext, ivec, iboot, imeas, isite, iplot, vec = 0, 0, 0, 1, 1, 0, 1, 0
    hpars, bpars, PDir = [], [], []
    CS, crd = '-1', 's'
    nb = 1000
    fmt = 'pdf'
    ResRecs = []
    orlist = []
    outfile, comp, Dir, gtcirc, PDir = 'rmag_results.txt', 0, [], 0, []
    infile = 'rmag_anisotropy.txt'
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if '-WD' in args:
        ind = args.index('-WD')
        dir_path = args[ind+1]
    if '-n' in args:
        ind = args.index('-n')
        nb = int(args[ind+1])
    if '-usr' in args:
        ind = args.index('-usr')
        user = args[ind+1]
    else:
        user = ""
    if '-B' in args:
        iboot, ihext = 0, 1
    if '-par' in args:
        ipar = 1
    if '-x' in args:
        ihext = 1
    if '-v' in args:
        ivec = 1
    if '-sit' in args:
        isite = 1
    if '-P' in args:
        iplot = 0
    if '-f' in args:
        ind = args.index('-f')
        infile = args[ind+1]
    if '-F' in args:
        ind = args.index('-F')
        outfile = args[ind+1]
    if '-crd' in sys.argv:
        ind = sys.argv.index('-crd')
        crd = sys.argv[ind+1]
        if crd == 'g':
            CS = '0'
        if crd == 't':
            CS = '100'
    if '-fmt' in args:
        ind = args.index('-fmt')
        fmt = args[ind+1]
    if '-sav' in args:
        plots = 1
        verbose = 0
    else:
        plots = 0
    if '-gtc' in args:
        ind = args.index('-gtc')
        d, i = float(args[ind+1]), float(args[ind+2])
        PDir.append(d)
        PDir.append(i)
    if '-d' in args:
        comp = 1
        ind = args.index('-d')
        vec = int(args[ind+1])-1
        Dir = [float(args[ind+2]), float(args[ind+3])]
#
# set up plots
#
    if infile[0] != '/':
        infile = dir_path+'/'+infile
    if outfile[0] != '/':
        outfile = dir_path+'/'+outfile
    ANIS = {}
    initcdf, inittcdf = 0, 0
    ANIS['data'], ANIS['conf'] = 1, 2
    if iboot == 1:
        ANIS['tcdf'] = 3
        if iplot == 1:
            inittcdf = 1
            pmagplotlib.plot_init(ANIS['tcdf'], 5, 5)
        if comp == 1 and iplot == 1:
            initcdf = 1
            ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6
            pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5)
            pmagplotlib.plot_init(ANIS['vycdf'], 5, 5)
            pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5)
    if iplot == 1:
        pmagplotlib.plot_init(ANIS['conf'], 5, 5)
        pmagplotlib.plot_init(ANIS['data'], 5, 5)
# read in the data
    data, ifiletype = pmag.magic_read(infile)
    for rec in data:  # find all the orientation systems
        if 'anisotropy_tilt_correction' not in rec.keys():
            rec['anisotropy_tilt_correction'] = '-1'
        if rec['anisotropy_tilt_correction'] not in orlist:
            orlist.append(rec['anisotropy_tilt_correction'])
    if CS not in orlist:
        if len(orlist) > 0:
            CS = orlist[0]
        else:
            CS = '-1'
        if CS == '-1':
            crd = 's'
        if CS == '0':
            crd = 'g'
        if CS == '100':
            crd = 't'
        if verbose:
            print("desired coordinate system not available, using available: ", crd)
    if isite == 1:
        sitelist = []
        for rec in data:
            if rec['er_site_name'] not in sitelist:
                sitelist.append(rec['er_site_name'])
        sitelist.sort()
        plt = len(sitelist)
    else:
        plt = 1
    k = 0
    while k < plt:
        site = ""
        sdata, Ss = [], []  # list of S format data
        Locs, Sites, Samples, Specimens, Cits = [], [], [], [], []
        if isite == 0:
            sdata = data
        else:
            site = sitelist[k]
            for rec in data:
                if rec['er_site_name'] == site:
                    sdata.append(rec)
        anitypes = []
        csrecs = pmag.get_dictitem(
            sdata, 'anisotropy_tilt_correction', CS, 'T')
        for rec in csrecs:
            if rec['anisotropy_type'] not in anitypes:
                anitypes.append(rec['anisotropy_type'])
            if rec['er_location_name'] not in Locs:
                Locs.append(rec['er_location_name'])
            if rec['er_site_name'] not in Sites:
                Sites.append(rec['er_site_name'])
            if rec['er_sample_name'] not in Samples:
                Samples.append(rec['er_sample_name'])
            if rec['er_specimen_name'] not in Specimens:
                Specimens.append(rec['er_specimen_name'])
            if rec['er_citation_names'] not in Cits:
                Cits.append(rec['er_citation_names'])
            s = []
            s.append(float(rec["anisotropy_s1"]))
            s.append(float(rec["anisotropy_s2"]))
            s.append(float(rec["anisotropy_s3"]))
            s.append(float(rec["anisotropy_s4"]))
            s.append(float(rec["anisotropy_s5"]))
            s.append(float(rec["anisotropy_s6"]))
            if s[0] <= 1.0:
                Ss.append(s)  # protect against crap
            # tau,Vdirs=pmag.doseigs(s)
            ResRec = {}
            ResRec['er_location_names'] = rec['er_location_name']
            ResRec['er_citation_names'] = rec['er_citation_names']
            ResRec['er_site_names'] = rec['er_site_name']
            ResRec['er_sample_names'] = rec['er_sample_name']
            ResRec['er_specimen_names'] = rec['er_specimen_name']
            ResRec['rmag_result_name'] = rec['er_specimen_name'] + \
                ":"+rec['anisotropy_type']
            ResRec["er_analyst_mail_names"] = user
            ResRec["tilt_correction"] = CS
            ResRec["anisotropy_type"] = rec['anisotropy_type']
            if "anisotropy_n" not in rec.keys():
                rec["anisotropy_n"] = "6"
            if "anisotropy_sigma" not in rec.keys():
                rec["anisotropy_sigma"] = "0"
            fpars = pmag.dohext(
                int(rec["anisotropy_n"])-6, float(rec["anisotropy_sigma"]), s)
            ResRec["anisotropy_v1_dec"] = '%7.1f' % (fpars['v1_dec'])
            ResRec["anisotropy_v2_dec"] = '%7.1f' % (fpars['v2_dec'])
            ResRec["anisotropy_v3_dec"] = '%7.1f' % (fpars['v3_dec'])
            ResRec["anisotropy_v1_inc"] = '%7.1f' % (fpars['v1_inc'])
            ResRec["anisotropy_v2_inc"] = '%7.1f' % (fpars['v2_inc'])
            ResRec["anisotropy_v3_inc"] = '%7.1f' % (fpars['v3_inc'])
            ResRec["anisotropy_t1"] = '%10.8f' % (fpars['t1'])
            ResRec["anisotropy_t2"] = '%10.8f' % (fpars['t2'])
            ResRec["anisotropy_t3"] = '%10.8f' % (fpars['t3'])
            ResRec["anisotropy_ftest"] = '%10.3f' % (fpars['F'])
            ResRec["anisotropy_ftest12"] = '%10.3f' % (fpars['F12'])
            ResRec["anisotropy_ftest23"] = '%10.3f' % (fpars['F23'])
            ResRec["result_description"] = 'F_crit: ' + \
                fpars['F_crit']+'; F12,F23_crit: '+fpars['F12_crit']
            ResRec['anisotropy_type'] = pmag.makelist(anitypes)
            ResRecs.append(ResRec)
        if len(Ss) > 1:
            if pmagplotlib.isServer:
                title = "LO:_"+ResRec['er_location_names'] + \
                    '_SI:_'+site+'_SA:__SP:__CO:_'+crd
            else:
                title = ResRec['er_location_names']
                if site:
                    title += "_{}".format(site)
                title += '_{}'.format(crd)
            ResRec['er_location_names'] = pmag.makelist(Locs)
            bpars, hpars = pmagplotlib.plot_anis(
                ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb)
            if len(PDir) > 0:
                pmagplotlib.plot_circ(ANIS['data'], PDir, 90., 'g')
                pmagplotlib.plot_circ(ANIS['conf'], PDir, 90., 'g')
            if verbose and plots == 0:
                pmagplotlib.draw_figs(ANIS)
            ResRec['er_location_names'] = pmag.makelist(Locs)
            if plots == 1:
                save(ANIS, fmt, title)
            ResRec = {}
            ResRec['er_citation_names'] = pmag.makelist(Cits)
            ResRec['er_location_names'] = pmag.makelist(Locs)
            ResRec['er_site_names'] = pmag.makelist(Sites)
            ResRec['er_sample_names'] = pmag.makelist(Samples)
            ResRec['er_specimen_names'] = pmag.makelist(Specimens)
            ResRec['rmag_result_name'] = pmag.makelist(
                Sites)+":"+pmag.makelist(anitypes)
            ResRec['anisotropy_type'] = pmag.makelist(anitypes)
            ResRec["er_analyst_mail_names"] = user
            ResRec["tilt_correction"] = CS
            if isite == "0":
                ResRec['result_description'] = "Study average using coordinate system: " + CS
            if isite == "1":
                ResRec['result_description'] = "Site average using coordinate system: " + CS
            if hpars != [] and ihext == 1:
                HextRec = {}
                for key in ResRec.keys():
                    HextRec[key] = ResRec[key]   # copy over stuff
                HextRec["anisotropy_v1_dec"] = '%7.1f' % (hpars["v1_dec"])
                HextRec["anisotropy_v2_dec"] = '%7.1f' % (hpars["v2_dec"])
                HextRec["anisotropy_v3_dec"] = '%7.1f' % (hpars["v3_dec"])
                HextRec["anisotropy_v1_inc"] = '%7.1f' % (hpars["v1_inc"])
                HextRec["anisotropy_v2_inc"] = '%7.1f' % (hpars["v2_inc"])
                HextRec["anisotropy_v3_inc"] = '%7.1f' % (hpars["v3_inc"])
                HextRec["anisotropy_t1"] = '%10.8f' % (hpars["t1"])
                HextRec["anisotropy_t2"] = '%10.8f' % (hpars["t2"])
                HextRec["anisotropy_t3"] = '%10.8f' % (hpars["t3"])
                HextRec["anisotropy_hext_F"] = '%7.1f ' % (hpars["F"])
                HextRec["anisotropy_hext_F12"] = '%7.1f ' % (hpars["F12"])
                HextRec["anisotropy_hext_F23"] = '%7.1f ' % (hpars["F23"])
                HextRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % (
                    hpars["e12"])
                HextRec["anisotropy_v1_eta_dec"] = '%7.1f ' % (hpars["v2_dec"])
                HextRec["anisotropy_v1_eta_inc"] = '%7.1f ' % (hpars["v2_inc"])
                HextRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % (
                    hpars["e13"])
                HextRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % (
                    hpars["v3_dec"])
                HextRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % (
                    hpars["v3_inc"])
                HextRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % (
                    hpars["e12"])
                HextRec["anisotropy_v2_eta_dec"] = '%7.1f ' % (hpars["v1_dec"])
                HextRec["anisotropy_v2_eta_inc"] = '%7.1f ' % (hpars["v1_inc"])
                HextRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % (
                    hpars["e23"])
                HextRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % (
                    hpars["v3_dec"])
                HextRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % (
                    hpars["v3_inc"])
                HextRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % (
                    hpars["e12"])
                HextRec["anisotropy_v3_eta_dec"] = '%7.1f ' % (hpars["v1_dec"])
                HextRec["anisotropy_v3_eta_inc"] = '%7.1f ' % (hpars["v1_inc"])
                HextRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % (
                    hpars["e23"])
                HextRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % (
                    hpars["v2_dec"])
                HextRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % (
                    hpars["v2_inc"])
                HextRec["magic_method_codes"] = 'LP-AN:AE-H'
                if verbose:
                    print("Hext Statistics: ")
                    print(
                        " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I")
                    print(HextRec["anisotropy_t1"], HextRec["anisotropy_v1_dec"], HextRec["anisotropy_v1_inc"], HextRec["anisotropy_v1_eta_semi_angle"], HextRec["anisotropy_v1_eta_dec"],
                          HextRec["anisotropy_v1_eta_inc"], HextRec["anisotropy_v1_zeta_semi_angle"], HextRec["anisotropy_v1_zeta_dec"], HextRec["anisotropy_v1_zeta_inc"])
                    print(HextRec["anisotropy_t2"], HextRec["anisotropy_v2_dec"], HextRec["anisotropy_v2_inc"], HextRec["anisotropy_v2_eta_semi_angle"], HextRec["anisotropy_v2_eta_dec"],
                          HextRec["anisotropy_v2_eta_inc"], HextRec["anisotropy_v2_zeta_semi_angle"], HextRec["anisotropy_v2_zeta_dec"], HextRec["anisotropy_v2_zeta_inc"])
                    print(HextRec["anisotropy_t3"], HextRec["anisotropy_v3_dec"], HextRec["anisotropy_v3_inc"], HextRec["anisotropy_v3_eta_semi_angle"], HextRec["anisotropy_v3_eta_dec"],
                          HextRec["anisotropy_v3_eta_inc"], HextRec["anisotropy_v3_zeta_semi_angle"], HextRec["anisotropy_v3_zeta_dec"], HextRec["anisotropy_v3_zeta_inc"])
                HextRec['magic_software_packages'] = version_num
                ResRecs.append(HextRec)
            if bpars != []:
                BootRec = {}
                for key in ResRec.keys():
                    BootRec[key] = ResRec[key]   # copy over stuff
                BootRec["anisotropy_v1_dec"] = '%7.1f' % (bpars["v1_dec"])
                BootRec["anisotropy_v2_dec"] = '%7.1f' % (bpars["v2_dec"])
                BootRec["anisotropy_v3_dec"] = '%7.1f' % (bpars["v3_dec"])
                BootRec["anisotropy_v1_inc"] = '%7.1f' % (bpars["v1_inc"])
                BootRec["anisotropy_v2_inc"] = '%7.1f' % (bpars["v2_inc"])
                BootRec["anisotropy_v3_inc"] = '%7.1f' % (bpars["v3_inc"])
                BootRec["anisotropy_t1"] = '%10.8f' % (bpars["t1"])
                BootRec["anisotropy_t2"] = '%10.8f' % (bpars["t2"])
                BootRec["anisotropy_t3"] = '%10.8f' % (bpars["t3"])
                BootRec["anisotropy_v1_eta_inc"] = '%7.1f ' % (
                    bpars["v1_eta_inc"])
                BootRec["anisotropy_v1_eta_dec"] = '%7.1f ' % (
                    bpars["v1_eta_dec"])
                BootRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % (
                    bpars["v1_eta"])
                BootRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % (
                    bpars["v1_zeta_inc"])
                BootRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % (
                    bpars["v1_zeta_dec"])
                BootRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % (
                    bpars["v1_zeta"])
                BootRec["anisotropy_v2_eta_inc"] = '%7.1f ' % (
                    bpars["v2_eta_inc"])
                BootRec["anisotropy_v2_eta_dec"] = '%7.1f ' % (
                    bpars["v2_eta_dec"])
                BootRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % (
                    bpars["v2_eta"])
                BootRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % (
                    bpars["v2_zeta_inc"])
                BootRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % (
                    bpars["v2_zeta_dec"])
                BootRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % (
                    bpars["v2_zeta"])
                BootRec["anisotropy_v3_eta_inc"] = '%7.1f ' % (
                    bpars["v3_eta_inc"])
                BootRec["anisotropy_v3_eta_dec"] = '%7.1f ' % (
                    bpars["v3_eta_dec"])
                BootRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % (
                    bpars["v3_eta"])
                BootRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % (
                    bpars["v3_zeta_inc"])
                BootRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % (
                    bpars["v3_zeta_dec"])
                BootRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % (
                    bpars["v3_zeta"])
                BootRec["anisotropy_hext_F"] = ''
                BootRec["anisotropy_hext_F12"] = ''
                BootRec["anisotropy_hext_F23"] = ''
                # regular bootstrap
                BootRec["magic_method_codes"] = 'LP-AN:AE-H:AE-BS'
                if ipar == 1:
                    # parametric bootstrap
                    BootRec["magic_method_codes"] = 'LP-AN:AE-H:AE-BS-P'
                if verbose:
                    print("Boostrap Statistics: ")
                    print(
                        " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I")
                    print(BootRec["anisotropy_t1"], BootRec["anisotropy_v1_dec"], BootRec["anisotropy_v1_inc"], BootRec["anisotropy_v1_eta_semi_angle"], BootRec["anisotropy_v1_eta_dec"],
                          BootRec["anisotropy_v1_eta_inc"], BootRec["anisotropy_v1_zeta_semi_angle"], BootRec["anisotropy_v1_zeta_dec"], BootRec["anisotropy_v1_zeta_inc"])
                    print(BootRec["anisotropy_t2"], BootRec["anisotropy_v2_dec"], BootRec["anisotropy_v2_inc"], BootRec["anisotropy_v2_eta_semi_angle"], BootRec["anisotropy_v2_eta_dec"],
                          BootRec["anisotropy_v2_eta_inc"], BootRec["anisotropy_v2_zeta_semi_angle"], BootRec["anisotropy_v2_zeta_dec"], BootRec["anisotropy_v2_zeta_inc"])
                    print(BootRec["anisotropy_t3"], BootRec["anisotropy_v3_dec"], BootRec["anisotropy_v3_inc"], BootRec["anisotropy_v3_eta_semi_angle"], BootRec["anisotropy_v3_eta_dec"],
                          BootRec["anisotropy_v3_eta_inc"], BootRec["anisotropy_v3_zeta_semi_angle"], BootRec["anisotropy_v3_zeta_dec"], BootRec["anisotropy_v3_zeta_inc"])
                BootRec['magic_software_packages'] = version_num
                ResRecs.append(BootRec)
            k += 1
            goon = 1
            while goon == 1 and iplot == 1 and verbose:
                if iboot == 1:
                    print("compare with [d]irection ")
                print(
                    " plot [g]reat circle,  change [c]oord. system, change [e]llipse calculation,  s[a]ve plots, [q]uit ")
                if isite == 1:
                    print("  [p]revious, [s]ite, [q]uit, <return> for next ")
                ans = input("")
                if ans == "q":
                    sys.exit()
                if ans == "e":
                    iboot, ipar, ihext, ivec = 1, 0, 0, 0
                    e = input("Do Hext Statistics  1/[0]: ")
                    if e == "1":
                        ihext = 1
                    e = input("Suppress bootstrap 1/[0]: ")
                    if e == "1":
                        iboot = 0
                    if iboot == 1:
                        e = input("Parametric bootstrap 1/[0]: ")
                        if e == "1":
                            ipar = 1
                        e = input("Plot bootstrap eigenvectors:  1/[0]: ")
                        if e == "1":
                            ivec = 1
                        if iplot == 1:
                            if inittcdf == 0:
                                ANIS['tcdf'] = 3
                                pmagplotlib.plot_init(ANIS['tcdf'], 5, 5)
                                inittcdf = 1
                    bpars, hpars = pmagplotlib.plot_anis(
                        ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb)
                    if verbose and plots == 0:
                        pmagplotlib.draw_figs(ANIS)
                if ans == "c":
                    print("Current Coordinate system is: ")
                    if CS == '-1':
                        print(" Specimen")
                    if CS == '0':
                        print(" Geographic")
                    if CS == '100':
                        print(" Tilt corrected")
                    key = input(
                        " Enter desired coordinate system: [s]pecimen, [g]eographic, [t]ilt corrected ")
                    if key == 's':
                        CS = '-1'
                    if key == 'g':
                        CS = '0'
                    if key == 't':
                        CS = '100'
                    if CS not in orlist:
                        if len(orlist) > 0:
                            CS = orlist[0]
                        else:
                            CS = '-1'
                        if CS == '-1':
                            crd = 's'
                        if CS == '0':
                            crd = 'g'
                        if CS == '100':
                            crd = 't'
                        print(
                            "desired coordinate system not available, using available: ", crd)
                    k -= 1
                    goon = 0
                if ans == "":
                    if isite == 1:
                        goon = 0
                    else:
                        print("Good bye ")
                        sys.exit()
                if ans == 'd':
                    if initcdf == 0:
                        initcdf = 1
                        ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6
                        pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5)
                        pmagplotlib.plot_init(ANIS['vycdf'], 5, 5)
                        pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5)
                    Dir, comp = [], 1
                    print("""
                      Input: Vi D I to  compare  eigenvector Vi with direction D/I
                             where Vi=1: principal
                                   Vi=2: major
                                   Vi=3: minor
                                   D= declination of comparison direction
                                   I= inclination of comparison direction""")
                    con = 1
                    while con == 1:
                        try:
                            vdi = input("Vi D I: ").split()
                            vec = int(vdi[0])-1
                            Dir = [float(vdi[1]), float(vdi[2])]
                            con = 0
                        except IndexError:
                            print(" Incorrect entry, try again ")
                    bpars, hpars = pmagplotlib.plot_anis(
                        ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb)
                    Dir, comp = [], 0
                if ans == 'g':
                    con, cnt = 1, 0
                    while con == 1:
                        try:
                            print(
                                " Input:  input pole to great circle ( D I) to  plot a great circle:   ")
                            di = input(" D I: ").split()
                            PDir.append(float(di[0]))
                            PDir.append(float(di[1]))
                            con = 0
                        except:
                            cnt += 1
                            if cnt < 10:
                                print(
                                    " enter the dec and inc of the pole on one line ")
                            else:
                                print(
                                    "ummm - you are doing something wrong - i give up")
                                sys.exit()
                    pmagplotlib.plot_circ(ANIS['data'], PDir, 90., 'g')
                    pmagplotlib.plot_circ(ANIS['conf'], PDir, 90., 'g')
                    if verbose and plots == 0:
                        pmagplotlib.draw_figs(ANIS)
                if ans == "p":
                    k -= 2
                    goon = 0
                if ans == "q":
                    k = plt
                    goon = 0
                if ans == "s":
                    keepon = 1
                    site = input(" print site or part of site desired: ")
                    while keepon == 1:
                        try:
                            k = sitelist.index(site)
                            keepon = 0
                        except:
                            tmplist = []
                            for qq in range(len(sitelist)):
                                if site in sitelist[qq]:
                                    tmplist.append(sitelist[qq])
                            print(site, " not found, but this was: ")
                            print(tmplist)
                            site = input('Select one or try again\n ')
                            k = sitelist.index(site)
                    goon, ans = 0, ""
                if ans == "a":
                    locs = pmag.makelist(Locs)
                    if pmagplotlib.isServer:  # use server plot naming convention
                        title = "LO:_"+locs+'_SI:__'+'_SA:__SP:__CO:_'+crd
                    else:  # use more readable plot naming convention
                        title = "{}_{}".format(locs, crd)
                    save(ANIS, fmt, title)
                    goon = 0
        else:
            if verbose:
                print('skipping plot - not enough data points')
            k += 1
#   put rmag_results stuff here
    if len(ResRecs) > 0:
        ResOut, keylist = pmag.fillkeys(ResRecs)
        pmag.magic_write(outfile, ResOut, 'rmag_results')
    if verbose:
        print(" Good bye ")
Ejemplo n.º 40
0
def main():
    """
    NAME
       histplot.py

    DESCRIPTION
       makes histograms for data

    OPTIONS
       -h prints help message and quits
       -f input file name
       -b binsize
       -fmt [svg,png,pdf,eps,jpg] specify format for image, default is svg
       -sav save figure and quit
       -F output file name, default is hist.fmt
       -N don't normalize
       -twin plot both normalized and un-normalized y axes
       -xlab Label of X axis
       -ylab Label of Y axis

    INPUT FORMAT
        single variable

    SYNTAX
       histplot.py [command line options] [<file]

    """
    fname, fmt = "", 'svg'
    plot = 0
    if '-sav' in sys.argv:
        plot = 1
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind+1]
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        fname = sys.argv[ind+1]
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        outfile = sys.argv[ind+1]
        fmt = ""
    else:
        outfile = 'hist.'+fmt
    if '-N' in sys.argv:
        norm = 0
        ylab = 'Number'
    else:
        norm = 1
        ylab = 'Frequency'
    if '-twin' in sys.argv:
        norm=-1
    binsize = 0
    if '-b' in sys.argv:
        ind = sys.argv.index('-b')
        binsize = int(sys.argv[ind+1])
    if '-xlab' in sys.argv:
        ind = sys.argv.index('-xlab')
        xlab = sys.argv[ind+1]
    else:
        xlab = 'x'
    if fname != "":
        D = np.loadtxt(fname)
    else:
        print('-I- Trying to read from stdin... <ctrl>-c to quit')
        D = np.loadtxt(sys.stdin, dtype=np.float)
    # read in data
    #
    try:
        if not D:
            print('-W- No data found')
            return
    except ValueError:
        pass
    fig = pmagplotlib.plot_init(1, 8, 7)
    try:
        len(D)
    except TypeError:
        D = np.array([D])
    if len(D) < 5:
        print("-W- Not enough points to plot histogram ({} point(s) provided, 5 required)".format(len(D)))
        return
    # if binsize not provided, calculate reasonable binsize
    if not binsize:
        binsize = int(np.around(1 + 3.22 * np.log(len(D))))
    Nbins = int(len(D) / binsize)
    ax = fig.add_subplot(111)
    if norm==1:
        print ('normalizing')
        n, bins, patches = ax.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=True)
        ax.set_ylabel(ylab)
    elif norm==0:
        print ('not normalizing')
        n, bins, patches = ax.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=False)
        ax.set_ylabel(ylab)
    elif norm==-1:
        print ('trying twin')
        n, bins, patches = ax.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=True)
        ax.set_ylabel('Frequency')
        ax2=ax.twinx()
        n, bins, patches = ax2.hist(
            D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=False)
        ax2.set_ylabel('Number',rotation=-90)
    plt.axis([D.min(), D.max(), 0, n.max()+.1*n.max()])
    ax.set_xlabel(xlab)
    name = 'N = ' + str(len(D))
    plt.title(name)
    if plot == 0:
        pmagplotlib.draw_figs({1: 'hist'})
        p = input('s[a]ve to save plot, [q]uit to exit without saving  ')
        if p != 'a':
            sys.exit()
    if pmagplotlib.isServer:
        pmagplotlib.add_borders({'hist': 1}, {'hist': 'Intensity Histogram'})
    plt.savefig(outfile)
    print('plot saved in ', outfile)
Ejemplo n.º 41
0
def main():
    """
    NAME
       revtest_MM1990.py

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

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

    SYNTAX
       revtest_MM1990.py [command line options]

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

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

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

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

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

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

    if V>Vcrit:
        print("")
    elif V<Vcrit:
        if critical_angle<5:
            print("The McFadden and McElhinny (1990) classification for this test is: 'A'")
        elif critical_angle<10:
            print("The McFadden and McElhinny (1990) classification for this test is: 'B'")
        elif critical_angle<20:
            print("The McFadden and McElhinny (1990) classification for this test is: 'C'")
        else:
            print("The McFadden and McElhinny (1990) classification for this test is: 'INDETERMINATE;")
    if plot==1:
        CDF={'cdf':1}
        pmagplotlib.plot_init(CDF['cdf'],5,5)
        p1 = pmagplotlib.plot_cdf(CDF['cdf'],Vp,"Watson's V",'r',"")
        p2 = pmagplotlib.plot_vs(CDF['cdf'],[V],'g','-')
        p3 = pmagplotlib.plot_vs(CDF['cdf'],[Vp[k]],'b','--')
        pmagplotlib.draw_figs(CDF)
        files,fmt={},'svg'
        if file2!="":
            files['cdf']='WatsonsV_'+file1+'_'+file2+'.'+fmt
        else:
            files['cdf']='WatsonsV_'+file1+'.'+fmt
        if pmagplotlib.isServer:
            black     = '#000000'
            purple    = '#800080'
            titles={}
            titles['cdf']='Cumulative Distribution'
            CDF = pmagplotlib.add_borders(CDF,titles,black,purple)
            pmagplotlib.save_plots(CDF,files)
        else:
            ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans=="a": pmagplotlib.save_plots(CDF,files)
Ejemplo n.º 42
0
def main():
    """
    NAME
        zeq_magic.py

    DESCRIPTION
        reads in magic_measurements formatted file, makes plots of remanence decay
        during demagnetization experiments.  Reads in prior interpretations saved in
        a pmag_specimens formatted file [and  allows re-interpretations of best-fit lines
        and planes and saves (revised or new) interpretations in a pmag_specimens file.
        interpretations are saved in the coordinate system used. Also allows judicious editting of
        measurements to eliminate "bad" measurements.  These are marked as such in the magic_measurements
        input file.  they are NOT deleted, just ignored. ] Bracketed part not yet implemented

    SYNTAX
        zeq_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f  MEASFILE: sets measurements format input file, default: measurements.txt
        -fsp SPECFILE: sets specimens format file with prior interpreations, default: specimens.txt
        -fsa SAMPFILE: sets samples format file sample=>site information, default: samples.txt
        -fsi SITEFILE: sets sites format file with site=>location informationprior interpreations, default: samples.txt
        -Fp PLTFILE: sets filename for saved plot, default is name_type.fmt (where type is zijd, eqarea or decay curve)
        -crd [s,g,t]: sets coordinate system,  g=geographic, t=tilt adjusted, default: specimen coordinate system
        -spc SPEC  plots single specimen SPEC, saves plot with specified format
              with optional -dir settings and quits
        -dir [L,P,F][beg][end]: sets calculation type for principal component analysis, default is none
             beg: starting step for PCA calculation
             end: ending step for PCA calculation
             [L,P,F]: calculation type for line, plane or fisher mean
             must be used with -spc option
        -fmt FMT: set format of saved plot [png,svg,jpg]
        -A:  suppresses averaging of  replicate measurements, default is to average
        -sav: saves all plots without review
    SCREEN OUTPUT:
        Specimen, N, a95, StepMin, StepMax, Dec, Inc, calculation type

    """
    # initialize some variables
    doave, e, b = 1, 0, 0  # average replicates, initial end and beginning step
    intlist = ['magn_moment', 'magn_volume', 'magn_mass', 'magnitude']
    plots, coord = 0, 's'
    noorient = 0
    version_num = pmag.get_version()
    verbose = pmagplotlib.verbose
    calculation_type, fmt = "", "svg"
    spec_keys = []
    geo, tilt, ask = 0, 0, 0
    PriorRecs = []  # empty list for prior interpretations
    backup = 0
    specimen = ""  # can skip everything and just plot one specimen with bounds e,b
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", default_val=os.getcwd())
    meas_file = pmag.get_named_arg("-f", default_val="measurements.txt")
    spec_file = pmag.get_named_arg("-fsp", default_val="specimens.txt")
    samp_file = pmag.get_named_arg("-fsa", default_val="samples.txt")
    site_file = pmag.get_named_arg("-fsi", default_val="sites.txt")
    #meas_file = os.path.join(dir_path, meas_file)
    #spec_file = os.path.join(dir_path, spec_file)
    #samp_file = os.path.join(dir_path, samp_file)
    #site_file = os.path.join(dir_path, site_file)
    plot_file = pmag.get_named_arg("-Fp", default_val="")
    crd = pmag.get_named_arg("-crd", default_val="s")
    if crd == "s":
        coord = "-1"
    elif crd == "t":
        coord = "100"
    else:
        coord = "0"
    saved_coord = coord
    fmt = pmag.get_named_arg("-fmt", "svg")
    specimen = pmag.get_named_arg("-spc", default_val="")
    #if specimen: # just save plot and exit
    #    plots, verbose = 1, 0
    beg_pca, end_pca = "", ""
    if '-dir' in sys.argv:
        ind = sys.argv.index('-dir')
        direction_type = sys.argv[ind + 1]
        beg_pca = int(sys.argv[ind + 2])
        end_pca = int(sys.argv[ind + 3])
        if direction_type == 'L':
            calculation_type = 'DE-BFL'
        if direction_type == 'P':
            calculation_type = 'DE-BFP'
        if direction_type == 'F':
            calculation_type = 'DE-FM'
    if '-A' in sys.argv:
        doave = 0
    if '-sav' in sys.argv:
        plots, verbose = 1, 0
    #
    first_save = 1
    fnames = {
        'measurements': meas_file,
        'specimens': spec_file,
        'samples': samp_file,
        'sites': site_file
    }
    contribution = cb.Contribution(
        dir_path,
        custom_filenames=fnames,
        read_tables=['measurements', 'specimens', 'samples', 'sites'])
    #
    #   import  specimens

    if 'measurements' not in contribution.tables:
        print('-W- No measurements table found in your working directory')
        return

    specimen_cols = [
        'analysts', 'aniso_ftest', 'aniso_ftest12', 'aniso_ftest23', 'aniso_s',
        'aniso_s_mean', 'aniso_s_n_measurements', 'aniso_s_sigma',
        'aniso_s_unit', 'aniso_tilt_correction', 'aniso_type', 'aniso_v1',
        'aniso_v2', 'aniso_v3', 'citations', 'description', 'dir_alpha95',
        'dir_comp', 'dir_dec', 'dir_inc', 'dir_mad_free', 'dir_n_measurements',
        'dir_tilt_correction', 'experiments', 'geologic_classes',
        'geologic_types', 'hyst_bc', 'hyst_bcr', 'hyst_mr_moment',
        'hyst_ms_moment', 'int_abs', 'int_b', 'int_b_beta', 'int_b_sigma',
        'int_corr', 'int_dang', 'int_drats', 'int_f', 'int_fvds', 'int_gamma',
        'int_mad_free', 'int_md', 'int_n_measurements', 'int_n_ptrm', 'int_q',
        'int_rsc', 'int_treat_dc_field', 'lithologies', 'meas_step_max',
        'meas_step_min', 'meas_step_unit', 'method_codes', 'sample',
        'software_packages', 'specimen'
    ]
    if 'specimens' in contribution.tables:
        contribution.propagate_name_down('sample', 'measurements')
        # add location/site info to measurements table for naming plots
        if pmagplotlib.isServer:
            contribution.propagate_name_down('site', 'measurements')
            contribution.propagate_name_down('location', 'measurements')
        spec_container = contribution.tables['specimens']
        if 'method_codes' not in spec_container.df.columns:
            spec_container.df['method_codes'] = None
        prior_spec_data = spec_container.get_records_for_code(
            'LP-DIR', strict_match=False
        )  # look up all prior directional interpretations
#
#  tie sample names to measurement data
#
    else:
        spec_container, prior_spec_data = None, []

#
#   import samples  for orientation info
#
    if 'samples' in contribution.tables:
        samp_container = contribution.tables['samples']
        samps = samp_container.df
        samp_data = samps.to_dict(
            'records'
        )  # convert to list of dictionaries for use with get_orient
    else:
        samp_data = []
    #if ('samples' in contribution.tables) and ('specimens' in contribution.tables):
    #    #        contribution.propagate_name_down('site','measurements')
    #    contribution.propagate_cols(col_names=[
    #                                'azimuth', 'dip', 'orientation_quality','bed_dip','bed_dip_direction'], target_df_name='measurements', source_df_name='samples')
##
# define figure numbers for equal area, zijderveld,
#  and intensity vs. demagnetiztion step respectively
#
    ZED = {}
    ZED['eqarea'], ZED['zijd'], ZED['demag'] = 1, 2, 3
    pmagplotlib.plot_init(ZED['eqarea'], 6, 6)
    pmagplotlib.plot_init(ZED['zijd'], 6, 6)
    pmagplotlib.plot_init(ZED['demag'], 6, 6)
    #    save_pca=0
    angle, direction_type, setangle = "", "", 0
    #   create measurement dataframe
    #
    meas_container = contribution.tables['measurements']
    meas_data = meas_container.df
    #
    meas_data = meas_data[meas_data['method_codes'].str.contains(
        'LT-NO|LT-AF-Z|LT-T-Z|LT-M-Z') == True]  # fish out steps for plotting
    meas_data = meas_data[meas_data['method_codes'].str.contains(
        'AN|ARM|LP-TRM|LP-PI-ARM') == False]  # strip out unwanted experiments
    intensity_types = [
        col_name for col_name in meas_data.columns if col_name in intlist
    ]
    intensity_types = [
        col_name for col_name in intensity_types if any(meas_data[col_name])
    ]
    if not len(intensity_types):
        print('-W- No intensity columns found')
        return
    # plot first non-empty intensity method found - normalized to initial value anyway -
    # doesn't matter which used
    int_key = intensity_types[0]
    # get all the non-null intensity records of the same type
    meas_data = meas_data[meas_data[int_key].notnull()]
    if 'quality' not in meas_data.columns:
        meas_data['quality'] = 'g'  # set the default flag to good
# need to treat LP-NO specially  for af data, treatment should be zero,
# otherwise 273.
#meas_data['treatment'] = meas_data['treat_ac_field'].where(
#    cond=meas_data['treat_ac_field'] != 0, other=meas_data['treat_temp'])
    meas_data['treatment'] = meas_data['treat_ac_field'].where(
        cond=meas_data['treat_ac_field'].astype(bool),
        other=meas_data['treat_temp'])
    meas_data['ZI'] = 1  # initialize these to one
    meas_data['instrument_codes'] = ""  # initialize these to blank
    #   for unusual case of microwave power....
    if 'treat_mw_power' in meas_data.columns:
        meas_data.loc[
            (meas_data.treat_mw_power != 0) & (meas_data.treat_mw_power) &
            (meas_data.treat_mw_time),
            'treatment'] = meas_data.treat_mw_power * meas_data.treat_mw_time
#
# get list of unique specimen names from measurement data
#
# this is a list of all the specimen names
    specimen_names = meas_data.specimen.unique()
    specimen_names = specimen_names.tolist()
    specimen_names.sort()
    #
    # set up new DataFrame for this sessions specimen interpretations
    #
    data_container = cb.MagicDataFrame(dtype='specimens',
                                       columns=specimen_cols)
    # this is for interpretations from this session
    current_spec_data = data_container.df
    if specimen == "":
        k = 0
    else:
        k = specimen_names.index(specimen)
    # let's look at the data now
    while k < len(specimen_names):
        mpars = {"specimen_direction_type": "Error"}
        # set the current specimen for plotting
        this_specimen = specimen_names[k]
        # reset beginning/end pca if plotting more than one specimen
        if not specimen:
            beg_pca, end_pca = "", ""
        if verbose and this_specimen != "":
            print(this_specimen, k + 1, 'out of ', len(specimen_names))
        if setangle == 0:
            angle = ""
        this_specimen_measurements = meas_data[
            meas_data['specimen'].str.contains(this_specimen).astype(
                bool)]  # fish out this specimen
        this_specimen_measurements = this_specimen_measurements[
            -this_specimen_measurements['quality'].str.contains('b').astype(
                bool)]  # remove bad measurements
        if len(this_specimen_measurements) != 0:  # if there are measurements
            meas_list = this_specimen_measurements.to_dict(
                'records')  # get a list of dictionaries
            this_sample = ""
            if coord != '-1' and 'sample' in meas_list[0].keys(
            ):  # look up sample name
                this_sample = pmag.get_dictitem(meas_list, 'specimen',
                                                this_specimen, 'T')
                if len(this_sample) > 0:
                    this_sample = this_sample[0]['sample']
            #
            #    set up datablock [[treatment,dec, inc, int, direction_type],[....]]
            #
            #
            # figure out the method codes
            #
            units, methods, title = "", "", this_specimen

            if pmagplotlib.isServer:
                try:
                    loc = this_specimen_measurements.loc[:,
                                                         'location'].values[0]
                except:
                    loc = ""
                try:
                    site = this_specimen_measurements.loc[:, 'site'].values[0]
                except:
                    site = ""
                try:
                    samp = this_specimen_measurements.loc[:,
                                                          'sample'].values[0]
                except:
                    samp = ""
                title = "LO:_{}_SI:_{}_SA:_{}_SP:_{}_".format(
                    loc, site, samp, this_specimen)
            # this is a list of all the specimen method codes
            meas_meths = this_specimen_measurements.method_codes.unique()
            tr = pd.to_numeric(this_specimen_measurements.treatment).tolist()
            if any(cb.is_null(treat, False) for treat in tr):
                print(
                    '-W- Missing required values in measurements.treatment for {}, skipping'
                    .format(this_specimen))
                if specimen:
                    return
                k += 1
                continue
            if set(tr) == set([0]):
                print(
                    '-W- Missing required values in measurements.treatment for {}, skipping'
                    .format(this_specimen))
                if specimen:
                    return
                k += 1
                continue
            for m in meas_meths:
                if 'LT-AF-Z' in m and 'T' not in units:
                    units = 'T'  # units include tesla
                    tr[0] = 0
                if 'LT-T-Z' in m and 'K' not in units:
                    units = units + ":K"  # units include kelvin
                if 'LT-M-Z' in m and 'J' not in units:
                    units = units + ':J'  # units include joules
                    tr[0] = 0
                units = units.strip(':')  # strip off extra colons
                if 'LP-' in m:
                    methods = methods + ":" + m
            decs = pd.to_numeric(this_specimen_measurements.dir_dec).tolist()
            incs = pd.to_numeric(this_specimen_measurements.dir_inc).tolist()

            #
            #    fix the coordinate system
            #
            # revert to original coordinate system
            coord = saved_coord
            if coord != '-1':  # need to transform coordinates to geographic
                # get the azimuth
                or_info, az_type = pmag.get_orient(samp_data,
                                                   this_sample,
                                                   data_model=3)
                if 'azimuth' in or_info.keys() and cb.not_null(
                        or_info['azimuth']):
                    #azimuths = pd.to_numeric(
                    #    this_specimen_measurements.azimuth).tolist()
                    #dips = pd.to_numeric(this_specimen_measurements.dip).tolist()
                    azimuths = len(decs) * [or_info['azimuth']]
                    dips = len(decs) * [or_info['dip']]
                # if azimuth/dip is missing, plot using specimen coordinates instead
                else:
                    azimuths, dips = [], []
                if any([cb.is_null(az) for az in azimuths if az != 0]):
                    coord = '-1'
                    print("-W- Couldn't find azimuth and dip for {}".format(
                        this_specimen))
                    print("    Plotting with specimen coordinates instead")
                elif any([cb.is_null(dip) for dip in dips if dip != 0]):
                    coord = '-1'
                    print("-W- Couldn't find azimuth and dip for {}".format(
                        this_specimen))
                    print("    Plotting with specimen coordinates instead")
                else:
                    coord = saved_coord
                # if azimuth and dip were found, continue with geographic coordinates
                if coord != "-1" and len(azimuths) > 0:
                    dirs = [decs, incs, azimuths, dips]
                    # this transposes the columns and rows of the list of lists
                    dirs_geo = np.array(list(map(list, list(zip(*dirs)))))
                    decs, incs = pmag.dogeo_V(dirs_geo)
                    if coord == '100' and 'bed_dip_direction' in or_info.keys(
                    ) and or_info[
                            'bed_dip_direction'] != "":  # need to do tilt correction too
                        bed_dip_dirs = len(decs) * [
                            or_info['bed_dip_direction']
                        ]
                        bed_dips = len(decs) * [or_info['bed_dip']]
                        #bed_dip_dirs = pd.to_numeric(
                        #    this_specimen_measurements.bed_dip_direction).tolist()  # get the azimuths
                        #bed_dips = pd.to_numeric(
                        #    this_specimen_measurements.bed_dip).tolist()  # get the azimuths

                        dirs = [decs, incs, bed_dip_dirs, bed_dips]
                        ## this transposes the columns and rows of the list of lists
                        dirs_tilt = np.array(list(map(list, list(zip(*dirs)))))
                        decs, incs = pmag.dotilt_V(dirs_tilt)
                        if pmagplotlib.isServer:
                            title = title + "CO:_t_"
                        else:
                            title = title + '_t'
                    else:
                        if pmagplotlib.isServer:
                            title = title + "CO:_g_"
                        else:
                            title = title + '_g'
            if angle == "":
                angle = decs[0]
            ints = pd.to_numeric(this_specimen_measurements[int_key]).tolist()
            ZI = this_specimen_measurements.ZI.tolist()
            flags = this_specimen_measurements.quality.tolist()
            codes = this_specimen_measurements.instrument_codes.tolist()
            datalist = [tr, decs, incs, ints, ZI, flags, codes]
            # this transposes the columns and rows of the list of lists
            datablock = list(map(list, list(zip(*datalist))))
            pmagplotlib.plot_zed(ZED, datablock, angle, title, units)
            if verbose and not set_env.IS_WIN:
                pmagplotlib.draw_figs(ZED)
#
#     collect info for current_specimen_interpretation dictionary
#

#
#     find prior interpretation
#
            prior_specimen_interpretations = []
            if len(prior_spec_data):
                prior_specimen_interpretations = prior_spec_data[
                    prior_spec_data['specimen'].str.contains(
                        this_specimen) == True]
            if (beg_pca == "") and (len(prior_specimen_interpretations) != 0):
                if len(prior_specimen_interpretations) > 0:
                    beg_pcas = pd.to_numeric(prior_specimen_interpretations.
                                             meas_step_min.values).tolist()
                    end_pcas = pd.to_numeric(prior_specimen_interpretations.
                                             meas_step_max.values).tolist()
                    spec_methods = prior_specimen_interpretations.method_codes.tolist(
                    )
                    # step through all prior interpretations and plot them
                    for ind in range(len(beg_pcas)):
                        spec_meths = spec_methods[ind].split(':')
                        for m in spec_meths:
                            if 'DE-BFL' in m:
                                calculation_type = 'DE-BFL'  # best fit line
                            if 'DE-BFP' in m:
                                calculation_type = 'DE-BFP'  # best fit plane
                            if 'DE-FM' in m:
                                calculation_type = 'DE-FM'  # fisher mean
                            if 'DE-BFL-A' in m:
                                calculation_type = 'DE-BFL-A'  # anchored best fit line
                        if len(beg_pcas) != 0:
                            try:
                                # getting the starting and ending points
                                start, end = tr.index(beg_pcas[ind]), tr.index(
                                    end_pcas[ind])
                                mpars = pmag.domean(datablock, start, end,
                                                    calculation_type)
                            except ValueError:
                                print(
                                    '-W- Specimen record contains invalid start/stop bounds:'
                                )
                                mpars['specimen_direction_type'] = "Error"
                        # calculate direction/plane
                            if mpars["specimen_direction_type"] != "Error":
                                # put it on the plot
                                pmagplotlib.plot_dir(ZED, mpars, datablock,
                                                     angle)
                                if verbose and not set_env.IS_WIN:
                                    pmagplotlib.draw_figs(ZED)
### SKIP if no prior interpretation - this section should not be used:
#            else:
#                try:
#                    start, end = int(beg_pca), int(end_pca)
#                except ValueError:
#                    beg_pca = 0
#                    end_pca = len(datablock) - 1
#                    start, end = int(beg_pca), int(end_pca)
#            #    # calculate direction/plane
#                try:
#                    mpars = pmag.domean(datablock, start, end, calculation_type)
#                except Exception as ex:
#                    print('-I- Problem with {}'.format(this_specimen))
#                    print('   ', ex)
#                    print('    Skipping')
#                    continue
#                    k += 1
#                if mpars["specimen_direction_type"] != "Error":
#                    # put it on the plot
#                    pmagplotlib.plot_dir(ZED, mpars, datablock, angle)
#                    if verbose:
#                        pmagplotlib.draw_figs(ZED)

            if plots == 1 or specimen != "":
                if plot_file == "":
                    basename = title
                else:
                    basename = plot_file
                files = {}
                for key in list(ZED.keys()):
                    files[key] = basename + '_' + key + '.' + fmt
                    if pmagplotlib.isServer:
                        files[key] = basename + "TY:_{}_.".format(key) + fmt
                pmagplotlib.save_plots(ZED, files)
                if specimen != "":
                    sys.exit()
            if verbose:
                recnum = 0
                for plotrec in datablock:
                    if units == 'T':
                        print('%s: %i  %7.1f %s  %8.3e %7.1f %7.1f %s' %
                              (plotrec[5], recnum, plotrec[0] * 1e3, " mT",
                               plotrec[3], plotrec[1], plotrec[2], plotrec[6]))
                    if units == "K":
                        print('%s: %i  %7.1f %s  %8.3e %7.1f %7.1f %s' %
                              (plotrec[5], recnum, plotrec[0] - 273, ' C',
                               plotrec[3], plotrec[1], plotrec[2], plotrec[6]))
                    if units == "J":
                        print('%s: %i  %7.1f %s  %8.3e %7.1f %7.1f %s' %
                              (plotrec[5], recnum, plotrec[0], ' J',
                               plotrec[3], plotrec[1], plotrec[2], plotrec[6]))
                    if 'K' in units and 'T' in units:
                        if plotrec[0] >= 1.:
                            print('%s: %i  %7.1f %s  %8.3e %7.1f %7.1f %s' %
                                  (plotrec[5], recnum, plotrec[0] - 273, ' C',
                                   plotrec[3], plotrec[1], plotrec[2],
                                   plotrec[6]))
                        if plotrec[0] < 1.:
                            print('%s: %i  %7.1f %s  %8.3e %7.1f %7.1f %s' %
                                  (plotrec[5], recnum, plotrec[0] * 1e3, " mT",
                                   plotrec[3], plotrec[1], plotrec[2],
                                   plotrec[6]))
                    recnum += 1
            # we have a current interpretation
            elif mpars["specimen_direction_type"] != "Error":
                #
                # create a new specimen record for the interpreation for this
                # specimen
                this_specimen_interpretation = {
                    col: ""
                    for col in specimen_cols
                }
                #               this_specimen_interpretation["analysts"]=user
                this_specimen_interpretation['software_packages'] = version_num
                this_specimen_interpretation['specimen'] = this_specimen
                this_specimen_interpretation["method_codes"] = calculation_type
                this_specimen_interpretation["meas_step_unit"] = units
                this_specimen_interpretation["meas_step_min"] = tr[start]
                this_specimen_interpretation["meas_step_max"] = tr[end]
                this_specimen_interpretation["dir_dec"] = '%7.1f' % (
                    mpars['specimen_dec'])
                this_specimen_interpretation["dir_inc"] = '%7.1f' % (
                    mpars['specimen_inc'])
                this_specimen_interpretation["dir_dang"] = '%7.1f' % (
                    mpars['specimen_dang'])
                this_specimen_interpretation["dir_n_measurements"] = '%i' % (
                    mpars['specimen_n'])
                this_specimen_interpretation["dir_tilt_correction"] = coord
                methods = methods.replace(" ", "")
                if "T" in units:
                    methods = methods + ":LP-DIR-AF"
                if "K" in units:
                    methods = methods + ":LP-DIR-T"
                if "J" in units:
                    methods = methods + ":LP-DIR-M"
                this_specimen_interpretation["method_codes"] = methods.strip(
                    ':')
                this_specimen_interpretation[
                    "experiments"] = this_specimen_measurements.experiment.unique(
                    )[0]
                #
                #   print some stuff
                #
                if calculation_type != 'DE-FM':
                    this_specimen_interpretation["dir_mad_free"] = '%7.1f' % (
                        mpars['specimen_mad'])
                    this_specimen_interpretation["dir_alpha95"] = ''
                    if verbose:
                        if units == 'K':
                            print(
                                '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n'
                                %
                                (this_specimen_interpretation["specimen"],
                                 int(this_specimen_interpretation[
                                     "dir_n_measurements"]),
                                 float(this_specimen_interpretation[
                                     "dir_mad_free"]),
                                 float(
                                     this_specimen_interpretation["dir_dang"]),
                                 float(this_specimen_interpretation[
                                     "meas_step_min"]) - 273,
                                 float(this_specimen_interpretation[
                                     "meas_step_max"]) - 273,
                                 float(
                                     this_specimen_interpretation["dir_dec"]),
                                 float(
                                     this_specimen_interpretation["dir_inc"]),
                                 calculation_type))
                        elif units == 'T':
                            print(
                                '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n'
                                %
                                (this_specimen_interpretation["specimen"],
                                 int(this_specimen_interpretation[
                                     "dir_n_measurements"]),
                                 float(this_specimen_interpretation[
                                     "dir_mad_free"]),
                                 float(
                                     this_specimen_interpretation["dir_dang"]),
                                 float(this_specimen_interpretation[
                                     "meas_step_min"]) * 1e3,
                                 float(this_specimen_interpretation[
                                     "meas_step_max"]) * 1e3,
                                 float(
                                     this_specimen_interpretation["dir_dec"]),
                                 float(
                                     this_specimen_interpretation["dir_inc"]),
                                 calculation_type))
                        elif 'T' in units and 'K' in units:
                            if float(this_specimen_interpretation[
                                    'meas_step_min']) < 1.0:
                                min = float(this_specimen_interpretation[
                                    'meas_step_min']) * 1e3
                            else:
                                min = float(this_specimen_interpretation[
                                    'meas_step_min']) - 273
                            if float(this_specimen_interpretation[
                                    'meas_step_max']) < 1.0:
                                max = float(this_specimen_interpretation[
                                    'meas_step_max']) * 1e3
                            else:
                                max = float(this_specimen_interpretation[
                                    'meas_step_max']) - 273
                            print(
                                '%s %i %7.1f %i %i %7.1f %7.1f %7.1f %s \n' %
                                (this_specimen_interpretation["specimen"],
                                 int(this_specimen_interpretation[
                                     "dir_n_measurements"]),
                                 float(this_specimen_interpretation[
                                     "dir_mad_free"]),
                                 float(
                                     this_specimen_interpretation["dir_dang"]),
                                 min, max,
                                 float(
                                     this_specimen_interpretation["dir_dec"]),
                                 float(
                                     this_specimen_interpretation["dir_inc"]),
                                 calculation_type))
                        else:
                            print(
                                '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n'
                                %
                                (this_specimen_interpretation["specimen"],
                                 int(this_specimen_interpretation[
                                     "dir_n_measurements"]),
                                 float(this_specimen_interpretation[
                                     "dir_mad_free"]),
                                 float(
                                     this_specimen_interpretation["dir_dang"]),
                                 float(this_specimen_interpretation[
                                     "meas_step_min"]),
                                 float(this_specimen_interpretation[
                                     "meas_step_max"]),
                                 float(
                                     this_specimen_interpretation["dir_dec"]),
                                 float(
                                     this_specimen_interpretation["dir_inc"]),
                                 calculation_type))
                else:
                    this_specimen_interpretation["dir_alpha95"] = '%7.1f' % (
                        mpars['specimen_alpha95'])
                    this_specimen_interpretation["dir_mad_free"] = ''
                    if verbose:
                        if 'K' in units:
                            print(
                                '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n'
                                %
                                (this_specimen_interpretation["specimen"],
                                 int(this_specimen_interpretation[
                                     "dir_n_measurments"]),
                                 float(this_specimen_interpretation[
                                     "dir_mad_free"]),
                                 float(
                                     this_specimen_interpretation["dir_dang"]),
                                 float(this_specimen_interpretation[
                                     "meas_step_min"]) - 273,
                                 float(this_specimen_interpretation[
                                     "meas_step_max"]) - 273,
                                 float(
                                     this_specimen_interpretation["dir_dec"]),
                                 float(
                                     this_specimen_interpretation["dir_inc"]),
                                 calculation_type))
                        elif 'T' in units:
                            print(
                                '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n'
                                %
                                (this_specimen_interpretation["specimen"],
                                 int(this_specimen_interpretation[
                                     "dir_n_measurements"]),
                                 float(this_specimen_interpretation[
                                     "dir_alpha95"]),
                                 float(
                                     this_specimen_interpretation["dir_dang"]),
                                 float(this_specimen_interpretation[
                                     "meas_step_min"]) * 1e3,
                                 float(this_specimen_interpretation[
                                     "meas_step_max"]) * 1e3,
                                 float(
                                     this_specimen_interpretation["dir_dec"]),
                                 float(
                                     this_specimen_interpretation["dir_inc"]),
                                 calculation_type))
                        elif 'T' in units and 'K' in units:
                            if float(this_specimen_interpretation[
                                    'meas_step_min']) < 1.0:
                                min = float(this_specimen_interpretation[
                                    'meas_step_min']) * 1e3
                            else:
                                min = float(this_specimen_interpretation[
                                    'meas_step_min']) - 273
                            if float(this_specimen_interpretation[
                                    'meas_step_max']) < 1.0:
                                max = float(this_specimen_interpretation[
                                    'meas_step_max']) * 1e3
                            else:
                                max = float(this_specimen_interpretation[
                                    'meas_step_max']) - 273
                            print('%s %i %7.1f %i %i %7.1f %7.1f %s \n' % (
                                this_specimen_interpretation["specimen"],
                                int(this_specimen_interpretation[
                                    "dir_n_measurements"]),
                                float(
                                    this_specimen_interpretation["dir_alpha95"]
                                ), min, max,
                                float(this_specimen_interpretation["dir_dec"]),
                                float(this_specimen_interpretation["dir_inc"]),
                                calculation_type))
                        else:
                            print(
                                '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' %
                                (this_specimen_interpretation["specimen"],
                                 int(this_specimen_interpretation[
                                     "dir_n_measurements"]),
                                 float(this_specimen_interpretation[
                                     "dir_alpha95"]),
                                 float(this_specimen_interpretation[
                                     "meas_step_min"]),
                                 float(this_specimen_interpretation[
                                     "meas_step_max"]),
                                 float(
                                     this_specimen_interpretation["dir_dec"]),
                                 float(
                                     this_specimen_interpretation["dir_inc"]),
                                 calculation_type))
                if verbose:
                    saveit = input("Save this interpretation? [y]/n \n")
        else:
            print("no data", this_specimen)
        if verbose:
            pmagplotlib.draw_figs(ZED)
            #res = input('  <return> for next specimen, [q]uit  ')
            res = input("S[a]ve plots, [q]uit, or <return> to continue  ")
            if res == 'a':
                files = {
                    plot_type: this_specimen + "_" + plot_type + "." + fmt
                    for plot_type in ZED
                }
                pmagplotlib.save_plots(ZED, files)
                print("")
            if res == 'q':
                return
        k += 1
Ejemplo n.º 43
0
def plot(in_file="measurements.txt", dir_path=".", input_dir_path="",
         spec_file="specimens.txt", samp_file="samples.txt",
         site_file="sites.txt", loc_file="locations.txt",
         plot_by="loc", LT="AF", norm=True, XLP="",
         save_plots=True, fmt="svg"):

    """
    plots intensity decay curves for demagnetization experiments

    Parameters
    ----------
    in_file : str, default "measurements.txt"
    dir_path : str
        output directory, default "."
    input_dir_path : str
        input file directory (if different from dir_path), default ""
    spec_file : str
        input specimen file name, default "specimens.txt"
    samp_file: str
        input sample file name, default "samples.txt"
    site_file : str
        input site file name, default "sites.txt"
    loc_file : str
        input location file name, default "locations.txt"
    plot_by : str
        [spc, sam, sit, loc] (specimen, sample, site, location), default "loc"
    LT : str
        lab treatment [T, AF, M], default AF
    norm : bool
        normalize by NRM magnetization, default True
    XLP : str
        exclude specific  lab protocols, (for example, method codes like LP-PI)
        default ""
    save_plots : bool
        plot and save non-interactively, default True
    fmt : str
        ["png", "svg", "pdf", "jpg"], default "svg"

    Returns
    ---------
    type - Tuple : (True or False indicating if conversion was sucessful, file name(s) written)

    """
    dir_path = os.path.realpath(dir_path)
    if not input_dir_path:
        input_dir_path = dir_path
    input_dir_path = os.path.realpath(input_dir_path)

    # format plot_key
    name_dict = {'loc': 'location', 'sit': 'site',
                 'sam': 'sample', 'spc': 'specimen'}
    if plot_by not in name_dict.values():
        try:
            plot_key = name_dict[plot_by]
        except KeyError:
            print('Unrecognized plot_by {}, falling back to plot by location'.format(plot_by))
            plot_key = "loc"
    else:
        plot_key = plot_by


    # figure out what kind of experiment
    LT = "LT-" + LT + "-Z"
    print('LT', LT)
    if LT == "LT-T-Z":
        units, dmag_key = 'K', 'treat_temp'
    elif LT == "LT-AF-Z":
        units, dmag_key = 'T', 'treat_ac_field'
    elif LT == 'LT-M-Z':
        units, dmag_key = 'J', 'treat_mw_energy'
    else:
        units = 'U'


    # init
    FIG = {}  # plot dictionary
    FIG['demag'] = 1  # demag is figure 1
    # create contribution and add required headers
    fnames = {"specimens": spec_file, "samples": samp_file,
              'sites': site_file, 'locations': loc_file}
    if not os.path.exists(pmag.resolve_file_name(in_file, input_dir_path)):
        print('-E- Could not find {}'.format(in_file))
        return False, []
    contribution = cb.Contribution(input_dir_path, single_file=in_file,
                                   custom_filenames=fnames)
    file_type = list(contribution.tables.keys())[0]
    print(len(contribution.tables['measurements'].df), ' records read from ', in_file)
    # add plot_key into measurements table
    if plot_key not in contribution.tables['measurements'].df.columns:
        #contribution.propagate_name_down(plot_key, 'measurements')
        contribution.propagate_location_to_measurements()
    data_container = contribution.tables[file_type]
    # pare down to only records with useful data
    # grab records that have the requested code
    data_slice = data_container.get_records_for_code(LT)
    # and don't have the offending code
    data = data_container.get_records_for_code(XLP, incl=False, use_slice=True,
                                               sli=data_slice, strict_match=False)

    # make sure quality is in the dataframe
    if 'quality' not in data.columns:
        data['quality'] = 'g'
    # get intensity key and make sure intensity data is not blank
    intlist = ['magn_moment', 'magn_volume', 'magn_mass']
    IntMeths = [col_name for col_name in data.columns if col_name in intlist]
    # get rid of any entirely blank intensity columns
    for col_name in IntMeths:
        if not data[col_name].any():
            data.drop(col_name, axis=1, inplace=True)
    IntMeths = [col_name for col_name in data.columns if col_name in intlist]
    if len(IntMeths) == 0:
        print('-E- No intensity headers found')
        return False, []

    int_key = IntMeths[0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used
    data = data[data[int_key].notnull()]
    # make list of individual plots
    # by default, will be by location_name
    plotlist = data[plot_key].unique()
    plotlist.sort()
    pmagplotlib.plot_init(FIG['demag'], 5, 5)
    last_plot = False
    # iterate through and plot the data
    for plt in plotlist:
        if plt == plotlist[-1]:
            last_plot = True
        plot_data = data[data[plot_key] == plt].copy()
        if not save_plots:
            print(plt, 'plotting by: ', plot_key)
        if len(plot_data) > 2:
            title = plt
            spcs = []
            spcs = plot_data['specimen'].unique()
            for spc in spcs:
                INTblock = []
                spec_data = plot_data[plot_data['specimen'] == spc]
                for ind, rec in spec_data.iterrows():
                    INTblock.append([float(rec[dmag_key]), 0, 0, float(rec[int_key]), 1, rec['quality']])
                if len(INTblock) > 2:
                    pmagplotlib.plot_mag(FIG['demag'], INTblock,
                                       title, 0, units, norm)

            if save_plots:
                files = {}
                for key in list(FIG.keys()):
                    if pmagplotlib.isServer:
                        files[key] = title + '_' + LT + '.' + fmt
                        incl_dir = False
                    else: # if not server, include directory in output path
                        files[key] = os.path.join(dir_path, title + '_' + LT + '.' + fmt)
                        incl_dir = True

                pmagplotlib.save_plots(FIG, files, incl_directory=incl_dir)
            else:
                pmagplotlib.draw_figs(FIG)
                prompt = " S[a]ve to save plot, [q]uit,  Return to continue:  "
                ans = input(prompt)
                if ans == 'q':
                    return True, []
                if ans == "a":
                    files = {}
                    for key in list(FIG.keys()):
                        if pmagplotlib.isServer:
                            files[key] = title + '_' + LT + '.' + fmt
                            incl_dir = False
                        else: # if not server, include directory in output path
                            files[key] = os.path.join(dir_path, title + '_' + LT + '.' + fmt)
                            incl_dir = True
                    pmagplotlib.save_plots(FIG, files, incl_directory=incl_dir)
            pmagplotlib.clearFIG(FIG['demag'])
    if last_plot:
        return True, []
Ejemplo n.º 44
0
def main():
    """
    NAME
        chi_magic.py

    DESCRIPTION
        plots magnetic susceptibility as a function of frequency and temperature and AC field

    SYNTAX
        chi_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE, specify measurements format file, default "measurements.txt"
        -T IND, specify temperature step to plot
        -e EXP, specify experiment name to plot
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
        -sav save figure and quit

    """
    if "-h" in sys.argv:
        print(main.__doc__)
        return
    infile = pmag.get_named_arg("-f", "measurements.txt")
    dir_path = pmag.get_named_arg("-WD", ".")
    infile = pmag.resolve_file_name(infile, dir_path)
    fmt = pmag.get_named_arg("-fmt", "svg")
    show_plots = True
    if "-sav" in sys.argv:
        show_plots = False
    experiments = pmag.get_named_arg("-e", "")
    # read in data from data model 3 example file
    chi_data_all = pd.read_csv(infile, sep='\t', header=1)

    if not experiments:
        try:
            experiments = chi_data_all.experiment.unique()
        except Exception as ex:
            print(ex)
            experiments = ["all"]
    else:
         experiments = [experiments]

    plotnum = 0
    figs = {}
    fnames = {}
    for exp in experiments:
        if exp == "all":
            chi_data = chi_data_all
        chi_data = chi_data_all[chi_data_all.experiment == exp]
        if len(chi_data) <= 1:
            print('Not enough data to plot {}'.format(exp))
            continue

        plotnum += 1
        pmagplotlib.plot_init(plotnum, 5, 5)  # set up plot
        figs[str(plotnum)] = plotnum
        fnames[str(plotnum)] = exp + '_temperature.{}'.format(fmt)

        # get arrays of available temps, frequencies and fields
        Ts = np.sort(chi_data.meas_temp.unique())
        Fs = np.sort(chi_data.meas_freq.unique())
        Bs = np.sort(chi_data.meas_field_ac.unique())

        # plot chi versus temperature at constant field
        b = Bs.max()
        for num, f in enumerate(Fs):
            this_f = chi_data[chi_data.meas_freq == f]
            this_f = this_f[this_f.meas_field_ac == b]
            plt.plot(this_f.meas_temp, 1e6*this_f.susc_chi_volume,
                     label='%i' % (f)+' Hz')
        plt.legend()
        plt.xlabel('Temperature (K)')
        plt.ylabel('$\chi$ ($\mu$SI)')
        plt.title('B = '+'%7.2e' % (b) + ' T')

        plotnum += 1
        figs[str(plotnum)] = plotnum
        fnames[str(plotnum)] = exp + '_frequency.{}'.format(fmt)

        pmagplotlib.plot_init(plotnum, 5, 5)  # set up plot
        ## plot chi versus frequency at constant B
        b = Bs.max()
        t = Ts.min()
        this_t = chi_data[chi_data.meas_temp == t]
        this_t = this_t[this_t.meas_field_ac == b]
        plt.semilogx(this_t.meas_freq, 1e6 *
                     this_t.susc_chi_volume, label='%i' % (t)+' K')
        plt.legend()
        plt.xlabel('Frequency (Hz)')
        plt.ylabel('$\chi$ ($\mu$SI)')
        plt.title('B = '+'%7.2e' % (b) + ' T')

    if show_plots:
        pmagplotlib.draw_figs(figs)
        ans = input(
            "enter s[a]ve to save files,  [return] to quit ")
        if ans == 'a':
            pmagplotlib.save_plots(figs, fnames)
            sys.exit()
        else:
            sys.exit()

    else:
        pmagplotlib.save_plots(figs, fnames)
Ejemplo n.º 45
0
def main():
    """
    NAME
        igrf.py
    DESCRIPTION
        This program calculates igrf field values
    using the routine of Malin and  Barraclough (1981)
    based on d/igrfs from 1900 to 2010.
    between 1900 and 1000BCE, it uses CALS3K.4, ARCH3K.1
    Prior to 1000BCE, it uses PFM9k or CALS10k-4b
    Calculates reference field vector at  specified location and time.

    SYNTAX
       igrf.py [-h] [-i] -f FILE  [< filename]
    OPTIONS:
       -h prints help message and quits
       -i for interactive data entry
       -f FILE  specify file name with input data
       -fgh FILE specify file with custom field coefficients in format:  l m g h
       -F FILE  specify output file name
       -ages MIN MAX INCR: specify age minimum in years (+/- AD), maximum and increment, default is line by line
       -loc LAT LON;  specify location, default is line by line
       -alt ALT;  specify altitude in km, default is sealevel (0)
       -plt; make a plot of the time series
       -sav, saves plot and quits
       -fmt [pdf,jpg,eps,svg]  specify format for output figure  (default is svg)
       -mod [arch3k,cals3k,pfm9k,hfm10k,cals10k.2,shadif14k,cals10k.1b] specify model for 3ka to 1900 AD, default is cals10k
             NB:  program uses IGRF12 for dates 1900 to 2015.

    INPUT FORMAT
      interactive entry:
           date: decimal year
           alt:  altitude in km
           lat: positive north
           lon: positive east
       for file entry:
           space delimited string: date  alt   lat long
    OUTPUT  FORMAT
        Declination Inclination Intensity (nT) date alt lat long
    MODELS:  ARCH3K: (Korte et al., 2009);CALS3K (Korte & Contable, 2011); CALS10k (is .1b of Korte et al., 2011); PFM9K (Nilsson et al., 2014); HFM10k (is HFM.OL1.A1 of Constable et al., 2016); CALS10k_2 (is cals10k.2 of Constable et al., 2016), SHADIF14k (SHA.DIF.14K of Pavon-Carrasco et al., 2014).
    """
    plot, fmt = 0, 'svg'
    mod, alt, make_plot, lat, lon = 'cals10k', 0, 0, 0, 0
    if '-loc' in sys.argv:
        ind = sys.argv.index('-loc')
        lat = float(sys.argv[ind + 1])
        lon = float(sys.argv[ind + 2])
    if '-alt' in sys.argv:
        ind = sys.argv.index('-alt')
        alt = float(sys.argv[ind + 1])
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if len(sys.argv) != 0 and '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-mod' in sys.argv:
        ind = sys.argv.index('-mod')
        mod = sys.argv[ind + 1]
    if '-fgh' in sys.argv:
        ind = sys.argv.index('-fgh')
        ghfile = sys.argv[ind + 1]
        lmgh = numpy.loadtxt(ghfile)
        gh = []
        lmgh = numpy.loadtxt(ghfile).transpose()
        gh.append(lmgh[2][0])
        for i in range(1, lmgh.shape[1]):
            gh.append(lmgh[2][i])
            gh.append(lmgh[3][i])
        mod = 'custom'
        inp = [[0, alt, lat, lon]]
    elif '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file = sys.argv[ind + 1]
        inp = numpy.loadtxt(file)
    elif '-i' in sys.argv:
        while 1:
            try:
                line = []
                if mod != 'custom':
                    line.append(
                        float(input("Decimal year: <cntrl-D to quit> ")))
                else:
                    line.append(0)
                alt = input("Elevation in km [0] ")
                if alt == "":
                    alt = "0"
                line.append(float(alt))
                line.append(float(input("Latitude (positive north) ")))
                line.append(float(input("Longitude (positive east) ")))
                if mod == '':
                    x, y, z, f = pmag.doigrf(line[3] % 360., line[2], line[1],
                                             line[0])
                elif mod == 'custom':
                    x, y, z, f = pmag.docustom(line[3] % 360., line[2],
                                               line[1], gh)
                else:
                    x, y, z, f = pmag.doigrf(line[3] % 360.,
                                             line[2],
                                             line[1],
                                             line[0],
                                             mod=mod)
                Dir = pmag.cart2dir((x, y, z))
                print('%8.2f %8.2f %8.0f' % (Dir[0], Dir[1], f))
            except EOFError:
                print("\n Good-bye\n")
                sys.exit()
    elif '-ages' in sys.argv:
        ind = sys.argv.index('-ages')
        agemin = float(sys.argv[ind + 1])
        agemax = float(sys.argv[ind + 2])
        ageincr = float(sys.argv[ind + 3])
        ages = numpy.arange(agemin, agemax, ageincr)
        lats = numpy.ones(len(ages)) * lat
        lons = numpy.ones(len(ages)) * lon
        alts = numpy.ones(len(ages)) * alt
        inp = numpy.array([ages, alts, lats, lons]).transpose()
    else:
        inp = numpy.loadtxt(sys.stdin, dtype=numpy.float)
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        outfile = sys.argv[ind + 1]
        out = open(outfile, 'w')
    else:
        outfile = ""
    if '-sav' in sys.argv:
        plot = 1
    if '-plt' in sys.argv:
        make_plot = 1
        Ages, Decs, Incs, Ints, VADMs = [], [], [], [], []
    for line in inp:
        if mod != 'custom':
            x, y, z, f = pmag.doigrf(line[3] % 360.,
                                     line[2],
                                     line[1],
                                     line[0],
                                     mod=mod)
        else:
            x, y, z, f = pmag.docustom(line[3] % 360., line[2], line[1], gh)
        Dir = pmag.cart2dir((x, y, z))
        if outfile != "":
            out.write('%8.2f %8.2f %8.0f %7.1f %7.1f %7.1f %7.1f\n' %
                      (Dir[0], Dir[1], f, line[0], line[1], line[2], line[3]))
        elif make_plot:
            Ages.append(line[0])
            if Dir[0] > 180:
                Dir[0] = Dir[0] - 360.0
            Decs.append(Dir[0])
            Incs.append(Dir[1])
            Ints.append(f * 1e-3)
            VADMs.append(pmag.b_vdm(f * 1e-9, line[2]) * 1e-21)
        else:
            print('%8.2f %8.2f %8.0f %7.1f %7.1f %7.1f %7.1f' %
                  (Dir[0], Dir[1], f, line[0], line[1], line[2], line[3]))
    if make_plot:
        pmagplotlib.plot_init(1, 7, 9)
        fig = plt.figure(num=1, figsize=(7, 9))
        fig.add_subplot(411)
        plt.plot(Ages, Decs)
        plt.ylabel('Declination ($^{\circ}$)')
        fig.add_subplot(412)
        plt.plot(Ages, Incs)
        plt.ylabel('Inclination ($^{\circ}$)')
        fig.add_subplot(413)
        plt.plot(Ages, Ints)
        plt.ylabel('Intensity ($\mu$T)')
        fig.add_subplot(414)
        plt.plot(Ages, VADMs)
        plt.ylabel('VADMs (ZAm$^2$)')
        plt.xlabel('Ages')
        # show plot
        if plot == 0:
            pmagplotlib.draw_figs({'time series': 1})
            ans = input("S[a]ve to save figure, <Return>  to quit  ")
            if ans == 'a':
                plt.savefig('igrf.' + fmt)
                print('Figure saved as: ', 'igrf.' + fmt)
        # save plot without showing
        else:
            plt.savefig('igrf.' + fmt)
            print('Figure saved as: ', 'igrf.' + fmt)
        sys.exit()
Ejemplo n.º 46
0
def main():
    """
    NAME
       plotdi_a.py

    DESCRIPTION
       plots equal area projection  from dec inc data and fisher mean, cone of confidence

    INPUT FORMAT
       takes dec, inc, alpha95 as first three columns in space delimited file

    SYNTAX
       plotdi_a.py [-i][-f FILE]

    OPTIONS
        -f FILE to read file name from command line
        -fmt [png,jpg,eps,pdf,svg] set plot file format ['svg' is default]
        -sav save plot and quit

    """
    fmt,plot='svg',0
    if len(sys.argv) > 0:
        if '-h' in sys.argv: # check if help is needed
            print(main.__doc__)
            sys.exit() # graceful quit
        if '-fmt' in sys.argv:
            ind=sys.argv.index('-fmt')
            fmt=sys.argv[ind+1]
        if '-sav' in sys.argv:plot=1
        if '-f' in sys.argv:
            ind=sys.argv.index('-f')
            file=sys.argv[ind+1]
            f=open(file,'r')
            data=f.readlines()
        else:
            data=sys.stdin.readlines() # read in data from standard input
    DIs,Pars=[],[]
    for line in data:   # read in the data from standard input
        pars=[]
        rec=line.split() # split each line on space to get records
        DIs.append([float(rec[0]),float(rec[1])])
        pars.append(float(rec[0]))
        pars.append(float(rec[1]))
        pars.append(float(rec[2]))
        pars.append(float(rec[0]))
        isign=abs(float(rec[1])) / float(rec[1])
        pars.append(float(rec[1])-isign*90.) #Beta inc
        pars.append(float(rec[2])) # gamma
        pars.append(float(rec[0])+90.) # Beta dec
        pars.append(0.) #Beta inc
        Pars.append(pars)
#
    EQ={'eq':1} # make plot dictionary
    pmagplotlib.plot_init(EQ['eq'],5,5)
    title='Equal area projection'
    pmagplotlib.plot_eq(EQ['eq'],DIs,title)# plot directions
    for k in range(len(Pars)):
        pmagplotlib.plot_ell(EQ['eq'],Pars[k],'b',0,1) # plot ellipses
    files={}
    for key in list(EQ.keys()):
        files[key]=key+'.'+fmt
    titles={}
    titles['eq']='Equal Area Plot'
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(EQ,files)
    elif plot==0:
        pmagplotlib.draw_figs(EQ)
        ans=input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
        if ans=="q": sys.exit()
        if ans=="a":
            pmagplotlib.save_plots(EQ,files)
    else:
        pmagplotlib.save_plots(EQ,files)
Ejemplo n.º 47
0
def main():
    """
    NAME
        strip_magic.py

    DESCRIPTION
        plots various parameters versus depth or age

    SYNTAX
        strip_magic.py [command line optins]

    OPTIONS
        -h prints help message and quits
        -DM NUM: specify data model num, options 2 (legacy) or 3 (default)
        -f FILE: specify input magic format file from magic,default='pmag_results.txt'
         supported types=[pmag_specimens, pmag_samples, pmag_sites, pmag_results, magic_web]
        -obj [sit,sam,all]: specify object to site,sample,all for pmag_result table, default is all
        -fmt [svg,png,jpg], format for images - default is svg
        -x [age,pos]:  specify whether age or stratigraphic position
        -y [dec,inc,int,chi,lat,lon,vdm,vadm]
           (lat and lon are VGP lat and lon)
        -Iex: plot the expected inc at lat - only available for results with lat info in file
        -ts TS amin amax: plot the GPTS for the time interval between amin and amax (numbers in Ma)
           TS: [ck95, gts04]
        -mcd method_code, specify method code, default is first one encountered
        -sav  save plot and quit
    NOTES
        when x and/or y are not specified, a list of possibilities will be presented to the user for choosing

    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    xaxis, xplotind, yplotind = "", 0, 0  # (0 for strat pos)
    yaxis, Xinc = "", ""
    plot = 0
    obj = 'all'
    data_model_num = int(pmag.get_named_arg("-DM", 3))
    # 2.5 keys
    if data_model_num == 2:
        supported = [
            'pmag_specimens', 'pmag_samples', 'pmag_sites', 'pmag_results',
            'magic_web'
        ]  # available file types
        Depth_keys = [
            'specimen_core_depth', 'specimen_height', 'specimen_elevation',
            'specimen_composite_depth', 'sample_core_depth', 'sample_height',
            'sample_elevation', 'sample_composite_depth', 'site_core_depth',
            'site_height', 'site_elevation', 'site_composite_depth',
            'average_height'
        ]
        Age_keys = [
            'specimen_inferred_age', 'sample_inferred_age',
            'site_inferred_age', 'average_age'
        ]
        Unit_keys = {
            'specimen_inferred_age': 'specimen_inferred_age_unit',
            'sample_inferred_age': 'sample_inferred_age_unit',
            'site_inferred_age': 'site_inferred_age_unit',
            'average_age': 'average_age_unit'
        }
        Dec_keys = [
            'measurement_dec', 'specimen_dec', 'sample_dec', 'site_dec',
            'average_dec'
        ]
        Inc_keys = [
            'measurement_inc', 'specimen_inc', 'sample_inc', 'site_inc',
            'average_inc'
        ]
        Int_keys = [
            'measurement_magnitude', 'measurement_magn_moment',
            'measurement_magn_volume', 'measurement_magn_mass', 'specimen_int',
            'specimen_int_rel', 'sample_int', 'sample_int_rel', 'site_int',
            'site_int_rel', 'average_int', 'average_int_rel'
        ]
        Chi_keys = ['measurement_chi_volume', 'measurement_chi_mass']
        Lat_keys = ['sample_lat', 'site_lat', 'average_lat']
        VLat_keys = ['vgp_lat']
        VLon_keys = ['vgp_lon']
        Vdm_keys = ['vdm']
        Vadm_keys = ['vadm']
        method_col_name = "magic_method_codes"
    else:
        # 3.0 keys
        supported = ["specimens", "samples", "sites",
                     "locations"]  # available file types
        Depth_keys = ["height", "core_depth", "elevation", "composite_depth"]
        Age_keys = ["age"]
        Unit_keys = {"age": "age"}
        Chi_keys = ["susc_chi_volume", "susc_chi_mass"]
        Int_keys = [
            "magn_moment", "magn_volume", "magn_mass", "int_abs", "int_rel"
        ]
        Inc_keys = ["dir_inc"]
        Dec_keys = ["dir_dec"]
        Lat_Keys = ["lat"]
        VLat_keys = ["vgp_lat", "pole_lat"]
        VLon_keys = ["vgp_lon", "pole_lon"]
        Vdm_keys = ["vdm", "pdm"]
        Vadm_keys = ["vadm", "padm"]
        method_col_name = "method_codes"

    #
    X_keys = [Age_keys, Depth_keys]
    Y_keys = [
        Dec_keys, Inc_keys, Int_keys, Chi_keys, VLat_keys, VLon_keys, Vdm_keys,
        Vadm_keys
    ]
    method, fmt = "", 'svg'
    FIG = {'strat': 1}
    plotexp, pTS = 0, 0
    dir_path = pmag.get_named_arg("-WD", ".")
    # default files
    if data_model_num == 3:
        res_file = pmag.get_named_arg("-f", "sites.txt")
    else:
        res_file = pmag.get_named_arg("-f", "pmag_results.txt")
    res_file = pmag.resolve_file_name(res_file, dir_path)
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-obj' in sys.argv:
        ind = sys.argv.index('-obj')
        obj = sys.argv[ind + 1]
    if '-x' in sys.argv:
        ind = sys.argv.index('-x')
        xaxis = sys.argv[ind + 1]
    if '-y' in sys.argv:
        ind = sys.argv.index('-y')
        yaxis = sys.argv[ind + 1]
        if yaxis == 'dec':
            ykeys = Dec_keys
        if yaxis == 'inc':
            ykeys = Inc_keys
        if yaxis == 'int':
            ykeys = Int_keys
        if yaxis == 'chi':
            ykeys = Chi_keys
        if yaxis == 'lat':
            ykeys = VLat_keys
        if yaxis == 'lon':
            ykeys = VLon_keys
        if yaxis == 'vdm':
            ykeys = Vdm_keys
        if yaxis == 'vadm':
            ykeys = Vadm_keys
    if '-mcd' in sys.argv:
        ind = sys.argv.index('-mcd')
        method = sys.argv[ind + 1]
    if '-ts' in sys.argv:
        ind = sys.argv.index('-ts')
        ts = sys.argv[ind + 1]
        amin = float(sys.argv[ind + 2])
        amax = float(sys.argv[ind + 3])
        pTS = 1
    if '-Iex' in sys.argv:
        plotexp = 1
    if '-sav' in sys.argv:
        plot = 1
    #
    #
    # get data read in
    Results, file_type = pmag.magic_read(res_file)
    if file_type not in supported:
        print("Unsupported file type ({}), try again".format(file_type))
        sys.exit()
    PltObjs = ['all']
    if data_model_num == 2:
        if file_type == 'pmag_results':  # find out what to plot
            for rec in Results:
                resname = rec['pmag_result_name'].split()
                if 'Sample' in resname and 'sam' not in PltObjs:
                    PltObjs.append('sam')
                if 'Site' in resname and 'sit' not in PltObjs:
                    PltObjs.append('sit')

    methcodes = []
    # need to know all the measurement types from method_codes
    if "magic_method_codes" in list(Results[0].keys()):
        for rec in Results:
            meths = rec["magic_method_codes"].split(":")
            for meth in meths:
                if meth.strip() not in methcodes and 'LP' in meth:
                    # look for the lab treatments
                    methcodes.append(meth.strip())
    #
    # initialize some variables
    X_unit = ""  # Unit for age or depth plotting (meters if depth)
    Xplots, Yplots = [], []
    Xunits = []
    yplotind, xplotind = 0, 0
    #
    # step through possible plottable keys
    #
    if xaxis == "" or yaxis == "":
        for key in list(Results[0].keys()):
            for keys in X_keys:
                for xkeys in keys:
                    if key in xkeys:
                        for ResRec in Results:
                            if ResRec[key] != "":
                                # only plot something if there is something to plot!
                                Xplots.append(key)
                                break
            for keys in Y_keys:
                for pkeys in keys:
                    if key in pkeys:
                        for ResRec in Results:
                            if ResRec[key] != "":
                                Yplots.append(key)
                                break
        X, Y = [], []
        for plt in Xplots:
            if plt in Age_keys and 'age' not in X:
                X.append('age')
            if plt in Depth_keys and 'pos' not in X:
                X.append('pos')
        for plt in Yplots:
            if plt in Dec_keys and 'dec' not in Y:
                Y.append('dec')
            if plt in Inc_keys and 'inc' not in Y:
                Y.append('inc')
            if plt in Int_keys and 'int' not in Y:
                Y.append('int')
            if plt in Chi_keys and 'chi' not in Y:
                Y.append('chi')
            if plt in VLat_keys and 'lat' not in Y:
                Y.append('lat')
            if plt in VLon_keys and 'lon' not in Y:
                Y.append('lon')
            if plt in Vadm_keys and 'vadm' not in Y:
                Y.append('vadm')
            if plt in Vdm_keys and 'vdm' not in Y:
                Y.append('vdm')
        if file_type == 'pmag_results':
            print('available objects for plotting: ', PltObjs)
        print('available X plots: ', X)
        print('available Y plots: ', Y)
        print('available method codes: ', methcodes)
        f = open(dir_path + '/.striprc', 'w')
        for x in X:
            f.write('x:' + x + '\n')
        for y in Y:
            f.write('y:' + y + '\n')
        for m in methcodes:
            f.write('m:' + m + '\n')
        for obj in PltObjs:
            f.write('obj:' + obj + '\n')
        sys.exit()
    if plotexp == 1:
        for lkey in Lat_keys:
            for key in list(Results[0].keys()):
                if key == lkey:
                    lat = float(Results[0][lkey])
                    Xinc = [pmag.pinc(lat), -pmag.pinc(lat)]
                    break
        if Xinc == "":
            print('can not plot expected inc for site - lat unknown')
    if method != "" and method not in methcodes:
        print('your method not available, but these are:  ')
        print(methcodes)
        print('use ', methcodes[0], '? ^D to quit')
    if xaxis == 'age':
        for akey in Age_keys:
            for key in list(Results[0].keys()):
                if key == akey:
                    Xplots.append(key)
                    Xunits.append(Unit_keys[key])
    if xaxis == 'pos':
        for dkey in Depth_keys:
            for key in list(Results[0].keys()):
                if key == dkey:
                    Xplots.append(key)
    if len(Xplots) == 0:
        print('desired X axis  information not found')
        sys.exit()
    if xaxis == 'age':
        age_unit = Results[0][Xunits[0]]
    if len(Xplots) > 1:
        print('multiple X axis  keys found, using: ', Xplots[xplotind])
    for ykey in ykeys:
        for key in list(Results[0].keys()):
            if key == ykey:
                Yplots.append(key)
    if len(Yplots) == 0:
        print('desired Y axis  information not found')
        sys.exit()
    if len(Yplots) > 1:
        print('multiple Y axis  keys found, using: ', Yplots[yplotind])

    # check if age or depth info
    if len(Xplots) == 0:
        print("Must have either age or height info to plot ")
        sys.exit()
    #
    # check for variable to plot
    #
    #
    # determine X axis (age or depth)
    #
    if xaxis == "age":
        plotind = "1"
    if method == "":
        try:
            method = methcodes[0]
        except IndexError:
            method = ""
    if xaxis == 'pos':
        xlab = "Stratigraphic Height (meters)"
    else:
        xlab = "Age (" + age_unit + ")"
    Xkey = Xplots[xplotind]
    Ykey = Yplots[yplotind]
    ylab = Ykey
    #
    # collect the data for plotting
    XY = []
    isign = 1.
    #    if float(Results[0][Xkey])/float(Results[-1][Xkey])>0 and float(Results[0][Xkey])<0:
    #        isign=-1. # x axis all same sign and negative, take positive (e.g.,for depth in core)
    #        xlab="Stratigraphic Position (meters)"
    #    else:
    #        isign=1.
    for rec in Results:
        if "magic_method_codes" in list(rec.keys()):
            meths = rec["magic_method_codes"].split(":")
            if method in meths:  # make sure it is desired lab treatment step
                if obj == 'all' and rec[Xkey].strip() != "":
                    XY.append([isign * float(rec[Xkey]), float(rec[Ykey])])
                elif rec[Xkey].strip() != "":
                    name = rec['pmag_result_name'].split()
                    if obj == 'sit' and "Site" in name:
                        XY.append([isign * float(rec[Xkey]), float(rec[Ykey])])
                    if obj == 'sam' and "Sample" in name:
                        XY.append([isign * float(rec[Xkey]), float(rec[Ykey])])
        elif method == "":
            if obj == 'all' and rec[Xkey].strip() != "":
                XY.append([isign * float(rec[Xkey]), float(rec[Ykey])])
            elif rec[Xkey].strip() != "":
                name = rec['pmag_result_name'].split()
                if obj == 'sit' and "Site" in name:
                    XY.append([isign * float(rec[Xkey]), float(rec[Ykey])])
                if obj == 'sam' and "Sample" in name:
                    XY.append([isign * float(rec[Xkey]), float(rec[Ykey])])
        else:
            print("Something wrong with your plotting choices")
            break
    XY.sort()
    title = ""
    if "er_locations_names" in list(Results[0].keys()):
        title = Results[0]["er_location_names"]
    if "er_locations_name" in list(Results[0].keys()):
        title = Results[0]["er_location_name"]
    labels = [xlab, ylab, title]
    pmagplotlib.plot_init(FIG['strat'], 10, 5)
    pmagplotlib.plot_strat(FIG['strat'], XY, labels)  # plot them
    if plotexp == 1:
        pmagplotlib.plot_hs(FIG['strat'], Xinc, 'b', '--')
    if yaxis == 'inc' or yaxis == 'lat':
        pmagplotlib.plot_hs(FIG['strat'], [0], 'b', '-')
        pmagplotlib.plot_hs(FIG['strat'], [-90, 90], 'g', '-')
    if pTS == 1:
        FIG['ts'] = 2
        pmagplotlib.plot_init(FIG['ts'], 10, 5)
        pmagplotlib.plot_ts(FIG['ts'], [amin, amax], ts)
    files = {}
    for key in list(FIG.keys()):
        files[key] = key + '.' + fmt
    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        files = {}
        files['strat'] = xaxis + '_' + yaxis + '_.' + fmt
        files['ts'] = 'ts.' + fmt
        titles = {}
        titles['strat'] = 'Depth/Time Series Plot'
        titles['ts'] = 'Time Series Plot'
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    elif plot == 1:
        pmagplotlib.save_plots(FIG, files)
    else:
        pmagplotlib.draw_figs(FIG)
        ans = input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans == "a":
            pmagplotlib.save_plots(FIG, files)
Ejemplo n.º 48
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)
Ejemplo n.º 49
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)
Ejemplo n.º 50
0
def main():
    """
    NAME
       revtest_MM1990.py

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

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

    SYNTAX
       revtest_MM1990.py [command line options]

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

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

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

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

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


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

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

    if V > Vcrit:
        print("")
    elif V < Vcrit:
        if critical_angle < 5:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'A'"
            )
        elif critical_angle < 10:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'B'"
            )
        elif critical_angle < 20:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'C'"
            )
        else:
            print(
                "The McFadden and McElhinny (1990) classification for this test is: 'INDETERMINATE;"
            )
    if plot == 1:
        CDF = {'cdf': 1}
        pmagplotlib.plot_init(CDF['cdf'], 5, 5)
        p1 = pmagplotlib.plot_cdf(CDF['cdf'], Vp, "Watson's V", 'r', "")
        p2 = pmagplotlib.plot_vs(CDF['cdf'], [V], 'g', '-')
        p3 = pmagplotlib.plot_vs(CDF['cdf'], [Vp[k]], 'b', '--')
        pmagplotlib.draw_figs(CDF)
        files, fmt = {}, 'svg'
        if file2 != "":
            files['cdf'] = 'WatsonsV_' + file1 + '_' + file2 + '.' + fmt
        else:
            files['cdf'] = 'WatsonsV_' + file1 + '.' + fmt
        if pmagplotlib.isServer:
            black = '#000000'
            purple = '#800080'
            titles = {}
            titles['cdf'] = 'Cumulative Distribution'
            CDF = pmagplotlib.add_borders(CDF, titles, black, purple)
            pmagplotlib.save_plots(CDF, files)
        else:
            ans = input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans == "a": pmagplotlib.save_plots(CDF, files)
Ejemplo n.º 51
0
def main():
    """
    NAME
        quick_hyst.py

    DESCRIPTION
        makes plots of hysteresis data

    SYNTAX
        quick_hyst.py [command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f: specify input file, default is magic_measurements.txt
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args = sys.argv
    PLT = 1
    plots = 0
    user, meas_file = "", "magic_measurements.txt"
    pltspec = ""
    dir_path = '.'
    fmt = 'png'
    verbose = pmagplotlib.verbose
    version_num = pmag.get_version()
    if '-WD' in args:
        ind = args.index('-WD')
        dir_path = args[ind+1]
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if "-usr" in args:
        ind = args.index("-usr")
        user = args[ind+1]
    if '-f' in args:
        ind = args.index("-f")
        meas_file = args[ind+1]
    if '-sav' in args:
        verbose = 0
        plots = 1
    if '-spc' in args:
        ind = args.index("-spc")
        pltspec = args[ind+1]
        verbose = 0
        plots = 1
    if '-fmt' in args:
        ind = args.index("-fmt")
        fmt = args[ind+1]
    meas_file = dir_path+'/'+meas_file
    #
    #
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(main.__doc__)
        print('bad file')
        sys.exit()
    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs, RemRecs = [], []
    HDD = {}
    HDD['hyst'] = 1
    pmagplotlib.plot_init(HDD['hyst'], 5, 5)
    #
    # get list of unique experiment names and specimen names
    #
    experiment_names, sids = [], []
    hyst_data = pmag.get_dictitem(
        meas_data, 'magic_method_codes', 'LP-HYS', 'has')  # get all hysteresis data
    for rec in hyst_data:
        if 'er_synthetic_name' in rec.keys() and rec['er_synthetic_name'] != "":
            rec['er_specimen_name'] = rec['er_synthetic_name']
        if rec['magic_experiment_name'] not in experiment_names:
            experiment_names.append(rec['magic_experiment_name'])
        if rec['er_specimen_name'] not in sids:
            sids.append(rec['er_specimen_name'])
        if 'measurement_temp' not in rec.keys():
            # assume room T measurement unless otherwise specified
            rec['measurement_temp'] = '300'
    #
    k = 0
    if pltspec != "":
        k = sids.index(pltspec)
    intlist = ['measurement_magnitude', 'measurement_magn_moment',
               'measurement_magn_volume', 'measurement_magn_mass']
    while k < len(sids):
        locname, site, sample, synth = '', '', '', ''
        s = sids[k]
        hmeths = []
        if verbose:
            print(s, k+1, 'out of ', len(sids))
    #
    #
        B, M = [], []  # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        # get all measurements for this specimen
        spec = pmag.get_dictitem(hyst_data, 'er_specimen_name', s, 'T')
        if 'er_location_name' in spec[0].keys():
            locname = spec[0]['er_location_name']
        if 'er_site_name' in spec[0].keys():
            site = spec[0]['er_site_name']
        if 'er_sample_name' in spec[0].keys():
            sample = spec[0]['er_sample_name']
        if 'er_synthetic_name' in spec[0].keys():
            synth = spec[0]['er_synthetic_name']
        for m in intlist:
            # get all non-blank data for this specimen
            meas_data = pmag.get_dictitem(spec, m, '', 'F')
            if len(meas_data) > 0:
                break
        c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-']
        cnum = 0
        if len(meas_data) > 0:
            Temps = []
            xlab, ylab, title = '', '', ''
            for rec in meas_data:
                if rec['measurement_temp'] not in Temps:
                    Temps.append(rec['measurement_temp'])
            for t in Temps:
                print('working on t: ', t)
                t_data = pmag.get_dictitem(
                    meas_data, 'measurement_temp', t, 'T')
                B, M = [], []
                for rec in t_data:
                    B.append(float(rec['measurement_lab_field_dc']))
                    M.append(float(rec[m]))
    # now plot the hysteresis curve(s)
    #
                if len(B) > 0:
                    B = numpy.array(B)
                    M = numpy.array(M)
                    if t == Temps[-1]:
                        xlab = 'Field (T)'
                        ylab = m
                        title = 'Hysteresis: '+s
                    if t == Temps[0]:
                        pmagplotlib.clearFIG(HDD['hyst'])
                    pmagplotlib.plot_xy(
                        HDD['hyst'], B, M, sym=c[cnum], xlab=xlab, ylab=ylab, title=title)
                    pmagplotlib.plot_xy(HDD['hyst'], [
                                        1.1*B.min(), 1.1*B.max()], [0, 0], sym='k-', xlab=xlab, ylab=ylab, title=title)
                    pmagplotlib.plot_xy(HDD['hyst'], [0, 0], [
                                        1.1*M.min(), 1.1*M.max()], sym='k-', xlab=xlab, ylab=ylab, title=title)
                    if verbose:
                        pmagplotlib.draw_figs(HDD)
                    cnum += 1
                    if cnum == len(c):
                        cnum = 0
    #
        files = {}
        if plots:
            if pltspec != "":
                s = pltspec
            files = {}
            for key in HDD.keys():
                if pmagplotlib.isServer:  # use server plot naming convention
                    if synth == '':
                        filename = "LO:_"+locname+'_SI:_'+site + \
                            '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt
                    else:
                        filename = 'SY:_'+synth+'_TY:_'+key+'_.'+fmt
                    files[key] = filename
                else:  # use more readable plot naming convention
                    if synth == '':
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                    else:
                        filename = synth+'_'+key+'.fmt'
                    files[key] = filename

            pmagplotlib.save_plots(HDD, files)
            if pltspec != "":
                sys.exit()
        if verbose:
            pmagplotlib.draw_figs(HDD)
            ans = raw_input(
                "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ")
            if ans == "a":
                files = {}
                for key in HDD.keys():
                    if pmagplotlib.isServer:
                        print('server')
                        files[key] = "LO:_"+locname+'_SI:_'+site + \
                            '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt
                    else:
                        print('not server')
                        filename = ''
                        for item in [locname, site, sample, s, key]:
                            if item:
                                item = item.replace(' ', '_')
                                filename += item + '_'
                        if filename.endswith('_'):
                            filename = filename[:-1]
                        filename += ".{}".format(fmt)
                        files[key] = filename
                print('files', files)
                pmagplotlib.save_plots(HDD, files)
            if ans == '':
                k += 1
            if ans == "p":
                del HystRecs[-1]
                k -= 1
            if ans == 'q':
                print("Good bye")
                sys.exit()
            if ans == 's':
                keepon = 1
                specimen = raw_input(
                    'Enter desired specimen name (or first part there of): ')
                while keepon == 1:
                    try:
                        k = sids.index(specimen)
                        keepon = 0
                    except:
                        tmplist = []
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:
                                tmplist.append(sids[qq])
                        print(specimen, " not found, but this was: ")
                        print(tmplist)
                        specimen = raw_input('Select one or try again\n ')
                        k = sids.index(specimen)
        else:
            k += 1
        if len(B) == 0:
            if verbose:
                print('skipping this one - no hysteresis data')
            k += 1
Ejemplo n.º 52
0
def main():
    """
    NAME
        hysteresis_magic.py

    DESCRIPTION
        calculates hystereis parameters and saves them in rmag_hystereis format file
        makes plots if option selected

    SYNTAX
        hysteresis_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -usr USER:   identify user, default is ""
        -f: specify input file, default is agm_measurements.txt
        -fh: specify rmag_hysteresis.txt input file
        -F: specify output file, default is rmag_hysteresis.txt
        -P: do not make the plots
        -spc SPEC: specify specimen name to plot and quit
        -sav save all plots and quit
        -fmt [png,svg,eps,jpg]
    """
    args = sys.argv
    PLT = 1
    plots = 0
    user, meas_file, rmag_out, rmag_file = "", "agm_measurements.txt", "rmag_hysteresis.txt", ""
    pltspec = ""
    dir_path = '.'
    fmt = 'svg'
    verbose = pmagplotlib.verbose
    version_num = pmag.get_version()
    if '-WD' in args:
        ind = args.index('-WD')
        dir_path = args[ind+1]
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    if "-usr" in args:
        ind = args.index("-usr")
        user = args[ind+1]
    if '-f' in args:
        ind = args.index("-f")
        meas_file = args[ind+1]
    if '-F' in args:
        ind = args.index("-F")
        rmag_out = args[ind+1]
    if '-fh' in args:
        ind = args.index("-fh")
        rmag_file = args[ind+1]
        rmag_file = dir_path+'/'+rmag_file
    if '-P' in args:
        PLT = 0
        irm_init, imag_init = -1, -1
    if '-sav' in args:
        verbose = 0
        plots = 1
    if '-spc' in args:
        ind = args.index("-spc")
        pltspec = args[ind+1]
        verbose = 0
        plots = 1
    if '-fmt' in args:
        ind = args.index("-fmt")
        fmt = args[ind+1]
    rmag_out = dir_path+'/'+rmag_out
    meas_file = dir_path+'/'+meas_file
    rmag_rem = dir_path+"/rmag_remanence.txt"
    #
    #
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(main.__doc__)
        print('bad file')
        sys.exit()
    #
    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs, RemRecs = [], []
    HDD = {}
    if verbose:
        if verbose and PLT:
            print("Plots may be on top of each other - use mouse to place ")
    if PLT:
        HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'] = 1, 2, 3
        pmagplotlib.plot_init(HDD['DdeltaM'], 5, 5)
        pmagplotlib.plot_init(HDD['deltaM'], 5, 5)
        pmagplotlib.plot_init(HDD['hyst'], 5, 5)
        imag_init = 0
        irm_init = 0
    else:
        HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'], HDD['irm'], HDD['imag'] = 0, 0, 0, 0, 0
    #
    if rmag_file != "":
        hyst_data, file_type = pmag.magic_read(rmag_file)
    #
    # get list of unique experiment names and specimen names
    #
    experiment_names, sids = [], []
    for rec in meas_data:
        meths = rec['magic_method_codes'].split(':')
        methods = []
        for meth in meths:
            methods.append(meth.strip())
        if 'LP-HYS' in methods:
            if 'er_synthetic_name' in list(rec.keys()) and rec['er_synthetic_name'] != "":
                rec['er_specimen_name'] = rec['er_synthetic_name']
            if rec['magic_experiment_name'] not in experiment_names:
                experiment_names.append(rec['magic_experiment_name'])
            if rec['er_specimen_name'] not in sids:
                sids.append(rec['er_specimen_name'])
    #
    k = 0
    locname = ''
    if pltspec != "":
        k = sids.index(pltspec)
        print(sids[k])
    while k < len(sids):
        s = sids[k]
        if verbose and PLT:
            print(s, k+1, 'out of ', len(sids))
    #
    #
        # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        B, M, Bdcd, Mdcd = [], [], [], []
        Bimag, Mimag = [], []  # Bimag,Mimag for initial magnetization curves
        first_dcd_rec, first_rec, first_imag_rec = 1, 1, 1
        for rec in meas_data:
            methcodes = rec['magic_method_codes'].split(':')
            meths = []
            for meth in methcodes:
                meths.append(meth.strip())
            if rec['er_specimen_name'] == s and "LP-HYS" in meths:
                B.append(float(rec['measurement_lab_field_dc']))
                M.append(float(rec['measurement_magn_moment']))
                if first_rec == 1:
                    e = rec['magic_experiment_name']
                    HystRec = {}
                    first_rec = 0
                    if "er_location_name" in list(rec.keys()):
                        HystRec["er_location_name"] = rec["er_location_name"]
                        locname = rec['er_location_name'].replace('/', '-')
                    if "er_sample_name" in list(rec.keys()):
                        HystRec["er_sample_name"] = rec["er_sample_name"]
                    if "er_site_name" in list(rec.keys()):
                        HystRec["er_site_name"] = rec["er_site_name"]
                    if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name'] != "":
                        HystRec["er_synthetic_name"] = rec["er_synthetic_name"]
                    else:
                        HystRec["er_specimen_name"] = rec["er_specimen_name"]
            if rec['er_specimen_name'] == s and "LP-IRM-DCD" in meths:
                Bdcd.append(float(rec['treatment_dc_field']))
                Mdcd.append(float(rec['measurement_magn_moment']))
                if first_dcd_rec == 1:
                    RemRec = {}
                    irm_exp = rec['magic_experiment_name']
                    first_dcd_rec = 0
                    if "er_location_name" in list(rec.keys()):
                        RemRec["er_location_name"] = rec["er_location_name"]
                    if "er_sample_name" in list(rec.keys()):
                        RemRec["er_sample_name"] = rec["er_sample_name"]
                    if "er_site_name" in list(rec.keys()):
                        RemRec["er_site_name"] = rec["er_site_name"]
                    if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name'] != "":
                        RemRec["er_synthetic_name"] = rec["er_synthetic_name"]
                    else:
                        RemRec["er_specimen_name"] = rec["er_specimen_name"]
            if rec['er_specimen_name'] == s and "LP-IMAG" in meths:
                if first_imag_rec == 1:
                    imag_exp = rec['magic_experiment_name']
                    first_imag_rec = 0
                Bimag.append(float(rec['measurement_lab_field_dc']))
                Mimag.append(float(rec['measurement_magn_moment']))
    #
    # now plot the hysteresis curve
    #
        if len(B) > 0:
            hmeths = []
            for meth in meths:
                hmeths.append(meth)
            hpars = pmagplotlib.plot_hdd(HDD, B, M, e)
            if verbose and PLT:
                pmagplotlib.draw_figs(HDD)
    #
    # get prior interpretations from hyst_data
            if rmag_file != "":
                hpars_prior = {}
                for rec in hyst_data:
                    if rec['magic_experiment_names'] == e:
                        if rec['hysteresis_bcr'] != "" and rec['hysteresis_mr_moment'] != "":
                            hpars_prior['hysteresis_mr_moment'] = rec['hysteresis_mr_moment']
                            hpars_prior['hysteresis_ms_moment'] = rec['hysteresis_ms_moment']
                            hpars_prior['hysteresis_bc'] = rec['hysteresis_bc']
                            hpars_prior['hysteresis_bcr'] = rec['hysteresis_bcr']
                            break
                if verbose:
                    pmagplotlib.plot_hpars(HDD, hpars_prior, 'ro')
            else:
                if verbose:
                    pmagplotlib.plot_hpars(HDD, hpars, 'bs')
                HystRec['hysteresis_mr_moment'] = hpars['hysteresis_mr_moment']
                HystRec['hysteresis_ms_moment'] = hpars['hysteresis_ms_moment']
                HystRec['hysteresis_bc'] = hpars['hysteresis_bc']
                HystRec['hysteresis_bcr'] = hpars['hysteresis_bcr']
                HystRec['hysteresis_xhf'] = hpars['hysteresis_xhf']
                HystRec['magic_experiment_names'] = e
                HystRec['magic_software_packages'] = version_num
                if hpars["magic_method_codes"] not in hmeths:
                    hmeths.append(hpars["magic_method_codes"])
                methods = ""
                for meth in hmeths:
                    methods = methods+meth.strip()+":"
                HystRec["magic_method_codes"] = methods[:-1]
                HystRec["er_citation_names"] = "This study"
                HystRecs.append(HystRec)
    #
        if len(Bdcd) > 0:
            rmeths = []
            for meth in meths:
                rmeths.append(meth)
            if verbose and PLT:
                print('plotting IRM')
            if irm_init == 0:
                HDD['irm'] = 5
                pmagplotlib.plot_init(HDD['irm'], 5, 5)
                irm_init = 1
            rpars = pmagplotlib.plot_irm(HDD['irm'], Bdcd, Mdcd, irm_exp)
            RemRec['remanence_mr_moment'] = rpars['remanence_mr_moment']
            RemRec['remanence_bcr'] = rpars['remanence_bcr']
            RemRec['magic_experiment_names'] = irm_exp
            if rpars["magic_method_codes"] not in meths:
                meths.append(rpars["magic_method_codes"])
            methods = ""
            for meth in rmeths:
                methods = methods+meth.strip()+":"
            RemRec["magic_method_codes"] = methods[:-1]
            RemRec["er_citation_names"] = "This study"
            RemRecs.append(RemRec)
        else:
            if irm_init:
                pmagplotlib.clearFIG(HDD['irm'])
        if len(Bimag) > 0:
            if verbose:
                print('plotting initial magnetization curve')
# first normalize by Ms
            Mnorm = []
            for m in Mimag:
                Mnorm.append(m / float(hpars['hysteresis_ms_moment']))
            if imag_init == 0:
                HDD['imag'] = 4
                pmagplotlib.plot_init(HDD['imag'], 5, 5)
                imag_init = 1
            pmagplotlib.plot_imag(HDD['imag'], Bimag, Mnorm, imag_exp)
        else:
            if imag_init:
                pmagplotlib.clearFIG(HDD['imag'])
    #
        files = {}
        if plots:
            if pltspec != "":
                s = pltspec
            files = {}
            for key in list(HDD.keys()):
                files[key] = locname+'_'+s+'_'+key+'.'+fmt
            pmagplotlib.save_plots(HDD, files)
            if pltspec != "":
                sys.exit()
        if verbose and PLT:
            pmagplotlib.draw_figs(HDD)
            ans = input(
                "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ")
            if ans == "a":
                files = {}
                for key in list(HDD.keys()):
                    files[key] = locname+'_'+s+'_'+key+'.'+fmt
                pmagplotlib.save_plots(HDD, files)
            if ans == '':
                k += 1
            if ans == "p":
                del HystRecs[-1]
                k -= 1
            if ans == 'q':
                print("Good bye")
                sys.exit()
            if ans == 's':
                keepon = 1
                specimen = input(
                    'Enter desired specimen name (or first part there of): ')
                while keepon == 1:
                    try:
                        k = sids.index(specimen)
                        keepon = 0
                    except:
                        tmplist = []
                        for qq in range(len(sids)):
                            if specimen in sids[qq]:
                                tmplist.append(sids[qq])
                        print(specimen, " not found, but this was: ")
                        print(tmplist)
                        specimen = input('Select one or try again\n ')
                        k = sids.index(specimen)
        else:
            k += 1
        if len(B) == 0 and len(Bdcd) == 0:
            if verbose:
                print('skipping this one - no hysteresis data')
            k += 1
    if rmag_out == "" and ans == 's' and verbose:
        really = input(
            " Do you want to overwrite the existing rmag_hystersis.txt file? 1/[0] ")
        if really == "":
            print('i thought not - goodbye')
            sys.exit()
        rmag_out = "rmag_hysteresis.txt"
    if len(HystRecs) > 0:
        pmag.magic_write(rmag_out, HystRecs, "rmag_hysteresis")
        if verbose:
            print("hysteresis parameters saved in ", rmag_out)
    if len(RemRecs) > 0:
        pmag.magic_write(rmag_rem, RemRecs, "rmag_remanence")
        if verbose:
            print("remanence parameters saved in ", rmag_rem)
Ejemplo n.º 53
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)
Ejemplo n.º 54
0
def main():
    """
    NAME
        lowrie.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX
        lowrie -h [command line options]

    INPUT
       takes SIO formatted input files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file
        -N do not normalize by maximum magnetization
        -fmt [svg, pdf, eps, png] specify fmt, default is svg
        -sav save plots and quit
    """
    fmt, plot = 'svg', 0
    FIG = {}  # plot dictionary
    FIG['lowrie'] = 1  # demag is figure 1
    pmagplotlib.plot_init(FIG['lowrie'], 6, 6)
    norm = 1  # default is to normalize by maximum axis
    if len(sys.argv) > 1:
        if '-h' in sys.argv:
            print(main.__doc__)
            sys.exit()
        if '-N' in sys.argv:
            norm = 0  # don't normalize
        if '-sav' in sys.argv:
            plot = 1  # don't normalize
        if '-fmt' in sys.argv:  # sets input filename
            ind = sys.argv.index("-fmt")
            fmt = sys.argv[ind + 1]
        if '-f' in sys.argv:  # sets input filename
            ind = sys.argv.index("-f")
            in_file = sys.argv[ind + 1]
        else:
            print(main.__doc__)
            print('you must supply a file name')
            sys.exit()
    else:
        print(main.__doc__)
        print('you must supply a file name')
        sys.exit()
    data = pmag.open_file(in_file)
    PmagRecs = []  # set up a list for the results
    keys = ['specimen', 'treatment', 'csd', 'M', 'dec', 'inc']
    for line in data:
        PmagRec = {}
        rec = line.replace('\n', '').split()
        for k in range(len(keys)):
            PmagRec[keys[k]] = rec[k]
        PmagRecs.append(PmagRec)
    specs = pmag.get_dictkey(PmagRecs, 'specimen', '')
    sids = []
    for spec in specs:
        if spec not in sids:
            sids.append(spec)  # get list of unique specimen names
    for spc in sids:  # step through the specimen names
        pmagplotlib.plot_init(FIG['lowrie'], 6, 6)
        print(spc)
        specdata = pmag.get_dictitem(
            PmagRecs, 'specimen', spc, 'T')  # get all this one's data
        DIMs, Temps = [], []
        for dat in specdata:  # step through the data
            DIMs.append([float(dat['dec']), float(
                dat['inc']), float(dat['M']) * 1e-3])
            Temps.append(float(dat['treatment']))
        carts = pmag.dir2cart(DIMs).transpose()
        # if norm==1: # want to normalize
        #    nrm=max(max(abs(carts[0])),max(abs(carts[1])),max(abs(carts[2]))) # by maximum of x,y,z values
        #    ylab="M/M_max"
        if norm == 1:  # want to normalize
            nrm = (DIMs[0][2])  # normalize by NRM
            ylab = "M/M_o"
        else:
            nrm = 1.  # don't normalize
            ylab = "Magnetic moment (Am^2)"
        xlab = "Temperature (C)"
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[0]), nrm), sym='r-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[0]), nrm), sym='ro')  # X direction
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[1]), nrm), sym='c-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[1]), nrm), sym='cs')  # Y direction
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[2]), nrm), sym='k-')
        pmagplotlib.plot_xy(FIG['lowrie'], Temps, old_div(
            abs(carts[2]), nrm), sym='k^', title=spc, xlab=xlab, ylab=ylab)  # Z direction
        files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt}
        if plot == 0:
            pmagplotlib.draw_figs(FIG)
            ans = input('S[a]ve figure? [q]uit, <return> to continue   ')
            if ans == 'a':
                pmagplotlib.save_plots(FIG, files)
            elif ans == 'q':
                sys.exit()
        else:
            pmagplotlib.save_plots(FIG, files)
        pmagplotlib.clearFIG(FIG['lowrie'])
Ejemplo n.º 55
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,'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)
Ejemplo n.º 56
0
def main():
    """
    NAME
        site_edit_magic.py

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

    SYNTAX
        site_edit_magic.py [command line options]

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

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

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