code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# (must use fillna to replace np.nan with False for indexing)
if use_slice:
df = sli.copy()
else:
df = self.df.copy()
# if meth_code not provided, return unchanged dataframe
if not meth_code:
return df
# get regex
if no... | def get_records_for_code(self, meth_code, incl=True, use_slice=False,
sli=None, strict_match=True) | Use regex to see if meth_code is in the method_codes ":" delimited list.
If incl == True, return all records WITH meth_code.
If incl == False, return all records WITHOUT meth_code.
If strict_match == True, return only records with the exact meth_code.
If strict_match == False, return rec... | 4.296887 | 4.203293 | 1.022267 |
if self.df.empty:
return df1
elif df1.empty:
return self.df
#copy to prevent mutation
cdf2 = self.df.copy()
#split data into types and decide which to replace
# if replace_dir_or_int == 'dir' and 'method_codes' in cdf2.columns:
# ... | def merge_dfs(self, df1) | Description: takes new calculated data and replaces the corresponding data in self.df with the new input data preserving the most important metadata if they are not otherwise saved. Note this does not mutate self.df it simply returns the merged dataframe if you want to replace self.df you'll have to do that yourself.
... | 3.573515 | 3.527367 | 1.013083 |
# don't let custom name start with "./"
if custom_name:
if custom_name.startswith('.'):
custom_name = os.path.split(custom_name)[1]
# put columns in logical order (by group)
self.sort_dataframe_cols()
# if indexing column was put in, remove it... | def write_magic_file(self, custom_name=None, dir_path=".",
append=False, multi_type=False, df=None) | Write self.df out to tab-delimited file.
By default will use standard MagIC filenames (specimens.txt, etc.),
or you can provide a custom_name to write to instead.
By default will write to custom_name if custom_name is a full path,
or will write to dir_path + custom_name if custom_name
... | 2.785546 | 2.749264 | 1.013197 |
table_dm = self.data_model.dm[self.dtype]
approved_cols = table_dm.index
unrecognized_cols = (set(self.df.columns) - set(approved_cols))
return unrecognized_cols | def get_non_magic_cols(self) | Find all columns in self.df that are not real MagIC 3 columns.
Returns
--------
unrecognized_cols : list | 6.966476 | 6.010682 | 1.159016 |
short_df = self.df.loc[ind_name, col_name]
mask = pd.notnull(short_df)
print(short_df[mask])
try:
val = short_df[mask].unique()[0]
except IndexError:
val = None
return val | def get_first_non_null_value(self, ind_name, col_name) | For a given index and column, find the first non-null value.
Parameters
----------
self : MagicDataFrame
ind_name : str
index name for indexing
col_name : str
column name for indexing
Returns
---------
single value of str, float, ... | 3.036253 | 3.307678 | 0.917941 |
dtype = dtype.strip()
if dtype.endswith('s'):
return dtype[:-1], dtype
elif dtype == 'criteria':
return 'table_column', 'criteria'
elif dtype == 'contribution':
return 'doi', 'contribution' | def get_singular_and_plural_dtype(self, dtype) | Parameters
----------
dtype : str
MagIC table type (specimens, samples, contribution, etc.)
Returns
---------
name : str
singular name for MagIC table ('specimen' for specimens table, etc.)
dtype : str
plural dtype for MagIC table ('spec... | 5.738036 | 4.852006 | 1.182611 |
args = sys.argv
fmt = pmag.get_named_arg('-fmt', 'svg')
output_dir_path = pmag.get_named_arg('-WD', '.')
input_dir_path = pmag.get_named_arg('-ID', "")
if "-h" in args:
print(main.__doc__)
sys.exit()
meas_file = pmag.get_named_arg('-f', 'measurements.txt')
spec_file = pm... | def main() | NAME
hysteresis_magic.py
DESCRIPTION
calculates hystereis parameters and saves them in 3.0 specimen format file
makes plots if option selected
SYNTAX
hysteresis_magic.py [command line options]
OPTIONS
-h prints help message and quits
-f: specify input file,... | 2.876342 | 2.295226 | 1.253184 |
if 'data_files' in os.listdir(sys.prefix):
return os.path.join(sys.prefix, 'data_files')
else:
return os.path.join(get_pmag_dir(), 'data_files') | def get_data_files_dir() | Find directory with data_files (sys.prefix or local PmagPy/data_files)
and return the path. | 3.139017 | 2.034421 | 1.542954 |
# this is correct for py2exe (DEPRECATED)
#win_frozen = is_frozen()
#if win_frozen:
# path = os.path.abspath(unicode(sys.executable, sys.getfilesystemencoding()))
# path = os.path.split(path)[0]
# return path
# this is correct for py2app
try:
return os.environ['RESO... | def get_pmag_dir() | Returns directory in which PmagPy is installed | 3.555745 | 3.537633 | 1.00512 |
dir_path="./"
if '-WD' in sys.argv:
ind=sys.argv.index('-WD')
dir_path=sys.argv[ind+1]
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-f' in sys.argv:
ind=sys.argv.index('-f')
magic_file=dir_path+'/'+sys.argv[ind+1]
else:
print(ma... | def main() | NAME
plot_magic_keys.py
DESCRIPTION
picks out keys and makes and xy plot
SYNTAX
plot_magic_keys.py [command line options]
OPTIONS
-h prints help message and quits
-f FILE: specify input magic format file
-xkey KEY: specify key for X
-ykey KEY: speci... | 2.052176 | 1.92815 | 1.064324 |
title = ""
files, fmt = {}, 'svg'
sym = {'lower': ['o', 'r'], 'upper': ['o', 'w']}
plot = 0
if '-h' in sys.argv: # check if help is needed
print(main.__doc__)
sys.exit() # graceful quit
if '-sav' in sys.argv:
plot = 1
if '-fmt' in sys.argv:
ind = sys.ar... | def main() | NAME
eqarea.py
DESCRIPTION
makes equal area projections from declination/inclination data
INPUT FORMAT
takes dec/inc as first two columns in space delimited file
SYNTAX
eqarea.py [options]
OPTIONS
-f FILE, specify file on command line
-sav save figure and ... | 2.680557 | 2.302145 | 1.164374 |
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) | create change directory frame | 4.512805 | 4.511103 | 1.000377 |
if self.grid_frame:
print('-I- You already have a grid frame open')
pw.simple_warning("You already have a grid open")
return
try:
grid_type = event.GetButtonObj().Name[:-4] # remove '_btn'
except AttributeError:
grid_type = se... | def make_grid_frame(self, event) | Create a GridFrame for data type of the button that was clicked | 6.619886 | 6.508301 | 1.017145 |
# coherence validations
wait = wx.BusyInfo('Validating data, please wait...')
wx.SafeYield()
spec_warnings, samp_warnings, site_warnings, loc_warnings = self.er_magic.validate_data()
result_warnings = self.er_magic.validate_results(self.er_magic.results)
meas_war... | def on_upload_file(self, event) | Write all data to appropriate er_* and pmag_* files.
Then use those files to create a MagIC upload format file.
Validate the upload file. | 3.611288 | 3.413794 | 1.057852 |
if self.parent.grid_frame:
if self.parent.grid_frame.grid.changes:
dlg = wx.MessageDialog(self,caption="Message:", message="Are you sure you want to exit the program?\nYou have a grid open with unsaved changes.\n ", style=wx.OK|wx.CANCEL)
result = dlg.ShowMod... | def on_quit(self, event) | shut down application | 4.162089 | 4.203822 | 0.990073 |
dia = pmag_menu_dialogs.ClearWD(self.parent, self.parent.WD)
clear = dia.do_clear()
if clear:
print('-I- Clear data object')
self.parent.er_magic = builder.ErMagicBuilder(self.parent.WD, self.parent.data_model)
print('-I- Initializing headers')
... | def on_clear(self, event) | initialize window to allow user to empty the working directory | 7.880715 | 7.513271 | 1.048906 |
#
# initialize variables
#
version_num=pmag.get_version()
orient_file,samp_file = "orient","er_samples.txt"
args=sys.argv
dir_path,out_path='.','.'
default_outfile = True
#
#
if '-WD' in args:
ind=args.index('-WD')
dir_path=args[ind+1]
if '-OD' in arg... | def main() | NAME
convert_samples.py
DESCRIPTION
takes an er_samples or magic_measurements format file and creates an orient.txt template
SYNTAX
convert_samples.py [command line options]
OPTIONS
-f FILE: specify input file, default is er_samples.txt
-F FILE: specify output ... | 2.998103 | 2.802967 | 1.069618 |
if len(sys.argv) > 0:
if '-h' in sys.argv: # check if help is needed
print(main.__doc__)
sys.exit() # graceful quit
if '-f' in sys.argv: # ask for filename
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
f=open(file,'r')
data... | def main() | NAME
gobing.py
DESCRIPTION
calculates Bingham parameters from dec inc data
INPUT FORMAT
takes dec/inc as first two columns in space delimited file
SYNTAX
gobing.py [options]
OPTIONS
-f FILE to read from FILE
-F, specifies output file name
< filen... | 3.188945 | 2.567588 | 1.242 |
# initialize some parameters
args = sys.argv
if "-h" in args:
print(main.__doc__)
sys.exit()
#if "-Fa" in args:
# ind = args.index("-Fa")
# rmag_anis = args[ind + 1]
#if "-Fr" in args:
# ind = args.index("-Fr")
# rmag_res = args[ind + 1]
#meas_... | def main() | NAME
atrm_magic.py
DESCRIPTION
Converts ATRM data to best-fit tensor (6 elements plus sigma)
Original program ARMcrunch written to accomodate ARM anisotropy data
collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the
off-axis remanence terms to construct the t... | 3.096891 | 2.512175 | 1.232753 |
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')
else:
out=''
if '-i' in sys.argv: # if one is -i
a95=0
while 1:
try:
... | def main() | NAME
di_vgp.py
DESCRIPTION
converts declination/inclination to virtual geomagnetic pole
SYNTAX
di_vgp.py [-h] [options]
OPTIONS
-h prints help message and quits
-i interactive data entry
-f FILE to specify intput file
-F FILE to specify output... | 3.124416 | 2.867468 | 1.089608 |
os.chdir(self.WD)
options = {}
HUJI_file = self.bSizer0.return_value()
if not HUJI_file:
pw.simple_warning("You must select a HUJI format file")
return False
options['magfile'] = HUJI_file
dat_file = self.bSizer0A.return_value()
if... | def on_okButton(self, event) | grab user input values, format them, and run huji_magic.py with the appropriate flags | 2.654307 | 2.564778 | 1.034907 |
'''
create an editable grid showing demag_orient.txt
'''
#--------------------------------
# orient.txt supports many other headers
# but we will only initialize with
# the essential headers for
# sample orientation and headers present
# in existin... | def create_sheet(self) | create an editable grid showing demag_orient.txt | 3.023397 | 2.798974 | 1.080181 |
'''
open orient.txt
read the data
display the data from the file in a new grid
'''
dlg = wx.FileDialog(
self, message="choose orient file",
defaultDir=self.WD,
defaultFile="",
style=wx.FD_OPEN | wx.FD_CHANGE_DIR
... | def on_m_open_file(self,event) | open orient.txt
read the data
display the data from the file in a new grid | 5.787887 | 4.446056 | 1.301803 |
if not sample_names:
return []
full_headers = list(self.orient_data[sample_names[0]].keys())
add_ons = []
for head in full_headers:
if head not in self.header_names:
add_ons.append((head, head))
return add_ons | def add_extra_headers(self, sample_names) | If there are samples, add any additional keys they might use
to supplement the default headers.
Return the headers headers for adding, with the format:
[(header_name, header_display_name), ....] | 3.828915 | 3.598292 | 1.064092 |
'''
open orient.txt
read the data
display the data from the file in a new grid
'''
dlg = wx.FileDialog(
self, message="choose orient file",
defaultDir=self.WD,
defaultFile="",
style=wx.FD_OPEN | wx.FD_CHANGE_DIR
... | def on_m_open_file(self,event) | open orient.txt
read the data
display the data from the file in a new grid | 5.675565 | 4.247652 | 1.336165 |
'''
save demag_orient.txt
(only the columns that appear on the grid frame)
'''
fout = open(os.path.join(self.WD, "demag_orient.txt"), 'w')
STR = "tab\tdemag_orient\n"
fout.write(STR)
headers = [header[0] for header in self.headers]
STR = "\t".join... | def on_m_save_file(self,event) | save demag_orient.txt
(only the columns that appear on the grid frame) | 3.581652 | 2.622743 | 1.365613 |
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
zfile, tfile = 'zeq_redo', 'thellier_redo'
zredo, tredo = "", ""
dir_path = pmag.get_named_arg('-WD', '.')
inspec = pmag.get_named_arg('-f', 'specimens.txt')
if '-F' in sys.argv:
ind = sys.argv.index('-F')
r... | def main() | NAME
mk_redo.py
DESCRIPTION
Makes thellier_redo and zeq_redo files from existing pmag_specimens format file
SYNTAX
mk_redo.py [-h] [command line options]
INPUT
takes specimens.txt formatted input file
OPTIONS
-h: prints help message and quits
-f FILE: ... | 3.019249 | 2.746263 | 1.099403 |
minx, miny, maxx, maxy = ls.bounds
points = {'left': [(minx, miny), (minx, maxy)],
'right': [(maxx, miny), (maxx, maxy)],
'bottom': [(minx, miny), (maxx, miny)],
'top': [(minx, maxy), (maxx, maxy)],}
return sgeom.LineString(points[side]) | def find_side(ls, side) | Given a shapely LineString which is assumed to be rectangular, return the
line corresponding to a given side of the rectangle. | 2.060503 | 1.869859 | 1.101957 |
te = lambda xy: xy[0]
lc = lambda t, n, b: np.vstack((np.zeros(n) + t, np.linspace(b[2], b[3], n))).T
xticks, xticklabels = _lambert_ticks(ax, ticks, 'bottom', lc, te)
ax.xaxis.tick_bottom()
ax.set_xticks(xticks)
ax.set_xticklabels([ax.xaxis.get_major_formatter()(xtick) for xtick in xtickla... | def lambert_xticks(ax, ticks) | Draw ticks on the bottom x-axis of a Lambert Conformal projection. | 3.116162 | 2.901938 | 1.073821 |
te = lambda xy: xy[1]
lc = lambda t, n, b: np.vstack((np.linspace(b[0], b[1], n), np.zeros(n) + t)).T
yticks, yticklabels = _lambert_ticks(ax, ticks, 'left', lc, te)
ax.yaxis.tick_left()
ax.set_yticks(yticks)
ax.set_yticklabels([ax.yaxis.get_major_formatter()(ytick) for ytick in yticklabels... | def lambert_yticks(ax, ticks) | Draw ricks on the left y-axis of a Lamber Conformal projection. | 3.048911 | 2.919083 | 1.044476 |
outline_patch = sgeom.LineString(ax.outline_patch.get_path().vertices.tolist())
axis = find_side(outline_patch, tick_location)
n_steps = 30
extent = ax.get_extent(ccrs.PlateCarree())
_ticks = []
for t in ticks:
xy = line_constructor(t, n_steps, extent)
proj_xyz = ax.projecti... | def _lambert_ticks(ax, ticks, tick_location, line_constructor, tick_extractor) | Get the tick locations and labels for an axis of a Lambert Conformal projection. | 3.157393 | 3.067827 | 1.029195 |
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
# initialize variables from command line + defaults
dir_path = pmag.get_named_arg("-WD", default_val=".")
input_dir_path = pmag.get_named_arg('-ID', '')
if not input_dir_path:
input_dir_path = dir_path
in_file = pma... | def main() | NAME
dmag_magic.py
DESCRIPTION
plots intensity decay curves for demagnetization experiments
SYNTAX
dmag_magic -h [command line options]
INPUT
takes magic formatted measurements.txt files
OPTIONS
-h prints help message and quits
-f FILE: specify input fil... | 2.647302 | 2.062853 | 1.283321 |
norm=0
if '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
data=np.loadtxt(file)
dates=[2000]
elif '-d' in sys.argv:
ind=sys.argv.index('-d')
dates=[float(sys.argv[ind+1])]
elif '-r' in sys.argv:
ind=sys.argv.index('-r')
... | def main() | NAME
lowes.py
DESCRIPTION
Plots Lowes spectrum for input IGRF-like file
SYNTAX
lowes.py [options]
OPTIONS:
-h prints help message and quits
-f FILE specify file name with input data
-d date specify desired date
-r read desired dates from file
-n no... | 3.55561 | 3.1958 | 1.112588 |
import numpy
X=arange(.1,10.1,.2) #make a list of numbers
Y=myfunc(X) # calls myfunc with argument X
for i in range(len(X)):
print(X[i],Y[i]) | def main() | This program prints doubled values! | 6.906274 | 6.034245 | 1.144513 |
d,i,file2="","",""
fmt,plot='svg',0
if '-h' in sys.argv: # check if help is needed
print(main.__doc__)
sys.exit() # graceful quit
if '-sav' in sys.argv: plot=1
if '-fmt' in sys.argv:
ind=sys.argv.index('-fmt')
fmt=sys.argv[ind+1]
if '-f' in sys.argv:
... | def main() | NAME
common_mean.py
DESCRIPTION
calculates bootstrap statistics to test for common mean
INPUT FORMAT
takes dec/inc as first two columns in two space delimited files
SYNTAX
common_mean.py [command line options]
OPTIONS
-h prints help message and quits
... | 3.165464 | 2.985441 | 1.0603 |
# makes sure all values are floats, then norms them by largest value
X = numpy.array(list(map(float, x)))
X = old_div(X, max(X))
Y = numpy.array(list(map(float, y)))
Y = old_div(Y, max(Y))
XY = numpy.array(list(zip(X, Y)))
#Provide the intitial estimate
E1=TaubinS... | def AraiCurvature(x=x,y=y) | input: list of x points, list of y points
output: k, a, b, SSE. curvature, circle center, and SSE
Function for calculating the radius of the best fit circle to a set of
x-y coordinates.
Paterson, G. A., (2011), A simple test for the presence of multidomain
behaviour during paleointensity experimen... | 3.988959 | 3.85191 | 1.03558 |
XY = numpy.array(XY)
X = XY[:,0] - numpy.mean(XY[:,0]) # norming points by x avg
Y = XY[:,1] - numpy.mean(XY[:,1]) # norming points by y avg
centroid = [numpy.mean(XY[:,0]), numpy.mean(XY[:,1])]
Z = X * X + Y * Y
Zmean = numpy.mean(Z)
Z0 = old_div((Z - Zmean), (2. * numpy.sqrt(Zmean))... | def TaubinSVD(XY) | algebraic circle fit
input: list [[x_1, y_1], [x_2, y_2], ....]
output: a, b, r. a and b are the center of the fitting circle, and r is the radius
Algebraic circle fit by Taubin
G. Taubin, "Estimation Of Planar Curves, Surfaces And Nonplanar
Space Curves Defined By Implicit Equati... | 3.291682 | 3.072565 | 1.071314 |
XY = numpy.array(XY)
n = len(XY)
if n < 4:
raise Warning("Circle cannot be calculated with less than 4 data points. Please include more data")
Dx = XY[:,0] - Par[0]
Dy = XY[:,1] - Par[1]
D = numpy.sqrt(Dx * Dx + Dy * Dy) - Par[2]
result = old_div(numpy.dot(D, D),(n-3))
retur... | def VarCircle(XY, Par): # must have at least 4 sets of xy points or else division by zero occurs
if type(XY) != numpy.ndarray | computing the sample variance of distances from data points (XY) to the circle Par = [a b R] | 3.741473 | 3.3297 | 1.123667 |
SSE = 0
X = numpy.array(x)
Y = numpy.array(y)
for i in range(len(X)):
x = X[i]
y = Y[i]
v = (numpy.sqrt( (x -a)**2 + (y - b)**2 ) - r )**2
SSE += v
return SSE | def get_SSE(a,b,r,x,y) | input: a, b, r, x, y. circle center, radius, xpts, ypts
output: SSE | 2.524791 | 2.605513 | 0.969019 |
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')
data=f.readlines() # read in data from standard input
for line in data: # step through line by line
dec... | def main() | NAME
sundec.py
DESCRIPTION
calculates calculates declination from sun compass measurements
INPUT FORMAT
GMT_offset, lat,long,year,month,day,hours,minutes,shadow_angle
where GMT_offset is the hours to subtract from local time for GMT.
SYNTAX
sundec.py [-i][-f FILE] [< ... | 4.680617 | 4.097637 | 1.142272 |
# set defaults
site_file="er_sites.txt"
loc_file="er_locations.txt"
Names,user=[],"unknown"
Done=[]
version_num=pmag.get_version()
args=sys.argv
dir_path='.'
# get command line stuff
if '-WD' in args:
ind=args.index("-WD")
dir_path=args[ind+1]
if "-h" in args:
... | def main() | NAME
sites_locations.py
DESCRIPTION
reads in er_sites.txt file and finds all locations and bounds of locations
outputs er_locations.txt file
SYNTAX
sites_locations.py [command line options]
OPTIONS
-h prints help message and quits
-f: specimen input er_site... | 2.684956 | 2.550357 | 1.052777 |
cond = method_list['dtype'] == mtype
codes = method_list[cond]
return codes | def get_one_meth_type(self, mtype, method_list) | Get all codes of one type (i.e., 'anisotropy_estimation') | 8.624582 | 4.815665 | 1.790943 |
categories = Series(code_types[code_types[category] == True].index)
cond = all_codes['dtype'].isin(categories)
codes = all_codes[cond]
return codes | def get_one_meth_category(self, category, all_codes, code_types) | Get all codes in one category (i.e., all pmag codes).
This can include multiple method types (i.e., 'anisotropy_estimation', 'sample_prepartion', etc.) | 5.855303 | 5.682757 | 1.030363 |
args = sys.argv
if "-h" in args:
print(main.__doc__)
sys.exit()
dataframe = extractor.command_line_dataframe([['f', False, 'orient.txt'], ['Fsa', False, 'samples.txt'], ['ncn', False, "1"], ['mcd', False, 'FS-FD'], ['loc', False, 'unknown'], ['app', False, False], ['WD', False, '.'], ... | def main() | NAME
azdip_magic.py
DESCRIPTION
takes space delimited AzDip file and converts to MagIC formatted tables
SYNTAX
azdip_magic.py [command line options]
OPTIONS
-f FILE: specify input file
-Fsa FILE: specify output file, default is: er_samples.txt/samples.txt
-... | 5.471479 | 3.132997 | 1.746404 |
args = sys.argv
if '-h' in args:
print(do_help())
sys.exit()
# def k15_magic(k15file, specnum=0, sample_naming_con='1', er_location_name="unknown", measfile='magic_measurements.txt', sampfile="er_samples.txt", aniso_outfile='rmag_anisotropy.txt', result_file="rmag_results.txt", input_d... | def main() | NAME
k15_magic.py
DESCRIPTION
converts .k15 format data to magic_measurements format.
assums Jelinek Kappabridge measurement scheme
SYNTAX
k15_magic.py [-h] [command line options]
OPTIONS
-h prints help message and quits
-DM DATA_MODEL: specify data model ... | 4.278393 | 3.310023 | 1.292557 |
missing = []
for col in reqd_cols:
if col not in data[0]:
missing.append(col)
return missing | def check_for_reqd_cols(data, reqd_cols) | Check data (PmagPy list of dicts) for required columns | 2.774794 | 2.336335 | 1.18767 |
if '-h' in sys.argv: # check if help is needed
print(main.__doc__)
sys.exit() # graceful quit
if '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
f=open(file,'r')
data=f.readlines()
else:
data=sys.stdin.readlines() # read in data fr... | def main() | NAME
pca.py
DESCRIPTION
calculates best-fit line/plane through demagnetization data
INPUT FORMAT
takes specimen_name treatment intensity declination inclination in space delimited file
SYNTAX
pca.py [command line options][< filename]
OPTIONS
-h prints help and qu... | 3.110276 | 2.691899 | 1.155421 |
# if column name is present, no need to check if it is required
if col_name in df.columns:
return None
arg_list = arg.split(",")
arg_list = [argument.strip('"') for argument in arg_list]
msg = ""
for a in arg_list:
# ignore validations that reference a different table
... | def requiredUnless(col_name, arg, dm, df, *args) | Arg is a string in the format "str1, str2, ..."
Each string will be a column name.
Col_name is required in df unless each column from arg is present. | 4.19059 | 4.219822 | 0.993073 |
table_name = arg
if col_name in df.columns:
return None
elif not con:
return None
elif table_name in con.tables:
return None
else:
return "{} column is required unless table {} is present".format(col_name, table_name) | def requiredUnlessTable(col_name, arg, dm, df, con=None) | Col_name must be present in df unless
arg (table_name) is present in contribution | 3.495086 | 3.479565 | 1.00446 |
group_name = arg
groups = set()
columns = df.columns
for col in columns:
if col not in dm.index:
continue
group = dm.loc[col]['group']
groups.add(group)
if group_name in groups:
if col_name in columns:
return None
else:
... | def requiredIfGroup(col_name, arg, dm, df, *args) | Col_name is required if other columns of
the group arg are present. | 3.312187 | 3.340847 | 0.991421 |
if col_name in df.columns:
return None
else:
return '"{}" column is required'.format(col_name) | def required(col_name, arg, dm, df, *args) | Col_name is required in df.columns.
Return error message if not. | 3.498728 | 3.174848 | 1.102014 |
#grade = df.apply(func, args=(validation_name, arg, dm), axis=1)
cell_value = row[col_name]
cell_value = str(cell_value)
if not cell_value:
return None
elif cell_value == 'None':
return None
elif cell_value == 'nan':
return None
elif not con:
return None
... | def isIn(row, col_name, arg, dm, df, con=None) | row[col_name] must contain a value from another column.
If not, return error message. | 3.012755 | 2.895299 | 1.040568 |
cell_value = row[col_name]
if not cell_value:
return None
elif isinstance(cell_value, float):
if np.isnan(cell_value):
return None
try:
arg_val = float(arg)
except ValueError:
if arg in row.index:
arg_val = row[arg]
else:
... | def checkMax(row, col_name, arg, *args) | row[col_name] must be less than or equal to arg.
else, return error message. | 3.187425 | 3.155139 | 1.010233 |
vocabulary = con.vocab.vocabularies
cell_value = str(row[col_name])
if not cell_value:
return None
elif cell_value == "None":
return None
cell_values = cell_value.split(":")
cell_values = [c.strip() for c in cell_values]
# get possible values for controlled vocabulary
... | def cv(row, col_name, arg, current_data_model, df, con) | row[col_name] must contain only values from the appropriate controlled vocabulary | 3.379461 | 3.174306 | 1.06463 |
if col_name in df.columns:
# if the column name is present, return nothing
return None
else:
# if the column name is missing, return column name
return col_name | def requiredOneInGroup(col_name, group, dm, df, *args) | If col_name is present in df, the group validation is satisfied.
If not, it still may be satisfied, but not by THIS col_name.
If col_name is missing, return col_name, else return None.
Later, we will validate to see if there is at least one None (non-missing)
value for this group. | 4.002305 | 3.726749 | 1.07394 |
# check column validity
required_one = {} # keep track of req'd one in group validations here
cols = df.columns
invalid_cols = [col for col in cols if col not in dm.index]
# go through and run all validations for the data type
for validation_name, validation in dm.iterrows():
value... | def validate_df(df, dm, con=None) | Take in a DataFrame and corresponding data model.
Run all validations for that DataFrame.
Output is the original DataFrame with some new columns
that contain the validation output.
Validation columns start with:
presence_pass_ (checking that req'd columns are present)
type_pass_ (checking that ... | 3.600406 | 3.397886 | 1.059602 |
value_cols = df.columns.str.match("^value_pass_")
present_cols = df.columns.str.match("^presence_pass")
type_cols = df.columns.str.match("^type_pass_")
groups_missing = df.columns.str.match("^group_pass_")
#
value_col_names = df.columns[value_cols]
present_col_names = df.columns[present... | def get_validation_col_names(df) | Input: validated pandas DataFrame (using validate_df)
Output: names of all value validation columns,
names of all presence validation columns,
names of all type validation columns,
names of all missing group columns,
names of all validation columns (excluding groups). | 2.284206 | 1.995639 | 1.144599 |
if outfile_name:
outfile = open(outfile_name, "w")
outfile.write("\t".join(["name", "row_number", "problem_type",
"problem_col", "error_message"]))
outfile.write("\n")
else:
outfile = None
for ind, row in failing_items.iterrows():
... | def print_row_failures(failing_items, verbose=False, outfile_name=None) | Take output from get_row_failures (DataFrame), and output it to
stdout, an outfile, or both. | 2.932698 | 2.835089 | 1.034429 |
# set temporary numeric index
df["num"] = list(range(len(df)))
# get column names for value & type validations
names = value_cols.union(type_cols)
# drop all non validation columns
value_problems = df[names.union(["num"])]
# drop validation columns that contain no problems
failing_i... | def get_row_failures(df, value_cols, type_cols, verbose=False, outfile=None) | Input: already validated DataFrame, value & type column names,
and output options.
Get details on each detected issue, row by row.
Output: DataFrame with type & value validation columns,
plus an "issues" column with a dictionary of every problem
for that row. | 4.707396 | 4.388013 | 1.072785 |
df["num"] = list(range(len(df)))
problems = df[validation_names.union(["num"])]
all_problems = problems.dropna(how='all', axis=0, subset=validation_names)
value_problems = problems.dropna(how='all', axis=0, subset=type_col_names.union(value_col_names))
all_problems = all_problems.dropna(how='al... | def get_bad_rows_and_cols(df, validation_names, type_col_names,
value_col_names, verbose=False) | Input: validated DataFrame, all validation names, names of the type columns,
names of the value columns, verbose (True or False).
Output: list of rows with bad values, list of columns with bad values,
list of missing (but required) columns. | 2.811609 | 2.844595 | 0.988404 |
print("-I- Validating {}".format(dtype))
# grab dataframe
current_df = the_con.tables[dtype].df
# grab data model
current_dm = the_con.tables[dtype].data_model.dm[dtype]
# run all validations (will add columns to current_df)
current_df = validate_df(current_df, current_dm, the_con)
... | def validate_table(the_con, dtype, verbose=False, output_dir=".") | Return name of bad table, or False if no errors found.
Calls validate_df then parses its output. | 3.407808 | 3.276973 | 1.039926 |
passing = True
for dtype in list(the_con.tables.keys()):
print("validating {}".format(dtype))
fail = validate_table(the_con, dtype)
if fail:
passing = False
print('--') | def validate_contribution(the_con) | Go through a Contribution and validate each table | 6.017747 | 5.010869 | 1.200939 |
ind = string.index("(")
return string[:ind], string[ind+1:-1].strip('"') | def split_func(string) | Take a string like 'requiredIf("arg_name")'
return the function name and the argument:
(requiredIf, arg_name) | 4.988427 | 4.717177 | 1.057502 |
vals = ['lon_w', 'lon_e', 'lat_lon_precision', 'pole_lon',
'paleolon', 'paleolon_sigma',
'lon', 'lon_sigma', 'vgp_lon', 'paleo_lon', 'paleo_lon_sigma',
'azimuth', 'azimuth_dec_correction', 'dir_dec',
'geographic_precision', 'bed_dip_direction']
relevant_cols ... | def get_degree_cols(df) | Take in a pandas DataFrame, and return a list of columns
that are in that DataFrame AND should be between 0 - 360 degrees. | 7.383753 | 7.111902 | 1.038225 |
prefixes = ["presence_pass_", "value_pass_", "type_pass_"]
end = string.rfind("_")
for prefix in prefixes:
if string.startswith(prefix):
return prefix[:-6], string[len(prefix):end]
return string, string | def extract_col_name(string) | Take a string and split it.
String will be a format like "presence_pass_azimuth",
where "azimuth" is the MagIC column name and "presence_pass"
is the validation.
Return "presence", "azimuth". | 6.548547 | 4.377915 | 1.495814 |
ind = row[row.notnull()].index
values = row[row.notnull()].values
# to transformation with extract_col_name here???
return dict(list(zip(ind, values))) | def make_row_dict(row) | Takes in a DataFrame row (Series),
and return a dictionary with the row's index as key,
and the row's values as values.
{col1_name: col1_value, col2_name: col2_value} | 13.64119 | 12.705272 | 1.073664 |
out=""
UP=0
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-f' in sys.argv:
dat=[]
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
f=open(file,'r')
input=f.readlines()
else:
input = sys.stdin.readlines() # read from stand... | def main() | NAME
eq_di.py
DESCRIPTION
converts x,y pairs digitized from equal area projection to dec inc data
SYNTAX
eq_di.py [command line options] [< filename]
OPTIONS
-f FILE, input file
-F FILE, specifies output file name
-up if data are upper hemisphere | 3.528221 | 3.241194 | 1.088556 |
print(main.__doc__)
if '-h' in sys.argv:sys.exit()
cont,Int,Top=1,[],[]
while cont==1:
try:
Int.append(int(input(" Enter desired treatment step interval: <return> to quit ")))
Top.append(int(input(" Enter upper bound for this interval: ")))
except:
... | def main() | Welcome to the thellier-thellier experiment automatic chart maker.
Please select desired step interval and upper bound for which it is valid.
e.g.,
50
500
10
600
a blank entry signals the end of data entry.
which would generate steps with 50 degree intervals up to 500, follo... | 10.486938 | 7.362645 | 1.424344 |
inc=[]
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 inc data: ")
inc=numpy.loadtxt(file)
elif '-f' in sys.argv:
ind=sys.argv.index('-f')
... | def main() | NAME
incfish.py
DESCRIPTION
calculates fisher parameters from inc only data
INPUT FORMAT
takes inc data
SYNTAX
incfish.py [options] [< filename]
OPTIONS
-h prints help message and quits
-i for interactive filename entry
-f FILE, specify input fil... | 4.308864 | 3.282904 | 1.312516 |
decorated = [(len(dict_[sort_on]) if hasattr(dict_[sort_on], '__len__') else dict_[
sort_on], index) for (index, dict_) in enumerate(undecorated)]
decorated.sort()
return[undecorated[index] for (key, index) in decorated] | def sort_diclist(undecorated, sort_on) | Sort a list of dictionaries by the value in each
dictionary for the sorting key
Parameters
----------
undecorated : list of dicts
sort_on : str, numeric
key that is present in all dicts to sort on
Returns
---------
ordered list of dicts
Examples
---------
>>> lst =... | 3.801591 | 4.806747 | 0.790886 |
if float_to_int:
try:
v = str(math.trunc(float(v)))
except ValueError: # catches non floatable strings
pass
except TypeError: # catches None
pass
fixed_In = []
for dictionary in In:
if k in dictionary:
val... | def get_dictitem(In, k, v, flag, float_to_int=False) | returns a list of dictionaries from list In with key,k = value, v . CASE INSENSITIVE # allowed keywords:
requires that the value of k in the dictionaries contained in In be castable to string and requires that v be castable to a string if flag is T,F
,has or not and requires they be castable to float i... | 1.933703 | 1.780541 | 1.08602 |
Out = []
for d in In:
if dtype == '':
Out.append(d[k])
if dtype == 'f':
if d[k] == "":
Out.append(0)
elif d[k] == None:
Out.append(0)
else:
Out.append(float(d[k]))
if dtype == 'int':
... | def get_dictkey(In, k, dtype) | returns list of given key (k) from input list of dictionaries (In) in data type dtype. uses command:
get_dictkey(In,k,dtype). If dtype =="", data are strings; if "int", data are integers; if "f", data are floats. | 1.876867 | 1.62434 | 1.155464 |
if isinstance(samp_data, pd.DataFrame):
samp_data = (samp_data.T.apply(dict))
# set orientation priorities
EX = ["SO-ASC", "SO-POM"]
samp_key, az_key, dip_key = 'er_sample_name', 'sample_azimuth', 'sample_dip'
disc_key, or_key, meth_key = 'sample_description', 'sample_orientation_flag',... | def get_orient(samp_data, er_sample_name, **kwargs) | samp_data : PmagPy list of dicts or pandas DataFrame
er_sample_name : sample name | 3.7603 | 3.61183 | 1.041107 |
poly_tk03 = [3.15976125e-06, -3.52459817e-04, -
1.46641090e-02, 2.89538539e+00]
return poly_tk03[0] * inc**3 + poly_tk03[1] * inc**2 + poly_tk03[2] * inc + poly_tk03[3] | def EI(inc) | Given a mean inclination value of a distribution of directions, this
function calculates the expected elongation of this distribution using a
best-fit polynomial of the TK03 GAD secular variation model (Tauxe and
Kent, 2004).
Parameters
----------
inc : inclination in degrees (int or float)
... | 4.507572 | 4.183495 | 1.077466 |
rad = np.pi/180.
Es, Is, Fs, V2s = [], [], [], []
ppars = doprinc(data)
D = ppars['dec']
Decs, Incs = data.transpose()[0], data.transpose()[1]
Tan_Incs = np.tan(Incs * rad)
for f in np.arange(1., .2, -.01):
U = old_div(np.arctan((old_div(1., f)) * Tan_Incs), rad)
fdata =... | def find_f(data) | Given a distribution of directions, this function determines parameters
(elongation, inclination, flattening factor, and elongation direction) that
are consistent with the TK03 secular variation model.
Parameters
----------
data : array of declination, inclination pairs
(e.g. np.array([[140... | 2.786108 | 2.552096 | 1.091694 |
New = []
for rec in Recs:
if 'model_lat' in list(rec.keys()) and rec['model_lat'] != "":
New.append(rec)
elif 'average_age' in list(rec.keys()) and rec['average_age'] != "" and float(rec['average_age']) <= 5.:
if 'site_lat' in list(rec.keys()) and rec['site_lat'] != ... | def convert_lat(Recs) | uses lat, for age<5Ma, model_lat if present, else tries to use average_inc to estimate plat. | 2.540287 | 1.976513 | 1.285237 |
if data_model == 3:
site_key = 'site'
agekey = "age"
keybase = ""
else:
site_key = 'er_site_names'
agekey = find('age', list(rec.keys()))
if agekey != "":
keybase = agekey.split('_')[0] + '_'
New = []
for rec in Recs:
age = ''
... | def convert_ages(Recs, data_model=3) | converts ages to Ma
Parameters
_________
Recs : list of dictionaries in data model by data_model
data_model : MagIC data model (default is 3) | 2.608892 | 2.515391 | 1.037172 |
new_recs = []
for rec in data:
new_rec = map_magic.mapping(rec, mapping)
new_recs.append(new_rec)
return new_recs | def convert_items(data, mapping) | Input: list of dicts (each dict a record for one item),
mapping with column names to swap into the records.
Output: updated list of dicts. | 3.700096 | 3.805186 | 0.972382 |
convert = {'specimens': map_magic.spec_magic2_2_magic3_map,
'samples': map_magic.samp_magic2_2_magic3_map,
'sites': map_magic.site_magic2_2_magic3_map,
'locations': map_magic.loc_magic2_2_magic3_map,
'ages': map_magic.age_magic2_2_magic3_map}
full... | def convert_directory_2_to_3(meas_fname="magic_measurements.txt", input_dir=".",
output_dir=".", meas_only=False, data_model=None) | Convert 2.0 measurements file into 3.0 measurements file.
Merge and convert specimen, sample, site, and location data.
Also translates criteria data.
Parameters
----------
meas_name : name of measurement file (do not include full path,
default is "magic_measurements.txt")
input_dir : na... | 2.962224 | 2.523801 | 1.173716 |
# read in er_ data & make DataFrame
er_file = os.path.join(input_dir, 'er_{}.txt'.format(dtype))
er_data, er_dtype = magic_read(er_file)
if len(er_data):
er_df = pd.DataFrame(er_data)
if dtype == 'ages':
pass
# remove records with blank ages
#er_d... | def convert_and_combine_2_to_3(dtype, map_dict, input_dir=".", output_dir=".", data_model=None) | Read in er_*.txt file and pmag_*.txt file in working directory.
Combine the data, then translate headers from 2.5 --> 3.0.
Last, write out the data in 3.0.
Parameters
----------
dtype : string for input type (specimens, samples, sites, etc.)
map_dict : dictionary with format {header2_format: he... | 3.11743 | 2.8061 | 1.110948 |
# get criteria from infile
fname = os.path.join(input_dir, fname)
if not os.path.exists(fname):
return False, None
orig_crit, warnings = read_criteria_from_file(fname, initialize_acceptance_criteria(),
data_model=2, return_warnings=True)
... | def convert_criteria_file_2_to_3(fname="pmag_criteria.txt", input_dir=".",
output_dir=".", data_model=None) | Convert a criteria file from 2.5 to 3.0 format and write it out to file
Parameters
----------
fname : string of filename (default "pmag_criteria.txt")
input_dir : string of input directory (default ".")
output_dir : string of output directory (default ".")
data_model : data_model.DataModel obje... | 4.459457 | 4.181808 | 1.066395 |
or_con = str(or_con)
if mag_azimuth == -999:
return "", ""
if or_con == "1": # lab_mag_az=mag_az; sample_dip = -dip
return mag_azimuth, -field_dip
if or_con == "2":
return mag_azimuth - 90., -field_dip
if or_con == "3": # lab_mag_az=mag_az; sample_dip = 90.-dip
... | def orient(mag_azimuth, field_dip, or_con) | uses specified orientation convention to convert user supplied orientations
to laboratory azimuth and plunge | 1.913188 | 1.862993 | 1.026943 |
Sb, N = 0., 0.
for rec in data:
delta = 90. - abs(rec['vgp_lat'])
if rec['average_k'] != 0:
k = rec['average_k']
L = rec['average_lat'] * np.pi / 180. # latitude in radians
Nsi = rec['average_nn']
K = old_div(k, (2. * (1. + 3. * np.sin(L)**2)... | def get_Sb(data) | returns vgp scatter for data set | 4.709038 | 4.441119 | 1.060327 |
df['delta'] = 90.-df.vgp_lat
Sp2 = np.sum(df.delta**2)/(df.shape[0]-1)
if 'dir_k' in df.columns and mm97:
ks = df.dir_k
Ns = df.dir_n
Ls = np.radians(df.lat)
A95s = 140./np.sqrt(ks*Ns)
Sw2_n = 0.335*(A95s**2)*(2.*(1.+3.*np.sin(Ls)**2) /
... | def get_sb_df(df, mm97=False) | Calculates Sf for a dataframe with VGP Lat., and optional Fisher's k, site latitude and N information can be used to correct for within site scatter (McElhinny & McFadden, 1997)
Parameters
_________
df : Pandas Dataframe with columns
REQUIRED:
vgp_lat : VGP latitude
ONLY REQUIRED f... | 6.288589 | 4.855157 | 1.295239 |
ppars = doprinc(di_block) # get principle direction
if combine:
D3 = []
D1, D2 = [], []
for rec in di_block:
ang = angle([rec[0], rec[1]], [ppars['dec'], ppars['inc']])
if ang > 90.:
d, i = (rec[0] - 180.) % 360., -rec[1]
D2.append([d, i])
... | def flip(di_block, combine=False) | determines 'normal' direction along the principle eigenvector, then flips the antipodes of
the reverse mode to the antipode
Parameters
___________
di_block : nested list of directions
Return
D1 : normal mode
D2 : flipped reverse mode as two DI blocks
combine : if True return combined D1... | 3.608239 | 3.444214 | 1.047624 |
vds, X = 0, []
for rec in data:
X.append(dir2cart(rec))
for k in range(len(X) - 1):
xdif = X[k + 1][0] - X[k][0]
ydif = X[k + 1][1] - X[k][1]
zdif = X[k + 1][2] - X[k][2]
vds += np.sqrt(xdif**2 + ydif**2 + zdif**2)
vds += np.sqrt(X[-1][0]**2 + X[-1][1]**2 + X... | def dovds(data) | calculates vector difference sum for demagnetization data | 2.105141 | 1.944698 | 1.082502 |
vdata, Dirdata, step_meth = [], [], ""
if len(data) == 0:
return vdata
treat_init = ["treatment_temp", "treatment_temp_decay_rate", "treatment_temp_dc_on", "treatment_temp_dc_off", "treatment_ac_field", "treatment_ac_field_decay_rate", "treatment_ac_field_dc_on",
"treatment_ac... | def vspec_magic(data) | Takes average vector of replicate measurements | 3.487965 | 3.409069 | 1.023143 |
# sort the specimen names
speclist = []
for rec in data:
try:
spec = rec["er_specimen_name"]
except KeyError as e:
spec = rec["specimen"]
if spec not in speclist:
speclist.append(spec)
speclist.sort()
return speclist | def get_specs(data) | Takes a magic format file and returns a list of unique specimen names | 3.537832 | 3.001507 | 1.178685 |
Xbar = np.zeros((3))
X = dir2cart(data).transpose()
for i in range(3):
Xbar[i] = X[i].sum()
R = np.sqrt(Xbar[0]**2+Xbar[1]**2+Xbar[2]**2)
Xbar = Xbar/R
dir = cart2dir(Xbar)
return dir, R | def vector_mean(data) | calculates the vector mean of a given set of vectors
Parameters
__________
data : nested array of [dec,inc,intensity]
Returns
_______
dir : array of [dec, inc, 1]
R : resultant vector length | 3.290087 | 2.944184 | 1.117487 |
datablock = []
for rec in data:
if rec['er_specimen_name'] == s:
meths = rec['magic_method_codes'].split(':')
if 'LT-NO' in meths or 'LT-AF-Z' in meths or 'LT-T-Z' in meths:
datablock.append(rec)
dmagrec = datablock[ind]
for k in range(len(data)):
... | def mark_dmag_rec(s, ind, data) | Edits demagnetization data to mark "bad" points with measurement_flag | 2.18193 | 2.20996 | 0.987317 |
try:
with codecs.open(infile, "r", "utf-8") as f:
lines = list(f.readlines())
# file might not exist
except FileNotFoundError:
if verbose:
print(
'-W- You are trying to open a file: {} that does not exist'.format(infile))
return []
# e... | def open_file(infile, verbose=True) | Open file and return a list of the file's lines.
Try to use utf-8 encoding, and if that fails use Latin-1.
Parameters
----------
infile : str
full path to file
Returns
----------
data: list
all lines in the file | 3.845847 | 3.837408 | 1.002199 |
DATA = {}
#fin = open(path, 'r')
#first_line = fin.readline()
lines = open_file(path)
if not lines:
if return_keys:
return {}, 'empty_file', None
else:
return {}, 'empty_file'
first_line = lines.pop(0)
if first_line[0] == "s" or first_line[1] == "... | def magic_read_dict(path, data=None, sort_by_this_name=None, return_keys=False) | Read a magic-formatted tab-delimited file and 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_specimen... | 2.210306 | 2.158959 | 1.023783 |
'''
Sort magic_data by header (like er_specimen_name for example)
'''
magic_data_sorted = {}
for rec in magic_data:
name = rec[sort_name]
if name not in list(magic_data_sorted.keys()):
magic_data_sorted[name] = []
magic_data_sorted[name].append(rec)
return mag... | def sort_magic_data(magic_data, sort_name) | Sort magic_data by header (like er_specimen_name for example) | 3.401698 | 2.016388 | 1.687025 |
delim = 'tab'
hold, magic_data, magic_record, magic_keys = [], [], {}, []
f = open(infile, "r")
#
# look for right table
#
line = f.readline()[:-1]
file_type = line.split('\t')[1]
if file_type == 'delimited':
file_type = line.split('\t')[2]
if delim == 'tab':
line = f.re... | def upload_read(infile, table) | Reads a table from a MagIC upload (or downloaded) txt file, puts data in a
list of dictionaries | 3.517844 | 3.467792 | 1.014433 |
pmag_out = open(ofile, 'a')
outstring = ""
for key in keylist:
try:
outstring = outstring + '\t' + str(Rec[key]).strip()
except:
print(key, Rec[key])
# raw_input()
outstring = outstring + '\n'
pmag_out.write(outstring[1:])
pmag_out.close() | def putout(ofile, keylist, Rec) | writes out a magic format record to ofile | 2.924839 | 2.791511 | 1.047762 |
keylist = []
opened = False
# sometimes Windows needs a little extra time to open a file
# or else it throws an error
while not opened:
try:
pmag_out = open(ofile, 'w')
opened = True
except IOError:
time.sleep(1)
outstring = "tab \t" + fil... | def first_rec(ofile, Rec, file_type) | opens the file ofile as a magic template file with headers as the keys to Rec | 3.533392 | 3.555578 | 0.99376 |
if len(Recs) < 1:
print ('nothing to write')
return
pmag_out = open(ofile, 'w')
outstring = "tab \t" + file_type + "\n"
pmag_out.write(outstring)
keystring = ""
keylist = []
for key in list(Recs[0].keys()):
keylist.append(key)
keylist.sort()
for key in ke... | def magic_write_old(ofile, Recs, file_type) | writes out a magic format list of dictionaries to ofile
Parameters
_________
ofile : path to output file
Recs : list of dictionaries in MagIC format
file_type : MagIC table type (e.g., specimens)
Effects :
writes a MagIC formatted file from Recs | 2.227152 | 2.228367 | 0.999455 |
if len(Recs) < 1:
print('No records to write to file {}'.format(ofile))
return False, ""
if os.path.split(ofile)[0] != "" and not os.path.isdir(os.path.split(ofile)[0]):
os.mkdir(os.path.split(ofile)[0])
pmag_out = open(ofile, 'w+', errors="backslashreplace")
outstring = "ta... | def magic_write(ofile, Recs, file_type) | Parameters
_________
ofile : path to output file
Recs : list of dictionaries in MagIC format
file_type : MagIC table type (e.g., specimens)
Return :
[True,False] : True if successful
ofile : same as input
Effects :
writes a MagIC formatted file from Recs | 2.420057 | 2.406595 | 1.005594 |
rad = old_div(np.pi, 180.) # converts from degrees to radians
X = dir2cart([dec, inc, 1.]) # get cartesian coordinates of dec,inc
# get some sines and cosines of new coordinate system
sa, ca = -np.sin(bed_az * rad), np.cos(bed_az * rad)
cdp, sdp = np.cos(bed_dip * rad), np.sin(bed_dip * rad)
# do... | def dotilt(dec, inc, bed_az, bed_dip) | Does a tilt correction on a direction (dec,inc) using bedding dip direction
and bedding dip.
Parameters
----------
dec : declination directions in degrees
inc : inclination direction in degrees
bed_az : bedding dip direction
bed_dip : bedding dip
Returns
-------
dec,inc : a tup... | 3.46855 | 3.559769 | 0.974375 |
indat = indat.transpose()
# unpack input array into separate arrays
dec, inc, bed_az, bed_dip = indat[0], indat[1], indat[2], indat[3]
rad = old_div(np.pi, 180.) # convert to radians
Dir = np.array([dec, inc]).transpose()
X = dir2cart(Dir).transpose() # get cartesian coordinates
N = n... | def dotilt_V(indat) | Does a tilt correction on an array with rows of dec,inc bedding dip direction and dip.
Parameters
----------
input : declination, inclination, bedding dip direction and bedding dip
nested array of [[dec1, inc1, bed_az1, bed_dip1],[dec2,inc2,bed_az2,bed_dip2]...]
Returns
-------
dec,inc : a... | 3.499204 | 3.229907 | 1.083376 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.