Exemplo n.º 1
0
def main():
    """
    NAME 
        pmag_results_extract.py

    DESCRIPTION
        make a tab delimited output file from pmag_results table
 
    SYNTAX
        pmag_results_extract.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f RFILE, specify pmag_results table; default is pmag_results.txt
        -fa AFILE, specify er_ages table; default is NONE
        -fsp SFILE, specify pmag_specimens table, default is NONE
        -fcr CFILE, specify pmag_criteria table, default is NONE
        -g include specimen_grade in table - only works for PmagPy generated pmag_specimen formatted files.
        -tex,  output in LaTeX format
    """
    do_help = pmag.get_flag_arg_from_sys('-h')
    if do_help:
        print(main.__doc__)
        return False
    res_file = pmag.get_named_arg_from_sys('-f', 'pmag_results.txt')
    crit_file = pmag.get_named_arg_from_sys('-fcr', '')
    spec_file = pmag.get_named_arg_from_sys('-fsp', '')
    age_file = pmag.get_named_arg_from_sys('-fa', '')
    grade = pmag.get_flag_arg_from_sys('-g')
    latex = pmag.get_flag_arg_from_sys('-tex')
    WD = pmag.get_named_arg_from_sys('-WD', os.getcwd())
    ipmag.pmag_results_extract(res_file, crit_file, spec_file, age_file, latex, grade, WD)
Exemplo n.º 2
0
def main():
    """
    NAME 
        pmag_results_extract.py

    DESCRIPTION
        make a tab delimited output file from pmag_results table
 
    SYNTAX
        pmag_results_extract.py [command line options]

    OPTIONS
        -h prints help message and quits
        -f RFILE, specify pmag_results table; default is pmag_results.txt
        -fa AFILE, specify er_ages table; default is NONE
        -fsp SFILE, specify pmag_specimens table, default is NONE
        -fcr CFILE, specify pmag_criteria table, default is NONE
        -g include specimen_grade in table - only works for PmagPy generated pmag_specimen formatted files.
        -tex,  output in LaTeX format
    """
    do_help = pmag.get_flag_arg_from_sys('-h')
    if do_help:
        print(main.__doc__)
        return False
    res_file = pmag.get_named_arg('-f', 'pmag_results.txt')
    crit_file = pmag.get_named_arg('-fcr', '')
    spec_file = pmag.get_named_arg('-fsp', '')
    age_file = pmag.get_named_arg('-fa', '')
    grade = pmag.get_flag_arg_from_sys('-g')
    latex = pmag.get_flag_arg_from_sys('-tex')
    WD = pmag.get_named_arg('-WD', os.getcwd())
    ipmag.pmag_results_extract(res_file, crit_file, spec_file, age_file, latex, grade, WD)
Exemplo n.º 3
0
def main():
    """
    NAME
        dmag_magic.py

    DESCRIPTION
       plots intensity decay curves for demagnetization experiments

    SYNTAX
        dmag_magic -h [command line options]

    INPUT
       takes magic formatted measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot,
               default is by location
        -LT [AF,T,M]: specify lab treatment type, default AF
        -XLP [PI]: exclude specific  lab protocols,
               (for example, method codes like LP-PI)
        -N do not normalize by NRM magnetization
        -sav save plots silently and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    # initialize variables from command line + defaults
    dir_path = pmag.get_named_arg("-WD", default_val=".")
    input_dir_path = pmag.get_named_arg('-ID', '')
    if not input_dir_path:
        input_dir_path = dir_path
    in_file = pmag.get_named_arg("-f", default_val="measurements.txt")
    in_file = pmag.resolve_file_name(in_file, input_dir_path)
    if "-ID" not in sys.argv:
        input_dir_path = os.path.split(in_file)[0]
    plot_by = pmag.get_named_arg("-obj", default_val="loc")
    LT = pmag.get_named_arg("-LT", "AF")
    no_norm = pmag.get_flag_arg_from_sys("-N")
    norm = False if no_norm else True
    interactive = True
    save_plots = pmag.get_flag_arg_from_sys("-sav")
    if save_plots:
        interactive = False
    fmt = pmag.get_named_arg("-fmt", "svg")
    XLP = pmag.get_named_arg("-XLP", "")
    spec_file = pmag.get_named_arg("-fsp", default_val="specimens.txt")
    samp_file = pmag.get_named_arg("-fsa", default_val="samples.txt")
    site_file = pmag.get_named_arg("-fsi", default_val="sites.txt")
    loc_file = pmag.get_named_arg("-flo", default_val="locations.txt")
    ipmag.dmag_magic(in_file, dir_path, input_dir_path, spec_file, samp_file,
                     site_file, loc_file, plot_by, LT, norm, XLP,
                     save_plots, fmt, interactive)
Exemplo n.º 4
0
def main():
    """
    NAME
        dmag_magic.py

    DESCRIPTION
       plots intensity decay curves for demagnetization experiments

    SYNTAX
        dmag_magic -h [command line options]

    INPUT
       takes magic formatted measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot,
               default is by location
        -LT [AF,T,M]: specify lab treatment type, default AF
        -XLP [PI]: exclude specific  lab protocols,
               (for example, method codes like LP-PI)
        -N do not normalize by NRM magnetization
        -sav save plots silently and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    # initialize variables from command line + defaults
    dir_path = pmag.get_named_arg("-WD", default_val=".")
    input_dir_path = pmag.get_named_arg('-ID', '')
    if not input_dir_path:
        input_dir_path = dir_path
    in_file = pmag.get_named_arg("-f", default_val="measurements.txt")
    in_file = pmag.resolve_file_name(in_file, input_dir_path)
    if "-ID" not in sys.argv:
        input_dir_path = os.path.split(in_file)[0]
    plot_by = pmag.get_named_arg("-obj", default_val="loc")
    LT = pmag.get_named_arg("-LT", "AF")
    no_norm = pmag.get_flag_arg_from_sys("-N")
    norm = False if no_norm else True
    interactive = True
    save_plots = pmag.get_flag_arg_from_sys("-sav")
    if save_plots:
        interactive = False
    fmt = pmag.get_named_arg("-fmt", "svg")
    XLP = pmag.get_named_arg("-XLP", "")
    spec_file = pmag.get_named_arg("-fsp", default_val="specimens.txt")
    samp_file = pmag.get_named_arg("-fsa", default_val="samples.txt")
    site_file = pmag.get_named_arg("-fsi", default_val="sites.txt")
    loc_file = pmag.get_named_arg("-flo", default_val="locations.txt")
    ipmag.dmag_magic(in_file, dir_path, input_dir_path, spec_file, samp_file,
                     site_file, loc_file, plot_by, LT, norm, XLP,
                     save_plots, fmt, interactive, n_plots="all")
Exemplo n.º 5
0
def main():
    """
    NAME
        download_magic.py

    DESCRIPTION
        unpacks a magic formatted smartbook .txt file from the MagIC database into the
        tab delimited MagIC format txt files for use with the MagIC-Py programs.

    SYNTAX
        download_magic.py command line options]
    INPUT
        takes either the upload.txt file created by upload_magic.py or a file
        downloaded from the MagIC database (http://earthref.org/MagIC)


    OPTIONS
        -h prints help message and quits
        -i allows interactive entry of filename
        -f FILE specifies input file name
        -sep write location data to separate subdirectories (Location_*), (default False)
        -O do not overwrite duplicate Location_* directories while downloading
        -DM data model (2 or 3, default 3)
    """
    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]
    # interactive entry
    if '-i' in sys.argv:
        infile = input("Magic txt file for unpacking? ")
        dir_path = '.'
        input_dir_path = '.'
    # non-interactive
    else:
        infile = pmag.get_named_arg("-f", reqd=True)
        # if -O flag is present, overwrite is False
        overwrite = pmag.get_flag_arg_from_sys("-O", true=False, false=True)
        # if -sep flag is present, sep is True
        sep = pmag.get_flag_arg_from_sys("-sep", true=True, false=False)
        data_model = pmag.get_named_arg("-DM", default_val=3, reqd=False)
        dir_path = pmag.get_named_arg("-WD", default_val=".", reqd=False)
        input_dir_path = pmag.get_named_arg("-ID", default_val=".", reqd=False)

    #if '-ID' not in sys.argv and '-WD' in sys.argv:
    #    input_dir_path = dir_path
    if "-WD" not in sys.argv and "-ID" not in sys.argv:
        input_dir_path = os.path.split(infile)[0]
    if not input_dir_path:
        input_dir_path = "."

    ipmag.download_magic(infile, dir_path, input_dir_path, overwrite, True,
                         data_model, sep)
Exemplo n.º 6
0
def main():
    """
    NAME
        download_magic.py

    DESCRIPTION
        unpacks a magic formatted smartbook .txt file from the MagIC database into the
        tab delimited MagIC format txt files for use with the MagIC-Py programs.

    SYNTAX
        download_magic.py command line options]
    INPUT
        takes either the upload.txt file created by upload_magic.py or a file
        downloaded from the MagIC database (http://earthref.org/MagIC)


    OPTIONS
        -h prints help message and quits
        -i allows interactive entry of filename
        -f FILE specifies input file name
        -sep write location data to separate subdirectories (Location_*), (default False)
        -O do not overwrite duplicate Location_* directories while downloading
        -DM data model (2 or 3, default 3)
    """
    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]
    # interactive entry
    if '-i' in sys.argv:
        infile=input("Magic txt file for unpacking? ")
        dir_path = '.'
        input_dir_path = '.'
    # non-interactive
    else:
        infile = pmag.get_named_arg("-f", reqd=True)
        # if -O flag is present, overwrite is False
        overwrite = pmag.get_flag_arg_from_sys("-O", true=False, false=True)
        # if -sep flag is present, sep is True
        sep = pmag.get_flag_arg_from_sys("-sep", true=True, false=False)
        data_model = pmag.get_named_arg("-DM", default_val=3, reqd=False)
        dir_path = pmag.get_named_arg("-WD", default_val=".", reqd=False)
        input_dir_path = pmag.get_named_arg("-ID", default_val=".", reqd=False)

    #if '-ID' not in sys.argv and '-WD' in sys.argv:
    #    input_dir_path = dir_path
    if "-WD" not in sys.argv and "-ID" not in sys.argv:
        input_dir_path = os.path.split(infile)[0]
    if not input_dir_path:
        input_dir_path = "."

    ipmag.download_magic(infile, dir_path, input_dir_path, overwrite, True, data_model, sep)
Exemplo n.º 7
0
def main():
    """
    NAME
        aniso_magic.py

    DESCRIPTION
        plots anisotropy data with either bootstrap or hext ellipses

    SYNTAX
        aniso_magic.py [-h] [command line options]
    OPTIONS
        -h plots help message and quits
        -f AFILE, specify specimens.txt formatted file for input
        -fsa SAMPFILE, specify samples.txt file (required to plot by site)
        -fsi SITEFILE, specify site file (required to include location information)
        -x Hext [1963] and bootstrap
        -B DON'T do bootstrap, do Hext
        -par Tauxe [1998] parametric bootstrap
        -v plot bootstrap eigenvectors instead of ellipses
        -sit plot by site instead of entire file
        -crd [s,g,t] coordinate system, default is specimen (g=geographic, t=tilt corrected)
        -P don't make any plots - just fill in the specimens, samples, sites tables
        -sav don't make the tables - just save all the plots
        -fmt [svg, jpg, eps] format for output images, png default
        -gtc DEC INC  dec,inc of pole to great circle [down(up) in green (cyan)
        -d Vi DEC INC; Vi (1,2,3) to compare to direction DEC INC
        -n N; specifies the number of bootstraps - default is 1000
    DEFAULTS
       AFILE:  specimens.txt
       plot bootstrap ellipses of Constable & Tauxe [1987]
    NOTES
       minor axis: circles
       major axis: triangles
       principal axis: squares
       directions are plotted on the lower hemisphere
       for bootstrapped eigenvector components: Xs: blue, Ys: red, Zs: black
"""

    args = sys.argv
    if '-h' in args:
        print(main.__doc__)
        return
    dir_path = pmag.get_named_arg("-WD", ".")
    if '-ID' in args and dir_path == '.':
        dir_path = pmag.get_named_arg("-ID", ".")
    iboot, vec = 1, 0
    num_bootstraps = pmag.get_named_arg("-n", 1000)
    ipar = pmag.get_flag_arg_from_sys("-par", true=1, false=0)
    ihext = pmag.get_flag_arg_from_sys("-x", true=1, false=0)
    ivec = pmag.get_flag_arg_from_sys("-v", true=1, false=0)
    if ivec:
        vec = 3
    #iplot = pmag.get_flag_arg_from_sys("-P", true=0, false=1)
    isite = pmag.get_flag_arg_from_sys("-sit", true=1, false=0)
    infile = pmag.get_named_arg('-f', 'specimens.txt')
    samp_file = pmag.get_named_arg('-fsa', 'samples.txt')
    site_file = pmag.get_named_arg('-fsi', 'sites.txt')
    #outfile = pmag.get_named_arg("-F", "rmag_results.txt")
    fmt = pmag.get_named_arg("-fmt", "png")
    crd = pmag.get_named_arg("-crd", "s")
    comp, Dir, PDir = 0, [], []
    user = pmag.get_named_arg("-usr", "")
    if '-B' in args:
        iboot, ihext = 0, 1
    save_plots, verbose, interactive = False, True, True
    if '-sav' in args:
        save_plots = True
        verbose = False
        interactive = False
    if '-gtc' in args:
        ind = args.index('-gtc')
        d, i = float(args[ind+1]), float(args[ind+2])
        PDir.append(d)
        PDir.append(i)
    if '-d' in args:
        comp = 1
        ind = args.index('-d')
        vec = int(args[ind+1])-1
        Dir = [float(args[ind+2]), float(args[ind+3])]
    ipmag.aniso_magic_nb(infile, samp_file, site_file, verbose,
                         ipar, ihext, ivec, isite, False, iboot,
                         vec, Dir, PDir, crd, num_bootstraps,
                         dir_path, save_plots=save_plots, interactive=interactive,
                         fmt=fmt)
