code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
pole_lat, pole_lon = bc02(data) # get the pole for these parameters # get the declination and inclination for that pole ExpDec, ExpInc = vgp_di(pole_lat, pole_lon, data[1], data[2]) # convert the inclination to paleo latitude paleo_lat = magnetic_lat(ExpInc) if print_results: # print everything out print(' Age Paleolat. Dec. Inc. Pole_lat. Pole_Long.') print('%7.1f %7.1f %7.1f %7.1f %7.1f %7.1f\n' % (data[3], paleo_lat, ExpDec, ExpInc, pole_lat, pole_lon)) else: return [data[3], paleo_lat, ExpDec, ExpInc, pole_lat, pole_lon]
def apwp(data, print_results=False)
calculates expected pole positions and directions for given plate, location and age Parameters _________ data : [plate,lat,lon,age] plate : [NA, SA, AF, IN, EU, AU, ANT, GL] NA : North America SA : South America AF : Africa IN : India EU : Eurasia AU : Australia ANT: Antarctica GL : Greenland lat/lon : latitude/longitude in degrees N/E age : age in millions of years print_results : if True will print out nicely formatted results Returns _________ if print_results is False, [Age,Paleolat, Dec, Inc, Pole_lat, Pole_lon]
4.767505
3.811745
1.250741
low, k, iz = start, 0, 0 Tzero = [] f = open('chart.txt', 'w') vline = '\t%s\n' % ( ' | | | | | | | |') hline = '______________________________________________________________________________\n' f.write('file:_________________ field:___________uT\n\n\n') f.write('%s\n' % ( ' date | run# | zone I | zone II | zone III | start | sp | cool|')) f.write(hline) f.write('\t%s' % (' 0.0')) f.write(vline) f.write(hline) for k in range(len(Top)): for t in range(low, Top[k]+Int[k], Int[k]): if iz == 0: Tzero.append(t) # zero field first step f.write('%s \t %s' % ('Z', str(t)+'.'+str(iz))) f.write(vline) f.write(hline) if len(Tzero) > 1: f.write('%s \t %s' % ('P', str(Tzero[-2])+'.'+str(2))) f.write(vline) f.write(hline) iz = 1 # infield after zero field first f.write('%s \t %s' % ('I', str(t)+'.'+str(iz))) f.write(vline) f.write(hline) # f.write('%s \t %s'%('T',str(t)+'.'+str(3))) # print second zero field (tail check) # f.write(vline) # f.write(hline) elif iz == 1: # infield first step f.write('%s \t %s' % ('I', str(t)+'.'+str(iz))) f.write(vline) f.write(hline) iz = 0 # zero field step (after infield) f.write('%s \t %s' % ('Z', str(t)+'.'+str(iz))) f.write(vline) f.write(hline) try: low = Top[k]+Int[k+1] # increment to next temp step except: f.close() print("output stored in: chart.txt")
def chart_maker(Int, Top, start=100, outfile='chart.txt')
Makes a chart for performing IZZI experiments. Print out the file and tape it to the oven. This chart will help keep track of the different steps. Z : performed in zero field - enter the temperature XXX.0 in the sio formatted measurement file created by the LabView program I : performed in the lab field written at the top of the form P : a pTRM step - performed at the temperature and in the lab field. Parameters __________ Int : list of intervals [e.g., 50,10,5] Top : list of upper bounds for each interval [e.g., 500, 550, 600] start : first temperature step, default is 100 outfile : name of output file, default is 'chart.txt' Output _________ creates a file with: file: write down the name of the measurement file field: write down the lab field for the infield steps (in uT) the type of step (Z: zerofield, I: infield, P: pTRM step temperature of the step and code for SIO-like treatment steps XXX.0 [zero field] XXX.1 [in field] XXX.2 [pTRM check] - done in a lab field date : date the step was performed run # : an optional run number zones I-III : field in the zones in the oven start : time the run was started sp : time the setpoint was reached cool : time cooling started
3.932478
3.295902
1.193142
Basemap = None has_basemap = True has_cartopy = import_cartopy()[0] try: from mpl_toolkits.basemap import Basemap WARNINGS['has_basemap'] = True except ImportError: has_basemap = False # if they have installed cartopy, no warning is needed if has_cartopy: return has_basemap, False # if they haven't installed Basemap or cartopy, they need to be warned if not WARNINGS['basemap']: print( "-W- You haven't installed a module for plotting maps (cartopy or Basemap)") print(" Recommended: install cartopy. With conda:") print(" conda install cartopy") print( " For more information, see http://earthref.org/PmagPy/Cookbook#getting_python") except (KeyError, FileNotFoundError): has_basemap = False # if cartopy is installed, no warning is needed if has_cartopy: return has_basemap, False if not WARNINGS['basemap']: print('-W- Basemap is installed but could not be imported.') print(' You are probably missing a required environment variable') print( ' If you need to use Basemap, you will need to run this program or notebook in a conda env.') print(' For more on how to create a conda env, see: https://conda.io/docs/user-guide/tasks/manage-environments.html') print( ' Recommended alternative: install cartopy for plotting maps. With conda:') print(' conda install cartopy') if has_basemap and not has_cartopy: print("-W- You have installed Basemap but not cartopy.") print(" In the future, Basemap will no longer be supported.") print(" To continue to make maps, install using conda:") print(' conda install cartopy') WARNINGS['basemap'] = True return has_basemap, Basemap
def import_basemap()
Try to import Basemap and print out a useful help message if Basemap is either not installed or is missing required environment variables. Returns --------- has_basemap : bool Basemap : Basemap package if possible else None
4.196239
4.089678
1.026056
cartopy = None has_cartopy = True try: import cartopy WARNINGS['has_cartopy'] = True except ImportError: has_cartopy = False if not WARNINGS['cartopy']: print('-W- cartopy is not installed') print(' If you want to make maps, install using conda:') print(' conda install cartopy') WARNINGS['cartopy'] = True return has_cartopy, cartopy
def import_cartopy()
Try to import cartopy and print out a help message if it is not installed Returns --------- has_cartopy : bool cartopy : cartopy package if available else None
3.678018
3.751373
0.980446
ageBP = -1e9 if age_unit == "Years AD (+/-)" or age_unit == "Years Cal AD (+/-)": if age < 0: age = age+1 # to correct for there being no 0 AD ageBP = 1950-age elif age_unit == "Years BP" or age_unit == "Years Cal BP": ageBP = age elif age_unit == "ka": ageBP = age*1000 elif age_unit == "Ma": ageBP = age*1e6 elif age_unit == "Ga": ageBP = age*1e9 else: print("Age unit invalid. Age set to -1.0e9") return ageBP
def age_to_BP(age, age_unit)
Convert an age value into the equivalent in time Before Present(BP) where Present is 1950 Returns --------- ageBP : number
3.962179
3.92771
1.008776
if not input_dir_path: input_dir_path = output_dir_path input_dir_path = os.path.realpath(input_dir_path) output_dir_path = os.path.realpath(output_dir_path) return input_dir_path, output_dir_path
def fix_directories(input_dir_path, output_dir_path)
Take arguments input/output directories and fixes them. If no input_directory, default to output_dir_path for both. Then return realpath for both values. Parameters ---------- input_dir_path : str output_dir_path : str Returns --------- input_dir_path, output_dir_path
1.726475
1.559562
1.107026
#get parameters from kwargs.get(parameter_name, default_value) user = kwargs.get('user', '') magfile = kwargs.get('magfile') #do any extra formating you need to variables here #open magfile to start reading data try: infile=open(magfile,'r') except Exception as ex: print(("bad file path: ", magfile)) return False, "bad file path" #Depending on the dataset you may need to read in all data here put it in a list of dictionaries or something here. If you do just replace the "for line in infile.readlines():" bellow with "for d in data:" where data is the structure you put your data into #define the lists that hold each line of data for their respective tables SpecRecs,SampRecs,SiteRecs,LocRecs,MeasRecs=[],[],[],[],[] #itterate over the contence of the file for line in infile.readlines(): MeasRec,SpecRec,SampRec,SiteRec,LocRec={},{},{},{},{} #extract data from line and put it in variables #fill this line of the Specimen table using above variables if specimen!="" and specimen not in [x['specimen'] if 'specimen' in list(x.keys()) else "" for x in SpecRecs]: SpecRec['analysts']=user SpecRecs.append(SpecRec) #fill this line of the Sample table using above variables if sample!="" and sample not in [x['sample'] if 'sample' in list(x.keys()) else "" for x in SampRecs]: SampRec['analysts']=user SampRecs.append(SampRec) #fill this line of the Site table using above variables if site!="" and site not in [x['site'] if 'site' in list(x.keys()) else "" for x in SiteRecs]: SiteRec['analysts']=user SiteRecs.append(SiteRec) #fill this line of the Location table using above variables if location!="" and location not in [x['location'] if 'location' in list(x.keys()) else "" for x in LocRecs]: LocRec['analysts']=user LocRecs.append(LocRec) #Fill this line of Meas Table using data in line MeasRec['analysts']=user MeasRecs.append(MeasRec) #close your file object so Python3 doesn't throw an annoying warning infile.close() #open a Contribution object con = cb.Contribution(output_dir_path,read_tables=[]) #Create Magic Tables and add to a contribution 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) #figures out method codes for measuremet data con.add_magic_table_from_data(dtype='measurements', data=MeasOuts) #write to file con.write_table_to_file('specimens', custom_name=spec_file) con.write_table_to_file('samples', custom_name=samp_file) con.write_table_to_file('sites', custom_name=site_file) con.write_table_to_file('locations', custom_name=loc_file) meas_file = con.write_table_to_file('measurements', custom_name=meas_file) return True, meas_file
def convert(**kwargs)
EXAMPLE DOCSTRING for function (you would usually put the discription here) Parameters ----------- user : colon delimited list of analysts (default : "") magfile : input magnetometer file (required) Returns ----------- type - Tuple : (True or False indicating if conversion was sucessful, meas_file name written)
3.45007
3.299906
1.045506
inp,out="","" 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] f=open(file,'r') inp=f.readlines() if '-F' in sys.argv: ind=sys.argv.index('-F') o=sys.argv[ind+1] out=open(o,'w') if '-i' in sys.argv: cont=1 while cont==1: try: b=1e-6*float(input('B (in microtesla): <cntl-D to quit ')) lat=float(input('Latitude: ')) except: print("\nGood bye\n") sys.exit() vdm= pmag.b_vdm(b,lat) print('%10.3e '%(vdm)) if inp=="": inp = sys.stdin.readlines() # read from standard input for line in inp: vdm=spitout(line) if out=="": print('%10.3e'%(vdm)) else: out.write('%10.3e \n'%(vdm))
def main()
NAME b_vdm.py DESCRIPTION converts B (in microT) and (magnetic) latitude to V(A)DM INPUT (COMMAND LINE ENTRY) B (microtesla), latitude (positive north) OUTPUT V[A]DM SYNTAX b_vdm.py [command line options] [< filename] OPTIONS -h prints help and quits -i for interactive data entry -f FILE input file -F FILE output
3.722272
2.901158
1.28303
data_files = {} def cond(File, prefix): file_path = path.join(prefix, 'data_files', File) return (not File.startswith('!') and not File.endswith('~') and not File.endswith('#') and not File.endswith('.pyc') and not File.startswith('.') and path.exists(path.join(prefix, File))) for (dir_path, dirs, files) in os.walk(data_path): data_files[dir_path] = [f for f in files if cond(f, dir_path)] if not dirs: continue else: for Dir in dirs: do_walk(os.path.join(dir_path, Dir)) return data_files
def do_walk(data_path)
Walk through data_files and list all in dict format
3.503617
3.32664
1.0532
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
2.67217
2.314279
1.154644
if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-WD' in sys.argv: ind=sys.argv.index('-WD') dir_path=sys.argv[ind+1] # interactive entry if '-i' in sys.argv: infile=input("Magic txt file for unpacking? ") dir_path = '.' input_dir_path = '.' # non-interactive else: infile = pmag.get_named_arg("-f", reqd=True) # if -O flag is present, overwrite is False overwrite = pmag.get_flag_arg_from_sys("-O", true=False, false=True) # if -sep flag is present, sep is True sep = pmag.get_flag_arg_from_sys("-sep", true=True, false=False) data_model = pmag.get_named_arg("-DM", default_val=3, reqd=False) dir_path = pmag.get_named_arg("-WD", default_val=".", reqd=False) input_dir_path = pmag.get_named_arg("-ID", default_val=".", reqd=False) #if '-ID' not in sys.argv and '-WD' in sys.argv: # input_dir_path = dir_path if "-WD" not in sys.argv and "-ID" not in sys.argv: input_dir_path = os.path.split(infile)[0] if not input_dir_path: input_dir_path = "." ipmag.download_magic(infile, dir_path, input_dir_path, overwrite, True, data_model, sep)
def main()
NAME download_magic.py DESCRIPTION unpacks a magic formatted smartbook .txt file from the MagIC database into the tab delimited MagIC format txt files for use with the MagIC-Py programs. SYNTAX download_magic.py command line options] INPUT takes either the upload.txt file created by upload_magic.py or a file downloaded from the MagIC database (http://earthref.org/MagIC) OPTIONS -h prints help message and quits -i allows interactive entry of filename -f FILE specifies input file name -sep write location data to separate subdirectories (Location_*), (default False) -O do not overwrite duplicate Location_* directories while downloading -DM data model (2 or 3, default 3)
3.023526
2.577524
1.173035
args = sys.argv if "-h" in args: print(main.__doc__) sys.exit() pltspec = "" verbose = pmagplotlib.verbose dir_path = pmag.get_named_arg('-WD', '.') dir_path = os.path.realpath(dir_path) meas_file = pmag.get_named_arg('-f', 'measurements.txt') fmt = pmag.get_named_arg('-fmt', 'png') save_plots = False interactive = True if '-sav' in args: verbose = False save_plots = True interactive = False if '-spc' in args: ind = args.index("-spc") pltspec = args[ind+1] verbose = False save_plots = True ipmag.quick_hyst(dir_path, meas_file, save_plots, interactive, fmt, pltspec, verbose)
def main()
NAME quick_hyst.py DESCRIPTION makes plots of hysteresis data SYNTAX quick_hyst.py [command line options] OPTIONS -h prints help message and quits -f: specify input file, default is measurements.txt -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg]
3.136668
2.504101
1.252612
if x.ndim != 1: raise ValueError("smooth only accepts 1 dimension arrays.") if x.size < window_len: raise ValueError("Input vector needs to be bigger than window size.") if window_len<3: return x # numpy available windows if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError("Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'") # padding the beggining and the end of the signal with an average value to evoid edge effect start=[average(x[0:10])]*window_len end=[average(x[-10:])]*window_len s=start+list(x)+end #s=numpy.r_[2*x[0]-x[window_len:1:-1],x,2*x[-1]-x[-1:-window_len:-1]] if window == 'flat': #moving average w=ones(window_len,'d') else: w=eval('numpy.'+window+'(window_len)') y=numpy.convolve(old_div(w,w.sum()),s,mode='same') return array(y[window_len:-window_len])
def smooth(x,window_len,window='bartlett')
smooth the data using a sliding window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by padding the beginning and the end of the signal with average of the first (last) ten values of the signal, to evoid jumps at the beggining/end input: x: the input signal, equaly spaced! window_len: the dimension of the smoothing window window: type of window from numpy library ['flat','hanning','hamming','bartlett','blackman'] -flat window will produce a moving average smoothing. -Bartlett window is very similar to triangular window, but always ends with zeros at points 1 and n, -hanning,hamming,blackman are used for smoothing the Fourier transfrom for curie temperature calculation the default is Bartlett output: aray of the smoothed signal
2.301434
2.156344
1.067285
m_,x_,y_,xy_,x_2=0.,0.,0.,0.,0. for ix in range(i,i+n,1): x_=x_+x[ix] y_=y_+y[ix] xy_=xy_+x[ix]*y[ix] x_2=x_2+x[ix]**2 m= old_div(( (n*xy_) - (x_*y_) ), ( n*x_2-(x_)**2)) return(m)
def deriv1(x,y,i,n)
alternative way to smooth the derivative of a noisy signal using least square fit. x=array of x axis y=array of y axis n=smoothing factor i= position in this method the slope in position i is calculated by least square fit of n points before and after position.
3.273846
3.480453
0.940638
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
2.970755
2.4803
1.19774
if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file=input("Enter file name with dec, inc data: ") f=open(file,'r') data=f.readlines() elif '-f' in sys.argv: dat=[] ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') data=f.readlines() else: data = sys.stdin.readlines() # read from standard input ofile = "" if '-F' in sys.argv: ind = sys.argv.index('-F') ofile= sys.argv[ind+1] out = open(ofile, 'w + a') DIs= [] # set up list for dec inc data for line in data: # read in the data from standard input if '\t' in line: rec=line.split('\t') # split each line on space to get records else: rec=line.split() # split each line on space to get records DIs.append((float(rec[0]),float(rec[1]))) # fpars=pmag.fisher_mean(DIs) outstring='%7.1f %7.1f %i %10.4f %8.1f %7.1f %7.1f'%(fpars['dec'],fpars['inc'],fpars['n'],fpars['r'],fpars['k'],fpars['alpha95'], fpars['csd']) if ofile == "": print(outstring) else: out.write(outstring+'\n')
def main()
NAME gofish.py DESCRIPTION calculates fisher parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX gofish.py [options] [< filename] OPTIONS -h prints help message and quits -i for interactive filename entry -f FILE, specify input file -F FILE, specifies output file name < filename for reading from standard input OUTPUT mean dec, mean inc, N, R, k, a95, csd
3.690727
2.900126
1.272609
args = sys.argv if "-h" in args: print(main.__doc__) sys.exit() # # initialize variables Z = 1 # get arguments from the command line orient_file = pmag.get_named_arg("-f", reqd=True) data_model_num = int(float(pmag.get_named_arg("-DM", 3))) if data_model_num == 2: samp_file = pmag.get_named_arg("-Fsa", "er_samples.txt") site_file = pmag.get_named_arg("-Fsi", "er_sites.txt") else: samp_file = pmag.get_named_arg("-Fsa", "samples.txt") site_file = pmag.get_named_arg("-Fsi", "sites.txt") samp_con = pmag.get_named_arg("-ncn", "1") if "4" in samp_con: if "-" not in samp_con: print("option [4] must be in form 3-Z where Z is an integer") sys.exit() else: Z = samp_con.split("-")[1] #samp_con = "4" print(samp_con)#, Z) meths = pmag.get_named_arg("-mcd", 'FS-FD:SO-POM:SO-SUN') location_name = pmag.get_named_arg("-loc", "unknown") if "-Iso" in args: ignore = 0 else: ignore = 1 convert.huji_sample(orient_file, meths, location_name, samp_con, ignore)
def main()
NAME huji_sample_magic.py DESCRIPTION takes tab delimited Hebrew University sample file and converts to MagIC formatted tables SYNTAX huji_sample_magic.py [command line options] OPTIONS -f FILE: specify input file -Fsa FILE: specify sample output file, default is: samples.txt -Fsi FILE: specify site output file, default is: sites.txt -Iso: import sample orientation info - default is to set sample_az/dip to 0,0 -ncn NCON: specify naming convention: default is #1 below -mcd: specify sampling method codes as a colon delimited string: [default is: FS-FD:SO-POM:SO-SUN] 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 -loc: location name, default="unknown" -DM: data model number (MagIC 2 or 3, default 3) INPUT FORMAT Input files must be tab delimited: Samp Az Dip Dip_dir Dip Orientation convention: Lab arrow azimuth = mag_azimuth; Lab arrow dip = 90-field_dip e.g. field_dip is degrees from horizontal of drill direction Magnetic declination convention: Az is already corrected in file 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 ltauxe@ucsd.edu for help. OUTPUT output saved in samples will overwrite any existing files
4.003347
2.645711
1.513146
if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-f' in sys.argv: dat=[] ind=sys.argv.index('-f') file=sys.argv[ind+1] else: file = sys.stdin # read from standard input ofile="" if '-F' in sys.argv: ind = sys.argv.index('-F') ofile= sys.argv[ind+1] out = open(ofile, 'w + a') DIIs=numpy.loadtxt(file,dtype=numpy.float) # read in the data # vpars,R=pmag.vector_mean(DIIs) outstring='%7.1f %7.1f %10.3e %i'%(vpars[0],vpars[1],R,len(DIIs)) if ofile == "": print(outstring) else: out.write(outstring + "\n")
def main()
NAME vector_mean.py DESCRIPTION calculates vector mean of vector data INPUT FORMAT takes dec, inc, int from an input file SYNTAX vector_mean.py [command line options] [< filename] OPTIONS -h prints help message and quits -f FILE, specify input file -F FILE, specify output file < filename for reading from standard input OUTPUT mean dec, mean inc, R, N
4.288796
3.56875
1.201764
kappa, cutoff = 0, 180 rev, anti, boot = 0, 0, 0 spin,n,v,mm97 = 0,0,0,0 if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-f' in sys.argv: ind = sys.argv.index("-f") in_file = sys.argv[ind + 1] vgp_df=pd.read_csv(in_file,delim_whitespace=True,header=None) else: vgp_df=pd.read_csv(sys.stdin,delim_whitespace=True,header=None) if '-c' in sys.argv: ind = sys.argv.index('-c') cutoff = float(sys.argv[ind + 1]) if '-k' in sys.argv: ind = sys.argv.index('-k') kappa = float(sys.argv[ind + 1]) if '-n' in sys.argv: ind = sys.argv.index('-n') n = int(sys.argv[ind + 1]) if '-a' in sys.argv: anti = 1 if '-r' in sys.argv: rev=1 if '-b' in sys.argv: boot = 1 if '-v' in sys.argv: v = 1 if '-p' in sys.argv: spin = 1 if '-mm97' in sys.argv: mm97=1 # # if len(list(vgp_df.columns))==2: vgp_df.columns=['vgp_lon','vgp_lat'] vgp_df['dir_k'],vgp_df['dir_n_samples'],vgp_df['lat']=0,0,0 else: vgp_df.columns=['vgp_lon','vgp_lat','dir_k','dir_n_samples','lat'] N,S_B,low,high,cutoff=pmag.scalc_vgp_df(vgp_df,anti=anti,rev=rev,cutoff=cutoff,kappa=kappa,n=n,spin=spin,v=v,boot=boot,mm97=mm97) if high!=0: print(N, '%7.1f %7.1f %7.1f %7.1f ' % (S_B, low, high, cutoff)) else: print(N, '%7.1f %7.1f ' % (S_B, cutoff))
def main()
NAME scalc.py DESCRIPTION calculates Sb from VGP Long,VGP Lat,Directional kappa,Site latitude data SYNTAX scalc -h [command line options] [< standard input] INPUT takes space delimited files with PLong, PLat,[kappa, N_site, slat] OPTIONS -h prints help message and quits -f FILE: specify input file -c cutoff: specify VGP colatitude cutoff value -k cutoff: specify kappa cutoff -v : use the VanDammme criterion -a: use antipodes of reverse data: default is to use only normal -r use only reverse data, default is False -b: do a bootstrap for confidence -p: do relative to principle axis -n: set minimum n for samples (specimens) per site -mm97: correct for within site scatter (McElhinny & McFadden, 1997) NOTES if kappa, N_site, lat supplied, will consider within site scatter OUTPUT N Sb Sb_lower Sb_upper Co-lat. Cutoff
2.61408
2.164549
1.207679
the_slice = () for j in range(num_axes): if j == axis: the_slice = the_slice + (i,) else: the_slice = the_slice + (slice(None),) return the_slice
def all_but_axis(i, axis, num_axes)
Return a slice covering all combinations with coordinate i along axis. (Effectively the hyperplane perpendicular to axis at i.)
2.340682
2.361133
0.991338
"Apply an ordinary function to all values in an array." flat_ar = ravel(ar) out = zeros(len(flat_ar), flat_ar.typecode()) for i in range(len(flat_ar)): out[i] = f(flat_ar[i]) out.shape = ar.shape return out
def array_map(f, ar)
Apply an ordinary function to all values in an array.
3.115911
2.55021
1.221825
if not self.xdata or not self.ydata: return pos=event.GetPosition() width, height = self.canvas.get_width_height() pos[1] = height - pos[1] xpick_data,ypick_data = pos xdata_org = self.xdata ydata_org = self.ydata data_corrected = self.map.transData.transform(vstack([xdata_org,ydata_org]).T) xdata,ydata = data_corrected.T xdata = list(map(float,xdata)) ydata = list(map(float,ydata)) e = 4e0 index = None for i,(x,y) in enumerate(zip(xdata,ydata)): if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e: index = i break if index==None: print("Couldn't find point %.1f,%.1f"%(xpick_data,ypick_data)) self.change_selected(index)
def on_plot_select(self,event)
Select data point if cursor is in range of a data point @param: event -> the wx Mouseevent for that click
3.403823
3.445381
0.987938
if not self.xdata or not self.ydata: return pos=event.GetPosition() width, height = self.canvas.get_width_height() pos[1] = height - pos[1] xpick_data,ypick_data = pos xdata_org = self.xdata ydata_org = self.ydata data_corrected = self.map.transData.transform(vstack([xdata_org,ydata_org]).T) xdata,ydata = data_corrected.T xdata = list(map(float,xdata)) ydata = list(map(float,ydata)) e = 4e0 if self.plot_setting == "Zoom": self.canvas.SetCursor(wx.Cursor(wx.CURSOR_CROSS)) else: self.canvas.SetCursor(wx.Cursor(wx.CURSOR_ARROW)) for i,(x,y) in enumerate(zip(xdata,ydata)): if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e: self.canvas.SetCursor(wx.Cursor(wx.CURSOR_HAND)) break event.Skip()
def on_change_plot_cursor(self,event)
If mouse is over data point making it selectable change the shape of the cursor @param: event -> the wx Mouseevent for that click
3.035939
3.014339
1.007166
return_dict = {} for i,ctrl in enumerate(self.list_ctrls): if hasattr(self.parse_funcs,'__getitem__') and len(self.parse_funcs)>i and hasattr(self.parse_funcs[i],'__call__'): try: return_dict[self.inputs[i]] = self.parse_funcs[i](ctrl.GetValue()) except: return_dict[self.inputs[i]] = ctrl.GetValue() else: return_dict[self.inputs[i]] = ctrl.GetValue() return ('' not in list(return_dict.values()), return_dict)
def get_values(self)
Applies parsing functions to each input as specified in init before returning a tuple with first entry being a boolean which specifies if the user entered all values and a second entry which is a dictionary of input names to parsed values.
2.985225
2.415845
1.235686
if '-h' in sys.argv: print(main.__doc__) sys.exit() else: data_model_num = pmag.get_named_arg("-DM", 3) dataframe = extractor.command_line_dataframe([['cat', False, 0], ['F', False, ''], ['f', False, '']]) checked_args = extractor.extract_and_check_args(sys.argv, dataframe) dir_path, concat = extractor.get_vars(['WD', 'cat'], checked_args) data_model_num = int(float(data_model_num)) if data_model_num == 2: ipmag.upload_magic2(concat, dir_path) else: ipmag.upload_magic(concat, dir_path)
def main()
NAME upload_magic.py DESCRIPTION This program will prepare your MagIC text files for uploading to the MagIC database it will check for all the MagIC text files and skip the missing ones SYNTAX upload_magic.py INPUT MagIC txt files OPTIONS -h prints help message and quits -all include all the measurement data, default is only those used in interpretations -DM specify which MagIC data model number to use (2 or 3). Default is 3. OUTPUT upload file: file for uploading to MagIC database
5.731437
4.934551
1.161491
''' #================================================= /poly fit for every SF grid data #================================================= ''' X, Y = np.meshgrid(x, y, copy=False) X = X.flatten() Y = Y.flatten() A = np.array([np.ones(len(X)), X, X**2, Y, Y**2, X*Y]).T Z = np.array(z) B = Z.flatten() # print(A.shape,B.shape) coeff, r, rank, s = np.linalg.lstsq(A, B, rcond=None) return -coeff[5]
def d2_func(x, y, z)
#================================================= /poly fit for every SF grid data #=================================================
4.330457
2.670203
1.621771
''' #================================================= /process the grid data /convert to list data for poly fitting #================================================= ''' a = [] b = [] M = [] for i in data: a.append(i[0]) # np.array([i[1] for i in data], dtype=np.float64) b.append(i[1]) # np.array([i[0] for i in data], dtype=np.float64) M.append(i[2]) # np.array([i[2] for i in data], dtype=np.float64) a = np.array(a, dtype=np.float64).tolist() b = np.array(b, dtype=np.float64).tolist() M = np.array(M, dtype=np.float64).tolist() a = list(set(a)) b = list(set(b)) return a, b, M
def grid_list(data)
#================================================= /process the grid data /convert to list data for poly fitting #=================================================
2.453381
1.780646
1.377804
#print("-I- getting data model, please be patient!!!!") url = 'http://earthref.org/services/MagIC-data-model.txt' offline = True # always get cached data model, as 2.5 is now static #try: # data = urllib2.urlopen(url) #except urllib2.URLError: # print '-W- Unable to fetch data model online\nTrying to use cached data model instead' # offline = True #except httplib.BadStatusLine: # print '-W- Website: {} not responding\nTrying to use cached data model instead'.format(url) # offline = True if offline: data = get_data_offline() data_model, file_type = pmag.magic_read(None, data) if file_type in ('bad file', 'empty_file'): print('-W- Unable to read online data model.\nTrying to use cached data model instead') data = get_data_offline() data_model, file_type = pmag.magic_read(None, data) ref_dicts = [d for d in data_model if d['column_nmb'] != '>>>>>>>>>>'] file_types = [d['field_name'] for d in data_model if d['column_nmb'] == 'tab delimited'] file_types.insert(0, file_type) complete_ref = {} dictionary = {} n = 0 for d in ref_dicts: if d['field_name'] in file_types: complete_ref[file_types[n]] = dictionary n += 1 dictionary = {} else: dictionary[d['field_name_oracle']] = {'data_type': d['data_type'], 'data_status': d['data_status']} return complete_ref
def get_data_model()
try to grab the up to date data model document from the EarthRef site. if that fails, try to get the data model document from the PmagPy directory on the user's computer. if that fails, return False. data_model is a set of nested dictionaries that looks like this: {'magic_contributions': {'group_userid': {'data_status': 'Optional', 'data_type': 'String(10)'}, 'activate': {'data_status': 'Optional', 'data_type': 'String(1)'}, ....}, 'er_synthetics': {'synthetic_type': {'data_status': 'Required', 'data_type': 'String(50)'}, 'er_citation_names': {'data_status': 'Required', 'data_type': 'List(500)'}, ...}, .... } the top level keys are the file types. the second level keys are the possible headers for that file type. the third level keys are data_type and data_status for that header.
4.552768
4.20574
1.082513
container = [] new_list = [] for line in lines: if '>>>' in line: container.append(new_list) new_list = [] else: new_list.append(line) container.append(new_list) return container
def split_lines(lines)
split a MagIC upload format file into lists. the lists are split by the '>>>' lines between file_types.
2.35145
2.099506
1.120002
data_dictionaries = [] for chunk in data[:-1]: if not chunk: continue data1 = data[0] file_type = chunk[0].split('\t')[1].strip('\n').strip('\r') keys = chunk[1].split('\t') clean_keys = [] # remove new-line characters, and any empty string keys for key in keys: clean_key = key.strip('\n').strip('\r') if clean_key: clean_keys.append(clean_key) for line in chunk[2:]: data_dict = {} for key in clean_keys: data_dict[key] = "" line = line.split('\t') for n, key in enumerate(clean_keys): data_dict[key] = line[n].strip('\n').strip('\r') data_dict['file_type'] = file_type data_dictionaries.append(data_dict) return data_dictionaries
def get_dicts(data)
data must be a list of lists, from a tab delimited file. in each list: the first list item will be the type of data. the second list item will be a tab delimited list of headers. the remaining items will be a tab delimited list following the list of headers.
2.606145
2.521809
1.033443
if ghfile != "": lmgh = np.loadtxt(ghfile) gh = [] lmgh = np.loadtxt(ghfile).transpose() gh.append(lmgh[2][0]) for i in range(1, lmgh.shape[1]): gh.append(lmgh[2][i]) gh.append(lmgh[3][i]) if len(gh) == 0: print('no valid gh file') return mod = 'custom' if mod == "": x, y, z, f = pmag.doigrf( input_list[3] % 360., input_list[2], input_list[1], input_list[0]) elif mod != 'custom': x, y, z, f = pmag.doigrf( input_list[3] % 360., input_list[2], input_list[1], input_list[0], mod=mod) else: x, y, z, f = pmag.docustom( input_list[3] % 360., input_list[2], input_list[1], gh) igrf_array = pmag.cart2dir((x, y, z)) return igrf_array
def igrf(input_list, mod='', ghfile="")
Determine Declination, Inclination and Intensity from the IGRF model. (http://www.ngdc.noaa.gov/IAGA/vmod/igrf.html) Parameters ---------- input_list : list with format [Date, Altitude, Latitude, Longitude] date must be in decimal year format XXXX.XXXX (Common Era) mod : desired model "" : Use the IGRF custom : use values supplied in ghfile or choose from this list ['arch3k','cals3k','pfm9k','hfm10k','cals10k.2','cals10k.1b'] where: arch3k (Korte et al., 2009) cals3k (Korte and Constable, 2011) cals10k.1b (Korte et al., 2011) pfm9k (Nilsson et al., 2014) hfm10k is the hfm.OL1.A1 of Constable et al. (2016) cals10k.2 (Constable et al., 2016) the first four of these models, are constrained to agree with gufm1 (Jackson et al., 2000) for the past four centuries gh : path to file with l m g h data Returns ------- igrf_array : array of IGRF values (0: dec; 1: inc; 2: intensity (in nT)) Examples -------- >>> local_field = ipmag.igrf([2013.6544, .052, 37.87, -122.27]) >>> local_field array([ 1.39489916e+01, 6.13532008e+01, 4.87452644e+04]) >>> ipmag.igrf_print(local_field) Declination: 13.949 Inclination: 61.353 Intensity: 48745.264 nT
2.731758
2.865263
0.953406
dd = float(degrees) + old_div(float(minutes), 60) + \ old_div(float(seconds), (60 * 60)) return dd
def dms2dd(degrees, minutes, seconds)
Convert latitude/longitude of a location that is in degrees, minutes, seconds to decimal degrees Parameters ---------- degrees : degrees of latitude/longitude minutes : minutes of latitude/longitude seconds : seconds of latitude/longitude Returns ------- degrees : decimal degrees of location Examples -------- Convert 180 degrees 4 minutes 23 seconds to decimal degrees: >>> ipmag.dms2dd(180,4,23) 180.07305555555556
2.925851
4.758879
0.614819
if di_block is None: di_block = make_di_block(dec, inc) return pmag.fisher_mean(di_block) else: return pmag.fisher_mean(di_block)
def fisher_mean(dec=None, inc=None, di_block=None)
Calculates the Fisher mean and associated parameters from either a list of declination values and a separate list of inclination values or from a di_block (a nested list a nested list of [dec,inc,1.0]). Returns a dictionary with the Fisher mean and statistical parameters. Parameters ---------- dec : list of declinations or longitudes inc : list of inclinations or latitudes di_block : a nested list of [dec,inc,1.0] A di_block can be provided instead of dec, inc lists in which case it will be used. Either dec, inc lists or a di_block need to be provided. Returns ------- fisher_mean : dictionary containing the Fisher mean parameters Examples -------- Use lists of declination and inclination to calculate a Fisher mean: >>> ipmag.fisher_mean(dec=[140,127,142,136],inc=[21,23,19,22]) {'alpha95': 7.292891411309177, 'csd': 6.4097743211340896, 'dec': 136.30838974272072, 'inc': 21.347784026899987, 'k': 159.69251473636305, 'n': 4, 'r': 3.9812138971889026} Use a di_block to calculate a Fisher mean (will give the same output as the example with the lists): >>> ipmag.fisher_mean(di_block=[[140,21],[127,23],[142,19],[136,22]])
2.752281
3.368235
0.817129
''' The angle from the true mean within which a chosen percentage of directions lie can be calculated from the Fisher distribution. This function uses the calculated Fisher concentration parameter to estimate this angle from directional data. The 63 percent confidence interval is often called the angular standard deviation. Parameters ---------- dec : list of declinations or longitudes inc : list of inclinations or latitudes di_block : a nested list of [dec,inc,1.0] A di_block can be provided instead of dec, inc lists in which case it will be used. Either dec, inc lists or a di_block need to be provided. confidence : 50 percent, 63 percent or 95 percent Returns ------- theta : critical angle of interest from the mean which contains the percentage of directions specified by the confidence parameter ''' if di_block is None: di_block = make_di_block(dec, inc) mean = pmag.fisher_mean(di_block) else: mean = pmag.fisher_mean(di_block) if confidence == 50: theta = old_div(67.5, np.sqrt(mean['k'])) if confidence == 63: theta = old_div(81, np.sqrt(mean['k'])) if confidence == 95: theta = old_div(140, np.sqrt(mean['k'])) return theta
def fisher_angular_deviation(dec=None, inc=None, di_block=None, confidence=95)
The angle from the true mean within which a chosen percentage of directions lie can be calculated from the Fisher distribution. This function uses the calculated Fisher concentration parameter to estimate this angle from directional data. The 63 percent confidence interval is often called the angular standard deviation. Parameters ---------- dec : list of declinations or longitudes inc : list of inclinations or latitudes di_block : a nested list of [dec,inc,1.0] A di_block can be provided instead of dec, inc lists in which case it will be used. Either dec, inc lists or a di_block need to be provided. confidence : 50 percent, 63 percent or 95 percent Returns ------- theta : critical angle of interest from the mean which contains the percentage of directions specified by the confidence parameter
5.229063
1.550914
3.371602
if di_block is None: di_block = make_di_block(dec, inc) return pmag.dobingham(di_block) else: return pmag.dobingham(di_block)
def bingham_mean(dec=None, inc=None, di_block=None)
Calculates the Bingham mean and associated statistical parameters from either a list of declination values and a separate list of inclination values or from a di_block (a nested list a nested list of [dec,inc,1.0]). Returns a dictionary with the Bingham mean and statistical parameters. Parameters ---------- dec: list of declinations inc: list of inclinations or di_block: a nested list of [dec,inc,1.0] A di_block can be provided instead of dec, inc lists in which case it will be used. Either dec, inc lists or a di_block need to passed to the function. Returns --------- bpars : dictionary containing the Bingham mean and associated statistics. Examples -------- Use lists of declination and inclination to calculate a Bingham mean: >>> ipmag.bingham_mean(dec=[140,127,142,136],inc=[21,23,19,22]) {'Edec': 220.84075754194598, 'Einc': -13.745780972597291, 'Eta': 9.9111522306938742, 'Zdec': 280.38894136954474, 'Zeta': 9.8653370276451113, 'Zinc': 64.23509410796224, 'dec': 136.32637167111312, 'inc': 21.34518678073179, 'n': 4} Use a di_block to calculate a Bingham mean (will give the same output as the example with the lists): >>> ipmag.bingham_mean(di_block=[[140,21],[127,23],[142,19],[136,22]])
3.767063
4.51536
0.834277
if di_block is None: di_block = make_di_block(dec, inc) return pmag.dokent(di_block, len(di_block)) else: return pmag.dokent(di_block, len(di_block))
def kent_mean(dec=None, inc=None, di_block=None)
Calculates the Kent mean and associated statistical parameters from either a list of declination values and a separate list of inclination values or from a di_block (a nested list a nested list of [dec,inc,1.0]). Returns a dictionary with the Kent mean and statistical parameters. Parameters ---------- dec: list of declinations inc: list of inclinations or di_block: a nested list of [dec,inc,1.0] A di_block can be provided instead of dec, inc lists in which case it will be used. Either dec, inc lists or a di_block need to passed to the function. Returns ---------- kpars : dictionary containing Kent mean and associated statistics. Examples -------- Use lists of declination and inclination to calculate a Kent mean: >>> ipmag.kent_mean(dec=[140,127,142,136],inc=[21,23,19,22]) {'Edec': 280.38683553668795, 'Einc': 64.236598921744289, 'Eta': 0.72982112760919715, 'Zdec': 40.824690028412761, 'Zeta': 6.7896823241008795, 'Zinc': 13.739412321974067, 'dec': 136.30838974272072, 'inc': 21.347784026899987, 'n': 4} Use a di_block to calculate a Kent mean (will give the same output as the example with the lists): >>> ipmag.kent_mean(di_block=[[140,21],[127,23],[142,19],[136,22]])
3.453635
4.722939
0.731247
print('Dec: ' + str(round(mean_dictionary['dec'], 1)) + ' Inc: ' + str(round(mean_dictionary['inc'], 1))) print('Number of directions in mean (n): ' + str(mean_dictionary['n'])) print('Angular radius of 95% confidence (a_95): ' + str(round(mean_dictionary['alpha95'], 1))) print('Precision parameter (k) estimate: ' + str(round(mean_dictionary['k'], 1)))
def print_direction_mean(mean_dictionary)
Does a pretty job printing a Fisher mean and associated statistics for directional data. Parameters ---------- mean_dictionary: output dictionary of pmag.fisher_mean Examples -------- Generate a Fisher mean using ``ipmag.fisher_mean`` and then print it nicely using ``ipmag.print_direction_mean`` >>> my_mean = ipmag.fisher_mean(di_block=[[140,21],[127,23],[142,19],[136,22]]) >>> ipmag.print_direction_mean(my_mean) Dec: 136.3 Inc: 21.3 Number of directions in mean (n): 4 Angular radius of 95% confidence (a_95): 7.3 Precision parameter (k) estimate: 159.7
3.868104
1.673053
2.312004
print('Plon: ' + str(round(mean_dictionary['dec'], 1)) + ' Plat: ' + str(round(mean_dictionary['inc'], 1))) print('Number of directions in mean (n): ' + str(mean_dictionary['n'])) print('Angular radius of 95% confidence (A_95): ' + str(round(mean_dictionary['alpha95'], 1))) print('Precision parameter (k) estimate: ' + str(round(mean_dictionary['k'], 1)))
def print_pole_mean(mean_dictionary)
Does a pretty job printing a Fisher mean and associated statistics for mean paleomagnetic poles. Parameters ---------- mean_dictionary: output dictionary of pmag.fisher_mean Examples -------- Generate a Fisher mean using ``ipmag.fisher_mean`` and then print it nicely using ``ipmag.print_pole_mean`` >>> my_mean = ipmag.fisher_mean(di_block=[[140,21],[127,23],[142,19],[136,22]]) >>> ipmag.print_pole_mean(my_mean) Plon: 136.3 Plat: 21.3 Number of directions in mean (n): 4 Angular radius of 95% confidence (A_95): 7.3 Precision parameter (k) estimate: 159.7
4.533714
1.800779
2.517641
directions = [] declinations = [] inclinations = [] if di_block == True: for data in range(n): d, i = pmag.fshdev(k) drot, irot = pmag.dodirot(d, i, dec, inc) directions.append([drot, irot, 1.]) return directions else: for data in range(n): d, i = pmag.fshdev(k) drot, irot = pmag.dodirot(d, i, dec, inc) declinations.append(drot) inclinations.append(irot) return declinations, inclinations
def fishrot(k=20, n=100, dec=0, inc=90, di_block=True)
Generates Fisher distributed unit vectors from a specified distribution using the pmag.py fshdev and dodirot functions. Parameters ---------- k : kappa precision parameter (default is 20) n : number of vectors to determine (default is 100) dec : mean declination of distribution (default is 0) inc : mean inclination of distribution (default is 90) di_block : this function returns a nested list of [dec,inc,1.0] as the default if di_block = False it will return a list of dec and a list of inc Returns --------- di_block : a nested list of [dec,inc,1.0] (default) dec, inc : a list of dec and a list of inc (if di_block = False) Examples -------- >>> ipmag.fishrot(k=20, n=5, dec=40, inc=60) [[44.766285502555775, 37.440866867657235, 1.0], [33.866315796883725, 64.732532250463436, 1.0], [47.002912770597163, 54.317853800896977, 1.0], [36.762165614432547, 56.857240672884252, 1.0], [71.43950604474395, 59.825830945715431, 1.0]]
2.839666
2.108287
1.346907
tk_03_output = [] for k in range(n): gh = pmag.mktk03(8, k, G2, G3) # terms and random seed # get a random longitude, between 0 and 359 lon = random.randint(0, 360) vec = pmag.getvec(gh, lat, lon) # send field model and lat to getvec vec[0] += dec if vec[0] >= 360.: vec[0] -= 360. if k % 2 == 0 and rev == 'yes': vec[0] += 180. vec[1] = -vec[1] tk_03_output.append([vec[0], vec[1], vec[2]]) return tk_03_output
def tk03(n=100, dec=0, lat=0, rev='no', G2=0, G3=0)
Generates vectors drawn from the TK03.gad model of secular variation (Tauxe and Kent, 2004) at given latitude and rotated about a vertical axis by the given declination. Return a nested list of of [dec,inc,intensity]. Parameters ---------- n : number of vectors to determine (default is 100) dec : mean declination of data set (default is 0) lat : latitude at which secular variation is simulated (default is 0) rev : if reversals are to be included this should be 'yes' (default is 'no') G2 : specify average g_2^0 fraction (default is 0) G3 : specify average g_3^0 fraction (default is 0) Returns ---------- tk_03_output : a nested list of declination, inclination, and intensity (in nT) Examples -------- >>> ipmag.tk03(n=5, dec=0, lat=0) [[14.752502674158681, -36.189370642603834, 16584.848620957589], [9.2859465437113311, -10.064247301056071, 17383.950391596223], [2.4278460589582913, 4.8079990844938019, 18243.679003572055], [352.93759572283585, 0.086693343935840397, 18524.551174838372], [352.48366219759953, 11.579098286352332, 24928.412830772766]]
4.65096
4.308976
1.079366
try: length = len(incs) incs_unsquished = [] for n in range(0, length): inc_rad = np.deg2rad(incs[n]) # convert to radians inc_new_rad = (old_div(1., f)) * np.tan(inc_rad) # convert back to degrees inc_new = np.rad2deg(np.arctan(inc_new_rad)) incs_unsquished.append(inc_new) return incs_unsquished except: inc_rad = np.deg2rad(incs) # convert to radians inc_new_rad = (old_div(1., f)) * np.tan(inc_rad) inc_new = np.rad2deg(np.arctan(inc_new_rad)) # convert back to degrees return inc_new
def unsquish(incs, f)
This function applies uses a flattening factor (f) to unflatten inclination data (incs) and returns 'unsquished' values. Parameters ---------- incs : list of inclination values or a single value f : unflattening factor (between 0.0 and 1.0) Returns ---------- incs_unsquished : List of unflattened inclinations (in degrees) Examples -------- Take a list of inclinations, flatten them using ``ipmag.squish`` and then use ``ipmag.squish`` and the flattening factor to unflatten them. >>> inclinations = [43,47,41] >>> squished_incs = ipmag.squish(inclinations,0.4) >>> ipmag.unsquish(squished_incs,0.4) [43.0, 47.0, 41.0]
2.099882
2.081587
1.008789
try: length = len(incs) incs_squished = [] for n in range(0, length): inc_rad = incs[n] * np.pi / 180. # convert to radians inc_new_rad = f * np.tan(inc_rad) inc_new = np.arctan(inc_new_rad) * 180. / \ np.pi # convert back to degrees incs_squished.append(inc_new) return incs_squished except: inc_rad = incs * np.pi / 180. # convert to radians inc_new_rad = f * np.tan(inc_rad) inc_new = np.arctan(inc_new_rad) * 180. / \ np.pi # convert back to degrees return inc_new
def squish(incs, f)
This function applies an flattening factor (f) to inclination data (incs) and returns 'squished' values. Parameters ---------- incs : list of inclination values or a single value f : flattening factor (between 0.0 and 1.0) Returns --------- incs_squished : List of flattened directions (in degrees) Examples -------- Take a list of inclinations, flatten them. >>> inclinations = [43,47,41] >>> ipmag.squish(inclinations,0.4) [20.455818908027187, 23.216791019112204, 19.173314360172309]
1.872402
1.878303
0.996859
if di_block is None: dec_flip = [] inc_flip = [] for n in range(0, len(dec)): dec_flip.append((dec[n] - 180.) % 360.0) inc_flip.append(-inc[n]) return dec_flip, inc_flip else: dflip = [] for rec in di_block: d, i = (rec[0] - 180.) % 360., -rec[1] dflip.append([d, i, 1.0]) return dflip
def do_flip(dec=None, inc=None, di_block=None)
This function returns the antipode (i.e. it flips) of directions. The function can take dec and inc as seperate lists if they are of equal length and explicitly specified or are the first two arguments. It will then return a list of flipped decs and a list of flipped incs. If a di_block (a nested list of [dec, inc, 1.0]) is specified then it is used and the function returns a di_block with the flipped directions. Parameters ---------- dec: list of declinations inc: list of inclinations or di_block: a nested list of [dec, inc, 1.0] A di_block can be provided instead of dec, inc lists in which case it will be used. Either dec, inc lists or a di_block need to passed to the function. Returns ---------- dec_flip, inc_flip : list of flipped declinations and inclinations or dflip : a nested list of [dec, inc, 1.0] Examples ---------- Lists of declination and inclination can be flipped to their antipodes: >>> decs = [1.0, 358.0, 2.0] >>> incs = [10.0, 12.0, 8.0] >>> ipmag.do_flip(decs, incs) ([181.0, 178.0, 182.0], [-10.0, -12.0, -8.0]) The function can also take a di_block and returns a flipped di_block: >>> directions = [[1.0,10.0],[358.0,12.0,],[2.0,8.0]] >>> ipmag.do_flip(di_block=directions) [[181.0, -10.0, 1.0], [178.0, -12.0, 1.0], [182.0, -8.0, 1.0]]
2.636766
2.198636
1.199274
rad = old_div(np.pi, 180.) paleo_lat = old_div(np.arctan(0.5 * np.tan(inc * rad)), rad) if a95 is not None: paleo_lat_max = old_div( np.arctan(0.5 * np.tan((inc + a95) * rad)), rad) paleo_lat_min = old_div( np.arctan(0.5 * np.tan((inc - a95) * rad)), rad) return paleo_lat, paleo_lat_max, paleo_lat_min else: return paleo_lat
def lat_from_inc(inc, a95=None)
Calculate paleolatitude from inclination using the dipole equation Required Parameter ---------- inc: (paleo)magnetic inclination in degrees Optional Parameter ---------- a95: 95% confidence interval from Fisher mean Returns ---------- if a95 is provided paleo_lat, paleo_lat_max, paleo_lat_min are returned otherwise, it just returns paleo_lat
1.879106
1.636391
1.148323
ref_loc = (ref_loc_lon, ref_loc_lat) pole = (pole_plon, pole_plat) paleo_lat = 90 - pmag.angle(pole, ref_loc) return float(paleo_lat)
def lat_from_pole(ref_loc_lon, ref_loc_lat, pole_plon, pole_plat)
Calculate paleolatitude for a reference location based on a paleomagnetic pole Required Parameters ---------- ref_loc_lon: longitude of reference location in degrees ref_loc_lat: latitude of reference location pole_plon: paleopole longitude in degrees pole_plat: paleopole latitude in degrees
3.13369
3.3403
0.938146
rad = old_div(np.pi, 180.) inc = old_div(np.arctan(2 * np.tan(lat * rad)), rad) return inc
def inc_from_lat(lat)
Calculate inclination predicted from latitude using the dipole equation Parameter ---------- lat : latitude in degrees Returns ------- inc : inclination calculated using the dipole equation
4.318492
4.507553
0.958057
# make the perimeter plt.figure(num=fignum,) plt.clf() plt.axis("off") Dcirc = np.arange(0, 361.) Icirc = np.zeros(361, 'f') Xcirc, Ycirc = [], [] for k in range(361): XY = pmag.dimap(Dcirc[k], Icirc[k]) Xcirc.append(XY[0]) Ycirc.append(XY[1]) plt.plot(Xcirc, Ycirc, 'k') # put on the tick marks Xsym, Ysym = [], [] for I in range(10, 100, 10): XY = pmag.dimap(0., I) Xsym.append(XY[0]) Ysym.append(XY[1]) plt.plot(Xsym, Ysym, 'k+') Xsym, Ysym = [], [] for I in range(10, 90, 10): XY = pmag.dimap(90., I) Xsym.append(XY[0]) Ysym.append(XY[1]) plt.plot(Xsym, Ysym, 'k+') Xsym, Ysym = [], [] for I in range(10, 90, 10): XY = pmag.dimap(180., I) Xsym.append(XY[0]) Ysym.append(XY[1]) plt.plot(Xsym, Ysym, 'k+') Xsym, Ysym = [], [] for I in range(10, 90, 10): XY = pmag.dimap(270., I) Xsym.append(XY[0]) Ysym.append(XY[1]) plt.plot(Xsym, Ysym, 'k+') for D in range(0, 360, 10): Xtick, Ytick = [], [] for I in range(4): XY = pmag.dimap(D, I) Xtick.append(XY[0]) Ytick.append(XY[1]) plt.plot(Xtick, Ytick, 'k') plt.axis("equal") plt.axis((-1.05, 1.05, -1.05, 1.05))
def plot_net(fignum)
Draws circle and tick marks for equal area projection.
1.767205
1.734628
1.01878
X_down = [] X_up = [] Y_down = [] Y_up = [] color_down = [] color_up = [] if di_block is not None: di_lists = unpack_di_block(di_block) if len(di_lists) == 3: dec, inc, intensity = di_lists if len(di_lists) == 2: dec, inc = di_lists try: length = len(dec) for n in range(len(dec)): XY = pmag.dimap(dec[n], inc[n]) if inc[n] >= 0: X_down.append(XY[0]) Y_down.append(XY[1]) if type(color) == list: color_down.append(color[n]) else: color_down.append(color) else: X_up.append(XY[0]) Y_up.append(XY[1]) if type(color) == list: color_up.append(color[n]) else: color_up.append(color) except: XY = pmag.dimap(dec, inc) if inc >= 0: X_down.append(XY[0]) Y_down.append(XY[1]) color_down.append(color) else: X_up.append(XY[0]) Y_up.append(XY[1]) color_up.append(color) if len(X_up) > 0: plt.scatter(X_up, Y_up, facecolors='none', edgecolors=color_up, s=markersize, marker=marker, label=label,alpha=alpha) if len(X_down) > 0: plt.scatter(X_down, Y_down, facecolors=color_down, edgecolors=edge, s=markersize, marker=marker, label=label,alpha=alpha) if legend == 'yes': plt.legend(loc=2) plt.tight_layout() if title != "": plt.title(title)
def plot_di(dec=None, inc=None, di_block=None, color='k', marker='o', markersize=20, legend='no', label='', title='', edge='',alpha=1)
Plot declination, inclination data on an equal area plot. Before this function is called a plot needs to be initialized with code that looks something like: >fignum = 1 >plt.figure(num=fignum,figsize=(10,10),dpi=160) >ipmag.plot_net(fignum) Required Parameters ----------- dec : declination being plotted inc : inclination being plotted or di_block: a nested list of [dec,inc,1.0] (di_block can be provided instead of dec, inc in which case it will be used) Optional Parameters (defaults are used if not specified) ----------- color : the default color is black. Other colors can be chosen (e.g. 'r') marker : the default marker is a circle ('o') markersize : default size is 20 label : the default label is blank ('') legend : the default is no legend ('no'). Putting 'yes' will plot a legend. edge : marker edge color - if blank, is color of marker alpha : opacity
1.663607
1.720863
0.966728
DI_dimap = pmag.dimap(dec, inc) if inc < 0: plt.scatter(DI_dimap[0], DI_dimap[1], edgecolors=color, facecolors='white', marker=marker, s=markersize, label=label) if inc >= 0: plt.scatter(DI_dimap[0], DI_dimap[1], edgecolors=color, facecolors=color, marker=marker, s=markersize, label=label) Xcirc, Ycirc = [], [] Da95, Ia95 = pmag.circ(dec, inc, a95) if legend == 'yes': plt.legend(loc=2) for k in range(len(Da95)): XY = pmag.dimap(Da95[k], Ia95[k]) Xcirc.append(XY[0]) Ycirc.append(XY[1]) plt.plot(Xcirc, Ycirc, c=color) plt.tight_layout()
def plot_di_mean(dec, inc, a95, color='k', marker='o', markersize=20, label='', legend='no')
Plot a mean direction (declination, inclination) with alpha_95 ellipse on an equal area plot. Before this function is called, a plot needs to be initialized with code that looks something like: >fignum = 1 >plt.figure(num=fignum,figsize=(10,10),dpi=160) >ipmag.plot_net(fignum) Required Parameters ----------- dec : declination of mean being plotted inc : inclination of mean being plotted a95 : a95 confidence ellipse of mean being plotted Optional Parameters (defaults are used if not specified) ----------- color : the default color is black. Other colors can be chosen (e.g. 'r'). marker : the default is a circle. Other symbols can be chosen (e.g. 's'). markersize : the default is 20. Other sizes can be chosen. label : the default is no label. Labels can be assigned. legend : the default is no legend ('no'). Putting 'yes' will plot a legend.
2.512662
2.695646
0.932119
plot_di_mean_ellipse(bingham_dictionary, fignum=fignum, color=color, marker=marker, markersize=markersize, label=label, legend=legend)
def plot_di_mean_bingham(bingham_dictionary, fignum=1, color='k', marker='o', markersize=20, label='', legend='no')
see plot_di_mean_ellipse
2.285513
1.891534
1.208285
pars = [] pars.append(dictionary['dec']) pars.append(dictionary['inc']) pars.append(dictionary['Zeta']) pars.append(dictionary['Zdec']) pars.append(dictionary['Zinc']) pars.append(dictionary['Eta']) pars.append(dictionary['Edec']) pars.append(dictionary['Einc']) DI_dimap = pmag.dimap(dictionary['dec'], dictionary['inc']) if dictionary['inc'] < 0: plt.scatter(DI_dimap[0], DI_dimap[1], edgecolors=color, facecolors='white', marker=marker, s=markersize, label=label) if dictionary['inc'] >= 0: plt.scatter(DI_dimap[0], DI_dimap[1], edgecolors=color, facecolors=color, marker=marker, s=markersize, label=label) pmagplotlib.plot_ell(fignum, pars, color, 0, 1)
def plot_di_mean_ellipse(dictionary, fignum=1, color='k', marker='o', markersize=20, label='', legend='no')
Plot a mean direction (declination, inclination) confidence ellipse. Parameters ----------- dictionary : a dictionary generated by the pmag.dobingham or pmag.dokent funcitons
2.4948
2.462049
1.013303
''' Function creates and returns an orthographic map projection using cartopy Example ------- >>> map_axis = make_orthographic_map(central_longitude=200,central_latitude=30) Optional Parameters ----------- central_longitude : central longitude of projection (default is 0) central_latitude : central latitude of projection (default is 0) figsize : size of the figure (default is 8x8) add_land : chose whether land is plotted on map (default is true) land_color : specify land color (default is 'tan') add_ocean : chose whether land is plotted on map (default is False, change to True to plot) ocean_color : specify ocean color (default is 'lightblue') grid_lines : chose whether gird lines are plotted on map (default is true) lat_grid : specify the latitude grid (default is 30 degree spacing) lon_grid : specify the longitude grid (default is 30 degree spacing) ''' if not has_cartopy: print('-W- cartopy must be installed to run ipmag.make_orthographic_map') return fig = plt.figure(figsize=figsize) map_projection = ccrs.Orthographic( central_longitude=central_longitude, central_latitude=central_latitude) ax = plt.axes(projection=map_projection) ax.set_global() if add_ocean == True: ax.add_feature(cartopy.feature.OCEAN, zorder=0, facecolor=ocean_color) if add_land == True: ax.add_feature(cartopy.feature.LAND, zorder=0, facecolor=land_color, edgecolor='black') if grid_lines == True: ax.gridlines(xlocs=lon_grid, ylocs=lat_grid, linewidth=1, color='black', linestyle='dotted') return ax
def make_orthographic_map(central_longitude=0, central_latitude=0, figsize=(8, 8), add_land=True, land_color='tan', add_ocean=False, ocean_color='lightblue', grid_lines=True, lat_grid=[-80., -60., -30., 0., 30., 60., 80.], lon_grid=[-180., -150., -120., -90., -60., -30., 0., 30., 60., 90., 120., 150., 180.])
Function creates and returns an orthographic map projection using cartopy Example ------- >>> map_axis = make_orthographic_map(central_longitude=200,central_latitude=30) Optional Parameters ----------- central_longitude : central longitude of projection (default is 0) central_latitude : central latitude of projection (default is 0) figsize : size of the figure (default is 8x8) add_land : chose whether land is plotted on map (default is true) land_color : specify land color (default is 'tan') add_ocean : chose whether land is plotted on map (default is False, change to True to plot) ocean_color : specify ocean color (default is 'lightblue') grid_lines : chose whether gird lines are plotted on map (default is true) lat_grid : specify the latitude grid (default is 30 degree spacing) lon_grid : specify the longitude grid (default is 30 degree spacing)
2.286147
1.491369
1.532918
if not has_cartopy: print('-W- cartopy must be installed to run ipmag.plot_pole') return A95_km = A95 * 111.32 map_axis.scatter(plon, plat, marker=marker, color=color, edgecolors=edgecolor, s=markersize, label=label, zorder=101, transform=ccrs.Geodetic()) equi(map_axis, plon, plat, A95_km, color) if legend == 'yes': plt.legend(loc=2)
def plot_pole(map_axis, plon, plat, A95, label='', color='k', edgecolor='k', marker='o', markersize=20, legend='no')
This function plots a paleomagnetic pole and A95 error ellipse on a cartopy map axis. Before this function is called, a plot needs to be initialized with code such as that in the make_orthographic_map function. Example ------- >>> plon = 200 >>> plat = 60 >>> A95 = 6 >>> map_axis = ipmag.make_orthographic_map(central_longitude=200,central_latitude=30) >>> ipmag.plot_pole(map_axis, plon, plat, A95 ,color='red',markersize=40) Required Parameters ----------- map_axis : the name of the current map axis that has been developed using cartopy plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) A95 : the A_95 confidence ellipse of the paleomagnetic pole (in degrees) Optional Parameters (defaults are used if not specified) ----------- color : the default color is black. Other colors can be chosen (e.g. 'r') marker : the default is a circle. Other symbols can be chosen (e.g. 's') markersize : the default is 20. Other size can be chosen label : the default is no label. Labels can be assigned. legend : the default is no legend ('no'). Putting 'yes' will plot a legend.
3.35161
3.575413
0.937405
map_axis.scatter(plon, plat, marker=marker, color=color, edgecolors=edgecolor, s=markersize, label=label, zorder=101, transform=ccrs.Geodetic()) if isinstance(color,str)==True: for n in range(0,len(A95)): A95_km = A95[n] * 111.32 equi(map_axis, plon[n], plat[n], A95_km, color) else: for n in range(0,len(A95)): A95_km = A95[n] * 111.32 equi(map_axis, plon[n], plat[n], A95_km, color[n]) if legend == 'yes': plt.legend(loc=2)
def plot_poles(map_axis, plon, plat, A95, label='', color='k', edgecolor='k', marker='o', markersize=20, legend='no')
This function plots paleomagnetic poles and A95 error ellipses on a cartopy map axis. Before this function is called, a plot needs to be initialized with code such as that in the make_orthographic_map function. Examples ------- >>> plons = [200, 180, 210] >>> plats = [60, 40, 35] >>> A95 = [6, 3, 10] >>> map_axis = ipmag.make_orthographic_map(central_longitude=200, central_latitude=30) >>> ipmag.plot_poles(map_axis, plons, plats, A95s, color='red', markersize=40) >>> plons = [200, 180, 210] >>> plats = [60, 40, 35] >>> A95 = [6, 3, 10] >>> colors = ['red','green','blue'] >>> map_axis = ipmag.make_orthographic_map(central_longitude=200, central_latitude=30) >>> ipmag.plot_poles(map_axis, plons, plats, A95s, color=colors, markersize=40) Required Parameters ----------- map_axis : the name of the current map axis that has been developed using cartopy plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) A95 : the A_95 confidence ellipse of the paleomagnetic pole (in degrees) Optional Parameters (defaults are used if not specified) ----------- color : the default color is black. Other colors can be chosen (e.g. 'r') a list of colors can also be given so that each pole has a distinct color edgecolor : the default edgecolor is black. Other colors can be chosen (e.g. 'r') marker : the default is a circle. Other symbols can be chosen (e.g. 's') markersize : the default is 20. Other size can be chosen label : the default is no label. Labels can be assigned. legend : the default is no legend ('no'). Putting 'yes' will plot a legend.
1.992684
2.232263
0.892674
centerlon, centerlat = mapname(plon, plat) A95_km = A95 * 111.32 mapname.scatter(centerlon, centerlat, marker=marker, color=color, edgecolors=edgecolor, s=markersize, label=label, zorder=101) equi_basemap(mapname, plon, plat, A95_km, color) if legend == 'yes': plt.legend(loc=2)
def plot_pole_basemap(mapname, plon, plat, A95, label='', color='k', edgecolor='k', marker='o', markersize=20, legend='no')
This function plots a paleomagnetic pole and A95 error ellipse on whatever current map projection has been set using the basemap plotting library. Before this function is called, a plot needs to be initialized with code that looks something like: >from mpl_toolkits.basemap import Basemap >mapname = Basemap(projection='ortho',lat_0=35,lon_0=200) >plt.figure(figsize=(6, 6)) >mapname.drawcoastlines(linewidth=0.25) >mapname.fillcontinents(color='bisque',lake_color='white',zorder=1) >mapname.drawmapboundary(fill_color='white') >mapname.drawmeridians(np.arange(0,360,30)) >mapname.drawparallels(np.arange(-90,90,30)) Required Parameters ----------- mapname : the name of the current map that has been developed using basemap plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) A95 : the A_95 confidence ellipse of the paleomagnetic pole (in degrees) Optional Parameters (defaults are used if not specified) ----------- color : the default color is black. Other colors can be chosen (e.g. 'r') marker : the default is a circle. Other symbols can be chosen (e.g. 's') markersize : the default is 20. Other size can be chosen label : the default is no label. Labels can be assigned. legend : the default is no legend ('no'). Putting 'yes' will plot a legend.
2.809866
3.305369
0.850092
if not has_cartopy: print('-W- cartopy must be installed to run ipmag.plot_poles_colorbar') return color_mapping = plt.cm.ScalarMappable(cmap=colormap, norm=plt.Normalize(vmin=vmin, vmax=vmax)) colors = color_mapping.to_rgba(colorvalues).tolist() plot_poles(map_axis, plons, plats, A95s, label='', color=colors, edgecolor=edgecolor, marker=marker) if colorbar == True: sm = plt.cm.ScalarMappable( cmap=colormap, norm=plt.Normalize(vmin=vmin, vmax=vmax)) sm._A = [] plt.colorbar(sm, orientation='horizontal', shrink=0.8, pad=0.05, label=colorbar_label)
def plot_poles_colorbar(map_axis, plons, plats, A95s, colorvalues, vmin, vmax, colormap='viridis', edgecolor='k', marker='o', markersize='20', alpha=1.0, colorbar=True, colorbar_label='pole age (Ma)')
This function plots multiple paleomagnetic pole and A95 error ellipse on a cartopy map axis. The poles are colored by the defined colormap. Before this function is called, a plot needs to be initialized with code such as that in the make_orthographic_map function. Example ------- >>> plons = [200, 180, 210] >>> plats = [60, 40, 35] >>> A95s = [6, 3, 10] >>> ages = [100,200,300] >>> vmin = 0 >>> vmax = 300 >>> map_axis = ipmag.make_orthographic_map(central_longitude=200, central_latitude=30) >>> ipmag.plot_poles_colorbar(map_axis, plons, plats, A95s, ages, vmin, vmax) Required Parameters ----------- map_axis : the name of the current map axis that has been developed using cartopy plons : the longitude of the paleomagnetic pole being plotted (in degrees E) plats : the latitude of the paleomagnetic pole being plotted (in degrees) A95s : the A_95 confidence ellipse of the paleomagnetic pole (in degrees) colorvalues : what attribute is being used to determine the colors vmin : what is the minimum range for the colormap vmax : what is the maximum range for the colormap Optional Parameters (defaults are used if not specified) ----------- colormap : the colormap used (default is 'viridis'; others should be put as a string with quotes, e.g. 'plasma') edgecolor : the color desired for the symbol outline marker : the marker shape desired for the pole mean symbol (default is 'o' aka a circle) colorbar : the default is to include a colorbar (True). Putting False will make it so no legend is plotted. colorbar_label : label for the colorbar
2.648572
2.720922
0.97341
if not has_cartopy: print('-W- cartopy must be installed to run ipmag.plot_vgp') return if di_block != None: di_lists = unpack_di_block(di_block) if len(di_lists) == 3: vgp_lon, vgp_lat, intensity = di_lists if len(di_lists) == 2: vgp_lon, vgp_lat = di_lists map_axis.scatter(vgp_lon, vgp_lat, marker=marker, edgecolors=[edge], s=markersize, color=color, label=label, zorder=100, transform=ccrs.Geodetic()) map_axis.set_global() if legend == True: plt.legend(loc=2)
def plot_vgp(map_axis, vgp_lon=None, vgp_lat=None, di_block=None, label='', color='k', marker='o', edge='black', markersize=20, legend=False)
This function plots a paleomagnetic pole position on a cartopy map axis. Before this function is called, a plot needs to be initialized with code such as that in the make_orthographic_map function. Example ------- >>> vgps = ipmag.fishrot(dec=200,inc=30) >>> vgp_lon_list,vgp_lat_list,intensities= ipmag.unpack_di_block(vgps) >>> map_axis = ipmag.make_orthographic_map(central_longitude=200,central_latitude=30) >>> ipmag.plot_vgp(map_axis,vgp_lon=vgp_lon_list,vgp_lat=vgp_lat_list,color='red',markersize=40) Required Parameters ----------- map_axis : the name of the current map axis that has been developed using cartopy plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) Optional Parameters (defaults are used if not specified) ----------- color : the color desired for the symbol (default is 'k' aka black) marker : the marker shape desired for the pole mean symbol (default is 'o' aka a circle) edge : the color of the edge of the marker (default is black) markersize : size of the marker in pt (default is 20) label : the default is no label. Labels can be assigned. legend : the default is no legend (False). Putting True will plot a legend.
2.828435
2.627627
1.076422
if di_block != None: di_lists = unpack_di_block(di_block) if len(di_lists) == 3: vgp_lon, vgp_lat, intensity = di_lists if len(di_lists) == 2: vgp_lon, vgp_lat = di_lists centerlon, centerlat = mapname(vgp_lon, vgp_lat) mapname.scatter(centerlon, centerlat, marker=marker, s=markersize, color=color, label=label, zorder=100) if legend == 'yes': plt.legend(loc=2)
def plot_vgp_basemap(mapname, vgp_lon=None, vgp_lat=None, di_block=None, label='', color='k', marker='o', markersize=20, legend='no')
This function plots a paleomagnetic pole on whatever current map projection has been set using the basemap plotting library. Before this function is called, a plot needs to be initialized with code that looks something like: >from mpl_toolkits.basemap import Basemap >mapname = Basemap(projection='ortho',lat_0=35,lon_0=200) >plt.figure(figsize=(6, 6)) >mapname.drawcoastlines(linewidth=0.25) >mapname.fillcontinents(color='bisque',lake_color='white',zorder=1) >mapname.drawmapboundary(fill_color='white') >mapname.drawmeridians(np.arange(0,360,30)) >mapname.drawparallels(np.arange(-90,90,30)) Required Parameters ----------- mapname : the name of the current map that has been developed using basemap plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) Optional Parameters (defaults are used if not specified) ----------- color : the color desired for the symbol and its A95 ellipse (default is 'k' aka black) marker : the marker shape desired for the pole mean symbol (default is 'o' aka a circle) label : the default is no label. Labels can be assigned. legend : the default is no legend ('no'). Putting 'yes' will plot a legend.
2.354486
2.442127
0.964113
# calculate the mean from the directional data dataframe_dirs = [] for n in range(0, len(dataframe)): dataframe_dirs.append([dataframe[dec_tc][n], dataframe[inc_tc][n], 1.]) dataframe_dir_mean = pmag.fisher_mean(dataframe_dirs) # calculate the mean from the vgp data dataframe_poles = [] dataframe_pole_lats = [] dataframe_pole_lons = [] for n in range(0, len(dataframe)): dataframe_poles.append([dataframe['vgp_lon'][n], dataframe['vgp_lat'][n], 1.]) dataframe_pole_lats.append(dataframe['vgp_lat'][n]) dataframe_pole_lons.append(dataframe['vgp_lon'][n]) dataframe_pole_mean = pmag.fisher_mean(dataframe_poles) # calculate mean paleolatitude from the directional data dataframe['paleolatitude'] = lat_from_inc(dataframe_dir_mean['inc']) angle_list = [] for n in range(0, len(dataframe)): angle = pmag.angle([dataframe['vgp_lon'][n], dataframe['vgp_lat'][n]], [dataframe_pole_mean['dec'], dataframe_pole_mean['inc']]) angle_list.append(angle[0]) dataframe['delta_mean_pole'] = angle_list if site_correction == 'yes': # use eq. 2 of Cox (1970) to translate the directional precision parameter # into pole coordinates using the assumption of a Fisherian distribution in # directional coordinates and the paleolatitude as calculated from mean # inclination using the dipole equation dataframe['K'] = old_div(dataframe['k'], (0.125 * (5 + 18 * np.sin(np.deg2rad(dataframe['paleolatitude']))**2 + 9 * np.sin(np.deg2rad(dataframe['paleolatitude']))**4))) dataframe['Sw'] = old_div(81, (dataframe['K']**0.5)) summation = 0 N = 0 for n in range(0, len(dataframe)): quantity = dataframe['delta_mean_pole'][n]**2 - \ old_div(dataframe['Sw'][n]**2, dataframe['n'][n]) summation += quantity N += 1 Sb = ((old_div(1.0, (N - 1.0))) * summation)**0.5 if site_correction == 'no': summation = 0 N = 0 for n in range(0, len(dataframe)): quantity = dataframe['delta_mean_pole'][n]**2 summation += quantity N += 1 Sb = ((old_div(1.0, (N - 1.0))) * summation)**0.5 return Sb
def sb_vgp_calc(dataframe, site_correction='yes', dec_tc='dec_tc', inc_tc='inc_tc')
This function calculates the angular dispersion of VGPs and corrects for within site dispersion (unless site_correction = 'no') to return a value S_b. The input data needs to be within a pandas Dataframe. Parameters ----------- dataframe : the name of the pandas.DataFrame containing the data the data frame needs to contain these columns: dataframe['site_lat'] : latitude of the site dataframe['site_lon'] : longitude of the site dataframe['k'] : fisher precision parameter for directions dataframe['vgp_lat'] : VGP latitude dataframe['vgp_lon'] : VGP longitude ----- the following default parameters can be changes by keyword argument ----- dataframe['inc_tc'] : tilt-corrected inclination dataframe['dec_tc'] : tilt-corrected declination plot : default is 'no', will make a plot of poles if 'yes'
2.888916
2.793502
1.034156
di_block = [] for n in range(0, len(dec)): di_block.append([dec[n], inc[n], 1.0]) return di_block
def make_di_block(dec, inc)
Some pmag.py and ipmag.py functions require or will take a list of unit vectors [dec,inc,1.] as input. This function takes declination and inclination data and make it into such a nest list of lists. Parameters ----------- dec : list of declinations inc : list of inclinations Returns ----------- di_block : nested list of declination, inclination lists Example ----------- >>> decs = [180.3, 179.2, 177.2] >>> incs = [12.1, 13.7, 11.9] >>> ipmag.make_di_block(decs,incs) [[180.3, 12.1, 1.0], [179.2, 13.7, 1.0], [177.2, 11.9, 1.0]]
2.79303
3.40094
0.821252
dec_list = [] inc_list = [] moment_list = [] for n in range(0, len(di_block)): dec = di_block[n][0] inc = di_block[n][1] dec_list.append(dec) inc_list.append(inc) if len(di_block[n]) > 2: moment = di_block[n][2] moment_list.append(moment) return dec_list, inc_list, moment_list
def unpack_di_block(di_block)
This function unpacks a nested list of [dec,inc,mag_moment] into a list of declination values, a list of inclination values and a list of magnetic moment values. Mag_moment values are optional, while dec and inc values are required. Parameters ----------- di_block : nested list of declination, inclination lists Returns ----------- dec : list of declinations inc : list of inclinations mag_moment : list of magnetic moment (if present in di_block) Example ----------- The di_block nested lists of lists can be unpacked using the function >>> directions = [[180.3, 12.1, 1.0], [179.2, 13.7, 1.0], [177.2, 11.9, 1.0]] >>> ipmag.unpack_di_block(directions) ([180.3, 179.2, 177.2], [12.1, 13.7, 11.9], [1.0, 1.0, 1.0]) These unpacked values can be assigned to variables: >>> dec, inc, moment = ipmag.unpack_di_block(directions)
1.998897
1.717899
1.163571
diddd_block = [] for n in range(0, len(dec)): diddd_block.append([dec[n], inc[n], dip_direction[n], dip[n]]) diddd_array = np.array(diddd_block) return diddd_array
def make_diddd_array(dec, inc, dip_direction, dip)
Some pmag.py functions such as the bootstrap fold test require a numpy array of dec, inc, dip direction, dip [dec, inc, dd, dip] as input. This function makes such an array. Parameters ----------- dec : paleomagnetic declination in degrees inc : paleomagnetic inclination in degrees dip_direction : the dip direction of bedding (in degrees between 0 and 360) dip: dip of bedding (in degrees) Returns ------- array : an array of [dec, inc, dip_direction, dip] Examples -------- Data in separate lists of dec, inc, dip_direction, dip data can be made into an array. >>> dec = [132.5,124.3,142.7,130.3,163.2] >>> inc = [12.1,23.2,34.2,37.7,32.6] >>> dip_direction = [265.0,265.0,265.0,164.0,164.0] >>> dip = [20.0,20.0,20.0,72.0,72.0] >>> data_array = ipmag.make_diddd_array(dec,inc,dip_direction,dip) >>> data_array array([[ 132.5, 12.1, 265. , 20. ], [ 124.3, 23.2, 265. , 20. ], [ 142.7, 34.2, 265. , 20. ], [ 130.3, 37.7, 164. , 72. ], [ 163.2, 32.6, 164. , 72. ]])
2.040063
2.843683
0.717401
if not has_cartopy: print('-W- cartopy must be installed to run ipmag.equi') return glon1 = centerlon glat1 = centerlat X = [] Y = [] for azimuth in range(0, 360): glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius) X.append(glon2) Y.append(glat2) X.append(X[0]) Y.append(Y[0]) plt.plot(X[::-1], Y[::-1], color=color, transform=ccrs.Geodetic(), alpha=alpha)
def equi(map_axis, centerlon, centerlat, radius, color, alpha=1.0)
This function enables A95 error ellipses to be drawn in cartopy around paleomagnetic poles in conjunction with shoot (modified from: http://www.geophysique.be/2011/02/20/matplotlib-basemap-tutorial-09-drawing-circles/).
3.082409
2.8738
1.07259
glon1 = centerlon glat1 = centerlat X = [] Y = [] for azimuth in range(0, 360): glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius) X.append(glon2) Y.append(glat2) X.append(X[0]) Y.append(Y[0]) X, Y = m(X, Y) plt.plot(X, Y, color)
def equi_basemap(m, centerlon, centerlat, radius, color)
This function enables A95 error ellipses to be drawn in basemap around paleomagnetic poles in conjunction with shoot (from: http://www.geophysique.be/2011/02/20/matplotlib-basemap-tutorial-09-drawing-circles/).
2.496239
2.298755
1.085909
if not has_cartopy: print('-W- cartopy must be installed to run ipmag.ellipse') return False angle = angle*(np.pi/180) glon1 = centerlon glat1 = centerlat X = [] Y = [] for azimuth in np.linspace(0, 360, n): az_rad = azimuth*(np.pi/180) radius = ((major_axis*minor_axis)/(((minor_axis*np.cos(az_rad-angle)) ** 2 + (major_axis*np.sin(az_rad-angle))**2)**.5)) glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius) X.append((360+glon2) % 360) Y.append(glat2) X.append(X[0]) Y.append(Y[0]) if filled: ellip = np.array((X, Y)).T ellip = map_axis.projection.transform_points( ccrs.PlateCarree(), ellip[:, 0], ellip[:, 1]) poly = Polygon(ellip[:, :2], **kwargs) map_axis.add_patch(poly) else: try: map_axis.plot(X, Y, transform=ccrs.Geodetic(), **kwargs) return True except ValueError: return False
def ellipse(map_axis, centerlon, centerlat, major_axis, minor_axis, angle, n=360, filled=False, **kwargs)
This function enables general error ellipses to be drawn on the cartopy projection of the input map axis using a center and a set of major and minor axes and a rotation angle east of north. (Adapted from equi). Parameters ----------- map_axis : cartopy axis centerlon : longitude of the center of the ellipse centerlat : latitude of the center of the ellipse major_axis : Major axis of ellipse minor_axis : Minor axis of ellipse angle : angle of major axis in degrees east of north n : number of points with which to apporximate the ellipse filled : boolean specifying if the ellipse should be plotted as a filled polygon or as a set of line segments (Doesn't work right now) kwargs : any other key word arguments can be passed for the line Returns --------- The map object with the ellipse plotted on it
2.796456
2.874417
0.972877
plt.figure(num=fignum, figsize=(5, 5)) if intensity: int_key=intensity else: intlist = ['magn_moment', 'magn_volume', 'magn_mass'] # get which key we have IntMeths = [col_name for col_name in data.columns if col_name in intlist] int_key = IntMeths[0] data = data[data[int_key].notnull()] # fish out all data with this key units = "U" # this sets the units for plotting to undefined if not dmag_key: if 'treat_temp' in data.columns: units = "K" # kelvin elif 'treat_ac_field' in data.columns: units = "T" # tesla elif 'treat_mw_energy' in data.columns: units = "J" # joules if dmag_key=='treat_temp': units='K' if dmag_key=='treat_ac_field': units='T' if dmag_key=='treat_mw_energy': units='J' spcs = data.specimen.unique() # get a list of all specimens in DataFrame data if len(spcs)==0: print('no data for plotting') return # step through specimens to put on plot for spc in spcs: spec_data = data[data.specimen.str.contains(spc)] INTblock = [] for ind, rec in spec_data.iterrows(): INTblock.append([float(rec[dmag_key]), 0, 0, float(rec[int_key]), 1, rec['quality']]) if len(INTblock) > 2: pmagplotlib.plot_mag(fignum, INTblock, title, 0, units, norm)
def plot_dmag(data="", title="", fignum=1, norm=1,dmag_key='treat_ac_field',intensity='', quality=False)
plots demagenetization data versus step for all specimens in pandas dataframe datablock Parameters ______________ data : Pandas dataframe with MagIC data model 3 columns: fignum : figure number specimen : specimen name dmag_key : one of these: ['treat_temp','treat_ac_field','treat_mw_energy'] selected using method_codes : ['LT_T-Z','LT-AF-Z','LT-M-Z'] respectively intensity : if blank will choose one of these: ['magn_moment', 'magn_volume', 'magn_mass'] quality : if True use the quality column of the DataFrame title : title for plot norm : if True, normalize data to first step Output : matptlotlib plot
4.051779
3.482318
1.163529
file = os.path.join(dir_path, infile) eigs_data = np.loadtxt(file) Ss = [] for ind in range(eigs_data.shape[0]): tau, Vdirs = [], [] for k in range(0, 9, 3): tau.append(eigs_data[ind][k]) Vdirs.append([eigs_data[ind][k+1], eigs_data[ind][k+2]]) s = list(pmag.doeigs_s(tau, Vdirs)) Ss.append(s) return Ss
def eigs_s(infile="", dir_path='.')
Converts eigenparamters format data to s format Parameters ___________________ Input: file : input file name with eigenvalues (tau) and eigenvectors (V) with format: tau_1 V1_dec V1_inc tau_2 V2_dec V2_inc tau_3 V3_dec V3_inc Output the six tensor elements as a nested array [[x11,x22,x33,x12,x23,x13],....]
3.091789
2.925421
1.05687
for pole in poles: pmagplotlib.plot_circ(fignum, pole, 90., color)
def plot_gc(poles, color='g', fignum=1)
plots a great circle on an equal area projection Parameters ____________________ Input fignum : number of matplotlib object poles : nested list of [Dec,Inc] pairs of poles color : color of lower hemisphere dots for great circle - must be in form: 'g','r','y','k',etc. upper hemisphere is always cyan
7.822077
10.464476
0.747489
# we could return the type of coordinates ACTUALLY used # transform geographic decs = this_spec_meas_df['dir_dec'].values.tolist() incs = this_spec_meas_df['dir_inc'].values.tolist() or_info, az_type = pmag.get_orient(samp_df,samp,data_model=3) if 'azimuth' in or_info.keys() and cb.not_null(or_info['azimuth'], False): azimuths=len(decs)*[or_info['azimuth']] dips=len(decs)*[or_info['dip']] # if azimuth/dip is missing, or orientation is bad, # stick with specimen coordinates else: return this_spec_meas_df dirs = [decs, incs, azimuths, dips] dirs_geo = np.array(list(map(list, list(zip(*dirs))))) decs, incs = pmag.dogeo_V(dirs_geo) if coord == '100' and 'bed_dip_direction' in or_info.keys() and or_info['bed_dip_direction']!="": # need to do tilt correction too bed_dip_dirs = len(decs)*[or_info['bed_dip_direction']] bed_dips = len(decs) * [or_info['bed_dip']] dirs = [decs, incs, bed_dip_dirs, bed_dips] ## this transposes the columns and rows of the list of lists dirs_tilt = np.array(list(map(list, list(zip(*dirs))))) decs, incs = pmag.dotilt_V(dirs_tilt) this_spec_meas_df['dir_dec'] = decs this_spec_meas_df['dir_inc'] = incs return this_spec_meas_df
def transform_to_geographic(this_spec_meas_df, samp_df, samp, coord="0")
Transform decs/incs to geographic coordinates. Calls pmag.dogeo_V for the heavy lifting Parameters ---------- this_spec_meas_df : pandas dataframe of measurements for a single specimen samp_df : pandas dataframe of samples samp : samp name Returns --------- this_spec_meas_df : measurements dataframe with transformed coordinates
3.75687
3.396364
1.106145
input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, output_dir_path) try: fname = pmag.resolve_file_name(spec_file, input_dir_path) except IOError: print("bad specimen file name") return False, "bad specimen file name" spec_df = pd.read_csv(fname, sep='\t', header=1) spec_df.dropna('columns', how='all', inplace=True) if 'int_abs' in spec_df.columns: spec_df.dropna(subset=['int_abs'], inplace=True) if len(spec_df) > 0: table_df = map_magic.convert_specimen_dm3_table(spec_df) out_file = pmag.resolve_file_name(output_file, output_dir_path) if latex: if out_file.endswith('.xls'): out_file = out_file.rsplit('.')[0] + ".tex" info_out = open(out_file, 'w+', errors="backslashreplace") info_out.write('\documentclass{article}\n') info_out.write('\\usepackage{booktabs}\n') if landscape: info_out.write('\\usepackage{lscape}') if longtable: info_out.write('\\usepackage{longtable}\n') info_out.write('\\begin{document}\n') if landscape: info_out.write('\\begin{landscape}\n') info_out.write(table_df.to_latex(index=False, longtable=longtable, escape=True, multicolumn=False)) if landscape: info_out.write('\end{landscape}\n') info_out.write('\end{document}\n') info_out.close() else: table_df.to_excel(out_file, index=False) else: print("No specimen data for ouput.") return True, [out_file]
def specimens_extract(spec_file='specimens.txt', output_file='specimens.xls', landscape=False, longtable=False, output_dir_path='.', input_dir_path='', latex=False)
Extracts specimen results from a MagIC 3.0 format specimens.txt file. Default output format is an Excel file. typeset with latex on your own computer. Parameters ___________ spec_file : str, default "specimens.txt" input file name output_file : str, default "specimens.xls" output file name landscape : boolean, default False if True output latex landscape table longtable : boolean if True output latex longtable output_dir_path : str, default "." output file directory input_dir_path : str, default "" path for intput file if different from output_dir_path (default is same) latex : boolean, default False if True, output file should be latex formatted table with a .tex ending Return : [True,False], data table error type : True if successful Effects : writes xls or latex formatted tables for use in publications
2.365232
2.389146
0.98999
input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, output_dir_path) try: fname = pmag.resolve_file_name(crit_file, input_dir_path) except IOError: print("bad criteria file name") return False, "bad criteria file name" crit_df = pd.read_csv(fname, sep='\t', header=1) if len(crit_df) > 0: out_file = pmag.resolve_file_name(output_file, output_dir_path) s = crit_df['table_column'].str.split(pat='.', expand=True) crit_df['table'] = s[0] crit_df['column'] = s[1] crit_df = crit_df[['table', 'column', 'criterion_value', 'criterion_operation']] crit_df.columns = ['Table', 'Statistic', 'Threshold', 'Operation'] if latex: if out_file.endswith('.xls'): out_file = out_file.rsplit('.')[0] + ".tex" crit_df.loc[crit_df['Operation'].str.contains( '<'), 'operation'] = 'maximum' crit_df.loc[crit_df['Operation'].str.contains( '>'), 'operation'] = 'minimum' crit_df.loc[crit_df['Operation'] == '=', 'operation'] = 'equal to' info_out = open(out_file, 'w+', errors="backslashreplace") info_out.write('\documentclass{article}\n') info_out.write('\\usepackage{booktabs}\n') # info_out.write('\\usepackage{longtable}\n') # T1 will ensure that symbols like '<' are formatted correctly info_out.write("\\usepackage[T1]{fontenc}\n") info_out.write('\\begin{document}') info_out.write(crit_df.to_latex(index=False, longtable=False, escape=True, multicolumn=False)) info_out.write('\end{document}\n') info_out.close() else: crit_df.to_excel(out_file, index=False) else: print("No criteria for ouput.") return True, [out_file]
def criteria_extract(crit_file='criteria.txt', output_file='criteria.xls', output_dir_path='.', input_dir_path='', latex=False)
Extracts criteria from a MagIC 3.0 format criteria.txt file. Default output format is an Excel file. typeset with latex on your own computer. Parameters ___________ crit_file : str, default "criteria.txt" input file name output_file : str, default "criteria.xls" output file name output_dir_path : str, default "." output file directory input_dir_path : str, default "" path for intput file if different from output_dir_path (default is same) latex : boolean, default False if True, output file should be latex formatted table with a .tex ending Return : [True,False], data table error type : True if successful Effects : writes xls or latex formatted tables for use in publications
2.702687
2.742865
0.985352
# set outfile name if outfile: fmt = "" else: outfile = 'hist.'+fmt # read in data from infile or use data argument if os.path.exists(infile): D = np.loadtxt(infile) else: D = np.array(data) try: if not len(D): print('-W- No data found') return False, [] except ValueError: pass fig = pmagplotlib.plot_init(1, 8, 7) try: len(D) except TypeError: D = np.array([D]) if len(D) < 5: print("-W- Not enough points to plot histogram ({} point(s) provided, 5 required)".format(len(D))) return False, [] # if binsize not provided, calculate reasonable binsize if not binsize: binsize = int(np.around(1 + 3.22 * np.log(len(D)))) binsize = int(binsize) Nbins = int(len(D) / binsize) ax = fig.add_subplot(111) if norm == 1: print('normalizing') n, bins, patches = ax.hist( D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=True) ax.set_ylabel('Frequency') elif norm == 0: print('not normalizing') n, bins, patches = ax.hist( D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=False) ax.set_ylabel('Number') elif norm == -1: #print('trying twin') n, bins, patches = ax.hist( D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=True) ax.set_ylabel('Frequency') ax2 = ax.twinx() n, bins, patches = ax2.hist( D, bins=Nbins, facecolor='#D3D3D3', histtype='stepfilled', color='black', density=False) ax2.set_ylabel('Number', rotation=-90) plt.axis([D.min(), D.max(), 0, n.max()+.1*n.max()]) ax.set_xlabel(xlab) name = 'N = ' + str(len(D)) plt.title(name) if interactive: pmagplotlib.draw_figs({1: 'hist'}) p = input('s[a]ve to save plot, [q]uit to exit without saving ') if p != 'a': return True, [] plt.savefig(outfile) print('plot saved in ', outfile) return True, [outfile] if pmagplotlib.isServer: pmagplotlib.add_borders({'hist': 1}, {'hist': 'Intensity Histogram'}) if save_plots: plt.savefig(outfile) print('plot saved in ', outfile) return True, [outfile]
def histplot(infile="", data=(), outfile="", xlab='x', binsize=False, norm=1, fmt='svg', save_plots=True, interactive=False)
makes histograms for data Parameters ---------- infile : str, default "" input file name format: single variable data : list-like, default () list/array of values to plot if infile is not provided outfile : str, default "" name for plot, if not provided defaults to hist.FMT xlab : str, default 'x' label for x axis binsize : int, default False desired binsize. if not specified, an appropriate binsize will be calculated. norm : int, default 1 1: norm, 0: don't norm, -1: show normed and non-normed axes fmt : str, default "svg" format for figures, ["svg", "jpg", "pdf", "png"] save_plots : bool, default True if True, create and save all requested plots interactive : bool, default False interactively plot and display (this is best used on the command line only)
2.714673
2.676642
1.014209
'''USE PARSE_ALL_FITS unless otherwise necessary Isolate fits by the name of the fit; we also set 'specimen_tilt_correction' to zero in order to only include data in geographic coordinates - THIS NEEDS TO BE GENERALIZED ''' fits = self.fits.loc[self.fits.specimen_comp_name == fit_name].loc[self.fits.specimen_tilt_correction == 0] fits.reset_index(inplace=True) means = self.means.loc[self.means.site_comp_name == fit_name].loc[self.means.site_tilt_correction == 0] means.reset_index(inplace=True) mean_name = str(fit_name) + "_mean" setattr(self, fit_name, fits) setattr(self, mean_name, means)
def parse_fits(self, fit_name)
USE PARSE_ALL_FITS unless otherwise necessary Isolate fits by the name of the fit; we also set 'specimen_tilt_correction' to zero in order to only include data in geographic coordinates - THIS NEEDS TO BE GENERALIZED
5.701769
2.214956
2.574214
# # 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 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
2.083657
1.803532
1.155321
if wind: wind.Destroy() if not self.parent.IsShown(): self.on_show_mainframe(None) # re-do the quit binding self.parent.Bind(wx.EVT_MENU, self.on_quit, self.file_quit) else: self.parent.Close()
def on_quit(self, event, wind=None)
shut down application if in the main frame. otherwise, destroy the top window (wind) and restore the main frame.
4.124154
3.836335
1.075024
self.parent.Enable() self.parent.Show() self.parent.Raise()
def on_show_mainframe(self, event)
Show mainframe window
4.691349
3.766137
1.245666
dia = pmag_menu_dialogs.ClearWD(self.parent, self.parent.WD) clear = dia.do_clear() if clear: # clear directory, but use previously acquired data_model if self.data_model_num == 2.5: self.parent.er_magic = builder.ErMagicBuilder(self.parent.WD, self.parent.er_magic.data_model) elif self.data_model_num == 3: self.parent.contribution = cb.Contribution(self.parent.WD, dmodel=self.parent.contribution.data_model)
def on_clear(self, event)
initialize window to allow user to empty the working directory
7.577708
7.065486
1.072496
infile,outfile,data,indata="","",[],[] if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-F' in sys.argv: ind=sys.argv.index('-F') outfile=sys.argv[ind+1] out=open(outfile,'w') if '-i' in sys.argv: print("Welcome to paleolatitude calculator\n") while 1: data=[] print("pick a plate: NA, SA, AF, IN, EU, AU, ANT, GL \n cntl-D to quit") try: plate=input("Plate\n").upper() except: print("Goodbye \n") sys.exit() lat=float(input( "Site latitude\n")) lon=float(input(" Site longitude\n")) age=float(input(" Age\n")) data=[plate,lat,lon,age] print("Age Paleolat. Dec. Inc. Pole_lat. Pole_Long.") print(spitout(data)) elif '-f' in sys.argv: ind=sys.argv.index('-f') infile=sys.argv[ind+1] f=open(infile,'r') inp=f.readlines() elif '-P' in sys.argv: ind=sys.argv.index('-P') plate=sys.argv[ind+1].upper() if '-lat' in sys.argv: ind=sys.argv.index('-lat') lat=float(sys.argv[ind+1]) else: print(main.__doc__) sys.exit() if '-lon' in sys.argv: ind=sys.argv.index('-lon') lon=float(sys.argv[ind+1]) else: print(main.__doc__) sys.exit() if '-age' in sys.argv: ind=sys.argv.index('-age') age=float(sys.argv[ind+1]) else: print(main.__doc__) sys.exit() data=[plate,lat,lon,age] outstring=spitout(data) if outfile=="": print("Age Paleolat. Dec. Inc. Pole_lat. Pole_Long.") print(outstring) else: out.write(outstring) sys.exit() else: inp=sys.stdin.readlines() # read from standard input if len(inp)>0: for line in inp: data=[] rec=line.split() data.append(rec[0]) for k in range(1,4): data.append(float(rec[k])) indata.append(data) if len(indata)>0: for line in indata: outstring=spitout(line) if outfile=="": print(outstring) else: out.write(outstring) else: print('no input data') sys.exit()
def main()
NAME apwp.py DESCRIPTION returns predicted paleolatitudes, directions and pole latitude/longitude from apparent polar wander paths of Besse and Courtillot (2002). SYNTAX apwp.py [command line options][< filename] OPTIONS -h prints help message and quits -i allows interactive data entry f file: read plate, lat, lon, age data from file -F output_file: write output to output_file -P [NA, SA, AF, IN, EU, AU, ANT, GL] plate -lat LAT specify present latitude (positive = North; negative=South) -lon LON specify present longitude (positive = East, negative=West) -age AGE specify Age in Ma Note: must have all -P, -lat, -lon, -age or none. OUTPUT Age Paleolat. Dec. Inc. Pole_lat. Pole_Long.
2.737417
2.088104
1.310958
t,V,tr=[],[],0. ind1,ind2,ind3=0,1,2 evalues,evectmps=numpy.linalg.eig(T) evectors=numpy.transpose(evectmps) # to make compatible with Numeric convention for tau in evalues: tr += tau # tr totals tau values if tr != 0: for i in range(3): evalues[i]=old_div(evalues[i], tr) # convention is norming eigenvalues so they sum to 1. else: return t,V # if eigenvalues add up to zero, no sorting is needed # sort evalues,evectors t1, t2, t3 = 0., 0., 1. for k in range(3): if evalues[k] > t1: t1,ind1 = evalues[k],k if evalues[k] < t3: t3,ind3 = evalues[k],k for k in range(3): if evalues[k] != t1 and evalues[k] != t3: t2,ind2=evalues[k],k V.append(evectors[ind1]) V.append(evectors[ind2]) V.append(evectors[ind3]) t.append(t1) t.append(t2) t.append(t3) return t,V
def tauV(T)
gets the eigenvalues (tau) and eigenvectors (V) from matrix T
3.83989
3.516238
1.092045
n = len(X1_prime) - 1 X1 = X1_prime[0] - X1_prime[n] X2 = X2_prime[0] - X2_prime[n] X3 = X3_prime[0] - X3_prime[n] R= numpy.array([X1, X2, X3]) #print 'R (reference vector for PD direction)', R dot = numpy.dot(PD, R) # dot product of reference vector and the principal axis of the V matrix #print 'dot (dot of PD and R)', dot if dot < -1: dot = -1 elif dot > 1: dot = 1 if numpy.arccos(dot) > old_div(numpy.pi, 2.): #print 'numpy.arccos(dot) {} > numpy.pi / 2. {}'.format(numpy.arccos(dot), numpy.pi / 2) #print 'correcting PD direction' PD = -1. * numpy.array(PD) #print 'PD after get PD direction', PD return PD
def get_PD_direction(X1_prime, X2_prime, X3_prime, PD)
takes arrays of X1_prime, X2_prime, X3_prime, and the PD. checks that the PD vector direction is correct
2.984182
2.873551
1.0385
# tau is ordered so that tau[0] > tau[1] > tau[2] for t in tau: if isinstance(t, complex): return -999 MAD = math.degrees(numpy.arctan(numpy.sqrt(old_div((tau[1] + tau[2]), tau[0]))) ) return MAD
def get_MAD(tau)
input: eigenvalues of PCA matrix output: Maximum Angular Deviation
5.854747
5.872925
0.996905
ints = numpy.array(d[2]) else: ints = numpy.array([1.]) cart = numpy.array([ints * numpy.cos(decs) * numpy.cos(incs), ints * numpy.sin(decs) * numpy.cos(incs), ints * numpy.sin(incs) ]).transpose() return cart
def dir2cart(d): # from pmag.py ints = numpy.ones(len(d)).transpose() # get an array of ones to plug into dec,inc pairs d = numpy.array(d) rad = old_div(numpy.pi, 180.) if len(d.shape) > 1: # array of vectors decs, incs = d[:,0] * rad, d[:,1] * rad if d.shape[1] == 3: ints = d[:,2] # take the given lengths else: # single vector decs, incs = numpy.array(d[0]) * rad, numpy.array(d[1]) * rad if len(d) == 3
converts list or array of vector directions, in degrees, to array of cartesian coordinates, in x,y,z form
2.361444
2.045129
1.154667
D1 = D1[:,0:2] # strip off intensity else: D1 = D1[:2] D2 = numpy.array(D2) if len(D2.shape) > 1: D2 = D2[:,0:2] # strip off intensity else: D2 = D2[:2] X1 = dir2cart(D1) # convert to cartesian from polar X2 = dir2cart(D2) angles = [] # set up a list for angles for k in range(X1.shape[0]): # single vector angle = numpy.arccos(numpy.dot(X1[k],X2[k]))*180./numpy.pi # take the dot product angle = angle%360. angles.append(angle) return numpy.array(angles)
def pmag_angle(D1,D2): # use this D1 = numpy.array(D1) if len(D1.shape) > 1
finds the angle between lists of two directions D1,D2
2.712826
2.641089
1.027162
v1 = numpy.array(v1) v2 = numpy.array(v2) angle = numpy.arctan2(numpy.linalg.norm(numpy.cross(v1, v2)), numpy.dot(v1, v2)) return math.degrees(angle)
def new_get_angle_diff(v1,v2)
returns angular difference in degrees between two vectors. may be more precise in certain cases. see SPD
1.719638
1.724552
0.99715
v1 = numpy.array(v1) v2 = numpy.array(v2) angle=numpy.arccos(old_div((numpy.dot(v1, v2) ), (numpy.sqrt(math.fsum(v1**2)) * numpy.sqrt(math.fsum(v2**2))))) return math.degrees(angle)
def get_angle_difference(v1, v2)
returns angular difference in degrees between two vectors. takes in cartesian coordinates.
2.82206
2.620251
1.077019
ptrms_angle = math.degrees(math.acos(old_div(numpy.dot(ptrms_best_fit_vector,B_lab_vector),(numpy.sqrt(sum(ptrms_best_fit_vector**2)) * numpy.sqrt(sum(B_lab_vector**2)))))) # from old thellier_gui.py code return ptrms_angle
def get_ptrms_angle(ptrms_best_fit_vector, B_lab_vector)
gives angle between principal direction of the ptrm data and the b_lab vector. this is NOT in SPD, but taken from Ron Shaar's old thellier_gui.py code. see PmagPy on github
3.539646
2.399297
1.475285
filename = pmag.get_named_arg('-f') if not filename: return with open(filename, 'rb+') as f: content = f.read() f.seek(0) f.write(content.replace(b'\r', b'')) f.truncate()
def main()
Take out dos problem characters from any file
3.538533
3.086608
1.146415
'''criteria used only in thellier gui these criteria are not written to pmag_criteria.txt ''' category="thellier_gui" for crit in ['sample_int_n_outlier_check','site_int_n_outlier_check']: acceptance_criteria[crit]={} acceptance_criteria[crit]['category']=category acceptance_criteria[crit]['criterion_name']=crit acceptance_criteria[crit]['value']=-999 acceptance_criteria[crit]['threshold_type']="low" acceptance_criteria[crit]['decimal_points']=0 for crit in ['sample_int_interval_uT','sample_int_interval_perc',\ 'site_int_interval_uT','site_int_interval_perc',\ 'sample_int_BS_68_uT','sample_int_BS_95_uT','sample_int_BS_68_perc','sample_int_BS_95_perc','specimen_int_max_slope_diff']: acceptance_criteria[crit]={} acceptance_criteria[crit]['category']=category acceptance_criteria[crit]['criterion_name']=crit acceptance_criteria[crit]['value']=-999 acceptance_criteria[crit]['threshold_type']="high" if crit in ['specimen_int_max_slope_diff']: acceptance_criteria[crit]['decimal_points']=-999 else: acceptance_criteria[crit]['decimal_points']=1 acceptance_criteria[crit]['comments']="thellier_gui_only" for crit in ['average_by_sample_or_site','interpreter_method']: acceptance_criteria[crit]={} acceptance_criteria[crit]['category']=category acceptance_criteria[crit]['criterion_name']=crit if crit in ['average_by_sample_or_site']: acceptance_criteria[crit]['value']='sample' if crit in ['interpreter_method']: acceptance_criteria[crit]['value']='stdev_opt' acceptance_criteria[crit]['threshold_type']="flag" acceptance_criteria[crit]['decimal_points']=-999 for crit in ['include_nrm']: acceptance_criteria[crit]={} acceptance_criteria[crit]['category']=category acceptance_criteria[crit]['criterion_name']=crit acceptance_criteria[crit]['value']=True acceptance_criteria[crit]['threshold_type']="bool" acceptance_criteria[crit]['decimal_points']=-999
def add_thellier_gui_criteria(acceptance_criteria)
criteria used only in thellier gui these criteria are not written to pmag_criteria.txt
2.468762
2.286611
1.07966
dir_path='.' inspec="pmag_specimens.txt" 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=sys.argv[ind+1] basename=inspec.split('.')[:-1] inspec=dir_path+"/"+inspec ofile_base=dir_path+"/"+basename[0] # # read in data # prior_spec_data,file_type=pmag.magic_read(inspec) if file_type != 'pmag_specimens': print(file_type, " this is not a valid pmag_specimens file") sys.exit() # get list of specimens in file, components, coordinate systems available specs,comps,coords=[],[],[] for spec in prior_spec_data: if spec['er_specimen_name'] not in specs:specs.append(spec['er_specimen_name']) if 'specimen_comp_name' not in list(spec.keys()):spec['specimen_comp_name']='A' if 'specimen_tilt_correction' not in list(spec.keys()):spec['tilt_correction']='-1' # assume specimen coordinates if spec['specimen_comp_name'] not in comps:comps.append(spec['specimen_comp_name']) if spec['specimen_tilt_correction'] not in coords:coords.append(spec['specimen_tilt_correction']) # work on separating out components, coordinate systems by specimen for coord in coords: print(coord) for comp in comps: print(comp) speclist=[] for spec in prior_spec_data: if spec['specimen_tilt_correction']==coord and spec['specimen_comp_name']==comp:speclist.append(spec) ofile=ofile_base+'_'+coord+'_'+comp+'.txt' pmag.magic_write(ofile,speclist,'pmag_specimens') print('coordinate system: ',coord,' component name: ',comp,' saved in ',ofile)
def main()
NAME sort_specimens.py DESCRIPTION Reads in a pmag_specimen formatted file and separates it into different components (A,B...etc.) SYNTAX sort_specimens.py [-h] [command line options] INPUT takes pmag_specimens.txt formatted input file OPTIONS -h: prints help message and quits -f FILE: specify input file, default is 'pmag_specimens.txt' OUTPUT makes pmag_specimen formatted files with input filename plus _X_Y where X is the component name and Y is s,g,t for coordinate system
2.62103
2.485601
1.054485
self.menubar = wx.MenuBar() menu_about = wx.Menu() menu_help = menu_about.Append(-1, "&Some notes", "") self.Bind(wx.EVT_MENU, self.on_menu_help, menu_help) self.menubar.Append(menu_about, "& Instructions") self.SetMenuBar(self.menubar)
def create_menu(self)
Create menu
2.914411
2.781118
1.047928
#wait = wx.BusyInfo("Please wait, working...") #wx.SafeYield() self.contribution.propagate_lithology_cols() spec_df = self.contribution.tables['specimens'].df self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER) self.grid_frame = grid_frame3.GridFrame(self.contribution, self.WD, 'specimens', 'specimens', self.panel, main_frame=self.main_frame) # redefine default 'save & exit grid' button to go to next dialog instead self.grid_frame.exitButton.SetLabel('Save and continue') grid = self.grid_frame.grid self.grid_frame.Bind(wx.EVT_BUTTON, lambda event: self.onContinue(event, grid, self.InitSampCheck), self.grid_frame.exitButton) # add back button self.backButton = wx.Button(self.grid_frame.panel, id=-1, label='Back', name='back_btn') self.backButton.Disable() self.grid_frame.main_btn_vbox.Add(self.backButton, flag=wx.ALL, border=5) # re-do fit self.grid_frame.do_fit(None, self.min_size) # center self.grid_frame.Centre() return
def InitSpecCheck(self)
make an interactive grid in which users can edit specimen names as well as which sample a specimen belongs to
5.495868
5.269896
1.04288
# propagate average lat/lon info from samples table if # available in samples and missing in sites self.contribution.propagate_average_up(cols=['lat', 'lon', 'height'], target_df_name='sites', source_df_name='samples') # propagate lithology columns self.contribution.propagate_lithology_cols() site_df = self.contribution.tables['sites'].df self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER) self.grid_frame = grid_frame3.GridFrame(self.contribution, self.WD, 'sites', 'sites', self.panel, main_frame=self.main_frame) # redefine default 'save & exit grid' button to go to next dialog instead self.grid_frame.exitButton.SetLabel('Save and continue') grid = self.grid_frame.grid self.grid_frame.Bind(wx.EVT_BUTTON, lambda event: self.onContinue(event, grid, self.InitLocCheck), self.grid_frame.exitButton) # add back button self.backButton = wx.Button(self.grid_frame.panel, id=-1, label='Back', name='back_btn') self.Bind(wx.EVT_BUTTON, lambda event: self.onbackButton(event, self.InitSampCheck), self.backButton) self.grid_frame.main_btn_vbox.Add(self.backButton, flag=wx.ALL, border=5) # re-do fit self.grid_frame.do_fit(None, self.min_size) # center self.grid_frame.Centre() return
def InitSiteCheck(self)
make an interactive grid in which users can edit site names as well as which location a site belongs to
5.57248
5.409788
1.030074
# if there is a location without a name, name it 'unknown' self.contribution.rename_item('locations', 'nan', 'unknown') # propagate lat/lon values from sites table self.contribution.get_min_max_lat_lon() # propagate lithologies & geologic classes from sites table self.contribution.propagate_cols_up(['lithologies', 'geologic_classes'], 'locations', 'sites') res = self.contribution.propagate_min_max_up() if cb.not_null(res): self.contribution.propagate_cols_up(['age_unit'], 'locations', 'sites') # set up frame self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER) self.grid_frame = grid_frame3.GridFrame(self.contribution, self.WD, 'locations', 'locations', self.panel, main_frame=self.main_frame) # redefine default 'save & exit grid' button to go to next dialog instead self.grid_frame.exitButton.SetLabel('Save and continue') grid = self.grid_frame.grid self.grid_frame.Bind(wx.EVT_BUTTON, lambda event: self.onContinue(event, grid, self.InitAgeCheck), self.grid_frame.exitButton) # add back button self.backButton = wx.Button(self.grid_frame.panel, id=-1, label='Back', name='back_btn') self.Bind(wx.EVT_BUTTON, lambda event: self.onbackButton(event, self.InitSiteCheck), self.backButton) self.grid_frame.main_btn_vbox.Add(self.backButton, flag=wx.ALL, border=5) # re-do fit self.grid_frame.do_fit(None, min_size=self.min_size) # center self.grid_frame.Centre() return
def InitLocCheck(self)
make an interactive grid in which users can edit locations
5.106756
5.015839
1.018126
age_df = self.contribution.tables['ages'].df self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER) self.grid_frame = grid_frame3.GridFrame(self.contribution, self.WD, 'ages', 'ages', self.panel, main_frame=self.main_frame) self.grid_frame.exitButton.SetLabel('Save and continue') grid = self.grid_frame.grid self.grid_frame.Bind(wx.EVT_BUTTON, lambda event: self.onContinue(event, grid, None), self.grid_frame.exitButton) # add back button self.backButton = wx.Button(self.grid_frame.panel, id=-1, label='Back', name='back_btn') self.Bind(wx.EVT_BUTTON, lambda event: self.onbackButton(event, self.InitLocCheck), self.backButton) self.grid_frame.main_btn_vbox.Add(self.backButton, flag=wx.ALL, border=5) # re-do fit self.grid_frame.do_fit(None, self.min_size) # center self.grid_frame.Centre() return
def InitAgeCheck(self)
make an interactive grid in which users can edit ages
4.548309
4.335291
1.049136
# deselect column, including remove 'EDIT ALL' label if self.grid_frame.drop_down_menu: self.grid_frame.drop_down_menu.clean_up() # remove '**' and '^^' from col names #self.remove_starred_labels(grid) grid.remove_starred_labels() grid.SaveEditControlValue() # locks in value in cell currently edited grid_name = str(grid.GetName()) # save all changes to data object and write to file self.grid_frame.grid_builder.save_grid_data() # check that all required data are present validation_errors = self.validate(grid) if validation_errors: warn_string = "" for error_name, error_cols in list(validation_errors.items()): if error_cols: warn_string += "You have {}: {}.\n\n".format(error_name, ", ".join(error_cols)) warn_string += "Are you sure you want to continue?" result = pw.warning_with_override(warn_string) if result == wx.ID_YES: pass else: return False else: wx.MessageBox('Saved!', 'Info', style=wx.OK | wx.ICON_INFORMATION) self.panel.Destroy() if next_dia: next_dia() else: # propagate any type/lithology/class data from sites to samples table # will only overwrite if sample values are blank or "Not Specified" self.contribution.propagate_lithology_cols() wx.MessageBox('Done!', 'Info', style=wx.OK | wx.ICON_INFORMATION)
def onContinue(self, event, grid, next_dia=None):#, age_data_type='site')
Save grid data in the data object
6.716593
6.704659
1.00178
grid_name = str(grid.GetName()) dmodel = self.contribution.dmodel reqd_headers = dmodel.get_reqd_headers(grid_name) df = self.contribution.tables[grid_name].df df = df.replace('', np.nan) # python does not view empty strings as null if df.empty: return {} col_names = set(df.columns) missing_headers = set(reqd_headers) - col_names present_headers = set(reqd_headers) - set(missing_headers) non_null_headers = df.dropna(how='all', axis='columns').columns null_reqd_headers = present_headers - set(non_null_headers) if any(missing_headers) or any (null_reqd_headers): warnings = {'missing required column(s)': sorted(missing_headers), 'no data in required column(s)': sorted(null_reqd_headers)} else: warnings = {} return warnings
def validate(self, grid)
Using the MagIC data model, generate validation errors on a MagicGrid. Parameters ---------- grid : dialogs.magic_grid3.MagicGrid The MagicGrid to be validated Returns --------- warnings: dict Empty dict if no warnings, otherwise a dict with format {name of problem: [problem_columns]}
3.688267
3.394063
1.086682
wait = wx.BusyInfo("Please wait, working...") wx.SafeYield() if self.grid_frame.drop_down_menu: # unhighlight selected columns, etc. self.grid_frame.drop_down_menu.clean_up() # remove '**' and '^^' from col labels starred_cols, hatted_cols = grid.remove_starred_labels() grid.SaveEditControlValue() # locks in value in cell currently edited grid.HideCellEditControl() # removes focus from cell that was being edited if grid.changes: self.onSave(grid) for col in starred_cols: label = grid.GetColLabelValue(col) grid.SetColLabelValue(col, label + '**') for col in hatted_cols: label = grid.GetColLabelValue(col) grid.SetColLabelValue(col, label + '^^') del wait
def on_saveButton(self, event, grid)
saves any editing of the grid but does not continue to the next window
5.912751
5.643551
1.0477
x, y = grid.CalcUnscrolledPosition(event.GetX(), event.GetY()) coords = grid.XYToCell(x, y) col = coords[1] row = coords[0] # creates tooltip message for cells with long values # note: this works with EPD for windows, and modern wxPython, but not with Canopy Python msg = grid.GetCellValue(row, col) if len(msg) > 15: event.GetEventObject().SetToolTipString(msg) else: event.GetEventObject().SetToolTipString('')
def onMouseOver(self, event, grid)
Displays a tooltip over any cell in a certain column
5.170862
4.712387
1.097292
# for use on the command line: path = find_pmag_dir.get_pmag_dir() # for use with pyinstaller #path = self.main_frame.resource_dir help_page = os.path.join(path, 'dialogs', 'help_files', page) # if using with py2app, the directory structure is flat, # so check to see where the resource actually is if not os.path.exists(help_page): help_page = os.path.join(path, 'help_files', page) html_frame = pw.HtmlFrame(self, page=help_page) html_frame.Show()
def on_helpButton(self, event, page=None)
shows html help page
6.747508
6.572702
1.026596
#wait = wx.BusyInfo("Please wait, working...") # unhighlight selected columns, etc. if self.drop_down_menu: self.drop_down_menu.clean_up() # remove '**' from col names #self.remove_starred_labels(grid) grid.remove_starred_labels() grid.SaveEditControlValue() # locks in value in cell currently edited grid_name = str(grid.GetName()) # check that all required data are present validation_errors = self.validate(grid) if validation_errors: result = pw.warning_with_override("You are missing required data in these columns: {}\nAre you sure you want to continue without these data?".format(', '.join(validation_errors))) if result == wx.ID_YES: pass else: return False if grid.changes: self.onSave(grid) self.deleteRowButton = None #self.panel.Destroy() # calling Destroy here breaks with Anaconda Python (segfault) # make sure that specimens get propagated with # any default sample info if next_dia == self.InitLocCheck: if self.er_magic_data.specimens: for spec in self.er_magic_data.specimens: spec.propagate_data() if next_dia: wait = wx.BusyInfo("Please wait, working...") wx.SafeYield() wx.CallAfter(self.panel.Destroy) # no segfault here! next_dia() # need to wait to process the resize: event = wx.PyCommandEvent(wx.EVT_SIZE.typeId, self.GetId()) wx.CallAfter(self.GetEventHandler().ProcessEvent, event) del wait else: wait = wx.BusyInfo("Please wait, writing data to files...") wx.SafeYield() # actually write data: self.er_magic_data.write_files() self.Destroy() del wait
def on_continueButton(self, event, grid, next_dia=None)
pulls up next dialog, if there is one. gets any updated information from the current grid and runs ErMagicBuilder
6.780525
6.641616
1.020915