def test_magic_read_success(self): fname = os.path.join(WD, "data_files", "3_0", "McMurdo", "sites.txt") data, ftype = pmag.magic_read(fname) self.assertEqual(ftype, 'sites') self.assertEqual(len(data), 542) data, ftype, magic_keys = pmag.magic_read(fname, return_keys=True) self.assertEqual(magic_keys[-1], 'vgp_n_samples')
def main(): """ NAME measurements_normalize.py DESCRIPTION takes magic_measurements file and normalized moment by sample_weight and sample_volume in the er_specimens table SYNTAX measurements_normalize.py [command line options] OPTIONS -f FILE: specify input file, default is: magic_measurements.txt -fsp FILE: specify input specimen file, default is: er_specimens.txt -F FILE: specify output measurements, default is to overwrite input file """ # # initialize variables # # # dir_path='.' if "-WD" in sys.argv: ind=sys.argv.index("-WD") dir_path=sys.argv[ind+1] meas_file,spec_file= dir_path+"/magic_measurements.txt",dir_path+"/er_specimens.txt" out_file=meas_file MeasRecs,SpecRecs=[],[] OutRecs=[] if "-h" in sys.argv: print(main.__doc__) sys.exit() if "-f" in sys.argv: ind=sys.argv.index("-f") meas_file=dir_path+'/'+sys.argv[ind+1] if "-fsp" in sys.argv: ind=sys.argv.index("-fsp") spec_file=dir_path+'/'+sys.argv[ind+1] if "-F" in sys.argv: ind=sys.argv.index("-F") out_file=dir_path+'/'+sys.argv[ind+1] MeasRecs,file_type=pmag.magic_read(meas_file) Specs,file_type=pmag.magic_read(spec_file) for rec in MeasRecs: if 'measurement_magn_moment' in list(rec.keys()) and rec['measurement_magn_moment'] != "": for spec in Specs: if spec['er_specimen_name']==rec['er_specimen_name']: if 'specimen_weight' in list(spec.keys()) and spec['specimen_weight']!="": rec['measurement_magn_mass']='%e'%(old_div(float(rec['measurement_magn_moment']),float(spec['specimen_weight']))) if 'specimen_volume' in list(spec.keys()) and spec['specimen_volume']!="": rec['measurement_magn_volume']='%e'%(old_div(float(rec['measurement_magn_moment']),float(spec['specimen_volume']))) break if 'measurement_magn_volume' not in list(rec.keys()): rec['measurement_magn_volume']='' if 'measurement_magn_mass' not in list(rec.keys()): rec['measurement_magn_mass']='' OutRecs.append(rec) pmag.magic_write(out_file,OutRecs,"magic_measurements") print("Data saved in ", out_file)
def get_Data(magic_file): #------------------------------------------------ # Read magic measurement file and sort to blocks #------------------------------------------------ Data = {} try: meas_data, file_type = pmag.magic_read(magic_file) except: print "-E- ERROR: Cant read magic_measurement.txt file. File is corrupted." return Data # get list of unique specimen names #sids=pmag.get_specs(meas_data) # samples ID's for rec in meas_data: s = rec["er_specimen_name"] method_codes = rec["magic_method_codes"].strip('\n') method_codes.replace(" ", "") methods = method_codes.split(":") if "LP-AN-TRM" in methods: if s not in Data.keys(): Data[s] = {} if 'atrmblock' not in Data[s].keys(): Data[s]['atrmblock'] = [] Data[s]['atrmblock'].append(rec) if "LP-AN-ARM" in methods: if s not in Data.keys(): Data[s] = {} if 'aarmblock' not in Data[s].keys(): Data[s]['aarmblock'] = [] Data[s]['aarmblock'].append(rec) return (Data)
def main(): """ NAME change_case_magic.py DESCRIPTION picks out key and converts to upper or lower case SYNTAX change_case_magic.py [command line options] OPTIONS -h prints help message and quits -f FILE: specify input magic format file -F FILE: specify output magic format file , default is to overwrite input file -keys KEY1:KEY2 specify colon delimited list of keys to convert -[U,l] : specify [U]PPER or [l]ower case, default is lower """ dir_path = "./" change = 'l' 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 '-f' in sys.argv: ind = sys.argv.index('-f') magic_file = dir_path + '/' + sys.argv[ind + 1] else: print(main.__doc__) sys.exit() if '-F' in sys.argv: ind = sys.argv.index('-F') out_file = dir_path + '/' + sys.argv[ind + 1] else: out_file = magic_file if '-keys' in sys.argv: ind = sys.argv.index('-keys') grab_keys = sys.argv[ind + 1].split(":") else: print(main.__doc__) sys.exit() if '-U' in sys.argv: change = 'U' # # # get data read in Data, file_type = pmag.magic_read(magic_file) if len(Data) > 0: for grab_key in grab_keys: for rec in Data: if change == 'l': rec[grab_key] = rec[grab_key].lower() else: rec[grab_key] = rec[grab_key].upper() else: print('bad file name') pmag.magic_write(out_file, Data, file_type)
def main(): """ NAME change_case_magic.py DESCRIPTION picks out key and converts to upper or lower case SYNTAX change_case_magic.py [command line options] OPTIONS -h prints help message and quits -f FILE: specify input magic format file -F FILE: specify output magic format file , default is to overwrite input file -keys KEY1:KEY2 specify colon delimited list of keys to convert -[U,l] : specify [U]PPER or [l]ower case, default is lower """ dir_path="./" change='l' 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 '-f' in sys.argv: ind=sys.argv.index('-f') magic_file=dir_path+'/'+sys.argv[ind+1] else: print(main.__doc__) sys.exit() if '-F' in sys.argv: ind=sys.argv.index('-F') out_file=dir_path+'/'+sys.argv[ind+1] else: out_file=magic_file if '-keys' in sys.argv: ind=sys.argv.index('-keys') grab_keys=sys.argv[ind+1].split(":") else: print(main.__doc__) sys.exit() if '-U' in sys.argv: change='U' # # # get data read in Data,file_type=pmag.magic_read(magic_file) if len(Data)>0: for grab_key in grab_keys: for rec in Data: if change=='l': rec[grab_key]=rec[grab_key].lower() else: rec[grab_key]=rec[grab_key].upper() else: print('bad file name') pmag.magic_write(out_file,Data,file_type)
def test_bgc_with_append(self): options = {'input_dir_path': self.input_dir, 'mag_file': 'BC0-3A'} program_ran, outfile = bgc_magic.convert(**options) self.assertTrue(program_ran) options['append'] = True program_ran, outfile = bgc_magic.convert(**options) self.assertTrue(program_ran) lines, file_type = pmag.magic_read(os.path.join(WD, 'specimens.txt')) self.assertEqual(len(lines), 2)
def main(): """ NAME extract_methods.py DESCRIPTION reads in a magic table and creates a file with method codes SYNTAX extract_methods.py [command line options] OPTIONS -h: prints the help message and quits. -f FILE: specify magic format input file, default is magic_measurements.txt -F FILE: specify method code output file, default is magic_methods.txt """ citation='This study' args=sys.argv outfile='magic_methods.txt' infile='magic_measurements.txt' # # get command line arguments # dir_path='.' if '-WD' in args: ind=args.index("-WD") dir_path=args[ind+1] if "-h" in args: print main.__doc__ sys.exit() if '-F' in args: ind=args.index("-F") outfile=args[ind+1] if '-f' in args: ind=args.index("-f") infile=args[ind+1] infile=dir_path+'/'+infile outfile=dir_path+'/'+outfile data,file_type=pmag.magic_read(infile) MethRecs=[] methods=[] for rec in data: meths=rec['magic_method_codes'].split(":") for meth in meths: if meth not in methods: MethRec={} methods.append(meth) MethRec['magic_method_code']=meth MethRecs.append(MethRec) pmag.magic_write(outfile,MethRecs,'magic_methods')
def main(): """ NAME extract_methods.py DESCRIPTION reads in a magic table and creates a file with method codes SYNTAX extract_methods.py [command line options] OPTIONS -h: prints the help message and quits. -f FILE: specify magic format input file, default is magic_measurements.txt -F FILE: specify method code output file, default is magic_methods.txt """ citation='This study' args=sys.argv outfile='magic_methods.txt' infile='magic_measurements.txt' # # get command line arguments # dir_path='.' if '-WD' in args: ind=args.index("-WD") dir_path=args[ind+1] if "-h" in args: print(main.__doc__) sys.exit() if '-F' in args: ind=args.index("-F") outfile=args[ind+1] if '-f' in args: ind=args.index("-f") infile=args[ind+1] infile=dir_path+'/'+infile outfile=dir_path+'/'+outfile data,file_type=pmag.magic_read(infile) MethRecs=[] methods=[] for rec in data: meths=rec['magic_method_codes'].split(":") for meth in meths: if meth not in methods: MethRec={} methods.append(meth) MethRec['magic_method_code']=meth MethRecs.append(MethRec) pmag.magic_write(outfile,MethRecs,'magic_methods')
def main(): """ NAME grab_magic_key.py DESCRIPTION picks out key and saves to file SYNTAX grab_magic_key.py [command line optins] OPTIONS -h prints help message and quits -f FILE: specify input magic format file -key KEY: specify key to print to standard output """ dir_path = "./" 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 '-f' in sys.argv: ind = sys.argv.index('-f') magic_file = dir_path+'/'+sys.argv[ind+1] else: print(main.__doc__) sys.exit() if '-key' in sys.argv: ind = sys.argv.index('-key') grab_key = sys.argv[ind+1] else: print(main.__doc__) sys.exit() # # # get data read in Data, file_type = pmag.magic_read(magic_file) if len(Data) > 0: for rec in Data: print(rec[grab_key]) else: print('bad file name')
def main(): """ NAME grab_magic_key.py DESCRIPTION picks out key and saves to file SYNTAX grab_magic_key.py [command line optins] OPTIONS -h prints help message and quits -f FILE: specify input magic format file -key KEY: specify key to print to standard output """ dir_path = "./" 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 '-f' in sys.argv: ind = sys.argv.index('-f') magic_file = dir_path + '/' + sys.argv[ind + 1] else: print(main.__doc__) sys.exit() if '-key' in sys.argv: ind = sys.argv.index('-key') grab_key = sys.argv[ind + 1] else: print(main.__doc__) sys.exit() # # # get data read in Data, file_type = pmag.magic_read(magic_file) if len(Data) > 0: for rec in Data: print(rec[grab_key]) else: print('bad file name')
def test_make_plots(self): dir_path = os.path.join(WD, 'data_files', '3_0', 'Osler') image_file = os.path.join(dir_path, 'images.txt') os.chdir(dir_path) for filename in glob.glob("*error*"): os.remove(filename) os.system("new_make_magic_plots.py") self.assertFalse(glob.glob("errors.txt")) self.assertTrue(os.path.exists(image_file)) lines = pmag.magic_read(image_file)[0] self.assertEqual(len(lines), 7) self.assertFalse("image" in lines[0].keys()) if pmagplotlib.isServer: self.assertFalse(glob.glob("thumbnail_errors.txt")) self.assertEqual(14, len(glob.glob("*.png"))) self.assertEqual(7, len(glob.glob("*thumb*.png"))) else: self.assertEqual(10, len(glob.glob("*.png"))) self.assertEqual(5, len(glob.glob("*thumb*.png")))
def test_make_plots_long(self): #if not pmagplotlib.isServer: # # only run this annoyingly slow test 10% of the time # num = random.randint(1, 10) # if num != 3: # return # make a backup of images.txt os.chdir(os.path.join(WD, 'data_files', '3_0', 'McMurdo')) for filename in glob.glob("*error*"): os.remove(filename) os.system("new_make_magic_plots.py") lines = pmag.magic_read("images.txt")[0] for line in lines[-3:]: print(line) self.assertEqual(len(lines), 541) self.assertFalse("image" in lines[0].keys()) self.assertFalse(glob.glob("errors.txt")) num_pngs = len(glob.glob("*png")) num_thumbnails = len(glob.glob("*thumb.png")) self.assertEqual(num_pngs / 2, num_thumbnails) self.assertFalse(glob.glob("thumbnail_errors.txt"))
def get_Data(magic_file): #------------------------------------------------ # Read magic measurement file and sort to blocks #------------------------------------------------ Data={} try: meas_data,file_type=pmag.magic_read(magic_file) except: print "-E- ERROR: Cant read magic_measurement.txt file. File is corrupted." return Data # get list of unique specimen names #sids=pmag.get_specs(meas_data) # samples ID's for rec in meas_data: s=rec["er_specimen_name"] method_codes= rec["magic_method_codes"].strip('\n') method_codes.replace(" ","") methods=method_codes.split(":") if "LP-AN-TRM" in methods: if s not in Data.keys(): Data[s]={} if 'atrmblock' not in Data[s].keys(): Data[s]['atrmblock']=[] Data[s]['atrmblock'].append(rec) if "LP-AN-ARM" in methods: if s not in Data.keys(): Data[s]={} if 'aarmblock' not in Data[s].keys(): Data[s]['aarmblock']=[] Data[s]['aarmblock'].append(rec) return (Data)
def main(): """ NAME thellier_magic.py DESCRIPTION plots Thellier-Thellier, allowing interactive setting of bounds and customizing of selection criteria. Saves and reads interpretations from a pmag_specimen formatted table, default: thellier_specimens.txt SYNTAX thellier_magic.py [command line options] OPTIONS -h prints help message and quits -f MEAS, set magic_measurements input file -fsp PRIOR, set pmag_specimen prior interpretations file -fan ANIS, set rmag_anisotropy file for doing the anisotropy corrections -fcr CRIT, set criteria file for grading. -fmt [svg,png,jpg], format for images - default is svg -sav, saves plots with out review (default format) -spc SPEC, plots single specimen SPEC, saves plot with specified format with optional -b bounds adn quits -b BEG END: sets bounds for calculation BEG: starting step for slope calculation END: ending step for slope calculation -z use only z component difference for pTRM calculation DEFAULTS MEAS: magic_measurements.txt REDO: thellier_redo CRIT: NONE PRIOR: NONE OUTPUT figures: ALL: numbers refer to temperature steps in command line window 1) Arai plot: closed circles are zero-field first/infield open circles are infield first/zero-field triangles are pTRM checks squares are pTRM tail checks VDS is vector difference sum diamonds are bounds for interpretation 2) Zijderveld plot: closed (open) symbols are X-Y (X-Z) planes X rotated to NRM direction 3) (De/Re)Magnetization diagram: circles are NRM remaining squares are pTRM gained 4) equal area projections: green triangles are pTRM gained direction red (purple) circles are lower(upper) hemisphere of ZI step directions blue (cyan) squares are lower(upper) hemisphere IZ step directions 5) Optional: TRM acquisition 6) Optional: TDS normalization command line window: list is: temperature step numbers, temperatures (C), Dec, Inc, Int (units of magic_measuements) list of possible commands: type letter followed by return to select option saving of plots creates .svg format files with specimen_name, plot type as name """ # # initializations # meas_file,critout,inspec="magic_measurements.txt","","thellier_specimens.txt" first=1 inlt=0 version_num=pmag.get_version() TDinit,Tinit,field,first_save=0,0,-1,1 user,comment,AniSpec,locname="",'',"","" ans,specimen,recnum,start,end=0,0,0,0,0 plots,pmag_out,samp_file,style=0,"","","svg" verbose=pmagplotlib.verbose fmt='.'+style # # default acceptance criteria # accept=pmag.default_criteria(0)[0] # set the default criteria # # parse command line options # Zdiff,anis=0,0 spc,BEG,END="","","" if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind=sys.argv.index('-f') meas_file=sys.argv[ind+1] if '-fsp' in sys.argv: ind=sys.argv.index('-fsp') inspec=sys.argv[ind+1] if '-fan' in sys.argv: ind=sys.argv.index('-fan') anisfile=sys.argv[ind+1] anis=1 anis_data,file_type=pmag.magic_read(anisfile) if verbose: print "Anisotropy data read in from ", anisfile if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt='.'+sys.argv[ind+1] if '-dpi' in sys.argv: ind=sys.argv.index('-dpi') dpi='.'+sys.argv[ind+1] else: dpi=100 if '-sav' in sys.argv: plots=1 verbose=0 if '-z' in sys.argv: Zdiff=1 if '-spc' in sys.argv: ind=sys.argv.index('-spc') spc=sys.argv[ind+1] if '-b' in sys.argv: ind=sys.argv.index('-b') BEG=int(sys.argv[ind+1]) END=int(sys.argv[ind+2]) if '-fcr' in sys.argv: ind=sys.argv.index('-fcr') critout=sys.argv[ind+1] crit_data,file_type=pmag.magic_read(critout) if file_type!='pmag_criteria': if verbose: print 'bad pmag_criteria file, using no acceptance criteria' accept=pmag.default_criteria(1)[0] else: if verbose: print "Acceptance criteria read in from ", critout accept={'pmag_criteria_code':'ACCEPTANCE','er_citation_names':'This study'} for critrec in crit_data: if 'sample_int_sigma_uT' in critrec.keys(): # accommodate Shaar's new criterion critrec['sample_int_sigma']='%10.3e'%(eval(critrec['sample_int_sigma_uT'])*1e-6) for key in critrec.keys(): if key not in accept.keys() and critrec[key]!='': accept[key]=critrec[key] try: open(inspec,'rU') PriorRecs,file_type=pmag.magic_read(inspec) if file_type != 'pmag_specimens': print file_type print file_type,inspec," is not a valid pmag_specimens file " sys.exit() for rec in PriorRecs: if 'magic_software_packages' not in rec.keys():rec['magic_software_packages']="" except IOError: PriorRecs=[] if verbose:print "starting new specimen interpretation file: ",inspec meas_data,file_type=pmag.magic_read(meas_file) if file_type != 'magic_measurements': print file_type print file_type,"This is not a valid magic_measurements file " sys.exit() backup=0 # define figure numbers for arai, zijderveld and # de-,re-magization diagrams AZD={} AZD['deremag'], AZD['zijd'],AZD['arai'],AZD['eqarea']=1,2,3,4 pmagplotlib.plot_init(AZD['arai'],5,5) pmagplotlib.plot_init(AZD['zijd'],5,5) pmagplotlib.plot_init(AZD['deremag'],5,5) pmagplotlib.plot_init(AZD['eqarea'],5,5) # # # # get list of unique specimen names # CurrRec=[] sids=pmag.get_specs(meas_data) # get plots for specimen s - default is just to step through arai diagrams # if spc!="": specimen =sids.index(spc) while specimen < len(sids): methcodes=[] if verbose: print sids[specimen],specimen+1, 'of ', len(sids) MeasRecs=[] s=sids[specimen] datablock,trmblock,tdsrecs=[],[],[] PmagSpecRec={} if first==0: for key in keys:PmagSpecRec[key]="" # make sure all new records have same set of keys PmagSpecRec["er_analyst_mail_names"]=user PmagSpecRec["specimen_correction"]='u' # # find the data from the meas_data file for this specimen # for rec in meas_data: if rec["er_specimen_name"]==s: MeasRecs.append(rec) if "magic_method_codes" not in rec.keys(): rec["magic_method_codes"]="" methods=rec["magic_method_codes"].split(":") meths=[] for meth in methods: meths.append(meth.strip()) # take off annoying spaces methods="" for meth in meths: if meth.strip() not in methcodes and "LP-" in meth:methcodes.append(meth.strip()) methods=methods+meth+":" methods=methods[:-1] rec["magic_method_codes"]=methods if "LP-PI-TRM" in meths: datablock.append(rec) if "LP-TRM" in meths: trmblock.append(rec) if "LP-TRM-TD" in meths: tdsrecs.append(rec) if len(trmblock)>2 and inspec!="": if Tinit==0: Tinit=1 AZD['TRM']=5 pmagplotlib.plot_init(AZD['TRM'],5,5) elif Tinit==1: # clear the TRM figure if not needed pmagplotlib.clearFIG(AZD['TRM']) if len(tdsrecs)>2: if TDinit==0: TDinit=1 AZD['TDS']=6 pmagplotlib.plot_init(AZD['TDS'],5,5) elif TDinit==1: # clear the TDS figure if not needed pmagplotlib.clearFIG(AZD['TDS']) if len(datablock) <4: if backup==0: specimen+=1 if verbose: print 'skipping specimen - moving forward ', s else: specimen-=1 if verbose: print 'skipping specimen - moving backward ', s # # collect info for the PmagSpecRec dictionary # else: rec=datablock[0] PmagSpecRec["er_citation_names"]="This study" PmagSpecRec["er_specimen_name"]=s PmagSpecRec["er_sample_name"]=rec["er_sample_name"] PmagSpecRec["er_site_name"]=rec["er_site_name"] PmagSpecRec["er_location_name"]=rec["er_location_name"] locname=rec['er_location_name'].replace('/','-') if "er_expedition_name" in rec.keys():PmagSpecRec["er_expedition_name"]=rec["er_expedition_name"] if "magic_instrument_codes" not in rec.keys():rec["magic_instrument_codes"]="" PmagSpecRec["magic_instrument_codes"]=rec["magic_instrument_codes"] PmagSpecRec["measurement_step_unit"]="K" if "magic_experiment_name" not in rec.keys(): rec["magic_experiment_name"]="" else: PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"] meths=rec["magic_method_codes"].split() # sort data into types araiblock,field=pmag.sortarai(datablock,s,Zdiff) first_Z=araiblock[0] GammaChecks=araiblock[5] if len(first_Z)<3: if backup==0: specimen+=1 if verbose: print 'skipping specimen - moving forward ', s else: specimen-=1 if verbose: print 'skipping specimen - moving backward ', s else: backup=0 zijdblock,units=pmag.find_dmag_rec(s,meas_data) recnum=0 if verbose: print "index step Dec Inc Int Gamma" for plotrec in zijdblock: if GammaChecks!="": gamma="" for g in GammaChecks: if g[0]==plotrec[0]-273: gamma=g[1] break if gamma!="": print '%i %i %7.1f %7.1f %8.3e %7.1f' % (recnum,plotrec[0]-273,plotrec[1],plotrec[2],plotrec[3],gamma) else: print '%i %i %7.1f %7.1f %8.3e ' % (recnum,plotrec[0]-273,plotrec[1],plotrec[2],plotrec[3]) recnum += 1 pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0]) if verbose:pmagplotlib.drawFIGS(AZD) if len(tdsrecs)>2: # a TDS experiment tdsblock=[] # make a list for the TDS data Mkeys=['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measuruement_magn_mass'] mkey,k="",0 while mkey=="" and k<len(Mkeys)-1: # find which type of intensity key= Mkeys[k] if key in tdsrecs[0].keys() and tdsrecs[0][key]!="": mkey=key k+=1 if mkey=="":break # get outta here Tnorm="" for tdrec in tdsrecs: meths=tdrec['magic_method_codes'].split(":") for meth in meths: meth.replace(" ","") # strip off potential nasty spaces if 'LT-T-I' in meths and Tnorm=="": # found first total TRM Tnorm=float(tdrec[mkey]) # normalize by total TRM tdsblock.append([273,zijdblock[0][3]/Tnorm,1.]) # put in the zero step if 'LT-T-Z' in meths and Tnorm!="": # found a LP-TRM-TD demag step, now need complementary LT-T-Z from zijdblock step=float(tdrec['treatment_temp']) Tint="" if mkey!="": Tint=float(tdrec[mkey]) if Tint!="": for zrec in zijdblock: if zrec[0]==step: # found matching tdsblock.append([step,zrec[3]/Tnorm,Tint/Tnorm]) break if len(tdsblock)>2: pmagplotlib.plotTDS(AZD['TDS'],tdsblock,s+':LP-PI-TDS:') if verbose:pmagplotlib(drawFIGS(AZD)) else: print "Something wrong here" if anis==1: # look up anisotropy data for this specimen AniSpec="" for aspec in anis_data: if aspec["er_specimen_name"]==PmagSpecRec["er_specimen_name"]: AniSpec=aspec if verbose: print 'Found anisotropy record...' break if inspec !="": if verbose: print 'Looking up saved interpretation....' found = 0 for k in range(len(PriorRecs)): try: if PriorRecs[k]["er_specimen_name"]==s: found =1 CurrRec.append(PriorRecs[k]) for j in range(len(zijdblock)): if float(zijdblock[j][0])==float(PriorRecs[k]["measurement_step_min"]):start=j if float(zijdblock[j][0])==float(PriorRecs[k]["measurement_step_max"]):end=j pars,errcode=pmag.PintPars(datablock,araiblock,zijdblock,start,end,accept) pars['measurement_step_unit']="K" pars['experiment_type']='LP-PI-TRM' del PriorRecs[k] # put in CurrRec, take out of PriorRecs if errcode!=1: pars["specimen_lab_field_dc"]=field pars["specimen_int"]=-1*field*pars["specimen_b"] pars["er_specimen_name"]=s if verbose: print 'Saved interpretation: ' pars,kill=pmag.scoreit(pars,PmagSpecRec,accept,'',verbose) pmagplotlib.plotB(AZD,araiblock,zijdblock,pars) if verbose:pmagplotlib.drawFIGS(AZD) if len(trmblock)>2: blab=field best=pars["specimen_int"] Bs,TRMs=[],[] for trec in trmblock: Bs.append(float(trec['treatment_dc_field'])) TRMs.append(float(trec['measurement_magn_moment'])) NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc Mp,Bp=[],[] for k in range(int(max(Bs)*1e6)): Bp.append(float(k)*1e-6) npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM(AZD['TRM'],Bs,TRMs,Bp,Mp,NLpars,trec['magic_experiment_name']) PmagSpecRec['specimen_int']=NLpars['banc'] if verbose: print 'Banc= ',float(NLpars['banc'])*1e6 pmagplotlib.drawFIGS(AZD) mpars=pmag.domean(araiblock[1],start,end,'DE-BFL') if verbose: print 'pTRM direction= ','%7.1f'%(mpars['specimen_dec']),' %7.1f'%(mpars['specimen_inc']),' MAD:','%7.1f'%(mpars['specimen_mad']) if AniSpec!="": CpTRM=pmag.Dir_anis_corr([mpars['specimen_dec'],mpars['specimen_inc']],AniSpec) AniSpecRec=pmag.doaniscorr(PmagSpecRec,AniSpec) if verbose: print 'Anisotropy corrected TRM direction= ','%7.1f'%(CpTRM[0]),' %7.1f'%(CpTRM[1]) print 'Anisotropy corrected intensity= ',float(AniSpecRec['specimen_int'])*1e6 else: print 'error on specimen ',s except: pass if verbose and found==0: print ' None found :( ' if spc!="": if BEG!="": pars,errcode=pmag.PintPars(datablock,araiblock,zijdblock,BEG,END,accept) pars['measurement_step_unit']="K" pars["specimen_lab_field_dc"]=field pars["specimen_int"]=-1*field*pars["specimen_b"] pars["er_specimen_name"]=s pars['specimen_grade']='' # ungraded pmagplotlib.plotB(AZD,araiblock,zijdblock,pars) if verbose:pmagplotlib.drawFIGS(AZD) if len(trmblock)>2: if inlt==0: inlt=1 blab=field best=pars["specimen_int"] Bs,TRMs=[],[] for trec in trmblock: Bs.append(float(trec['treatment_dc_field'])) TRMs.append(float(trec['measurement_magn_moment'])) NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc # Mp,Bp=[],[] for k in range(int(max(Bs)*1e6)): Bp.append(float(k)*1e-6) npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field files={} for key in AZD.keys(): files[key]=s+'_'+key+fmt pmagplotlib.saveP(AZD,files,dpi=dpi) sys.exit() if verbose: ans='b' while ans != "": print """ s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit: """ ans=raw_input('Return for next specimen \n') if ans=="": specimen +=1 if ans=="d": save_redo(PriorRecs,inspec) CurrRec=[] pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0]) if verbose:pmagplotlib.drawFIGS(AZD) if ans=='a': files={} for key in AZD.keys(): files[key]="LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name']+'_SA:_'+PmagSpecRec['er_sample_name']+'_SP:_'+s+'_CO:_s_TY:_'+key+fmt pmagplotlib.saveP(AZD,files) ans="" if ans=='q': print "Good bye" sys.exit() if ans=='p': specimen =specimen -1 backup = 1 ans="" if ans=='s': keepon=1 spec=raw_input('Enter desired specimen name (or first part there of): ') while keepon==1: try: specimen =sids.index(spec) keepon=0 except: tmplist=[] for qq in range(len(sids)): if spec in sids[qq]:tmplist.append(sids[qq]) print specimen," not found, but this was: " print tmplist spec=raw_input('Select one or try again\n ') ans="" if ans=='b': if end==0 or end >=len(zijdblock):end=len(zijdblock)-1 GoOn=0 while GoOn==0: answer=raw_input('Enter index of first point for calculation: ['+str(start)+'] ') try: start=int(answer) answer=raw_input('Enter index of last point for calculation: ['+str(end)+'] ') end=int(answer) if start >=0 and start <len(zijdblock)-2 and end >0 and end <len(zijdblock) or start>=end: GoOn=1 else: print "Bad endpoints - try again! " start,end=0,len(zijdblock) except ValueError: print "Bad endpoints - try again! " start,end=0,len(zijdblock) s=sids[specimen] pars,errcode=pmag.PintPars(datablock,araiblock,zijdblock,start,end,accept) pars['measurement_step_unit']="K" pars["specimen_lab_field_dc"]=field pars["specimen_int"]=-1*field*pars["specimen_b"] pars["er_specimen_name"]=s pars,kill=pmag.scoreit(pars,PmagSpecRec,accept,'',0) PmagSpecRec['specimen_scat']=pars['specimen_scat'] PmagSpecRec['specimen_frac']='%5.3f'%(pars['specimen_frac']) PmagSpecRec['specimen_gmax']='%5.3f'%(pars['specimen_gmax']) PmagSpecRec["measurement_step_min"]='%8.3e' % (pars["measurement_step_min"]) PmagSpecRec["measurement_step_max"]='%8.3e' % (pars["measurement_step_max"]) PmagSpecRec["measurement_step_unit"]="K" PmagSpecRec["specimen_int_n"]='%i'%(pars["specimen_int_n"]) PmagSpecRec["specimen_lab_field_dc"]='%8.3e'%(pars["specimen_lab_field_dc"]) PmagSpecRec["specimen_int"]='%9.4e '%(pars["specimen_int"]) PmagSpecRec["specimen_b"]='%5.3f '%(pars["specimen_b"]) PmagSpecRec["specimen_q"]='%5.1f '%(pars["specimen_q"]) PmagSpecRec["specimen_f"]='%5.3f '%(pars["specimen_f"]) PmagSpecRec["specimen_fvds"]='%5.3f'%(pars["specimen_fvds"]) PmagSpecRec["specimen_b_beta"]='%5.3f'%(pars["specimen_b_beta"]) PmagSpecRec["specimen_int_mad"]='%7.1f'%(pars["specimen_int_mad"]) PmagSpecRec["specimen_Z"]='%7.1f'%(pars["specimen_Z"]) PmagSpecRec["specimen_gamma"]='%7.1f'%(pars["specimen_gamma"]) PmagSpecRec["specimen_grade"]=pars["specimen_grade"] if pars["method_codes"]!="": tmpcodes=pars["method_codes"].split(":") for t in tmpcodes: if t.strip() not in methcodes:methcodes.append(t.strip()) PmagSpecRec["specimen_dec"]='%7.1f'%(pars["specimen_dec"]) PmagSpecRec["specimen_inc"]='%7.1f'%(pars["specimen_inc"]) PmagSpecRec["specimen_tilt_correction"]='-1' PmagSpecRec["specimen_direction_type"]='l' PmagSpecRec["direction_type"]='l' # this is redundant, but helpful - won't be imported PmagSpecRec["specimen_int_dang"]='%7.1f '%(pars["specimen_int_dang"]) PmagSpecRec["specimen_drats"]='%7.1f '%(pars["specimen_drats"]) PmagSpecRec["specimen_drat"]='%7.1f '%(pars["specimen_drat"]) PmagSpecRec["specimen_int_ptrm_n"]='%i '%(pars["specimen_int_ptrm_n"]) PmagSpecRec["specimen_rsc"]='%6.4f '%(pars["specimen_rsc"]) PmagSpecRec["specimen_md"]='%i '%(int(pars["specimen_md"])) if PmagSpecRec["specimen_md"]=='-1':PmagSpecRec["specimen_md"]="" PmagSpecRec["specimen_b_sigma"]='%5.3f '%(pars["specimen_b_sigma"]) if "IE-TT" not in methcodes:methcodes.append("IE-TT") methods="" for meth in methcodes: methods=methods+meth+":" PmagSpecRec["magic_method_codes"]=methods[:-1] PmagSpecRec["specimen_description"]=comment PmagSpecRec["magic_software_packages"]=version_num pmagplotlib.plotAZ(AZD,araiblock,zijdblock,s,units[0]) pmagplotlib.plotB(AZD,araiblock,zijdblock,pars) if verbose:pmagplotlib.drawFIGS(AZD) if len(trmblock)>2: blab=field best=pars["specimen_int"] Bs,TRMs=[],[] for trec in trmblock: Bs.append(float(trec['treatment_dc_field'])) TRMs.append(float(trec['measurement_magn_moment'])) NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc Mp,Bp=[],[] for k in range(int(max(Bs)*1e6)): Bp.append(float(k)*1e-6) npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM(AZD['TRM'],Bs,TRMs,Bp,Mp,NLpars,trec['magic_experiment_name']) if verbose: print 'Non-linear TRM corrected intensity= ',float(NLpars['banc'])*1e6 if verbose:pmagplotlib.drawFIGS(AZD) pars["specimen_lab_field_dc"]=field pars["specimen_int"]=-1*field*pars["specimen_b"] pars,kill=pmag.scoreit(pars,PmagSpecRec,accept,'',verbose) saveit=raw_input("Save this interpretation? [y]/n \n") if saveit!='n': PriorRecs.append(PmagSpecRec) # put back an interpretation specimen+=1 save_redo(PriorRecs,inspec) ans="" elif plots==1: specimen+=1 if fmt != ".pmag": files={} for key in AZD.keys(): files[key]="LO:_"+locname+'_SI:_'+PmagSpecRec['er_site_name']+'_SA:_'+PmagSpecRec['er_sample_name']+'_SP:_'+s+'_CO:_s_TY:_'+key+'_'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['deremag']='DeReMag Plot' titles['zijd']='Zijderveld Plot' titles['arai']='Arai Plot' AZD = pmagplotlib.addBorders(AZD,titles,black,purple) pmagplotlib.saveP(AZD,files,dpi=dpi) # pmagplotlib.combineFigs(s,files,3) else: # save in pmag format script="grep "+s+" output.mag | thellier -mfsi" script=script+' %8.4e'%(field) min='%i'%((pars["measurement_step_min"]-273)) Max='%i'%((pars["measurement_step_max"]-273)) script=script+" "+min+" "+Max script=script+" |plotxy;cat mypost >>thellier.ps\n" pltf.write(script) pmag.domagicmag(outf,MeasRecs) if len(CurrRec)>0: for rec in CurrRec: PriorRecs.append(rec) CurrRec=[] if plots!=1 and verbose: ans=raw_input(" Save last plot? 1/[0] ") if ans=="1": if fmt != ".pmag": files={} for key in AZD.keys(): files[key]=s+'_'+key+fmt pmagplotlib.saveP(AZD,files,dpi=dpi) else: print "\n Good bye\n" sys.exit() if len(CurrRec)>0:PriorRecs.append(CurrRec) # put back an interpretation if len(PriorRecs)>0: save_redo(PriorRecs,inspec) print 'Updated interpretations saved in ',inspec if verbose: print "Good bye"
def main(): """ NAME s_magic.py DESCRIPTION converts .s format data to magic_measurements format. SYNTAX s_magic.py [command line options] OPTIONS -h prints help message and quits -f SFILE specifies the .s file name -sig last column has sigma -typ Anisotropy type: AMS,AARM,ATRM (default is AMS) -F RFILE specifies the rmag_anisotropy file name -usr USER specify username -loc location specify location/study name -spc NUM : specify number of characters to designate a specimen, default = 0 -spn SPECNAME, this specimen has the name SPECNAME -n first column has specimen name -crd [s,g,t], specify coordinate system of data s=specimen,g=geographic,t=tilt adjusted, default is 's' -ncn NCON: naming conventionconvention NCON Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXXYYY: YYY is sample designation with Z characters from site XXX [5] sample = site [6] sample, site, location info in er_samples.txt -- NOT CURRENTLY SUPPORTED [7-Z] [XXX]YYY: XXX is site designation with Z characters from samples XXXYYY NB: all others you will have to either customize your self or e-mail [email protected] for help. DEFAULT RFILE: rmag_anisotropy.txt INPUT X11,X22,X33,X12,X23,X13 (.s format file) X11,X22,X33,X12,X23,X13,sigma (.s format file with -sig option) SID, X11,X22,X33,X12,X23,X13 (.s format file with -n option) OUTPUT rmag_anisotropy.txt format file NOTE because .s files do not have specimen names or location information, the output MagIC files will have to be changed prior to importing to data base. """ sfile, anisfile = "", "rmag_anisotropy.txt" location = 'unknown' user = "" sitename, specnum = 'unknown', 0 samp_con, Z = "", 1 user = "" dir_path = '.' name, sigma, spec = 0, 0, 'unknown' type = 'AMS' 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 "-spc" in sys.argv: ind = sys.argv.index("-spc") specnum = int(sys.argv[ind + 1]) if specnum != 0: specnum = -specnum if "-spn" in sys.argv: ind = sys.argv.index("-spn") spec = sys.argv[ind + 1] if '-f' in sys.argv: ind = sys.argv.index('-f') sfile = sys.argv[ind + 1] if '-sig' in sys.argv: sigma = 1 if '-typ' in sys.argv: ind = sys.argv.index('-typ') type = sys.argv[ind + 1] if '-F' in sys.argv: ind = sys.argv.index('-F') anisfile = sys.argv[ind + 1] if '-usr' in sys.argv: ind = sys.argv.index('-usr') user = sys.argv[ind + 1] if '-loc' in sys.argv: ind = sys.argv.index('-loc') location = sys.argv[ind + 1] if "-n" in sys.argv: name = 1 coord = '-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 "-ncn" in sys.argv: ind = sys.argv.index("-ncn") samp_con = sys.argv[ind + 1] if "4" in samp_con: if "-" not in samp_con: print("option [4] must be in form 4-Z where Z is an integer") sys.exit() else: Z = samp_con.split("-")[1] samp_con = "4" if samp_con == '6': Samps, filetype = pmag.magic_read(dirpath + '/er_samples.txt') # # get down to bidness sfile = dir_path + '/' + sfile anisfile = dir_path + '/' + anisfile input = open(sfile, 'r') AnisRecs = [] linecnt = 0 citation = "This study" # read in data for line in input.readlines(): AnisRec = {} rec = line.split() if name == 1: k = 1 spec = rec[0] else: k = 0 trace = float(rec[k]) + float(rec[k + 1]) + float(rec[k + 2]) s1 = '%10.9e' % (old_div(float(rec[k]), trace)) s2 = '%10.9e' % (old_div(float(rec[k + 1]), trace)) s3 = '%10.9e' % (old_div(float(rec[k + 2]), trace)) s4 = '%10.9e' % (old_div(float(rec[k + 3]), trace)) s5 = '%10.9e' % (old_div(float(rec[k + 4]), trace)) s6 = '%10.9e' % (old_div(float(rec[k + 5]), trace)) AnisRec["er_citation_names"] = citation AnisRec["er_specimen_name"] = spec if specnum != 0: AnisRec["er_sample_name"] = spec[:specnum] else: AnisRec["er_sample_name"] = spec if samp_con == "6": for samp in Samps: if samp['er_sample_name'] == AnisRec["er_sample_name"]: sitename = samp['er_site_name'] location = samp['er_location_name'] elif samp_con != "": sitename = pmag.parse_site(AnisRec['er_sample_name'], samp_con, Z) AnisRec["er_location_name"] = location AnisRec["er_site_name"] = sitename AnisRec["er_anylist_mail_names"] = user if type == 'AMS': AnisRec["anisotropy_type"] = "AMS" AnisRec["magic_experiment_names"] = spec + ":LP-X" else: AnisRec["anisotropy_type"] = type AnisRec["magic_experiment_names"] = spec + ":LP-" + type AnisRec["anisotropy_s1"] = s1 AnisRec["anisotropy_s2"] = s2 AnisRec["anisotropy_s3"] = s3 AnisRec["anisotropy_s4"] = s4 AnisRec["anisotropy_s5"] = s5 AnisRec["anisotropy_s6"] = s6 if sigma == 1: AnisRec["anisotropy_sigma"] = '%10.8e' % (old_div( float(rec[k + 6]), trace)) AnisRec["anisotropy_unit"] = 'SI' AnisRec["anisotropy_tilt_correction"] = coord AnisRec["magic_method_codes"] = 'LP-' + type AnisRecs.append(AnisRec) pmag.magic_write(anisfile, AnisRecs, 'rmag_anisotropy') print('data saved in ', anisfile)
def main(): """ NAME agm_magic.py DESCRIPTION converts Micromag agm files to magic format SYNTAX agm_magic.py [-h] [command line options] OPTIONS -usr USER: identify user, default is "" - put in quotation marks! -bak: this is a IRM backfield curve -f FILE, specify input file, required -fsa SAMPFILE, specify er_samples.txt file relating samples, site and locations names,default is none -F MFILE, specify magic measurements formatted output file, default is agm_measurements.txt -spn SPEC, specimen name, default is base of input file name, e.g. SPECNAME.agm -spc NUM, specify number of characters to designate a specimen, default = 0 -Fsp SPECFILE : name of er_specimens.txt file for appending data to [default: er_specimens.txt] -ncn NCON,: specify naming convention: default is #1 below -syn SYN, synthetic specimen name -loc LOCNAME : specify location/study name, should have either LOCNAME or SAMPFILE (unless synthetic) -ins INST : specify which instrument was used (e.g, SIO-Maud), default is "" -u units: [cgs,SI], default is cgs Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX [5] site name same as sample [6] site is entered under a separate column -- NOT CURRENTLY SUPPORTED [7-Z] [XXXX]YYY: XXXX is site designation with Z characters with sample name XXXXYYYY [8] specimen is a synthetic - it has no sample, site, location information NB: all others you will have to customize your self or e-mail [email protected] for help. OUTPUT MagIC format files: magic_measurements, er_specimens, er_sample, er_site """ citation='This study' MeasRecs=[] units='cgs' meth="LP-HYS" version_num=pmag.get_version() args=sys.argv fmt='old' er_sample_name,er_site_name,er_location_name="","","" inst="" er_location_name="unknown" er_synthetic_name="" user="" er_site_name="" dir_path='.' dm=3 if "-WD" in args: ind=args.index("-WD") dir_path=args[ind+1] if "-ID" in args: ind = args.index("-ID") input_dir_path = args[ind+1] else: input_dir_path = dir_path output_dir_path = dir_path specfile = output_dir_path+'/er_specimens.txt' output = output_dir_path+"/agm_measurements.txt" if "-h" in args: print(main.__doc__) sys.exit() if "-bak" in args: meth="LP-IRM-DCD" output = output_dir_path+"/irm_measurements.txt" if "-new" in args: fmt='new' if "-usr" in args: ind=args.index("-usr") user=args[ind+1] if '-F' in args: ind=args.index("-F") output = output_dir_path+'/'+args[ind+1] if '-f' in args: ind=args.index("-f") agm_file= input_dir_path+'/'+args[ind+1] er_specimen_name=args[ind+1].split('.')[0] else: print("agm_file field is required option") print(main.__doc__) sys.exit() if '-Fsp' in args: ind=args.index("-Fsp") specfile= output_dir_path+'/'+args[ind+1] specnum,samp_con,Z=0,'1',1 if "-spc" in args: ind=args.index("-spc") specnum=int(args[ind+1]) if specnum!=0:specnum=-specnum if "-spn" in args: ind=args.index("-spn") er_specimen_name=args[ind+1] #elif "-syn" not in args: # print "you must specify a specimen name" # sys.exit() if "-syn" in args: ind=args.index("-syn") er_synthetic_name=args[ind+1] er_specimen_name="" if "-loc" in args: ind=args.index("-loc") er_location_name=args[ind+1] if "-fsa" in args: ind=args.index("-fsa") sampfile = input_dir_path+'/'+args[ind+1] Samps,file_type=pmag.magic_read(sampfile) print('sample_file successfully read in') if "-ncn" in args: ind=args.index("-ncn") samp_con=sys.argv[ind+1] if "4" in samp_con: if "-" not in samp_con: print("option [4] must be in form 4-Z where Z is an integer") sys.exit() else: Z=samp_con.split("-")[1] samp_con="4" if "7" in samp_con: if "-" not in samp_con: print("option [7] must be in form 7-Z where Z is an integer") sys.exit() else: Z=samp_con.split("-")[1] samp_con="7" if "-ins" in args: ind=args.index("-ins") inst=args[ind+1] if "-u" in args: ind=args.index("-u") units=args[ind+1] dm = pmag.get_named_arg_from_sys("-DM", 2) ErSpecRecs,filetype=pmag.magic_read(specfile) ErSpecRec,MeasRec={},{} ErSpecRec['er_citation_names']="This study" ErSpecRec['er_specimen_name']=er_specimen_name ErSpecRec['er_synthetic_name']=er_synthetic_name if specnum!=0: ErSpecRec["er_sample_name"]=er_specimen_name[:specnum] else: ErSpecRec["er_sample_name"]=er_specimen_name if "-fsa" in args and er_synthetic_name=="": for samp in Samps: if samp["er_sample_name"] == ErSpecRec["er_sample_name"]: ErSpecRec["er_location_name"]=samp["er_location_name"] ErSpecRec["er_site_name"]=samp["er_site_name"] break elif int(samp_con)!=6 and int(samp_con)!=8: site=pmag.parse_site(ErSpecRec['er_sample_name'],samp_con,Z) ErSpecRec["er_site_name"]=site ErSpecRec["er_location_name"]=er_location_name ErSpecRec['er_scientist_mail_names']=user.strip() insert=1 for rec in ErSpecRecs: if rec['er_specimen_name']==er_specimen_name: insert=0 break if insert==1: ErSpecRecs.append(ErSpecRec) ErSpecRecs,keylist=pmag.fillkeys(ErSpecRecs) pmag.magic_write(specfile,ErSpecRecs,'er_specimens') print("specimen name put in ",specfile) f=open(agm_file,'r') Data=f.readlines() if "ASCII" not in Data[0]:fmt='new' measnum,start=1,"" if fmt=='new': # new Micromag formatted file end=2 for skip in range(len(Data)): line=Data[skip] rec=line.split() if 'Units' in line:units=rec[-1] if "Raw" in rec: start=skip+2 if "Field" in rec and "Moment" in rec and start=="": start=skip+2 break else: start = 2 end=1 for i in range(start,len(Data)-end): # skip header stuff MeasRec={} for key in list(ErSpecRec.keys()): MeasRec[key]=ErSpecRec[key] MeasRec['magic_instrument_codes']=inst MeasRec['magic_method_codes']=meth if 'er_synthetic_name' in list(MeasRec.keys()) and MeasRec['er_synthetic_name']!="": MeasRec['magic_experiment_name']=er_synthetic_name+':'+meth else: MeasRec['magic_experiment_name']=er_specimen_name+':'+meth line=Data[i] rec=line.split(',') # data comma delimited if rec[0]!='\n': if units=='cgs': field =float(rec[0])*1e-4 # convert from oe to tesla else: field =float(rec[0]) # field in tesla if meth=="LP-HYS": MeasRec['measurement_lab_field_dc']='%10.3e'%(field) MeasRec['treatment_dc_field']='' else: MeasRec['measurement_lab_field_dc']='' MeasRec['treatment_dc_field']='%10.3e'%(field) if units=='cgs': MeasRec['measurement_magn_moment']='%10.3e'%(float(rec[1])*1e-3) # convert from emu to Am^2 else: MeasRec['measurement_magn_moment']='%10.3e'%(float(rec[1])) # Am^2 MeasRec['treatment_temp']='273' # temp in kelvin MeasRec['measurement_temp']='273' # temp in kelvin MeasRec['measurement_flag']='g' MeasRec['measurement_standard']='u' MeasRec['measurement_number']='%i'%(measnum) measnum+=1 MeasRec['magic_software_packages']=version_num MeasRecs.append(MeasRec) # now we have to relabel LP-HYS method codes. initial loop is LP-IMT, minor loops are LP-M - do this in measurements_methods function if meth=='LP-HYS': recnum=0 while float(MeasRecs[recnum]['measurement_lab_field_dc'])<float(MeasRecs[recnum+1]['measurement_lab_field_dc']) and recnum+1<len(MeasRecs): # this is LP-IMAG MeasRecs[recnum]['magic_method_codes']='LP-IMAG' MeasRecs[recnum]['magic_experiment_name']=MeasRecs[recnum]['er_specimen_name']+":"+'LP-IMAG' recnum+=1 # if int(dm)==2: pmag.magic_write(output,MeasRecs,'magic_measurements') else: print ('MagIC 3 is not supported yet') sys.exit() pmag.magic_write(output,MeasRecs,'measurements') print("results put in ", output)
def main(): """ NAME quick_hyst.py DESCRIPTION makes plots of hysteresis data SYNTAX quick_hyst.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specify input file, default is magic_measurements.txt -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg] """ args = sys.argv PLT = 1 plots = 0 user, meas_file = "", "magic_measurements.txt" pltspec = "" dir_path = '.' fmt = 'png' verbose = pmagplotlib.verbose version_num = pmag.get_version() if '-WD' in args: ind = args.index('-WD') dir_path = args[ind+1] if "-h" in args: print(main.__doc__) sys.exit() if "-usr" in args: ind = args.index("-usr") user = args[ind+1] if '-f' in args: ind = args.index("-f") meas_file = args[ind+1] if '-sav' in args: verbose = 0 plots = 1 if '-spc' in args: ind = args.index("-spc") pltspec = args[ind+1] verbose = 0 plots = 1 if '-fmt' in args: ind = args.index("-fmt") fmt = args[ind+1] meas_file = dir_path+'/'+meas_file # # meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(main.__doc__) print('bad file') sys.exit() # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs, RemRecs = [], [] HDD = {} HDD['hyst'] = 1 pmagplotlib.plot_init(HDD['hyst'], 5, 5) # # get list of unique experiment names and specimen names # experiment_names, sids = [], [] hyst_data = pmag.get_dictitem( meas_data, 'magic_method_codes', 'LP-HYS', 'has') # get all hysteresis data for rec in hyst_data: if 'er_synthetic_name' in rec.keys() and rec['er_synthetic_name'] != "": rec['er_specimen_name'] = rec['er_synthetic_name'] if rec['magic_experiment_name'] not in experiment_names: experiment_names.append(rec['magic_experiment_name']) if rec['er_specimen_name'] not in sids: sids.append(rec['er_specimen_name']) if 'measurement_temp' not in rec.keys(): # assume room T measurement unless otherwise specified rec['measurement_temp'] = '300' # k = 0 if pltspec != "": k = sids.index(pltspec) intlist = ['measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume', 'measurement_magn_mass'] while k < len(sids): locname, site, sample, synth = '', '', '', '' s = sids[k] hmeths = [] if verbose: print(s, k+1, 'out of ', len(sids)) # # B, M = [], [] # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data # get all measurements for this specimen spec = pmag.get_dictitem(hyst_data, 'er_specimen_name', s, 'T') if 'er_location_name' in spec[0].keys(): locname = spec[0]['er_location_name'] if 'er_site_name' in spec[0].keys(): site = spec[0]['er_site_name'] if 'er_sample_name' in spec[0].keys(): sample = spec[0]['er_sample_name'] if 'er_synthetic_name' in spec[0].keys(): synth = spec[0]['er_synthetic_name'] for m in intlist: # get all non-blank data for this specimen meas_data = pmag.get_dictitem(spec, m, '', 'F') if len(meas_data) > 0: break c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-'] cnum = 0 if len(meas_data) > 0: Temps = [] xlab, ylab, title = '', '', '' for rec in meas_data: if rec['measurement_temp'] not in Temps: Temps.append(rec['measurement_temp']) for t in Temps: print('working on t: ', t) t_data = pmag.get_dictitem( meas_data, 'measurement_temp', t, 'T') B, M = [], [] for rec in t_data: B.append(float(rec['measurement_lab_field_dc'])) M.append(float(rec[m])) # now plot the hysteresis curve(s) # if len(B) > 0: B = numpy.array(B) M = numpy.array(M) if t == Temps[-1]: xlab = 'Field (T)' ylab = m title = 'Hysteresis: '+s if t == Temps[0]: pmagplotlib.clearFIG(HDD['hyst']) pmagplotlib.plot_xy( HDD['hyst'], B, M, sym=c[cnum], xlab=xlab, ylab=ylab, title=title) pmagplotlib.plot_xy(HDD['hyst'], [ 1.1*B.min(), 1.1*B.max()], [0, 0], sym='k-', xlab=xlab, ylab=ylab, title=title) pmagplotlib.plot_xy(HDD['hyst'], [0, 0], [ 1.1*M.min(), 1.1*M.max()], sym='k-', xlab=xlab, ylab=ylab, title=title) if verbose: pmagplotlib.draw_figs(HDD) cnum += 1 if cnum == len(c): cnum = 0 # files = {} if plots: if pltspec != "": s = pltspec files = {} for key in HDD.keys(): if pmagplotlib.isServer: # use server plot naming convention if synth == '': filename = "LO:_"+locname+'_SI:_'+site + \ '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt else: filename = 'SY:_'+synth+'_TY:_'+key+'_.'+fmt files[key] = filename else: # use more readable plot naming convention if synth == '': filename = '' for item in [locname, site, sample, s, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) else: filename = synth+'_'+key+'.fmt' files[key] = filename pmagplotlib.save_plots(HDD, files) if pltspec != "": sys.exit() if verbose: pmagplotlib.draw_figs(HDD) ans = raw_input( "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ") if ans == "a": files = {} for key in HDD.keys(): if pmagplotlib.isServer: print('server') files[key] = "LO:_"+locname+'_SI:_'+site + \ '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt else: print('not server') filename = '' for item in [locname, site, sample, s, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) files[key] = filename print('files', files) pmagplotlib.save_plots(HDD, files) if ans == '': k += 1 if ans == "p": del HystRecs[-1] k -= 1 if ans == 'q': print("Good bye") sys.exit() if ans == 's': keepon = 1 specimen = raw_input( 'Enter desired specimen name (or first part there of): ') while keepon == 1: try: k = sids.index(specimen) keepon = 0 except: tmplist = [] for qq in range(len(sids)): if specimen in sids[qq]: tmplist.append(sids[qq]) print(specimen, " not found, but this was: ") print(tmplist) specimen = raw_input('Select one or try again\n ') k = sids.index(specimen) else: k += 1 if len(B) == 0: if verbose: print('skipping this one - no hysteresis data') k += 1
def main(): """ NAME trmaq_magic.py DESCTIPTION does non-linear trm acquisisiton correction SYNTAX trmaq_magic.py [-h][-i][command line options] OPTIONS -h prints help message and quits -i allows interactive setting of file names -f MFILE, sets magic_measurements input file -ft TSPEC, sets thellier_specimens input file -F OUT, sets output for non-linear TRM acquisition corrected data DEFAULTS MFILE: trmaq_measurements.txt TSPEC: thellier_specimens.txt OUT: NLT_specimens.txt """ meas_file = 'trmaq_measurements.txt' tspec = "thellier_specimens.txt" output = 'NLT_specimens.txt' if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-i' in sys.argv: meas_file = input( "Input magic_measurements file name? [trmaq_measurements.txt] ") if meas_file == "": meas_file = "trmaq_measurements.txt" tspec = input( " thellier_specimens file name? [thellier_specimens.txt] ") if tspec == "": tspec = "thellier_specimens.txt" output = input( "File for non-linear TRM adjusted specimen data: [NLTspecimens.txt] " ) if output == "": output = "NLT_specimens.txt" if '-f' in sys.argv: ind = sys.argv.index('-f') meas_file = sys.argv[ind + 1] if '-ft' in sys.argv: ind = sys.argv.index('-ft') tspec = sys.argv[ind + 1] if '-F' in sys.argv: ind = sys.argv.index('-F') output = sys.argv[ind + 1] # PLT = {'aq': 1} pmagplotlib.plot_init(PLT['aq'], 5, 5) # # get name of file from command line # comment = "" # # meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(file_type) print(file_type, "This is not a valid magic_measurements file ") sys.exit() sids = pmag.get_specs(meas_data) specimen = 0 # # read in thellier_specimen data # nrm, file_type = pmag.magic_read(tspec) PmagSpecRecs = [] while specimen < len(sids): # # find corresoponding paleointensity data for this specimen # s = sids[specimen] blab, best = "", "" for nrec in nrm: # pick out the Banc data for this spec if nrec["er_specimen_name"] == s: blab = float(nrec["specimen_lab_field_dc"]) best = float(nrec["specimen_int"]) TrmRec = nrec break if blab == "": print("skipping ", s, " : no best ") specimen += 1 else: print(sids[specimen], specimen + 1, 'of ', len(sids), 'Best = ', best * 1e6) MeasRecs = [] # # find the data from the meas_data file for this specimen # for rec in meas_data: if rec["er_specimen_name"] == s: meths = rec["magic_method_codes"].split(":") methcodes = [] for meth in meths: methcodes.append(meth.strip()) if "LP-TRM" in methcodes: MeasRecs.append(rec) if len(MeasRecs) < 2: specimen += 1 print('skipping specimen - no trm acquisition data ', s) # # collect info for the PmagSpecRec dictionary # else: TRMs, Bs = [], [] for rec in MeasRecs: Bs.append(float(rec['treatment_dc_field'])) TRMs.append(float(rec['measurement_magn_moment'])) NLpars = nlt.NLtrm( Bs, TRMs, best, blab, 0 ) # calculate best fit parameters through TRM acquisition data, and get new banc # Mp, Bp = [], [] for k in range(int(max(Bs) * 1e6)): Bp.append(float(k) * 1e-6) npred = nlt.TRM( Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1]) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM(PLT['aq'], Bs, TRMs, Bp, Mp, NLpars, rec['magic_experiment_name']) pmagplotlib.drawFIGS(PLT) print('Banc= ', float(NLpars['banc']) * 1e6) trmTC = {} for key in list(TrmRec.keys()): trmTC[key] = TrmRec[ key] # copy of info from thellier_specimens record trmTC['specimen_int'] = '%8.3e' % (NLpars['banc']) trmTC['magic_method_codes'] = TrmRec[ "magic_method_codes"] + ":DA-NL" PmagSpecRecs.append(trmTC) ans = input("Return for next specimen, s[a]ve plot ") if ans == 'a': Name = {'aq': rec['er_specimen_name'] + '_TRM.svg'} pmagplotlib.saveP(PLT, Name) specimen += 1 pmag.magic_write(output, PmagSpecRecs, 'pmag_specimens')
def main(): """ NAME make_magic_plots.py DESCRIPTION inspects magic directory for available plots. SYNTAX make_magic_plots.py [command line options] INPUT magic files OPTIONS -h prints help message and quits -f FILE specifies input file name -fmt [png,eps,svg,jpg,pdf] specify format, default is png """ if '-h' in sys.argv: print(main.__doc__) sys.exit() # reset log files for fname in ['log.txt', 'errors.txt']: f = os.path.join(os.getcwd(), fname) if os.path.exists(f): os.remove(f) dirlist = ['./'] dir_path = os.getcwd() # if '-fmt' in sys.argv: ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] else: fmt = 'png' if '-f' in sys.argv: ind = sys.argv.index("-f") filelist = [sys.argv[ind + 1]] else: filelist = os.listdir(dir_path) ## initialize some variables samp_file = 'samples.txt' azimuth_key = 'azimuth' meas_file = 'measurements.txt' loc_key = 'location' loc_file = 'locations.txt' method_key = 'method_codes' dec_key = 'dir_dec' inc_key = 'dir_inc' tilt_corr_key = "dir_tilt_correction" aniso_tilt_corr_key = "aniso_tilt_correction" hyst_bcr_key = "hyst_bcr" hyst_mr_key = "hyst_mr_moment" hyst_ms_key = "hyst_ms_moment" hyst_bc_key = "hyst_bc" Mkeys = ['magnitude', 'magn_moment', 'magn_volume', 'magn_mass'] results_file = 'sites.txt' hyst_file = 'specimens.txt' aniso_file = 'specimens.txt' # create contribution and propagate data throughout con = cb.Contribution() con.propagate_location_to_measurements() con.propagate_location_to_specimens() con.propagate_location_to_samples() if not con.tables: print('-E- No MagIC tables could be found in this directory') error_log("No MagIC tables found") return # check to see if propagation worked, otherwise you can't plot by location lowest_table = None for table in con.ancestry: if table in con.tables: lowest_table = table break do_full_directory = False # check that locations propagated down to the lowest table in the contribution if 'location' in con.tables[lowest_table].df.columns: # are there any locations in the lowest table? if not all(con.tables[lowest_table].df['location'].isnull()): locs = con.tables['locations'].df.index.unique() lowest_locs = con.tables[lowest_table].df['location'].unique() incorrect_locs = set(lowest_locs).difference(set(locs)) # are they actual locations? if not incorrect_locs: info_log( 'location names propagated to {}'.format(lowest_table)) else: do_full_directory = True error_log('location names did not propagate fully to {} table'. format(lowest_table)) else: do_full_directory = True error_log( 'could not propagate location names down to {} table'.format( lowest_table)) else: do_full_directory = True error_log('could not propagate location names down to {} table'.format( lowest_table)) all_data = {} all_data['measurements'] = con.tables.get('measurements', None) all_data['specimens'] = con.tables.get('specimens', None) all_data['samples'] = con.tables.get('samples', None) all_data['sites'] = con.tables.get('sites', None) all_data['locations'] = con.tables.get('locations', None) locations = con.tables['locations'].df.index.unique() dirlist = [loc for loc in locations if cb.not_null(loc) and loc != 'nan'] if not dirlist: dirlist = ["./"] if do_full_directory: dirlist = ["./"] # plot the whole contribution as one location if dirlist == ["./"]: error_log('plotting the entire contribution as one location') for fname in os.listdir("."): if fname.endswith(".txt"): shutil.copy(fname, "tmp_" + fname) # if possible, go through all data by location # use tmp_*.txt files to separate out by location for loc in dirlist: print('\nworking on: ', loc) def get_data(dtype, loc_name): """ Extract data of type dtype for location loc_name. Write tmp_dtype.txt files if possible. """ if cb.not_null(all_data[dtype]): data_container = all_data[dtype] data_df = data_container.df[data_container.df['location'] == loc_name] data = data_container.convert_to_pmag_data_list(df=data_df) res = data_container.write_magic_file( 'tmp_{}.txt'.format(dtype), df=data_df) if not res: return [] return data meas_data = get_data('measurements', loc) spec_data = get_data('specimens', loc) samp_data = get_data('samples', loc) site_data = get_data('sites', loc) location_data = get_data('locations', loc) if loc == "./": # if you can't sort by location, do everything together try: meas_data = con.tables[ 'measurements'].convert_to_pmag_data_list() except KeyError: meas_data = None try: spec_data = con.tables['specimens'].convert_to_pmag_data_list() except KeyError: spec_data = None try: samp_data = con.tables['samples'].convert_to_pmag_data_list() except KeyError: samp_data = None try: site_data = con.tables['sites'].convert_to_pmag_data_list() except KeyError: site_data = None crd = 's' if samp_file in filelist: # find coordinate systems samps = samp_data file_type = "samples" # get all non blank sample orientations Srecs = pmag.get_dictitem(samps, azimuth_key, '', 'F') if len(Srecs) > 0: crd = 'g' print('using geographic coordinates') else: print('using specimen coordinates') else: if VERBOSE: print('-I- No sample data found') if meas_file in filelist: # start with measurement data print('working on measurements data') data = meas_data file_type = 'measurements' # looking for zeq_magic possibilities # get all non blank method codes AFZrecs = pmag.get_dictitem(data, method_key, 'LT-AF-Z', 'has') # get all non blank method codes TZrecs = pmag.get_dictitem(data, method_key, 'LT-T-Z', 'has') # get all non blank method codes MZrecs = pmag.get_dictitem(data, method_key, 'LT-M-Z', 'has') # get all dec measurements Drecs = pmag.get_dictitem(data, dec_key, '', 'F') # get all inc measurements Irecs = pmag.get_dictitem(data, inc_key, '', 'F') for key in Mkeys: Mrecs = pmag.get_dictitem(data, key, '', 'F') # get intensity data if len(Mrecs) > 0: break # potential for stepwise demag curves if len(AFZrecs) > 0 or len(TZrecs) > 0 or len(MZrecs) > 0 and len( Drecs) > 0 and len(Irecs) > 0 and len(Mrecs) > 0: CMD = 'zeq_magic.py -f tmp_measurements.txt -fsp tmp_specimens.txt -fsa tmp_samples.txt -fsi tmp_sites.txt -sav -fmt ' + fmt + ' -crd ' + crd print(CMD) info_log(CMD, loc) os.system(CMD) # looking for thellier_magic possibilities if len(pmag.get_dictitem(data, method_key, 'LP-PI-TRM', 'has')) > 0: CMD = 'thellier_magic.py -f tmp_measurements.txt -fsp tmp_specimens.txt -sav -fmt ' + fmt print(CMD) info_log(CMD, loc) os.system(CMD) # looking for hysteresis possibilities if len(pmag.get_dictitem(data, method_key, 'LP-HYS', 'has')) > 0: # find hyst experiments # check for reqd columns missing = check_for_reqd_cols(data, ['treat_temp']) if missing: error_log( 'LP-HYS method code present, but required column(s) [{}] missing' .format(", ".join(missing)), loc, "quick_hyst.py") else: CMD = 'quick_hyst.py -f tmp_measurements.txt -sav -fmt ' + fmt print(CMD) info_log(CMD, loc) os.system(CMD) # equal area plots of directional data # at measurment level (by specimen) if data: missing = check_for_reqd_cols(data, ['dir_dec', 'dir_inc']) if not missing: CMD = "eqarea_magic.py -f tmp_measurements.txt -obj spc -sav -no-tilt -fmt " + fmt print(CMD) os.system(CMD) info_log(CMD, loc, "eqarea_magic.py") else: if VERBOSE: print('-I- No measurement data found') # site data if results_file in filelist: print('-I- result file found', results_file) data = site_data file_type = 'sites' print('-I- working on site directions') print('number of datapoints: ', len(data), loc) dec_key = 'dir_dec' inc_key = 'dir_inc' int_key = 'int_abs' SiteDIs = pmag.get_dictitem(data, dec_key, "", 'F') # find decs SiteDIs = pmag.get_dictitem(SiteDIs, inc_key, "", 'F') # find decs and incs dir_data_found = len(SiteDIs) print('{} Dec/inc pairs found'.format(dir_data_found)) # only individual results - not poles # get only individual results (if result_type col is available) if SiteDIs: if 'result_type' in SiteDIs[0]: SiteDIs = pmag.get_dictitem(SiteDIs, 'result_type', 'i', 'has') # then convert tilt_corr_key to correct format old_SiteDIs = SiteDIs SiteDIs = [] for rec in old_SiteDIs: if tilt_corr_key not in rec: error_log( "Directional data found, but missing {}, can't plot directions" .format(tilt_corr_key), loc, "eqarea_magic.py") break if cb.is_null( rec[tilt_corr_key]) and rec[tilt_corr_key] != 0: rec[tilt_corr_key] = "" else: try: rec[tilt_corr_key] = str( int(float(rec[tilt_corr_key]))) except ValueError: rec[tilt_corr_key] = "" SiteDIs.append(rec) print('number of individual directions: ', len(SiteDIs)) # tilt corrected coordinates SiteDIs_t = pmag.get_dictitem(SiteDIs, tilt_corr_key, '100', 'T', float_to_int=True) print('number of tilt corrected directions: ', len(SiteDIs_t)) SiteDIs_g = pmag.get_dictitem( SiteDIs, tilt_corr_key, '0', 'T', float_to_int=True) # geographic coordinates print('number of geographic directions: ', len(SiteDIs_g)) SiteDIs_s = pmag.get_dictitem( SiteDIs, tilt_corr_key, '-1', 'T', float_to_int=True) # sample coordinates print('number of sample directions: ', len(SiteDIs_s)) SiteDIs_x = pmag.get_dictitem(SiteDIs, tilt_corr_key, '', 'T') # no coordinates print('number of no coordinates directions: ', len(SiteDIs_x)) if len(SiteDIs_t) > 0 or len(SiteDIs_g) > 0 or len( SiteDIs_s) > 0 or len(SiteDIs_x) > 0: CRD = "" if len(SiteDIs_t) > 0: CRD = ' -crd t' elif len(SiteDIs_g) > 0: CRD = ' -crd g' elif len(SiteDIs_s) > 0: CRD = ' -crd s' CMD = 'eqarea_magic.py -f tmp_sites.txt -fsp tmp_specimens.txt -fsa tmp_samples.txt -flo tmp_locations.txt -sav -fmt ' + fmt + CRD print(CMD) info_log(CMD, loc) os.system(CMD) else: if dir_data_found: error_log( '{} dec/inc pairs found, but no equal area plots were made' .format(dir_data_found), loc, "equarea_magic.py") # print('-I- working on VGP map') VGPs = pmag.get_dictitem(SiteDIs, 'vgp_lat', "", 'F') # are there any VGPs? if len(VGPs) > 0: # YES! CMD = 'vgpmap_magic.py -f tmp_sites.txt -prj moll -res c -sym ro 5 -sav -fmt png' print(CMD) info_log(CMD, loc, 'vgpmap_magic.py') os.system(CMD) else: print('-I- No vgps found') print('-I- Look for intensities') # is there any intensity data? if site_data: if int_key in site_data[0].keys(): # old way, wasn't working right: #CMD = 'magic_select.py -key ' + int_key + ' 0. has -F tmp1.txt -f tmp_sites.txt' Selection = pmag.get_dictkey(site_data, int_key, dtype="f") with open('intensities.txt', 'w') as out: for rec in Selection: if rec != 0: out.write(str(rec * 1e6) + "\n") histfile = 'LO:_' + loc + \ '_TY:_intensities_histogram:_.' + fmt # maybe run histplot.main here instead, so you can return an error message CMD = "histplot.py -b 1 -xlab 'Intensity (uT)' -sav -f intensities.txt -F " + histfile os.system(CMD) info_log(CMD, loc) print(CMD) else: print('-I- No intensities found') else: print('-I- No intensities found') ## if hyst_file in filelist: print('working on hysteresis', hyst_file) data = spec_data file_type = 'specimens' hdata = pmag.get_dictitem(data, hyst_bcr_key, '', 'F') hdata = pmag.get_dictitem(hdata, hyst_mr_key, '', 'F') hdata = pmag.get_dictitem(hdata, hyst_ms_key, '', 'F') # there are data for a dayplot hdata = pmag.get_dictitem(hdata, hyst_bc_key, '', 'F') if len(hdata) > 0: CMD = 'dayplot_magic.py -f tmp_specimens.txt -sav -fmt ' + fmt info_log(CMD, loc) print(CMD) else: print('no hysteresis data found') if aniso_file in filelist: # do anisotropy plots if possible print('working on anisotropy', aniso_file) data = spec_data file_type = 'specimens' # make sure there is some anisotropy data if not data: print('No anisotropy data found') elif 'aniso_s' not in data[0]: print('No anisotropy data found') else: # get specimen coordinates if aniso_tilt_corr_key not in data[0]: sdata = data else: sdata = pmag.get_dictitem(data, aniso_tilt_corr_key, '-1', 'T', float_to_int=True) # get specimen coordinates gdata = pmag.get_dictitem(data, aniso_tilt_corr_key, '0', 'T', float_to_int=True) # get specimen coordinates tdata = pmag.get_dictitem(data, aniso_tilt_corr_key, '100', 'T', float_to_int=True) CRD = "" CMD = 'aniso_magic.py -x -B -sav -fmt ' + fmt if len(sdata) > 3: CMD = CMD + ' -crd s' print(CMD) info_log(CMD, loc) os.system(CMD) if len(gdata) > 3: CMD = CMD + ' -crd g' print(CMD) info_log(CMD, loc) os.system(CMD) if len(tdata) > 3: CMD = CMD + ' -crd t' print(CMD) info_log(CMD, loc) os.system(CMD) # remove temporary files for fname in glob.glob('tmp*.txt'): os.remove(fname) try: os.remove('intensities.txt') except FileNotFoundError: pass if loc_file in filelist: data, file_type = pmag.magic_read(loc_file) # read in location data print('-I- working on pole map') poles = pmag.get_dictitem(data, 'pole_lat', "", 'F') # are there any poles? poles = pmag.get_dictitem(poles, 'pole_lon', "", 'F') # are there any poles? if len(poles) > 0: # YES! CMD = 'polemap_magic.py -sav -fmt png' print(CMD) info_log(CMD, "all locations", "polemap_magic.py") os.system(CMD) else: print('-I- No poles found')
def main(): """ NAME mk_redo.py DESCRIPTION Makes thellier_redo and zeq_redo files from existing pmag_specimens format file SYNTAX mk_redo.py [-h] [command line options] INPUT takes specimens.txt formatted input file OPTIONS -h: prints help message and quits -f FILE: specify input file, default is 'specimens.txt' -F REDO: specify output file suffix, default is redo so that output filenames are 'thellier_redo' for thellier data and 'zeq_redo' for direction only data OUTPUT makes a thellier_redo or a zeq_redo format file """ if '-h' in sys.argv: print(main.__doc__) sys.exit() zfile, tfile = 'zeq_redo', 'thellier_redo' zredo, tredo = "", "" dir_path = pmag.get_named_arg('-WD', '.') inspec = pmag.get_named_arg('-f', 'specimens.txt') if '-F' in sys.argv: ind = sys.argv.index('-F') redo = sys.argv[ind + 1] tfile = redo zfile = redo inspec = pmag.resolve_file_name(inspec, dir_path) zfile = pmag.resolve_file_name(zfile, dir_path) tfile = pmag.resolve_file_name(tfile, dir_path) # # read in data # specs = [] prior_spec_data, file_type = pmag.magic_read(inspec) if file_type != 'specimens': print(file_type, " this is not a valid pmag_specimens file") sys.exit() outstrings = [] for spec in prior_spec_data: tmp = spec["method_codes"].split(":") meths = [] for meth in tmp: methods = meth.strip().split('-') for m in methods: if m not in meths: meths.append(m) if 'DIR' in meths: # DE-BFL, DE-BFP or DE-FM specs.append(spec['specimen']) if 'dir_comp' in list(spec.keys()) and spec['dir_comp'] != "" and spec['dir_comp'] != " ": comp_name = spec['dir_comp'] else: comp_name = string.ascii_uppercase[specs.count( spec['specimen']) - 1] calculation_type = "DE-BFL" # assume default calculation type is best-fit line if "BFP" in meths: calculation_type = 'DE-BFP' elif "FM" in meths: calculation_type = 'DE-FM' if zredo == "": zredo = open(zfile, "w") outstring = '%s %s %s %s %s \n' % ( spec["specimen"], calculation_type, spec["meas_step_min"], spec["meas_step_max"], comp_name) if outstring not in outstrings: zredo.write(outstring) outstrings.append(outstring) # only writes unique interpretions elif "PI" in meths and "TRM" in meths: # thellier record if tredo == "": tredo = open(tfile, "w") outstring = '%s %i %i \n' % (spec["specimen"], float( spec["meas_step_min"]), float(spec["meas_step_max"])) if outstring not in outstrings: tredo.write(outstring) outstrings.append(outstring) # only writes unique interpretions print('Redo files saved to: ', zfile, tfile)
def main(): """ NAME mst_magic.py DESCRIPTION converts MsT data (T,M) to magic_measurements format files SYNTAX mst_magic.py [command line options] OPTIONS -h: prints the help message and quits. -usr USER: identify user, default is "" -f FILE: specify T,M format input file, required -fsa SFILE: name with sample, site, location information -F FILE: specify output file, default is MsT_measurements.txt -dc H: specify applied field during measurement, default is 0.5 T -syn : This is a synthetic specimen and has no sample/site/location information -spn SPEC: specimen name -spc NUM : specify number of characters to designate a specimen, default = 0 -loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic -ncn NCON: specify naming convention: default is #1 below Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX [5] site name same as sample [6] site is entered under a separate column [7-Z] [XXXX]YYY: XXXX is site designation with Z characters with sample name XXXXYYYY NB: all others you will have to customize your self or e-mail [email protected] for help. INPUT files: T M: T is in Centigrade and M is uncalibrated magnitude """ # initialize some stuff samp_con,Z="1","0" dir_path='.' citation='This study' args=sys.argv specnum,measnum=0,1 # # get command line arguments # user="" if '-WD' in args: ind=args.index("-WD") dir_path=args[ind+1] meas_file=dir_path+"/MsT_measurements.txt" if "-h" in args: print main.__doc__ sys.exit() if "-usr" in args: ind=args.index("-usr") user=args[ind+1] labfield='0.5' if "-dc" in args: ind=args.index("-dc") labfield=args[ind+1] if '-F' in args: ind=args.index("-F") meas_file=dir_path+'/'+args[ind+1] if "-fsa" in args: ind=args.index("-fsa") samp_file=dir_path+'/'+args[ind+1] Samps,file_type=pmag.magic_read(samp_file) if '-f' in args: ind=args.index("-f") infile=dir_path+'/'+args[ind+1] try: input=open(infile,'rU') except: print "bad mag file name" sys.exit() else: print main.__doc__ print "-f is required option" sys.exit() if "-spc" in args: ind=args.index("-spc") specnum=int(args[ind+1]) if specnum!=0:specnum=-specnum er_location_name,syn,specimen_name='unknown',0,'unknown' if "-loc" in args: ind=args.index("-loc") er_location_name=args[ind+1] if "-spn" in args: ind=args.index("-spn") specimen_name=args[ind+1] else: print main.__doc__ print "-spn is required option" sys.exit() if "-syn" in args: syn=1 if "-ncn" in args: ind=args.index("-ncn") samp_con=sys.argv[ind+1] if "4" in samp_con: if "-" not in samp_con: print "option [4] must be in form 4-Z where Z is an integer" sys.exit() else: Z=samp_con.split("-")[1] samp_con="4" samp_con=sys.argv[ind+1] if "7" in samp_con: if "-" not in samp_con: print "option [7] must be in form 7-Z where Z is an integer" sys.exit() else: Z=samp_con.split("-")[1] samp_con="7" MagRecs,specs=[],[] version_num=pmag.get_version() data=input.readlines() T0=float(data[0].split()[0]) for line in data: instcode="" if len(line)>1: MagRec={} if syn==0: MagRec['er_location_name']=er_location_name MagRec['magic_software_packages']=version_num MagRec["treatment_dc_field"]=labfield rec=line.split() T=float(rec[0]) MagRec["measurment_temp"]='%8.3e' % (float(rec[0])+273.) # temp in kelvin if T>T0: MagRec["magic_method_codes"]='LP-MW-I' elif T<T0: MagRec["magic_method_codes"]='LP-MC-I' T0=T else: print 'skipping repeated temperature step' MagRec["magic_method_codes"]='' T0=T MagRec["measurement_magnitude"]='%10.3e'% (float(rec[1])) # uncalibrated magnitude if syn==0: MagRec["er_specimen_name"]=specimen_name MagRec["er_site_name"]="" if specnum!=0: MagRec["er_sample_name"]=specimen_name[:specnum] else: MagRec["er_sample_name"]=specimen_name if "-fsa" in args: for samp in Samps: if samp["er_sample_name"] == MagRec["er_sample_name"]: MagRec["er_location_name"]=samp["er_location_name"] MagRec["er_site_name"]=samp["er_site_name"] break elif int(samp_con)!=6: site=pmag.parse_site(MagRec['er_sample_name'],samp_con,Z) MagRec["er_site_name"]=site if MagRec['er_site_name']=="": print 'No site name found for: ',MagRec['er_specimen_name'],MagRec['er_sample_name'] if MagRec["er_location_name"]=="": print 'no location name for: ',MagRec["er_specimen_name"] else: MagRec["er_synthetic_name"]=specimen_name MagRec["er_location_name"]="" MagRec["er_sample_name"]="" MagRec["er_site_name"]="" MagRec["er_specimen_name"]="" MagRec["magic_instrument_codes"]=instcode MagRec["er_analyst_mail_names"]=user MagRec["er_citation_names"]=citation MagRec["measurement_flag"]='g' MagRec["measurement_number"]=str(measnum) measnum+=1 MagRecs.append(MagRec) for rec in MagRecs: # sort out the measurements by experiment type rec['magic_experiment_name']=specimen_name if rec['magic_method_codes']=='LP-MW-I': rec["magic_experiment_name"]=specimen_name+':LP-MW-I:Curie' elif rec['magic_method_codes']=='LP-MC-I': rec["magic_experiment_name"]=specimen_name+':LP-MC-I' pmag.magic_write(meas_file,MagRecs,'magic_measurements') print "results put in ",meas_file
def convert(**kwargs): # initialize some stuff methcode="LP-NO" phi,theta,peakfield,labfield=0,0,0,0 pTRM,MD=0,0 dec=[315,225,180,135,45,90,270,270,270,90,180,180,0,0,0] inc=[0,0,0,0,0,-45,-45,0,45,45,45,-45,-90,-45,45] tdec=[0,90,0,180,270,0,0,90,0] tinc=[0,0,90,0,0,-90,0,0,90] missing=1 demag="N" citations='This study' fmt='old' Samps=[] trm=0 irm=0 #get args user = kwargs.get('user', '') dir_path = kwargs.get('dir_path', '.') output_dir_path = dir_path meas_file = kwargs.get('meas_file', 'measurements.txt') spec_file = kwargs.get('spec_file', 'specimens.txt') # specimen outfile samp_file = kwargs.get('samp_file', 'samples.txt') # sample outfile site_file = kwargs.get('site_file', 'sites.txt') # site outfile loc_file = kwargs.get('loc_file', 'locations.txt') # location outfile mag_file = kwargs.get('mag_file', '') labfield = kwargs.get('labfield', '') if labfield: labfield = float(labfield) *1e-6 else: labfield = 0 phi = kwargs.get('phi', 0) if phi: phi = float(phi) else: phi = 0 theta = kwargs.get('theta', 0) if theta: theta=float(theta) else: theta = 0 peakfield = kwargs.get('peakfield', 0) if peakfield: peakfield=float(peakfield) *1e-3 else: peakfield = 0 specnum = kwargs.get('specnum', 0) samp_con = kwargs.get('samp_con', '1') location = kwargs.get('location', 'unknown') samp_infile = kwargs.get('samp_infile', '') syn = kwargs.get('syn', 0) institution = kwargs.get('institution', '') syntype = kwargs.get('syntype', '') inst = kwargs.get('inst', '') noave = kwargs.get('noave', 0) codelist = kwargs.get('codelist', '') coil = kwargs.get('coil', '') cooling_rates = kwargs.get('cooling_rates', '') lat = kwargs.get('lat', '') lon = kwargs.get('lon', '') timezone = kwargs.get('timezone', 'UTC') # make sure all initial values are correctly set up (whether they come from the command line or a GUI) if samp_infile: Samps, file_type = pmag.magic_read(samp_infile) if coil: coil = str(coil) methcode="LP-IRM" irmunits = "V" if coil not in ["1","2","3"]: print(__doc__) print('not a valid coil specification') return False, '{} is not a valid coil specification'.format(coil) if mag_file: lines = pmag.open_file(mag_file) if not lines: print("you must provide a valid mag_file") return False, "you must provide a valid mag_file" if not mag_file: print(__doc__) print("mag_file field is required option") return False, "mag_file field is required option" if specnum!=0: specnum=-specnum if "4" == samp_con[0]: if "-" not in samp_con: print("naming convention option [4] must be in form 4-Z where Z is an integer") print('---------------') return False, "naming convention option [4] must be in form 4-Z where Z is an integer" else: Z=samp_con.split("-")[1] samp_con="4" if "7" == samp_con[0]: if "-" not in samp_con: print("option [7] must be in form 7-Z where Z is an integer") return False, "option [7] must be in form 7-Z where Z is an integer" else: Z=samp_con.split("-")[1] samp_con="7" else: Z = 0 if codelist: codes=codelist.split(':') if "AF" in codes: demag='AF' if'-dc' not in sys.argv: methcode="LT-AF-Z" if'-dc' in sys.argv: methcode="LT-AF-I" if "T" in codes: demag="T" if '-dc' not in sys.argv: methcode="LT-T-Z" if '-dc' in sys.argv: methcode="LT-T-I" if "I" in codes: methcode="LP-IRM" irmunits="mT" if "I3d" in codes: methcode="LT-T-Z:LP-IRM-3D" if "S" in codes: demag="S" methcode="LP-PI-TRM:LP-PI-ALT-AFARM" trm_labfield=labfield ans=input("DC lab field for ARM step: [50uT] ") if ans=="": arm_labfield=50e-6 else: arm_labfield=float(ans)*1e-6 ans=input("temperature for total trm step: [600 C] ") if ans=="": trm_peakT=600+273 # convert to kelvin else: trm_peakT=float(ans)+273 # convert to kelvin if "G" in codes: methcode="LT-AF-G" if "D" in codes: methcode="LT-AF-D" if "TRM" in codes: demag="T" trm=1 if "CR" in codes: demag="T" cooling_rate_experiment=1 if command_line: ind=sys.argv.index("CR") cooling_rates=sys.argv[ind+1] cooling_rates_list=cooling_rates.split(',') else: cooling_rates_list=str(cooling_rates).split(',') if demag=="T" and "ANI" in codes: methcode="LP-AN-TRM" if demag=="T" and "CR" in codes: methcode="LP-CR-TRM" if demag=="AF" and "ANI" in codes: methcode="LP-AN-ARM" if labfield==0: labfield=50e-6 if peakfield==0: peakfield=.180 MeasRecs,SpecRecs,SampRecs,SiteRecs,LocRecs=[],[],[],[],[] version_num=pmag.get_version() ################################## for line in lines: instcode="" if len(line)>2: MeasRec,SpecRec,SampRec,SiteRec,LocRec={},{},{},{},{} MeasRec['software_packages']=version_num MeasRec["description"]="" MeasRec["treat_temp"]='%8.3e' % (273) # room temp in kelvin MeasRec["meas_temp"]='%8.3e' % (273) # room temp in kelvin MeasRec["treat_ac_field"]='0' MeasRec["treat_dc_field"]='0' MeasRec["treat_dc_field_phi"]='0' MeasRec["treat_dc_field_theta"]='0' meas_type="LT-NO" rec=line.split() try: float(rec[0]); print("No specimen name for line #%d in the measurement file"%lines.index(line)); continue except ValueError: pass if rec[1]==".00":rec[1]="0.00" treat=rec[1].split('.') if methcode=="LP-IRM": if irmunits=='mT': labfield=float(treat[0])*1e-3 else: labfield=pmag.getfield(irmunits,coil,treat[0]) if rec[1][0]!="-": phi,theta=0.,90. else: phi,theta=0.,-90. meas_type="LT-IRM" MeasRec["treat_dc_field"]='%8.3e'%(labfield) MeasRec["treat_dc_field_phi"]='%7.1f'%(phi) MeasRec["treat_dc_field_theta"]='%7.1f'%(theta) if len(rec)>6: code1=rec[6].split(';') # break e.g., 10/15/02;7:45 indo date and time if len(code1)==2: # old format with AM/PM missing=0 code2=code1[0].split('/') # break date into mon/day/year code3=rec[7].split(';') # break e.g., AM;C34;200 into time;instr/axes/measuring pos;number of measurements yy=int(code2[2]) if yy <90: yyyy=str(2000+yy) else: yyyy=str(1900+yy) mm=int(code2[0]) if mm<10: mm="0"+str(mm) else: mm=str(mm) dd=int(code2[1]) if dd<10: dd="0"+str(dd) else: dd=str(dd) time=code1[1].split(':') hh=int(time[0]) if code3[0]=="PM":hh=hh+12 if hh<10: hh="0"+str(hh) else: hh=str(hh) min=int(time[1]) if min<10: min= "0"+str(min) else: min=str(min) dt=yyyy+":"+mm+":"+dd+":"+hh+":"+min+":00" local = pytz.timezone(timezone) naive = datetime.datetime.strptime(dt, "%Y:%m:%d:%H:%M:%S") local_dt = local.localize(naive, is_dst=None) utc_dt = local_dt.astimezone(pytz.utc) MeasRec["timestamp"]=utc_dt.strftime("%Y-%m-%dT%H:%M:%S")+"Z" if inst=="": if code3[1][0]=='C':instcode='SIO-bubba' if code3[1][0]=='G':instcode='SIO-flo' else: instcode='' MeasRec["meas_n_orient"]=code3[1][2] elif len(code1)>2: # newest format (cryo7 or later) if "LP-AN-ARM" not in methcode:labfield=0 fmt='new' date=code1[0].split('/') # break date into mon/day/year yy=int(date[2]) if yy <90: yyyy=str(2000+yy) else: yyyy=str(1900+yy) mm=int(date[0]) if mm<10: mm="0"+str(mm) else: mm=str(mm) dd=int(date[1]) if dd<10: dd="0"+str(dd) else: dd=str(dd) time=code1[1].split(':') hh=int(time[0]) if hh<10: hh="0"+str(hh) else: hh=str(hh) min=int(time[1]) if min<10: min= "0"+str(min) else: min=str(min) dt=yyyy+":"+mm+":"+dd+":"+hh+":"+min+":00" local = pytz.timezone(timezone) naive = datetime.datetime.strptime(dt, "%Y:%m:%d:%H:%M:%S") local_dt = local.localize(naive, is_dst=None) utc_dt = local_dt.astimezone(pytz.utc) MeasRec["timestamp"]=utc_dt.strftime("%Y-%m-%dT%H:%M:%S")+"Z" if inst=="": if code1[6][0]=='C': instcode='SIO-bubba' if code1[6][0]=='G': instcode='SIO-flo' else: instcode='' if len(code1)>1: MeasRec["meas_n_orient"]=code1[6][2] else: MeasRec["meas_n_orient"]=code1[7] # takes care of awkward format with bubba and flo being different if user=="":user=code1[5] if code1[2][-1]=='C': demag="T" if code1[4]=='microT' and float(code1[3])!=0. and "LP-AN-ARM" not in methcode: labfield=float(code1[3])*1e-6 if code1[2]=='mT' and methcode!="LP-IRM": demag="AF" if code1[4]=='microT' and float(code1[3])!=0.: labfield=float(code1[3])*1e-6 if code1[4]=='microT' and labfield!=0. and meas_type!="LT-IRM": phi,theta=0.,-90. if demag=="T": meas_type="LT-T-I" if demag=="AF": meas_type="LT-AF-I" MeasRec["treat_dc_field"]='%8.3e'%(labfield) MeasRec["treat_dc_field_phi"]='%7.1f'%(phi) MeasRec["treat_dc_field_theta"]='%7.1f'%(theta) if code1[4]=='' or labfield==0. and meas_type!="LT-IRM": if demag=='T':meas_type="LT-T-Z" if demag=="AF":meas_type="LT-AF-Z" MeasRec["treat_dc_field"]='0' if syn==0: specimen=rec[0] MeasRec["specimen"]=specimen if specnum!=0: sample=rec[0][:specnum] else: sample=rec[0] if samp_infile and Samps: # if samp_infile was provided AND yielded sample data samp=pmag.get_dictitem(Samps,'sample',sample,'T') if len(samp)>0: location=samp[0]["location"] site=samp[0]["site"] else: location='' site='' else: site=pmag.parse_site(sample,samp_con,Z) if location!='' and location not in [x['location'] if 'location' in list(x.keys()) else '' for x in LocRecs]: LocRec['location'] = location LocRec['lat_n'] = lat LocRec['lat_s'] = lat LocRec['lon_e'] = lon LocRec['lon_w'] = lon LocRecs.append(LocRec) if site!='' and site not in [x['site'] if 'site' in list(x.keys()) else '' for x in SiteRecs]: SiteRec['location'] = location SiteRec['site'] = site SiteRec['lat'] = lat SiteRec['lon'] = lon SiteRecs.append(SiteRec) if sample!='' and sample not in [x['sample'] if 'sample' in list(x.keys()) else '' for x in SampRecs]: SampRec['site'] = site SampRec['sample'] = sample SampRecs.append(SampRec) if specimen!='' and specimen not in [x['specimen'] if 'specimen' in list(x.keys()) else '' for x in SpecRecs]: SpecRec["specimen"]=specimen SpecRec['sample'] = sample SpecRecs.append(SpecRec) else: specimen=rec[0] MeasRec["specimen"]=specimen if specnum!=0: sample=rec[0][:specnum] else: sample=rec[0] site=pmag.parse_site(sample,samp_con,Z) if location!='' and location not in [x['location'] if 'location' in list(x.keys()) else '' for x in LocRecs]: LocRec['location'] = location LocRec['lat_n'] = lat LocRec['lat_s'] = lat LocRec['lon_e'] = lon LocRec['lon_w'] = lon LocRecs.append(LocRec) if site!='' and site not in [x['site'] if 'site' in list(x.keys()) else '' for x in SiteRecs]: SiteRec['location'] = location SiteRec['site'] = site SiteRec['lat'] = lat SiteRec['lon'] = lon SiteRecs.append(SiteRec) if sample!='' and sample not in [x['sample'] if 'sample' in list(x.keys()) else '' for x in SampRecs]: SampRec['site'] = site SampRec['sample'] = sample SampRecs.append(SampRec) if specimen!='' and specimen not in [x['specimen'] if 'specimen' in list(x.keys()) else '' for x in SpecRecs]: SpecRec["specimen"]=specimen SpecRec['sample'] = sample SpecRecs.append(SpecRec) SampRec["institution"]=institution SampRec["material_type"]=syntype if float(rec[1])==0: pass elif demag=="AF": if methcode != "LP-AN-ARM": MeasRec["treat_ac_field"]='%8.3e' %(float(rec[1])*1e-3) # peak field in tesla if meas_type=="LT-AF-Z": MeasRec["treat_dc_field"]='0' else: # AARM experiment if treat[1][0]=='0': meas_type="LT-AF-Z:LP-AN-ARM:" MeasRec["treat_ac_field"]='%8.3e' %(peakfield) # peak field in tesla MeasRec["treat_dc_field"]='%8.3e'%(0) if labfield!=0 and methcode!="LP-AN-ARM": print("Warning - inconsistency in mag file with lab field - overriding file with 0") else: meas_type="LT-AF-I:LP-AN-ARM" ipos=int(treat[0])-1 MeasRec["treat_dc_field_phi"]='%7.1f' %(dec[ipos]) MeasRec["treat_dc_field_theta"]='%7.1f'% (inc[ipos]) MeasRec["treat_dc_field"]='%8.3e'%(labfield) MeasRec["treat_ac_field"]='%8.3e' %(peakfield) # peak field in tesla elif demag=="T" and methcode == "LP-AN-TRM": MeasRec["treat_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin if treat[1][0]=='0': meas_type="LT-T-Z:LP-AN-TRM" MeasRec["treat_dc_field"]='%8.3e'%(0) MeasRec["treat_dc_field_phi"]='0' MeasRec["treat_dc_field_theta"]='0' else: MeasRec["treat_dc_field"]='%8.3e'%(labfield) if treat[1][0]=='7': # alteration check as final measurement meas_type="LT-PTRM-I:LP-AN-TRM" else: meas_type="LT-T-I:LP-AN-TRM" # find the direction of the lab field in two ways: # (1) using the treatment coding (XX.1=+x, XX.2=+y, XX.3=+z, XX.4=-x, XX.5=-y, XX.6=-z) ipos_code=int(treat[1][0])-1 # (2) using the magnetization DEC=float(rec[4]) INC=float(rec[5]) if INC < 45 and INC > -45: if DEC>315 or DEC<45: ipos_guess=0 if DEC>45 and DEC<135: ipos_guess=1 if DEC>135 and DEC<225: ipos_guess=3 if DEC>225 and DEC<315: ipos_guess=4 else: if INC >45: ipos_guess=2 if INC <-45: ipos_guess=5 # prefer the guess over the code ipos=ipos_guess MeasRec["treat_dc_field_phi"]='%7.1f' %(tdec[ipos]) MeasRec["treat_dc_field_theta"]='%7.1f'% (tinc[ipos]) # check it if ipos_guess!=ipos_code and treat[1][0]!='7': print("-E- ERROR: check specimen %s step %s, ATRM measurements, coding does not match the direction of the lab field!"%(rec[0],".".join(list(treat)))) elif demag=="S": # Shaw experiment if treat[1][1]=='0': if int(treat[0])!=0: MeasRec["treat_ac_field"]='%8.3e' % (float(treat[0])*1e-3) # AF field in tesla MeasRec["treat_dc_field"]='0' meas_type="LT-AF-Z" # first AF else: meas_type="LT-NO" MeasRec["treat_ac_field"]='0' MeasRec["treat_dc_field"]='0' elif treat[1][1]=='1': if int(treat[0])==0: MeasRec["treat_ac_field"]='%8.3e' %(peakfield) # peak field in tesla MeasRec["treat_dc_field"]='%8.3e'%(arm_labfield) MeasRec["treat_dc_field_phi"]='%7.1f'%(phi) MeasRec["treat_dc_field_theta"]='%7.1f'%(theta) meas_type="LT-AF-I" else: MeasRec["treat_ac_field"]='%8.3e' % ( float(treat[0])*1e-3) # AF field in tesla MeasRec["treat_dc_field"]='0' meas_type="LT-AF-Z" elif treat[1][1]=='2': if int(treat[0])==0: MeasRec["treat_ac_field"]='0' MeasRec["treat_dc_field"]='%8.3e'%(trm_labfield) MeasRec["treat_dc_field_phi"]='%7.1f'%(phi) MeasRec["treat_dc_field_theta"]='%7.1f'%(theta) MeasRec["treat_temp"]='%8.3e' % (trm_peakT) meas_type="LT-T-I" else: MeasRec["treat_ac_field"]='%8.3e' % ( float(treat[0])*1e-3) # AF field in tesla MeasRec["treat_dc_field"]='0' meas_type="LT-AF-Z" elif treat[1][1]=='3': if int(treat[0])==0: MeasRec["treat_ac_field"]='%8.3e' %(peakfield) # peak field in tesla MeasRec["treat_dc_field"]='%8.3e'%(arm_labfield) MeasRec["treat_dc_field_phi"]='%7.1f'%(phi) MeasRec["treat_dc_field_theta"]='%7.1f'%(theta) meas_type="LT-AF-I" else: MeasRec["treat_ac_field"]='%8.3e' % ( float(treat[0])*1e-3) # AF field in tesla MeasRec["treat_dc_field"]='0' meas_type="LT-AF-Z" # Cooling rate experient # added by rshaar elif demag=="T" and methcode == "LP-CR-TRM": MeasRec["treat_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin if treat[1][0]=='0': meas_type="LT-T-Z:LP-CR-TRM" MeasRec["treat_dc_field"]='%8.3e'%(0) MeasRec["treat_dc_field_phi"]='0' MeasRec["treat_dc_field_theta"]='0' else: MeasRec["treat_dc_field"]='%8.3e'%(labfield) if treat[1][0]=='7': # alteration check as final measurement meas_type="LT-PTRM-I:LP-CR-TRM" else: meas_type="LT-T-I:LP-CR-TRM" MeasRec["treat_dc_field_phi"]='%7.1f' % (phi) # labfield phi MeasRec["treat_dc_field_theta"]='%7.1f' % (theta) # labfield theta indx=int(treat[1][0])-1 # alteration check matjed as 0.7 in the measurement file if indx==6: cooling_time= cooling_rates_list[-1] else: cooling_time=cooling_rates_list[indx] MeasRec["description"]="cooling_rate"+":"+cooling_time+":"+"K/min" elif demag!='N': if len(treat)==1:treat.append('0') MeasRec["treat_temp"]='%8.3e' % (float(treat[0])+273.) # temp in kelvin if trm==0: # demag=T and not trmaq if treat[1][0]=='0': meas_type="LT-T-Z" else: MeasRec["treat_dc_field"]='%8.3e' % (labfield) # labfield in tesla (convert from microT) MeasRec["treat_dc_field_phi"]='%7.1f' % (phi) # labfield phi MeasRec["treat_dc_field_theta"]='%7.1f' % (theta) # labfield theta if treat[1][0]=='1':meas_type="LT-T-I" # in-field thermal step if treat[1][0]=='2': meas_type="LT-PTRM-I" # pTRM check pTRM=1 if treat[1][0]=='3': MeasRec["treat_dc_field"]='0' # this is a zero field step meas_type="LT-PTRM-MD" # pTRM tail check else: labfield=float(treat[1])*1e-6 MeasRec["treat_dc_field"]='%8.3e' % (labfield) # labfield in tesla (convert from microT) MeasRec["treat_dc_field_phi"]='%7.1f' % (phi) # labfield phi MeasRec["treat_dc_field_theta"]='%7.1f' % (theta) # labfield theta meas_type="LT-T-I:LP-TRM" # trm acquisition experiment MeasRec["dir_csd"]=rec[2] MeasRec["magn_moment"]='%10.3e'% (float(rec[3])*1e-3) # moment in Am^2 (from emu) MeasRec["dir_dec"]=rec[4] MeasRec["dir_inc"]=rec[5] MeasRec["instrument_codes"]=instcode MeasRec["analysts"]=user MeasRec["citations"]=citations if "LP-IRM-3D" in methcode : meas_type=methcode #MeasRec["method_codes"]=methcode.strip(':') MeasRec["method_codes"]=meas_type MeasRec["quality"]='g' if 'std' in rec[0]: MeasRec["standard"]='s' else: MeasRec["standard"]='u' MeasRec["treat_step_num"]='1' #print MeasRec['treat_temp'] MeasRecs.append(MeasRec) con = nb.Contribution(output_dir_path,read_tables=[]) # create MagIC tables con.add_magic_table_from_data(dtype='specimens', data=SpecRecs) con.add_magic_table_from_data(dtype='samples', data=SampRecs) con.add_magic_table_from_data(dtype='sites', data=SiteRecs) con.add_magic_table_from_data(dtype='locations', data=LocRecs) MeasOuts=pmag.measurements_methods3(MeasRecs,noave) con.add_magic_table_from_data(dtype='measurements', data=MeasOuts) # write MagIC tables to file con.tables['specimens'].write_magic_file(custom_name=spec_file) con.tables['samples'].write_magic_file(custom_name=samp_file) con.tables['sites'].write_magic_file(custom_name=site_file) con.tables['locations'].write_magic_file(custom_name=loc_file) con.tables['measurements'].write_magic_file(custom_name=meas_file) return True, meas_file
def main(): """ NAME vgpmap_magic.py DESCRIPTION makes a map of vgps and a95/dp,dm for site means in a pmag_results table SYNTAX vgpmap_magic.py [command line options] OPTIONS -h prints help and quits -eye ELAT ELON [specify eyeball location], default is 90., 0. -f FILE pmag_results format file, [default is pmag_results.txt] -res [c,l,i,h] specify resolution (crude, low, intermediate, high] -etp plot the etopo20 topographpy data (requires high resolution data set) -prj PROJ, specify one of the following: ortho = orthographic lcc = lambert conformal moll = molweide merc = mercator -sym SYM SIZE: choose a symbol and size, examples: ro 5 : small red circles bs 10 : intermediate blue squares g^ 20 : large green triangles -ell plot dp/dm or a95 ellipses -rev RSYM RSIZE : flip reverse poles to normal antipode -S: plot antipodes of all poles -age : plot the ages next to the poles -crd [g,t] : choose coordinate system, default is to plot all site VGPs -fmt [pdf, png, eps...] specify output format, default is pdf -sav save and quit DEFAULTS FILE: pmag_results.txt res: c prj: ortho ELAT,ELON = 0,0 SYM SIZE: ro 8 RSYM RSIZE: g^ 8 """ dir_path = '.' res, ages = 'c', 0 plot = 0 proj = 'ortho' results_file = 'pmag_results.txt' ell, flip = 0, 0 lat_0, lon_0 = 90., 0. fmt = 'pdf' sym, size = 'ro', 8 rsym, rsize = 'g^', 8 anti = 0 fancy = 0 coord = "" if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path = sys.argv[ind+1] if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-S' in sys.argv: anti = 1 if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind+1] if '-sav' in sys.argv: plot = 1 if '-res' in sys.argv: ind = sys.argv.index('-res') res = sys.argv[ind+1] if '-etp' in sys.argv: fancy = 1 if '-prj' in sys.argv: ind = sys.argv.index('-prj') proj = sys.argv[ind+1] if '-rev' in sys.argv: flip = 1 ind = sys.argv.index('-rev') rsym = (sys.argv[ind+1]) rsize = int(sys.argv[ind+2]) if '-sym' in sys.argv: ind = sys.argv.index('-sym') sym = (sys.argv[ind+1]) size = int(sys.argv[ind+2]) if '-eye' in sys.argv: ind = sys.argv.index('-eye') lat_0 = float(sys.argv[ind+1]) lon_0 = float(sys.argv[ind+2]) if '-ell' in sys.argv: ell = 1 if '-age' in sys.argv: ages = 1 if '-f' in sys.argv: ind = sys.argv.index('-f') results_file = sys.argv[ind+1] if '-crd' in sys.argv: ind = sys.argv.index('-crd') crd = sys.argv[ind+1] if crd == 'g': coord = '0' if crd == 't': coord = '100' results_file = dir_path+'/'+results_file data, file_type = pmag.magic_read(results_file) if file_type != 'pmag_results': print("bad results file") sys.exit() FIG = {'map': 1} pmagplotlib.plot_init(FIG['map'], 6, 6) # read in er_sites file lats, lons, dp, dm, a95 = [], [], [], [], [] Pars = [] dates, rlats, rlons = [], [], [] if 'data_type' in data[0].keys(): # get all site level data Results = pmag.get_dictitem(data, 'data_type', 'i', 'T') else: Results = data # get all non-blank latitudes Results = pmag.get_dictitem(Results, 'vgp_lat', '', 'F') # get all non-blank longitudes Results = pmag.get_dictitem(Results, 'vgp_lon', '', 'F') if coord != "": # get specified coordinate system Results = pmag.get_dictitem(Results, 'tilt_correction', coord, 'T') location = "" for rec in Results: if rec['er_location_names'] not in location: location = location+':'+rec['er_location_names'] if 'average_age' in rec.keys() and rec['average_age'] != "" and ages == 1: dates.append(rec['average_age']) lat = float(rec['vgp_lat']) lon = float(rec['vgp_lon']) if flip == 0: lats.append(lat) lons.append(lon) elif flip == 1: if lat < 0: rlats.append(-lat) lon = lon+180. if lon > 360: lon = lon-360. rlons.append(lon) else: lats.append(lat) lons.append(lon) elif anti == 1: lats.append(-lat) lon = lon+180. if lon > 360: lon = lon-360. lons.append(lon) ppars = [] ppars.append(lon) ppars.append(lat) ell1, ell2 = "", "" if 'vgp_dm' in rec.keys() and rec['vgp_dm'] != "": ell1 = float(rec['vgp_dm']) if 'vgp_dp' in rec.keys() and rec['vgp_dp'] != "": ell2 = float(rec['vgp_dp']) if 'vgp_alpha95' in rec.keys() and rec['vgp_alpha95'] != "": ell1, ell2 = float(rec['vgp_alpha95']), float(rec['vgp_alpha95']) if ell1 != "" and ell2 != "": ppars = [] ppars.append(lons[-1]) ppars.append(lats[-1]) ppars.append(ell1) ppars.append(lons[-1]) isign = abs(lats[-1])/lats[-1] ppars.append(lats[-1]-isign*90.) ppars.append(ell2) ppars.append(lons[-1]+90.) ppars.append(0.) Pars.append(ppars) location = location.strip(':') Opts = {'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360., 'lat_0': lat_0, 'lon_0': lon_0, 'proj': proj, 'sym': 'bs', 'symsize': 3, 'pltgrid': 0, 'res': res, 'boundinglat': 0.} Opts['details'] = {'coasts': 1, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 1, 'fancy': fancy} # make the base map with a blue triangle at the pole` pmagplotlib.plot_map(FIG['map'], [90.], [0.], Opts) Opts['pltgrid'] = -1 Opts['sym'] = sym Opts['symsize'] = size if len(dates) > 0: Opts['names'] = dates if len(lats) > 0: # add the lats and lons of the poles pmagplotlib.plot_map(FIG['map'], lats, lons, Opts) Opts['names'] = [] if len(rlats) > 0: Opts['sym'] = rsym Opts['symsize'] = rsize # add the lats and lons of the poles pmagplotlib.plot_map(FIG['map'], rlats, rlons, Opts) if plot == 0: pmagplotlib.draw_figs(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.plot_ell(FIG['map'], ppars, 'g.', 0, 0) elats, elons = [], [] for pt in PTS: elons.append(pt[0]) elats.append(pt[1]) # make the base map with a blue triangle at the pole` pmagplotlib.plot_map(FIG['map'], elats, elons, Opts) if plot == 0: pmagplotlib.draw_figs(FIG) files = {} for key in FIG.keys(): if pmagplotlib.isServer: # use server plot naming convention files[key] = 'LO:_'+location+'_VGP_map.'+fmt else: # use more readable plot naming convention files[key] = '{}_VGP_map.{}'.format( location.replace(' ', '_'), fmt) if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['eq'] = 'LO:_'+location+'_VGP_map' FIG = pmagplotlib.add_borders(FIG, titles, black, purple) pmagplotlib.save_plots(FIG, files) elif plot == 0: pmagplotlib.draw_figs(FIG) ans = input(" S[a]ve to save plot, Return to quit: ") if ans == "a": pmagplotlib.save_plots(FIG, files) else: print("Good bye") sys.exit() else: pmagplotlib.save_plots(FIG, files)
def main(): """ NAME foldtest_magic.py DESCRIPTION does a fold test (Tauxe, 2010) on data INPUT FORMAT pmag_specimens format file, er_samples.txt format file (for bedding) SYNTAX foldtest_magic.py [command line options] OPTIONS -h prints help message and quits -f sites formatted file [default for 3.0 is sites.txt, for 2.5, pmag_sites.txt] -fsa samples formatted file -fsi sites formatted file -exc use criteria to set acceptance criteria (supported only for data model 3) -n NB, set number of bootstraps, default is 1000 -b MIN, MAX, set bounds for untilting, default is -10, 150 -fmt FMT, specify format - default is svg -sav saves plots and quits -DM NUM MagIC data model number (2 or 3, default 3) OUTPUT 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 """ if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit kappa = 0 dir_path = pmag.get_named_arg("-WD", ".") nboot = int(float(pmag.get_named_arg("-n", 1000))) # number of bootstraps fmt = pmag.get_named_arg("-fmt", "svg") data_model_num = int(float(pmag.get_named_arg("-DM", 3))) if data_model_num == 3: infile = pmag.get_named_arg("-f", 'sites.txt') orfile = 'samples.txt' site_col = 'site' dec_col = 'dir_dec' inc_col = 'dir_inc' tilt_col = 'dir_tilt_correction' dipkey, azkey = 'bed_dip', 'bed_dip_direction' crit_col = 'criterion' critfile = 'criteria.txt' else: infile = pmag.get_named_arg("-f", 'pmag_sites.txt') orfile = 'er_samples.txt' site_col = 'er_site_name' dec_col = 'site_dec' inc_col = 'site_inc' tilt_col = 'site_tilt_correction' dipkey, azkey = 'sample_bed_dip', 'sample_bed_dip_direction' crit_col = 'pmag_criteria_code' critfile = 'pmag_criteria.txt' if '-sav' in sys.argv: plot = 1 else: plot = 0 if '-b' in sys.argv: ind = sys.argv.index('-b') untilt_min = int(sys.argv[ind+1]) untilt_max = int(sys.argv[ind+2]) else: untilt_min, untilt_max = -10, 150 if '-fsa' in sys.argv: orfile = pmag.get_named_arg("-fsa", "") elif '-fsi' in sys.argv: orfile = pmag.get_named_arg("-fsi", "") if data_model_num == 3: dipkey, azkey = 'bed_dip', 'bed_dip_direction' else: dipkey, azkey = 'site_bed_dip', 'site_bed_dip_direction' else: if data_model_num == 3: orfile = 'sites.txt' else: orfile = 'pmag_sites.txt' orfile = pmag.resolve_file_name(orfile, dir_path) infile = pmag.resolve_file_name(infile, dir_path) critfile = pmag.resolve_file_name(critfile, dir_path) df = pd.read_csv(infile, sep='\t', header=1) # keep only records with tilt_col data = df.copy() data = data[data[tilt_col].notnull()] data = data.where(data.notnull(), "") # turn into pmag data list data = list(data.T.apply(dict)) # get orientation data if data_model_num == 3: # often orientation will be in infile (sites table) if os.path.split(orfile)[1] == os.path.split(infile)[1]: ordata = df[df[azkey].notnull()] ordata = ordata[ordata[dipkey].notnull()] ordata = list(ordata.T.apply(dict)) # sometimes orientation might be in a sample file instead else: ordata = pd.read_csv(orfile, sep='\t', header=1) ordata = list(ordata.T.apply(dict)) else: ordata, file_type = pmag.magic_read(orfile) if '-exc' in sys.argv: crits, file_type = pmag.magic_read(critfile) SiteCrits = [] for crit in crits: if crit[crit_col] == "DE-SITE": SiteCrits.append(crit) #break # get to work # PLTS = {'geo': 1, 'strat': 2, 'taus': 3} # make plot dictionary if not set_env.IS_WIN: pmagplotlib.plot_init(PLTS['geo'], 5, 5) pmagplotlib.plot_init(PLTS['strat'], 5, 5) pmagplotlib.plot_init(PLTS['taus'], 5, 5) if data_model_num == 2: GEOrecs = pmag.get_dictitem(data, tilt_col, '0', 'T') else: GEOrecs = data if len(GEOrecs) > 0: # have some geographic data num_dropped = 0 DIDDs = [] # set up list for dec inc dip_direction, dip for rec in GEOrecs: # parse data dip, dip_dir = 0, -1 Dec = float(rec[dec_col]) Inc = float(rec[inc_col]) orecs = pmag.get_dictitem( ordata, site_col, rec[site_col], 'T') if len(orecs) > 0: if orecs[0][azkey] != "": dip_dir = float(orecs[0][azkey]) if orecs[0][dipkey] != "": dip = float(orecs[0][dipkey]) if dip != 0 and dip_dir != -1: if '-exc' in sys.argv: keep = 1 for site_crit in SiteCrits: crit_name = site_crit['table_column'].split('.')[1] if crit_name and crit_name in rec.keys() and rec[crit_name]: # get the correct operation (<, >=, =, etc.) op = OPS[site_crit['criterion_operation']] # then make sure the site record passes if op(float(rec[crit_name]), float(site_crit['criterion_value'])): keep = 0 if keep == 1: DIDDs.append([Dec, Inc, dip_dir, dip]) else: num_dropped += 1 else: DIDDs.append([Dec, Inc, dip_dir, dip]) if num_dropped: print("-W- Dropped {} records because each failed one or more criteria".format(num_dropped)) else: print('no geographic directional data found') sys.exit() pmagplotlib.plot_eq(PLTS['geo'], DIDDs, 'Geographic') data = np.array(DIDDs) D, I = pmag.dotilt_V(data) TCs = np.array([D, I]).transpose() pmagplotlib.plot_eq(PLTS['strat'], TCs, 'Stratigraphic') if plot == 0: pmagplotlib.draw_figs(PLTS) Percs = list(range(untilt_min, untilt_max)) Cdf, Untilt = [], [] plt.figure(num=PLTS['taus']) print('doing ', nboot, ' iterations...please be patient.....') for n in range(nboot): # 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 = np.array([1., 1., 1., 0.01*perc]) D, I = pmag.dotilt_V(PDs*tilt) TCs = np.array([D, I]).transpose() ppars = pmag.doprinc(TCs) # get principal directions Taus.append(ppars['tau1']) if n < 25: plt.plot(Percs, Taus, 'r--') # tilt that gives maximum tau Untilt.append(Percs[Taus.index(np.max(Taus))]) Cdf.append(float(n) / float(nboot)) plt.plot(Percs, Taus, 'k') plt.xlabel('% Untilting') plt.ylabel('tau_1 (red), CDF (green)') Untilt.sort() # now for CDF of tilt of maximum tau plt.plot(Untilt, Cdf, 'g') lower = int(.025*nboot) upper = int(.975*nboot) plt.axvline(x=Untilt[lower], ymin=0, ymax=1, linewidth=1, linestyle='--') plt.axvline(x=Untilt[upper], ymin=0, ymax=1, linewidth=1, linestyle='--') tit = '%i - %i %s' % (Untilt[lower], Untilt[upper], 'Percent Unfolding') print(tit) plt.title(tit) if plot == 0: pmagplotlib.draw_figs(PLTS) ans = input('S[a]ve all figures, <Return> to quit \n ') if ans != 'a': print("Good bye") sys.exit() files = {} for key in list(PLTS.keys()): files[key] = ('foldtest_'+'%s' % (key.strip()[:2])+'.'+fmt) pmagplotlib.save_plots(PLTS, files)
def main(): """ NAME dayplot_magic.py DESCRIPTION makes 'day plots' (Day et al. 1977) and squareness/coercivity, plots 'linear mixing' curve from Dunlop and Carter-Stiglitz (2006). squareness coercivity of remanence (Neel, 1955) plots after Tauxe et al. (2002) SYNTAX dayplot_magic.py [command line options] OPTIONS -h prints help message and quits -f: specify input hysteresis file, default is rmag_hysteresis.txt -fr: specify input remanence file, default is rmag_remanence.txt -fmt [svg,png,jpg] format for output plots -sav saves plots and quits quietly -n label specimen names """ args = sys.argv hyst_file, rem_file = "rmag_hysteresis.txt", "rmag_remanence.txt" dir_path = '.' verbose = pmagplotlib.verbose fmt = 'svg' # default file format if '-WD' in args: ind = args.index('-WD') dir_path = args[ind + 1] if "-h" in args: print(main.__doc__) sys.exit() if '-f' in args: ind = args.index("-f") hyst_file = args[ind + 1] if '-fr' in args: ind = args.index("-fr") rem_file = args[ind + 1] if '-fmt' in sys.argv: ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] if '-sav' in sys.argv: plots = 1 verbose = 0 else: plots = 0 if '-n' in sys.argv: label = 1 else: label = 0 hyst_file = os.path.realpath(os.path.join(dir_path, hyst_file)) rem_file = os.path.realpath(os.path.join(dir_path, rem_file)) # # initialize some variables # define figure numbers for Day,S-Bc,S-Bcr DSC = {} DSC['day'], DSC['S-Bc'], DSC['S-Bcr'], DSC['bcr1-bcr2'] = 1, 2, 3, 4 pmagplotlib.plot_init(DSC['day'], 5, 5) pmagplotlib.plot_init(DSC['S-Bc'], 5, 5) pmagplotlib.plot_init(DSC['S-Bcr'], 5, 5) pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5) # # hyst_data, file_type = pmag.magic_read(hyst_file) rem_data, file_type = pmag.magic_read(rem_file) # S, BcrBc, Bcr2, Bc, hsids, Bcr = [], [], [], [], [], [] Ms, Bcr1, Bcr1Bc, S1 = [], [], [], [] names = [] locations = '' for rec in hyst_data: if 'er_location_name' in rec.keys( ) and rec['er_location_name'] not in locations: locations = locations + rec['er_location_name'] + '_' if rec['hysteresis_bcr'] != "" and rec['hysteresis_mr_moment'] != "": S.append( float(rec['hysteresis_mr_moment']) / float(rec['hysteresis_ms_moment'])) Bcr.append(float(rec['hysteresis_bcr'])) Bc.append(float(rec['hysteresis_bc'])) BcrBc.append(Bcr[-1] / Bc[-1]) if 'er_synthetic_name' in rec.keys( ) and rec['er_synthetic_name'] != "": rec['er_specimen_name'] = rec['er_synthetic_name'] hsids.append(rec['er_specimen_name']) names.append(rec['er_specimen_name']) if len(rem_data) > 0: for rec in rem_data: if rec['remanence_bcr'] != "" and float(rec['remanence_bcr']) > 0: try: ind = hsids.index(rec['er_specimen_name']) Bcr1.append(float(rec['remanence_bcr'])) Bcr1Bc.append(Bcr1[-1] / Bc[ind]) S1.append(S[ind]) Bcr2.append(Bcr[ind]) except ValueError: if verbose: print('hysteresis data for ', rec['er_specimen_name'], ' not found') # # now plot the day and S-Bc, S-Bcr plots # leglist = [] if label == 0: names = [] if len(Bcr1) > 0: pmagplotlib.plotDay(DSC['day'], Bcr1Bc, S1, 'ro', names=names) pmagplotlib.plotSBcr(DSC['S-Bcr'], Bcr1, S1, 'ro') pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5) pmagplotlib.plotBcr(DSC['bcr1-bcr2'], Bcr1, Bcr2) else: del DSC['bcr1-bcr2'] pmagplotlib.plotDay(DSC['day'], BcrBc, S, 'bs', names=names) pmagplotlib.plotSBcr(DSC['S-Bcr'], Bcr, S, 'bs') pmagplotlib.plotSBc(DSC['S-Bc'], Bc, S, 'bs') files = {} if len(locations) > 0: locations = locations[:-1] for key in DSC.keys(): if pmagplotlib.isServer: # use server plot naming convention files[ key] = 'LO:_' + locations + '_' + 'SI:__SA:__SP:__TY:_' + key + '_.' + fmt else: # use more readable plot naming convention files[key] = '{}_{}.{}'.format(locations, key, fmt) if verbose: pmagplotlib.drawFIGS(DSC) ans = raw_input(" S[a]ve to save plots, return to quit: ") if ans == "a": pmagplotlib.saveP(DSC, files) else: sys.exit() if plots: pmagplotlib.saveP(DSC, files)
def main(): """ NAME lnp_magic.py DESCRIPTION makes equal area projections site by site from pmag_specimen formatted file with Fisher confidence ellipse using McFadden and McElhinny (1988) technique for combining lines and planes SYNTAX lnp_magic [command line options] INPUT takes magic formatted pmag_specimens file OUPUT prints site_name n_lines n_planes K alpha95 dec inc R OPTIONS -h prints help message and quits -f FILE: specify input file, default is 'pmag_specimens.txt' -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted default is specimen -fmt [svg,png,jpg] format for plots, default is svg -sav save plots and quit -P: do not plot -F FILE, specify output file of dec, inc, alpha95 data for plotting with plotdi_a and plotdi_e -exc use criteria in pmag_criteria.txt """ dir_path='.' FIG={} # plot dictionary FIG['eqarea']=1 # eqarea is figure 1 in_file,plot_key,coord='pmag_specimens.txt','er_site_name',"-1" out_file="" fmt,plt,plot='svg',1,0 Crits="" M,N,acutoff,kcutoff=180.,1,180.,0. if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-WD' in sys.argv: ind=sys.argv.index('-WD') dir_path=sys.argv[ind+1] if '-f' in sys.argv: ind=sys.argv.index("-f") in_file=sys.argv[ind+1] if '-exc' in sys.argv: Crits,file_type=pmag.magic_read(dir_path+'/pmag_criteria.txt') for crit in Crits: if 'specimen_mad' in crit: M=float(crit['specimen_mad']) if 'specimen_n' in crit: N=float(crit['specimen_n']) if 'site_alpha95' in crit: acutoff=float(crit['site_alpha95']) if 'site_k' in crit: kcutoff=float(crit['site_k']) if '-F' in sys.argv: ind=sys.argv.index("-F") out_file=sys.argv[ind+1] out=open(dir_path+'/'+out_file,'w') if '-crd' in sys.argv: ind=sys.argv.index("-crd") crd=sys.argv[ind+1] if crd=='s':coord="-1" if crd=='g':coord="0" if crd=='t':coord="100" if '-fmt' in sys.argv: ind=sys.argv.index("-fmt") fmt=sys.argv[ind+1] if '-P' in sys.argv:plt=0 if '-sav' in sys.argv:plot=1 # in_file=dir_path+'/'+in_file Specs,file_type=pmag.magic_read(in_file) if file_type!='pmag_specimens': print('Error opening file') sys.exit() sitelist=[] for rec in Specs: if rec['er_site_name'] not in sitelist: sitelist.append(rec['er_site_name']) sitelist.sort() if plt==1: EQ={} EQ['eqarea']=1 pmagplotlib.plot_init(EQ['eqarea'],4,4) for site in sitelist: print(site) data=[] for spec in Specs: if 'specimen_tilt_correction' not in list(spec.keys()):spec['specimen_tilt_correction']='-1' # assume unoriented if spec['er_site_name']==site: if 'specimen_mad' not in list(spec.keys()) or spec['specimen_mad']=="": if 'specimen_alpha95' in list(spec.keys()) and spec['specimen_alpha95']!="": spec['specimen_mad']=spec['specimen_alpha95'] else: spec['specimen_mad']='180' if spec['specimen_tilt_correction']==coord and float(spec['specimen_mad'])<=M and float(spec['specimen_n'])>=N: rec={} for key in list(spec.keys()):rec[key]=spec[key] rec["dec"]=float(spec['specimen_dec']) rec["inc"]=float(spec['specimen_inc']) rec["tilt_correction"]=spec['specimen_tilt_correction'] data.append(rec) if len(data)>2: fpars=pmag.dolnp(data,'specimen_direction_type') print("Site lines planes kappa a95 dec inc") print(site, fpars["n_lines"], fpars["n_planes"], fpars["K"], fpars["alpha95"], fpars["dec"], fpars["inc"], fpars["R"]) if out_file!="": if float(fpars["alpha95"])<=acutoff and float(fpars["K"])>=kcutoff: out.write('%s %s %s\n'%(fpars["dec"],fpars['inc'],fpars['alpha95'])) print('% tilt correction: ',coord) if plt==1: files={} files['eqarea']=site+'_'+crd+'_'+'eqarea'+'.'+fmt pmagplotlib.plotLNP(EQ['eqarea'],site,data,fpars,'specimen_direction_type') if plot==0: pmagplotlib.drawFIGS(EQ) ans=input("s[a]ve plot, [q]uit, <return> to continue:\n ") if ans=="a": pmagplotlib.saveP(EQ,files) if ans=="q": sys.exit() else: pmagplotlib.saveP(EQ,files) else: print('skipping site - not enough data with specified coordinate system')
def main(): """ NAME aniso_magic.py DESCRIPTION plots anisotropy data with either bootstrap or hext ellipses SYNTAX aniso_magic.py [-h] [command line options] OPTIONS -h plots help message and quits -usr USER: set the user name -f AFILE, specify rmag_anisotropy formatted file for input -F RFILE, specify rmag_results formatted file for output -x Hext [1963] and bootstrap -B DON'T do bootstrap, do Hext -par Tauxe [1998] parametric bootstrap -v plot bootstrap eigenvectors instead of ellipses -sit plot by site instead of entire file -crd [s,g,t] coordinate system, default is specimen (g=geographic, t=tilt corrected) -P don't make any plots - just make rmag_results table -sav don't make the rmag_results table - just save all the plots -fmt [svg, jpg, eps] format for output images, pdf default -gtc DEC INC dec,inc of pole to great circle [down(up) in green (cyan) -d Vi DEC INC; Vi (1,2,3) to compare to direction DEC INC -nb N; specifies the number of bootstraps - default is 1000 DEFAULTS AFILE: rmag_anisotropy.txt RFILE: rmag_results.txt plot bootstrap ellipses of Constable & Tauxe [1987] NOTES minor axis: circles major axis: triangles principal axis: squares directions are plotted on the lower hemisphere for bootstrapped eigenvector components: Xs: blue, Ys: red, Zs: black """ # dir_path = "." version_num = pmag.get_version() verbose = pmagplotlib.verbose args = sys.argv ipar, ihext, ivec, iboot, imeas, isite, iplot, vec = 0, 0, 0, 1, 1, 0, 1, 0 hpars, bpars, PDir = [], [], [] CS, crd = '-1', 's' nb = 1000 fmt = 'pdf' ResRecs = [] orlist = [] outfile, comp, Dir, gtcirc, PDir = 'rmag_results.txt', 0, [], 0, [] infile = 'rmag_anisotropy.txt' if "-h" in args: print(main.__doc__) sys.exit() if '-WD' in args: ind = args.index('-WD') dir_path = args[ind + 1] if '-nb' in args: ind = args.index('-nb') nb = int(args[ind + 1]) if '-usr' in args: ind = args.index('-usr') user = args[ind + 1] else: user = "" if '-B' in args: iboot, ihext = 0, 1 if '-par' in args: ipar = 1 if '-x' in args: ihext = 1 if '-v' in args: ivec = 1 if '-sit' in args: isite = 1 if '-P' in args: iplot = 0 if '-f' in args: ind = args.index('-f') infile = args[ind + 1] if '-F' in args: ind = args.index('-F') outfile = args[ind + 1] if '-crd' in sys.argv: ind = sys.argv.index('-crd') crd = sys.argv[ind + 1] if crd == 'g': CS = '0' if crd == 't': CS = '100' if '-fmt' in args: ind = args.index('-fmt') fmt = args[ind + 1] if '-sav' in args: plots = 1 verbose = 0 else: plots = 0 if '-gtc' in args: ind = args.index('-gtc') d, i = float(args[ind + 1]), float(args[ind + 2]) PDir.append(d) PDir.append(i) if '-d' in args: comp = 1 ind = args.index('-d') vec = int(args[ind + 1]) - 1 Dir = [float(args[ind + 2]), float(args[ind + 3])] # # set up plots # if infile[0] != '/': infile = dir_path + '/' + infile if outfile[0] != '/': outfile = dir_path + '/' + outfile ANIS = {} initcdf, inittcdf = 0, 0 ANIS['data'], ANIS['conf'] = 1, 2 if iboot == 1: ANIS['tcdf'] = 3 if iplot == 1: inittcdf = 1 pmagplotlib.plot_init(ANIS['tcdf'], 5, 5) if comp == 1 and iplot == 1: initcdf = 1 ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6 pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5) pmagplotlib.plot_init(ANIS['vycdf'], 5, 5) pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5) if iplot == 1: pmagplotlib.plot_init(ANIS['conf'], 5, 5) pmagplotlib.plot_init(ANIS['data'], 5, 5) # read in the data data, ifiletype = pmag.magic_read(infile) for rec in data: # find all the orientation systems if 'anisotropy_tilt_correction' not in rec.keys(): rec['anisotropy_tilt_correction'] = '-1' if rec['anisotropy_tilt_correction'] not in orlist: orlist.append(rec['anisotropy_tilt_correction']) if CS not in orlist: if len(orlist) > 0: CS = orlist[0] else: CS = '-1' if CS == '-1': crd = 's' if CS == '0': crd = 'g' if CS == '100': crd = 't' if verbose: print("desired coordinate system not available, using available: ", crd) if isite == 1: sitelist = [] for rec in data: if rec['er_site_name'] not in sitelist: sitelist.append(rec['er_site_name']) sitelist.sort() plt = len(sitelist) else: plt = 1 k = 0 while k < plt: site = "" sdata, Ss = [], [] # list of S format data Locs, Sites, Samples, Specimens, Cits = [], [], [], [], [] if isite == 0: sdata = data else: site = sitelist[k] for rec in data: if rec['er_site_name'] == site: sdata.append(rec) anitypes = [] csrecs = pmag.get_dictitem(sdata, 'anisotropy_tilt_correction', CS, 'T') for rec in csrecs: if rec['anisotropy_type'] not in anitypes: anitypes.append(rec['anisotropy_type']) if rec['er_location_name'] not in Locs: Locs.append(rec['er_location_name']) if rec['er_site_name'] not in Sites: Sites.append(rec['er_site_name']) if rec['er_sample_name'] not in Samples: Samples.append(rec['er_sample_name']) if rec['er_specimen_name'] not in Specimens: Specimens.append(rec['er_specimen_name']) if rec['er_citation_names'] not in Cits: Cits.append(rec['er_citation_names']) s = [] s.append(float(rec["anisotropy_s1"])) s.append(float(rec["anisotropy_s2"])) s.append(float(rec["anisotropy_s3"])) s.append(float(rec["anisotropy_s4"])) s.append(float(rec["anisotropy_s5"])) s.append(float(rec["anisotropy_s6"])) if s[0] <= 1.0: Ss.append(s) # protect against crap #tau,Vdirs=pmag.doseigs(s) ResRec = {} ResRec['er_location_names'] = rec['er_location_name'] ResRec['er_citation_names'] = rec['er_citation_names'] ResRec['er_site_names'] = rec['er_site_name'] ResRec['er_sample_names'] = rec['er_sample_name'] ResRec['er_specimen_names'] = rec['er_specimen_name'] ResRec['rmag_result_name'] = rec['er_specimen_name'] + ":" + rec[ 'anisotropy_type'] ResRec["er_analyst_mail_names"] = user ResRec["tilt_correction"] = CS ResRec["anisotropy_type"] = rec['anisotropy_type'] if "anisotropy_n" not in rec.keys(): rec["anisotropy_n"] = "6" if "anisotropy_sigma" not in rec.keys(): rec["anisotropy_sigma"] = "0" fpars = pmag.dohext( int(rec["anisotropy_n"]) - 6, float(rec["anisotropy_sigma"]), s) ResRec["anisotropy_v1_dec"] = '%7.1f' % (fpars['v1_dec']) ResRec["anisotropy_v2_dec"] = '%7.1f' % (fpars['v2_dec']) ResRec["anisotropy_v3_dec"] = '%7.1f' % (fpars['v3_dec']) ResRec["anisotropy_v1_inc"] = '%7.1f' % (fpars['v1_inc']) ResRec["anisotropy_v2_inc"] = '%7.1f' % (fpars['v2_inc']) ResRec["anisotropy_v3_inc"] = '%7.1f' % (fpars['v3_inc']) ResRec["anisotropy_t1"] = '%10.8f' % (fpars['t1']) ResRec["anisotropy_t2"] = '%10.8f' % (fpars['t2']) ResRec["anisotropy_t3"] = '%10.8f' % (fpars['t3']) ResRec["anisotropy_ftest"] = '%10.3f' % (fpars['F']) ResRec["anisotropy_ftest12"] = '%10.3f' % (fpars['F12']) ResRec["anisotropy_ftest23"] = '%10.3f' % (fpars['F23']) ResRec["result_description"] = 'F_crit: ' + fpars[ 'F_crit'] + '; F12,F23_crit: ' + fpars['F12_crit'] ResRec['anisotropy_type'] = pmag.makelist(anitypes) ResRecs.append(ResRec) if len(Ss) > 1: if pmagplotlib.isServer: title = "LO:_" + ResRec[ 'er_location_names'] + '_SI:_' + site + '_SA:__SP:__CO:_' + crd else: title = ResRec['er_location_names'] if site: title += "_{}".format(site) title += '_{}'.format(crd) ResRec['er_location_names'] = pmag.makelist(Locs) bpars, hpars = pmagplotlib.plotANIS(ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb) if len(PDir) > 0: pmagplotlib.plotC(ANIS['data'], PDir, 90., 'g') pmagplotlib.plotC(ANIS['conf'], PDir, 90., 'g') if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) ResRec['er_location_names'] = pmag.makelist(Locs) if plots == 1: save(ANIS, fmt, title) ResRec = {} ResRec['er_citation_names'] = pmag.makelist(Cits) ResRec['er_location_names'] = pmag.makelist(Locs) ResRec['er_site_names'] = pmag.makelist(Sites) ResRec['er_sample_names'] = pmag.makelist(Samples) ResRec['er_specimen_names'] = pmag.makelist(Specimens) ResRec['rmag_result_name'] = pmag.makelist( Sites) + ":" + pmag.makelist(anitypes) ResRec['anisotropy_type'] = pmag.makelist(anitypes) ResRec["er_analyst_mail_names"] = user ResRec["tilt_correction"] = CS if isite == "0": ResRec[ 'result_description'] = "Study average using coordinate system: " + CS if isite == "1": ResRec[ 'result_description'] = "Site average using coordinate system: " + CS if hpars != [] and ihext == 1: HextRec = {} for key in ResRec.keys(): HextRec[key] = ResRec[key] # copy over stuff HextRec["anisotropy_v1_dec"] = '%7.1f' % (hpars["v1_dec"]) HextRec["anisotropy_v2_dec"] = '%7.1f' % (hpars["v2_dec"]) HextRec["anisotropy_v3_dec"] = '%7.1f' % (hpars["v3_dec"]) HextRec["anisotropy_v1_inc"] = '%7.1f' % (hpars["v1_inc"]) HextRec["anisotropy_v2_inc"] = '%7.1f' % (hpars["v2_inc"]) HextRec["anisotropy_v3_inc"] = '%7.1f' % (hpars["v3_inc"]) HextRec["anisotropy_t1"] = '%10.8f' % (hpars["t1"]) HextRec["anisotropy_t2"] = '%10.8f' % (hpars["t2"]) HextRec["anisotropy_t3"] = '%10.8f' % (hpars["t3"]) HextRec["anisotropy_hext_F"] = '%7.1f ' % (hpars["F"]) HextRec["anisotropy_hext_F12"] = '%7.1f ' % (hpars["F12"]) HextRec["anisotropy_hext_F23"] = '%7.1f ' % (hpars["F23"]) HextRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars["e12"]) HextRec["anisotropy_v1_eta_dec"] = '%7.1f ' % (hpars["v2_dec"]) HextRec["anisotropy_v1_eta_inc"] = '%7.1f ' % (hpars["v2_inc"]) HextRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars["e13"]) HextRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars["v3_dec"]) HextRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars["v3_inc"]) HextRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars["e12"]) HextRec["anisotropy_v2_eta_dec"] = '%7.1f ' % (hpars["v1_dec"]) HextRec["anisotropy_v2_eta_inc"] = '%7.1f ' % (hpars["v1_inc"]) HextRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars["e23"]) HextRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars["v3_dec"]) HextRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars["v3_inc"]) HextRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars["e12"]) HextRec["anisotropy_v3_eta_dec"] = '%7.1f ' % (hpars["v1_dec"]) HextRec["anisotropy_v3_eta_inc"] = '%7.1f ' % (hpars["v1_inc"]) HextRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars["e23"]) HextRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars["v2_dec"]) HextRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars["v2_inc"]) HextRec["magic_method_codes"] = 'LP-AN:AE-H' if verbose: print("Hext Statistics: ") print( " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I" ) print(HextRec["anisotropy_t1"], HextRec["anisotropy_v1_dec"], HextRec["anisotropy_v1_inc"], HextRec["anisotropy_v1_eta_semi_angle"], HextRec["anisotropy_v1_eta_dec"], HextRec["anisotropy_v1_eta_inc"], HextRec["anisotropy_v1_zeta_semi_angle"], HextRec["anisotropy_v1_zeta_dec"], HextRec["anisotropy_v1_zeta_inc"]) print(HextRec["anisotropy_t2"], HextRec["anisotropy_v2_dec"], HextRec["anisotropy_v2_inc"], HextRec["anisotropy_v2_eta_semi_angle"], HextRec["anisotropy_v2_eta_dec"], HextRec["anisotropy_v2_eta_inc"], HextRec["anisotropy_v2_zeta_semi_angle"], HextRec["anisotropy_v2_zeta_dec"], HextRec["anisotropy_v2_zeta_inc"]) print(HextRec["anisotropy_t3"], HextRec["anisotropy_v3_dec"], HextRec["anisotropy_v3_inc"], HextRec["anisotropy_v3_eta_semi_angle"], HextRec["anisotropy_v3_eta_dec"], HextRec["anisotropy_v3_eta_inc"], HextRec["anisotropy_v3_zeta_semi_angle"], HextRec["anisotropy_v3_zeta_dec"], HextRec["anisotropy_v3_zeta_inc"]) HextRec['magic_software_packages'] = version_num ResRecs.append(HextRec) if bpars != []: BootRec = {} for key in ResRec.keys(): BootRec[key] = ResRec[key] # copy over stuff BootRec["anisotropy_v1_dec"] = '%7.1f' % (bpars["v1_dec"]) BootRec["anisotropy_v2_dec"] = '%7.1f' % (bpars["v2_dec"]) BootRec["anisotropy_v3_dec"] = '%7.1f' % (bpars["v3_dec"]) BootRec["anisotropy_v1_inc"] = '%7.1f' % (bpars["v1_inc"]) BootRec["anisotropy_v2_inc"] = '%7.1f' % (bpars["v2_inc"]) BootRec["anisotropy_v3_inc"] = '%7.1f' % (bpars["v3_inc"]) BootRec["anisotropy_t1"] = '%10.8f' % (bpars["t1"]) BootRec["anisotropy_t2"] = '%10.8f' % (bpars["t2"]) BootRec["anisotropy_t3"] = '%10.8f' % (bpars["t3"]) BootRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( bpars["v1_eta_inc"]) BootRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( bpars["v1_eta_dec"]) BootRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( bpars["v1_eta"]) BootRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( bpars["v1_zeta_inc"]) BootRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( bpars["v1_zeta_dec"]) BootRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( bpars["v1_zeta"]) BootRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( bpars["v2_eta_inc"]) BootRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( bpars["v2_eta_dec"]) BootRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( bpars["v2_eta"]) BootRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( bpars["v2_zeta_inc"]) BootRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( bpars["v2_zeta_dec"]) BootRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( bpars["v2_zeta"]) BootRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( bpars["v3_eta_inc"]) BootRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( bpars["v3_eta_dec"]) BootRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( bpars["v3_eta"]) BootRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( bpars["v3_zeta_inc"]) BootRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( bpars["v3_zeta_dec"]) BootRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( bpars["v3_zeta"]) BootRec["anisotropy_hext_F"] = '' BootRec["anisotropy_hext_F12"] = '' BootRec["anisotropy_hext_F23"] = '' BootRec[ "magic_method_codes"] = 'LP-AN:AE-H:AE-BS' # regular bootstrap if ipar == 1: BootRec[ "magic_method_codes"] = 'LP-AN:AE-H:AE-BS-P' # parametric bootstrap if verbose: print("Boostrap Statistics: ") print( " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I" ) print(BootRec["anisotropy_t1"], BootRec["anisotropy_v1_dec"], BootRec["anisotropy_v1_inc"], BootRec["anisotropy_v1_eta_semi_angle"], BootRec["anisotropy_v1_eta_dec"], BootRec["anisotropy_v1_eta_inc"], BootRec["anisotropy_v1_zeta_semi_angle"], BootRec["anisotropy_v1_zeta_dec"], BootRec["anisotropy_v1_zeta_inc"]) print(BootRec["anisotropy_t2"], BootRec["anisotropy_v2_dec"], BootRec["anisotropy_v2_inc"], BootRec["anisotropy_v2_eta_semi_angle"], BootRec["anisotropy_v2_eta_dec"], BootRec["anisotropy_v2_eta_inc"], BootRec["anisotropy_v2_zeta_semi_angle"], BootRec["anisotropy_v2_zeta_dec"], BootRec["anisotropy_v2_zeta_inc"]) print(BootRec["anisotropy_t3"], BootRec["anisotropy_v3_dec"], BootRec["anisotropy_v3_inc"], BootRec["anisotropy_v3_eta_semi_angle"], BootRec["anisotropy_v3_eta_dec"], BootRec["anisotropy_v3_eta_inc"], BootRec["anisotropy_v3_zeta_semi_angle"], BootRec["anisotropy_v3_zeta_dec"], BootRec["anisotropy_v3_zeta_inc"]) BootRec['magic_software_packages'] = version_num ResRecs.append(BootRec) k += 1 goon = 1 while goon == 1 and iplot == 1 and verbose: if iboot == 1: print("compare with [d]irection ") print( " plot [g]reat circle, change [c]oord. system, change [e]llipse calculation, s[a]ve plots, [q]uit " ) if isite == 1: print(" [p]revious, [s]ite, [q]uit, <return> for next ") ans = input("") if ans == "q": sys.exit() if ans == "e": iboot, ipar, ihext, ivec = 1, 0, 0, 0 e = input("Do Hext Statistics 1/[0]: ") if e == "1": ihext = 1 e = input("Suppress bootstrap 1/[0]: ") if e == "1": iboot = 0 if iboot == 1: e = input("Parametric bootstrap 1/[0]: ") if e == "1": ipar = 1 e = input("Plot bootstrap eigenvectors: 1/[0]: ") if e == "1": ivec = 1 if iplot == 1: if inittcdf == 0: ANIS['tcdf'] = 3 pmagplotlib.plot_init(ANIS['tcdf'], 5, 5) inittcdf = 1 bpars, hpars = pmagplotlib.plotANIS( ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb) if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) if ans == "c": print("Current Coordinate system is: ") if CS == '-1': print(" Specimen") if CS == '0': print(" Geographic") if CS == '100': print(" Tilt corrected") key = input( " Enter desired coordinate system: [s]pecimen, [g]eographic, [t]ilt corrected " ) if key == 's': CS = '-1' if key == 'g': CS = '0' if key == 't': CS = '100' if CS not in orlist: if len(orlist) > 0: CS = orlist[0] else: CS = '-1' if CS == '-1': crd = 's' if CS == '0': crd = 'g' if CS == '100': crd = 't' print( "desired coordinate system not available, using available: ", crd) k -= 1 goon = 0 if ans == "": if isite == 1: goon = 0 else: print("Good bye ") sys.exit() if ans == 'd': if initcdf == 0: initcdf = 1 ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6 pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5) pmagplotlib.plot_init(ANIS['vycdf'], 5, 5) pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5) Dir, comp = [], 1 print(""" Input: Vi D I to compare eigenvector Vi with direction D/I where Vi=1: principal Vi=2: major Vi=3: minor D= declination of comparison direction I= inclination of comparison direction""") con = 1 while con == 1: try: vdi = input("Vi D I: ").split() vec = int(vdi[0]) - 1 Dir = [float(vdi[1]), float(vdi[2])] con = 0 except IndexError: print(" Incorrect entry, try again ") bpars, hpars = pmagplotlib.plotANIS( ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb) Dir, comp = [], 0 if ans == 'g': con, cnt = 1, 0 while con == 1: try: print( " Input: input pole to great circle ( D I) to plot a great circle: " ) di = input(" D I: ").split() PDir.append(float(di[0])) PDir.append(float(di[1])) con = 0 except: cnt += 1 if cnt < 10: print( " enter the dec and inc of the pole on one line " ) else: print( "ummm - you are doing something wrong - i give up" ) sys.exit() pmagplotlib.plotC(ANIS['data'], PDir, 90., 'g') pmagplotlib.plotC(ANIS['conf'], PDir, 90., 'g') if verbose and plots == 0: pmagplotlib.drawFIGS(ANIS) if ans == "p": k -= 2 goon = 0 if ans == "q": k = plt goon = 0 if ans == "s": keepon = 1 site = input(" print site or part of site desired: ") while keepon == 1: try: k = sitelist.index(site) keepon = 0 except: tmplist = [] for qq in range(len(sitelist)): if site in sitelist[qq]: tmplist.append(sitelist[qq]) print(site, " not found, but this was: ") print(tmplist) site = input('Select one or try again\n ') k = sitelist.index(site) goon, ans = 0, "" if ans == "a": locs = pmag.makelist(Locs) if pmagplotlib.isServer: # use server plot naming convention title = "LO:_" + locs + '_SI:__' + '_SA:__SP:__CO:_' + crd else: # use more readable plot naming convention title = "{}_{}".format(locs, crd) save(ANIS, fmt, title) goon = 0 else: if verbose: print('skipping plot - not enough data points') k += 1 # put rmag_results stuff here if len(ResRecs) > 0: ResOut, keylist = pmag.fillkeys(ResRecs) pmag.magic_write(outfile, ResOut, 'rmag_results') if verbose: print(" Good bye ")
def main(): """ NAME thellier_magic.py DESCRIPTION plots Thellier-Thellier, allowing interactive setting of bounds and customizing of selection criteria. Saves and reads interpretations from a pmag_specimen formatted table, default: thellier_specimens.txt SYNTAX thellier_magic.py [command line options] OPTIONS -h prints help message and quits -f MEAS, set magic_measurements input file -fsp PRIOR, set pmag_specimen prior interpretations file -fan ANIS, set rmag_anisotropy file for doing the anisotropy corrections -fcr CRIT, set criteria file for grading. -fmt [svg,png,jpg], format for images - default is svg -sav, saves plots with out review (default format) -spc SPEC, plots single specimen SPEC, saves plot with specified format with optional -b bounds adn quits -b BEG END: sets bounds for calculation BEG: starting step for slope calculation END: ending step for slope calculation -z use only z component difference for pTRM calculation DEFAULTS MEAS: magic_measurements.txt REDO: thellier_redo CRIT: NONE PRIOR: NONE OUTPUT figures: ALL: numbers refer to temperature steps in command line window 1) Arai plot: closed circles are zero-field first/infield open circles are infield first/zero-field triangles are pTRM checks squares are pTRM tail checks VDS is vector difference sum diamonds are bounds for interpretation 2) Zijderveld plot: closed (open) symbols are X-Y (X-Z) planes X rotated to NRM direction 3) (De/Re)Magnetization diagram: circles are NRM remaining squares are pTRM gained 4) equal area projections: green triangles are pTRM gained direction red (purple) circles are lower(upper) hemisphere of ZI step directions blue (cyan) squares are lower(upper) hemisphere IZ step directions 5) Optional: TRM acquisition 6) Optional: TDS normalization command line window: list is: temperature step numbers, temperatures (C), Dec, Inc, Int (units of magic_measuements) list of possible commands: type letter followed by return to select option saving of plots creates .svg format files with specimen_name, plot type as name """ # # initializations # meas_file, critout, inspec = "magic_measurements.txt", "", "thellier_specimens.txt" first = 1 inlt = 0 version_num = pmag.get_version() TDinit, Tinit, field, first_save = 0, 0, -1, 1 user, comment, AniSpec, locname = "", '', "", "" ans, specimen, recnum, start, end = 0, 0, 0, 0, 0 plots, pmag_out, samp_file, style = 0, "", "", "svg" verbose = pmagplotlib.verbose fmt = '.' + style # # default acceptance criteria # accept = pmag.default_criteria(0)[0] # set the default criteria # # parse command line options # Zdiff, anis = 0, 0 spc, BEG, END = "", "", "" if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-f' in sys.argv: ind = sys.argv.index('-f') meas_file = sys.argv[ind + 1] if '-fsp' in sys.argv: ind = sys.argv.index('-fsp') inspec = sys.argv[ind + 1] if '-fan' in sys.argv: ind = sys.argv.index('-fan') anisfile = sys.argv[ind + 1] anis = 1 anis_data, file_type = pmag.magic_read(anisfile) if verbose: print("Anisotropy data read in from ", anisfile) if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = '.' + sys.argv[ind + 1] if '-dpi' in sys.argv: ind = sys.argv.index('-dpi') dpi = '.' + sys.argv[ind + 1] else: dpi = 100 if '-sav' in sys.argv: plots = 1 verbose = 0 if '-z' in sys.argv: Zdiff = 1 if '-spc' in sys.argv: ind = sys.argv.index('-spc') spc = sys.argv[ind + 1] if '-b' in sys.argv: ind = sys.argv.index('-b') BEG = int(sys.argv[ind + 1]) END = int(sys.argv[ind + 2]) if '-fcr' in sys.argv: ind = sys.argv.index('-fcr') critout = sys.argv[ind + 1] crit_data, file_type = pmag.magic_read(critout) if file_type != 'pmag_criteria': if verbose: print('bad pmag_criteria file, using no acceptance criteria') accept = pmag.default_criteria(1)[0] else: if verbose: print("Acceptance criteria read in from ", critout) accept = { 'pmag_criteria_code': 'ACCEPTANCE', 'er_citation_names': 'This study' } for critrec in crit_data: if 'sample_int_sigma_uT' in critrec.keys( ): # accommodate Shaar's new criterion critrec['sample_int_sigma'] = '%10.3e' % ( eval(critrec['sample_int_sigma_uT']) * 1e-6) for key in critrec.keys(): if key not in accept.keys() and critrec[key] != '': accept[key] = critrec[key] try: open(inspec, 'rU') PriorRecs, file_type = pmag.magic_read(inspec) if file_type != 'pmag_specimens': print(file_type) print(file_type, inspec, " is not a valid pmag_specimens file ") sys.exit() for rec in PriorRecs: if 'magic_software_packages' not in rec.keys(): rec['magic_software_packages'] = "" except IOError: PriorRecs = [] if verbose: print("starting new specimen interpretation file: ", inspec) meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(file_type) print(file_type, "This is not a valid magic_measurements file ") sys.exit() backup = 0 # define figure numbers for arai, zijderveld and # de-,re-magization diagrams AZD = {} AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4 pmagplotlib.plot_init(AZD['arai'], 5, 5) pmagplotlib.plot_init(AZD['zijd'], 5, 5) pmagplotlib.plot_init(AZD['deremag'], 5, 5) pmagplotlib.plot_init(AZD['eqarea'], 5, 5) # # # # get list of unique specimen names # CurrRec = [] sids = pmag.get_specs(meas_data) # get plots for specimen s - default is just to step through arai diagrams # if spc != "": specimen = sids.index(spc) while specimen < len(sids): methcodes = [] if verbose: print(sids[specimen], specimen + 1, 'of ', len(sids)) MeasRecs = [] s = sids[specimen] datablock, trmblock, tdsrecs = [], [], [] PmagSpecRec = {} if first == 0: for key in keys: # make sure all new records have same set of keys PmagSpecRec[key] = "" 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.plot_arai_zij(AZD, araiblock, zijdblock, s, units[0]) if verbose: pmagplotlib.draw_figs(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 # find which type of intensity while mkey == "" and k < len(Mkeys) - 1: 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: # strip off potential nasty spaces meth.replace(" ", "") if 'LT-T-I' in meths and Tnorm == "": # found first total TRM # normalize by total TRM Tnorm = float(tdrec[mkey]) # put in the zero step tdsblock.append([273, zijdblock[0][3] / Tnorm, 1.]) # found a LP-TRM-TD demag step, now need complementary LT-T-Z from zijdblock if 'LT-T-Z' in meths and Tnorm != "": 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.plot_tds(AZD['TDS'], tdsblock, s + ':LP-PI-TDS:') if verbose: pmagplotlib(draw_figs(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' # put in CurrRec, take out of PriorRecs del PriorRecs[k] 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.plot_b(AZD, araiblock, zijdblock, pars) if verbose: pmagplotlib.draw_figs(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']) ) # calculate best fit parameters through TRM acquisition data, and get new banc NLpars = nlt.NLtrm( Bs, TRMs, best, blab, 0) Mp, Bp = [], [] for k in range(int(max(Bs) * 1e6)): Bp.append(float(k) * 1e-6) # predicted NRM for this field npred = nlt.TRM( Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1]) Mp.append(npred) pmagplotlib.plot_trm( 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.draw_figs(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.plot_b(AZD, araiblock, zijdblock, pars) if verbose: pmagplotlib.draw_figs(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'])) # calculate best fit parameters through TRM acquisition data, and get new banc NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0) # Mp, Bp = [], [] for k in range(int(max(Bs) * 1e6)): Bp.append(float(k) * 1e-6) # predicted NRM for this field npred = nlt.TRM(Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1]) files = {} for key in AZD.keys(): files[key] = s + '_' + key + fmt pmagplotlib.save_plots(AZD, files, dpi=dpi) sys.exit() if verbose: ans = 'b' while ans != "": print(""" s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit: """) ans = input('Return for next specimen \n') if ans == "": specimen += 1 if ans == "d": save_redo(PriorRecs, inspec) CurrRec = [] pmagplotlib.plot_arai_zij(AZD, araiblock, zijdblock, s, units[0]) if verbose: pmagplotlib.draw_figs(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.save_plots(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 = 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 = 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 = input( 'Enter index of first point for calculation: [' + str(start) + '] ') try: start = int(answer) answer = 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' # this is redundant, but helpful - won't be imported PmagSpecRec["direction_type"] = 'l' 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.plot_arai_zij(AZD, araiblock, zijdblock, s, units[0]) pmagplotlib.plot_b(AZD, araiblock, zijdblock, pars) if verbose: pmagplotlib.draw_figs(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'])) # calculate best fit parameters through TRM acquisition data, and get new banc NLpars = nlt.NLtrm(Bs, TRMs, best, blab, 0) Mp, Bp = [], [] for k in range(int(max(Bs) * 1e6)): Bp.append(float(k) * 1e-6) # predicted NRM for this field npred = nlt.TRM(Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1]) Mp.append(npred) pmagplotlib.plot_trm( 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.draw_figs(AZD) pars["specimen_lab_field_dc"] = field pars["specimen_int"] = -1 * field * pars[ "specimen_b"] pars, kill = pmag.scoreit(pars, PmagSpecRec, accept, '', verbose) saveit = input( "Save this interpretation? [y]/n \n") if saveit != 'n': # put back an interpretation PriorRecs.append(PmagSpecRec) 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.add_borders( AZD, titles, black, purple) pmagplotlib.save_plots(AZD, files, dpi=dpi) # pmagplotlib.combineFigs(s,files,3) else: # save in pmag format script = "grep " + s + " output.mag | thellier -mfsi" script = script + ' %8.4e' % (field) min = '%i' % ((pars["measurement_step_min"] - 273)) Max = '%i' % ((pars["measurement_step_max"] - 273)) script = script + " " + min + " " + Max script = script + " |plotxy;cat mypost >>thellier.ps\n" pltf.write(script) pmag.domagicmag(outf, MeasRecs) if len(CurrRec) > 0: for rec in CurrRec: PriorRecs.append(rec) CurrRec = [] if plots != 1 and verbose: ans = input(" Save last plot? 1/[0] ") if ans == "1": if fmt != ".pmag": files = {} for key in AZD.keys(): files[key] = s + '_' + key + fmt pmagplotlib.save_plots(AZD, files, dpi=dpi) else: print("\n Good bye\n") sys.exit() if len(CurrRec) > 0: PriorRecs.append(CurrRec) # put back an interpretation if len(PriorRecs) > 0: save_redo(PriorRecs, inspec) print('Updated interpretations saved in ', inspec) if verbose: print("Good bye")
def main(): """ NAME thellier_magic_redo.py DESCRIPTION Calculates paleointensity parameters for thellier-thellier type data using bounds stored in the "redo" file SYNTAX thellier_magic_redo [command line options] OPTIONS -h prints help message -usr USER: identify user, default is "" -fcr CRIT, set criteria for grading -f IN: specify input file, default is magic_measurements.txt -fre REDO: specify redo file, default is "thellier_redo" -F OUT: specify output file, default is thellier_specimens.txt -leg: attaches "Recalculated from original measurements; supercedes published results. " to comment field -CR PERC TYPE: apply a blanket cooling rate correction if none supplied in the er_samples.txt file PERC should be a percentage of original (say reduce to 90%) TYPE should be one of the following: EG (for educated guess); PS (based on pilots); TRM (based on comparison of two TRMs) -ANI: perform anisotropy correction -fsa SAMPFILE: er_samples.txt file with cooling rate correction information, default is NO CORRECTION -Fcr CRout: specify pmag_specimen format file for cooling rate corrected data -fan ANIFILE: specify rmag_anisotropy format file, default is rmag_anisotropy.txt -Fac ACout: specify pmag_specimen format file for anisotropy corrected data default is AC_specimens.txt -fnl NLTFILE: specify magic_measurments format file, default is magic_measurements.txt -Fnl NLTout: specify pmag_specimen format file for non-linear trm corrected data default is NLT_specimens.txt -z use z component differenences for pTRM calculation INPUT a thellier_redo file is Specimen_name Tmin Tmax (where Tmin and Tmax are in Centigrade) """ dir_path = '.' critout = "" version_num = pmag.get_version() field, first_save = -1, 1 spec, recnum, start, end = 0, 0, 0, 0 crfrac = 0 NltRecs, PmagSpecs, AniSpecRecs, NltSpecRecs, CRSpecs = [], [], [], [], [] meas_file, pmag_file, mk_file = "magic_measurements.txt", "thellier_specimens.txt", "thellier_redo" anis_file = "rmag_anisotropy.txt" anisout, nltout = "AC_specimens.txt", "NLT_specimens.txt" crout = "CR_specimens.txt" nlt_file = "" samp_file = "" comment, user = "", "unknown" anis, nltrm = 0, 0 jackknife = 0 # maybe in future can do jackknife args = sys.argv Zdiff = 0 if '-WD' in args: ind = args.index('-WD') dir_path = args[ind + 1] if "-h" in args: print main.__doc__ sys.exit() if "-usr" in args: ind = args.index("-usr") user = sys.argv[ind + 1] if "-leg" in args: comment = "Recalculated from original measurements; supercedes published results. " cool = 0 if "-CR" in args: cool = 1 ind = args.index("-CR") crfrac = .01 * float(sys.argv[ind + 1]) crtype = 'DA-CR-' + sys.argv[ind + 2] if "-Fcr" in args: ind = args.index("-Fcr") crout = sys.argv[ind + 1] if "-f" in args: ind = args.index("-f") meas_file = sys.argv[ind + 1] if "-F" in args: ind = args.index("-F") pmag_file = sys.argv[ind + 1] if "-fre" in args: ind = args.index("-fre") mk_file = args[ind + 1] if "-fsa" in args: ind = args.index("-fsa") samp_file = dir_path + '/' + args[ind + 1] Samps, file_type = pmag.magic_read(samp_file) SampCRs = pmag.get_dictitem( Samps, 'cooling_rate_corr', '', 'F') # get samples cooling rate corrections cool = 1 if file_type != 'er_samples': print 'not a valid er_samples.txt file' sys.exit() # # if "-ANI" in args: anis = 1 ind = args.index("-ANI") if "-Fac" in args: ind = args.index("-Fac") anisout = args[ind + 1] if "-fan" in args: ind = args.index("-fan") anis_file = args[ind + 1] # if "-NLT" in args: if "-Fnl" in args: ind = args.index("-Fnl") nltout = args[ind + 1] if "-fnl" in args: ind = args.index("-fnl") nlt_file = args[ind + 1] if "-z" in args: Zdiff = 1 if '-fcr' in sys.argv: ind = args.index("-fcr") critout = sys.argv[ind + 1] # # start reading in data: # meas_file = dir_path + "/" + meas_file mk_file = dir_path + "/" + mk_file accept = pmag.default_criteria(1)[0] # set criteria to none if critout != "": critout = dir_path + "/" + critout crit_data, file_type = pmag.magic_read(critout) if file_type != 'pmag_criteria': print 'bad pmag_criteria file, using no acceptance criteria' print "Acceptance criteria read in from ", critout 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] 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() try: mk_f = open(mk_file, 'rU') except: print "Bad redo file" sys.exit() mkspec = [] speclist = [] for line in mk_f.readlines(): tmp = line.split() mkspec.append(tmp) speclist.append(tmp[0]) if anis == 1: anis_file = dir_path + "/" + anis_file anis_data, file_type = pmag.magic_read(anis_file) if file_type != 'rmag_anisotropy': print file_type print file_type, "This is not a valid rmag_anisotropy file " sys.exit() if nlt_file == "": nlt_data = pmag.get_dictitem( meas_data, 'magic_method_codes', 'LP-TRM', 'has') # look for trm acquisition data in the meas_data file else: nlt_file = dir_path + "/" + nlt_file nlt_data, file_type = pmag.magic_read(nlt_file) if len(nlt_data) > 0: nltrm = 1 # # sort the specimen names and step through one by one # sids = pmag.get_specs(meas_data) # print 'Processing ', len(speclist), ' specimens - please wait ' while spec < len(speclist): s = speclist[spec] recnum = 0 datablock = [] PmagSpecRec = {} PmagSpecRec["er_analyst_mail_names"] = user PmagSpecRec["er_citation_names"] = "This study" PmagSpecRec["magic_software_packages"] = version_num methcodes, inst_code = [], "" # # find the data from the meas_data file for this specimen # datablock = pmag.get_dictitem(meas_data, 'er_specimen_name', s, 'T') datablock = pmag.get_dictitem( datablock, 'magic_method_codes', 'LP-PI-TRM', 'has') #pick out the thellier experiment data if len(datablock) > 0: for rec in datablock: if "magic_instrument_codes" not in rec.keys(): rec["magic_instrument_codes"] = "unknown" # # collect info for the PmagSpecRec dictionary # rec = datablock[0] 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"] PmagSpecRec["measurement_step_unit"] = "K" PmagSpecRec["specimen_correction"] = 'u' if "er_expedition_name" in rec.keys(): PmagSpecRec["er_expedition_name"] = rec["er_expedition_name"] if "magic_instrument_codes" not in rec.keys(): PmagSpecRec["magic_instrument_codes"] = "unknown" else: PmagSpecRec["magic_instrument_codes"] = rec[ "magic_instrument_codes"] if "magic_experiment_name" not in rec.keys(): rec["magic_experiment_name"] = "" else: PmagSpecRec["magic_experiment_names"] = rec[ "magic_experiment_name"] meths = rec["magic_experiment_name"].split(":") for meth in meths: if meth.strip() not in methcodes and "LP-" in meth: methcodes.append(meth.strip()) # # sort out the data into first_Z, first_I, ptrm_check, ptrm_tail # araiblock, field = pmag.sortarai(datablock, s, Zdiff) first_Z = araiblock[0] first_I = araiblock[1] ptrm_check = araiblock[2] ptrm_tail = araiblock[3] if len(first_I) < 3 or len(first_Z) < 4: spec += 1 print 'skipping specimen ', s else: # # get start, end # for redospec in mkspec: if redospec[0] == s: b, e = float(redospec[1]), float(redospec[2]) break if e > float(first_Z[-1][0]): e = float(first_Z[-1][0]) for recnum in range(len(first_Z)): if first_Z[recnum][0] == b: start = recnum if first_Z[recnum][0] == e: end = recnum nsteps = end - start if nsteps > 2: zijdblock, units = pmag.find_dmag_rec(s, meas_data) pars, errcode = pmag.PintPars(datablock, araiblock, zijdblock, start, end, accept) if 'specimen_scat' in pars.keys(): PmagSpecRec['specimen_scat'] = pars['specimen_scat'] if 'specimen_frac' in pars.keys(): PmagSpecRec['specimen_frac'] = '%5.3f' % ( pars['specimen_frac']) if 'specimen_gmax' in pars.keys(): PmagSpecRec['specimen_gmax'] = '%5.3f' % ( pars['specimen_gmax']) pars['measurement_step_unit'] = units pars["specimen_lab_field_dc"] = field pars["specimen_int"] = -1 * field * pars["specimen_b"] PmagSpecRec["measurement_step_min"] = '%8.3e' % ( pars["measurement_step_min"]) PmagSpecRec["measurement_step_max"] = '%8.3e' % ( pars["measurement_step_max"]) 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"]) if pars["method_codes"] != "" and pars[ "method_codes"] not in methcodes: methcodes.append(pars["method_codes"]) PmagSpecRec["specimen_dec"] = '%7.1f' % ( pars["specimen_dec"]) PmagSpecRec["specimen_inc"] = '%7.1f' % ( pars["specimen_inc"]) PmagSpecRec["specimen_tilt_correction"] = '-1' PmagSpecRec["specimen_direction_type"] = 'l' PmagSpecRec[ "direction_type"] = 'l' # this is redudant, but helpful - won't be imported PmagSpecRec["specimen_dang"] = '%7.1f ' % ( pars["specimen_dang"]) PmagSpecRec["specimen_drats"] = '%7.1f ' % ( pars["specimen_drats"]) PmagSpecRec["specimen_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.strip(':') PmagSpecRec["magic_software_packages"] = version_num PmagSpecRec["specimen_description"] = comment if critout != "": kill = pmag.grade(PmagSpecRec, accept, 'specimen_int') if len(kill) > 0: Grade = 'F' # fails else: Grade = 'A' # passes PmagSpecRec["specimen_grade"] = Grade else: PmagSpecRec["specimen_grade"] = "" # not graded if nltrm == 0 and anis == 0 and cool != 0: # apply cooling rate correction SCR = pmag.get_dictitem( SampCRs, 'er_sample_name', PmagSpecRec['er_sample_name'], 'T') # get this samples, cooling rate correction CrSpecRec = pmag.cooling_rate(PmagSpecRec, SCR, crfrac, crtype) if CrSpecRec['er_specimen_name'] != 'none': CrSpecs.append(CrSpecRec) PmagSpecs.append(PmagSpecRec) NltSpecRec = "" # # check on non-linear TRM correction # if nltrm == 1: # # find the data from the nlt_data list for this specimen # TRMs, Bs = [], [] NltSpecRec = "" NltRecs = pmag.get_dictitem( nlt_data, 'er_specimen_name', PmagSpecRec['er_specimen_name'], 'has' ) # fish out all the NLT data for this specimen if len(NltRecs) > 2: for NltRec in NltRecs: Bs.append(float(NltRec['treatment_dc_field'])) TRMs.append( float(NltRec['measurement_magn_moment'])) NLTpars = nlt.NLtrm( Bs, TRMs, float(PmagSpecRec['specimen_int']), float(PmagSpecRec['specimen_lab_field_dc']), 0) if NLTpars['banc'] > 0: NltSpecRec = {} for key in PmagSpecRec.keys(): NltSpecRec[key] = PmagSpecRec[key] NltSpecRec['specimen_int'] = '%9.4e' % ( NLTpars['banc']) NltSpecRec['magic_method_codes'] = PmagSpecRec[ "magic_method_codes"] + ":DA-NL" NltSpecRec["specimen_correction"] = 'c' NltSpecRec['specimen_grade'] = PmagSpecRec[ 'specimen_grade'] NltSpecRec[ "magic_software_packages"] = version_num print NltSpecRec[ 'er_specimen_name'], ' Banc= ', float( NLTpars['banc']) * 1e6 if anis == 0 and cool != 0: SCR = pmag.get_dictitem( SampCRs, 'er_sample_name', NltSpecRec['er_sample_name'], 'T' ) # get this samples, cooling rate correction CrSpecRec = pmag.cooling_rate( NltSpecRec, SCR, crfrac, crtype) if CrSpecRec['er_specimen_name'] != 'none': CrSpecs.append(CrSpecRec) NltSpecRecs.append(NltSpecRec) # # check on anisotropy correction if anis == 1: if NltSpecRec != "": Spc = NltSpecRec else: # find uncorrected data Spc = PmagSpecRec AniSpecs = pmag.get_dictitem( anis_data, 'er_specimen_name', PmagSpecRec['er_specimen_name'], 'T') if len(AniSpecs) > 0: AniSpec = AniSpecs[0] AniSpecRec = pmag.doaniscorr(Spc, AniSpec) AniSpecRec['specimen_grade'] = PmagSpecRec[ 'specimen_grade'] AniSpecRec[ "magic_instrument_codes"] = PmagSpecRec[ 'magic_instrument_codes'] AniSpecRec["specimen_correction"] = 'c' AniSpecRec[ "magic_software_packages"] = version_num if cool != 0: SCR = pmag.get_dictitem( SampCRs, 'er_sample_name', AniSpecRec['er_sample_name'], 'T' ) # get this samples, cooling rate correction CrSpecRec = pmag.cooling_rate( AniSpecRec, SCR, crfrac, crtype) if CrSpecRec['er_specimen_name'] != 'none': CrSpecs.append(CrSpecRec) AniSpecRecs.append(AniSpecRec) elif anis == 1: AniSpecs = pmag.get_dictitem( anis_data, 'er_specimen_name', PmagSpecRec['er_specimen_name'], 'T') if len(AniSpecs) > 0: AniSpec = AniSpecs[0] AniSpecRec = pmag.doaniscorr(PmagSpecRec, AniSpec) AniSpecRec['specimen_grade'] = PmagSpecRec[ 'specimen_grade'] AniSpecRec["magic_instrument_codes"] = PmagSpecRec[ "magic_instrument_codes"] AniSpecRec["specimen_correction"] = 'c' AniSpecRec["magic_software_packages"] = version_num if crfrac != 0: CrSpecRec = {} for key in AniSpecRec.keys(): CrSpecRec[key] = AniSpecRec[key] inten = frac * float(CrSpecRec['specimen_int']) CrSpecRec["specimen_int"] = '%9.4e ' % ( inten ) # adjust specimen intensity by cooling rate correction CrSpecRec['magic_method_codes'] = CrSpecRec[ 'magic_method_codes'] + ':DA-CR-' + crtype CRSpecs.append(CrSpecRec) AniSpecRecs.append(AniSpecRec) spec += 1 else: print "skipping ", s spec += 1 pmag_file = dir_path + '/' + pmag_file pmag.magic_write(pmag_file, PmagSpecs, 'pmag_specimens') print 'uncorrected thellier data saved in: ', pmag_file if anis == 1 and len(AniSpecRecs) > 0: anisout = dir_path + '/' + anisout pmag.magic_write(anisout, AniSpecRecs, 'pmag_specimens') print 'anisotropy corrected data saved in: ', anisout if nltrm == 1 and len(NltSpecRecs) > 0: nltout = dir_path + '/' + nltout pmag.magic_write(nltout, NltSpecRecs, 'pmag_specimens') print 'non-linear TRM corrected data saved in: ', nltout if crfrac != 0: crout = dir_path + '/' + crout pmag.magic_write(crout, CRSpecs, 'pmag_specimens') print 'cooling rate corrected data saved in: ', crout
def main(command_line=True, **kwargs): """ NAME old_iodp_jr6_magic.py DESCRIPTION converts shipboard .jr6 format files to magic_measurements format files SYNTAX old_iodp_jr6_magic.py [command line options] OPTIONS -h: prints the help message and quits. -f FILE: specify input file, or -F FILE: specify output file, default is magic_measurements.txt -fsa FILE: specify er_samples.txt file for sample name lookup , default is 'er_samples.txt' -loc HOLE : specify hole name (U1456A) -A: don't average replicate measurements INPUT JR6 .jr6 format file """ def fix_separation(filename, new_filename): old_file = open(filename, 'rU') data = old_file.readlines() new_data = [] for line in data: new_line = line.replace('-', ' -') new_line = new_line.replace(' ', ' ') new_data.append(new_line) new_file = open(new_filename, 'w') for s in new_data: new_file.write(s) old_file.close() new_file.close() return new_filename def old_fix_separation(filename, new_filename): old_file = open(filename, 'rU') data = old_file.readlines() new_data = [] for line in data: new_line = [] for i in line.split(): if '-' in i[1:]: lead_char = '-' if i[0] == '-' else '' if lead_char: v = i[1:].split('-') else: v = i.split('-') new_line.append(lead_char + v[0]) new_line.append('-' + v[1]) else: new_line.append(i) new_line = (' '.join(new_line)) + '\n' new_data.append(new_line) new_file = open(new_filename, 'w') for s in new_data: new_file.write(s) new_file.close() old_file.close() return new_filename # initialize some stuff noave=0 volume=2.5**3 #default volume is a 2.5cm cube inst="" samp_con,Z='5',"" missing=1 demag="N" er_location_name="unknown" citation='This study' args=sys.argv meth_code="LP-NO" version_num=pmag.get_version() dir_path='.' MagRecs=[] samp_file = 'er_samples.txt' meas_file = 'magic_measurements.txt' mag_file = '' # # get command line arguments # if command_line: if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path=sys.argv[ind+1] if '-ID' in sys.argv: ind = sys.argv.index('-ID') input_dir_path = sys.argv[ind+1] else: input_dir_path = dir_path output_dir_path = dir_path if "-h" in args: print main.__doc__ return False if '-F' in args: ind=args.index("-F") meas_file = args[ind+1] if '-fsa' in args: ind = args.index("-fsa") samp_file = args[ind+1] if samp_file[0]!='/': samp_file = os.path.join(input_dir_path, samp_file) try: open(samp_file,'rU') ErSamps,file_type=pmag.magic_read(samp_file) except: print samp_file,' not found: ' print ' download csv file and import to MagIC with iodp_samples_magic.py' if '-f' in args: ind = args.index("-f") mag_file= args[ind+1] if "-loc" in args: ind=args.index("-loc") er_location_name=args[ind+1] if "-A" in args: noave=1 if not command_line: dir_path = kwargs.get('dir_path', '.') input_dir_path = kwargs.get('input_dir_path', dir_path) output_dir_path = dir_path meas_file = kwargs.get('meas_file', 'magic_measurements.txt') mag_file = kwargs.get('mag_file', '') samp_file = kwargs.get('samp_file', 'er_samples.txt') specnum = kwargs.get('specnum', 1) samp_con = kwargs.get('samp_con', '1') if len(str(samp_con)) > 1: samp_con, Z = samp_con.split('-') else: Z = '' er_location_name = kwargs.get('er_location_name', '') noave = kwargs.get('noave', 0) # default (0) means DO average meth_code = kwargs.get('meth_code', "LP-NO") # format variables meth_code=meth_code+":FS-C-DRILL-IODP:SP-SS-C:SO-V" meth_code=meth_code.strip(":") if mag_file: mag_file = os.path.join(input_dir_path, mag_file) samp_file = os.path.join(input_dir_path, samp_file) meas_file = os.path.join(output_dir_path, meas_file) # validate variables if not mag_file: print "You must provide an IODP_jr6 format file" return False, "You must provide an IODP_jr6 format file" if not os.path.exists(mag_file): print 'The input file you provided: {} does not exist.\nMake sure you have specified the correct filename AND correct input directory name.'.format(os.path.join(input_dir_path, mag_file)) return False, 'The input file you provided: {} does not exist.\nMake sure you have specified the correct filename AND correct input directory name.'.format(magfile) if not os.path.exists(samp_file): print 'samp_file', samp_file print "Your input directory:\n{}\nmust contain an er_samples.txt file, or you must explicitly provide one".format(input_dir_path) return False, "Your input directory:\n{}\nmust contain an er_samples.txt file, or you must explicitly provide one".format(input_dir_path) # parse data temp = os.path.join(output_dir_path, 'temp.txt') fix_separation(mag_file, temp) #os.rename('temp.txt', mag_file) #data = open(mag_file, 'rU').readlines() data=pd.read_csv(temp, delim_whitespace=True,header=None) os.remove(temp) samples,filetype = pmag.magic_read(samp_file) data.columns=['specname','step','negz','y','x','expon','sample_azimuth','sample_dip','sample_bed_dip_direction','sample_bed_dip','bed_dip_dir2','bed_dip2','param1','param2','param3','param4','measurement_csd'] cart=np.array([data['x'],data['y'],-data['negz']]).transpose() dir= pmag.cart2dir(cart).transpose() data['measurement_dec']=dir[0] data['measurement_inc']=dir[1] data['measurement_magn_volume']=dir[2]*(10.0**data['expon']) # A/m - data in A/m data['measurement_flag']='g' data['measurement_standard']='u' data['measurement_number']='1' data['measurement_temp']='273' data['er_location_name']=er_location_name for rowNum, row in data.iterrows(): MagRec={} spec_text_id=row['specname'].split('_')[1] SampRecs=pmag.get_dictitem(samples,'er_sample_alternatives',spec_text_id,'has') # retrieve sample record for this specimen if len(SampRecs)>0: # found one MagRec['er_specimen_name']=SampRecs[0]['er_sample_name'] MagRec['er_sample_name']=MagRec['er_specimen_name'] MagRec['er_site_name']=MagRec['er_specimen_name'] MagRec["er_citation_names"]="This study" MagRec['er_location_name']=er_location_name MagRec['magic_software_packages']=version_num MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin MagRec["measurement_flag"]='g' MagRec["measurement_standard"]='u' MagRec["measurement_number"]='1' MagRec["treatment_ac_field"]='0' volume=float(SampRecs[0]['sample_volume']) moment=row['measurement_magn_volume'] * volume MagRec["measurement_magn_moment"]=str(moment) MagRec["measurement_magn_volume"]=str(row['measurement_magn_volume']) MagRec["measurement_dec"]='%7.1f'%(row['measurement_dec']) MagRec["measurement_inc"]='%7.1f'%(row['measurement_inc']) if row['step'] == 'NRM': meas_type="LT-NO" elif row['step'][0:2] == 'AD': meas_type="LT-AF-Z" treat=float(row['step'][2:]) MagRec["treatment_ac_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla elif row['step'][0] == 'TD': meas_type="LT-T-Z" treat=float(row['step'][2:]) MagRec["treatment_temp"]='%8.3e' % (treat+273.) # temp in kelvin elif row['step'][0:3]=='ARM': # meas_type="LT-AF-I" treat=float(row['step'][3:]) MagRec["treatment_ac_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla MagRec["treatment_dc_field"]='%8.3e' %(50e-6) # assume 50uT DC field MagRec["measurement_description"]='Assumed DC field - actual unknown' elif row['step'][0:3]=='IRM': # meas_type="LT-IRM" treat=float(row['step'][3:]) MagRec["treatment_dc_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla else: print 'unknown treatment type for ',row return False, 'unknown treatment type for ',row MagRec['magic_method_codes']=meas_type MagRecs.append(MagRec.copy()) else: print 'sample name not found: ',row['specname'] MagOuts=pmag.measurements_methods(MagRecs,noave) file_created, error_message = pmag.magic_write(meas_file,MagOuts,'magic_measurements') if file_created: return True, meas_file else: return False, 'Results not written to file'
def main(): """ NAME trmaq_magic.py DESCTIPTION does non-linear trm acquisisiton correction SYNTAX trmaq_magic.py [-h][-i][command line options] OPTIONS -h prints help message and quits -i allows interactive setting of file names -f MFILE, sets magic_measurements input file -ft TSPEC, sets thellier_specimens input file -F OUT, sets output for non-linear TRM acquisition corrected data DEFAULTS MFILE: trmaq_measurements.txt TSPEC: thellier_specimens.txt OUT: NLT_specimens.txt """ meas_file='trmaq_measurements.txt' tspec="thellier_specimens.txt" output='NLT_specimens.txt' if '-h' in sys.argv: print main.__doc__ sys.exit() if '-i' in sys.argv: meas_file=raw_input("Input magic_measurements file name? [trmaq_measurements.txt] ") if meas_file=="":meas_file="trmaq_measurements.txt" tspec=raw_input(" thellier_specimens file name? [thellier_specimens.txt] ") if tspec=="":tspec="thellier_specimens.txt" output=raw_input("File for non-linear TRM adjusted specimen data: [NLTspecimens.txt] ") if output=="":output="NLT_specimens.txt" if '-f' in sys.argv: ind=sys.argv.index('-f') meas_file=sys.argv[ind+1] if '-ft' in sys.argv: ind=sys.argv.index('-ft') tspec=sys.argv[ind+1] if '-F' in sys.argv: ind=sys.argv.index('-F') output=sys.argv[ind+1] # PLT={'aq':1} pmagplotlib.plot_init(PLT['aq'],5,5) # # get name of file from command line # comment="" # # meas_data,file_type=pmag.magic_read(meas_file) if file_type != 'magic_measurements': print file_type print file_type,"This is not a valid magic_measurements file " sys.exit() sids=pmag.get_specs(meas_data) specimen=0 # # read in thellier_specimen data # nrm,file_type=pmag.magic_read(tspec) PmagSpecRecs=[] while specimen < len(sids): # # find corresoponding paleointensity data for this specimen # s=sids[specimen] blab,best="","" for nrec in nrm: # pick out the Banc data for this spec if nrec["er_specimen_name"]==s: blab=float(nrec["specimen_lab_field_dc"]) best=float(nrec["specimen_int"]) TrmRec=nrec break if blab=="": print "skipping ",s," : no best " specimen+=1 else: print sids[specimen],specimen+1, 'of ', len(sids),'Best = ',best*1e6 MeasRecs=[] # # find the data from the meas_data file for this specimen # for rec in meas_data: if rec["er_specimen_name"]==s: meths=rec["magic_method_codes"].split(":") methcodes=[] for meth in meths: methcodes.append(meth.strip()) if "LP-TRM" in methcodes: MeasRecs.append(rec) if len(MeasRecs) <2: specimen+=1 print 'skipping specimen - no trm acquisition data ', s # # collect info for the PmagSpecRec dictionary # else: TRMs,Bs=[],[] for rec in MeasRecs: Bs.append(float(rec['treatment_dc_field'])) TRMs.append(float(rec['measurement_magn_moment'])) NLpars=nlt.NLtrm(Bs,TRMs,best,blab,0) # calculate best fit parameters through TRM acquisition data, and get new banc # Mp,Bp=[],[] for k in range(int(max(Bs)*1e6)): Bp.append(float(k)*1e-6) npred=nlt.TRM(Bp[-1],NLpars['xopt'][0],NLpars['xopt'][1]) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM(PLT['aq'],Bs,TRMs,Bp,Mp,NLpars,rec['magic_experiment_name']) pmagplotlib.drawFIGS(PLT) print 'Banc= ',float(NLpars['banc'])*1e6 trmTC={} for key in TrmRec.keys(): trmTC[key]=TrmRec[key] # copy of info from thellier_specimens record trmTC['specimen_int']='%8.3e'%(NLpars['banc']) trmTC['magic_method_codes']=TrmRec["magic_method_codes"]+":DA-NL" PmagSpecRecs.append(trmTC) ans=raw_input("Return for next specimen, s[a]ve plot ") if ans=='a': Name={'aq':rec['er_specimen_name']+'_TRM.svg'} pmagplotlib.saveP(PLT,Name) specimen+=1 pmag.magic_write(output,PmagSpecRecs,'pmag_specimens')
def main(): """ NAME aarm_magic.py DESCRIPTION Converts AARM data to best-fit tensor (6 elements plus sigma) Original program ARMcrunch written to accomodate ARM anisotropy data collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the off-axis remanence terms to construct the tensor. A better way to do the anisotropy of ARMs is to use 9,12 or 15 measurements in the Hext rotational scheme. SYNTAX aarm_magic.py [-h][command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f FILE: specify input file, default is aarm_measurements.txt -crd [s,g,t] specify coordinate system, requires er_samples.txt file -fsa FILE: specify er_samples.txt file, default is er_samples.txt -Fa FILE: specify anisotropy output file, default is arm_anisotropy.txt -Fr FILE: specify results output file, default is aarm_results.txt INPUT Input for the present program is a series of baseline, ARM pairs. The baseline should be the AF demagnetized state (3 axis demag is preferable) for the following ARM acquisition. The order of the measurements is: positions 1,2,3, 6,7,8, 11,12,13 (for 9 positions) positions 1,2,3,4, 6,7,8,9, 11,12,13,14 (for 12 positions) positions 1-15 (for 15 positions) """ # initialize some parameters args = sys.argv user = "" meas_file = "aarm_measurements.txt" samp_file = "er_samples.txt" rmag_anis = "arm_anisotropy.txt" rmag_res = "aarm_results.txt" dir_path = '.' # # get name of file from command line # if '-WD' in args: ind = args.index('-WD') dir_path = args[ind + 1] if "-h" in args: print main.__doc__ sys.exit() if "-usr" in args: ind = args.index("-usr") user = sys.argv[ind + 1] if "-f" in args: ind = args.index("-f") meas_file = sys.argv[ind + 1] coord = '-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 "-fsa" in args: ind = args.index("-fsa") samp_file = sys.argv[ind + 1] if "-Fa" in args: ind = args.index("-Fa") rmag_anis = args[ind + 1] if "-Fr" in args: ind = args.index("-Fr") rmag_res = args[ind + 1] meas_file = dir_path + '/' + meas_file samp_file = dir_path + '/' + samp_file rmag_anis = dir_path + '/' + rmag_anis rmag_res = dir_path + '/' + rmag_res # read in data meas_data, file_type = pmag.magic_read(meas_file) meas_data = pmag.get_dictitem(meas_data, 'magic_method_codes', 'LP-AN-ARM', 'has') if file_type != 'magic_measurements': print file_type print file_type, "This is not a valid magic_measurements file " sys.exit() if coord != '-1': # need to read in sample data samp_data, file_type = pmag.magic_read(samp_file) if file_type != 'er_samples': print file_type print file_type, "This is not a valid er_samples file " print "Only specimen coordinates will be calculated" coord = '-1' # # sort the specimen names # ssort = [] for rec in meas_data: spec = rec["er_specimen_name"] if spec not in ssort: ssort.append(spec) if len(ssort) > 1: sids = sorted(ssort) else: sids = ssort # # work on each specimen # specimen = 0 RmagSpecRecs, RmagResRecs = [], [] while specimen < len(sids): s = sids[specimen] data = [] RmagSpecRec = {} RmagResRec = {} method_codes = [] # # find the data from the meas_data file for this sample # data = pmag.get_dictitem(meas_data, 'er_specimen_name', s, 'T') # # find out the number of measurements (9, 12 or 15) # npos = len(data) / 2 if npos == 9: # # get dec, inc, int and convert to x,y,z # B, H, tmpH = pmag.designAARM( npos) # B matrix made from design matrix for positions X = [] for rec in data: Dir = [] Dir.append(float(rec["measurement_dec"])) Dir.append(float(rec["measurement_inc"])) Dir.append(float(rec["measurement_magn_moment"])) X.append(pmag.dir2cart(Dir)) # # subtract baseline and put in a work array # work = numpy.zeros((npos, 3), 'f') for i in range(npos): for j in range(3): work[i][j] = X[2 * i + 1][j] - X[2 * i][j] # # calculate tensor elements # first put ARM components in w vector # w = numpy.zeros((npos * 3), 'f') index = 0 for i in range(npos): for j in range(3): w[index] = work[i][j] index += 1 s = numpy.zeros((6), 'f') # initialize the s matrix for i in range(6): for j in range(len(w)): s[i] += B[i][j] * w[j] trace = s[0] + s[1] + s[2] # normalize by the trace for i in range(6): s[i] = s[i] / trace a = pmag.s2a(s) #------------------------------------------------------------ # Calculating dels is different than in the Kappabridge # routine. Use trace normalized tensor (a) and the applied # unit field directions (tmpH) to generate model X,Y,Z # components. Then compare these with the measured values. #------------------------------------------------------------ S = 0. comp = numpy.zeros((npos * 3), 'f') for i in range(npos): for j in range(3): index = i * 3 + j compare = a[j][0] * tmpH[i][0] + a[j][1] * tmpH[i][1] + a[ j][2] * tmpH[i][2] comp[index] = compare for i in range(npos * 3): d = w[i] / trace - comp[i] # del values S += d * d nf = float(npos * 3 - 6) # number of degrees of freedom if S > 0: sigma = numpy.sqrt(S / nf) else: sigma = 0 RmagSpecRec["rmag_anisotropy_name"] = data[0]["er_specimen_name"] RmagSpecRec["er_location_name"] = data[0]["er_location_name"] RmagSpecRec["er_specimen_name"] = data[0]["er_specimen_name"] RmagSpecRec["er_sample_name"] = data[0]["er_sample_name"] RmagSpecRec["er_site_name"] = data[0]["er_site_name"] RmagSpecRec["magic_experiment_names"] = RmagSpecRec[ "rmag_anisotropy_name"] + ":AARM" RmagSpecRec["er_citation_names"] = "This study" RmagResRec[ "rmag_result_name"] = data[0]["er_specimen_name"] + ":AARM" RmagResRec["er_location_names"] = data[0]["er_location_name"] RmagResRec["er_specimen_names"] = data[0]["er_specimen_name"] RmagResRec["er_sample_names"] = data[0]["er_sample_name"] RmagResRec["er_site_names"] = data[0]["er_site_name"] RmagResRec["magic_experiment_names"] = RmagSpecRec[ "rmag_anisotropy_name"] + ":AARM" RmagResRec["er_citation_names"] = "This study" if "magic_instrument_codes" in data[0].keys(): RmagSpecRec["magic_instrument_codes"] = data[0][ "magic_instrument_codes"] else: RmagSpecRec["magic_instrument_codes"] = "" RmagSpecRec["anisotropy_type"] = "AARM" RmagSpecRec[ "anisotropy_description"] = "Hext statistics adapted to AARM" if coord != '-1': # need to rotate s # set orientation priorities SO_methods = [] for rec in samp_data: if "magic_method_codes" not in rec: rec['magic_method_codes'] = 'SO-NO' if "magic_method_codes" in rec: methlist = rec["magic_method_codes"] for meth in methlist.split(":"): if "SO" in meth and "SO-POM" not in meth.strip(): if meth.strip() not in SO_methods: SO_methods.append(meth.strip()) SO_priorities = pmag.set_priorities(SO_methods, 0) # continue here redo, p = 1, 0 if len(SO_methods) <= 1: az_type = SO_methods[0] orient = pmag.find_samp_rec(RmagSpecRec["er_sample_name"], samp_data, az_type) if orient["sample_azimuth"] != "": method_codes.append(az_type) redo = 0 while redo == 1: if p >= len(SO_priorities): print "no orientation data for ", s orient["sample_azimuth"] = "" orient["sample_dip"] = "" method_codes.append("SO-NO") redo = 0 else: az_type = SO_methods[SO_methods.index( SO_priorities[p])] orient = pmag.find_samp_rec( PmagSpecRec["er_sample_name"], samp_data, az_type) if orient["sample_azimuth"] != "": method_codes.append(az_type) redo = 0 p += 1 az, pl = orient['sample_azimuth'], orient['sample_dip'] s = pmag.dosgeo(s, az, pl) # rotate to geographic coordinates if coord == '100': sampe_bed_dir, sample_bed_dip = orient[ 'sample_bed_dip_direction'], orient['sample_bed_dip'] s = pmag.dostilt( s, bed_dir, bed_dip) # rotate to geographic coordinates hpars = pmag.dohext(nf, sigma, s) # # prepare for output # RmagSpecRec["anisotropy_s1"] = '%8.6f' % (s[0]) RmagSpecRec["anisotropy_s2"] = '%8.6f' % (s[1]) RmagSpecRec["anisotropy_s3"] = '%8.6f' % (s[2]) RmagSpecRec["anisotropy_s4"] = '%8.6f' % (s[3]) RmagSpecRec["anisotropy_s5"] = '%8.6f' % (s[4]) RmagSpecRec["anisotropy_s6"] = '%8.6f' % (s[5]) RmagSpecRec["anisotropy_mean"] = '%8.3e' % (trace / 3) RmagSpecRec["anisotropy_sigma"] = '%8.6f' % (sigma) RmagSpecRec["anisotropy_unit"] = "Am^2" RmagSpecRec["anisotropy_n"] = '%i' % (npos) RmagSpecRec["anisotropy_tilt_correction"] = coord RmagSpecRec["anisotropy_F"] = '%7.1f ' % ( hpars["F"] ) # used by thellier_gui - must be taken out for uploading RmagSpecRec["anisotropy_F_crit"] = hpars[ "F_crit"] # used by thellier_gui - must be taken out for uploading RmagResRec["anisotropy_t1"] = '%8.6f ' % (hpars["t1"]) RmagResRec["anisotropy_t2"] = '%8.6f ' % (hpars["t2"]) RmagResRec["anisotropy_t3"] = '%8.6f ' % (hpars["t3"]) RmagResRec["anisotropy_v1_dec"] = '%7.1f ' % (hpars["v1_dec"]) RmagResRec["anisotropy_v2_dec"] = '%7.1f ' % (hpars["v2_dec"]) RmagResRec["anisotropy_v3_dec"] = '%7.1f ' % (hpars["v3_dec"]) RmagResRec["anisotropy_v1_inc"] = '%7.1f ' % (hpars["v1_inc"]) RmagResRec["anisotropy_v2_inc"] = '%7.1f ' % (hpars["v2_inc"]) RmagResRec["anisotropy_v3_inc"] = '%7.1f ' % (hpars["v3_inc"]) RmagResRec["anisotropy_ftest"] = '%7.1f ' % (hpars["F"]) RmagResRec["anisotropy_ftest12"] = '%7.1f ' % (hpars["F12"]) RmagResRec["anisotropy_ftest23"] = '%7.1f ' % (hpars["F23"]) RmagResRec["result_description"] = 'Critical F: ' + hpars[ "F_crit"] + ';Critical F12/F13: ' + hpars["F12_crit"] if hpars["e12"] > hpars["e13"]: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) if hpars["e23"] > hpars['e12']: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["tilt_correction"] = '-1' RmagResRec["anisotropy_type"] = 'AARM' RmagResRec["magic_method_codes"] = 'LP-AN-ARM:AE-H' RmagSpecRec["magic_method_codes"] = 'LP-AN-ARM:AE-H' RmagResRec["magic_software_packages"] = pmag.get_version() RmagSpecRec["magic_software_packages"] = pmag.get_version() specimen += 1 RmagSpecRecs.append(RmagSpecRec) RmagResRecs.append(RmagResRec) else: print 'skipping specimen ', s, ' only 9 positions supported', '; this has ', npos specimen += 1 if rmag_anis == "": rmag_anis = "rmag_anisotropy.txt" pmag.magic_write(rmag_anis, RmagSpecRecs, 'rmag_anisotropy') print "specimen tensor elements stored in ", rmag_anis if rmag_res == "": rmag_res = "rmag_results.txt" pmag.magic_write(rmag_res, RmagResRecs, 'rmag_results') print "specimen statistics and eigenparameters stored in ", rmag_res
def main(): """ NAME dayplot_magic.py DESCRIPTION makes 'day plots' (Day et al. 1977) and squareness/coercivity, plots 'linear mixing' curve from Dunlop and Carter-Stiglitz (2006). squareness coercivity of remanence (Neel, 1955) plots after Tauxe et al. (2002) SYNTAX dayplot_magic.py [command line options] OPTIONS -h prints help message and quits -f: specify input hysteresis file, default is rmag_hysteresis.txt -fr: specify input remanence file, default is rmag_remanence.txt -fmt [svg,png,jpg] format for output plots -sav saves plots and quits quietly -n label specimen names """ args=sys.argv hyst_file,rem_file="rmag_hysteresis.txt","rmag_remanence.txt" dir_path='.' verbose=pmagplotlib.verbose fmt='svg' # default file format if '-WD' in args: ind=args.index('-WD') dir_path=args[ind+1] if "-h" in args: print(main.__doc__) sys.exit() if '-f' in args: ind=args.index("-f") hyst_file=args[ind+1] if '-fr' in args: ind=args.index("-fr") rem_file=args[ind+1] if '-fmt' in sys.argv: ind=sys.argv.index("-fmt") fmt=sys.argv[ind+1] if '-sav' in sys.argv: plots=1 verbose=0 else: plots=0 if '-n' in sys.argv: label=1 else: label=0 hyst_file = os.path.realpath(os.path.join(dir_path, hyst_file)) rem_file = os.path.realpath(os.path.join(dir_path, rem_file)) # # initialize some variables # define figure numbers for Day,S-Bc,S-Bcr DSC={} DSC['day'],DSC['S-Bc'],DSC['S-Bcr'],DSC['bcr1-bcr2']=1,2,3,4 pmagplotlib.plot_init(DSC['day'],5,5) pmagplotlib.plot_init(DSC['S-Bc'],5,5) pmagplotlib.plot_init(DSC['S-Bcr'],5,5) pmagplotlib.plot_init(DSC['bcr1-bcr2'],5,5) # # hyst_data,file_type=pmag.magic_read(hyst_file) rem_data,file_type=pmag.magic_read(rem_file) # S,BcrBc,Bcr2,Bc,hsids,Bcr=[],[],[],[],[],[] Ms,Bcr1,Bcr1Bc,S1=[],[],[],[] names=[] locations='' for rec in hyst_data: if 'er_location_name' in rec.keys() and rec['er_location_name'] not in locations: locations=locations+rec['er_location_name']+'_' if rec['hysteresis_bcr'] !="" and rec['hysteresis_mr_moment']!="": S.append(float(rec['hysteresis_mr_moment'])/float(rec['hysteresis_ms_moment'])) Bcr.append(float(rec['hysteresis_bcr'])) Bc.append(float(rec['hysteresis_bc'])) BcrBc.append(Bcr[-1]/Bc[-1]) if 'er_synthetic_name' in rec.keys() and rec['er_synthetic_name']!="": rec['er_specimen_name']=rec['er_synthetic_name'] hsids.append(rec['er_specimen_name']) names.append(rec['er_specimen_name']) if len(rem_data)>0: for rec in rem_data: if rec['remanence_bcr'] !="" and float(rec['remanence_bcr'])>0: try: ind=hsids.index(rec['er_specimen_name']) Bcr1.append(float(rec['remanence_bcr'])) Bcr1Bc.append(Bcr1[-1]/Bc[ind]) S1.append(S[ind]) Bcr2.append(Bcr[ind]) except ValueError: if verbose:print('hysteresis data for ',rec['er_specimen_name'],' not found') # # now plot the day and S-Bc, S-Bcr plots # leglist=[] if label==0:names=[] if len(Bcr1)>0: pmagplotlib.plotDay(DSC['day'],Bcr1Bc,S1,'ro',names=names) pmagplotlib.plotSBcr(DSC['S-Bcr'],Bcr1,S1,'ro') pmagplotlib.plot_init(DSC['bcr1-bcr2'],5,5) pmagplotlib.plotBcr(DSC['bcr1-bcr2'],Bcr1,Bcr2) else: del DSC['bcr1-bcr2'] pmagplotlib.plotDay(DSC['day'],BcrBc,S,'bs',names=names) pmagplotlib.plotSBcr(DSC['S-Bcr'],Bcr,S,'bs') pmagplotlib.plotSBc(DSC['S-Bc'],Bc,S,'bs') files={} if len(locations)>0:locations=locations[:-1] for key in DSC.keys(): if pmagplotlib.isServer: # use server plot naming convention files[key] = 'LO:_'+locations+'_'+'SI:__SA:__SP:__TY:_'+key+'_.'+fmt else: # use more readable plot naming convention files[key] = '{}_{}.{}'.format(locations, key, fmt) if verbose: pmagplotlib.drawFIGS(DSC) ans=raw_input(" S[a]ve to save plots, return to quit: ") if ans=="a": pmagplotlib.saveP(DSC,files) else: sys.exit() if plots: pmagplotlib.saveP(DSC,files)
def main(): """ NAME lnp_magic.py DESCRIPTION makes equal area projections site by site from 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 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 'specimens.txt', ('pmag_specimens.txt' for legacy data model 2) -fsa FILE: specify samples file, required to plot by site for data model 3 (otherwise will plot by sample) default is 'samples.txt' -crd [s,g,t]: specify coordinate system, [s]pecimen, [g]eographic, [t]ilt adjusted default is specimen -fmt [svg,png,jpg] format for plots, default is svg -sav save plots and quit -P: do not plot -F FILE, specify output file of dec, inc, alpha95 data for plotting with plotdi_a and plotdi_e -exc use criteria in criteria table # NOT IMPLEMENTED -DM NUMBER MagIC data model (2 or 3, default 3) """ if '-h' in sys.argv: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg("-WD", ".") data_model = int(float(pmag.get_named_arg("-DM", 3))) fmt = pmag.get_named_arg("-fmt", 'svg') if data_model == 2: in_file = pmag.get_named_arg('-f', 'pmag_specimens.txt') crit_file = "pmag_criteria.txt" else: in_file = pmag.get_named_arg('-f', 'specimens.txt') samp_file = pmag.get_named_arg('-fsa', 'samples.txt') crit_file = "criteria.txt" in_file = pmag.resolve_file_name(in_file, dir_path) dir_path = os.path.split(in_file)[0] if data_model == 3: samp_file = pmag.resolve_file_name(samp_file, dir_path) 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" else: coord = "-1" out_file = pmag.get_named_arg('-F', '') if out_file: out = open(dir_path+'/'+out_file, 'w') if '-P' in sys.argv: make_plots = 0 # do not plot else: make_plots = 1 # do plot if '-sav' in sys.argv: plot = 1 # save plots and quit else: plot = 0 # show plots intereactively (if make_plots) # if data_model == 2: Specs, file_type = pmag.magic_read(in_file) if 'specimens' not in file_type: print('Error opening ', in_file, file_type) sys.exit() else: fnames = {'specimens': in_file, 'samples': samp_file} con = cb.Contribution(dir_path, read_tables=['samples', 'specimens'], custom_filenames=fnames) con.propagate_name_down('site', 'specimens') if 'site' in con.tables['specimens'].df.columns: site_col = 'site' else: site_col = 'sample' tilt_corr_col = "dir_tilt_correction" mad_col = "dir_mad_free" alpha95_col = "dir_alpha95" site_alpha95_col = "dir_alpha95" dec_col = "dir_dec" inc_col = "dir_inc" num_meas_col = "dir_n_measurements" k_col = "dir_k" cols = [site_col, tilt_corr_col, mad_col, alpha95_col, dec_col, inc_col] con.tables['specimens'].front_and_backfill(cols) con.tables['specimens'].df = con.tables['specimens'].df.where(con.tables['specimens'].df.notnull(), "") Specs = con.tables['specimens'].convert_to_pmag_data_list() ## using criteria file was never fully implemented #if '-exc' in sys.argv: # Crits, file_type = pmag.magic_read(pmag.resolve_file_name(crit_file, dir_path)) # for crit in Crits: # if mad_col in crit: # M = float(crit['specimen_mad']) # if num_meas_col in crit: # N = float(crit['specimen_n']) # if site_alpha95_col in crit and 'site' in crit: # acutoff = float(crit['site_alpha95']) # if k_col in crit: # kcutoff = float(crit['site_k']) #else: # Crits = "" sitelist = [] # initialize some variables FIG = {} # plot dictionary FIG['eqarea'] = 1 # eqarea is figure 1 M, N, acutoff, kcutoff = 180., 1, 180., 0. if data_model == 2: site_col = 'er_site_name' tilt_corr_col = "specimen_tilt_correction" mad_col = "specimen_mad" alpha95_col = 'specimen_alpha95' dec_col = "specimen_dec" inc_col = "specimen_inc" num_meas_col = "specimen_n" site_alpha95_col = "site_alpha95" else: # data model 3 pass for rec in Specs: if rec[site_col] not in sitelist: sitelist.append(rec[site_col]) sitelist.sort() if make_plots == 1: EQ = {} EQ['eqarea'] = 1 for site in sitelist: pmagplotlib.plot_init(EQ['eqarea'], 4, 4) print(site) data = [] for spec in Specs: if tilt_corr_col not in list(spec.keys()): spec[tilt_corr_col] = '-1' # assume unoriented if spec[site_col] == site: if mad_col not in list(spec.keys()) or spec[mad_col] == "": if alpha95_col in list(spec.keys()) and spec[alpha95_col] != "": spec[mad_col] = spec[alpha95_col] else: spec[mad_col] = '180' if not spec[num_meas_col]: continue if (float(spec[tilt_corr_col]) == float(coord)) and (float(spec[mad_col]) <= M) and (float(spec[num_meas_col]) >= N): rec = {} for key in list(spec.keys()): rec[key] = spec[key] rec["dec"] = float(spec[dec_col]) rec["inc"] = float(spec[inc_col]) rec["tilt_correction"] = spec[tilt_corr_col] 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 make_plots == 1: files = {} files['eqarea'] = site+'_'+crd+'_'+'eqarea'+'.'+fmt pmagplotlib.plot_lnp(EQ['eqarea'], site, data, fpars, 'specimen_direction_type') if plot == 0: pmagplotlib.draw_figs(EQ) ans = input( "s[a]ve plot, [q]uit, <return> to continue:\n ") if ans == "a": pmagplotlib.save_plots(EQ, files) if ans == "q": sys.exit() else: pmagplotlib.save_plots(EQ, files) else: print('skipping site - not enough data with specified coordinate system')
def main(): """ NAME basemap_magic.py NB: this program no longer maintained - use plot_mapPTS.py for greater functionality DESCRIPTION makes a map of locations in er_sites.txt SYNTAX basemap_magic.py [command line options] OPTIONS -h prints help message and quits -f SFILE, specify er_sites.txt or pmag_results.txt format file -res [c,l,i,h] specify resolution (crude,low,intermediate,high) -etp plot the etopo20 topographic mesh -pad [LAT LON] pad bounding box by LAT/LON (default is [.5 .5] degrees) -grd SPACE specify grid spacing -prj [lcc] , specify projection (lcc=lambert conic conformable), default is mercator -n print site names (default is not) -l print location names (default is not) -o color ocean blue/land green (default is not) -R don't plot details of rivers -B don't plot national/state boundaries, etc. -sav save plot and quit quietly -fmt [png,svg,eps,jpg,pdf] specify format for output, default is pdf DEFAULTS SFILE: 'er_sites.txt' resolution: intermediate saved images are in pdf """ dir_path='.' sites_file='er_sites.txt' ocean=0 res='i' proj='merc' prn_name=0 prn_loc=0 fancy=0 rivers,boundaries=0,0 padlon,padlat,gridspace,details=.5,.5,.5,1 fmt='pdf' if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind = sys.argv.index('-f') sites_file=sys.argv[ind+1] if '-res' in sys.argv: ind = sys.argv.index('-res') res=sys.argv[ind+1] if '-etp' in sys.argv:fancy=1 if '-n' in sys.argv:prn_name=1 if '-l' in sys.argv:prn_loc=1 if '-o' in sys.argv:ocean=1 if '-R' in sys.argv:rivers=0 if '-B' in sys.argv:boundaries=0 if '-prj' in sys.argv: ind = sys.argv.index('-prj') proj=sys.argv[ind+1] if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt=sys.argv[ind+1] verbose=pmagplotlib.verbose if '-sav' in sys.argv: verbose=0 if '-pad' in sys.argv: ind = sys.argv.index('-pad') padlat=float(sys.argv[ind+1]) padlon=float(sys.argv[ind+2]) if '-grd' in sys.argv: ind = sys.argv.index('-grd') gridspace=float(sys.argv[ind+1]) if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path=sys.argv[ind+1] sites_file=dir_path+'/'+sites_file location="" FIG={'map':1} pmagplotlib.plot_init(FIG['map'],6,6) # read in er_sites file Sites,file_type=pmag.magic_read(sites_file) if 'results' in file_type: latkey='average_lat' lonkey='average_lon' namekey='pmag_result_name' lockey='er_location_names' else: latkey='site_lat' lonkey='site_lon' namekey='er_site_name' lockey='er_location_name' lats,lons=[],[] slats,slons=[],[] names,locs=[],[] for site in Sites: if prn_loc==1 and location=="":location=site['er_location_name'] lats.append(float(site[latkey])) l=float(site[lonkey]) if l<0:l=l+360. # make positive lons.append(l) if prn_name==1:names.append(site[namekey]) if prn_loc==1:locs.append(site[lockey]) for lat in lats:slats.append(lat) for lon in lons:slons.append(lon) Opts={'res':res,'proj':proj,'loc_name':locs,'padlon':padlon,'padlat':padlat,'latmin':numpy.min(slats)-padlat,'latmax':numpy.max(slats)+padlat,'lonmin':numpy.min(slons)-padlon,'lonmax':numpy.max(slons)+padlon,'sym':'ro','boundinglat':0.,'pltgrid':1.} Opts['lon_0']=0.5*(numpy.min(slons)+numpy.max(slons)) Opts['lat_0']=0.5*(numpy.min(slats)+numpy.max(slats)) Opts['names']=names Opts['gridspace']=gridspace Opts['details']={'coasts':1,'rivers':1,'states':1,'countries':1,'ocean':0} if ocean==1:Opts['details']['ocean']=1 if rivers==1: Opts['details']['rivers']=0 if boundaries==1: Opts['details']['states']=0 Opts['details']['countries']=0 Opts['details']['fancy']=fancy pmagplotlib.plotMAP(FIG['map'],lats,lons,Opts) if verbose:pmagplotlib.drawFIGS(FIG) files={} for key in FIG.keys(): files[key]='Site_map'+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['map']='Site Map' FIG = pmagplotlib.addBorders(FIG,titles,black,purple) pmagplotlib.saveP(FIG,files) elif verbose: ans=raw_input(" S[a]ve to save plot, Return to quit: ") if ans=="a": pmagplotlib.saveP(FIG,files) else: pmagplotlib.saveP(FIG,files)
def main(): """ NAME dmag_magic.py DESCRIPTION plots intensity decay curves for demagnetization experiments SYNTAX dmag_magic -h [command line options] INPUT takes magic formatted magic_measurements.txt files OPTIONS -h prints help message and quits -f FILE: specify input file, default is: magic_measurements.txt -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is by location -LT [AF,T,M]: specify lab treatment type, default AF -XLP [PI]: exclude specific lab protocols (for example, method codes like LP-PI) -N do not normalize by NRM magnetization -sav save plots silently and quit -fmt [svg,jpg,png,pdf] set figure format [default is svg] NOTE loc: location (study); sit: site; sam: sample; spc: specimen """ FIG={} # plot dictionary FIG['demag']=1 # demag is figure 1 in_file,plot_key,LT='magic_measurements.txt','er_location_name',"LT-AF-Z" XLP="" norm=1 LT='LT-AF-Z' units,dmag_key='T','treatment_ac_field' plot=0 fmt='svg' if len(sys.argv)>1: if '-h' in sys.argv: print main.__doc__ sys.exit() if '-N' in sys.argv: norm=0 if '-sav' in sys.argv: plot=1 if '-f' in sys.argv: ind=sys.argv.index("-f") in_file=sys.argv[ind+1] if '-fmt' in sys.argv: ind=sys.argv.index("-fmt") fmt=sys.argv[ind+1] if '-obj' in sys.argv: ind=sys.argv.index('-obj') plot_by=sys.argv[ind+1] if plot_by=='sit':plot_key='er_site_name' if plot_by=='sam':plot_key='er_sample_name' if plot_by=='spc':plot_key='er_specimen_name' if '-XLP' in sys.argv: ind=sys.argv.index("-XLP") XLP=sys.argv[ind+1] # get lab protocol for excluding if '-LT' in sys.argv: ind=sys.argv.index("-LT") LT='LT-'+sys.argv[ind+1]+'-Z' # get lab treatment for plotting if LT=='LT-T-Z': units,dmag_key='K','treatment_temp' elif LT=='LT-AF-Z': units,dmag_key='T','treatment_ac_field' elif LT=='LT-M-Z': units,dmag_key='J','treatment_mw_energy' else: units='U' data,file_type=pmag.magic_read(in_file) sids=pmag.get_specs(data) pmagplotlib.plot_init(FIG['demag'],5,5) print len(data),' records read from ',in_file # # # find desired intensity data # # plotlist,intlist=[],['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass'] IntMeths=[] FixData=[] for rec in data: meths=[] methcodes=rec['magic_method_codes'].split(':') for meth in methcodes:meths.append(meth.strip()) for key in rec.keys(): if key in intlist and rec[key]!="": if key not in IntMeths:IntMeths.append(key) if rec[plot_key] not in plotlist and LT in meths: plotlist.append(rec[plot_key]) if 'measurement_flag' not in rec.keys():rec['measurement_flag']='g' FixData.append(rec) plotlist.sort() if len(IntMeths)==0: print 'No intensity information found' sys.exit() data=FixData int_key=IntMeths[0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used for plt in plotlist: if plot==0: print plt,'plotting by: ',plot_key PLTblock=pmag.get_dictitem(data,plot_key,plt,'T') # fish out all the data for this type of plot PLTblock=pmag.get_dictitem(PLTblock,'magic_method_codes',LT,'has') # fish out all the dmag for this experiment type PLTblock=pmag.get_dictitem(PLTblock,int_key,'','F') # get all with this intensity key non-blank if XLP!="":PLTblock=pmag.get_dictitem(PLTblock,'magic_method_codes',XLP,'not') # reject data with XLP in method_code if len(PLTblock)>2: title=PLTblock[0][plot_key] spcs=[] for rec in PLTblock: if rec['er_specimen_name'] not in spcs:spcs.append(rec['er_specimen_name']) for spc in spcs: SPCblock=pmag.get_dictitem(PLTblock,'er_specimen_name',spc,'T') # plot specimen by specimen INTblock=[] for rec in SPCblock: INTblock.append([float(rec[dmag_key]),0,0,float(rec[int_key]),1,rec['measurement_flag']]) if len(INTblock)>2: pmagplotlib.plotMT(FIG['demag'],INTblock,title,0,units,norm) if plot==1: files={} for key in FIG.keys(): files[key]=title+'_'+LT+'.'+fmt pmagplotlib.saveP(FIG,files) sys.exit() else: pmagplotlib.drawFIGS(FIG) ans=raw_input(" S[a]ve to save plot, [q]uit, Return to continue: ") if ans=='q':sys.exit() if ans=="a": files={} for key in FIG.keys(): files[key]=title+'_'+LT+'.svg' pmagplotlib.saveP(FIG,files) pmagplotlib.clearFIG(FIG['demag'])
def main(): """ NAME customize_criteria.py NB: This program has been deprecated - use demag_gui or thellier_gui to customize acceptance criteria - OR pandas from within a jupyter notebook DESCRIPTION Allows user to specify acceptance criteria, saves them in pmag_criteria.txt SYNTAX customize_criteria.py [-h][command line options] OPTIONS -h prints help message and quits -f IFILE, reads in existing criteria -F OFILE, writes to pmag_criteria format file DEFAULTS IFILE: pmag_criteria.txt OFILE: pmag_criteria.txt OUTPUT creates a pmag_criteria.txt formatted output file """ infile, critout = "", "pmag_criteria.txt" # parse command line options if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-f' in sys.argv: ind = sys.argv.index('-f') infile = sys.argv[ind + 1] crit_data, file_type = pmag.magic_read(infile) if file_type != 'pmag_criteria': print('bad input file') print(main.__doc__) sys.exit() print("Acceptance criteria read in from ", infile) if '-F' in sys.argv: ind = sys.argv.index('-F') critout = sys.argv[ind + 1] Dcrit, Icrit, nocrit = 0, 0, 0 custom = '1' crit = input( " [0] Use no acceptance criteria?\n [1] Use default criteria\n [2] customize criteria \n " ) if crit == '0': print('Very very loose criteria saved in ', critout) crit_data = pmag.default_criteria(1) pmag.magic_write(critout, crit_data, 'pmag_criteria') sys.exit() crit_data = pmag.default_criteria(0) if crit == '1': print('Default criteria saved in ', critout) pmag.magic_write(critout, crit_data, 'pmag_criteria') sys.exit() CritRec = crit_data[0] crit_keys = list(CritRec.keys()) crit_keys.sort() print( "Enter new threshold value.\n Return to keep default.\n Leave blank to not use as a criterion\n " ) for key in crit_keys: if key != 'pmag_criteria_code' and key != 'er_citation_names' and key != 'criteria_definition' and CritRec[ key] != "": print(key, CritRec[key]) new = input('new value: ') if new != "": CritRec[key] = (new) pmag.magic_write(critout, [CritRec], 'pmag_criteria') print("Criteria saved in pmag_criteria.txt")
def main(): """ NAME plotxy_magic.py DESCRIPTION Makes simple X,Y plots INPUT FORMAT Any MagIC formatted file SYNTAX plotxy_magic.py [command line options] OPTIONS -h prints this help message -f FILE to set file name on command rec -c col1 col2 specify columns names to plot -sym SYM SIZE specify symbol and size to plot: default is red dots -S don't plot symbols -xlab XLAB -ylab YLAB -l connect symbols with lines -b xmin xmax ymin ymax, sets bounds # -b [key:max:min,key:max:min,etc.] leave or min blank for no cutoff """ col1,col2=0,1 sym,size = 'ro',20 xlab,ylab='','' lines=0 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] else: '-f option is a required field' print(main.__doc__) sys.exit() if '-c' in sys.argv: ind=sys.argv.index('-c') col1=sys.argv[ind+1] col2=sys.argv[ind+2] else: 'Column headers a required field' print(main.__doc__) sys.exit() if '-xlab' in sys.argv: ind=sys.argv.index('-xlab') xlab=sys.argv[ind+1] if '-ylab' in sys.argv: ind=sys.argv.index('-ylab') ylab=sys.argv[ind+1] # if '-b' in sys.argv: # ind=sys.argv.index('-b') # bounds=sys.argv[ind+1].split(',') if '-b' in sys.argv: ind=sys.argv.index('-b') xmin=float(sys.argv[ind+1]) xmax=float(sys.argv[ind+2]) ymin=float(sys.argv[ind+3]) ymax=float(sys.argv[ind+4]) if '-sym' in sys.argv: ind=sys.argv.index('-sym') sym=sys.argv[ind+1] size=int(sys.argv[ind+2]) if '-l' in sys.argv: lines=1 if '-S' in sys.argv: sym='' X,Y=[],[] data,file_type=pmag.magic_read(file) print(file_type) for rec in data: if col1 not in list(rec.keys()) or col2 not in list(rec.keys()): print(col1,' and/or ',col2, ' not in file headers') print('try again') sys.exit() if rec[col1]!='' and rec[col2]!='': skip=0 if '-crit' in sys.argv: for crit in bounds: crits=crit.split(':') crit_key=crits[0] crit_min=crits[1] crit_max=crits[2] if rec[crit_key]=="": skip=1 else: if crit_min!="" and float(rec[crit_key])<float(crit_min):skip=1 if crit_max!="" and float(rec[crit_key])>float(crit_min):skip=1 if skip==0: X.append(float(rec[col1])) Y.append(float(rec[col2])) if len(X)==0: print(col1,' and/or ',col2, ' have no data ') print('try again') sys.exit() else: print(len(X),' data points') if sym!='':pylab.scatter(X,Y,c=sym[0],marker=sym[1],s=size) if xlab!='':pylab.xlabel(xlab) if ylab!='':pylab.ylabel(ylab) if lines==1:pylab.plot(X,Y,'k-') if '-b' in sys.argv:pylab.axis([xmin,xmax,ymin,ymax]) pylab.draw() ans=input("Press return to quit ") sys.exit()
def main(command_line=True, **kwargs): """ NAME iodp_jr6_magic.py DESCRIPTION converts shipboard .jr6 format files to magic_measurements format files SYNTAX iodp_jr6_magic.py [command line options] OPTIONS -h: prints the help message and quits. -f FILE: specify input file, or -F FILE: specify output file, default is magic_measurements.txt -fsa FILE: specify er_samples.txt file for sample name lookup , default is 'er_samples.txt' -loc HOLE : specify hole name (U1456A) -A: don't average replicate measurements INPUT JR6 .jr6 format file """ def fix_separation(filename, new_filename): old_file = open(filename, 'r') data = old_file.readlines() new_data = [] for line in data: new_line = line.replace('-', ' -') new_line = new_line.replace(' ', ' ') new_data.append(new_line) new_file = open(new_filename, 'w') for s in new_data: new_file.write(s) old_file.close() new_file.close() return new_filename def old_fix_separation(filename, new_filename): old_file = open(filename, 'r') data = old_file.readlines() new_data = [] for line in data: new_line = [] for i in line.split(): if '-' in i[1:]: lead_char = '-' if i[0] == '-' else '' if lead_char: v = i[1:].split('-') else: v = i.split('-') new_line.append(lead_char + v[0]) new_line.append('-' + v[1]) else: new_line.append(i) new_line = (' '.join(new_line)) + '\n' new_data.append(new_line) new_file = open(new_filename, 'w') for s in new_data: new_file.write(s) new_file.close() old_file.close() return new_filename # initialize some stuff noave = 0 volume = 2.5**3 #default volume is a 2.5cm cube inst = "" samp_con, Z = '5', "" missing = 1 demag = "N" er_location_name = "unknown" citation = 'This study' args = sys.argv meth_code = "LP-NO" version_num = pmag.get_version() dir_path = '.' MagRecs = [] samp_file = 'er_samples.txt' meas_file = 'magic_measurements.txt' mag_file = '' # # get command line arguments # if command_line: if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path = sys.argv[ind + 1] if '-ID' in sys.argv: ind = sys.argv.index('-ID') input_dir_path = sys.argv[ind + 1] else: input_dir_path = dir_path output_dir_path = dir_path if "-h" in args: print(main.__doc__) return False if '-F' in args: ind = args.index("-F") meas_file = args[ind + 1] if '-fsa' in args: ind = args.index("-fsa") samp_file = args[ind + 1] if samp_file[0] != '/': samp_file = os.path.join(input_dir_path, samp_file) try: open(samp_file, 'r') ErSamps, file_type = pmag.magic_read(samp_file) except: print(samp_file, ' not found: ') print( ' download csv file and import to MagIC with iodp_samples_magic.py' ) if '-f' in args: ind = args.index("-f") mag_file = args[ind + 1] if "-loc" in args: ind = args.index("-loc") er_location_name = args[ind + 1] if "-A" in args: noave = 1 if not command_line: dir_path = kwargs.get('dir_path', '.') input_dir_path = kwargs.get('input_dir_path', dir_path) output_dir_path = dir_path meas_file = kwargs.get('meas_file', 'magic_measurements.txt') mag_file = kwargs.get('mag_file', '') samp_file = kwargs.get('samp_file', 'er_samples.txt') specnum = kwargs.get('specnum', 1) samp_con = kwargs.get('samp_con', '1') if len(str(samp_con)) > 1: samp_con, Z = samp_con.split('-') else: Z = '' er_location_name = kwargs.get('er_location_name', '') noave = kwargs.get('noave', 0) # default (0) means DO average meth_code = kwargs.get('meth_code', "LP-NO") # format variables meth_code = meth_code + ":FS-C-DRILL-IODP:SP-SS-C:SO-V" meth_code = meth_code.strip(":") if mag_file: mag_file = os.path.join(input_dir_path, mag_file) samp_file = os.path.join(input_dir_path, samp_file) meas_file = os.path.join(output_dir_path, meas_file) # validate variables if not mag_file: print("You must provide an IODP_jr6 format file") return False, "You must provide an IODP_jr6 format file" if not os.path.exists(mag_file): print( 'The input file you provided: {} does not exist.\nMake sure you have specified the correct filename AND correct input directory name.' .format(mag_file)) return False, 'The input file you provided: {} does not exist.\nMake sure you have specified the correct filename AND correct input directory name.'.format( mag_file) if not os.path.exists(samp_file): print( "Your input directory:\n{}\nmust contain an er_samples.txt file, or you must explicitly provide one" .format(input_dir_path)) return False, "Your input directory:\n{}\nmust contain an er_samples.txt file, or you must explicitly provide one".format( input_dir_path) # parse data temp = os.path.join(output_dir_path, 'temp.txt') fix_separation(mag_file, temp) samples, filetype = pmag.magic_read(samp_file) with open(temp, 'r') as finput: lines = finput.readlines() os.remove(temp) for line in lines: MagRec = {} line = line.split() spec_text_id = line[0].split('_')[1] SampRecs = pmag.get_dictitem(samples, 'er_sample_alternatives', spec_text_id, 'has') if len(SampRecs) > 0: # found one MagRec['er_specimen_name'] = SampRecs[0]['er_sample_name'] MagRec['er_sample_name'] = MagRec['er_specimen_name'] MagRec['er_site_name'] = MagRec['er_specimen_name'] MagRec["er_citation_names"] = "This study" MagRec['er_location_name'] = er_location_name MagRec['magic_software_packages'] = version_num MagRec["treatment_temp"] = '%8.3e' % (273) # room temp in kelvin MagRec["measurement_temp"] = '%8.3e' % (273) # room temp in kelvin MagRec["measurement_flag"] = 'g' MagRec["measurement_standard"] = 'u' MagRec["measurement_number"] = '1' MagRec["treatment_ac_field"] = '0' volume = float(SampRecs[0]['sample_volume']) x = float(line[4]) y = float(line[3]) negz = float(line[2]) cart = np.array([x, y, -negz]).transpose() direction = pmag.cart2dir(cart).transpose() expon = float(line[5]) magn_volume = direction[2] * (10.0**expon) moment = magn_volume * volume MagRec["measurement_magn_moment"] = str(moment) MagRec["measurement_magn_volume"] = str( magn_volume) #str(direction[2] * (10.0 ** expon)) MagRec["measurement_dec"] = '%7.1f' % (direction[0]) MagRec["measurement_inc"] = '%7.1f' % (direction[1]) step = line[1] if step == 'NRM': meas_type = "LT-NO" elif step[0:2] == 'AD': meas_type = "LT-AF-Z" treat = float(step[2:]) MagRec["treatment_ac_field"] = '%8.3e' % ( treat * 1e-3) # convert from mT to tesla elif step[0:2] == 'TD': meas_type = "LT-T-Z" treat = float(step[2:]) MagRec["treatment_temp"] = '%8.3e' % (treat + 273. ) # temp in kelvin elif step[0:3] == 'ARM': # meas_type = "LT-AF-I" treat = float(row['step'][3:]) MagRec["treatment_ac_field"] = '%8.3e' % ( treat * 1e-3) # convert from mT to tesla MagRec["treatment_dc_field"] = '%8.3e' % ( 50e-6) # assume 50uT DC field MagRec[ "measurement_description"] = 'Assumed DC field - actual unknown' elif step[0:3] == 'IRM': # meas_type = "LT-IRM" treat = float(step[3:]) MagRec["treatment_dc_field"] = '%8.3e' % ( treat * 1e-3) # convert from mT to tesla else: print('unknown treatment type for ', row) return False, 'unknown treatment type for ', row MagRec['magic_method_codes'] = meas_type MagRecs.append(MagRec.copy()) else: print('sample name not found: ', row['specname']) MagOuts = pmag.measurements_methods(MagRecs, noave) file_created, error_message = pmag.magic_write(meas_file, MagOuts, 'magic_measurements') if file_created: return True, meas_file else: return False, 'Results not written to file'
def main(command_line=True, **kwargs): """ NAME _2g_bin_magic.py DESCRIPTION takes the binary 2g format magnetometer files and converts them to magic_measurements, er_samples.txt and er_sites.txt file SYNTAX 2g_bin_magic.py [command line options] OPTIONS -f FILE: specify input 2g (binary) file -F FILE: specify magic_measurements output file, default is: magic_measurements.txt -Fsa FILE: specify output file, default is: er_samples.txt -Fsi FILE: specify output file, default is: er_sites.txt -ncn NCON: specify naming convention: default is #2 below -ocn OCON: specify orientation convention, default is #5 below -mcd: specify sampling method codes as a colon delimited string: [default is: FS-FD:SO-POM] FS-FD field sampling done with a drill FS-H field sampling done with hand samples FS-LOC-GPS field location done with GPS FS-LOC-MAP field location done with map SO-POM a Pomeroy orientation device was used SO-ASC an ASC orientation device was used SO-MAG orientation with magnetic compass SO-SUN orientation with sun compass -loc: location name, default="unknown" -spc NUM : specify number of characters to designate a specimen, default = 0 -ins INST : specify instsrument name -a: average replicate measurements INPUT FORMAT Input files are horrible mag binary format (who knows why?) Orientation convention: [1] Lab arrow azimuth= mag_azimuth; Lab arrow dip=-field_dip i.e., field_dip is degrees from vertical down - the hade [default] [2] Lab arrow azimuth = mag_azimuth-90; Lab arrow dip = -field_dip i.e., mag_azimuth is strike and field_dip is hade [3] Lab arrow azimuth = mag_azimuth; Lab arrow dip = 90-field_dip i.e., lab arrow same as field arrow, but field_dip was a hade. [4] lab azimuth and dip are same as mag_azimuth, field_dip [5] lab azimuth is same as mag_azimuth,lab arrow dip=field_dip-90 [6] Lab arrow azimuth = mag_azimuth-90; Lab arrow dip = 90-field_dip [7] all others you will have to either customize your self or e-mail [email protected] for help. Magnetic declination convention: Az will use supplied declination to correct azimuth Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX [5] site name = sample name [6] site name entered in site_name column in the orient.txt format input file -- NOT CURRENTLY SUPPORTED [7-Z] [XXX]YYY: XXX is site designation with Z characters from samples XXXYYY NB: all others you will have to either customize your self or e-mail [email protected] for help. OUTPUT output saved in magic_measurements.txt & er_samples.txt formatted files will overwrite any existing files """ # # initialize variables # mag_file = '' specnum=0 ub_file,samp_file,or_con,corr,meas_file = "","er_samples.txt","3","1","magic_measurements.txt" pos_file,site_file="","er_sites.txt" noave=1 args=sys.argv bed_dip,bed_dip_dir="","" samp_con,Z,average_bedding="2",1,"0" meths='FS-FD' sclass,lithology,_type="","","" user,inst="","" DecCorr=0. location_name="unknown" months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] gmeths="" # # dir_path='.' if command_line: if '-WD' in args: ind=args.index("-WD") dir_path=sys.argv[ind+1] if "-h" in args: print main.__doc__ return False if "-f" in args: ind=args.index("-f") mag_file=sys.argv[ind+1] if "-fpos" in args: ind=args.index("-fpos") pos_file=sys.argv[ind+1] if "-F" in args: ind=args.index("-F") meas_file=sys.argv[ind+1] if "-Fsa" in args: ind=args.index("-Fsa") samp_file=sys.argv[ind+1] if "-Fsi" in args: ind=args.index("-Fsi") site_file=sys.argv[ind+1] if "-ocn" in args: ind=args.index("-ocn") or_con=sys.argv[ind+1] if "-ncn" in args: ind=args.index("-ncn") samp_con=sys.argv[ind+1] if "-mcd" in args: ind=args.index("-mcd") gmeths=(sys.argv[ind+1]) if "-loc" in args: ind=args.index("-loc") location_name=(sys.argv[ind+1]) if "-spc" in args: ind=args.index("-spc") specnum=int(args[ind+1]) if "-ins" in args: ind=args.index("-ins") inst=args[ind+1] if "-a" in args: noave=0 # ID = False if '-ID' in args: ind = args.index('-ID') ID = args[ind+1] # if not command_line: dir_path = kwargs.get('dir_path', '.') mag_file = kwargs.get('mag_file', '') pos_file = kwargs.get('pos_file', '') meas_file = kwargs.get('meas_file', 'magic_measurements.txt') samp_file = kwargs.get('samp_file', 'er_samples.txt') site_file = kwargs.get('site_file', 'er_sites.txt') or_con = kwargs.get('or_con', '3') samp_con = kwargs.get('samp_con', '2') corr = kwargs.get('corr', '1') gmeths = kwargs.get('gmeths', '') location_name = kwargs.get('location_name', '') specnum = int(kwargs.get('specnum', 0)) inst = kwargs.get('inst', '') noave = kwargs.get('noave', 1) # default is DO average ID = kwargs.get('ID', '') # format and fix variables acquired from command line args or input with **kwargs if specnum!=0:specnum=-specnum if ID: input_dir_path = ID else: input_dir_path = dir_path if samp_con: if "4" in samp_con: if "-" not in samp_con: print "option [4] must be in form 4-Z where Z is an integer" return False, "option [4] must be in form 4-Z where Z is an integer" else: Z=samp_con.split("-")[1] samp_con="4" if "7" in samp_con: if "-" not in samp_con: print "option [7] must be in form 7-Z where Z is an integer" return False, "option [7] must be in form 7-Z where Z is an integer" else: Z=samp_con.split("-")[1] samp_con="7" if "6" in samp_con: try: Samps,file_type=pmag.magic_read(os.path.join(input_dir_path, 'er_samples.txt')) except: print "there is no er_samples.txt file in your input directory - you can't use naming convention #6" return False, "there is no er_samples.txt file in your input directory - you can't use naming convention #6" if file_type == 'bad_file': print "there is no er_samples.txt file in your input directory - you can't use naming convention #6" return False, "there is no er_samples.txt file in your input directory - you can't use naming convention #6" if not mag_file: print "mag file is required input" return False, "mag file is required input" output_dir_path = dir_path mag_file = os.path.join(input_dir_path, mag_file) samp_file = output_dir_path+'/'+samp_file site_file = output_dir_path+'/'+site_file meas_file= output_dir_path+'/'+meas_file samplist=[] try: Samps,file_type=pmag.magic_read(samp_file) for samp in Samps: if samp['er_sample_name'] not in samplist: samplist.append(samp['er_sample_name']) except: Samps=[] MagRecs=[] try: f=open(mag_file,'rU') input=f.read() f.close() except Exception as ex: print 'ex', ex print "bad mag file" return False, "bad mag file" firstline,date=1,"" d=input.split('\xcd') for line in d: rec=line.split('\x00') if firstline==1: firstline=0 spec,vol="",1 for c in line[15:23]: if c!='\x00':spec=spec+c # check for bad sample name test=spec.split('.') date="" if len(test)>1: spec=test[0] kk=24 while line[kk]!='\x01' and line[kk]!='\x00': kk+=1 vcc=line[24:kk] el=10 while rec[el].strip()!='':el+=1 date,comments=rec[el+7],[] else: el=9 while rec[el]!='\x01':el+=1 vcc,date,comments=rec[el-3],rec[el+7],[] specname=spec.lower() print 'importing ',specname el+=8 while rec[el].isdigit()==False: comments.append(rec[el]) el+=1 while rec[el]=="":el+=1 az=float(rec[el]) el+=1 while rec[el]=="":el+=1 pl=float(rec[el]) el+=1 while rec[el]=="":el+=1 bed_dip_dir=float(rec[el]) el+=1 while rec[el]=="":el+=1 bed_dip=float(rec[el]) el+=1 while rec[el]=="":el+=1 if rec[el]=='\x01': bed_dip=180.-bed_dip el+=1 while rec[el]=="":el+=1 fold_az=float(rec[el]) el+=1 while rec[el]=="":el+=1 fold_pl=rec[el] el+=1 while rec[el]=="":el+=1 if rec[el]!="" and rec[el]!='\x02' and rec[el]!='\x01': deccorr=float(rec[el]) az+=deccorr bed_dip_dir+=deccorr fold_az+=deccorr if bed_dip_dir>=360:bed_dip_dir=bed_dip_dir-360. if az>=360.:az=az-360. if fold_az>=360.:fold_az=fold_az-360. else: deccorr=0 if specnum!=0: sample=specname[:specnum] else: sample=specname SampRec={} SampRec["er_sample_name"]=sample SampRec["er_location_name"]=location_name SampRec["er_citation_names"]="This study" labaz,labdip=pmag.orient(az,pl,or_con) # convert to labaz, labpl # # parse information common to all orientation methods # SampRec["sample_bed_dip"]='%7.1f'%(bed_dip) SampRec["sample_bed_dip_direction"]='%7.1f'%(bed_dip_dir) SampRec["sample_dip"]='%7.1f'%(labdip) SampRec["sample_azimuth"]='%7.1f'%(labaz) if vcc.strip()!="":vol=float(vcc)*1e-6 # convert to m^3 from cc SampRec["sample_volume"]='%10.3e'%(vol) # SampRec["sample_class"]=sclass SampRec["sample_lithology"]=lithology SampRec["sample_type"]=_type SampRec["sample_declination_correction"]='%7.1f'%(deccorr) methods=gmeths.split(':') if deccorr!="0": if 'SO-MAG' in methods:del methods[methods.index('SO-MAG')] methods.append('SO-CMD-NORTH') meths="" for meth in methods:meths=meths+meth+":" meths=meths[:-1] SampRec["magic_method_codes"]=meths if int(samp_con)<6 or int(samp_con) == 7: site=pmag.parse_site(SampRec["er_sample_name"],samp_con,Z) # parse out the site name SampRec["er_site_name"]=site elif len(Samps)>1: site,location="","" for samp in Samps: if samp["er_sample_name"] == SampRec["er_sample_name"]: site=samp["er_site_name"] location=samp["er_location_name"] break SampRec["er_location_name"]=samp["er_location_name"] SampRec["er_site_name"]=samp["er_site_name"] if sample not in samplist: samplist.append(sample) Samps.append(SampRec) else: MagRec={} MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin MagRec["treatment_ac_field"]='0' MagRec["treatment_dc_field"]='0' MagRec["treatment_dc_field_phi"]='0' MagRec["treatment_dc_field_theta"]='0' meas_type="LT-NO" MagRec["measurement_flag"]='g' MagRec["measurement_standard"]='u' MagRec["measurement_number"]='1' MagRec["er_specimen_name"]=specname MagRec["er_sample_name"]=SampRec['er_sample_name'] MagRec["er_site_name"]=SampRec['er_site_name'] MagRec["er_location_name"]=location_name el,demag=1,'' treat=rec[el] if treat[-1]=='C': demag='T' elif treat!='NRM': demag='AF' el+=1 while rec[el]=="":el+=1 MagRec["measurement_dec"]=rec[el] cdec=float(rec[el]) el+=1 while rec[el]=="":el+=1 MagRec["measurement_inc"]=rec[el] cinc=float(rec[el]) el+=1 while rec[el]=="":el+=1 gdec=rec[el] el+=1 while rec[el]=="":el+=1 ginc=rec[el] el=skip(2,el,rec) # skip bdec,binc # el=skip(4,el,rec) # skip gdec,ginc,bdec,binc # print 'moment emu: ',rec[el] MagRec["measurement_magn_moment"]='%10.3e'% (float(rec[el])*1e-3) # moment in Am^2 (from emu) MagRec["measurement_magn_volume"]='%10.3e'% (float(rec[el])*1e-3/vol) # magnetization in A/m el=skip(2,el,rec) # skip to xsig MagRec["measurement_sd_x"]='%10.3e'% (float(rec[el])*1e-3) # convert from emu el=skip(3,el,rec) # skip to ysig MagRec["measurement_sd_y"]='%10.3e'% (float(rec[el])*1e-3) # convert from emu el=skip(3,el,rec) # skip to zsig MagRec["measurement_sd_z"]='%10.3e'% (float(rec[el])*1e-3) # convert from emu el+=1 # skip to positions MagRec["measurement_positions"]=rec[el] # el=skip(5,el,rec) # skip to date # mm=str(months.index(date[0])) # if len(mm)==1: # mm='0'+str(mm) # else: # mm=str(mm) # dstring=date[2]+':'+mm+':'+date[1]+":"+date[3] # MagRec['measurement_date']=dstring MagRec["magic_instrument_codes"]=inst MagRec["er_analyst_mail_names"]="" MagRec["er_citation_names"]="This study" MagRec["magic_method_codes"]=meas_type if demag=="AF": MagRec["treatment_ac_field"]='%8.3e' %(float(treat[:-2])*1e-3) # peak field in tesla meas_type="LT-AF-Z" MagRec["treatment_dc_field"]='0' elif demag=="T": MagRec["treatment_temp"]='%8.3e' % (float(treat[:-1])+273.) # temp in kelvin meas_type="LT-T-Z" MagRec['magic_method_codes']=meas_type MagRecs.append(MagRec) MagOuts=pmag.measurements_methods(MagRecs,noave) MagOuts, keylist = pmag.fillkeys(MagOuts) pmag.magic_write(meas_file,MagOuts,'magic_measurements') print "Measurements put in ",meas_file SampsOut,sampkeys=pmag.fillkeys(Samps) pmag.magic_write(samp_file,SampsOut,"er_samples") Sites=[] for samp in Samps: SiteRec={} SiteRec['er_site_name']=samp['er_site_name'] SiteRec['er_location_name']=samp['er_location_name'] SiteRec['site_definition']='s' SiteRec['er_citation_names']='This study' if 'sample_class' in samp.keys():SiteRec['site_class']=samp['sample_class'] if 'sample_lithology' in samp.keys():SiteRec['site_lithology']=samp['sample_lithology'] if 'sample_type' in samp.keys():SiteRec['site_lithology']=samp['sample_lithology'] if 'sample_lat' in samp.keys(): SiteRec['site_lat']=samp['sample_lat'] else: SiteRec['site_lat']="-999" if 'sample_lon' in samp.keys(): SiteRec['site_lon']=samp['sample_lon'] else: SiteRec['site_lon']="-999" if 'sample_height' in samp.keys():SiteRec['site_height']=samp['sample_height'] Sites.append(SiteRec) pmag.magic_write(site_file,Sites,'er_sites') return True, meas_file
def main(): """ NAME sites_locations.py DESCRIPTION reads in er_sites.txt file and finds all locations and bounds of locations outputs er_locations.txt file SYNTAX sites_locations.py [command line options] OPTIONS -h prints help message and quits -f: specimen input er_sites format file, default is "er_sites.txt" -F: locations table: default is "er_locations.txt" """ # set defaults site_file = "er_sites.txt" loc_file = "er_locations.txt" Names, user = [], "unknown" Done = [] version_num = pmag.get_version() args = sys.argv dir_path = '.' # get command line stuff if '-WD' in args: ind = args.index("-WD") dir_path = args[ind + 1] if "-h" in args: print(main.__doc__) sys.exit() if '-f' in args: ind = args.index("-f") site_file = args[ind + 1] if '-F' in args: ind = args.index("-F") loc_file = args[ind + 1] # site_file = dir_path + '/' + site_file loc_file = dir_path + '/' + loc_file Sites, file_type = pmag.magic_read(site_file) if file_type != 'er_sites': print(file_type) print(file_type, "This is not a valid er_sites file ") sys.exit() # read in site data # LocNames, Locations = [], [] for site in Sites: if site['er_location_name'] not in LocNames: # new location name LocNames.append(site['er_location_name']) sites_locs = pmag.get_dictitem(Sites, 'er_location_name', site['er_location_name'], 'T') # get all sites for this loc lats = pmag.get_dictkey(sites_locs, 'site_lat', 'f') # get all the latitudes as floats lons = pmag.get_dictkey(sites_locs, 'site_lon', 'f') # get all the longitudes as floats LocRec = { 'er_citation_names': 'This study', 'er_location_name': site['er_location_name'], 'location_type': '' } LocRec['location_begin_lat'] = str(min(lats)) LocRec['location_end_lat'] = str(max(lats)) LocRec['location_begin_lon'] = str(min(lons)) LocRec['location_end_lon'] = str(max(lons)) Locations.append(LocRec) if len(Locations) > 0: pmag.magic_write(loc_file, Locations, "er_locations") print("Locations written to: ", loc_file)
def main(): """ NAME chi_magic.py DESCRIPTION plots magnetic susceptibility as a function of frequency and temperature and AC field SYNTAX chi_magic.py [command line options] OPTIONS -h prints help message and quits -i allows interactive setting of FILE and temperature step -f FILE, specify magic_measurements format file -T IND, specify temperature step to plot -e EXP, specify experiment name to plot -fmt [svg,jpg,png,pdf] set figure format [default is svg] -sav save figure and quit DEFAULTS FILE: magic_measurements.txt IND: first SPEC: step through one by one """ cont,FTinit,BTinit,k="",0,0,0 meas_file="magic_measurements.txt" spec="" Tind,cont=0,"" EXP="" fmt='svg' # default image type for saving plot=0 if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-i' in sys.argv: file=input("Input magic_measurements file name? [magic_measurements.txt] ") if file!="":meas_file=file if '-e' in sys.argv: ind=sys.argv.index('-e') EXP=sys.argv[ind+1] if '-f' in sys.argv: ind=sys.argv.index('-f') meas_file=sys.argv[ind+1] if '-T' in sys.argv: ind=sys.argv.index('-T') Tind=int(sys.argv[ind+1]) if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-sav' in sys.argv:plot=1 # meas_data,file_type=pmag.magic_read(meas_file) # # get list of unique experiment names # # initialize some variables (a continuation flag, plot initialization flags and the experiment counter experiment_names=[] for rec in meas_data: if rec['magic_experiment_name'] not in experiment_names:experiment_names.append(rec['magic_experiment_name']) # # hunt through by experiment name if EXP!="": try: k=experiment_names.index(EXP) except: print("Bad experiment name") sys.exit() while k < len(experiment_names): e=experiment_names[k] if EXP=="":print(e, k+1 , 'out of ',len(experiment_names)) # # initialize lists of data, susceptibility, temperature, frequency and field X,T,F,B=[],[],[],[] for rec in meas_data: methcodes=rec['magic_method_codes'] meths=methcodes.strip().split(':') if rec['magic_experiment_name']==e and "LP-X" in meths: # looking for chi measurement if 'measurement_temp' not in list(rec.keys()):rec['measurement_temp']='300' # set defaults if 'measurement_freq' not in list(rec.keys()):rec['measurement_freq']='0' # set defaults if 'measurement_lab_field_ac' not in list(rec.keys()):rec['measurement_lab_field_ac']='0' # set default X.append(float(rec['measurement_x'])) T.append(float(rec['measurement_temp'])) F.append(float(rec['measurement_freq'])) B.append(float(rec['measurement_lab_field_ac'])) # # get unique list of Ts,Fs, and Bs # Ts,Fs,Bs=[],[],[] for k in range(len(X)): # hunt through all the measurements if T[k] not in Ts:Ts.append(T[k]) # append if not in list if F[k] not in Fs:Fs.append(F[k]) if B[k] not in Bs:Bs.append(B[k]) Ts.sort() # sort list of temperatures, frequencies and fields Fs.sort() Bs.sort() if '-x' in sys.argv: k=len(experiment_names)+1 # just plot the one else: k+=1 # increment experiment number # # plot chi versus T and F holding B constant # plotnum=1 # initialize plot number to 1 if len(X)>2: # if there are any data to plot, continue b=Bs[-1] # keeping field constant and at maximum XTF=[] # initialize list of chi versus Temp and freq for f in Fs: # step through frequencies sequentially XT=[] # initialize list of chi versus temp for kk in range(len(X)): # hunt through all the data if F[kk]==f and B[kk]==b: # select data with given freq and field XT.append([X[kk],T[kk]]) # append to list XTF.append(XT) # append list to list of frequencies if len(XT)>1: # if there are any temperature dependent data pmagplotlib.plot_init(plotnum,5,5) # initialize plot pmagplotlib.plotXTF(plotnum,XTF,Fs,e,b) # call the plotting function if plot==0:pmagplotlib.drawFIGS({'fig':plotnum}) #make it visible plotnum+=1 # increment plot number f=Fs[0] # set frequency to minimum XTB=[] # initialize list if chi versus Temp and field for b in Bs: # step through field values XT=[] # initial chi versus temp list for this field for kk in range(len(X)): # hunt through all the data if F[kk]==f and B[kk]==b: # select data with given freq and field XT.append([X[kk],T[kk]]) # append to list XTB.append(XT) if len(XT)>1: # if there are any temperature dependent data pmagplotlib.plot_init(plotnum,5,5) # set up plot pmagplotlib.plotXTB(plotnum,XTB,Bs,e,f) # call the plotting function if plot==0:pmagplotlib.drawFIGS({'fig':plotnum}) plotnum+=1 # increment plot number if '-i' in sys.argv: for ind in range(len(Ts)): # print list of temperatures available print(ind,int(Ts[ind])) cont=input("Enter index of desired temperature step, s[a]ve plots, [return] to quit ") if cont=='a': files={} PLTS={} for p in range(1,plotnum): key=str(p) files[key]=e+'_'+key+'.'+fmt PLTS[key]=key pmagplotlib.saveP(PLTS,files) cont=input("Enter index of desired temperature step, s[a]ve plots, [return] to quit ") if cont=="":cont='q' while cont!="q": if '-i' in sys.argv:Tind=int(cont) # set temperature index b=Bs[-1] # set field to max available XF=[] # initial chi versus frequency list for kk in range(len(X)): # hunt through the data if T[kk]==Ts[Tind] and B[kk]==b: # if temperature and field match, XF.append([X[kk],F[kk]]) # append the data if len(XF)>1: # if there are any data to plot if FTinit==0: # if not already initialized, initialize plot #print 'initializing ',plotnum pmagplotlib.plot_init(plotnum,5,5) FTinit=1 XFplot=plotnum plotnum+=1 # increment plotnum pmagplotlib.plotXFT(XFplot,XF,Ts[Tind],e,b) if plot==0:pmagplotlib.drawFIGS({'fig':plotnum}) else: print('\n *** Skipping susceptibitily-frequency plot as a function of temperature *** \n') f=Fs[0] # set frequency to minimum available XB=[] # initialize chi versus field list for kk in range(len(X)): # hunt through the data if T[kk]==Ts[Tind] and F[kk]==f: # if temperature and field match those desired XB.append([X[kk],B[kk]]) # append the data to list if len(XB)>4: # if there are any data if BTinit==0: # if plot not already initialized pmagplotlib.plot_init(plotnum,5,5) # do it BTinit=1 pmagplotlib.plotXBT(plotnum,XB,Ts[Tind],e,f) # and call plotting function if plot==0:pmagplotlib.drawFIGS({'fig':plotnum}) else: print('Skipping susceptibitily - AC field plot as a function of temperature') files={} PLTS={} for p in range(1,plotnum): key=str(p) files[key]=e+'_'+key+'.'+fmt PLTS[key]=p if '-i' in sys.argv: for ind in range(len(Ts)): # just in case you forgot, print out a new list of temperatures print(ind,int(Ts[ind])) cont=input("Enter index of next temperature step, s[a]ve plots, [return] to quit ") # ask for new temp if cont=="":sys.exit() if cont=='a': pmagplotlib.saveP(PLTS,files) cont=input("Enter index of desired temperature step, s[a]ve plots, [return] to quit ") if cont=="":sys.exit() elif plot==0: ans=input("enter s[a]ve to save files, [return] to quit ") if ans=='a': pmagplotlib.saveP(PLTS,files) sys.exit() else: sys.exit() else: pmagplotlib.saveP(PLTS,files) sys.exit()
def main(): """ NAME make_magic_plots.py DESCRIPTION inspects magic directory for available plots. SYNTAX make_magic_plots.py [command line options] INPUT magic files OPTIONS -h prints help message and quits -f FILE specifies input file name -fmt [png,eps,svg,jpg,pdf] specify format, default is png """ dirlist=['./'] dir_path=os.getcwd() names=os.listdir(dir_path) for n in names: if 'Location' in n: dirlist.append(n) if '-fmt' in sys.argv: ind=sys.argv.index("-fmt") fmt=sys.argv[ind+1] else: fmt='png' if '-f' in sys.argv: ind=sys.argv.index("-f") filelist=[sys.argv[ind+1]] else: filelist=os.listdir(dir_path) if '-h' in sys.argv: print main.__doc__ sys.exit() for loc in dirlist: print 'working on: ',loc os.chdir(loc) # change working directories to each location crd='s' if 'er_samples.txt' in filelist: # find coordinate systems samps,file_type=pmag.magic_read('er_samples.txt') # read in data Srecs=pmag.get_dictitem(samps,'sample_azimuth','','F')# get all none blank sample orientations if len(Srecs)>0: crd='g' if 'magic_measurements.txt' in filelist: # start with measurement data print 'working on measurements data' data,file_type=pmag.magic_read('magic_measurements.txt') # read in data if loc == './': data=pmag.get_dictitem(data,'er_location_name','','T') # get all the blank location names from data file # looking for zeq_magic possibilities AFZrecs=pmag.get_dictitem(data,'magic_method_codes','LT-AF-Z','has')# get all none blank method codes TZrecs=pmag.get_dictitem(data,'magic_method_codes','LT-T-Z','has')# get all none blank method codes MZrecs=pmag.get_dictitem(data,'magic_method_codes','LT-M-Z','has')# get all none blank method codes Drecs=pmag.get_dictitem(data,'measurement_dec','','F') # get all dec measurements Irecs=pmag.get_dictitem(data,'measurement_inc','','F') # get all dec measurements Mkeys=['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass'] for key in Mkeys: Mrecs=pmag.get_dictitem(data,key,'','F') # get intensity data if len(Mrecs)>0:break if len(AFZrecs)>0 or len(TZrecs)>0 or len(MZrecs)>0 and len(Drecs)>0 and len(Irecs)>0 and len(Mrecs)>0: # potential for stepwise demag curves print 'zeq_magic.py -fsp pmag_specimens.txt -sav -fmt '+fmt+' -crd '+crd os.system('zeq_magic.py -sav -fmt '+fmt+' -crd '+crd ) # looking for thellier_magic possibilities if len(pmag.get_dictitem(data,'magic_method_codes','LP-PI-TRM','has'))>0: print 'thellier_magic.py -fsp pmag_specimens.txt -sav -fmt '+fmt os.system('thellier_magic.py -sav -fmt '+fmt) # looking for hysteresis possibilities if len(pmag.get_dictitem(data,'magic_method_codes','LP-HYS','has'))>0: # find hyst experiments print 'quick_hyst.py -sav -fmt '+fmt os.system('quick_hyst.py -sav -fmt '+fmt) if 'pmag_results.txt' in filelist: # start with measurement data data,file_type=pmag.magic_read('pmag_results.txt') # read in data print 'number of datapoints: ',len(data) if loc == './': data=pmag.get_dictitem(data,'er_location_names',':','has') # get all the concatenated location names from data file print 'number of datapoints: ',len(data) ,loc print 'working on pmag_results directions' SiteDIs=pmag.get_dictitem(data,'average_dec',"",'F') # find decs print 'number of directions: ',len(SiteDIs) SiteDIs=pmag.get_dictitem(SiteDIs,'average_inc',"",'F') # find decs and incs print 'number of directions: ',len(SiteDIs) SiteDIs=pmag.get_dictitem(SiteDIs,'data_type','i','has') # only individual results - not poles print 'number of directions: ',len(SiteDIs) SiteDIs_t=pmag.get_dictitem(SiteDIs,'tilt_correction','100','T')# tilt corrected coordinates print 'number of directions: ',len(SiteDIs) if len(SiteDIs_t)>0: print 'eqarea_magic.py -sav -crd t -fmt '+fmt os.system('eqarea_magic.py -sav -crd t -fmt '+fmt) elif len(SiteDIs)>0 and 'tilt_correction' not in SiteDIs[0].keys(): print 'eqarea_magic.py -sav -fmt '+fmt os.system('eqarea_magic.py -sav -fmt '+fmt) else: SiteDIs_g=pmag.get_dictitem(SiteDIs,'tilt_correction','0','T')# geographic coordinates if len(SiteDIs_g)>0: print 'eqarea_magic.py -sav -crd g -fmt '+fmt os.system('eqarea_magic.py -sav -crd g -fmt '+fmt) else: SiteDIs_s=pmag.get_dictitem(SiteDIs,'tilt_correction','-1','T')# sample coordinates if len(SiteDIs_s)>0: print 'eqarea_magic.py -sav -crd s -fmt '+fmt os.system('eqarea_magic.py -sav -crd s -fmt '+fmt) else: SiteDIs_x=pmag.get_dictitem(SiteDIs,'tilt_correction','','T')# no coordinates if len(SiteDIs_x)>0: print 'eqarea_magic.py -sav -fmt '+fmt os.system('eqarea_magic.py -sav -fmt '+fmt) print 'working on pmag_results VGP map' VGPs=pmag.get_dictitem(SiteDIs,'vgp_lat',"",'F') # are there any VGPs? if len(VGPs)>0: # YES! os.system('vgpmap_magic.py -prj moll -res c -sym ro 5 -sav -fmt png') print 'working on pmag_results intensities' os.system('magic_select.py -f pmag_results.txt -key data_type i T -F tmp.txt') os.system('magic_select.py -f tmp.txt -key average_int 0. has -F tmp1.txt') os.system("grab_magic_key.py -f tmp1.txt -key average_int | awk '{print $1*1e6}' >tmp2.txt") data,file_type=pmag.magic_read('tmp1.txt') # read in data locations=pmag.get_dictkey(data,'er_location_names',"") histfile='LO:_'+locations[0]+'_intensities_histogram:_.'+fmt os.system("histplot.py -b 1 -xlab 'Intensity (uT)' -sav -f tmp2.txt -F " +histfile) print "histplot.py -b 1 -xlab 'Intensity (uT)' -sav -f tmp2.txt -F " +histfile os.system('rm tmp*.txt') if 'rmag_hysteresis.txt' in filelist: # start with measurement data print 'working on rmag_hysteresis' data,file_type=pmag.magic_read('rmag_hysteresis.txt') # read in data if loc == './': data=pmag.get_dictitem(data,'er_location_name','','T') # get all the blank location names from data file hdata=pmag.get_dictitem(data,'hysteresis_bcr','','F') hdata=pmag.get_dictitem(hdata,'hysteresis_mr_moment','','F') hdata=pmag.get_dictitem(hdata,'hysteresis_ms_moment','','F') hdata=pmag.get_dictitem(hdata,'hysteresis_bc','','F') # there are data for a dayplot if len(hdata)>0: print 'dayplot_magic.py -sav -fmt '+fmt os.system('dayplot_magic.py -sav -fmt '+fmt) #if 'er_sites.txt' in filelist: # start with measurement data # print 'working on er_sites' #os.system('basemap_magic.py -sav -fmt '+fmt) if 'rmag_anisotropy.txt' in filelist: # do anisotropy plots if possible print 'working on rmag_anisotropy' data,file_type=pmag.magic_read('rmag_anisotropy.txt') # read in data if loc == './': data=pmag.get_dictitem(data,'er_location_name','','T') # get all the blank location names from data file sdata=pmag.get_dictitem(data,'anisotropy_tilt_correction','-1','T') # get specimen coordinates gdata=pmag.get_dictitem(data,'anisotropy_tilt_correction','0','T') # get specimen coordinates tdata=pmag.get_dictitem(data,'anisotropy_tilt_correction','100','T') # get specimen coordinates if len(sdata)>3: print 'aniso_magic.py -x -B -crd s -sav -fmt '+fmt os.system('aniso_magic.py -x -B -crd s -sav -fmt '+fmt) if len(gdata)>3: os.system('aniso_magic.py -x -B -crd g -sav -fmt '+fmt) if len(tdata)>3: os.system('aniso_magic.py -x -B -crd t -sav -fmt '+fmt) if loc!='./':os.chdir('..') # change working directories to each location
def main(): """ NAME odp_dcs_magic.py DESCRIPTION converts ODP discrete sample format files to magic_measurements format files SYNTAX odp_dsc_magic.py [command line options] OPTIONS -h: prints the help message and quits. -F FILE: specify output measurements file, default is magic_measurements.txt -Fsp FILE: specify output er_specimens.txt file, default is er_specimens.txt -Fsa FILE: specify output er_samples.txt file for appending, default is er_samples.txt -Fsi FILE: specify output er_sites.txt file, default is er_sites.txt -dc B PHI THETA: dc lab field (in micro tesla) and phi,theta, default is none NB: use PHI, THETA = -1 -1 to signal that it changes, i.e. in anisotropy experiment -ac B : peak AF field (in mT) for ARM acquisition, default is none -A : don't average replicate measurements INPUT Put data from separate experiments (all AF, thermal, thellier, trm aquisition, Shaw, etc.) in separate directory """ # # version_num = pmag.get_version() meas_file = 'magic_measurements.txt' spec_file = 'er_specimens.txt' samp_file = 'er_samples.txt' site_file = 'er_sites.txt' ErSpecs, ErSamps, ErSites, ErLocs, ErCits = [], [], [], [], [] MagRecs = [] citation = "This study" dir_path, demag = '.', 'NRM' args = sys.argv noave = 0 if '-WD' in args: ind = args.index("-WD") dir_path = args[ind + 1] if "-h" in args: print(main.__doc__) sys.exit() if "-A" in args: noave = 1 if '-F' in args: ind = args.index("-F") meas_file = args[ind + 1] if '-Fsp' in args: ind = args.index("-Fsp") spec_file = args[ind + 1] if '-Fsa' in args: ind = args.index("-Fsa") samp_file = dir_path + '/' + args[ind + 1] ErSamps, file_type = pmag.magic_read(samp_file) else: samp_file = dir_path + '/' + samp_file if '-LP' in args: ind = args.index("-LP") codelist = args[ind + 1] codes = codelist.split(':') if "AF" in codes: demag = 'AF' if '-dc' not in args: methcode = "LT-AF-Z" if '-dc' in args: methcode = "LT-AF-I" if "T" in codes: demag = "T" if '-dc' not in args: methcode = "LT-T-Z" if '-dc' in args: methcode = "LT-T-I" if "I" in codes: methcode = "LP-IRM" if "S" in codes: demag = "S" methcode = "LP-PI-TRM:LP-PI-ALT-AFARM" trm_labfield = labfield ans = input("DC lab field for ARM step: [50uT] ") if ans == "": arm_labfield = 50e-6 else: arm_labfield = float(ans) * 1e-6 ans = input("temperature for total trm step: [600 C] ") if ans == "": trm_peakT = 600 + 273 # convert to kelvin else: trm_peakT = float(ans) + 273 # convert to kelvin if "G" in codes: methcode = "LT-AF-G" if "D" in codes: methcode = "LT-AF-D" if "TRM" in codes: demag = "T" trm = 1 if demag == "T" and "ANI" in codes: methcode = "LP-AN-TRM" if demag == "AF" and "ANI" in codes: methcode = "LP-AN-ARM" if labfield == 0: labfield = 50e-6 if peakfield == 0: peakfield = .180 spec_file = dir_path + '/' + spec_file site_file = dir_path + '/' + site_file meas_file = dir_path + '/' + meas_file filelist = os.listdir(dir_path) # read in list of files to import specimens, samples, sites = [], [], [] MagRecs, SpecRecs, SampRecs = [], [], [] for samp in ErSamps: if samp['er_sample_name'] not in samples: samples.append(samp['er_sample_name']) SampRecs.append(samp) for file in filelist: # parse each file if file[-3:].lower() == 'dsc': print('processing: ', file) MagRec, SpecRec, SampRec = {}, {}, {} treatment_type, treatment_value, user = "", "", "" inst = "ODP-SRM" input = open(dir_path + '/' + file, 'r').readlines() IDs = file.split('_') # splits on underscores pieces = IDs[0].split('-') expedition = pieces[0] location = pieces[1] if file[0] != '_': while len(pieces[2]) < 4: pieces[2] = '0' + pieces[2] # pad core to be 3 characters specimen = "" else: specimen = "test" for piece in pieces: specimen = specimen + piece + '-' specimen = specimen[:-1] alt_spec = IDs[ 1] # alternate specimen is second field in field name # set up specimen record for Er_specimens table SpecRec['er_expedition_name'] = expedition SpecRec['er_location_name'] = location SpecRec['er_site_name'] = specimen SpecRec['er_sample_name'] = specimen SpecRec['er_citation_names'] = citation for key in list(SpecRec.keys()): SampRec[key] = SpecRec[key] SampRec['sample_azimuth'] = '0' SampRec['sample_dip'] = '0' SampRec['magic_method_codes'] = 'FS-C-DRILL-IODP:SP-SS-C:SO-V' SpecRec['er_specimen_name'] = specimen SampRec['er_specimen_names'] = specimen for key in list(SpecRec.keys()): MagRec[key] = SpecRec[key] # set up measurement record - default is NRM MagRec['er_analyst_mail_names'] = user MagRec['magic_method_codes'] = 'LT-NO' MagRec['magic_software_packages'] = version_num MagRec["treatment_temp"] = '%8.3e' % (273) # room temp in kelvin MagRec["measurement_temp"] = '%8.3e' % (273) # room temp in kelvin MagRec["treatment_ac_field"] = 0. MagRec["treatment_dc_field"] = '0' MagRec["treatment_dc_field_phi"] = '0' MagRec["treatment_dc_field_theta"] = '0' MagRec["measurement_flag"] = 'g' # assume all data are "good" MagRec["measurement_standard"] = 'u' # assume all data are "good" MagRec["measurement_csd"] = '' # set csd to blank SpecRec['er_specimen_alternatives'] = alt_spec vol = 7e-6 # assume 7 cc samples datestamp = input[1].split() # date time is second line of file mmddyy = datestamp[0].split('/') # break into month day year date = mmddyy[2] + ':' + mmddyy[0] + ":" + mmddyy[ 1] + ':' + datestamp[1] MagRec["measurement_date"] = date for k in range(len(input)): fields = input[k].split("=") if 'treatment_type' in fields[0]: if "Alternating Frequency Demagnetization" in fields[1]: MagRec['magic_method_codes'] = 'LT-AF-Z' inst = inst + ':ODP-DTECH' # measured on shipboard AF DTECH D2000 treatment_type = "AF" if "Anhysteretic Remanent Magnetization" in fields[1]: MagRec['magic_method_codes'] = 'LT-AF-I' inst = inst + ':ODP-DTECH' # measured on shipboard AF DTECH D2000 treatment_type = "ARM" if "Isothermal Remanent Magnetization" in fields[1]: MagRec['magic_method_codes'] = 'LT-IRM' inst = inst + ':ODP-IMP' # measured on shipboard ASC IMPULSE magnetizer treatment_type = "IRM" if "treatment_value" in fields[0]: values = fields[1].split(',') value = values[0] if value != " \n": if treatment_type == "AF": treatment_value = float(value) * 1e-3 MagRec[ "treatment_ac_field"] = treatment_value # AF demag in treat mT => T elif treatment_type == "IRM": treatment_value = float(value) * 1e-3 MagRec["treatment_dc_field"] = '%8.3e' % ( treatment_value) # IRM treat mT => T if treatment_type == "ARM": treatment_value = float(value) * 1e-3 dc_value = float(values[1]) * 1e-3 MagRec[ "treatment_ac_field"] = treatment_value # AF demag in treat mT => T MagRec["treatment_dc_field"] = '%8.3e' % ( dc_value) # DC mT => T if 'user' in fields[0]: user = fields[-1] MagRec["er_analyst_mail_names"] = user if 'sample_orientation' in fields[0]: MagRec["measurement_description"] = fields[-1] MagRec[ "measurement_standard"] = 'u' # assume all data are "good" if 'sample_area' in fields[0]: vol = float( fields[1] ) * 1e-6 # takes volume (cc) and converts to m^3 if 'run_number' in fields[0]: MagRec['external_database_ids'] = fields[ 1] # run number is the LIMS measurement number MagRec['external_database_names'] = 'LIMS' if input[k][0:7] == '<MULTI>': rec = input[k + 1].split(',') # list of data for item in rec: items = item.split('=') if items[0].strip( ) == 'demag_level' and treatment_value == "": treat = float(items[1]) if treat != 0: MagRec['magic_method_codes'] = 'LT-AF-Z' inst = inst + ':ODP-SRM-AF' MagRec[ "treatment_ac_field"] = treat * 1e-3 # AF demag in treat mT => T if items[0].strip() == 'inclination_w_tray_w_bkgrd': MagRec['measurement_inc'] = items[1] if items[0].strip() == 'declination_w_tray_w_bkgrd': MagRec['measurement_dec'] = items[1] if items[0].strip() == 'intensity_w_tray_w_bkgrd': MagRec['measurement_magn_moment'] = '%8.3e' % ( float(items[1]) * vol ) # convert intensity from A/m to Am^2 using vol if items[0].strip() == 'x_stdev': MagRec['measurement_x_sd'] = items[1] if items[0].strip() == 'y_stdev': MagRec['measurement_y_sd'] = items[1] if items[0].strip() == 'z_stdev': MagRec['measurement_sd_z'] = items[1] MagRec['magic_instrument_codes'] = inst MagRec['measurement_number'] = '1' MagRec['measurement_positions'] = '' MagRecs.append(MagRec) if specimen not in specimens: specimens.append(specimen) SpecRecs.append(SpecRec) if MagRec['er_sample_name'] not in samples: samples.append(MagRec['er_sample_name']) SampRecs.append(SampRec) MagOuts = pmag.sort_diclist(MagRecs, 'treatment_ac_field') for MagRec in MagOuts: MagRec["treatment_ac_field"] = '%8.3e' % (MagRec["treatment_ac_field"] ) # convert to string pmag.magic_write(spec_file, SpecRecs, 'er_specimens') if len(SampRecs) > 0: SampOut, keys = pmag.fillkeys(SampRecs) pmag.magic_write(samp_file, SampOut, 'er_samples') print('samples stored in ', samp_file) pmag.magic_write(samp_file, SampRecs, 'er_samples') print('specimens stored in ', spec_file) Fixed = pmag.measurements_methods(MagOuts, noave) pmag.magic_write(meas_file, Fixed, 'magic_measurements') print('data stored in ', meas_file)
def main(): """ NAME lowrie_magic.py DESCRIPTION plots intensity decay curves for Lowrie experiments SYNTAX lowrie_magic.py -h [command line options] INPUT takes magic_measurements formatted input files OPTIONS -h prints help message and quits -f FILE: specify input file, default is magic_measurements.txt -N do not normalize by maximum magnetization -fmt [svg, pdf, eps, png] specify fmt, default is svg -sav saves plots and quits """ fmt, plot = 'svg', 0 FIG = {} # plot dictionary FIG['lowrie'] = 1 # demag is figure 1 pmagplotlib.plot_init(FIG['lowrie'], 6, 6) norm = 1 # default is to normalize by maximum axis in_file, dir_path = 'magic_measurements.txt', '.' if len(sys.argv) > 1: if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path = sys.argv[ind + 1] if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-N' in sys.argv: norm = 0 # don't normalize if '-sav' in sys.argv: plot = 1 # don't normalize if '-fmt' in sys.argv: # sets input filename ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] if '-f' in sys.argv: # sets input filename ind = sys.argv.index("-f") in_file = sys.argv[ind + 1] else: print(main.__doc__) print('you must supply a file name') sys.exit() in_file = dir_path + '/' + in_file print(in_file) PmagRecs, file_type = pmag.magic_read(in_file) if file_type != "magic_measurements": print('bad input file') sys.exit() PmagRecs = pmag.get_dictitem(PmagRecs, 'magic_method_codes', 'LP-IRM-3D', 'has') # get all 3D IRM records if len(PmagRecs) == 0: print('no records found') sys.exit() specs = pmag.get_dictkey(PmagRecs, 'er_specimen_name', '') sids = [] for spec in specs: if spec not in sids: sids.append(spec) # get list of unique specimen names for spc in sids: # step through the specimen names print(spc) specdata = pmag.get_dictitem(PmagRecs, 'er_specimen_name', spc, 'T') # get all this one's data DIMs, Temps = [], [] for dat in specdata: # step through the data DIMs.append([ float(dat['measurement_dec']), float(dat['measurement_inc']), float(dat['measurement_magn_moment']) ]) Temps.append(float(dat['treatment_temp']) - 273.) carts = pmag.dir2cart(DIMs).transpose() if norm == 1: # want to normalize nrm = (DIMs[0][2]) # normalize by NRM ylab = "M/M_o" else: nrm = 1. # don't normalize ylab = "Magnetic moment (Am^2)" xlab = "Temperature (C)" pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[0]), nrm), sym='r-') pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[0]), nrm), sym='ro') # X direction pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[1]), nrm), sym='c-') pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[1]), nrm), sym='cs') # Y direction pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[2]), nrm), sym='k-') pmagplotlib.plotXY(FIG['lowrie'], Temps, old_div(abs(carts[2]), nrm), sym='k^', title=spc, xlab=xlab, ylab=ylab) # Z direction files = {'lowrie': 'lowrie:_' + spc + '_.' + fmt} if plot == 0: pmagplotlib.drawFIGS(FIG) ans = input('S[a]ve figure? [q]uit, <return> to continue ') if ans == 'a': pmagplotlib.saveP(FIG, files) elif ans == 'q': sys.exit() else: pmagplotlib.saveP(FIG, files) pmagplotlib.clearFIG(FIG['lowrie'])
def main(): """ NAME hysteresis_magic.py DESCRIPTION calculates hystereis parameters and saves them in 3.0 specimen format file makes plots if option selected SYNTAX hysteresis_magic.py [command line options] OPTIONS -h prints help message and quits -f: specify input file, default is agm_measurements.txt -F: specify specimens.txt output file -P: do not make the plots -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg] """ args=sys.argv PLT=1 plots=0 fmt=pmag.get_named_arg_from_sys('-fmt','svg') dir_path=pmag.get_named_arg_from_sys('-WD','.') dir_path=os.path.realpath(dir_path) verbose=pmagplotlib.verbose version_num=pmag.get_version() user=pmag.get_named_arg_from_sys('-usr','') if "-h" in args: print(main.__doc__) sys.exit() meas_file=pmag.get_named_arg_from_sys('-f','agm_measurements.txt') spec_file=pmag.get_named_arg_from_sys('-F','specimens.txt') if '-P' in args: PLT=0 irm_init,imag_init=-1,-1 if '-sav' in args: verbose=0 plots=1 pltspec=pmag.get_named_arg_from_sys('-spc',0) if pltspec: #pltspec= args[ind+1] verbose=0 plots=1 spec_file=dir_path+'/'+spec_file meas_file=dir_path+'/'+meas_file SpecRecs=[] # # meas_data,file_type=pmag.magic_read(meas_file) if file_type!='measurements': print(main.__doc__) print('bad file') sys.exit() # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs,RemRecs=[],[] HDD={} if verbose: if verbose and PLT:print("Plots may be on top of each other - use mouse to place ") if PLT: HDD['hyst'],HDD['deltaM'],HDD['DdeltaM']=1,2,3 pmagplotlib.plot_init(HDD['DdeltaM'],5,5) pmagplotlib.plot_init(HDD['deltaM'],5,5) pmagplotlib.plot_init(HDD['hyst'],5,5) imag_init=0 irm_init=0 else: HDD['hyst'],HDD['deltaM'],HDD['DdeltaM'],HDD['irm'],HDD['imag']=0,0,0,0,0 # if spec_file: prior_data,file_type=pmag.magic_read(spec_file) # # get list of unique experiment names and specimen names # experiment_names,sids=[],[] hys_data=pmag.get_dictitem(meas_data,'method_codes','LP-HYS','has') dcd_data=pmag.get_dictitem(meas_data,'method_codes','LP-IRM-DCD','has') imag_data=pmag.get_dictitem(meas_data,'method_codes','LP-IMAG','has') for rec in hys_data: if rec['experiment'] not in experiment_names:experiment_names.append(rec['experiment']) if rec['specimen'] not in sids:sids.append(rec['specimen']) # k=0 if pltspec: k=sids.index(pltspec) print(sids[k]) while k < len(sids): specimen=sids[k] HystRec={'specimen':specimen,'experiment':""} # initialize a new specimen hysteresis record if verbose and PLT:print(specimen, k+1 , 'out of ',len(sids)) # # B,M,Bdcd,Mdcd=[],[],[],[] #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data Bimag,Mimag=[],[] #Bimag,Mimag for initial magnetization curves spec_data=pmag.get_dictitem(hys_data,'specimen',specimen,'T') # fish out all the LP-HYS data for this specimen if len(spec_data)>0: meths=spec_data[0]['method_codes'].split(':') e=spec_data[0]['experiment'] HystRec['experiment']=spec_data[0]['experiment'] for rec in spec_data: B.append(float(rec['meas_field_dc'])) M.append(float(rec['magn_moment'])) spec_data=pmag.get_dictitem(dcd_data,'specimen',specimen,'T') # fish out all the data for this specimen if len(spec_data)>0: HystRec['experiment']=HystRec['experiment']+':'+spec_data[0]['experiment'] irm_exp=spec_data[0]['experiment'] for rec in spec_data: Bdcd.append(float(rec['treat_dc_field'])) Mdcd.append(float(rec['magn_moment'])) spec_data=pmag.get_dictitem(imag_data,'specimen',specimen,'T') # fish out all the data for this specimen if len(spec_data)>0: imag_exp=spec_data[0]['experiment'] for rec in spec_data: Bimag.append(float(rec['meas_field_dc'])) Mimag.append(float(rec['magn_moment'])) # # now plot the hysteresis curve # if len(B)>0: hmeths=[] for meth in meths: hmeths.append(meth) hpars=pmagplotlib.plotHDD(HDD,B,M,e) if verbose and PLT:pmagplotlib.drawFIGS(HDD) # if verbose:pmagplotlib.plotHPARS(HDD,hpars,'bs') HystRec['hyst_mr_moment']=hpars['hysteresis_mr_moment'] HystRec['hyst_ms_moment']=hpars['hysteresis_ms_moment'] HystRec['hyst_bc']=hpars['hysteresis_bc'] HystRec['hyst_bcr']=hpars['hysteresis_bcr'] HystRec['susc_h']=hpars['hysteresis_xhf'] HystRec['experiments']=e HystRec['software_packages']=version_num if hpars["magic_method_codes"] not in hmeths:hmeths.append(hpars["magic_method_codes"]) methods="" for meth in hmeths: methods=methods+meth.strip()+":" HystRec["method_codes"]=methods[:-1] HystRec["citations"]="This study" # if len(Bdcd)>0: rmeths=[] for meth in meths: rmeths.append(meth) if verbose and PLT:print('plotting IRM') if irm_init==0: HDD['irm']=5 pmagplotlib.plot_init(HDD['irm'],5,5) irm_init=1 rpars=pmagplotlib.plotIRM(HDD['irm'],Bdcd,Mdcd,irm_exp) HystRec['rem_mr_moment']=rpars['remanence_mr_moment'] HystRec['rem_bcr']=rpars['remanence_bcr'] HystRec['experiments']=specimen+':'+irm_exp if rpars["magic_method_codes"] not in meths:meths.append(rpars["magic_method_codes"]) methods="" for meth in rmeths: methods=methods+meth.strip()+":" HystRec["method_codes"]=HystRec['method_codes']+':'+methods[:-1] HystRec["citations"]="This study" else: if irm_init:pmagplotlib.clearFIG(HDD['irm']) if len(Bimag)>0: if verbose and PLT:print('plotting initial magnetization curve') # first normalize by Ms Mnorm=[] for m in Mimag: Mnorm.append(old_div(m,float(hpars['hysteresis_ms_moment']))) if imag_init==0: HDD['imag']=4 pmagplotlib.plot_init(HDD['imag'],5,5) imag_init=1 pmagplotlib.plotIMAG(HDD['imag'],Bimag,Mnorm,imag_exp) else: if imag_init:pmagplotlib.clearFIG(HDD['imag']) if len(list(HystRec.keys()))>0:HystRecs.append(HystRec) # files={} if plots: if pltspec:s=pltspec files={} for key in list(HDD.keys()): files[key]=s+'_'+key+'.'+fmt pmagplotlib.saveP(HDD,files) if pltspec:sys.exit() if verbose and PLT: pmagplotlib.drawFIGS(HDD) ans=input("S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ") if ans=="a": files={} for key in list(HDD.keys()): files[key]=specimen+'_'+key+'.'+fmt pmagplotlib.saveP(HDD,files) if ans=='':k+=1 if ans=="p": del HystRecs[-1] k-=1 if ans=='q': print("Good bye") sys.exit() if ans=='s': keepon=1 specimen=input('Enter desired specimen name (or first part there of): ') while keepon==1: try: k =sids.index(specimen) keepon=0 except: tmplist=[] for qq in range(len(sids)): if specimen in sids[qq]:tmplist.append(sids[qq]) print(specimen," not found, but this was: ") print(tmplist) specimen=input('Select one or try again\n ') k =sids.index(specimen) else: k+=1 if len(B)==0 and len(Bdcd)==0: if verbose:print('skipping this one - no hysteresis data') k+=1 if len(HystRecs)>0: # go through prior_data, clean out prior results and save combined file as spec_file SpecRecs,keys=[],list(HystRecs[0].keys()) if len(prior_data)>0: prior_keys=list(prior_data[0].keys()) else: prior_keys=[] for rec in prior_data: for key in keys: if key not in list(rec.keys()):rec[key]="" if 'LP-HYS' not in rec['method_codes']: SpecRecs.append(rec) for rec in HystRecs: for key in prior_keys: if key not in list(rec.keys()):rec[key]="" prior=pmag.get_dictitem(prior_data,'specimen',rec['specimen'],'T') if len(prior)>0 and 'sample' in list(prior[0].keys()): rec['sample']=prior[0]['sample'] # pull sample name from prior specimens table SpecRecs.append(rec) pmag.magic_write(spec_file,SpecRecs,"specimens") if verbose:print("hysteresis parameters saved in ",spec_file)
def main(): """ NAME hysteresis_magic.py DESCRIPTION calculates hystereis parameters and saves them in rmag_hystereis format file makes plots if option selected SYNTAX hysteresis_magic.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specify input file, default is agm_measurements.txt -fh: specify rmag_hysteresis.txt input file -F: specify output file, default is rmag_hysteresis.txt -P: do not make the plots -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg] """ args = sys.argv PLT = 1 plots = 0 user, meas_file, rmag_out, rmag_file = "", "agm_measurements.txt", "rmag_hysteresis.txt", "" pltspec = "" dir_path = '.' fmt = 'svg' verbose = pmagplotlib.verbose version_num = pmag.get_version() if '-WD' in args: ind = args.index('-WD') dir_path = args[ind + 1] if "-h" in args: print main.__doc__ sys.exit() if "-usr" in args: ind = args.index("-usr") user = args[ind + 1] if '-f' in args: ind = args.index("-f") meas_file = args[ind + 1] if '-F' in args: ind = args.index("-F") rmag_out = args[ind + 1] if '-fh' in args: ind = args.index("-fh") rmag_file = args[ind + 1] rmag_file = dir_path + '/' + rmag_file if '-P' in args: PLT = 0 irm_init, imag_init = -1, -1 if '-sav' in args: verbose = 0 plots = 1 if '-spc' in args: ind = args.index("-spc") pltspec = args[ind + 1] verbose = 0 plots = 1 if '-fmt' in args: ind = args.index("-fmt") fmt = args[ind + 1] rmag_out = dir_path + '/' + rmag_out meas_file = dir_path + '/' + meas_file rmag_rem = dir_path + "/rmag_remanence.txt" # # meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print main.__doc__ print 'bad file' sys.exit() # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs, RemRecs = [], [] HDD = {} if verbose: if verbose and PLT: print "Plots may be on top of each other - use mouse to place " if PLT: HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'] = 1, 2, 3 pmagplotlib.plot_init(HDD['DdeltaM'], 5, 5) pmagplotlib.plot_init(HDD['deltaM'], 5, 5) pmagplotlib.plot_init(HDD['hyst'], 5, 5) imag_init = 0 irm_init = 0 else: HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'], HDD['irm'], HDD[ 'imag'] = 0, 0, 0, 0, 0 # if rmag_file != "": hyst_data, file_type = pmag.magic_read(rmag_file) # # get list of unique experiment names and specimen names # experiment_names, sids = [], [] for rec in meas_data: meths = rec['magic_method_codes'].split(':') methods = [] for meth in meths: methods.append(meth.strip()) if 'LP-HYS' in methods: if 'er_synthetic_name' in rec.keys( ) and rec['er_synthetic_name'] != "": rec['er_specimen_name'] = rec['er_synthetic_name'] if rec['magic_experiment_name'] not in experiment_names: experiment_names.append(rec['magic_experiment_name']) if rec['er_specimen_name'] not in sids: sids.append(rec['er_specimen_name']) # k = 0 locname = '' if pltspec != "": k = sids.index(pltspec) print sids[k] while k < len(sids): s = sids[k] if verbose and PLT: print s, k + 1, 'out of ', len(sids) # # B, M, Bdcd, Mdcd = [], [], [], [ ] #B,M for hysteresis, Bdcd,Mdcd for irm-dcd data Bimag, Mimag = [], [] #Bimag,Mimag for initial magnetization curves first_dcd_rec, first_rec, first_imag_rec = 1, 1, 1 for rec in meas_data: methcodes = rec['magic_method_codes'].split(':') meths = [] for meth in methcodes: meths.append(meth.strip()) if rec['er_specimen_name'] == s and "LP-HYS" in meths: B.append(float(rec['measurement_lab_field_dc'])) M.append(float(rec['measurement_magn_moment'])) if first_rec == 1: e = rec['magic_experiment_name'] HystRec = {} first_rec = 0 if "er_location_name" in rec.keys(): HystRec["er_location_name"] = rec["er_location_name"] locname = rec['er_location_name'].replace('/', '-') if "er_sample_name" in rec.keys(): HystRec["er_sample_name"] = rec["er_sample_name"] if "er_site_name" in rec.keys(): HystRec["er_site_name"] = rec["er_site_name"] if "er_synthetic_name" in rec.keys( ) and rec['er_synthetic_name'] != "": HystRec["er_synthetic_name"] = rec["er_synthetic_name"] else: HystRec["er_specimen_name"] = rec["er_specimen_name"] if rec['er_specimen_name'] == s and "LP-IRM-DCD" in meths: Bdcd.append(float(rec['treatment_dc_field'])) Mdcd.append(float(rec['measurement_magn_moment'])) if first_dcd_rec == 1: RemRec = {} irm_exp = rec['magic_experiment_name'] first_dcd_rec = 0 if "er_location_name" in rec.keys(): RemRec["er_location_name"] = rec["er_location_name"] if "er_sample_name" in rec.keys(): RemRec["er_sample_name"] = rec["er_sample_name"] if "er_site_name" in rec.keys(): RemRec["er_site_name"] = rec["er_site_name"] if "er_synthetic_name" in rec.keys( ) and rec['er_synthetic_name'] != "": RemRec["er_synthetic_name"] = rec["er_synthetic_name"] else: RemRec["er_specimen_name"] = rec["er_specimen_name"] if rec['er_specimen_name'] == s and "LP-IMAG" in meths: if first_imag_rec == 1: imag_exp = rec['magic_experiment_name'] first_imag_rec = 0 Bimag.append(float(rec['measurement_lab_field_dc'])) Mimag.append(float(rec['measurement_magn_moment'])) # # now plot the hysteresis curve # if len(B) > 0: hmeths = [] for meth in meths: hmeths.append(meth) hpars = pmagplotlib.plotHDD(HDD, B, M, e) if verbose and PLT: pmagplotlib.drawFIGS(HDD) # # get prior interpretations from hyst_data if rmag_file != "": hpars_prior = {} for rec in hyst_data: if rec['magic_experiment_names'] == e: if rec['hysteresis_bcr'] != "" and rec[ 'hysteresis_mr_moment'] != "": hpars_prior['hysteresis_mr_moment'] = rec[ 'hysteresis_mr_moment'] hpars_prior['hysteresis_ms_moment'] = rec[ 'hysteresis_ms_moment'] hpars_prior['hysteresis_bc'] = rec['hysteresis_bc'] hpars_prior['hysteresis_bcr'] = rec[ 'hysteresis_bcr'] break if verbose: pmagplotlib.plotHPARS(HDD, hpars_prior, 'ro') else: if verbose: pmagplotlib.plotHPARS(HDD, hpars, 'bs') HystRec['hysteresis_mr_moment'] = hpars['hysteresis_mr_moment'] HystRec['hysteresis_ms_moment'] = hpars['hysteresis_ms_moment'] HystRec['hysteresis_bc'] = hpars['hysteresis_bc'] HystRec['hysteresis_bcr'] = hpars['hysteresis_bcr'] HystRec['hysteresis_xhf'] = hpars['hysteresis_xhf'] HystRec['magic_experiment_names'] = e HystRec['magic_software_packages'] = version_num if hpars["magic_method_codes"] not in hmeths: hmeths.append(hpars["magic_method_codes"]) methods = "" for meth in hmeths: methods = methods + meth.strip() + ":" HystRec["magic_method_codes"] = methods[:-1] HystRec["er_citation_names"] = "This study" HystRecs.append(HystRec) # if len(Bdcd) > 0: rmeths = [] for meth in meths: rmeths.append(meth) if verbose and PLT: print 'plotting IRM' if irm_init == 0: HDD['irm'] = 5 pmagplotlib.plot_init(HDD['irm'], 5, 5) irm_init = 1 rpars = pmagplotlib.plotIRM(HDD['irm'], Bdcd, Mdcd, irm_exp) RemRec['remanence_mr_moment'] = rpars['remanence_mr_moment'] RemRec['remanence_bcr'] = rpars['remanence_bcr'] RemRec['magic_experiment_names'] = irm_exp if rpars["magic_method_codes"] not in meths: meths.append(rpars["magic_method_codes"]) methods = "" for meth in rmeths: methods = methods + meth.strip() + ":" RemRec["magic_method_codes"] = methods[:-1] RemRec["er_citation_names"] = "This study" RemRecs.append(RemRec) else: if irm_init: pmagplotlib.clearFIG(HDD['irm']) if len(Bimag) > 0: if verbose: print 'plotting initial magnetization curve' # first normalize by Ms Mnorm = [] for m in Mimag: Mnorm.append(m / float(hpars['hysteresis_ms_moment'])) if imag_init == 0: HDD['imag'] = 4 pmagplotlib.plot_init(HDD['imag'], 5, 5) imag_init = 1 pmagplotlib.plotIMAG(HDD['imag'], Bimag, Mnorm, imag_exp) else: if imag_init: pmagplotlib.clearFIG(HDD['imag']) # files = {} if plots: if pltspec != "": s = pltspec files = {} for key in HDD.keys(): files[key] = locname + '_' + s + '_' + key + '.' + fmt pmagplotlib.saveP(HDD, files) if pltspec != "": sys.exit() if verbose and PLT: pmagplotlib.drawFIGS(HDD) ans = raw_input( "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n " ) if ans == "a": files = {} for key in HDD.keys(): files[key] = locname + '_' + s + '_' + key + '.' + fmt pmagplotlib.saveP(HDD, files) if ans == '': k += 1 if ans == "p": del HystRecs[-1] k -= 1 if ans == 'q': print "Good bye" sys.exit() if ans == 's': keepon = 1 specimen = raw_input( 'Enter desired specimen name (or first part there of): ') while keepon == 1: try: k = sids.index(specimen) keepon = 0 except: tmplist = [] for qq in range(len(sids)): if specimen in sids[qq]: tmplist.append(sids[qq]) print specimen, " not found, but this was: " print tmplist specimen = raw_input('Select one or try again\n ') k = sids.index(specimen) else: k += 1 if len(B) == 0 and len(Bdcd) == 0: if verbose: print 'skipping this one - no hysteresis data' k += 1 if rmag_out == "" and ans == 's' and verbose: really = raw_input( " Do you want to overwrite the existing rmag_hystersis.txt file? 1/[0] " ) if really == "": print 'i thought not - goodbye' sys.exit() rmag_out = "rmag_hysteresis.txt" if len(HystRecs) > 0: pmag.magic_write(rmag_out, HystRecs, "rmag_hysteresis") if verbose: print "hysteresis parameters saved in ", rmag_out if len(RemRecs) > 0: pmag.magic_write(rmag_rem, RemRecs, "rmag_remanence") if verbose: print "remanence parameters saved in ", rmag_rem
def main(): """ NAME strip_magic.py DESCRIPTION plots various parameters versus depth or age SYNTAX strip_magic.py [command line optins] OPTIONS -h prints help message and quits -DM NUM: specify data model num, options 2 (legacy) or 3 (default) -f FILE: specify input magic format file from magic,default='pmag_results.txt' supported types=[pmag_specimens, pmag_samples, pmag_sites, pmag_results, magic_web] -obj [sit,sam,all]: specify object to site,sample,all for pmag_result table, default is all -fmt [svg,png,jpg], format for images - default is svg -x [age,pos]: specify whether age or stratigraphic position -y [dec,inc,int,chi,lat,lon,vdm,vadm] (lat and lon are VGP lat and lon) -Iex: plot the expected inc at lat - only available for results with lat info in file -ts TS amin amax: plot the GPTS for the time interval between amin and amax (numbers in Ma) TS: [ck95, gts04] -mcd method_code, specify method code, default is first one encountered -sav save plot and quit NOTES when x and/or y are not specified, a list of possibilities will be presented to the user for choosing """ if '-h' in sys.argv: print(main.__doc__) sys.exit() xaxis, xplotind, yplotind = "", 0, 0 # (0 for strat pos) yaxis, Xinc = "", "" plot = 0 obj = 'all' data_model_num = int(pmag.get_named_arg("-DM", 3)) # 2.5 keys if data_model_num == 2: supported = [ 'pmag_specimens', 'pmag_samples', 'pmag_sites', 'pmag_results', 'magic_web' ] # available file types Depth_keys = [ 'specimen_core_depth', 'specimen_height', 'specimen_elevation', 'specimen_composite_depth', 'sample_core_depth', 'sample_height', 'sample_elevation', 'sample_composite_depth', 'site_core_depth', 'site_height', 'site_elevation', 'site_composite_depth', 'average_height' ] Age_keys = [ 'specimen_inferred_age', 'sample_inferred_age', 'site_inferred_age', 'average_age' ] Unit_keys = { 'specimen_inferred_age': 'specimen_inferred_age_unit', 'sample_inferred_age': 'sample_inferred_age_unit', 'site_inferred_age': 'site_inferred_age_unit', 'average_age': 'average_age_unit' } Dec_keys = [ 'measurement_dec', 'specimen_dec', 'sample_dec', 'site_dec', 'average_dec' ] Inc_keys = [ 'measurement_inc', 'specimen_inc', 'sample_inc', 'site_inc', 'average_inc' ] Int_keys = [ 'measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume', 'measurement_magn_mass', 'specimen_int', 'specimen_int_rel', 'sample_int', 'sample_int_rel', 'site_int', 'site_int_rel', 'average_int', 'average_int_rel' ] Chi_keys = ['measurement_chi_volume', 'measurement_chi_mass'] Lat_keys = ['sample_lat', 'site_lat', 'average_lat'] VLat_keys = ['vgp_lat'] VLon_keys = ['vgp_lon'] Vdm_keys = ['vdm'] Vadm_keys = ['vadm'] method_col_name = "magic_method_codes" else: # 3.0 keys supported = ["specimens", "samples", "sites", "locations"] # available file types Depth_keys = ["height", "core_depth", "elevation", "composite_depth"] Age_keys = ["age"] Unit_keys = {"age": "age"} Chi_keys = ["susc_chi_volume", "susc_chi_mass"] Int_keys = [ "magn_moment", "magn_volume", "magn_mass", "int_abs", "int_rel" ] Inc_keys = ["dir_inc"] Dec_keys = ["dir_dec"] Lat_Keys = ["lat"] VLat_keys = ["vgp_lat", "pole_lat"] VLon_keys = ["vgp_lon", "pole_lon"] Vdm_keys = ["vdm", "pdm"] Vadm_keys = ["vadm", "padm"] method_col_name = "method_codes" # X_keys = [Age_keys, Depth_keys] Y_keys = [ Dec_keys, Inc_keys, Int_keys, Chi_keys, VLat_keys, VLon_keys, Vdm_keys, Vadm_keys ] method, fmt = "", 'svg' FIG = {'strat': 1} plotexp, pTS = 0, 0 dir_path = pmag.get_named_arg("-WD", ".") # default files if data_model_num == 3: res_file = pmag.get_named_arg("-f", "sites.txt") else: res_file = pmag.get_named_arg("-f", "pmag_results.txt") res_file = pmag.resolve_file_name(res_file, dir_path) if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = sys.argv[ind + 1] if '-obj' in sys.argv: ind = sys.argv.index('-obj') obj = sys.argv[ind + 1] if '-x' in sys.argv: ind = sys.argv.index('-x') xaxis = sys.argv[ind + 1] if '-y' in sys.argv: ind = sys.argv.index('-y') yaxis = sys.argv[ind + 1] if yaxis == 'dec': ykeys = Dec_keys if yaxis == 'inc': ykeys = Inc_keys if yaxis == 'int': ykeys = Int_keys if yaxis == 'chi': ykeys = Chi_keys if yaxis == 'lat': ykeys = VLat_keys if yaxis == 'lon': ykeys = VLon_keys if yaxis == 'vdm': ykeys = Vdm_keys if yaxis == 'vadm': ykeys = Vadm_keys if '-mcd' in sys.argv: ind = sys.argv.index('-mcd') method = sys.argv[ind + 1] if '-ts' in sys.argv: ind = sys.argv.index('-ts') ts = sys.argv[ind + 1] amin = float(sys.argv[ind + 2]) amax = float(sys.argv[ind + 3]) pTS = 1 if '-Iex' in sys.argv: plotexp = 1 if '-sav' in sys.argv: plot = 1 # # # get data read in Results, file_type = pmag.magic_read(res_file) if file_type not in supported: print("Unsupported file type ({}), try again".format(file_type)) sys.exit() PltObjs = ['all'] if data_model_num == 2: if file_type == 'pmag_results': # find out what to plot for rec in Results: resname = rec['pmag_result_name'].split() if 'Sample' in resname and 'sam' not in PltObjs: PltObjs.append('sam') if 'Site' in resname and 'sit' not in PltObjs: PltObjs.append('sit') methcodes = [] # need to know all the measurement types from method_codes if "magic_method_codes" in list(Results[0].keys()): for rec in Results: meths = rec["magic_method_codes"].split(":") for meth in meths: if meth.strip() not in methcodes and 'LP' in meth: # look for the lab treatments methcodes.append(meth.strip()) # # initialize some variables X_unit = "" # Unit for age or depth plotting (meters if depth) Xplots, Yplots = [], [] Xunits = [] yplotind, xplotind = 0, 0 # # step through possible plottable keys # if xaxis == "" or yaxis == "": for key in list(Results[0].keys()): for keys in X_keys: for xkeys in keys: if key in xkeys: for ResRec in Results: if ResRec[key] != "": # only plot something if there is something to plot! Xplots.append(key) break for keys in Y_keys: for pkeys in keys: if key in pkeys: for ResRec in Results: if ResRec[key] != "": Yplots.append(key) break X, Y = [], [] for plt in Xplots: if plt in Age_keys and 'age' not in X: X.append('age') if plt in Depth_keys and 'pos' not in X: X.append('pos') for plt in Yplots: if plt in Dec_keys and 'dec' not in Y: Y.append('dec') if plt in Inc_keys and 'inc' not in Y: Y.append('inc') if plt in Int_keys and 'int' not in Y: Y.append('int') if plt in Chi_keys and 'chi' not in Y: Y.append('chi') if plt in VLat_keys and 'lat' not in Y: Y.append('lat') if plt in VLon_keys and 'lon' not in Y: Y.append('lon') if plt in Vadm_keys and 'vadm' not in Y: Y.append('vadm') if plt in Vdm_keys and 'vdm' not in Y: Y.append('vdm') if file_type == 'pmag_results': print('available objects for plotting: ', PltObjs) print('available X plots: ', X) print('available Y plots: ', Y) print('available method codes: ', methcodes) f = open(dir_path + '/.striprc', 'w') for x in X: f.write('x:' + x + '\n') for y in Y: f.write('y:' + y + '\n') for m in methcodes: f.write('m:' + m + '\n') for obj in PltObjs: f.write('obj:' + obj + '\n') sys.exit() if plotexp == 1: for lkey in Lat_keys: for key in list(Results[0].keys()): if key == lkey: lat = float(Results[0][lkey]) Xinc = [pmag.pinc(lat), -pmag.pinc(lat)] break if Xinc == "": print('can not plot expected inc for site - lat unknown') if method != "" and method not in methcodes: print('your method not available, but these are: ') print(methcodes) print('use ', methcodes[0], '? ^D to quit') if xaxis == 'age': for akey in Age_keys: for key in list(Results[0].keys()): if key == akey: Xplots.append(key) Xunits.append(Unit_keys[key]) if xaxis == 'pos': for dkey in Depth_keys: for key in list(Results[0].keys()): if key == dkey: Xplots.append(key) if len(Xplots) == 0: print('desired X axis information not found') sys.exit() if xaxis == 'age': age_unit = Results[0][Xunits[0]] if len(Xplots) > 1: print('multiple X axis keys found, using: ', Xplots[xplotind]) for ykey in ykeys: for key in list(Results[0].keys()): if key == ykey: Yplots.append(key) if len(Yplots) == 0: print('desired Y axis information not found') sys.exit() if len(Yplots) > 1: print('multiple Y axis keys found, using: ', Yplots[yplotind]) # check if age or depth info if len(Xplots) == 0: print("Must have either age or height info to plot ") sys.exit() # # check for variable to plot # # # determine X axis (age or depth) # if xaxis == "age": plotind = "1" if method == "": try: method = methcodes[0] except IndexError: method = "" if xaxis == 'pos': xlab = "Stratigraphic Height (meters)" else: xlab = "Age (" + age_unit + ")" Xkey = Xplots[xplotind] Ykey = Yplots[yplotind] ylab = Ykey # # collect the data for plotting XY = [] isign = 1. # if float(Results[0][Xkey])/float(Results[-1][Xkey])>0 and float(Results[0][Xkey])<0: # isign=-1. # x axis all same sign and negative, take positive (e.g.,for depth in core) # xlab="Stratigraphic Position (meters)" # else: # isign=1. for rec in Results: if "magic_method_codes" in list(rec.keys()): meths = rec["magic_method_codes"].split(":") if method in meths: # make sure it is desired lab treatment step if obj == 'all' and rec[Xkey].strip() != "": XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) elif rec[Xkey].strip() != "": name = rec['pmag_result_name'].split() if obj == 'sit' and "Site" in name: XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) if obj == 'sam' and "Sample" in name: XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) elif method == "": if obj == 'all' and rec[Xkey].strip() != "": XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) elif rec[Xkey].strip() != "": name = rec['pmag_result_name'].split() if obj == 'sit' and "Site" in name: XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) if obj == 'sam' and "Sample" in name: XY.append([isign * float(rec[Xkey]), float(rec[Ykey])]) else: print("Something wrong with your plotting choices") break XY.sort() title = "" if "er_locations_names" in list(Results[0].keys()): title = Results[0]["er_location_names"] if "er_locations_name" in list(Results[0].keys()): title = Results[0]["er_location_name"] labels = [xlab, ylab, title] pmagplotlib.plot_init(FIG['strat'], 10, 5) pmagplotlib.plot_strat(FIG['strat'], XY, labels) # plot them if plotexp == 1: pmagplotlib.plot_hs(FIG['strat'], Xinc, 'b', '--') if yaxis == 'inc' or yaxis == 'lat': pmagplotlib.plot_hs(FIG['strat'], [0], 'b', '-') pmagplotlib.plot_hs(FIG['strat'], [-90, 90], 'g', '-') if pTS == 1: FIG['ts'] = 2 pmagplotlib.plot_init(FIG['ts'], 10, 5) pmagplotlib.plot_ts(FIG['ts'], [amin, amax], ts) files = {} for key in list(FIG.keys()): files[key] = key + '.' + fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' files = {} files['strat'] = xaxis + '_' + yaxis + '_.' + fmt files['ts'] = 'ts.' + fmt titles = {} titles['strat'] = 'Depth/Time Series Plot' titles['ts'] = 'Time Series Plot' FIG = pmagplotlib.add_borders(FIG, titles, black, purple) pmagplotlib.save_plots(FIG, files) elif plot == 1: pmagplotlib.save_plots(FIG, files) else: pmagplotlib.draw_figs(FIG) ans = input(" S[a]ve to save plot, [q]uit without saving: ") if ans == "a": pmagplotlib.save_plots(FIG, files)
def main(): """ NAME lsq_redo.py DESCRIPTION converts a tab delimited LSQ format to PmagPy redo file and edits the magic_measurements table to mark "bad" measurements. SYNTAX lsq_redo.py [-h] [command line options] OPTIONS -h: prints help message and quits -f FILE: specify LSQ input file -fm MFILE: specify measurements file for editting, default is magic_measurements.txt -F FILE: specify output file, default is 'zeq_redo' """ letters = string.ascii_uppercase for l in string.ascii_lowercase: letters = letters + l dir_path = '.' 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 '-f' in sys.argv: ind = sys.argv.index('-f') inspec = dir_path + '/' + sys.argv[ind + 1] else: zfile = dir_path + '/zeq_redo' if '-fm' in sys.argv: ind = sys.argv.index('-f') meas_file = dir_path + '/' + sys.argv[ind + 1] else: meas_file = dir_path + '/magic_measurements.txt' if '-F' in sys.argv: ind = sys.argv.index('-F') zfile = dir_path + '/' + sys.argv[ind + 1] else: zfile = dir_path + '/zeq_redo' try: open(meas_file, "r") meas_data, file_type = pmag.magic_read(meas_file) except IOError: print(main.__doc__) print("""You must have a valid measurements file prior to converting this LSQ file""") sys.exit() zredo = open(zfile, "w") MeasRecs = [] # # read in LSQ file # specs, MeasOuts = [], [] prior_spec_data = open(inspec, 'r').readlines() for line in prior_spec_data: if len(line) < 2: sys.exit() # spec=line[0:14].strip().replace(" ","") # get out the specimen name = collapsing spaces # rec=line[14:].split() # split up the rest of the line rec = line.split('\t') spec = rec[0].lower() specs.append(spec) comp_name = rec[2] # assign component name calculation_type = "DE-FM" if rec[1][0] == "L": calculation_type = "DE-BFL" # best-fit line else: calculation_type = "DE-BFP" # best-fit line lists = rec[7].split('-') # get list of data used incl = [] for l in lists[0]: incl.append(letters.index(l)) for l in letters[letters.index(lists[0][-1]) + 1:letters.index(lists[1][0])]: incl.append(letters.index(l)) # add in the in between parts for l in lists[1]: incl.append(letters.index(l)) if len(lists) > 2: for l in letters[letters.index(lists[1][-1]) + 1:letters.index(lists[2][0])]: incl.append(letters.index(l)) # add in the in between parts for l in lists[2]: incl.append(letters.index(l)) # now find all the data for this specimen in measurements datablock, min, max = [], "", "" demag = 'N' for s in meas_data: if s['er_specimen_name'].lower() == spec.lower(): meths = s['magic_method_codes'].replace(" ", "").split(":") if 'LT-NO' in meths or 'LT-AF-Z' in meths or 'LT-T-Z' in meths: datablock.append(s) if len(datablock) > 0: for t in datablock: print(t['magic_method_codes']) incl_int = len(incl) while incl[-1] > len(datablock) - 1: del incl[ -1] # don't include measurements beyond what is in file if len(incl) != incl_int: 'converting calculation type to best-fit line' meths0 = datablock[incl[0]]['magic_method_codes'].replace( " ", "").split(':') meths1 = datablock[incl[-1]]['magic_method_codes'].replace( " ", "").split(':') H0 = datablock[incl[0]]['treatment_ac_field'] T0 = datablock[incl[0]]['treatment_temp'] H1 = datablock[incl[-1]]['treatment_ac_field'] T1 = datablock[incl[-1]]['treatment_temp'] if 'LT-T-Z' in meths1: max = T1 demag = "T" elif 'LT-AF-Z' in meths1: demag = "AF" max = H1 if 'LT-NO' in meths0: if demag == 'T': min = 273 else: min = 0 elif 'LT-T-Z' in meths0: min = T0 else: min = H0 for ind in range(incl[0]): MeasRecs.append(datablock[ind]) for ind in range(incl[0], incl[-1]): if ind not in incl: # datapoint not used in calculation datablock[ind]['measurement_flag'] = 'b' MeasRecs.append(datablock[ind]) for ind in range(incl[-1], len(datablock)): MeasRecs.append(datablock[ind]) outstring = '%s %s %s %s %s \n' % (spec, calculation_type, min, max, comp_name) zredo.write(outstring) for s in meas_data: # collect the rest of the measurement data not already included if s['er_specimen_name'] not in specs: MeasRecs.append(s) pmag.magic_write(meas_file, MeasRecs, 'magic_measurements') # write out annotated measurements
def main(): """ NAME microwave_magic.py DESCRIPTION plots microwave paleointensity data, allowing interactive setting of bounds. Saves and reads interpretations from a pmag_specimen formatted table, default: microwave_specimens.txt SYNTAX microwave_magic.py [command line options] OPTIONS -h prints help message and quits -f MEAS, set magic_measurements input file -fsp PRIOR, set pmag_specimen prior interpretations file -fcr CRIT, set criteria file for grading. -fmt [svg,png,jpg], format for images - default is svg -sav, saves plots with out review (default format) -spc SPEC, plots single specimen SPEC, saves plot with specified format with optional -b bounds adn quits -b BEG END: sets bounds for calculation BEG: starting step for slope calculation END: ending step for slope calculation DEFAULTS MEAS: magic_measurements.txt CRIT: NONE PRIOR: microwave_specimens.txt OUTPUT figures: ALL: numbers refer to temperature steps in command line window 1) Arai plot: closed circles are zero-field first/infield open circles are infield first/zero-field triangles are pTRM checks squares are pTRM tail checks VDS is vector difference sum diamonds are bounds for interpretation 2) Zijderveld plot: closed (open) symbols are X-Y (X-Z) planes X rotated to NRM direction 3) (De/Re)Magnetization diagram: circles are NRM remaining squares are pTRM gained command line window: list is: temperature step numbers, power (J), Dec, Inc, Int (units of magic_measuements) list of possible commands: type letter followed by return to select option saving of plots creates .svg format files with specimen_name, plot type as name """ # # initializations # meas_file, critout, inspec = "magic_measurements.txt", "", "microwave_specimens.txt" inlt = 0 version_num = pmag.get_version() Tinit, DCZ, field, first_save = 0, 0, -1, 1 user, comment = "", '' ans, specimen, recnum, start, end = 0, 0, 0, 0, 0 plots, pmag_out, samp_file, style = 0, "", "", "svg" fmt = '.' + style # # default acceptance criteria # accept_keys = [ 'specimen_int_ptrm_n', 'specimen_md', 'specimen_fvds', 'specimen_b_beta', 'specimen_dang', 'specimen_drats', 'specimen_Z' ] accept = {} accept['specimen_int_ptrm_n'] = 2 accept['specimen_md'] = 10 accept['specimen_fvds'] = 0.35 accept['specimen_b_beta'] = .1 accept['specimen_int_mad'] = 7 accept['specimen_dang'] = 10 accept['specimen_drats'] = 10 accept['specimen_Z'] = 10 # # parse command line options # spc, BEG, END = "", "", "" if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind = sys.argv.index('-f') meas_file = sys.argv[ind + 1] if '-fsp' in sys.argv: ind = sys.argv.index('-fsp') inspec = sys.argv[ind + 1] if '-fcr' in sys.argv: ind = sys.argv.index('-fcr') critout = sys.argv[ind + 1] if '-fmt' in sys.argv: ind = sys.argv.index('-fmt') fmt = '.' + sys.argv[ind + 1] if '-spc' in sys.argv: ind = sys.argv.index('-spc') spc = sys.argv[ind + 1] if '-b' in sys.argv: ind = sys.argv.index('-b') BEG = int(sys.argv[ind + 1]) END = int(sys.argv[ind + 2]) if critout != "": crit_data, file_type = pmag.magic_read(critout) if pmagplotlib.verbose: print "Acceptance criteria read in from ", critout accept = {} accept['specimen_int_ptrm_n'] = 2.0 for critrec in crit_data: if critrec["pmag_criteria_code"] == "IE-SPEC": for key in accept_keys: if key not in critrec.keys(): accept[key] = -1 else: accept[key] = float(critrec[key]) try: open(inspec, 'rU') PriorRecs, file_type = pmag.magic_read(inspec) if file_type != 'pmag_specimens': print file_type print file_type, inspec, " is not a valid pmag_specimens file " sys.exit() for rec in PriorRecs: if 'magic_software_packages' not in rec.keys(): rec['magic_software_packages'] = "" except IOError: PriorRecs = [] if pmagplotlib.verbose: print "starting new specimen interpretation file: ", inspec meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print file_type print file_type, "This is not a valid magic_measurements file " sys.exit() backup = 0 # define figure numbers for arai, zijderveld and # de-,re-magization diagrams AZD = {} AZD['deremag'], AZD['zijd'], AZD['arai'], AZD['eqarea'] = 1, 2, 3, 4 pmagplotlib.plot_init(AZD['arai'], 4, 4) pmagplotlib.plot_init(AZD['zijd'], 4, 4) pmagplotlib.plot_init(AZD['deremag'], 4, 4) pmagplotlib.plot_init(AZD['eqarea'], 4, 4) # # # # get list of unique specimen names # CurrRec = [] sids = pmag.get_specs(meas_data) # get plots for specimen s - default is just to step through arai diagrams # if spc != "": specimen = sids.index(spc) while specimen < len(sids): methcodes = [] if pmagplotlib.verbose and spc != "": print sids[specimen], specimen + 1, 'of ', len(sids) MeasRecs = [] s = sids[specimen] datablock, trmblock = [], [] PmagSpecRec = {} PmagSpecRec["er_analyst_mail_names"] = user PmagSpecRec["specimen_correction"] = 'u' # # find the data from the meas_data file for this specimen # for rec in meas_data: if rec["er_specimen_name"] == s: MeasRecs.append(rec) methods = rec["magic_method_codes"].split(":") meths = [] for meth in methods: meths.append(meth.strip()) # take off annoying spaces methods = "" for meth in meths: if meth.strip() not in methcodes and "LP-" in meth: methcodes.append(meth.strip()) methods = methods + meth + ":" methods = methods[:-1] rec["magic_method_codes"] = methods if "LP-PI-M" in meths: datablock.append(rec) if "LP-MRM" in meths: trmblock.append(rec) if len(trmblock) > 2 and inspec != "": if Tinit == 0: Tinit = 1 AZD['MRM'] = 4 pmagplotlib.plot_init(AZD['MRM'], 4, 4) elif Tinit == 1: pmagplotlib.clearFIG(AZD['MRM']) if len(datablock) < 4: if backup == 0: specimen += 1 if pmagplotlib.verbose: print 'skipping specimen - moving forward ', s else: specimen -= 1 if pmagplotlib.verbose: print 'skipping specimen - moving backward ', s # # collect info for the PmagSpecRec dictionary # else: rec = datablock[0] PmagSpecRec["er_citation_names"] = "This study" PmagSpecRec["er_specimen_name"] = s PmagSpecRec["er_sample_name"] = rec["er_sample_name"] PmagSpecRec["er_site_name"] = rec["er_site_name"] PmagSpecRec["er_location_name"] = rec["er_location_name"] if "magic_instrument_codes" not in rec.keys(): rec["magic_instrument_codes"] = "" PmagSpecRec["magic_instrument_codes"] = rec[ "magic_instrument_codes"] PmagSpecRec["measurement_step_unit"] = "J" if "magic_experiment_name" not in rec.keys(): rec["magic_experiment_name"] = "" else: PmagSpecRec["magic_experiment_names"] = rec[ "magic_experiment_name"] meths = rec["magic_method_codes"].split(':') # sort data into types if "LP-PI-M-D" in meths: # this is a double heating experiment exp_type = "LP-PI-M-D" elif "LP-PI-M-S" in meths: exp_type = "LP-PI-M-S" else: print "experiment type not supported yet " break araiblock, field = pmag.sortmwarai(datablock, exp_type) first_Z = araiblock[0] first_I = araiblock[1] GammaChecks = araiblock[-3] ThetaChecks = araiblock[-2] DeltaChecks = araiblock[-1] if len(first_Z) < 3: if backup == 0: specimen += 1 if pmagplotlib.verbose: print 'skipping specimen - moving forward ', s else: specimen -= 1 if pmagplotlib.verbose: print 'skipping specimen - moving backward ', s else: backup = 0 zijdblock, units = pmag.find_dmag_rec(s, meas_data) if exp_type == "LP-PI-M-D": recnum = 0 print "ZStep Watts Dec Inc Int" for plotrec in zijdblock: if pmagplotlib.verbose: print '%i %i %7.1f %7.1f %8.3e ' % ( recnum, plotrec[0], plotrec[1], plotrec[2], plotrec[3]) recnum += 1 recnum = 1 if GammaChecks != "": print "IStep Watts Gamma" for gamma in GammaChecks: if pmagplotlib.verbose: print '%i %i %7.1f ' % (recnum, gamma[0], gamma[1]) recnum += 1 if exp_type == "LP-PI-M-S": if pmagplotlib.verbose: print "IStep Watts Theta" kk = 0 for theta in ThetaChecks: kk += 1 print '%i %i %7.1f ' % (kk, theta[0], theta[1]) if pmagplotlib.verbose: print "Watts Delta" for delta in DeltaChecks: print '%i %7.1f ' % (delta[0], delta[1]) pmagplotlib.plotAZ(AZD, araiblock, zijdblock, s, units[0]) if inspec != "": if pmagplotlib.verbose: print 'Looking up saved interpretation....' found = 0 for k in range(len(PriorRecs)): try: if PriorRecs[k]["er_specimen_name"] == s: found = 1 CurrRec.append(PriorRecs[k]) for j in range(len(araiblock[0])): if float(araiblock[0][j][0]) == float( PriorRecs[k] ["measurement_step_min"]): start = j if float(araiblock[0][j][0]) == float( PriorRecs[k] ["measurement_step_max"]): end = j pars, errcode = pmag.PintPars( araiblock, zijdblock, start, end) pars['measurement_step_unit'] = "J" del PriorRecs[ k] # put in CurrRec, take out of PriorRecs if errcode != 1: pars["specimen_lab_field_dc"] = field pars["specimen_int"] = -1 * field * pars[ "specimen_b"] pars["er_specimen_name"] = s if pmagplotlib.verbose: print 'Saved interpretation: ' pars = pmag.scoreit( pars, PmagSpecRec, accept, '', 0) pmagplotlib.plotB(AZD, araiblock, zijdblock, pars) if len(trmblock) > 2: blab = field best = pars["specimen_int"] Bs, TRMs = [], [] for trec in trmblock: Bs.append( float( trec['treatment_dc_field']) ) TRMs.append( float(trec[ 'measurement_magn_moment']) ) NLpars = nlt.NLtrm( Bs, TRMs, best, blab, 0 ) # calculate best fit parameters through TRM acquisition data, and get new banc Mp, Bp = [], [] for k in range(int(max(Bs) * 1e6)): Bp.append(float(k) * 1e-6) npred = nlt.TRM( Bp[-1], NLpars['xopt'][0], NLpars['xopt'][1] ) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM( AZD['MRM'], Bs, TRMs, Bp, Mp, NLpars, trec['magic_experiment_name']) print npred print 'Banc= ', float( NLpars['banc']) * 1e6 if pmagplotlib.verbose: print 'Banc= ', float( NLpars['banc']) * 1e6 pmagplotlib.drawFIGS(AZD) else: print 'error on specimen ', s except: pass if pmagplotlib.verbose and found == 0: print ' None found :( ' if spc != "": if BEG != "": pars, errcode = pmag.PintPars(araiblock, zijdblock, BEG, END) pars['measurement_step_unit'] = "J" pars["specimen_lab_field_dc"] = field pars["specimen_int"] = -1 * field * pars["specimen_b"] pars["er_specimen_name"] = s pars['specimen_grade'] = '' # ungraded pmagplotlib.plotB(AZD, araiblock, zijdblock, pars) if len(trmblock) > 2: if inlt == 0: donlt() inlt = 1 blab = field best = pars["specimen_int"] Bs, TRMs = [], [] for trec in trmblock: Bs.append(float(trec['treatment_dc_field'])) TRMs.append( float(trec['measurement_magn_moment'])) NLpars = nlt.NLtrm( Bs, TRMs, best, blab, 0 ) # calculate best fit parameters through TRM acquisition data, and get new banc # Mp, Bp = [], [] for k in range(int(max(Bs) * 1e6)): Bp.append(float(k) * 1e-6) npred = nlt.TRM( Bp[-1], NLpars['xopt'][0], NLpars['xopt'] [1]) # predicted NRM for this field files = {} for key in AZD.keys(): files[key] = s + '_' + key + fmt pmagplotlib.saveP(AZD, files) sys.exit() if plots == 0: ans = 'b' while ans != "": print """ s[a]ve plot, set [b]ounds for calculation, [d]elete current interpretation, [p]revious, [s]ample, [q]uit: """ ans = raw_input('Return for next specimen \n') if ans == "": specimen += 1 if ans == "d": save_redo(PriorRecs, inspec) CurrRec = [] pmagplotlib.plotAZ(AZD, araiblock, zijdblock, s, units[0]) pmagplotlib.drawFIGS(AZD) if ans == 'a': files = {} for key in AZD.keys(): files[key] = s + '_' + key + fmt pmagplotlib.saveP(AZD, files) ans = "" if ans == 'q': print "Good bye" sys.exit() if ans == 'p': specimen = specimen - 1 backup = 1 ans = "" if ans == 's': keepon = 1 spec = raw_input( 'Enter desired specimen name (or first part there of): ' ) while keepon == 1: try: specimen = sids.index(spec) keepon = 0 except: tmplist = [] for qq in range(len(sids)): if spec in sids[qq]: tmplist.append(sids[qq]) print specimen, " not found, but this was: " print tmplist spec = raw_input( 'Select one or try again\n ') ans = "" if ans == 'b': if end == 0 or end >= len(araiblock[0]): end = len(araiblock[0]) - 1 GoOn = 0 while GoOn == 0: print 'Enter index of first point for calculation: ', '[', start, ']' answer = raw_input('return to keep default ') if answer != "": start = int(answer) print 'Enter index of last point for calculation: ', '[', end, ']' answer = raw_input('return to keep default ') if answer != "": end = int(answer) if start >= 0 and start < len(araiblock[ 0]) - 2 and end > 0 and end < len( araiblock[0]) and start < end: GoOn = 1 else: print "Bad endpoints - try again! " start, end = 0, len(araiblock) s = sids[specimen] pars, errcode = pmag.PintPars( araiblock, zijdblock, start, end) pars['measurement_step_unit'] = "J" pars["specimen_lab_field_dc"] = field pars["specimen_int"] = -1 * field * pars[ "specimen_b"] pars["er_specimen_name"] = s pars = pmag.scoreit(pars, PmagSpecRec, accept, '', 0) PmagSpecRec["measurement_step_min"] = '%8.3e' % ( pars["measurement_step_min"]) PmagSpecRec["measurement_step_max"] = '%8.3e' % ( pars["measurement_step_max"]) PmagSpecRec["measurement_step_unit"] = "J" PmagSpecRec["specimen_int_n"] = '%i' % ( pars["specimen_int_n"]) PmagSpecRec["specimen_lab_field_dc"] = '%8.3e' % ( pars["specimen_lab_field_dc"]) PmagSpecRec["specimen_int"] = '%8.3e ' % ( pars["specimen_int"]) PmagSpecRec["specimen_b"] = '%5.3f ' % ( pars["specimen_b"]) PmagSpecRec["specimen_q"] = '%5.1f ' % ( pars["specimen_q"]) PmagSpecRec["specimen_f"] = '%5.3f ' % ( pars["specimen_f"]) PmagSpecRec["specimen_fvds"] = '%5.3f' % ( pars["specimen_fvds"]) PmagSpecRec["specimen_b_beta"] = '%5.3f' % ( pars["specimen_b_beta"]) PmagSpecRec["specimen_int_mad"] = '%7.1f' % ( pars["specimen_int_mad"]) PmagSpecRec["specimen_Z"] = '%7.1f' % ( pars["specimen_Z"]) if pars["method_codes"] != "": tmpcodes = pars["method_codes"].split(":") for t in tmpcodes: if t.strip() not in methcodes: methcodes.append(t.strip()) PmagSpecRec["specimen_dec"] = '%7.1f' % ( pars["specimen_dec"]) PmagSpecRec["specimen_inc"] = '%7.1f' % ( pars["specimen_inc"]) PmagSpecRec["specimen_tilt_correction"] = '-1' PmagSpecRec["specimen_direction_type"] = 'l' PmagSpecRec[ "direction_type"] = 'l' # this is redudant, but helpful - won't be imported PmagSpecRec["specimen_dang"] = '%7.1f ' % ( pars["specimen_dang"]) PmagSpecRec["specimen_drats"] = '%7.1f ' % ( pars["specimen_drats"]) PmagSpecRec["specimen_int_ptrm_n"] = '%i ' % ( pars["specimen_int_ptrm_n"]) PmagSpecRec["specimen_rsc"] = '%6.4f ' % ( pars["specimen_rsc"]) PmagSpecRec["specimen_md"] = '%i ' % (int( pars["specimen_md"])) if PmagSpecRec["specimen_md"] == '-1': PmagSpecRec["specimen_md"] = "" PmagSpecRec["specimen_b_sigma"] = '%5.3f ' % ( pars["specimen_b_sigma"]) if "IE-TT" not in methcodes: methcodes.append("IE-TT") methods = "" for meth in methcodes: methods = methods + meth + ":" PmagSpecRec["magic_method_codes"] = methods[:-1] PmagSpecRec["specimen_description"] = comment PmagSpecRec[ "magic_software_packages"] = version_num pmagplotlib.plotAZ(AZD, araiblock, zijdblock, s, units[0]) pmagplotlib.plotB(AZD, araiblock, zijdblock, pars) if len(trmblock) > 2: blab = field best = pars["specimen_int"] Bs, TRMs = [], [] for trec in trmblock: Bs.append(float( trec['treatment_dc_field'])) TRMs.append( float(trec['measurement_magn_moment'])) NLpars = nlt.NLtrm( Bs, TRMs, best, blab, 0 ) # calculate best fit parameters through TRM acquisition data, and get new banc Mp, Bp = [], [] for k in range(int(max(Bs) * 1e6)): Bp.append(float(k) * 1e-6) npred = nlt.TRM( Bp[-1], NLpars['xopt'][0], NLpars['xopt'] [1]) # predicted NRM for this field Mp.append(npred) pmagplotlib.plotTRM( AZD['MRM'], Bs, TRMs, Bp, Mp, NLpars, trec['magic_experiment_name']) print 'Banc= ', float(NLpars['banc']) * 1e6 pmagplotlib.drawFIGS(AZD) pars["specimen_lab_field_dc"] = field pars["specimen_int"] = -1 * field * pars[ "specimen_b"] saveit = raw_input( "Save this interpretation? [y]/n \n") if saveit != 'n': specimen += 1 PriorRecs.append( PmagSpecRec) # put back an interpretation save_redo(PriorRecs, inspec) ans = "" else: specimen += 1 if fmt != ".pmag": basename = s + '_microwave' + fmt files = {} for key in AZD.keys(): files[key] = s + '_' + key + fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles = {} titles['deremag'] = 'DeReMag Plot' titles['zijd'] = 'Zijderveld Plot' titles['arai'] = 'Arai Plot' AZD = pmagplotlib.addBorders( AZD, titles, black, purple) pmagplotlib.saveP(AZD, files) # pmagplotlib.combineFigs(s,files,3) if len(CurrRec) > 0: for rec in CurrRec: PriorRecs.append(rec) CurrRec = [] if plots != 1: ans = raw_input(" Save last plot? 1/[0] ") if ans == "1": if fmt != ".pmag": files = {} for key in AZD.keys(): files[key] = s + '_' + key + fmt pmagplotlib.saveP(AZD, files) if len(CurrRec) > 0: PriorRecs.append(CurrRec) # put back an interpretation if len(PriorRecs) > 0: save_redo(PriorRecs, inspec) print 'Updated interpretations saved in ', inspec if pmagplotlib.verbose: print "Good bye"
def main(): """ NAME make_magic_plots.py DESCRIPTION inspects magic directory for available plots. SYNTAX make_magic_plots.py [command line options] INPUT magic files OPTIONS -h prints help message and quits -f FILE specifies input file name -fmt [png,eps,svg,jpg,pdf] specify format, default is png -DM [2,3] define data model """ dirlist=['./'] dir_path=os.getcwd() names=os.listdir(dir_path) for n in names: if 'Location' in n: dirlist.append(n) if '-fmt' in sys.argv: ind=sys.argv.index("-fmt") fmt=sys.argv[ind+1] else: fmt='png' if '-f' in sys.argv: ind=sys.argv.index("-f") filelist=[sys.argv[ind+1]] else: filelist=os.listdir(dir_path) new_model=0 if '-DM' in sys.argv: ind=sys.argv.index("-DM") data_model=sys.argv[ind+1] if data_model=='3': new_model=1 if new_model: samp_file='samples.txt' azimuth_key='azimuth' meas_file='measurements.txt' loc_key='location' method_key='method_codes' dec_key='dir_dec' inc_key='dir_inc' Mkeys=['magnitude','magn_moment','magn_volume','magn_mass'] results_file='sites.txt' tilt_key='direction_tilt_correction' hyst_file='specimens.txt' aniso_file='specimens.txt' else: new_model=0 samp_file='er_samples.txt' azimuth_key='sample_azimuth' meas_file='magic_measurements.txt' loc_key='er_location_name' method_key='magic_method_codes' dec_key='measurement_dec' inc_key='measurement_inc' Mkeys=['measurement_magnitude','measurement_magn_moment','measurement_magn_volume','measurement_magn_mass'] results_file='pmag_results.txt' tilt_key='tilt_correction' hyst_file='rmag_hysteresis' aniso_file='rmag_anisotropy' if '-h' in sys.argv: print(main.__doc__) sys.exit() for loc in dirlist: print('working on: ',loc) os.chdir(loc) # change working directories to each location crd='s' print(samp_file) if samp_file in filelist: # find coordinate systems print('found sample file') samps,file_type=pmag.magic_read(samp_file) # read in data Srecs=pmag.get_dictitem(samps,azimuth_key,'','F')# get all none blank sample orientations if len(Srecs)>0: crd='g' if meas_file in filelist: # start with measurement data print('working on measurements data') data,file_type=pmag.magic_read(meas_file) # read in data if loc == './': data=pmag.get_dictitem(data,loc_key,'','T') # get all the blank location names from data file # looking for zeq_magic possibilities AFZrecs=pmag.get_dictitem(data,method_key,'LT-AF-Z','has')# get all none blank method codes TZrecs=pmag.get_dictitem(data,method_key,'LT-T-Z','has')# get all none blank method codes MZrecs=pmag.get_dictitem(data,method_key,'LT-M-Z','has')# get all none blank method codes Drecs=pmag.get_dictitem(data,dec_key,'','F') # get all dec measurements Irecs=pmag.get_dictitem(data,inc_key,'','F') # get all inc measurements for key in Mkeys: Mrecs=pmag.get_dictitem(data,key,'','F') # get intensity data if len(Mrecs)>0:break if len(AFZrecs)>0 or len(TZrecs)>0 or len(MZrecs)>0 and len(Drecs)>0 and len(Irecs)>0 and len(Mrecs)>0: # potential for stepwise demag curves if new_model: CMD = 'zeq_magic3.py -fsp specimens.txt -sav -fmt '+fmt+' -crd '+crd else: CMD='zeq_magic.py -fsp pmag_specimens.txt -sav -fmt '+fmt+' -crd '+crd print(CMD) os.system(CMD) # looking for thellier_magic possibilities if len(pmag.get_dictitem(data,method_key,'LP-PI-TRM','has'))>0: if new_model: CMD= 'thellier_magic3.py -fsp specimens.txt -sav -fmt '+fmt else: CMD= 'thellier_magic.py -fsp pmag_specimens.txt -sav -fmt '+fmt print(CMD) os.system(CMD) # looking for hysteresis possibilities if len(pmag.get_dictitem(data,method_key,'LP-HYS','has'))>0: # find hyst experiments if new_model: CMD= 'quick_hyst3.py -sav -fmt '+fmt else: CMD= 'quick_hyst.py -sav -fmt '+fmt print(CMD) os.system(CMD) if results_file in filelist: # start with measurement data data,file_type=pmag.magic_read(results_file) # read in data print('number of datapoints: ',len(data)) if loc == './': data=pmag.get_dictitem(data,loc_key,':','has') # get all the concatenated location names from data file print('number of datapoints: ',len(data) ,loc) if new_model: print('working on site directions') dec_key='dir_dec' inc_key='dir_inc' int_key='int_abs' else: print('working on results directions') dec_key='average_dec' inc_key='average_inc' int_key='average_int' SiteDIs=pmag.get_dictitem(data,dec_key,"",'F') # find decs SiteDIs=pmag.get_dictitem(SiteDIs,inc_key,"",'F') # find decs and incs SiteDIs=pmag.get_dictitem(SiteDIs,'data_type','i','has') # only individual results - not poles print('number of directions: ',len(SiteDIs)) SiteDIs_t=pmag.get_dictitem(SiteDIs,tilt_key,'100','T')# tilt corrected coordinates print('number of tilt corrected directions: ',len(SiteDIs)) SiteDIs_g=pmag.get_dictitem(SiteDIs,tilt_key,'0','T')# geographic coordinates SiteDIs_s=pmag.get_dictitem(SiteDIs,'tilt_correction','-1','T')# sample coordinates SiteDIs_x=pmag.get_dictitem(SiteDIs,'tilt_correction','','T')# no coordinates if len(SiteDIs_t)>0 or len(SiteDIs_g) >0 or len(SiteDIs_s)>0 or len(SiteDIs_x)>0: CRD="" if len(SiteDIs_t)>0: CRD=' -crd t' elif len(SiteDIs_g )>0: CRD=' -crd g' elif len(SiteDIs_s )>0: CRD=' -crd s' if new_model: CMD= 'eqarea_magic3.py -sav -crd t -fmt '+fmt +CRD else: CMD= 'eqarea_magic.py -sav -crd t -fmt '+fmt +CRD print(CMD) os.system(CMD) print('working on VGP map') VGPs=pmag.get_dictitem(SiteDIs,'vgp_lat',"",'F') # are there any VGPs? if len(VGPs)>0: # YES! os.system('vgpmap_magic.py -prj moll -res c -sym ro 5 -sav -fmt png') print('working on intensities') if not new_model: CMD='magic_select.py -f '+results_file+' -key data_type i T -F tmp.txt' os.system(CMD) infile=' tmp.txt' else: infile=results_file print(int_key) CMD='magic_select.py -key '+int_key +' 0. has -F tmp1.txt -f '+infile os.system(CMD) CMD="grab_magic_key.py -f tmp1.txt -key "+int_key+ " | awk '{print $1*1e6}' >tmp2.txt" os.system(CMD) data,file_type=pmag.magic_read('tmp1.txt') # read in data if new_model: locations=pmag.get_dictkey(data,loc_key,"") else: locations=pmag.get_dictkey(data,loc_key+'s',"") histfile='LO:_'+locations[0]+'_intensities_histogram:_.'+fmt os.system("histplot.py -b 1 -xlab 'Intensity (uT)' -sav -f tmp2.txt -F " +histfile) print("histplot.py -b 1 -xlab 'Intensity (uT)' -sav -f tmp2.txt -F " +histfile) os.system('rm tmp*.txt') if hyst_file in filelist: # start with measurement data print('working on hysteresis') data,file_type=pmag.magic_read(hyst_file) # read in data if loc == './': data=pmag.get_dictitem(data,loc_key,'','T') # get all the blank location names from data file hdata=pmag.get_dictitem(data,'hysteresis_bcr','','F') hdata=pmag.get_dictitem(hdata,'hysteresis_mr_moment','','F') hdata=pmag.get_dictitem(hdata,'hysteresis_ms_moment','','F') hdata=pmag.get_dictitem(hdata,'hysteresis_bc','','F') # there are data for a dayplot if len(hdata)>0: print('dayplot_magic.py -sav -fmt '+fmt) os.system('dayplot_magic.py -sav -fmt '+fmt) if aniso_file in filelist: # do anisotropy plots if possible print('working on anisotropy') data,file_type=pmag.magic_read(aniso_file) # read in data if loc == './': data=pmag.get_dictitem(data,loc_key,'','T') # get all the blank location names from data file sdata=pmag.get_dictitem(data,'anisotropy_tilt_correction','-1','T') # get specimen coordinates gdata=pmag.get_dictitem(data,'anisotropy_tilt_correction','0','T') # get specimen coordinates tdata=pmag.get_dictitem(data,'anisotropy_tilt_correction','100','T') # get specimen coordinates CRD="" if new_model: CMD= 'aniso_magic3.py -x -B -sav -fmt '+fmt else: CMD= 'aniso_magic.py -x -B -sav -fmt '+fmt if len(sdata)>3: CMD=CMD+' -crd s' print(CMD) os.system(CMD) if len(gdata)>3: CMD=CMD+' -crd g' print(CMD) os.system(CMD) if len(tdata)>3: CMD=CMD+' -crd t' print(CMD) os.system(CMD) if loc!='./':os.chdir('..') # change working directories to each location
def main(): """ NAME make_magic_plots.py DESCRIPTION inspects magic directory for available plots. SYNTAX make_magic_plots.py [command line options] INPUT magic files OPTIONS -h prints help message and quits -f FILE specifies input file name -fmt [png,eps,svg,jpg,pdf] specify format, default is png """ dirlist = ['./'] dir_path = os.getcwd() names = os.listdir(dir_path) for n in names: if 'Location' in n: dirlist.append(n) if '-fmt' in sys.argv: ind = sys.argv.index("-fmt") fmt = sys.argv[ind + 1] else: fmt = 'png' if '-f' in sys.argv: ind = sys.argv.index("-f") filelist = [sys.argv[ind + 1]] else: filelist = os.listdir(dir_path) if '-h' in sys.argv: print(main.__doc__) sys.exit() for loc in dirlist: print('working on: ', loc) os.chdir(loc) # change working directories to each location crd = 's' if 'er_samples.txt' in filelist: # find coordinate systems samps, file_type = pmag.magic_read( 'er_samples.txt') # read in data Srecs = pmag.get_dictitem( samps, 'sample_azimuth', '', 'F') # get all none blank sample orientations if len(Srecs) > 0: crd = 'g' if 'magic_measurements.txt' in filelist: # start with measurement data print('working on measurements data') data, file_type = pmag.magic_read( 'magic_measurements.txt') # read in data if loc == './': data = pmag.get_dictitem( data, 'er_location_name', '', 'T') # get all the blank location names from data file # looking for zeq_magic possibilities AFZrecs = pmag.get_dictitem( data, 'magic_method_codes', 'LT-AF-Z', 'has') # get all none blank method codes TZrecs = pmag.get_dictitem( data, 'magic_method_codes', 'LT-T-Z', 'has') # get all none blank method codes MZrecs = pmag.get_dictitem( data, 'magic_method_codes', 'LT-M-Z', 'has') # get all none blank method codes Drecs = pmag.get_dictitem(data, 'measurement_dec', '', 'F') # get all dec measurements Irecs = pmag.get_dictitem(data, 'measurement_inc', '', 'F') # get all dec measurements Mkeys = [ 'measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume', 'measurement_magn_mass' ] for key in Mkeys: Mrecs = pmag.get_dictitem(data, key, '', 'F') # get intensity data if len(Mrecs) > 0: break if len(AFZrecs) > 0 or len(TZrecs) > 0 or len(MZrecs) > 0 and len( Drecs) > 0 and len(Irecs) > 0 and len( Mrecs) > 0: # potential for stepwise demag curves print('zeq_magic.py -fsp pmag_specimens.txt -sav -fmt ' + fmt + ' -crd ' + crd) os.system('zeq_magic.py -sav -fmt ' + fmt + ' -crd ' + crd) # looking for thellier_magic possibilities if len( pmag.get_dictitem(data, 'magic_method_codes', 'LP-PI-TRM', 'has')) > 0: print('thellier_magic.py -fsp pmag_specimens.txt -sav -fmt ' + fmt) os.system('thellier_magic.py -sav -fmt ' + fmt) # looking for hysteresis possibilities if len( pmag.get_dictitem(data, 'magic_method_codes', 'LP-HYS', 'has')) > 0: # find hyst experiments print('quick_hyst.py -sav -fmt ' + fmt) os.system('quick_hyst.py -sav -fmt ' + fmt) if 'pmag_results.txt' in filelist: # start with measurement data data, file_type = pmag.magic_read( 'pmag_results.txt') # read in data print('number of datapoints: ', len(data)) if loc == './': data = pmag.get_dictitem( data, 'er_location_names', ':', 'has' ) # get all the concatenated location names from data file print('number of datapoints: ', len(data), loc) print('working on pmag_results directions') SiteDIs = pmag.get_dictitem(data, 'average_dec', "", 'F') # find decs print('number of directions: ', len(SiteDIs)) SiteDIs = pmag.get_dictitem(SiteDIs, 'average_inc', "", 'F') # find decs and incs print('number of directions: ', len(SiteDIs)) SiteDIs = pmag.get_dictitem( SiteDIs, 'data_type', 'i', 'has') # only individual results - not poles print('number of directions: ', len(SiteDIs)) SiteDIs_t = pmag.get_dictitem(SiteDIs, 'tilt_correction', '100', 'T') # tilt corrected coordinates print('number of directions: ', len(SiteDIs)) if len(SiteDIs_t) > 0: print('eqarea_magic.py -sav -crd t -fmt ' + fmt) os.system('eqarea_magic.py -sav -crd t -fmt ' + fmt) elif len(SiteDIs) > 0 and 'tilt_correction' not in SiteDIs[0].keys( ): print('eqarea_magic.py -sav -fmt ' + fmt) os.system('eqarea_magic.py -sav -fmt ' + fmt) else: SiteDIs_g = pmag.get_dictitem(SiteDIs, 'tilt_correction', '0', 'T') # geographic coordinates if len(SiteDIs_g) > 0: print('eqarea_magic.py -sav -crd g -fmt ' + fmt) os.system('eqarea_magic.py -sav -crd g -fmt ' + fmt) else: SiteDIs_s = pmag.get_dictitem(SiteDIs, 'tilt_correction', '-1', 'T') # sample coordinates if len(SiteDIs_s) > 0: print('eqarea_magic.py -sav -crd s -fmt ' + fmt) os.system('eqarea_magic.py -sav -crd s -fmt ' + fmt) else: SiteDIs_x = pmag.get_dictitem(SiteDIs, 'tilt_correction', '', 'T') # no coordinates if len(SiteDIs_x) > 0: print('eqarea_magic.py -sav -fmt ' + fmt) os.system('eqarea_magic.py -sav -fmt ' + fmt) print('working on pmag_results VGP map') VGPs = pmag.get_dictitem(SiteDIs, 'vgp_lat', "", 'F') # are there any VGPs? if len(VGPs) > 0: # YES! os.system( 'vgpmap_magic.py -prj moll -res c -sym ro 5 -sav -fmt png') print('working on pmag_results intensities') os.system( 'magic_select.py -f pmag_results.txt -key data_type i T -F tmp.txt' ) os.system( 'magic_select.py -f tmp.txt -key average_int 0. has -F tmp1.txt' ) os.system( "grab_magic_key.py -f tmp1.txt -key average_int | awk '{print $1*1e6}' >tmp2.txt" ) data, file_type = pmag.magic_read('tmp1.txt') # read in data locations = pmag.get_dictkey(data, 'er_location_names', "") histfile = 'LO:_' + locations[0] + '_intensities_histogram:_.' + fmt os.system( "histplot.py -b 1 -xlab 'Intensity (uT)' -sav -f tmp2.txt -F " + histfile) print( "histplot.py -b 1 -xlab 'Intensity (uT)' -sav -f tmp2.txt -F " + histfile) os.system('rm tmp*.txt') if 'rmag_hysteresis.txt' in filelist: # start with measurement data print('working on rmag_hysteresis') data, file_type = pmag.magic_read( 'rmag_hysteresis.txt') # read in data if loc == './': data = pmag.get_dictitem( data, 'er_location_name', '', 'T') # get all the blank location names from data file hdata = pmag.get_dictitem(data, 'hysteresis_bcr', '', 'F') hdata = pmag.get_dictitem(hdata, 'hysteresis_mr_moment', '', 'F') hdata = pmag.get_dictitem(hdata, 'hysteresis_ms_moment', '', 'F') hdata = pmag.get_dictitem(hdata, 'hysteresis_bc', '', 'F') # there are data for a dayplot if len(hdata) > 0: print('dayplot_magic.py -sav -fmt ' + fmt) os.system('dayplot_magic.py -sav -fmt ' + fmt) #if 'er_sites.txt' in filelist: # start with measurement data # print 'working on er_sites' #os.system('basemap_magic.py -sav -fmt '+fmt) if 'rmag_anisotropy.txt' in filelist: # do anisotropy plots if possible print('working on rmag_anisotropy') data, file_type = pmag.magic_read( 'rmag_anisotropy.txt') # read in data if loc == './': data = pmag.get_dictitem( data, 'er_location_name', '', 'T') # get all the blank location names from data file sdata = pmag.get_dictitem(data, 'anisotropy_tilt_correction', '-1', 'T') # get specimen coordinates gdata = pmag.get_dictitem(data, 'anisotropy_tilt_correction', '0', 'T') # get specimen coordinates tdata = pmag.get_dictitem(data, 'anisotropy_tilt_correction', '100', 'T') # get specimen coordinates if len(sdata) > 3: print('aniso_magic.py -x -B -crd s -sav -fmt ' + fmt) os.system('aniso_magic.py -x -B -crd s -sav -fmt ' + fmt) if len(gdata) > 3: os.system('aniso_magic.py -x -B -crd g -sav -fmt ' + fmt) if len(tdata) > 3: os.system('aniso_magic.py -x -B -crd t -sav -fmt ' + fmt) if loc != './': os.chdir('..') # change working directories to each location
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 customize_criteria.py DESCRIPTION Allows user to specify acceptance criteria, saves them in pmag_criteria.txt SYNTAX customize_criteria.py [-h][command line options] OPTIONS -h prints help message and quits -f IFILE, reads in existing criteria -F OFILE, writes to pmag_criteria format file DEFAULTS IFILE: pmag_criteria.txt OFILE: pmag_criteria.txt OUTPUT creates a pmag_criteria.txt formatted output file """ infile,critout="","pmag_criteria.txt" # parse command line options if '-h' in sys.argv: print main.__doc__ sys.exit() if '-f' in sys.argv: ind=sys.argv.index('-f') infile=sys.argv[ind+1] crit_data,file_type=pmag.magic_read(infile) if file_type!='pmag_criteria': print 'bad input file' print main.__doc__ sys.exit() print "Acceptance criteria read in from ", infile if '-F' in sys.argv: ind=sys.argv.index('-F') critout=sys.argv[ind+1] Dcrit,Icrit,nocrit=0,0,0 custom='1' crit=raw_input(" [0] Use no acceptance criteria?\n [1] Use default criteria\n [2] customize criteria \n ") if crit=='0': print 'Very very loose criteria saved in ',critout crit_data=pmag.default_criteria(1) pmag.magic_write(critout,crit_data,'pmag_criteria') sys.exit() crit_data=pmag.default_criteria(0) if crit=='1': print 'Default criteria saved in ',critout pmag.magic_write(critout,crit_data,'pmag_criteria') sys.exit() CritRec=crit_data[0] crit_keys=CritRec.keys() crit_keys.sort() print "Enter new threshold value.\n Return to keep default.\n Leave blank to not use as a criterion\n " for key in crit_keys: if key!='pmag_criteria_code' and key!='er_citation_names' and key!='criteria_definition' and CritRec[key]!="": print key, CritRec[key] new=raw_input('new value: ') if new != "": CritRec[key]=(new) pmag.magic_write(critout,[CritRec],'pmag_criteria') print "Criteria saved in pmag_criteria.txt"