code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
DRATS = (old_div(sum_ptrm_checks, x_Arai[end])) * 100. DRATS_prime = (old_div(sum_abs_ptrm_checks, x_Arai[end])) * 100. return DRATS, DRATS_prime
def get_DRATS(sum_ptrm_checks, sum_abs_ptrm_checks, x_Arai, end)
input: sum of ptrm check diffs, sum of absolute value of ptrm check diffs, x_Arai set of points, end. output: DRATS (uses sum of diffs), DRATS_prime (uses sum of absolute diffs)
2.101726
2.13367
0.985029
if not n_pTRM: return float('nan'), float('nan') mean_DRAT = ((old_div(1., n_pTRM)) * (old_div(sum_ptrm_checks, L))) * 100 mean_DRAT_prime = ((old_div(1., n_pTRM)) * (old_div(sum_abs_ptrm_checks, L))) * 100 return mean_DRAT, mean_DRAT_prime
def get_mean_DRAT(sum_ptrm_checks, sum_abs_ptrm_checks, n_pTRM, L)
input: sum_ptrm_checks, sum_abs_ptrm_checks, n_pTRM, L output: mean DRAT (the average difference produced by a pTRM check, normalized by the length of the best-fit line)
1.980775
2.110226
0.938656
if not n_pTRM: return float('nan'), float('nan') mean_DEV = ((old_div(1., n_pTRM)) * (old_div(sum_ptrm_checks, delta_x_prime))) * 100 mean_DEV_prime= ((old_div(1., n_pTRM)) * (old_div(sum_abs_ptrm_checks, delta_x_prime))) * 100 return mean_DEV, mean_DEV_prime
def get_mean_DEV(sum_ptrm_checks, sum_abs_ptrm_checks, n_pTRM, delta_x_prime)
input: sum_ptrm_checks, sum_abs_ptrm_checks, n_pTRM, delta_x_prime output: Mean deviation of a pTRM check
2.097305
2.25805
0.928812
PTRMS = numpy.array(PTRMS) PTRM_Checks = numpy.array(PTRM_Checks) TRM_1 = lib_direct.dir2cart(PTRMS[0,1:3]) PTRMS_cart = [] Checks_cart = [] for num, ptrm in enumerate(PTRMS): ptrm_cart = lib_direct.dir2cart([PTRMS[num][1], PTRMS[num][2], old_div(PTRMS[num][3], NRM)]) PTRMS_...
def get_delta_pal_vectors(PTRMS, PTRM_Checks, NRM)
takes in PTRM data in this format: [temp, dec, inc, moment, ZI or IZ] -- and PTRM_check data in this format: [temp, dec, inc, moment]. Returns them in vector form (cartesian).
2.379424
2.277274
1.044856
ptrm_temps = numpy.array(ptrms_orig)[:,0] check_temps = numpy.array(checks_orig)[:,0] index = numpy.zeros(len(ptrm_temps)) for num, temp in enumerate(ptrm_temps): if len(numpy.where(check_temps == temp)[0]): index[num] = numpy.where(check_temps == temp)[0][0] else: ...
def get_diffs(ptrms_vectors, ptrm_checks_vectors, ptrms_orig, checks_orig)
input: ptrms_vectors, ptrm_checks_vectors, ptrms_orig, checks_orig output: vector diffs between original and ptrm check, C
2.517461
2.482919
1.013912
TRM_star = numpy.zeros([len(ptrms_vectors), 3]) TRM_star[0] = [0., 0., 0.] x_star = numpy.zeros(len(ptrms_vectors)) for num, vec in enumerate(ptrms_vectors[1:]): TRM_star[num+1] = vec + C[num] # print 'vec', vec # print 'C', C[num] for num, trm in enumerate(TRM_star): ...
def get_TRM_star(C, ptrms_vectors, start, end)
input: C, ptrms_vectors, start, end output: TRM_star, x_star (for delta_pal statistic)
2.879695
2.785906
1.033665
#print "x_star, should be same as Xcorr / NRM" #print x_star x_star_mean = numpy.mean(x_star) x_err = x_star - x_star_mean b_star = -1* numpy.sqrt( old_div(sum(numpy.array(y_err)**2), sum(numpy.array(x_err)**2)) ) # averaged slope #print "y_segment", y_segment b_star = numpy.sign(sum(x...
def get_b_star(x_star, y_err, y_mean, y_segment)
input: x_star, y_err, y_mean, y_segment output: b_star (corrected slope for delta_pal statistic)
3.929813
3.824688
1.027486
delta_pal = numpy.abs(old_div((b - b_star), b)) * 100 return delta_pal
def get_delta_pal(b, b_star)
input: b, b_star (actual and corrected slope) output: delta_pal
4.24024
4.0484
1.047387
#print "-------" #print "calling get_full_delta_pal in lib" # return 0 PTRMS_cart, checks, TRM_1 = get_delta_pal_vectors(PTRMS, PTRM_Checks, NRM) # print "PTRMS_Cart", PTRMS_cart diffs, C = get_diffs(PTRMS_cart, checks, PTRMS, PTRM_Checks) # print "C", C TRM_star, x_star = get_TRM_star...
def get_full_delta_pal(PTRMS, PTRM_Checks, NRM, y_err, y_mean, b, start, end, y_segment)
input: PTRMS, PTRM_Checks, NRM, y_err, y_mean, b, start, end, y_segment runs full sequence necessary to get delta_pal
3.912563
3.716794
1.052671
ptrms_included = [] checks_included = [] ptrms = numpy.array(ptrms) for ptrm in ptrms: if ptrm[0] <= tmax: ptrms_included.append(ptrm) for check in ptrm_checks: if check[0] <= tmax: checks_included.append(check) #print "checks", ptrm_checks #print...
def get_segments(ptrms, ptrm_checks, tmax)
input: ptrms, ptrm_checks, tmax grabs ptrms that are done below tmax grabs ptrm checks that are done below tmax AND whose starting temp is below tmax output: ptrms_included, checks_included
2.379215
1.922018
1.237873
if self.GUI==None: return self.GUI.current_fit = self if self.tmax != None and self.tmin != None: self.GUI.update_bounds_boxes() if self.PCA_type != None: self.GUI.update_PCA_box() try: self.GUI.zijplot except AttributeError: self.GUI.draw...
def select(self)
Makes this fit the selected fit on the GUI that is it's parent (Note: may be moved into GUI soon)
7.076731
5.966331
1.186111
if coordinate_system == 'DA-DIR' or coordinate_system == 'specimen': return self.pars elif coordinate_system == 'DA-DIR-GEO' or coordinate_system == 'geographic': return self.geopars elif coordinate_system == 'DA-DIR-TILT' or coordinate_system == 'tilt-corrected'...
def get(self,coordinate_system)
Return the pmagpy paramters dictionary associated with this fit and the given coordinate system @param: coordinate_system -> the coordinate system who's parameters to return
4.753367
4.107324
1.15729
if specimen != None: if type(new_pars)==dict: if 'er_specimen_name' not in list(new_pars.keys()): new_pars['er_specimen_name'] = specimen if 'specimen_comp_name' not in list(new_pars.keys()): new_pars['specimen_comp_name'] = self.name if type(new...
def put(self,specimen,coordinate_system,new_pars)
Given a coordinate system and a new parameters dictionary that follows pmagpy convention given by the pmag.py/domean function it alters this fit's bounds and parameters such that it matches the new data. @param: specimen -> None if fit is for a site or a sample or a valid specimen from self.GUI ...
2.486183
2.259495
1.100327
return str(self.name) == str(name) and str(self.tmin) == str(tmin) and str(self.tmax) == str(tmax)
def has_values(self, name, tmin, tmax)
A basic fit equality checker compares name and bounds of 2 fits @param: name -> name of the other fit @param: tmin -> lower bound of the other fit @param: tmax -> upper bound of the other fit @return: boolean comaparing 2 fits
2.277257
2.717764
0.837916
#print "tail_temps: {0}, tmax: {0}".format(tail_temps, tmax) t_index = 0 adj_tmax = 0 if tmax < tail_temps[0]: return 0 try: t_index = list(tail_temps).index(tmax) except: # finds correct tmax if there was no tail check performed at tmax for temp in tail_temps: ...
def get_n_tail(tmax, tail_temps)
determines number of included tail checks in best fit segment
3.506437
3.220932
1.088641
if not n_tail: return float('nan'), [] tail_compare = [] y_Arai_compare = [] for temp in tail_temps[:n_tail]: tail_index = list(tail_temps).index(temp) tail_check = y_tail[tail_index] tail_compare.append(tail_check) arai_index = list(t_Arai).index(temp) ...
def get_max_tail_check(y_Arai, y_tail, t_Arai, tail_temps, n_tail)
input: y_Arai, y_tail, t_Arai, tail_temps, n_tail output: max_check, diffs
2.593626
2.303735
1.125835
if max_check == 0: return float('nan') DRAT_tail = (old_div(max_check, L)) * 100. return DRAT_tail
def get_DRAT_tail(max_check, L)
input: tail_check_max, best fit line length output: DRAT_tail
3.794321
3.183594
1.191836
if tail_check_max == 0 or numpy.isnan(tail_check_max): return float('nan') delta_TR = (old_div(tail_check_max, abs(y_int))) * 100. return delta_TR
def get_delta_TR(tail_check_max, y_int)
input: tail_check_max, y_intercept output: delta_TR
3.201471
3.077257
1.040365
if tail_check_max == 0 or numpy.isnan(tail_check_max): return float('nan') MD_VDS = (old_div(tail_check_max, vds)) * 100 return MD_VDS
def get_MD_VDS(tail_check_max, vds)
input: tail_check_max, vector difference sum output: MD_VDS
3.378304
3.097763
1.090563
dir_path='.' zfile='zeq_redo' 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] if '-F' in sys.argv...
def main()
NAME dir_redo.py DESCRIPTION converts the Cogne DIR format to PmagPy redo file SYNTAX dir_redo.py [-h] [command line options] OPTIONS -h: prints help message and quits -f FILE: specify input file -F FILE: specify output file, default is 'zeq_redo'
3.47656
3.214935
1.081378
#enable or disable self.btn1a if self.data_model_num == 3: self.btn1a.Enable() else: self.btn1a.Disable() # # set pmag_gui_dialogs global pmag_gui_dialogs if self.data_model_num == 2: pmag_gui_dialogs = pgd2 ...
def set_dm(self, num)
Make GUI changes based on data model num. Get info from WD in appropriate format.
4.307293
3.87906
1.110396
wait = wx.BusyInfo('Reading in data from current working directory, please wait...') #wx.Yield() print('-I- Read in any available data from working directory') self.contribution = cb.Contribution(self.WD, dmodel=self.data_model) del wait
def get_wd_data(self)
Show dialog to get user input for which directory to set as working directory. Called by self.get_dm_and_wd
16.086525
15.915738
1.010731
wait = wx.BusyInfo('Reading in data from current working directory, please wait...') #wx.Yield() print('-I- Read in any available data from working directory (data model 2)') self.er_magic = builder.ErMagicBuilder(self.WD, data_mod...
def get_wd_data2(self)
Get 2.5 data from self.WD and put it into ErMagicBuilder object. Called by get_dm_and_wd
20.272758
12.926164
1.568351
if "-WD" in sys.argv and self.FIRST_RUN: ind = sys.argv.index('-WD') self.WD = os.path.abspath(sys.argv[ind+1]) os.chdir(self.WD) self.WD = os.getcwd() self.dir_path.SetValue(self.WD) else: self.on_change_dir_button(None) ...
def get_dir(self)
Choose a working directory dialog. Called by self.get_dm_and_wd.
3.718477
3.261161
1.140231
if not self.check_for_meas_file(): return if not self.check_for_uncombined_files(): return outstring = "thellier_gui.py -WD %s"%self.WD print("-I- running python script:\n %s"%(outstring)) if self.data_model_num == 2.5: thellier_gui.ma...
def on_btn_thellier_gui(self, event)
Open Thellier GUI
5.732827
5.69562
1.006533
if not self.check_for_meas_file(): return if not self.check_for_uncombined_files(): return outstring = "demag_gui.py -WD %s"%self.WD print("-I- running python script:\n %s"%(outstring)) if self.data_model_num == 2: demag_gui.start(sel...
def on_btn_demag_gui(self, event)
Open Demag GUI
5.903833
5.761805
1.02465
dia = pw.UpgradeDialog(None) dia.Center() res = dia.ShowModal() if res == wx.ID_CANCEL: webbrowser.open("https://www2.earthref.org/MagIC/upgrade", new=2) return ## more nicely styled way, but doesn't link to earthref #msg = "This tool is m...
def on_btn_convert_3(self, event)
Open dialog for rough conversion of 2.5 files to 3.0 files. Offer link to earthref for proper upgrade.
5.433988
5.210323
1.042927
# make sure we have a measurements file if not self.check_for_meas_file(): return # make sure all files of the same type have been combined if not self.check_for_uncombined_files(): return if self.data_model_num == 2: wait = wx.BusyInf...
def on_btn_metadata(self, event)
Initiate the series of windows to add metadata to the contribution.
4.647913
4.50109
1.03262
self.check_dia = pmag_er_magic_dialogs.ErMagicCheckFrame(self, 'Check Data', self.WD, self.er_magic)
def init_check_window2(self)
initiates the object that will control steps 1-6 of checking headers, filling in cell values, etc.
28.173519
26.812321
1.050768
self.check_dia = pmag_er_magic_dialogs.ErMagicCheckFrame3(self, 'Check Data', self.WD, self.contribution)
def init_check_window(self)
initiates the object that will control steps 1-6 of checking headers, filling in cell values, etc.
41.324818
39.735718
1.039992
wait = wx.BusyInfo('Compiling required data, please wait...') wx.SafeYield() #dw, dh = wx.DisplaySize() size = wx.DisplaySize() size = (size[0]-0.1 * size[0], size[1]-0.1 * size[1]) if self.data_model_num == 3: frame = pmag_gui_dialogs.OrientFrameGrid...
def on_btn_orientation(self, event)
Create and fill wxPython grid for entering orientation data.
5.697572
5.365642
1.061862
dlg = wx.FileDialog( None, message = "choose txt file to unpack", defaultDir=self.WD, defaultFile="", style=wx.FD_OPEN #| wx.FD_CHANGE_DIR ) if dlg.ShowModal() == wx.ID_OK: FILE = dlg.GetPath() input_dir, f = os...
def on_btn_unpack(self, event)
Create dialog to choose a file to unpack with download magic. Then run download_magic and create self.contribution.
5.008838
4.635531
1.080532
if not self.check_for_uncombined_files(): return outstring="upload_magic.py" print("-I- running python script:\n %s"%(outstring)) wait = wx.BusyInfo("Please wait, working...") wx.SafeYield() self.contribution.tables['measurements'].add_measurement_nam...
def on_btn_upload(self, event)
Try to run upload_magic. Open validation mode if the upload file has problems.
4.665507
4.541836
1.027229
self.Enable() self.Show() self.magic_gui_frame.Destroy()
def on_end_validation(self, event)
Switch back from validation mode to main Pmag GUI mode. Hide validation frame and show main frame.
14.623173
7.372368
1.983511
# also delete appropriate copy file try: self.help_window.Destroy() except: pass if '-i' in sys.argv: self.Destroy() try: sys.exit() # can raise TypeError if wx inspector was used except Exception as ex: ...
def on_menu_exit(self, event)
Exit the GUI
9.182778
9.212513
0.996772
wd_files = os.listdir(self.WD) if self.data_model_num == 2: ftypes = ['er_specimens.txt', 'er_samples.txt', 'er_sites.txt', 'er_locations.txt', 'pmag_specimens.txt', 'pmag_samples.txt', 'pmag_sites.txt', 'rmag_specimens.txt', 'rmag_results.txt', 'rmag_anisotropy.txt'] else: ...
def check_for_uncombined_files(self)
Go through working directory and check for uncombined files. (I.e., location1_specimens.txt and location2_specimens.txt but no specimens.txt.) Show a warning if uncombined files are found. Return True if no uncombined files are found OR user elects to continue anyway.
3.698585
3.417016
1.082402
if self.data_model_num == 2: meas_file_name = "magic_measurements.txt" dm = "2.5" else: meas_file_name = "measurements.txt" dm = "3.0" if not os.path.isfile(os.path.join(self.WD, meas_file_name)): pw.simple_warning("Your workin...
def check_for_meas_file(self)
Check the working directory for a measurement file. If not found, show a warning and return False. Otherwise return True.
7.966942
7.627094
1.044558
args = sys.argv if "-h" in args: print(main.__doc__) sys.exit() dir_path = pmag.get_named_arg('-WD', '.') fmt = pmag.get_named_arg('-fmt', 'svg') save_plots = False interactive = True if '-sav' in sys.argv: save_plots = True interactive = False infile...
def main()
NAME dayplot_magic.py DESCRIPTION makes 'day plots' (Day et al. 1977) and squareness/coercivity, plots 'linear mixing' curve from Dunlop and Carter-Stiglitz (2006). squareness coercivity of remanence (Neel, 1955) plots after Tauxe et al. (2002) SYNTAX dayplo...
3.782117
2.689426
1.406292
pmag_menu_dialogs.MoveFileIntoWD(self.parent, self.parent.WD)
def on_import1(self, event)
initialize window to import an arbitrary file into the working directory
51.942787
35.365383
1.468747
pmag_menu_dialogs.ImportAzDipFile(self.parent, self.parent.WD)
def orient_import2(self, event)
initialize window to import an AzDip format file into the working directory
48.650883
19.050924
2.553728
if 84 >= Lat >= 72: return 'X' elif 72 > Lat >= 64: return 'W' elif 64 > Lat >= 56: return 'V' elif 56 > Lat >= 48: return 'U' elif 48 > Lat >= 40: return 'T' elif 40 > Lat >= 32: return 'S' elif 32 > Lat >= 24: return 'R' elif 24 > Lat ...
def _UTMLetterDesignator(Lat)
This routine determines the correct UTM letter designator for the given latitude returns 'Z' if latitude is outside the UTM limits of 84N to 80S Written by Chuck Gantz- chuck.gantz@globalstar.com
1.346076
1.270089
1.059828
k0 = 0.9996 a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius] eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared] e1 = old_div((1-sqrt(1-eccSquared)),(1+sqrt(1-eccSquared))) #NorthernHemisphere; //1 for northern hemispher, 0 for southern x = e...
def UTMtoLL(ReferenceEllipsoid, easting, northing, zone)
converts UTM coords to lat/long. Equations from USGS Bulletin 1532 East Longitudes are positive, West longitudes are negative. North latitudes are positive, South latitudes are negative Lat and Long are in decimal degrees. Written by Chuck Gantz- chuck.gantz@globalstar.com Conve...
1.786418
1.800434
0.992215
currentDirectory = self.WD #os.getcwd() change_dir_dialog = wx.DirDialog(self.panel, "Choose your working directory to create or edit a MagIC contribution:", defaultPath=currentDirectory, ...
def on_change_dir_button(self, event=None)
create change directory frame
3.134894
3.125379
1.003045
if has_problems: self.validation_mode = set(has_problems) # highlighting doesn't work with Windows if sys.platform in ['win32', 'win62']: self.message.SetLabel('The following grid(s) have incorrect or incomplete data:\n{}'.format(', '.join(self.valida...
def highlight_problems(self, has_problems)
Outline grid buttons in red if they have validation errors
4.93057
4.735405
1.041214
for dtype in ["specimens", "samples", "sites", "locations", "ages"]: wind = self.FindWindowByName(dtype + '_btn') wind.Unbind(wx.EVT_PAINT, handler=self.highlight_button) self.Refresh() #self.message.SetLabel('Highlighted grids have incorrect or incomplete data')...
def reset_highlights(self)
Remove red outlines from all buttons
10.976931
10.098999
1.086933
wind = event.GetEventObject() pos = wind.GetPosition() size = wind.GetSize() try: dc = wx.PaintDC(self) except wx._core.PyAssertionError: # if it's not a native paint event, we can't us wx.PaintDC dc = wx.ClientDC(self) dc.SetP...
def highlight_button(self, event)
Draw a red highlight line around the event object
3.302558
3.064418
1.077711
dia = pmag_menu_dialogs.ClearWD(self.parent, self.parent.WD) clear = dia.do_clear() if clear: print('-I- Clear data object') self.contribution = cb.Contribution(self.WD, dmodel=self.data_model) self.edited = False
def on_clear(self, event)
initialize window to allow user to empty the working directory
12.605948
11.702265
1.077223
if self.parent.grid_frame: self.parent.grid_frame.onSave(None) self.parent.grid_frame.Destroy()
def on_close_grid(self, event)
If there is an open grid, save its data and close it.
5.050507
3.560501
1.418482
firstline,itilt,igeo,linecnt,key=1,0,0,0,"" out="" data,k15=[],[] dir='./' ofile="" if '-WD' in sys.argv: ind=sys.argv.index('-WD') dir=sys.argv[ind+1]+'/' if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-i' in sys.argv: file=input("In...
def main()
NAME k15_s.py DESCRIPTION converts .k15 format data to .s format. assumes Jelinek Kappabridge measurement scheme SYNTAX k15_s.py [-h][-i][command line options][<filename] OPTIONS -h prints help message and quits -i allows interactive entry of options...
3.311236
3.10525
1.066335
if '-h' in sys.argv: print(main.__doc__) sys.exit() elif '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') data=f.readlines() elif '-i' not in sys.argv: data=sys.stdin.readlines() if '-i' not in sys.argv: for ...
def main()
NAME dipole_plat.py DESCRIPTION gives paleolatitude from given inclination, assuming GAD field SYNTAX dipole_plat.py [command line options]<filename OPTIONS -h prints help message and quits -i allows interactive entry of latitude -f file, specifies file n...
4.174235
3.27567
1.274315
if '-h' in sys.argv: print(main.__doc__) return dir_path = pmag.get_named_arg("-WD", default_val=os.getcwd()) meas_file = pmag.get_named_arg( "-f", default_val="measurements.txt") spec_file = pmag.get_named_arg( "-fsp", default_val="specimens.txt") specimen = pma...
def main()
NAME zeq_magic.py DESCRIPTION reads in a MagIC measurements formatted file, makes plots of remanence decay during demagnetization experiments. Reads in prior interpretations saved in a specimens formatted file interpretations in a specimens file. interpretations are saved in...
2.63472
2.130167
1.236861
sx = sx + x[i] sx2 = sx2 + x[i]**2 sx3 = sx3 + x[i]**3 sy = sy + y[i] sy2 = sy2 + y[i]**2 sy3 = sy3 + y[i]**3 sxy = sxy + x[i] * y[i] sxy2 = sxy2 + x[i] * y[i]**2 syx2 = syx2 + y[i] * x[i]**2 A = n * sx2 - sx**2 B = n * sxy - sx*sy C =...
def fitcircle(n, x, y): # n points, x points, y points # adding in normalize vectors step #x = numpy.array(x) / max(x) #y = numpy.array(y) / max(y) # sx, sx2, sx3, sy, sy2, sy3, sxy, sxy2, syx2 = (0,) * 9 print(type(sx), sx) for i in range(n)
c Fit circle to arbitrary number of x,y pairs, based on the c modified least squares method of Umback and Jones (2000), c IEEE Transactions on Instrumentation and Measurement.
2.260797
2.285125
0.989354
if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-i' in sys.argv: # if one is -i while 1: try: ans=input("Input Pole Latitude [positive north]: <cntrl-D to quit> ") plat=float(ans) # assign input to plat, after conversion to float...
def main()
NAME vgp_di.py DESCRIPTION converts site latitude, longitude and pole latitude, longitude to declination, inclination SYNTAX vgp_di.py [-h] [-i] [-f FILE] [< filename] OPTIONS -h prints help message and quits -i interactive data entry -f FILE to specif...
4.297571
3.566052
1.205134
PmagPyDir = os.path.abspath(".") COMMAND = % (PmagPyDir, PmagPyDir, PmagPyDir, PmagPyDir) frc_path = os.path.join( os.environ["HOME"], ".bashrc") # not recommended, but hey it freaking works fbprof_path = os.path.join(os.environ["HOME"], ".bash_profile") fprof_path = os.path.join(os.e...
def unix_install()
Edits or creates .bashrc, .bash_profile, and .profile files in the users HOME directory in order to add your current directory (hopefully your PmagPy directory) and assorted lower directories in the PmagPy/programs directory to your PATH environment variable. It also adds the PmagPy and the PmagPy/progr...
3.868872
3.296403
1.173665
if not path_to_python: print("Please enter the path to your python.exe you wish Windows to use to run python files. If you do not, this script will not be able to set up a full python environment in Windows. If you already have a python environment set up in Windows such that you can run python scripts...
def windows_install(path_to_python="")
Sets the .py extension to be associated with the ftype Python which is then set to the python.exe you provide in the path_to_python variable or after the -p flag if run as a script. Once the python environment is set up the function proceeds to set PATH and PYTHONPATH using setx. Parameters -------...
3.212929
3.14318
1.02219
do_help = pmag.get_flag_arg_from_sys('-h') if do_help: print(main.__doc__) return False res_file = pmag.get_named_arg('-f', 'pmag_results.txt') crit_file = pmag.get_named_arg('-fcr', '') spec_file = pmag.get_named_arg('-fsp', '') age_file = pmag.get_named_arg('-fa', '') ...
def main()
NAME pmag_results_extract.py DESCRIPTION make a tab delimited output file from pmag_results table SYNTAX pmag_results_extract.py [command line options] OPTIONS -h prints help message and quits -f RFILE, specify pmag_results table; default is pmag_results.txt ...
2.931121
2.361638
1.241139
dir_path='.' tspec="thellier_specimens.txt" aspec="AC_specimens.txt" ofile="TorAC_specimens.txt" critfile="pmag_criteria.txt" ACSamplist,Samplist,sigmin=[],[],10000 GoodSamps,SpecOuts=[],[] # get arguments from command line if '-h' in sys.argv: print(main.__doc__) sy...
def main()
NAME replace_AC_specimens.py DESCRIPTION finds anisotropy corrected data and replaces that specimen with it. puts in pmag_specimen format file SYNTAX replace_AC_specimens.py [command line options] OPTIONS -h prints help message and quits -...
2.815912
2.447563
1.150496
''' # Check if specimen pass Acceptance criteria ''' #if 'pars' not in self.Data[specimen].kes(): # return pars['specimen_fail_criteria']=[] for crit in list(acceptance_criteria.keys()): if crit not in list(pars.keys()): continue if acceptance_criteria[crit]['...
def check_specimen_PI_criteria(pars,acceptance_criteria)
# Check if specimen pass Acceptance criteria
3.699362
3.523345
1.049957
dir_path = "./" if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path = sys.argv[ind+1] if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-f' in sys.argv: ind = sys.argv.index('-f') magic_file = dir_path+'/'+sys.argv[ind+1] else: ...
def main()
NAME grab_magic_key.py DESCRIPTION picks out key and saves to file SYNTAX grab_magic_key.py [command line optins] OPTIONS -h prints help message and quits -f FILE: specify input magic format file -key KEY: specify key to print to standard output
2.706456
2.375403
1.139367
if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-i' in sys.argv: # if one is -i while 1: try: ans=input("Input Declination: <cntrl-D to quit> ") Dec=float(ans) # assign input to Dec, after conversion to floating point ...
def main()
NAME dia_vgp.py DESCRIPTION converts declination inclination alpha95 to virtual geomagnetic pole, dp and dm SYNTAX dia_vgp.py [-h] [-i] [-f FILE] [< filename] OPTIONS -h prints help message and quits -i interactive data entry -f FILE to specify file na...
4.087254
3.362762
1.215446
fmt='svg' title="" if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] X=numpy.loadtxt(file) file=sys.argv[ind+2] X2=numpy.loadtxt(file) # else: # X=numpy.loadtxt(sys.std...
def main()
NAME plot_2cdfs.py DESCRIPTION makes plots of cdfs of data in input file SYNTAX plot_2cdfs.py [-h][command line options] OPTIONS -h prints help message and quits -f FILE1 FILE2 -t TITLE -fmt [svg,eps,png,pdf,jpg..] specify format of output figure, ...
2.899871
2.868151
1.011059
infile='pmag_specimens.txt' sampfile="er_samples.txt" outfile="er_samples.txt" # get command line stuff if "-h" in sys.argv: print(main.__doc__) sys.exit() if '-fsp' in sys.argv: ind=sys.argv.index("-fsp") infile=sys.argv[ind+1] if '-fsm' in sys.argv: ...
def main()
NAME reorder_samples.py DESCRIPTION takes specimen file and reorders sample file with selected orientation methods placed first SYNTAX reorder_samples.py [command line options] OPTIONS -h prints help message and quits -fsp: specimen input pmag_specimens format file...
2.422288
1.903953
1.272242
def can_iter(x): try: any(x) return True except TypeError: return False def not_empty(x): if len(x): return True return False def exists(x): if x: return True retur...
def not_null(val, zero_as_null=True)
Comprehensive check to see if a value is null or not. Returns True for: non-empty iterables, True, non-zero floats and ints, non-emtpy strings. Returns False for: empty iterables, False, zero, empty strings. Parameters ---------- val : any Python object zero_as_null: bool treat zero...
3.721386
3.553366
1.047285
# possible intensity columns intlist = ['magn_moment', 'magn_volume', 'magn_mass','magn_uncal'] # intensity columns that are in the data int_meths = [col_name for col_name in data.columns if col_name in intlist] # drop fully null columns data.dropna(axis='columns', how='all') # ignore c...
def get_intensity_col(data)
Check measurement dataframe for intensity columns 'magn_moment', 'magn_volume', 'magn_mass','magn_uncal'. Return the first intensity column that is in the dataframe AND has data. Parameters ---------- data : pandas DataFrame Returns --------- str intensity method column or ""
4.535319
3.136352
1.446049
reqd_tables = ['measurements', 'specimens', 'samples', 'sites'] con = Contribution(dir_path, read_tables=reqd_tables) # check that all required tables are available missing_tables = [] for table in reqd_tables: if table not in con.tables: missing_tables.append(table) if ...
def add_sites_to_meas_table(dir_path)
Add site columns to measurements table (e.g., to plot intensity data), or generate an informative error message. Parameters ---------- dir_path : str directory with data files Returns ---------- status : bool True if successful, else False data : pandas DataFrame ...
3.589623
3.80361
0.943741
# initialize dropna = list(dropna) reqd_cols = list(reqd_cols) # get intensity column try: magn_col = get_intensity_col(data) except AttributeError: return False, "Could not get intensity method from data" # drop empty columns if magn_col not in dropna: dropn...
def prep_for_intensity_plot(data, meth_code, dropna=(), reqd_cols=())
Strip down measurement data to what is needed for an intensity plot. Find the column with intensity data. Drop empty columns, and make sure required columns are present. Keep only records with the specified method code. Parameters ---------- data : pandas DataFrame measurement dataframe...
2.91621
2.727689
1.069114
df = df.copy() df[col_name] = df[col_name].fillna("") df[col_name] = df[col_name].astype(str) return df
def stringify_col(df, col_name)
Take a dataframe and string-i-fy a column of values. Turn nan/None into "" and all other values into strings. Parameters ---------- df : dataframe col_name : string
2.03361
2.254746
0.901924
if dtype not in self.table_names: print("-W- {} is not a valid MagIC table name".format(dtype)) print("-I- Valid table names are: {}".format(", ".join(self.table_names))) return data_container = MagicDataFrame(dtype=dtype, columns=col_names, groups=groups) ...
def add_empty_magic_table(self, dtype, col_names=None, groups=None)
Add a blank MagicDataFrame to the contribution. You can provide either a list of column names, or a list of column group names. If provided, col_names takes precedence.
4.107532
4.045399
1.015359
self.tables[dtype] = MagicDataFrame(dtype=dtype, data=data) if dtype == 'measurements': self.tables['measurements'].add_sequence() return dtype, self.tables[dtype]
def add_magic_table_from_data(self, dtype, data)
Add a MagIC table to the contribution from a data list Parameters ---------- dtype : str MagIC table type, i.e. 'specimens' data : list of dicts data list with format [{'key1': 'val1', ...}, {'key1': 'val2', ...}, ... }]
5.32988
5.555773
0.959341
if df is None: # if providing a filename but no data type if dtype == "unknown": filename = os.path.join(self.directory, fname) if not os.path.exists(filename): return False, False data_container = MagicDataFram...
def add_magic_table(self, dtype, fname=None, df=None)
Read in a new file to add a table to self.tables. Requires dtype argument and EITHER filename or df. Parameters ---------- dtype : str MagIC table name (plural, i.e. 'specimens') fname : str filename of MagIC format file (short path, directory...
3.012653
2.940735
1.024456
meas_df = self.tables['measurements'].df names_list = ['specimen', 'sample', 'site', 'location'] # add in any tables that you can for num, name in enumerate(names_list): # don't replace tables that already exist if (name + "s") in self.tables: ...
def propagate_measurement_info(self)
Take a contribution with a measurement table. Create specimen, sample, site, and location tables using the unique names in the measurement table to fill in the index.
3.997929
3.63149
1.100906
if table_name not in self.ancestry: return None, None parent_ind = self.ancestry.index(table_name) + 1 if parent_ind + 1 > len(self.ancestry): parent_name = None else: parent_name = self.ancestry[parent_ind] child_ind = self.ancestry.i...
def get_parent_and_child(self, table_name)
Get the name of the parent table and the child table for a given MagIC table name. Parameters ---------- table_name : string of MagIC table name ['specimens', 'samples', 'sites', 'locations'] Returns ------- parent_name : string of parent table name chil...
1.693325
1.750224
0.967491
cols = ['lithologies', 'geologic_types', 'geologic_classes'] #for table in ['specimens', 'samples']: # convert "Not Specified" to blank #self.tables[table].df.replace("^[Nn]ot [Ss]pecified", '', # regex=True, inplace=True) ...
def propagate_lithology_cols(self)
Propagate any data from lithologies, geologic_types, or geologic_classes from the sites table to the samples and specimens table. In the samples/specimens tables, null or "Not Specified" values will be overwritten based on the data from their parent site.
3.951835
3.232747
1.222439
# define some helper methods: def put_together_if_list(item): try: res = ":".join(item) return ":".join(item) except TypeError as ex: #print ex return item def replace_colon_delimited_...
def rename_item(self, table_name, item_old_name, item_new_name)
Rename item (such as a site) everywhere that it occurs. This change often spans multiple tables. For example, a site name will occur in the sites table, the samples table, and possibly in the locations/ages tables.
2.736309
2.716994
1.007109
if ind >= len(self.ancestry): return "", "" if ind > -1: table_name = self.ancestry[ind] ###name = table_name[:-1] + "_name" name = table_name[:-1] return table_name, name return "", ""
def get_table_name(self, ind)
Return both the table_name (i.e., 'specimens') and the col_name (i.e., 'specimen') for a given index in self.ancestry.
4.931142
3.739619
1.318622
print("-I- Trying to propagate {} columns from {} table into {} table".format(cols, source_df_name, target_df_name)) # make...
def propagate_cols_up(self, cols, target_df_name, source_df_name)
Take values from source table, compile them into a colon-delimited list, and apply them to the target table. This method won't overwrite values in the target table, it will only supply values where they are missing. Parameters ---------- cols : list-like list...
2.65999
2.559061
1.03944
def get_level(ser, levels=('specimen', 'sample', 'site', 'location')): for level in levels: if pd.notnull(ser[level]): if len(ser[level]): # guard against empty strings return level return # get available level...
def get_age_levels(self)
Method to add a "level" column to the ages table. Finds the lowest filled in level (i.e., specimen, sample, etc.) for that particular row. I.e., a row with both site and sample name filled in is considered a sample-level age. Returns --------- self.tables['ages']...
4.095322
3.133826
1.306812
# if there is no age table, skip if 'ages' not in self.tables: return # if age table has no data, skip if not len(self.tables['ages'].df): return # get levels in age table self.get_age_levels() # if age levels could not be determin...
def propagate_ages(self)
Mine ages table for any age data, and write it into specimens, samples, sites, locations tables. Do not overwrite existing age data.
3.467269
3.36473
1.030475
for table_name in self.tables: table = self.tables[table_name] table.remove_non_magic_cols_from_table()
def remove_non_magic_cols(self)
Remove all non-MagIC columns from all tables.
3.44949
2.715306
1.270387
if custom_name: fname = custom_name else: fname = self.filenames[dtype] if not dir_path: dir_path=self.directory if dtype in self.tables: write_df = self.remove_names(dtype) outfile = self.tables[dtype].write_magic_file...
def write_table_to_file(self, dtype, custom_name=None, append=False, dir_path=None)
Write out a MagIC table to file, using custom filename as specified in self.filenames. Parameters ---------- dtype : str magic table name
4.330293
4.009305
1.080061
if dtype not in self.ancestry: return if dtype in self.tables: # remove extra columns here self_ind = self.ancestry.index(dtype) parent_ind = self_ind + 1 if self_ind < (len(self.ancestry) -1) else self_ind remove = set(self.ancestry)....
def remove_names(self, dtype)
Remove unneeded name columns ('specimen'/'sample'/etc) from the specified table. Parameters ---------- dtype : str Returns --------- pandas DataFrame without the unneeded columns Example --------- Contribution.tables['specimens'].df = Co...
3.732815
3.80388
0.981318
parent_dtype, child_dtype = self.get_parent_and_child(dtype) if not child_dtype in self.tables: return set() items = set(self.tables[dtype].df.index.unique()) items_in_child_table = set(self.tables[child_dtype].df[dtype[:-1]].unique()) return {i for i in (ite...
def find_missing_items(self, dtype)
Find any items that are referenced in a child table but are missing in their own table. For example, a site that is listed in the samples table, but has no entry in the sites table. Parameters ---------- dtype : str table name, e.g. 'specimens' Retur...
3.924477
3.827021
1.025465
con_id = "" if "contribution" in self.tables: if "id" in self.tables["contribution"].df.columns: con_id = str(self.tables["contribution"].df["id"].values[0]) return con_id
def get_con_id(self)
Return contribution id if available
3.385219
2.71224
1.248127
def stringify(x): # float --> string, # truncating floats like 3.0 --> 3 if isinstance(x, float): if x.is_integer(): #print('{} --> {}'.format(x, str(x).rstrip('0').rstrip('.'))) return str(x).rstrip('0').rstrip...
def all_to_str(self)
In all columns, turn all floats/ints into strings. If a float ends with .0, strip off '.0' from the resulting string.
3.056505
2.947147
1.037106
unrecognized_cols = self.get_non_magic_cols() for col in ignore_cols: if col in unrecognized_cols: unrecognized_cols.remove(col) if unrecognized_cols: print('-I- Removing non-MagIC column names from {}:'.format(self.dtype), end=' ') fo...
def remove_non_magic_cols_from_table(self, ignore_cols=())
Remove all non-magic columns from self.df. Changes in place. Parameters ---------- ignore_cols : list-like columns not to remove, whether they are proper MagIC columns or not Returns --------- unrecognized_cols : list any colu...
3.052277
2.79167
1.093352
if sorted(row_data.keys()) != sorted(self.df.columns): # add any new column names for key in row_data: if key not in self.df.columns: self.df[key] = None # add missing column names into row_data for col_label in self.df...
def update_row(self, ind, row_data)
Update a row with data. Must provide the specific numeric index (not row label). If any new keys are present in row_data dictionary, that column will be added to the dataframe. This is done inplace.
2.613307
2.425878
1.077262
# use provided column order, making sure you don't lose any values # from self.df.columns if len(columns): if sorted(self.df.columns) == sorted(columns): self.df.columns = columns else: new_columns = [] new_columns....
def add_row(self, label, row_data, columns="")
Add a row with data. If any new keys are present in row_data dictionary, that column will be added to the dataframe. This is done inplace
3.53629
3.499171
1.010608
df.index = df[name] df.index.name = name + " name" self.df = df
def add_data(self, data): # add append option later df = pd.DataFrame(data) name, dtype = self.get_singular_and_plural_dtype(self.dtype) if name in df.columns
Add df to a MagicDataFrame using a data list. Parameters ---------- data : list of dicts data list with format [{'key1': 'val1', ...}, {'key1': 'val2', ...}, ... }] dtype : str MagIC table type
10.507619
13.483824
0.779276
col_labels = self.df.columns blank_item = pd.Series({}, index=col_labels, name=label) # use .loc to add in place (append won't do that) self.df.loc[blank_item.name] = blank_item return self.df
def add_blank_row(self, label)
Add a blank row with only an index value to self.df. This is done inplace.
6.161639
5.352903
1.151084
self.df = pd.concat([self.df[:ind], self.df[ind+1:]], sort=True) return self.df
def delete_row(self, ind)
remove self.df row at ind inplace
3.148049
2.826414
1.113796
self.df['num'] = list(range(len(self.df))) df_data = self.df # delete all records that meet condition if len(df_data[condition]) > 0: #we have one or more records to delete inds = df_data[condition]['num'] # list of all rows where condition is TRUE for i...
def delete_rows(self, condition, info_str=None)
delete all rows with condition==True inplace Parameters ---------- condition : pandas DataFrame indexer all self.df rows that meet this condition will be deleted info_str : str description of the kind of rows to be deleted, e.g "specimen rows...
4.728871
4.604872
1.026928
# ignore citations if they just say 'This study' if 'citations' in self.df.columns: if list(self.df['citations'].unique()) == ['This study']: ignore_cols = ignore_cols + ('citations',) drop_cols = self.df.columns.difference(ignore_cols) self.df.dropna...
def drop_stub_rows(self, ignore_cols=('specimen', 'sample', 'software_packages', 'num'))
Drop self.df rows that have only null values, ignoring certain columns. Parameters ---------- ignore_cols : list-like list of column names to ignore for Returns --------- self.df : pandas DataFrame
3.194098
3.75672
0.850236
# keep any row with a unique index unique_index = self.df.index.unique() cond1 = ~self.df.index.duplicated(keep=False) # or with actual data ignore_cols = [col for col in ignore_cols if col in self.df.columns] relevant_df = self.df.drop(ignore_cols, axis=1) ...
def drop_duplicate_rows(self, ignore_cols=['specimen', 'sample'])
Drop self.df rows that have only null values, ignoring certain columns BUT only if those rows do not have a unique index. Different from drop_stub_rows because it only drops empty rows if there is another row with that index. Parameters ---------- ignore_cols : ...
3.609466
3.51989
1.025448
# add numeric index column temporarily self.df['num'] = list(range(len(self.df))) df_data = self.df condition2 = (df_data.index == name) # edit first of existing data that meets condition if len(df_data[condition & condition2]) > 0: #we have one or more records ...
def update_record(self, name, new_data, condition, update_only=False, debug=False)
Find the first row in self.df with index == name and condition == True. Update that record with new_data, then delete any additional records where index == name and condition == True. Change is inplace
4.491676
4.207624
1.067509
cols = list(cols) for col in cols: if col not in self.df.columns: self.df[col] = np.nan short_df = self.df[cols] # horrible, bizarre hack to test for pandas malfunction tester = short_df.groupby(short_df.index, sort=False).fillna(method='ffill') if no...
def front_and_backfill(self, cols, inplace=True)
Groups dataframe by index name then replaces null values in selected columns with front/backfilled values if available. Changes self.df inplace. Parameters ---------- self : MagicDataFrame cols : array-like list of column names Returns ------...
3.835676
3.941434
0.973168
# get the group for each column cols = self.df.columns groups = list(map(lambda x: self.data_model.get_group_for_col(self.dtype, x), cols)) sorted_cols = cols.groupby(groups) ordered_cols = [] # put names first try: names = sorted_cols.pop('Na...
def sort_dataframe_cols(self)
Sort self.df so that self.name is the first column, and the rest of the columns are sorted by group.
3.282994
3.036601
1.081141
for col in col_list: if col in self.df.columns: if not all([is_null(val, False) for val in self.df[col]]): return col
def find_filled_col(self, col_list)
return the first col_name from the list that is both a. present in self.df.columns and b. self.df[col_name] has at least one non-null value Parameters ---------- self: MagicDataFrame col_list : iterable list of columns to check Returns -------...
4.128403
3.875601
1.065229
if isinstance(df, type(None)): df = self.df # replace np.nan / None with "" df = df.where(df.notnull(), "") # string-i-fy everything df = df.astype(str) if lst_or_dict == "lst": return list(df.T.apply(dict)) else: ret...
def convert_to_pmag_data_list(self, lst_or_dict="lst", df=None)
Take MagicDataFrame and turn it into a list of dictionaries. This will have the same format as reading in a 2.5 file with pmag.magic_read(), i.e.: if "lst": [{"sample": "samp_name", "azimuth": 12, ...}, {...}] if "dict": {"samp_name": {"azimuth": 12, ...}, "samp_name2...
4.31919
4.61182
0.936548
# if slice is provided, use it if any(df_slice): df_slice = df_slice # if given index_names, grab a slice using fancy indexing elif index_names: df_slice = self.df.loc[index_names] # otherwise, use the full DataFrame else: df_s...
def get_name(self, col_name, df_slice="", index_names="")
Takes in a column name, and either a DataFrame slice or a list of index_names to slice self.df using fancy indexing. Then return the value for that column in the relevant slice. (Assumes that all values for column will be the same in the chosen slice, so return the first one.)
2.761145
2.37894
1.160662
tilt_corr = int(tilt_corr) if isinstance(df_slice, str): if df_slice.lower() == "all": # use entire DataFrame df_slice = self.df elif do_index: # use fancy indexing (but note this will give duplicates) df_slice = self.d...
def get_di_block(self, df_slice=None, do_index=False, item_names=None, tilt_corr='100', excl=None, ignore_tilt=False)
Input either a DataFrame slice or do_index=True and a list of index_names. Optional arguments: Provide tilt_corr (default 100). Excl is a list of method codes to exclude. Output dec/inc from the slice in this format: [[dec1, inc1], [dec2, inc2], ...]. Not ...
4.582019
4.530319
1.011412