def common_dir_boot(dir1,dir2,bootsteps=1000,plot='no'): #test for a common direction using bootstrap method #directions given as pandas Series listing mean direction/pole parameters #this is assuming published means without input directions, so bootstrap is a little different from the one #described in Tauxe: not a pseudoselection from specified points but drawing from fisher distribution directly. #adds a level of abstraction which hopefully does not invalidate procedure BDI1,BDI2=[],[] for s in range(bootsteps): fpars1=pmag.fisher_mean(get_fish(dir1)) fpars2=pmag.fisher_mean(get_fish(dir2)) BDI1.append([fpars1['dec'],fpars1['inc']]) BDI2.append([fpars2['dec'],fpars2['inc']]) bounds1=get_bounds(BDI1) bounds2=get_bounds(BDI2) #now want to check if is a pass or a fail - only pass if error bounds overlap in x,y,and z bresult=[] for b1,b2 in zip(bounds1,bounds2): if (b1[0]>b2[1] or b1[1]<b2[0]): bresult.append(0) else: bresult.append(1) if sum(bresult)==3: outcome='Pass' else: outcome='Fail' angle=pmag.angle((dir1['dec'],dir1['inc']),(dir2['dec'],dir2['inc'])) # set up plots - can run this if want to visually check what's going on. if plot=='yes': CDF={'X':1,'Y':2,'Z':3} pmagplotlib.plot_init(CDF['X'],4,4) pmagplotlib.plot_init(CDF['Y'],4,4) pmagplotlib.plot_init(CDF['Z'],4,4) # draw the cdfs pmagplotlib.plotCOM(CDF,BDI1,BDI2,["",""]) pmagplotlib.drawFIGS(CDF) return pd.Series([outcome,angle[0]],index=['Outcome','angle'])
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 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 -i for interactive filename entry -f FILE, specify file on command line 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). """ if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file=raw_input("Enter file name with dec, inc data: ") f=open(file,'rU') data=f.readlines() elif '-f' in sys.argv: # ask for filename ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'rU') 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 pmagplotlib.drawFIGS(QQ) files,fmt={},'svg' for key in 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) 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 probRo.py DESCRIPTION Calculates Ro as a test for randomness - if R exceeds Ro given N, then set is not random at 95% level of confindence SYNTAX probRo.py [command line options] OPTIONS -h prints this help message -Nm number of Monte Carlo simulations (default is 10000) -Nmax maximum number for dataset (default is 10) """ Ns,Nm=range(4,11),10000 files,fmt={},'svg' if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit if '-Nm' in sys.argv: ind=sys.argv.index('-Nm') Nm=int(sys.argv[ind+1]) if '-Nmax' in sys.argv: ind=sys.argv.index('-Nmax') Nmax=int(sys.argv[ind+1]) Ns=range(3,Nmax+1) PLT={'plt':1} pmagplotlib.plot_init(PLT['plt'],5,5) Ro=[] for N in Ns: Rs=[] n=0 while n<Nm: dirs=pmag.get_unf(N) pars=pmag.fisher_mean(dirs) Rs.append(pars['r']) n+=1 Rs.sort() crit=int(.95*Nm) Ro.append(Rs[crit]) pmagplotlib.plotXY(PLT['plt'],Ns,Ro,'-','N','Ro','') pmagplotlib.plotXY(PLT['plt'],Ns,Ro,'ro','N','Ro','') pmagplotlib.drawFIGS(PLT) for key in PLT.keys(): files[key]=key+'.'+fmt ans=raw_input(" S[a]ve to save plot, [q]uit without saving: ") if ans=="a": pmagplotlib.saveP(PLT,files)
def main(): """ NAME plot_cdfs.py DESCRIPTION makes plots of cdfs of data in input file SYNTAX plot_cdfs.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 """ 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) # 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", "") 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_cdfs.py DESCRIPTION makes plots of cdfs of data in input file SYNTAX plot_cdfs.py [-h][command line options] OPTIONS -h prints help message and quits -f FILE -t TITLE """ title="" if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind=sys.argv.index('-f') specfile=sys.argv[ind+1] if '-t' in sys.argv: ind=sys.argv.index('-t') title=sys.argv[ind+1] X=[] f=open(specfile,'rU') for line in f.readlines(): rec=line.split() X.append(float(rec[0])) CDF={'X':1} pmagplotlib.plot_init(CDF['X'],5,5) pmagplotlib.plotCDF(CDF['X'],X,title,'r','') pmagplotlib.drawFIGS(CDF) try: raw_input('Return to save all figures, cntl-d to quit') except EOFError: print "Good bye" sys.exit() files={} for key in CDF.keys(): files[key]=(key+'.svg') pmagplotlib.saveP(CDF,files)
def main(): """ """ dir_path='.' ocean=0 proj='ortho' euler_file='' cont='ind.asc' Poles=[] lat_0,lon_0=0.,0. fmt='svg' lon_0=45. lat_0=20. euler_file='polerots.ind' f=open(euler_file,'rU') edata=f.readlines() for line in edata: rec=line.split() Poles.append([float(rec[0]),float(rec[1]),float(rec[2])]) FIG={'map':1} pmagplotlib.plot_init(FIG['map'],6,6) # read in er_sites file lats,lons=[],[] data=continents.get_continent(cont) for line in data: lats.append(float(line[0])) lons.append(float(line[1])) Opts={'latmin':-90,'latmax':90,'lonmin':0.,'lonmax':360.,'lat_0':lat_0,'lon_0':lon_0,'proj':proj,'details':0,'sym':'r-','padlat':0,'padlon':0,'res':'i'} pmagplotlib.plotMAP(FIG['map'],lats,lons,Opts) pmagplotlib.drawFIGS(FIG) plats=[90.] plons=[0.] Opts['sym']='ro' pmagplotlib.plotMAP(FIG['map'],plats,plons,Opts) pmagplotlib.drawFIGS(FIG) newlats,newlons=[],[] for lat in plats:newlats.append(lat) for lon in plons:newlons.append(lon) for pole in Poles: Rlats,Rlons=pmag.PTrot(pole,newlats,newlons) pmagplotlib.plotMAP(FIG['map'],Rlats,Rlons,Opts) pmagplotlib.drawFIGS(FIG) newlats,newlons=[],[] for lat in Rlats:newlats.append(lat) for lon in Rlons:newlons.append(lon) files={} for key in FIG.keys(): files[key]='pole_rot'+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='Site Map' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) else: ans=raw_input(" S[a]ve to save plot, Return to quit: ") if ans=="a": pmagplotlib.saveP(FIG,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] -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 DEFAULTS FILE: pmag_results.txt res: c prj: mercator ELAT,ELON = 0,0 SYM SIZE: ro 8 RSYM RSIZE: g^ 8 """ dir_path='.' res,ages='c',0 proj='npstere' 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 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 '-res' in sys.argv: ind = sys.argv.index('-res') res=sys.argv[ind+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=[],[],[] Results=[] for rec in data: if 'pmag_result_name' in rec.keys(): name=rec['pmag_result_name'].split() if 'Site' in name: if coord=="" or rec['tilt_correction']==coord:Results.append(rec) elif coord=="" or rec['tilt_correction']==coord:Results.append(rec) for rec in Results: if 'vgp_lat' in rec.keys() and rec['vgp_lat']!="" and 'vgp_lon' in rec.keys() and rec['vgp_lon']!="": 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) 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} pmagplotlib.plotMAP(FIG['map'],[90.],[0.],Opts) # make the base map with a blue triangle at the pole` Opts['details']={'coasts':0,'rivers':0, 'states':0, 'countries':0,'ocean':0} 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 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` pmagplotlib.drawFIGS(FIG) files={} for key in FIG.keys(): files[key]='VGP_map'+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='VGP Map' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) else: 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()
def main(): """ NAME EI.py [command line options] DESCRIPTION Finds bootstrap confidence bounds on Elongation and Inclination data SYNTAX EI.py [command line options] OPTIONS -h prints help message and quits -f FILE specifies input file -p do parametric bootstrap INPUT dec/inc pairs OUTPUT makes a plot of the E/I pair and bootstrapped confidence bounds along with the E/I trend predicted by the TK03 field model prints out: Io (mean inclination), I_lower and I_upper are 95% confidence bounds on inclination Eo (elongation), E_lower and E_upper are 95% confidence bounds on elongation Edec,Einc are the elongation direction """ par=0 if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind=sys.argv.index('-f') file=open(sys.argv[ind+1],'rU') if '-p' in sys.argv: par=1 rseed,nb,data=10,5000,[] upper,lower=int(round(.975*nb)),int(round(.025*nb)) Es,Is=[],[] PLTS={'eq':1,'ei':2} pmagplotlib.plot_init(PLTS['eq'],5,5) pmagplotlib.plot_init(PLTS['ei'],5,5) # poly_tab= [ 3.07448925e-06, -3.49555831e-04, -1.46990847e-02, 2.90905483e+00] poly_new= [ 3.15976125e-06, -3.52459817e-04, -1.46641090e-02, 2.89538539e+00] # poly_cp88= [ 5.34558576e-06, -7.70922659e-04, 5.18529685e-03, 2.90941351e+00] # poly_qc96= [ 7.08210133e-06, -8.79536536e-04, 1.09625547e-03, 2.92513660e+00] # poly_cj98=[ 6.56675431e-06, -7.91823539e-04, -1.08211350e-03, 2.80557710e+00] # poly_tk03_g20= [ 4.96757685e-06, -6.02256097e-04, -5.96103272e-03, 2.84227449e+00] # poly_tk03_g30= [ 7.82525963e-06, -1.39781724e-03, 4.47187092e-02, 2.54637535e+00] # poly_gr99_g=[ 1.24362063e-07, -1.69383384e-04, -4.24479223e-03, 2.59257437e+00] # poly_gr99_e=[ 1.26348154e-07, 2.01691452e-04, -4.99142308e-02, 3.69461060e+00] E_EI,E_tab,E_new,E_cp88,E_cj98,E_qc96,E_tk03_g20=[],[],[],[],[],[],[] E_tk03_g30,E_gr99_g,E_gr99_e=[],[],[] I2=range(0,90,5) for inc in I2: E_new.append(EI(inc,poly_new)) # use the polynomial from Tauxe et al. (2008) pmagplotlib.plotEI(PLTS['ei'],E_new,I2,1) if '-f' in sys.argv: random.seed(rseed) for line in file.readlines(): rec=line.split() dec=float(rec[0]) inc=float(rec[1]) if par==1: if len(rec)==4: N=(int(rec[2])) # append n K=float(rec[3]) # append k rec=[dec,inc,N,K] data.append(rec) else: rec=[dec,inc] data.append(rec) pmagplotlib.plotEQ(PLTS['eq'],data,'Data') ppars=pmag.doprinc(data) n=ppars["N"] Io=ppars['inc'] Edec=ppars['Edir'][0] Einc=ppars['Edir'][1] Eo=(ppars['tau2']/ppars['tau3']) b=0 print 'doing bootstrap - be patient' while b<nb: bdata=[] for j in range(n): boot=random.randint(0,n-1) random.jumpahead(rseed) if par==1: DIs=[] D,I,N,K=data[boot][0],data[boot][1],data[boot][2],data[boot][3] for k in range(N): dec,inc=pmag.fshdev(K) drot,irot=pmag.dodirot(dec,inc,D,I) DIs.append([drot,irot]) fpars=pmag.fisher_mean(DIs) bdata.append([fpars['dec'],fpars['inc'],1.]) # replace data[boot] with parametric dec,inc else: bdata.append(data[boot]) ppars=pmag.doprinc(bdata) Is.append(ppars['inc']) Es.append(ppars['tau2']/ppars['tau3']) b+=1 if b%100==0:print b Is.sort() Es.sort() x,std=pmag.gausspars(Es) stderr=std/math.sqrt(len(data)) pmagplotlib.plotX(PLTS['ei'],Io,Eo,Is[lower],Is[upper],Es[lower],Es[upper],'b-') # pmagplotlib.plotX(PLTS['ei'],Io,Eo,Is[lower],Is[upper],Eo-stderr,Eo+stderr,'b-') print 'Io, Eo, I_lower, I_upper, E_lower, E_upper, Edec, Einc' print '%7.1f %4.2f %7.1f %7.1f %4.2f %4.2f %7.1f %7.1f' %(Io,Eo,Is[lower],Is[upper],Es[lower],Es[upper], Edec,Einc) # print '%7.1f %4.2f %7.1f %7.1f %4.2f %4.2f' %(Io,Eo,Is[lower],Is[upper],Eo-stderr,Eo+stderr) pmagplotlib.drawFIGS(PLTS) files,fmt={},'svg' for key in PLTS.keys(): files[key]=key+'.'+fmt ans=raw_input(" S[a]ve to save plot, [q]uit without saving: ") if ans=="a": pmagplotlib.saveP(PLTS,files)
def main(): """ NAME pick_AC_specimens.py DESCRIPTION finds whether anisotropy correction yeilds more tightly grouped intensities than uncorrected data. picks either all corrected or all uncorrected data and puts in pmag_specimen format file SYNTAX pick_AC_specimens.py [-h][-i][-fu TFILE][-fc AFILE][-F FILE] OPTIONS -h prints help message and quits -i allows interactive setting of file names -fu TFILE uncorrected pmag_specimen format file with thellier interpretations created by thellier_magic_redo.py -fc AFILE anisotropy corrected pmag_specimen format file created by thellier_magic_redo.py -fcr CRIT pmag_criteria.txt format file with acceptance criteria -opt SIG use the optimizer_thelpars.txt file for criteria -F FILE pmag_specimens format output file with "best" set of data DEFAULTS TFILE: thellier_specimens.txt AFILE: AC_specimens.txt FILE: pmag_specimens.txt """ tspec="thellier_specimens.txt" aspec="AC_specimens.txt" ofile="pmag_specimens.txt" critfile="pmag_criteria.txt" ACSamplist,Samplist,sigmin=[],[],10000 GoodSamps,SpecOuts=[],[] P={'cdf':1} pmagplotlib.plot_init(P['cdf'],5,5) # get arguments from command line if '-h' in sys.argv: print main.__doc__ sys.exit() if '-fu' in sys.argv: ind=sys.argv.index('-fu') tspec=sys.argv[ind+1] if '-fc' in sys.argv: ind=sys.argv.index('-fc') aspec=sys.argv[ind+1] if '-fcr' in sys.argv: ind=sys.argv.index('-fcr') critfile=sys.argv[ind+1] if '-opt' in sys.argv: ind=sys.argv.index('-opt') critfile='optimum_thelpars.txt' sigcutoff=sys.argv[ind+1] if '-F' in sys.argv: ind=sys.argv.index('-F') ofile=sys.argv[ind+1] if '-i' in sys.argv: file=raw_input(" thellier_specimnens.txt file [thellier_specimens.txt]: ") if file!="":tfile=file file=raw_input(" AC_specimnens.txt file [AC_specimens.txt]: ") if file!="":afile=file file=raw_input(" pmag_specimnens.txt file [pmag_specimens.txt]: ") if file!="":ofile=file # read in pmag_specimens file Specs,file_type=pmag.magic_read(tspec) Speclist=pmag.get_specs(Specs) ACSpecs,file_type=pmag.magic_read(aspec) ACspeclist=pmag.get_specs(ACSpecs) Crits,file_type=pmag.magic_read(critfile) keys=['specimen_int_mad','specimen_drats','specimen_fvds','specimen_b_beta','specimen_Z','specimen_md','specimen_dang'] accept={} for crit in Crits: if critfile!='optimum_thelpars.txt': if crit['pmag_criteria_code']=='IE-SPEC': for key in keys: accept[key]=float(crit[key]) # assign acceptance criteria break else: if float(crit['sample_int_sigma_perc'])==float(sigcutoff): for key in keys: accept[key]=float(crit[key]) Diff=[] for aspec in ACSpecs: grade,kill=pmag.grade(aspec,accept) if grade==len(accept): print 'AC: ',aspec["er_specimen_name"],'%i'%(1e6*float(aspec["specimen_int"])) aint=(1e6*float(aspec["specimen_int"])) for spec in Specs: if spec["er_specimen_name"]==aspec['er_specimen_name']: print 'UC: ',spec["er_specimen_name"],'%i'%(1e6*float(spec["specimen_int"])) int=(1e6*float(spec["specimen_int"])) Diff.append(100.*abs(aint-int)/aint) x,s=pmag.gausspars(Diff) print x,s Diff.sort() print Diff[0],Diff[-1] pmagplotlib.plotCDF(P['cdf'],Diff,'% Difference','r') pmagplotlib.drawFIGS(P) raw_input()
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 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 pre-tilt magnetization is indicated If the 95% conf bounds include 100, then a post-tilt magnetization is indicated If the 95% conf bounds exclude both 0 and 100, syn-tilt magnetization is possible as is vertical axis rotation or other pathologies 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='svg' 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 '-b' in sys.argv: ind=sys.argv.index('-b') min=float(sys.argv[ind+1]) max=float(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') 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) pmagplotlib.drawFIGS(PLTS) ans= raw_input('S[a]ve all figures, <Return> to quit ') if ans!='a': print "Good bye" sys.exit() else: files={} for key in PLTS.keys(): files[key]=('foldtest_'+'%s'%(key.strip()[:2])+'.'+fmt) pmagplotlib.saveP(PLTS,files)
def main(): """ """ dir_path = '.' ocean = 0 proj = 'ortho' euler_file = '' cont = 'ind.asc' Poles = [] lat_0, lon_0 = 0., 0. fmt = 'svg' lon_0 = 45. lat_0 = 20. euler_file = 'polerots.ind' f = open(euler_file, 'rU') edata = f.readlines() for line in edata: rec = line.split() Poles.append([float(rec[0]), float(rec[1]), float(rec[2])]) FIG = {'map': 1} pmagplotlib.plot_init(FIG['map'], 6, 6) # read in er_sites file lats, lons = [], [] data = continents.get_continent(cont) for line in data: lats.append(float(line[0])) lons.append(float(line[1])) Opts = { 'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360., 'lat_0': lat_0, 'lon_0': lon_0, 'proj': proj, 'details': 0, 'sym': 'r-', 'padlat': 0, 'padlon': 0, 'res': 'i' } pmagplotlib.plotMAP(FIG['map'], lats, lons, Opts) pmagplotlib.drawFIGS(FIG) plats = [90.] plons = [0.] Opts['sym'] = 'ro' pmagplotlib.plotMAP(FIG['map'], plats, plons, Opts) pmagplotlib.drawFIGS(FIG) newlats, newlons = [], [] for lat in plats: newlats.append(lat) for lon in plons: newlons.append(lon) for pole in Poles: Rlats, Rlons = pmag.PTrot(pole, newlats, newlons) pmagplotlib.plotMAP(FIG['map'], Rlats, Rlons, Opts) pmagplotlib.drawFIGS(FIG) newlats, newlons = [], [] for lat in Rlats: newlats.append(lat) for lon in Rlons: newlons.append(lon) files = {} for key in FIG.keys(): files[key] = 'pole_rot' + '.' + fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['eq'] = 'Site Map' FIG = pmagplotlib.addBorders(FIG, titles, black, purple) pmagplotlib.saveP(FIG, files) else: ans = raw_input(" S[a]ve to save plot, Return to quit: ") if ans == "a": pmagplotlib.saveP(FIG, files)
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 CDF.keys(): files[key]='REV'+'_'+key+'.'+fmt if plot==0: pmagplotlib.drawFIGS(CDF) ans= raw_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 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 """ 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" f=open(file,'rU') data=f.readlines() # datablock= [] # set up list for data fmt='svg' # default image format 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 pmagplotlib.drawFIGS(ZED) while 1: # # 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 end_pca=len(datablock)-1 # initialize end_pca, beg_pca to first and last measurement beg_pca=0 ans=raw_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 ZED.keys(): files[key]=s+'_'+key+'.'+fmt pmagplotlib.saveP(ZED,files) if ans=='h': angle=float(raw_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=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 ') 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=raw_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"])
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, aus, eur, ind, sam, ant, grn, lau, nam] -eye ELAT ELON [specify eyeball location] -eul PLAT PLON OMEGA [specify euler rotation vector] -feu EFILE, specifies series of euler rotations vector in tab delimited file -res [c,l,i,h] specify resolution (crude, low, intermediate, high] -prj PROJ, specify one of the following: stere = Stereographic geos = geostationary lcc = lambert conformal robin = Robinson moll = molweide merc = mercator laea = Lambert azimuthal equal area DEFAULTS con: nam res: i prj: mercator ELAT,ELON = 0,0 NB: MUST have either -eul or -feu set """ dir_path = '.' ocean = 0 proj = 'ortho' euler_file = '' cont = 'waf.asc' Poles = [] lat_0, lon_0 = 0., 0. fmt = 'svg' lon_0 = 45. lat_0 = 20. euler_file = 'polerots' f = open(euler_file, 'rU') edata = f.readlines() for line in edata: rec = line.split() Poles.append([float(rec[0]), float(rec[1]), float(rec[2])]) FIG = {'map': 1} pmagplotlib.plot_init(FIG['map'], 6, 6) # read in er_sites file lats, lons = [], [] data = continents.get_continent(cont) for line in data: lats.append(float(line[0])) lons.append(float(line[1])) Opts = { 'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360., 'lat_0': lat_0, 'lon_0': lon_0, 'proj': proj, 'details': 0, 'sym': 'r-', 'padlat': 0, 'padlon': 0, 'res': 'i' } pmagplotlib.plotMAP(FIG['map'], lats, lons, Opts) pmagplotlib.drawFIGS(FIG) gclats = range(20, 91) gclons = [] for lat in gclats: gclons.append(355.) Opts['sym'] = 'b-' pmagplotlib.plotMAP(FIG['map'], gclats, gclons, Opts) pmagplotlib.drawFIGS(FIG) newlats, newlons = [], [] for lat in gclats: newlats.append(lat) for lon in gclons: newlons.append(lon) for pole in Poles: Opts['sym'] = 'b-' Rlats, Rlons = pmag.PTrot(pole, newlats, newlons) pmagplotlib.plotMAP(FIG['map'], Rlats, Rlons, Opts) Opts['sym'] = 'bo' pmagplotlib.plotMAP(FIG['map'], [Rlats[-1]], [Rlons[-1]], Opts) pmagplotlib.drawFIGS(FIG) Opts['sym'] = 'b-' newlats, newlons = [], [] for lat in Rlats: newlats.append(lat) for lon in Rlons: newlons.append(lon) files = {} for key in FIG.keys(): files[key] = 'pole_rot' + '.' + fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['eq'] = 'Site Map' FIG = pmagplotlib.addBorders(FIG, titles, black, purple) pmagplotlib.saveP(FIG, files) else: ans = raw_input(" S[a]ve to save plot, Return to quit: ") if ans == "a": pmagplotlib.saveP(FIG, files)
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, "rU") for line in f1.readlines(): rec = line.split() Dec, Inc = float(rec[0]), float(rec[1]) D1.append([Dec, Inc, 1.0]) f1.close() if "-f2" in sys.argv: ind = sys.argv.index("-f2") file2 = sys.argv[ind + 1] f2 = open(file2, "rU") 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.0]) f2.close() # take the antipode for the directions in file 2 D2_flip = [] for rec in D2: d, i = (rec[0] - 180.0) % 360.0, -rec[1] D2_flip.append([d, i, 1.0]) 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(0.95 * NumSims) Vcrit = Vp[k] # # equation 18 of McFadden and McElhinny, 1990 calculates the critical value of R (Rwc) # Rwc = Sr - (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(((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 = raw_input(" S[a]ve to save plot, [q]uit without saving: ") if ans == "a": pmagplotlib.saveP(CDF, files)
def main(): """ NAME specimens_results_magic.py DESCRIPTION combines pmag_specimens.txt file with age, location, acceptance criteria and outputs pmag_results table along with other MagIC tables necessary for uploading to the database SYNTAX specimens_results_magic.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specimen input magic_measurements format file, default is "magic_measurements.txt" -fsp: specimen input pmag_specimens format file, default is "pmag_specimens.txt" -fsm: sample input er_samples format file, default is "er_samples.txt" -fsi: specimen input er_sites format file, default is "er_sites.txt" -fla: specify a file with paleolatitudes for calculating VADMs, default is not to calculate VADMS format is: site_name paleolatitude (space delimited file) -fa AGES: specify er_ages format file with age information -crd [s,g,t,b]: specify coordinate system (s, specimen, g geographic, t, tilt corrected, b, geographic and tilt corrected) Default is to assume geographic NB: only the tilt corrected data will appear on the results table, if both g and t are selected. -cor [AC:CR:NL]: colon delimited list of required data adjustments for all specimens included in intensity calculations (anisotropy, cooling rate, non-linear TRM) unless specified, corrections will not be applied -pri [TRM:ARM] colon delimited list of priorities for anisotropy correction (-cor must also be set to include AC). default is TRM, then ARM -age MIN MAX UNITS: specify age boundaries and units -exc: use exiting selection criteria (in pmag_criteria.txt file), default is default criteria -C: no acceptance criteria -aD: average directions per sample, default is NOT -aI: average multiple specimen intensities per sample, default is by site -aC: average all components together, default is NOT -pol: calculate polarity averages -sam: save sample level vgps and v[a]dms, default is by site -xSi: skip the site level intensity calculation -p: plot directions and look at intensities by site, default is NOT -fmt: specify output for saved images, default is svg (only if -p set) -lat: use present latitude for calculating VADMs, default is not to calculate VADMs -xD: skip directions -xI: skip intensities OUPUT writes pmag_samples, pmag_sites, pmag_results tables """ # set defaults Comps = [] # list of components version_num = pmag.get_version() args = sys.argv DefaultAge = ["none"] skipdirs, coord, excrit, custom, vgps, average, Iaverage, plotsites, opt = 1, 0, 0, 0, 0, 0, 0, 0, 0 get_model_lat = 0 # this skips VADM calculation altogether, when get_model_lat=1, uses present day fmt = 'svg' dir_path = "." model_lat_file = "" Caverage = 0 infile = 'pmag_specimens.txt' measfile = "magic_measurements.txt" sampfile = "er_samples.txt" sitefile = "er_sites.txt" agefile = "er_ages.txt" specout = "er_specimens.txt" sampout = "pmag_samples.txt" siteout = "pmag_sites.txt" resout = "pmag_results.txt" critout = "pmag_criteria.txt" instout = "magic_instruments.txt" sigcutoff, OBJ = "", "" noDir, noInt = 0, 0 polarity = 0 coords = ['0'] Dcrit, Icrit, nocrit = 0, 0, 0 corrections = [] nocorrection = ['DA-NL', 'DA-AC', 'DA-CR'] priorities = ['DA-AC-ARM', 'DA-AC-TRM'] # priorities for anisotropy correction # get command line stuff if "-h" in args: print main.__doc__ sys.exit() if '-WD' in args: ind = args.index("-WD") dir_path = args[ind + 1] if '-cor' in args: ind = args.index('-cor') cors = args[ind + 1].split(':') # list of required data adjustments for cor in cors: nocorrection.remove('DA-' + cor) corrections.append('DA-' + cor) if '-pri' in args: ind = args.index('-pri') priorities = args[ind + 1].split( ':') # list of required data adjustments for p in priorities: p = 'DA-AC-' + p if '-f' in args: ind = args.index("-f") measfile = args[ind + 1] if '-fsp' in args: ind = args.index("-fsp") infile = args[ind + 1] if '-fsi' in args: ind = args.index("-fsi") sitefile = args[ind + 1] if "-crd" in args: ind = args.index("-crd") coord = args[ind + 1] if coord == 's': coords = ['-1'] if coord == 'g': coords = ['0'] if coord == 't': coords = ['100'] if coord == 'b': coords = ['0', '100'] if "-usr" in args: ind = args.index("-usr") user = sys.argv[ind + 1] else: user = "" if "-C" in args: Dcrit, Icrit, nocrit = 1, 1, 1 # no selection criteria if "-sam" in args: vgps = 1 # save sample level VGPS/VADMs if "-xSi" in args: nositeints = 1 # skip site level intensity else: nositeints = 0 if "-age" in args: ind = args.index("-age") DefaultAge[0] = args[ind + 1] DefaultAge.append(args[ind + 2]) DefaultAge.append(args[ind + 3]) Daverage, Iaverage, Caverage = 0, 0, 0 if "-aD" in args: Daverage = 1 # average by sample directions if "-aI" in args: Iaverage = 1 # average by sample intensities if "-aC" in args: Caverage = 1 # average all components together ??? why??? if "-pol" in args: polarity = 1 # calculate averages by polarity if '-xD' in args: noDir = 1 if '-xI' in args: noInt = 1 elif "-fla" in args: if '-lat' in args: print "you should set a paleolatitude file OR use present day lat - not both" sys.exit() ind = args.index("-fla") model_lat_file = dir_path + '/' + args[ind + 1] get_model_lat = 2 mlat = open(model_lat_file, 'rU') ModelLats = [] for line in mlat.readlines(): ModelLat = {} tmp = line.split() ModelLat["er_site_name"] = tmp[0] ModelLat["site_model_lat"] = tmp[1] ModelLat["er_sample_name"] = tmp[0] ModelLat["sample_lat"] = tmp[1] ModelLats.append(ModelLat) get_model_lat = 2 elif '-lat' in args: get_model_lat = 1 if "-p" in args: plotsites = 1 if "-fmt" in args: ind = args.index("-fmt") fmt = args[ind + 1] if noDir == 0: # plot by site - set up plot window import pmagplotlib EQ = {} EQ['eqarea'] = 1 pmagplotlib.plot_init( EQ['eqarea'], 5, 5) # define figure 1 as equal area projection pmagplotlib.plotNET( EQ['eqarea'] ) # I don't know why this has to be here, but otherwise the first plot never plots... pmagplotlib.drawFIGS(EQ) if '-WD' in args: infile = dir_path + '/' + infile measfile = dir_path + '/' + measfile instout = dir_path + '/' + instout sampfile = dir_path + '/' + sampfile sitefile = dir_path + '/' + sitefile agefile = dir_path + '/' + agefile specout = dir_path + '/' + specout sampout = dir_path + '/' + sampout siteout = dir_path + '/' + siteout resout = dir_path + '/' + resout critout = dir_path + '/' + critout if "-exc" in args: # use existing pmag_criteria file if "-C" in args: print 'you can not use both existing and no criteria - choose either -exc OR -C OR neither (for default)' sys.exit() crit_data, file_type = pmag.magic_read(critout) print "Acceptance criteria read in from ", critout else: # use default criteria (if nocrit set, then get really loose criteria as default) crit_data = pmag.default_criteria(nocrit) if nocrit == 0: print "Acceptance criteria are defaults" else: print "No acceptance criteria used " accept = {} for critrec in crit_data: for key in critrec.keys(): # need to migrate specimen_dang to specimen_int_dang for intensity data using old format if 'IE-SPEC' in critrec.keys() and 'specimen_dang' in critrec.keys( ) and 'specimen_int_dang' not in critrec.keys(): critrec['specimen_int_dang'] = critrec['specimen_dang'] del critrec['specimen_dang'] # need to get rid of ron shaars sample_int_sigma_uT if 'sample_int_sigma_uT' in critrec.keys(): critrec['sample_int_sigma'] = '%10.3e' % ( eval(critrec['sample_int_sigma_uT']) * 1e-6) if key not in accept.keys() and critrec[key] != '': accept[key] = critrec[key] # # if "-exc" not in args and "-C" not in args: print "args", args pmag.magic_write(critout, [accept], 'pmag_criteria') print "\n Pmag Criteria stored in ", critout, '\n' # # now we're done slow dancing # SiteNFO, file_type = pmag.magic_read( sitefile) # read in site data - has the lats and lons SampNFO, file_type = pmag.magic_read( sampfile) # read in site data - has the lats and lons height_nfo = pmag.get_dictitem(SiteNFO, 'site_height', '', 'F') # find all the sites with height info. if agefile != "": AgeNFO, file_type = pmag.magic_read( agefile) # read in the age information Data, file_type = pmag.magic_read( infile) # read in specimen interpretations IntData = pmag.get_dictitem(Data, 'specimen_int', '', 'F') # retrieve specimens with intensity data comment, orient = "", [] samples, sites = [], [] for rec in Data: # run through the data filling in missing keys and finding all components, coordinates available # fill in missing fields, collect unique sample and site names if 'er_sample_name' not in rec.keys(): rec['er_sample_name'] = "" elif rec['er_sample_name'] not in samples: samples.append(rec['er_sample_name']) if 'er_site_name' not in rec.keys(): rec['er_site_name'] = "" elif rec['er_site_name'] not in sites: sites.append(rec['er_site_name']) if 'specimen_int' not in rec.keys(): rec['specimen_int'] = '' if 'specimen_comp_name' not in rec.keys( ) or rec['specimen_comp_name'] == "": rec['specimen_comp_name'] = 'A' if rec['specimen_comp_name'] not in Comps: Comps.append(rec['specimen_comp_name']) rec['specimen_tilt_correction'] = rec[ 'specimen_tilt_correction'].strip('\n') if "specimen_tilt_correction" not in rec.keys(): rec["specimen_tilt_correction"] = "-1" # assume sample coordinates if rec["specimen_tilt_correction"] not in orient: orient.append(rec["specimen_tilt_correction"] ) # collect available coordinate systems if "specimen_direction_type" not in rec.keys(): rec["specimen_direction_type"] = 'l' # assume direction is line - not plane if "specimen_dec" not in rec.keys(): rec["specimen_direction_type"] = '' # if no declination, set direction type to blank if "specimen_n" not in rec.keys(): rec["specimen_n"] = '' # put in n if "specimen_alpha95" not in rec.keys(): rec["specimen_alpha95"] = '' # put in alpha95 if "magic_method_codes" not in rec.keys(): rec["magic_method_codes"] = '' # # start parsing data into SpecDirs, SpecPlanes, SpecInts SpecInts, SpecDirs, SpecPlanes = [], [], [] samples.sort() # get sorted list of samples and sites sites.sort() if noInt == 0: # don't skip intensities IntData = pmag.get_dictitem( Data, 'specimen_int', '', 'F') # retrieve specimens with intensity data if nocrit == 0: # use selection criteria for rec in IntData: # do selection criteria kill = pmag.grade(rec, accept, 'specimen_int') if len(kill) == 0: SpecInts.append( rec ) # intensity record to be included in sample, site calculations else: SpecInts = IntData[:] # take everything - no selection criteria # check for required data adjustments if len(corrections) > 0 and len(SpecInts) > 0: for cor in corrections: SpecInts = pmag.get_dictitem( SpecInts, 'magic_method_codes', cor, 'has') # only take specimens with the required corrections if len(nocorrection) > 0 and len(SpecInts) > 0: for cor in nocorrection: SpecInts = pmag.get_dictitem( SpecInts, 'magic_method_codes', cor, 'not' ) # exclude the corrections not specified for inclusion # take top priority specimen of its name in remaining specimens (only one per customer) PrioritySpecInts = [] specimens = pmag.get_specs(SpecInts) # get list of uniq specimen names for spec in specimens: ThisSpecRecs = pmag.get_dictitem( SpecInts, 'er_specimen_name', spec, 'T') # all the records for this specimen if len(ThisSpecRecs) == 1: PrioritySpecInts.append(ThisSpecRecs[0]) elif len(ThisSpecRecs) > 1: # more than one prec = [] for p in priorities: ThisSpecRecs = pmag.get_dictitem( SpecInts, 'magic_method_codes', p, 'has') # all the records for this specimen if len(ThisSpecRecs) > 0: prec.append(ThisSpecRecs[0]) PrioritySpecInts.append(prec[0]) # take the best one SpecInts = PrioritySpecInts # this has the first specimen record if noDir == 0: # don't skip directions AllDirs = pmag.get_dictitem( Data, 'specimen_direction_type', '', 'F') # retrieve specimens with directed lines and planes Ns = pmag.get_dictitem( AllDirs, 'specimen_n', '', 'F') # get all specimens with specimen_n information if nocrit != 1: # use selection criteria for rec in Ns: # look through everything with specimen_n for "good" data kill = pmag.grade(rec, accept, 'specimen_dir') if len(kill) == 0: # nothing killed it SpecDirs.append(rec) else: # no criteria SpecDirs = AllDirs[:] # take them all # SpecDirs is now the list of all specimen directions (lines and planes) that pass muster # PmagSamps, SampDirs = [], [ ] # list of all sample data and list of those that pass the DE-SAMP criteria PmagSites, PmagResults = [], [ ] # list of all site data and selected results SampInts = [] for samp in samples: # run through the sample names if Daverage == 1: # average by sample if desired SampDir = pmag.get_dictitem( SpecDirs, 'er_sample_name', samp, 'T') # get all the directional data for this sample if len(SampDir) > 0: # there are some directions for coord in coords: # step through desired coordinate systems CoordDir = pmag.get_dictitem( SampDir, 'specimen_tilt_correction', coord, 'T') # get all the directions for this sample if len(CoordDir ) > 0: # there are some with this coordinate system if Caverage == 0: # look component by component for comp in Comps: CompDir = pmag.get_dictitem( CoordDir, 'specimen_comp_name', comp, 'T' ) # get all directions from this component if len(CompDir) > 0: # there are some PmagSampRec = pmag.lnpbykey( CompDir, 'sample', 'specimen' ) # get a sample average from all specimens PmagSampRec["er_location_name"] = CompDir[0][ 'er_location_name'] # decorate the sample record PmagSampRec["er_site_name"] = CompDir[0][ 'er_site_name'] PmagSampRec["er_sample_name"] = samp PmagSampRec[ "er_citation_names"] = "This study" PmagSampRec["er_analyst_mail_names"] = user PmagSampRec[ 'magic_software_packages'] = version_num if nocrit != 1: PmagSampRec[ 'pmag_criteria_codes'] = "ACCEPT" if agefile != "": PmagSampRec = pmag.get_age( PmagSampRec, "er_site_name", "sample_inferred_", AgeNFO, DefaultAge) site_height = pmag.get_dictitem( height_nfo, 'er_site_name', PmagSampRec['er_site_name'], 'T') if len(site_height) > 0: PmagSampRec[ "sample_height"] = site_height[0][ 'site_height'] # add in height if available PmagSampRec['sample_comp_name'] = comp PmagSampRec[ 'sample_tilt_correction'] = coord PmagSampRec[ 'er_specimen_names'] = pmag.get_list( CompDir, 'er_specimen_name' ) # get a list of the specimen names used PmagSampRec[ 'magic_method_codes'] = pmag.get_list( CompDir, 'magic_method_codes' ) # get a list of the methods used if nocrit != 1: # apply selection criteria kill = pmag.grade( PmagSampRec, accept, 'sample_dir') else: kill = [] if len(kill) == 0: SampDirs.append(PmagSampRec) if vgps == 1: # if sample level VGP info desired, do that now PmagResRec = pmag.getsampVGP( PmagSampRec, SiteNFO) if PmagResRec != "": PmagResults.append(PmagResRec) PmagSamps.append(PmagSampRec) if Caverage == 1: # average all components together basically same as above PmagSampRec = pmag.lnpbykey( CoordDir, 'sample', 'specimen') PmagSampRec["er_location_name"] = CoordDir[0][ 'er_location_name'] PmagSampRec["er_site_name"] = CoordDir[0][ 'er_site_name'] PmagSampRec["er_sample_name"] = samp PmagSampRec["er_citation_names"] = "This study" PmagSampRec["er_analyst_mail_names"] = user PmagSampRec[ 'magic_software_packages'] = version_num if nocrit != 1: PmagSampRec['pmag_criteria_codes'] = "" if agefile != "": PmagSampRec = pmag.get_age( PmagSampRec, "er_site_name", "sample_inferred_", AgeNFO, DefaultAge) site_height = pmag.get_dictitem( height_nfo, 'er_site_name', site, 'T') if len(site_height) > 0: PmagSampRec["sample_height"] = site_height[0][ 'site_height'] # add in height if available PmagSampRec['sample_tilt_correction'] = coord PmagSampRec['sample_comp_name'] = pmag.get_list( CoordDir, 'specimen_comp_name') # get components used PmagSampRec['er_specimen_names'] = pmag.get_list( CoordDir, 'er_specimen_name' ) # get specimne names averaged PmagSampRec['magic_method_codes'] = pmag.get_list( CoordDir, 'magic_method_codes') # assemble method codes if nocrit != 1: # apply selection criteria kill = pmag.grade(PmagSampRec, accept, 'sample_dir') if len(kill) == 0: # passes the mustard SampDirs.append(PmagSampRec) if vgps == 1: PmagResRec = pmag.getsampVGP( PmagSampRec, SiteNFO) if PmagResRec != "": PmagResults.append(PmagResRec) else: # take everything SampDirs.append(PmagSampRec) if vgps == 1: PmagResRec = pmag.getsampVGP( PmagSampRec, SiteNFO) if PmagResRec != "": PmagResults.append(PmagResRec) PmagSamps.append(PmagSampRec) if Iaverage == 1: # average by sample if desired SampI = pmag.get_dictitem( SpecInts, 'er_sample_name', samp, 'T') # get all the intensity data for this sample if len(SampI) > 0: # there are some PmagSampRec = pmag.average_int( SampI, 'specimen', 'sample') # get average intensity stuff PmagSampRec[ "sample_description"] = "sample intensity" # decorate sample record PmagSampRec["sample_direction_type"] = "" PmagSampRec['er_site_name'] = SampI[0]["er_site_name"] PmagSampRec['er_sample_name'] = samp PmagSampRec['er_location_name'] = SampI[0]["er_location_name"] PmagSampRec["er_citation_names"] = "This study" PmagSampRec["er_analyst_mail_names"] = user if agefile != "": PmagSampRec = pmag.get_age(PmagSampRec, "er_site_name", "sample_inferred_", AgeNFO, DefaultAge) site_height = pmag.get_dictitem(height_nfo, 'er_site_name', PmagSampRec['er_site_name'], 'T') if len(site_height) > 0: PmagSampRec["sample_height"] = site_height[0][ 'site_height'] # add in height if available PmagSampRec['er_specimen_names'] = pmag.get_list( SampI, 'er_specimen_name') PmagSampRec['magic_method_codes'] = pmag.get_list( SampI, 'magic_method_codes') if nocrit != 1: # apply criteria! kill = pmag.grade(PmagSampRec, accept, 'sample_int') if len(kill) == 0: PmagSampRec['pmag_criteria_codes'] = "ACCEPT" SampInts.append(PmagSampRec) PmagSamps.append(PmagSampRec) else: PmagSampRec = {} # sample rejected else: # no criteria SampInts.append(PmagSampRec) PmagSamps.append(PmagSampRec) PmagSampRec['pmag_criteria_codes'] = "" if vgps == 1 and get_model_lat != 0 and PmagSampRec != {}: # if get_model_lat == 1: # use sample latitude PmagResRec = pmag.getsampVDM(PmagSampRec, SampNFO) del (PmagResRec['model_lat'] ) # get rid of the model lat key elif get_model_lat == 2: # use model latitude PmagResRec = pmag.getsampVDM(PmagSampRec, ModelLats) if PmagResRec != {}: PmagResRec['magic_method_codes'] = PmagResRec[ 'magic_method_codes'] + ":IE-MLAT" if PmagResRec != {}: PmagResRec['er_specimen_names'] = PmagSampRec[ 'er_specimen_names'] PmagResRec['er_sample_names'] = PmagSampRec[ 'er_sample_name'] PmagResRec['pmag_criteria_codes'] = 'ACCEPT' PmagResRec['average_int_sigma_perc'] = PmagSampRec[ 'sample_int_sigma_perc'] PmagResRec['average_int_sigma'] = PmagSampRec[ 'sample_int_sigma'] PmagResRec['average_int_n'] = PmagSampRec[ 'sample_int_n'] PmagResRec['vadm_n'] = PmagSampRec['sample_int_n'] PmagResRec['data_type'] = 'i' PmagResults.append(PmagResRec) if len(PmagSamps) > 0: TmpSamps, keylist = pmag.fillkeys( PmagSamps) # fill in missing keys from different types of records pmag.magic_write(sampout, TmpSamps, 'pmag_samples') # save in sample output file print ' sample averages written to ', sampout # #create site averages from specimens or samples as specified # for site in sites: if Daverage == 0: key, dirlist = 'specimen', SpecDirs # if specimen averages at site level desired if Daverage == 1: key, dirlist = 'sample', SampDirs # if sample averages at site level desired tmp = pmag.get_dictitem(dirlist, 'er_site_name', site, 'T') # get all the sites with directions tmp1 = pmag.get_dictitem( tmp, key + '_tilt_correction', coords[-1], 'T') # use only the last coordinate if Caverage==0 sd = pmag.get_dictitem( SiteNFO, 'er_site_name', site, 'T') # fish out site information (lat/lon, etc.) if len(sd) > 0: sitedat = sd[0] if Caverage == 0: # do component wise averaging for comp in Comps: siteD = pmag.get_dictitem(tmp1, key + '_comp_name', comp, 'T') # get all components comp if len( siteD ) > 0: # there are some for this site and component name PmagSiteRec = pmag.lnpbykey( siteD, 'site', key) # get an average for this site PmagSiteRec[ 'site_comp_name'] = comp # decorate the site record PmagSiteRec["er_location_name"] = siteD[0][ 'er_location_name'] PmagSiteRec["er_site_name"] = siteD[0]['er_site_name'] PmagSiteRec['site_tilt_correction'] = coords[-1] PmagSiteRec['site_comp_name'] = pmag.get_list( siteD, key + '_comp_name') if Daverage == 1: PmagSiteRec['er_sample_names'] = pmag.get_list( siteD, 'er_sample_name') else: PmagSiteRec['er_specimen_names'] = pmag.get_list( siteD, 'er_specimen_name') # determine the demagnetization code (DC3,4 or 5) for this site AFnum = len( pmag.get_dictitem(siteD, 'magic_method_codes', 'LP-DIR-AF', 'has')) Tnum = len( pmag.get_dictitem(siteD, 'magic_method_codes', 'LP-DIR-T', 'has')) DC = 3 if AFnum > 0: DC += 1 if Tnum > 0: DC += 1 PmagSiteRec['magic_method_codes'] = pmag.get_list( siteD, 'magic_method_codes') + ':' + 'LP-DC' + str(DC) PmagSiteRec['magic_method_codes'].strip(":") if plotsites == 1: print PmagSiteRec['er_site_name'] pmagplotlib.plotSITE(EQ['eqarea'], PmagSiteRec, siteD, key) # plot and list the data pmagplotlib.drawFIGS(EQ) PmagSites.append(PmagSiteRec) else: # last component only siteD = tmp1[:] # get the last orientation system specified if len(siteD) > 0: # there are some PmagSiteRec = pmag.lnpbykey( siteD, 'site', key) # get the average for this site PmagSiteRec["er_location_name"] = siteD[0][ 'er_location_name'] # decorate the record PmagSiteRec["er_site_name"] = siteD[0]['er_site_name'] PmagSiteRec['site_comp_name'] = comp PmagSiteRec['site_tilt_correction'] = coords[-1] PmagSiteRec['site_comp_name'] = pmag.get_list( siteD, key + '_comp_name') PmagSiteRec['er_specimen_names'] = pmag.get_list( siteD, 'er_specimen_name') PmagSiteRec['er_sample_names'] = pmag.get_list( siteD, 'er_sample_name') AFnum = len( pmag.get_dictitem(siteD, 'magic_method_codes', 'LP-DIR-AF', 'has')) Tnum = len( pmag.get_dictitem(siteD, 'magic_method_codes', 'LP-DIR-T', 'has')) DC = 3 if AFnum > 0: DC += 1 if Tnum > 0: DC += 1 PmagSiteRec['magic_method_codes'] = pmag.get_list( siteD, 'magic_method_codes') + ':' + 'LP-DC' + str(DC) PmagSiteRec['magic_method_codes'].strip(":") if Daverage == 0: PmagSiteRec['site_comp_name'] = pmag.get_list( siteD, key + '_comp_name') if plotsites == 1: pmagplotlib.plotSITE(EQ['eqarea'], PmagSiteRec, siteD, key) pmagplotlib.drawFIGS(EQ) PmagSites.append(PmagSiteRec) else: print 'site information not found in er_sites for site, ', site, ' site will be skipped' for PmagSiteRec in PmagSites: # now decorate each dictionary some more, and calculate VGPs etc. for results table PmagSiteRec["er_citation_names"] = "This study" PmagSiteRec["er_analyst_mail_names"] = user PmagSiteRec['magic_software_packages'] = version_num if agefile != "": PmagSiteRec = pmag.get_age(PmagSiteRec, "er_site_name", "site_inferred_", AgeNFO, DefaultAge) PmagSiteRec['pmag_criteria_codes'] = 'ACCEPT' if 'site_n_lines' in PmagSiteRec.keys( ) and 'site_n_planes' in PmagSiteRec.keys() and PmagSiteRec[ 'site_n_lines'] != "" and PmagSiteRec['site_n_planes'] != "": if int(PmagSiteRec["site_n_planes"]) > 0: PmagSiteRec["magic_method_codes"] = PmagSiteRec[ 'magic_method_codes'] + ":DE-FM-LP" elif int(PmagSiteRec["site_n_lines"]) > 2: PmagSiteRec["magic_method_codes"] = PmagSiteRec[ 'magic_method_codes'] + ":DE-FM" kill = pmag.grade(PmagSiteRec, accept, 'site_dir') if len(kill) == 0: PmagResRec = { } # set up dictionary for the pmag_results table entry PmagResRec['data_type'] = 'i' # decorate it a bit PmagResRec['magic_software_packages'] = version_num PmagSiteRec[ 'site_description'] = 'Site direction included in results table' PmagResRec['pmag_criteria_codes'] = 'ACCEPT' dec = float(PmagSiteRec["site_dec"]) inc = float(PmagSiteRec["site_inc"]) if 'site_alpha95' in PmagSiteRec.keys( ) and PmagSiteRec['site_alpha95'] != "": a95 = float(PmagSiteRec["site_alpha95"]) else: a95 = 180. sitedat = pmag.get_dictitem( SiteNFO, 'er_site_name', PmagSiteRec['er_site_name'], 'T')[0] # fish out site information (lat/lon, etc.) lat = float(sitedat['site_lat']) lon = float(sitedat['site_lon']) plong, plat, dp, dm = pmag.dia_vgp( dec, inc, a95, lat, lon) # get the VGP for this site if PmagSiteRec['site_tilt_correction'] == '-1': C = ' (spec coord) ' if PmagSiteRec['site_tilt_correction'] == '0': C = ' (geog. coord) ' if PmagSiteRec['site_tilt_correction'] == '100': C = ' (strat. coord) ' PmagResRec["pmag_result_name"] = "VGP Site: " + PmagSiteRec[ "er_site_name"] # decorate some more PmagResRec[ "result_description"] = "Site VGP, coord system = " + str( coord) + ' component: ' + comp PmagResRec['er_site_names'] = PmagSiteRec['er_site_name'] PmagResRec['pmag_criteria_codes'] = 'ACCEPT' PmagResRec['er_citation_names'] = 'This study' PmagResRec['er_analyst_mail_names'] = user PmagResRec["er_location_names"] = PmagSiteRec[ "er_location_name"] if Daverage == 1: PmagResRec["er_sample_names"] = PmagSiteRec[ "er_sample_names"] else: PmagResRec["er_specimen_names"] = PmagSiteRec[ "er_specimen_names"] PmagResRec["tilt_correction"] = PmagSiteRec[ 'site_tilt_correction'] PmagResRec["pole_comp_name"] = PmagSiteRec['site_comp_name'] PmagResRec["average_dec"] = PmagSiteRec["site_dec"] PmagResRec["average_inc"] = PmagSiteRec["site_inc"] PmagResRec["average_alpha95"] = PmagSiteRec["site_alpha95"] PmagResRec["average_n"] = PmagSiteRec["site_n"] PmagResRec["average_n_lines"] = PmagSiteRec["site_n_lines"] PmagResRec["average_n_planes"] = PmagSiteRec["site_n_planes"] PmagResRec["vgp_n"] = PmagSiteRec["site_n"] PmagResRec["average_k"] = PmagSiteRec["site_k"] PmagResRec["average_r"] = PmagSiteRec["site_r"] PmagResRec["average_lat"] = '%10.4f ' % (lat) PmagResRec["average_lon"] = '%10.4f ' % (lon) if agefile != "": PmagResRec = pmag.get_age(PmagResRec, "er_site_names", "average_", AgeNFO, DefaultAge) site_height = pmag.get_dictitem(height_nfo, 'er_site_name', site, 'T') if len(site_height) > 0: PmagResRec["average_height"] = site_height[0][ 'site_height'] PmagResRec["vgp_lat"] = '%7.1f ' % (plat) PmagResRec["vgp_lon"] = '%7.1f ' % (plong) PmagResRec["vgp_dp"] = '%7.1f ' % (dp) PmagResRec["vgp_dm"] = '%7.1f ' % (dm) PmagResRec["magic_method_codes"] = PmagSiteRec[ "magic_method_codes"] if PmagSiteRec['site_tilt_correction'] == '0': PmagSiteRec['magic_method_codes'] = PmagSiteRec[ 'magic_method_codes'] + ":DA-DIR-GEO" if PmagSiteRec['site_tilt_correction'] == '100': PmagSiteRec['magic_method_codes'] = PmagSiteRec[ 'magic_method_codes'] + ":DA-DIR-TILT" PmagSiteRec['site_polarity'] = "" if polarity == 1: # assign polarity based on angle of pole lat to spin axis - may want to re-think this sometime angle = pmag.angle([0, 0], [0, (90 - plat)]) if angle <= 55.: PmagSiteRec["site_polarity"] = 'n' if angle > 55. and angle < 125.: PmagSiteRec["site_polarity"] = 't' if angle >= 125.: PmagSiteRec["site_polarity"] = 'r' PmagResults.append(PmagResRec) if polarity == 1: crecs = pmag.get_dictitem(PmagSites, 'site_tilt_correction', '100', 'T') # find the tilt corrected data if len(crecs) < 2: crecs = pmag.get_dictitem( PmagSites, 'site_tilt_correction', '0', 'T') # if there aren't any, find the geographic corrected data if len(crecs) > 2: # if there are some, comp = pmag.get_list( crecs, 'site_comp_name').split(':')[0] # find the first component crecs = pmag.get_dictitem( crecs, 'site_comp_name', comp, 'T') # fish out all of the first component precs = [] for rec in crecs: precs.append({ 'dec': rec['site_dec'], 'inc': rec['site_inc'], 'name': rec['er_site_name'], 'loc': rec['er_location_name'] }) polpars = pmag.fisher_by_pol( precs) # calculate average by polarity for mode in polpars.keys( ): # hunt through all the modes (normal=A, reverse=B, all=ALL) PolRes = {} PolRes['er_citation_names'] = 'This study' PolRes[ "pmag_result_name"] = "Polarity Average: Polarity " + mode # PolRes["data_type"] = "a" PolRes["average_dec"] = '%7.1f' % (polpars[mode]['dec']) PolRes["average_inc"] = '%7.1f' % (polpars[mode]['inc']) PolRes["average_n"] = '%i' % (polpars[mode]['n']) PolRes["average_r"] = '%5.4f' % (polpars[mode]['r']) PolRes["average_k"] = '%6.0f' % (polpars[mode]['k']) PolRes["average_alpha95"] = '%7.1f' % ( polpars[mode]['alpha95']) PolRes['er_site_names'] = polpars[mode]['sites'] PolRes['er_location_names'] = polpars[mode]['locs'] PolRes['magic_software_packages'] = version_num PmagResults.append(PolRes) if noInt != 1 and nositeints != 1: for site in sites: # now do intensities for each site if plotsites == 1: print site if Iaverage == 0: key, intlist = 'specimen', SpecInts # if using specimen level data if Iaverage == 1: key, intlist = 'sample', PmagSamps # if using sample level data Ints = pmag.get_dictitem( intlist, 'er_site_name', site, 'T') # get all the intensities for this site if len(Ints) > 0: # there are some PmagSiteRec = pmag.average_int( Ints, key, 'site') # get average intensity stuff for site table PmagResRec = pmag.average_int( Ints, key, 'average') # get average intensity stuff for results table if plotsites == 1: # if site by site examination requested - print this site out to the screen for rec in Ints: print rec['er_' + key + '_name'], ' %7.1f' % ( 1e6 * float(rec[key + '_int'])) if len(Ints) > 1: print 'Average: ', '%7.1f' % (1e6 * float( PmagResRec['average_int'])), 'N: ', len(Ints) print 'Sigma: ', '%7.1f' % ( 1e6 * float(PmagResRec['average_int_sigma']) ), 'Sigma %: ', PmagResRec['average_int_sigma_perc'] raw_input('Press any key to continue\n') er_location_name = Ints[0]["er_location_name"] PmagSiteRec[ "er_location_name"] = er_location_name # decorate the records PmagSiteRec["er_citation_names"] = "This study" PmagResRec["er_location_names"] = er_location_name PmagResRec["er_citation_names"] = "This study" PmagSiteRec["er_analyst_mail_names"] = user PmagResRec["er_analyst_mail_names"] = user PmagResRec["data_type"] = 'i' if Iaverage == 0: PmagSiteRec['er_specimen_names'] = pmag.get_list( Ints, 'er_specimen_name') # list of all specimens used PmagResRec['er_specimen_names'] = pmag.get_list( Ints, 'er_specimen_name') PmagSiteRec['er_sample_names'] = pmag.get_list( Ints, 'er_sample_name') # list of all samples used PmagResRec['er_sample_names'] = pmag.get_list( Ints, 'er_sample_name') PmagSiteRec['er_site_name'] = site PmagResRec['er_site_names'] = site PmagSiteRec['magic_method_codes'] = pmag.get_list( Ints, 'magic_method_codes') PmagResRec['magic_method_codes'] = pmag.get_list( Ints, 'magic_method_codes') kill = pmag.grade(PmagSiteRec, accept, 'site_int') if nocrit == 1 or len(kill) == 0: b, sig = float(PmagResRec['average_int']), "" if (PmagResRec['average_int_sigma']) != "": sig = float(PmagResRec['average_int_sigma']) sdir = pmag.get_dictitem(PmagResults, 'er_site_names', site, 'T') # fish out site direction if len(sdir) > 0 and sdir[-1][ 'average_inc'] != "": # get the VDM for this record using last average inclination (hope it is the right one!) inc = float(sdir[0]['average_inc']) # mlat = pmag.magnetic_lat( inc) # get magnetic latitude using dipole formula PmagResRec["vdm"] = '%8.3e ' % (pmag.b_vdm( b, mlat)) # get VDM with magnetic latitude PmagResRec["vdm_n"] = PmagResRec['average_int_n'] if 'average_int_sigma' in PmagResRec.keys( ) and PmagResRec['average_int_sigma'] != "": vdm_sig = pmag.b_vdm( float(PmagResRec['average_int_sigma']), mlat) PmagResRec["vdm_sigma"] = '%8.3e ' % (vdm_sig) else: PmagResRec["vdm_sigma"] = "" mlat = "" # define a model latitude if get_model_lat == 1: # use present site latitude mlats = pmag.get_dictitem(SiteNFO, 'er_site_name', site, 'T') if len(mlats) > 0: mlat = mlats[0]['site_lat'] elif get_model_lat == 2: # use a model latitude from some plate reconstruction model (or something) mlats = pmag.get_dictitem(ModelLats, 'er_site_name', site, 'T') if len(mlats) > 0: PmagResRec['model_lat'] = mlats[0][ 'site_model_lat'] mlat = PmagResRec['model_lat'] if mlat != "": PmagResRec["vadm"] = '%8.3e ' % ( pmag.b_vdm(b, float(mlat)) ) # get the VADM using the desired latitude if sig != "": vdm_sig = pmag.b_vdm( float(PmagResRec['average_int_sigma']), float(mlat)) PmagResRec["vadm_sigma"] = '%8.3e ' % (vdm_sig) PmagResRec["vadm_n"] = PmagResRec['average_int_n'] else: PmagResRec["vadm_sigma"] = "" sitedat = pmag.get_dictitem( SiteNFO, 'er_site_name', PmagSiteRec['er_site_name'], 'T') # fish out site information (lat/lon, etc.) if len(sitedat) > 0: sitedat = sitedat[0] PmagResRec['average_lat'] = sitedat['site_lat'] PmagResRec['average_lon'] = sitedat['site_lon'] else: PmagResRec['average_lon'] = 'UNKNOWN' PmagResRec['average_lon'] = 'UNKNOWN' PmagResRec['magic_software_packages'] = version_num PmagResRec["pmag_result_name"] = "V[A]DM: Site " + site PmagResRec["result_description"] = "V[A]DM of site" PmagResRec["pmag_criteria_codes"] = "ACCEPT" if agefile != "": PmagResRec = pmag.get_age(PmagResRec, "er_site_names", "average_", AgeNFO, DefaultAge) site_height = pmag.get_dictitem(height_nfo, 'er_site_name', site, 'T') if len(site_height) > 0: PmagResRec["average_height"] = site_height[0][ 'site_height'] PmagSites.append(PmagSiteRec) PmagResults.append(PmagResRec) if len(PmagSites) > 0: Tmp, keylist = pmag.fillkeys(PmagSites) pmag.magic_write(siteout, Tmp, 'pmag_sites') print ' sites written to ', siteout else: print "No Site level table" if len(PmagResults) > 0: TmpRes, keylist = pmag.fillkeys(PmagResults) pmag.magic_write(resout, TmpRes, 'pmag_results') print ' results written to ', resout else: print "No Results level table"
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 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_key='er_location_name' if len(sys.argv)>1: if '-h' in sys.argv: print main.__doc__ sys.exit() if '-N' in sys.argv: norm=0 if '-f' in sys.argv: ind=sys.argv.index("-f") in_file=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 # # get plotlist # 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 plot in plotlist: print plot,'plotting by: ',plot_key PLTblock=pmag.get_dictitem(data,plot_key,plot,'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) 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 watson_common_mean(Data1, Data2, NumSims=5000, plot='no'): """ Conduct a Watson V test for a common mean on two declination, inclination data sets This function calculates Watson's V statistic from input files through Monte Carlo simulation in order to test whether two populations of directional data could have been drawn from a common mean. The critical angle between the two sample mean directions and the corresponding McFadden and McElhinny (1990) classification is printed. Required Arguments ---------- Data1 : a list of directional data [dec,inc] Data2 : a list of directional data [dec,inc] Optional Arguments ---------- NumSims : number of Monte Carlo simulations (default is 5000) plot : the default is no plot ('no'). Putting 'yes' will the plot the CDF from the Monte Carlo simulations. """ pars_1 = pmag.fisher_mean(Data1) pars_2 = pmag.fisher_mean(Data2) 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 = np.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 as data, # but a common mean counter = 0 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 - (Vcrit / 2) # following equation 19 of McFadden and McElhinny (1990) the critical # angle is calculated. If the observed angle (also calculated below) # between the data set means exceeds the critical angle the hypothesis # of a common mean direction may be rejected at the 95% confidence # level. The critical angle is simply a different way to present # Watson's V parameter so it makes sense to use the Watson V parameter # in comparison with the critical value of V for considering the test # results. What calculating the critical angle allows for is the # classification of McFadden and McElhinny (1990) to be made # for data sets that are consistent with sharing a common mean. k1 = pars_1['k'] k2 = pars_2['k'] R1 = pars_1['r'] R2 = pars_2['r'] critical_angle = np.degrees( np.arccos(((Rwc**2) - ((k1 * R1)**2) - ((k2 * R2)**2)) / (2 * k1 * R1 * k2 * R2))) D1 = (pars_1['dec'], pars_1['inc']) D2 = (pars_2['dec'], pars_2['inc']) angle = pmag.angle(D1, D2) 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' print 'that the two populations are drawn from distributions' print 'that share a common mean direction can not be rejected.' elif V > Vcrit: print '"Fail": Since V is greater than Vcrit, the two means can' print 'be distinguished at the 95% confidence level.' print "" print "M&M1990 classification:" print "" print "Angle between data set means: " '%.1f' % (angle) print "Critical angle for M&M1990: " '%.1f' % (critical_angle) if V > Vcrit: print "" elif V < Vcrit: if critical_angle < 5: print "The McFadden and McElhinny (1990) classification for" print "this test is: 'A'" elif critical_angle < 10: print "The McFadden and McElhinny (1990) classification for" print "this test is: 'B'" elif critical_angle < 20: print "The McFadden and McElhinny (1990) classification for" print "this test is: 'C'" else: print "The McFadden and McElhinny (1990) classification for" print "this test is: 'INDETERMINATE;" if plot == 'yes': 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)
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 curie.py DESCTIPTION plots and interprets curie temperature data. the 1st derivative is calculated from smoothed M-T curve (convolution with trianfular window with width= <-w> degrees) the 2nd derivative is calculated from smoothed 1st derivative curve ( using the same sliding window width) the estinated curie temp. is the maximum of the 2nd derivative - the temperature steps should be in multiples of 1.0 degrees INPUT T,M SYNTAX curie.py [command line options] OPTIONS -h prints help message and quits -f FILE, sets M,T input file (required) -w size of sliding window in degrees (default - 3 degrees) -t <min> <max> temperature range (optional) example: curie.py -f ex2.1 -w 30 -t 300 700 """ 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] else: print "missing -f\n" sys.exit() if '-w' in sys.argv: ind=sys.argv.index('-w') window_len=int(sys.argv[ind+1]) else: window_len=3 if '-t' in sys.argv: ind=sys.argv.index('-t') t_begin=int(sys.argv[ind+1]) t_end=int(sys.argv[ind+2]) else: t_begin='' t_end='' # read data from file Data=numpy.loadtxt(meas_file,dtype=numpy.float) T=Data.transpose()[0] M=Data.transpose()[1] # cut the data if -t is one of the flags if t_begin: while T[0]<t_begin: M.pop(0);T.pop(0) while T[-1]>t_end: M.pop(-1);T.pop(-1) # prepare the signal: # from M(T) array with unequal deltaT # to M(T) array with deltaT=(1 degree). # if delataT is larger, then points are added using linear fit between # consecutive data points. # exit if deltaT is not integer i=0 while i<(len(T)-1): if (T[i+1]-T[i])%1>0.001: print "delta T should be integer, this program will not work!" print "temperature range:",T[i],T[i+1] sys.exit() if (T[i+1]-T[i])==0.: M[i]=average([M[i],M[i+1]]) M.pop(i+1);T.pop(i+1) elif (T[i+1]-T[i])<0.: M.pop(i+1);T.pop(i+1) print "check data in T=%.0f ,M[T] is ignored"%(T[i]) elif (T[i+1]-T[i])>1.: slope,b=polyfit([T[i],T[i+1]],[M[i],M[i+1]],1) for j in range(int(T[i+1])-int(T[i])-1): M.insert(i+1,slope*(T[i]+1.)+b) T.insert(i+1,(T[i]+1.)) i=i+1 i=i+1 # calculate the smoothed signal M=array(M,'f') T=array(T,'f') M_smooth=[] M_smooth=smooth(M,window_len) #plot the original data and the smooth data PLT={'M_T':1,'der1':2,'der2':3,'Curie':4} pmagplotlib.plot_init(PLT['M_T'],5,5) string='M-T (sliding window=%i)'%int(window_len) pmagplotlib.plotXY(PLT['M_T'],T,M_smooth,sym='-') pmagplotlib.plotXY(PLT['M_T'],T,M,sym='--',xlab='Temperature C',ylab='Magnetization',title=string) #calculate first derivative d1,T_d1=[],[] for i in range(len(M_smooth)-1): Dy=M_smooth[i-1]-M_smooth[i+1] Dx=T[i-1]-T[i+1] d1.append(Dy/Dx) T_d1=T[1:len(T-1)] d1=array(d1,'f') d1_smooth=smooth(d1,window_len) #plot the first derivative pmagplotlib.plot_init(PLT['der1'],5,5) string='1st dervative (sliding window=%i)'%int(window_len) pmagplotlib.plotXY(PLT['der1'],T_d1,d1_smooth,sym='-',xlab='Temperature C',title=string) pmagplotlib.plotXY(PLT['der1'],T_d1,d1,sym='b--') #calculate second derivative d2,T_d2=[],[] for i in range(len(d1_smooth)-1): Dy=d1_smooth[i-1]-d1_smooth[i+1] Dx=T[i-1]-T[i+1] #print Dy/Dx d2.append(Dy/Dx) T_d2=T[2:len(T-2)] d2=array(d2,'f') d2_smooth=smooth(d2,window_len) #plot the second derivative pmagplotlib.plot_init(PLT['der2'],5,5) string='2nd dervative (sliding window=%i)'%int(window_len) pmagplotlib.plotXY(PLT['der2'],T_d2,d2,sym='-',xlab='Temperature C',title=string) d2=list(d2) print 'second deriative maximum is at T=%i'%int(T_d2[d2.index(max(d2))]) # calculate Curie temperature for different width of sliding windows curie,curie_1=[],[] wn=range(5,50,1) for win in wn: # calculate the smoothed signal M_smooth=[] M_smooth=smooth(M,win) #calculate first derivative d1,T_d1=[],[] for i in range(len(M_smooth)-1): Dy=M_smooth[i-1]-M_smooth[i+1] Dx=T[i-1]-T[i+1] d1.append(Dy/Dx) T_d1=T[1:len(T-1)] d1=array(d1,'f') d1_smooth=smooth(d1,win) #calculate second derivative d2,T_d2=[],[] for i in range(len(d1_smooth)-1): Dy=d1_smooth[i-1]-d1_smooth[i+1] Dx=T[i-1]-T[i+1] d2.append(Dy/Dx) T_d2=T[2:len(T-2)] d2=array(d2,'f') d2_smooth=smooth(d2,win) d2=list(d2) d2_smooth=list(d2_smooth) curie.append(T_d2[d2.index(max(d2))]) curie_1.append(T_d2[d2_smooth.index(max(d2_smooth))]) #plot Curie temp for different sliding window length pmagplotlib.plot_init(PLT['Curie'],5,5) pmagplotlib.plotXY(PLT['Curie'],wn,curie,sym='.',xlab='Sliding Window Width (degrees)',ylab='Curie Temp',title='Curie Statistics') pmagplotlib.drawFIGS(PLT) 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 PLT.keys(): files[key]=str(key) + ".svg" pmagplotlib.saveP(PLT,files)
def main(): """ NAME revtest_magic.py DESCRIPTION calculates bootstrap statistics to test for antipodality INPUT FORMAT takes dec/inc data from pmag_sites table SYNTAX revtest_magic.py [command line options] OPTION -h prints help message and quits -f FILE, sets pmag_sites filename on command line -crd [s,g,t], set coordinate system, default is geographic -exc use pmag_criteria.txt to set acceptance criteria -fmt [svg,png,jpg], sets format for image output """ D,fmt=[],'svg' coord='0' infile='pmag_sites.txt' critfile='pmag_criteria.txt' dir_path='.' if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit 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') infile=sys.argv[ind+1] if '-crd' in sys.argv: ind=sys.argv.index('-crd') coord=sys.argv[ind+1] if coord=='s':coord='-1' if coord=='g':coord='0' if coord=='t':coord='100' if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] # infile=dir_path+'/'+infile critfile=dir_path+'/'+critfile Accept=['site_k','site_alpha95','site_n','site_n_lines'] data,file_type=pmag.magic_read(infile) if file_type!='pmag_sites': print "Error opening file" sys.exit() # ordata,file_type=pmag.magic_read(orfile) if '-exc' in sys.argv: crits,file_type=pmag.magic_read(critfile) for crit in crits: if crit['pmag_criteria_code']=="DE-SITE": SiteCrit=crit for rec in data: if rec['site_tilt_correction']==coord: Dec=float(rec['site_dec']) Inc=float(rec['site_inc']) if '-exc' in sys.argv: for key in Accept: if SiteCrit[key]!="": if float(rec[key])<=float(SiteCrit[key]): D.append([Dec,Inc,1.]) else: D.append([Dec,Inc,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 # if len(D1) < 5 or len(D2) < 5: print 'not enough data in two different modes for reversals test' sys.exit() print 'doing first mode, be patient' BDI1=pmag.di_boot(D1) print 'doing second mode, be patient' BDI2=pmag.di_boot(D2) pmagplotlib.plotCOM(CDF,BDI1,BDI2,[""]) pmagplotlib.drawFIGS(CDF) ans= raw_input("s[a]ve plots, [q]uit: ") if ans=='a': files={} for key in CDF.keys(): files[key]='REV'+'_'+key+'.'+fmt pmagplotlib.saveP(CDF,files) else: print 'good bye' sys.exit()
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 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 '-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) 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) # 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) 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 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] -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 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 '-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 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 '-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) 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) 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) 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) 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) pmagplotlib.drawFIGS(FIG) Opts['sym']='g^' Opts['symsize']=5 pmagplotlib.plotMAP(FIG['map'],[pole[0]],[pole[1]],Opts) pmagplotlib.drawFIGS(FIG) files={} for key in FIG.keys(): files[key]='Cont_rot'+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='Site Map' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) else: ans=raw_input(" S[a]ve to save plot, Return to quit: ") if ans=="a": pmagplotlib.saveP(FIG,files)
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] [-i] [command line options] OPTION -h prints help message and quits -i for interactive entry of file names from command line -f FILE, sets input filename on command line -fmt [svg,png,jpg], sets format for image output """ D,fmt=[],'svg' if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file=raw_input("Enter file name with dec, inc data: ") f=open(file,'rU') data=f.readlines() elif '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'rU') data=f.readlines() if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] for line in data: if '\t' in line: rec=line.split('\t') # split each line on space to get records else: rec=line.split() # split each line on space to get records Dec,Inc=float(rec[0]),float(rec[1]) D.append([Dec,Inc,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,[""]) pmagplotlib.drawFIGS(CDF) ans= raw_input("s[a]ve plots, [q]uit: ") if ans=='a': files={} for key in CDF.keys(): files[key]='REV'+'_'+key+'.'+fmt pmagplotlib.saveP(CDF,files) else: print 'good bye' sys.exit()
def watson_common_mean(Data1,Data2,NumSims=5000,plot='no'): """ Conduct a Watson V test for a common mean on two declination, inclination data sets This function calculates Watson's V statistic from input files through Monte Carlo simulation in order to test whether two populations of directional data could have been drawn from a common mean. The critical angle between the two sample mean directions and the corresponding McFadden and McElhinny (1990) classification is printed. Required Arguments ---------- Data1 : a list of directional data [dec,inc] Data2 : a list of directional data [dec,inc] Optional Arguments ---------- NumSims : number of Monte Carlo simulations (default is 5000) plot : the default is no plot ('no'). Putting 'yes' will the plot the CDF from the Monte Carlo simulations. """ pars_1=pmag.fisher_mean(Data1) pars_2=pmag.fisher_mean(Data2) 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=np.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 as data, # but a common mean counter=0 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-(Vcrit/2) # following equation 19 of McFadden and McElhinny (1990) the critical # angle is calculated. If the observed angle (also calculated below) # between the data set means exceeds the critical angle the hypothesis # of a common mean direction may be rejected at the 95% confidence # level. The critical angle is simply a different way to present # Watson's V parameter so it makes sense to use the Watson V parameter # in comparison with the critical value of V for considering the test # results. What calculating the critical angle allows for is the # classification of McFadden and McElhinny (1990) to be made # for data sets that are consistent with sharing a common mean. k1=pars_1['k'] k2=pars_2['k'] R1=pars_1['r'] R2=pars_2['r'] critical_angle=np.degrees(np.arccos(((Rwc**2)-((k1*R1)**2) -((k2*R2)**2))/ (2*k1*R1*k2*R2))) D1=(pars_1['dec'],pars_1['inc']) D2=(pars_2['dec'],pars_2['inc']) angle=pmag.angle(D1,D2) 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' print 'that the two populations are drawn from distributions' print 'that share a common mean direction can not be rejected.' elif V>Vcrit: print '"Fail": Since V is greater than Vcrit, the two means can' print 'be distinguished at the 95% confidence level.' print "" print "M&M1990 classification:" print "" print "Angle between data set means: " '%.1f'%(angle) print "Critical angle for M&M1990: " '%.1f'%(critical_angle) if V>Vcrit: print "" elif V<Vcrit: if critical_angle<5: print "The McFadden and McElhinny (1990) classification for" print "this test is: 'A'" elif critical_angle<10: print "The McFadden and McElhinny (1990) classification for" print "this test is: 'B'" elif critical_angle<20: print "The McFadden and McElhinny (1990) classification for" print "this test is: 'C'" else: print "The McFadden and McElhinny (1990) classification for" print "this test is: 'INDETERMINATE;" if plot=='yes': 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)
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 -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,plot='svg',1 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:plot=0 # 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 plot==1: import pmagplotlib 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 spec.keys():spec['specimen_tilt_correction']='-1' # assume unoriented if spec['er_site_name']==site: if 'specimen_mad' not in spec.keys() or spec['specimen_mad']=="": if 'specimen_alpha95' in 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 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 plot==1: pmagplotlib.plotLNP(EQ['eqarea'],site,data,fpars,'specimen_direction_type') pmagplotlib.drawFIGS(EQ) ans=raw_input("s[a]ve plot, [q]uit, <return> to continue:\n ") if ans=="a": files={} files['eqarea']=site+'_'+crd+'_'+'eqarea'+'.'+fmt pmagplotlib.saveP(EQ,files) if ans=="q": sys.exit() else: print 'skipping site - not enough data with specified coordinate system'
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 eqarea_magic.py DESCRIPTION makes equal area projections from declination/inclination data SYNTAX eqarea_magic.py [command line options] INPUT takes magic formatted pmag_results, pmag_sites, pmag_samples or pmag_specimens OPTIONS -h prints help message and quits -f FILE: specify input magic format file from magic,default='pmag_results.txt' supported types=[magic_measurements,pmag_specimens, pmag_samples, pmag_sites, pmag_results, magic_web] -obj OBJ: specify level of plot [all, sit, sam, spc], default is all -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted default is geographic, unspecified assumed geographic -fmt [svg,png,jpg] format for output plots -ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors -c plot as colour contour -sav save plot and quit quietly NOTE all: entire file; sit: site; sam: sample; spc: specimen """ FIG = {} # plot dictionary FIG['eqarea'] = 1 # eqarea is figure 1 in_file, plot_key, coord, crd = 'pmag_results.txt', 'all', "0", 'g' plotE, contour = 0, 0 dir_path = '.' fmt = 'svg' verbose = pmagplotlib.verbose if '-h' in sys.argv: print main.__doc__ sys.exit() if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path = sys.argv[ind + 1] pmagplotlib.plot_init(FIG['eqarea'], 5, 5) if '-f' in sys.argv: ind = sys.argv.index("-f") in_file = dir_path + "/" + sys.argv[ind + 1] if '-obj' in sys.argv: ind = sys.argv.index('-obj') plot_by = sys.argv[ind + 1] if plot_by == 'all': plot_key = 'all' if plot_by == 'sit': plot_key = 'er_site_name' if plot_by == 'sam': plot_key = 'er_sample_name' if plot_by == 'spc': plot_key = 'er_specimen_name' if '-c' in sys.argv: contour = 1 plots = 0 if '-sav' in sys.argv: plots = 1 verbose = 0 if '-ell' in sys.argv: plotE = 1 ind = sys.argv.index('-ell') ell_type = sys.argv[ind + 1] if ell_type == 'F': dist = 'F' if ell_type == 'K': dist = 'K' if ell_type == 'B': dist = 'B' if ell_type == 'Be': dist = 'BE' if ell_type == 'Bv': dist = 'BV' FIG['bdirs'] = 2 pmagplotlib.plot_init(FIG['bdirs'], 5, 5) if '-crd' in sys.argv: ind = sys.argv.index("-crd") crd = sys.argv[ind + 1] if crd == 's': coord = "-1" if crd == 'g': coord = "0" if crd == 't': coord = "100" if '-fmt' in sys.argv: ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] Dec_keys = ['site_dec', 'sample_dec', 'specimen_dec', 'measurement_dec', 'average_dec', 'none'] Inc_keys = ['site_inc', 'sample_inc', 'specimen_inc', 'measurement_inc', 'average_inc', 'none'] Tilt_keys = ['tilt_correction', 'site_tilt_correction', 'sample_tilt_correction', 'specimen_tilt_correction', 'none'] Dir_type_keys = ['', 'site_direction_type', 'sample_direction_type', 'specimen_direction_type'] Name_keys = ['er_specimen_name', 'er_sample_name', 'er_site_name', 'pmag_result_name'] data, file_type = pmag.magic_read(in_file) if file_type == 'pmag_results' and plot_key != "all": plot_key = plot_key + 's' # need plural for results table if verbose: print len(data), ' records read from ', in_file # # # find desired dec,inc data: # dir_type_key = '' # # get plotlist if not plotting all records # plotlist = [] if plot_key != "all": plots = pmag.get_dictitem(data, plot_key, '', 'F') for rec in plots: if rec[plot_key] not in plotlist: plotlist.append(rec[plot_key]) plotlist.sort() else: plotlist.append('All') for plot in plotlist: if verbose: print plot DIblock = [] GCblock = [] SLblock, SPblock = [], [] title = plot mode = 1 dec_key, inc_key, tilt_key, name_key, k = "", "", "", "", 0 if plot != "All": odata = pmag.get_dictitem(data, plot_key, plot, 'T') else: odata = data # data for this obj for dec_key in Dec_keys: Decs = pmag.get_dictitem(odata, dec_key, '', 'F') # get all records with this dec_key not blank if len(Decs) > 0: break for inc_key in Inc_keys: Incs = pmag.get_dictitem(Decs, inc_key, '', 'F') # get all records with this inc_key not blank if len(Incs) > 0: break for tilt_key in Tilt_keys: if tilt_key in Incs[0].keys(): break # find the tilt_key for these records if tilt_key == 'none': # no tilt key in data, need to fix this with fake data which will be unknown tilt tilt_key = 'tilt_correction' for rec in Incs: rec[tilt_key] = '' cdata = pmag.get_dictitem(Incs, tilt_key, coord, 'T') # get all records matching specified coordinate system if coord == '0': # geographic udata = pmag.get_dictitem(Incs, tilt_key, '', 'T') # get all the blank records - assume geographic if len(cdata) == 0: crd = '' if len(udata) > 0: for d in udata: cdata.append(d) crd = crd + 'u' for name_key in Name_keys: Names = pmag.get_dictitem(cdata, name_key, '', 'F') # get all records with this name_key not blank if len(Names) > 0: break for dir_type_key in Dir_type_keys: Dirs = pmag.get_dictitem(cdata, dir_type_key, '', 'F') # get all records with this direction type if len(Dirs) > 0: break if dir_type_key == "": dir_type_key = 'direction_type' locations, site, sample, specimen = "", "", "", "" for rec in cdata: # pick out the data if 'er_location_name' in rec.keys() and rec['er_location_name'] != "" and rec[ 'er_location_name'] not in locations: locations = locations + rec['er_location_name'].replace("/", "") + "_" if 'er_location_names' in rec.keys() and rec['er_location_names'] != "": locs = rec['er_location_names'].split(':') for loc in locs: if loc not in locations: locations = locations + loc.replace("/", "") + '_' if plot_key == 'er_site_name' or plot_key == 'er_sample_name' or plot_key == 'er_specimen_name': site = rec['er_site_name'] if plot_key == 'er_sample_name' or plot_key == 'er_specimen_name': sample = rec['er_sample_name'] if plot_key == 'er_specimen_name': specimen = rec['er_specimen_name'] if plot_key == 'er_site_names' or plot_key == 'er_sample_names' or plot_key == 'er_specimen_names': site = rec['er_site_names'] if plot_key == 'er_sample_names' or plot_key == 'er_specimen_names': sample = rec['er_sample_names'] if plot_key == 'er_specimen_names': specimen = rec['er_specimen_names'] if dir_type_key not in rec.keys() or rec[dir_type_key] == "": rec[dir_type_key] = 'l' if 'magic_method_codes' not in rec.keys(): rec['magic_method_codes'] = "" DIblock.append([float(rec[dec_key]), float(rec[inc_key])]) SLblock.append([rec[name_key], rec['magic_method_codes']]) if rec[tilt_key] == coord and rec[dir_type_key] != 'l' and rec[dec_key] != "" and rec[inc_key] != "": GCblock.append([float(rec[dec_key]), float(rec[inc_key])]) SPblock.append([rec[name_key], rec['magic_method_codes']]) if len(DIblock) == 0 and len(GCblock) == 0: if verbose: print "no records for plotting" sys.exit() if verbose: for k in range(len(SLblock)): print '%s %s %7.1f %7.1f' % (SLblock[k][0], SLblock[k][1], DIblock[k][0], DIblock[k][1]) for k in range(len(SPblock)): print '%s %s %7.1f %7.1f' % (SPblock[k][0], SPblock[k][1], GCblock[k][0], GCblock[k][1]) if len(DIblock) > 0: if contour == 0: pmagplotlib.plotEQ(FIG['eqarea'], DIblock, title) else: pmagplotlib.plotEQcont(FIG['eqarea'], DIblock) else: pmagplotlib.plotNET(FIG['eqarea']) if len(GCblock) > 0: for rec in GCblock: pmagplotlib.plotC(FIG['eqarea'], rec, 90., 'g') if plotE == 1: ppars = pmag.doprinc(DIblock) # get principal directions nDIs, rDIs, npars, rpars = [], [], [], [] for rec in DIblock: angle = pmag.angle([rec[0], rec[1]], [ppars['dec'], ppars['inc']]) if angle > 90.: rDIs.append(rec) else: nDIs.append(rec) if dist == 'B': # do on whole dataset etitle = "Bingham confidence ellipse" bpars = pmag.dobingham(DIblock) for key in bpars.keys(): if key != 'n' and verbose: print " ", key, '%7.1f' % (bpars[key]) if key == 'n' and verbose: print " ", key, ' %i' % (bpars[key]) npars.append(bpars['dec']) npars.append(bpars['inc']) npars.append(bpars['Zeta']) npars.append(bpars['Zdec']) npars.append(bpars['Zinc']) npars.append(bpars['Eta']) npars.append(bpars['Edec']) npars.append(bpars['Einc']) if dist == 'F': etitle = "Fisher confidence cone" if len(nDIs) > 2: fpars = pmag.fisher_mean(nDIs) for key in fpars.keys(): if key != 'n' and verbose: print " ", key, '%7.1f' % (fpars[key]) if key == 'n' and verbose: print " ", key, ' %i' % (fpars[key]) mode += 1 npars.append(fpars['dec']) npars.append(fpars['inc']) npars.append(fpars['alpha95']) # Beta npars.append(fpars['dec']) isign = abs(fpars['inc']) / fpars['inc'] npars.append(fpars['inc'] - isign * 90.) #Beta inc npars.append(fpars['alpha95']) # gamma npars.append(fpars['dec'] + 90.) # Beta dec npars.append(0.) #Beta inc if len(rDIs) > 2: fpars = pmag.fisher_mean(rDIs) if verbose: print "mode ", mode for key in fpars.keys(): if key != 'n' and verbose: print " ", key, '%7.1f' % (fpars[key]) if key == 'n' and verbose: print " ", key, ' %i' % (fpars[key]) mode += 1 rpars.append(fpars['dec']) rpars.append(fpars['inc']) rpars.append(fpars['alpha95']) # Beta rpars.append(fpars['dec']) isign = abs(fpars['inc']) / fpars['inc'] rpars.append(fpars['inc'] - isign * 90.) #Beta inc rpars.append(fpars['alpha95']) # gamma rpars.append(fpars['dec'] + 90.) # Beta dec rpars.append(0.) #Beta inc if dist == 'K': etitle = "Kent confidence ellipse" if len(nDIs) > 3: kpars = pmag.dokent(nDIs, len(nDIs)) if verbose: print "mode ", mode for key in kpars.keys(): if key != 'n' and verbose: print " ", key, '%7.1f' % (kpars[key]) if key == 'n' and verbose: print " ", key, ' %i' % (kpars[key]) mode += 1 npars.append(kpars['dec']) npars.append(kpars['inc']) npars.append(kpars['Zeta']) npars.append(kpars['Zdec']) npars.append(kpars['Zinc']) npars.append(kpars['Eta']) npars.append(kpars['Edec']) npars.append(kpars['Einc']) if len(rDIs) > 3: kpars = pmag.dokent(rDIs, len(rDIs)) if verbose: print "mode ", mode for key in kpars.keys(): if key != 'n' and verbose: print " ", key, '%7.1f' % (kpars[key]) if key == 'n' and verbose: print " ", key, ' %i' % (kpars[key]) mode += 1 rpars.append(kpars['dec']) rpars.append(kpars['inc']) rpars.append(kpars['Zeta']) rpars.append(kpars['Zdec']) rpars.append(kpars['Zinc']) rpars.append(kpars['Eta']) rpars.append(kpars['Edec']) rpars.append(kpars['Einc']) else: # assume bootstrap if dist == 'BE': if len(nDIs) > 5: BnDIs = pmag.di_boot(nDIs) Bkpars = pmag.dokent(BnDIs, 1.) if verbose: print "mode ", mode for key in Bkpars.keys(): if key != 'n' and verbose: print " ", key, '%7.1f' % (Bkpars[key]) if key == 'n' and verbose: print " ", key, ' %i' % (Bkpars[key]) mode += 1 npars.append(Bkpars['dec']) npars.append(Bkpars['inc']) npars.append(Bkpars['Zeta']) npars.append(Bkpars['Zdec']) npars.append(Bkpars['Zinc']) npars.append(Bkpars['Eta']) npars.append(Bkpars['Edec']) npars.append(Bkpars['Einc']) if len(rDIs) > 5: BrDIs = pmag.di_boot(rDIs) Bkpars = pmag.dokent(BrDIs, 1.) if verbose: print "mode ", mode for key in Bkpars.keys(): if key != 'n' and verbose: print " ", key, '%7.1f' % (Bkpars[key]) if key == 'n' and verbose: print " ", key, ' %i' % (Bkpars[key]) mode += 1 rpars.append(Bkpars['dec']) rpars.append(Bkpars['inc']) rpars.append(Bkpars['Zeta']) rpars.append(Bkpars['Zdec']) rpars.append(Bkpars['Zinc']) rpars.append(Bkpars['Eta']) rpars.append(Bkpars['Edec']) rpars.append(Bkpars['Einc']) etitle = "Bootstrapped confidence ellipse" elif dist == 'BV': sym = {'lower': ['o', 'c'], 'upper': ['o', 'g'], 'size': 3, 'edgecolor': 'face'} if len(nDIs) > 5: BnDIs = pmag.di_boot(nDIs) pmagplotlib.plotEQsym(FIG['bdirs'], BnDIs, 'Bootstrapped Eigenvectors', sym) if len(rDIs) > 5: BrDIs = pmag.di_boot(rDIs) if len(nDIs) > 5: # plot on existing plots pmagplotlib.plotDIsym(FIG['bdirs'], BrDIs, sym) else: pmagplotlib.plotEQ(FIG['bdirs'], BrDIs, 'Bootstrapped Eigenvectors') if dist == 'B': if len(nDIs) > 3 or len(rDIs) > 3: pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], npars, 0) elif len(nDIs) > 3 and dist != 'BV': pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], npars, 0) if len(rDIs) > 3: pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], rpars, 0) elif len(rDIs) > 3 and dist != 'BV': pmagplotlib.plotCONF(FIG['eqarea'], etitle, [], rpars, 0) if verbose: pmagplotlib.drawFIGS(FIG) # files = {} locations = locations[:-1] for key in FIG.keys(): filename = 'LO:_' + locations + '_SI:_' + site + '_SA:_' + sample + '_SP:_' + specimen + '_CO:_' + crd + '_TY:_' + key + '_.' + fmt files[key] = filename if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['eq'] = 'Equal Area Plot' FIG = pmagplotlib.addBorders(FIG, titles, black, purple) pmagplotlib.saveP(FIG, files) elif verbose: ans = raw_input(" S[a]ve to save plot, [q]uit, Return to continue: ") if ans == "q": sys.exit() if ans == "a": pmagplotlib.saveP(FIG, files) if plots: pmagplotlib.saveP(FIG, 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 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 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 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]) # 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 pmagplotlib.drawFIGS({'fig':plotnum}) 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 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 pmagplotlib.plot_init(plotnum,5,5) FTinit=1 XFplot=plotnum plotnum+=1 # increment plotnum pmagplotlib.plotXFT(XFplot,XF,Ts[Tind],e,b) 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)>1: # 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 else: print 'Skipping susceptibitily - AC field plot as a function of temperature' 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': files={} PLTS={} for p in range(1,plotnum): key=str(p) files[key]=e+'_'+key+'.'+fmt PLTS[key]=p pmagplotlib.saveP(PLTS,files) cont=raw_input("Enter index of desired temperature step, s[a]ve plots, [return] to quit ") if cont=="":sys.exit() else: ans=raw_input("enter s[a]ve to save files, [return] to quit ") if ans=='a': files={} PLTS={} for p in range(1,plotnum): key=str(p) files[key]=e+'_'+key+'.'+fmt PLTS[key]=p pmagplotlib.saveP(PLTS,files) sys.exit() else: sys.exit()
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) fpars = pmag.dohext(int(rec["anisotropy_n"]) - 6, float(rec["anisotropy_sigma"]), 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"] 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: title = "LO:_" + ResRec["er_location_names"] + "_SI:_" + site + "_SA:__SP:__CO:_" + 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.0, "g") pmagplotlib.plotC(ANIS["conf"], PDir, 90.0, "g") if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) ResRec["er_location_names"] = pmag.makelist(Locs) if plots == 1: save(ANIS, fmt, title) ResRec = {} ResRec["er_citation_names"] = pmag.makelist(Cits) ResRec["er_location_names"] = pmag.makelist(Locs) ResRec["er_site_names"] = pmag.makelist(Sites) ResRec["er_sample_names"] = pmag.makelist(Samples) ResRec["er_specimen_names"] = pmag.makelist(Specimens) ResRec["rmag_result_name"] = pmag.makelist(Sites) + ":" + pmag.makelist(anitypes) ResRec["anisotropy_type"] = pmag.makelist(anitypes) ResRec["er_analyst_mail_names"] = user ResRec["tilt_correction"] = CS if isite == "0": ResRec["result_description"] = "Study average using coordinate system: " + CS if isite == "1": ResRec["result_description"] = "Site average using coordinate system: " + CS if hpars != [] and ihext == 1: HextRec = {} for key in ResRec.keys(): HextRec[key] = ResRec[key] # copy over stuff HextRec["anisotropy_v1_dec"] = "%7.1f" % (hpars["v1_dec"]) HextRec["anisotropy_v2_dec"] = "%7.1f" % (hpars["v2_dec"]) HextRec["anisotropy_v3_dec"] = "%7.1f" % (hpars["v3_dec"]) HextRec["anisotropy_v1_inc"] = "%7.1f" % (hpars["v1_inc"]) HextRec["anisotropy_v2_inc"] = "%7.1f" % (hpars["v2_inc"]) HextRec["anisotropy_v3_inc"] = "%7.1f" % (hpars["v3_inc"]) HextRec["anisotropy_t1"] = "%10.8f" % (hpars["t1"]) HextRec["anisotropy_t2"] = "%10.8f" % (hpars["t2"]) HextRec["anisotropy_t3"] = "%10.8f" % (hpars["t3"]) HextRec["anisotropy_hext_F"] = "%7.1f " % (hpars["F"]) HextRec["anisotropy_hext_F12"] = "%7.1f " % (hpars["F12"]) HextRec["anisotropy_hext_F23"] = "%7.1f " % (hpars["F23"]) HextRec["anisotropy_v1_eta_semi_angle"] = "%7.1f " % (hpars["e12"]) HextRec["anisotropy_v1_eta_dec"] = "%7.1f " % (hpars["v2_dec"]) HextRec["anisotropy_v1_eta_inc"] = "%7.1f " % (hpars["v2_inc"]) HextRec["anisotropy_v1_zeta_semi_angle"] = "%7.1f " % (hpars["e13"]) HextRec["anisotropy_v1_zeta_dec"] = "%7.1f " % (hpars["v3_dec"]) HextRec["anisotropy_v1_zeta_inc"] = "%7.1f " % (hpars["v3_inc"]) HextRec["anisotropy_v2_eta_semi_angle"] = "%7.1f " % (hpars["e12"]) HextRec["anisotropy_v2_eta_dec"] = "%7.1f " % (hpars["v1_dec"]) HextRec["anisotropy_v2_eta_inc"] = "%7.1f " % (hpars["v1_inc"]) HextRec["anisotropy_v2_zeta_semi_angle"] = "%7.1f " % (hpars["e23"]) HextRec["anisotropy_v2_zeta_dec"] = "%7.1f " % (hpars["v3_dec"]) HextRec["anisotropy_v2_zeta_inc"] = "%7.1f " % (hpars["v3_inc"]) HextRec["anisotropy_v3_eta_semi_angle"] = "%7.1f " % (hpars["e12"]) HextRec["anisotropy_v3_eta_dec"] = "%7.1f " % (hpars["v1_dec"]) HextRec["anisotropy_v3_eta_inc"] = "%7.1f " % (hpars["v1_inc"]) HextRec["anisotropy_v3_zeta_semi_angle"] = "%7.1f " % (hpars["e23"]) HextRec["anisotropy_v3_zeta_dec"] = "%7.1f " % (hpars["v2_dec"]) HextRec["anisotropy_v3_zeta_inc"] = "%7.1f " % (hpars["v2_inc"]) HextRec["magic_method_codes"] = "LP-AN:AE-H" if verbose: print "Hext Statistics: " print " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I" print HextRec["anisotropy_t1"], HextRec["anisotropy_v1_dec"], HextRec["anisotropy_v1_inc"], HextRec[ "anisotropy_v1_eta_semi_angle" ], HextRec["anisotropy_v1_eta_dec"], HextRec["anisotropy_v1_eta_inc"], HextRec[ "anisotropy_v1_zeta_semi_angle" ], HextRec[ "anisotropy_v1_zeta_dec" ], HextRec[ "anisotropy_v1_zeta_inc" ] print HextRec["anisotropy_t2"], HextRec["anisotropy_v2_dec"], HextRec["anisotropy_v2_inc"], HextRec[ "anisotropy_v2_eta_semi_angle" ], HextRec["anisotropy_v2_eta_dec"], HextRec["anisotropy_v2_eta_inc"], HextRec[ "anisotropy_v2_zeta_semi_angle" ], HextRec[ "anisotropy_v2_zeta_dec" ], HextRec[ "anisotropy_v2_zeta_inc" ] print HextRec["anisotropy_t3"], HextRec["anisotropy_v3_dec"], HextRec["anisotropy_v3_inc"], HextRec[ "anisotropy_v3_eta_semi_angle" ], HextRec["anisotropy_v3_eta_dec"], HextRec["anisotropy_v3_eta_inc"], HextRec[ "anisotropy_v3_zeta_semi_angle" ], HextRec[ "anisotropy_v3_zeta_dec" ], HextRec[ "anisotropy_v3_zeta_inc" ] HextRec["magic_software_packages"] = version_num ResRecs.append(HextRec) if bpars != []: BootRec = {} for key in ResRec.keys(): BootRec[key] = ResRec[key] # copy over stuff BootRec["anisotropy_v1_dec"] = "%7.1f" % (bpars["v1_dec"]) BootRec["anisotropy_v2_dec"] = "%7.1f" % (bpars["v2_dec"]) BootRec["anisotropy_v3_dec"] = "%7.1f" % (bpars["v3_dec"]) BootRec["anisotropy_v1_inc"] = "%7.1f" % (bpars["v1_inc"]) BootRec["anisotropy_v2_inc"] = "%7.1f" % (bpars["v2_inc"]) BootRec["anisotropy_v3_inc"] = "%7.1f" % (bpars["v3_inc"]) BootRec["anisotropy_t1"] = "%10.8f" % (bpars["t1"]) BootRec["anisotropy_t2"] = "%10.8f" % (bpars["t2"]) BootRec["anisotropy_t3"] = "%10.8f" % (bpars["t3"]) BootRec["anisotropy_v1_eta_inc"] = "%7.1f " % (bpars["v1_eta_inc"]) BootRec["anisotropy_v1_eta_dec"] = "%7.1f " % (bpars["v1_eta_dec"]) BootRec["anisotropy_v1_eta_semi_angle"] = "%7.1f " % (bpars["v1_eta"]) BootRec["anisotropy_v1_zeta_inc"] = "%7.1f " % (bpars["v1_zeta_inc"]) BootRec["anisotropy_v1_zeta_dec"] = "%7.1f " % (bpars["v1_zeta_dec"]) BootRec["anisotropy_v1_zeta_semi_angle"] = "%7.1f " % (bpars["v1_zeta"]) BootRec["anisotropy_v2_eta_inc"] = "%7.1f " % (bpars["v2_eta_inc"]) BootRec["anisotropy_v2_eta_dec"] = "%7.1f " % (bpars["v2_eta_dec"]) BootRec["anisotropy_v2_eta_semi_angle"] = "%7.1f " % (bpars["v2_eta"]) BootRec["anisotropy_v2_zeta_inc"] = "%7.1f " % (bpars["v2_zeta_inc"]) BootRec["anisotropy_v2_zeta_dec"] = "%7.1f " % (bpars["v2_zeta_dec"]) BootRec["anisotropy_v2_zeta_semi_angle"] = "%7.1f " % (bpars["v2_zeta"]) BootRec["anisotropy_v3_eta_inc"] = "%7.1f " % (bpars["v3_eta_inc"]) BootRec["anisotropy_v3_eta_dec"] = "%7.1f " % (bpars["v3_eta_dec"]) BootRec["anisotropy_v3_eta_semi_angle"] = "%7.1f " % (bpars["v3_eta"]) BootRec["anisotropy_v3_zeta_inc"] = "%7.1f " % (bpars["v3_zeta_inc"]) BootRec["anisotropy_v3_zeta_dec"] = "%7.1f " % (bpars["v3_zeta_dec"]) BootRec["anisotropy_v3_zeta_semi_angle"] = "%7.1f " % (bpars["v3_zeta"]) BootRec["anisotropy_hext_F"] = "" BootRec["anisotropy_hext_F12"] = "" BootRec["anisotropy_hext_F23"] = "" BootRec["magic_method_codes"] = "LP-AN:AE-H:AE-BS" # regular bootstrap if ipar == 1: BootRec["magic_method_codes"] = "LP-AN:AE-H:AE-BS-P" # parametric bootstrap if verbose: print "Boostrap Statistics: " print " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I" print BootRec["anisotropy_t1"], BootRec["anisotropy_v1_dec"], BootRec["anisotropy_v1_inc"], BootRec[ "anisotropy_v1_eta_semi_angle" ], BootRec["anisotropy_v1_eta_dec"], BootRec["anisotropy_v1_eta_inc"], BootRec[ "anisotropy_v1_zeta_semi_angle" ], BootRec[ "anisotropy_v1_zeta_dec" ], BootRec[ "anisotropy_v1_zeta_inc" ] print BootRec["anisotropy_t2"], BootRec["anisotropy_v2_dec"], BootRec["anisotropy_v2_inc"], BootRec[ "anisotropy_v2_eta_semi_angle" ], BootRec["anisotropy_v2_eta_dec"], BootRec["anisotropy_v2_eta_inc"], BootRec[ "anisotropy_v2_zeta_semi_angle" ], BootRec[ "anisotropy_v2_zeta_dec" ], BootRec[ "anisotropy_v2_zeta_inc" ] print BootRec["anisotropy_t3"], BootRec["anisotropy_v3_dec"], BootRec["anisotropy_v3_inc"], BootRec[ "anisotropy_v3_eta_semi_angle" ], BootRec["anisotropy_v3_eta_dec"], BootRec["anisotropy_v3_eta_inc"], BootRec[ "anisotropy_v3_zeta_semi_angle" ], BootRec[ "anisotropy_v3_zeta_dec" ], BootRec[ "anisotropy_v3_zeta_inc" ] BootRec["magic_software_packages"] = version_num ResRecs.append(BootRec) k += 1 goon = 1 while goon == 1 and iplot == 1 and verbose: if iboot == 1: print "compare with [d]irection " print " plot [g]reat circle, change [c]oord. system, change [e]llipse calculation, s[a]ve plots, [q]uit " if isite == 1: print " [p]revious, [s]ite, [q]uit, <return> for next " ans = raw_input("") if ans == "q": sys.exit() if ans == "e": iboot, ipar, ihext, ivec = 1, 0, 0, 0 e = raw_input("Do Hext Statistics 1/[0]: ") if e == "1": ihext = 1 e = raw_input("Suppress bootstrap 1/[0]: ") if e == "1": iboot = 0 if iboot == 1: e = raw_input("Parametric bootstrap 1/[0]: ") if e == "1": ipar = 1 e = raw_input("Plot bootstrap eigenvectors: 1/[0]: ") if e == "1": ivec = 1 if iplot == 1: if inittcdf == 0: ANIS["tcdf"] = 3 pmagplotlib.plot_init(ANIS["tcdf"], 5, 5) inittcdf = 1 bpars, hpars = pmagplotlib.plotANIS( ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb ) if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) if ans == "c": print "Current Coordinate system is: " if CS == "-1": print " Specimen" if CS == "0": print " Geographic" if CS == "100": print " Tilt corrected" key = raw_input(" Enter desired coordinate system: [s]pecimen, [g]eographic, [t]ilt corrected ") if key == "s": CS = "-1" if key == "g": CS = "0" if key == "t": CS = "100" if CS not in orlist: if len(orlist) > 0: CS = orlist[0] else: CS = "-1" if CS == "-1": crd = "s" if CS == "0": crd = "g" if CS == "100": crd = "t" print "desired coordinate system not available, using available: ", crd k -= 1 goon = 0 if ans == "": if isite == 1: goon = 0 else: print "Good bye " sys.exit() if ans == "d": if initcdf == 0: initcdf = 1 ANIS["vxcdf"], ANIS["vycdf"], ANIS["vzcdf"] = 4, 5, 6 pmagplotlib.plot_init(ANIS["vxcdf"], 5, 5) pmagplotlib.plot_init(ANIS["vycdf"], 5, 5) pmagplotlib.plot_init(ANIS["vzcdf"], 5, 5) Dir, comp = [], 1 print """ Input: Vi D I to compare eigenvector Vi with direction D/I where Vi=1: principal Vi=2: major Vi=3: minor D= declination of comparison direction I= inclination of comparison direction""" con = 1 while con == 1: try: vdi = raw_input("Vi D I: ").split() vec = int(vdi[0]) - 1 Dir = [float(vdi[1]), float(vdi[2])] con = 0 except IndexError: print " Incorrect entry, try again " bpars, hpars = pmagplotlib.plotANIS( ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb ) Dir, comp = [], 0 if ans == "g": con, cnt = 1, 0 while con == 1: try: print " Input: input pole to great circle ( D I) to plot a great circle: " di = raw_input(" D I: ").split() PDir.append(float(di[0])) PDir.append(float(di[1])) con = 0 except: cnt += 1 if cnt < 10: print " enter the dec and inc of the pole on one line " else: print "ummm - you are doing something wrong - i give up" sys.exit() pmagplotlib.plotC(ANIS["data"], PDir, 90.0, "g") pmagplotlib.plotC(ANIS["conf"], PDir, 90.0, "g") if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) if ans == "p": k -= 2 goon = 0 if ans == "q": k = plt goon = 0 if ans == "s": keepon = 1 site = raw_input(" print site or part of site desired: ") while keepon == 1: try: k = sitelist.index(site) keepon = 0 except: tmplist = [] for qq in range(len(sitelist)): if site in sitelist[qq]: tmplist.append(sitelist[qq]) print site, " not found, but this was: " print tmplist site = raw_input("Select one or try again\n ") k = sitelist.index(site) goon, ans = 0, "" if ans == "a": locs = pmag.makelist(Locs) title = "LO:_" + locs + "_SI:__" + "_SA:__SP:__CO:_" + crd save(ANIS, fmt, title) goon = 0 else: if verbose: print "skipping plot - not enough data points" k += 1 # put rmag_results stuff here if len(ResRecs) > 0: ResOut, keylist = pmag.fillkeys(ResRecs) pmag.magic_write(outfile, ResOut, "rmag_results") if verbose: print " Good bye "
def main(): """ NAME watsonsV.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 watsonsV.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: 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']='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) 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 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)