Exemple #1
0
def main():
    """
    NAME
        eqarea_magic.py

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

            files[key]=filename

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

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

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

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

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

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

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

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

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

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



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

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

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

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

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

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

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


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

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

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

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

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

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

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

            files[key]=filename

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

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

    DESCRIPTION
        plots anisotropy data with either bootstrap or hext ellipses

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

    DESCRIPTION
       makes equal area projections from declination/inclination data

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

    DESCRIPTION
       makes equal area projections from declination/inclination data

    SYNTAX
        eqarea_magic.py [command line options]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    DESCRIPTION
        plots anisotropy data with either bootstrap or hext ellipses

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