Exemplo n.º 8
0
def main():
    """
    NAME
        dmag_magic.py

    DESCRIPTION
       plots intensity decay curves for demagnetization experiments

    SYNTAX
        dmag_magic -h [command line options]

    INPUT
       takes magic formatted magic_measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot,
               default is by location
        -LT [AF,T,M]: specify lab treatment type, default AF
        -XLP [PI]: exclude specific  lab protocols,
               (for example, method codes like LP-PI)
        -N do not normalize by NRM magnetization
        -sav save plots silently and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    # initialize variables from command line + defaults
    FIG = {}  # plot dictionary
    FIG['demag'] = 1  # demag is figure 1
    in_file = pmag.get_named_arg_from_sys("-f", default_val="measurements.txt")
    plot_by = pmag.get_named_arg_from_sys("-obj", default_val="loc")
    name_dict = {
        'loc': 'location',
        'sit': 'site',
        'sam': 'sample',
        'spc': 'specimen'
    }
    plot_key = name_dict[plot_by]
    LT = "LT-" + pmag.get_named_arg_from_sys("-LT", "AF") + "-Z"
    if LT == "LT-T-Z":
        units, dmag_key = 'K', 'treat_temp'
    elif LT == "LT-AF-Z":
        units, dmag_key = 'T', 'treat_ac_field'
    elif LT == 'LT-M-Z':
        units, dmag_key = 'J', 'treat_mw_energy'
    else:
        units = 'U'
    no_norm = pmag.get_flag_arg_from_sys("-N")
    norm = 0 if no_norm else 1
    no_plot = pmag.get_flag_arg_from_sys("-sav")
    plot = 0 if no_plot else 1
    fmt = pmag.get_named_arg_from_sys("-fmt", "svg")
    XLP = pmag.get_named_arg_from_sys("-XLP", "")
    dir_path = pmag.get_named_arg_from_sys("-WD", os.getcwd())
    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")

    # create contribution and add required headers
    fnames = {"specimens": spec_file, "samples": samp_file, 'sites': site_file}
    contribution = nb.Contribution(dir_path,
                                   single_file=in_file,
                                   custom_filenames=fnames)
    file_type = list(contribution.tables.keys())[0]
    print(len(contribution.tables['measurements'].df), ' records read from ',
          in_file)
    # add plot_key into measurements table
    if plot_key not in contribution.tables['measurements'].df.columns:
        #contribution.propagate_name_down(plot_key, 'measurements')
        contribution.propagate_location_to_measurements()
    data_container = contribution.tables[file_type]
    # pare down to only records with useful data
    # grab records that have the requested code
    data_slice = data_container.get_records_for_code(LT)
    # and don't have the offending code
    data = data_container.get_records_for_code(XLP,
                                               incl=False,
                                               use_slice=True,
                                               sli=data_slice,
                                               strict_match=False)

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

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

            if not plot:
                files = {}
                for key in list(FIG.keys()):
                    files[key] = title + '_' + LT + '.' + fmt
                pmagplotlib.saveP(FIG, files)
                #sys.exit()
            else:
                pmagplotlib.drawFIGS(FIG)
                prompt = " S[a]ve to save plot, [q]uit,  Return to continue:  "
                ans = input(prompt)
                if ans == 'q':
                    sys.exit()
                if ans == "a":
                    files = {}
                    for key in list(FIG.keys()):
                        files[key] = title + '_' + LT + '.' + fmt
                    pmagplotlib.saveP(FIG, files)
            pmagplotlib.clearFIG(FIG['demag'])
Exemplo n.º 9
0
def main():
    """
    NAME
        biplot_magic.py

    DESCRIPTION
        makes a biplot of specified variables from magic_measurements.txt format file
  
    SYNTAX
        biplot_magic.py [-h] [-i] [command line options]

    INPUT 
        takes magic formated magic_measurments file

    OPTIONS
        -h prints help message and quits
        -i interactively set filename and axes for plotting
        -f FILE: specifies file name, default: magic_measurements.txt
        -fmt [svg,png,jpg], format for images - default is svg
        -sav figure and quit
        -x XMETH:key:step, specify method code for X axis (optional key and treatment values)
        -y YMETH:key:step, specify method code for X axis
        -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is whole file
        -n [V,M] plot volume or mass normalized data only
    NOTES
        if nothing is specified for x and y, the user will be presented with options
        key = ['treatment_ac_field','treatment_dc_field',treatment_temp'] 
        step in mT for fields, K for temperatures
           """ 
    #
    file='magic_measurements.txt'
    methx,methy,fmt="","",'.svg'
    plot_key=''
    norm_by=""
    #plot=0
    no_plot = pmag.get_flag_arg_from_sys('-sav')
    if not no_plot:
        do_plot = True
    else:
        do_plot = False
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    if '-f' in sys.argv:
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
    if '-fmt' in sys.argv:
        ind=sys.argv.index('-fmt')
        fmt='.'+sys.argv[ind+1]
    if '-n' in sys.argv:
        ind=sys.argv.index('-n')
        norm_by=sys.argv[ind+1]
    xtreat_key,ytreat_key,xstep,ystep="","","",""
    if '-x' in sys.argv:
        ind=sys.argv.index('-x')
        meths=sys.argv[ind+1].split(':')
        methx=meths[0]
        if len(meths)>1:
            xtreat_key=meths[1]
            xstep=float(meths[2])
    if '-y' in sys.argv:
        ind=sys.argv.index('-y')
        meths=sys.argv[ind+1].split(':')
        methy=meths[0]
        if len(meths)>1:
            ytreat_key=meths[1]
            ystep=float(meths[2])
    if '-obj' in sys.argv: 
        ind=sys.argv.index('-obj')
        plot_by=sys.argv[ind+1]
        if plot_by=='loc':plot_key='er_location_name'
        if plot_by=='sit':plot_key='er_site_name'
        if plot_by=='sam':plot_key='er_sample_name'
        if plot_by=='spc':plot_key='er_specimen_name'
    if '-h' in sys.argv:
        do_plot = False
    if '-i' in sys.argv: 
    #
    # get name of file from command line
    #
        file=raw_input("Input magic_measurments file name? [magic_measurements.txt] ")
        if file=="":file="magic_measurements.txt"
    #
    #
    FIG={'fig':1}
    pmagplotlib.plot_init(FIG['fig'],5,5)
    data,file_type=pmag.magic_read(file)
    if file_type!="magic_measurements":
        print file_type,' not correct format for magic_measurments file'
        sys.exit()
    #
    # collect method codes
    methods,plotlist=[],[]
    for rec in  data:
        if plot_key!="":
            if rec[plot_key] not in plotlist:plotlist.append(rec[plot_key])
        elif len(plotlist)==0:
            plotlist.append('All')
        meths=rec['magic_method_codes'].split(':')
        for meth in meths:
            if meth.strip() not in methods and meth.strip()!="LP-":
                methods.append(meth.strip())
    #
    if '-i' in sys.argv:
        print methods
    elif methx =="" or methy=="": 
	print methods
        sys.exit()
    GoOn=1
    while GoOn==1:
        if '-i' in sys.argv:methx=raw_input('Select method for x axis: ')
        if methx not in methods:
            if '-i' in sys.argv:
                print 'try again! method not available'
            else: 
                print main.__doc__
                print '\n must specify X axis method\n'
                sys.exit()
        else:
            if pmagplotlib.verbose: print methx, ' selected for X axis'
            GoOn=0
    GoOn=1
    while GoOn==1:
        if '-i' in sys.argv:methy=raw_input('Select method for y axis: ')
        if methy not in methods:
            if '-i' in sys.argv:
                print 'try again! method not available'
            else: 
                print main.__doc__
                print '\n must specify Y axis method\n'
                sys.exit()
        else:
            if pmagplotlib.verbose: print methy, ' selected for Y axis'
            GoOn=0
    if norm_by=="":
        measkeys=['measurement_magn_mass','measurement_magn_volume','measurement_magn_moment','measurement_magnitude','measurement_chi_volume','measurement_chi_mass','measurement_chi']
    elif norm_by=="V":
        measkeys=['measurement_magn_volume','measurement_chi_volume']
    elif norm_by=="M":
        measkeys=['measurement_magn_mass','measurement_chi_mass']
    xmeaskey,ymeaskey="",""
    plotlist.sort()
    for plot in plotlist: # go through objects
        if pmagplotlib.verbose:
            print plot
        X,Y=[],[]
        x,y='',''
        for rec in data:
            if plot_key!="" and rec[plot_key]!=plot:
                pass
            else:
                meths=rec['magic_method_codes'].split(':')
                for meth in meths:
                    if meth.strip()==methx:
                        if xmeaskey=="":
                            for key in measkeys:
                                if key in rec.keys() and rec[key]!="":
                                    xmeaskey=key
                                    if pmagplotlib.verbose:
                                        print xmeaskey,' being used for plotting X.'
                                    break 
                    if meth.strip()==methy:
                        if ymeaskey=="":
                            for key in measkeys:
                                if key in rec.keys() and rec[key]!="":
                                    ymeaskey=key
                                    if pmagplotlib.verbose:
                                        print ymeaskey,' being used for plotting Y'
                                    break 
        if ymeaskey!="" and xmeaskey!="":
            for rec in data:
                x,y='',''
                spec=rec['er_specimen_name'] # get the ydata for this specimen
                if rec[ymeaskey]!="" and methy in rec['magic_method_codes'].split(':'): 
                    if ytreat_key=="" or (ytreat_key in rec.keys() and float(rec[ytreat_key])==ystep):
                        y=float(rec[ymeaskey])
                        for rec in data: # now find the xdata 
                            if rec['er_specimen_name']==spec and rec[xmeaskey]!="" and methx in rec['magic_method_codes'].split(':'): 
                                if xtreat_key=="" or (xtreat_key in rec.keys() and float(rec[xtreat_key])==xstep):
                                    x=float(rec[xmeaskey])
                if x != '' and y!= '':
                    X.append(x)
                    Y.append(y)
        if len(X)>0:
            pmagplotlib.clearFIG(FIG['fig'])
            pmagplotlib.plotXY(FIG['fig'],X,Y,sym='ro',xlab=methx,ylab=methy,title=plot+':Biplot')
            if not pmagplotlib.isServer and do_plot:
                pmagplotlib.drawFIGS(FIG)
                ans=raw_input('S[a]ve plots, [q]uit,  Return for next plot ' )
                if ans=='a':
                    files={}
                    for key in FIG.keys(): files[key]=plot+'_'+key+fmt
                    pmagplotlib.saveP(FIG,files)
                if ans=='q':
                    print "Good-bye\n"
                    sys.exit()
            else:
                files={}
                for key in FIG.keys(): files[key]=plot+'_'+key+fmt
                if pmagplotlib.isServer:
                    black     = '#000000'
                    purple    = '#800080'
                    titles={}
                    titles['fig']='X Y Plot'
                    FIG = pmagplotlib.addBorders(FIG,titles,black,purple)
                pmagplotlib.saveP(FIG,files)
        else:
            print 'nothing to plot for ',plot
Exemplo n.º 10
0
def main():
    """
    NAME
        aniso_magic.py

    DESCRIPTION
        plots anisotropy data with either bootstrap or hext ellipses

    SYNTAX
        aniso_magic.py [-h] [command line options]
    OPTIONS
        -h plots help message and quits
        -f AFILE, specify specimens.txt formatted file for input
        -fsa SAMPFILE, specify samples.txt file (required to plot by site)
        -fsi SITEFILE, specify site file (required to include location information)
        -x Hext [1963] and bootstrap
        -B DON'T do bootstrap, do Hext
        -par Tauxe [1998] parametric bootstrap
        -v plot bootstrap eigenvectors instead of ellipses
        -sit plot by site instead of entire file
        -crd [s,g,t] coordinate system, default is specimen (g=geographic, t=tilt corrected)
        -P don't make any plots - just fill in the specimens, samples, sites tables
        -sav don't make the tables - just save all the plots
        -fmt [svg, jpg, eps] format for output images, png default
        -gtc DEC INC  dec,inc of pole to great circle [down(up) in green (cyan)
        -d Vi DEC INC; Vi (1,2,3) to compare to direction DEC INC
        -n N; specifies the number of bootstraps - default is 1000
    DEFAULTS
       AFILE:  specimens.txt
       plot bootstrap ellipses of Constable & Tauxe [1987]
    NOTES
       minor axis: circles
       major axis: triangles
       principal axis: squares
       directions are plotted on the lower hemisphere
       for bootstrapped eigenvector components: Xs: blue, Ys: red, Zs: black
"""

    args = sys.argv
    if '-h' in args:
        print(new.__doc__)
        return
    dir_path = pmag.get_named_arg("-WD", ".")
    if '-ID' in args and dir_path == '.':
        dir_path = pmag.get_named_arg("-ID", ".")
    iboot, vec = 1, 0
    num_bootstraps = pmag.get_named_arg("-n", 1000)
    ipar = pmag.get_flag_arg_from_sys("-par", true=1, false=0)
    ihext = pmag.get_flag_arg_from_sys("-x", true=1, false=0)
    ivec = pmag.get_flag_arg_from_sys("-v", true=1, false=0)
    if ivec:
        vec = 3
    #iplot = pmag.get_flag_arg_from_sys("-P", true=0, false=1)
    isite = pmag.get_flag_arg_from_sys("-sit", true=1, false=0)
    infile = pmag.get_named_arg('-f', 'specimens.txt')
    samp_file = pmag.get_named_arg('-fsa', 'samples.txt')
    site_file = pmag.get_named_arg('-fsi', 'sites.txt')
    #outfile = pmag.get_named_arg("-F", "rmag_results.txt")
    fmt = pmag.get_named_arg("-fmt", "png")
    crd = pmag.get_named_arg("-crd", "s")
    comp, Dir, PDir = 0, [], []
    user = pmag.get_named_arg("-usr", "")
    if '-B' in args:
        iboot, ihext = 0, 1
    save_plots, verbose, interactive = False, True, True
    if '-sav' in args:
        save_plots = True
        verbose = False
        interactive = False
    if '-gtc' in args:
        ind = args.index('-gtc')
        d, i = float(args[ind+1]), float(args[ind+2])
        PDir.append(d)
        PDir.append(i)
    if '-d' in args:
        comp = 1
        ind = args.index('-d')
        vec = int(args[ind+1])-1
        Dir = [float(args[ind+2]), float(args[ind+3])]
    ipmag.aniso_magic_nb(infile, samp_file, site_file, verbose,
                         ipar, ihext, ivec, isite, False, iboot,
                         vec, Dir, PDir, crd, num_bootstraps,
                         dir_path, save_plots=save_plots, interactive=interactive,
                         fmt=fmt)
Exemplo n.º 11
0
def main():
    """
    NAME
        s_magic.py

    DESCRIPTION
        converts .s format data to measurements  format.

    SYNTAX
        s_magic.py [command line options]

    OPTIONS
        -h prints help message and quits
        -DM DATA_MODEL_NUM data model number (default is 3)
        -f SFILE specifies the .s file name
        -sig last column has sigma
        -typ Anisotropy type:  AMS,AARM,ATRM (default is AMS)
        -F FILE specifies the specimens formatted file name
        -usr USER specify username
        -loc location specify location/study name
        -spc NUM : specify number of characters to
              designate a  specimen, default = 0
        -spn SPECNAME, this specimen has the name SPECNAME
        -n first column has specimen name
        -crd [s,g,t], specify coordinate system of data
           s=specimen,g=geographic,t=tilt adjusted, default is 's'
        -ncn NCON: naming convention
       Sample naming convention:
            [1] XXXXY: where XXXX is an arbitrary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            [4-Z] XXXXYYY:  YYY is sample designation with Z characters from site XXX
            [5] sample = site
            [6] sample, site, location info in er_samples.txt -- NOT CURRENTLY SUPPORTED
            [7-Z] [XXX]YYY:  XXX is site designation with Z characters from samples  XXXYYY
            NB: all others you will have to either customize your
                self or e-mail [email protected] for help.


    DEFAULT
        FILE:  specimens.txt

    INPUT
        X11,X22,X33,X12,X23,X13  (.s format file)
        X11,X22,X33,X12,X23,X13,sigma (.s format file with -sig option)
        SID, X11,X22,X33,X12,X23,X13  (.s format file with -n option)

    OUTPUT
        specimens.txt format file

    NOTE
        because .s files do not have specimen names or location information, the output MagIC files
        will have to be changed prior to importing to data base.
    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    data_model_num = pmag.get_named_arg("-DM", 3)
    data_model_num = int(float(data_model_num))
    sfile = pmag.get_named_arg("-f", reqd=True)
    if data_model_num == 2:
       anisfile = pmag.get_named_arg("-F", "rmag_anisotropy.txt")
    else:
        anisfile = pmag.get_named_arg("-F", "specimens.txt")
    location = pmag.get_named_arg("-loc", "unknown")
    user = pmag.get_named_arg("-usr", "")
    sitename = pmag.get_named_arg("unknown", "")
    specnum = pmag.get_named_arg("-spc", 0)
    specnum = -int(specnum)
    dir_path = pmag.get_named_arg("-WD", ".")
    name = pmag.get_flag_arg_from_sys("-n")
    sigma = pmag.get_flag_arg_from_sys("-sig")
    spec = pmag.get_named_arg("-spn", "unknown")
    atype = pmag.get_named_arg("-typ", 'AMS')
    samp_con = pmag.get_named_arg("-ncn", "1")
    #if '-sig' in sys.argv:
    #    sigma = 1
    #if "-n" in sys.argv:
    #    name = 1
    coord_type = pmag.get_named_arg("-crd", 's')
    convert.s_magic(sfile, anisfile, dir_path, atype,
            coord_type, sigma, samp_con, specnum,
            location, spec, sitename, user, data_model_num, name)
Exemplo n.º 12
0
def main():
    """
    NAME
        aniso_magic.py

    DESCRIPTION
        plots anisotropy data with either bootstrap or hext ellipses

    SYNTAX
        aniso_magic.py [-h] [command line options]
    OPTIONS
        -h plots help message and quits
        -usr USER: set the user name
        -f AFILE, specify specimens.txt formatted file for input
        -fsa SAMPFILE, specify samples.txt file (required to plot by site)
        -fsi SITEFILE, specify site file (required to include location information)
        -x Hext [1963] and bootstrap
        -B DON'T do bootstrap, do Hext
        -par Tauxe [1998] parametric bootstrap
        -v plot bootstrap eigenvectors instead of ellipses
        -sit plot by site instead of entire file
        -crd [s,g,t] coordinate system, default is specimen (g=geographic, t=tilt corrected)
        -P don't make any plots - just fill in the specimens, samples, sites tables
        -sav don't make the tables - just save all the plots
        -fmt [svg, jpg, eps] format for output images, pdf default
        -gtc DEC INC  dec,inc of pole to great circle [down(up) in green (cyan)
        -d Vi DEC INC; Vi (1,2,3) to compare to direction DEC INC
        -nb N; specifies the number of bootstraps - default is 1000
    DEFAULTS
       AFILE:  specimens.txt
       plot bootstrap ellipses of Constable & Tauxe [1987]
    NOTES
       minor axis: circles
       major axis: triangles
       principal axis: squares
       directions are plotted on the lower hemisphere
       for bootstrapped eigenvector components: Xs: blue, Ys: red, Zs: black
"""
    args = sys.argv
    if "-h" in args:
        print(main.__doc__)
        sys.exit()
    #version_num = pmag.get_version()
    verbose = pmagplotlib.verbose
    dir_path = pmag.get_named_arg_from_sys("-WD", ".")
    num_bootstraps = pmag.get_named_arg_from_sys("-nb", 1000)
    #user = pmag.get_named_arg_from_sys("-usr", "")
    ipar = pmag.get_flag_arg_from_sys("-par", true=1, false=0)
    ihext = pmag.get_flag_arg_from_sys("-x", true=1, false=0)
    ivec = pmag.get_flag_arg_from_sys("-v", true=1, false=0)
    iplot = pmag.get_flag_arg_from_sys("-P", true=0, false=1)
    isite = pmag.get_flag_arg_from_sys("-sit", true=1, false=0)
    iboot, vec = 1, 0
    infile = pmag.get_named_arg_from_sys('-f', 'specimens.txt')
    samp_file = pmag.get_named_arg_from_sys('-fsa', 'samples.txt')
    site_file = pmag.get_named_arg_from_sys('-fsi', 'sites.txt')
    #outfile = pmag.get_named_arg_from_sys("-F", "rmag_results.txt")
    fmt = pmag.get_named_arg_from_sys("-fmt", "pdf")
    hpars, bpars = [], []
    CS, crd = -1, 's'
    ResRecs = []
    comp, Dir, PDir = 0, [], []
    if '-B' in args:
        iboot, ihext = 0, 1
    if '-crd' in sys.argv:
        ind = sys.argv.index('-crd')
        crd = sys.argv[ind + 1]
        if crd == 'g':
            CS = 0
        if crd == 't':
            CS = 100
    if '-sav' in args:
        plots = 1
        verbose = 0
    else:
        plots = 0
    if '-gtc' in args:
        ind = args.index('-gtc')
        d, i = float(args[ind + 1]), float(args[ind + 2])
        PDir.append(d)
        PDir.append(i)
    if '-d' in args:
        comp = 1
        ind = args.index('-d')
        vec = int(args[ind + 1]) - 1
        Dir = [float(args[ind + 2]), float(args[ind + 3])]

    #
    # set up plots
    #
    ANIS = {}
    initcdf, inittcdf = 0, 0
    ANIS['data'], ANIS['conf'] = 1, 2
    if iboot == 1:
        ANIS['tcdf'] = 3
        if iplot == 1:
            inittcdf = 1
            pmagplotlib.plot_init(ANIS['tcdf'], 5, 5)
        if comp == 1 and iplot == 1:
            initcdf = 1
            ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6
            pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5)
            pmagplotlib.plot_init(ANIS['vycdf'], 5, 5)
            pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5)
    if iplot == 1:
        pmagplotlib.plot_init(ANIS['conf'], 5, 5)
        pmagplotlib.plot_init(ANIS['data'], 5, 5)
    # read in the data
    fnames = {'specimens': infile, 'samples': samp_file, 'sites': site_file}
    con = nb.Contribution(dir_path,
                          read_tables=['specimens', 'samples', 'sites'],
                          custom_filenames=fnames)
    con.propagate_location_to_specimens()
    spec_container = con.tables['specimens']
    # get only anisotropy records
    spec_df = spec_container.get_records_for_code('AE-', strict_match=False)
    if 'aniso_tilt_correction' not in spec_df.columns:
        spec_df['aniso_tilt_correction'] = None
    orlist = spec_df['aniso_tilt_correction'].dropna().unique()
    if CS not in orlist:
        if len(orlist) > 0:
            CS = orlist[0]
        else:
            CS = -1
        if CS == -1:
            crd = 's'
        if CS == 0:
            crd = 'g'
        if CS == 100:
            crd = 't'
        if verbose:
            print("desired coordinate system not available, using available: ",
                  crd)
    if isite == 1:
        sitelist = spec_df['site'].unique()
        sitelist.sort()
        plt = len(sitelist)
    else:
        plt = 1
    k = 0
    while k < plt:
        site = ""
        loc_name = ""
        sdata, Ss = [], []  # list of S format data
        if isite == 0:
            sdata = spec_df
            if 'location' in sdata.columns:
                loc_name = ':'.join(sdata['location'].unique())
        else:
            site = sitelist[k]
            sdata = spec_df[spec_df['site'] == site]
            if 'location' in sdata.columns:
                loc_name = sdata['location'][0]
        csrecs = sdata[sdata['aniso_tilt_correction'] == CS]
        #anitypes = csrecs['aniso_type'].unique()
        for name in ['citations', 'location', 'site', 'sample']:
            if name not in csrecs:
                csrecs[name] = ""
        Locs = csrecs['location'].unique()
        #Sites = csrecs['site'].unique()
        #Samples = csrecs['sample'].unique()
        #Specimens = csrecs['specimen'].unique()
        #Cits = csrecs['citations'].unique()
        for ind, rec in csrecs.iterrows():
            s = [float(i.strip()) for i in rec['aniso_s'].split(':')]
            if s[0] <= 1.0:
                Ss.append(s)  # protect against crap
            # tau,Vdirs=pmag.doseigs(s)
            # do we need fpars somewhere???
            # fpars = pmag.dohext(int(rec["aniso_s_n_measurements"]) -6, float(rec["aniso_s_sigma"]), s)
            # fill in ResRecs (ignoring this for now, grab it from aniso_magic if needed)
        if len(Ss) > 1:
            if pmagplotlib.isServer:  # use server plot naming convention
                title = "LO:_" + loc_name + '_SI:_' + site + '_SA:__SP:__CO:_' + crd
            else:  # use more readable plot naming convention
                title = "{}_{}_{}".format(loc_name, site, crd)
            bpars, hpars = pmagplotlib.plotANIS(ANIS, Ss, iboot, ihext, ivec,
                                                ipar, title, iplot, comp, vec,
                                                Dir, num_bootstraps)
            if len(PDir) > 0:
                pmagplotlib.plotC(ANIS['data'], PDir, 90., 'g')
                pmagplotlib.plotC(ANIS['conf'], PDir, 90., 'g')
            if verbose and plots == 0:
                pmagplotlib.drawFIGS(ANIS)
            if plots == 1:
                save(ANIS, fmt, title)

            if hpars != [] and ihext == 1:
                HextRec = {}
                #for key in ResRec.keys():HextRec[key]=ResRec[key]   # copy over stuff
                HextRec["anisotropy_v1_dec"] = '%7.1f' % (hpars["v1_dec"])
                HextRec["anisotropy_v2_dec"] = '%7.1f' % (hpars["v2_dec"])
                HextRec["anisotropy_v3_dec"] = '%7.1f' % (hpars["v3_dec"])
                HextRec["anisotropy_v1_inc"] = '%7.1f' % (hpars["v1_inc"])
                HextRec["anisotropy_v2_inc"] = '%7.1f' % (hpars["v2_inc"])
                HextRec["anisotropy_v3_inc"] = '%7.1f' % (hpars["v3_inc"])
                HextRec["anisotropy_t1"] = '%10.8f' % (hpars["t1"])
                HextRec["anisotropy_t2"] = '%10.8f' % (hpars["t2"])
                HextRec["anisotropy_t3"] = '%10.8f' % (hpars["t3"])
                HextRec["anisotropy_hext_F"] = '%7.1f ' % (hpars["F"])
                HextRec["anisotropy_hext_F12"] = '%7.1f ' % (hpars["F12"])
                HextRec["anisotropy_hext_F23"] = '%7.1f ' % (hpars["F23"])
                HextRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % (
                    hpars["e12"])
                HextRec["anisotropy_v1_eta_dec"] = '%7.1f ' % (hpars["v2_dec"])
                HextRec["anisotropy_v1_eta_inc"] = '%7.1f ' % (hpars["v2_inc"])
                HextRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % (
                    hpars["e13"])
                HextRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % (
                    hpars["v3_dec"])
                HextRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % (
                    hpars["v3_inc"])
                HextRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % (
                    hpars["e12"])
                HextRec["anisotropy_v2_eta_dec"] = '%7.1f ' % (hpars["v1_dec"])
                HextRec["anisotropy_v2_eta_inc"] = '%7.1f ' % (hpars["v1_inc"])
                HextRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % (
                    hpars["e23"])
                HextRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % (
                    hpars["v3_dec"])
                HextRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % (
                    hpars["v3_inc"])
                HextRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % (
                    hpars["e12"])
                HextRec["anisotropy_v3_eta_dec"] = '%7.1f ' % (hpars["v1_dec"])
                HextRec["anisotropy_v3_eta_inc"] = '%7.1f ' % (hpars["v1_inc"])
                HextRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % (
                    hpars["e23"])
                HextRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % (
                    hpars["v2_dec"])
                HextRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % (
                    hpars["v2_inc"])
                HextRec["magic_method_codes"] = 'LP-AN:AE-H'
                if verbose:
                    print("Hext Statistics: ")
                    print(
                        " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I"
                    )
                    print(HextRec["anisotropy_t1"],
                          HextRec["anisotropy_v1_dec"],
                          end=' ')
                    print(HextRec["anisotropy_v1_inc"],
                          HextRec["anisotropy_v1_eta_semi_angle"],
                          end=' ')
                    print(HextRec["anisotropy_v1_eta_dec"],
                          HextRec["anisotropy_v1_eta_inc"],
                          end=' ')
                    print(HextRec["anisotropy_v1_zeta_semi_angle"],
                          HextRec["anisotropy_v1_zeta_dec"],
                          end=' ')
                    print(HextRec["anisotropy_v1_zeta_inc"])
                    #
                    print(HextRec["anisotropy_t2"],
                          HextRec["anisotropy_v2_dec"],
                          end=' ')
                    print(HextRec["anisotropy_v2_inc"],
                          HextRec["anisotropy_v2_eta_semi_angle"],
                          end=' ')
                    print(HextRec["anisotropy_v2_eta_dec"],
                          HextRec["anisotropy_v2_eta_inc"],
                          end=' ')
                    print(HextRec["anisotropy_v2_zeta_semi_angle"],
                          HextRec["anisotropy_v2_zeta_dec"],
                          end=' ')
                    print(HextRec["anisotropy_v2_zeta_inc"])
                    #
                    print(HextRec["anisotropy_t3"],
                          HextRec["anisotropy_v3_dec"],
                          end=' ')
                    print(HextRec["anisotropy_v3_inc"],
                          HextRec["anisotropy_v3_eta_semi_angle"],
                          end=' ')
                    print(HextRec["anisotropy_v3_eta_dec"],
                          HextRec["anisotropy_v3_eta_inc"],
                          end=' ')
                    print(HextRec["anisotropy_v3_zeta_semi_angle"],
                          HextRec["anisotropy_v3_zeta_dec"],
                          end=' ')
                    print(HextRec["anisotropy_v3_zeta_inc"])
                #HextRec['magic_software_packages']=version_num
                #ResRecs.append(HextRec)
            if bpars != []:
                BootRec = {}
                #for key in ResRec.keys():BootRec[key]=ResRec[key]   # copy over stuff
                BootRec["anisotropy_v1_dec"] = '%7.1f' % (bpars["v1_dec"])
                BootRec["anisotropy_v2_dec"] = '%7.1f' % (bpars["v2_dec"])
                BootRec["anisotropy_v3_dec"] = '%7.1f' % (bpars["v3_dec"])
                BootRec["anisotropy_v1_inc"] = '%7.1f' % (bpars["v1_inc"])
                BootRec["anisotropy_v2_inc"] = '%7.1f' % (bpars["v2_inc"])
                BootRec["anisotropy_v3_inc"] = '%7.1f' % (bpars["v3_inc"])
                BootRec["anisotropy_t1"] = '%10.8f' % (bpars["t1"])
                BootRec["anisotropy_t2"] = '%10.8f' % (bpars["t2"])
                BootRec["anisotropy_t3"] = '%10.8f' % (bpars["t3"])
                BootRec["anisotropy_v1_eta_inc"] = '%7.1f ' % (
                    bpars["v1_eta_inc"])
                BootRec["anisotropy_v1_eta_dec"] = '%7.1f ' % (
                    bpars["v1_eta_dec"])
                BootRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % (
                    bpars["v1_eta"])
                BootRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % (
                    bpars["v1_zeta_inc"])
                BootRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % (
                    bpars["v1_zeta_dec"])
                BootRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % (
                    bpars["v1_zeta"])
                BootRec["anisotropy_v2_eta_inc"] = '%7.1f ' % (
                    bpars["v2_eta_inc"])
                BootRec["anisotropy_v2_eta_dec"] = '%7.1f ' % (
                    bpars["v2_eta_dec"])
                BootRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % (
                    bpars["v2_eta"])
                BootRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % (
                    bpars["v2_zeta_inc"])
                BootRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % (
                    bpars["v2_zeta_dec"])
                BootRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % (
                    bpars["v2_zeta"])
                BootRec["anisotropy_v3_eta_inc"] = '%7.1f ' % (
                    bpars["v3_eta_inc"])
                BootRec["anisotropy_v3_eta_dec"] = '%7.1f ' % (
                    bpars["v3_eta_dec"])
                BootRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % (
                    bpars["v3_eta"])
                BootRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % (
                    bpars["v3_zeta_inc"])
                BootRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % (
                    bpars["v3_zeta_dec"])
                BootRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % (
                    bpars["v3_zeta"])
                BootRec["anisotropy_hext_F"] = ''
                BootRec["anisotropy_hext_F12"] = ''
                BootRec["anisotropy_hext_F23"] = ''
                BootRec[
                    "magic_method_codes"] = 'LP-AN:AE-H:AE-BS'  # regular bootstrap
                if ipar == 1:
                    BootRec[
                        "magic_method_codes"] = 'LP-AN:AE-H:AE-BS-P'  # parametric bootstrap
                if verbose:
                    print("Boostrap Statistics: ")
                    print(
                        " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I"
                    )
                    print(BootRec["anisotropy_t1"],
                          BootRec["anisotropy_v1_dec"],
                          end=' ')
                    print(BootRec["anisotropy_v1_inc"],
                          BootRec["anisotropy_v1_eta_semi_angle"],
                          end=' ')
                    print(BootRec["anisotropy_v1_eta_dec"],
                          BootRec["anisotropy_v1_eta_inc"],
                          end=' ')
                    print(BootRec["anisotropy_v1_zeta_semi_angle"],
                          BootRec["anisotropy_v1_zeta_dec"],
                          end=' ')
                    print(BootRec["anisotropy_v1_zeta_inc"])
                    #
                    print(BootRec["anisotropy_t2"],
                          BootRec["anisotropy_v2_dec"],
                          BootRec["anisotropy_v2_inc"],
                          end=' ')
                    print(BootRec["anisotropy_v2_eta_semi_angle"],
                          BootRec["anisotropy_v2_eta_dec"],
                          end=' ')
                    print(BootRec["anisotropy_v2_eta_inc"],
                          BootRec["anisotropy_v2_zeta_semi_angle"],
                          end=' ')
                    print(BootRec["anisotropy_v2_zeta_dec"],
                          BootRec["anisotropy_v2_zeta_inc"])
                    #
                    print(BootRec["anisotropy_t3"],
                          BootRec["anisotropy_v3_dec"],
                          BootRec["anisotropy_v3_inc"],
                          end=' ')
                    print(BootRec["anisotropy_v3_eta_semi_angle"],
                          BootRec["anisotropy_v3_eta_dec"],
                          end=' ')
                    print(BootRec["anisotropy_v3_eta_inc"],
                          BootRec["anisotropy_v3_zeta_semi_angle"],
                          end=' ')
                    print(BootRec["anisotropy_v3_zeta_dec"],
                          BootRec["anisotropy_v3_zeta_inc"])
                #BootRec['magic_software_packages'] = version_num
                ResRecs.append(BootRec)
            k += 1
            goon = 1
            while goon == 1 and iplot == 1 and verbose:
                if iboot == 1:
                    print("compare with [d]irection ")
                print(
                    " plot [g]reat circle,  change [c]oord. system, change [e]llipse calculation,  s[a]ve plots, [q]uit "
                )
                if isite == 1:
                    print("  [p]revious, [s]ite, [q]uit, <return> for next ")
                ans = input("")
                if ans == "q":
                    sys.exit()
                if ans == "e":
                    iboot, ipar, ihext, ivec = 1, 0, 0, 0
                    e = input("Do Hext Statistics  1/[0]: ")
                    if e == "1":
                        ihext = 1
                    e = input("Suppress bootstrap 1/[0]: ")
                    if e == "1":
                        iboot = 0
                    if iboot == 1:
                        e = input("Parametric bootstrap 1/[0]: ")
                        if e == "1":
                            ipar = 1
                        e = input("Plot bootstrap eigenvectors:  1/[0]: ")
                        if e == "1":
                            ivec = 1
                        if iplot == 1:
                            if inittcdf == 0:
                                ANIS['tcdf'] = 3
                                pmagplotlib.plot_init(ANIS['tcdf'], 5, 5)
                                inittcdf = 1
                    bpars, hpars = pmagplotlib.plotANIS(
                        ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp,
                        vec, Dir, num_bootstraps)
                    if verbose and plots == 0:
                        pmagplotlib.drawFIGS(ANIS)
                if ans == "c":
                    print("Current Coordinate system is: ")
                    if CS == -1:
                        print(" Specimen")
                    if CS == 0:
                        print(" Geographic")
                    if CS == 100:
                        print(" Tilt corrected")
                    key = input(
                        " Enter desired coordinate system: [s]pecimen, [g]eographic, [t]ilt corrected "
                    )
                    if key == 's':
                        CS = -1
                    if key == 'g':
                        CS = 0
                    if key == 't':
                        CS = 100
                    if CS not in orlist:
                        if len(orlist) > 0:
                            CS = orlist[0]
                        else:
                            CS = -1
                        if CS == -1:
                            crd = 's'
                        if CS == 0:
                            crd = 'g'
                        if CS == 100:
                            crd = 't'
                        print(
                            "desired coordinate system not available, using available: ",
                            crd)
                    k -= 1
                    goon = 0
                if ans == "":
                    if isite == 1:
                        goon = 0
                    else:
                        print("Good bye ")
                        sys.exit()
                if ans == 'd':
                    if initcdf == 0:
                        initcdf = 1
                        ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6
                        pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5)
                        pmagplotlib.plot_init(ANIS['vycdf'], 5, 5)
                        pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5)
                    Dir, comp = [], 1
                    print("""
                      Input: Vi D I to  compare  eigenvector Vi with direction D/I
                             where Vi=1: principal
                                   Vi=2: major
                                   Vi=3: minor
                                   D= declination of comparison direction
                                   I= inclination of comparison direction""")
                    con = 1
                    while con == 1:
                        try:
                            vdi = input("Vi D I: ").split()
                            vec = int(vdi[0]) - 1
                            Dir = [float(vdi[1]), float(vdi[2])]
                            con = 0
                        except IndexError:
                            print(" Incorrect entry, try again ")
                    bpars, hpars = pmagplotlib.plotANIS(
                        ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp,
                        vec, Dir, num_bootstraps)
                    Dir, comp = [], 0
                if ans == 'g':
                    con, cnt = 1, 0
                    while con == 1:
                        try:
                            print(
                                " Input:  input pole to great circle ( D I) to  plot a great circle:   "
                            )
                            di = input(" D I: ").split()
                            PDir.append(float(di[0]))
                            PDir.append(float(di[1]))
                            con = 0
                        except:
                            cnt += 1
                            if cnt < 10:
                                print(
                                    " enter the dec and inc of the pole on one line "
                                )
                            else:
                                print(
                                    "ummm - you are doing something wrong - i give up"
                                )
                                sys.exit()
                    pmagplotlib.plotC(ANIS['data'], PDir, 90., 'g')
                    pmagplotlib.plotC(ANIS['conf'], PDir, 90., 'g')
                    if verbose and plots == 0:
                        pmagplotlib.drawFIGS(ANIS)
                if ans == "p":
                    k -= 2
                    goon = 0
                if ans == "q":
                    k = plt
                    goon = 0
                if ans == "s":
                    keepon = 1
                    site = input(" print site or part of site desired: ")
                    while keepon == 1:
                        try:
                            k = sitelist.index(site)
                            keepon = 0
                        except:
                            tmplist = []
                            for qq in range(len(sitelist)):
                                if site in sitelist[qq]:
                                    tmplist.append(sitelist[qq])
                            print(site, " not found, but this was: ")
                            print(tmplist)
                            site = input('Select one or try again\n ')
                            k = sitelist.index(site)
                    goon, ans = 0, ""
                if ans == "a":
                    locs = pmag.makelist(Locs)
                    site_name = "_"
                    if isite:
                        site_name = site
                    if pmagplotlib.isServer:  # use server plot naming convention
                        title = "LO:_" + locs + '_SI:_' + site_name + '_SA:__SP:__CO:_' + crd
                    else:  # use more readable plot naming convention
                        title = "{}_{}_{}".format(locs, site_name, crd)
                    save(ANIS, fmt, title)
                    goon = 0
        else:
            if verbose:
                print('skipping plot - not enough data points')
            k += 1
    #   put rmag_results stuff here
    #if len(ResRecs)>0:
    #    ResOut,keylist=pmag.fillkeys(ResRecs)
    #    pmag.magic_write(outfile,ResOut,'rmag_results')
    if verbose:
        print(" Good bye ")
