code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
ancestry = self.er_magic_data.ancestry
child_type = ancestry[ancestry.index(data_type) - 1]
names = [self.grid.GetCellValue(row, 0) for row in self.selected_rows]
if data_type == 'site':
how_to_fix = 'Make sure to select a new site for each orphaned sample in the nex... | def onDeleteRow(self, event, data_type) | On button click, remove relevant object from both the data model and the grid. | 4.31424 | 4.190672 | 1.029486 |
if event.Col == -1 and event.Row == -1:
pass
elif event.Col < 0:
self.onSelectRow(event)
elif event.Row < 0:
self.drop_down_menu.on_label_click(event) | def onLeftClickLabel(self, event) | When user clicks on a grid label, determine if it is a row label or a col label.
Pass along the event to the appropriate function.
(It will either highlight a column for editing all values, or highlight a row for deletion). | 4.44499 | 4.031965 | 1.102438 |
grid = self.grid
row = event.Row
default = (255, 255, 255, 255)
highlight = (191, 216, 216, 255)
cell_color = grid.GetCellBackgroundColour(row, 0)
attr = wx.grid.GridCellAttr()
if cell_color == default:
attr.SetBackgroundColour(highlight)
... | def onSelectRow(self, event) | Highlight or unhighlight a row for possible deletion. | 2.447914 | 2.312391 | 1.058607 |
data_methods = {'specimen': self.er_magic_data.change_specimen,
'sample': self.er_magic_data.change_sample,
'site': self.er_magic_data.change_site,
'location': self.er_magic_data.change_location,
'age': self... | def update_grid(self, grid) | takes in wxPython grid and ErMagic data object to be updated | 3.302321 | 2.823812 | 1.169455 |
# deselect column, including remove 'EDIT ALL' label
if self.drop_down_menu:
self.drop_down_menu.clean_up()
# save all changes to er_magic data object
self.grid_builder.save_grid_data()
# don't actually write data in this step (time-consuming)
# ins... | def onSave(self, grid):#, age_data_type='site') | Save grid data in the data object | 11.140358 | 11.125902 | 1.001299 |
dir_path='.'
meas_file='magic_measurements.txt'
samp_file="er_samples.txt"
out_file='magic_measurements.txt'
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-WD' in sys.argv:
ind = sys.argv.index('-WD')
dir_path=sys.argv[ind+1]
if '-f' in sys.argv... | def main() | NAME
update_measurements.py
DESCRIPTION
update the magic_measurements table with new orientation info
SYNTAX
update_measurements.py [command line options]
OPTIONS
-h prints help message and quits
-f MFILE, specify magic_measurements file; default is magic_measure... | 2.320462 | 2.120319 | 1.094393 |
out = ""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
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:
dir1, dir2 = [], []
tr... | def main() | NAME
angle.py
DESCRIPTION
calculates angle between two input directions D1,D2
INPUT (COMMAND LINE ENTRY)
D1_dec D1_inc D1_dec D2_inc
OUTPUT
angle
SYNTAX
angle.py [-h][-i] [command line options] [< filename]
OPTIONS
-h prints help and quits
... | 2.938923 | 2.722208 | 1.07961 |
N,kappa,D,I=100,20.,0.,90.
if len(sys.argv)!=0 and '-h' in sys.argv:
print(main.__doc__)
sys.exit()
elif '-i' in sys.argv:
ans=input(' Kappa: ')
kappa=float(ans)
ans=input(' N: ')
N=int(ans)
ans=input(' Mean Dec: ')
D=float(ans)
... | def main() | NAME
fishrot.py
DESCRIPTION
generates set of Fisher distributed data from specified distribution
SYNTAX
fishrot.py [-h][-i][command line options]
OPTIONS
-h prints help message and quits
-i for interactive entry
-k kappa specify kappa, default is 20
... | 2.735889 | 2.226606 | 1.228726 |
ofile=""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-F' in sys.argv:
ind=sys.argv.index('-F')
ofile=sys.argv[ind+1]
out=open(ofile,'w')
if '-flt' in sys.argv:
ind=sys.argv.index('-flt')
flt=float(sys.argv[ind+1])
else:
... | def main() | NAME
squish.py
DESCRIPTION
takes dec/inc data and "squishes" with specified flattening factor, flt
using formula tan(Io)=flt*tan(If)
INPUT
declination inclination
OUTPUT
"squished" declincation inclination
SYNTAX
squish.py [command line ... | 2.81866 | 2.43643 | 1.156881 |
if "-h" in sys.argv:
print(main.__doc__)
sys.exit()
dataframe = extractor.command_line_dataframe([['WD', False, '.'], ['ID', False, '.'], ['f', True, ''], ['Fsa', False, 'samples.txt'], ['DM', False, 3]])
args = sys.argv
checked_args = extractor.extract_and_check_args(args, datafra... | def main() | iodp_samples_magic.py
OPTIONS:
-f FILE, input csv file
-Fsa FILE, output samples file for updating, default is to overwrite existing samples file | 5.642965 | 4.551832 | 1.239713 |
# print "calling cart2dir(), not in anything"
cart=numpy.array(cart)
rad=old_div(numpy.pi,180.) # constant to convert degrees to radians
if len(cart.shape)>1:
Xs,Ys,Zs=cart[:,0],cart[:,1],cart[:,2]
else: #single vector
Xs,Ys,Zs=cart[0],cart[1],cart... | def cart2dir(self,cart) | converts a direction to cartesian coordinates | 4.322353 | 4.258452 | 1.015006 |
# print "calling magic_read(self, infile)", infile
hold,magic_data,magic_record,magic_keys=[],[],{},[]
try:
f=open(infile,"r")
except:
return [],'bad_file'
d = f.readline()[:-1].strip('\n')
if d[0]=="s" or d[1]=="s":
delim='spac... | def magic_read(self,infile) | reads a Magic template file, puts data in a list of dictionaries | 3.081265 | 3.007837 | 1.024412 |
# sort the specimen names
#
# print "calling get_specs()"
speclist=[]
for rec in data:
spec=rec["er_specimen_name"]
if spec not in speclist:speclist.append(spec)
speclist.sort()
#print speclist
return speclist | def get_specs(self,data) | takes a magic format file and returns a list of unique specimen names | 6.132009 | 4.969864 | 1.233838 |
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
dir_path = pmag.get_named_arg("-WD", ".")
# plot: default is 0, if -sav in sys.argv should be 1
interactive = True
save_plots = pmag.get_flag_arg_from_sys("-sav", true=1, false=0)
if save_plots:
interactive = False
... | def main() | NAME
vgpmap_magic.py
DESCRIPTION
makes a map of vgps and a95/dp,dm for site means in a sites table
SYNTAX
vgpmap_magic.py [command line options]
OPTIONS
-h prints help and quits
-eye ELAT ELON [specify eyeball location], default is 90., 0.
-f FILE sites fo... | 2.785435 | 2.043481 | 1.363084 |
num_rows = self.GetNumberRows()
current_grid_rows = [self.GetCellValue(num, 0) for num in range(num_rows)]
er_data = {item.name: item.er_data for item in items_list}
pmag_data = {item.name: item.pmag_data for item in items_list}
items_list = sorted(items_list, key=lambda... | def add_items(self, items_list, incl_pmag=True, incl_parents=True) | Add items and/or update existing items in grid | 2.649594 | 2.510265 | 1.055504 |
self.AppendRows(1)
last_row = self.GetNumberRows() - 1
self.SetCellValue(last_row, 0, str(label))
self.row_labels.append(label)
self.row_items.append(item) | def add_row(self, label='', item='') | Add a row to the grid | 2.762397 | 2.472142 | 1.117411 |
#DeleteRows(self, pos, numRows, updateLabel
if not row_num and row_num != 0:
row_num = self.GetNumberRows() - 1
label = self.GetCellValue(row_num, 0)
self.DeleteRows(pos=row_num, numRows=1, updateLabels=True)
# remove label from row_labels
try:
... | def remove_row(self, row_num=None) | Remove a row from the grid | 5.025679 | 5.039396 | 0.997278 |
if col_label in ['magic_method_codes', 'magic_method_codes++']:
self.add_method_drop_down(col_number, col_label)
if col_label in vocab.possible_vocabularies:
if col_number not in list(self.choices.keys()): # if not already assigned above
self.grid.SetColL... | def add_drop_down(self, col_number, col_label) | Add a correctly formatted drop-down-menu for given col_label, if required.
Otherwise do nothing. | 4.760268 | 4.692792 | 1.014379 |
if self.data_type == 'age':
method_list = vocab.age_methods
elif '++' in col_label:
method_list = vocab.pmag_methods
elif self.data_type == 'result':
method_list = vocab.pmag_methods
else:
method_list = vocab.er_methods
sel... | def add_method_drop_down(self, col_number, col_label) | Add drop-down-menu options for magic_method_codes columns | 4.610744 | 4.633088 | 0.995177 |
if self.selected_col:
col_label_value = self.grid.GetColLabelValue(self.selected_col)
col_label_value = col_label_value.strip('\nEDIT ALL')
self.grid.SetColLabelValue(self.selected_col, col_label_value)
for row in range(self.grid.GetNumberRows()):
... | def clean_up(self):#, grid) | de-select grid cols, refresh grid | 2.798273 | 2.56485 | 1.091008 |
color = self.grid.GetCellBackgroundColour(event.GetRow(), event.GetCol())
# allow user to cherry-pick cells for editing. gets selection of meta key for mac, ctrl key for pc
if event.ControlDown() or event.MetaDown():
row, col = event.GetRow(), event.GetCol()
if ... | def on_left_click(self, event, grid, choices) | creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values | 2.543674 | 2.499791 | 1.017555 |
if self.grid.changes: # if user selects a menuitem, that is an edit
self.grid.changes.add(row)
else:
self.grid.changes = {row}
item_id = event.GetId()
item = event.EventObject.FindItemById(item_id)
label = item.Label
cell_value = grid.Ge... | def on_select_menuitem(self, event, grid, row, col, selection) | sets value of selected cell to value selected from menu | 4.095611 | 3.953412 | 1.035969 |
fmt,plot='svg',0
title=""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-sav' in sys.argv:plot=1
if '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
X=numpy.loadtxt(file)
# else:
# X=numpy.loadtxt(sys.stdin,dtype=numpy.floa... | def main() | NAME
plot_cdf.py
DESCRIPTION
makes plots of cdfs of data in input file
SYNTAX
plot_cdf.py [-h][command line options]
OPTIONS
-h prints help message and quits
-f FILE
-t TITLE
-fmt [svg,eps,png,pdf,jpg..] specify format of output figure, default is ... | 3.010746 | 2.98279 | 1.009373 |
if not requests:
return False
try:
req = requests.get(url, timeout=.2)
if not req.ok:
return []
return req
except (requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError,
requests.exceptions... | def get_json_online(self, url) | Use requests module to json from Earthref.
If this fails or times out, return false.
Returns
---------
result : requests.models.Response, or [] if unsuccessful | 3.485462 | 3.322058 | 1.049188 |
categories = Series(code_types[code_types[mtype] == True].index)
codes = {cat: list(self.get_one_meth_type(cat, all_codes).index) for cat in categories}
return codes | def get_tiered_meth_category(self, mtype, all_codes, code_types) | Get a tiered list of all er/pmag_age codes
i.e. pmag_codes = {'anisotropy_codes': ['code1', 'code2'],
'sample_preparation': [code1, code2], ...} | 5.327725 | 5.573102 | 0.955971 |
if len(VOCAB):
self.set_vocabularies()
return
data = []
controlled_vocabularies = []
# try to get online
if not set_env.OFFLINE:
url = 'https://www2.earthref.org/vocabularies/controlled.json'
try:
raw = self... | def get_controlled_vocabularies(self, vocab_types=default_vocab_types) | Get all non-method controlled vocabularies | 4.423636 | 4.402727 | 1.004749 |
'''
#====================================================================
in:
read measured raw data file,
search the line [' Field Remanence '] in measured data file,
skip all the rows above and the last line,
otherwise, load data as two columns.
#
out:
rawDf,fitDf are... | def loadData(filePath=None) | #====================================================================
in:
read measured raw data file,
search the line [' Field Remanence '] in measured data file,
skip all the rows above and the last line,
otherwise, load data as two columns.
#
out:
rawDf,fitDf are the pandas ... | 3.988074 | 2.359533 | 1.690197 |
'''
#====================================================================
plot the fitted results for data fit and refit
#====================================================================
'''
global _yfits_
_yfits_ = yfit
ax.plot(xfit, yfit)
ax.plot(xfit, np.sum(yfit,axis=1))
... | def fit_plots(ax,xfit,xraw,yfit,yraw) | #====================================================================
plot the fitted results for data fit and refit
#==================================================================== | 6.728464 | 4.510396 | 1.491768 |
outf=""
N=100
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-F' in sys.argv:
ind=sys.argv.index('-F')
outf=sys.argv[ind+1]
if outf!="": out=open(outf,'w')
if '-n' in sys.argv:
ind=sys.argv.index('-n')
N=int(sys.argv[ind+1])
dirs=... | def main() | NAME
uniform.py
DESCRIPTION
draws N directions from uniform distribution on a sphere
SYNTAX
uniform.py [-h][command line options]
-h prints help message and quits
-n N, specify N on the command line (default is 100)
-F file, specify output file name, defaul... | 2.694431 | 2.559347 | 1.052781 |
if 'Top offset (cm)' in df.columns:
offset_key='Top offset (cm)'
elif 'Offset (cm)' in df.columns:
offset_key='Offset (cm)'
else:
print ('No offset key found')
return False,[]
interval=df[offset_key].astype('float').astype('str')
holes=df['Site'].astype('str')+df... | def iodp_sample_names(df) | Convert expedition, hole, section, type, interval to sample name in format:
exp-hole-type-sect-interval
Parameters
___________
df : Pandas DataFrame
dataframe read in from .csv file downloaded from LIMS online database
Returns
--------------
holes : list
IODP Holes nam... | 5.5739 | 4.689844 | 1.188504 |
cwd = os.getcwd()
main_dir = cwd + '/SPD'
try:
import new_lj_thellier_gui_spd as tgs
gui = tgs.Arai_GUI('/magic_measurements.txt', main_dir)
specimens = list(gui.Data.keys())
thing = PintPars(gui.Data, '0238x6011044', 473., 623.)
thing.calculate_all_statistics()
... | def make_thing() | makes example PintPars object | 7.550762 | 6.709851 | 1.125325 |
if len(self.x_Arai_segment) < 4:
self.pars['specimen_k_prime'], self.pars['specimen_k_prime_sse'] = 0, 0
return 0
data = lib_k.AraiCurvature(self.x_Arai_segment, self.y_Arai_segment)
self.pars['specimen_k_prime'] = data[0]
self.pars['specimen_k_prime_sse'... | def get_curve_prime(self) | not in SPD documentation. same as k, but using the segment instead of the full data set | 4.531971 | 3.88533 | 1.166432 |
PTRMS = self.PTRMS[1:]
CART_pTRMS_orig = numpy.array([lib_direct.dir2cart(row[1:4]) for row in PTRMS])
#B_lab_dir = [self.B_lab_dir[0], self.B_lab_dir[1], 1.] # dir
tmin, tmax = self.t_Arai[0], self.t_Arai[-1]
ptrms_dec_Free, ptrms_inc_Free, ptrm_best_fit_vector_Free, pt... | def get_ptrm_dec_and_inc(self) | not included in spd. | 4.184273 | 4.147146 | 1.008953 |
#
# parse command line options
#
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
dir_path = pmag.get_named_arg("-WD", default_val=".")
input_dir_path = pmag.get_named_arg('-ID', "")
input_dir_path, dir_path = pmag.fix_directories(input_dir_path, dir_path)
meas_file = pmag.... | def main() | NAME
thellier_magic.py
DESCRIPTION
plots Thellier-Thellier data in version 3.0 format
Reads saved interpretations from a specimen formatted table, default: specimens.txt
SYNTAX
thellier_magic.py [command line options]
OPTIONS
-h prints help message and quits
... | 2.534327 | 2.072818 | 1.222648 |
if len(DM):
self.dm = DM
self.crit_map = CRIT_MAP
return
if not set_env.OFFLINE:
dm = self.get_dm_online()
if dm:
print('-I- Using online data model')
#self.cache_data_model(dm)
return se... | def get_data_model(self) | Try to download the data model from Earthref.
If that fails, grab the cached data model. | 6.749041 | 5.930315 | 1.138058 |
model_file = self.find_cached_dm()
try:
f = open(model_file, 'r', encoding='utf-8-sig')
except TypeError:
f = open(model_file, 'r')
string = '\n'.join(f.readlines())
f.close()
raw = json.loads(string)
full = pd.DataFrame(raw)
... | def get_dm_offline(self) | Grab the 3.0 data model from the PmagPy/pmagpy directory
Returns
---------
full : DataFrame
cached data model json in DataFrame format | 3.986563 | 3.192938 | 1.248556 |
if not requests:
return False
try:
req = requests.get("https://earthref.org/MagIC/data-models/3.0.json", timeout=3)
if not req.ok:
return False
return req
except (requests.exceptions.ConnectTimeout, requests.exceptions.Conn... | def get_dm_online(self) | Use requests module to get data model from Earthref.
If this fails or times out, return false.
Returns
---------
result : requests.models.Response, False if unsuccessful | 5.005898 | 3.694422 | 1.354988 |
data_model = {}
levels = ['specimens', 'samples', 'sites', 'locations',
'ages', 'measurements', 'criteria', 'contribution',
'images']
criteria_map = pd.DataFrame(full_df['criteria_map'])
for level in levels:
df = pd.DataFrame(full_... | def parse_cache(self, full_df) | Format the cached data model into a dictionary of DataFrames
and a criteria map DataFrame.
Parameters
----------
full_df : DataFrame
result of self.get_dm_offline()
Returns
----------
data_model : dictionary of DataFrames
crit_map : DataFrame | 4.665666 | 4.118067 | 1.132975 |
# data model
tables = pd.DataFrame(data_model)
data_model = {}
for table_name in tables.columns:
data_model[table_name] = pd.DataFrame(tables[table_name]['columns']).T
# replace np.nan with None
data_model[table_name] = data_model[table_name].... | def parse(self, data_model, crit) | Take the relevant pieces of the data model json
and parse into data model and criteria map.
Parameters
----------
data_model : data model piece of json (nested dicts)
crit : criteria map piece of json (nested dicts)
Returns
----------
data_model : dictio... | 3.095528 | 2.912444 | 1.062863 |
tables = raw.json()['tables']
crit = raw.json()['criteria_map']
return self.parse(tables, crit) | def parse_response(self, raw) | Format the requested data model into a dictionary of DataFrames
and a criteria map DataFrame.
Take data returned by a requests.get call to Earthref.
Parameters
----------
raw: 'requests.models.Response'
Returns
---------
data_model : dictionary of DataFr... | 13.954059 | 7.461175 | 1.870223 |
pmag_dir = find_pmag_dir.get_pmag_dir()
if pmag_dir is None:
pmag_dir = '.'
model_file = os.path.join(pmag_dir, 'pmagpy',
'data_model', 'data_model.json')
# for py2app:
if not os.path.isfile(model_file):
model_fil... | def find_cached_dm(self) | Find filename where cached data model json is stored.
Returns
---------
model_file : str
data model json file location | 2.055767 | 1.975929 | 1.040406 |
output_json = json.loads(raw.content)
output_file = self.find_cached_dm()
json.dump(output_json, open(output_file, 'w+')) | def cache_data_model(self, raw) | Cache the data model json.
Take data returned by a requests.get call to Earthref.
Parameters
----------
raw: requests.models.Response | 5.439997 | 5.576272 | 0.975562 |
df = self.dm[table_name]
return list(df['group'].unique()) | def get_groups(self, table_name) | Return list of all groups for a particular data type | 8.107651 | 6.11915 | 1.324964 |
# get all headers of a particular group
df = self.dm[table_name]
cond = df['group'] == group_name
return df[cond].index | def get_group_headers(self, table_name, group_name) | Return a list of all headers for a given group | 6.928447 | 6.926326 | 1.000306 |
df = self.dm[table_name]
cond = df['validations'].map(lambda x: 'required()' in str(x))
return df[cond].index | def get_reqd_headers(self, table_name) | Return a list of all required headers for a particular table | 10.302163 | 8.977221 | 1.147589 |
df = self.dm[table_name]
try:
group_name = df.loc[col_name, 'group']
except KeyError:
return ''
return group_name | def get_group_for_col(self, table_name, col_name) | Check data model to find group name for a given column header
Parameters
----------
table_name: str
col_name: str
Returns
---------
group_name: str | 3.825243 | 4.017732 | 0.95209 |
N,kappa=100,20
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
elif '-i' in sys.argv:
ans=input(' Kappa: ')
kappa=float(ans)
ans=input(' N: ')
N=int(ans)
else:
if '-k' in sys.argv:
ind=sys.argv.index('-k')
kap... | def main() | NAME
fisher.py
DESCRIPTION
generates set of Fisher distribed data from specified distribution
INPUT (COMMAND LINE ENTRY)
OUTPUT
dec, inc
SYNTAX
fisher.py [-h] [-i] [command line options]
OPTIONS
-h prints help message and quits
-i for interactive ... | 2.72541 | 2.467851 | 1.104366 |
dir_path='.'
if '-WD' in sys.argv:
ind=sys.argv.index('-WD')
dir_path=sys.argv[ind+1]
zfile=dir_path+'/zeq_redo'
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-f' in sys.argv:
ind=sys.argv.index('-f')
inspec=dir_path+'/'+sys.argv[ind+1]
... | def main() | NAME
pmm_redo.py
DESCRIPTION
converts the UCSC PMM files format to PmagPy redo file
SYNTAX
pmm_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.609235 | 3.248829 | 1.110934 |
if not items_list:
return ''
string_list = []
for item in items_list:
try:
name = item.name
string_list.append(name)
except AttributeError:
pass
return ":".join(string_list) | def get_item_string(items_list) | take in a list of pmag_objects
return a colon-delimited list of the findable names | 2.639032 | 2.264948 | 1.165162 |
old_data_keys = list(old_dict.keys())
new_data_keys = list(new_dict.keys())
all_keys = set(old_data_keys).union(new_data_keys)
combined_data_dict = {}
for k in all_keys:
try:
combined_data_dict[k] = new_dict[k]
except KeyError:
combined_data_dict[k] = old... | def combine_dicts(new_dict, old_dict) | returns a dictionary with all key, value pairs from new_dict.
also returns key, value pairs from old_dict, if that key does not exist in new_dict.
if a key is present in both new_dict and old_dict, the new_dict value will take precedence. | 1.720615 | 1.702668 | 1.01054 |
if not name_list:
names = [item.name for item in items_list if item]
else:
names = name_list
if item_name in names:
ind = names.index(item_name)
return items_list[ind]
return False | def find_by_name(self, item_name, items_list, name_list=None) | Return item from items_list with name item_name. | 2.305834 | 2.129586 | 1.082761 |
item = self.find_by_name(item_name, items_list)
if not item:
item = self.data_lists[item_type][2](item_name, None)
return item | def find_or_create_by_name(self, item_name, items_list, item_type) | See if item with item_name exists in item_list.
If not, create that item.
Either way, return an item of type item_type. | 3.647676 | 3.54211 | 1.029803 |
if not self.data_model:
self.data_model = validate_upload.get_data_model()
if not self.data_model:
print("Can't access MagIC-data-model at the moment.\nIf you are working offline, make sure MagIC-data-model.txt is in your PmagPy directory (or download it from htt... | def init_default_headers(self) | initialize default required headers.
if there were any pre-existing headers, keep them also. | 2.320349 | 2.274033 | 1.020367 |
specimen = self.find_by_name(spec_name, self.specimens)
measurement = Measurement(exp_name, meas_num, specimen, er_data)
self.measurements.append(measurement)
return measurement | def add_measurement(self, exp_name, meas_num, spec_name=None, er_data=None, pmag_data=None) | Find actual data object for specimen.
Then create a measurement belonging to that specimen and add it to the data object | 2.57832 | 2.440368 | 1.056529 |
specimen = self.find_by_name(old_spec_name, self.specimens)
if not specimen:
print('-W- {} is not a currently existing specimen, so cannot be updated'.format(old_spec_name))
return False
if new_sample_name:
new_sample = self.find_by_name(new_sample_na... | def change_specimen(self, old_spec_name, new_spec_name,
new_sample_name=None, new_er_data=None, new_pmag_data=None,
replace_data=False) | Find actual data objects for specimen and sample.
Then call Specimen class change method to update specimen name and data. | 2.198706 | 2.188006 | 1.004891 |
specimen = self.find_by_name(spec_name, self.specimens)
if not specimen:
return False
sample = specimen.sample
if sample:
sample.specimens.remove(specimen)
self.specimens.remove(specimen)
del specimen
return [] | def delete_specimen(self, spec_name) | Remove specimen with name spec_name from self.specimens.
If the specimen belonged to a sample, remove it from the sample's specimen list. | 2.721157 | 2.282468 | 1.192199 |
if samp_name:
sample = self.find_by_name(samp_name, self.samples)
if not sample:
print(.format(samp_name, samp_name))
sample = self.add_sample(samp_name)
else:
sample = None
specimen = Specimen(spec_name, sample, self.... | def add_specimen(self, spec_name, samp_name=None, er_data=None, pmag_data=None) | Create a Specimen object and add it to self.specimens.
If a sample name is provided, add the specimen to sample.specimens as well. | 2.456594 | 2.38639 | 1.029418 |
sample = self.find_by_name(old_samp_name, self.samples)
if not sample:
print('-W- {} is not a currently existing sample, so it cannot be updated'.format(old_samp_name))
return False
if new_site_name:
new_site = self.find_by_name(new_site_name, self.si... | def change_sample(self, old_samp_name, new_samp_name, new_site_name=None,
new_er_data=None, new_pmag_data=None, replace_data=False) | Find actual data objects for sample and site.
Then call Sample class change method to update sample name and data.. | 2.896879 | 2.890532 | 1.002196 |
if site_name:
site = self.find_by_name(site_name, self.sites)
if not site:
print(.format(site_name, site_name))
site = self.add_site(site_name)
else:
site = None
sample = Sample(samp_name, site, self.data_model, er_data... | def add_sample(self, samp_name, site_name=None, er_data=None, pmag_data=None) | Create a Sample object and add it to self.samples.
If a site name is provided, add the sample to site.samples as well. | 2.488013 | 2.336056 | 1.065049 |
sample = self.find_by_name(sample_name, self.samples)
if not sample:
return False
specimens = sample.specimens
site = sample.site
if site:
site.samples.remove(sample)
self.samples.remove(sample)
for spec in specimens:
s... | def delete_sample(self, sample_name, replacement_samp=None) | Remove sample with name sample_name from self.samples.
If the sample belonged to a site, remove it from the site's sample list.
If the sample had any specimens, change specimen.sample to "". | 3.351785 | 2.387077 | 1.404138 |
site = self.find_by_name(old_site_name, self.sites)
if not site:
print('-W- {} is not a currently existing site, so it cannot be updated.'.format(old_site_name))
return False
if new_location_name:
if site.location:
old_location = self.... | def change_site(self, old_site_name, new_site_name, new_location_name=None,
new_er_data=None, new_pmag_data=None, replace_data=False) | Find actual data objects for site and location.
Then call the Site class change method to update site name and data. | 2.752392 | 2.719438 | 1.012118 |
if location_name:
location = self.find_by_name(location_name, self.locations)
if not location:
location = self.add_location(location_name)
else:
location = None
## check all declinations/azimuths/longitudes in range 0=>360.
#f... | def add_site(self, site_name, location_name=None, er_data=None, pmag_data=None) | Create a Site object and add it to self.sites.
If a location name is provided, add the site to location.sites as well. | 3.169111 | 3.027206 | 1.046877 |
site = self.find_by_name(site_name, self.sites)
if not site:
return False
self.sites.remove(site)
if site.location:
site.location.sites.remove(site)
samples = site.samples
for samp in samples:
samp.site = ''
del site
... | def delete_site(self, site_name, replacement_site=None) | Remove site with name site_name from self.sites.
If the site belonged to a location, remove it from the location's site list.
If the site had any samples, change sample.site to "". | 3.656231 | 2.564705 | 1.425595 |
location = self.find_by_name(old_location_name, self.locations)
if not location:
print('-W- {} is not a currently existing location, so it cannot be updated.'.format(old_location_name))
return False
location.change_location(new_location_name, new_er_data, new_pma... | def change_location(self, old_location_name, new_location_name, new_parent_name=None,
new_er_data=None, new_pmag_data=None, replace_data=False) | Find actual data object for location with old_location_name.
Then call Location class change method to update location name and data. | 3.019348 | 2.869639 | 1.05217 |
if not location_name:
return False
location = Location(location_name, data_model=self.data_model, er_data=er_data, pmag_data=pmag_data)
self.locations.append(location)
return location | def add_location(self, location_name, parent_name=None, er_data=None, pmag_data=None) | Create a Location object and add it to self.locations. | 2.320904 | 2.096155 | 1.10722 |
location = self.find_by_name(location_name, self.locations)
if not location:
return False
sites = location.sites
self.locations.remove(location)
for site in sites:
if site:
site.location = ''
del location
return sit... | def delete_location(self, location_name) | Remove location with name location_name from self.locations.
If the location had any sites, change site.location to "". | 3.733307 | 2.953812 | 1.263894 |
result = self.find_by_name(old_result_name, self.results)
if not result:
msg = '-W- {} is not a currently existing result, so it cannot be updated.'.format(old_result_name)
print(msg)
return False
else:
specimens, samples, sites, locations... | def change_result(self, old_result_name, new_result_name, new_er_data=None,
new_pmag_data=None, spec_names=None, samp_names=None,
site_names=None, loc_names=None, replace_data=False) | Find actual data object for result with old_result_name.
Then call Result class change method to update result name and data. | 1.867539 | 1.844017 | 1.012756 |
meas_file = os.path.join(self.WD, 'magic_measurements.txt')
if not os.path.isfile(meas_file):
print("-I- No magic_measurements.txt file")
return {}
try:
meas_data, file_type = pmag.magic_read(meas_file)
except IOError:
print("-I- N... | def get_data(self) | attempt to read measurements file in working directory. | 2.364628 | 2.31286 | 1.022383 |
# use filename if provided, otherwise find er_ages.txt in WD
if not filename:
short_filename = 'er_ages.txt'
magic_file = os.path.join(self.WD, short_filename)
else:
magic_file = filename
if not os.path.isfile(magic_file):
print('-... | def get_age_info(self, filename=None) | Read er_ages.txt file.
Parse information into dictionaries for each site/sample.
Then add it to the site/sample object as site/sample.age_data. | 4.013684 | 3.962181 | 1.012999 |
if not filename:
short_filename = "pmag_results.txt"
magic_file = os.path.join(self.WD, short_filename)
else:
magic_file = filename
if not os.path.isfile(magic_file):
print('-W- Could not find {} in your working directory {}'.format(short_... | def get_results_info(self, filename=None) | Read pmag_results.txt file.
Parse information into dictionaries for each item.
Then add it to the item object as object.results_data. | 2.492908 | 2.424284 | 1.028307 |
DATA = {}
with open(path, 'r') as fin:
lines = list(fin.readlines())
first_line = lines[0]
if not first_line:
return False, None, 'empty_file'
if first_line[0] == "s" or first_line[1] == "s":
delim = ' '
elif first_line[0] == "... | def read_magic_file(self, path, sort_by_this_name, sort_by_file_type=False) | read a magic-formatted tab-delimited file.
return a dictionary of dictionaries, with this format:
{'Z35.5a': {'specimen_weight': '1.000e-03', 'er_citation_names': 'This study', 'specimen_volume': '', 'er_location_name': '', 'er_site_name': 'Z35.', 'er_sample_name': 'Z35.5', 'specimen_class': '', 'er_spe... | 2.343089 | 2.283092 | 1.026279 |
warnings = self.validate_data()
print('-I- Writing all saved data to files')
if self.measurements:
self.write_measurements_file()
for dtype in ['specimen', 'sample', 'site']:
if self.data_lists[dtype][0]:
do_pmag = dtype in self.incl_pmag... | def write_files(self) | write all data out into er_* and pmag_* files as appropriate | 3.923313 | 3.310577 | 1.185084 |
if not self.write_ages:
print('-I- No age data available to write')
return
first_headers = self.first_age_headers
actual_headers = sorted(self.headers['age']['er'][0])
for header in first_headers:
if header in actual_headers:
a... | def write_age_file(self) | Write er_ages.txt based on updated ErMagicBuilder data object | 2.761092 | 2.692777 | 1.02537 |
warnings = {}
spec_warnings, samp_warnings, site_warnings, loc_warnings = {}, {}, {}, {}
if self.specimens:
spec_warnings = self.validate_items(self.specimens, 'specimen')
if self.samples:
samp_warnings = self.validate_items(self.samples, 'sample')
... | def validate_data(self) | Validate specimen, sample, site, and location data. | 2.142415 | 1.666074 | 1.285906 |
def append_or_create_dict_item(warning_type, dictionary, key, value):
if not value:
return
try:
name = key.name
except AttributeError:
name = key
if not name in dictionary:
dicti... | def validate_items(self, item_list, item_type) | Go through a list Pmag_objects and check for:
parent errors,
children errors,
type errors.
Return a dictionary of exceptions in this format:
{sample1: {'parent': [warning1, warning2, warning3], 'child': [warning1, warning2]},
sample2: {'child': [warning1], 'type': [warni... | 2.11604 | 1.985278 | 1.065866 |
d = {}
for location in locations:
sites = location.sites
max_lat, min_lat = '', ''
max_lon, min_lon = '', ''
if not any(sites):
d[location.name] = {'location_begin_lat': min_lat, 'location_begin_lon': min_lon,
... | def get_min_max_lat_lon(self, locations) | Take a list of locations and return a dictionary with:
location1:
'location_begin_lat', 'location_begin_lon',
'location_end_lat', 'location_end_lon'.
and so on. | 1.945969 | 1.807658 | 1.076514 |
self.sample = new_samp
if new_samp:
if not isinstance(new_samp, Sample):
raise Exception
self.propagate_data()
return new_samp | def set_parent(self, new_samp) | Set self.sample as either an empty string, or with a new Sample. | 4.53259 | 3.8998 | 1.162262 |
if new_site:
if not isinstance(new_site, Site):
raise Exception
self.site = new_site
self.propagate_data()
return new_site | def set_parent(self, new_site) | Set self.site as either an empty string, or with a new Site. | 4.672548 | 3.749271 | 1.246255 |
self.name = new_name
if new_location:
self.location = new_location
self.update_data(new_er_data, new_pmag_data, replace_data) | def change_site(self, new_name, new_location=None, new_er_data=None,
new_pmag_data=None, replace_data=False) | Update a site's name, location, er_data, and pmag_data.
By default, new data will be added in to pre-existing data, overwriting existing values.
If replace_data is True, the new data dictionary will simply take the place of the existing dict. | 2.081329 | 2.210835 | 0.941422 |
'''
take a LIST and find the nearest value in LIST to 'value'
'''
diff = inf
for a in LIST:
if abs(value - a) < diff:
diff = abs(value - a)
result = a
return(result) | def find_close_value(self, LIST, value) | take a LIST and find the nearest value in LIST to 'value' | 4.288908 | 2.68985 | 1.594479 |
'''
find the best interpretation with the minimum stratard deviation (in units of percent % !)
'''
Best_array = []
best_array_std_perc = inf
Best_array_tmp = []
Best_interpretations = {}
Best_interpretations_tmp = {}
for this_specimen in list(Inte... | def find_sample_min_std(self, Intensities) | find the best interpretation with the minimum stratard deviation (in units of percent % !) | 2.829079 | 2.265185 | 1.248939 |
'''
calcualte sample or site bootstrap paleointensities
and statistics
Grade_As={}
'''
thellier_interpreter_pars = {}
thellier_interpreter_pars['fail_criteria'] = []
thellier_interpreter_pars['pass_or_fail'] = 'pass'
BOOTSTRAP_N = int(self.prefere... | def thellier_interpreter_BS_pars_calc(self, Grade_As) | calcualte sample or site bootstrap paleointensities
and statistics
Grade_As={} | 2.521534 | 2.281107 | 1.105399 |
mapped_dictionary = {}
for key, value in dictionary.items():
if key in list(mapping.keys()):
new_key = mapping[key]
# if there is already a mapped value, try to figure out which value to use
# (i.e., if both er_synthetic_name and er_specimen_name are in one measu... | def mapping(dictionary, mapping) | takes in a dictionary and a mapping which contains new key names,
and returns a new dictionary with the updated key names, i.e.:
dictionary = {'a': 1, 'b': 2, 'c': 3}
mapping = {'a': 'aa', 'c': 'cc'}
mapped_dictionary = mapping(dictionary, mapping)
mapped_dictionary = {'aa': 1, b, 2, 'cc': 3} | 2.200696 | 2.243247 | 0.981032 |
def get_2_to_3(dm_type, dm):
table_names3_2_table_names2 = {'measurements': ['magic_measurements'],
'locations': ['er_locations'],
'sites': ['er_sites', 'pmag_sites'],
'samples': ['er_sa... | def cache_mappings(file_path) | Make a full mapping for 2 --> 3 columns.
Output the mapping to json in the specified file_path.
Note: This file is currently called maps.py,
full path is PmagPy/pmagpy/mapping/maps.py.
Parameters
----------
file_path : string with full file path to dump mapping json.
Returns
---------
... | 3.236662 | 2.982852 | 1.08509 |
if int(output) == 2:
thellier_gui_meas3_2_meas2_map = meas_magic3_2_magic2_map.copy()
if 'treat_step_num' in input_df.columns:
thellier_gui_meas3_2_meas2_map.update(
{'treat_step_num': 'measurement_number'})
thellier_gui_meas3_2_meas2_map.pop('measurement... | def get_thellier_gui_meas_mapping(input_df, output=2) | Get the appropriate mapping for translating measurements in Thellier GUI.
This requires special handling for treat_step_num/measurement/measurement_number.
Parameters
----------
input_df : pandas DataFrame
MagIC records
output : int
output to this MagIC data model (2 or 3)
Outp... | 2.300471 | 2.082084 | 1.104889 |
output = int(output)
meas_mapping = get_thellier_gui_meas_mapping(meas_df_in, output)
meas_df_out = meas_df_in.rename(columns=meas_mapping)
if 'measurement' not in meas_df_out.columns:
meas_df_out['measurement'] = meas_df_in['measurement']
return meas_df_out | def convert_meas_df_thellier_gui(meas_df_in, output) | Take a measurement dataframe and convert column names
from MagIC 2 --> 3 or vice versa.
Use treat_step_num --> measurement_number if available,
otherwise measurement --> measurement_number.
Parameters
----------
meas_df_in : pandas DataFrame
input dataframe with measurement data
out... | 2.549783 | 3.075717 | 0.829004 |
if direction == 'magic3':
columns = meas_magic2_2_magic3_map
MeasRec = {}
for key in columns:
if key in list(Rec.keys()):
# transfer info and change column name to data model 3.0
MeasRec[columns[key]] = Rec[key]
return MeasRec
else... | def convert_meas(direction, Rec) | converts measurments tables from magic 2 to 3 (direction=magic3)
or from model 3 to 2.5 (direction=magic2) [not available] | 9.630214 | 7.261703 | 1.326165 |
# directional
# do directional stuff first
# a few things need cleaning up
dir_df = sites_df.copy().dropna(
subset=['dir_dec', 'dir_inc']) # delete blank directions
# sort by absolute value of vgp_lat in order to eliminate duplicate rows for
# directions put in by accident on inten... | def convert_site_dm3_table_directions(sites_df) | Convert MagIC site headers to short/readable
headers for a figure (used by ipmag.sites_extract)
Directional table only.
Parameters
----------
sites_df : pandas DataFrame
sites information
Returns
---------
dir_df : pandas DataFrame
directional site data with easily read... | 3.459689 | 3.370052 | 1.026598 |
coordinate_list = ['specimen']
initial_coordinate = 'specimen'
for specimen in self.specimens:
if 'geographic' not in coordinate_list and self.Data[specimen]['zijdblock_geo']:
coordinate_list.append('geographic')
initial_coordinate = 'geograph... | def get_coordinate_system(self) | Check self.Data for available coordinate systems.
Returns
---------
initial_coordinate, coordinate_list : str, list
i.e., 'geographic', ['specimen', 'geographic'] | 3.629201 | 2.615927 | 1.387348 |
self.initialize_CART_rot(s)
# Draw Zij plot
self.draw_zijderveld()
# Draw specimen equal area
self.draw_spec_eqarea()
# Draw M/M0 plot ( or NLT data on the same area in the GUI)
self.draw_MM0()
# If measurements are selected redisplay selected... | def draw_figure(self, s, update_high_plots=True) | Convenience function that sets current specimen to s and calculates
data for that specimen then redraws all plots.
Parameters
----------
s : specimen to set current specimen too
update_high_plots : bool which decides if high level mean plot
updates (default: False) | 11.479923 | 10.821042 | 1.060889 |
# self.toolbar4.home()
high_level = self.level_box.GetValue()
self.UPPER_LEVEL_NAME = self.level_names.GetValue()
self.UPPER_LEVEL_MEAN = self.mean_type_box.GetValue()
draw_net(self.high_level_eqarea)
what_is_it = self.level_box.GetValue()+": "+self.level_names.G... | def plot_high_levels_data(self) | Complicated function that draws the high level mean plot on canvas4,
draws all specimen, sample, or site interpretations according to the
UPPER_LEVEL_SHOW variable, draws the fisher mean or fisher mean by
polarity of all interpretations displayed, draws sample orientation
check if on, an... | 5.886344 | 5.306547 | 1.109261 |
if self.COORDINATE_SYSTEM == "geographic":
dirtype = 'DA-DIR-GEO'
elif self.COORDINATE_SYSTEM == "tilt-corrected":
dirtype = 'DA-DIR-TILT'
else:
dirtype = 'DA-DIR'
if self.level_box.GetValue() == 'sample':
high_level_type = 'sampl... | def get_levels_and_coordinates_names(self) | Get the current level of the high level mean plot and the name of
the corrisponding site, study, etc. As well as the code for the
current coordinate system.
Returns
-------
(high_level_type,high_level_name,coordinate_system) : tuple object
containing current high lev... | 2.987525 | 2.651896 | 1.126562 |
if pars == {}:
pass
elif 'calculation_type' in list(pars.keys()) and pars['calculation_type'] == 'DE-BFP':
ymin, ymax = fig.get_ylim()
xmin, xmax = fig.get_xlim()
D_c, I_c = pmag.circ(pars["specimen_dec"],
pars["s... | def plot_eqarea_pars(self, pars, fig) | Given a dictionary of parameters (pars) that is returned from
pmag.domean plots those pars to the given fig | 2.167434 | 2.152554 | 1.006913 |
mpars_to_plot = []
if meanpars == {}:
return
if meanpars['calculation_type'] == 'Fisher by polarity':
for mode in list(meanpars.keys()):
if type(meanpars[mode]) == dict and meanpars[mode] != {}:
mpars_to_plot.append(meanpars[mo... | def plot_eqarea_mean(self, meanpars, fig) | Given a dictionary of parameters from pmag.dofisher, pmag.dolnp, or
pmag.dobingham (meanpars) plots parameters to fig | 2.739015 | 2.686801 | 1.019434 |
if specimen not in list(self.Data.keys()) and not suppress_warnings:
self.user_warning(
"there is no measurement data for %s and therefore no interpretation can be created for this specimen" % (specimen))
return
if fmax != None and fmax not in self.Data[s... | def add_fit(self, specimen, name, fmin, fmax, PCA_type="DE-BFL", color=None, suppress_warnings=False, saved=True) | Goes through the data checks required to add an interpretation to
the param specimen with the name param name, the bounds param fmin
and param fmax, and calculation type param PCA_type.
Parameters
----------
specimen : specimen with measurement data to add the
interpreta... | 2.996965 | 2.955424 | 1.014056 |
if specimen == None:
for spec in self.pmag_results_data['specimens']:
if fit in self.pmag_results_data['specimens'][spec]:
specimen = spec
break
if specimen not in self.pmag_results_data['specimens']:
return
... | def delete_fit(self, fit, specimen=None) | removes fit from GUI results data
Parameters
----------
fit : fit to remove
specimen : specimen of fit to remove, if not provided and
set to None then the function will find the specimen itself | 2.671973 | 2.696558 | 0.990883 |
if "age" not in list(er_ages_rec.keys()):
return(er_ages_rec)
if "age_unit" not in list(er_ages_rec.keys()):
return(er_ages_rec)
if er_ages_rec["age_unit"] == "":
return(er_ages_rec)
if er_ages_rec["age"] == "":
if "age_range_high... | def convert_ages_to_calendar_year(self, er_ages_rec) | convert all age units to calendar year
Parameters
----------
er_ages_rec : Dict type object containing preferbly at least keys
'age', 'age_unit', and either 'age_range_high', 'age_range_low'
or 'age_sigma'
Returns
-------
er_ages_rec : Same dict ... | 1.647712 | 1.567827 | 1.050952 |
self.warning_text = ""
if self.s in list(self.pmag_results_data['specimens'].keys()):
for fit in self.pmag_results_data['specimens'][self.s]:
beg_pca, end_pca = self.get_indices(
fit, fit.tmin, fit.tmax, self.s)
if beg_pca == None ... | def generate_warning_text(self) | generates warnings for the current specimen then adds them to the
current warning text for the GUI which will be rendered on a call to
update_warning_box. | 3.005062 | 2.953909 | 1.017317 |
# import pdb; pdb.set_trace()
acceptance_criteria = pmag.initialize_acceptance_criteria()
if self.data_model == 3:
if criteria_file_name == None:
criteria_file_name = "criteria.txt"
contribution = cb.Contribution(self.WD, read_tables=[
... | def read_criteria_file(self, criteria_file_name=None) | reads 2.5 or 3.0 formatted PmagPy criteria file and returns a set of
nested dictionary 2.5 formated criteria data that can be passed into
pmag.grade to filter data.
Parameters
----------
criteria_file : name of criteria file to read in
Returns
-------
ne... | 3.141894 | 3.205125 | 0.980272 |
if tmin == '' or tmax == '':
return
beg_pca, end_pca = self.get_indices(fit, tmin, tmax, specimen)
if coordinate_system == 'geographic' or coordinate_system == 'DA-DIR-GEO':
block = self.Data[specimen]['zijdblock_geo']
elif coordinate_system == 'tilt-cor... | def get_PCA_parameters(self, specimen, fit, tmin, tmax, coordinate_system, calculation_type) | Uses pmag.domean to preform a line, line-with-origin, line-anchored,
or plane least squared regression or a fisher mean on the
measurement data of specimen in coordinate system between bounds
tmin to tmax
Parameters
----------
specimen : specimen with measurement data in... | 3.878672 | 3.312064 | 1.171074 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.