def main(): """ NAME qqunf.py DESCRIPTION makes qq plot from input data against uniform distribution SYNTAX qqunf.py [command line options] OPTIONS -h help message -f FILE, specify file on command line """ fmt, plot = 'svg', 0 if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit elif '-f' in sys.argv: # ask for filename ind = sys.argv.index('-f') file = sys.argv[ind + 1] f = open(file, 'rU') input = f.readlines() Data = [] for line in input: line.replace('\n', '') if '\t' in line: # read in the data from standard input rec = line.split('\t') # split each line on space to get records else: rec = line.split() # split each line on space to get records Data.append(float(rec[0])) # if len(Data) >= 10: QQ = {'unf1': 1} pmagplotlib.plot_init(QQ['unf1'], 5, 5) pmagplotlib.plotQQunf(QQ['unf1'], Data, 'QQ-Uniform') # make plot else: print 'you need N> 10' sys.exit() pmagplotlib.drawFIGS(QQ) files = {} for key in QQ.keys(): files[key] = key + '.' + fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['eq'] = 'Equal Area Plot' EQ = pmagplotlib.addBorders(EQ, titles, black, purple) pmagplotlib.saveP(QQ, files) elif plot == 1: files['qq'] = file + '.' + fmt pmagplotlib.saveP(QQ, files) else: ans = raw_input(" S[a]ve to save plot, [q]uit without saving: ") if ans == "a": pmagplotlib.saveP(QQ, files)
def main(): """ NAME qqunf.py DESCRIPTION makes qq plot from input data against uniform distribution SYNTAX qqunf.py [command line options] OPTIONS -h help message -f FILE, specify file on command line """ fmt,plot='svg',0 if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit elif '-f' in sys.argv: # ask for filename ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'rU') input=f.readlines() Data=[] for line in input: line.replace('\n','') if '\t' in line: # read in the data from standard input rec=line.split('\t') # split each line on space to get records else: rec=line.split() # split each line on space to get records Data.append(float(rec[0])) # if len(Data) >=10: QQ={'unf1':1} pmagplotlib.plot_init(QQ['unf1'],5,5) pmagplotlib.plotQQunf(QQ['unf1'],Data,'QQ-Uniform') # make plot else: print 'you need N> 10' sys.exit() pmagplotlib.drawFIGS(QQ) files={} for key in QQ.keys(): files[key]=key+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='Equal Area Plot' EQ = pmagplotlib.addBorders(EQ,titles,black,purple) pmagplotlib.saveP(QQ,files) elif plot==1: files['qq']=file+'.'+fmt pmagplotlib.saveP(QQ,files) else: ans=raw_input(" S[a]ve to save plot, [q]uit without saving: ") if ans=="a": pmagplotlib.saveP(QQ,files)
def main(): """ NAME plot_2cdfs.py DESCRIPTION makes plots of cdfs of data in input file SYNTAX plot_2cdfs.py [-h][command line options] OPTIONS -h prints help message and quits -f FILE1 FILE2 -t TITLE -fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is svg """ fmt = 'svg' title = "" if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind = sys.argv.index('-f') file = sys.argv[ind + 1] X = numpy.loadtxt(file) file = sys.argv[ind + 2] X2 = numpy.loadtxt(file) # else: # X=numpy.loadtxt(sys.stdin,dtype=numpy.float) else: print '-f option required' print main.__doc__ sys.exit() if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-t' in sys.argv: ind = sys.argv.index('-t') title = sys.argv[ind + 1] CDF = {'X': 1} pmagplotlib.plot_init(CDF['X'], 5, 5) pmagplotlib.plotCDF(CDF['X'], X, '', 'r', '') pmagplotlib.plotCDF(CDF['X'], X2, title, 'b', '') D, p = scipy.stats.ks_2samp(X, X2) if p >= .05: print D, p, ' not rejected at 95%' else: print D, p, ' rejected at 95%' pmagplotlib.drawFIGS(CDF) ans = raw_input('S[a]ve plot, <Return> to quit ') if ans == 'a': files = {'X': 'CDF_.' + fmt} pmagplotlib.saveP(CDF, files)
def main(): """ NAME plot_2cdfs.py DESCRIPTION makes plots of cdfs of data in input file SYNTAX plot_2cdfs.py [-h][command line options] OPTIONS -h prints help message and quits -f FILE1 FILE2 -t TITLE -fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is svg """ fmt = "svg" title = "" if "-h" in sys.argv: print main.__doc__ sys.exit() if "-f" in sys.argv: ind = sys.argv.index("-f") file = sys.argv[ind + 1] X = numpy.loadtxt(file) file = sys.argv[ind + 2] X2 = numpy.loadtxt(file) # else: # X=numpy.loadtxt(sys.stdin,dtype=numpy.float) else: print "-f option required" print main.__doc__ sys.exit() if "-fmt" in sys.argv: ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] if "-t" in sys.argv: ind = sys.argv.index("-t") title = sys.argv[ind + 1] CDF = {"X": 1} pmagplotlib.plot_init(CDF["X"], 5, 5) pmagplotlib.plotCDF(CDF["X"], X, "", "r", "") pmagplotlib.plotCDF(CDF["X"], X2, title, "b", "") D, p = scipy.stats.ks_2samp(X, X2) if p >= 0.05: print D, p, " not rejected at 95%" else: print D, p, " rejected at 95%" pmagplotlib.drawFIGS(CDF) ans = raw_input("S[a]ve plot, <Return> to quit ") if ans == "a": files = {"X": "CDF_." + fmt} pmagplotlib.saveP(CDF, files)
def main(): """ NAME plot_cdf.py DESCRIPTION makes plots of cdfs of data in input file SYNTAX plot_cdf.py [-h][command line options] OPTIONS -h prints help message and quits -f FILE -t TITLE -fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is svg -sav saves plot and quits """ fmt, plot = 'svg', 0 title = "" if '-h' in sys.argv: print main.__doc__ sys.exit() if '-sav' in sys.argv: plot = 1 if '-f' in sys.argv: ind = sys.argv.index('-f') file = sys.argv[ind + 1] X = numpy.loadtxt(file) # else: # X=numpy.loadtxt(sys.stdin,dtype=numpy.float) else: print '-f option required' print main.__doc__ sys.exit() if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-t' in sys.argv: ind = sys.argv.index('-t') title = sys.argv[ind + 1] CDF = {'X': 1} pmagplotlib.plot_init(CDF['X'], 5, 5) pmagplotlib.plotCDF(CDF['X'], X, title, 'r', '') files = {'X': 'CDF_.' + fmt} if plot == 0: pmagplotlib.drawFIGS(CDF) ans = raw_input('S[a]ve plot, <Return> to quit ') if ans == 'a': pmagplotlib.saveP(CDF, files) else: pmagplotlib.saveP(CDF, files)
def main(): """ NAME plot_cdf.py DESCRIPTION makes plots of cdfs of data in input file SYNTAX plot_cdf.py [-h][command line options] OPTIONS -h prints help message and quits -f FILE -t TITLE -fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is svg -sav saves plot and quits """ fmt,plot='svg',0 title="" if '-h' in sys.argv: print main.__doc__ sys.exit() if '-sav' in sys.argv:plot=1 if '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] X=numpy.loadtxt(file) # else: # X=numpy.loadtxt(sys.stdin,dtype=numpy.float) else: print '-f option required' print main.__doc__ sys.exit() if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-t' in sys.argv: ind=sys.argv.index('-t') title=sys.argv[ind+1] CDF={'X':1} pmagplotlib.plot_init(CDF['X'],5,5) pmagplotlib.plotCDF(CDF['X'],X,title,'r','') files={'X':'CDF_.'+fmt} if plot==0: pmagplotlib.drawFIGS(CDF) ans= raw_input('S[a]ve plot, <Return> to quit ') if ans=='a': pmagplotlib.saveP(CDF,files) else: pmagplotlib.saveP(CDF,files)
def main(): """ NAME plotdi_a.py DESCRIPTION plots equal area projection from dec inc data and fisher mean, cone of confidence INPUT FORMAT takes dec, inc, alpha95 as first three columns in space delimited file SYNTAX plotdi_a.py [-i][-f FILE] OPTIONS -f FILE to read file name from command line -fmt [png,jpg,eps,pdf,svg] set plot file format ['svg' is default] -sav save plot and quit """ fmt,plot='svg',0 if len(sys.argv) > 0: if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-sav' in sys.argv:plot=1 if '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') data=f.readlines() else: data=sys.stdin.readlines() # read in data from standard input DIs,Pars=[],[] for line in data: # read in the data from standard input pars=[] rec=line.split() # split each line on space to get records DIs.append([float(rec[0]),float(rec[1])]) pars.append(float(rec[0])) pars.append(float(rec[1])) pars.append(float(rec[2])) pars.append(float(rec[0])) isign=old_div(abs(float(rec[1])),float(rec[1])) pars.append(float(rec[1])-isign*90.) #Beta inc pars.append(float(rec[2])) # gamma pars.append(float(rec[0])+90.) # Beta dec pars.append(0.) #Beta inc Pars.append(pars) # EQ={'eq':1} # make plot dictionary pmagplotlib.plot_init(EQ['eq'],5,5) title='Equal area projection' pmagplotlib.plotEQ(EQ['eq'],DIs,title)# plot directions for k in range(len(Pars)): pmagplotlib.plotELL(EQ['eq'],Pars[k],'b',0,1) # plot ellipses files={} for key in list(EQ.keys()): files[key]=key+'.'+fmt titles={} titles['eq']='Equal Area Plot' if pmagplotlib.isServer: black = '#000000' purple = '#800080' EQ = pmagplotlib.addBorders(EQ,titles,black,purple) pmagplotlib.saveP(EQ,files) elif plot==0: pmagplotlib.drawFIGS(EQ) ans=input(" S[a]ve to save plot, [q]uit, Return to continue: ") if ans=="q": sys.exit() if ans=="a": pmagplotlib.saveP(EQ,files) else: pmagplotlib.saveP(EQ,files)
def main(): """ NAME plotdi_e.py DESCRIPTION plots equal area projection from dec inc data and cones of confidence (Fisher, kent or Bingham or bootstrap). INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX plotdi_e.py [command line options] OPTIONS -h prints help message and quits -i for interactive parameter entry -f FILE, sets input filename on command line -Fish plots unit vector mean direction, alpha95 -Bing plots Principal direction, Bingham confidence ellipse -Kent plots unit vector mean direction, confidence ellipse -Boot E plots unit vector mean direction, bootstrapped confidence ellipse -Boot V plots unit vector mean direction, distribution of bootstrapped means """ dist = 'F' # default distribution is Fisherian mode = 1 EQ = {'eq': 1} if len(sys.argv) > 0: if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file = raw_input("Enter file name with dec, inc data: ") dist = raw_input( "Enter desired distrubution: [Fish]er, [Bing]ham, [Kent] [Boot] [default is Fisher]: " ) if dist == "": dist = "F" if dist == "Boot": type = raw_input( " Ellipses or distribution of vectors? [E]/V ") if type == "" or type == "E": dist = "BE" else: dist = "BE" else: # if '-f' in sys.argv: ind = sys.argv.index('-f') file = sys.argv[ind + 1] else: print 'you must specify a file name' print main.__doc__ sys.exit() if '-Bing' in sys.argv: dist = 'B' if '-Kent' in sys.argv: dist = 'K' if '-Boot' in sys.argv: ind = sys.argv.index('-Boot') type = sys.argv[ind + 1] if type == 'E': dist = 'BE' elif type == 'V': dist = 'BV' EQ['bdirs'] = 2 pmagplotlib.plot_init(EQ['bdirs'], 5, 5) else: print main.__doc__ sys.exit() pmagplotlib.plot_init(EQ['eq'], 5, 5) # # get to work f = open(file, 'r') data = f.readlines() # DIs = [] # set up list for dec inc data DiRecs = [] pars = [] nDIs, rDIs, npars, rpars = [], [], [], [] mode = 1 for line in data: # read in the data from standard input DiRec = {} rec = line.split() # split each line on space to get records DIs.append((float(rec[0]), float(rec[1]), 1.)) DiRec['dec'] = rec[0] DiRec['inc'] = rec[1] DiRec['direction_type'] = 'l' DiRecs.append(DiRec) # split into two modes ppars = pmag.doprinc(DIs) # get principal directions for rec in DIs: angle = pmag.angle([rec[0], rec[1]], [ppars['dec'], ppars['inc']]) if angle > 90.: rDIs.append(rec) else: nDIs.append(rec) if dist == 'B': # do on whole dataset title = "Bingham confidence ellipse" bpars = pmag.dobingham(DIs) for key in bpars.keys(): if key != 'n': print " ", key, '%7.1f' % (bpars[key]) if key == 'n': print " ", key, ' %i' % (bpars[key]) npars.append(bpars['dec']) npars.append(bpars['inc']) npars.append(bpars['Zeta']) npars.append(bpars['Zdec']) npars.append(bpars['Zinc']) npars.append(bpars['Eta']) npars.append(bpars['Edec']) npars.append(bpars['Einc']) if dist == 'F': title = "Fisher confidence cone" if len(nDIs) > 3: fpars = pmag.fisher_mean(nDIs) print "mode ", mode for key in fpars.keys(): if key != 'n': print " ", key, '%7.1f' % (fpars[key]) if key == 'n': print " ", key, ' %i' % (fpars[key]) mode += 1 npars.append(fpars['dec']) npars.append(fpars['inc']) npars.append(fpars['alpha95']) # Beta npars.append(fpars['dec']) isign = abs(fpars['inc']) / fpars['inc'] npars.append(fpars['inc'] - isign * 90.) #Beta inc npars.append(fpars['alpha95']) # gamma npars.append(fpars['dec'] + 90.) # Beta dec npars.append(0.) #Beta inc if len(rDIs) > 3: fpars = pmag.fisher_mean(rDIs) print "mode ", mode for key in fpars.keys(): if key != 'n': print " ", key, '%7.1f' % (fpars[key]) if key == 'n': print " ", key, ' %i' % (fpars[key]) mode += 1 rpars.append(fpars['dec']) rpars.append(fpars['inc']) rpars.append(fpars['alpha95']) # Beta rpars.append(fpars['dec']) isign = abs(fpars['inc']) / fpars['inc'] rpars.append(fpars['inc'] - isign * 90.) #Beta inc rpars.append(fpars['alpha95']) # gamma rpars.append(fpars['dec'] + 90.) # Beta dec rpars.append(0.) #Beta inc if dist == 'K': title = "Kent confidence ellipse" if len(nDIs) > 3: kpars = pmag.dokent(nDIs, len(nDIs)) print "mode ", mode for key in kpars.keys(): if key != 'n': print " ", key, '%7.1f' % (kpars[key]) if key == 'n': print " ", key, ' %i' % (kpars[key]) mode += 1 npars.append(kpars['dec']) npars.append(kpars['inc']) npars.append(kpars['Zeta']) npars.append(kpars['Zdec']) npars.append(kpars['Zinc']) npars.append(kpars['Eta']) npars.append(kpars['Edec']) npars.append(kpars['Einc']) if len(rDIs) > 3: kpars = pmag.dokent(rDIs, len(rDIs)) print "mode ", mode for key in kpars.keys(): if key != 'n': print " ", key, '%7.1f' % (kpars[key]) if key == 'n': print " ", key, ' %i' % (kpars[key]) mode += 1 rpars.append(kpars['dec']) rpars.append(kpars['inc']) rpars.append(kpars['Zeta']) rpars.append(kpars['Zdec']) rpars.append(kpars['Zinc']) rpars.append(kpars['Eta']) rpars.append(kpars['Edec']) rpars.append(kpars['Einc']) else: # assume bootstrap if dist == 'BE': if len(nDIs) > 5: BnDIs = pmag.di_boot(nDIs) Bkpars = pmag.dokent(BnDIs, 1.) print "mode ", mode for key in Bkpars.keys(): if key != 'n': print " ", key, '%7.1f' % (Bkpars[key]) if key == 'n': print " ", key, ' %i' % (Bkpars[key]) mode += 1 npars.append(Bkpars['dec']) npars.append(Bkpars['inc']) npars.append(Bkpars['Zeta']) npars.append(Bkpars['Zdec']) npars.append(Bkpars['Zinc']) npars.append(Bkpars['Eta']) npars.append(Bkpars['Edec']) npars.append(Bkpars['Einc']) if len(rDIs) > 5: BrDIs = pmag.di_boot(rDIs) Bkpars = pmag.dokent(BrDIs, 1.) print "mode ", mode for key in Bkpars.keys(): if key != 'n': print " ", key, '%7.1f' % (Bkpars[key]) if key == 'n': print " ", key, ' %i' % (Bkpars[key]) mode += 1 rpars.append(Bkpars['dec']) rpars.append(Bkpars['inc']) rpars.append(Bkpars['Zeta']) rpars.append(Bkpars['Zdec']) rpars.append(Bkpars['Zinc']) rpars.append(Bkpars['Eta']) rpars.append(Bkpars['Edec']) rpars.append(Bkpars['Einc']) title = "Bootstrapped confidence ellipse" elif dist == 'BV': if len(nDIs) > 5: pmagplotlib.plotEQ(EQ['eq'], nDIs, 'Data') BnDIs = pmag.di_boot(nDIs) pmagplotlib.plotEQ(EQ['bdirs'], BnDIs, 'Bootstrapped Eigenvectors') if len(rDIs) > 5: BrDIs = pmag.di_boot(rDIs) if len(nDIs) > 5: # plot on existing plots pmagplotlib.plotDI(EQ['eq'], rDIs) pmagplotlib.plotDI(EQ['bdirs'], BrDIs) else: pmagplotlib.plotEQ(EQ['eq'], rDIs, 'Data') pmagplotlib.plotEQ(EQ['bdirs'], BrDIs, 'Bootstrapped Eigenvectors') pmagplotlib.drawFIGS(EQ) ans = raw_input('s[a]ve, [q]uit ') if ans == 'q': sys.exit() if ans == 'a': files = {} for key in EQ.keys(): files[key] = 'BE_' + key + '.svg' pmagplotlib.saveP(EQ, files) sys.exit() if len(nDIs) > 5: pmagplotlib.plotCONF(EQ['eq'], title, DiRecs, npars, 1) if len(rDIs) > 5 and dist != 'B': pmagplotlib.plotCONF(EQ['eq'], title, [], rpars, 0) elif len(rDIs) > 5 and dist != 'B': pmagplotlib.plotCONF(EQ['eq'], title, DiRecs, rpars, 1) pmagplotlib.drawFIGS(EQ) ans = raw_input('s[a]ve, [q]uit ') if ans == 'q': sys.exit() if ans == 'a': files = {} for key in EQ.keys(): files[key] = key + '.svg' pmagplotlib.saveP(EQ, files)
def main(): """ NAME eqarea.py DESCRIPTION makes equal area projections from declination/inclination data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX eqarea.py [options] OPTIONS -f FILE, specify file on command line -sav save figure and quit -fmt [svg,jpg,png,pdf] set figure format [default is svg] -s SIZE specify symbol size - default is 20 -Lsym SHAPE COLOR specify shape and color for lower hemisphere -Usym SHAPE COLOR specify shape and color for upper hemisphere shapes: 's': square,'o': circle,'^,>,v,<': [up,right,down,left] triangle, 'd': diamond, 'p': pentagram, 'h': hexagon, '8': octagon, '+': plus, 'x': cross colors: [b]lue,[g]reen,[r]ed,[c]yan,[m]agenta,[y]ellow,blac[k],[w]hite """ title = "" files, fmt = {}, 'svg' sym = {'lower': ['o', 'r'], 'upper': ['o', 'w']} plot = 0 if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit if '-sav' in sys.argv: plot = 1 if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-s' in sys.argv: ind = sys.argv.index('-s') sym['size'] = int(sys.argv[ind + 1]) else: sym['size'] = 20 if '-Lsym' in sys.argv: ind = sys.argv.index('-Lsym') sym['lower'][0] = sys.argv[ind + 1] sym['lower'][1] = sys.argv[ind + 2] if '-Usym' in sys.argv: ind = sys.argv.index('-Usym') sym['upper'][0] = sys.argv[ind + 1] sym['upper'][1] = sys.argv[ind + 2] if '-f' in sys.argv: # ask for filename ind = sys.argv.index('-f') file = sys.argv[ind + 1] else: print main.__doc__ print ' \n -f option required' sys.exit() # graceful quit DI = numpy.loadtxt(file) EQ = {'eq': 1} pmagplotlib.plot_init(EQ['eq'], 5, 5) pmagplotlib.plotEQsym(EQ['eq'], DI, 'Equal Area Plot', sym) # make plot if plot == 0: pmagplotlib.drawFIGS(EQ) # make it visible for key in EQ.keys(): files[key] = key + '.' + fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['eq'] = 'Equal Area Plot' EQ = pmagplotlib.addBorders(EQ, titles, black, purple) pmagplotlib.saveP(EQ, files) elif plot == 1: files['eq'] = file + '.' + fmt pmagplotlib.saveP(EQ, files) else: ans = raw_input(" S[a]ve to save plot, [q]uit without saving: ") if ans == "a": pmagplotlib.saveP(EQ, files)
def main(): """ NAME quick_hyst.py DESCRIPTION makes plots of hysteresis data SYNTAX quick_hyst.py [command line options] OPTIONS -h prints help message and quits -f: specify input file, default is measurements.txt -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg] """ args = sys.argv if "-h" in args: print(main.__doc__) sys.exit() plots = 0 pltspec = "" verbose = pmagplotlib.verbose #version_num = pmag.get_version() dir_path = pmag.get_named_arg_from_sys('-WD', '.') dir_path = os.path.realpath(dir_path) meas_file = pmag.get_named_arg_from_sys('-f', 'measurements.txt') fmt = pmag.get_named_arg_from_sys('-fmt', 'png') if '-sav' in args: verbose = 0 plots = 1 if '-spc' in args: ind = args.index("-spc") pltspec = args[ind + 1] verbose = 0 plots = 1 # con = nb.Contribution(dir_path, read_tables=['measurements'], custom_filenames={'measurements': meas_file}) # get as much name data as possible (used for naming plots) if not 'measurements' in con.tables: print("-W- No measurement file found") return con.propagate_location_to_measurements() if 'measurements' not in con.tables: print(main.__doc__) print('bad file') sys.exit() meas_container = con.tables['measurements'] #meas_df = meas_container.df # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs = [] HDD = {} HDD['hyst'] = 1 pmagplotlib.plot_init(HDD['hyst'], 5, 5) # # get list of unique experiment names and specimen names # sids = [] hyst_data = meas_container.get_records_for_code('LP-HYS') #experiment_names = hyst_data['experiment_name'].unique() if not len(hyst_data): print("-W- No hysteresis data found") return sids = hyst_data['specimen'].unique() # if 'treat_temp' is provided, use that value, otherwise assume 300 hyst_data['treat_temp'].where(hyst_data['treat_temp'].notnull(), '300', inplace=True) # start at first specimen, or at provided specimen ('-spc') k = 0 if pltspec != "": try: print(sids) k = list(sids).index(pltspec) except ValueError: print('-W- No specimen named: {}.'.format(pltspec)) print('-W- Please provide a valid specimen name') return intlist = ['magn_moment', 'magn_volume', 'magn_mass'] while k < len(sids): locname, site, sample, synth = '', '', '', '' s = sids[k] if verbose: print(s, k + 1, 'out of ', len(sids)) # B, M for hysteresis, Bdcd,Mdcd for irm-dcd data B, M = [], [] # get all measurements for this specimen spec = hyst_data[hyst_data['specimen'] == s] # get names if 'location' in spec: locname = spec['location'][0] if 'site' in spec: site = spec['sample'][0] if 'sample' in spec: sample = spec['sample'][0] # get all records with non-blank values in any intlist column # find intensity data for int_column in intlist: if int_column in spec.columns: int_col = int_column break meas_data = spec[spec[int_column].notnull()] if len(meas_data) == 0: break # c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-'] cnum = 0 Temps = [] xlab, ylab, title = '', '', '' Temps = meas_data['treat_temp'].unique() for t in Temps: print('working on t: ', t) t_data = meas_data[meas_data['treat_temp'] == t] m = int_col B = t_data['meas_field_dc'].astype(float).values M = t_data[m].astype(float).values # now plot the hysteresis curve(s) # if len(B) > 0: B = numpy.array(B) M = numpy.array(M) if t == Temps[-1]: xlab = 'Field (T)' ylab = m title = 'Hysteresis: ' + s if t == Temps[0]: pmagplotlib.clearFIG(HDD['hyst']) pmagplotlib.plotXY(HDD['hyst'], B, M, sym=c[cnum], xlab=xlab, ylab=ylab, title=title) pmagplotlib.plotXY(HDD['hyst'], [1.1 * B.min(), 1.1 * B.max()], [0, 0], sym='k-', xlab=xlab, ylab=ylab, title=title) pmagplotlib.plotXY(HDD['hyst'], [0, 0], [1.1 * M.min(), 1.1 * M.max()], sym='k-', xlab=xlab, ylab=ylab, title=title) if verbose: pmagplotlib.drawFIGS(HDD) cnum += 1 if cnum == len(c): cnum = 0 # files = {} if plots: if pltspec != "": s = pltspec for key in list(HDD.keys()): if pmagplotlib.isServer: if synth == '': files[ key] = "LO:_" + locname + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + s + '_TY:_' + key + '_.' + fmt else: files[ key] = 'SY:_' + synth + '_TY:_' + key + '_.' + fmt else: if synth == '': filename = '' for item in [locname, site, sample, s, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) files[key] = filename else: files[key] = "{}_{}.{}".format(synth, key, fmt) pmagplotlib.saveP(HDD, files) if pltspec != "": sys.exit() if verbose: pmagplotlib.drawFIGS(HDD) ans = input( "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n " ) if ans == "a": files = {} for key in list(HDD.keys()): if pmagplotlib.isServer: # use server plot naming convention files[ key] = "LO:_" + locname + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + s + '_TY:_' + key + '_.' + fmt else: # use more readable plot naming convention filename = '' for item in [locname, site, sample, s, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) files[key] = filename pmagplotlib.saveP(HDD, files) if ans == '': k += 1 if ans == "p": del HystRecs[-1] k -= 1 if ans == 'q': print("Good bye") sys.exit() if ans == 's': keepon = 1 specimen = input( 'Enter desired specimen name (or first part there of): ') while keepon == 1: try: k = sids.index(specimen) keepon = 0 except: tmplist = [] for qq in range(len(sids)): if specimen in sids[qq]: tmplist.append(sids[qq]) print(specimen, " not found, but this was: ") print(tmplist) specimen = input('Select one or try again\n ') k = sids.index(specimen) else: k += 1 if len(B) == 0: if verbose: print('skipping this one - no hysteresis data') k += 1
def main(): """ NAME dmag_magic.py DESCRIPTION plots intensity decay curves for demagnetization experiments SYNTAX dmag_magic -h [command line options] INPUT takes magic formatted magic_measurements.txt files OPTIONS -h prints help message and quits -f FILE: specify input file, default is: magic_measurements.txt -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is by location -LT [AF,T,M]: specify lab treatment type, default AF -XLP [PI]: exclude specific lab protocols (for example, method codes like LP-PI) -N do not normalize by NRM magnetization -sav save plots silently and quit -fmt [svg,jpg,png,pdf] set figure format [default is svg] NOTE loc: location (study); sit: site; sam: sample; spc: specimen """ FIG={} # plot dictionary FIG['demag']=1 # demag is figure 1 in_file,plot_key,LT='magic_measurements.txt','er_location_name',"LT-AF-Z" XLP="" norm=1 LT='LT-AF-Z' units,dmag_key='T','treatment_ac_field' plot=0 fmt='svg' if len(sys.argv)>1: if '-h' in sys.argv: print main.__doc__ sys.exit() if '-N' in sys.argv: norm=0 if '-sav' in sys.argv: plot=1 if '-f' in sys.argv: ind=sys.argv.index("-f") in_file=sys.argv[ind+1] if '-fmt' in sys.argv: ind=sys.argv.index("-fmt") fmt=sys.argv[ind+1] if '-obj' in sys.argv: ind=sys.argv.index('-obj') plot_by=sys.argv[ind+1] if plot_by=='sit':plot_key='er_site_name' if plot_by=='sam':plot_key='er_sample_name' if plot_by=='spc':plot_key='er_specimen_name' if '-XLP' in sys.argv: ind=sys.argv.index("-XLP") XLP=sys.argv[ind+1] # get lab protocol for excluding if '-LT' in sys.argv: ind=sys.argv.index("-LT") LT='LT-'+sys.argv[ind+1]+'-Z' # get lab treatment for plotting if LT=='LT-T-Z': units,dmag_key='K','treatment_temp' elif LT=='LT-AF-Z': units,dmag_key='T','treatment_ac_field' elif LT=='LT-M-Z': units,dmag_key='J','treatment_mw_energy' else: units='U' data,file_type=pmag.magic_read(in_file) sids=pmag.get_specs(data) pmagplotlib.plot_init(FIG['demag'],5,5) print len(data),' records read from ',in_file # # # find desired intensity data # # plotlist,intlist=[],['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass'] IntMeths=[] FixData=[] for rec in data: meths=[] methcodes=rec['magic_method_codes'].split(':') for meth in methcodes:meths.append(meth.strip()) for key in rec.keys(): if key in intlist and rec[key]!="": if key not in IntMeths:IntMeths.append(key) if rec[plot_key] not in plotlist and LT in meths: plotlist.append(rec[plot_key]) if 'measurement_flag' not in rec.keys():rec['measurement_flag']='g' FixData.append(rec) plotlist.sort() if len(IntMeths)==0: print 'No intensity information found' sys.exit() data=FixData int_key=IntMeths[0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used for plt in plotlist: if plot==0: print plt,'plotting by: ',plot_key PLTblock=pmag.get_dictitem(data,plot_key,plt,'T') # fish out all the data for this type of plot PLTblock=pmag.get_dictitem(PLTblock,'magic_method_codes',LT,'has') # fish out all the dmag for this experiment type PLTblock=pmag.get_dictitem(PLTblock,int_key,'','F') # get all with this intensity key non-blank if XLP!="":PLTblock=pmag.get_dictitem(PLTblock,'magic_method_codes',XLP,'not') # reject data with XLP in method_code if len(PLTblock)>2: title=PLTblock[0][plot_key] spcs=[] for rec in PLTblock: if rec['er_specimen_name'] not in spcs:spcs.append(rec['er_specimen_name']) for spc in spcs: SPCblock=pmag.get_dictitem(PLTblock,'er_specimen_name',spc,'T') # plot specimen by specimen INTblock=[] for rec in SPCblock: INTblock.append([float(rec[dmag_key]),0,0,float(rec[int_key]),1,rec['measurement_flag']]) if len(INTblock)>2: pmagplotlib.plotMT(FIG['demag'],INTblock,title,0,units,norm) if plot==1: files={} for key in FIG.keys(): files[key]=title+'_'+LT+'.'+fmt pmagplotlib.saveP(FIG,files) sys.exit() else: 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": files={} for key in FIG.keys(): files[key]=title+'_'+LT+'.svg' pmagplotlib.saveP(FIG,files) pmagplotlib.clearFIG(FIG['demag'])
def main(): """ NAME basemap_magic.py NB: this program no longer maintained - use plot_mapPTS.py for greater functionality DESCRIPTION makes a map of locations in er_sites.txt SYNTAX basemap_magic.py [command line options] OPTIONS -h prints help message and quits -f SFILE, specify er_sites.txt or pmag_results.txt format file -res [c,l,i,h] specify resolution (crude,low,intermediate,high) -etp plot the etopo20 topographic mesh -pad [LAT LON] pad bounding box by LAT/LON (default is [.5 .5] degrees) -grd SPACE specify grid spacing -prj [lcc] , specify projection (lcc=lambert conic conformable), default is mercator -n print site names (default is not) -l print location names (default is not) -o color ocean blue/land green (default is not) -R don't plot details of rivers -B don't plot national/state boundaries, etc. -sav save plot and quit quietly -fmt [png,svg,eps,jpg,pdf] specify format for output, default is pdf DEFAULTS SFILE: 'er_sites.txt' resolution: intermediate saved images are in pdf """ dir_path='.' sites_file='er_sites.txt' ocean=0 res='i' proj='merc' prn_name=0 prn_loc=0 fancy=0 rivers,boundaries=0,0 padlon,padlat,gridspace,details=.5,.5,.5,1 fmt='pdf' if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind = sys.argv.index('-f') sites_file=sys.argv[ind+1] if '-res' in sys.argv: ind = sys.argv.index('-res') res=sys.argv[ind+1] if '-etp' in sys.argv:fancy=1 if '-n' in sys.argv:prn_name=1 if '-l' in sys.argv:prn_loc=1 if '-o' in sys.argv:ocean=1 if '-R' in sys.argv:rivers=0 if '-B' in sys.argv:boundaries=0 if '-prj' in sys.argv: ind = sys.argv.index('-prj') proj=sys.argv[ind+1] if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt=sys.argv[ind+1] verbose=pmagplotlib.verbose if '-sav' in sys.argv: verbose=0 if '-pad' in sys.argv: ind = sys.argv.index('-pad') padlat=float(sys.argv[ind+1]) padlon=float(sys.argv[ind+2]) if '-grd' in sys.argv: ind = sys.argv.index('-grd') gridspace=float(sys.argv[ind+1]) if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path=sys.argv[ind+1] sites_file=dir_path+'/'+sites_file location="" FIG={'map':1} pmagplotlib.plot_init(FIG['map'],6,6) # read in er_sites file Sites,file_type=pmag.magic_read(sites_file) if 'results' in file_type: latkey='average_lat' lonkey='average_lon' namekey='pmag_result_name' lockey='er_location_names' else: latkey='site_lat' lonkey='site_lon' namekey='er_site_name' lockey='er_location_name' lats,lons=[],[] slats,slons=[],[] names,locs=[],[] for site in Sites: if prn_loc==1 and location=="":location=site['er_location_name'] lats.append(float(site[latkey])) l=float(site[lonkey]) if l<0:l=l+360. # make positive lons.append(l) if prn_name==1:names.append(site[namekey]) if prn_loc==1:locs.append(site[lockey]) for lat in lats:slats.append(lat) for lon in lons:slons.append(lon) Opts={'res':res,'proj':proj,'loc_name':locs,'padlon':padlon,'padlat':padlat,'latmin':numpy.min(slats)-padlat,'latmax':numpy.max(slats)+padlat,'lonmin':numpy.min(slons)-padlon,'lonmax':numpy.max(slons)+padlon,'sym':'ro','boundinglat':0.,'pltgrid':1.} Opts['lon_0']=0.5*(numpy.min(slons)+numpy.max(slons)) Opts['lat_0']=0.5*(numpy.min(slats)+numpy.max(slats)) Opts['names']=names Opts['gridspace']=gridspace Opts['details']={'coasts':1,'rivers':1,'states':1,'countries':1,'ocean':0} if ocean==1:Opts['details']['ocean']=1 if rivers==1: Opts['details']['rivers']=0 if boundaries==1: Opts['details']['states']=0 Opts['details']['countries']=0 Opts['details']['fancy']=fancy pmagplotlib.plotMAP(FIG['map'],lats,lons,Opts) if verbose:pmagplotlib.drawFIGS(FIG) files={} for key in FIG.keys(): files[key]='Site_map'+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['map']='Site Map' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) elif verbose: ans=raw_input(" S[a]ve to save plot, Return to quit: ") if ans=="a": pmagplotlib.saveP(FIG,files) else: pmagplotlib.saveP(FIG,files)
def main(): """ NAME trmaq_magic.py DESCTIPTION does non-linear trm acquisisiton correction SYNTAX trmaq_magic.py [-h][-i][command line options] OPTIONS -h prints help message and quits -i allows interactive setting of file names -f MFILE, sets magic_measurements input file -ft TSPEC, sets thellier_specimens input file -F OUT, sets output for non-linear TRM acquisition corrected data DEFAULTS MFILE: trmaq_measurements.txt TSPEC: thellier_specimens.txt OUT: NLT_specimens.txt """ meas_file='trmaq_measurements.txt' tspec="thellier_specimens.txt" output='NLT_specimens.txt' if '-h' in sys.argv: print main.__doc__ sys.exit() if '-i' in sys.argv: meas_file=raw_input("Input magic_measurements file name? [trmaq_measurements.txt] ") if meas_file=="":meas_file="trmaq_measurements.txt" tspec=raw_input(" thellier_specimens file name? [thellier_specimens.txt] ") if tspec=="":tspec="thellier_specimens.txt" output=raw_input("File for non-linear TRM adjusted specimen data: [NLTspecimens.txt] ") if output=="":output="NLT_specimens.txt" if '-f' in sys.argv: ind=sys.argv.index('-f') meas_file=sys.argv[ind+1] if '-ft' in sys.argv: ind=sys.argv.index('-ft') tspec=sys.argv[ind+1] if '-F' in sys.argv: ind=sys.argv.index('-F') output=sys.argv[ind+1] # PLT={'aq':1} pmagplotlib.plot_init(PLT['aq'],5,5) # # get name of file from command line # comment="" # # meas_data,file_type=pmag.magic_read(meas_file) if file_type != 'magic_measurements': print file_type print file_type,"This is not a valid magic_measurements file " sys.exit() sids=pmag.get_specs(meas_data) specimen=0 # # read in thellier_specimen data # nrm,file_type=pmag.magic_read(tspec) PmagSpecRecs=[] while specimen < len(sids): # # find corresoponding paleointensity data for this specimen # s=sids[specimen] blab,best="","" for nrec in nrm: # pick out the Banc data for this spec if nrec["er_specimen_name"]==s: blab=float(nrec["specimen_lab_field_dc"]) best=float(nrec["specimen_int"]) TrmRec=nrec break if blab=="": print "skipping ",s," : no best " specimen+=1 else: print sids[specimen],specimen+1, 'of ', len(sids),'Best = ',best*1e6 MeasRecs=[] # # find the data from the meas_data file for this specimen # for rec in meas_data: if rec["er_specimen_name"]==s: meths=rec["magic_method_codes"].split(":") methcodes=[] for meth in meths: methcodes.append(meth.strip()) if "LP-TRM" in methcodes: MeasRecs.append(rec) if len(MeasRecs) <2: specimen+=1 print 'skipping specimen - no trm acquisition data ', s # # collect info for the PmagSpecRec dictionary # else: TRMs,Bs=[],[] for rec in MeasRecs: Bs.append(float(rec['treatment_dc_field'])) TRMs.append(float(rec['measurement_magn_moment'])) NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc # Mp,Bp=[],[] for k in range(int(max(Bs)*1e6)): Bp.append(float(k)*1e-6) npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM(PLT['aq'],Bs,TRMs,Bp,Mp,NLpars,rec['magic_experiment_name']) pmagplotlib.drawFIGS(PLT) print 'Banc= ',float(NLpars['banc'])*1e6 trmTC={} for key in TrmRec.keys(): trmTC[key]=TrmRec[key] # copy of info from thellier_specimens record trmTC['specimen_int']='%8.3e'%(NLpars['banc']) trmTC['magic_method_codes']=TrmRec["magic_method_codes"]+":DA-NL" PmagSpecRecs.append(trmTC) ans=raw_input("Return for next specimen, s[a]ve plot ") if ans=='a': Name={'aq':rec['er_specimen_name']+'_TRM.svg'} pmagplotlib.saveP(PLT,Name) specimen+=1 pmag.magic_write(output,PmagSpecRecs,'pmag_specimens')
def main(): """ NAME quick_hyst.py DESCRIPTION makes plots of hysteresis data SYNTAX quick_hyst.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specify input file, default is magic_measurements.txt -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg] """ args=sys.argv PLT=1 plots=0 user,meas_file="","magic_measurements.txt" pltspec="" dir_path='.' fmt='png' verbose=pmagplotlib.verbose print 'verbose?', verbose version_num=pmag.get_version() if '-WD' in args: ind=args.index('-WD') dir_path=args[ind+1] if "-h" in args: print main.__doc__ sys.exit() if "-usr" in args: ind=args.index("-usr") user=args[ind+1] if '-f' in args: ind=args.index("-f") meas_file=args[ind+1] if '-sav' in args: verbose=0 plots=1 if '-spc' in args: ind=args.index("-spc") pltspec= args[ind+1] verbose=0 plots=1 if '-fmt' in args: ind=args.index("-fmt") fmt=args[ind+1] meas_file=dir_path+'/'+meas_file print 'verbose', verbose # # meas_data,file_type=pmag.magic_read(meas_file) if file_type!='magic_measurements': print main.__doc__ print 'bad file' sys.exit() # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs,RemRecs=[],[] HDD={} HDD['hyst']=1 pmagplotlib.plot_init(HDD['hyst'],5,5) # # get list of unique experiment names and specimen names # experiment_names,sids=[],[] hyst_data=pmag.get_dictitem(meas_data,'magic_method_codes','LP-HYS','has') # get all hysteresis data for rec in hyst_data: if 'er_synthetic_name' in rec.keys() and rec['er_synthetic_name']!="": rec['er_specimen_name']=rec['er_synthetic_name'] if rec['magic_experiment_name'] not in experiment_names:experiment_names.append(rec['magic_experiment_name']) if rec['er_specimen_name'] not in sids:sids.append(rec['er_specimen_name']) if 'measurement_temp' not in rec.keys(): rec['measurement_temp']='300' # assume room T measurement unless otherwise specified # k=0 if pltspec!="": k=sids.index(pltspec) intlist=['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass'] while k < len(sids): locname,site,sample,synth='','','','' s=sids[k] hmeths=[] if verbose:print s, k+1 , 'out of ',len(sids) # # B,M=[],[] #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data spec=pmag.get_dictitem(hyst_data,'er_specimen_name',s,'T') # get all measurements for this specimen if 'er_location_name' in spec[0].keys(): locname=spec[0]['er_location_name'] if 'er_site_name' in spec[0].keys(): site=spec[0]['er_site_name'] if 'er_sample_name' in spec[0].keys(): sample=spec[0]['er_sample_name'] if 'er_synthetic_name' in spec[0].keys(): synth=spec[0]['er_synthetic_name'] for m in intlist: meas_data=pmag.get_dictitem(spec,m,'','F') # get all non-blank data for this specimen if len(meas_data)>0: break c=['k-','b-','c-','g-','m-','r-','y-'] cnum=0 if len(meas_data)>0: Temps=[] xlab,ylab,title='','','' for rec in meas_data: if rec['measurement_temp'] not in Temps:Temps.append(rec['measurement_temp']) for t in Temps: print 'working on t: ',t t_data=pmag.get_dictitem(meas_data,'measurement_temp',t,'T') B,M=[],[] for rec in t_data: B.append(float(rec['measurement_lab_field_dc'])) M.append(float(rec[m])) # now plot the hysteresis curve(s) # if len(B)>0: B=numpy.array(B) M=numpy.array(M) if t==Temps[-1]: xlab='Field (T)' ylab=m title='Hysteresis: '+s if t==Temps[0]: pmagplotlib.clearFIG(HDD['hyst']) pmagplotlib.plotXY(HDD['hyst'],B,M,sym=c[cnum],xlab=xlab,ylab=ylab,title=title) pmagplotlib.plotXY(HDD['hyst'],[1.1*B.min(),1.1*B.max()],[0,0],sym='k-',xlab=xlab,ylab=ylab,title=title) pmagplotlib.plotXY(HDD['hyst'],[0,0],[1.1*M.min(),1.1*M.max()],sym='k-',xlab=xlab,ylab=ylab,title=title) if verbose:pmagplotlib.drawFIGS(HDD) cnum+=1 if cnum==len(c):cnum=0 # files={} if plots: if pltspec!="":s=pltspec files={} for key in HDD.keys(): if synth=='': files[key]="LO:_"+locname+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt else: files[key]='SY:_'+synth+'_TY:_'+key+'_.'+fmt pmagplotlib.saveP(HDD,files) if pltspec!="":sys.exit() if verbose: pmagplotlib.drawFIGS(HDD) ans=raw_input("S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ") if ans=="a": files={} for key in HDD.keys(): files[key]="LO:_"+locname+'_SI:_'+site+'_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt pmagplotlib.saveP(HDD,files) if ans=='':k+=1 if ans=="p": del HystRecs[-1] k-=1 if ans=='q': print "Good bye" sys.exit() if ans=='s': keepon=1 specimen=raw_input('Enter desired specimen name (or first part there of): ') while keepon==1: try: k =sids.index(specimen) keepon=0 except: tmplist=[] for qq in range(len(sids)): if specimen in sids[qq]:tmplist.append(sids[qq]) print specimen," not found, but this was: " print tmplist specimen=raw_input('Select one or try again\n ') k =sids.index(specimen) else: k+=1 if len(B)==0: if verbose:print 'skipping this one - no hysteresis data' k+=1
def main(): """ NAME cont_rot.py DESCRIPTION rotates continental fragments according to specified Euler pole SYNTAX cont_rot.py [command line options] OPTIONS -h prints help and quits -con [af, congo, kala, aus, balt, eur, ind, sam, ant, grn, lau, nam, gond] , specify colon delimited list of continents to be displayed, e.g., af, af:aus], etc -age use finite rotations of Torsvik et al. 2008 for specific age (5 Ma increments <325Ma) rotates to paleomagnetic reference frame available conts: [congo kala aus eur ind sam ant grn nam] -sac include rotation of south african craton to pmag reference -sym [ro, bs, g^, r., b-, etc.] [1,5,10] symbol and size for continent colors are r=red,b=blue,g=green, etc. symbols are '.' for points, ^, for triangle, s for square, etc. -, for lines, -- for dotted lines, see matplotlib online documentation for plot() -eye ELAT ELON [specify eyeball location] -pfr PLAT PLON OMEGA [specify pole of finite rotation lat,lon and degrees] -ffr FFILE, specifies series of finite rotations vector in tab delimited file -sr treat poles as sequential rotations -fpp PFILE, specifies series of paleopoles from which euler poles can be calculated: vector in tab delimited file -pt LAT LON, specify a point to rotate along with continent -fpt PTFILE, specifies file with a series of points to be plotted -res [c,l,i,h] specify resolution (crude, low, intermediate, high] -fmt [png,jpg,svg,pdf] format for saved figure - pdf is default -sav saves plots and quits -prj PROJ, specify one of the supported projections: (see basemap.py online documentation) aeqd = Azimuthal Equidistant poly = Polyconic gnom = Gnomonic moll = Mollweide tmerc = Transverse Mercator nplaea = North-Polar Lambert Azimuthal mill = Miller Cylindrical merc = Mercator stere = Stereographic npstere = North-Polar Stereographic geos = Geostationary laea = Lambert Azimuthal Equal Area sinu = Sinusoidal spstere = South-Polar Stereographic lcc = Lambert Conformal npaeqd = North-Polar Azimuthal Equidistant eqdc = Equidistant Conic cyl = Cylindrical Equidistant omerc = Oblique Mercator aea = Albers Equal Area spaeqd = South-Polar Azimuthal Equidistant ortho = Orthographic cass= Cassini-Soldner splaea = South-Polar Lambert Azimuthal robin = Robinson DEFAULTS con: nam res: c prj: mollweide ELAT,ELON = 0,0 NB: high resolution or lines can be very slow """ dir_path='.' ocean=0 res='c' proj='moll' euler_file='' Conts=[] Poles=[] PTS=[] lat_0,lon_0=0.,0. fmt='pdf' sym='r.' symsize=5 plot=0 SEQ,age,SAC=0,0,0 rconts=['af','congo','kala','aus','eur','ind','sam','ant','grn','nam'] if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path=sys.argv[ind+1] if '-h' in sys.argv: print main.__doc__ sys.exit() if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-con' in sys.argv: ind = sys.argv.index('-con') Conts=sys.argv[ind+1].split(':') if '-age' in sys.argv: ind = sys.argv.index('-age') age=int(sys.argv[ind+1]) if age%5!=0 and age>320: print main.__doc__ print 'age must be multiple of 5 less than 325' sys.exit() import pmagpy.frp as frp if '-res' in sys.argv: ind = sys.argv.index('-res') res=sys.argv[ind+1] if res!= 'c' and res!='l': print 'this resolution will take a while - be patient' if '-prj' in sys.argv: ind = sys.argv.index('-prj') proj=sys.argv[ind+1] if '-sav' in sys.argv: plot=1 if '-eye' in sys.argv: ind = sys.argv.index('-eye') lat_0=float(sys.argv[ind+1]) lon_0=float(sys.argv[ind+2]) if '-pt' in sys.argv: ind = sys.argv.index('-pt') pt_lat=float(sys.argv[ind+1]) pt_lon=float(sys.argv[ind+2]) PTS.append([pt_lat,pt_lon]) if '-sym' in sys.argv: ind = sys.argv.index('-sym') sym=sys.argv[ind+1] symsize=int(sys.argv[ind+2]) # if '-rsym' in sys.argv: # ind = sys.argv.index('-rsym') # rsym=sys.argv[ind+1] # rsymsize=int(sys.argv[ind+2]) if '-sr' in sys.argv: SEQ=1 if '-sac' in sys.argv: SAC=1 if '-pfr' in sys.argv: ind = sys.argv.index('-pfr') Poles.append([float(sys.argv[ind+1]),float(sys.argv[ind+2]),float(sys.argv[ind+3])]) elif '-ffr' in sys.argv: ind = sys.argv.index('-ffr') file=dir_path+'/'+sys.argv[ind+1] f=open(file,'rU') edata=f.readlines() for line in edata: rec=line.split() Poles.append([float(rec[0]),float(rec[1]),float(rec[2])]) elif '-fpp' in sys.argv: ind = sys.argv.index('-fpp') file=dir_path+'/'+sys.argv[ind+1] f=open(file,'rU') pdata=f.readlines() for line in pdata: rec=line.split() # transform paleopole to Euler pole taking shortest route Poles.append([0.,float(rec[1])-90.,90.-float(rec[0])]) if '-fpt' in sys.argv: ind = sys.argv.index('-fpt') file=dir_path+'/'+sys.argv[ind+1] f=open(file,'rU') ptdata=f.readlines() for line in ptdata: rec=line.split() PTS.append([float(rec[0]),float(rec[1])]) FIG={'map':1} pmagplotlib.plot_init(FIG['map'],6,6) # read in er_sites file if res=='c':skip=8 if res=='l':skip=5 if res=='i':skip=2 if res=='h':skip=1 cnt=0 Opts={'latmin':-90,'latmax':90,'lonmin':0.,'lonmax':360.,'lat_0':lat_0,'lon_0':lon_0,'proj':proj,'sym':sym,'symsize':3,'pltgrid':0,'res':res,'boundinglat':0.} if proj=='merc': Opts['latmin']=-70 Opts['latmax']=70 Opts['lonmin']=-180 Opts['lonmax']=180 pmagplotlib.plotMAP(FIG['map'],[],[],Opts) # plot the basemap Opts['pltgrid']=-1 # turn off replotting of gridlines if '-pt' in sys.argv: Opts['sym']=sym Opts['symsize']=symsize pmagplotlib.plotMAP(FIG['map'],[pt_lat],[pt_lon],Opts) if plot==0:pmagplotlib.drawFIGS(FIG) for cont in Conts: Opts['sym']=sym lats,lons=[],[] if age!=0: Poles=[] rcont=cont if rcont not in rconts: print main.__doc__ print rcont print 'continents must be one of following: ' print rconts sys.exit() if rcont=='congo':rcont='nwaf' if rcont=='kala':rcont='neaf' if rcont=='sam':rcont='sac' if rcont=='ant':rcont='eant' if rcont!='af': Poles.append(frp.get_pole(rcont,age)) else: Poles.append([0,0,0]) if SAC==1:Poles.append(frp.get_pole('saf',age)) SEQ=1 if Poles[-1]=='NONE': print 'continent does not exist for rotation, try again ' sys.exit() data=continents.get_continent(cont+'.asc') for line in data: if float(line[0])==0 and float(line[1])==0:line[0]='100.' # change stupid 0,0s to delimeters with lat=100 if float(line[0])>90: lats.append(float(line[0])) lons.append(float(line[1])) elif cnt%skip==0: lats.append(float(line[0])) lons.append(float(line[1])) cnt+=1 if len(lats)>0 and len(Poles)==0: pmagplotlib.plotMAP(FIG['map'],lats,lons,Opts) if plot==0:pmagplotlib.drawFIGS(FIG) newlats,newlons=[],[] for lat in lats:newlats.append(lat) for lon in lons:newlons.append(lon) Opts['pltgrid']=-1 # turns off replotting of meridians and parallels for pole in Poles: Rlats,Rlons=pmag.PTrot(pole,newlats,newlons) Opts['sym']=sym Opts['symsize']=3 if SEQ==0: pmagplotlib.plotMAP(FIG['map'],Rlats,Rlons,Opts) elif pole==Poles[-1]: # plot only last pole for sequential rotations pmagplotlib.plotMAP(FIG['map'],Rlats,Rlons,Opts) if plot==0:pmagplotlib.drawFIGS(FIG) if SEQ==1: # treat poles as sequential rotations newlats,newlons=[],[] for lat in Rlats:newlats.append(lat) for lon in Rlons:newlons.append(lon) for pt in PTS: pt_lat=pt[0] pt_lon=pt[1] Opts['sym']='r*' Opts['symsize']=5 pmagplotlib.plotMAP(FIG['map'],[pt[0]],[pt[1]],Opts) if plot==0:pmagplotlib.drawFIGS(FIG) Opts['pltgrid']=-1 # turns off replotting of meridians and parallels for pole in Poles: Opts['sym']=sym Opts['symsize']=symsize Rlats,Rlons=pmag.PTrot(pole,[pt_lat],[pt_lon]) print Rlats,Rlons pmagplotlib.plotMAP(FIG['map'],Rlats,Rlons,Opts) if plot==0:pmagplotlib.drawFIGS(FIG) Opts['sym']='g^' Opts['symsize']=5 pmagplotlib.plotMAP(FIG['map'],[pole[0]],[pole[1]],Opts) if plot==0:pmagplotlib.drawFIGS(FIG) files={} for key in FIG.keys(): files[key]='Cont_rot'+'.'+fmt if plot==1: pmagplotlib.saveP(FIG,files) sys.exit() if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='Site Map' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) else: pmagplotlib.drawFIGS(FIG) ans=raw_input(" S[a]ve to save plot, Return to quit: ") if ans=="a": pmagplotlib.saveP(FIG,files)
def main(): """ NAME zeq_magic.py DESCRIPTION reads in magic_measurements formatted file, makes plots of remanence decay during demagnetization experiments. Reads in prior interpretations saved in a pmag_specimens formatted file and allows re-interpretations of best-fit lines and planes and saves (revised or new) interpretations in a pmag_specimens file. interpretations are saved in the coordinate system used. Also allows judicious editting of measurements to eliminate "bad" measurements. These are marked as such in the magic_measurements input file. they are NOT deleted, just ignored. SYNTAX zeq_magic.py [command line options] OPTIONS -h prints help message and quits -f MEASFILE: sets magic_measurements format input file, default: magic_measurements.txt -fsp SPECFILE: sets pmag_specimens format file with prior interpreations, default: zeq_specimens.txt -Fp PLTFILE: sets filename for saved plot, default is name_type.fmt (where type is zijd, eqarea or decay curve) -crd [s,g,t]: sets coordinate system, g=geographic, t=tilt adjusted, default: specimen coordinate system -fsa SAMPFILE: sets er_samples format file with orientation information, default: er_samples.txt -spc SPEC plots single specimen SPEC, saves plot with specified format with optional -dir settings and quits -dir [L,P,F][beg][end]: sets calculation type for principal component analysis, default is none beg: starting step for PCA calculation end: ending step for PCA calculation [L,P,F]: calculation type for line, plane or fisher mean must be used with -spc option -fmt FMT: set format of saved plot [png,svg,jpg] -A: suppresses averaging of replicate measurements, default is to average -sav: saves all plots without review SCREEN OUTPUT: Specimen, N, a95, StepMin, StepMax, Dec, Inc, calculation type """ # initialize some variables doave,e,b=1,0,0 # average replicates, initial end and beginning step plots,coord=0,'s' noorient=0 version_num=pmag.get_version() verbose=pmagplotlib.verbose beg_pca,end_pca,direction_type="","",'l' calculation_type,fmt="","svg" user,spec_keys,locname="",[],'' plot_file="" sfile="" plot_file="" PriorRecs=[] # empty list for prior interpretations backup=0 specimen="" # can skip everything and just plot one specimen with bounds e,b if '-h' in sys.argv: print main.__doc__ sys.exit() if '-WD' in sys.argv: ind=sys.argv.index('-WD') dir_path=sys.argv[ind+1] else: dir_path='.' inspec=dir_path+'/'+'zeq_specimens.txt' meas_file,geo,tilt,ask,samp_file=dir_path+'/magic_measurements.txt',0,0,0,dir_path+'/er_samples.txt' if '-f' in sys.argv: ind=sys.argv.index('-f') meas_file=dir_path+'/'+sys.argv[ind+1] if '-fsp' in sys.argv: ind=sys.argv.index('-fsp') inspec=dir_path+'/'+sys.argv[ind+1] if '-fsa' in sys.argv: ind=sys.argv.index('-fsa') samp_file=dir_path+'/'+sys.argv[ind+1] sfile='ok' if '-crd' in sys.argv: ind=sys.argv.index('-crd') coord=sys.argv[ind+1] if coord=='g' or coord=='t': samp_data,file_type=pmag.magic_read(samp_file) if file_type=='er_samples':sfile='ok' geo=1 if coord=='t':tilt=1 if '-spc' in sys.argv: ind=sys.argv.index('-spc') specimen=sys.argv[ind+1] if '-dir' in sys.argv: ind=sys.argv.index('-dir') direction_type=sys.argv[ind+1] beg_pca=int(sys.argv[ind+2]) end_pca=int(sys.argv[ind+3]) if direction_type=='L':calculation_type='DE-BFL' if direction_type=='P':calculation_type='DE-BFP' if direction_type=='F':calculation_type='DE-FM' if '-Fp' in sys.argv: ind=sys.argv.index('-Fp') plot_file=dir_path+'/'+sys.argv[ind+1] if '-A' in sys.argv: doave=0 if '-sav' in sys.argv: plots=1 verbose=0 if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] # first_save=1 meas_data,file_type=pmag.magic_read(meas_file) changeM,changeS=0,0 # check if data or interpretations have changed if file_type != 'magic_measurements': print file_type print file_type,"This is not a valid magic_measurements file " sys.exit() for rec in meas_data: if "magic_method_codes" not in rec.keys(): rec["magic_method_codes"]="" methods="" tmp=rec["magic_method_codes"].replace(" ","").split(":") for meth in tmp: methods=methods+meth+":" rec["magic_method_codes"]=methods[:-1] # get rid of annoying spaces in Anthony's export files if "magic_instrument_codes" not in rec.keys() :rec["magic_instrument_codes"]="" PriorSpecs=[] PriorRecs,file_type=pmag.magic_read(inspec) if len(PriorRecs)==0: if verbose:print "starting new file ",inspec for Rec in PriorRecs: if 'magic_software_packages' not in Rec.keys():Rec['magic_software_packages']="" if Rec['er_specimen_name'] not in PriorSpecs: if 'specimen_comp_name' not in Rec.keys():Rec['specimen_comp_name']="A" PriorSpecs.append(Rec['er_specimen_name']) else: if 'specimen_comp_name' not in Rec.keys():Rec['specimen_comp_name']="A" if "magic_method_codes" in Rec.keys(): methods=[] tmp=Rec["magic_method_codes"].replace(" ","").split(":") for meth in tmp: methods.append(meth) if 'DE-FM' in methods: Rec['calculation_type']='DE-FM' # this won't be imported but helps if 'DE-BFL' in methods: Rec['calculation_type']='DE-BFL' if 'DE-BFL-A' in methods: Rec['calculation_type']='DE-BFL-A' if 'DE-BFL-O' in methods: Rec['calculation_type']='DE-BFL-O' if 'DE-BFP' in methods: Rec['calculation_type']='DE-BFP' else: Rec['calculation_type']='DE-BFL' # default is to assume a best-fit line # # get list of unique specimen names # sids=pmag.get_specs(meas_data) # # set up plots, angle sets X axis to horizontal, direction_type 'l' is best-fit line # direction_type='p' is great circle # # # draw plots for sample s - default is just to step through zijderveld diagrams # # # define figure numbers for equal area, zijderveld, # and intensity vs. demagnetiztion step respectively ZED={} ZED['eqarea'],ZED['zijd'], ZED['demag']=1,2,3 pmagplotlib.plot_init(ZED['eqarea'],5,5) pmagplotlib.plot_init(ZED['zijd'],6,5) pmagplotlib.plot_init(ZED['demag'],5,5) save_pca=0 if specimen=="": k = 0 else: k=sids.index(specimen) angle,direction_type="","" setangle=0 CurrRecs=[] while k < len(sids): CurrRecs=[] if setangle==0:angle="" method_codes,inst_code=[],"" s=sids[k] PmagSpecRec={} PmagSpecRec["er_analyst_mail_names"]=user PmagSpecRec['magic_software_packages']=version_num PmagSpecRec['specimen_description']="" PmagSpecRec['magic_method_codes']="" if verbose and s!="":print s, k , 'out of ',len(sids) # # collect info for the PmagSpecRec dictionary # s_meas=pmag.get_dictitem(meas_data,'er_specimen_name',s,'T') # fish out this specimen s_meas=pmag.get_dictitem(s_meas,'magic_method_codes','Z','has') # fish out zero field steps if len(s_meas)>0: for rec in s_meas: # fix up a few things for the output record PmagSpecRec["magic_instrument_codes"]=rec["magic_instrument_codes"] # copy over instruments PmagSpecRec["er_citation_names"]="This study" PmagSpecRec["er_specimen_name"]=s PmagSpecRec["er_sample_name"]=rec["er_sample_name"] PmagSpecRec["er_site_name"]=rec["er_site_name"] PmagSpecRec["er_location_name"]=rec["er_location_name"] locname=rec['er_location_name'] if 'er_expedition_name' in rec.keys(): PmagSpecRec["er_expedition_name"]=rec["er_expedition_name"] PmagSpecRec["magic_method_codes"]=rec["magic_method_codes"] if "magic_experiment_name" not in rec.keys(): PmagSpecRec["magic_experiment_names"]="" else: PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"] break # # find the data from the meas_data file for this specimen # data,units=pmag.find_dmag_rec(s,meas_data) PmagSpecRec["measurement_step_unit"]= units u=units.split(":") if "T" in units:PmagSpecRec["magic_method_codes"]=PmagSpecRec["magic_method_codes"]+":LP-DIR-AF" if "K" in units:PmagSpecRec["magic_method_codes"]=PmagSpecRec["magic_method_codes"]+":LP-DIR-T" if "J" in units:PmagSpecRec["magic_method_codes"]=PmagSpecRec["magic_method_codes"]+":LP-DIR-M" # # find prior interpretation # if len(CurrRecs)==0: # check if already in beg_pca,end_pca="","" calculation_type="" if inspec !="": if verbose: print " looking up previous interpretations..." precs=pmag.get_dictitem(PriorRecs,'er_specimen_name',s,'T') # get all the prior recs with this specimen name precs=pmag.get_dictitem(precs,'magic_method_codes','LP-DIR','has') # get the directional data PriorRecs=pmag.get_dictitem(PriorRecs,'er_specimen_name',s,'F') # take them all out of prior recs # get the ones that meet the current coordinate system for prec in precs: if 'specimen_tilt_correction' not in prec.keys() or prec['specimen_tilt_correction']=='-1': crd='s' elif prec['specimen_tilt_correction']=='0': crd='g' elif prec['specimen_tilt_correction']=='100': crd='t' else: crd='?' CurrRec={} for key in prec.keys():CurrRec[key]=prec[key] CurrRecs.append(CurrRec) # put in CurrRecs method_codes= CurrRec["magic_method_codes"].replace(" ","").split(':') calculation_type='DE-BFL' if 'DE-FM' in method_codes: calculation_type='DE-FM' if 'DE-BFP' in method_codes: calculation_type='DE-BFP' if 'DE-BFL-A' in method_codes: calculation_type='DE-BFL-A' if 'specimen_dang' not in CurrRec.keys(): if verbose:print 'Run mk_redo.py and zeq_magic_redo.py to get the specimen_dang values' CurrRec['specimen_dang']=-1 if calculation_type!='DE-FM' and crd==coord: # not a fisher mean if verbose:print "Specimen N MAD DANG start end dec inc type component coordinates" if units=='K': if verbose:print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s %s %s \n' % (CurrRec["er_specimen_name"],int(CurrRec["specimen_n"]),float(CurrRec["specimen_mad"]),float(CurrRec["specimen_dang"]),float(CurrRec["measurement_step_min"])-273,float(CurrRec["measurement_step_max"])-273,float(CurrRec["specimen_dec"]),float(CurrRec["specimen_inc"]),calculation_type,CurrRec['specimen_comp_name'],crd) elif units=='T': if verbose:print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s %s %s \n' % (CurrRec["er_specimen_name"],int(CurrRec["specimen_n"]),float(CurrRec["specimen_mad"]),float(CurrRec["specimen_dang"]),float(CurrRec["measurement_step_min"])*1e3,float(CurrRec["measurement_step_max"])*1e3,float(CurrRec["specimen_dec"]),float(CurrRec["specimen_inc"]),calculation_type,CurrRec['specimen_comp_name'],crd) elif 'T' in units and 'K' in units: if float(CurrRec['measurement_step_min'])<1.0 : min=float(CurrRec['measurement_step_min'])*1e3 else: min=float(CurrRec['measurement_step_min'])-273 if float(CurrRec['measurement_step_max'])<1.0 : max=float(CurrRec['measurement_step_max'])*1e3 else: max=float(CurrRec['measurement_step_max'])-273 if verbose:print '%s %i %7.1f %i %i %7.1f %7.1f %7.1f, %s %s\n' % (CurrRec["er_specimen_name"],int(CurrRec["specimen_n"]),float(CurrRec["specimen_mad"]),float(CurrRec['specimen_dang']),min,max,float(CurrRec["specimen_dec"]),float(CurrRec["specimen_inc"]),calculation_type,crd) elif 'J' in units: if verbose:print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s %s %s \n' % (CurrRec["er_specimen_name"],int(CurrRec["specimen_n"]),float(CurrRec["specimen_mad"]),float(CurrRec['specimen_dang']),float(CurrRec["measurement_step_min"]),float(CurrRec["measurement_step_max"]),float(CurrRec["specimen_dec"]),float(CurrRec["specimen_inc"]),calculation_type,CurrRec['specimen_comp_name'],crd) elif calculation_type=='DE-FM' and crd==coord: # fisher mean if verbose:print "Specimen a95 DANG start end dec inc type component coordinates" if units=='K': if verbose:print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %s %s %s \n' % (CurrRec["er_specimen_name"],int(CurrRec["specimen_n"]),float(CurrRec["specimen_alpha95"]),float(CurrRec["measurement_step_min"])-273,float(CurrRec["measurement_step_max"])-273,float(CurrRec["specimen_dec"]),float(CurrRec["specimen_inc"]),calculation_type,CurrRec['specimen_comp_name'],crd) elif units=='T': if verbose:print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %s %s %s \n' % (CurrRec["er_specimen_name"],int(CurrRec["specimen_n"]),float(CurrRec["specimen_alpha95"]),float(CurrRec["measurement_step_min"])*1e3,float(CurrRec["measurement_step_max"])*1e3,float(CurrRec["specimen_dec"]),float(CurrRec["specimen_inc"]),calculation_type,CurrRec['specimen_comp_name'],crd) elif 'T' in units and 'K' in units: if float(CurrRec['measurement_step_min'])<1.0 : min=float(CurrRec['measurement_step_min'])*1e3 else: min=float(CurrRec['measurement_step_min'])-273 if float(CurrRec['measurement_step_max'])<1.0 : max=float(CurrRec['measurement_step_max'])*1e3 else: max=float(CurrRec['measurement_step_max'])-273 if verbose:print '%s %i %7.1f %i %i %7.1f %7.1f %s %s \n' % (CurrRec["er_specimen_name"],int(CurrRec["specimen_n"]),float(CurrRec["specimen_alpha95"]),min,max,float(CurrRec["specimen_dec"]),float(CurrRec["specimen_inc"]),calculation_type,crd) elif 'J' in units: if verbose:print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %s %s %s \n' % (CurrRec["er_specimen_name"],int(CurrRec["specimen_n"]),float(CurrRec["specimen_mad"]),float(CurrRec["measurement_step_min"]),float(CurrRec["measurement_step_max"]),float(CurrRec["specimen_dec"]),float(CurrRec["specimen_inc"]),calculation_type,CurrRec['specimen_comp_name'],crd) if len(CurrRecs)==0:beg_pca,end_pca="","" datablock=data noskip=1 if len(datablock) <3: noskip=0 if backup==0: k+=1 else: k-=1 if len(CurrRecs)>0: for rec in CurrRecs: PriorRecs.append(rec) CurrRecs=[] else: backup=0 if noskip: # # find replicate measurements at given treatment step and average them # # step_meth,avedata=pmag.vspec(data) # if len(avedata) != len(datablock): # if doave==1: # method_codes.append("DE-VM") # datablock=avedata # # # do geo or stratigraphic correction now # if geo==1: # # find top priority orientation method orient,az_type=pmag.get_orient(samp_data,PmagSpecRec["er_sample_name"]) if az_type=='SO-NO': if verbose: print "no orientation data for ",s orient["sample_azimuth"]=0 orient["sample_dip"]=0 noorient=1 method_codes.append("SO-NO") orient["sample_azimuth"]=0 orient["sample_dip"]=0 orient["sample_bed_dip_azimuth"]=0 orient["sample_bed_dip"]=0 noorient=1 method_codes.append("SO-NO") else: noorient=0 # # if stratigraphic selected, get stratigraphic correction # tiltblock,geoblock=[],[] for rec in datablock: d_geo,i_geo=pmag.dogeo(rec[1],rec[2],float(orient["sample_azimuth"]),float(orient["sample_dip"])) geoblock.append([rec[0],d_geo,i_geo,rec[3],rec[4],rec[5],rec[6]]) if tilt==1 and "sample_bed_dip" in orient.keys() and float(orient['sample_bed_dip'])!=0: d_tilt,i_tilt=pmag.dotilt(d_geo,i_geo,float(orient["sample_bed_dip_direction"]),float(orient["sample_bed_dip"])) tiltblock.append([rec[0],d_tilt,i_tilt,rec[3],rec[4],rec[5],rec[6]]) if tilt==1: plotblock=tiltblock if geo==1 and tilt==0:plotblock=geoblock if geo==0 and tilt==0: plotblock=datablock # # set the end pca point to last point if not set if e==0 or e>len(plotblock)-1: e=len(plotblock)-1 if angle=="": angle=plotblock[0][1] # rotate to NRM declination title=s+'_s' if geo==1 and tilt==0 and noorient!=1:title=s+'_g' if tilt==1 and noorient!=1:title=s+'_t' pmagplotlib.plotZED(ZED,plotblock,angle,title,units) if verbose:pmagplotlib.drawFIGS(ZED) if len(CurrRecs)!=0: for prec in CurrRecs: if 'calculation_type' not in prec.keys(): calculation_type='' else: calculation_type=prec["calculation_type"] direction_type=prec["specimen_direction_type"] if calculation_type !="": beg_pca,end_pca="","" for j in range(len(datablock)): if data[j][0]==float(prec["measurement_step_min"]):beg_pca=j if data[j][0]==float(prec["measurement_step_max"]):end_pca=j if beg_pca=="" or end_pca=="": if verbose: print "something wrong with prior interpretation " break if calculation_type!="": if beg_pca=="":beg_pca=0 if end_pca=="":end_pca=len(plotblock)-1 if geo==1 and tilt==0: mpars=pmag.domean(geoblock,beg_pca,end_pca,calculation_type) if mpars["specimen_direction_type"]!="Error": pmagplotlib.plotDir(ZED,mpars,geoblock,angle) if verbose:pmagplotlib.drawFIGS(ZED) if geo==1 and tilt==1: mpars=pmag.domean(tiltblock,beg_pca,end_pca,calculation_type) if mpars["specimen_direction_type"]!="Error": pmagplotlib.plotDir(ZED,mpars,tiltblock,angle) if verbose:pmagplotlib.drawFIGS(ZED) if geo==0 and tilt==0: mpars=pmag.domean(datablock,beg_pca,end_pca,calculation_type) if mpars["specimen_direction_type"]!="Error": pmagplotlib.plotDir(ZED,mpars,plotblock,angle) if verbose:pmagplotlib.drawFIGS(ZED) # # print out data for this sample to screen # recnum=0 for plotrec in plotblock: if units=='T' and verbose: print '%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum,plotrec[0]*1e3," mT",plotrec[3],plotrec[1],plotrec[2],plotrec[6]) if units=="K" and verbose: print '%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum,plotrec[0]-273,' C',plotrec[3],plotrec[1],plotrec[2],plotrec[6]) if units=="J" and verbose: print '%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum,plotrec[0],' J',plotrec[3],plotrec[1],plotrec[2],plotrec[6]) if 'K' in units and 'T' in units: if plotrec[0]>=1. and verbose: print '%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum,plotrec[0]-273,' C',plotrec[3],plotrec[1],plotrec[2],plotrec[6]) if plotrec[0]<1. and verbose: print '%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum,plotrec[0]*1e3," mT",plotrec[3],plotrec[1],plotrec[2],plotrec[6]) recnum += 1 if specimen!="": if plot_file=="": basename=locname+'_'+s else: basename=plot_file files={} for key in ZED.keys(): files[key]=basename+'_'+key+'.'+fmt pmagplotlib.saveP(ZED,files) sys.exit() else: # interactive if plots==0: ans='b' k+=1 changeS=0 while ans != "": if len(CurrRecs)==0: print """ g/b: indicates good/bad measurement. "bad" measurements excluded from calculation set s[a]ve plot, [b]ounds for pca and calculate, [p]revious, [s]pecimen, change [h]orizontal projection angle, change [c]oordinate systems, [e]dit data, [q]uit: """ else: print """ g/b: indicates good/bad measurement. "bad" measurements excluded from calculation set s[a]ve plot, [b]ounds for pca and calculate, [p]revious, [s]pecimen, change [h]orizontal projection angle, change [c]oordinate systems, [d]elete current interpretation(s), [e]dit data, [q]uit: """ ans=raw_input('<Return> for next specimen \n') setangle=0 if ans=='d': # delete this interpretation CurrRecs=[] k-=1 # replot same specimen ans="" changeS=1 if ans=='q': if changeM==1: ans=raw_input('Save changes to magic_measurements.txt? y/[n] ') if ans=='y': pmag.magic_write(meas_file,meas_data,'magic_measurements') print "Good bye" sys.exit() if ans=='a': if plot_file=="": basename=locname+'_'+s+'_' else: basename=plot_file files={} for key in ZED.keys(): files[key]=basename+'_'+coord+'_'+key+'.'+fmt pmagplotlib.saveP(ZED,files) ans="" if ans=='p': k-=2 ans="" backup=1 if ans=='c': k-=1 # replot same block if tilt==0 and geo ==1:print "You are currently viewing geographic coordinates " if tilt==1 and geo ==1:print "You are currently viewing stratigraphic coordinates " if tilt==0 and geo ==0: print "You are currently viewing sample coordinates " print "\n Which coordinate system do you wish to view? " coord=raw_input(" <Return> specimen, [g] geographic, [t] tilt corrected ") if coord=="g":geo,tilt=1,0 if coord=="t": geo=1 tilt=1 if coord=="": coord='s' geo=0 tilt=0 if geo==1 and sfile=="": samp_file=raw_input(" Input er_samples file for sample orientations [er_samples.txt] " ) if samp_file=="":samp_file="er_samples.txt" samp_data,file_type=pmag.magic_read(samp_file) if file_type != 'er_samples': print file_type print "This is not a valid er_samples file - coordinate system not changed" else: sfile="ok" ans="" if ans=='s': keepon=1 sample=raw_input('Enter desired specimen name (or first part there of): ') while keepon==1: try: k =sids.index(sample) keepon=0 except: tmplist=[] for qq in range(len(sids)): if sample in sids[qq]:tmplist.append(sids[qq]) print sample," not found, but this was: " print tmplist sample=raw_input('Select one or try again\n ') angle,direction_type="","" setangle=0 ans="" if ans=='h': k-=1 angle=raw_input("Enter desired declination for X axis 0-360 ") angle=float(angle) if angle==0:angle=0.001 s=sids[k] setangle=1 ans="" if ans=='e': k-=1 ans="" recnum=0 for plotrec in plotblock: if plotrec[0]<=200 and verbose: print '%s: %i %7.1f %s %8.3e %7.1f %7.1f ' % (plotrec[5], recnum,plotrec[0]*1e3," mT",plotrec[3],plotrec[1],plotrec[2]) if plotrec[0]>200 and verbose: print '%s: %i %7.1f %s %8.3e %7.1f %7.1f ' % (plotrec[5], recnum,plotrec[0]-273,' C',plotrec[3],plotrec[1],plotrec[2]) recnum += 1 answer=raw_input('Enter index of point to change from bad to good or vice versa: ') try: ind=int(answer) meas_data=pmag.mark_dmag_rec(s,ind,meas_data) changeM=1 except: 'bad entry, try again' if ans=='b': if end_pca=="":end_pca=len(plotblock)-1 if beg_pca=="":beg_pca=0 k-=1 # stay on same sample until through GoOn=0 while GoOn==0: print 'Enter index of first point for pca: ','[',beg_pca,']' answer=raw_input('return to keep default ') if answer != "": beg_pca=int(answer) print 'Enter index of last point for pca: ','[',end_pca,']' answer=raw_input('return to keep default ') try: end_pca=int(answer) if plotblock[beg_pca][5]=='b' or plotblock[end_pca][5]=='b': print "Can't select 'bad' measurement for PCA bounds -try again" end_pca=len(plotblock)-1 beg_pca=0 elif beg_pca >=0 and beg_pca<=len(plotblock)-2 and end_pca>0 and end_pca<len(plotblock): GoOn=1 else: print beg_pca,end_pca, " are bad entry of indices - try again" end_pca=len(plotblock)-1 beg_pca=0 except: print beg_pca,end_pca, " are bad entry of indices - try again" end_pca=len(plotblock)-1 beg_pca=0 GoOn=0 while GoOn==0: if calculation_type!="": print "Prior calculation type = ",calculation_type ct=raw_input('Enter new Calculation Type: best-fit line, plane or fisher mean [l]/p/f : ' ) if ct=="" or ct=="l": direction_type="l" calculation_type="DE-BFL" GoOn=1 elif ct=='p': direction_type="p" calculation_type="DE-BFP" GoOn=1 elif ct=='f': direction_type="l" calculation_type="DE-FM" GoOn=1 else: print "bad entry of calculation type: try again. " pmagplotlib.plotZED(ZED,plotblock,angle,s,units) if verbose:pmagplotlib.drawFIGS(ZED) if geo==1 and tilt==0: mpars=pmag.domean(geoblock,beg_pca,end_pca,calculation_type) if mpars['specimen_direction_type']=='Error':break PmagSpecRec["specimen_dec"]='%7.1f ' %(mpars["specimen_dec"]) PmagSpecRec["specimen_inc"]='%7.1f ' %(mpars["specimen_inc"]) if "SO-NO" not in method_codes: PmagSpecRec["specimen_tilt_correction"]='0' method_codes.append("DA-DIR-GEO") else: PmagSpecRec["specimen_tilt_correction"]='-1' pmagplotlib.plotDir(ZED,mpars,geoblock,angle) if verbose:pmagplotlib.drawFIGS(ZED) if geo==1 and tilt==1: mpars=pmag.domean(tiltblock,beg_pca,end_pca,calculation_type) if mpars['specimen_direction_type']=='Error':break PmagSpecRec["specimen_dec"]='%7.1f ' %(mpars["specimen_dec"]) PmagSpecRec["specimen_inc"]='%7.1f ' %(mpars["specimen_inc"]) if "SO-NO" not in method_codes: PmagSpecRec["specimen_tilt_correction"]='100' method_codes.append("DA-DIR-TILT") else: PmagSpecRec["specimen_tilt_correction"]='-1' pmagplotlib.plotDir(ZED,mpars,tiltblock,angle) if verbose:pmagplotlib.drawFIGS(ZED) if geo==0 and tilt==0: mpars=pmag.domean(datablock,beg_pca,end_pca,calculation_type) if mpars['specimen_direction_type']=='Error':break PmagSpecRec["specimen_dec"]='%7.1f ' %(mpars["specimen_dec"]) PmagSpecRec["specimen_inc"]='%7.1f ' %(mpars["specimen_inc"]) PmagSpecRec["specimen_tilt_correction"]='-1' pmagplotlib.plotDir(ZED,mpars,plotblock,angle) if verbose:pmagplotlib.drawFIGS(ZED) PmagSpecRec["measurement_step_min"]='%8.3e ' %(mpars["measurement_step_min"]) PmagSpecRec["measurement_step_max"]='%8.3e ' %(mpars["measurement_step_max"]) PmagSpecRec["specimen_correction"]='u' PmagSpecRec["specimen_dang"]='%7.1f ' %(mpars['specimen_dang']) print 'DANG: ',PmagSpecRec["specimen_dang"] if calculation_type!='DE-FM': PmagSpecRec["specimen_mad"]='%7.1f ' %(mpars["specimen_mad"]) PmagSpecRec["specimen_alpha95"]="" else: PmagSpecRec["specimen_alpha95"]='%7.1f ' %(mpars["specimen_alpha95"]) PmagSpecRec["specimen_mad"]="" PmagSpecRec["specimen_n"]='%i ' %(mpars["specimen_n"]) PmagSpecRec["specimen_direction_type"]=direction_type PmagSpecRec["calculation_type"]=calculation_type # redundant and won't be imported - just for convenience method_codes=PmagSpecRec["magic_method_codes"].split(':') if len(method_codes) != 0: methstring="" for meth in method_codes: ctype=meth.split('-') if 'DE' not in ctype:methstring=methstring+ ":" +meth # don't include old direction estimation methods methstring=methstring+':'+calculation_type PmagSpecRec["magic_method_codes"]= methstring.strip(':') print 'Method codes: ',PmagSpecRec['magic_method_codes'] if calculation_type!='DE-FM': if units=='K': print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f, %s \n' % (PmagSpecRec["er_specimen_name"],int(PmagSpecRec["specimen_n"]),float(PmagSpecRec["specimen_mad"]),float(PmagSpecRec["specimen_dang"]),float(PmagSpecRec["measurement_step_min"])-273,float(PmagSpecRec["measurement_step_max"])-273,float(PmagSpecRec["specimen_dec"]),float(PmagSpecRec["specimen_inc"]),calculation_type) elif units== 'T': print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f, %s \n' % (PmagSpecRec["er_specimen_name"],int(PmagSpecRec["specimen_n"]),float(PmagSpecRec["specimen_mad"]),float(PmagSpecRec["specimen_dang"]),float(PmagSpecRec["measurement_step_min"])*1e3,float(PmagSpecRec["measurement_step_max"])*1e3,float(PmagSpecRec["specimen_dec"]),float(PmagSpecRec["specimen_inc"]),calculation_type) elif 'T' in units and 'K' in units: if float(PmagSpecRec['measurement_step_min'])<1.0 : min=float(PmagSpecRec['measurement_step_min'])*1e3 else: min=float(PmagSpecRec['measurement_step_min'])-273 if float(PmagSpecRec['measurement_step_max'])<1.0 : max=float(PmagSpecRec['measurement_step_max'])*1e3 else: max=float(PmagSpecRec['measurement_step_max'])-273 print '%s %i %7.1f %i %i %7.1f %7.1f %7.1f, %s \n' % (PmagSpecRec["er_specimen_name"],int(PmagSpecRec["specimen_n"]),float(PmagSpecRec["specimen_mad"]),float(PmagSpecRec["specimen_dang"]),min,max,float(PmagSpecRec["specimen_dec"]),float(PmagSpecRec["specimen_inc"]),calculation_type) else: print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f, %s \n' % (PmagSpecRec["er_specimen_name"],int(PmagSpecRec["specimen_n"]),float(PmagSpecRec["specimen_mad"]),float(PmagSpecRec["specimen_dang"]),float(PmagSpecRec["measurement_step_min"]),float(PmagSpecRec["measurement_step_max"]),float(PmagSpecRec["specimen_dec"]),float(PmagSpecRec["specimen_inc"]),calculation_type) else: if 'K' in units: print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f, %s \n' % (PmagSpecRec["er_specimen_name"],int(PmagSpecRec["specimen_n"]),float(PmagSpecRec["specimen_alpha95"]),float(PmagSpecRec["specimen_dang"]),float(PmagSpecRec["measurement_step_min"])-273,float(PmagSpecRec["measurement_step_max"])-273,float(PmagSpecRec["specimen_dec"]),float(PmagSpecRec["specimen_inc"]),calculation_type) elif 'T' in units: print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f, %s \n' % (PmagSpecRec["er_specimen_name"],int(PmagSpecRec["specimen_n"]),float(PmagSpecRec["specimen_alpha95"]),float(PmagSpecRec["specimen_dang"]),float(PmagSpecRec["measurement_step_min"])*1e3,float(PmagSpecRec["measurement_step_max"])*1e3,float(PmagSpecRec["specimen_dec"]),float(PmagSpecRec["specimen_inc"]),calculation_type) elif 'T' in units and 'K' in units: if float(PmagSpecRec['measurement_step_min'])<1.0 : min=float(PmagSpecRec['measurement_step_min'])*1e3 else: min=float(PmagSpecRec['measurement_step_min'])-273 if float(PmagSpecRec['measurement_step_max'])<1.0 : max=float(PmagSpecRec['measurement_step_max'])*1e3 else: max=float(PmagSpecRec['measurement_step_max'])-273 print '%s %i %7.1f %i %i %7.1f %7.1f, %s \n' % (PmagSpecRec["er_specimen_name"],int(PmagSpecRec["specimen_n"]),float(PmagSpecRec["specimen_alpha95"]),min,max,float(PmagSpecRec["specimen_dec"]),float(PmagSpecRec["specimen_inc"]),calculation_type) else: print '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f, %s \n' % (PmagSpecRec["er_specimen_name"],int(PmagSpecRec["specimen_n"]),float(PmagSpecRec["specimen_alpha95"]),float(PmagSpecRec["measurement_step_min"]),float(PmagSpecRec["measurement_step_max"]),float(PmagSpecRec["specimen_dec"]),float(PmagSpecRec["specimen_inc"]),calculation_type) saveit=raw_input("Save this interpretation? [y]/n \n") if saveit!="n": changeS=1 # # put in details # angle,direction_type,setangle="","",0 if len(CurrRecs)>0: replace=raw_input(" [0] add new component, or [1] replace existing interpretation(s) [default is replace] ") if replace=="1" or replace=="": CurrRecs=[] PmagSpecRec['specimen_comp_name']='A' CurrRecs.append(PmagSpecRec) else: print 'These are the current component names for this specimen: ' for trec in CurrRecs:print trec['specimen_comp_name'] compnum=raw_input("Enter new component name: ") PmagSpecRec['specimen_comp_name']=compnum print "Adding new component: ",PmagSpecRec['specimen_comp_name'] CurrRecs.append(PmagSpecRec) else: PmagSpecRec['specimen_comp_name']='A' CurrRecs.append(PmagSpecRec) k+=1 ans="" else: ans="" else: # plots=1 k+=1 files={} locname.replace('/','-') print PmagSpecRec for key in ZED.keys(): files[key]="LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name']+'_SA:_'+PmagSpecRec['er_sample_name']+'_SP:_'+s+'_CO:_'+coord+'_TY:_'+key+'_.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['demag']='DeMag Plot' titles['zijd']='Zijderveld Plot' titles['eqarea']='Equal Area Plot' ZED = pmagplotlib.addBorders(ZED,titles,black,purple) pmagplotlib.saveP(ZED,files) if len(CurrRecs)>0: for rec in CurrRecs: PriorRecs.append(rec) if changeS==1: if len(PriorRecs)>0: save_redo(PriorRecs,inspec) else: os.system('rm '+inspec) CurrRecs,beg_pca,end_pca=[],"","" # next up changeS=0 else: k+=1 # skip record - not enough data if changeM==1: pmag.magic_write(meas_file,meas_data,'magic_measurements')
def main(): """ NAME thellier_magic.py DESCRIPTION plots Thellier-Thellier data in version 3.0 format Reads saved interpretations from a specimen formatted table, default: specimens.txt SYNTAX thellier_magic.py [command line options] OPTIONS -h prints help message and quits -f MEAS, set measurements input file, default is 'measurements.txt' -fsp PRIOR, set specimens.txt prior interpretations file, default is 'specimens.txt' -fcr CRIT, set criteria file for grading. # not yet implemented -fmt [svg,png,jpg], format for images - default is svg -sav, saves plots with out review (in format specified by -fmt key or default) -spc SPEC, plots single specimen SPEC, saves plot with specified format with optional -b bounds and quits -b BEG END: sets bounds for calculation BEG: starting step number for slope calculation END: ending step number for slope calculation -z use only z component difference for pTRM calculation OUTPUT figures: ALL: numbers refer to temperature steps in command line window 1) Arai plot: closed circles are zero-field first/infield open circles are infield first/zero-field triangles are pTRM checks squares are pTRM tail checks VDS is vector difference sum diamonds are bounds for interpretation 2) Zijderveld plot: closed (open) symbols are X-Y (X-Z) planes X rotated to NRM direction 3) (De/Re)Magnetization diagram: circles are NRM remaining squares are pTRM gained 4) equal area projections: green triangles are pTRM gained direction red (purple) circles are lower(upper) hemisphere of ZI step directions blue (cyan) squares are lower(upper) hemisphere IZ step directions 5) Optional: TRM acquisition 6) Optional: TDS normalization command line window: list is: temperature step numbers, temperatures (C), Dec, Inc, Int (units of measuements) list of possible commands: type letter followed by return to select option saving of plots creates image files with specimen, plot type as name """ # # initializations # version_num = pmag.get_version() verbose = pmagplotlib.verbose # # default acceptance criteria # accept = pmag.default_criteria(0)[0] # set the default criteria # # parse command line options # plots, fmt, Zdiff = 0, 'svg', 0 if '-h' in sys.argv: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg_from_sys("-WD", default_val=os.getcwd()) meas_file = pmag.get_named_arg_from_sys("-f", default_val="measurements.txt") spec_file = pmag.get_named_arg_from_sys("-fsp", default_val="specimens.txt") crit_file = pmag.get_named_arg_from_sys("-fcr", default_val="criteria.txt") spec_file = os.path.join(dir_path, spec_file) meas_file = os.path.join(dir_path, meas_file) crit_file = os.path.join(dir_path, crit_file) fmt = pmag.get_named_arg_from_sys("-fmt", "svg") if '-sav' in sys.argv: plots, verbose = 1, 0 if '-z' in sys.argv: Zdiff = 1 specimen = pmag.get_named_arg_from_sys("-spc", default_val="") if '-b' in sys.argv: ind = sys.argv.index('-b') start = int(sys.argv[ind + 1]) end = int(sys.argv[ind + 2]) else: start, end = "", "" fnames = { 'measurements': meas_file, 'specimens': spec_file, 'criteria': crit_file } contribution = nb.Contribution( dir_path, custom_filenames=fnames, read_tables=['measurements', 'specimens', 'criteria']) # # import prior interpretations from specimen file # specimen_cols = [ 'analysts', 'aniso_ftest', 'aniso_ftest12', 'aniso_ftest23', 'aniso_s', 'aniso_s_mean', 'aniso_s_n_measurements', 'aniso_s_sigma', 'aniso_s_unit', 'aniso_tilt_correction', 'aniso_type', 'aniso_v1', 'aniso_v2', 'aniso_v3', 'citations', 'description', 'dir_alpha95', 'dir_comp', 'dir_dec', 'dir_inc', 'dir_mad_free', 'dir_n_measurements', 'dir_tilt_correction', 'experiments', 'geologic_classes', 'geologic_types', 'hyst_bc', 'hyst_bcr', 'hyst_mr_moment', 'hyst_ms_moment', 'int_abs', 'int_b', 'int_b_beta', 'int_b_sigma', 'int_corr', 'int_dang', 'int_drats', 'int_f', 'int_fvds', 'int_gamma', 'int_mad_free', 'int_md', 'int_n_measurements', 'int_n_ptrm', 'int_q', 'int_rsc', 'int_treat_dc_field', 'lithologies', 'meas_step_max', 'meas_step_min', 'meas_step_unit', 'method_codes', 'sample', 'software_packages', 'specimen' ] if 'specimens' in contribution.tables: spec_container = contribution.tables['specimens'] prior_spec_data = spec_container.get_records_for_code( 'LP-PI-TRM', strict_match=False) # look up all prior intensity interpretations else: spec_container, prior_spec_data = None, [] backup = 0 # Mkeys = ['magn_moment', 'magn_volume', 'magn_mass'] # # create measurement dataframe # meas_container = contribution.tables['measurements'] meas_data = meas_container.df # meas_data['method_codes'] = meas_data['method_codes'].str.replace( " ", "") # get rid of nasty spaces meas_data = meas_data[meas_data['method_codes'].str.contains( 'LP-PI-TRM|LP-TRM|LP-TRM-TD') == True] # fish out zero field steps for plotting intensity_types = [ col_name for col_name in meas_data.columns if col_name in Mkeys ] int_key = intensity_types[ 0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used meas_data = meas_data[meas_data[int_key].notnull( )] # get all the non-null intensity records of the same type if 'flag' not in meas_data.columns: meas_data['flag'] = 'g' # set the default flag to good meas_data = meas_data[meas_data['flag'].str.contains('g') == True] # only the 'good' measurements thel_data = meas_data[meas_data['method_codes'].str.contains('LP-PI-TRM') == True] # get all the Thellier data trm_data = meas_data[meas_data['method_codes'].str.contains('LP-TRM') == True] # get all the TRM acquisition data td_data = meas_data[meas_data['method_codes'].str.contains('LP-TRM-TD') == True] # get all the TD data anis_data = meas_data[meas_data['method_codes'].str.contains('LP-AN') == True] # get all the anisotropy data # # get list of unique specimen names from measurement data # specimen_names = meas_data.specimen.unique( ) # this is a Series of all the specimen names specimen_names = specimen_names.tolist() # turns it into a list specimen_names.sort() # sorts by specimen name # # set up new DataFrame for this sessions specimen interpretations # spec_container = nb.MagicDataFrame(dtype='specimens', columns=specimen_cols) current_spec_data = spec_container.df # this is for interpretations from this session if specimen == "": # do all specimens k = 0 else: k = specimen_names.index(specimen) # just do this one # define figure numbers for arai, zijderveld and # de-,re-magnetization diagrams AZD = {} AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4 pmagplotlib.plot_init(AZD['arai'], 5, 5) pmagplotlib.plot_init(AZD['zijd'], 5, 5) pmagplotlib.plot_init(AZD['deremag'], 5, 5) pmagplotlib.plot_init(AZD['eqarea'], 5, 5) if len(trm_data) > 0: AZD['TRM'] = 5 pmagplotlib.plot_init(AZD['TRM'], 5, 5) if len(td_data) > 0: AZD['TDS'] = 6 pmagplotlib.plot_init(AZD['TDS'], 5, 5) # while k < len(specimen_names): this_specimen = specimen_names[ k] # set the current specimen for plotting if verbose and this_specimen != "": print(this_specimen, k + 1, 'out of ', len(specimen_names)) # # set up datablocks # thelblock = thel_data[thel_data['specimen'].str.contains(this_specimen) == True] # fish out this specimen trmblock = trm_data[trm_data['specimen'].str.contains(this_specimen) == True] # fish out this specimen tdsrecs = td_data[td_data['specimen'].str.contains(this_specimen) == True] # fish out this specimen anisblock = anis_data[anis_data['specimen'].str.contains(this_specimen) == True] # fish out the anisotropy data prior_specimen_interpretations = prior_spec_data[ prior_spec_data['specimen'].str.contains( this_specimen) == True] # fish out prior interpretation # # sort data into types # araiblock, field = pmag.sortarai(thelblock, this_specimen, Zdiff, version=3) first_Z = araiblock[0] GammaChecks = araiblock[5] if len(first_Z) < 3: if backup == 0: k += 1 if verbose: print('skipping specimen - moving forward ', this_specimen) else: k -= 1 if verbose: print('skipping specimen - moving backward ', this_specimen) else: backup = 0 zijdblock, units = pmag.find_dmag_rec(this_specimen, thelblock, version=3) if start == "" and len(prior_specimen_interpretations) > 0: if verbose: print('Looking up saved interpretation....') # # get prior interpretation steps # beg_int = pd.to_numeric(prior_specimen_interpretations. meas_step_min.values).tolist()[0] end_int = pd.to_numeric(prior_specimen_interpretations. meas_step_max.values).tolist()[0] else: beg_int, end_int = "", "" recnum = 0 if verbose: print("index step Dec Inc Int Gamma") for plotrec in zijdblock: if plotrec[0] == beg_int: start = recnum # while we are at it, collect these bounds if plotrec[0] == end_int: end = recnum if verbose: if GammaChecks != "": gamma = "" for g in GammaChecks: if g[0] == plotrec[0] - 273: gamma = g[1] break if gamma != "": print('%i %i %7.1f %7.1f %8.3e %7.1f' % (recnum, plotrec[0] - 273, plotrec[1], plotrec[2], plotrec[3], gamma)) else: print('%i %i %7.1f %7.1f %8.3e ' % (recnum, plotrec[0] - 273, plotrec[1], plotrec[2], plotrec[3])) recnum += 1 for fig in list(AZD.keys()): pmagplotlib.clearFIG(AZD[fig]) # clear all figures pmagplotlib.plotAZ(AZD, araiblock, zijdblock, this_specimen, units[0]) if verbose: pmagplotlib.drawFIGS(AZD) pars, errcode = pmag.PintPars(thelblock, araiblock, zijdblock, start, end, accept, version=3) pars['measurement_step_unit'] = "K" pars['experiment_type'] = 'LP-PI-TRM' # # work on saving interpretations stuff later # if errcode != 1: # no problem in PintPars pars["specimen_lab_field_dc"] = field pars["specimen_int"] = -1 * field * pars["specimen_b"] pars["er_specimen_name"] = this_specimen #pars,kill=pmag.scoreit(pars,this_specimen_interpretation,accept,'',verbose) # deal with this later pars["specimen_grade"] = 'None' pars['measurement_step_min'] = pars['meas_step_min'] pars['measurement_step_max'] = pars['meas_step_max'] if pars['measurement_step_unit'] == 'K': outstr = "specimen Tmin Tmax N lab_field B_anc b q f(coe) Fvds beta MAD Dang Drats Nptrm Grade R MD% sigma Gamma_max \n" pars_out = (this_specimen, (pars["meas_step_min"] - 273), (pars["meas_step_max"] - 273), (pars["specimen_int_n"]), 1e6 * (pars["specimen_lab_field_dc"]), 1e6 * (pars["specimen_int"]), pars["specimen_b"], pars["specimen_q"], pars["specimen_f"], pars["specimen_fvds"], pars["specimen_b_beta"], pars["int_mad_free"], pars["int_dang"], pars["int_drats"], pars["int_n_ptrm"], pars["specimen_grade"], np.sqrt(pars["specimen_rsc"]), int(pars["int_md"]), pars["specimen_b_sigma"], pars['specimen_gamma']) outstring = '%s %4.0f %4.0f %i %4.1f %4.1f %5.3f %5.1f %5.3f %5.3f %5.3f %7.1f %7.1f %7.1f %s %s %6.3f %i %5.3f %7.1f' % pars_out + '\n' elif pars['measurement_step_unit'] == 'J': outstr = "specimen Wmin Wmax N lab_field B_anc b q f(coe) Fvds beta MAD Dang Drats Nptrm Grade R MD% sigma ThetaMax DeltaMax GammaMax\n" pars_out = ( this_specimen, (pars["meas_step_min"]), (pars["meas_step_max"]), (pars["specimen_int_n"]), 1e6 * (pars["specimen_lab_field_dc"]), 1e6 * (pars["specimen_int"]), pars["specimen_b"], pars["specimen_q"], pars["specimen_f"], pars["specimen_fvds"], pars["specimen_b_beta"], pars["specimen_int_mad"], pars["specimen_int_dang"], pars["specimen_drats"], pars["specimen_int_ptrm_n"], pars["specimen_grade"], np.sqrt(pars["specimen_rsc"]), int(pars["specimen_md"]), pars["specimen_b_sigma"], pars["specimen_theta"], pars["specimen_delta"], pars["specimen_gamma"]) outstring = '%s %4.0f %4.0f %i %4.1f %4.1f %5.3f %5.1f %5.3f %5.3f %5.3f %7.1f %7.1f %7.1f %s %s %6.3f %i %5.3f %7.1f %7.1f %7.1f' % pars_out + '\n' print(outstr) print(outstring) pmagplotlib.plotB(AZD, araiblock, zijdblock, pars) mpars = pmag.domean(araiblock[1], start, end, 'DE-BFL') if verbose: pmagplotlib.drawFIGS(AZD) print('pTRM direction= ', '%7.1f' % (mpars['specimen_dec']), ' %7.1f' % (mpars['specimen_inc']), ' MAD:', '%7.1f' % (mpars['specimen_mad'])) if len(anisblock) > 0: # this specimen has anisotropy data if verbose: print('Found anisotropy record... but ignoring for now ') if plots == 1: if fmt != "pmag": files = {} for key in list(AZD.keys()): files[ key] = 'SP:_' + this_specimen + '_TY:_' + key + '_' + '.' + fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['deremag'] = 'DeReMag Plot' titles['zijd'] = 'Zijderveld Plot' titles['arai'] = 'Arai Plot' titles['TRM'] = 'TRM Acquisition data' AZD = pmagplotlib.addBorders(AZD, titles, black, purple) pmagplotlib.saveP(AZD, files) else: # save in pmag format print('pmag format no longer supported') #script="grep "+this_specimen+" output.mag | thellier -mfsi" #script=script+' %8.4e'%(field) #min='%i'%((pars["measurement_step_min"]-273)) #Max='%i'%((pars["measurement_step_max"]-273)) #script=script+" "+min+" "+Max #script=script+" |plotxy;cat mypost >>thellier.ps\n" #pltf.write(script) #pmag.domagicmag(outf,MeasRecs) if specimen != "": sys.exit() # syonara if verbose: ans = input('Return for next specimen, q to quit: ') if ans == 'q': sys.exit() k += 1 # moving on
def main(): """ NAME zeq.py DESCRIPTION plots demagnetization data. The equal area projection has the X direction (usually North in geographic coordinates) to the top. The red line is the X axis of the Zijderveld diagram. Solid symbols are lower hemisphere. The solid (open) symbols in the Zijderveld diagram are X,Y (X,Z) pairs. The demagnetization diagram plots the fractional remanence remaining after each step. The green line is the fraction of the total remaence removed between each step. INPUT FORMAT takes specimen_name treatment intensity declination inclination in space delimited file SYNTAX zeq.py [command line options OPTIONS -f FILE for reading from command line -u [mT,C] specify units of mT OR C, default is unscaled -sav save figure and quit -fmt [svg,jpg,png,pdf] set figure format [default is svg] -beg [step number] treatment step for beginning of PCA calculation, 0 is default -end [step number] treatment step for end of PCA calculation, last step is default -ct [l,p,f] Calculation Type: best-fit line, plane or fisher mean; line is default """ files, fmt, plot = {}, 'svg', 0 end_pca, beg_pca = "", "" calculation_type = 'DE-BFL' if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit else: if '-f' in sys.argv: ind = sys.argv.index('-f') file = sys.argv[ind + 1] else: print(main.__doc__) sys.exit() if '-u' in sys.argv: ind = sys.argv.index('-u') units = sys.argv[ind + 1] if units == "C": SIunits = "K" if units == "mT": SIunits = "T" else: units = "U" SIunits = "U" if '-sav' in sys.argv: plot = 1 if '-ct' in sys.argv: ind = sys.argv.index('-ct') ct = sys.argv[ind + 1] if ct == 'f': calculation_type = 'DE-FM' if ct == 'p': calculation_type = 'DE-BFP' if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-beg' in sys.argv: ind = sys.argv.index('-beg') beg_pca = int(sys.argv[ind + 1]) if '-end' in sys.argv: ind = sys.argv.index('-end') end_pca = int(sys.argv[ind + 1]) f = open(file, 'r') data = f.readlines() # datablock = [] # set up list for data s = "" # initialize specimen name angle = 0. for line in data: # read in the data from standard input rec = line.split() # split each line on space to get records if angle == "": angle = float(rec[3]) if s == "": s = rec[0] if units == 'mT': datablock.append([ float(rec[1]) * 1e-3, float(rec[3]), float(rec[4]), 1e-3 * float(rec[2]), '', 'g' ]) # treatment, dec, inc, int # convert to T and Am^2 (assume emu) if units == 'C': datablock.append([ float(rec[1]) + 273., float(rec[3]), float(rec[4]), 1e-3 * float(rec[2]), '', 'g' ]) # treatment, dec, inc, int, convert to K and Am^2, assume emu if units == 'U': datablock.append([ float(rec[1]), float(rec[3]), float(rec[4]), float(rec[2]), '', 'g' ]) # treatment, dec, inc, int, using unscaled units # define figure numbers in a dictionary for equal area, zijderveld, # and intensity vs. demagnetiztion step respectively ZED = {} ZED['eqarea'], ZED['zijd'], ZED['demag'] = 1, 2, 3 pmagplotlib.plot_init(ZED['eqarea'], 5, 5) # initialize plots pmagplotlib.plot_init(ZED['zijd'], 5, 5) pmagplotlib.plot_init(ZED['demag'], 5, 5) # # pmagplotlib.plotZED(ZED, datablock, angle, s, SIunits) # plot the data if plot == 0: pmagplotlib.drawFIGS(ZED) # # print out data for this sample to screen # recnum = 0 for plotrec in datablock: if units == 'mT': print( '%i %7.1f %8.3e %7.1f %7.1f ' % (recnum, plotrec[0] * 1e3, plotrec[3], plotrec[1], plotrec[2])) if units == 'C': print('%i %7.1f %8.3e %7.1f %7.1f ' % (recnum, plotrec[0] - 273., plotrec[3], plotrec[1], plotrec[2])) if units == 'U': print('%i %7.1f %8.3e %7.1f %7.1f ' % (recnum, plotrec[0], plotrec[3], plotrec[1], plotrec[2])) recnum += 1 if plot == 0: while 1: if beg_pca != "" and end_pca != "" and calculation_type != "": pmagplotlib.plotZED(ZED, datablock, angle, s, SIunits) # plot the data mpars = pmag.domean( datablock, beg_pca, end_pca, calculation_type) # get best-fit direction/great circle pmagplotlib.plotDir( ZED, mpars, datablock, angle) # plot the best-fit direction/great circle print('Specimen, calc_type, N, min, max, MAD, dec, inc') if units == 'mT': print('%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"] * 1e3, mpars["measurement_step_max"] * 1e3, mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) if units == 'C': print('%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"] - 273, mpars["measurement_step_max"] - 273, mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) if units == 'U': print( '%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"], mpars["measurement_step_max"], mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) if end_pca == "": end_pca = len( datablock ) - 1 # initialize end_pca, beg_pca to first and last measurement if beg_pca == "": beg_pca = 0 ans = input( " s[a]ve plot, [b]ounds for pca and calculate, change [h]orizontal projection angle, [q]uit: " ) if ans == 'q': sys.exit() if ans == 'a': files = {} for key in list(ZED.keys()): files[key] = s + '_' + key + '.' + fmt pmagplotlib.saveP(ZED, files) if ans == 'h': angle = float( input(" Declination to project onto horizontal axis? ")) pmagplotlib.plotZED(ZED, datablock, angle, s, SIunits) # plot the data if ans == 'b': GoOn = 0 while GoOn == 0: # keep going until reasonable bounds are set print('Enter index of first point for pca: ', '[', beg_pca, ']') answer = input('return to keep default ') if answer != "": beg_pca = int(answer) print('Enter index of last point for pca: ', '[', end_pca, ']') answer = input('return to keep default ') if answer != "": end_pca = int(answer) if beg_pca >= 0 and beg_pca <= len( datablock) - 2 and end_pca > 0 and end_pca < len( datablock): GoOn = 1 else: print("Bad entry of indices - try again") end_pca = len(datablock) - 1 beg_pca = 0 GoOn = 0 while GoOn == 0: ct = input( 'Enter Calculation Type: best-fit line, plane or fisher mean [l]/p/f : ' ) if ct == "" or ct == "l": calculation_type = "DE-BFL" GoOn = 1 # all good elif ct == 'p': calculation_type = "DE-BFP" GoOn = 1 # all good elif ct == 'f': calculation_type = "DE-FM" GoOn = 1 # all good else: print("bad entry of calculation type: try again. " ) # keep going pmagplotlib.plotZED(ZED, datablock, angle, s, SIunits) # plot the data mpars = pmag.domean( datablock, beg_pca, end_pca, calculation_type ) # get best-fit direction/great circle pmagplotlib.plotDir( ZED, mpars, datablock, angle) # plot the best-fit direction/great circle print('Specimen, calc_type, N, min, max, MAD, dec, inc') if units == 'mT': print('%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"] * 1e3, mpars["measurement_step_max"] * 1e3, mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) if units == 'C': print('%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"] - 273, mpars["measurement_step_max"] - 273, mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) if units == 'U': print('%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"], mpars["measurement_step_max"], mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) pmagplotlib.drawFIGS(ZED) else: print(beg_pca, end_pca) if beg_pca != "" and end_pca != "": pmagplotlib.plotZED(ZED, datablock, angle, s, SIunits) # plot the data mpars = pmag.domean( datablock, beg_pca, end_pca, calculation_type) # get best-fit direction/great circle pmagplotlib.plotDir( ZED, mpars, datablock, angle) # plot the best-fit direction/great circle print('Specimen, calc_type, N, min, max, MAD, dec, inc') if units == 'mT': print('%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"] * 1e3, mpars["measurement_step_max"] * 1e3, mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) if units == 'C': print('%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"] - 273, mpars["measurement_step_max"] - 273, mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) if units == 'U': print('%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"], mpars["measurement_step_max"], mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) files = {} for key in list(ZED.keys()): files[key] = s + '_' + key + '.' + fmt pmagplotlib.saveP(ZED, files)
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 ")
def main(): """ NAME revtest_MM1990.py DESCRIPTION calculates Watson's V statistic from input files through Monte Carlo simulation in order to test whether normal and reversed populations could have been drawn from a common mean (equivalent to watsonV.py). Also provides the critical angle between the two sample mean directions and the corresponding McFadden and McElhinny (1990) classification. INPUT FORMAT takes dec/inc as first two columns in two space delimited files (one file for normal directions, one file for reversed directions). SYNTAX revtest_MM1990.py [command line options] OPTIONS -h prints help message and quits -f FILE -f2 FILE -P (don't plot the Watson V cdf) OUTPUT Watson's V between the two populations and the Monte Carlo Critical Value Vc. M&M1990 angle, critical angle and classification Plot of Watson's V CDF from Monte Carlo simulation (red line), V is solid and Vc is dashed. """ D1,D2=[],[] plot=1 Flip=1 if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-P' in sys.argv: plot=0 if '-f' in sys.argv: ind=sys.argv.index('-f') file1=sys.argv[ind+1] f1=open(file1,'r') for line in f1.readlines(): rec=line.split() Dec,Inc=float(rec[0]),float(rec[1]) D1.append([Dec,Inc,1.]) f1.close() if '-f2' in sys.argv: ind=sys.argv.index('-f2') file2=sys.argv[ind+1] f2=open(file2,'r') print("be patient, your computer is doing 5000 simulations...") for line in f2.readlines(): rec=line.split() Dec,Inc=float(rec[0]),float(rec[1]) D2.append([Dec,Inc,1.]) f2.close() #take the antipode for the directions in file 2 D2_flip=[] for rec in D2: d,i=(rec[0]-180.)%360.,-rec[1] D2_flip.append([d,i,1.]) pars_1=pmag.fisher_mean(D1) pars_2=pmag.fisher_mean(D2_flip) cart_1=pmag.dir2cart([pars_1["dec"],pars_1["inc"],pars_1["r"]]) cart_2=pmag.dir2cart([pars_2['dec'],pars_2['inc'],pars_2["r"]]) Sw=pars_1['k']*pars_1['r']+pars_2['k']*pars_2['r'] # k1*r1+k2*r2 xhat_1=pars_1['k']*cart_1[0]+pars_2['k']*cart_2[0] # k1*x1+k2*x2 xhat_2=pars_1['k']*cart_1[1]+pars_2['k']*cart_2[1] # k1*y1+k2*y2 xhat_3=pars_1['k']*cart_1[2]+pars_2['k']*cart_2[2] # k1*z1+k2*z2 Rw=numpy.sqrt(xhat_1**2+xhat_2**2+xhat_3**2) V=2*(Sw-Rw) # #keep weighted sum for later when determining the "critical angle" let's save it as Sr (notation of McFadden and McElhinny, 1990) # Sr=Sw # # do monte carlo simulation of datasets with same kappas, but common mean # counter,NumSims=0,5000 Vp=[] # set of Vs from simulations for k in range(NumSims): # # get a set of N1 fisher distributed vectors with k1, calculate fisher stats # Dirp=[] for i in range(pars_1["n"]): Dirp.append(pmag.fshdev(pars_1["k"])) pars_p1=pmag.fisher_mean(Dirp) # # get a set of N2 fisher distributed vectors with k2, calculate fisher stats # Dirp=[] for i in range(pars_2["n"]): Dirp.append(pmag.fshdev(pars_2["k"])) pars_p2=pmag.fisher_mean(Dirp) # # get the V for these # Vk=pmag.vfunc(pars_p1,pars_p2) Vp.append(Vk) # # sort the Vs, get Vcrit (95th percentile one) # Vp.sort() k=int(.95*NumSims) Vcrit=Vp[k] # # equation 18 of McFadden and McElhinny, 1990 calculates the critical value of R (Rwc) # Rwc=Sr-(old_div(Vcrit,2)) # #following equation 19 of McFadden and McElhinny (1990) the critical angle is calculated. # k1=pars_1['k'] k2=pars_2['k'] R1=pars_1['r'] R2=pars_2['r'] critical_angle=numpy.degrees(numpy.arccos(old_div(((Rwc**2)-((k1*R1)**2)-((k2*R2)**2)),(2*k1*R1*k2*R2)))) D1_mean=(pars_1['dec'],pars_1['inc']) D2_mean=(pars_2['dec'],pars_2['inc']) angle=pmag.angle(D1_mean,D2_mean) # # print the results of the test # print("") print("Results of Watson V test: ") print("") print("Watson's V: " '%.1f' %(V)) print("Critical value of V: " '%.1f' %(Vcrit)) if V<Vcrit: print('"Pass": Since V is less than Vcrit, the null hypothesis that the two populations are drawn from distributions that share a common mean direction (antipodal to one another) cannot be rejected.') elif V>Vcrit: print('"Fail": Since V is greater than Vcrit, the two means can be distinguished at the 95% confidence level.') print("") print("M&M1990 classification:") print("") print("Angle between data set means: " '%.1f'%(angle)) print("Critical angle of M&M1990: " '%.1f'%(critical_angle)) if V>Vcrit: print("") elif V<Vcrit: if critical_angle<5: print("The McFadden and McElhinny (1990) classification for this test is: 'A'") elif critical_angle<10: print("The McFadden and McElhinny (1990) classification for this test is: 'B'") elif critical_angle<20: print("The McFadden and McElhinny (1990) classification for this test is: 'C'") else: print("The McFadden and McElhinny (1990) classification for this test is: 'INDETERMINATE;") if plot==1: CDF={'cdf':1} pmagplotlib.plot_init(CDF['cdf'],5,5) p1 = pmagplotlib.plotCDF(CDF['cdf'],Vp,"Watson's V",'r',"") p2 = pmagplotlib.plotVs(CDF['cdf'],[V],'g','-') p3 = pmagplotlib.plotVs(CDF['cdf'],[Vp[k]],'b','--') pmagplotlib.drawFIGS(CDF) files,fmt={},'svg' if file2!="": files['cdf']='WatsonsV_'+file1+'_'+file2+'.'+fmt else: files['cdf']='WatsonsV_'+file1+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['cdf']='Cumulative Distribution' CDF = pmagplotlib.addBorders(CDF,titles,black,purple) pmagplotlib.saveP(CDF,files) else: ans=input(" S[a]ve to save plot, [q]uit without saving: ") if ans=="a": pmagplotlib.saveP(CDF,files)
def main(): """ NAME plotdi_e.py DESCRIPTION plots equal area projection from dec inc data and cones of confidence (Fisher, kent or Bingham or bootstrap). INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX plotdi_e.py [command line options] OPTIONS -h prints help message and quits -i for interactive parameter entry -f FILE, sets input filename on command line -Fish plots unit vector mean direction, alpha95 -Bing plots Principal direction, Bingham confidence ellipse -Kent plots unit vector mean direction, confidence ellipse -Boot E plots unit vector mean direction, bootstrapped confidence ellipse -Boot V plots unit vector mean direction, distribution of bootstrapped means """ dist='F' # default distribution is Fisherian mode=1 EQ={'eq':1} if len(sys.argv) > 0: if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file=raw_input("Enter file name with dec, inc data: ") dist=raw_input("Enter desired distrubution: [Fish]er, [Bing]ham, [Kent] [Boot] [default is Fisher]: ") if dist=="":dist="F" if dist=="Boot": type=raw_input(" Ellipses or distribution of vectors? [E]/V ") if type=="" or type=="E": dist="BE" else: dist="BE" else: # if '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] else: print 'you must specify a file name' print main.__doc__ sys.exit() if '-Bing' in sys.argv:dist='B' if '-Kent' in sys.argv:dist='K' if '-Boot' in sys.argv: ind=sys.argv.index('-Boot') type=sys.argv[ind+1] if type=='E': dist='BE' elif type=='V': dist='BV' EQ['bdirs']=2 pmagplotlib.plot_init(EQ['bdirs'],5,5) else: print main.__doc__ sys.exit() pmagplotlib.plot_init(EQ['eq'],5,5) # # get to work f=open(file,'r') data=f.readlines() # DIs= [] # set up list for dec inc data DiRecs=[] pars=[] nDIs,rDIs,npars,rpars=[],[],[],[] mode =1 for line in data: # read in the data from standard input DiRec={} rec=line.split() # split each line on space to get records DIs.append((float(rec[0]),float(rec[1]),1.)) DiRec['dec']=rec[0] DiRec['inc']=rec[1] DiRec['direction_type']='l' DiRecs.append(DiRec) # split into two modes ppars=pmag.doprinc(DIs) # get principal directions for rec in DIs: angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']]) if angle>90.: rDIs.append(rec) else: nDIs.append(rec) if dist=='B': # do on whole dataset title="Bingham confidence ellipse" bpars=pmag.dobingham(DIs) for key in bpars.keys(): if key!='n':print " ",key, '%7.1f'%(bpars[key]) if key=='n':print " ",key, ' %i'%(bpars[key]) npars.append(bpars['dec']) npars.append(bpars['inc']) npars.append(bpars['Zeta']) npars.append(bpars['Zdec']) npars.append(bpars['Zinc']) npars.append(bpars['Eta']) npars.append(bpars['Edec']) npars.append(bpars['Einc']) if dist=='F': title="Fisher confidence cone" if len(nDIs)>3: fpars=pmag.fisher_mean(nDIs) print "mode ",mode for key in fpars.keys(): if key!='n':print " ",key, '%7.1f'%(fpars[key]) if key=='n':print " ",key, ' %i'%(fpars[key]) mode+=1 npars.append(fpars['dec']) npars.append(fpars['inc']) npars.append(fpars['alpha95']) # Beta npars.append(fpars['dec']) isign=abs(fpars['inc'])/fpars['inc'] npars.append(fpars['inc']-isign*90.) #Beta inc npars.append(fpars['alpha95']) # gamma npars.append(fpars['dec']+90.) # Beta dec npars.append(0.) #Beta inc if len(rDIs)>3: fpars=pmag.fisher_mean(rDIs) print "mode ",mode for key in fpars.keys(): if key!='n':print " ",key, '%7.1f'%(fpars[key]) if key=='n':print " ",key, ' %i'%(fpars[key]) mode+=1 rpars.append(fpars['dec']) rpars.append(fpars['inc']) rpars.append(fpars['alpha95']) # Beta rpars.append(fpars['dec']) isign=abs(fpars['inc'])/fpars['inc'] rpars.append(fpars['inc']-isign*90.) #Beta inc rpars.append(fpars['alpha95']) # gamma rpars.append(fpars['dec']+90.) # Beta dec rpars.append(0.) #Beta inc if dist=='K': title="Kent confidence ellipse" if len(nDIs)>3: kpars=pmag.dokent(nDIs,len(nDIs)) print "mode ",mode for key in kpars.keys(): if key!='n':print " ",key, '%7.1f'%(kpars[key]) if key=='n':print " ",key, ' %i'%(kpars[key]) mode+=1 npars.append(kpars['dec']) npars.append(kpars['inc']) npars.append(kpars['Zeta']) npars.append(kpars['Zdec']) npars.append(kpars['Zinc']) npars.append(kpars['Eta']) npars.append(kpars['Edec']) npars.append(kpars['Einc']) if len(rDIs)>3: kpars=pmag.dokent(rDIs,len(rDIs)) print "mode ",mode for key in kpars.keys(): if key!='n':print " ",key, '%7.1f'%(kpars[key]) if key=='n':print " ",key, ' %i'%(kpars[key]) mode+=1 rpars.append(kpars['dec']) rpars.append(kpars['inc']) rpars.append(kpars['Zeta']) rpars.append(kpars['Zdec']) rpars.append(kpars['Zinc']) rpars.append(kpars['Eta']) rpars.append(kpars['Edec']) rpars.append(kpars['Einc']) else: # assume bootstrap if dist=='BE': if len(nDIs)>5: BnDIs=pmag.di_boot(nDIs) Bkpars=pmag.dokent(BnDIs,1.) print "mode ",mode for key in Bkpars.keys(): if key!='n':print " ",key, '%7.1f'%(Bkpars[key]) if key=='n':print " ",key, ' %i'%(Bkpars[key]) mode+=1 npars.append(Bkpars['dec']) npars.append(Bkpars['inc']) npars.append(Bkpars['Zeta']) npars.append(Bkpars['Zdec']) npars.append(Bkpars['Zinc']) npars.append(Bkpars['Eta']) npars.append(Bkpars['Edec']) npars.append(Bkpars['Einc']) if len(rDIs)>5: BrDIs=pmag.di_boot(rDIs) Bkpars=pmag.dokent(BrDIs,1.) print "mode ",mode for key in Bkpars.keys(): if key!='n':print " ",key, '%7.1f'%(Bkpars[key]) if key=='n':print " ",key, ' %i'%(Bkpars[key]) mode+=1 rpars.append(Bkpars['dec']) rpars.append(Bkpars['inc']) rpars.append(Bkpars['Zeta']) rpars.append(Bkpars['Zdec']) rpars.append(Bkpars['Zinc']) rpars.append(Bkpars['Eta']) rpars.append(Bkpars['Edec']) rpars.append(Bkpars['Einc']) title="Bootstrapped confidence ellipse" elif dist=='BV': if len(nDIs)>5: pmagplotlib.plotEQ(EQ['eq'],nDIs,'Data') BnDIs=pmag.di_boot(nDIs) pmagplotlib.plotEQ(EQ['bdirs'],BnDIs,'Bootstrapped Eigenvectors') if len(rDIs)>5: BrDIs=pmag.di_boot(rDIs) if len(nDIs)>5: # plot on existing plots pmagplotlib.plotDI(EQ['eq'],rDIs) pmagplotlib.plotDI(EQ['bdirs'],BrDIs) else: pmagplotlib.plotEQ(EQ['eq'],rDIs,'Data') pmagplotlib.plotEQ(EQ['bdirs'],BrDIs,'Bootstrapped Eigenvectors') pmagplotlib.drawFIGS(EQ) ans=raw_input('s[a]ve, [q]uit ') if ans=='q':sys.exit() if ans=='a': files={} for key in EQ.keys(): files[key]='BE_'+key+'.svg' pmagplotlib.saveP(EQ,files) sys.exit() if len(nDIs)>5: pmagplotlib.plotCONF(EQ['eq'],title,DiRecs,npars,1) if len(rDIs)>5 and dist!='B': pmagplotlib.plotCONF(EQ['eq'],title,[],rpars,0) elif len(rDIs)>5 and dist!='B': pmagplotlib.plotCONF(EQ['eq'],title,DiRecs,rpars,1) pmagplotlib.drawFIGS(EQ) ans=raw_input('s[a]ve, [q]uit ') if ans=='q':sys.exit() if ans=='a': files={} for key in EQ.keys(): files[key]=key+'.svg' pmagplotlib.saveP(EQ,files)
def main(): """ NAME dayplot_magic.py DESCRIPTION makes 'day plots' (Day et al. 1977) and squareness/coercivity, plots 'linear mixing' curve from Dunlop and Carter-Stiglitz (2006). squareness coercivity of remanence (Neel, 1955) plots after Tauxe et al. (2002) SYNTAX dayplot_magic.py [command line options] OPTIONS -h prints help message and quits -f: specify input hysteresis file, default is rmag_hysteresis.txt -fr: specify input remanence file, default is rmag_remanence.txt -fmt [svg,png,jpg] format for output plots -sav saves plots and quits quietly -n label specimen names """ args=sys.argv hyst_file,rem_file="rmag_hysteresis.txt","rmag_remanence.txt" dir_path='.' verbose=pmagplotlib.verbose fmt='svg' # default file format if '-WD' in args: ind=args.index('-WD') dir_path=args[ind+1] if "-h" in args: print(main.__doc__) sys.exit() if '-f' in args: ind=args.index("-f") hyst_file=args[ind+1] if '-fr' in args: ind=args.index("-fr") rem_file=args[ind+1] if '-fmt' in sys.argv: ind=sys.argv.index("-fmt") fmt=sys.argv[ind+1] if '-sav' in sys.argv: plots=1 verbose=0 else: plots=0 if '-n' in sys.argv: label=1 else: label=0 hyst_file = os.path.realpath(os.path.join(dir_path, hyst_file)) rem_file = os.path.realpath(os.path.join(dir_path, rem_file)) # # initialize some variables # define figure numbers for Day,S-Bc,S-Bcr DSC={} DSC['day'],DSC['S-Bc'],DSC['S-Bcr'],DSC['bcr1-bcr2']=1,2,3,4 pmagplotlib.plot_init(DSC['day'],5,5) pmagplotlib.plot_init(DSC['S-Bc'],5,5) pmagplotlib.plot_init(DSC['S-Bcr'],5,5) pmagplotlib.plot_init(DSC['bcr1-bcr2'],5,5) # # hyst_data,file_type=pmag.magic_read(hyst_file) rem_data,file_type=pmag.magic_read(rem_file) # S,BcrBc,Bcr2,Bc,hsids,Bcr=[],[],[],[],[],[] Ms,Bcr1,Bcr1Bc,S1=[],[],[],[] names=[] locations='' for rec in hyst_data: if 'er_location_name' in rec.keys() and rec['er_location_name'] not in locations: locations=locations+rec['er_location_name']+'_' if rec['hysteresis_bcr'] !="" and rec['hysteresis_mr_moment']!="": S.append(float(rec['hysteresis_mr_moment'])/float(rec['hysteresis_ms_moment'])) Bcr.append(float(rec['hysteresis_bcr'])) Bc.append(float(rec['hysteresis_bc'])) BcrBc.append(Bcr[-1]/Bc[-1]) if 'er_synthetic_name' in rec.keys() and rec['er_synthetic_name']!="": rec['er_specimen_name']=rec['er_synthetic_name'] hsids.append(rec['er_specimen_name']) names.append(rec['er_specimen_name']) if len(rem_data)>0: for rec in rem_data: if rec['remanence_bcr'] !="" and float(rec['remanence_bcr'])>0: try: ind=hsids.index(rec['er_specimen_name']) Bcr1.append(float(rec['remanence_bcr'])) Bcr1Bc.append(Bcr1[-1]/Bc[ind]) S1.append(S[ind]) Bcr2.append(Bcr[ind]) except ValueError: if verbose:print('hysteresis data for ',rec['er_specimen_name'],' not found') # # now plot the day and S-Bc, S-Bcr plots # leglist=[] if label==0:names=[] if len(Bcr1)>0: pmagplotlib.plotDay(DSC['day'],Bcr1Bc,S1,'ro',names=names) pmagplotlib.plotSBcr(DSC['S-Bcr'],Bcr1,S1,'ro') pmagplotlib.plot_init(DSC['bcr1-bcr2'],5,5) pmagplotlib.plotBcr(DSC['bcr1-bcr2'],Bcr1,Bcr2) else: del DSC['bcr1-bcr2'] pmagplotlib.plotDay(DSC['day'],BcrBc,S,'bs',names=names) pmagplotlib.plotSBcr(DSC['S-Bcr'],Bcr,S,'bs') pmagplotlib.plotSBc(DSC['S-Bc'],Bc,S,'bs') files={} if len(locations)>0:locations=locations[:-1] for key in DSC.keys(): if pmagplotlib.isServer: # use server plot naming convention files[key] = 'LO:_'+locations+'_'+'SI:__SA:__SP:__TY:_'+key+'_.'+fmt else: # use more readable plot naming convention files[key] = '{}_{}.{}'.format(locations, key, fmt) if verbose: pmagplotlib.drawFIGS(DSC) ans=raw_input(" S[a]ve to save plots, return to quit: ") if ans=="a": pmagplotlib.saveP(DSC,files) else: sys.exit() if plots: pmagplotlib.saveP(DSC,files)
def main(): """ NAME biplot_magic.py DESCRIPTION makes a biplot of specified variables from magic_measurements.txt format file SYNTAX biplot_magic.py [-h] [-i] [command line options] INPUT takes magic formated magic_measurments file OPTIONS -h prints help message and quits -i interactively set filename and axes for plotting -f FILE: specifies file name, default: magic_measurements.txt -fmt [svg,png,jpg], format for images - default is svg -sav figure and quit -x XMETH:key:step, specify method code for X axis (optional key and treatment values) -y YMETH:key:step, specify method code for X axis -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is whole file -n [V,M] plot volume or mass normalized data only NOTES if nothing is specified for x and y, the user will be presented with options key = ['treatment_ac_field','treatment_dc_field',treatment_temp'] step in mT for fields, K for temperatures """ # file='magic_measurements.txt' methx,methy,fmt="","",'.svg' plot_key='' norm_by="" #plot=0 no_plot = pmag.get_flag_arg_from_sys('-sav') if not no_plot: do_plot = True else: do_plot = False if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt='.'+sys.argv[ind+1] if '-n' in sys.argv: ind=sys.argv.index('-n') norm_by=sys.argv[ind+1] xtreat_key,ytreat_key,xstep,ystep="","","","" if '-x' in sys.argv: ind=sys.argv.index('-x') meths=sys.argv[ind+1].split(':') methx=meths[0] if len(meths)>1: xtreat_key=meths[1] xstep=float(meths[2]) if '-y' in sys.argv: ind=sys.argv.index('-y') meths=sys.argv[ind+1].split(':') methy=meths[0] if len(meths)>1: ytreat_key=meths[1] ystep=float(meths[2]) if '-obj' in sys.argv: ind=sys.argv.index('-obj') plot_by=sys.argv[ind+1] if plot_by=='loc':plot_key='er_location_name' if plot_by=='sit':plot_key='er_site_name' if plot_by=='sam':plot_key='er_sample_name' if plot_by=='spc':plot_key='er_specimen_name' if '-h' in sys.argv: do_plot = False if '-i' in sys.argv: # # get name of file from command line # file=raw_input("Input magic_measurments file name? [magic_measurements.txt] ") if file=="":file="magic_measurements.txt" # # FIG={'fig':1} pmagplotlib.plot_init(FIG['fig'],5,5) data,file_type=pmag.magic_read(file) if file_type!="magic_measurements": print file_type,' not correct format for magic_measurments file' sys.exit() # # collect method codes methods,plotlist=[],[] for rec in data: if plot_key!="": if rec[plot_key] not in plotlist:plotlist.append(rec[plot_key]) elif len(plotlist)==0: plotlist.append('All') meths=rec['magic_method_codes'].split(':') for meth in meths: if meth.strip() not in methods and meth.strip()!="LP-": methods.append(meth.strip()) # if '-i' in sys.argv: print methods elif methx =="" or methy=="": print methods sys.exit() GoOn=1 while GoOn==1: if '-i' in sys.argv:methx=raw_input('Select method for x axis: ') if methx not in methods: if '-i' in sys.argv: print 'try again! method not available' else: print main.__doc__ print '\n must specify X axis method\n' sys.exit() else: if pmagplotlib.verbose: print methx, ' selected for X axis' GoOn=0 GoOn=1 while GoOn==1: if '-i' in sys.argv:methy=raw_input('Select method for y axis: ') if methy not in methods: if '-i' in sys.argv: print 'try again! method not available' else: print main.__doc__ print '\n must specify Y axis method\n' sys.exit() else: if pmagplotlib.verbose: print methy, ' selected for Y axis' GoOn=0 if norm_by=="": measkeys=['measurement_magn_mass','measurement_magn_volume','measurement_magn_moment','measurement_magnitude','measurement_chi_volume','measurement_chi_mass','measurement_chi'] elif norm_by=="V": measkeys=['measurement_magn_volume','measurement_chi_volume'] elif norm_by=="M": measkeys=['measurement_magn_mass','measurement_chi_mass'] xmeaskey,ymeaskey="","" plotlist.sort() for plot in plotlist: # go through objects if pmagplotlib.verbose: print plot X,Y=[],[] x,y='','' for rec in data: if plot_key!="" and rec[plot_key]!=plot: pass else: meths=rec['magic_method_codes'].split(':') for meth in meths: if meth.strip()==methx: if xmeaskey=="": for key in measkeys: if key in rec.keys() and rec[key]!="": xmeaskey=key if pmagplotlib.verbose: print xmeaskey,' being used for plotting X.' break if meth.strip()==methy: if ymeaskey=="": for key in measkeys: if key in rec.keys() and rec[key]!="": ymeaskey=key if pmagplotlib.verbose: print ymeaskey,' being used for plotting Y' break if ymeaskey!="" and xmeaskey!="": for rec in data: x,y='','' spec=rec['er_specimen_name'] # get the ydata for this specimen if rec[ymeaskey]!="" and methy in rec['magic_method_codes'].split(':'): if ytreat_key=="" or (ytreat_key in rec.keys() and float(rec[ytreat_key])==ystep): y=float(rec[ymeaskey]) for rec in data: # now find the xdata if rec['er_specimen_name']==spec and rec[xmeaskey]!="" and methx in rec['magic_method_codes'].split(':'): if xtreat_key=="" or (xtreat_key in rec.keys() and float(rec[xtreat_key])==xstep): x=float(rec[xmeaskey]) if x != '' and y!= '': X.append(x) Y.append(y) if len(X)>0: pmagplotlib.clearFIG(FIG['fig']) pmagplotlib.plotXY(FIG['fig'],X,Y,sym='ro',xlab=methx,ylab=methy,title=plot+':Biplot') if not pmagplotlib.isServer and do_plot: pmagplotlib.drawFIGS(FIG) ans=raw_input('S[a]ve plots, [q]uit, Return for next plot ' ) if ans=='a': files={} for key in FIG.keys(): files[key]=plot+'_'+key+fmt pmagplotlib.saveP(FIG,files) if ans=='q': print "Good-bye\n" sys.exit() else: files={} for key in FIG.keys(): files[key]=plot+'_'+key+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['fig']='X Y Plot' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) else: print 'nothing to plot for ',plot
def main(): """ NAME eqarea.py DESCRIPTION makes equal area projections from declination/inclination data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX eqarea.py [options] OPTIONS -f FILE, specify file on command line -sav save figure and quit -fmt [svg,jpg,png,pdf] set figure format [default is svg] -s SIZE specify symbol size - default is 20 -Lsym SHAPE COLOR specify shape and color for lower hemisphere -Usym SHAPE COLOR specify shape and color for upper hemisphere shapes: 's': square,'o': circle,'^,>,v,<': [up,right,down,left] triangle, 'd': diamond, 'p': pentagram, 'h': hexagon, '8': octagon, '+': plus, 'x': cross colors: [b]lue,[g]reen,[r]ed,[c]yan,[m]agenta,[y]ellow,blac[k],[w]hite """ title="" files,fmt={},'svg' sym={'lower':['o','r'],'upper':['o','w']} plot=0 if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit if '-sav' in sys.argv: plot=1 if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-s' in sys.argv: ind=sys.argv.index('-s') sym['size']=int(sys.argv[ind+1]) else: sym['size']=20 if '-Lsym' in sys.argv: ind=sys.argv.index('-Lsym') sym['lower'][0]=sys.argv[ind+1] sym['lower'][1]=sys.argv[ind+2] if '-Usym' in sys.argv: ind=sys.argv.index('-Usym') sym['upper'][0]=sys.argv[ind+1] sym['upper'][1]=sys.argv[ind+2] if '-f' in sys.argv: # ask for filename ind=sys.argv.index('-f') file=sys.argv[ind+1] else: print main.__doc__ print ' \n -f option required' sys.exit() # graceful quit DI=numpy.loadtxt(file) EQ={'eq':1} pmagplotlib.plot_init(EQ['eq'],5,5) pmagplotlib.plotEQsym(EQ['eq'],DI,'Equal Area Plot',sym) # make plot if plot==0:pmagplotlib.drawFIGS(EQ) # make it visible for key in EQ.keys(): files[key]=key+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='Equal Area Plot' EQ = pmagplotlib.addBorders(EQ,titles,black,purple) pmagplotlib.saveP(EQ,files) elif plot==1: files['eq']=file+'.'+fmt pmagplotlib.saveP(EQ,files) else: ans=raw_input(" S[a]ve to save plot, [q]uit without saving: ") if ans=="a": pmagplotlib.saveP(EQ,files)
def main(): """ NAME dayplot_magic.py DESCRIPTION makes 'day plots' (Day et al. 1977) and squareness/coercivity, plots 'linear mixing' curve from Dunlop and Carter-Stiglitz (2006). squareness coercivity of remanence (Neel, 1955) plots after Tauxe et al. (2002) SYNTAX dayplot_magic.py [command line options] OPTIONS -h prints help message and quits -f: specify input hysteresis file, default is specimens.txt -fmt [svg,png,jpg] format for output plots -sav saves plots and quits quietly """ args = sys.argv if "-h" in args: print(main.__doc__) sys.exit() verbose = pmagplotlib.verbose dir_path = pmag.get_named_arg_from_sys('-WD', '.') fmt = pmag.get_named_arg_from_sys('-fmt', 'svg') if '-sav' in sys.argv: plots = 1 verbose = False else: plots = 0 infile = pmag.get_named_arg_from_sys("-f", "specimens.txt") fnames = {'specimens': infile} con = nb.Contribution(dir_path, read_tables=['specimens'], custom_filenames=fnames) spec_container = con.tables['specimens'] spec_df = spec_container.df # # initialize some variables # define figure numbers for Day,S-Bc,S-Bcr DSC = {} DSC['day'], DSC['S-Bc'], DSC['S-Bcr'], DSC['bcr1-bcr2'] = 1, 2, 3, 4 pmagplotlib.plot_init(DSC['day'], 5, 5) pmagplotlib.plot_init(DSC['S-Bc'], 5, 5) pmagplotlib.plot_init(DSC['S-Bcr'], 5, 5) pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5) S, BcrBc, Bcr2, Bc, hsids, Bcr = [], [], [], [], [], [] Bcr1, Bcr1Bc, S1 = [], [], [] locations = '' if 'location' in spec_df.columns: locations = spec_df['location'].unique() do_rem = bool('rem_bcr' in spec_df.columns) for ind, row in spec_df.iterrows(): if row['hyst_bcr'] and row['hyst_mr_moment']: S.append(old_div(float(row['hyst_mr_moment']), float(row['hyst_ms_moment']))) Bcr.append(float(row['hyst_bcr'])) Bc.append(float(row['hyst_bc'])) BcrBc.append(old_div(Bcr[-1], Bc[-1])) hsids.append(row['specimen']) if do_rem: if row['rem_bcr'] and float(row['rem_bcr']) > 0: try: Bcr1.append(float(row['rem_bcr'])) Bcr1Bc.append(old_div(Bcr1[-1], Bc[-1])) S1.append(S[-1]) Bcr2.append(Bcr[-1]) except ValueError: if verbose: print('hysteresis data for ', row['specimen'], end=' ') print(' not found') # # now plot the day and S-Bc, S-Bcr plots # if len(Bcr1) > 0: pmagplotlib.plotDay(DSC['day'], Bcr1Bc, S1, 'ro') pmagplotlib.plotSBcr(DSC['S-Bcr'], Bcr1, S1, 'ro') pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5) pmagplotlib.plotBcr(DSC['bcr1-bcr2'], Bcr1, Bcr2) else: del DSC['bcr1-bcr2'] pmagplotlib.plotDay(DSC['day'], BcrBc, S, 'bs') pmagplotlib.plotSBcr(DSC['S-Bcr'], Bcr, S, 'bs') pmagplotlib.plotSBc(DSC['S-Bc'], Bc, S, 'bs') files = {} if len(locations) > 0: locations = locations[:-1] for key in list(DSC.keys()): if pmagplotlib.isServer: # use server plot naming convention files[key] = 'LO:_' + locations + '_' + 'SI:__SA:__SP:__TY:_' + key + '_.' + fmt else: # use more readable plot naming convention files[key] = '{}_{}.{}'.format(locations, key, fmt) if verbose: pmagplotlib.drawFIGS(DSC) ans = input(" S[a]ve to save plots, return to quit: ") if ans == "a": pmagplotlib.saveP(DSC, files) else: sys.exit() if plots: pmagplotlib.saveP(DSC, files)
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
def main(): """ NAME lowrie.py DESCRIPTION plots intensity decay curves for Lowrie experiments SYNTAX lowrie -h [command line options] INPUT takes SIO formatted input files OPTIONS -h prints help message and quits -f FILE: specify input file -N do not normalize by maximum magnetization -fmt [svg, pdf, eps, png] specify fmt, default is svg -sav save plots and quit """ fmt, plot = 'svg', 0 FIG = {} # plot dictionary FIG['lowrie'] = 1 # demag is figure 1 pmagplotlib.plot_init(FIG['lowrie'], 6, 6) norm = 1 # default is to normalize by maximum axis if len(sys.argv) > 1: if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-N' in sys.argv: norm = 0 # don't normalize if '-sav' in sys.argv: plot = 1 # don't normalize if '-fmt' in sys.argv: # sets input filename ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] if '-f' in sys.argv: # sets input filename ind = sys.argv.index("-f") in_file = sys.argv[ind + 1] else: print(main.__doc__) print('you must supply a file name') sys.exit() else: print(main.__doc__) print('you must supply a file name') sys.exit() data = pmag.open_file(in_file) PmagRecs = [] # set up a list for the results keys = ['specimen', 'treatment', 'csd', 'M', 'dec', 'inc'] for line in data: PmagRec = {} rec = line.replace('\n', '').split() for k in range(len(keys)): PmagRec[keys[k]] = rec[k] PmagRecs.append(PmagRec) specs = pmag.get_dictkey(PmagRecs, 'specimen', '') sids = [] for spec in specs: if spec not in sids: sids.append(spec) # get list of unique specimen names for spc in sids: # step through the specimen names print(spc) specdata = pmag.get_dictitem(PmagRecs, 'specimen', spc, 'T') # get all this one's data DIMs, Temps = [], [] for dat in specdata: # step through the data DIMs.append( [float(dat['dec']), float(dat['inc']), float(dat['M']) * 1e-3]) Temps.append(float(dat['treatment'])) carts = pmag.dir2cart(DIMs).transpose() # if norm==1: # want to normalize # nrm=max(max(abs(carts[0])),max(abs(carts[1])),max(abs(carts[2]))) # by maximum of x,y,z values # ylab="M/M_max" if norm == 1: # want to normalize nrm = (DIMs[0][2]) # normalize by NRM ylab = "M/M_o" else: nrm = 1. # don't normalize ylab = "Magnetic moment (Am^2)" xlab = "Temperature (C)" pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[0]), nrm), sym='r-') pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[0]), nrm), sym='ro') # X direction pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[1]), nrm), sym='c-') pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[1]), nrm), sym='cs') # Y direction pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[2]), nrm), sym='k-') pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[2]), nrm), sym='k^', title=spc, xlab=xlab, ylab=ylab) # Z direction files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt} if plot == 0: pmagplotlib.drawFIGS(FIG) ans = input('S[a]ve figure? [q]uit, <return> to continue ') if ans == 'a': pmagplotlib.saveP(FIG, files) elif ans == 'q': sys.exit() else: pmagplotlib.saveP(FIG, files) pmagplotlib.clearFIG(FIG['lowrie'])
def main(): """ NAME dmag_magic.py DESCRIPTION plots intensity decay curves for demagnetization experiments SYNTAX dmag_magic -h [command line options] INPUT takes magic formatted magic_measurements.txt files OPTIONS -h prints help message and quits -f FILE: specify input file, default is: magic_measurements.txt -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is by location -LT [AF,T,M]: specify lab treatment type, default AF -XLP [PI]: exclude specific lab protocols, (for example, method codes like LP-PI) -N do not normalize by NRM magnetization -sav save plots silently and quit -fmt [svg,jpg,png,pdf] set figure format [default is svg] NOTE loc: location (study); sit: site; sam: sample; spc: specimen """ if '-h' in sys.argv: print(main.__doc__) sys.exit() # initialize variables from command line + defaults FIG = {} # plot dictionary FIG['demag'] = 1 # demag is figure 1 in_file = pmag.get_named_arg_from_sys("-f", default_val="measurements.txt") plot_by = pmag.get_named_arg_from_sys("-obj", default_val="loc") name_dict = { 'loc': 'location', 'sit': 'site', 'sam': 'sample', 'spc': 'specimen' } plot_key = name_dict[plot_by] LT = "LT-" + pmag.get_named_arg_from_sys("-LT", "AF") + "-Z" if LT == "LT-T-Z": units, dmag_key = 'K', 'treat_temp' elif LT == "LT-AF-Z": units, dmag_key = 'T', 'treat_ac_field' elif LT == 'LT-M-Z': units, dmag_key = 'J', 'treat_mw_energy' else: units = 'U' no_norm = pmag.get_flag_arg_from_sys("-N") norm = 0 if no_norm else 1 no_plot = pmag.get_flag_arg_from_sys("-sav") plot = 0 if no_plot else 1 fmt = pmag.get_named_arg_from_sys("-fmt", "svg") XLP = pmag.get_named_arg_from_sys("-XLP", "") dir_path = pmag.get_named_arg_from_sys("-WD", os.getcwd()) spec_file = pmag.get_named_arg_from_sys("-fsp", default_val="specimens.txt") samp_file = pmag.get_named_arg_from_sys("-fsa", default_val="samples.txt") site_file = pmag.get_named_arg_from_sys("-fsi", default_val="sites.txt") # create contribution and add required headers fnames = {"specimens": spec_file, "samples": samp_file, 'sites': site_file} contribution = nb.Contribution(dir_path, single_file=in_file, custom_filenames=fnames) file_type = list(contribution.tables.keys())[0] print(len(contribution.tables['measurements'].df), ' records read from ', in_file) # add plot_key into measurements table if plot_key not in contribution.tables['measurements'].df.columns: #contribution.propagate_name_down(plot_key, 'measurements') contribution.propagate_location_to_measurements() data_container = contribution.tables[file_type] # pare down to only records with useful data # grab records that have the requested code data_slice = data_container.get_records_for_code(LT) # and don't have the offending code data = data_container.get_records_for_code(XLP, incl=False, use_slice=True, sli=data_slice, strict_match=False) # make sure quality is in the dataframe if 'quality' not in data.columns: data['quality'] = 'g' # get intensity key and make sure intensity data is not blank intlist = ['magn_moment', 'magn_volume', 'magn_mass'] IntMeths = [col_name for col_name in data.columns if col_name in intlist] # get rid of any entirely blank intensity columns for col_name in IntMeths: if not data[col_name].any(): data.drop(col_name, axis=1, inplace=True) IntMeths = [col_name for col_name in data.columns if col_name in intlist] if len(IntMeths) == 0: print('No intensity headers found') sys.exit() int_key = IntMeths[ 0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used data = data[data[int_key].notnull()] # make list of individual plots # by default, will be by location_name plotlist = data[plot_key].unique() plotlist.sort() pmagplotlib.plot_init(FIG['demag'], 5, 5) # iterate through and plot the data for plt in plotlist: plot_data = data[data[plot_key] == plt].copy() if plot: print(plt, 'plotting by: ', plot_key) if len(plot_data) > 2: title = plt spcs = [] spcs = plot_data['specimen'].unique() for spc in spcs: INTblock = [] spec_data = plot_data[plot_data['specimen'] == spc] for ind, rec in spec_data.iterrows(): INTblock.append([ float(rec[dmag_key]), 0, 0, float(rec[int_key]), 1, rec['quality'] ]) if len(INTblock) > 2: pmagplotlib.plotMT(FIG['demag'], INTblock, title, 0, units, norm) if not plot: files = {} for key in list(FIG.keys()): files[key] = title + '_' + LT + '.' + fmt pmagplotlib.saveP(FIG, files) #sys.exit() else: pmagplotlib.drawFIGS(FIG) prompt = " S[a]ve to save plot, [q]uit, Return to continue: " ans = input(prompt) if ans == 'q': sys.exit() if ans == "a": files = {} for key in list(FIG.keys()): files[key] = title + '_' + LT + '.' + fmt pmagplotlib.saveP(FIG, files) pmagplotlib.clearFIG(FIG['demag'])
def main(): """ NAME irmaq_magic.py DESCRIPTION plots IRM acquisition curves from magic_measurements file SYNTAX irmaq_magic [command line options] INPUT takes magic formatted magic_measurements.txt files OPTIONS -h prints help message and quits -f FILE: specify input file, default is: magic_measurements.txt -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is by location -N ; do not normalize by last point - use original units -fmt [png,jpg,eps,pdf] set plot file format [default is svg] -sav save plot[s] and quit NOTE loc: location (study); sit: site; sam: sample; spc: specimen """ FIG = {} # plot dictionary FIG['exp'] = 1 # exp is figure 1 dir_path = './' plot, fmt = 0, 'svg' units, dmag_key = 'T', 'treatment_dc_field' XLP = [] norm = 1 in_file, plot_key, LP = 'magic_measurements.txt', 'er_location_name', "LP-IRM" if len(sys.argv) > 1: if '-h' in sys.argv: print main.__doc__ sys.exit() if '-N' in sys.argv: norm = 0 if '-sav' in sys.argv: plot = 1 if '-fmt' in sys.argv: ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] if '-f' in sys.argv: ind = sys.argv.index("-f") in_file = sys.argv[ind + 1] if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path = sys.argv[ind + 1] in_file = dir_path + '/' + in_file if '-obj' in sys.argv: ind = sys.argv.index('-obj') plot_by = sys.argv[ind + 1] if plot_by == 'sit': plot_key = 'er_site_name' if plot_by == 'sam': plot_key = 'er_sample_name' if plot_by == 'spc': plot_key = 'er_specimen_name' data, file_type = pmag.magic_read(in_file) sids = pmag.get_specs(data) pmagplotlib.plot_init(FIG['exp'], 6, 6) # # # find desired intensity data # # get plotlist # plotlist, intlist = [], [ 'measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume', 'measurement_magn_mass' ] IntMeths = [] data = pmag.get_dictitem( data, 'magic_method_codes', LP, 'has') # get all the records with this lab protocol Ints = {} NoInts, int_key = 1, "" for key in intlist: Ints[key] = pmag.get_dictitem( data, key, '', 'F') # get all non-blank data for intensity type if len(Ints[key]) > 0: NoInts = 0 if int_key == "": int_key = key if NoInts == 1: print 'No intensity information found' sys.exit() for rec in Ints[int_key]: if rec[plot_key] not in plotlist: plotlist.append(rec[plot_key]) plotlist.sort() for plt in plotlist: print plt INTblock = [] data = pmag.get_dictitem( Ints[int_key], plot_key, plt, 'T' ) # get data with right intensity info whose plot_key matches plot sids = pmag.get_specs( data) # get a list of specimens with appropriate data if len(sids) > 0: title = data[0][plot_key] for s in sids: INTblock = [] sdata = pmag.get_dictitem(data, 'er_specimen_name', s, 'T') # get data for each specimen for rec in sdata: INTblock.append( [float(rec[dmag_key]), 0, 0, float(rec[int_key]), 1, 'g']) pmagplotlib.plotMT(FIG['exp'], INTblock, title, 0, units, norm) files = {} for key in FIG.keys(): files[key] = title + '_' + LP + '.' + fmt if plot == 0: 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) else: pmagplotlib.saveP(FIG, files) pmagplotlib.clearFIG(FIG['exp'])
def main(): """ NAME revtest.py DESCRIPTION calculates bootstrap statistics to test for antipodality INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX revtest.py [-h] [command line options] OPTION -h prints help message and quits -f FILE, sets input filename on command line -fmt [svg,png,jpg], sets format for image output -sav saves the figures silently and quits """ fmt,plot='svg',0 if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] data=numpy.loadtxt(file).transpose() D=numpy.array([data[0],data[1]]).transpose() else: print('-f is a required switch') print(main.__doc__) print(sys.exit()) if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-sav' in sys.argv:plot=1 # set up plots d="" CDF={'X':1,'Y':2,'Z':3} pmagplotlib.plot_init(CDF['X'],5,5) pmagplotlib.plot_init(CDF['Y'],5,5) pmagplotlib.plot_init(CDF['Z'],5,5) # # flip reverse mode # D1,D2=pmag.flip(D) counter,NumSims=0,500 # # get bootstrapped means for each data set # print('doing first mode, be patient') BDI1=pmag.di_boot(D1) print('doing second mode, be patient') BDI2=pmag.di_boot(D2) pmagplotlib.plotCOM(CDF,BDI1,BDI2,[""]) files={} for key in list(CDF.keys()): files[key]='REV'+'_'+key+'.'+fmt if plot==0: pmagplotlib.drawFIGS(CDF) ans= input("s[a]ve plots, [q]uit: ") if ans=='a': pmagplotlib.saveP(CDF,files) print('good bye') sys.exit() else: pmagplotlib.saveP(CDF,files)
def main(): """ NAME eqarea_ell.py DESCRIPTION makes equal area projections from declination/inclination data and plot ellipses SYNTAX eqarea_ell.py -h [command line options] INPUT takes space delimited Dec/Inc data OPTIONS -h prints help message and quits -f FILE -fmt [svg,png,jpg] format for output plots -sav saves figures and quits -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors """ FIG={} # plot dictionary FIG['eq']=1 # eqarea is figure 1 fmt,dist,mode,plot='svg','F',1,0 sym={'lower':['o','r'],'upper':['o','w'],'size':10} plotE=0 if '-h' in sys.argv: print main.__doc__ sys.exit() pmagplotlib.plot_init(FIG['eq'],5,5) if '-sav' in sys.argv:plot=1 if '-f' in sys.argv: ind=sys.argv.index("-f") title=sys.argv[ind+1] data=numpy.loadtxt(title).transpose() if '-ell' in sys.argv: plotE=1 ind=sys.argv.index('-ell') ell_type=sys.argv[ind+1] if ell_type=='F':dist='F' if ell_type=='K':dist='K' if ell_type=='B':dist='B' if ell_type=='Be':dist='BE' if ell_type=='Bv': dist='BV' FIG['bdirs']=2 pmagplotlib.plot_init(FIG['bdirs'],5,5) if '-fmt' in sys.argv: ind=sys.argv.index("-fmt") fmt=sys.argv[ind+1] DIblock=numpy.array([data[0],data[1]]).transpose() if len(DIblock)>0: pmagplotlib.plotEQsym(FIG['eq'],DIblock,title,sym) if plot==0:pmagplotlib.drawFIGS(FIG) else: print "no data to plot" sys.exit() if plotE==1: ppars=pmag.doprinc(DIblock) # get principal directions nDIs,rDIs,npars,rpars=[],[],[],[] for rec in DIblock: angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']]) if angle>90.: rDIs.append(rec) else: nDIs.append(rec) if dist=='B': # do on whole dataset etitle="Bingham confidence ellipse" bpars=pmag.dobingham(DIblock) for key in bpars.keys(): if key!='n' and pmagplotlib.verbose:print " ",key, '%7.1f'%(bpars[key]) if key=='n' and pmagplotlib.verbose:print " ",key, ' %i'%(bpars[key]) npars.append(bpars['dec']) npars.append(bpars['inc']) npars.append(bpars['Zeta']) npars.append(bpars['Zdec']) npars.append(bpars['Zinc']) npars.append(bpars['Eta']) npars.append(bpars['Edec']) npars.append(bpars['Einc']) if dist=='F': etitle="Fisher confidence cone" if len(nDIs)>3: fpars=pmag.fisher_mean(nDIs) for key in fpars.keys(): if key!='n' and pmagplotlib.verbose:print " ",key, '%7.1f'%(fpars[key]) if key=='n' and pmagplotlib.verbose:print " ",key, ' %i'%(fpars[key]) mode+=1 npars.append(fpars['dec']) npars.append(fpars['inc']) npars.append(fpars['alpha95']) # Beta npars.append(fpars['dec']) isign=abs(fpars['inc'])/fpars['inc'] npars.append(fpars['inc']-isign*90.) #Beta inc npars.append(fpars['alpha95']) # gamma npars.append(fpars['dec']+90.) # Beta dec npars.append(0.) #Beta inc if len(rDIs)>3: fpars=pmag.fisher_mean(rDIs) if pmagplotlib.verbose:print "mode ",mode for key in fpars.keys(): if key!='n' and pmagplotlib.verbose:print " ",key, '%7.1f'%(fpars[key]) if key=='n' and pmagplotlib.verbose:print " ",key, ' %i'%(fpars[key]) mode+=1 rpars.append(fpars['dec']) rpars.append(fpars['inc']) rpars.append(fpars['alpha95']) # Beta rpars.append(fpars['dec']) isign=abs(fpars['inc'])/fpars['inc'] rpars.append(fpars['inc']-isign*90.) #Beta inc rpars.append(fpars['alpha95']) # gamma rpars.append(fpars['dec']+90.) # Beta dec rpars.append(0.) #Beta inc if dist=='K': etitle="Kent confidence ellipse" if len(nDIs)>3: kpars=pmag.dokent(nDIs,len(nDIs)) if pmagplotlib.verbose:print "mode ",mode for key in kpars.keys(): if key!='n' and pmagplotlib.verbose:print " ",key, '%7.1f'%(kpars[key]) if key=='n' and pmagplotlib.verbose:print " ",key, ' %i'%(kpars[key]) mode+=1 npars.append(kpars['dec']) npars.append(kpars['inc']) npars.append(kpars['Zeta']) npars.append(kpars['Zdec']) npars.append(kpars['Zinc']) npars.append(kpars['Eta']) npars.append(kpars['Edec']) npars.append(kpars['Einc']) if len(rDIs)>3: kpars=pmag.dokent(rDIs,len(rDIs)) if pmagplotlib.verbose:print "mode ",mode for key in kpars.keys(): if key!='n' and pmagplotlib.verbose:print " ",key, '%7.1f'%(kpars[key]) if key=='n' and pmagplotlib.verbose:print " ",key, ' %i'%(kpars[key]) mode+=1 rpars.append(kpars['dec']) rpars.append(kpars['inc']) rpars.append(kpars['Zeta']) rpars.append(kpars['Zdec']) rpars.append(kpars['Zinc']) rpars.append(kpars['Eta']) rpars.append(kpars['Edec']) rpars.append(kpars['Einc']) else: # assume bootstrap if len(nDIs)<10 and len(rDIs)<10: print 'too few data points for bootstrap' sys.exit() if dist=='BE': print 'Be patient for bootstrap...' if len(nDIs)>=10: BnDIs=pmag.di_boot(nDIs) Bkpars=pmag.dokent(BnDIs,1.) if pmagplotlib.verbose:print "mode ",mode for key in Bkpars.keys(): if key!='n' and pmagplotlib.verbose:print " ",key, '%7.1f'%(Bkpars[key]) if key=='n' and pmagplotlib.verbose:print " ",key, ' %i'%(Bkpars[key]) mode+=1 npars.append(Bkpars['dec']) npars.append(Bkpars['inc']) npars.append(Bkpars['Zeta']) npars.append(Bkpars['Zdec']) npars.append(Bkpars['Zinc']) npars.append(Bkpars['Eta']) npars.append(Bkpars['Edec']) npars.append(Bkpars['Einc']) if len(rDIs)>=10: BrDIs=pmag.di_boot(rDIs) Bkpars=pmag.dokent(BrDIs,1.) if pmagplotlib.verbose:print "mode ",mode for key in Bkpars.keys(): if key!='n' and pmagplotlib.verbose:print " ",key, '%7.1f'%(Bkpars[key]) if key=='n' and pmagplotlib.verbose:print " ",key, ' %i'%(Bkpars[key]) mode+=1 rpars.append(Bkpars['dec']) rpars.append(Bkpars['inc']) rpars.append(Bkpars['Zeta']) rpars.append(Bkpars['Zdec']) rpars.append(Bkpars['Zinc']) rpars.append(Bkpars['Eta']) rpars.append(Bkpars['Edec']) rpars.append(Bkpars['Einc']) etitle="Bootstrapped confidence ellipse" elif dist=='BV': print 'Be patient for bootstrap...' vsym={'lower':['+','k'],'upper':['x','k'],'size':5} if len(nDIs)>5: BnDIs=pmag.di_boot(nDIs) pmagplotlib.plotEQsym(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors',vsym) if len(rDIs)>5: BrDIs=pmag.di_boot(rDIs) if len(nDIs)>5: # plot on existing plots pmagplotlib.plotDIsym(FIG['bdirs'],BrDIs,vsym) else: pmagplotlib.plotEQ(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors',vsym) if dist=='B': if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plotCONF(FIG['eq'],etitle,[],npars,0) elif len(nDIs)>3 and dist!='BV': pmagplotlib.plotCONF(FIG['eq'],etitle,[],npars,0) if len(rDIs)>3: pmagplotlib.plotCONF(FIG['eq'],etitle,[],rpars,0) elif len(rDIs)>3 and dist!='BV': pmagplotlib.plotCONF(FIG['eq'],etitle,[],rpars,0) if plot==0:pmagplotlib.drawFIGS(FIG) if plot==0:pmagplotlib.drawFIGS(FIG) # files={} for key in FIG.keys(): files[key]=title+'_'+key+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='Equal Area Plot' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) elif plot==0: ans=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) else: pmagplotlib.saveP(FIG,files)
def main(): """ NAME hysteresis_magic.py DESCRIPTION calculates hystereis parameters and saves them in 3.0 specimen format file makes plots if option selected SYNTAX hysteresis_magic.py [command line options] OPTIONS -h prints help message and quits -f: specify input file, default is agm_measurements.txt -F: specify specimens.txt output file -P: do not make the plots -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg] """ args=sys.argv PLT=1 plots=0 fmt=pmag.get_named_arg_from_sys('-fmt','svg') dir_path=pmag.get_named_arg_from_sys('-WD','.') dir_path=os.path.realpath(dir_path) verbose=pmagplotlib.verbose version_num=pmag.get_version() user=pmag.get_named_arg_from_sys('-usr','') if "-h" in args: print(main.__doc__) sys.exit() meas_file=pmag.get_named_arg_from_sys('-f','agm_measurements.txt') spec_file=pmag.get_named_arg_from_sys('-F','specimens.txt') if '-P' in args: PLT=0 irm_init,imag_init=-1,-1 if '-sav' in args: verbose=0 plots=1 pltspec=pmag.get_named_arg_from_sys('-spc',0) if pltspec: #pltspec= args[ind+1] verbose=0 plots=1 spec_file=dir_path+'/'+spec_file meas_file=dir_path+'/'+meas_file SpecRecs=[] # # meas_data,file_type=pmag.magic_read(meas_file) if file_type!='measurements': print(main.__doc__) print('bad file') sys.exit() # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs,RemRecs=[],[] HDD={} if verbose: if verbose and PLT:print("Plots may be on top of each other - use mouse to place ") if PLT: HDD['hyst'],HDD['deltaM'],HDD['DdeltaM']=1,2,3 pmagplotlib.plot_init(HDD['DdeltaM'],5,5) pmagplotlib.plot_init(HDD['deltaM'],5,5) pmagplotlib.plot_init(HDD['hyst'],5,5) imag_init=0 irm_init=0 else: HDD['hyst'],HDD['deltaM'],HDD['DdeltaM'],HDD['irm'],HDD['imag']=0,0,0,0,0 # if spec_file: prior_data,file_type=pmag.magic_read(spec_file) # # get list of unique experiment names and specimen names # experiment_names,sids=[],[] hys_data=pmag.get_dictitem(meas_data,'method_codes','LP-HYS','has') dcd_data=pmag.get_dictitem(meas_data,'method_codes','LP-IRM-DCD','has') imag_data=pmag.get_dictitem(meas_data,'method_codes','LP-IMAG','has') for rec in hys_data: if rec['experiment'] not in experiment_names:experiment_names.append(rec['experiment']) if rec['specimen'] not in sids:sids.append(rec['specimen']) # k=0 if pltspec: k=sids.index(pltspec) print(sids[k]) while k < len(sids): specimen=sids[k] HystRec={'specimen':specimen,'experiment':""} # initialize a new specimen hysteresis record if verbose and PLT:print(specimen, k+1 , 'out of ',len(sids)) # # B,M,Bdcd,Mdcd=[],[],[],[] #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data Bimag,Mimag=[],[] #Bimag,Mimag for initial magnetization curves spec_data=pmag.get_dictitem(hys_data,'specimen',specimen,'T') # fish out all the LP-HYS data for this specimen if len(spec_data)>0: meths=spec_data[0]['method_codes'].split(':') e=spec_data[0]['experiment'] HystRec['experiment']=spec_data[0]['experiment'] for rec in spec_data: B.append(float(rec['meas_field_dc'])) M.append(float(rec['magn_moment'])) spec_data=pmag.get_dictitem(dcd_data,'specimen',specimen,'T') # fish out all the data for this specimen if len(spec_data)>0: HystRec['experiment']=HystRec['experiment']+':'+spec_data[0]['experiment'] irm_exp=spec_data[0]['experiment'] for rec in spec_data: Bdcd.append(float(rec['treat_dc_field'])) Mdcd.append(float(rec['magn_moment'])) spec_data=pmag.get_dictitem(imag_data,'specimen',specimen,'T') # fish out all the data for this specimen if len(spec_data)>0: imag_exp=spec_data[0]['experiment'] for rec in spec_data: Bimag.append(float(rec['meas_field_dc'])) Mimag.append(float(rec['magn_moment'])) # # now plot the hysteresis curve # if len(B)>0: hmeths=[] for meth in meths: hmeths.append(meth) hpars=pmagplotlib.plotHDD(HDD,B,M,e) if verbose and PLT:pmagplotlib.drawFIGS(HDD) # if verbose:pmagplotlib.plotHPARS(HDD,hpars,'bs') HystRec['hyst_mr_moment']=hpars['hysteresis_mr_moment'] HystRec['hyst_ms_moment']=hpars['hysteresis_ms_moment'] HystRec['hyst_bc']=hpars['hysteresis_bc'] HystRec['hyst_bcr']=hpars['hysteresis_bcr'] HystRec['susc_h']=hpars['hysteresis_xhf'] HystRec['experiments']=e HystRec['software_packages']=version_num if hpars["magic_method_codes"] not in hmeths:hmeths.append(hpars["magic_method_codes"]) methods="" for meth in hmeths: methods=methods+meth.strip()+":" HystRec["method_codes"]=methods[:-1] HystRec["citations"]="This study" # if len(Bdcd)>0: rmeths=[] for meth in meths: rmeths.append(meth) if verbose and PLT:print('plotting IRM') if irm_init==0: HDD['irm']=5 pmagplotlib.plot_init(HDD['irm'],5,5) irm_init=1 rpars=pmagplotlib.plotIRM(HDD['irm'],Bdcd,Mdcd,irm_exp) HystRec['rem_mr_moment']=rpars['remanence_mr_moment'] HystRec['rem_bcr']=rpars['remanence_bcr'] HystRec['experiments']=specimen+':'+irm_exp if rpars["magic_method_codes"] not in meths:meths.append(rpars["magic_method_codes"]) methods="" for meth in rmeths: methods=methods+meth.strip()+":" HystRec["method_codes"]=HystRec['method_codes']+':'+methods[:-1] HystRec["citations"]="This study" else: if irm_init:pmagplotlib.clearFIG(HDD['irm']) if len(Bimag)>0: if verbose and PLT:print('plotting initial magnetization curve') # first normalize by Ms Mnorm=[] for m in Mimag: Mnorm.append(old_div(m,float(hpars['hysteresis_ms_moment']))) if imag_init==0: HDD['imag']=4 pmagplotlib.plot_init(HDD['imag'],5,5) imag_init=1 pmagplotlib.plotIMAG(HDD['imag'],Bimag,Mnorm,imag_exp) else: if imag_init:pmagplotlib.clearFIG(HDD['imag']) if len(list(HystRec.keys()))>0:HystRecs.append(HystRec) # files={} if plots: if pltspec:s=pltspec files={} for key in list(HDD.keys()): files[key]=s+'_'+key+'.'+fmt pmagplotlib.saveP(HDD,files) if pltspec:sys.exit() if verbose and PLT: pmagplotlib.drawFIGS(HDD) ans=input("S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ") if ans=="a": files={} for key in list(HDD.keys()): files[key]=specimen+'_'+key+'.'+fmt pmagplotlib.saveP(HDD,files) if ans=='':k+=1 if ans=="p": del HystRecs[-1] k-=1 if ans=='q': print("Good bye") sys.exit() if ans=='s': keepon=1 specimen=input('Enter desired specimen name (or first part there of): ') while keepon==1: try: k =sids.index(specimen) keepon=0 except: tmplist=[] for qq in range(len(sids)): if specimen in sids[qq]:tmplist.append(sids[qq]) print(specimen," not found, but this was: ") print(tmplist) specimen=input('Select one or try again\n ') k =sids.index(specimen) else: k+=1 if len(B)==0 and len(Bdcd)==0: if verbose:print('skipping this one - no hysteresis data') k+=1 if len(HystRecs)>0: # go through prior_data, clean out prior results and save combined file as spec_file SpecRecs,keys=[],list(HystRecs[0].keys()) if len(prior_data)>0: prior_keys=list(prior_data[0].keys()) else: prior_keys=[] for rec in prior_data: for key in keys: if key not in list(rec.keys()):rec[key]="" if 'LP-HYS' not in rec['method_codes']: SpecRecs.append(rec) for rec in HystRecs: for key in prior_keys: if key not in list(rec.keys()):rec[key]="" prior=pmag.get_dictitem(prior_data,'specimen',rec['specimen'],'T') if len(prior)>0 and 'sample' in list(prior[0].keys()): rec['sample']=prior[0]['sample'] # pull sample name from prior specimens table SpecRecs.append(rec) pmag.magic_write(spec_file,SpecRecs,"specimens") if verbose:print("hysteresis parameters saved in ",spec_file)
def main(): """ NAME chi_magic.py DESCRIPTION plots magnetic susceptibility as a function of frequency and temperature and AC field SYNTAX chi_magic.py [command line options] OPTIONS -h prints help message and quits -i allows interactive setting of FILE and temperature step -f FILE, specify magic_measurements format file -T IND, specify temperature step to plot -e EXP, specify experiment name to plot -fmt [svg,jpg,png,pdf] set figure format [default is svg] -sav save figure and quit DEFAULTS FILE: magic_measurements.txt IND: first SPEC: step through one by one """ cont, FTinit, BTinit, k = "", 0, 0, 0 meas_file = "magic_measurements.txt" spec = "" Tind, cont = 0, "" EXP = "" fmt = 'svg' # default image type for saving plot = 0 if '-h' in sys.argv: print main.__doc__ sys.exit() if '-i' in sys.argv: file = raw_input( "Input magic_measurements file name? [magic_measurements.txt] ") if file != "": meas_file = file if '-e' in sys.argv: ind = sys.argv.index('-e') EXP = sys.argv[ind + 1] if '-f' in sys.argv: ind = sys.argv.index('-f') meas_file = sys.argv[ind + 1] if '-T' in sys.argv: ind = sys.argv.index('-T') Tind = int(sys.argv[ind + 1]) if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-sav' in sys.argv: plot = 1 # meas_data, file_type = pmag.magic_read(meas_file) # # get list of unique experiment names # # initialize some variables (a continuation flag, plot initialization flags and the experiment counter experiment_names = [] for rec in meas_data: if rec['magic_experiment_name'] not in experiment_names: experiment_names.append(rec['magic_experiment_name']) # # hunt through by experiment name if EXP != "": try: k = experiment_names.index(EXP) except: print "Bad experiment name" sys.exit() while k < len(experiment_names): e = experiment_names[k] if EXP == "": print e, k + 1, 'out of ', len(experiment_names) # # initialize lists of data, susceptibility, temperature, frequency and field X, T, F, B = [], [], [], [] for rec in meas_data: methcodes = rec['magic_method_codes'] meths = methcodes.strip().split(':') if rec['magic_experiment_name'] == e and "LP-X" in meths: # looking for chi measurement if 'measurement_temp' not in rec.keys(): rec['measurement_temp'] = '300' # set defaults if 'measurement_freq' not in rec.keys(): rec['measurement_freq'] = '0' # set defaults if 'measurement_lab_field_ac' not in rec.keys(): rec['measurement_lab_field_ac'] = '0' # set default X.append(float(rec['measurement_x'])) T.append(float(rec['measurement_temp'])) F.append(float(rec['measurement_freq'])) B.append(float(rec['measurement_lab_field_ac'])) # # get unique list of Ts,Fs, and Bs # Ts, Fs, Bs = [], [], [] for k in range(len(X)): # hunt through all the measurements if T[k] not in Ts: Ts.append(T[k]) # append if not in list if F[k] not in Fs: Fs.append(F[k]) if B[k] not in Bs: Bs.append(B[k]) Ts.sort() # sort list of temperatures, frequencies and fields Fs.sort() Bs.sort() if '-x' in sys.argv: k = len(experiment_names) + 1 # just plot the one else: k += 1 # increment experiment number # # plot chi versus T and F holding B constant # plotnum = 1 # initialize plot number to 1 if len(X) > 2: # if there are any data to plot, continue b = Bs[-1] # keeping field constant and at maximum XTF = [] # initialize list of chi versus Temp and freq for f in Fs: # step through frequencies sequentially XT = [] # initialize list of chi versus temp for kk in range(len(X)): # hunt through all the data if F[kk] == f and B[ kk] == b: # select data with given freq and field XT.append([X[kk], T[kk]]) # append to list XTF.append(XT) # append list to list of frequencies if len(XT) > 1: # if there are any temperature dependent data pmagplotlib.plot_init(plotnum, 5, 5) # initialize plot pmagplotlib.plotXTF(plotnum, XTF, Fs, e, b) # call the plotting function if plot == 0: pmagplotlib.drawFIGS({'fig': plotnum}) #make it visible plotnum += 1 # increment plot number f = Fs[0] # set frequency to minimum XTB = [] # initialize list if chi versus Temp and field for b in Bs: # step through field values XT = [] # initial chi versus temp list for this field for kk in range(len(X)): # hunt through all the data if F[kk] == f and B[ kk] == b: # select data with given freq and field XT.append([X[kk], T[kk]]) # append to list XTB.append(XT) if len(XT) > 1: # if there are any temperature dependent data pmagplotlib.plot_init(plotnum, 5, 5) # set up plot pmagplotlib.plotXTB(plotnum, XTB, Bs, e, f) # call the plotting function if plot == 0: pmagplotlib.drawFIGS({'fig': plotnum}) plotnum += 1 # increment plot number if '-i' in sys.argv: for ind in range( len(Ts)): # print list of temperatures available print ind, int(Ts[ind]) cont = raw_input( "Enter index of desired temperature step, s[a]ve plots, [return] to quit " ) if cont == 'a': files = {} PLTS = {} for p in range(1, plotnum): key = str(p) files[key] = e + '_' + key + '.' + fmt PLTS[key] = key pmagplotlib.saveP(PLTS, files) cont = raw_input( "Enter index of desired temperature step, s[a]ve plots, [return] to quit " ) if cont == "": cont = 'q' while cont != "q": if '-i' in sys.argv: Tind = int(cont) # set temperature index b = Bs[-1] # set field to max available XF = [] # initial chi versus frequency list for kk in range(len(X)): # hunt through the data if T[kk] == Ts[Tind] and B[ kk] == b: # if temperature and field match, XF.append([X[kk], F[kk]]) # append the data if len(XF) > 1: # if there are any data to plot if FTinit == 0: # if not already initialized, initialize plot #print 'initializing ',plotnum pmagplotlib.plot_init(plotnum, 5, 5) FTinit = 1 XFplot = plotnum plotnum += 1 # increment plotnum pmagplotlib.plotXFT(XFplot, XF, Ts[Tind], e, b) if plot == 0: pmagplotlib.drawFIGS({'fig': plotnum}) else: print '\n *** Skipping susceptibitily-frequency plot as a function of temperature *** \n' f = Fs[0] # set frequency to minimum available XB = [] # initialize chi versus field list for kk in range(len(X)): # hunt through the data if T[kk] == Ts[Tind] and F[ kk] == f: # if temperature and field match those desired XB.append([X[kk], B[kk]]) # append the data to list if len(XB) > 4: # if there are any data if BTinit == 0: # if plot not already initialized pmagplotlib.plot_init(plotnum, 5, 5) # do it BTinit = 1 pmagplotlib.plotXBT(plotnum, XB, Ts[Tind], e, f) # and call plotting function if plot == 0: pmagplotlib.drawFIGS({'fig': plotnum}) else: print 'Skipping susceptibitily - AC field plot as a function of temperature' files = {} PLTS = {} for p in range(1, plotnum): key = str(p) files[key] = e + '_' + key + '.' + fmt PLTS[key] = p if '-i' in sys.argv: for ind in range( len(Ts) ): # just in case you forgot, print out a new list of temperatures print ind, int(Ts[ind]) cont = raw_input( "Enter index of next temperature step, s[a]ve plots, [return] to quit " ) # ask for new temp if cont == "": sys.exit() if cont == 'a': pmagplotlib.saveP(PLTS, files) cont = raw_input( "Enter index of desired temperature step, s[a]ve plots, [return] to quit " ) if cont == "": sys.exit() elif plot == 0: ans = raw_input( "enter s[a]ve to save files, [return] to quit ") if ans == 'a': pmagplotlib.saveP(PLTS, files) sys.exit() else: sys.exit() else: pmagplotlib.saveP(PLTS, files) sys.exit()
def main(): """ NAME microwave_magic.py DESCRIPTION plots microwave paleointensity data, allowing interactive setting of bounds. Saves and reads interpretations from a pmag_specimen formatted table, default: microwave_specimens.txt SYNTAX microwave_magic.py [command line options] OPTIONS -h prints help message and quits -f MEAS, set magic_measurements input file -fsp PRIOR, set pmag_specimen prior interpretations file -fcr CRIT, set criteria file for grading. -fmt [svg,png,jpg], format for images - default is svg -sav, saves plots with out review (default format) -spc SPEC, plots single specimen SPEC, saves plot with specified format with optional -b bounds adn quits -b BEG END: sets bounds for calculation BEG: starting step for slope calculation END: ending step for slope calculation DEFAULTS MEAS: magic_measurements.txt CRIT: NONE PRIOR: microwave_specimens.txt OUTPUT figures: ALL: numbers refer to temperature steps in command line window 1) Arai plot: closed circles are zero-field first/infield open circles are infield first/zero-field triangles are pTRM checks squares are pTRM tail checks VDS is vector difference sum diamonds are bounds for interpretation 2) Zijderveld plot: closed (open) symbols are X-Y (X-Z) planes X rotated to NRM direction 3) (De/Re)Magnetization diagram: circles are NRM remaining squares are pTRM gained command line window: list is: temperature step numbers, power (J), Dec, Inc, Int (units of magic_measuements) list of possible commands: type letter followed by return to select option saving of plots creates .svg format files with specimen_name, plot type as name """ # # initializations # meas_file, critout, inspec = "magic_measurements.txt", "", "microwave_specimens.txt" inlt = 0 version_num = pmag.get_version() Tinit, DCZ, field, first_save = 0, 0, -1, 1 user, comment = "", '' ans, specimen, recnum, start, end = 0, 0, 0, 0, 0 plots, pmag_out, samp_file, style = 0, "", "", "svg" fmt = '.' + style # # default acceptance criteria # accept_keys = [ 'specimen_int_ptrm_n', 'specimen_md', 'specimen_fvds', 'specimen_b_beta', 'specimen_dang', 'specimen_drats', 'specimen_Z' ] accept = {} accept['specimen_int_ptrm_n'] = 2 accept['specimen_md'] = 10 accept['specimen_fvds'] = 0.35 accept['specimen_b_beta'] = .1 accept['specimen_int_mad'] = 7 accept['specimen_dang'] = 10 accept['specimen_drats'] = 10 accept['specimen_Z'] = 10 # # parse command line options # spc, BEG, END = "", "", "" if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind = sys.argv.index('-f') meas_file = sys.argv[ind + 1] if '-fsp' in sys.argv: ind = sys.argv.index('-fsp') inspec = sys.argv[ind + 1] if '-fcr' in sys.argv: ind = sys.argv.index('-fcr') critout = sys.argv[ind + 1] if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = '.' + sys.argv[ind + 1] if '-spc' in sys.argv: ind = sys.argv.index('-spc') spc = sys.argv[ind + 1] if '-b' in sys.argv: ind = sys.argv.index('-b') BEG = int(sys.argv[ind + 1]) END = int(sys.argv[ind + 2]) if critout != "": crit_data, file_type = pmag.magic_read(critout) if pmagplotlib.verbose: print "Acceptance criteria read in from ", critout accept = {} accept['specimen_int_ptrm_n'] = 2.0 for critrec in crit_data: if critrec["pmag_criteria_code"] == "IE-SPEC": for key in accept_keys: if key not in critrec.keys(): accept[key] = -1 else: accept[key] = float(critrec[key]) try: open(inspec, 'rU') PriorRecs, file_type = pmag.magic_read(inspec) if file_type != 'pmag_specimens': print file_type print file_type, inspec, " is not a valid pmag_specimens file " sys.exit() for rec in PriorRecs: if 'magic_software_packages' not in rec.keys(): rec['magic_software_packages'] = "" except IOError: PriorRecs = [] if pmagplotlib.verbose: print "starting new specimen interpretation file: ", inspec meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print file_type print file_type, "This is not a valid magic_measurements file " sys.exit() backup = 0 # define figure numbers for arai, zijderveld and # de-,re-magization diagrams AZD = {} AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4 pmagplotlib.plot_init(AZD['arai'], 4, 4) pmagplotlib.plot_init(AZD['zijd'], 4, 4) pmagplotlib.plot_init(AZD['deremag'], 4, 4) pmagplotlib.plot_init(AZD['eqarea'], 4, 4) # # # # get list of unique specimen names # CurrRec = [] sids = pmag.get_specs(meas_data) # get plots for specimen s - default is just to step through arai diagrams # if spc != "": specimen = sids.index(spc) while specimen < len(sids): methcodes = [] if pmagplotlib.verbose and spc != "": print sids[specimen], specimen + 1, 'of ', len(sids) MeasRecs = [] s = sids[specimen] datablock, trmblock = [], [] PmagSpecRec = {} PmagSpecRec["er_analyst_mail_names"] = user PmagSpecRec["specimen_correction"] = 'u' # # find the data from the meas_data file for this specimen # for rec in meas_data: if rec["er_specimen_name"] == s: MeasRecs.append(rec) methods = rec["magic_method_codes"].split(":") meths = [] for meth in methods: meths.append(meth.strip()) # take off annoying spaces methods = "" for meth in meths: if meth.strip() not in methcodes and "LP-" in meth: methcodes.append(meth.strip()) methods = methods + meth + ":" methods = methods[:-1] rec["magic_method_codes"] = methods if "LP-PI-M" in meths: datablock.append(rec) if "LP-MRM" in meths: trmblock.append(rec) if len(trmblock) > 2 and inspec != "": if Tinit == 0: Tinit = 1 AZD['MRM'] = 4 pmagplotlib.plot_init(AZD['MRM'], 4, 4) elif Tinit == 1: pmagplotlib.clearFIG(AZD['MRM']) if len(datablock) < 4: if backup == 0: specimen += 1 if pmagplotlib.verbose: print 'skipping specimen - moving forward ', s else: specimen -= 1 if pmagplotlib.verbose: print 'skipping specimen - moving backward ', s # # collect info for the PmagSpecRec dictionary # else: rec = datablock[0] PmagSpecRec["er_citation_names"] = "This study" PmagSpecRec["er_specimen_name"] = s PmagSpecRec["er_sample_name"] = rec["er_sample_name"] PmagSpecRec["er_site_name"] = rec["er_site_name"] PmagSpecRec["er_location_name"] = rec["er_location_name"] if "magic_instrument_codes" not in rec.keys(): rec["magic_instrument_codes"] = "" PmagSpecRec["magic_instrument_codes"] = rec[ "magic_instrument_codes"] PmagSpecRec["measurement_step_unit"] = "J" if "magic_experiment_name" not in rec.keys(): rec["magic_experiment_name"] = "" else: PmagSpecRec["magic_experiment_names"] = rec[ "magic_experiment_name"] meths = rec["magic_method_codes"].split(':') # sort data into types if "LP-PI-M-D" in meths: # this is a double heating experiment exp_type = "LP-PI-M-D" elif "LP-PI-M-S" in meths: exp_type = "LP-PI-M-S" else: print "experiment type not supported yet " break araiblock, field = pmag.sortmwarai(datablock, exp_type) first_Z = araiblock[0] first_I = araiblock[1] GammaChecks = araiblock[-3] ThetaChecks = araiblock[-2] DeltaChecks = araiblock[-1] if len(first_Z) < 3: if backup == 0: specimen += 1 if pmagplotlib.verbose: print 'skipping specimen - moving forward ', s else: specimen -= 1 if pmagplotlib.verbose: print 'skipping specimen - moving backward ', s else: backup = 0 zijdblock, units = pmag.find_dmag_rec(s, meas_data) if exp_type == "LP-PI-M-D": recnum = 0 print "ZStep Watts Dec Inc Int" for plotrec in zijdblock: if pmagplotlib.verbose: print '%i %i %7.1f %7.1f %8.3e ' % ( recnum, plotrec[0], plotrec[1], plotrec[2], plotrec[3]) recnum += 1 recnum = 1 if GammaChecks != "": print "IStep Watts Gamma" for gamma in GammaChecks: if pmagplotlib.verbose: print '%i %i %7.1f ' % (recnum, gamma[0], gamma[1]) recnum += 1 if exp_type == "LP-PI-M-S": if pmagplotlib.verbose: print "IStep Watts Theta" kk = 0 for theta in ThetaChecks: kk += 1 print '%i %i %7.1f ' % (kk, theta[0], theta[1]) if pmagplotlib.verbose: print "Watts Delta" for delta in DeltaChecks: print '%i %7.1f ' % (delta[0], delta[1]) pmagplotlib.plotAZ(AZD, araiblock, zijdblock, s, units[0]) if inspec != "": if pmagplotlib.verbose: print 'Looking up saved interpretation....' found = 0 for k in range(len(PriorRecs)): try: if PriorRecs[k]["er_specimen_name"] == s: found = 1 CurrRec.append(PriorRecs[k]) for j in range(len(araiblock[0])): if float(araiblock[0][j][0]) == float( PriorRecs[k] ["measurement_step_min"]): start = j if float(araiblock[0][j][0]) == float( PriorRecs[k] ["measurement_step_max"]): end = j pars, errcode = pmag.PintPars( araiblock, zijdblock, start, end) pars['measurement_step_unit'] = "J" del PriorRecs[ k] # put in CurrRec, take out of PriorRecs if errcode != 1: pars["specimen_lab_field_dc"] = field pars["specimen_int"] = -1 * field * pars[ "specimen_b"] pars["er_specimen_name"] = s if pmagplotlib.verbose: print 'Saved interpretation: ' pars = pmag.scoreit( pars, PmagSpecRec, accept, '', 0) pmagplotlib.plotB(AZD, araiblock, zijdblock, pars) if len(trmblock) > 2: blab = field best = pars["specimen_int"] Bs, TRMs = [], [] for trec in trmblock: Bs.append( float( trec['treatment_dc_field']) ) TRMs.append( float(trec[ 'measurement_magn_moment']) ) NLpars = nlt.NLtrm( Bs, TRMs, best, blab, 0 ) # calculate best fit parameters through TRM acquisition data, and get new banc Mp, Bp = [], [] for k in range(int(max(Bs) * 1e6)): Bp.append(float(k) * 1e-6) npred = nlt.TRM( Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1] ) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM( AZD['MRM'], Bs, TRMs, Bp, Mp, NLpars, trec['magic_experiment_name']) print npred print 'Banc= ', float( NLpars['banc']) * 1e6 if pmagplotlib.verbose: print 'Banc= ', float( NLpars['banc']) * 1e6 pmagplotlib.drawFIGS(AZD) else: print 'error on specimen ', s except: pass if pmagplotlib.verbose and found == 0: print ' None found :( ' if spc != "": if BEG != "": pars, errcode = pmag.PintPars(araiblock, zijdblock, BEG, END) pars['measurement_step_unit'] = "J" pars["specimen_lab_field_dc"] = field pars["specimen_int"] = -1 * field * pars["specimen_b"] pars["er_specimen_name"] = s pars['specimen_grade'] = '' # ungraded pmagplotlib.plotB(AZD, araiblock, zijdblock, pars) if len(trmblock) > 2: if inlt == 0: donlt() inlt = 1 blab = field best = pars["specimen_int"] Bs, TRMs = [], [] for trec in trmblock: Bs.append(float(trec['treatment_dc_field'])) TRMs.append( float(trec['measurement_magn_moment'])) NLpars = nlt.NLtrm( Bs, TRMs, best, blab, 0 ) # calculate best fit parameters through TRM acquisition data, and get new banc # Mp, Bp = [], [] for k in range(int(max(Bs) * 1e6)): Bp.append(float(k) * 1e-6) npred = nlt.TRM( Bp[-1], NLpars['xopt'][0], NLpars['xopt'] [1]) # predicted NRM for this field files = {} for key in AZD.keys(): files[key] = s + '_' + key + fmt pmagplotlib.saveP(AZD, files) sys.exit() if plots == 0: ans = 'b' while ans != "": print """ s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit: """ ans = raw_input('Return for next specimen \n') if ans == "": specimen += 1 if ans == "d": save_redo(PriorRecs, inspec) CurrRec = [] pmagplotlib.plotAZ(AZD, araiblock, zijdblock, s, units[0]) pmagplotlib.drawFIGS(AZD) if ans == 'a': files = {} for key in AZD.keys(): files[key] = s + '_' + key + fmt pmagplotlib.saveP(AZD, files) ans = "" if ans == 'q': print "Good bye" sys.exit() if ans == 'p': specimen = specimen - 1 backup = 1 ans = "" if ans == 's': keepon = 1 spec = raw_input( 'Enter desired specimen name (or first part there of): ' ) while keepon == 1: try: specimen = sids.index(spec) keepon = 0 except: tmplist = [] for qq in range(len(sids)): if spec in sids[qq]: tmplist.append(sids[qq]) print specimen, " not found, but this was: " print tmplist spec = raw_input( 'Select one or try again\n ') ans = "" if ans == 'b': if end == 0 or end >= len(araiblock[0]): end = len(araiblock[0]) - 1 GoOn = 0 while GoOn == 0: print 'Enter index of first point for calculation: ', '[', start, ']' answer = raw_input('return to keep default ') if answer != "": start = int(answer) print 'Enter index of last point for calculation: ', '[', end, ']' answer = raw_input('return to keep default ') if answer != "": end = int(answer) if start >= 0 and start < len(araiblock[ 0]) - 2 and end > 0 and end < len( araiblock[0]) and start < end: GoOn = 1 else: print "Bad endpoints - try again! " start, end = 0, len(araiblock) s = sids[specimen] pars, errcode = pmag.PintPars( araiblock, zijdblock, start, end) pars['measurement_step_unit'] = "J" pars["specimen_lab_field_dc"] = field pars["specimen_int"] = -1 * field * pars[ "specimen_b"] pars["er_specimen_name"] = s pars = pmag.scoreit(pars, PmagSpecRec, accept, '', 0) PmagSpecRec["measurement_step_min"] = '%8.3e' % ( pars["measurement_step_min"]) PmagSpecRec["measurement_step_max"] = '%8.3e' % ( pars["measurement_step_max"]) PmagSpecRec["measurement_step_unit"] = "J" PmagSpecRec["specimen_int_n"] = '%i' % ( pars["specimen_int_n"]) PmagSpecRec["specimen_lab_field_dc"] = '%8.3e' % ( pars["specimen_lab_field_dc"]) PmagSpecRec["specimen_int"] = '%8.3e ' % ( pars["specimen_int"]) PmagSpecRec["specimen_b"] = '%5.3f ' % ( pars["specimen_b"]) PmagSpecRec["specimen_q"] = '%5.1f ' % ( pars["specimen_q"]) PmagSpecRec["specimen_f"] = '%5.3f ' % ( pars["specimen_f"]) PmagSpecRec["specimen_fvds"] = '%5.3f' % ( pars["specimen_fvds"]) PmagSpecRec["specimen_b_beta"] = '%5.3f' % ( pars["specimen_b_beta"]) PmagSpecRec["specimen_int_mad"] = '%7.1f' % ( pars["specimen_int_mad"]) PmagSpecRec["specimen_Z"] = '%7.1f' % ( pars["specimen_Z"]) if pars["method_codes"] != "": tmpcodes = pars["method_codes"].split(":") for t in tmpcodes: if t.strip() not in methcodes: methcodes.append(t.strip()) PmagSpecRec["specimen_dec"] = '%7.1f' % ( pars["specimen_dec"]) PmagSpecRec["specimen_inc"] = '%7.1f' % ( pars["specimen_inc"]) PmagSpecRec["specimen_tilt_correction"] = '-1' PmagSpecRec["specimen_direction_type"] = 'l' PmagSpecRec[ "direction_type"] = 'l' # this is redudant, but helpful - won't be imported PmagSpecRec["specimen_dang"] = '%7.1f ' % ( pars["specimen_dang"]) PmagSpecRec["specimen_drats"] = '%7.1f ' % ( pars["specimen_drats"]) PmagSpecRec["specimen_int_ptrm_n"] = '%i ' % ( pars["specimen_int_ptrm_n"]) PmagSpecRec["specimen_rsc"] = '%6.4f ' % ( pars["specimen_rsc"]) PmagSpecRec["specimen_md"] = '%i ' % (int( pars["specimen_md"])) if PmagSpecRec["specimen_md"] == '-1': PmagSpecRec["specimen_md"] = "" PmagSpecRec["specimen_b_sigma"] = '%5.3f ' % ( pars["specimen_b_sigma"]) if "IE-TT" not in methcodes: methcodes.append("IE-TT") methods = "" for meth in methcodes: methods = methods + meth + ":" PmagSpecRec["magic_method_codes"] = methods[:-1] PmagSpecRec["specimen_description"] = comment PmagSpecRec[ "magic_software_packages"] = version_num pmagplotlib.plotAZ(AZD, araiblock, zijdblock, s, units[0]) pmagplotlib.plotB(AZD, araiblock, zijdblock, pars) if len(trmblock) > 2: blab = field best = pars["specimen_int"] Bs, TRMs = [], [] for trec in trmblock: Bs.append(float( trec['treatment_dc_field'])) TRMs.append( float(trec['measurement_magn_moment'])) NLpars = nlt.NLtrm( Bs, TRMs, best, blab, 0 ) # calculate best fit parameters through TRM acquisition data, and get new banc Mp, Bp = [], [] for k in range(int(max(Bs) * 1e6)): Bp.append(float(k) * 1e-6) npred = nlt.TRM( Bp[-1], NLpars['xopt'][0], NLpars['xopt'] [1]) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM( AZD['MRM'], Bs, TRMs, Bp, Mp, NLpars, trec['magic_experiment_name']) print 'Banc= ', float(NLpars['banc']) * 1e6 pmagplotlib.drawFIGS(AZD) pars["specimen_lab_field_dc"] = field pars["specimen_int"] = -1 * field * pars[ "specimen_b"] saveit = raw_input( "Save this interpretation? [y]/n \n") if saveit != 'n': specimen += 1 PriorRecs.append( PmagSpecRec) # put back an interpretation save_redo(PriorRecs, inspec) ans = "" else: specimen += 1 if fmt != ".pmag": basename = s + '_microwave' + fmt files = {} for key in AZD.keys(): files[key] = s + '_' + key + fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['deremag'] = 'DeReMag Plot' titles['zijd'] = 'Zijderveld Plot' titles['arai'] = 'Arai Plot' AZD = pmagplotlib.addBorders( AZD, titles, black, purple) pmagplotlib.saveP(AZD, files) # pmagplotlib.combineFigs(s,files,3) if len(CurrRec) > 0: for rec in CurrRec: PriorRecs.append(rec) CurrRec = [] if plots != 1: ans = raw_input(" Save last plot? 1/[0] ") if ans == "1": if fmt != ".pmag": files = {} for key in AZD.keys(): files[key] = s + '_' + key + fmt pmagplotlib.saveP(AZD, files) if len(CurrRec) > 0: PriorRecs.append(CurrRec) # put back an interpretation if len(PriorRecs) > 0: save_redo(PriorRecs, inspec) print 'Updated interpretations saved in ', inspec if pmagplotlib.verbose: print "Good bye"
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
def main(): """ NAME plot_geomagia.py DESCRIPTION makes a map and VADM plot of geomagia download file SYNTAX plot_geomagia.py [command line options] OPTIONS -h prints help message and quits -f FILE, specify geomagia download file -res [c,l,i,h] specify resolution (crude,low,intermediate,high) -etp plot the etopo20 topographic mesh -pad [LAT LON] pad bounding box by LAT/LON (default is [.5 .5] degrees) -grd SPACE specify grid spacing -prj [lcc] , specify projection (lcc=lambert conic conformable), default is mercator -o color ocean blue/land green (default is not) -d plot details of rivers, boundaries, etc. -sav save plot and quit quietly -fmt [png,svg,eps,jpg,pdf] specify format for output, default is pdf DEFAULTS resolution: intermediate saved images are in pdf """ dir_path='.' names,res,proj,locs,padlon,padlat,fancy,gridspace,details=[],'l','lcc','',0,0,0,15,1 Age_bounds=[-5000,2000] Lat_bounds=[20,45] Lon_bounds=[15,55] fmt='pdf' if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind = sys.argv.index('-f') sites_file=sys.argv[ind+1] if '-res' in sys.argv: ind = sys.argv.index('-res') res=sys.argv[ind+1] if '-etp' in sys.argv:fancy=1 if '-o' in sys.argv:ocean=1 if '-d' in sys.argv:details=1 if '-prj' in sys.argv: ind = sys.argv.index('-prj') proj=sys.argv[ind+1] if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt=sys.argv[ind+1] verbose=pmagplotlib.verbose if '-sav' in sys.argv: verbose=0 if '-pad' in sys.argv: ind = sys.argv.index('-pad') padlat=float(sys.argv[ind+1]) padlon=float(sys.argv[ind+2]) if '-grd' in sys.argv: ind = sys.argv.index('-grd') gridspace=float(sys.argv[ind+1]) if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path=sys.argv[ind+1] sites_file=dir_path+'/'+sites_file geo_in=open(sites_file,'rU').readlines() Age,AgeErr,Vadm,VadmErr,slats,slons=[],[],[],[],[],[] for line in geo_in[2:]: # skip top two rows` rec=line.split() if float(rec[0])>Age_bounds[0] and float(rec[0])<Age_bounds[1] \ and float(rec[12])>Lat_bounds[0] and float(rec[12]) < Lat_bounds[1]\ and float(rec[13])>Lon_bounds[0] and float(rec[13])<Lon_bounds[1]: Age.append(float(rec[0])) AgeErr.append(float(rec[1])) Vadm.append(10.*float(rec[6])) VadmErr.append(10.*float(rec[7])) slats.append(float(rec[12])) slons.append(float(rec[13])) FIGS={'map':1,'vadms':2} pmagplotlib.plot_init(FIGS['map'],6,6) pmagplotlib.plot_init(FIGS['vadms'],6,6) Opts={'res':res,'proj':proj,'loc_name':locs,'padlon':padlon,'padlat':padlat,'latmin':numpy.min(slats)-padlat,'latmax':numpy.max(slats)+padlat,'lonmin':numpy.min(slons)-padlon,'lonmax':numpy.max(slons)+padlon,'sym':'ro','boundinglat':0.,'pltgrid':1} Opts['lon_0']=int(0.5*(numpy.min(slons)+numpy.max(slons))) Opts['lat_0']=int(0.5*(numpy.min(slats)+numpy.max(slats))) Opts['gridspace']=gridspace if details==1: Opts['details']={'coasts':1,'rivers':0,'states':1,'countries':1,'ocean':1} else: Opts['details']={'coasts':1,'rivers':0,'states':0,'countries':0,'ocean':1} Opts['details']['fancy']=fancy pmagplotlib.plotMAP(FIGS['map'],slats,slons,Opts) pmagplotlib.plotXY(FIGS['vadms'],Age,Vadm,sym='bo',xlab='Age (Years CE)',ylab=r'VADM (ZAm$^2$)') if verbose:pmagplotlib.drawFIGS(FIGS) files={} for key in FIGS.keys(): files[key]=key+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['map']='Map' titles['vadms']='VADMs' FIG = pmagplotlib.addBorders(FIGS,titles,black,purple) pmagplotlib.saveP(FIGS,files) elif verbose: ans=raw_input(" S[a]ve to save plot, Return to quit: ") if ans=="a": pmagplotlib.saveP(FIGS,files) else: pmagplotlib.saveP(FIGS,files)
def main(): """ NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a pmag_results table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ELON [specify eyeball location], default is 90., 0. -f FILE pmag_results format file, [default is pmag_results.txt] -res [c,l,i,h] specify resolution (crude, low, intermediate, high] -etp plot the etopo20 topographpy data (requires high resolution data set) -prj PROJ, specify one of the following: ortho = orthographic lcc = lambert conformal moll = molweide merc = mercator -sym SYM SIZE: choose a symbol and size, examples: ro 5 : small red circles bs 10 : intermediate blue squares g^ 20 : large green triangles -ell plot dp/dm or a95 ellipses -rev RSYM RSIZE : flip reverse poles to normal antipode -S: plot antipodes of all poles -age : plot the ages next to the poles -crd [g,t] : choose coordinate system, default is to plot all site VGPs -fmt [pdf, png, eps...] specify output format, default is pdf -sav save and quit DEFAULTS FILE: pmag_results.txt res: c prj: ortho ELAT,ELON = 0,0 SYM SIZE: ro 8 RSYM RSIZE: g^ 8 """ dir_path='.' res,ages='c',0 plot=0 proj='ortho' results_file='pmag_results.txt' ell,flip=0,0 lat_0,lon_0=90.,0. fmt='pdf' sym,size='ro',8 rsym,rsize='g^',8 anti=0 fancy=0 coord="" if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path=sys.argv[ind+1] if '-h' in sys.argv: print main.__doc__ sys.exit() if '-S' in sys.argv:anti=1 if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-sav' in sys.argv:plot=1 if '-res' in sys.argv: ind = sys.argv.index('-res') res=sys.argv[ind+1] if '-etp' in sys.argv:fancy=1 if '-prj' in sys.argv: ind = sys.argv.index('-prj') proj=sys.argv[ind+1] if '-rev' in sys.argv: flip=1 ind = sys.argv.index('-rev') rsym=(sys.argv[ind+1]) rsize=int(sys.argv[ind+2]) if '-sym' in sys.argv: ind = sys.argv.index('-sym') sym=(sys.argv[ind+1]) size=int(sys.argv[ind+2]) if '-eye' in sys.argv: ind = sys.argv.index('-eye') lat_0=float(sys.argv[ind+1]) lon_0=float(sys.argv[ind+2]) if '-ell' in sys.argv: ell=1 if '-age' in sys.argv: ages=1 if '-f' in sys.argv: ind = sys.argv.index('-f') results_file=sys.argv[ind+1] if '-crd' in sys.argv: ind = sys.argv.index('-crd') crd=sys.argv[ind+1] if crd=='g':coord='0' if crd=='t':coord='100' results_file=dir_path+'/'+results_file data,file_type=pmag.magic_read(results_file) if file_type!='pmag_results': print "bad results file" sys.exit() FIG={'map':1} pmagplotlib.plot_init(FIG['map'],6,6) # read in er_sites file lats,lons,dp,dm,a95=[],[],[],[],[] Pars=[] dates,rlats,rlons=[],[],[] if 'data_type' in data[0].keys(): Results=pmag.get_dictitem(data,'data_type','i','T') # get all site level data else: Results=data Results=pmag.get_dictitem(Results,'vgp_lat','','F') # get all non-blank latitudes Results=pmag.get_dictitem(Results,'vgp_lon','','F') # get all non-blank longitudes if coord!="":Results=pmag.get_dictitem(Results,'tilt_correction',coord,'T') # get specified coordinate system location="" for rec in Results: if rec['er_location_names'] not in location:location = location+':'+rec['er_location_names'] if 'average_age' in rec.keys() and rec['average_age']!="" and ages==1: dates.append(rec['average_age']) lat=float(rec['vgp_lat']) lon=float(rec['vgp_lon']) if flip==0: lats.append(lat) lons.append(lon) elif flip==1: if lat<0: rlats.append(-lat) lon=lon+180. if lon>360:lon=lon-360. rlons.append(lon) else: lats.append(lat) lons.append(lon) elif anti==1: lats.append(-lat) lon=lon+180. if lon>360:lon=lon-360. lons.append(lon) ppars=[] ppars.append(lon) ppars.append(lat) ell1,ell2="","" if 'vgp_dm' in rec.keys() and rec['vgp_dm']!="":ell1=float(rec['vgp_dm']) if 'vgp_dp' in rec.keys() and rec['vgp_dp']!="":ell2=float(rec['vgp_dp']) if 'vgp_alpha95' in rec.keys() and rec['vgp_alpha95']!="":ell1,ell2=float(rec['vgp_alpha95']),float(rec['vgp_alpha95']) if ell1!="" and ell2!="": ppars=[] ppars.append(lons[-1]) ppars.append(lats[-1]) ppars.append(ell1) ppars.append(lons[-1]) isign=abs(lats[-1])/lats[-1] ppars.append(lats[-1]-isign*90.) ppars.append(ell2) ppars.append(lons[-1]+90.) ppars.append(0.) Pars.append(ppars) location=location.strip(':') Opts={'latmin':-90,'latmax':90,'lonmin':0.,'lonmax':360.,'lat_0':lat_0,'lon_0':lon_0,'proj':proj,'sym':'bs','symsize':3,'pltgrid':0,'res':res,'boundinglat':0.} Opts['details']={'coasts':1,'rivers':0, 'states':0, 'countries':0,'ocean':1,'fancy':fancy} pmagplotlib.plotMAP(FIG['map'],[90.],[0.],Opts) # make the base map with a blue triangle at the pole` Opts['pltgrid']=-1 Opts['sym']=sym Opts['symsize']=size if len(dates)>0:Opts['names']=dates if len(lats)>0:pmagplotlib.plotMAP(FIG['map'],lats,lons,Opts) # add the lats and lons of the poles Opts['names']=[] if len(rlats)>0: Opts['sym']=rsym Opts['symsize']=rsize pmagplotlib.plotMAP(FIG['map'],rlats,rlons,Opts) # add the lats and lons of the poles if plot==0: pmagplotlib.drawFIGS(FIG) if ell==1: # add ellipses if desired. Opts['details']={'coasts':0,'rivers':0, 'states':0, 'countries':0,'ocean':0} Opts['pltgrid']=-1 # turn off meridian replotting Opts['symsize']=2 Opts['sym']='g-' for ppars in Pars: if ppars[2]!=0: PTS=pmagplotlib.plotELL(FIG['map'],ppars,'g.',0,0) elats,elons=[],[] for pt in PTS: elons.append(pt[0]) elats.append(pt[1]) pmagplotlib.plotMAP(FIG['map'],elats,elons,Opts) # make the base map with a blue triangle at the pole` if plot==0:pmagplotlib.drawFIGS(FIG) files={} for key in FIG.keys(): files[key]='LO:_'+location+'_VGP_map.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='LO:_'+location+'_VGP_map' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) elif plot==0: pmagplotlib.drawFIGS(FIG) ans=raw_input(" S[a]ve to save plot, Return to quit: ") if ans=="a": pmagplotlib.saveP(FIG,files) else: print "Good bye" sys.exit() else: pmagplotlib.saveP(FIG,files)
def main(): """ NAME lowrie.py DESCRIPTION plots intensity decay curves for Lowrie experiments SYNTAX lowrie -h [command line options] INPUT takes SIO formatted input files OPTIONS -h prints help message and quits -f FILE: specify input file -N do not normalize by maximum magnetization -fmt [svg, pdf, eps, png] specify fmt, default is svg -sav save plots and quit """ fmt, plot = "svg", 0 FIG = {} # plot dictionary FIG["lowrie"] = 1 # demag is figure 1 pmagplotlib.plot_init(FIG["lowrie"], 6, 6) norm = 1 # default is to normalize by maximum axis if len(sys.argv) > 1: if "-h" in sys.argv: print main.__doc__ sys.exit() if "-N" in sys.argv: norm = 0 # don't normalize if "-sav" in sys.argv: plot = 1 # don't normalize if "-fmt" in sys.argv: # sets input filename ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] if "-f" in sys.argv: # sets input filename ind = sys.argv.index("-f") in_file = sys.argv[ind + 1] else: print main.__doc__ print "you must supply a file name" sys.exit() else: print main.__doc__ print "you must supply a file name" sys.exit() data = open(in_file).readlines() # open the SIO format file PmagRecs = [] # set up a list for the results keys = ["specimen", "treatment", "csd", "M", "dec", "inc"] for line in data: PmagRec = {} rec = line.replace("\n", "").split() for k in range(len(keys)): PmagRec[keys[k]] = rec[k] PmagRecs.append(PmagRec) specs = pmag.get_dictkey(PmagRecs, "specimen", "") sids = [] for spec in specs: if spec not in sids: sids.append(spec) # get list of unique specimen names for spc in sids: # step through the specimen names print spc specdata = pmag.get_dictitem(PmagRecs, "specimen", spc, "T") # get all this one's data DIMs, Temps = [], [] for dat in specdata: # step through the data DIMs.append([float(dat["dec"]), float(dat["inc"]), float(dat["M"]) * 1e-3]) Temps.append(float(dat["treatment"])) carts = pmag.dir2cart(DIMs).transpose() # if norm==1: # want to normalize # nrm=max(max(abs(carts[0])),max(abs(carts[1])),max(abs(carts[2]))) # by maximum of x,y,z values # ylab="M/M_max" if norm == 1: # want to normalize nrm = DIMs[0][2] # normalize by NRM ylab = "M/M_o" else: nrm = 1.0 # don't normalize ylab = "Magnetic moment (Am^2)" xlab = "Temperature (C)" pmagplotlib.plotXY(FIG["lowrie"], Temps, abs(carts[0]) / nrm, sym="r-") pmagplotlib.plotXY(FIG["lowrie"], Temps, abs(carts[0]) / nrm, sym="ro") # X direction pmagplotlib.plotXY(FIG["lowrie"], Temps, abs(carts[1]) / nrm, sym="c-") pmagplotlib.plotXY(FIG["lowrie"], Temps, abs(carts[1]) / nrm, sym="cs") # Y direction pmagplotlib.plotXY(FIG["lowrie"], Temps, abs(carts[2]) / nrm, sym="k-") pmagplotlib.plotXY( FIG["lowrie"], Temps, abs(carts[2]) / nrm, sym="k^", title=spc, xlab=xlab, ylab=ylab ) # Z direction files = {"lowrie": "lowrie:_" + spc + "_." + fmt} if plot == 0: pmagplotlib.drawFIGS(FIG) ans = raw_input("S[a]ve figure? [q]uit, <return> to continue ") if ans == "a": pmagplotlib.saveP(FIG, files) elif ans == "q": sys.exit() else: pmagplotlib.saveP(FIG, files) pmagplotlib.clearFIG(FIG["lowrie"])
def main(): """ NAME dmag_magic.py DESCRIPTION plots intensity decay curves for demagnetization experiments SYNTAX dmag_magic -h [command line options] INPUT takes magic formatted magic_measurements.txt files OPTIONS -h prints help message and quits -f FILE: specify input file, default is: magic_measurements.txt -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is by location -LT [AF,T,M]: specify lab treatment type, default AF -XLP [PI]: exclude specific lab protocols (for example, method codes like LP-PI) -N do not normalize by NRM magnetization -sav save plots silently and quit -fmt [svg,jpg,png,pdf] set figure format [default is svg] NOTE loc: location (study); sit: site; sam: sample; spc: specimen """ FIG = {} # plot dictionary FIG['demag'] = 1 # demag is figure 1 in_file, plot_key, LT = 'magic_measurements.txt', 'er_location_name', "LT-AF-Z" XLP = "" norm = 1 LT = 'LT-AF-Z' units, dmag_key = 'T', 'treatment_ac_field' plot = 0 fmt = 'svg' if len(sys.argv) > 1: if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-N' in sys.argv: norm = 0 if '-sav' in sys.argv: plot = 1 if '-f' in sys.argv: ind = sys.argv.index("-f") in_file = sys.argv[ind + 1] if '-fmt' in sys.argv: ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] if '-obj' in sys.argv: ind = sys.argv.index('-obj') plot_by = sys.argv[ind + 1] if plot_by == 'sit': plot_key = 'er_site_name' if plot_by == 'sam': plot_key = 'er_sample_name' if plot_by == 'spc': plot_key = 'er_specimen_name' if '-XLP' in sys.argv: ind = sys.argv.index("-XLP") XLP = sys.argv[ind + 1] # get lab protocol for excluding if '-LT' in sys.argv: ind = sys.argv.index("-LT") LT = 'LT-' + sys.argv[ind + 1] + '-Z' # get lab treatment for plotting if LT == 'LT-T-Z': units, dmag_key = 'K', 'treatment_temp' elif LT == 'LT-AF-Z': units, dmag_key = 'T', 'treatment_ac_field' elif LT == 'LT-M-Z': units, dmag_key = 'J', 'treatment_mw_energy' else: units = 'U' data, file_type = pmag.magic_read(in_file) sids = pmag.get_specs(data) pmagplotlib.plot_init(FIG['demag'], 5, 5) print(len(data), ' records read from ', in_file) # # # find desired intensity data # # plotlist, intlist = [], [ 'measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume', 'measurement_magn_mass' ] IntMeths = [] FixData = [] for rec in data: meths = [] methcodes = rec['magic_method_codes'].split(':') for meth in methcodes: meths.append(meth.strip()) for key in rec.keys(): if key in intlist and rec[key] != "": if key not in IntMeths: IntMeths.append(key) if rec[plot_key] not in plotlist and LT in meths: plotlist.append(rec[plot_key]) if 'measurement_flag' not in rec.keys(): rec['measurement_flag'] = 'g' FixData.append(rec) plotlist.sort() if len(IntMeths) == 0: print('No intensity information found') sys.exit() data = FixData int_key = IntMeths[ 0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used for plt in plotlist: if plot == 0: print(plt, 'plotting by: ', plot_key) PLTblock = pmag.get_dictitem( data, plot_key, plt, 'T') # fish out all the data for this type of plot PLTblock = pmag.get_dictitem( PLTblock, 'magic_method_codes', LT, 'has') # fish out all the dmag for this experiment type PLTblock = pmag.get_dictitem( PLTblock, int_key, '', 'F') # get all with this intensity key non-blank if XLP != "": PLTblock = pmag.get_dictitem( PLTblock, 'magic_method_codes', XLP, 'not') # reject data with XLP in method_code if len(PLTblock) > 2: title = PLTblock[0][plot_key] spcs = [] for rec in PLTblock: if rec['er_specimen_name'] not in spcs: spcs.append(rec['er_specimen_name']) for spc in spcs: SPCblock = pmag.get_dictitem(PLTblock, 'er_specimen_name', spc, 'T') # plot specimen by specimen INTblock = [] for rec in SPCblock: INTblock.append([ float(rec[dmag_key]), 0, 0, float(rec[int_key]), 1, rec['measurement_flag'] ]) if len(INTblock) > 2: pmagplotlib.plotMT(FIG['demag'], INTblock, title, 0, units, norm) if plot == 1: files = {} for key in FIG.keys(): files[key] = title + '_' + LT + '.' + fmt pmagplotlib.saveP(FIG, files) sys.exit() else: 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": files = {} for key in FIG.keys(): files[key] = title + '_' + LT + '.' + fmt pmagplotlib.saveP(FIG, files) pmagplotlib.clearFIG(FIG['demag'])
def main(): """ NAME qqplot.py DESCRIPTION makes qq plot of input data against a Normal distribution. INPUT FORMAT takes real numbers in single column SYNTAX qqplot.py [-h][-i][-f FILE] OPTIONS -f FILE, specify file on command line -fmt [png,svg,jpg,eps] set plot output format [default is svg] -sav saves and quits OUTPUT calculates the K-S D and the D expected for a normal distribution when D<Dc, distribution is normal (at 95% level of confidence). """ fmt,plot='svg',0 if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-sav' in sys.argv: plot=1 if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-f' in sys.argv: # ask for filename ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') data=f.readlines() X= [] # set up list for data for line in data: # read in the data from standard input rec=line.split() # split each line on space to get records X.append(float(rec[0])) # append data to X # QQ={'qq':1} pmagplotlib.plot_init(QQ['qq'],5,5) pmagplotlib.plotQQnorm(QQ['qq'],X,'Q-Q Plot') # make plot if plot==0: pmagplotlib.drawFIGS(QQ) files={} for key in list(QQ.keys()): files[key]=key+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='Q-Q Plot' QQ = pmagplotlib.addBorders(EQ,titles,black,purple) pmagplotlib.saveP(QQ,files) elif plot==0: ans=input(" S[a]ve to save plot, [q]uit without saving: ") if ans=="a": pmagplotlib.saveP(QQ,files) else: pmagplotlib.saveP(QQ,files)
def main(): """ NAME foldtest.py DESCRIPTION does a fold test (Tauxe, 2010) on data INPUT FORMAT dec inc dip_direction dip SYNTAX foldtest.py [command line options] OPTIONS -h prints help message and quits -f FILE file with input data -F FILE for confidence bounds on fold test -u ANGLE (circular standard deviation) for uncertainty on bedding poles -b MIN MAX bounds for quick search of percent untilting [default is -10 to 150%] -n NB number of bootstrap samples [default is 1000] -fmt FMT, specify format - default is svg -sav save figures and quit INPUT FILE Dec Inc Dip_Direction Dip in space delimited file OUTPUT PLOTS Geographic: is an equal area projection of the input data in original coordinates Stratigraphic: is an equal area projection of the input data in tilt adjusted coordinates % Untilting: The dashed (red) curves are representative plots of maximum eigenvalue (tau_1) as a function of untilting The solid line is the cumulative distribution of the % Untilting required to maximize tau for all the bootstrapped data sets. The dashed vertical lines are 95% confidence bounds on the % untilting that yields the most clustered result (maximum tau_1). Command line: prints out the bootstrapped iterations and finally the confidence bounds on optimum untilting. If the 95% conf bounds include 0, then a post-tilt magnetization is indicated If the 95% conf bounds include 100, then a pre-tilt magnetization is indicated If the 95% conf bounds exclude both 0 and 100, syn-tilt magnetization is possible as is vertical axis rotation or other pathologies Geographic: is an equal area projection of the input data in OPTIONAL OUTPUT FILE: The output file has the % untilting within the 95% confidence bounds nd the number of bootstrap samples """ kappa = 0 fmt, plot = 'svg', 0 nb = 1000 # number of bootstraps min, max = -10, 150 if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit if '-F' in sys.argv: ind = sys.argv.index('-F') outfile = open(sys.argv[ind + 1], 'w') else: outfile = "" if '-f' in sys.argv: ind = sys.argv.index('-f') file = sys.argv[ind + 1] DIDDs = numpy.loadtxt(file) else: print main.__doc__ sys.exit() if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-sav' in sys.argv: plot = 1 if '-b' in sys.argv: ind = sys.argv.index('-b') min = int(sys.argv[ind + 1]) max = int(sys.argv[ind + 2]) if '-n' in sys.argv: ind = sys.argv.index('-n') nb = int(sys.argv[ind + 1]) if '-u' in sys.argv: ind = sys.argv.index('-u') csd = float(sys.argv[ind + 1]) kappa = (81. / csd)**2 # # get to work # PLTS = {'geo': 1, 'strat': 2, 'taus': 3} # make plot dictionary pmagplotlib.plot_init(PLTS['geo'], 5, 5) pmagplotlib.plot_init(PLTS['strat'], 5, 5) pmagplotlib.plot_init(PLTS['taus'], 5, 5) pmagplotlib.plotEQ(PLTS['geo'], DIDDs, 'Geographic') D, I = pmag.dotilt_V(DIDDs) TCs = numpy.array([D, I]).transpose() pmagplotlib.plotEQ(PLTS['strat'], TCs, 'Stratigraphic') if plot == 0: pmagplotlib.drawFIGS(PLTS) Percs = range(min, max) Cdf, Untilt = [], [] pylab.figure(num=PLTS['taus']) print 'doing ', nb, ' iterations...please be patient.....' for n in range( nb): # do bootstrap data sets - plot first 25 as dashed red line if n % 50 == 0: print n Taus = [] # set up lists for taus PDs = pmag.pseudo(DIDDs) if kappa != 0: for k in range(len(PDs)): d, i = pmag.fshdev(kappa) dipdir, dip = pmag.dodirot(d, i, PDs[k][2], PDs[k][3]) PDs[k][2] = dipdir PDs[k][3] = dip for perc in Percs: tilt = numpy.array([1., 1., 1., 0.01 * perc]) D, I = pmag.dotilt_V(PDs * tilt) TCs = numpy.array([D, I]).transpose() ppars = pmag.doprinc(TCs) # get principal directions Taus.append(ppars['tau1']) if n < 25: pylab.plot(Percs, Taus, 'r--') Untilt.append(Percs[Taus.index( numpy.max(Taus))]) # tilt that gives maximum tau Cdf.append(float(n) / float(nb)) pylab.plot(Percs, Taus, 'k') pylab.xlabel('% Untilting') pylab.ylabel('tau_1 (red), CDF (green)') Untilt.sort() # now for CDF of tilt of maximum tau pylab.plot(Untilt, Cdf, 'g') lower = int(.025 * nb) upper = int(.975 * nb) pylab.axvline(x=Untilt[lower], ymin=0, ymax=1, linewidth=1, linestyle='--') pylab.axvline(x=Untilt[upper], ymin=0, ymax=1, linewidth=1, linestyle='--') tit = '%i - %i %s' % (Untilt[lower], Untilt[upper], 'Percent Unfolding') print tit print 'range of all bootstrap samples: ', Untilt[0], ' - ', Untilt[-1] pylab.title(tit) outstring = '%i - %i; %i\n' % (Untilt[lower], Untilt[upper], nb) if outfile != "": outfile.write(outstring) files = {} for key in PLTS.keys(): files[key] = ('foldtest_' + '%s' % (key.strip()[:2]) + '.' + fmt) if plot == 0: pmagplotlib.drawFIGS(PLTS) ans = raw_input('S[a]ve all figures, <Return> to quit ') if ans != 'a': print "Good bye" sys.exit() pmagplotlib.saveP(PLTS, files)
def main(): """ NAME quick_hyst.py DESCRIPTION makes plots of hysteresis data SYNTAX quick_hyst.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specify input file, default is magic_measurements.txt -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg] """ args = sys.argv PLT = 1 plots = 0 user, meas_file = "", "magic_measurements.txt" pltspec = "" dir_path = '.' fmt = 'png' verbose = pmagplotlib.verbose version_num = pmag.get_version() if '-WD' in args: ind = args.index('-WD') dir_path = args[ind + 1] if "-h" in args: print(main.__doc__) sys.exit() if "-usr" in args: ind = args.index("-usr") user = args[ind + 1] if '-f' in args: ind = args.index("-f") meas_file = args[ind + 1] if '-sav' in args: verbose = 0 plots = 1 if '-spc' in args: ind = args.index("-spc") pltspec = args[ind + 1] verbose = 0 plots = 1 if '-fmt' in args: ind = args.index("-fmt") fmt = args[ind + 1] meas_file = dir_path + '/' + meas_file print('verbose', verbose) # # meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(main.__doc__) print('bad file') sys.exit() # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs, RemRecs = [], [] HDD = {} HDD['hyst'] = 1 pmagplotlib.plot_init(HDD['hyst'], 5, 5) # # get list of unique experiment names and specimen names # experiment_names, sids = [], [] hyst_data = pmag.get_dictitem(meas_data, 'magic_method_codes', 'LP-HYS', 'has') # get all hysteresis data for rec in hyst_data: if 'er_synthetic_name' in rec.keys( ) and rec['er_synthetic_name'] != "": rec['er_specimen_name'] = rec['er_synthetic_name'] if rec['magic_experiment_name'] not in experiment_names: experiment_names.append(rec['magic_experiment_name']) if rec['er_specimen_name'] not in sids: sids.append(rec['er_specimen_name']) if 'measurement_temp' not in rec.keys(): rec['measurement_temp'] = '300' # assume room T measurement unless otherwise specified # k = 0 if pltspec != "": k = sids.index(pltspec) intlist = [ 'measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume', 'measurement_magn_mass' ] while k < len(sids): locname, site, sample, synth = '', '', '', '' s = sids[k] hmeths = [] if verbose: print(s, k + 1, 'out of ', len(sids)) # # B, M = [], [] #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data spec = pmag.get_dictitem(hyst_data, 'er_specimen_name', s, 'T') # get all measurements for this specimen if 'er_location_name' in spec[0].keys(): locname = spec[0]['er_location_name'] if 'er_site_name' in spec[0].keys(): site = spec[0]['er_site_name'] if 'er_sample_name' in spec[0].keys(): sample = spec[0]['er_sample_name'] if 'er_synthetic_name' in spec[0].keys(): synth = spec[0]['er_synthetic_name'] for m in intlist: meas_data = pmag.get_dictitem( spec, m, '', 'F') # get all non-blank data for this specimen if len(meas_data) > 0: break c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-'] cnum = 0 if len(meas_data) > 0: Temps = [] xlab, ylab, title = '', '', '' for rec in meas_data: if rec['measurement_temp'] not in Temps: Temps.append(rec['measurement_temp']) for t in Temps: print('working on t: ', t) t_data = pmag.get_dictitem(meas_data, 'measurement_temp', t, 'T') B, M = [], [] for rec in t_data: B.append(float(rec['measurement_lab_field_dc'])) M.append(float(rec[m])) # now plot the hysteresis curve(s) # if len(B) > 0: B = numpy.array(B) M = numpy.array(M) if t == Temps[-1]: xlab = 'Field (T)' ylab = m title = 'Hysteresis: ' + s if t == Temps[0]: pmagplotlib.clearFIG(HDD['hyst']) pmagplotlib.plotXY(HDD['hyst'], B, M, sym=c[cnum], xlab=xlab, ylab=ylab, title=title) pmagplotlib.plotXY(HDD['hyst'], [1.1 * B.min(), 1.1 * B.max()], [0, 0], sym='k-', xlab=xlab, ylab=ylab, title=title) pmagplotlib.plotXY(HDD['hyst'], [0, 0], [1.1 * M.min(), 1.1 * M.max()], sym='k-', xlab=xlab, ylab=ylab, title=title) if verbose: pmagplotlib.drawFIGS(HDD) cnum += 1 if cnum == len(c): cnum = 0 # files = {} if plots: if pltspec != "": s = pltspec files = {} for key in HDD.keys(): if pmagplotlib.isServer: # use server plot naming convention if synth == '': filename = "LO:_" + locname + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + s + '_TY:_' + key + '_.' + fmt else: filename = 'SY:_' + synth + '_TY:_' + key + '_.' + fmt files[key] = filename else: # use more readable plot naming convention if synth == '': filename = '' for item in [locname, site, sample, s, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) else: filename = synth + '_' + key + '.fmt' files[key] = filename pmagplotlib.saveP(HDD, files) if pltspec != "": sys.exit() if verbose: pmagplotlib.drawFIGS(HDD) ans = raw_input( "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n " ) if ans == "a": files = {} for key in HDD.keys(): if pmagplotlib.isServer: print('server') files[ key] = "LO:_" + locname + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + s + '_TY:_' + key + '_.' + fmt else: print('not server') filename = '' for item in [locname, site, sample, s, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) files[key] = filename print('files', files) pmagplotlib.saveP(HDD, files) if ans == '': k += 1 if ans == "p": del HystRecs[-1] k -= 1 if ans == 'q': print("Good bye") sys.exit() if ans == 's': keepon = 1 specimen = raw_input( 'Enter desired specimen name (or first part there of): ') while keepon == 1: try: k = sids.index(specimen) keepon = 0 except: tmplist = [] for qq in range(len(sids)): if specimen in sids[qq]: tmplist.append(sids[qq]) print(specimen, " not found, but this was: ") print(tmplist) specimen = raw_input('Select one or try again\n ') k = sids.index(specimen) else: k += 1 if len(B) == 0: if verbose: print('skipping this one - no hysteresis data') k += 1
def main(): """ NAME find_EI.py DESCRIPTION Applies series of assumed flattening factor and "unsquishes" inclinations assuming tangent function. Finds flattening factor that gives elongation/inclination pair consistent with TK03. Finds bootstrap confidence bounds SYNTAX find_EI.py [command line options] OPTIONS -h prints help message and quits -f FILE specify input file name -nb N specify number of bootstraps - the more the better, but slower!, default is 1000 -sc uses a "site-level" correction to a Fisherian distribution instead of a "study-level" correction to a TK03-consistent distribution. Note that many directions (~ 100) are needed for this correction to be reliable. -fmt [svg,png,eps,pdf..] change plot format, default is svg -sav saves the figures and quits INPUT dec/inc pairs, delimited with space or tabs OUTPUT four plots: 1) equal area plot of original directions 2) Elongation/inclination pairs as a function of f, data plus 25 bootstrap samples 3) Cumulative distribution of bootstrapped optimal inclinations plus uncertainties. Estimate from original data set plotted as solid line 4) Orientation of principle direction through unflattening NOTE: If distribution does not have a solution, plot labeled: Pathological. Some bootstrap samples may have valid solutions and those are plotted in the CDFs and E/I plot. """ fmt, nb = 'svg', 1000 plot = 0 if '-h' in sys.argv: print(main.__doc__) sys.exit() # graceful quit elif '-f' in sys.argv: ind = sys.argv.index('-f') file = sys.argv[ind + 1] else: print(main.__doc__) sys.exit() if '-nb' in sys.argv: ind = sys.argv.index('-nb') nb = int(sys.argv[ind + 1]) if '-sc' in sys.argv: site_correction = True else: site_correction = False if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-sav' in sys.argv: plot = 1 data = numpy.loadtxt(file) upper, lower = int(round(.975 * nb)), int(round(.025 * nb)) E, I = [], [] PLTS = {'eq': 1, 'ei': 2, 'cdf': 3, 'v2': 4} pmagplotlib.plot_init(PLTS['eq'], 6, 6) pmagplotlib.plot_init(PLTS['ei'], 5, 5) pmagplotlib.plot_init(PLTS['cdf'], 5, 5) pmagplotlib.plot_init(PLTS['v2'], 5, 5) pmagplotlib.plotEQ(PLTS['eq'], data, 'Data') if plot == 0: pmagplotlib.drawFIGS(PLTS) ppars = pmag.doprinc(data) Io = ppars['inc'] n = ppars["N"] Es, Is, Fs, V2s = pmag.find_f(data) if site_correction: Inc, Elong = Is[Es.index(min(Es))], Es[Es.index(min(Es))] flat_f = Fs[Es.index(min(Es))] else: Inc, Elong = Is[-1], Es[-1] flat_f = Fs[-1] pmagplotlib.plotEI(PLTS['ei'], Es, Is, flat_f) pmagplotlib.plotV2s(PLTS['v2'], V2s, Is, flat_f) b = 0 print("Bootstrapping.... be patient") while b < nb: bdata = pmag.pseudo(data) Esb, Isb, Fsb, V2sb = pmag.find_f(bdata) if b < 25: pmagplotlib.plotEI(PLTS['ei'], Esb, Isb, Fsb[-1]) if Esb[-1] != 0: ppars = pmag.doprinc(bdata) if site_correction: I.append(abs(Isb[Esb.index(min(Esb))])) E.append(Esb[Esb.index(min(Esb))]) else: I.append(abs(Isb[-1])) E.append(Esb[-1]) b += 1 if b % 25 == 0: print(b, ' out of ', nb) I.sort() E.sort() Eexp = [] for i in I: Eexp.append(pmag.EI(i)) if Inc == 0: title = 'Pathological Distribution: ' + '[%7.1f, %7.1f]' % (I[lower], I[upper]) else: title = '%7.1f [%7.1f, %7.1f]' % (Inc, I[lower], I[upper]) pmagplotlib.plotEI(PLTS['ei'], Eexp, I, 1) pmagplotlib.plotCDF(PLTS['cdf'], I, 'Inclinations', 'r', title) pmagplotlib.plotVs(PLTS['cdf'], [I[lower], I[upper]], 'b', '--') pmagplotlib.plotVs(PLTS['cdf'], [Inc], 'g', '-') pmagplotlib.plotVs(PLTS['cdf'], [Io], 'k', '-') if plot == 0: pmagplotlib.drawFIGS(PLTS) print("Io Inc I_lower, I_upper, Elon, E_lower, E_upper") print('%7.1f %s %7.1f _ %7.1f ^ %7.1f: %6.4f _ %6.4f ^ %6.4f' % (Io, " => ", Inc, I[lower], I[upper], Elong, E[lower], E[upper])) ans = input("S[a]ve plots - <return> to quit: ") if ans != 'a': print("\n Good bye\n") sys.exit() files = {} files['eq'] = 'findEI_eq.' + fmt files['ei'] = 'findEI_ei.' + fmt files['cdf'] = 'findEI_cdf.' + fmt files['v2'] = 'findEI_v2.' + fmt pmagplotlib.saveP(PLTS, files)
def main(): """ NAME watsons_v.py DESCRIPTION calculates Watson's V statistic from input files INPUT FORMAT takes dec/inc as first two columns in two space delimited files SYNTAX watsons_v.py [command line options] OPTIONS -h prints help message and quits -f FILE (with optional second) -f2 FILE (second file) -ant, flip antipodal directions to opposite direction in first file if only one file or flip all in second, if two files -P (don't save or show plot) -sav save figure and quit silently -fmt [png,svg,eps,pdf,jpg] format for saved figure OUTPUT Watson's V and the Monte Carlo Critical Value Vc. in plot, V is solid and Vc is dashed. """ Flip = 0 show, plot = 1, 0 fmt = 'svg' file2 = "" if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit if '-ant' in sys.argv: Flip = 1 if '-sav' in sys.argv: show, plot = 0, 1 # don't display, but do save plot if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-P' in sys.argv: show = 0 # don't display or save plot if '-f' in sys.argv: ind = sys.argv.index('-f') file1 = sys.argv[ind + 1] data = numpy.loadtxt(file1).transpose() D1 = numpy.array([data[0], data[1]]).transpose() else: print "-f is required" print main.__doc__ sys.exit() if '-f2' in sys.argv: ind = sys.argv.index('-f2') file2 = sys.argv[ind + 1] data2 = numpy.loadtxt(file2).transpose() D2 = numpy.array([data2[0], data2[1]]).transpose() if Flip == 1: D2, D = pmag.flip(D2) # D2 are now flipped if len(D2) != 0: if len(D) != 0: D2 = numpy.concatenate(D, D2) # put all in D2 elif len(D) != 0: D2 = D else: print 'length of second file is zero' sys.exit() elif Flip == 1: D2, D1 = pmag.flip(D1) # peel out antipodal directions, put in D2 # counter, NumSims = 0, 5000 # # first calculate the fisher means and cartesian coordinates of each set of Directions # pars_1 = pmag.fisher_mean(D1) pars_2 = pmag.fisher_mean(D2) # # get V statistic for these # V = pmag.vfunc(pars_1, pars_2) # # do monte carlo simulation of datasets with same kappas, but common mean # Vp = [] # set of Vs from simulations if show == 1: print "Doing ", NumSims, " simulations" for k in range(NumSims): counter += 1 if counter == 50: if show == 1: print k + 1 counter = 0 Dirp = [] # get a set of N1 fisher distributed vectors with k1, calculate fisher stats for i in range(pars_1["n"]): Dirp.append(pmag.fshdev(pars_1["k"])) pars_p1 = pmag.fisher_mean(Dirp) # get a set of N2 fisher distributed vectors with k2, calculate fisher stats Dirp = [] for i in range(pars_2["n"]): Dirp.append(pmag.fshdev(pars_2["k"])) pars_p2 = pmag.fisher_mean(Dirp) # get the V for these Vk = pmag.vfunc(pars_p1, pars_p2) Vp.append(Vk) # # sort the Vs, get Vcrit (95th one) # Vp.sort() k = int(.95 * NumSims) if show == 1: print "Watson's V, Vcrit: " print ' %10.1f %10.1f' % (V, Vp[k]) if show == 1 or plot == 1: print "Watson's V, Vcrit: " print ' %10.1f %10.1f' % (V, Vp[k]) CDF = {'cdf': 1} pmagplotlib.plot_init(CDF['cdf'], 5, 5) pmagplotlib.plotCDF(CDF['cdf'], Vp, "Watson's V", 'r', "") pmagplotlib.plotVs(CDF['cdf'], [V], 'g', '-') pmagplotlib.plotVs(CDF['cdf'], [Vp[k]], 'b', '--') if plot == 0: pmagplotlib.drawFIGS(CDF) files = {} if file2 != "": files['cdf'] = 'watsons_v_' + file1 + '_' + file2 + '.' + fmt else: files['cdf'] = 'watsons_v_' + file1 + '.' + fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['cdf'] = 'Cumulative Distribution' CDF = pmagplotlib.addBorders(CDF, titles, black, purple) pmagplotlib.saveP(CDF, files) elif plot == 0: ans = raw_input(" S[a]ve to save plot, [q]uit without saving: ") if ans == "a": pmagplotlib.saveP(CDF, files) if plot == 1: # save and quit silently pmagplotlib.saveP(CDF, files)
def main(): """ NAME hysteresis_magic.py DESCRIPTION calculates hystereis parameters and saves them in rmag_hystereis format file makes plots if option selected SYNTAX hysteresis_magic.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specify input file, default is agm_measurements.txt -fh: specify rmag_hysteresis.txt input file -F: specify output file, default is rmag_hysteresis.txt -P: do not make the plots -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg] """ args=sys.argv PLT=1 plots=0 user,meas_file,rmag_out,rmag_file="","agm_measurements.txt","rmag_hysteresis.txt","" pltspec="" dir_path='.' fmt='svg' verbose=pmagplotlib.verbose version_num=pmag.get_version() if '-WD' in args: ind=args.index('-WD') dir_path=args[ind+1] if "-h" in args: print(main.__doc__) sys.exit() if "-usr" in args: ind=args.index("-usr") user=args[ind+1] if '-f' in args: ind=args.index("-f") meas_file=args[ind+1] if '-F' in args: ind=args.index("-F") rmag_out=args[ind+1] if '-fh' in args: ind=args.index("-fh") rmag_file=args[ind+1] rmag_file=dir_path+'/'+rmag_file if '-P' in args: PLT=0 irm_init,imag_init=-1,-1 if '-sav' in args: verbose=0 plots=1 if '-spc' in args: ind=args.index("-spc") pltspec= args[ind+1] verbose=0 plots=1 if '-fmt' in args: ind=args.index("-fmt") fmt=args[ind+1] rmag_out=dir_path+'/'+rmag_out meas_file=dir_path+'/'+meas_file rmag_rem=dir_path+"/rmag_remanence.txt" # # meas_data,file_type=pmag.magic_read(meas_file) if file_type!='magic_measurements': print(main.__doc__) print('bad file') sys.exit() # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs,RemRecs=[],[] HDD={} if verbose: if verbose and PLT:print("Plots may be on top of each other - use mouse to place ") if PLT: HDD['hyst'],HDD['deltaM'],HDD['DdeltaM']=1,2,3 pmagplotlib.plot_init(HDD['DdeltaM'],5,5) pmagplotlib.plot_init(HDD['deltaM'],5,5) pmagplotlib.plot_init(HDD['hyst'],5,5) imag_init=0 irm_init=0 else: HDD['hyst'],HDD['deltaM'],HDD['DdeltaM'],HDD['irm'],HDD['imag']=0,0,0,0,0 # if rmag_file!="":hyst_data,file_type=pmag.magic_read(rmag_file) # # get list of unique experiment names and specimen names # experiment_names,sids=[],[] for rec in meas_data: meths=rec['magic_method_codes'].split(':') methods=[] for meth in meths: methods.append(meth.strip()) if 'LP-HYS' in methods: if 'er_synthetic_name' in list(rec.keys()) and rec['er_synthetic_name']!="": rec['er_specimen_name']=rec['er_synthetic_name'] if rec['magic_experiment_name'] not in experiment_names:experiment_names.append(rec['magic_experiment_name']) if rec['er_specimen_name'] not in sids:sids.append(rec['er_specimen_name']) # k=0 locname='' if pltspec!="": k=sids.index(pltspec) print(sids[k]) while k < len(sids): s=sids[k] if verbose and PLT:print(s, k+1 , 'out of ',len(sids)) # # B,M,Bdcd,Mdcd=[],[],[],[] #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data Bimag,Mimag=[],[] #Bimag,Mimag for initial magnetization curves first_dcd_rec,first_rec,first_imag_rec=1,1,1 for rec in meas_data: methcodes=rec['magic_method_codes'].split(':') meths=[] for meth in methcodes: meths.append(meth.strip()) if rec['er_specimen_name']==s and "LP-HYS" in meths: B.append(float(rec['measurement_lab_field_dc'])) M.append(float(rec['measurement_magn_moment'])) if first_rec==1: e=rec['magic_experiment_name'] HystRec={} first_rec=0 if "er_location_name" in list(rec.keys()): HystRec["er_location_name"]=rec["er_location_name"] locname=rec['er_location_name'].replace('/','-') if "er_sample_name" in list(rec.keys()):HystRec["er_sample_name"]=rec["er_sample_name"] if "er_site_name" in list(rec.keys()):HystRec["er_site_name"]=rec["er_site_name"] if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name']!="": HystRec["er_synthetic_name"]=rec["er_synthetic_name"] else: HystRec["er_specimen_name"]=rec["er_specimen_name"] if rec['er_specimen_name']==s and "LP-IRM-DCD" in meths: Bdcd.append(float(rec['treatment_dc_field'])) Mdcd.append(float(rec['measurement_magn_moment'])) if first_dcd_rec==1: RemRec={} irm_exp=rec['magic_experiment_name'] first_dcd_rec=0 if "er_location_name" in list(rec.keys()):RemRec["er_location_name"]=rec["er_location_name"] if "er_sample_name" in list(rec.keys()):RemRec["er_sample_name"]=rec["er_sample_name"] if "er_site_name" in list(rec.keys()):RemRec["er_site_name"]=rec["er_site_name"] if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name']!="": RemRec["er_synthetic_name"]=rec["er_synthetic_name"] else: RemRec["er_specimen_name"]=rec["er_specimen_name"] if rec['er_specimen_name']==s and "LP-IMAG" in meths: if first_imag_rec==1: imag_exp=rec['magic_experiment_name'] first_imag_rec=0 Bimag.append(float(rec['measurement_lab_field_dc'])) Mimag.append(float(rec['measurement_magn_moment'])) # # now plot the hysteresis curve # if len(B)>0: hmeths=[] for meth in meths: hmeths.append(meth) hpars=pmagplotlib.plotHDD(HDD,B,M,e) if verbose and PLT:pmagplotlib.drawFIGS(HDD) # # get prior interpretations from hyst_data if rmag_file!="": hpars_prior={} for rec in hyst_data: if rec['magic_experiment_names']==e: if rec['hysteresis_bcr'] !="" and rec['hysteresis_mr_moment']!="": hpars_prior['hysteresis_mr_moment']=rec['hysteresis_mr_moment'] hpars_prior['hysteresis_ms_moment']=rec['hysteresis_ms_moment'] hpars_prior['hysteresis_bc']=rec['hysteresis_bc'] hpars_prior['hysteresis_bcr']=rec['hysteresis_bcr'] break if verbose:pmagplotlib.plotHPARS(HDD,hpars_prior,'ro') else: if verbose:pmagplotlib.plotHPARS(HDD,hpars,'bs') HystRec['hysteresis_mr_moment']=hpars['hysteresis_mr_moment'] HystRec['hysteresis_ms_moment']=hpars['hysteresis_ms_moment'] HystRec['hysteresis_bc']=hpars['hysteresis_bc'] HystRec['hysteresis_bcr']=hpars['hysteresis_bcr'] HystRec['hysteresis_xhf']=hpars['hysteresis_xhf'] HystRec['magic_experiment_names']=e HystRec['magic_software_packages']=version_num if hpars["magic_method_codes"] not in hmeths:hmeths.append(hpars["magic_method_codes"]) methods="" for meth in hmeths: methods=methods+meth.strip()+":" HystRec["magic_method_codes"]=methods[:-1] HystRec["er_citation_names"]="This study" HystRecs.append(HystRec) # if len(Bdcd)>0: rmeths=[] for meth in meths: rmeths.append(meth) if verbose and PLT:print('plotting IRM') if irm_init==0: HDD['irm']=5 pmagplotlib.plot_init(HDD['irm'],5,5) irm_init=1 rpars=pmagplotlib.plotIRM(HDD['irm'],Bdcd,Mdcd,irm_exp) RemRec['remanence_mr_moment']=rpars['remanence_mr_moment'] RemRec['remanence_bcr']=rpars['remanence_bcr'] RemRec['magic_experiment_names']=irm_exp if rpars["magic_method_codes"] not in meths:meths.append(rpars["magic_method_codes"]) methods="" for meth in rmeths: methods=methods+meth.strip()+":" RemRec["magic_method_codes"]=methods[:-1] RemRec["er_citation_names"]="This study" RemRecs.append(RemRec) else: if irm_init:pmagplotlib.clearFIG(HDD['irm']) if len(Bimag)>0: if verbose:print('plotting initial magnetization curve') # first normalize by Ms Mnorm=[] for m in Mimag: Mnorm.append(old_div(m,float(hpars['hysteresis_ms_moment']))) if imag_init==0: HDD['imag']=4 pmagplotlib.plot_init(HDD['imag'],5,5) imag_init=1 pmagplotlib.plotIMAG(HDD['imag'],Bimag,Mnorm,imag_exp) else: if imag_init:pmagplotlib.clearFIG(HDD['imag']) # files={} if plots: if pltspec!="":s=pltspec files={} for key in list(HDD.keys()): files[key]=locname+'_'+s+'_'+key+'.'+fmt pmagplotlib.saveP(HDD,files) if pltspec!="":sys.exit() if verbose and PLT: pmagplotlib.drawFIGS(HDD) ans=input("S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ") if ans=="a": files={} for key in list(HDD.keys()): files[key]=locname+'_'+s+'_'+key+'.'+fmt pmagplotlib.saveP(HDD,files) if ans=='':k+=1 if ans=="p": del HystRecs[-1] k-=1 if ans=='q': print("Good bye") sys.exit() if ans=='s': keepon=1 specimen=input('Enter desired specimen name (or first part there of): ') while keepon==1: try: k =sids.index(specimen) keepon=0 except: tmplist=[] for qq in range(len(sids)): if specimen in sids[qq]:tmplist.append(sids[qq]) print(specimen," not found, but this was: ") print(tmplist) specimen=input('Select one or try again\n ') k =sids.index(specimen) else: k+=1 if len(B)==0 and len(Bdcd)==0: if verbose:print('skipping this one - no hysteresis data') k+=1 if rmag_out=="" and ans=='s' and verbose: really=input(" Do you want to overwrite the existing rmag_hystersis.txt file? 1/[0] ") if really=="": print('i thought not - goodbye') sys.exit() rmag_out="rmag_hysteresis.txt" if len(HystRecs)>0: pmag.magic_write(rmag_out,HystRecs,"rmag_hysteresis") if verbose:print("hysteresis parameters saved in ",rmag_out) if len(RemRecs)>0: pmag.magic_write(rmag_rem,RemRecs,"rmag_remanence") if verbose:print("remanence parameters saved in ",rmag_rem)
def main(): """ NAME trmaq_magic.py DESCTIPTION does non-linear trm acquisisiton correction SYNTAX trmaq_magic.py [-h][-i][command line options] OPTIONS -h prints help message and quits -i allows interactive setting of file names -f MFILE, sets magic_measurements input file -ft TSPEC, sets thellier_specimens input file -F OUT, sets output for non-linear TRM acquisition corrected data DEFAULTS MFILE: trmaq_measurements.txt TSPEC: thellier_specimens.txt OUT: NLT_specimens.txt """ meas_file = 'trmaq_measurements.txt' tspec = "thellier_specimens.txt" output = 'NLT_specimens.txt' if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-i' in sys.argv: meas_file = input( "Input magic_measurements file name? [trmaq_measurements.txt] ") if meas_file == "": meas_file = "trmaq_measurements.txt" tspec = input( " thellier_specimens file name? [thellier_specimens.txt] ") if tspec == "": tspec = "thellier_specimens.txt" output = input( "File for non-linear TRM adjusted specimen data: [NLTspecimens.txt] " ) if output == "": output = "NLT_specimens.txt" if '-f' in sys.argv: ind = sys.argv.index('-f') meas_file = sys.argv[ind + 1] if '-ft' in sys.argv: ind = sys.argv.index('-ft') tspec = sys.argv[ind + 1] if '-F' in sys.argv: ind = sys.argv.index('-F') output = sys.argv[ind + 1] # PLT = {'aq': 1} pmagplotlib.plot_init(PLT['aq'], 5, 5) # # get name of file from command line # comment = "" # # meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(file_type) print(file_type, "This is not a valid magic_measurements file ") sys.exit() sids = pmag.get_specs(meas_data) specimen = 0 # # read in thellier_specimen data # nrm, file_type = pmag.magic_read(tspec) PmagSpecRecs = [] while specimen < len(sids): # # find corresoponding paleointensity data for this specimen # s = sids[specimen] blab, best = "", "" for nrec in nrm: # pick out the Banc data for this spec if nrec["er_specimen_name"] == s: blab = float(nrec["specimen_lab_field_dc"]) best = float(nrec["specimen_int"]) TrmRec = nrec break if blab == "": print("skipping ", s, " : no best ") specimen += 1 else: print(sids[specimen], specimen + 1, 'of ', len(sids), 'Best = ', best * 1e6) MeasRecs = [] # # find the data from the meas_data file for this specimen # for rec in meas_data: if rec["er_specimen_name"] == s: meths = rec["magic_method_codes"].split(":") methcodes = [] for meth in meths: methcodes.append(meth.strip()) if "LP-TRM" in methcodes: MeasRecs.append(rec) if len(MeasRecs) < 2: specimen += 1 print('skipping specimen - no trm acquisition data ', s) # # collect info for the PmagSpecRec dictionary # else: TRMs, Bs = [], [] for rec in MeasRecs: Bs.append(float(rec['treatment_dc_field'])) TRMs.append(float(rec['measurement_magn_moment'])) NLpars = nlt.NLtrm( Bs, TRMs, best, blab, 0 ) # calculate best fit parameters through TRM acquisition data, and get new banc # Mp, Bp = [], [] for k in range(int(max(Bs) * 1e6)): Bp.append(float(k) * 1e-6) npred = nlt.TRM( Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1]) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM(PLT['aq'], Bs, TRMs, Bp, Mp, NLpars, rec['magic_experiment_name']) pmagplotlib.drawFIGS(PLT) print('Banc= ', float(NLpars['banc']) * 1e6) trmTC = {} for key in list(TrmRec.keys()): trmTC[key] = TrmRec[ key] # copy of info from thellier_specimens record trmTC['specimen_int'] = '%8.3e' % (NLpars['banc']) trmTC['magic_method_codes'] = TrmRec[ "magic_method_codes"] + ":DA-NL" PmagSpecRecs.append(trmTC) ans = input("Return for next specimen, s[a]ve plot ") if ans == 'a': Name = {'aq': rec['er_specimen_name'] + '_TRM.svg'} pmagplotlib.saveP(PLT, Name) specimen += 1 pmag.magic_write(output, PmagSpecRecs, 'pmag_specimens')
def main(): """ NAME plot_map_pts.py DESCRIPTION plots points on map SYNTAX plot_map_pts.py [command line options] OPTIONS -h prints help and quits -sym [ro, bs, g^, r., b-, etc.] [1,5,10] symbol and size for points colors are r=red,b=blue,g=green, etc. symbols are '.' for points, ^, for triangle, s for square, etc. -, for lines, -- for dotted lines, see matplotlib online documentation for plot() -eye ELAT ELON [specify eyeball location] -etp put on topography -f FILE, specify input file -o color ocean blue/land green (default is not) -res [c,l,i,h] specify resolution (crude, low, intermediate, high] -fmt [pdf,eps, png] specify output format (default is pdf) -R don't plot details of rivers -B don't plot national/state boundaries, etc. -pad [LAT LON] pad bounding box by LAT/LON (default is not) -grd SPACE specify grid spacing -sav save plot and quit -prj PROJ, specify one of the supported projections: (see basemap.py online documentation) aeqd = Azimuthal Equidistant poly = Polyconic gnom = Gnomonic moll = Mollweide tmerc = Transverse Mercator nplaea = North-Polar Lambert Azimuthal mill = Miller Cylindrical merc = Mercator stere = Stereographic npstere = North-Polar Stereographic geos = Geostationary laea = Lambert Azimuthal Equal Area sinu = Sinusoidal spstere = South-Polar Stereographic lcc = Lambert Conformal npaeqd = North-Polar Azimuthal Equidistant eqdc = Equidistant Conic cyl = Cylindrical Equidistant omerc = Oblique Mercator aea = Albers Equal Area spaeqd = South-Polar Azimuthal Equidistant ortho = Orthographic cass= Cassini-Soldner splaea = South-Polar Lambert Azimuthal robin = Robinson Special codes for MagIC formatted input files: -n -l INPUTS space or tab delimited LON LAT data OR: standard MagIC formatted er_sites or pmag_results table DEFAULTS res: c prj: mollweide; lcc for MagIC format files ELAT,ELON = 0,0 pad LAT,LON=0,0 NB: high resolution or lines can be very slow """ dir_path='.' plot=0 ocean=0 res='c' proj='moll' Lats,Lons=[],[] fmt='pdf' sym='ro' symsize=5 fancy=0 rivers,boundaries,ocean=1,1,0 latmin,latmax,lonmin,lonmax,lat_0,lon_0=-90,90,0.,360.,0.,0. padlat,padlon,gridspace=0,0,30 lat_0,lon_0="","" prn_name,prn_loc,names,locs=0,0,[],[] if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path=sys.argv[ind+1] if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-res' in sys.argv: ind = sys.argv.index('-res') res=sys.argv[ind+1] if res!= 'c' and res!='l': print('this resolution will take a while - be patient') if '-etp' in sys.argv: fancy=1 if '-sav' in sys.argv: plot=1 if '-R' in sys.argv:rivers=0 if '-B' in sys.argv:boundaries=0 if '-o' in sys.argv:ocean=1 if '-grd' in sys.argv: ind = sys.argv.index('-grd') gridspace=float(sys.argv[ind+1]) if '-eye' in sys.argv: ind = sys.argv.index('-eye') lat_0=float(sys.argv[ind+1]) lon_0=float(sys.argv[ind+2]) if '-sym' in sys.argv: ind = sys.argv.index('-sym') sym=sys.argv[ind+1] symsize=int(sys.argv[ind+2]) if '-pad' in sys.argv: ind = sys.argv.index('-pad') padlat=float(sys.argv[ind+1]) padlon=float(sys.argv[ind+2]) if '-f' in sys.argv: ind = sys.argv.index('-f') file=dir_path+'/'+sys.argv[ind+1] header=open(file,'r').readlines()[0].split('\t') if 'tab' in header[0]: if '-n' in sys.argv:prn_name=1 if '-l' in sys.argv:prn_loc=1 proj='lcc' if 'results' in header[1]: latkey='average_lat' lonkey='average_lon' namekey='pmag_result_name' lockey='er_location_names' elif 'sites' in header[1]: latkey='site_lat' lonkey='site_lon' namekey='er_site_name' lockey='er_location_name' else: print('file type not supported') print(main.__doc__) sys.exit() Sites,file_type=pmag.magic_read(file) Lats=pmag.get_dictkey(Sites,latkey,'f') Lons=pmag.get_dictkey(Sites,lonkey,'f') if prn_name==1:names=pmag.get_dictkey(Sites,namekey,'') if prn_loc==1:names=pmag.get_dictkey(Sites,lockey,'') else: ptdata=numpy.loadtxt(file) Lons=ptdata.transpose()[0] Lats=ptdata.transpose()[1] latmin=numpy.min(Lats)-padlat lonmin=numpy.min(Lons)-padlon latmax=numpy.max(Lats)+padlat lonmax=numpy.max(Lons)+padlon if lon_0=="": lon_0=0.5*(lonmin+lonmax) lat_0=0.5*(latmin+latmax) else: print("input file must be specified") sys.exit() if '-prj' in sys.argv: ind = sys.argv.index('-prj') proj=sys.argv[ind+1] FIG={'map':1} pmagplotlib.plot_init(FIG['map'],6,6) if res=='c':skip=8 if res=='l':skip=5 if res=='i':skip=2 if res=='h':skip=1 cnt=0 Opts={'latmin':latmin,'latmax':latmax,'lonmin':lonmin,'lonmax':lonmax,'lat_0':lat_0,'lon_0':lon_0,'proj':proj,'sym':sym,'symsize':3,'pltgrid':1,'res':res,'boundinglat':0.,'padlon':padlon,'padlat':padlat,'gridspace':gridspace} Opts['details']={} Opts['details']['coasts']=1 Opts['details']['rivers']=rivers Opts['details']['states']=boundaries Opts['details']['countries']=boundaries Opts['details']['ocean']=ocean Opts['details']['fancy']=fancy if len(names)>0:Opts['names']=names if len(locs)>0:Opts['loc_name']=locs if proj=='merc': Opts['latmin']=-70 Opts['latmax']=70 Opts['lonmin']=-180 Opts['lonmax']=180 print('please wait to draw points') Opts['sym']=sym Opts['symsize']=symsize pmagplotlib.plotMAP(FIG['map'],Lats,Lons,Opts) files={} titles={} titles['map']='PT Map' for key in list(FIG.keys()): files[key]='Map_PTS'+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) if plot==1: pmagplotlib.saveP(FIG,files) else: pmagplotlib.drawFIGS(FIG) ans=input(" S[a]ve to save plot, Return to quit: ") if ans=="a": pmagplotlib.saveP(FIG,files)
def main(): """ NAME lowrie_magic.py DESCRIPTION plots intensity decay curves for Lowrie experiments SYNTAX lowrie_magic.py -h [command line options] INPUT takes magic_measurements formatted input files OPTIONS -h prints help message and quits -f FILE: specify input file, default is magic_measurements.txt -N do not normalize by maximum magnetization -fmt [svg, pdf, eps, png] specify fmt, default is svg -sav saves plots and quits """ fmt, plot = 'svg', 0 FIG = {} # plot dictionary FIG['lowrie'] = 1 # demag is figure 1 pmagplotlib.plot_init(FIG['lowrie'], 6, 6) norm = 1 # default is to normalize by maximum axis in_file, dir_path = 'magic_measurements.txt', '.' if len(sys.argv) > 1: if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path = sys.argv[ind + 1] if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-N' in sys.argv: norm = 0 # don't normalize if '-sav' in sys.argv: plot = 1 # don't normalize if '-fmt' in sys.argv: # sets input filename ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] if '-f' in sys.argv: # sets input filename ind = sys.argv.index("-f") in_file = sys.argv[ind + 1] else: print(main.__doc__) print('you must supply a file name') sys.exit() in_file = dir_path + '/' + in_file print(in_file) PmagRecs, file_type = pmag.magic_read(in_file) if file_type != "magic_measurements": print('bad input file') sys.exit() PmagRecs = pmag.get_dictitem(PmagRecs, 'magic_method_codes', 'LP-IRM-3D', 'has') # get all 3D IRM records if len(PmagRecs) == 0: print('no records found') sys.exit() specs = pmag.get_dictkey(PmagRecs, 'er_specimen_name', '') sids = [] for spec in specs: if spec not in sids: sids.append(spec) # get list of unique specimen names for spc in sids: # step through the specimen names print(spc) specdata = pmag.get_dictitem(PmagRecs, 'er_specimen_name', spc, 'T') # get all this one's data DIMs, Temps = [], [] for dat in specdata: # step through the data DIMs.append([ float(dat['measurement_dec']), float(dat['measurement_inc']), float(dat['measurement_magn_moment']) ]) Temps.append(float(dat['treatment_temp']) - 273.) carts = pmag.dir2cart(DIMs).transpose() if norm == 1: # want to normalize nrm = (DIMs[0][2]) # normalize by NRM ylab = "M/M_o" else: nrm = 1. # don't normalize ylab = "Magnetic moment (Am^2)" xlab = "Temperature (C)" pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[0]), nrm), sym='r-') pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[0]), nrm), sym='ro') # X direction pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[1]), nrm), sym='c-') pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[1]), nrm), sym='cs') # Y direction pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[2]), nrm), sym='k-') pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[2]), nrm), sym='k^', title=spc, xlab=xlab, ylab=ylab) # Z direction files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt} if plot == 0: pmagplotlib.drawFIGS(FIG) ans = input('S[a]ve figure? [q]uit, <return> to continue ') if ans == 'a': pmagplotlib.saveP(FIG, files) elif ans == 'q': sys.exit() else: pmagplotlib.saveP(FIG, files) pmagplotlib.clearFIG(FIG['lowrie'])
def main(): """ NAME chi_magic.py DESCRIPTION plots magnetic susceptibility as a function of frequency and temperature and AC field SYNTAX chi_magic.py [command line options] OPTIONS -h prints help message and quits -i allows interactive setting of FILE and temperature step -f FILE, specify magic_measurements format file -T IND, specify temperature step to plot -e EXP, specify experiment name to plot -fmt [svg,jpg,png,pdf] set figure format [default is svg] -sav save figure and quit DEFAULTS FILE: magic_measurements.txt IND: first SPEC: step through one by one """ cont,FTinit,BTinit,k="",0,0,0 meas_file="magic_measurements.txt" spec="" Tind,cont=0,"" EXP="" fmt='svg' # default image type for saving plot=0 if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-i' in sys.argv: file=input("Input magic_measurements file name? [magic_measurements.txt] ") if file!="":meas_file=file if '-e' in sys.argv: ind=sys.argv.index('-e') EXP=sys.argv[ind+1] if '-f' in sys.argv: ind=sys.argv.index('-f') meas_file=sys.argv[ind+1] if '-T' in sys.argv: ind=sys.argv.index('-T') Tind=int(sys.argv[ind+1]) if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-sav' in sys.argv:plot=1 # meas_data,file_type=pmag.magic_read(meas_file) # # get list of unique experiment names # # initialize some variables (a continuation flag, plot initialization flags and the experiment counter experiment_names=[] for rec in meas_data: if rec['magic_experiment_name'] not in experiment_names:experiment_names.append(rec['magic_experiment_name']) # # hunt through by experiment name if EXP!="": try: k=experiment_names.index(EXP) except: print("Bad experiment name") sys.exit() while k < len(experiment_names): e=experiment_names[k] if EXP=="":print(e, k+1 , 'out of ',len(experiment_names)) # # initialize lists of data, susceptibility, temperature, frequency and field X,T,F,B=[],[],[],[] for rec in meas_data: methcodes=rec['magic_method_codes'] meths=methcodes.strip().split(':') if rec['magic_experiment_name']==e and "LP-X" in meths: # looking for chi measurement if 'measurement_temp' not in list(rec.keys()):rec['measurement_temp']='300' # set defaults if 'measurement_freq' not in list(rec.keys()):rec['measurement_freq']='0' # set defaults if 'measurement_lab_field_ac' not in list(rec.keys()):rec['measurement_lab_field_ac']='0' # set default X.append(float(rec['measurement_x'])) T.append(float(rec['measurement_temp'])) F.append(float(rec['measurement_freq'])) B.append(float(rec['measurement_lab_field_ac'])) # # get unique list of Ts,Fs, and Bs # Ts,Fs,Bs=[],[],[] for k in range(len(X)): # hunt through all the measurements if T[k] not in Ts:Ts.append(T[k]) # append if not in list if F[k] not in Fs:Fs.append(F[k]) if B[k] not in Bs:Bs.append(B[k]) Ts.sort() # sort list of temperatures, frequencies and fields Fs.sort() Bs.sort() if '-x' in sys.argv: k=len(experiment_names)+1 # just plot the one else: k+=1 # increment experiment number # # plot chi versus T and F holding B constant # plotnum=1 # initialize plot number to 1 if len(X)>2: # if there are any data to plot, continue b=Bs[-1] # keeping field constant and at maximum XTF=[] # initialize list of chi versus Temp and freq for f in Fs: # step through frequencies sequentially XT=[] # initialize list of chi versus temp for kk in range(len(X)): # hunt through all the data if F[kk]==f and B[kk]==b: # select data with given freq and field XT.append([X[kk],T[kk]]) # append to list XTF.append(XT) # append list to list of frequencies if len(XT)>1: # if there are any temperature dependent data pmagplotlib.plot_init(plotnum,5,5) # initialize plot pmagplotlib.plotXTF(plotnum,XTF,Fs,e,b) # call the plotting function if plot==0:pmagplotlib.drawFIGS({'fig':plotnum}) #make it visible plotnum+=1 # increment plot number f=Fs[0] # set frequency to minimum XTB=[] # initialize list if chi versus Temp and field for b in Bs: # step through field values XT=[] # initial chi versus temp list for this field for kk in range(len(X)): # hunt through all the data if F[kk]==f and B[kk]==b: # select data with given freq and field XT.append([X[kk],T[kk]]) # append to list XTB.append(XT) if len(XT)>1: # if there are any temperature dependent data pmagplotlib.plot_init(plotnum,5,5) # set up plot pmagplotlib.plotXTB(plotnum,XTB,Bs,e,f) # call the plotting function if plot==0:pmagplotlib.drawFIGS({'fig':plotnum}) plotnum+=1 # increment plot number if '-i' in sys.argv: for ind in range(len(Ts)): # print list of temperatures available print(ind,int(Ts[ind])) cont=input("Enter index of desired temperature step, s[a]ve plots, [return] to quit ") if cont=='a': files={} PLTS={} for p in range(1,plotnum): key=str(p) files[key]=e+'_'+key+'.'+fmt PLTS[key]=key pmagplotlib.saveP(PLTS,files) cont=input("Enter index of desired temperature step, s[a]ve plots, [return] to quit ") if cont=="":cont='q' while cont!="q": if '-i' in sys.argv:Tind=int(cont) # set temperature index b=Bs[-1] # set field to max available XF=[] # initial chi versus frequency list for kk in range(len(X)): # hunt through the data if T[kk]==Ts[Tind] and B[kk]==b: # if temperature and field match, XF.append([X[kk],F[kk]]) # append the data if len(XF)>1: # if there are any data to plot if FTinit==0: # if not already initialized, initialize plot #print 'initializing ',plotnum pmagplotlib.plot_init(plotnum,5,5) FTinit=1 XFplot=plotnum plotnum+=1 # increment plotnum pmagplotlib.plotXFT(XFplot,XF,Ts[Tind],e,b) if plot==0:pmagplotlib.drawFIGS({'fig':plotnum}) else: print('\n *** Skipping susceptibitily-frequency plot as a function of temperature *** \n') f=Fs[0] # set frequency to minimum available XB=[] # initialize chi versus field list for kk in range(len(X)): # hunt through the data if T[kk]==Ts[Tind] and F[kk]==f: # if temperature and field match those desired XB.append([X[kk],B[kk]]) # append the data to list if len(XB)>4: # if there are any data if BTinit==0: # if plot not already initialized pmagplotlib.plot_init(plotnum,5,5) # do it BTinit=1 pmagplotlib.plotXBT(plotnum,XB,Ts[Tind],e,f) # and call plotting function if plot==0:pmagplotlib.drawFIGS({'fig':plotnum}) else: print('Skipping susceptibitily - AC field plot as a function of temperature') files={} PLTS={} for p in range(1,plotnum): key=str(p) files[key]=e+'_'+key+'.'+fmt PLTS[key]=p if '-i' in sys.argv: for ind in range(len(Ts)): # just in case you forgot, print out a new list of temperatures print(ind,int(Ts[ind])) cont=input("Enter index of next temperature step, s[a]ve plots, [return] to quit ") # ask for new temp if cont=="":sys.exit() if cont=='a': pmagplotlib.saveP(PLTS,files) cont=input("Enter index of desired temperature step, s[a]ve plots, [return] to quit ") if cont=="":sys.exit() elif plot==0: ans=input("enter s[a]ve to save files, [return] to quit ") if ans=='a': pmagplotlib.saveP(PLTS,files) sys.exit() else: sys.exit() else: pmagplotlib.saveP(PLTS,files) sys.exit()
def main(): """ NAME hysteresis_magic.py DESCRIPTION calculates hystereis parameters and saves them in rmag_hystereis format file makes plots if option selected SYNTAX hysteresis_magic.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specify input file, default is agm_measurements.txt -fh: specify rmag_hysteresis.txt input file -F: specify output file, default is rmag_hysteresis.txt -P: do not make the plots -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg] """ args = sys.argv PLT = 1 plots = 0 user, meas_file, rmag_out, rmag_file = "", "agm_measurements.txt", "rmag_hysteresis.txt", "" pltspec = "" dir_path = '.' fmt = 'svg' verbose = pmagplotlib.verbose version_num = pmag.get_version() if '-WD' in args: ind = args.index('-WD') dir_path = args[ind + 1] if "-h" in args: print main.__doc__ sys.exit() if "-usr" in args: ind = args.index("-usr") user = args[ind + 1] if '-f' in args: ind = args.index("-f") meas_file = args[ind + 1] if '-F' in args: ind = args.index("-F") rmag_out = args[ind + 1] if '-fh' in args: ind = args.index("-fh") rmag_file = args[ind + 1] rmag_file = dir_path + '/' + rmag_file if '-P' in args: PLT = 0 irm_init, imag_init = -1, -1 if '-sav' in args: verbose = 0 plots = 1 if '-spc' in args: ind = args.index("-spc") pltspec = args[ind + 1] verbose = 0 plots = 1 if '-fmt' in args: ind = args.index("-fmt") fmt = args[ind + 1] rmag_out = dir_path + '/' + rmag_out meas_file = dir_path + '/' + meas_file rmag_rem = dir_path + "/rmag_remanence.txt" # # meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print main.__doc__ print 'bad file' sys.exit() # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs, RemRecs = [], [] HDD = {} if verbose: if verbose and PLT: print "Plots may be on top of each other - use mouse to place " if PLT: HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'] = 1, 2, 3 pmagplotlib.plot_init(HDD['DdeltaM'], 5, 5) pmagplotlib.plot_init(HDD['deltaM'], 5, 5) pmagplotlib.plot_init(HDD['hyst'], 5, 5) imag_init = 0 irm_init = 0 else: HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'], HDD['irm'], HDD[ 'imag'] = 0, 0, 0, 0, 0 # if rmag_file != "": hyst_data, file_type = pmag.magic_read(rmag_file) # # get list of unique experiment names and specimen names # experiment_names, sids = [], [] for rec in meas_data: meths = rec['magic_method_codes'].split(':') methods = [] for meth in meths: methods.append(meth.strip()) if 'LP-HYS' in methods: if 'er_synthetic_name' in rec.keys( ) and rec['er_synthetic_name'] != "": rec['er_specimen_name'] = rec['er_synthetic_name'] if rec['magic_experiment_name'] not in experiment_names: experiment_names.append(rec['magic_experiment_name']) if rec['er_specimen_name'] not in sids: sids.append(rec['er_specimen_name']) # k = 0 locname = '' if pltspec != "": k = sids.index(pltspec) print sids[k] while k < len(sids): s = sids[k] if verbose and PLT: print s, k + 1, 'out of ', len(sids) # # B, M, Bdcd, Mdcd = [], [], [], [ ] #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data Bimag, Mimag = [], [] #Bimag,Mimag for initial magnetization curves first_dcd_rec, first_rec, first_imag_rec = 1, 1, 1 for rec in meas_data: methcodes = rec['magic_method_codes'].split(':') meths = [] for meth in methcodes: meths.append(meth.strip()) if rec['er_specimen_name'] == s and "LP-HYS" in meths: B.append(float(rec['measurement_lab_field_dc'])) M.append(float(rec['measurement_magn_moment'])) if first_rec == 1: e = rec['magic_experiment_name'] HystRec = {} first_rec = 0 if "er_location_name" in rec.keys(): HystRec["er_location_name"] = rec["er_location_name"] locname = rec['er_location_name'].replace('/', '-') if "er_sample_name" in rec.keys(): HystRec["er_sample_name"] = rec["er_sample_name"] if "er_site_name" in rec.keys(): HystRec["er_site_name"] = rec["er_site_name"] if "er_synthetic_name" in rec.keys( ) and rec['er_synthetic_name'] != "": HystRec["er_synthetic_name"] = rec["er_synthetic_name"] else: HystRec["er_specimen_name"] = rec["er_specimen_name"] if rec['er_specimen_name'] == s and "LP-IRM-DCD" in meths: Bdcd.append(float(rec['treatment_dc_field'])) Mdcd.append(float(rec['measurement_magn_moment'])) if first_dcd_rec == 1: RemRec = {} irm_exp = rec['magic_experiment_name'] first_dcd_rec = 0 if "er_location_name" in rec.keys(): RemRec["er_location_name"] = rec["er_location_name"] if "er_sample_name" in rec.keys(): RemRec["er_sample_name"] = rec["er_sample_name"] if "er_site_name" in rec.keys(): RemRec["er_site_name"] = rec["er_site_name"] if "er_synthetic_name" in rec.keys( ) and rec['er_synthetic_name'] != "": RemRec["er_synthetic_name"] = rec["er_synthetic_name"] else: RemRec["er_specimen_name"] = rec["er_specimen_name"] if rec['er_specimen_name'] == s and "LP-IMAG" in meths: if first_imag_rec == 1: imag_exp = rec['magic_experiment_name'] first_imag_rec = 0 Bimag.append(float(rec['measurement_lab_field_dc'])) Mimag.append(float(rec['measurement_magn_moment'])) # # now plot the hysteresis curve # if len(B) > 0: hmeths = [] for meth in meths: hmeths.append(meth) hpars = pmagplotlib.plotHDD(HDD, B, M, e) if verbose and PLT: pmagplotlib.drawFIGS(HDD) # # get prior interpretations from hyst_data if rmag_file != "": hpars_prior = {} for rec in hyst_data: if rec['magic_experiment_names'] == e: if rec['hysteresis_bcr'] != "" and rec[ 'hysteresis_mr_moment'] != "": hpars_prior['hysteresis_mr_moment'] = rec[ 'hysteresis_mr_moment'] hpars_prior['hysteresis_ms_moment'] = rec[ 'hysteresis_ms_moment'] hpars_prior['hysteresis_bc'] = rec['hysteresis_bc'] hpars_prior['hysteresis_bcr'] = rec[ 'hysteresis_bcr'] break if verbose: pmagplotlib.plotHPARS(HDD, hpars_prior, 'ro') else: if verbose: pmagplotlib.plotHPARS(HDD, hpars, 'bs') HystRec['hysteresis_mr_moment'] = hpars['hysteresis_mr_moment'] HystRec['hysteresis_ms_moment'] = hpars['hysteresis_ms_moment'] HystRec['hysteresis_bc'] = hpars['hysteresis_bc'] HystRec['hysteresis_bcr'] = hpars['hysteresis_bcr'] HystRec['hysteresis_xhf'] = hpars['hysteresis_xhf'] HystRec['magic_experiment_names'] = e HystRec['magic_software_packages'] = version_num if hpars["magic_method_codes"] not in hmeths: hmeths.append(hpars["magic_method_codes"]) methods = "" for meth in hmeths: methods = methods + meth.strip() + ":" HystRec["magic_method_codes"] = methods[:-1] HystRec["er_citation_names"] = "This study" HystRecs.append(HystRec) # if len(Bdcd) > 0: rmeths = [] for meth in meths: rmeths.append(meth) if verbose and PLT: print 'plotting IRM' if irm_init == 0: HDD['irm'] = 5 pmagplotlib.plot_init(HDD['irm'], 5, 5) irm_init = 1 rpars = pmagplotlib.plotIRM(HDD['irm'], Bdcd, Mdcd, irm_exp) RemRec['remanence_mr_moment'] = rpars['remanence_mr_moment'] RemRec['remanence_bcr'] = rpars['remanence_bcr'] RemRec['magic_experiment_names'] = irm_exp if rpars["magic_method_codes"] not in meths: meths.append(rpars["magic_method_codes"]) methods = "" for meth in rmeths: methods = methods + meth.strip() + ":" RemRec["magic_method_codes"] = methods[:-1] RemRec["er_citation_names"] = "This study" RemRecs.append(RemRec) else: if irm_init: pmagplotlib.clearFIG(HDD['irm']) if len(Bimag) > 0: if verbose: print 'plotting initial magnetization curve' # first normalize by Ms Mnorm = [] for m in Mimag: Mnorm.append(m / float(hpars['hysteresis_ms_moment'])) if imag_init == 0: HDD['imag'] = 4 pmagplotlib.plot_init(HDD['imag'], 5, 5) imag_init = 1 pmagplotlib.plotIMAG(HDD['imag'], Bimag, Mnorm, imag_exp) else: if imag_init: pmagplotlib.clearFIG(HDD['imag']) # files = {} if plots: if pltspec != "": s = pltspec files = {} for key in HDD.keys(): files[key] = locname + '_' + s + '_' + key + '.' + fmt pmagplotlib.saveP(HDD, files) if pltspec != "": sys.exit() if verbose and PLT: pmagplotlib.drawFIGS(HDD) ans = raw_input( "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n " ) if ans == "a": files = {} for key in HDD.keys(): files[key] = locname + '_' + s + '_' + key + '.' + fmt pmagplotlib.saveP(HDD, files) if ans == '': k += 1 if ans == "p": del HystRecs[-1] k -= 1 if ans == 'q': print "Good bye" sys.exit() if ans == 's': keepon = 1 specimen = raw_input( 'Enter desired specimen name (or first part there of): ') while keepon == 1: try: k = sids.index(specimen) keepon = 0 except: tmplist = [] for qq in range(len(sids)): if specimen in sids[qq]: tmplist.append(sids[qq]) print specimen, " not found, but this was: " print tmplist specimen = raw_input('Select one or try again\n ') k = sids.index(specimen) else: k += 1 if len(B) == 0 and len(Bdcd) == 0: if verbose: print 'skipping this one - no hysteresis data' k += 1 if rmag_out == "" and ans == 's' and verbose: really = raw_input( " Do you want to overwrite the existing rmag_hystersis.txt file? 1/[0] " ) if really == "": print 'i thought not - goodbye' sys.exit() rmag_out = "rmag_hysteresis.txt" if len(HystRecs) > 0: pmag.magic_write(rmag_out, HystRecs, "rmag_hysteresis") if verbose: print "hysteresis parameters saved in ", rmag_out if len(RemRecs) > 0: pmag.magic_write(rmag_rem, RemRecs, "rmag_remanence") if verbose: print "remanence parameters saved in ", rmag_rem
def main(): """ NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a pmag_results table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ELON [specify eyeball location], default is 90., 0. -f FILE pmag_results format file, [default is pmag_results.txt] -res [c,l,i,h] specify resolution (crude, low, intermediate, high] -etp plot the etopo20 topographpy data (requires high resolution data set) -prj PROJ, specify one of the following: ortho = orthographic lcc = lambert conformal moll = molweide merc = mercator -sym SYM SIZE: choose a symbol and size, examples: ro 5 : small red circles bs 10 : intermediate blue squares g^ 20 : large green triangles -ell plot dp/dm or a95 ellipses -rev RSYM RSIZE : flip reverse poles to normal antipode -S: plot antipodes of all poles -age : plot the ages next to the poles -crd [g,t] : choose coordinate system, default is to plot all site VGPs -fmt [pdf, png, eps...] specify output format, default is pdf -sav save and quit DEFAULTS FILE: pmag_results.txt res: c prj: ortho ELAT,ELON = 0,0 SYM SIZE: ro 8 RSYM RSIZE: g^ 8 """ dir_path = '.' res, ages = 'c', 0 plot = 0 proj = 'ortho' results_file = 'pmag_results.txt' ell, flip = 0, 0 lat_0, lon_0 = 90., 0. fmt = 'pdf' sym, size = 'ro', 8 rsym, rsize = 'g^', 8 anti = 0 fancy = 0 coord = "" if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path = sys.argv[ind + 1] if '-h' in sys.argv: print main.__doc__ sys.exit() if '-S' in sys.argv: anti = 1 if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-sav' in sys.argv: plot = 1 if '-res' in sys.argv: ind = sys.argv.index('-res') res = sys.argv[ind + 1] if '-etp' in sys.argv: fancy = 1 if '-prj' in sys.argv: ind = sys.argv.index('-prj') proj = sys.argv[ind + 1] if '-rev' in sys.argv: flip = 1 ind = sys.argv.index('-rev') rsym = (sys.argv[ind + 1]) rsize = int(sys.argv[ind + 2]) if '-sym' in sys.argv: ind = sys.argv.index('-sym') sym = (sys.argv[ind + 1]) size = int(sys.argv[ind + 2]) if '-eye' in sys.argv: ind = sys.argv.index('-eye') lat_0 = float(sys.argv[ind + 1]) lon_0 = float(sys.argv[ind + 2]) if '-ell' in sys.argv: ell = 1 if '-age' in sys.argv: ages = 1 if '-f' in sys.argv: ind = sys.argv.index('-f') results_file = sys.argv[ind + 1] if '-crd' in sys.argv: ind = sys.argv.index('-crd') crd = sys.argv[ind + 1] if crd == 'g': coord = '0' if crd == 't': coord = '100' results_file = dir_path + '/' + results_file data, file_type = pmag.magic_read(results_file) if file_type != 'pmag_results': print "bad results file" sys.exit() FIG = {'map': 1} pmagplotlib.plot_init(FIG['map'], 6, 6) # read in er_sites file lats, lons, dp, dm, a95 = [], [], [], [], [] Pars = [] dates, rlats, rlons = [], [], [] if 'data_type' in data[0].keys(): Results = pmag.get_dictitem(data, 'data_type', 'i', 'T') # get all site level data else: Results = data Results = pmag.get_dictitem(Results, 'vgp_lat', '', 'F') # get all non-blank latitudes Results = pmag.get_dictitem(Results, 'vgp_lon', '', 'F') # get all non-blank longitudes if coord != "": Results = pmag.get_dictitem(Results, 'tilt_correction', coord, 'T') # get specified coordinate system location = "" for rec in Results: if rec['er_location_names'] not in location: location = location + ':' + rec['er_location_names'] if 'average_age' in rec.keys( ) and rec['average_age'] != "" and ages == 1: dates.append(rec['average_age']) lat = float(rec['vgp_lat']) lon = float(rec['vgp_lon']) if flip == 0: lats.append(lat) lons.append(lon) elif flip == 1: if lat < 0: rlats.append(-lat) lon = lon + 180. if lon > 360: lon = lon - 360. rlons.append(lon) else: lats.append(lat) lons.append(lon) elif anti == 1: lats.append(-lat) lon = lon + 180. if lon > 360: lon = lon - 360. lons.append(lon) ppars = [] ppars.append(lon) ppars.append(lat) ell1, ell2 = "", "" if 'vgp_dm' in rec.keys() and rec['vgp_dm'] != "": ell1 = float(rec['vgp_dm']) if 'vgp_dp' in rec.keys() and rec['vgp_dp'] != "": ell2 = float(rec['vgp_dp']) if 'vgp_alpha95' in rec.keys() and rec['vgp_alpha95'] != "": ell1, ell2 = float(rec['vgp_alpha95']), float(rec['vgp_alpha95']) if ell1 != "" and ell2 != "": ppars = [] ppars.append(lons[-1]) ppars.append(lats[-1]) ppars.append(ell1) ppars.append(lons[-1]) isign = abs(lats[-1]) / lats[-1] ppars.append(lats[-1] - isign * 90.) ppars.append(ell2) ppars.append(lons[-1] + 90.) ppars.append(0.) Pars.append(ppars) location = location.strip(':') Opts = { 'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360., 'lat_0': lat_0, 'lon_0': lon_0, 'proj': proj, 'sym': 'bs', 'symsize': 3, 'pltgrid': 0, 'res': res, 'boundinglat': 0. } Opts['details'] = { 'coasts': 1, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 1, 'fancy': fancy } pmagplotlib.plotMAP( FIG['map'], [90.], [0.], Opts) # make the base map with a blue triangle at the pole` Opts['pltgrid'] = -1 Opts['sym'] = sym Opts['symsize'] = size if len(dates) > 0: Opts['names'] = dates if len(lats) > 0: pmagplotlib.plotMAP(FIG['map'], lats, lons, Opts) # add the lats and lons of the poles Opts['names'] = [] if len(rlats) > 0: Opts['sym'] = rsym Opts['symsize'] = rsize pmagplotlib.plotMAP(FIG['map'], rlats, rlons, Opts) # add the lats and lons of the poles if plot == 0: pmagplotlib.drawFIGS(FIG) if ell == 1: # add ellipses if desired. Opts['details'] = { 'coasts': 0, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 0 } Opts['pltgrid'] = -1 # turn off meridian replotting Opts['symsize'] = 2 Opts['sym'] = 'g-' for ppars in Pars: if ppars[2] != 0: PTS = pmagplotlib.plotELL(FIG['map'], ppars, 'g.', 0, 0) elats, elons = [], [] for pt in PTS: elons.append(pt[0]) elats.append(pt[1]) pmagplotlib.plotMAP( FIG['map'], elats, elons, Opts ) # make the base map with a blue triangle at the pole` if plot == 0: pmagplotlib.drawFIGS(FIG) files = {} for key in FIG.keys(): files[key] = 'LO:_' + location + '_VGP_map.' + fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['eq'] = 'LO:_' + location + '_VGP_map' FIG = pmagplotlib.addBorders(FIG, titles, black, purple) pmagplotlib.saveP(FIG, files) elif plot == 0: pmagplotlib.drawFIGS(FIG) ans = raw_input(" S[a]ve to save plot, Return to quit: ") if ans == "a": pmagplotlib.saveP(FIG, files) else: print "Good bye" sys.exit() else: pmagplotlib.saveP(FIG, files)
def main(): """ NAME foldtest.py DESCRIPTION does a fold test (Tauxe, 2010) on data INPUT FORMAT dec inc dip_direction dip SYNTAX foldtest.py [command line options] OPTIONS -h prints help message and quits -f FILE file with input data -F FILE for confidence bounds on fold test -u ANGLE (circular standard deviation) for uncertainty on bedding poles -b MIN MAX bounds for quick search of percent untilting [default is -10 to 150%] -n NB number of bootstrap samples [default is 1000] -fmt FMT, specify format - default is svg -sav save figures and quit INPUT FILE Dec Inc Dip_Direction Dip in space delimited file OUTPUT PLOTS Geographic: is an equal area projection of the input data in original coordinates Stratigraphic: is an equal area projection of the input data in tilt adjusted coordinates % Untilting: The dashed (red) curves are representative plots of maximum eigenvalue (tau_1) as a function of untilting The solid line is the cumulative distribution of the % Untilting required to maximize tau for all the bootstrapped data sets. The dashed vertical lines are 95% confidence bounds on the % untilting that yields the most clustered result (maximum tau_1). Command line: prints out the bootstrapped iterations and finally the confidence bounds on optimum untilting. If the 95% conf bounds include 0, then a post-tilt magnetization is indicated If the 95% conf bounds include 100, then a pre-tilt magnetization is indicated If the 95% conf bounds exclude both 0 and 100, syn-tilt magnetization is possible as is vertical axis rotation or other pathologies Geographic: is an equal area projection of the input data in OPTIONAL OUTPUT FILE: The output file has the % untilting within the 95% confidence bounds nd the number of bootstrap samples """ kappa=0 fmt,plot='svg',0 nb=1000 # number of bootstraps min,max=-10,150 if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit if '-F' in sys.argv: ind=sys.argv.index('-F') outfile=open(sys.argv[ind+1],'w') else: outfile="" if '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] DIDDs=numpy.loadtxt(file) else: print main.__doc__ sys.exit() if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-sav' in sys.argv:plot=1 if '-b' in sys.argv: ind=sys.argv.index('-b') min=int(sys.argv[ind+1]) max=int(sys.argv[ind+2]) if '-n' in sys.argv: ind=sys.argv.index('-n') nb=int(sys.argv[ind+1]) if '-u' in sys.argv: ind=sys.argv.index('-u') csd=float(sys.argv[ind+1]) kappa=(81./csd)**2 # # get to work # PLTS={'geo':1,'strat':2,'taus':3} # make plot dictionary pmagplotlib.plot_init(PLTS['geo'],5,5) pmagplotlib.plot_init(PLTS['strat'],5,5) pmagplotlib.plot_init(PLTS['taus'],5,5) pmagplotlib.plotEQ(PLTS['geo'],DIDDs,'Geographic') D,I=pmag.dotilt_V(DIDDs) TCs=numpy.array([D,I]).transpose() pmagplotlib.plotEQ(PLTS['strat'],TCs,'Stratigraphic') if plot==0:pmagplotlib.drawFIGS(PLTS) Percs=range(min,max) Cdf,Untilt=[],[] pylab.figure(num=PLTS['taus']) print 'doing ',nb,' iterations...please be patient.....' for n in range(nb): # do bootstrap data sets - plot first 25 as dashed red line if n%50==0:print n Taus=[] # set up lists for taus PDs=pmag.pseudo(DIDDs) if kappa!=0: for k in range(len(PDs)): d,i=pmag.fshdev(kappa) dipdir,dip=pmag.dodirot(d,i,PDs[k][2],PDs[k][3]) PDs[k][2]=dipdir PDs[k][3]=dip for perc in Percs: tilt=numpy.array([1.,1.,1.,0.01*perc]) D,I=pmag.dotilt_V(PDs*tilt) TCs=numpy.array([D,I]).transpose() ppars=pmag.doprinc(TCs) # get principal directions Taus.append(ppars['tau1']) if n<25:pylab.plot(Percs,Taus,'r--') Untilt.append(Percs[Taus.index(numpy.max(Taus))]) # tilt that gives maximum tau Cdf.append(float(n)/float(nb)) pylab.plot(Percs,Taus,'k') pylab.xlabel('% Untilting') pylab.ylabel('tau_1 (red), CDF (green)') Untilt.sort() # now for CDF of tilt of maximum tau pylab.plot(Untilt,Cdf,'g') lower=int(.025*nb) upper=int(.975*nb) pylab.axvline(x=Untilt[lower],ymin=0,ymax=1,linewidth=1,linestyle='--') pylab.axvline(x=Untilt[upper],ymin=0,ymax=1,linewidth=1,linestyle='--') tit= '%i - %i %s'%(Untilt[lower],Untilt[upper],'Percent Unfolding') print tit print 'range of all bootstrap samples: ', Untilt[0], ' - ', Untilt[-1] pylab.title(tit) outstring= '%i - %i; %i\n'%(Untilt[lower],Untilt[upper],nb) if outfile!="":outfile.write(outstring) files={} for key in PLTS.keys(): files[key]=('foldtest_'+'%s'%(key.strip()[:2])+'.'+fmt) if plot==0: pmagplotlib.drawFIGS(PLTS) ans= raw_input('S[a]ve all figures, <Return> to quit ') if ans!='a': print "Good bye" sys.exit() pmagplotlib.saveP(PLTS,files)
def main(): """ NAME thellier_magic.py DESCRIPTION plots Thellier-Thellier, allowing interactive setting of bounds and customizing of selection criteria. Saves and reads interpretations from a pmag_specimen formatted table, default: thellier_specimens.txt SYNTAX thellier_magic.py [command line options] OPTIONS -h prints help message and quits -f MEAS, set magic_measurements input file -fsp PRIOR, set pmag_specimen prior interpretations file -fan ANIS, set rmag_anisotropy file for doing the anisotropy corrections -fcr CRIT, set criteria file for grading. -fmt [svg,png,jpg], format for images - default is svg -sav, saves plots with out review (default format) -spc SPEC, plots single specimen SPEC, saves plot with specified format with optional -b bounds adn quits -b BEG END: sets bounds for calculation BEG: starting step for slope calculation END: ending step for slope calculation -z use only z component difference for pTRM calculation DEFAULTS MEAS: magic_measurements.txt REDO: thellier_redo CRIT: NONE PRIOR: NONE OUTPUT figures: ALL: numbers refer to temperature steps in command line window 1) Arai plot: closed circles are zero-field first/infield open circles are infield first/zero-field triangles are pTRM checks squares are pTRM tail checks VDS is vector difference sum diamonds are bounds for interpretation 2) Zijderveld plot: closed (open) symbols are X-Y (X-Z) planes X rotated to NRM direction 3) (De/Re)Magnetization diagram: circles are NRM remaining squares are pTRM gained 4) equal area projections: green triangles are pTRM gained direction red (purple) circles are lower(upper) hemisphere of ZI step directions blue (cyan) squares are lower(upper) hemisphere IZ step directions 5) Optional: TRM acquisition 6) Optional: TDS normalization command line window: list is: temperature step numbers, temperatures (C), Dec, Inc, Int (units of magic_measuements) list of possible commands: type letter followed by return to select option saving of plots creates .svg format files with specimen_name, plot type as name """ # # initializations # meas_file,critout,inspec="magic_measurements.txt","","thellier_specimens.txt" first=1 inlt=0 version_num=pmag.get_version() TDinit,Tinit,field,first_save=0,0,-1,1 user,comment,AniSpec,locname="",'',"","" ans,specimen,recnum,start,end=0,0,0,0,0 plots,pmag_out,samp_file,style=0,"","","svg" verbose=pmagplotlib.verbose fmt='.'+style # # default acceptance criteria # accept=pmag.default_criteria(0)[0] # set the default criteria # # parse command line options # Zdiff,anis=0,0 spc,BEG,END="","","" if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind=sys.argv.index('-f') meas_file=sys.argv[ind+1] if '-fsp' in sys.argv: ind=sys.argv.index('-fsp') inspec=sys.argv[ind+1] if '-fan' in sys.argv: ind=sys.argv.index('-fan') anisfile=sys.argv[ind+1] anis=1 anis_data,file_type=pmag.magic_read(anisfile) if verbose: print "Anisotropy data read in from ", anisfile if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt='.'+sys.argv[ind+1] if '-dpi' in sys.argv: ind=sys.argv.index('-dpi') dpi='.'+sys.argv[ind+1] else: dpi=100 if '-sav' in sys.argv: plots=1 verbose=0 if '-z' in sys.argv: Zdiff=1 if '-spc' in sys.argv: ind=sys.argv.index('-spc') spc=sys.argv[ind+1] if '-b' in sys.argv: ind=sys.argv.index('-b') BEG=int(sys.argv[ind+1]) END=int(sys.argv[ind+2]) if '-fcr' in sys.argv: ind=sys.argv.index('-fcr') critout=sys.argv[ind+1] crit_data,file_type=pmag.magic_read(critout) if file_type!='pmag_criteria': if verbose: print 'bad pmag_criteria file, using no acceptance criteria' accept=pmag.default_criteria(1)[0] else: if verbose: print "Acceptance criteria read in from ", critout accept={'pmag_criteria_code':'ACCEPTANCE','er_citation_names':'This study'} for critrec in crit_data: if 'sample_int_sigma_uT' in critrec.keys(): # accommodate Shaar's new criterion critrec['sample_int_sigma']='%10.3e'%(eval(critrec['sample_int_sigma_uT'])*1e-6) for key in critrec.keys(): if key not in accept.keys() and critrec[key]!='': accept[key]=critrec[key] try: open(inspec,'rU') PriorRecs,file_type=pmag.magic_read(inspec) if file_type != 'pmag_specimens': print file_type print file_type,inspec," is not a valid pmag_specimens file " sys.exit() for rec in PriorRecs: if 'magic_software_packages' not in rec.keys():rec['magic_software_packages']="" except IOError: PriorRecs=[] if verbose:print "starting new specimen interpretation file: ",inspec meas_data,file_type=pmag.magic_read(meas_file) if file_type != 'magic_measurements': print file_type print file_type,"This is not a valid magic_measurements file " sys.exit() backup=0 # define figure numbers for arai, zijderveld and # de-,re-magization diagrams AZD={} AZD['deremag'], AZD['zijd'],AZD['arai'],AZD['eqarea']=1,2,3,4 pmagplotlib.plot_init(AZD['arai'],5,5) pmagplotlib.plot_init(AZD['zijd'],5,5) pmagplotlib.plot_init(AZD['deremag'],5,5) pmagplotlib.plot_init(AZD['eqarea'],5,5) # # # # get list of unique specimen names # CurrRec=[] sids=pmag.get_specs(meas_data) # get plots for specimen s - default is just to step through arai diagrams # if spc!="": specimen =sids.index(spc) while specimen < len(sids): methcodes=[] if verbose: print sids[specimen],specimen+1, 'of ', len(sids) MeasRecs=[] s=sids[specimen] datablock,trmblock,tdsrecs=[],[],[] PmagSpecRec={} if first==0: for key in keys:PmagSpecRec[key]="" # make sure all new records have same set of keys PmagSpecRec["er_analyst_mail_names"]=user PmagSpecRec["specimen_correction"]='u' # # find the data from the meas_data file for this specimen # for rec in meas_data: if rec["er_specimen_name"]==s: MeasRecs.append(rec) if "magic_method_codes" not in rec.keys(): rec["magic_method_codes"]="" methods=rec["magic_method_codes"].split(":") meths=[] for meth in methods: meths.append(meth.strip()) # take off annoying spaces methods="" for meth in meths: if meth.strip() not in methcodes and "LP-" in meth:methcodes.append(meth.strip()) methods=methods+meth+":" methods=methods[:-1] rec["magic_method_codes"]=methods if "LP-PI-TRM" in meths: datablock.append(rec) if "LP-TRM" in meths: trmblock.append(rec) if "LP-TRM-TD" in meths: tdsrecs.append(rec) if len(trmblock)>2 and inspec!="": if Tinit==0: Tinit=1 AZD['TRM']=5 pmagplotlib.plot_init(AZD['TRM'],5,5) elif Tinit==1: # clear the TRM figure if not needed pmagplotlib.clearFIG(AZD['TRM']) if len(tdsrecs)>2: if TDinit==0: TDinit=1 AZD['TDS']=6 pmagplotlib.plot_init(AZD['TDS'],5,5) elif TDinit==1: # clear the TDS figure if not needed pmagplotlib.clearFIG(AZD['TDS']) if len(datablock) <4: if backup==0: specimen+=1 if verbose: print 'skipping specimen - moving forward ', s else: specimen-=1 if verbose: print 'skipping specimen - moving backward ', s # # collect info for the PmagSpecRec dictionary # else: rec=datablock[0] PmagSpecRec["er_citation_names"]="This study" PmagSpecRec["er_specimen_name"]=s PmagSpecRec["er_sample_name"]=rec["er_sample_name"] PmagSpecRec["er_site_name"]=rec["er_site_name"] PmagSpecRec["er_location_name"]=rec["er_location_name"] locname=rec['er_location_name'].replace('/','-') if "er_expedition_name" in rec.keys():PmagSpecRec["er_expedition_name"]=rec["er_expedition_name"] if "magic_instrument_codes" not in rec.keys():rec["magic_instrument_codes"]="" PmagSpecRec["magic_instrument_codes"]=rec["magic_instrument_codes"] PmagSpecRec["measurement_step_unit"]="K" if "magic_experiment_name" not in rec.keys(): rec["magic_experiment_name"]="" else: PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"] meths=rec["magic_method_codes"].split() # sort data into types araiblock,field=pmag.sortarai(datablock,s,Zdiff) first_Z=araiblock[0] GammaChecks=araiblock[5] if len(first_Z)<3: if backup==0: specimen+=1 if verbose: print 'skipping specimen - moving forward ', s else: specimen-=1 if verbose: print 'skipping specimen - moving backward ', s else: backup=0 zijdblock,units=pmag.find_dmag_rec(s,meas_data) recnum=0 if verbose: print "index step Dec Inc Int Gamma" for plotrec in zijdblock: if GammaChecks!="": gamma="" for g in GammaChecks: if g[0]==plotrec[0]-273: gamma=g[1] break if gamma!="": print '%i %i %7.1f %7.1f %8.3e %7.1f' % (recnum,plotrec[0]-273,plotrec[1],plotrec[2],plotrec[3],gamma) else: print '%i %i %7.1f %7.1f %8.3e ' % (recnum,plotrec[0]-273,plotrec[1],plotrec[2],plotrec[3]) recnum += 1 pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0]) if verbose:pmagplotlib.drawFIGS(AZD) if len(tdsrecs)>2: # a TDS experiment tdsblock=[] # make a list for the TDS data Mkeys=['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measuruement_magn_mass'] mkey,k="",0 while mkey=="" and k<len(Mkeys)-1: # find which type of intensity key= Mkeys[k] if key in tdsrecs[0].keys() and tdsrecs[0][key]!="": mkey=key k+=1 if mkey=="":break # get outta here Tnorm="" for tdrec in tdsrecs: meths=tdrec['magic_method_codes'].split(":") for meth in meths: meth.replace(" ","") # strip off potential nasty spaces if 'LT-T-I' in meths and Tnorm=="": # found first total TRM Tnorm=float(tdrec[mkey]) # normalize by total TRM tdsblock.append([273,zijdblock[0][3]/Tnorm,1.]) # put in the zero step if 'LT-T-Z' in meths and Tnorm!="": # found a LP-TRM-TD demag step, now need complementary LT-T-Z from zijdblock step=float(tdrec['treatment_temp']) Tint="" if mkey!="": Tint=float(tdrec[mkey]) if Tint!="": for zrec in zijdblock: if zrec[0]==step: # found matching tdsblock.append([step,zrec[3]/Tnorm,Tint/Tnorm]) break if len(tdsblock)>2: pmagplotlib.plotTDS(AZD['TDS'],tdsblock,s+':LP-PI-TDS:') if verbose:pmagplotlib(drawFIGS(AZD)) else: print "Something wrong here" if anis==1: # look up anisotropy data for this specimen AniSpec="" for aspec in anis_data: if aspec["er_specimen_name"]==PmagSpecRec["er_specimen_name"]: AniSpec=aspec if verbose: print 'Found anisotropy record...' break if inspec !="": if verbose: print 'Looking up saved interpretation....' found = 0 for k in range(len(PriorRecs)): try: if PriorRecs[k]["er_specimen_name"]==s: found =1 CurrRec.append(PriorRecs[k]) for j in range(len(zijdblock)): if float(zijdblock[j][0])==float(PriorRecs[k]["measurement_step_min"]):start=j if float(zijdblock[j][0])==float(PriorRecs[k]["measurement_step_max"]):end=j pars,errcode=pmag.PintPars(datablock,araiblock,zijdblock,start,end,accept) pars['measurement_step_unit']="K" pars['experiment_type']='LP-PI-TRM' del PriorRecs[k] # put in CurrRec, take out of PriorRecs if errcode!=1: pars["specimen_lab_field_dc"]=field pars["specimen_int"]=-1*field*pars["specimen_b"] pars["er_specimen_name"]=s if verbose: print 'Saved interpretation: ' pars,kill=pmag.scoreit(pars,PmagSpecRec,accept,'',verbose) pmagplotlib.plotB(AZD,araiblock,zijdblock,pars) if verbose:pmagplotlib.drawFIGS(AZD) if len(trmblock)>2: blab=field best=pars["specimen_int"] Bs,TRMs=[],[] for trec in trmblock: Bs.append(float(trec['treatment_dc_field'])) TRMs.append(float(trec['measurement_magn_moment'])) NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc Mp,Bp=[],[] for k in range(int(max(Bs)*1e6)): Bp.append(float(k)*1e-6) npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM(AZD['TRM'],Bs,TRMs,Bp,Mp,NLpars,trec['magic_experiment_name']) PmagSpecRec['specimen_int']=NLpars['banc'] if verbose: print 'Banc= ',float(NLpars['banc'])*1e6 pmagplotlib.drawFIGS(AZD) mpars=pmag.domean(araiblock[1],start,end,'DE-BFL') if verbose: print 'pTRM direction= ','%7.1f'%(mpars['specimen_dec']),' %7.1f'%(mpars['specimen_inc']),' MAD:','%7.1f'%(mpars['specimen_mad']) if AniSpec!="": CpTRM=pmag.Dir_anis_corr([mpars['specimen_dec'],mpars['specimen_inc']],AniSpec) AniSpecRec=pmag.doaniscorr(PmagSpecRec,AniSpec) if verbose: print 'Anisotropy corrected TRM direction= ','%7.1f'%(CpTRM[0]),' %7.1f'%(CpTRM[1]) print 'Anisotropy corrected intensity= ',float(AniSpecRec['specimen_int'])*1e6 else: print 'error on specimen ',s except: pass if verbose and found==0: print ' None found :( ' if spc!="": if BEG!="": pars,errcode=pmag.PintPars(datablock,araiblock,zijdblock,BEG,END,accept) pars['measurement_step_unit']="K" pars["specimen_lab_field_dc"]=field pars["specimen_int"]=-1*field*pars["specimen_b"] pars["er_specimen_name"]=s pars['specimen_grade']='' # ungraded pmagplotlib.plotB(AZD,araiblock,zijdblock,pars) if verbose:pmagplotlib.drawFIGS(AZD) if len(trmblock)>2: if inlt==0: inlt=1 blab=field best=pars["specimen_int"] Bs,TRMs=[],[] for trec in trmblock: Bs.append(float(trec['treatment_dc_field'])) TRMs.append(float(trec['measurement_magn_moment'])) NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc # Mp,Bp=[],[] for k in range(int(max(Bs)*1e6)): Bp.append(float(k)*1e-6) npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field files={} for key in AZD.keys(): files[key]=s+'_'+key+fmt pmagplotlib.saveP(AZD,files,dpi=dpi) sys.exit() if verbose: ans='b' while ans != "": print """ s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit: """ ans=raw_input('Return for next specimen \n') if ans=="": specimen +=1 if ans=="d": save_redo(PriorRecs,inspec) CurrRec=[] pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0]) if verbose:pmagplotlib.drawFIGS(AZD) if ans=='a': files={} for key in AZD.keys(): files[key]="LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name']+'_SA:_'+PmagSpecRec['er_sample_name']+'_SP:_'+s+'_CO:_s_TY:_'+key+fmt pmagplotlib.saveP(AZD,files) ans="" if ans=='q': print "Good bye" sys.exit() if ans=='p': specimen =specimen -1 backup = 1 ans="" if ans=='s': keepon=1 spec=raw_input('Enter desired specimen name (or first part there of): ') while keepon==1: try: specimen =sids.index(spec) keepon=0 except: tmplist=[] for qq in range(len(sids)): if spec in sids[qq]:tmplist.append(sids[qq]) print specimen," not found, but this was: " print tmplist spec=raw_input('Select one or try again\n ') ans="" if ans=='b': if end==0 or end >=len(zijdblock):end=len(zijdblock)-1 GoOn=0 while GoOn==0: answer=raw_input('Enter index of first point for calculation: ['+str(start)+'] ') try: start=int(answer) answer=raw_input('Enter index of last point for calculation: ['+str(end)+'] ') end=int(answer) if start >=0 and start <len(zijdblock)-2 and end >0 and end <len(zijdblock) or start>=end: GoOn=1 else: print "Bad endpoints - try again! " start,end=0,len(zijdblock) except ValueError: print "Bad endpoints - try again! " start,end=0,len(zijdblock) s=sids[specimen] pars,errcode=pmag.PintPars(datablock,araiblock,zijdblock,start,end,accept) pars['measurement_step_unit']="K" pars["specimen_lab_field_dc"]=field pars["specimen_int"]=-1*field*pars["specimen_b"] pars["er_specimen_name"]=s pars,kill=pmag.scoreit(pars,PmagSpecRec,accept,'',0) PmagSpecRec['specimen_scat']=pars['specimen_scat'] PmagSpecRec['specimen_frac']='%5.3f'%(pars['specimen_frac']) PmagSpecRec['specimen_gmax']='%5.3f'%(pars['specimen_gmax']) PmagSpecRec["measurement_step_min"]='%8.3e' % (pars["measurement_step_min"]) PmagSpecRec["measurement_step_max"]='%8.3e' % (pars["measurement_step_max"]) PmagSpecRec["measurement_step_unit"]="K" PmagSpecRec["specimen_int_n"]='%i'%(pars["specimen_int_n"]) PmagSpecRec["specimen_lab_field_dc"]='%8.3e'%(pars["specimen_lab_field_dc"]) PmagSpecRec["specimen_int"]='%9.4e '%(pars["specimen_int"]) PmagSpecRec["specimen_b"]='%5.3f '%(pars["specimen_b"]) PmagSpecRec["specimen_q"]='%5.1f '%(pars["specimen_q"]) PmagSpecRec["specimen_f"]='%5.3f '%(pars["specimen_f"]) PmagSpecRec["specimen_fvds"]='%5.3f'%(pars["specimen_fvds"]) PmagSpecRec["specimen_b_beta"]='%5.3f'%(pars["specimen_b_beta"]) PmagSpecRec["specimen_int_mad"]='%7.1f'%(pars["specimen_int_mad"]) PmagSpecRec["specimen_Z"]='%7.1f'%(pars["specimen_Z"]) PmagSpecRec["specimen_gamma"]='%7.1f'%(pars["specimen_gamma"]) PmagSpecRec["specimen_grade"]=pars["specimen_grade"] if pars["method_codes"]!="": tmpcodes=pars["method_codes"].split(":") for t in tmpcodes: if t.strip() not in methcodes:methcodes.append(t.strip()) PmagSpecRec["specimen_dec"]='%7.1f'%(pars["specimen_dec"]) PmagSpecRec["specimen_inc"]='%7.1f'%(pars["specimen_inc"]) PmagSpecRec["specimen_tilt_correction"]='-1' PmagSpecRec["specimen_direction_type"]='l' PmagSpecRec["direction_type"]='l' # this is redundant, but helpful - won't be imported PmagSpecRec["specimen_int_dang"]='%7.1f '%(pars["specimen_int_dang"]) PmagSpecRec["specimen_drats"]='%7.1f '%(pars["specimen_drats"]) PmagSpecRec["specimen_drat"]='%7.1f '%(pars["specimen_drat"]) PmagSpecRec["specimen_int_ptrm_n"]='%i '%(pars["specimen_int_ptrm_n"]) PmagSpecRec["specimen_rsc"]='%6.4f '%(pars["specimen_rsc"]) PmagSpecRec["specimen_md"]='%i '%(int(pars["specimen_md"])) if PmagSpecRec["specimen_md"]=='-1':PmagSpecRec["specimen_md"]="" PmagSpecRec["specimen_b_sigma"]='%5.3f '%(pars["specimen_b_sigma"]) if "IE-TT" not in methcodes:methcodes.append("IE-TT") methods="" for meth in methcodes: methods=methods+meth+":" PmagSpecRec["magic_method_codes"]=methods[:-1] PmagSpecRec["specimen_description"]=comment PmagSpecRec["magic_software_packages"]=version_num pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0]) pmagplotlib.plotB(AZD,araiblock,zijdblock,pars) if verbose:pmagplotlib.drawFIGS(AZD) if len(trmblock)>2: blab=field best=pars["specimen_int"] Bs,TRMs=[],[] for trec in trmblock: Bs.append(float(trec['treatment_dc_field'])) TRMs.append(float(trec['measurement_magn_moment'])) NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc Mp,Bp=[],[] for k in range(int(max(Bs)*1e6)): Bp.append(float(k)*1e-6) npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM(AZD['TRM'],Bs,TRMs,Bp,Mp,NLpars,trec['magic_experiment_name']) if verbose: print 'Non-linear TRM corrected intensity= ',float(NLpars['banc'])*1e6 if verbose:pmagplotlib.drawFIGS(AZD) pars["specimen_lab_field_dc"]=field pars["specimen_int"]=-1*field*pars["specimen_b"] pars,kill=pmag.scoreit(pars,PmagSpecRec,accept,'',verbose) saveit=raw_input("Save this interpretation? [y]/n \n") if saveit!='n': PriorRecs.append(PmagSpecRec) # put back an interpretation specimen+=1 save_redo(PriorRecs,inspec) ans="" elif plots==1: specimen+=1 if fmt != ".pmag": files={} for key in AZD.keys(): files[key]="LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name']+'_SA:_'+PmagSpecRec['er_sample_name']+'_SP:_'+s+'_CO:_s_TY:_'+key+'_'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['deremag']='DeReMag Plot' titles['zijd']='Zijderveld Plot' titles['arai']='Arai Plot' AZD = pmagplotlib.addBorders(AZD,titles,black,purple) pmagplotlib.saveP(AZD,files,dpi=dpi) # pmagplotlib.combineFigs(s,files,3) else: # save in pmag format script="grep "+s+" output.mag | thellier -mfsi" script=script+' %8.4e'%(field) min='%i'%((pars["measurement_step_min"]-273)) Max='%i'%((pars["measurement_step_max"]-273)) script=script+" "+min+" "+Max script=script+" |plotxy;cat mypost >>thellier.ps\n" pltf.write(script) pmag.domagicmag(outf,MeasRecs) if len(CurrRec)>0: for rec in CurrRec: PriorRecs.append(rec) CurrRec=[] if plots!=1 and verbose: ans=raw_input(" Save last plot? 1/[0] ") if ans=="1": if fmt != ".pmag": files={} for key in AZD.keys(): files[key]=s+'_'+key+fmt pmagplotlib.saveP(AZD,files,dpi=dpi) else: print "\n Good bye\n" sys.exit() if len(CurrRec)>0:PriorRecs.append(CurrRec) # put back an interpretation if len(PriorRecs)>0: save_redo(PriorRecs,inspec) print 'Updated interpretations saved in ',inspec if verbose: print "Good bye"
def main(): """ NAME zeq_magic.py DESCRIPTION reads in magic_measurements formatted file, makes plots of remanence decay during demagnetization experiments. Reads in prior interpretations saved in a pmag_specimens formatted file [and allows re-interpretations of best-fit lines and planes and saves (revised or new) interpretations in a pmag_specimens file. interpretations are saved in the coordinate system used. Also allows judicious editting of measurements to eliminate "bad" measurements. These are marked as such in the magic_measurements input file. they are NOT deleted, just ignored. ] Bracketed part not yet implemented SYNTAX zeq_magic.py [command line options] OPTIONS -h prints help message and quits -f MEASFILE: sets measurements format input file, default: measurements.txt -fsp SPECFILE: sets specimens format file with prior interpreations, default: specimens.txt -fsa SAMPFILE: sets samples format file sample=>site information, default: samples.txt -fsi SITEFILE: sets sites format file with site=>location informationprior interpreations, default: samples.txt -Fp PLTFILE: sets filename for saved plot, default is name_type.fmt (where type is zijd, eqarea or decay curve) -crd [s,g,t]: sets coordinate system, g=geographic, t=tilt adjusted, default: specimen coordinate system -spc SPEC plots single specimen SPEC, saves plot with specified format with optional -dir settings and quits -dir [L,P,F][beg][end]: sets calculation type for principal component analysis, default is none beg: starting step for PCA calculation end: ending step for PCA calculation [L,P,F]: calculation type for line, plane or fisher mean must be used with -spc option -fmt FMT: set format of saved plot [png,svg,jpg] -A: suppresses averaging of replicate measurements, default is to average -sav: saves all plots without review SCREEN OUTPUT: Specimen, N, a95, StepMin, StepMax, Dec, Inc, calculation type """ # initialize some variables doave, e, b = 1, 0, 0 # average replicates, initial end and beginning step intlist = ['magn_moment', 'magn_volume', 'magn_mass', 'magnitude'] plots, coord = 0, 's' noorient = 0 version_num = pmag.get_version() verbose = pmagplotlib.verbose calculation_type, fmt = "", "svg" user, spec_keys, locname = "", [], '' geo, tilt, ask = 0, 0, 0 PriorRecs = [] # empty list for prior interpretations backup = 0 specimen = "" # can skip everything and just plot one specimen with bounds e,b if '-h' in sys.argv: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg_from_sys("-WD", default_val=os.getcwd()) meas_file = pmag.get_named_arg_from_sys("-f", default_val="measurements.txt") 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") #meas_file = os.path.join(dir_path, meas_file) #spec_file = os.path.join(dir_path, spec_file) #samp_file = os.path.join(dir_path, samp_file) #site_file = os.path.join(dir_path, site_file) plot_file = pmag.get_named_arg_from_sys("-Fp", default_val="") crd = pmag.get_named_arg_from_sys("-crd", default_val="s") if crd == "s": coord = "-1" elif crd == "t": coord = "100" else: coord = "0" fmt = pmag.get_named_arg_from_sys("-fmt", "svg") specimen = pmag.get_named_arg_from_sys("-spc", default_val="") beg_pca, end_pca = "", "" if '-dir' in sys.argv: ind = sys.argv.index('-dir') direction_type = sys.argv[ind + 1] beg_pca = int(sys.argv[ind + 2]) end_pca = int(sys.argv[ind + 3]) if direction_type == 'L': calculation_type = 'DE-BFL' if direction_type == 'P': calculation_type = 'DE-BFP' if direction_type == 'F': calculation_type = 'DE-FM' if '-A' in sys.argv: doave = 0 if '-sav' in sys.argv: plots, verbose = 1, 0 # first_save = 1 fnames = { 'measurements': meas_file, 'specimens': spec_file, 'samples': samp_file, 'sites': site_file } contribution = nb.Contribution( dir_path, custom_filenames=fnames, read_tables=['measurements', 'specimens', 'samples', 'sites']) # # import specimens specimen_cols = [ 'analysts', 'aniso_ftest', 'aniso_ftest12', 'aniso_ftest23', 'aniso_s', 'aniso_s_mean', 'aniso_s_n_measurements', 'aniso_s_sigma', 'aniso_s_unit', 'aniso_tilt_correction', 'aniso_type', 'aniso_v1', 'aniso_v2', 'aniso_v3', 'citations', 'description', 'dir_alpha95', 'dir_comp', 'dir_dec', 'dir_inc', 'dir_mad_free', 'dir_n_measurements', 'dir_tilt_correction', 'experiments', 'geologic_classes', 'geologic_types', 'hyst_bc', 'hyst_bcr', 'hyst_mr_moment', 'hyst_ms_moment', 'int_abs', 'int_b', 'int_b_beta', 'int_b_sigma', 'int_corr', 'int_dang', 'int_drats', 'int_f', 'int_fvds', 'int_gamma', 'int_mad_free', 'int_md', 'int_n_measurements', 'int_n_ptrm', 'int_q', 'int_rsc', 'int_treat_dc_field', 'lithologies', 'meas_step_max', 'meas_step_min', 'meas_step_unit', 'method_codes', 'sample', 'software_packages', 'specimen' ] if 'specimens' in contribution.tables: # contribution.propagate_name_down('sample','measurements') spec_container = contribution.tables['specimens'] prior_spec_data = spec_container.get_records_for_code( 'LP-DIR', strict_match=False ) # look up all prior directional interpretations # # tie sample names to measurement data # else: spec_container, prior_spec_data = None, [] # # import samples for orientation info # if 'samples' in contribution.tables: # contribution.propagate_name_down('site','measurements') contribution.propagate_cols( col_names=['azimuth', 'dip', 'orientation_flag'], target_df_name='measurements', source_df_name='samples') # # define figure numbers for equal area, zijderveld, # and intensity vs. demagnetiztion step respectively # ZED = {} ZED['eqarea'], ZED['zijd'], ZED['demag'] = 1, 2, 3 pmagplotlib.plot_init(ZED['eqarea'], 6, 6) pmagplotlib.plot_init(ZED['zijd'], 6, 6) pmagplotlib.plot_init(ZED['demag'], 6, 6) # save_pca=0 angle, direction_type, setangle = "", "", 0 # create measurement dataframe # meas_container = contribution.tables['measurements'] meas_data = meas_container.df # meas_data = meas_data[meas_data['method_codes'].str.contains( 'LT-NO|LT-AF-Z|LT-T-Z|LT-M-Z') == True] # fish out steps for plotting meas_data = meas_data[meas_data['method_codes'].str.contains( 'AN|ARM|LP-TRM|LP-PI-ARM') == False] # strip out unwanted experiments intensity_types = [ col_name for col_name in meas_data.columns if col_name in intlist ] # plot first intensity method found - normalized to initial value anyway - # doesn't matter which used int_key = intensity_types[0] # get all the non-null intensity records of the same type meas_data = meas_data[meas_data[int_key].notnull()] if 'flag' not in meas_data.columns: meas_data['flag'] = 'g' # set the default flag to good # need to treat LP-NO specially for af data, treatment should be zero, # otherwise 273. meas_data['treatment'] = meas_data['treat_ac_field'].where( cond=meas_data['treat_ac_field'] != '0', other=meas_data['treat_temp']) meas_data['ZI'] = 1 # initialize these to one meas_data['instrument_codes'] = "" # initialize these to blank # for unusual case of microwave power.... if 'treat_mw_power' in meas_data.columns: meas_data.loc[ meas_data.treat_mw_power != 0, 'treatment'] = meas_data.treat_mw_power * meas_data.treat_mw_time # # get list of unique specimen names from measurement data # # this is a list of all the specimen names specimen_names = meas_data.specimen.unique() specimen_names = specimen_names.tolist() specimen_names.sort() # # set up new DataFrame for this sessions specimen interpretations # data_container = nb.MagicDataFrame(dtype='specimens', columns=specimen_cols) # this is for interpretations from this session current_spec_data = data_container.df locname = 'LookItUp' if specimen == "": k = 0 else: k = specimen_names.index(specimen) # let's look at the data now while k < len(specimen_names): # set the current specimen for plotting this_specimen = specimen_names[k] if verbose and this_specimen != "": print(this_specimen, k + 1, 'out of ', len(specimen_names)) if setangle == 0: angle = "" this_specimen_measurements = meas_data[ meas_data['specimen'].str.contains( this_specimen) == True] # fish out this specimen this_specimen_measurements = this_specimen_measurements[ this_specimen_measurements['flag'].str.contains( 'g') == True] # fish out this specimen if len(this_specimen_measurements) != 0: # if there are measurements # # set up datablock [[treatment,dec, inc, int, direction_type],[....]] # # # figure out the method codes # units, methods, title = "", "", this_specimen # this is a list of all the specimen method codes` meas_meths = this_specimen_measurements.method_codes.unique() tr = pd.to_numeric(this_specimen_measurements.treatment).tolist() if set(tr) == set([0]): k += 1 continue for m in meas_meths: if 'LT-AF-Z' in m: units = 'T' # units include tesla tr[0] = 0 if 'LT-T-Z' in m: units = units + ":K" # units include kelvin if 'LT-M-Z' in m: units = units + ':J' # units include joules tr[0] = 0 units = units.strip(':') # strip off extra colons if 'LP-' in m: methods = methods + ":" + m decs = pd.to_numeric(this_specimen_measurements.dir_dec).tolist() incs = pd.to_numeric(this_specimen_measurements.dir_inc).tolist() # # fix the coordinate system # if coord != '-1': # need to transform coordinates to geographic azimuths = pd.to_numeric(this_specimen_measurements.azimuth ).tolist() # get the azimuths # get the azimuths dips = pd.to_numeric(this_specimen_measurements.dip).tolist() dirs = [decs, incs, azimuths, dips] # this transposes the columns and rows of the list of lists dirs_geo = np.array(list(map(list, list(zip(*dirs))))) decs, incs = pmag.dogeo_V(dirs_geo) if coord == '100': # need to do tilt correction too bed_dip_dirs = pd.to_numeric( this_specimen_measurements.bed_dip_dir).tolist( ) # get the azimuths bed_dips = pd.to_numeric(this_specimen_measurements.bed_dip ).tolist() # get the azimuths dirs = [decs, incs, bed_dip_dirs, bed_dips] # this transposes the columns and rows of the list of lists dirs_tilt = np.array(list(map(list, list(zip(*dirs))))) decs, incs = pmag.dotilt_V(dirs_tilt) title = title + '_t' else: title = title + '_g' if angle == "": angle = decs[0] ints = pd.to_numeric(this_specimen_measurements[int_key]).tolist() ZI = this_specimen_measurements.ZI.tolist() flags = this_specimen_measurements.flag.tolist() codes = this_specimen_measurements.instrument_codes.tolist() datalist = [tr, decs, incs, ints, ZI, flags, codes] # this transposes the columns and rows of the list of lists datablock = list(map(list, list(zip(*datalist)))) pmagplotlib.plotZED(ZED, datablock, angle, title, units) if verbose: pmagplotlib.drawFIGS(ZED) # # collect info for current_specimen_interpretation dictionary # if beg_pca == "" and len(prior_spec_data) != 0: # # find prior interpretation # prior_specimen_interpretations = prior_spec_data[ prior_spec_data['specimen'].str.contains( this_specimen) == True] beg_pcas = pd.to_numeric(prior_specimen_interpretations. meas_step_min.values).tolist() end_pcas = pd.to_numeric(prior_specimen_interpretations. meas_step_max.values).tolist() spec_methods = prior_specimen_interpretations.method_codes.tolist( ) # step through all prior interpretations and plot them for ind in range(len(beg_pcas)): spec_meths = spec_methods[ind].split(':') for m in spec_meths: if 'DE-BFL' in m: calculation_type = 'DE-BFL' # best fit line if 'DE-BFP' in m: calculation_type = 'DE-BFP' # best fit plane if 'DE-FM' in m: calculation_type = 'DE-FM' # fisher mean if 'DE-BFL-A' in m: calculation_type = 'DE-BFL-A' # anchored best fit line start, end = tr.index(beg_pcas[ind]), tr.index( end_pcas[ind] ) # getting the starting and ending points # calculate direction/plane mpars = pmag.domean(datablock, start, end, calculation_type) if mpars["specimen_direction_type"] != "Error": # put it on the plot pmagplotlib.plotDir(ZED, mpars, datablock, angle) if verbose: pmagplotlib.drawFIGS(ZED) else: start, end = int(beg_pca), int(end_pca) # calculate direction/plane mpars = pmag.domean(datablock, start, end, calculation_type) if mpars["specimen_direction_type"] != "Error": # put it on the plot pmagplotlib.plotDir(ZED, mpars, datablock, angle) if verbose: pmagplotlib.drawFIGS(ZED) if plots == 1 or specimen != "": if plot_file == "": basename = title else: basename = plot_file files = {} for key in list(ZED.keys()): files[key] = basename + '_' + key + '.' + fmt pmagplotlib.saveP(ZED, files) if specimen != "": sys.exit() if verbose: recnum = 0 for plotrec in datablock: if units == 'T': print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum, plotrec[0] * 1e3, " mT", plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if units == "K": print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum, plotrec[0] - 273, ' C', plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if units == "J": print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum, plotrec[0], ' J', plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if 'K' in units and 'T' in units: if plotrec[0] >= 1.: print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum, plotrec[0] - 273, ' C', plotrec[3], plotrec[1], plotrec[2], plotrec[6])) if plotrec[0] < 1.: print('%s: %i %7.1f %s %8.3e %7.1f %7.1f %s' % (plotrec[5], recnum, plotrec[0] * 1e3, " mT", plotrec[3], plotrec[1], plotrec[2], plotrec[6])) recnum += 1 # we have a current interpretation elif mpars["specimen_direction_type"] != "Error": # # create a new specimen record for the interpreation for this # specimen this_specimen_interpretation = { col: "" for col in specimen_cols } # this_specimen_interpretation["analysts"]=user this_specimen_interpretation['software_packages'] = version_num this_specimen_interpretation['specimen'] = this_specimen this_specimen_interpretation["method_codes"] = calculation_type this_specimen_interpretation["meas_step_unit"] = units this_specimen_interpretation["meas_step_min"] = tr[start] this_specimen_interpretation["meas_step_max"] = tr[end] this_specimen_interpretation["dir_dec"] = '%7.1f' % ( mpars['specimen_dec']) this_specimen_interpretation["dir_inc"] = '%7.1f' % ( mpars['specimen_inc']) this_specimen_interpretation["dir_dang"] = '%7.1f' % ( mpars['specimen_dang']) this_specimen_interpretation["dir_n_measurements"] = '%i' % ( mpars['specimen_n']) this_specimen_interpretation["dir_tilt_correction"] = coord methods = methods.replace(" ", "") if "T" in units: methods = methods + ":LP-DIR-AF" if "K" in units: methods = methods + ":LP-DIR-T" if "J" in units: methods = methods + ":LP-DIR-M" this_specimen_interpretation["method_codes"] = methods.strip( ':') this_specimen_interpretation[ "experiments"] = this_specimen_measurements.experiment.unique( )[0] # # print some stuff # if calculation_type != 'DE-FM': this_specimen_interpretation["dir_mad_free"] = '%7.1f' % ( mpars['specimen_mad']) this_specimen_interpretation["dir_alpha95"] = '' if verbose: if units == 'K': print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_mad_free"]), float( this_specimen_interpretation["dir_dang"]), float(this_specimen_interpretation[ "meas_step_min"]) - 273, float(this_specimen_interpretation[ "meas_step_max"]) - 273, float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) elif units == 'T': print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_mad_free"]), float( this_specimen_interpretation["dir_dang"]), float(this_specimen_interpretation[ "meas_step_min"]) * 1e3, float(this_specimen_interpretation[ "meas_step_max"]) * 1e3, float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) elif 'T' in units and 'K' in units: if float(this_specimen_interpretation[ 'meas_step_min']) < 1.0: min = float(this_specimen_interpretation[ 'meas_step_min']) * 1e3 else: min = float(this_specimen_interpretation[ 'meas_step_min']) - 273 if float(this_specimen_interpretation[ 'meas_step_max']) < 1.0: max = float(this_specimen_interpretation[ 'meas_step_max']) * 1e3 else: max = float(this_specimen_interpretation[ 'meas_step_max']) - 273 print( '%s %i %7.1f %i %i %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_mad_free"]), float( this_specimen_interpretation["dir_dang"]), min, max, float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) else: print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_mad_free"]), float( this_specimen_interpretation["dir_dang"]), float(this_specimen_interpretation[ "meas_step_min"]), float(this_specimen_interpretation[ "meas_step_max"]), float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) else: this_specimen_interpretation["dir_alpha95"] = '%7.1f' % ( mpars['specimen_alpha95']) this_specimen_interpretation["dir_mad_free"] = '' if verbose: if 'K' in units: print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurments"]), float(this_specimen_interpretation[ "dir_mad_free"]), float( this_specimen_interpretation["dir_dang"]), float(this_specimen_interpretation[ "meas_step_min"]) - 273, float(this_specimen_interpretation[ "meas_step_max"]) - 273, float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) elif 'T' in units: print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_alpha95"]), float( this_specimen_interpretation["dir_dang"]), float(this_specimen_interpretation[ "meas_step_min"]) * 1e3, float(this_specimen_interpretation[ "meas_step_max"]) * 1e3, float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) elif 'T' in units and 'K' in units: if float(this_specimen_interpretation[ 'meas_step_min']) < 1.0: min = float(this_specimen_interpretation[ 'meas_step_min']) * 1e3 else: min = float(this_specimen_interpretation[ 'meas_step_min']) - 273 if float(this_specimen_interpretation[ 'meas_step_max']) < 1.0: max = float(this_specimen_interpretation[ 'meas_step_max']) * 1e3 else: max = float(this_specimen_interpretation[ 'meas_step_max']) - 273 print('%s %i %7.1f %i %i %7.1f %7.1f %s \n' % ( this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float( this_specimen_interpretation["dir_alpha95"] ), min, max, float(this_specimen_interpretation["dir_dec"]), float(this_specimen_interpretation["dir_inc"]), calculation_type)) else: print( '%s %i %7.1f %7.1f %7.1f %7.1f %7.1f %s \n' % (this_specimen_interpretation["specimen"], int(this_specimen_interpretation[ "dir_n_measurements"]), float(this_specimen_interpretation[ "dir_alpha95"]), float(this_specimen_interpretation[ "meas_step_min"]), float(this_specimen_interpretation[ "meas_step_max"]), float( this_specimen_interpretation["dir_dec"]), float( this_specimen_interpretation["dir_inc"]), calculation_type)) if verbose: saveit = input("Save this interpretation? [y]/n \n") # START HERE # # if len(current_spec_data)==0: # no interpretations yet for this session # print "no current interpretation" # beg_pca,end_pca="","" # calculation_type="" # get the ones that meet the current coordinate system else: print("no data") if verbose: input('Ready for next specimen ') k += 1
def main(): """ NAME lnp_magic.py DESCRIPTION makes equal area projections site by site from pmag_specimen formatted file with Fisher confidence ellipse using McFadden and McElhinny (1988) technique for combining lines and planes SYNTAX lnp_magic [command line options] INPUT takes magic formatted pmag_specimens file OUPUT prints site_name n_lines n_planes K alpha95 dec inc R OPTIONS -h prints help message and quits -f FILE: specify input file, default is 'pmag_specimens.txt' -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted default is specimen -fmt [svg,png,jpg] format for plots, default is svg -sav save plots and quit -P: do not plot -F FILE, specify output file of dec, inc, alpha95 data for plotting with plotdi_a and plotdi_e -exc use criteria in pmag_criteria.txt """ dir_path='.' FIG={} # plot dictionary FIG['eqarea']=1 # eqarea is figure 1 in_file,plot_key,coord='pmag_specimens.txt','er_site_name',"-1" out_file="" fmt,plt,plot='svg',1,0 Crits="" M,N,acutoff,kcutoff=180.,1,180.,0. if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-WD' in sys.argv: ind=sys.argv.index('-WD') dir_path=sys.argv[ind+1] if '-f' in sys.argv: ind=sys.argv.index("-f") in_file=sys.argv[ind+1] if '-exc' in sys.argv: Crits,file_type=pmag.magic_read(dir_path+'/pmag_criteria.txt') for crit in Crits: if 'specimen_mad' in crit: M=float(crit['specimen_mad']) if 'specimen_n' in crit: N=float(crit['specimen_n']) if 'site_alpha95' in crit: acutoff=float(crit['site_alpha95']) if 'site_k' in crit: kcutoff=float(crit['site_k']) if '-F' in sys.argv: ind=sys.argv.index("-F") out_file=sys.argv[ind+1] out=open(dir_path+'/'+out_file,'w') 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] if '-P' in sys.argv:plt=0 if '-sav' in sys.argv:plot=1 # in_file=dir_path+'/'+in_file Specs,file_type=pmag.magic_read(in_file) if file_type!='pmag_specimens': print('Error opening file') sys.exit() sitelist=[] for rec in Specs: if rec['er_site_name'] not in sitelist: sitelist.append(rec['er_site_name']) sitelist.sort() if plt==1: EQ={} EQ['eqarea']=1 pmagplotlib.plot_init(EQ['eqarea'],4,4) for site in sitelist: print(site) data=[] for spec in Specs: if 'specimen_tilt_correction' not in list(spec.keys()):spec['specimen_tilt_correction']='-1' # assume unoriented if spec['er_site_name']==site: if 'specimen_mad' not in list(spec.keys()) or spec['specimen_mad']=="": if 'specimen_alpha95' in list(spec.keys()) and spec['specimen_alpha95']!="": spec['specimen_mad']=spec['specimen_alpha95'] else: spec['specimen_mad']='180' if spec['specimen_tilt_correction']==coord and float(spec['specimen_mad'])<=M and float(spec['specimen_n'])>=N: rec={} for key in list(spec.keys()):rec[key]=spec[key] rec["dec"]=float(spec['specimen_dec']) rec["inc"]=float(spec['specimen_inc']) rec["tilt_correction"]=spec['specimen_tilt_correction'] data.append(rec) if len(data)>2: fpars=pmag.dolnp(data,'specimen_direction_type') print("Site lines planes kappa a95 dec inc") print(site, fpars["n_lines"], fpars["n_planes"], fpars["K"], fpars["alpha95"], fpars["dec"], fpars["inc"], fpars["R"]) if out_file!="": if float(fpars["alpha95"])<=acutoff and float(fpars["K"])>=kcutoff: out.write('%s %s %s\n'%(fpars["dec"],fpars['inc'],fpars['alpha95'])) print('% tilt correction: ',coord) if plt==1: files={} files['eqarea']=site+'_'+crd+'_'+'eqarea'+'.'+fmt pmagplotlib.plotLNP(EQ['eqarea'],site,data,fpars,'specimen_direction_type') if plot==0: pmagplotlib.drawFIGS(EQ) ans=input("s[a]ve plot, [q]uit, <return> to continue:\n ") if ans=="a": pmagplotlib.saveP(EQ,files) if ans=="q": sys.exit() else: pmagplotlib.saveP(EQ,files) else: print('skipping site - not enough data with specified coordinate system')
def main(): """ NAME site_edit_magic.py DESCRIPTION makes equal area projections site by site from pmag_specimens.txt file with Fisher confidence ellipse using McFadden and McElhinny (1988) technique for combining lines and planes allows testing and reject specimens for bad orientations SYNTAX site_edit_magic.py [command line options] OPTIONS -h: prints help and quits -f: specify pmag_specimen format file, default is pmag_specimens.txt -fsa: specify er_samples.txt file -exc: use existing pmag_criteria.txt file -N: reset all sample flags to good OUPUT edited er_samples.txt file """ dir_path='.' FIG={} # plot dictionary FIG['eqarea']=1 # eqarea is figure 1 in_file='pmag_specimens.txt' sampfile='er_samples.txt' out_file="" fmt,plot='svg',1 Crits="" M,N=180.,1 repeat='' renew=0 if '-h' in sys.argv: print main.__doc__ sys.exit() if '-WD' in sys.argv: ind=sys.argv.index('-WD') dir_path=sys.argv[ind+1] if '-f' in sys.argv: ind=sys.argv.index("-f") in_file=sys.argv[ind+1] if '-fsa' in sys.argv: ind=sys.argv.index("-fsa") sampfile=sys.argv[ind+1] if '-exc' in sys.argv: Crits,file_type=pmag.magic_read(dir_path+'/pmag_criteria.txt') for crit in Crits: if crit['pmag_criteria_code']=='DE-SPEC': M=float(crit['specimen_mad']) N=float(crit['specimen_n']) if '-fmt' in sys.argv: ind=sys.argv.index("-fmt") fmt=sys.argv[ind+1] if '-N' in sys.argv: renew=1 # if in_file[0]!="/":in_file=dir_path+'/'+in_file if sampfile[0]!="/":sampfile=dir_path+'/'+sampfile crd='s' Specs,file_type=pmag.magic_read(in_file) if file_type!='pmag_specimens': print ' bad pmag_specimen input file' sys.exit() Samps,file_type=pmag.magic_read(sampfile) if file_type!='er_samples': print ' bad er_samples input file' sys.exit() SO_methods=[] for rec in Samps: if 'sample_orientation_flag' not in rec.keys(): rec['sample_orientation_flag']='g' if 'sample_description' not in rec.keys(): rec['sample_description']='' if renew==1: rec['sample_orientation_flag']='g' description=rec['sample_description'] if '#' in description: newdesc="" c=0 while description[c]!='#' and c<len(description)-1: # look for first pound sign newdesc=newdesc+description[c] c+=1 while description[c]=='#': c+=1# skip first set of pound signs while description[c]!='#':c+=1 # find second set of pound signs while description[c]=='#' and c<len(description)-1:c+=1 # skip second set of pound signs while c<len(description)-1: # look for first pound sign newdesc=newdesc+description[c] c+=1 rec['sample_description']=newdesc # edit out old comment about orientations if "magic_method_codes" in rec: methlist=rec["magic_method_codes"] for meth in methlist.split(":"): if "SO" in meth.strip() and "SO-POM" not in meth.strip(): if meth.strip() not in SO_methods: SO_methods.append(meth.strip()) pmag.magic_write(sampfile,Samps,'er_samples') SO_priorities=pmag.set_priorities(SO_methods,0) sitelist=[] for rec in Specs: if rec['er_site_name'] not in sitelist: sitelist.append(rec['er_site_name']) sitelist.sort() EQ={} EQ['eqarea']=1 pmagplotlib.plot_init(EQ['eqarea'],5,5) k=0 while k<len(sitelist): site=sitelist[k] print site data=[] ThisSiteSpecs=pmag.get_dictitem(Specs,'er_site_name',site,'T') ThisSiteSpecs=pmag.get_dictitem(ThisSiteSpecs,'specimen_tilt_correction','-1','T') # get all the unoriented data for spec in ThisSiteSpecs: if spec['specimen_mad']!="" and spec['specimen_n']!="" and float(spec['specimen_mad'])<=M and float(spec['specimen_n'])>=N: # good spec, now get orientation.... redo,p=1,0 if len(SO_methods)<=1: az_type=SO_methods[0] orient=pmag.find_samp_rec(spec["er_sample_name"],Samps,az_type) redo=0 while redo==1: if p>=len(SO_priorities): print "no orientation data for ",spec['er_sample_name'] orient["sample_azimuth"]="" orient["sample_dip"]="" redo=0 else: az_type=SO_methods[SO_methods.index(SO_priorities[p])] orient=pmag.find_samp_rec(spec["er_sample_name"],Samps,az_type) if orient["sample_azimuth"] !="": redo=0 p+=1 if orient['sample_azimuth']!="": rec={} for key in spec.keys():rec[key]=spec[key] rec['dec'],rec['inc']=pmag.dogeo(float(spec['specimen_dec']),float(spec['specimen_inc']),float(orient['sample_azimuth']),float(orient['sample_dip'])) rec["tilt_correction"]='1' crd='g' rec['sample_azimuth']=orient['sample_azimuth'] rec['sample_dip']=orient['sample_dip'] data.append(rec) if len(data)>2: print 'specimen, dec, inc, n_meas/MAD,| method codes ' for i in range(len(data)): print '%s: %7.1f %7.1f %s / %s | %s' % (data[i]['er_specimen_name'], data[i]['dec'], data[i]['inc'], data[i]['specimen_n'], data[i]['specimen_mad'], data[i]['magic_method_codes']) fpars=pmag.dolnp(data,'specimen_direction_type') print "\n Site lines planes kappa a95 dec inc" print site, fpars["n_lines"], fpars["n_planes"], fpars["K"], fpars["alpha95"], fpars["dec"], fpars["inc"], fpars["R"] if out_file!="": if float(fpars["alpha95"])<=acutoff and float(fpars["K"])>=kcutoff: out.write('%s %s %s\n'%(fpars["dec"],fpars['inc'],fpars['alpha95'])) pmagplotlib.plotLNP(EQ['eqarea'],site,data,fpars,'specimen_direction_type') pmagplotlib.drawFIGS(EQ) if k!=0 and repeat!='y': ans=raw_input("s[a]ve plot, [q]uit, [e]dit specimens, [p]revious site, <return> to continue:\n ") elif k==0 and repeat!='y': ans=raw_input("s[a]ve plot, [q]uit, [e]dit specimens, <return> to continue:\n ") if ans=="p": k-=2 if ans=="a": files={} files['eqarea']=site+'_'+crd+'_eqarea'+'.'+fmt pmagplotlib.saveP(EQ,files) if ans=="q": sys.exit() if ans=="e" and Samps==[]: print "can't edit samples without orientation file, sorry" elif ans=="e": # k-=1 testspec=raw_input("Enter name of specimen to check: ") for spec in data: if spec['er_specimen_name']==testspec: # first test wrong direction of drill arrows (flip drill direction in opposite direction and re-calculate d,i d,i=pmag.dogeo(float(spec['specimen_dec']),float(spec['specimen_inc']),float(spec['sample_azimuth'])-180.,-float(spec['sample_dip'])) XY=pmag.dimap(d,i) pmagplotlib.plotXY(EQ['eqarea'],[XY[0]],[XY[1]],sym='g^') # first test wrong end of compass (take az-180.) d,i=pmag.dogeo(float(spec['specimen_dec']),float(spec['specimen_inc']),float(spec['sample_azimuth'])-180.,float(spec['sample_dip'])) XY=pmag.dimap(d,i) pmagplotlib.plotXY(EQ['eqarea'],[XY[0]],[XY[1]],sym='kv') # did the sample spin in the hole? # now spin around specimen's z X_up,Y_up,X_d,Y_d=[],[],[],[] for incr in range(0,360,5): d,i=pmag.dogeo(float(spec['specimen_dec'])+incr,float(spec['specimen_inc']),float(spec['sample_azimuth']),float(spec['sample_dip'])) XY=pmag.dimap(d,i) if i>=0: X_d.append(XY[0]) Y_d.append(XY[1]) else: X_up.append(XY[0]) Y_up.append(XY[1]) pmagplotlib.plotXY(EQ['eqarea'],X_d,Y_d,sym='b.') pmagplotlib.plotXY(EQ['eqarea'],X_up,Y_up,sym='c.') pmagplotlib.drawFIGS(EQ) break print "Triangle: wrong arrow for drill direction." print "Delta: wrong end of compass." print "Small circle: wrong mark on sample. [cyan upper hemisphere]" deleteme=raw_input("Mark this sample as bad? y/[n] ") if deleteme=='y': reason=raw_input("Reason: [1] broke, [2] wrong drill direction, [3] wrong compass direction, [4] bad mark, [5] displaced block [6] other ") if reason=='1': description=' sample broke while drilling' if reason=='2': description=' wrong drill direction ' if reason=='3': description=' wrong compass direction ' if reason=='4': description=' bad mark in field' if reason=='5': description=' displaced block' if reason=='6': description=raw_input('Enter brief reason for deletion: ') for samp in Samps: if samp['er_sample_name']==spec['er_sample_name']: samp['sample_orientation_flag']='b' samp['sample_description']=samp['sample_description']+' ## direction deleted because: '+description+'##' # mark description pmag.magic_write(sampfile,Samps,'er_samples') repeat=raw_input("Mark another sample, this site? y/[n] ") if repeat=='y': k-=1 else: print 'skipping site - not enough data with specified coordinate system' k+=1 print "sample flags stored in ",sampfile
def main(): """ NAME dayplot_magic.py DESCRIPTION makes 'day plots' (Day et al. 1977) and squareness/coercivity, plots 'linear mixing' curve from Dunlop and Carter-Stiglitz (2006). squareness coercivity of remanence (Neel, 1955) plots after Tauxe et al. (2002) SYNTAX dayplot_magic.py [command line options] OPTIONS -h prints help message and quits -f: specify input hysteresis file, default is rmag_hysteresis.txt -fr: specify input remanence file, default is rmag_remanence.txt -fmt [svg,png,jpg] format for output plots -sav saves plots and quits quietly -n label specimen names """ args = sys.argv hyst_file, rem_file = "rmag_hysteresis.txt", "rmag_remanence.txt" dir_path = '.' verbose = pmagplotlib.verbose fmt = 'svg' # default file format if '-WD' in args: ind = args.index('-WD') dir_path = args[ind + 1] if "-h" in args: print(main.__doc__) sys.exit() if '-f' in args: ind = args.index("-f") hyst_file = args[ind + 1] if '-fr' in args: ind = args.index("-fr") rem_file = args[ind + 1] if '-fmt' in sys.argv: ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] if '-sav' in sys.argv: plots = 1 verbose = 0 else: plots = 0 if '-n' in sys.argv: label = 1 else: label = 0 hyst_file = os.path.realpath(os.path.join(dir_path, hyst_file)) rem_file = os.path.realpath(os.path.join(dir_path, rem_file)) # # initialize some variables # define figure numbers for Day,S-Bc,S-Bcr DSC = {} DSC['day'], DSC['S-Bc'], DSC['S-Bcr'], DSC['bcr1-bcr2'] = 1, 2, 3, 4 pmagplotlib.plot_init(DSC['day'], 5, 5) pmagplotlib.plot_init(DSC['S-Bc'], 5, 5) pmagplotlib.plot_init(DSC['S-Bcr'], 5, 5) pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5) # # hyst_data, file_type = pmag.magic_read(hyst_file) rem_data, file_type = pmag.magic_read(rem_file) # S, BcrBc, Bcr2, Bc, hsids, Bcr = [], [], [], [], [], [] Ms, Bcr1, Bcr1Bc, S1 = [], [], [], [] names = [] locations = '' for rec in hyst_data: if 'er_location_name' in rec.keys( ) and rec['er_location_name'] not in locations: locations = locations + rec['er_location_name'] + '_' if rec['hysteresis_bcr'] != "" and rec['hysteresis_mr_moment'] != "": S.append( float(rec['hysteresis_mr_moment']) / float(rec['hysteresis_ms_moment'])) Bcr.append(float(rec['hysteresis_bcr'])) Bc.append(float(rec['hysteresis_bc'])) BcrBc.append(Bcr[-1] / Bc[-1]) if 'er_synthetic_name' in rec.keys( ) and rec['er_synthetic_name'] != "": rec['er_specimen_name'] = rec['er_synthetic_name'] hsids.append(rec['er_specimen_name']) names.append(rec['er_specimen_name']) if len(rem_data) > 0: for rec in rem_data: if rec['remanence_bcr'] != "" and float(rec['remanence_bcr']) > 0: try: ind = hsids.index(rec['er_specimen_name']) Bcr1.append(float(rec['remanence_bcr'])) Bcr1Bc.append(Bcr1[-1] / Bc[ind]) S1.append(S[ind]) Bcr2.append(Bcr[ind]) except ValueError: if verbose: print('hysteresis data for ', rec['er_specimen_name'], ' not found') # # now plot the day and S-Bc, S-Bcr plots # leglist = [] if label == 0: names = [] if len(Bcr1) > 0: pmagplotlib.plotDay(DSC['day'], Bcr1Bc, S1, 'ro', names=names) pmagplotlib.plotSBcr(DSC['S-Bcr'], Bcr1, S1, 'ro') pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5) pmagplotlib.plotBcr(DSC['bcr1-bcr2'], Bcr1, Bcr2) else: del DSC['bcr1-bcr2'] pmagplotlib.plotDay(DSC['day'], BcrBc, S, 'bs', names=names) pmagplotlib.plotSBcr(DSC['S-Bcr'], Bcr, S, 'bs') pmagplotlib.plotSBc(DSC['S-Bc'], Bc, S, 'bs') files = {} if len(locations) > 0: locations = locations[:-1] for key in DSC.keys(): if pmagplotlib.isServer: # use server plot naming convention files[ key] = 'LO:_' + locations + '_' + 'SI:__SA:__SP:__TY:_' + key + '_.' + fmt else: # use more readable plot naming convention files[key] = '{}_{}.{}'.format(locations, key, fmt) if verbose: pmagplotlib.drawFIGS(DSC) ans = raw_input(" S[a]ve to save plots, return to quit: ") if ans == "a": pmagplotlib.saveP(DSC, files) else: sys.exit() if plots: pmagplotlib.saveP(DSC, files)