Exemplo n.º 13
0
def main():
    """
    NAME
        vgpmap_magic.py

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

    SYNTAX
        vgpmap_magic.py [command line options]

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

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

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

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

    site_container = con.tables['sites']
    site_df = site_container.df
    # use individual results
    site_df = site_df[site_df['result_type'] == 'i']
    # use records with vgp_lat and vgp_lon
    cond1, cond2 = site_df['vgp_lat'].notnull(), site_df['vgp_lon'].notnull()
    Results = site_df[cond1 & cond2]
    # use tilt correction
    if coord and 'dir_tilt_correction' in Results.columns:
        Results = Results[Results['dir_tilt_correction'] == coord]
    # get location name and average ages
    location = ":".join(Results['location'].unique())
    if 'average_age' in Results.columns and ages == 1:
        dates = Results['average_age'].unique()

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

        ppars = []
        ppars.append(lon)
        ppars.append(lat)
        ell1, ell2 = "", ""
        if 'vgp_dm' in list(row.keys()) and row['vgp_dm']:
            ell1 = float(row['vgp_dm'])
        if 'vgp_dp' in list(row.keys()) and row['vgp_dp']:
            ell2 = float(row['vgp_dp'])
        if 'vgp_alpha95' in list(row.keys()) and row['vgp_alpha95'].notnull():
            ell1, ell2 = float(row['vgp_alpha95']), float(row['vgp_alpha95'])
        if ell1 and ell2:
            ppars = []
            ppars.append(lons[-1])
            ppars.append(lats[-1])
            ppars.append(ell1)
            ppars.append(lons[-1])
            isign = old_div(abs(lats[-1]), lats[-1])
            ppars.append(lats[-1] - isign * 90.)
            ppars.append(ell2)
            ppars.append(lons[-1] + 90.)
            ppars.append(0.)
            Pars.append(ppars)

    location = location.strip(':')
    Opts = {
        'latmin': -90,
        'latmax': 90,
        'lonmin': 0.,
        'lonmax': 360.,
        'lat_0': lat_0,
        'lon_0': lon_0,
        'proj': proj,
        'sym': 'bs',
        'symsize': 3,
        'pltgrid': 0,
        'res': res,
        'boundinglat': 0.
    }
    Opts['details'] = {
        'coasts': 1,
        'rivers': 0,
        'states': 0,
        'countries': 0,
        'ocean': 1,
        'fancy': fancy
    }
    # make the base map with a blue triangle at the pole
    pmagplotlib.plotMAP(FIG['map'], [90.], [0.], Opts)
    Opts['pltgrid'] = -1
    Opts['sym'] = sym
    Opts['symsize'] = size
    if len(dates) > 0:
        Opts['names'] = dates
    if len(lats) > 0:
        # add the lats and lons of the poles
        pmagplotlib.plotMAP(FIG['map'], lats, lons, Opts)
    Opts['names'] = []
    if len(rlats) > 0:
        Opts['sym'] = rsym
        Opts['symsize'] = rsize
        # add the lats and lons of the poles
        pmagplotlib.plotMAP(FIG['map'], rlats, rlons, Opts)
    if plot == 0:
        pmagplotlib.drawFIGS(FIG)
    if ell == 1:  # add ellipses if desired.
        Opts['details'] = {
            'coasts': 0,
            'rivers': 0,
            'states': 0,
            'countries': 0,
            'ocean': 0,
            'fancy': fancy
        }
        Opts['pltgrid'] = -1  # turn off meridian replotting
        Opts['symsize'] = 2
        Opts['sym'] = 'g-'
        for ppars in Pars:
            if ppars[2] != 0:
                PTS = pmagplotlib.plotELL(FIG['map'], ppars, 'g.', 0, 0)
                elats, elons = [], []
                for pt in PTS:
                    elons.append(pt[0])
                    elats.append(pt[1])
                # make the base map with a blue triangle at the pole
                pmagplotlib.plotMAP(FIG['map'], elats, elons, Opts)
                if plot == 0:
                    pmagplotlib.drawFIGS(FIG)
    files = {}
    for key in list(FIG.keys()):
        if pmagplotlib.isServer:  # use server plot naming convention
            files[key] = 'LO:_' + location + '_VGP_map.' + fmt
        else:  # use more readable naming convention
            files[key] = '{}_VGP_map.{}'.format(location, fmt)

    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['eq'] = 'LO:_' + location + '_VGP_map'
        FIG = pmagplotlib.addBorders(FIG, titles, black, purple)
        pmagplotlib.saveP(FIG, files)
    elif plot == 0:
        pmagplotlib.drawFIGS(FIG)
        ans = input(" S[a]ve to save plot, Return to quit:  ")
        if ans == "a":
            pmagplotlib.saveP(FIG, files)
        else:
            print("Good bye")
            sys.exit()
    else:
        pmagplotlib.saveP(FIG, files)
Exemplo n.º 14
0
def main():
    """
    NAME
        aniso_magic.py

    DESCRIPTION
        plots anisotropy data with either bootstrap or hext ellipses

    SYNTAX
        aniso_magic.py [-h] [command line options]
    OPTIONS
        -h plots help message and quits
        -usr USER: set the user name
        -f AFILE, specify specimens.txt formatted file for input
        -fsa SAMPFILE, specify samples.txt file (required to plot by site)
        -fsi SITEFILE, specify site file (required to include location information)
        -x Hext [1963] and bootstrap
        -B DON'T do bootstrap, do Hext
        -par Tauxe [1998] parametric bootstrap
        -v plot bootstrap eigenvectors instead of ellipses
        -sit plot by site instead of entire file
        -crd [s,g,t] coordinate system, default is specimen (g=geographic, t=tilt corrected)
        -P don't make any plots - just fill in the specimens, samples, sites tables
        -sav don't make the tables - just save all the plots
        -fmt [svg, jpg, eps] format for output images, pdf default
        -gtc DEC INC  dec,inc of pole to great circle [down(up) in green (cyan)
        -d Vi DEC INC; Vi (1,2,3) to compare to direction DEC INC
        -nb N; specifies the number of bootstraps - default is 1000
    DEFAULTS
       AFILE:  specimens.txt
       plot bootstrap ellipses of Constable & Tauxe [1987]
    NOTES
       minor axis: circles
       major axis: triangles
       principal axis: squares
       directions are plotted on the lower hemisphere
       for bootstrapped eigenvector components: Xs: blue, Ys: red, Zs: black
"""
    args = sys.argv
    if "-h" in args:
        print main.__doc__
        sys.exit()
    #version_num = pmag.get_version()
    verbose = pmagplotlib.verbose
    dir_path = pmag.get_named_arg_from_sys("-WD", ".")
    num_bootstraps = pmag.get_named_arg_from_sys("-nb", 1000)
    #user = pmag.get_named_arg_from_sys("-usr", "")
    ipar = pmag.get_flag_arg_from_sys("-par", true=1, false=0)
    ihext = pmag.get_flag_arg_from_sys("-x", true=1, false=0)
    ivec = pmag.get_flag_arg_from_sys("-v", true=1, false=0)
    iplot = pmag.get_flag_arg_from_sys("-P", true=0, false=1)
    isite = pmag.get_flag_arg_from_sys("-sit", true=1, false=0)
    iboot, vec = 1, 0
    infile = pmag.get_named_arg_from_sys('-f', 'specimens.txt')
    samp_file = pmag.get_named_arg_from_sys('-fsa', 'samples.txt')
    site_file = pmag.get_named_arg_from_sys('-fsi', 'sites.txt')
    #outfile = pmag.get_named_arg_from_sys("-F", "rmag_results.txt")
    fmt = pmag.get_named_arg_from_sys("-fmt", "pdf")
    hpars, bpars = [], []
    CS, crd = -1, 's'
    ResRecs = []
    comp, Dir, PDir = 0, [], []
    if '-B' in args:
        iboot, ihext = 0, 1
    if '-crd' in sys.argv:
        ind = sys.argv.index('-crd')
        crd = sys.argv[ind+1]
        if crd == 'g':
            CS = 0
        if crd == 't':
            CS = 100
    if '-sav' in args:
        plots = 1
        verbose = 0
    else:
        plots = 0
    if '-gtc' in args:
        ind = args.index('-gtc')
        d, i = float(args[ind+1]), float(args[ind+2])
        PDir.append(d)
        PDir.append(i)
    if '-d' in args:
        comp = 1
        ind = args.index('-d')
        vec = int(args[ind+1])-1
        Dir = [float(args[ind+2]), float(args[ind+3])]

    #
    # set up plots
    #
    ANIS = {}
    initcdf, inittcdf = 0, 0
    ANIS['data'], ANIS['conf'] = 1, 2
    if iboot == 1:
        ANIS['tcdf'] = 3
        if iplot == 1:
            inittcdf = 1
            pmagplotlib.plot_init(ANIS['tcdf'], 5, 5)
        if comp == 1 and iplot == 1:
            initcdf = 1
            ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6
            pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5)
            pmagplotlib.plot_init(ANIS['vycdf'], 5, 5)
            pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5)
    if iplot == 1:
        pmagplotlib.plot_init(ANIS['conf'], 5, 5)
        pmagplotlib.plot_init(ANIS['data'], 5, 5)
    # read in the data
    fnames = {'specimens': infile, 'samples': samp_file, 'sites': site_file}
    con = nb.Contribution(dir_path, read_tables=['specimens', 'samples', 'sites'],
                          custom_filenames=fnames)
    spec_container = con.tables['specimens']
    spec_df = con.propagate_name_down('location', 'specimens')
    # get only anisotropy records
    spec_df = spec_container.get_records_for_code('AE-', strict_match=False)
    if 'aniso_tilt_correction' not in spec_df.columns:
        spec_df['aniso_tilt_correction'] = None
    orlist = spec_df['aniso_tilt_correction'].dropna().unique()
    if CS not in orlist:
        if len(orlist) > 0:
            CS = orlist[0]
        else:
            CS = -1
        if CS == -1:
            crd = 's'
        if CS == 0:
            crd = 'g'
        if CS == 100:
            crd = 't'
        if verbose:
            print "desired coordinate system not available, using available: ", crd
    if isite == 1:
        sitelist = spec_df['site'].unique()
        sitelist.sort()
        plt = len(sitelist)
    else:
        plt = 1
    k = 0
    while k < plt:
        site = ""
        loc_name = ""
        sdata, Ss = [], [] # list of S format data
        if isite == 0:
            sdata = spec_df
            if 'location' in sdata.columns:
                loc_name = ':'.join(sdata['location'].unique())
        else:
            site = sitelist[k]
            sdata = spec_df[spec_df['site'] == site]
            if 'location' in sdata.columns:
                loc_name = sdata['location'][0]
        csrecs = sdata[sdata['aniso_tilt_correction'] == CS]
        #anitypes = csrecs['aniso_type'].unique()
        for name in ['citations', 'location', 'site', 'sample']:
            if name not in csrecs:
                csrecs[name] = ""
        Locs = csrecs['location'].unique()
        #Sites = csrecs['site'].unique()
        #Samples = csrecs['sample'].unique()
        #Specimens = csrecs['specimen'].unique()
        #Cits = csrecs['citations'].unique()
        for ind, rec in csrecs.iterrows():
            s = [float(i.strip()) for i in rec['aniso_s'].split(':')]
            if s[0] <= 1.0:
                Ss.append(s) # protect against crap
            # tau,Vdirs=pmag.doseigs(s)
            # do we need fpars somewhere???
            # fpars = pmag.dohext(int(rec["aniso_s_n_measurements"]) -6, float(rec["aniso_s_sigma"]), s)
            # fill in ResRecs (ignoring this for now, grab it from aniso_magic if needed)
        if len(Ss) > 1:
            title = "LO:_" + loc_name + '_SI:_' + site + '_SA:__SP:__CO:_' + crd
            bpars, hpars = pmagplotlib.plotANIS(ANIS, Ss, iboot, ihext, ivec, ipar,
                                                title, iplot, comp, vec, Dir, num_bootstraps)
            if len(PDir) > 0:
                pmagplotlib.plotC(ANIS['data'], PDir, 90., 'g')
                pmagplotlib.plotC(ANIS['conf'], PDir, 90., 'g')
            if verbose and plots == 0:
                pmagplotlib.drawFIGS(ANIS)
            if plots == 1:
                save(ANIS,fmt,title)

            if hpars != [] and ihext == 1:
                HextRec = {}
                #for key in ResRec.keys():HextRec[key]=ResRec[key]   # copy over stuff
                HextRec["anisotropy_v1_dec"] = '%7.1f'%(hpars["v1_dec"])
                HextRec["anisotropy_v2_dec"] = '%7.1f'%(hpars["v2_dec"])
                HextRec["anisotropy_v3_dec"] = '%7.1f'%(hpars["v3_dec"])
                HextRec["anisotropy_v1_inc"] = '%7.1f'%(hpars["v1_inc"])
                HextRec["anisotropy_v2_inc"] = '%7.1f'%(hpars["v2_inc"])
                HextRec["anisotropy_v3_inc"] = '%7.1f'%(hpars["v3_inc"])
                HextRec["anisotropy_t1"] = '%10.8f'%(hpars["t1"])
                HextRec["anisotropy_t2"] = '%10.8f'%(hpars["t2"])
                HextRec["anisotropy_t3"] = '%10.8f'%(hpars["t3"])
                HextRec["anisotropy_hext_F"] = '%7.1f '%(hpars["F"])
                HextRec["anisotropy_hext_F12"] = '%7.1f '%(hpars["F12"])
                HextRec["anisotropy_hext_F23"] = '%7.1f '%(hpars["F23"])
                HextRec["anisotropy_v1_eta_semi_angle"] = '%7.1f '%(hpars["e12"])
                HextRec["anisotropy_v1_eta_dec"] = '%7.1f '%(hpars["v2_dec"])
                HextRec["anisotropy_v1_eta_inc"] = '%7.1f '%(hpars["v2_inc"])
                HextRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f '%(hpars["e13"])
                HextRec["anisotropy_v1_zeta_dec"] = '%7.1f '%(hpars["v3_dec"])
                HextRec["anisotropy_v1_zeta_inc"] = '%7.1f '%(hpars["v3_inc"])
                HextRec["anisotropy_v2_eta_semi_angle"] = '%7.1f '%(hpars["e12"])
                HextRec["anisotropy_v2_eta_dec"] = '%7.1f '%(hpars["v1_dec"])
                HextRec["anisotropy_v2_eta_inc"] = '%7.1f '%(hpars["v1_inc"])
                HextRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f '%(hpars["e23"])
                HextRec["anisotropy_v2_zeta_dec"] = '%7.1f '%(hpars["v3_dec"])
                HextRec["anisotropy_v2_zeta_inc"] = '%7.1f '%(hpars["v3_inc"])
                HextRec["anisotropy_v3_eta_semi_angle"] = '%7.1f '%(hpars["e12"])
                HextRec["anisotropy_v3_eta_dec"] = '%7.1f '%(hpars["v1_dec"])
                HextRec["anisotropy_v3_eta_inc"] = '%7.1f '%(hpars["v1_inc"])
                HextRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f '%(hpars["e23"])
                HextRec["anisotropy_v3_zeta_dec"] = '%7.1f '%(hpars["v2_dec"])
                HextRec["anisotropy_v3_zeta_inc"] = '%7.1f '%(hpars["v2_inc"])
                HextRec["magic_method_codes"] = 'LP-AN:AE-H'
                if verbose:
                    print "Hext Statistics: "
                    print " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I"
                    print HextRec["anisotropy_t1"], HextRec["anisotropy_v1_dec"],
                    print HextRec["anisotropy_v1_inc"], HextRec["anisotropy_v1_eta_semi_angle"],
                    print HextRec["anisotropy_v1_eta_dec"], HextRec["anisotropy_v1_eta_inc"],
                    print HextRec["anisotropy_v1_zeta_semi_angle"], HextRec["anisotropy_v1_zeta_dec"],
                    print HextRec["anisotropy_v1_zeta_inc"]
                    #
                    print HextRec["anisotropy_t2"],HextRec["anisotropy_v2_dec"],
                    print HextRec["anisotropy_v2_inc"], HextRec["anisotropy_v2_eta_semi_angle"],
                    print HextRec["anisotropy_v2_eta_dec"], HextRec["anisotropy_v2_eta_inc"],
                    print HextRec["anisotropy_v2_zeta_semi_angle"], HextRec["anisotropy_v2_zeta_dec"],
                    print HextRec["anisotropy_v2_zeta_inc"]
                    #
                    print HextRec["anisotropy_t3"], HextRec["anisotropy_v3_dec"],
                    print HextRec["anisotropy_v3_inc"], HextRec["anisotropy_v3_eta_semi_angle"],
                    print HextRec["anisotropy_v3_eta_dec"], HextRec["anisotropy_v3_eta_inc"],
                    print HextRec["anisotropy_v3_zeta_semi_angle"], HextRec["anisotropy_v3_zeta_dec"],
                    print HextRec["anisotropy_v3_zeta_inc"]
                #HextRec['magic_software_packages']=version_num
                #ResRecs.append(HextRec)
            if bpars != []:
                BootRec = {}
                #for key in ResRec.keys():BootRec[key]=ResRec[key]   # copy over stuff
                BootRec["anisotropy_v1_dec"] = '%7.1f'%(bpars["v1_dec"])
                BootRec["anisotropy_v2_dec"] = '%7.1f'%(bpars["v2_dec"])
                BootRec["anisotropy_v3_dec"] = '%7.1f'%(bpars["v3_dec"])
                BootRec["anisotropy_v1_inc"] = '%7.1f'%(bpars["v1_inc"])
                BootRec["anisotropy_v2_inc"] = '%7.1f'%(bpars["v2_inc"])
                BootRec["anisotropy_v3_inc"] = '%7.1f'%(bpars["v3_inc"])
                BootRec["anisotropy_t1"] = '%10.8f'%(bpars["t1"])
                BootRec["anisotropy_t2"] = '%10.8f'%(bpars["t2"])
                BootRec["anisotropy_t3"] = '%10.8f'%(bpars["t3"])
                BootRec["anisotropy_v1_eta_inc"] = '%7.1f '%(bpars["v1_eta_inc"])
                BootRec["anisotropy_v1_eta_dec"] = '%7.1f '%(bpars["v1_eta_dec"])
                BootRec["anisotropy_v1_eta_semi_angle"] = '%7.1f '%(bpars["v1_eta"])
                BootRec["anisotropy_v1_zeta_inc"] = '%7.1f '%(bpars["v1_zeta_inc"])
                BootRec["anisotropy_v1_zeta_dec"] = '%7.1f '%(bpars["v1_zeta_dec"])
                BootRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f '%(bpars["v1_zeta"])
                BootRec["anisotropy_v2_eta_inc"] = '%7.1f '%(bpars["v2_eta_inc"])
                BootRec["anisotropy_v2_eta_dec"] = '%7.1f '%(bpars["v2_eta_dec"])
                BootRec["anisotropy_v2_eta_semi_angle"] = '%7.1f '%(bpars["v2_eta"])
                BootRec["anisotropy_v2_zeta_inc"] = '%7.1f '%(bpars["v2_zeta_inc"])
                BootRec["anisotropy_v2_zeta_dec"] = '%7.1f '%(bpars["v2_zeta_dec"])
                BootRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f '%(bpars["v2_zeta"])
                BootRec["anisotropy_v3_eta_inc"] = '%7.1f '%(bpars["v3_eta_inc"])
                BootRec["anisotropy_v3_eta_dec"] = '%7.1f '%(bpars["v3_eta_dec"])
                BootRec["anisotropy_v3_eta_semi_angle"] = '%7.1f '%(bpars["v3_eta"])
                BootRec["anisotropy_v3_zeta_inc"] = '%7.1f '%(bpars["v3_zeta_inc"])
                BootRec["anisotropy_v3_zeta_dec"] = '%7.1f '%(bpars["v3_zeta_dec"])
                BootRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f '%(bpars["v3_zeta"])
                BootRec["anisotropy_hext_F"] = ''
                BootRec["anisotropy_hext_F12"] = ''
                BootRec["anisotropy_hext_F23"] = ''
                BootRec["magic_method_codes"] = 'LP-AN:AE-H:AE-BS' # regular bootstrap
                if ipar == 1:
                    BootRec["magic_method_codes"] = 'LP-AN:AE-H:AE-BS-P' # parametric bootstrap
                if verbose:
                    print "Boostrap Statistics: "
                    print " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I"
                    print BootRec["anisotropy_t1"], BootRec["anisotropy_v1_dec"],
                    print BootRec["anisotropy_v1_inc"], BootRec["anisotropy_v1_eta_semi_angle"],
                    print BootRec["anisotropy_v1_eta_dec"], BootRec["anisotropy_v1_eta_inc"],
                    print BootRec["anisotropy_v1_zeta_semi_angle"], BootRec["anisotropy_v1_zeta_dec"],
                    print BootRec["anisotropy_v1_zeta_inc"]
                    #
                    print BootRec["anisotropy_t2"], BootRec["anisotropy_v2_dec"], BootRec["anisotropy_v2_inc"],
                    print BootRec["anisotropy_v2_eta_semi_angle"], BootRec["anisotropy_v2_eta_dec"],
                    print BootRec["anisotropy_v2_eta_inc"], BootRec["anisotropy_v2_zeta_semi_angle"],
                    print BootRec["anisotropy_v2_zeta_dec"], BootRec["anisotropy_v2_zeta_inc"]
                    #
                    print BootRec["anisotropy_t3"], BootRec["anisotropy_v3_dec"], BootRec["anisotropy_v3_inc"],
                    print BootRec["anisotropy_v3_eta_semi_angle"], BootRec["anisotropy_v3_eta_dec"],
                    print BootRec["anisotropy_v3_eta_inc"], BootRec["anisotropy_v3_zeta_semi_angle"],
                    print BootRec["anisotropy_v3_zeta_dec"], BootRec["anisotropy_v3_zeta_inc"]
                #BootRec['magic_software_packages'] = version_num
                ResRecs.append(BootRec)
            k += 1
            goon = 1
            while goon == 1 and iplot == 1 and verbose:
                if iboot == 1:
                    print "compare with [d]irection "
                print " plot [g]reat circle,  change [c]oord. system, change [e]llipse calculation,  s[a]ve plots, [q]uit "
                if isite == 1:
                    print "  [p]revious, [s]ite, [q]uit, <return> for next "
                ans = raw_input("")
                if ans == "q":
                    sys.exit()
                if ans == "e":
                    iboot, ipar, ihext, ivec = 1, 0, 0, 0
                    e = raw_input("Do Hext Statistics  1/[0]: ")
                    if e == "1":
                        ihext = 1
                    e = raw_input("Suppress bootstrap 1/[0]: ")
                    if e == "1":
                        iboot = 0
                    if iboot == 1:
                        e = raw_input("Parametric bootstrap 1/[0]: ")
                        if e == "1":
                            ipar = 1
                        e = raw_input("Plot bootstrap eigenvectors:  1/[0]: ")
                        if e == "1":
                            ivec=1
                        if iplot == 1:
                            if inittcdf == 0:
                                ANIS['tcdf'] = 3
                                pmagplotlib.plot_init(ANIS['tcdf'], 5, 5)
                                inittcdf = 1
                    bpars, hpars = pmagplotlib.plotANIS(ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot,
                                                        comp, vec, Dir, num_bootstraps)
                    if verbose and plots == 0:
                        pmagplotlib.drawFIGS(ANIS)
                if ans == "c":
                    print "Current Coordinate system is: "
                    if CS == -1:
                        print " Specimen"
                    if CS == 0:
                        print " Geographic"
                    if CS == 100:
                        print " Tilt corrected"
                    key = raw_input(" Enter desired coordinate system: [s]pecimen, [g]eographic, [t]ilt corrected ")
                    if key == 's':
                        CS = -1
                    if key == 'g':
                        CS = 0
                    if key == 't':
                        CS = 100
                    if CS not in orlist:
                        if len(orlist) > 0:
                            CS = orlist[0]
                        else:
                            CS = -1
                        if CS == -1:
                            crd = 's'
                        if CS == 0:
                            crd = 'g'
                        if CS == 100:
                            crd = 't'
                        print "desired coordinate system not available, using available: ", crd
                    k -= 1
                    goon = 0
                if ans == "":
                    if isite == 1:
                        goon = 0
                    else:
                        print "Good bye "
                        sys.exit()
                if ans == 'd':
                    if initcdf == 0:
                        initcdf = 1
                        ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6
                        pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5)
                        pmagplotlib.plot_init(ANIS['vycdf'], 5, 5)
                        pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5)
                    Dir, comp = [], 1
                    print """
                      Input: Vi D I to  compare  eigenvector Vi with direction D/I
                             where Vi=1: principal
                                   Vi=2: major
                                   Vi=3: minor
                                   D= declination of comparison direction
                                   I= inclination of comparison direction"""
                    con = 1
                    while con == 1:
                        try:
                            vdi = raw_input("Vi D I: ").split()
                            vec = int(vdi[0])-1
                            Dir = [float(vdi[1]), float(vdi[2])]
                            con = 0
                        except IndexError:
                            print " Incorrect entry, try again "
                    bpars, hpars = pmagplotlib.plotANIS(ANIS, Ss, iboot, ihext, ivec, ipar, title,
                                                        iplot, comp, vec, Dir, num_bootstraps)
                    Dir, comp = [], 0
                if ans == 'g':
                    con, cnt = 1, 0
                    while con == 1:
                        try:
                            print " Input:  input pole to great circle ( D I) to  plot a great circle:   "
                            di = raw_input(" D I: ").split()
                            PDir.append(float(di[0]))
                            PDir.append(float(di[1]))
                            con=0
                        except:
                            cnt += 1
                            if cnt < 10:
                                print " enter the dec and inc of the pole on one line "
                            else:
                                print "ummm - you are doing something wrong - i give up"
                                sys.exit()
                    pmagplotlib.plotC(ANIS['data'], PDir, 90., 'g')
                    pmagplotlib.plotC(ANIS['conf'], PDir, 90., 'g')
                    if verbose and plots == 0:
                        pmagplotlib.drawFIGS(ANIS)
                if ans == "p":
                    k -= 2
                    goon = 0
                if ans == "q":
                    k = plt
                    goon = 0
                if ans == "s":
                    keepon = 1
                    site = raw_input(" print site or part of site desired: ")
                    while keepon == 1:
                        try:
                            k = sitelist.index(site)
                            keepon = 0
                        except:
                            tmplist = []
                            for qq in range(len(sitelist)):
                                if site in sitelist[qq]:
                                    tmplist.append(sitelist[qq])
                            print site, " not found, but this was: "
                            print tmplist
                            site = raw_input('Select one or try again\n ')
                            k = sitelist.index(site)
                    goon, ans = 0, ""
                if ans == "a":
                    locs = pmag.makelist(Locs)
                    site_name = "_"
                    if isite:
                        site_name = site
                    title = "LO:_" + locs + '_SI:_' + site_name + '_SA:__SP:__CO:_' + crd
                    save(ANIS, fmt, title)
                    goon = 0
        else:
            if verbose:
                print 'skipping plot - not enough data points'
            k += 1
    #   put rmag_results stuff here
    #if len(ResRecs)>0:
    #    ResOut,keylist=pmag.fillkeys(ResRecs)
    #    pmag.magic_write(outfile,ResOut,'rmag_results')
    if verbose:
        print " Good bye "
Exemplo n.º 15
0
def main():
    """
    NAME
        vgpmap_magic.py

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

    SYNTAX
        vgpmap_magic.py [command line options]

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

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

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

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

    site_container = con.tables["sites"]
    site_df = site_container.df
    # use individual results
    site_df = site_df[site_df["result_type"] == "i"]
    # use records with vgp_lat and vgp_lon
    cond1, cond2 = site_df["vgp_lat"].notnull(), site_df["vgp_lon"].notnull()
    Results = site_df[cond1 & cond2]
    # use tilt correction
    if coord and "dir_tilt_correction" in Results.columns:
        Results = Results[Results["dir_tilt_correction"] == coord]
    # get location name and average ages
    location = ":".join(Results["location"].unique())
    if "average_age" in Results.columns and ages == 1:
        dates = Results["average_age"].unique()

    # go through rows and extract data
    for ind, row in Results.iterrows():
        lat, lon = float(row["vgp_lat"]), float(row["vgp_lon"])
        if anti == 1:
            lats.append(-lat)
            lon = lon + 180.0
            if lon > 360:
                lon = lon - 360.0
            lons.append(lon)
        elif flip == 0:
            lats.append(lat)
            lons.append(lon)
        elif flip == 1:
            if lat < 0:
                rlats.append(-lat)
                lon = lon + 180.0
                if lon > 360:
                    lon = lon - 360
                rlons.append(lon)
            else:
                lats.append(lat)
                lons.append(lon)

        ppars = []
        ppars.append(lon)
        ppars.append(lat)
        ell1, ell2 = "", ""
        if "vgp_dm" in row.keys() and row["vgp_dm"]:
            ell1 = float(row["vgp_dm"])
        if "vgp_dp" in row.keys() and row["vgp_dp"]:
            ell2 = float(row["vgp_dp"])
        if "vgp_alpha95" in row.keys() and row["vgp_alpha95"].notnull():
            ell1, ell2 = float(row["vgp_alpha95"]), float(row["vgp_alpha95"])
        if ell1 and ell2:
            ppars = []
            ppars.append(lons[-1])
            ppars.append(lats[-1])
            ppars.append(ell1)
            ppars.append(lons[-1])
            isign = abs(lats[-1]) / lats[-1]
            ppars.append(lats[-1] - isign * 90.0)
            ppars.append(ell2)
            ppars.append(lons[-1] + 90.0)
            ppars.append(0.0)
            Pars.append(ppars)

    location = location.strip(":")
    Opts = {
        "latmin": -90,
        "latmax": 90,
        "lonmin": 0.0,
        "lonmax": 360.0,
        "lat_0": lat_0,
        "lon_0": lon_0,
        "proj": proj,
        "sym": "bs",
        "symsize": 3,
        "pltgrid": 0,
        "res": res,
        "boundinglat": 0.0,
    }
    Opts["details"] = {"coasts": 1, "rivers": 0, "states": 0, "countries": 0, "ocean": 1, "fancy": fancy}
    # make the base map with a blue triangle at the pole
    pmagplotlib.plotMAP(FIG["map"], [90.0], [0.0], Opts)
    Opts["pltgrid"] = -1
    Opts["sym"] = sym
    Opts["symsize"] = size
    if len(dates) > 0:
        Opts["names"] = dates
    if len(lats) > 0:
        # add the lats and lons of the poles
        pmagplotlib.plotMAP(FIG["map"], lats, lons, Opts)
    Opts["names"] = []
    if len(rlats) > 0:
        Opts["sym"] = rsym
        Opts["symsize"] = rsize
        # add the lats and lons of the poles
        pmagplotlib.plotMAP(FIG["map"], rlats, rlons, Opts)
    if plot == 0:
        pmagplotlib.drawFIGS(FIG)
    if ell == 1:  # add ellipses if desired.
        Opts["details"] = {"coasts": 0, "rivers": 0, "states": 0, "countries": 0, "ocean": 0, "fancy": fancy}
        Opts["pltgrid"] = -1  # turn off meridian replotting
        Opts["symsize"] = 2
        Opts["sym"] = "g-"
        for ppars in Pars:
            if ppars[2] != 0:
                PTS = pmagplotlib.plotELL(FIG["map"], ppars, "g.", 0, 0)
                elats, elons = [], []
                for pt in PTS:
                    elons.append(pt[0])
                    elats.append(pt[1])
                # make the base map with a blue triangle at the pole
                pmagplotlib.plotMAP(FIG["map"], elats, elons, Opts)
                if plot == 0:
                    pmagplotlib.drawFIGS(FIG)
    files = {}
    for key in FIG.keys():
        files[key] = "LO:_" + location + "_VGP_map." + fmt
    if pmagplotlib.isServer:
        black = "#000000"
        purple = "#800080"
        titles = {}
        titles["eq"] = "LO:_" + location + "_VGP_map"
        FIG = pmagplotlib.addBorders(FIG, titles, black, purple)
        pmagplotlib.saveP(FIG, files)
    elif plot == 0:
        pmagplotlib.drawFIGS(FIG)
        ans = raw_input(" S[a]ve to save plot, Return to quit:  ")
        if ans == "a":
            pmagplotlib.saveP(FIG, files)
        else:
            print "Good bye"
            sys.exit()
    else:
        pmagplotlib.saveP(FIG, files)
Exemplo n.º 16
0
def main():
    """
    NAME
        polemap_magic.py

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

    SYNTAX
        polemap_magic.py [command line options]

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

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

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

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

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

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

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

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

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

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

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

    titles = {}
    files = {}

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

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

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

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

    return True, files
Exemplo n.º 17
0
def main():
    """
    NAME
        dmag_magic.py

    DESCRIPTION
       plots intensity decay curves for demagnetization experiments

    SYNTAX
        dmag_magic -h [command line options]

    INPUT
       takes magic formatted magic_measurements.txt files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is: magic_measurements.txt
        -obj OBJ: specify  object  [loc, sit, sam, spc] for plot,
               default is by location
        -LT [AF,T,M]: specify lab treatment type, default AF
        -XLP [PI]: exclude specific  lab protocols,
               (for example, method codes like LP-PI)
        -N do not normalize by NRM magnetization
        -sav save plots silently and quit
        -fmt [svg,jpg,png,pdf] set figure format [default is svg]
    NOTE
        loc: location (study); sit: site; sam: sample; spc: specimen
    """
    if '-h' in sys.argv:
        print main.__doc__
        sys.exit()
    # initialize variables from command line + defaults
    FIG = {}  # plot dictionary
    FIG['demag'] = 1  # demag is figure 1
    in_file = pmag.get_named_arg_from_sys("-f", default_val="measurements.txt")
    plot_by = pmag.get_named_arg_from_sys("-obj", default_val="loc")
    name_dict = {'loc': 'location', 'sit': 'site',
                 'sam': 'sample', 'spc': 'specimen'}
    plot_key = name_dict[plot_by]
    LT = "LT-" + pmag.get_named_arg_from_sys("-LT", "AF") + "-Z"
    if LT == "LT-T-Z":
        units, dmag_key = 'K', 'treat_temp'
    elif LT == "LT-AF-Z":
        units, dmag_key = 'T', 'treat_ac_field'
    elif LT == 'LT-M-Z':
        units, dmag_key = 'J', 'treat_mw_energy'
    else:
        units = 'U'
    no_norm = pmag.get_flag_arg_from_sys("-N")
    norm = 0 if no_norm else 1
    no_plot = pmag.get_flag_arg_from_sys("-sav")
    plot = 0 if no_plot else 1
    fmt = pmag.get_named_arg_from_sys("-fmt", "svg")
    XLP = pmag.get_named_arg_from_sys("-XLP", "")
    dir_path = pmag.get_named_arg_from_sys("-WD", os.getcwd())
    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")

    # create contribution and add required headers
    fnames = {"specimens": spec_file, "samples": samp_file, 'sites': site_file}
    contribution = nb.Contribution(dir_path, single_file=in_file,
                                   custom_filenames=fnames)
    file_type = contribution.tables.keys()[0]
    print len(contribution.tables['measurements'].df), ' records read from ', in_file
    # add plot_key into measurements table
    if plot_key not in contribution.tables['measurements'].df.columns:
        contribution.propagate_name_down(plot_key, 'measurements')
    data_container = contribution.tables[file_type]
    # pare down to only records with useful data
    # grab records that have the requested code
    data_slice = data_container.get_records_for_code(LT)
    # and don't have the offending code
    data = data_container.get_records_for_code(XLP, incl=False, use_slice=True,
                                               sli=data_slice, strict_match=False)

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

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

            if not plot:
                files = {}
                for key in FIG.keys():
                    files[key] = title + '_' + LT + '.' + fmt
                pmagplotlib.saveP(FIG, files)
                #sys.exit()
            else:
                pmagplotlib.drawFIGS(FIG)
                prompt = " S[a]ve to save plot, [q]uit,  Return to continue:  "
                ans = raw_input(prompt)
                if ans == 'q':
                    sys.exit()
                if ans == "a":
                    files = {}
                    for key in FIG.keys():
                        files[key] = title + '_' + LT + '.' + fmt
                    pmagplotlib.saveP(FIG, files)
            pmagplotlib.clearFIG(FIG['demag'])
Exemplo n.º 18
0
def main():
    """
    NAME
        polemap_magic.py

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

    SYNTAX
        polemap_magic.py [command line options]

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

    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", ".")
    # do_plot: default is 0, if -sav in sys.argv should be 1
    save_plots = pmag.get_flag_arg_from_sys("-sav", true=1, false=0)
    interactive = True
    if save_plots:
        interactive = False
    fmt = pmag.get_named_arg("-fmt", "pdf")
    res = pmag.get_named_arg("-res", "c")
    proj = pmag.get_named_arg("-prj", "ortho")
    anti = pmag.get_flag_arg_from_sys("-S", true=1, false=0)
    fancy = pmag.get_flag_arg_from_sys("-etp", true=1, false=0)
    ell = pmag.get_flag_arg_from_sys("-ell", true=1, false=0)
    ages = pmag.get_flag_arg_from_sys("-age", true=1, false=0)
    if '-rev' in sys.argv:
        flip = True
        ind = sys.argv.index('-rev')
        try:
            rsym = (sys.argv[ind + 1])
            rsize = int(sys.argv[ind + 2])
        except (IndexError, ValueError, KeyError):
            flip, rsym, rsize = True, "g^", 40
    else:
        flip, rsym, rsize = False, "g^", 40
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym = (sys.argv[ind + 1])
        size = int(sys.argv[ind + 2])
    else:
        sym, size = 'ro', 40
    if '-eye' in sys.argv:
        ind = sys.argv.index('-eye')
        lat_0 = float(sys.argv[ind + 1])
        lon_0 = float(sys.argv[ind + 2])
    else:
        lat_0, lon_0 = 90., 0.
    crd = pmag.get_named_arg("-crd", "")
    loc_file = pmag.get_named_arg("-f", "locations.txt")
    ipmag.polemap_magic(loc_file, dir_path, interactive, crd,
                        sym, size, rsym, rsize, fmt, res,
                        proj, flip, anti, fancy, ell, ages, lat_0, lon_0,
                        save_plots)
Exemplo n.º 19
0
def main():
    """
    NAME
        vgpmap_magic.py

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

    SYNTAX
        vgpmap_magic.py [command line options]

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

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

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

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

    site_container = con.tables['sites']
    site_df = site_container.df
    # use records with vgp_lat and vgp_lon
    if 'vgp_lat' in site_df.columns and 'vgp_lon' in site_df.columns:
        cond1, cond2 = site_df['vgp_lat'].notnull(), site_df['vgp_lon'].notnull()
    else:
        print ('nothing to plot')
        sys.exit()
    Results = site_df[cond1 & cond2]
    # use tilt correction
    if coord and 'dir_tilt_correction' in Results.columns:
        Results = Results[Results['dir_tilt_correction'] == coord]
    # get location name and average ages
    locs = Results['location'].unique()
    if len(locs):
        location = ":".join(Results['location'].unique())
    else:
        location = ""
    if 'age' in Results.columns and ages == 1:
        dates = Results['age'].unique()

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

        ppars = []
        ppars.append(lon)
        ppars.append(lat)
        ell1, ell2 = "", ""
        if 'vgp_dm' in list(row.keys()) and row['vgp_dm']:
            ell1 = float(row['vgp_dm'])
        if 'vgp_dp' in list(row.keys()) and row['vgp_dp']:
            ell2 = float(row['vgp_dp'])
        if 'vgp_alpha95' in list(row.keys()) and (row['vgp_alpha95'] or row['vgp_alpha95'] == 0):
            ell1, ell2 = float(row['vgp_alpha95']), float(row['vgp_alpha95'])
        if ell1 and ell2:
            ppars = []
            ppars.append(lons[-1])
            ppars.append(lats[-1])
            ppars.append(ell1)
            ppars.append(lons[-1])
            try:
                isign = abs(lats[-1]) / lats[-1]
            except ZeroDivisionError:
                isign = 1
            ppars.append(lats[-1] - isign * 90.)
            ppars.append(ell2)
            ppars.append(lons[-1] + 90.)
            ppars.append(0.)
            Pars.append(ppars)

    location = location.strip(':')
    Opts = {'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360.,
            'lat_0': lat_0, 'lon_0': lon_0, 'proj': proj, 'sym': 'bs',
            'symsize': 3, 'pltgrid': 0, 'res': res, 'boundinglat': 0.}
    Opts['details'] = {'coasts': 1, 'rivers': 0, 'states': 0,
                       'countries': 0, 'ocean': 1, 'fancy': fancy}
    # make the base map with a blue triangle at the pole
    pmagplotlib.plot_map(FIG['map'], [90.], [0.], Opts)
    Opts['pltgrid'] = -1
    Opts['sym'] = sym
    Opts['symsize'] = size
    if len(dates) > 0:
        Opts['names'] = dates
    if len(lats) > 0:
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], lats, lons, Opts)
    Opts['names'] = []
    if len(rlats) > 0:
        Opts['sym'] = rsym
        Opts['symsize'] = rsize
        # add the lats and lons of the poles
        pmagplotlib.plot_map(FIG['map'], rlats, rlons, Opts)
    if plot == 0 and not set_env.IS_WIN:
        pmagplotlib.draw_figs(FIG)
    if ell == 1:  # add ellipses if desired.
        Opts['details'] = {'coasts': 0, 'rivers': 0, 'states': 0,
                           'countries': 0, 'ocean': 0, 'fancy': fancy}
        Opts['pltgrid'] = -1  # turn off meridian replotting
        Opts['symsize'] = 2
        Opts['sym'] = 'g-'
        for ppars in Pars:
            if ppars[2] != 0:
                PTS = pmagplotlib.plot_ell(FIG['map'], ppars, 'g.', 0, 0)
                elats, elons = [], []
                for pt in PTS:
                    elons.append(pt[0])
                    elats.append(pt[1])
                # make the base map with a blue triangle at the pole
                pmagplotlib.plot_map(FIG['map'], elats, elons, Opts)
                if plot == 0 and not set_env.IS_WIN:
                    pmagplotlib.draw_figs(FIG)
    files = {}
    for key in list(FIG.keys()):
        if pmagplotlib.isServer:  # use server plot naming convention
            files[key] = 'LO:_' + location + '_TY:_VGP_map.' + fmt
        else:  # use more readable naming convention
            files[key] = '{}_VGP_map.{}'.format(location, fmt)

    if pmagplotlib.isServer:
        black = '#000000'
        purple = '#800080'
        titles = {}
        titles['map'] = location + ' VGP map'
        FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
        pmagplotlib.save_plots(FIG, files)
    elif plot == 0:
        pmagplotlib.draw_figs(FIG)
        ans = input(" S[a]ve to save plot, Return to quit:  ")
        if ans == "a":
            pmagplotlib.save_plots(FIG, files)
        else:
            print("Good bye")
            sys.exit()
    else:
        pmagplotlib.save_plots(FIG, files)
Exemplo n.º 20
0
def main():
    """
    NAME
        vgpmap_magic.py

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

    SYNTAX
        vgpmap_magic.py [command line options]

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

    """
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    dir_path = pmag.get_named_arg("-WD", ".")
    # plot: default is 0, if -sav in sys.argv should be 1
    interactive = True
    save_plots = pmag.get_flag_arg_from_sys("-sav", true=1, false=0)
    if save_plots:
        interactive = False
    fmt = pmag.get_named_arg("-fmt", "pdf")
    res = pmag.get_named_arg("-res", "c")
    proj = pmag.get_named_arg("-prj", "ortho")
    anti = pmag.get_flag_arg_from_sys("-S", true=1, false=0)
    fancy = pmag.get_flag_arg_from_sys("-etp", true=1, false=0)
    ell = pmag.get_flag_arg_from_sys("-ell", true=1, false=0)
    ages = pmag.get_flag_arg_from_sys("-age", true=1, false=0)
    if '-rev' in sys.argv:
        flip = 1
        ind = sys.argv.index('-rev')
        rsym = (sys.argv[ind + 1])
        rsize = int(sys.argv[ind + 2])
    else:
        flip, rsym, rsize = 0, "g^", 8
    if '-sym' in sys.argv:
        ind = sys.argv.index('-sym')
        sym = (sys.argv[ind + 1])
        size = int(sys.argv[ind + 2])
    else:
        sym, size = 'ro', 8
    if '-eye' in sys.argv:
        ind = sys.argv.index('-eye')
        lat_0 = float(sys.argv[ind + 1])
        lon_0 = float(sys.argv[ind + 2])
    else:
        lat_0, lon_0 = 90., 0.
    crd = pmag.get_named_arg("-crd", "")
    results_file = pmag.get_named_arg("-f", "sites.txt")
    ipmag.vgpmap_magic(dir_path, results_file, crd, sym, size, rsym, rsize,
                       fmt, res, proj, flip, anti, fancy, ell, ages, lat_0,
                       lon_0, save_plots, interactive)
Exemplo n.º 21
0
def main():
    """
    NAME
        plot_magmap.py

    DESCRIPTION
        makes a color contour map of desired field model

    SYNTAX
        plot_magmap.py [command line options]

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

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

    DESCRIPTION
        makes a biplot of specified variables from magic_measurements.txt format file

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

    INPUT
        takes magic formated magic_measurments file

    OPTIONS
        -h prints help message and quits
        -i interactively set filename and axes for plotting
        -f FILE: specifies file name, default: magic_measurements.txt
        -fmt [svg,png,jpg], format for images - default is svg
        -sav figure and quit
        -x XMETH:key:step, specify method code for X axis (optional key and treatment values)
        -y YMETH:key:step, specify method code for X axis
        -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is whole file
        -n [V,M] plot volume or mass normalized data only
    NOTES
        if nothing is specified for x and y, the user will be presented with options
        key = ['treatment_ac_field','treatment_dc_field',treatment_temp']
        step in mT for fields, K for temperatures
           """
    #
    file = 'magic_measurements.txt'
    methx, methy, fmt = "", "", '.svg'
    plot_key = ''
    norm_by = ""
    #plot=0
    no_plot = pmag.get_flag_arg_from_sys('-sav')
    if not no_plot:
        do_plot = True
    else:
        do_plot = False
    if '-h' in sys.argv:
        print(main.__doc__)
        sys.exit()
    if '-f' in sys.argv:
        ind = sys.argv.index('-f')
        file = sys.argv[ind + 1]
    if '-fmt' in sys.argv:
        ind = sys.argv.index('-fmt')
        fmt = '.' + sys.argv[ind + 1]
    if '-n' in sys.argv:
        ind = sys.argv.index('-n')
        norm_by = sys.argv[ind + 1]
    xtreat_key, ytreat_key, xstep, ystep = "", "", "", ""
    if '-x' in sys.argv:
        ind = sys.argv.index('-x')
        meths = sys.argv[ind + 1].split(':')
        methx = meths[0]
        if len(meths) > 1:
            xtreat_key = meths[1]
            xstep = float(meths[2])
    if '-y' in sys.argv:
        ind = sys.argv.index('-y')
        meths = sys.argv[ind + 1].split(':')
        methy = meths[0]
        if len(meths) > 1:
            ytreat_key = meths[1]
            ystep = float(meths[2])
    if '-obj' in sys.argv:
        ind = sys.argv.index('-obj')
        plot_by = sys.argv[ind + 1]
        if plot_by == 'loc': plot_key = 'er_location_name'
        if plot_by == 'sit': plot_key = 'er_site_name'
        if plot_by == 'sam': plot_key = 'er_sample_name'
        if plot_by == 'spc': plot_key = 'er_specimen_name'
    if '-h' in sys.argv:
        do_plot = False
    if '-i' in sys.argv:
        #
        # get name of file from command line
        #
        file = input(
            "Input magic_measurments file name? [magic_measurements.txt] ")
        if file == "": file = "magic_measurements.txt"
    #
    #
    FIG = {'fig': 1}
    pmagplotlib.plot_init(FIG['fig'], 5, 5)
    data, file_type = pmag.magic_read(file)
    if file_type != "magic_measurements":
        print(file_type, ' not correct format for magic_measurments file')
        sys.exit()
    #
    # collect method codes
    methods, plotlist = [], []
    for rec in data:
        if plot_key != "":
            if rec[plot_key] not in plotlist: plotlist.append(rec[plot_key])
        elif len(plotlist) == 0:
            plotlist.append('All')
        meths = rec['magic_method_codes'].split(':')
        for meth in meths:
            if meth.strip() not in methods and meth.strip() != "LP-":
                methods.append(meth.strip())
    #
    if '-i' in sys.argv:
        print(methods)
    elif methx == "" or methy == "":
        print(methods)
        sys.exit()
    GoOn = 1
    while GoOn == 1:
        if '-i' in sys.argv: methx = input('Select method for x axis: ')
        if methx not in methods:
            if '-i' in sys.argv:
                print('try again! method not available')
            else:
                print(main.__doc__)
                print('\n must specify X axis method\n')
                sys.exit()
        else:
            if pmagplotlib.verbose: print(methx, ' selected for X axis')
            GoOn = 0
    GoOn = 1
    while GoOn == 1:
        if '-i' in sys.argv: methy = input('Select method for y axis: ')
        if methy not in methods:
            if '-i' in sys.argv:
                print('try again! method not available')
            else:
                print(main.__doc__)
                print('\n must specify Y axis method\n')
                sys.exit()
        else:
            if pmagplotlib.verbose: print(methy, ' selected for Y axis')
            GoOn = 0
    if norm_by == "":
        measkeys = [
            'measurement_magn_mass', 'measurement_magn_volume',
            'measurement_magn_moment', 'measurement_magnitude',
            'measurement_chi_volume', 'measurement_chi_mass', 'measurement_chi'
        ]
    elif norm_by == "V":
        measkeys = ['measurement_magn_volume', 'measurement_chi_volume']
    elif norm_by == "M":
        measkeys = ['measurement_magn_mass', 'measurement_chi_mass']
    xmeaskey, ymeaskey = "", ""
    plotlist.sort()
    for plot in plotlist:  # go through objects
        if pmagplotlib.verbose:
            print(plot)
        X, Y = [], []
        x, y = '', ''
        for rec in data:
            if plot_key != "" and rec[plot_key] != plot:
                pass
            else:
                meths = rec['magic_method_codes'].split(':')
                for meth in meths:
                    if meth.strip() == methx:
                        if xmeaskey == "":
                            for key in measkeys:
                                if key in list(rec.keys()) and rec[key] != "":
                                    xmeaskey = key
                                    if pmagplotlib.verbose:
                                        print(xmeaskey,
                                              ' being used for plotting X.')
                                    break
                    if meth.strip() == methy:
                        if ymeaskey == "":
                            for key in measkeys:
                                if key in list(rec.keys()) and rec[key] != "":
                                    ymeaskey = key
                                    if pmagplotlib.verbose:
                                        print(ymeaskey,
                                              ' being used for plotting Y')
                                    break
        if ymeaskey != "" and xmeaskey != "":
            for rec in data:
                x, y = '', ''
                spec = rec[
                    'er_specimen_name']  # get the ydata for this specimen
                if rec[ymeaskey] != "" and methy in rec[
                        'magic_method_codes'].split(':'):
                    if ytreat_key == "" or (ytreat_key in list(rec.keys()) and
                                            float(rec[ytreat_key]) == ystep):
                        y = float(rec[ymeaskey])
                        for rec in data:  # now find the xdata
                            if rec['er_specimen_name'] == spec and rec[
                                    xmeaskey] != "" and methx in rec[
                                        'magic_method_codes'].split(':'):
                                if xtreat_key == "" or (
                                        xtreat_key in list(rec.keys())
                                        and float(rec[xtreat_key]) == xstep):
                                    x = float(rec[xmeaskey])
                if x != '' and y != '':
                    X.append(x)
                    Y.append(y)
        if len(X) > 0:
            pmagplotlib.clearFIG(FIG['fig'])
            pmagplotlib.plotXY(FIG['fig'],
                               X,
                               Y,
                               sym='ro',
                               xlab=methx,
                               ylab=methy,
                               title=plot + ':Biplot')
            if not pmagplotlib.isServer and do_plot:
                pmagplotlib.drawFIGS(FIG)
                ans = input('S[a]ve plots, [q]uit,  Return for next plot ')
                if ans == 'a':
                    files = {}
                    for key in list(FIG.keys()):
                        files[key] = plot + '_' + key + fmt
                    pmagplotlib.saveP(FIG, files)
                if ans == 'q':
                    print("Good-bye\n")
                    sys.exit()
            else:
                files = {}
                for key in list(FIG.keys()):
                    files[key] = plot + '_' + key + fmt
                if pmagplotlib.isServer:
                    black = '#000000'
                    purple = '#800080'
                    titles = {}
                    titles['fig'] = 'X Y Plot'
                    FIG = pmagplotlib.addBorders(FIG, titles, black, purple)
                pmagplotlib.saveP(FIG, files)
        else:
            print('nothing to plot for ', plot)