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

    DESCRIPTION
       calculates fisher parameters from dec inc data

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

    SYNTAX
       gofish.py [options]  [< filename]

    OPTIONS
        -h prints help message and quits
        -i for interactive filename entry
        -f FILE, specify input file
        -F FILE, specifies output file name
        < filename for reading from standard input
   
    OUTPUT
       mean dec, mean inc, N, R, k, a95, csd

    """
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    if '-i' in sys.argv: # ask for filename
        file=raw_input("Enter file name with dec, inc data: ")
        f=open(file,'rU')
        data=f.readlines()
    elif '-f' in sys.argv:
        dat=[]
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'rU')
        data=f.readlines()
    else:
        data = sys.stdin.readlines()  # read from standard input
    ofile = ""
    if '-F' in sys.argv:
        ind = sys.argv.index('-F')
        ofile= sys.argv[ind+1]
        out = open(ofile, 'w + a')
    DIs= [] # set up list for dec inc data
    for line in data:   # read in the data from standard input
        if '\t' in line:
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        DIs.append((float(rec[0]),float(rec[1])))
#
    fpars=pmag.fisher_mean(DIs)
    outstring='%7.1f %7.1f    %i %10.4f %8.1f %7.1f %7.1f'%(fpars['dec'],fpars['inc'],fpars['n'],fpars['r'],fpars['k'],fpars['alpha95'], fpars['csd'])
    if ofile == "":
        print outstring
    else:
        out.write(outstring+'\n')
Esempio n. 2
0
def fisher_stat(data, selected_dots, system):
    col_D = "Dg"
    col_I = "Ig"
    if system == "stratigraphic":
        col_D = "Ds"
        col_I = "Is"

    do_fisher_list = []
    for i in selected_dots:
        do_fisher_list.append([data[col_D][i], data[col_I][i], 1.0])

    fisher_mean_stat = pmag.fisher_mean(do_fisher_list)
    a95, K, D, I = fisher_mean_stat["alpha95"], fisher_mean_stat["k"], fisher_mean_stat["dec"], fisher_mean_stat["inc"]
    xm, ym, zm = dir_to_xyz(D, I, 1)

    Rs = np.sqrt(xm ** 2 + ym ** 2 + zm ** 2)
    xm /= Rs
    ym /= Rs
    zm /= Rs
    return a95, K, Rs, D, I, xm, ym, zm
Esempio n. 3
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)
Esempio n. 4
0
def main():
    """
    NAME
       watsons_v.py

    DESCRIPTION
       calculates Watson's V statistic from input files

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files
   
    SYNTAX
       watsons_v.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE (with optional second)
        -f2 FILE (second file) 
        -ant,  flip antipodal directions to opposite direction
           in first file if only one file or flip all in second, if two files 
        -P  (don't save or show plot)
        -sav save figure and quit silently
        -fmt [png,svg,eps,pdf,jpg] format for saved figure

    OUTPUT
        Watson's V and the Monte Carlo Critical Value Vc.
        in plot, V is solid and Vc is dashed.

    """
    Flip = 0
    show, plot = 1, 0
    fmt = 'svg'
    file2 = ""
    if '-h' in sys.argv:  # check if help is needed
        print main.__doc__
        sys.exit()  # graceful quit
    if '-ant' in sys.argv: Flip = 1
    if '-sav' in sys.argv: show, plot = 0, 1  # don't display, but do save plot
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = sys.argv[ind + 1]
    if '-P' in sys.argv: show = 0  # don't display or save plot
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file1 = sys.argv[ind + 1]
        data = numpy.loadtxt(file1).transpose()
        D1 = numpy.array([data[0], data[1]]).transpose()
    else:
        print "-f is required"
        print main.__doc__
        sys.exit()
    if '-f2' in sys.argv:
        ind = sys.argv.index('-f2')
        file2 = sys.argv[ind + 1]
        data2 = numpy.loadtxt(file2).transpose()
        D2 = numpy.array([data2[0], data2[1]]).transpose()
        if Flip == 1:
            D2, D = pmag.flip(D2)  # D2 are now flipped
            if len(D2) != 0:
                if len(D) != 0:
                    D2 = numpy.concatenate(D, D2)  # put all in D2
            elif len(D) != 0:
                D2 = D
            else:
                print 'length of second file is zero'
                sys.exit()
    elif Flip == 1:
        D2, D1 = pmag.flip(D1)  # peel out antipodal directions, put in D2
    #
    counter, NumSims = 0, 5000
    #
    # first calculate the fisher means and cartesian coordinates of each set of Directions
    #
    pars_1 = pmag.fisher_mean(D1)
    pars_2 = pmag.fisher_mean(D2)
    #
    # get V statistic for these
    #
    V = pmag.vfunc(pars_1, pars_2)
    #
    # do monte carlo simulation of datasets with same kappas, but common mean
    #
    Vp = []  # set of Vs from simulations
    if show == 1: print "Doing ", NumSims, " simulations"
    for k in range(NumSims):
        counter += 1
        if counter == 50:
            if show == 1: print k + 1
            counter = 0
        Dirp = []
        # get a set of N1 fisher distributed vectors with k1, calculate fisher stats
        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 one)
#
    Vp.sort()
    k = int(.95 * NumSims)
    if show == 1:
        print "Watson's V,  Vcrit: "
        print '   %10.1f %10.1f' % (V, Vp[k])
    if show == 1 or plot == 1:
        print "Watson's V,  Vcrit: "
        print '   %10.1f %10.1f' % (V, Vp[k])
        CDF = {'cdf': 1}
        pmagplotlib.plot_init(CDF['cdf'], 5, 5)
        pmagplotlib.plotCDF(CDF['cdf'], Vp, "Watson's V", 'r', "")
        pmagplotlib.plotVs(CDF['cdf'], [V], 'g', '-')
        pmagplotlib.plotVs(CDF['cdf'], [Vp[k]], 'b', '--')
        if plot == 0: pmagplotlib.drawFIGS(CDF)
        files = {}
        if file2 != "":
            files['cdf'] = 'watsons_v_' + file1 + '_' + file2 + '.' + fmt
        else:
            files['cdf'] = 'watsons_v_' + file1 + '.' + fmt
        if pmagplotlib.isServer:
            black = '#000000'
            purple = '#800080'
            titles = {}
            titles['cdf'] = 'Cumulative Distribution'
            CDF = pmagplotlib.addBorders(CDF, titles, black, purple)
            pmagplotlib.saveP(CDF, files)
        elif plot == 0:
            ans = raw_input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans == "a": pmagplotlib.saveP(CDF, files)
        if plot == 1:  # save and quit silently
            pmagplotlib.saveP(CDF, files)
Esempio n. 5
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

            files[key]=filename

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

        if plt:
            pmagplotlib.saveP(FIG,files)
            continue
        if verbose:
            pmagplotlib.drawFIGS(FIG)
            ans=input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
            if ans == "q":
                sys.exit()
            if ans == "a":
                pmagplotlib.saveP(FIG,files)
        continue
Esempio n. 6
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)
Esempio n. 7
0
def main():
    """
    NAME
       revtest_MM1990.py

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

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

    SYNTAX
       revtest_MM1990.py [command line options]

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

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

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

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

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

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

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

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

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

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

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

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

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

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

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



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

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

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

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

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

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

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


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

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

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

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

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

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

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

            files[key]=filename

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

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

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

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

    SYNTAX
       plotdi_e.py [command line options]

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

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

    DESCRIPTION
       calculates Watson's F statistic from input files

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files
   
    SYNTAX
       watsons_f.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE (with optional second)
        -f2 FILE (second file) 
        -ant,  flip antipodal directions in FILE to opposite direction

    OUTPUT
        Watson's F, critical value from F-tables for 2, 2(N-2) degrees of freedom

    """
    D,D1,D2=[],[],[]
    Flip=0
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    if '-ant' in  sys.argv: Flip=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]
    f=open(file1,'rU')
    for line in f.readlines():
        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
        Dec,Inc=float(rec[0]),float(rec[1]) 
        D1.append([Dec,Inc,1.])
        D.append([Dec,Inc,1.])
    f.close()
    if Flip==0:
        f=open(file2,'rU')
        for line in f.readlines():
            rec=line.split()
            Dec,Inc=float(rec[0]),float(rec[1]) 
            D2.append([Dec,Inc,1.])
            D.append([Dec,Inc,1.])
        f.close()
    else:
        D1,D2=pmag.flip(D1)
        for d in D2: D.append(d) 
#
# first calculate the fisher means and cartesian coordinates of each set of Directions
#
    pars_0=pmag.fisher_mean(D)
    pars_1=pmag.fisher_mean(D1)
    pars_2=pmag.fisher_mean(D2)
#
# get F statistic for these
#
    N= len(D)
    R=pars_0['r']
    R1=pars_1['r']
    R2=pars_2['r']
    F=(N-2)*((R1+R2-R)/(N-R1-R2))
    Fcrit=pmag.fcalc(2,2*(N-2))
    print '%7.2f %7.2f'%(F,Fcrit)
Esempio n. 11
0
def main():
    """
    NAME
       watsons_f.py

    DESCRIPTION
       calculates Watson's F statistic from input files

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files
   
    SYNTAX
       watsons_f.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE (with optional second)
        -f2 FILE (second file) 
        -ant,  flip antipodal directions in FILE to opposite direction

    OUTPUT
        Watson's F, critical value from F-tables for 2, 2(N-2) degrees of freedom

    """
    D, D1, D2 = [], [], []
    Flip = 0
    if '-h' in sys.argv:  # check if help is needed
        print main.__doc__
        sys.exit()  # graceful quit
    if '-ant' in sys.argv: Flip = 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]
    f = open(file1, 'rU')
    for line in f.readlines():
        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
        Dec, Inc = float(rec[0]), float(rec[1])
        D1.append([Dec, Inc, 1.])
        D.append([Dec, Inc, 1.])
    f.close()
    if Flip == 0:
        f = open(file2, 'rU')
        for line in f.readlines():
            rec = line.split()
            Dec, Inc = float(rec[0]), float(rec[1])
            D2.append([Dec, Inc, 1.])
            D.append([Dec, Inc, 1.])
        f.close()
    else:
        D1, D2 = pmag.flip(D1)
        for d in D2:
            D.append(d)


#
# first calculate the fisher means and cartesian coordinates of each set of Directions
#
    pars_0 = pmag.fisher_mean(D)
    pars_1 = pmag.fisher_mean(D1)
    pars_2 = pmag.fisher_mean(D2)
    #
    # get F statistic for these
    #
    N = len(D)
    R = pars_0['r']
    R1 = pars_1['r']
    R2 = pars_2['r']
    F = (N - 2) * ((R1 + R2 - R) / (N - R1 - R2))
    Fcrit = pmag.fcalc(2, 2 * (N - 2))
    print '%7.2f %7.2f' % (F, Fcrit)
Esempio n. 12
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

    INPUT
       takes magic formatted 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)
Esempio n. 13
0
def main():
    """
    NAME
       plotdi_e.py

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

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

    SYNTAX
       plotdi_e.py [command line options]

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

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

    DESCRIPTION
       calculates fisher parameters from dec inc data

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

    SYNTAX
       gofish.py [options]  [< filename]

    OPTIONS
        -h prints help message and quits
        -i for interactive filename entry
        -f FILE, specify input file
        -F FILE, specifies output file name
        < filename for reading from standard input
   
    OUTPUT
       mean dec, mean inc, N, R, k, a95, csd

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


#
    fpars = pmag.fisher_mean(DIs)
    outstring = '%7.1f %7.1f    %i %10.4f %8.1f %7.1f %7.1f' % (
        fpars['dec'], fpars['inc'], fpars['n'], fpars['r'], fpars['k'],
        fpars['alpha95'], fpars['csd'])
    if ofile == "":
        print(outstring)
    else:
        out.write(outstring + '\n')
Esempio n. 15
0
def main():
    """
    NAME
       watsons_v.py

    DESCRIPTION
       calculates Watson's V statistic from input files

    INPUT FORMAT
       takes dec/inc as first two columns in two space delimited files
   
    SYNTAX
       watsons_v.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f FILE (with optional second)
        -f2 FILE (second file) 
        -ant,  flip antipodal directions to opposite direction
           in first file if only one file or flip all in second, if two files 
        -P  (don't save or show plot)
        -sav save figure and quit silently
        -fmt [png,svg,eps,pdf,jpg] format for saved figure

    OUTPUT
        Watson's V and the Monte Carlo Critical Value Vc.
        in plot, V is solid and Vc is dashed.

    """
    Flip=0
    show,plot=1,0
    fmt='svg'
    file2=""
    if '-h' in sys.argv: # check if help is needed
        print main.__doc__
        sys.exit() # graceful quit
    if '-ant' in  sys.argv: Flip=1
    if '-sav' in sys.argv: show,plot=0,1 # don't display, but do save plot
    if '-fmt' in sys.argv: 
        ind=sys.argv.index('-fmt')
        fmt=sys.argv[ind+1]
    if '-P' in  sys.argv: show=0 # don't display or save plot
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file1=sys.argv[ind+1]
        data=numpy.loadtxt(file1).transpose()
        D1=numpy.array([data[0],data[1]]).transpose()
    else:
        print "-f is required"
        print main.__doc__
        sys.exit()
    if '-f2' in sys.argv:
        ind=sys.argv.index('-f2')
        file2=sys.argv[ind+1]
        data2=numpy.loadtxt(file2).transpose()
        D2=numpy.array([data2[0],data2[1]]).transpose()
        if Flip==1:
            D2,D=pmag.flip(D2) # D2 are now flipped
            if len(D2)!=0:
                if len(D)!=0: 
                    D2=numpy.concatenate(D,D2) # put all in D2
            elif len(D)!=0:
                D2=D
            else: 
                print 'length of second file is zero'
                sys.exit()
    elif Flip==1:D2,D1=pmag.flip(D1) # peel out antipodal directions, put in D2
#
    counter,NumSims=0,5000
#
# first calculate the fisher means and cartesian coordinates of each set of Directions
#
    pars_1=pmag.fisher_mean(D1)
    pars_2=pmag.fisher_mean(D2)
#
# get V statistic for these
#
    V=pmag.vfunc(pars_1,pars_2)
#
# do monte carlo simulation of datasets with same kappas, but common mean
# 
    Vp=[] # set of Vs from simulations
    if show==1:print "Doing ",NumSims," simulations"
    for k in range(NumSims):
        counter+=1
        if counter==50:
            if show==1:print k+1
            counter=0
        Dirp=[]
# get a set of N1 fisher distributed vectors with k1, calculate fisher stats
        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 one)
#
    Vp.sort()
    k=int(.95*NumSims)
    if show==1:
        print "Watson's V,  Vcrit: " 
        print '   %10.1f %10.1f'%(V,Vp[k])
    if show==1 or plot==1:
        print "Watson's V,  Vcrit: " 
        print '   %10.1f %10.1f'%(V,Vp[k])
        CDF={'cdf':1}
        pmagplotlib.plot_init(CDF['cdf'],5,5)
        pmagplotlib.plotCDF(CDF['cdf'],Vp,"Watson's V",'r',"")
        pmagplotlib.plotVs(CDF['cdf'],[V],'g','-')
        pmagplotlib.plotVs(CDF['cdf'],[Vp[k]],'b','--')
        if plot==0:pmagplotlib.drawFIGS(CDF)
        files={}
        if file2!="":
            files['cdf']='watsons_v_'+file1+'_'+file2+'.'+fmt
        else:
            files['cdf']='watsons_v_'+file1+'.'+fmt
        if pmagplotlib.isServer:
            black     = '#000000'
            purple    = '#800080'
            titles={}
            titles['cdf']='Cumulative Distribution'
            CDF = pmagplotlib.addBorders(CDF,titles,black,purple)
            pmagplotlib.saveP(CDF,files)
        elif plot==0:
            ans=raw_input(" S[a]ve to save plot, [q]uit without saving:  ")
            if ans=="a": pmagplotlib.saveP(CDF,files) 
        if plot==1: # save and quit silently
            pmagplotlib.saveP(CDF,files)
Esempio n. 16
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

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

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

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

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if plt:
            pmagplotlib.saveP(FIG, files)
            continue
        if verbose:
            pmagplotlib.drawFIGS(FIG)
            ans = raw_input(" S[a]ve to save plot, [q]uit, Return to continue:  ")
            if ans == "q":
                sys.exit()
            if ans == "a":
                pmagplotlib.saveP(FIG, files)
        continue