_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q11800
|
Demag_GUI.on_btn_delete_fit
|
train
|
def on_btn_delete_fit(self, event):
"""
removes the current interpretation
Parameters
----------
event : the wx.ButtonEvent that triggered this function
"""
self.delete_fit(self.current_fit, specimen=self.s)
|
python
|
{
"resource": ""
}
|
q11801
|
Demag_GUI.do_auto_save
|
train
|
def do_auto_save(self):
"""
Delete current fit if auto_save==False,
unless current fit has explicitly been saved.
"""
if not self.auto_save.GetValue():
if self.current_fit:
if not self.current_fit.saved:
self.delete_fit(self.current_fit, specimen=self.s)
|
python
|
{
"resource": ""
}
|
q11802
|
Demag_GUI.on_next_button
|
train
|
def on_next_button(self, event):
"""
update figures and text when a next button is selected
"""
self.do_auto_save()
self.selected_meas = []
index = self.specimens.index(self.s)
try:
fit_index = self.pmag_results_data['specimens'][self.s].index(
self.current_fit)
except KeyError:
fit_index = None
except ValueError:
fit_index = None
if index == len(self.specimens)-1:
index = 0
else:
index += 1
# sets self.s calculates params etc.
self.initialize_CART_rot(str(self.specimens[index]))
self.specimens_box.SetStringSelection(str(self.s))
if fit_index != None and self.s in self.pmag_results_data['specimens']:
try:
self.current_fit = self.pmag_results_data['specimens'][self.s][fit_index]
except IndexError:
self.current_fit = None
else:
self.current_fit = None
if self.ie_open:
self.ie.change_selected(self.current_fit)
self.update_selection()
|
python
|
{
"resource": ""
}
|
q11803
|
main
|
train
|
def main():
"""
NAME
watsons_f.py
DESCRIPTION
calculates Watson's F statistic from input files
INPUT FORMAT
takes dec/inc as first two columns in two space delimited files
SYNTAX
watsons_f.py [command line options]
OPTIONS
-h prints help message and quits
-f FILE (with optional second)
-f2 FILE (second file)
-ant, flip antipodal directions in FILE to opposite direction
OUTPUT
Watson's F, critical value from F-tables for 2, 2(N-2) degrees of freedom
"""
D,D1,D2=[],[],[]
Flip=0
if '-h' in sys.argv: # check if help is needed
print(main.__doc__)
sys.exit() # graceful quit
if '-ant' in sys.argv: Flip=1
if '-f' in sys.argv:
ind=sys.argv.index('-f')
file1=sys.argv[ind+1]
if '-f2' in sys.argv:
ind=sys.argv.index('-f2')
file2=sys.argv[ind+1]
f=open(file1,'r')
for line in f.readlines():
if '\t' in line:
rec=line.split('\t') # split each line on space to get records
else:
rec=line.split() # split each line on space to get records
Dec,Inc=float(rec[0]),float(rec[1])
D1.append([Dec,Inc,1.])
D.append([Dec,Inc,1.])
f.close()
if Flip==0:
f=open(file2,'r')
for line in f.readlines():
rec=line.split()
Dec,Inc=float(rec[0]),float(rec[1])
D2.append([Dec,Inc,1.])
D.append([Dec,Inc,1.])
f.close()
else:
D1,D2=pmag.flip(D1)
for d in D2: D.append(d)
#
# first calculate the fisher means and cartesian coordinates of each set of Directions
#
pars_0=pmag.fisher_mean(D)
pars_1=pmag.fisher_mean(D1)
pars_2=pmag.fisher_mean(D2)
#
# get F statistic for these
#
N= len(D)
R=pars_0['r']
R1=pars_1['r']
R2=pars_2['r']
F=(N-2)*(old_div((R1+R2-R),(N-R1-R2)))
Fcrit=pmag.fcalc(2,2*(N-2))
print('%7.2f %7.2f'%(F,Fcrit))
|
python
|
{
"resource": ""
}
|
q11804
|
in_SCAT_box
|
train
|
def in_SCAT_box(x, y, low_bound, high_bound, x_max, y_max):
"""determines if a particular point falls within a box"""
passing = True
upper_limit = high_bound(x)
lower_limit = low_bound(x)
if x > x_max or y > y_max:
passing = False
if x < 0 or y < 0:
passing = False
if y > upper_limit:
passing = False
if y < lower_limit:
passing = False
return passing
|
python
|
{
"resource": ""
}
|
q11805
|
get_SCAT_points
|
train
|
def get_SCAT_points(x_Arai_segment, y_Arai_segment, tmin, tmax, ptrm_checks_temperatures,
ptrm_checks_starting_temperatures, x_ptrm_check, y_ptrm_check,
tail_checks_temperatures, tail_checks_starting_temperatures,
x_tail_check, y_tail_check):
"""returns relevant points for a SCAT test"""
points = []
points_arai = []
points_ptrm = []
points_tail = []
for i in range(len(x_Arai_segment)): # uses only the best_fit segment, so no need for further selection
x = x_Arai_segment[i]
y = y_Arai_segment[i]
points.append((x, y))
points_arai.append((x,y))
for num, temp in enumerate(ptrm_checks_temperatures): #
if temp >= tmin and temp <= tmax: # if temp is within selected range
if (ptrm_checks_starting_temperatures[num] >= tmin and
ptrm_checks_starting_temperatures[num] <= tmax): # and also if it was not done after an out-of-range temp
x = x_ptrm_check[num]
y = y_ptrm_check[num]
points.append((x, y))
points_ptrm.append((x,y))
for num, temp in enumerate(tail_checks_temperatures):
if temp >= tmin and temp <= tmax:
if (tail_checks_starting_temperatures[num] >= tmin and
tail_checks_starting_temperatures[num] <= tmax):
x = x_tail_check[num]
y = y_tail_check[num]
points.append((x, y))
points_tail.append((x,y))
# print "points (tail checks added)", points
fancy_points = {'points_arai': points_arai, 'points_ptrm': points_ptrm, 'points_tail': points_tail}
return points, fancy_points
|
python
|
{
"resource": ""
}
|
q11806
|
get_SCAT
|
train
|
def get_SCAT(points, low_bound, high_bound, x_max, y_max):
"""
runs SCAT test and returns boolean
"""
# iterate through all relevant points and see if any of them fall outside of your SCAT box
SCAT = True
for point in points:
result = in_SCAT_box(point[0], point[1], low_bound, high_bound, x_max, y_max)
if result == False:
# print "SCAT TEST FAILED"
SCAT = False
return SCAT
|
python
|
{
"resource": ""
}
|
q11807
|
fancy_SCAT
|
train
|
def fancy_SCAT(points, low_bound, high_bound, x_max, y_max):
"""
runs SCAT test and returns 'Pass' or 'Fail'
"""
# iterate through all relevant points and see if any of them fall outside of your SCAT box
# {'points_arai': [(x,y),(x,y)], 'points_ptrm': [(x,y),(x,y)], ...}
SCAT = 'Pass'
SCATs = {'SCAT_arai': 'Pass', 'SCAT_ptrm': 'Pass', 'SCAT_tail': 'Pass'}
for point_type in points:
#print 'point_type', point_type
for point in points[point_type]:
#print 'point', point
result = in_SCAT_box(point[0], point[1], low_bound, high_bound, x_max, y_max)
if not result:
# print "SCAT TEST FAILED"
x = 'SCAT' + point_type[6:]
#print 'lib point type', point_type
#print 'xxxx', x
SCATs[x] = 'Fail'
SCAT = 'Fail'
return SCAT, SCATs
|
python
|
{
"resource": ""
}
|
q11808
|
get_R_det2
|
train
|
def get_R_det2(y_segment, y_avg, y_prime):
"""
takes in an array of y values, the mean of those values, and the array of y prime values.
returns R_det2
"""
numerator = sum((numpy.array(y_segment) - numpy.array(y_prime))**2)
denominator = sum((numpy.array(y_segment) - y_avg)**2)
if denominator: # prevent divide by zero error
R_det2 = 1 - (old_div(numerator, denominator))
return R_det2
else:
return float('nan')
|
python
|
{
"resource": ""
}
|
q11809
|
get_b_wiggle
|
train
|
def get_b_wiggle(x, y, y_int):
"""returns instantaneous slope from the ratio of NRM lost to TRM gained at the ith step"""
if x == 0:
b_wiggle = 0
else:
b_wiggle = old_div((y_int - y), x)
return b_wiggle
|
python
|
{
"resource": ""
}
|
q11810
|
main
|
train
|
def main():
"""
NAME
stats.py
DEFINITION
calculates Gauss statistics for input data
SYNTAX
stats [command line options][< filename]
INPUT
single column of numbers
OPTIONS
-h prints help message and quits
-i interactive entry of file name
-f input file name
-F output file name
OUTPUT
N, mean, sum, sigma, (%)
where sigma is the standard deviation
where % is sigma as percentage of the mean
stderr is the standard error and
95% conf.= 1.96*sigma/sqrt(N)
"""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-i' in sys.argv:
file=input("Enter file name: ")
f=open(file,'r')
elif '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
f=open(file,'r')
else:
f=sys.stdin
ofile = ""
if '-F' in sys.argv:
ind = sys.argv.index('-F')
ofile= sys.argv[ind+1]
out = open(ofile, 'w + a')
data=f.readlines()
dat=[]
sum=0
for line in data:
rec=line.split()
dat.append(float(rec[0]))
sum+=float(float(rec[0]))
mean,std=pmag.gausspars(dat)
outdata = len(dat),mean,sum,std,100*std/mean
if ofile == "":
print(len(dat),mean,sum,std,100*std/mean)
else:
for i in outdata:
i = str(i)
out.write(i + " ")
|
python
|
{
"resource": ""
}
|
q11811
|
main
|
train
|
def main():
"""
NAME
magic_select.py
DESCRIPTION
picks out records and dictitem options saves to magic_special file
SYNTAX
magic_select.py [command line optins]
OPTIONS
-h prints help message and quits
-f FILE: specify input magic format file
-F FILE: specify output magic format file
-dm : data model (default is 3.0, otherwise use 2.5)
-key KEY string [T,F,has, not, eval,min,max]
returns records where the value of the key either:
matches exactly the string (T)
does not match the string (F)
contains the string (has)
does not contain the string (not)
the value equals the numerical value of the string (eval)
the value is greater than the numerical value of the string (min)
the value is less than the numerical value of the string (max)
NOTES
for age range:
use KEY: age (converts to Ma, takes mid point of low, high if no value for age.
for paleolat:
use KEY: model_lat (uses lat, if age<5 Ma, else, model_lat, or attempts calculation from average_inc if no model_lat.) returns estimate in model_lat key
EXAMPLE:
# here I want to output all records where the site column exactly matches "MC01"
magic_select.py -f samples.txt -key site MC01 T -F select_samples.txt
"""
dir_path = "."
flag = ''
if '-WD' in sys.argv:
ind = sys.argv.index('-WD')
dir_path = sys.argv[ind+1]
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-f' in sys.argv:
ind = sys.argv.index('-f')
magic_file = dir_path+'/'+sys.argv[ind+1]
else:
print(main.__doc__)
print('-W- "-f" is a required option')
sys.exit()
if '-dm' in sys.argv:
ind = sys.argv.index('-dm')
data_model_num=sys.argv[ind+1]
if data_model_num!='3':data_model_num=2.5
else : data_model_num=3
if '-F' in sys.argv:
ind = sys.argv.index('-F')
outfile = dir_path+'/'+sys.argv[ind+1]
else:
print(main.__doc__)
print('-W- "-F" is a required option')
sys.exit()
if '-key' in sys.argv:
ind = sys.argv.index('-key')
grab_key = sys.argv[ind+1]
v = sys.argv[ind+2]
flag = sys.argv[ind+3]
else:
print(main.__doc__)
print('-key is required')
sys.exit()
#
# get data read in
Data, file_type = pmag.magic_read(magic_file)
if grab_key == 'age':
grab_key = 'average_age'
Data = pmag.convert_ages(Data,data_model=data_model_num)
if grab_key == 'model_lat':
Data = pmag.convert_lat(Data)
Data = pmag.convert_ages(Data,data_model=data_model_num)
#print(Data[0])
Selection = pmag.get_dictitem(Data, grab_key, v, flag, float_to_int=True)
if len(Selection) > 0:
pmag.magic_write(outfile, Selection, file_type)
else:
print('no data matched your criteria')
|
python
|
{
"resource": ""
}
|
q11812
|
main
|
train
|
def main():
"""
NAME
di_geo.py
DESCRIPTION
rotates specimen coordinate dec, inc data to geographic
coordinates using the azimuth and plunge of the X direction
INPUT FORMAT
declination inclination azimuth plunge
SYNTAX
di_geo.py [-h][-i][-f FILE] [< filename ]
OPTIONS
-h prints help message and quits
-i for interactive data entry
-f FILE command line entry of file name
-F OFILE, specify output file, default is standard output
OUTPUT:
declination inclination
"""
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')
print(ofile, ' opened for output')
else: ofile=""
if '-i' in sys.argv: # interactive flag
while 1:
try:
Dec=float(input("Declination: <cntrl-D> to quit "))
except EOFError:
print("\n Good-bye\n")
sys.exit()
Inc=float(input("Inclination: "))
Az=float(input("Azimuth: "))
Pl=float(input("Plunge: "))
print('%7.1f %7.1f'%(pmag.dogeo(Dec,Inc,Az,Pl)))
elif '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
data=numpy.loadtxt(file)
else:
data=numpy.loadtxt(sys.stdin,dtype=numpy.float) # read in the data from the datafile
D,I=pmag.dogeo_V(data)
for k in range(len(D)):
if ofile=="":
print('%7.1f %7.1f'%(D[k],I[k]))
else:
out.write('%7.1f %7.1f\n'%(D[k],I[k]))
|
python
|
{
"resource": ""
}
|
q11813
|
LinInt.call
|
train
|
def call(self, x):
"""
Evaluate the interpolant, assuming x is a scalar.
"""
# if out of range, return endpoint
if x <= self.x_vals[0]:
return self.y_vals[0]
if x >= self.x_vals[-1]:
return self.y_vals[-1]
pos = numpy.searchsorted(self.x_vals, x)
h = self.x_vals[pos]-self.x_vals[pos-1]
if h == 0.0:
raise BadInput
a = old_div((self.x_vals[pos] - x), h)
b = old_div((x - self.x_vals[pos-1]), h)
return a*self.y_vals[pos-1] + b*self.y_vals[pos]
|
python
|
{
"resource": ""
}
|
q11814
|
main
|
train
|
def main():
"""
NAME
aarm_magic.py
DESCRIPTION
Converts AARM data to best-fit tensor (6 elements plus sigma)
Original program ARMcrunch written to accomodate ARM anisotropy data
collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the
off-axis remanence terms to construct the tensor. A better way to
do the anisotropy of ARMs is to use 9,12 or 15 measurements in
the Hext rotational scheme.
SYNTAX
aarm_magic.py [-h][command line options]
OPTIONS
-h prints help message and quits
-f FILE: specify input file, default is aarm_measurements.txt
-crd [s,g,t] specify coordinate system, requires samples file
-fsa FILE: specify er_samples.txt file, default is er_samples.txt (2.5) or samples.txt (3.0)
-Fa FILE: specify anisotropy output file, default is arm_anisotropy.txt (MagIC 2.5 only)
-Fr FILE: specify results output file, default is aarm_results.txt (MagIC 2.5 only)
-Fsi FILE: specify output file, default is specimens.txt (MagIC 3 only)
-DM DATA_MODEL: specify MagIC 2 or MagIC 3, default is 3
INPUT
Input for the present program is a series of baseline, ARM pairs.
The baseline should be the AF demagnetized state (3 axis demag is
preferable) for the following ARM acquisition. The order of the
measurements is:
positions 1,2,3, 6,7,8, 11,12,13 (for 9 positions)
positions 1,2,3,4, 6,7,8,9, 11,12,13,14 (for 12 positions)
positions 1-15 (for 15 positions)
"""
# initialize some parameters
args = sys.argv
if "-h" in args:
print(main.__doc__)
sys.exit()
#meas_file = "aarm_measurements.txt"
#rmag_anis = "arm_anisotropy.txt"
#rmag_res = "aarm_results.txt"
#
# get name of file from command line
#
data_model_num = int(pmag.get_named_arg("-DM", 3))
spec_file = pmag.get_named_arg("-Fsi", "specimens.txt")
if data_model_num == 3:
samp_file = pmag.get_named_arg("-fsa", "samples.txt")
else:
samp_file = pmag.get_named_arg("-fsa", "er_samples.txt")
dir_path = pmag.get_named_arg('-WD', '.')
input_dir_path = pmag.get_named_arg('-ID', '')
infile = pmag.get_named_arg('-f', reqd=True)
coord = pmag.get_named_arg('-crd', '-1')
#if "-Fa" in args:
# ind = args.index("-Fa")
# rmag_anis = args[ind + 1]
#if "-Fr" in args:
# ind = args.index("-Fr")
# rmag_res = args[ind + 1]
ipmag.aarm_magic(infile, dir_path, input_dir_path,
spec_file, samp_file, data_model_num,
coord)
|
python
|
{
"resource": ""
}
|
q11815
|
main
|
train
|
def main():
"""
NAME
mini_magic.py
DESCRIPTION
converts the Yale minispin format to magic_measurements format files
SYNTAX
mini_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-usr USER: identify user, default is ""
-f FILE: specify input file, required
-F FILE: specify output file, default is magic_measurements.txt
-LP [colon delimited list of protocols, include all that apply]
AF: af demag
T: thermal including thellier but not trm acquisition
-A: don't average replicate measurements
-vol: volume assumed for measurement in cm^3 (default 12 cc)
-DM NUM: MagIC data model (2 or 3, default 3)
INPUT
Must put separate experiments (all AF, thermal, etc.) in
seperate files
Format of Yale MINI files:
LL-SI-SP_STEP, Declination, Inclination, Intensity (mA/m), X,Y,Z
"""
args = sys.argv
if "-h" in args:
print(main.__doc__)
sys.exit()
# initialize some stuff
methcode = "LP-NO"
demag = "N"
#
# get command line arguments
#
data_model_num = int(float(pmag.get_named_arg("-DM", 3)))
user = pmag.get_named_arg("-usr", "")
dir_path = pmag.get_named_arg("-WD", ".")
inst = pmag.get_named_arg("-inst", "")
magfile = pmag.get_named_arg("-f", reqd=True)
magfile = pmag.resolve_file_name(magfile, dir_path)
if "-A" in args:
noave = 1
else:
noave = 0
if data_model_num == 2:
meas_file = pmag.get_named_arg("-F", "magic_measurements.txt")
else:
meas_file = pmag.get_named_arg("-F", "measurements.txt")
meas_file = pmag.resolve_file_name(meas_file, dir_path)
volume = pmag.get_named_arg("-vol", 12) # assume a volume of 12 cc if not provided
methcode = pmag.get_named_arg("-LP", "LP-NO")
#ind = args.index("-LP")
#codelist = args[ind+1]
#codes = codelist.split(':')
#if "AF" in codes:
# demag = 'AF'
# methcode = "LT-AF-Z"
#if "T" in codes:
# demag = "T"
convert.mini(magfile, dir_path, meas_file, data_model_num,
volume, noave, inst, user, methcode)
|
python
|
{
"resource": ""
}
|
q11816
|
Arai_GUI.get_DIR
|
train
|
def get_DIR(self, WD=None):
"""
open dialog box for choosing a working directory
"""
if "-WD" in sys.argv and FIRST_RUN:
ind = sys.argv.index('-WD')
self.WD = sys.argv[ind + 1]
elif not WD: # if no arg was passed in for WD, make a dialog to choose one
dialog = wx.DirDialog(None, "Choose a directory:", defaultPath=self.currentDirectory,
style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON | wx.DD_CHANGE_DIR)
ok = self.show_dlg(dialog)
if ok == wx.ID_OK:
self.WD = dialog.GetPath()
else:
self.WD = os.getcwd()
dialog.Destroy()
self.WD = os.path.realpath(self.WD)
# name measurement file
if self.data_model == 3:
meas_file = 'measurements.txt'
else:
meas_file = 'magic_measurements.txt'
self.magic_file = os.path.join(self.WD, meas_file)
# intialize GUI_log
self.GUI_log = open(os.path.join(self.WD, "thellier_GUI.log"), 'w+')
self.GUI_log.write("starting...\n")
self.GUI_log.close()
self.GUI_log = open(os.path.join(self.WD, "thellier_GUI.log"), 'a')
os.chdir(self.WD)
self.WD = os.getcwd()
|
python
|
{
"resource": ""
}
|
q11817
|
Arai_GUI.update_selection
|
train
|
def update_selection(self):
"""
update figures and statistics windows with a new selection of specimen
"""
# clear all boxes
self.clear_boxes()
self.draw_figure(self.s)
# update temperature list
if self.Data[self.s]['T_or_MW'] == "T":
self.temperatures = np.array(self.Data[self.s]['t_Arai']) - 273.
else:
self.temperatures = np.array(self.Data[self.s]['t_Arai'])
self.T_list = ["%.0f" % T for T in self.temperatures]
self.tmin_box.SetItems(self.T_list)
self.tmax_box.SetItems(self.T_list)
self.tmin_box.SetValue("")
self.tmax_box.SetValue("")
self.Blab_window.SetValue(
"%.0f" % (float(self.Data[self.s]['pars']['lab_dc_field']) * 1e6))
if "saved" in self.Data[self.s]['pars']:
self.pars = self.Data[self.s]['pars']
self.update_GUI_with_new_interpretation()
self.Add_text(self.s)
self.write_sample_box()
|
python
|
{
"resource": ""
}
|
q11818
|
Arai_GUI.on_info_click
|
train
|
def on_info_click(self, event):
"""
Show popup info window when user clicks "?"
"""
def on_close(event, wind):
wind.Close()
wind.Destroy()
event.Skip()
wind = wx.PopupTransientWindow(self, wx.RAISED_BORDER)
if self.auto_save.GetValue():
info = "'auto-save' is currently selected. Temperature bounds will be saved when you click 'next' or 'back'."
else:
info = "'auto-save' is not selected. Temperature bounds will only be saved when you click 'save'."
text = wx.StaticText(wind, -1, info)
box = wx.StaticBox(wind, -1, 'Info:')
boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
boxSizer.Add(text, 5, wx.ALL | wx.CENTER)
exit_btn = wx.Button(wind, wx.ID_EXIT, 'Close')
wind.Bind(wx.EVT_BUTTON, lambda evt: on_close(evt, wind), exit_btn)
boxSizer.Add(exit_btn, 5, wx.ALL | wx.CENTER)
wind.SetSizer(boxSizer)
wind.Layout()
wind.Popup()
|
python
|
{
"resource": ""
}
|
q11819
|
Arai_GUI.on_prev_button
|
train
|
def on_prev_button(self, event):
"""
update figures and text when a previous button is selected
"""
if 'saved' not in self.Data[self.s]['pars'] or self.Data[self.s]['pars']['saved'] != True:
# check preferences
if self.auto_save.GetValue():
self.on_save_interpretation_button(None)
else:
del self.Data[self.s]['pars']
self.Data[self.s]['pars'] = {}
self.Data[self.s]['pars']['lab_dc_field'] = self.Data[self.s]['lab_dc_field']
self.Data[self.s]['pars']['er_specimen_name'] = self.Data[self.s]['er_specimen_name']
self.Data[self.s]['pars']['er_sample_name'] = self.Data[self.s]['er_sample_name']
# return to last saved interpretation if exist
if 'er_specimen_name' in list(self.last_saved_pars.keys()) and self.last_saved_pars['er_specimen_name'] == self.s:
for key in list(self.last_saved_pars.keys()):
self.Data[self.s]['pars'][key] = self.last_saved_pars[key]
self.last_saved_pars = {}
index = self.specimens.index(self.s)
if index == 0:
index = len(self.specimens)
index -= 1
self.s = self.specimens[index]
self.specimens_box.SetStringSelection(self.s)
self.update_selection()
|
python
|
{
"resource": ""
}
|
q11820
|
Arai_GUI.read_preferences_file
|
train
|
def read_preferences_file(self):
"""
If json preferences file exists, read it in.
"""
user_data_dir = find_pmag_dir.find_user_data_dir("thellier_gui")
if not user_data_dir:
return {}
if os.path.exists(user_data_dir):
pref_file = os.path.join(user_data_dir, "thellier_gui_preferences.json")
if os.path.exists(pref_file):
with open(pref_file, "r") as pfile:
return json.load(pfile)
return {}
|
python
|
{
"resource": ""
}
|
q11821
|
Arai_GUI.on_menu_exit
|
train
|
def on_menu_exit(self, event):
"""
Runs whenever Thellier GUI exits
"""
if self.close_warning:
TEXT = "Data is not saved to a file yet!\nTo properly save your data:\n1) Analysis --> Save current interpretations to a redo file.\nor\n1) File --> Save MagIC tables.\n\n Press OK to exit without saving."
dlg1 = wx.MessageDialog(
None, caption="Warning:", message=TEXT, style=wx.OK | wx.CANCEL | wx.ICON_EXCLAMATION)
if self.show_dlg(dlg1) == wx.ID_OK:
dlg1.Destroy()
self.GUI_log.close()
self.Destroy()
# if a custom quit event is specified, fire it
if self.evt_quit:
event = self.evt_quit(self.GetId())
self.GetEventHandler().ProcessEvent(event)
if self.standalone:
sys.exit()
else:
self.GUI_log.close()
self.Destroy()
# if a custom quit event is specified, fire it
if self.evt_quit:
event = self.evt_quit(self.GetId())
self.GetEventHandler().ProcessEvent(event)
if self.standalone:
sys.exit()
|
python
|
{
"resource": ""
}
|
q11822
|
Arai_GUI.On_close_criteria_box
|
train
|
def On_close_criteria_box(self, dia):
"""
after criteria dialog window is closed.
Take the acceptance criteria values and update
self.acceptance_criteria
"""
criteria_list = list(self.acceptance_criteria.keys())
criteria_list.sort()
#---------------------------------------
# check if averaging by sample or by site
# and intialize sample/site criteria
#---------------------------------------
avg_by = dia.set_average_by_sample_or_site.GetValue()
if avg_by == 'sample':
for crit in ['site_int_n', 'site_int_sigma', 'site_int_sigma_perc', 'site_aniso_mean', 'site_int_n_outlier_check']:
self.acceptance_criteria[crit]['value'] = -999
if avg_by == 'site':
for crit in ['sample_int_n', 'sample_int_sigma', 'sample_int_sigma_perc', 'sample_aniso_mean', 'sample_int_n_outlier_check']:
self.acceptance_criteria[crit]['value'] = -999
#---------
# get value for each criterion
for i in range(len(criteria_list)):
crit = criteria_list[i]
value, accept = dia.get_value_for_crit(crit, self.acceptance_criteria)
if accept:
self.acceptance_criteria.update(accept)
#---------
# thellier interpreter calculation type
if dia.set_stdev_opt.GetValue() == True:
self.acceptance_criteria['interpreter_method']['value'] = 'stdev_opt'
elif dia.set_bs.GetValue() == True:
self.acceptance_criteria['interpreter_method']['value'] = 'bs'
elif dia.set_bs_par.GetValue() == True:
self.acceptance_criteria['interpreter_method']['value'] = 'bs_par'
# message dialog
dlg1 = wx.MessageDialog(
self, caption="Warning:", message="changes are saved to the criteria file\n ", style=wx.OK)
result = self.show_dlg(dlg1)
if result == wx.ID_OK:
try:
self.clear_boxes()
except IndexError:
pass
try:
self.write_acceptance_criteria_to_boxes()
except IOError:
pass
if self.data_model == 3:
crit_file = 'criteria.txt'
else:
crit_file = 'pmag_criteria.txt'
try:
pmag.write_criteria_to_file(os.path.join(
self.WD, crit_file), self.acceptance_criteria, data_model=self.data_model, prior_crits=self.crit_data)
except AttributeError as ex:
print(ex)
print("no criteria given to save")
dlg1.Destroy()
dia.Destroy()
self.fig4.texts[0].remove()
txt = "{} data".format(avg_by).capitalize()
self.fig4.text(0.02, 0.96, txt, {
'family': self.font_type, 'fontsize': 10, 'style': 'normal', 'va': 'center', 'ha': 'left'})
self.recalculate_satistics()
try:
self.update_GUI_with_new_interpretation()
except KeyError:
pass
|
python
|
{
"resource": ""
}
|
q11823
|
Arai_GUI.read_criteria_file
|
train
|
def read_criteria_file(self, criteria_file):
'''
read criteria file.
initialize self.acceptance_criteria
try to guess if averaging by sample or by site.
'''
if self.data_model == 3:
self.acceptance_criteria = pmag.initialize_acceptance_criteria(
data_model=self.data_model)
self.add_thellier_gui_criteria()
fnames = {'criteria': criteria_file}
contribution = cb.Contribution(
self.WD, custom_filenames=fnames, read_tables=['criteria'])
if 'criteria' in contribution.tables:
crit_container = contribution.tables['criteria']
crit_data = crit_container.df
crit_data['definition'] = 'acceptance criteria for study'
# convert to list of dictionaries
self.crit_data = crit_data.to_dict('records')
for crit in self.crit_data: # step through and rename every f-ing one
# magic2[magic3.index(crit['table_column'])] # find data
# model 2.5 name
m2_name = map_magic.convert_intensity_criteria(
'magic2', crit['table_column'])
if not m2_name:
pass
elif m2_name not in self.acceptance_criteria:
print('-W- Your criteria file contains {}, which is not currently supported in Thellier GUI.'.format(m2_name))
print(' This record will be skipped:\n {}'.format(crit))
else:
if m2_name != crit['table_column'] and 'scat' not in m2_name != "":
self.acceptance_criteria[m2_name]['value'] = float(
crit['criterion_value'])
self.acceptance_criteria[m2_name]['pmag_criteria_code'] = crit['criterion']
if m2_name != crit['table_column'] and 'scat' in m2_name != "":
if crit['criterion_value'] == 'True':
self.acceptance_criteria[m2_name]['value'] = 1
else:
self.acceptance_criteria[m2_name]['value'] = 0
else:
print("-E- Can't read criteria file")
else: # Do it the data model 2.5 way:
self.crit_data = {}
try:
self.acceptance_criteria = pmag.read_criteria_from_file(
criteria_file, self.acceptance_criteria)
except:
print("-E- Can't read pmag criteria file")
# guesss if average by site or sample:
by_sample = True
flag = False
for crit in ['sample_int_n', 'sample_int_sigma_perc', 'sample_int_sigma']:
if self.acceptance_criteria[crit]['value'] == -999:
flag = True
if flag:
for crit in ['site_int_n', 'site_int_sigma_perc', 'site_int_sigma']:
if self.acceptance_criteria[crit]['value'] != -999:
by_sample = False
if not by_sample:
self.acceptance_criteria['average_by_sample_or_site']['value'] = 'site'
|
python
|
{
"resource": ""
}
|
q11824
|
Arai_GUI.on_menu_save_interpretation
|
train
|
def on_menu_save_interpretation(self, event):
'''
save interpretations to a redo file
'''
thellier_gui_redo_file = open(
os.path.join(self.WD, "thellier_GUI.redo"), 'w')
#--------------------------------------------------
# write interpretations to thellier_GUI.redo
#--------------------------------------------------
spec_list = list(self.Data.keys())
spec_list.sort()
redo_specimens_list = []
for sp in spec_list:
if 'saved' not in self.Data[sp]['pars']:
continue
if not self.Data[sp]['pars']['saved']:
continue
redo_specimens_list.append(sp)
thellier_gui_redo_file.write("%s %.0f %.0f\n" % (
sp, self.Data[sp]['pars']['measurement_step_min'], self.Data[sp]['pars']['measurement_step_max']))
dlg1 = wx.MessageDialog(
self, caption="Saved:", message="File thellier_GUI.redo is saved in MagIC working folder", style=wx.OK)
result = self.show_dlg(dlg1)
if result == wx.ID_OK:
dlg1.Destroy()
thellier_gui_redo_file.close()
return
thellier_gui_redo_file.close()
self.close_warning = False
|
python
|
{
"resource": ""
}
|
q11825
|
Arai_GUI.on_menu_clear_interpretation
|
train
|
def on_menu_clear_interpretation(self, event):
'''
clear all current interpretations.
'''
# delete all previous interpretation
for sp in list(self.Data.keys()):
del self.Data[sp]['pars']
self.Data[sp]['pars'] = {}
self.Data[sp]['pars']['lab_dc_field'] = self.Data[sp]['lab_dc_field']
self.Data[sp]['pars']['er_specimen_name'] = self.Data[sp]['er_specimen_name']
self.Data[sp]['pars']['er_sample_name'] = self.Data[sp]['er_sample_name']
self.Data_samples = {}
self.Data_sites = {}
self.tmin_box.SetValue("")
self.tmax_box.SetValue("")
self.clear_boxes()
self.draw_figure(self.s)
|
python
|
{
"resource": ""
}
|
q11826
|
Arai_GUI.get_new_T_PI_parameters
|
train
|
def get_new_T_PI_parameters(self, event):
"""
calcualte statisics when temperatures are selected
"""
# remember the last saved interpretation
if "saved" in list(self.pars.keys()):
if self.pars['saved']:
self.last_saved_pars = {}
for key in list(self.pars.keys()):
self.last_saved_pars[key] = self.pars[key]
self.pars['saved'] = False
t1 = self.tmin_box.GetValue()
t2 = self.tmax_box.GetValue()
if (t1 == "" or t2 == ""):
print("empty interpretation bounds")
return
if float(t2) < float(t1):
print("upper bound less than lower bound")
return
index_1 = self.T_list.index(t1)
index_2 = self.T_list.index(t2)
# if (index_2-index_1)+1 >= self.acceptance_criteria['specimen_int_n']:
if (index_2 - index_1) + 1 >= 3:
if self.Data[self.s]['T_or_MW'] != "MW":
self.pars = thellier_gui_lib.get_PI_parameters(self.Data, self.acceptance_criteria, self.preferences, self.s, float(
t1) + 273., float(t2) + 273., self.GUI_log, THERMAL, MICROWAVE)
self.Data[self.s]['pars'] = self.pars
else:
self.pars = thellier_gui_lib.get_PI_parameters(
self.Data, self.acceptance_criteria, self.preferences, self.s, float(t1), float(t2), self.GUI_log, THERMAL, MICROWAVE)
self.Data[self.s]['pars'] = self.pars
self.update_GUI_with_new_interpretation()
self.Add_text(self.s)
|
python
|
{
"resource": ""
}
|
q11827
|
main
|
train
|
def main():
"""
NAME
histplot.py
DESCRIPTION
makes histograms for data
OPTIONS
-h prints help message and quits
-f input file name
-b binsize
-fmt [svg,png,pdf,eps,jpg] specify format for image, default is svg
-sav save figure and quit
-F output file name, default is hist.fmt
-N don't normalize
-twin plot both normalized and un-normalized y axes
-xlab Label of X axis
-ylab Label of Y axis
INPUT FORMAT
single variable
SYNTAX
histplot.py [command line options] [<file]
"""
save_plots = False
if '-sav' in sys.argv:
save_plots = True
interactive = False
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
fmt = pmag.get_named_arg('-fmt', 'svg')
fname = pmag.get_named_arg('-f', '')
outfile = pmag.get_named_arg("-F", "")
norm = 1
if '-N' in sys.argv:
norm = 0
if '-twin' in sys.argv:
norm = - 1
binsize = pmag.get_named_arg('-b', 0)
if '-xlab' in sys.argv:
ind = sys.argv.index('-xlab')
xlab = sys.argv[ind+1]
else:
xlab = 'x'
data = []
if not fname:
print('-I- Trying to read from stdin... <ctrl>-c to quit')
data = np.loadtxt(sys.stdin, dtype=np.float)
ipmag.histplot(fname, data, outfile, xlab, binsize, norm,
fmt, save_plots, interactive)
|
python
|
{
"resource": ""
}
|
q11828
|
Menus.InitUI
|
train
|
def InitUI(self):
"""
Initialize interface for drop down menu
"""
if self.data_type in ['orient', 'ages']:
belongs_to = []
else:
parent_table_name = self.parent_type + "s"
if parent_table_name in self.contribution.tables:
belongs_to = sorted(self.contribution.tables[parent_table_name].df.index.unique())
else:
belongs_to = []
self.choices = {}
if self.data_type in ['specimens', 'samples', 'sites']:
self.choices = {1: (belongs_to, False)}
if self.data_type == 'orient':
self.choices = {1: (['g', 'b'], False)}
if self.data_type == 'ages':
for level in ['specimen', 'sample', 'site', 'location']:
if level in self.grid.col_labels:
level_names = []
if level + "s" in self.contribution.tables:
level_names = list(self.contribution.tables[level+"s"].df.index.unique())
num = self.grid.col_labels.index(level)
self.choices[num] = (level_names, False)
# Bind left click to drop-down menu popping out
self.grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK,
lambda event: self.on_left_click(event, self.grid, self.choices))
cols = self.grid.GetNumberCols()
col_labels = [self.grid.GetColLabelValue(col) for col in range(cols)]
# check if any additional columns have controlled vocabularies
# if so, get the vocabulary list
for col_number, label in enumerate(col_labels):
self.add_drop_down(col_number, label)
|
python
|
{
"resource": ""
}
|
q11829
|
Menus.add_drop_down
|
train
|
def add_drop_down(self, col_number, col_label):
"""
Add a correctly formatted drop-down-menu for given col_label,
if required or suggested.
Otherwise do nothing.
Parameters
----------
col_number : int
grid position at which to add a drop down menu
col_label : str
column name
"""
if col_label.endswith('**') or col_label.endswith('^^'):
col_label = col_label[:-2]
# add drop-down for experiments
if col_label == "experiments":
if 'measurements' in self.contribution.tables:
meas_table = self.contribution.tables['measurements'].df
if 'experiment' in meas_table.columns:
exps = meas_table['experiment'].unique()
self.choices[col_number] = (sorted(exps), False)
self.grid.SetColLabelValue(col_number, col_label + "**")
return
#
if col_label == 'method_codes':
self.add_method_drop_down(col_number, col_label)
elif col_label == 'magic_method_codes':
self.add_method_drop_down(col_number, 'method_codes')
elif col_label in ['specimens', 'samples', 'sites', 'locations']:
if col_label in self.contribution.tables:
item_df = self.contribution.tables[col_label].df
item_names = item_df.index.unique() #[col_label[:-1]].unique()
self.choices[col_number] = (sorted(item_names), False)
elif col_label in ['specimen', 'sample', 'site', 'location']:
if col_label + "s" in self.contribution.tables:
item_df = self.contribution.tables[col_label + "s"].df
item_names = item_df.index.unique() #[col_label[:-1]].unique()
self.choices[col_number] = (sorted(item_names), False)
# add vocabularies
if col_label in self.contribution.vocab.suggested:
typ = 'suggested'
elif col_label in self.contribution.vocab.vocabularies:
typ = 'controlled'
else:
return
# add menu, if not already set
if col_number not in list(self.choices.keys()):
if typ == 'suggested':
self.grid.SetColLabelValue(col_number, col_label + "^^")
controlled_vocabulary = self.contribution.vocab.suggested[col_label]
else:
self.grid.SetColLabelValue(col_number, col_label + "**")
controlled_vocabulary = self.contribution.vocab.vocabularies[col_label]
#
stripped_list = []
for item in controlled_vocabulary:
try:
stripped_list.append(str(item))
except UnicodeEncodeError:
# skips items with non ASCII characters
pass
if len(stripped_list) > 100:
# split out the list alphabetically, into a dict of lists {'A': ['alpha', 'artist'], 'B': ['beta', 'beggar']...}
dictionary = {}
for item in stripped_list:
letter = item[0].upper()
if letter not in list(dictionary.keys()):
dictionary[letter] = []
dictionary[letter].append(item)
stripped_list = dictionary
two_tiered = True if isinstance(stripped_list, dict) else False
self.choices[col_number] = (stripped_list, two_tiered)
return
|
python
|
{
"resource": ""
}
|
q11830
|
main
|
train
|
def main():
"""
NAME
di_tilt.py
DESCRIPTION
rotates geographic coordinate dec, inc data to stratigraphic
coordinates using the dip and dip direction (strike+90, dip if dip to right of strike)
INPUT FORMAT
declination inclination dip_direction dip
SYNTAX
di_tilt.py [-h][-i][-f FILE] [< filename ]
OPTIONS
-h prints help message and quits
-i for interactive data entry
-f FILE command line entry of file name
-F OFILE, specify output file, default is standard output
OUTPUT:
declination inclination
"""
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')
print(ofile, ' opened for output')
else: ofile=""
if '-i' in sys.argv: # interactive flag
while 1:
try:
Dec=float(input("Declination: <cntl-D> to quit "))
except:
print("\n Good-bye\n")
sys.exit()
Inc=float(input("Inclination: "))
Dip_dir=float(input("Dip direction: "))
Dip=float(input("Dip: "))
print('%7.1f %7.1f'%(pmag.dotilt(Dec,Inc,Dip_dir,Dip)))
elif '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
data=numpy.loadtxt(file)
else:
data=numpy.loadtxt(sys.stdin,dtype=numpy.float) # read in the data from the datafile
D,I=pmag.dotilt_V(data)
for k in range(len(D)):
if ofile=="":
print('%7.1f %7.1f'%(D[k],I[k]))
else:
out.write('%7.1f %7.1f\n'%(D[k],I[k]))
|
python
|
{
"resource": ""
}
|
q11831
|
main
|
train
|
def main():
"""
NAME
convert2unix.py
DESCRIPTION
converts mac or dos formatted file to unix file in place
SYNTAX
convert2unix.py FILE
OPTIONS
-h prints help and quits
"""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
file=sys.argv[1]
f=open(file,'r')
Input=f.readlines()
f.close()
out=open(file,'w')
for line in Input:
out.write(line)
out.close()
|
python
|
{
"resource": ""
}
|
q11832
|
main
|
train
|
def main():
"""
NAME
gokent.py
DESCRIPTION
calculates Kent parameters from dec inc data
INPUT FORMAT
takes dec/inc as first two columns in space delimited file
SYNTAX
gokent.py [options]
OPTIONS
-h prints help message and quits
-i for interactive filename entry
-f FILE, specify filename
-F FILE, specifies output file name
< filename for reading from standard input
OUTPUT
mean dec, mean inc, Eta, Deta, Ieta, Zeta, Zdec, Zinc, N
"""
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:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
f=open(file,'r')
data=f.readlines()
elif '-i' in sys.argv: # ask for filename
file=input("Enter file name with dec, inc data: ")
f=open(file,'r')
data=f.readlines()
else:
#
data=sys.stdin.readlines() # read in data from standard input
ofile = ""
if '-F' in sys.argv:
ind = sys.argv.index('-F')
ofile= sys.argv[ind+1]
out = open(ofile, 'w + a')
DIs= [] # set up list for dec inc data
for line in data: # read in the data from standard input
if '\t' in line:
rec=line.split('\t') # split each line on space to get records
else:
rec=line.split() # split each line on space to get records
DIs.append((float(rec[0]),float(rec[1])))
#
kpars=pmag.dokent(DIs,len(DIs))
output = '%7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %i' % (kpars["dec"],kpars["inc"],kpars["Eta"],kpars["Edec"],kpars["Einc"],kpars["Zeta"],kpars["Zdec"],kpars["Zinc"],kpars["n"])
if ofile == "":
print(output)
else:
out.write(output+'\n')
|
python
|
{
"resource": ""
}
|
q11833
|
plot3d_init
|
train
|
def plot3d_init(fignum):
"""
initializes 3D plot
"""
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(fignum)
ax = fig.add_subplot(111, projection='3d')
return ax
|
python
|
{
"resource": ""
}
|
q11834
|
plot_xy
|
train
|
def plot_xy(fignum, X, Y, **kwargs):
"""
deprecated, used in curie
"""
plt.figure(num=fignum)
# if 'poly' in kwargs.keys():
# coeffs=np.polyfit(X,Y,kwargs['poly'])
# polynomial=np.poly1d(coeffs)
# xs=np.arange(np.min(X),np.max(X))
# ys=polynomial(xs)
# plt.plot(xs,ys)
# print coefs
# print polynomial
if 'sym' in list(kwargs.keys()):
sym = kwargs['sym']
else:
sym = 'ro'
if 'lw' in list(kwargs.keys()):
lw = kwargs['lw']
else:
lw = 1
if 'xerr' in list(kwargs.keys()):
plt.errorbar(X, Y, fmt=sym, xerr=kwargs['xerr'])
if 'yerr' in list(kwargs.keys()):
plt.errorbar(X, Y, fmt=sym, yerr=kwargs['yerr'])
if 'axis' in list(kwargs.keys()):
if kwargs['axis'] == 'semilogx':
plt.semilogx(X, Y, marker=sym[1], markerfacecolor=sym[0])
if kwargs['axis'] == 'semilogy':
plt.semilogy(X, Y, marker=sym[1], markerfacecolor=sym[0])
if kwargs['axis'] == 'loglog':
plt.loglog(X, Y, marker=sym[1], markerfacecolor=sym[0])
else:
plt.plot(X, Y, sym, linewidth=lw)
if 'xlab' in list(kwargs.keys()):
plt.xlabel(kwargs['xlab'])
if 'ylab' in list(kwargs.keys()):
plt.ylabel(kwargs['ylab'])
if 'title' in list(kwargs.keys()):
plt.title(kwargs['title'])
if 'xmin' in list(kwargs.keys()):
plt.axis([kwargs['xmin'], kwargs['xmax'],
kwargs['ymin'], kwargs['ymax']])
if 'notes' in list(kwargs.keys()):
for note in kwargs['notes']:
plt.text(note[0], note[1], note[2])
|
python
|
{
"resource": ""
}
|
q11835
|
plot_qq_exp
|
train
|
def plot_qq_exp(fignum, I, title, subplot=False):
"""
plots data against an exponential distribution in 0=>90.
Parameters
_________
fignum : matplotlib figure number
I : data
title : plot title
subplot : boolean, if True plot as subplot with 1 row, two columns with fignum the plot number
"""
if subplot == True:
plt.subplot(1, 2, fignum)
else:
plt.figure(num=fignum)
X, Y, dpos, dneg = [], [], 0., 0.
rad = old_div(np.pi, 180.)
xsum = 0
for i in I:
theta = (90. - i) * rad
X.append(1. - np.cos(theta))
xsum += X[-1]
X.sort()
n = float(len(X))
kappa = old_div((n - 1.), xsum)
for i in range(len(X)):
p = old_div((float(i) - 0.5), n)
Y.append(-np.log(1. - p))
f = 1. - np.exp(-kappa * X[i])
ds = old_div(float(i), n) - f
if dpos < ds:
dpos = ds
ds = f - old_div((float(i) - 1.), n)
if dneg < ds:
dneg = ds
if dneg > dpos:
ds = dneg
else:
ds = dpos
Me = (ds - (old_div(0.2, n))) * (np.sqrt(n) + 0.26 +
(old_div(0.5, (np.sqrt(n))))) # Eq. 5.15 from Fisher et al. (1987)
plt.plot(Y, X, 'ro')
bounds = plt.axis()
plt.axis([0, bounds[1], 0., bounds[3]])
notestr = 'N: ' + '%i' % (n)
plt.text(.1 * bounds[1], .9 * bounds[3], notestr)
notestr = 'Me: ' + '%7.3f' % (Me)
plt.text(.1 * bounds[1], .8 * bounds[3], notestr)
if Me > 1.094:
notestr = "Not Exponential"
else:
notestr = "Exponential (95%)"
plt.text(.1 * bounds[1], .7 * bounds[3], notestr)
plt.title(title)
plt.xlabel('Exponential Quantile')
plt.ylabel('Data Quantile')
return Me, 1.094
|
python
|
{
"resource": ""
}
|
q11836
|
plot_zed
|
train
|
def plot_zed(ZED, datablock, angle, s, units):
"""
function to make equal area plot and zijderveld plot
Parameters
_________
ZED : dictionary with keys for plots
eqarea : figure number for equal area projection
zijd : figure number for zijderveld plot
demag : figure number for magnetization against demag step
datablock : nested list of [step, dec, inc, M (Am2), quality]
step : units assumed in SI
M : units assumed Am2
quality : [g,b], good or bad measurement; if bad will be marked as such
angle : angle for X axis in horizontal plane, if 0, x will be 0 declination
s : specimen name
units : SI units ['K','T','U'] for kelvin, tesla or undefined
Effects
_______
calls plotting functions for equal area, zijderveld and demag figures
"""
for fignum in list(ZED.keys()):
fig = plt.figure(num=ZED[fignum])
plt.clf()
if not isServer:
plt.figtext(.02, .01, version_num)
DIbad, DIgood = [], []
for rec in datablock:
if cb.is_null(rec[1],zero_as_null=False):
print('-W- You are missing a declination for specimen', s, ', skipping this row')
continue
if cb.is_null(rec[2],zero_as_null=False):
print('-W- You are missing an inclination for specimen', s, ', skipping this row')
continue
if rec[5] == 'b':
DIbad.append((rec[1], rec[2]))
else:
DIgood.append((rec[1], rec[2]))
badsym = {'lower': ['+', 'g'], 'upper': ['x', 'c']}
if len(DIgood) > 0:
plot_eq(ZED['eqarea'], DIgood, s)
if len(DIbad) > 0:
plot_di_sym(ZED['eqarea'], DIbad, badsym)
elif len(DIbad) > 0:
plot_eq_sym(ZED['eqarea'], DIbad, s, badsym)
AngleX, AngleY = [], []
XY = pmag.dimap(angle, 90.)
AngleX.append(XY[0])
AngleY.append(XY[1])
XY = pmag.dimap(angle, 0.)
AngleX.append(XY[0])
AngleY.append(XY[1])
plt.figure(num=ZED['eqarea'])
# Draw a line for Zijderveld horizontal axis
plt.plot(AngleX, AngleY, 'r-')
if AngleX[-1] == 0:
AngleX[-1] = 0.01
plt.text(AngleX[-1] + (old_div(AngleX[-1], abs(AngleX[-1]))) * .1,
AngleY[-1] + (old_div(AngleY[-1], abs(AngleY[-1]))) * .1, 'X')
norm = 1
#if units=="U": norm=0
# if there are NO good points, don't try to plot
if DIgood:
plot_mag(ZED['demag'], datablock, s, 1, units, norm)
plot_zij(ZED['zijd'], datablock, angle, s, norm)
else:
ZED.pop('demag')
ZED.pop('zijd')
return ZED
|
python
|
{
"resource": ""
}
|
q11837
|
plot_arai_zij
|
train
|
def plot_arai_zij(ZED, araiblock, zijdblock, s, units):
"""
calls the four plotting programs for Thellier-Thellier experiments
Parameters
__________
ZED : dictionary with plotting figure keys:
deremag : figure for de (re) magnezation plots
arai : figure for the Arai diagram
eqarea : equal area projection of data, color coded by
red circles: ZI steps
blue squares: IZ steps
yellow triangles : pTRM steps
zijd : Zijderveld diagram color coded by ZI, IZ steps
deremag : demagnetization and remagnetization versus temperature
araiblock : nested list of required data from Arai plots
zijdblock : nested list of required data for Zijderveld plots
s : specimen name
units : units for the arai and zijderveld plots
Effects
________
Makes four plots from the data by calling
plot_arai : Arai plots
plot_teq : equal area projection for Thellier data
plotZ : Zijderveld diagram
plot_np : de (re) magnetization diagram
"""
angle = zijdblock[0][1]
norm = 1
if units == "U":
norm = 0
plot_arai(ZED['arai'], araiblock, s, units)
plot_teq(ZED['eqarea'], araiblock, s, "")
plot_zij(ZED['zijd'], zijdblock, angle, s, norm)
plot_np(ZED['deremag'], araiblock, s, units)
return ZED
|
python
|
{
"resource": ""
}
|
q11838
|
plot_lnp
|
train
|
def plot_lnp(fignum, s, datablock, fpars, direction_type_key):
"""
plots lines and planes on a great circle with alpha 95 and mean
Parameters
_________
fignum : number of plt.figure() object
datablock : nested list of dictionaries with keys in 3.0 or 2.5 format
3.0 keys: dir_dec, dir_inc, dir_tilt_correction = [-1,0,100], direction_type_key =['p','l']
2.5 keys: dec, inc, tilt_correction = [-1,0,100],direction_type_key =['p','l']
fpars : Fisher parameters calculated by, e.g., pmag.dolnp() or pmag.dolnp3_0()
direction_type_key : key for dictionary direction_type ('specimen_direction_type')
Effects
_______
plots the site level figure
"""
# make the stereonet
plot_net(fignum)
#
# plot on the data
#
dec_key, inc_key, tilt_key = 'dec', 'inc', 'tilt_correction'
if 'dir_dec' in datablock[0].keys(): # this is data model 3.0
dec_key, inc_key, tilt_key = 'dir_dec', 'dir_inc', 'dir_tilt_correction'
coord = datablock[0][tilt_key]
title = s
if coord == '-1':
title = title + ": specimen coordinates"
if coord == '0':
title = title + ": geographic coordinates"
if coord == '100':
title = title + ": tilt corrected coordinates"
DIblock, GCblock = [], []
for plotrec in datablock:
if plotrec[direction_type_key] == 'p': # direction is pole to plane
GCblock.append((float(plotrec[dec_key]), float(plotrec[inc_key])))
else: # assume direction is a directed line
DIblock.append((float(plotrec[dec_key]), float(plotrec[inc_key])))
if len(DIblock) > 0:
plot_di(fignum, DIblock) # plot directed lines
if len(GCblock) > 0:
for pole in GCblock:
plot_circ(fignum, pole, 90., 'g') # plot directed lines
#
# put on the mean direction
#
x, y = [], []
XY = pmag.dimap(float(fpars["dec"]), float(fpars["inc"]))
x.append(XY[0])
y.append(XY[1])
plt.figure(num=fignum)
plt.scatter(x, y, marker='d', s=80, c='g')
plt.title(title)
#
# get the alpha95
#
Xcirc, Ycirc = [], []
Da95, Ia95 = pmag.circ(float(fpars["dec"]), float(
fpars["inc"]), float(fpars["alpha95"]))
for k in range(len(Da95)):
XY = pmag.dimap(Da95[k], Ia95[k])
Xcirc.append(XY[0])
Ycirc.append(XY[1])
plt.plot(Xcirc, Ycirc, 'g')
|
python
|
{
"resource": ""
}
|
q11839
|
plot_teq
|
train
|
def plot_teq(fignum, araiblock, s, pars):
"""
plots directions of pTRM steps and zero field steps
Parameters
__________
fignum : figure number for matplotlib object
araiblock : nested list of data from pmag.sortarai()
s : specimen name
pars : default is "",
otherwise is dictionary with keys:
'measurement_step_min' and 'measurement_step_max'
Effects
_______
makes the equal area projection with color coded symbols
red circles: ZI steps
blue squares: IZ steps
yellow : pTRM steps
"""
first_Z, first_I = araiblock[0], araiblock[1]
# make the stereonet
plt.figure(num=fignum)
plt.clf()
ZIblock, IZblock, pTblock = [], [], []
for zrec in first_Z: # sort out the zerofield steps
if zrec[4] == 1: # this is a ZI step
ZIblock.append([zrec[1], zrec[2]])
else:
IZblock.append([zrec[1], zrec[2]])
plot_net(fignum)
if pars != "":
min, max = float(pars["measurement_step_min"]), float(
pars["measurement_step_max"])
else:
min, max = first_I[0][0], first_I[-1][0]
for irec in first_I:
if irec[1] != 0 and irec[1] != 0 and irec[0] >= min and irec[0] <= max:
pTblock.append([irec[1], irec[2]])
if len(ZIblock) < 1 and len(IZblock) < 1 and len(pTblock) < 1:
return
if not isServer:
plt.figtext(.02, .01, version_num)
#
# put on the directions
#
sym = {'lower': ['o', 'r'], 'upper': ['o', 'm']}
if len(ZIblock) > 0:
plot_di_sym(fignum, ZIblock, sym) # plot ZI directions
sym = {'lower': ['s', 'b'], 'upper': ['s', 'c']}
if len(IZblock) > 0:
plot_di_sym(fignum, IZblock, sym) # plot IZ directions
sym = {'lower': ['^', 'g'], 'upper': ['^', 'y']}
if len(pTblock) > 0:
plot_di_sym(fignum, pTblock, sym) # plot pTRM directions
plt.axis("equal")
plt.text(-1.1, 1.15, s)
|
python
|
{
"resource": ""
}
|
q11840
|
plot_evec
|
train
|
def plot_evec(fignum, Vs, symsize, title):
"""
plots eigenvector directions of S vectors
Paramters
________
fignum : matplotlib figure number
Vs : nested list of eigenvectors
symsize : size in pts for symbol
title : title for plot
"""
#
plt.figure(num=fignum)
plt.text(-1.1, 1.15, title)
# plot V1s as squares, V2s as triangles and V3s as circles
symb, symkey = ['s', 'v', 'o'], 0
col = ['r', 'b', 'k'] # plot V1s rec, V2s blue, V3s black
for VEC in range(3):
X, Y = [], []
for Vdirs in Vs:
#
#
# plot the V1 data first
#
XY = pmag.dimap(Vdirs[VEC][0], Vdirs[VEC][1])
X.append(XY[0])
Y.append(XY[1])
plt.scatter(X, Y, s=symsize,
marker=symb[VEC], c=col[VEC], edgecolors='none')
plt.axis("equal")
|
python
|
{
"resource": ""
}
|
q11841
|
plot_hs
|
train
|
def plot_hs(fignum, Ys, c, ls):
"""
plots horizontal lines at Ys values
Parameters
_________
fignum : matplotlib figure number
Ys : list of Y values for lines
c : color for lines
ls : linestyle for lines
"""
fig = plt.figure(num=fignum)
for yv in Ys:
bounds = plt.axis()
plt.axhline(y=yv, xmin=0, xmax=1, linewidth=1, color=c, linestyle=ls)
|
python
|
{
"resource": ""
}
|
q11842
|
plot_vs
|
train
|
def plot_vs(fignum, Xs, c, ls):
"""
plots vertical lines at Xs values
Parameters
_________
fignum : matplotlib figure number
Xs : list of X values for lines
c : color for lines
ls : linestyle for lines
"""
fig = plt.figure(num=fignum)
for xv in Xs:
bounds = plt.axis()
plt.axvline(
x=xv, ymin=bounds[2], ymax=bounds[3], linewidth=1, color=c, linestyle=ls)
|
python
|
{
"resource": ""
}
|
q11843
|
plot_ts
|
train
|
def plot_ts(fignum, dates, ts):
"""
plot the geomagnetic polarity time scale
Parameters
__________
fignum : matplotlib figure number
dates : bounding dates for plot
ts : time scale ck95, gts04, or gts12
"""
vertical_plot_init(fignum, 10, 3)
TS, Chrons = pmag.get_ts(ts)
p = 1
X, Y = [], []
for d in TS:
if d <= dates[1]:
if d >= dates[0]:
if len(X) == 0:
ind = TS.index(d)
X.append(TS[ind - 1])
Y.append(p % 2)
X.append(d)
Y.append(p % 2)
p += 1
X.append(d)
Y.append(p % 2)
else:
X.append(dates[1])
Y.append(p % 2)
plt.plot(X, Y, 'k')
plot_vs(fignum, dates, 'w', '-')
plot_hs(fignum, [1.1, -.1], 'w', '-')
plt.xlabel("Age (Ma): " + ts)
isign = -1
for c in Chrons:
off = -.1
isign = -1 * isign
if isign > 0:
off = 1.05
if c[1] >= X[0] and c[1] < X[-1]:
plt.text(c[1] - .2, off, c[0])
return
|
python
|
{
"resource": ""
}
|
q11844
|
plot_delta_m
|
train
|
def plot_delta_m(fignum, B, DM, Bcr, s):
"""
function to plot Delta M curves
Parameters
__________
fignum : matplotlib figure number
B : array of field values
DM : array of difference between top and bottom curves in hysteresis loop
Bcr : coercivity of remanence
s : specimen name
"""
plt.figure(num=fignum)
plt.clf()
if not isServer:
plt.figtext(.02, .01, version_num)
plt.plot(B, DM, 'b')
plt.xlabel('B (T)')
plt.ylabel('Delta M')
linex = [0, Bcr, Bcr]
liney = [old_div(DM[0], 2.), old_div(DM[0], 2.), 0]
plt.plot(linex, liney, 'r')
plt.title(s)
|
python
|
{
"resource": ""
}
|
q11845
|
plot_day
|
train
|
def plot_day(fignum, BcrBc, S, sym, **kwargs):
"""
function to plot Day plots
Parameters
_________
fignum : matplotlib figure number
BcrBc : list or array ratio of coercivity of remenance to coercivity
S : list or array ratio of saturation remanence to saturation magnetization (squareness)
sym : matplotlib symbol (e.g., 'rs' for red squares)
**kwargs : dictionary with {'names':[list of names for symbols]}
"""
plt.figure(num=fignum)
plt.plot(BcrBc, S, sym)
plt.axhline(0, color='k')
plt.axhline(.05, color='k')
plt.axhline(.5, color='k')
plt.axvline(1, color='k')
plt.axvline(4, color='k')
plt.xlabel('Bcr/Bc')
plt.ylabel('Mr/Ms')
plt.title('Day Plot')
plt.xlim(0, 6)
#bounds= plt.axis()
#plt.axis([0, bounds[1],0, 1])
mu_o = 4. * np.pi * 1e-7
Bc_sd = 46e-3 # (MV1H) dunlop and carter-stiglitz 2006 (in T)
Bc_md = 5.56e-3 # (041183) dunlop and carter-stiglitz 2006 (in T)
chi_sd = 5.20e6 * mu_o # now in T
chi_md = 4.14e6 * mu_o # now in T
chi_r_sd = 4.55e6 * mu_o # now in T
chi_r_md = 0.88e6 * mu_o # now in T
Bcr_sd, Bcr_md = 52.5e-3, 26.1e-3 # (MV1H and 041183 in DC06 in tesla)
Ms = 480e3 # A/m
p = .1 # from Dunlop 2002
N = old_div(1., 3.) # demagnetizing factor
f_sd = np.arange(1., 0., -.01) # fraction of sd
f_md = 1. - f_sd # fraction of md
f_sp = 1. - f_sd # fraction of sp
# Mr/Ms ratios for USD,MD and Jax shaped
sdrat, mdrat, cbrat = 0.498, 0.048, 0.6
Mrat = f_sd * sdrat + f_md * mdrat # linear mixing - eq. 9 in Dunlop 2002
Bc = old_div((f_sd * chi_sd * Bc_sd + f_md * chi_md * Bc_md),
(f_sd * chi_sd + f_md * chi_md)) # eq. 10 in Dunlop 2002
Bcr = old_div((f_sd * chi_r_sd * Bcr_sd + f_md * chi_r_md * Bcr_md),
(f_sd * chi_r_sd + f_md * chi_r_md)) # eq. 11 in Dunlop 2002
chi_sps = np.arange(1, 5) * chi_sd
plt.plot(old_div(Bcr, Bc), Mrat, 'r-')
if 'names' in list(kwargs.keys()):
names = kwargs['names']
for k in range(len(names)):
plt.text(BcrBc[k], S[k], names[k])
|
python
|
{
"resource": ""
}
|
q11846
|
plot_s_bc
|
train
|
def plot_s_bc(fignum, Bc, S, sym):
"""
function to plot Squareness,Coercivity
Parameters
__________
fignum : matplotlib figure number
Bc : list or array coercivity values
S : list or array of ratio of saturation remanence to saturation
sym : matplotlib symbol (e.g., 'g^' for green triangles)
"""
plt.figure(num=fignum)
plt.plot(Bc, S, sym)
plt.xlabel('Bc')
plt.ylabel('Mr/Ms')
plt.title('Squareness-Coercivity Plot')
bounds = plt.axis()
plt.axis([0, bounds[1], 0, 1])
|
python
|
{
"resource": ""
}
|
q11847
|
plot_s_bcr
|
train
|
def plot_s_bcr(fignum, Bcr, S, sym):
"""
function to plot Squareness,Coercivity of remanence
Parameters
__________
fignum : matplotlib figure number
Bcr : list or array coercivity of remenence values
S : list or array of ratio of saturation remanence to saturation
sym : matplotlib symbol (e.g., 'g^' for green triangles)
"""
plt.figure(num=fignum)
plt.plot(Bcr, S, sym)
plt.xlabel('Bcr')
plt.ylabel('Mr/Ms')
plt.title('Squareness-Bcr Plot')
bounds = plt.axis()
plt.axis([0, bounds[1], 0, 1])
|
python
|
{
"resource": ""
}
|
q11848
|
plot_bcr
|
train
|
def plot_bcr(fignum, Bcr1, Bcr2):
"""
function to plot two estimates of Bcr against each other
"""
plt.figure(num=fignum)
plt.plot(Bcr1, Bcr2, 'ro')
plt.xlabel('Bcr1')
plt.ylabel('Bcr2')
plt.title('Compare coercivity of remanence')
|
python
|
{
"resource": ""
}
|
q11849
|
plot_irm
|
train
|
def plot_irm(fignum, B, M, title):
"""
function to plot IRM backfield curves
Parameters
_________
fignum : matplotlib figure number
B : list or array of field values
M : list or array of magnetizations
title : string title for plot
"""
rpars = {}
Mnorm = []
backfield = 0
X, Y = [], []
for k in range(len(B)):
if M[k] < 0:
break
if k <= 5:
kmin = 0
else:
kmin = k - 5
for k in range(kmin, k + 1):
X.append(B[k])
if B[k] < 0:
backfield = 1
Y.append(M[k])
if backfield == 1:
poly = np.polyfit(X, Y, 1)
if poly[0] != 0:
bcr = (old_div(-poly[1], poly[0]))
else:
bcr = 0
rpars['remanence_mr_moment'] = '%8.3e' % (M[0])
rpars['remanence_bcr'] = '%8.3e' % (-bcr)
rpars['magic_method_codes'] = 'LP-BCR-BF'
if M[0] != 0:
for m in M:
Mnorm.append(old_div(m, M[0])) # normalize to unity Msat
title = title + ':' + '%8.3e' % (M[0])
else:
if M[-1] != 0:
for m in M:
Mnorm.append(old_div(m, M[-1])) # normalize to unity Msat
title = title + ':' + '%8.3e' % (M[-1])
# do plots if desired
if fignum != 0 and M[0] != 0: # skip plot for fignum = 0
plt.figure(num=fignum)
plt.clf()
if not isServer:
plt.figtext(.02, .01, version_num)
plt.plot(B, Mnorm)
plt.axhline(0, color='k')
plt.axvline(0, color='k')
plt.xlabel('B (T)')
plt.ylabel('M/Mr')
plt.title(title)
if backfield == 1:
plt.scatter([bcr], [0], marker='s', c='b')
bounds = plt.axis()
n1 = 'Bcr: ' + '%8.2e' % (-bcr) + ' T'
plt.figtext(.2, .5, n1)
n2 = 'Mr: ' + '%8.2e' % (M[0]) + ' Am^2'
plt.figtext(.2, .45, n2)
elif fignum != 0:
plt.figure(num=fignum)
# plt.clf()
if not isServer:
plt.figtext(.02, .01, version_num)
print('M[0]=0, skipping specimen')
return rpars
|
python
|
{
"resource": ""
}
|
q11850
|
plot_xtb
|
train
|
def plot_xtb(fignum, XTB, Bs, e, f):
""" function to plot series of chi measurements as a function of temperature, holding frequency constant and varying B
"""
plt.figure(num=fignum)
plt.xlabel('Temperature (K)')
plt.ylabel('Susceptibility (m^3/kg)')
k = 0
Blab = []
for field in XTB:
T, X = [], []
for xt in field:
X.append(xt[0])
T.append(xt[1])
plt.plot(T, X)
plt.text(T[-1], X[-1], '%8.2e' % (Bs[k]) + ' T')
# Blab.append('%8.1e'%(Bs[k])+' T')
k += 1
plt.title(e + ': f = ' + '%i' % (int(f)) + ' Hz')
|
python
|
{
"resource": ""
}
|
q11851
|
plot_ltc
|
train
|
def plot_ltc(LTC_CM, LTC_CT, LTC_WM, LTC_WT, e):
"""
function to plot low temperature cycling experiments
"""
leglist, init = [], 0
if len(LTC_CM) > 2:
if init == 0:
plot_init(1, 5, 5)
plt.plot(LTC_CT, LTC_CM, 'b')
leglist.append('RT SIRM, measured while cooling')
init = 1
if len(LTC_WM) > 2:
if init == 0:
plot_init(1, 5, 5)
plt.plot(LTC_WT, LTC_WM, 'r')
leglist.append('RT SIRM, measured while warming')
if init != 0:
plt.legend(leglist, 'lower left')
plt.xlabel('Temperature (K)')
plt.ylabel('Magnetization (Am^2/kg)')
if len(LTC_CM) > 2:
plt.plot(LTC_CT, LTC_CM, 'bo')
if len(LTC_WM) > 2:
plt.plot(LTC_WT, LTC_WM, 'ro')
plt.title(e)
|
python
|
{
"resource": ""
}
|
q11852
|
plot_conf
|
train
|
def plot_conf(fignum, s, datablock, pars, new):
"""
plots directions and confidence ellipses
"""
# make the stereonet
if new == 1:
plot_net(fignum)
#
# plot the data
#
DIblock = []
for plotrec in datablock:
DIblock.append((float(plotrec["dec"]), float(plotrec["inc"])))
if len(DIblock) > 0:
plot_di(fignum, DIblock) # plot directed lines
#
# put on the mean direction
#
x, y = [], []
XY = pmag.dimap(float(pars[0]), float(pars[1]))
x.append(XY[0])
y.append(XY[1])
plt.figure(num=fignum)
if new == 1:
plt.scatter(x, y, marker='d', s=80, c='r')
else:
if float(pars[1] > 0):
plt.scatter(x, y, marker='^', s=100, c='r')
else:
plt.scatter(x, y, marker='^', s=100, c='y')
plt.title(s)
#
# plot the ellipse
#
plot_ell(fignum, pars, 'r-,', 0, 1)
|
python
|
{
"resource": ""
}
|
q11853
|
plot_ts
|
train
|
def plot_ts(ax, agemin, agemax, timescale='gts12', ylabel="Age (Ma)"):
"""
Make a time scale plot between specified ages.
Parameters:
------------
ax : figure object
agemin : Minimum age for timescale
agemax : Maximum age for timescale
timescale : Time Scale [ default is Gradstein et al., (2012)]
for other options see pmag.get_ts()
ylabel : if set, plot as ylabel
"""
ax.set_title(timescale.upper())
ax.axis([-.25, 1.5, agemax, agemin])
ax.axes.get_xaxis().set_visible(False)
# get dates and chron names for timescale
TS, Chrons = pmag.get_ts(timescale)
X, Y, Y2 = [0, 1], [], []
cnt = 0
if agemin < TS[1]: # in the Brunhes
Y = [agemin, agemin] # minimum age
Y1 = [TS[1], TS[1]] # age of the B/M boundary
ax.fill_between(X, Y, Y1, facecolor='black') # color in Brunhes, black
for d in TS[1:]:
pol = cnt % 2
cnt += 1
if d <= agemax and d >= agemin:
ind = TS.index(d)
Y = [TS[ind], TS[ind]]
Y1 = [TS[ind+1], TS[ind+1]]
if pol:
# fill in every other time
ax.fill_between(X, Y, Y1, facecolor='black')
ax.plot([0, 1, 1, 0, 0], [agemin, agemin, agemax, agemax, agemin], 'k-')
plt.yticks(np.arange(agemin, agemax+1, 1))
if ylabel != "":
ax.set_ylabel(ylabel)
ax2 = ax.twinx()
ax2.axis('off')
for k in range(len(Chrons)-1):
c = Chrons[k]
cnext = Chrons[k+1]
d = cnext[1]-(cnext[1]-c[1])/3.
if d >= agemin and d < agemax:
# make the Chron boundary tick
ax2.plot([1, 1.5], [c[1], c[1]], 'k-')
ax2.text(1.05, d, c[0])
ax2.axis([-.25, 1.5, agemax, agemin])
|
python
|
{
"resource": ""
}
|
q11854
|
InterpretationEditorFrame.update_editor
|
train
|
def update_editor(self):
"""
updates the logger and plot on the interpretation editor window
"""
self.fit_list = []
self.search_choices = []
for specimen in self.specimens_list:
if specimen not in self.parent.pmag_results_data['specimens']: continue
self.fit_list += [(fit,specimen) for fit in self.parent.pmag_results_data['specimens'][specimen]]
self.logger.DeleteAllItems()
offset = 0
for i in range(len(self.fit_list)):
i -= offset
v = self.update_logger_entry(i)
if v == "s": offset += 1
|
python
|
{
"resource": ""
}
|
q11855
|
InterpretationEditorFrame.logger_focus
|
train
|
def logger_focus(self,i,focus_shift=16):
"""
focuses the logger on an index 12 entries below i
@param: i -> index to focus on
"""
if self.logger.GetItemCount()-1 > i+focus_shift:
i += focus_shift
else:
i = self.logger.GetItemCount()-1
self.logger.Focus(i)
|
python
|
{
"resource": ""
}
|
q11856
|
InterpretationEditorFrame.OnClick_listctrl
|
train
|
def OnClick_listctrl(self, event):
"""
Edits the logger and the Zeq_GUI parent object to select the fit that was newly selected by a double click
@param: event -> wx.ListCtrlEvent that triggered this function
"""
i = event.GetIndex()
if self.parent.current_fit == self.fit_list[i][0]: return
self.parent.initialize_CART_rot(self.fit_list[i][1])
si = self.parent.specimens.index(self.fit_list[i][1])
self.parent.specimens_box.SetSelection(si)
self.parent.select_specimen(self.fit_list[i][1])
self.change_selected(i)
fi = 0
while (self.parent.s == self.fit_list[i][1] and i >= 0): i,fi = (i-1,fi+1)
self.parent.update_fit_box()
self.parent.fit_box.SetSelection(fi-1)
self.parent.update_selection()
|
python
|
{
"resource": ""
}
|
q11857
|
InterpretationEditorFrame.OnRightClickListctrl
|
train
|
def OnRightClickListctrl(self, event):
"""
Edits the logger and the Zeq_GUI parent object so that the selected interpretation is now marked as bad
@param: event -> wx.ListCtrlEvent that triggered this function
"""
i = event.GetIndex()
fit,spec = self.fit_list[i][0],self.fit_list[i][1]
if fit in self.parent.bad_fits:
if not self.parent.mark_fit_good(fit,spec=spec): return
if i == self.current_fit_index:
self.logger.SetItemBackgroundColour(i,"LIGHT BLUE")
else:
self.logger.SetItemBackgroundColour(i,"WHITE")
else:
if not self.parent.mark_fit_bad(fit): return
if i == self.current_fit_index:
self.logger.SetItemBackgroundColour(i,"red")
else:
self.logger.SetItemBackgroundColour(i,"red")
self.parent.calculate_high_levels_data()
self.parent.plot_high_levels_data()
self.logger_focus(i)
|
python
|
{
"resource": ""
}
|
q11858
|
InterpretationEditorFrame.on_select_show_box
|
train
|
def on_select_show_box(self,event):
"""
Changes the type of mean shown on the high levels mean plot so that single dots represent one of whatever the value of this box is.
@param: event -> the wx.COMBOBOXEVENT that triggered this function
"""
self.parent.UPPER_LEVEL_SHOW=self.show_box.GetValue()
self.parent.calculate_high_levels_data()
self.parent.plot_high_levels_data()
|
python
|
{
"resource": ""
}
|
q11859
|
InterpretationEditorFrame.on_select_high_level
|
train
|
def on_select_high_level(self,event,called_by_parent=False):
"""
alters the possible entries in level_names combobox to give the user selections for which specimen interpretations to display in the logger
@param: event -> the wx.COMBOBOXEVENT that triggered this function
"""
UPPER_LEVEL=self.level_box.GetValue()
if UPPER_LEVEL=='sample':
self.level_names.SetItems(self.parent.samples)
self.level_names.SetStringSelection(self.parent.Data_hierarchy['sample_of_specimen'][self.parent.s])
if UPPER_LEVEL=='site':
self.level_names.SetItems(self.parent.sites)
self.level_names.SetStringSelection(self.parent.Data_hierarchy['site_of_specimen'][self.parent.s])
if UPPER_LEVEL=='location':
self.level_names.SetItems(self.parent.locations)
self.level_names.SetStringSelection(self.parent.Data_hierarchy['location_of_specimen'][self.parent.s])
if UPPER_LEVEL=='study':
self.level_names.SetItems(['this study'])
self.level_names.SetStringSelection('this study')
if not called_by_parent:
self.parent.level_box.SetStringSelection(UPPER_LEVEL)
self.parent.onSelect_high_level(event,True)
self.on_select_level_name(event)
|
python
|
{
"resource": ""
}
|
q11860
|
InterpretationEditorFrame.on_select_level_name
|
train
|
def on_select_level_name(self,event,called_by_parent=False):
"""
change this objects specimens_list to control which specimen interpretatoins are displayed in this objects logger
@param: event -> the wx.ComboBoxEvent that triggered this function
"""
high_level_name=str(self.level_names.GetValue())
if self.level_box.GetValue()=='sample':
self.specimens_list=self.parent.Data_hierarchy['samples'][high_level_name]['specimens']
elif self.level_box.GetValue()=='site':
self.specimens_list=self.parent.Data_hierarchy['sites'][high_level_name]['specimens']
elif self.level_box.GetValue()=='location':
self.specimens_list=self.parent.Data_hierarchy['locations'][high_level_name]['specimens']
elif self.level_box.GetValue()=='study':
self.specimens_list=self.parent.Data_hierarchy['study']['this study']['specimens']
if not called_by_parent:
self.parent.level_names.SetStringSelection(high_level_name)
self.parent.onSelect_level_name(event,True)
self.specimens_list.sort(key=spec_key_func)
self.update_editor()
|
python
|
{
"resource": ""
}
|
q11861
|
InterpretationEditorFrame.on_select_mean_type_box
|
train
|
def on_select_mean_type_box(self, event):
"""
set parent Zeq_GUI to reflect change in this box and change the
@param: event -> the wx.ComboBoxEvent that triggered this function
"""
new_mean_type = self.mean_type_box.GetValue()
if new_mean_type == "None":
self.parent.clear_high_level_pars()
self.parent.mean_type_box.SetStringSelection(new_mean_type)
self.parent.onSelect_mean_type_box(event)
|
python
|
{
"resource": ""
}
|
q11862
|
InterpretationEditorFrame.on_select_mean_fit_box
|
train
|
def on_select_mean_fit_box(self, event):
"""
set parent Zeq_GUI to reflect the change in this box then replot the high level means plot
@param: event -> the wx.COMBOBOXEVENT that triggered this function
"""
new_mean_fit = self.mean_fit_box.GetValue()
self.parent.mean_fit_box.SetStringSelection(new_mean_fit)
self.parent.onSelect_mean_fit_box(event)
|
python
|
{
"resource": ""
}
|
q11863
|
InterpretationEditorFrame.add_highlighted_fits
|
train
|
def add_highlighted_fits(self, evnet):
"""
adds a new interpretation to each specimen highlighted in logger if multiple interpretations are highlighted of the same specimen only one new interpretation is added
@param: event -> the wx.ButtonEvent that triggered this function
"""
specimens = []
next_i = self.logger.GetNextSelected(-1)
if next_i == -1: return
while next_i != -1:
fit,specimen = self.fit_list[next_i]
if specimen in specimens:
next_i = self.logger.GetNextSelected(next_i)
continue
else: specimens.append(specimen)
next_i = self.logger.GetNextSelected(next_i)
for specimen in specimens:
self.add_fit_to_specimen(specimen)
self.update_editor()
self.parent.update_selection()
|
python
|
{
"resource": ""
}
|
q11864
|
InterpretationEditorFrame.delete_highlighted_fits
|
train
|
def delete_highlighted_fits(self, event):
"""
iterates through all highlighted fits in the logger of this object and removes them from the logger and the Zeq_GUI parent object
@param: event -> the wx.ButtonEvent that triggered this function
"""
next_i = -1
deleted_items = []
while True:
next_i = self.logger.GetNextSelected(next_i)
if next_i == -1:
break
deleted_items.append(next_i)
deleted_items.sort(reverse=True)
for item in deleted_items:
self.delete_entry(index=item)
self.parent.update_selection()
|
python
|
{
"resource": ""
}
|
q11865
|
InterpretationEditorFrame.delete_entry
|
train
|
def delete_entry(self, fit = None, index = None):
"""
deletes the single item from the logger of this object that corrisponds to either the passed in fit or index. Note this function mutaits the logger of this object if deleting more than one entry be sure to pass items to delete in from highest index to lowest or else odd things can happen.
@param: fit -> Fit object to delete from this objects logger
@param: index -> integer index of the entry to delete from this objects logger
"""
if type(index) == int and not fit:
fit,specimen = self.fit_list[index]
if fit and type(index) == int:
for i, (f,s) in enumerate(self.fit_list):
if fit == f:
index,specimen = i,s
break
if index == self.current_fit_index: self.current_fit_index = None
if fit not in self.parent.pmag_results_data['specimens'][specimen]:
print(("cannot remove item (entry #: " + str(index) + ") as it doesn't exist, this is a dumb bug contact devs"))
self.logger.DeleteItem(index)
return
self.parent.pmag_results_data['specimens'][specimen].remove(fit)
del self.fit_list[index]
self.logger.DeleteItem(index)
|
python
|
{
"resource": ""
}
|
q11866
|
InterpretationEditorFrame.apply_changes
|
train
|
def apply_changes(self, event):
"""
applies the changes in the various attribute boxes of this object to all highlighted fit objects in the logger, these changes are reflected both in this object and in the Zeq_GUI parent object.
@param: event -> the wx.ButtonEvent that triggered this function
"""
new_name = self.name_box.GetLineText(0)
new_color = self.color_box.GetValue()
new_tmin = self.tmin_box.GetValue()
new_tmax = self.tmax_box.GetValue()
next_i = -1
changed_i = []
while True:
next_i = self.logger.GetNextSelected(next_i)
if next_i == -1:
break
specimen = self.fit_list[next_i][1]
fit = self.fit_list[next_i][0]
if new_name:
if new_name not in [x.name for x in self.parent.pmag_results_data['specimens'][specimen]]: fit.name = new_name
if new_color:
fit.color = self.color_dict[new_color]
#testing
not_both = True
if new_tmin and new_tmax:
if fit == self.parent.current_fit:
self.parent.tmin_box.SetStringSelection(new_tmin)
self.parent.tmax_box.SetStringSelection(new_tmax)
fit.put(specimen,self.parent.COORDINATE_SYSTEM, self.parent.get_PCA_parameters(specimen,fit,new_tmin,new_tmax,self.parent.COORDINATE_SYSTEM,fit.PCA_type))
not_both = False
if new_tmin and not_both:
if fit == self.parent.current_fit:
self.parent.tmin_box.SetStringSelection(new_tmin)
fit.put(specimen,self.parent.COORDINATE_SYSTEM, self.parent.get_PCA_parameters(specimen,fit,new_tmin,fit.tmax,self.parent.COORDINATE_SYSTEM,fit.PCA_type))
if new_tmax and not_both:
if fit == self.parent.current_fit:
self.parent.tmax_box.SetStringSelection(new_tmax)
fit.put(specimen,self.parent.COORDINATE_SYSTEM, self.parent.get_PCA_parameters(specimen,fit,fit.tmin,new_tmax,self.parent.COORDINATE_SYSTEM,fit.PCA_type))
changed_i.append(next_i)
offset = 0
for i in changed_i:
i -= offset
v = self.update_logger_entry(i)
if v == "s":
offset += 1
self.parent.update_selection()
|
python
|
{
"resource": ""
}
|
q11867
|
InterpretationEditorFrame.pan_zoom_high_equalarea
|
train
|
def pan_zoom_high_equalarea(self,event):
"""
Uses the toolbar for the canvas to change the function from zoom to pan or pan to zoom
@param: event -> the wx.MouseEvent that triggered this funciton
"""
if event.LeftIsDown() or event.ButtonDClick():
return
elif self.high_EA_setting == "Zoom":
self.high_EA_setting = "Pan"
try: self.toolbar.pan('off')
except TypeError: pass
elif self.high_EA_setting == "Pan":
self.high_EA_setting = "Zoom"
try: self.toolbar.zoom()
except TypeError: pass
else:
self.high_EA_setting = "Zoom"
try: self.toolbar.zoom()
except TypeError: pass
|
python
|
{
"resource": ""
}
|
q11868
|
main
|
train
|
def main():
"""
NAME
tk03.py
DESCRIPTION
generates set of vectors drawn from TK03.gad at given lat and
rotated about vertical axis by given Dec
INPUT (COMMAND LINE ENTRY)
OUTPUT
dec, inc, int
SYNTAX
tk03.py [command line options] [> OutputFileName]
OPTIONS
-n N specify N, default is 100
-d D specify mean Dec, default is 0
-lat LAT specify latitude, default is 0
-rev include reversals
-t INT truncates intensities to >INT uT
-G2 FRAC specify average g_2^0 fraction (default is 0)
-G3 FRAC specify average g_3^0 fraction (default is 0)
"""
N, L, D, R = 100, 0., 0., 0
G2, G3 = 0., 0.
cnt = 1
Imax = 0
if len(sys.argv) != 0 and '-h' in sys.argv:
print(main.__doc__)
sys.exit()
else:
if '-n' in sys.argv:
ind = sys.argv.index('-n')
N = int(sys.argv[ind + 1])
if '-d' in sys.argv:
ind = sys.argv.index('-d')
D = float(sys.argv[ind + 1])
if '-lat' in sys.argv:
ind = sys.argv.index('-lat')
L = float(sys.argv[ind + 1])
if '-t' in sys.argv:
ind = sys.argv.index('-t')
Imax = 1e3 * float(sys.argv[ind + 1])
if '-rev' in sys.argv:
R = 1
if '-G2' in sys.argv:
ind = sys.argv.index('-G2')
G2 = float(sys.argv[ind + 1])
if '-G3' in sys.argv:
ind = sys.argv.index('-G3')
G3 = float(sys.argv[ind + 1])
for k in range(N):
gh = pmag.mktk03(8, k, G2, G3) # terms and random seed
# get a random longitude, between 0 and 359
lon = random.randint(0, 360)
vec = pmag.getvec(gh, L, lon) # send field model and lat to getvec
if vec[2] >= Imax:
vec[0] += D
if k % 2 == 0 and R == 1:
vec[0] += 180.
vec[1] = -vec[1]
if vec[0] >= 360.:
vec[0] -= 360.
print('%7.1f %7.1f %8.2f ' % (vec[0], vec[1], vec[2]))
|
python
|
{
"resource": ""
}
|
q11869
|
main
|
train
|
def main():
"""
NAME
gaussian.py
DESCRIPTION
generates set of normally distribed data from specified distribution
INPUT (COMMAND LINE ENTRY)
OUTPUT
x
SYNTAX
gaussian.py [command line options]
OPTIONS
-h prints help message and quits
-s specify standard deviation as next argument, default is 1
-n specify N as next argument, default is 100
-m specify mean as next argument, default is 0
-F specify output file
"""
N,mean,sigma=100,0,1.
outfile=""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
else:
if '-s' in sys.argv:
ind=sys.argv.index('-s')
sigma=float(sys.argv[ind+1])
if '-n' in sys.argv:
ind=sys.argv.index('-n')
N=int(sys.argv[ind+1])
if '-m' in sys.argv:
ind=sys.argv.index('-m')
mean=float(sys.argv[ind+1])
if '-F' in sys.argv:
ind=sys.argv.index('-F')
outfile=sys.argv[ind+1]
out=open(outfile,'w')
for k in range(N):
x='%f'%(pmag.gaussdev(mean,sigma)) # send kappa to fshdev
if outfile=="":
print(x)
else:
out.write(x+'\n')
|
python
|
{
"resource": ""
}
|
q11870
|
main
|
train
|
def main():
"""
NAME
qqunf.py
DESCRIPTION
makes qq plot from input data against uniform distribution
SYNTAX
qqunf.py [command line options]
OPTIONS
-h help message
-f FILE, specify file on command line
"""
fmt,plot='svg',0
if '-h' in sys.argv: # check if help is needed
print(main.__doc__)
sys.exit() # graceful quit
elif '-f' in sys.argv: # ask for filename
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
f=open(file,'r')
input=f.readlines()
Data=[]
for line in input:
line.replace('\n','')
if '\t' in line: # read in the data from standard input
rec=line.split('\t') # split each line on space to get records
else:
rec=line.split() # split each line on space to get records
Data.append(float(rec[0]))
#
if len(Data) >=10:
QQ={'unf1':1}
pmagplotlib.plot_init(QQ['unf1'],5,5)
pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot
else:
print('you need N> 10')
sys.exit()
pmagplotlib.draw_figs(QQ)
files={}
for key in list(QQ.keys()):
files[key]=key+'.'+fmt
if pmagplotlib.isServer:
black = '#000000'
purple = '#800080'
titles={}
titles['eq']='Equal Area Plot'
EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
pmagplotlib.save_plots(QQ,files)
elif plot==1:
files['qq']=file+'.'+fmt
pmagplotlib.save_plots(QQ,files)
else:
ans=input(" S[a]ve to save plot, [q]uit without saving: ")
if ans=="a": pmagplotlib.save_plots(QQ,files)
|
python
|
{
"resource": ""
}
|
q11871
|
main
|
train
|
def main():
"""
NAME
qqplot.py
DESCRIPTION
makes qq plot of input data against a Normal distribution.
INPUT FORMAT
takes real numbers in single column
SYNTAX
qqplot.py [-h][-i][-f FILE]
OPTIONS
-f FILE, specify file on command line
-fmt [png,svg,jpg,eps] set plot output format [default is svg]
-sav saves and quits
OUTPUT
calculates the K-S D and the D expected for a normal distribution
when D<Dc, distribution is normal (at 95% level of confidence).
"""
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: # ask for filename
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
f=open(file,'r')
data=f.readlines()
X= [] # set up list for data
for line in data: # read in the data from standard input
rec=line.split() # split each line on space to get records
X.append(float(rec[0])) # append data to X
#
QQ={'qq':1}
pmagplotlib.plot_init(QQ['qq'],5,5)
pmagplotlib.plot_qq_norm(QQ['qq'],X,'Q-Q Plot') # make plot
if plot==0:
pmagplotlib.draw_figs(QQ)
files={}
for key in list(QQ.keys()):
files[key]=key+'.'+fmt
if pmagplotlib.isServer:
black = '#000000'
purple = '#800080'
titles={}
titles['eq']='Q-Q Plot'
QQ = pmagplotlib.add_borders(EQ,titles,black,purple)
pmagplotlib.save_plots(QQ,files)
elif plot==0:
ans=input(" S[a]ve to save plot, [q]uit without saving: ")
if ans=="a":
pmagplotlib.save_plots(QQ,files)
else:
pmagplotlib.save_plots(QQ,files)
|
python
|
{
"resource": ""
}
|
q11872
|
GridFrame.on_key_down
|
train
|
def on_key_down(self, event):
"""
If user does command v,
re-size window in case pasting has changed the content size.
"""
keycode = event.GetKeyCode()
meta_down = event.MetaDown() or event.GetCmdDown()
if keycode == 86 and meta_down:
# treat it as if it were a wx.EVT_TEXT_SIZE
self.do_fit(event)
|
python
|
{
"resource": ""
}
|
q11873
|
GridFrame.add_new_header_groups
|
train
|
def add_new_header_groups(self, groups):
"""
compile list of all headers belonging to all specified groups
eliminate all headers that are already included
add any req'd drop-down menus
return errors
"""
already_present = []
for group in groups:
col_names = self.dm[self.dm['group'] == group].index
for col in col_names:
if col not in self.grid.col_labels:
col_number = self.grid.add_col(col)
# add to appropriate headers list
# add drop down menus for user-added column
if col in self.contribution.vocab.vocabularies:
self.drop_down_menu.add_drop_down(col_number, col)
elif col in self.contribution.vocab.suggested:
self.drop_down_menu.add_drop_down(col_number, col)
elif col in ['specimen', 'sample', 'site', 'location',
'specimens', 'samples', 'sites']:
self.drop_down_menu.add_drop_down(col_number, col)
elif col == 'experiments':
self.drop_down_menu.add_drop_down(col_number, col)
if col == "method_codes":
self.drop_down_menu.add_method_drop_down(col_number, col)
else:
already_present.append(col)
return already_present
|
python
|
{
"resource": ""
}
|
q11874
|
GridFrame.on_add_rows
|
train
|
def on_add_rows(self, event):
"""
add rows to grid
"""
num_rows = self.rows_spin_ctrl.GetValue()
#last_row = self.grid.GetNumberRows()
for row in range(num_rows):
self.grid.add_row()
#if not self.grid.changes:
# self.grid.changes = set([])
#self.grid.changes.add(last_row)
#last_row += 1
self.main_sizer.Fit(self)
|
python
|
{
"resource": ""
}
|
q11875
|
GridFrame.onImport
|
train
|
def onImport(self, event):
"""
Import a MagIC-format file
"""
if self.grid.changes:
print("-W- Your changes will be overwritten...")
wind = pw.ChooseOne(self, "Import file anyway", "Save grid first",
"-W- Your grid has unsaved changes which will be overwritten if you import a file now...")
wind.Centre()
res = wind.ShowModal()
# save grid first:
if res == wx.ID_NO:
self.onSave(None, alert=True, destroy=False)
# reset self.changes
self.grid.changes = set()
openFileDialog = wx.FileDialog(self, "Open MagIC-format file", self.WD, "",
"MagIC file|*.*", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
result = openFileDialog.ShowModal()
if result == wx.ID_OK:
# get filename
filename = openFileDialog.GetPath()
# make sure the dtype is correct
f = open(filename)
line = f.readline()
if line.startswith("tab"):
delim, dtype = line.split("\t")
else:
delim, dtype = line.split("")
f.close()
dtype = dtype.strip()
if (dtype != self.grid_type) and (dtype + "s" != self.grid_type):
text = "You are currently editing the {} grid, but you are trying to import a {} file.\nPlease open the {} grid and then re-try this import.".format(self.grid_type, dtype, dtype)
pw.simple_warning(text)
return
# grab old data for concatenation
if self.grid_type in self.contribution.tables:
old_df_container = self.contribution.tables[self.grid_type]
else:
old_df_container = None
old_col_names = self.grid.col_labels
# read in new file and update contribution
df_container = cb.MagicDataFrame(filename, dmodel=self.dm,
columns=old_col_names)
# concatenate if possible
if not isinstance(old_df_container, type(None)):
df_container.df = pd.concat([old_df_container.df, df_container.df],
axis=0, sort=True)
self.contribution.tables[df_container.dtype] = df_container
self.grid_builder = GridBuilder(self.contribution, self.grid_type,
self.panel, parent_type=self.parent_type,
reqd_headers=self.reqd_headers)
# delete old grid
self.grid_box.Hide(0)
self.grid_box.Remove(0)
# create new, updated grid
self.grid = self.grid_builder.make_grid()
self.grid.InitUI()
# add data to new grid
self.grid_builder.add_data_to_grid(self.grid, self.grid_type)
# add new grid to sizer and fit everything
self.grid_box.Add(self.grid, flag=wx.ALL, border=5)
self.main_sizer.Fit(self)
self.Centre()
# add any needed drop-down-menus
self.drop_down_menu = drop_down_menus.Menus(self.grid_type,
self.contribution,
self.grid)
# done!
return
|
python
|
{
"resource": ""
}
|
q11876
|
GridFrame.onCancelButton
|
train
|
def onCancelButton(self, event):
"""
Quit grid with warning if unsaved changes present
"""
if self.grid.changes:
dlg1 = wx.MessageDialog(self, caption="Message:",
message="Are you sure you want to exit this grid?\nYour changes will not be saved.\n ",
style=wx.OK|wx.CANCEL)
result = dlg1.ShowModal()
if result == wx.ID_OK:
dlg1.Destroy()
self.Destroy()
else:
self.Destroy()
if self.main_frame:
self.main_frame.Show()
self.main_frame.Raise()
|
python
|
{
"resource": ""
}
|
q11877
|
GridFrame.onSave
|
train
|
def onSave(self, event, alert=False, destroy=True):
"""
Save grid data
"""
# tidy up drop_down menu
if self.drop_down_menu:
self.drop_down_menu.clean_up()
# then save actual data
self.grid_builder.save_grid_data()
if not event and not alert:
return
# then alert user
wx.MessageBox('Saved!', 'Info',
style=wx.OK | wx.ICON_INFORMATION)
if destroy:
self.Destroy()
|
python
|
{
"resource": ""
}
|
q11878
|
GridFrame.onDragSelection
|
train
|
def onDragSelection(self, event):
"""
Set self.df_slice based on user's selection
"""
if self.grid.GetSelectionBlockTopLeft():
#top_left = self.grid.GetSelectionBlockTopLeft()
#bottom_right = self.grid.GetSelectionBlockBottomRight()
# awkward hack to fix wxPhoenix memory problem, (Github issue #221)
bottom_right = eval(repr(self.grid.GetSelectionBlockBottomRight()).replace("GridCellCoordsArray: ", "").replace("GridCellCoords", ""))
top_left = eval(repr(self.grid.GetSelectionBlockTopLeft()).replace("GridCellCoordsArray: ", "").replace("GridCellCoords", ""))
#
top_left = top_left[0]
bottom_right = bottom_right[0]
else:
return
# GetSelectionBlock returns (row, col)
min_col = top_left[1]
max_col = bottom_right[1]
min_row = top_left[0]
max_row = bottom_right[0]
self.df_slice = self.contribution.tables[self.grid_type].df.iloc[min_row:max_row+1, min_col:max_col+1]
|
python
|
{
"resource": ""
}
|
q11879
|
GridFrame.onKey
|
train
|
def onKey(self, event):
"""
Copy selection if control down and 'c'
"""
if event.CmdDown() or event.ControlDown():
if event.GetKeyCode() == 67:
self.onCopySelection(None)
|
python
|
{
"resource": ""
}
|
q11880
|
GridFrame.onSelectAll
|
train
|
def onSelectAll(self, event):
"""
Selects full grid and copies it to the Clipboard
"""
# do clean up here!!!
if self.drop_down_menu:
self.drop_down_menu.clean_up()
# save all grid data
self.grid_builder.save_grid_data()
df = self.contribution.tables[self.grid_type].df
# write df to clipboard for pasting
# header arg determines whether columns are taken
# index arg determines whether index is taken
pd.DataFrame.to_clipboard(df, header=False, index=False)
print('-I- You have copied all cells! You may paste them into a text document or spreadsheet using Command v.')
|
python
|
{
"resource": ""
}
|
q11881
|
GridFrame.onCopySelection
|
train
|
def onCopySelection(self, event):
"""
Copies self.df_slice to the Clipboard if slice exists
"""
if self.df_slice is not None:
pd.DataFrame.to_clipboard(self.df_slice, header=False, index=False)
self.grid.ClearSelection()
self.df_slice = None
print('-I- You have copied the selected cells. You may paste them into a text document or spreadsheet using Command v.')
else:
print('-W- No cells were copied! You must highlight a selection cells before hitting the copy button. You can do this by clicking and dragging, or by using the Shift key and click.')
|
python
|
{
"resource": ""
}
|
q11882
|
GridBuilder.current_grid_empty
|
train
|
def current_grid_empty(self):
"""
Check to see if grid is empty except for default values
"""
empty = True
# df IS empty if there are no rows
if not any(self.magic_dataframe.df.index):
empty = True
# df is NOT empty if there are at least two rows
elif len(self.grid.row_labels) > 1:
empty = False
# if there is one row, df MIGHT be empty
else:
# check all the non-null values
non_null_vals = [val for val in self.magic_dataframe.df.values[0] if cb.not_null(val, False)]
for val in non_null_vals:
if not isinstance(val, str):
empty = False
break
# if there are any non-default values, grid is not empty
if val.lower() not in ['this study', 'g', 'i']:
empty = False
break
return empty
|
python
|
{
"resource": ""
}
|
q11883
|
GridBuilder.fill_defaults
|
train
|
def fill_defaults(self):
"""
Fill in self.grid with default values in certain columns.
Only fill in new values if grid is missing those values.
"""
defaults = {'result_quality': 'g',
'result_type': 'i',
'orientation_quality': 'g',
'citations': 'This study'}
for col_name in defaults:
if col_name in self.grid.col_labels:
# try to grab existing values from contribution
if self.grid_type in self.contribution.tables:
if col_name in self.contribution.tables[self.grid_type].df.columns:
old_vals = self.contribution.tables[self.grid_type].df[col_name]
# if column is completely filled in, skip
if all([cb.not_null(val, False) for val in old_vals]):
continue
new_val = defaults[col_name]
vals = list(np.where((old_vals.notnull()) & (old_vals != ''), old_vals, new_val))
else:
vals = [defaults[col_name]] * self.grid.GetNumberRows()
# if values not available in contribution, use defaults
else:
vals = [defaults[col_name]] * self.grid.GetNumberRows()
# if col_name not present in grid, skip
else:
vals = None
#
if vals:
print('-I- Updating column "{}" with default values'.format(col_name))
if self.huge:
self.grid.SetColumnValues(col_name, vals)
else:
col_ind = self.grid.col_labels.index(col_name)
for row, val in enumerate(vals):
self.grid.SetCellValue(row, col_ind, val)
self.grid.changes = set(range(self.grid.GetNumberRows()))
|
python
|
{
"resource": ""
}
|
q11884
|
GridFrame.on_remove_cols
|
train
|
def on_remove_cols(self, event):
"""
enter 'remove columns' mode
"""
# open the help message
self.toggle_help(event=None, mode='open')
# first unselect any selected cols/cells
self.remove_cols_mode = True
self.grid.ClearSelection()
self.remove_cols_button.SetLabel("end delete column mode")
# change button to exit the delete columns mode
self.Unbind(wx.EVT_BUTTON, self.remove_cols_button)
self.Bind(wx.EVT_BUTTON, self.exit_col_remove_mode, self.remove_cols_button)
# then disable all other buttons
for btn in [self.add_cols_button, self.remove_row_button, self.add_many_rows_button]:
btn.Disable()
# then make some visual changes
self.msg_text.SetLabel("Remove grid columns: click on a column header to delete it. Required headers for {}s may not be deleted.".format(self.grid_type))
self.help_msg_boxsizer.Fit(self.help_msg_boxsizer.GetStaticBox())
self.main_sizer.Fit(self)
self.grid.SetWindowStyle(wx.DOUBLE_BORDER)
self.grid_box.GetStaticBox().SetWindowStyle(wx.DOUBLE_BORDER)
self.grid.Refresh()
self.main_sizer.Fit(self) # might not need this one
self.grid.changes = set(range(self.grid.GetNumberRows()))
|
python
|
{
"resource": ""
}
|
q11885
|
GridFrame.exit_col_remove_mode
|
train
|
def exit_col_remove_mode(self, event):
"""
go back from 'remove cols' mode to normal
"""
# close help messge
self.toggle_help(event=None, mode='close')
# update mode
self.remove_cols_mode = False
# re-enable all buttons
for btn in [self.add_cols_button, self.remove_row_button, self.add_many_rows_button]:
btn.Enable()
# unbind grid click for deletion
self.Unbind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK)
# undo visual cues
self.grid.SetWindowStyle(wx.DEFAULT)
self.grid_box.GetStaticBox().SetWindowStyle(wx.DEFAULT)
self.msg_text.SetLabel(self.default_msg_text)
self.help_msg_boxsizer.Fit(self.help_msg_boxsizer.GetStaticBox())
self.main_sizer.Fit(self)
# re-bind self.remove_cols_button
self.Bind(wx.EVT_BUTTON, self.on_remove_cols, self.remove_cols_button)
self.remove_cols_button.SetLabel("Remove columns")
|
python
|
{
"resource": ""
}
|
q11886
|
main
|
train
|
def main():
"""
NAME
mst_magic.py
DESCRIPTION
converts MsT data (T,M) to measurements format files
SYNTAX
mst_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-usr USER: identify user, default is ""
-f FILE: specify T,M format input file, required
-spn SPEC: specimen name, required
-fsa SFILE: name with sample, site, location information
-F FILE: specify output file, default is measurements.txt
-dc H: specify applied field during measurement, default is 0.5 T
-DM NUM: output to MagIC data model 2.5 or 3, default 3
-syn : This is a synthetic specimen and has no sample/site/location information
-spc NUM : specify number of characters to designate a specimen, default = 0
-loc LOCNAME : specify location/study name, must have either LOCNAME or SAMPFILE or be a synthetic
-ncn NCON: specify naming convention: default is #1 below
Sample naming convention:
[1] XXXXY: where XXXX is an arbitrary length site designation and Y
is the single character sample designation. e.g., TG001a is the
first sample from site TG001. [default]
[2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
[3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
[4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX
[5] site name same as sample
[6] site is entered under a separate column -- NOT CURRENTLY SUPPORTED
[7-Z] [XXXX]YYY: XXXX is site designation with Z characters with sample name XXXXYYYY
NB: all others you will have to customize your self
or e-mail ltauxe@ucsd.edu for help.
INPUT files:
T M: T is in Centigrade and M is uncalibrated magnitude
"""
#
# get command line arguments
#
args = sys.argv
if "-h" in args:
print(main.__doc__)
sys.exit()
dir_path = pmag.get_named_arg("-WD", ".")
user = pmag.get_named_arg("-usr", "")
labfield = pmag.get_named_arg("-dc", '0.5')
meas_file = pmag.get_named_arg("-F", "measurements.txt")
samp_file = pmag.get_named_arg("-fsa", "samples.txt")
try:
infile = pmag.get_named_arg("-f", reqd=True)
except pmag.MissingCommandLineArgException:
print(main.__doc__)
print("-f is required option")
sys.exit()
specnum = int(pmag.get_named_arg("-spc", 0))
location = pmag.get_named_arg("-loc", "")
specimen_name = pmag.get_named_arg("-spn", reqd=True)
syn = 0
if "-syn" in args:
syn = 1
samp_con = pmag.get_named_arg("-ncn", "1")
if "-ncn" in args:
ind = args.index("-ncn")
samp_con = sys.argv[ind+1]
data_model_num = int(pmag.get_named_arg("-DM", 3))
convert.mst(infile, specimen_name, dir_path, "", meas_file, samp_file,
user, specnum, samp_con, labfield, location, syn, data_model_num)
|
python
|
{
"resource": ""
}
|
q11887
|
main
|
train
|
def main():
"""
NAME
parse_measurements.py
DESCRIPTION
takes measurments file and creates specimen and instrument files
SYNTAX
parse_measurements.py [command line options]
OPTIONS
-h prints help message and quits
-f FILE magic_measurements input file, default is "magic_measurements.txt"
-fsi FILE er_sites input file, default is none
-Fsp FILE specimen output er_specimens format file, default is "er_specimens.txt"
-Fin FILE instrument output magic_instruments format file, default is "magic_instruments.txt"
OUPUT
writes er_specimens and magic_instruments formatted files
"""
infile = 'magic_measurements.txt'
sitefile = ""
specout = "er_specimens.txt"
instout = "magic_instruments.txt"
# get command line stuff
if "-h" in sys.argv:
print(main.__doc__)
sys.exit()
if '-f' in sys.argv:
ind = sys.argv.index("-f")
infile = sys.argv[ind + 1]
if '-fsi' in sys.argv:
ind = sys.argv.index("-fsi")
sitefile = sys.argv[ind + 1]
if '-Fsp' in sys.argv:
ind = sys.argv.index("-Fsp")
specout = sys.argv[ind + 1]
if '-Fin' in sys.argv:
ind = sys.argv.index("-Fin")
instout = sys.argv[ind + 1]
if '-WD' in sys.argv:
ind = sys.argv.index("-WD")
dir_path = sys.argv[ind + 1]
infile = dir_path + '/' + infile
if sitefile != "":
sitefile = dir_path + '/' + sitefile
specout = dir_path + '/' + specout
instout = dir_path + '/' + instout
# now do re-ordering
pmag.ParseMeasFile(infile, sitefile, instout, specout)
|
python
|
{
"resource": ""
}
|
q11888
|
OrientFrameGrid3.on_m_calc_orient
|
train
|
def on_m_calc_orient(self,event):
'''
This fucntion does exactly what the 'import orientation' fuction does in MagIC.py
after some dialog boxes the function calls orientation_magic.py
'''
# first see if demag_orient.txt
self.on_m_save_file(None)
orient_convention_dia = orient_convention(None)
orient_convention_dia.Center()
#orient_convention_dia.ShowModal()
if orient_convention_dia.ShowModal() == wx.ID_OK:
ocn_flag = orient_convention_dia.ocn_flag
dcn_flag = orient_convention_dia.dcn_flag
gmt_flags = orient_convention_dia.gmt_flags
orient_convention_dia.Destroy()
else:
return
or_con = orient_convention_dia.ocn
dec_correction_con = int(orient_convention_dia.dcn)
try:
hours_from_gmt = float(orient_convention_dia.gmt)
except:
hours_from_gmt = 0
try:
dec_correction = float(orient_convention_dia.correct_dec)
except:
dec_correction = 0
method_code_dia=method_code_dialog(None)
method_code_dia.Center()
if method_code_dia.ShowModal() == wx.ID_OK:
bedding_codes_flags=method_code_dia.bedding_codes_flags
methodcodes_flags=method_code_dia.methodcodes_flags
method_code_dia.Destroy()
else:
print("-I- Canceling calculation")
return
method_codes = method_code_dia.methodcodes
average_bedding = method_code_dia.average_bedding
bed_correction = method_code_dia.bed_correction
command_args=['orientation_magic.py']
command_args.append("-WD %s"%self.WD)
command_args.append("-Fsa er_samples_orient.txt")
command_args.append("-Fsi er_sites_orient.txt ")
command_args.append("-f %s"%"demag_orient.txt")
command_args.append(ocn_flag)
command_args.append(dcn_flag)
command_args.append(gmt_flags)
command_args.append(bedding_codes_flags)
command_args.append(methodcodes_flags)
commandline = " ".join(command_args)
print("-I- executing command: %s" %commandline)
os.chdir(self.WD)
if os.path.exists(os.path.join(self.WD, 'er_samples.txt')) or os.path.exists(os.path.join(self.WD, 'er_sites.txt')):
append = True
else:
append = False
samp_file = "er_samples.txt"
site_file = "er_sites.txt"
success, error_message = ipmag.orientation_magic(or_con, dec_correction_con, dec_correction,
bed_correction, hours_from_gmt=hours_from_gmt,
method_codes=method_codes, average_bedding=average_bedding,
orient_file='demag_orient.txt', samp_file=samp_file,
site_file=site_file, input_dir_path=self.WD,
output_dir_path=self.WD, append=append, data_model=3)
if not success:
dlg1 = wx.MessageDialog(None,caption="Message:", message="-E- ERROR: Error in running orientation_magic.py\n{}".format(error_message) ,style=wx.OK|wx.ICON_INFORMATION)
dlg1.ShowModal()
dlg1.Destroy()
print("-E- ERROR: Error in running orientation_magic.py")
return
else:
dlg2 = wx.MessageDialog(None,caption="Message:", message="-I- Successfully ran orientation_magic", style=wx.OK|wx.ICON_INFORMATION)
dlg2.ShowModal()
dlg2.Destroy()
self.Parent.Show()
self.Parent.Raise()
self.Destroy()
self.contribution.add_magic_table('samples')
return
|
python
|
{
"resource": ""
}
|
q11889
|
main
|
train
|
def main():
"""
NAME
eigs_s.py
DESCRIPTION
converts eigenparamters format data to s format
SYNTAX
eigs_s.py [-h][-i][command line options][<filename]
OPTIONS
-h prints help message and quits
-i allows interactive file name entry
-f FILE, specifies input file name
-F FILE, specifies output file name
< filenmae, reads file from standard input (Unix-like operating systems only)
INPUT
tau_i, dec_i inc_i of eigenvectors
OUTPUT
x11,x22,x33,x12,x23,x13
"""
file=""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
elif '-i' in sys.argv:
file=input("Enter eigenparameters data file name: ")
elif '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
if file!="":
f=open(file,'r')
data=f.readlines()
f.close()
else:
data=sys.stdin.readlines()
ofile=""
if '-F' in sys.argv:
ind = sys.argv.index('-F')
ofile= sys.argv[ind+1]
out = open(ofile, 'w + a')
file_outstring = ""
for line in data:
tau,Vdirs=[],[]
rec=line.split()
for k in range(0,9,3):
tau.append(float(rec[k]))
Vdirs.append((float(rec[k+1]),float(rec[k+2])))
srot=pmag.doeigs_s(tau,Vdirs)
outstring=""
for s in srot:outstring+='%10.8f '%(s)
if ofile=="":
print(outstring)
else:
out.write(outstring+'\n')
|
python
|
{
"resource": ""
}
|
q11890
|
get_numpy_dtype
|
train
|
def get_numpy_dtype(obj):
"""Return NumPy data type associated to obj
Return None if NumPy is not available
or if obj is not a NumPy array or scalar"""
if ndarray is not FakeObject:
# NumPy is available
import numpy as np
if isinstance(obj, np.generic) or isinstance(obj, np.ndarray):
# Numpy scalars all inherit from np.generic.
# Numpy arrays all inherit from np.ndarray.
# If we check that we are certain we have one of these
# types then we are less likely to generate an exception below.
try:
return obj.dtype.type
except (AttributeError, RuntimeError):
# AttributeError: some NumPy objects have no dtype attribute
# RuntimeError: happens with NetCDF objects (Issue 998)
return
|
python
|
{
"resource": ""
}
|
q11891
|
get_size
|
train
|
def get_size(item):
"""Return size of an item of arbitrary type"""
if isinstance(item, (list, set, tuple, dict)):
return len(item)
elif isinstance(item, (ndarray, MaskedArray)):
return item.shape
elif isinstance(item, Image):
return item.size
if isinstance(item, (DataFrame, Index, Series)):
return item.shape
else:
return 1
|
python
|
{
"resource": ""
}
|
q11892
|
get_object_attrs
|
train
|
def get_object_attrs(obj):
"""
Get the attributes of an object using dir.
This filters protected attributes
"""
attrs = [k for k in dir(obj) if not k.startswith('__')]
if not attrs:
attrs = dir(obj)
return attrs
|
python
|
{
"resource": ""
}
|
q11893
|
str_to_timedelta
|
train
|
def str_to_timedelta(value):
"""Convert a string to a datetime.timedelta value.
The following strings are accepted:
- 'datetime.timedelta(1, 5, 12345)'
- 'timedelta(1, 5, 12345)'
- '(1, 5, 12345)'
- '1, 5, 12345'
- '1'
if there are less then three parameters, the missing parameters are
assumed to be 0. Variations in the spacing of the parameters are allowed.
Raises:
ValueError for strings not matching the above criterion.
"""
m = re.match(r'^(?:(?:datetime\.)?timedelta)?'
r'\(?'
r'([^)]*)'
r'\)?$', value)
if not m:
raise ValueError('Invalid string for datetime.timedelta')
args = [int(a.strip()) for a in m.group(1).split(',')]
return datetime.timedelta(*args)
|
python
|
{
"resource": ""
}
|
q11894
|
get_color_name
|
train
|
def get_color_name(value):
"""Return color name depending on value type"""
if not is_known_type(value):
return CUSTOM_TYPE_COLOR
for typ, name in list(COLORS.items()):
if isinstance(value, typ):
return name
else:
np_dtype = get_numpy_dtype(value)
if np_dtype is None or not hasattr(value, 'size'):
return UNSUPPORTED_COLOR
elif value.size == 1:
return SCALAR_COLOR
else:
return ARRAY_COLOR
|
python
|
{
"resource": ""
}
|
q11895
|
default_display
|
train
|
def default_display(value, with_module=True):
"""Default display for unknown objects."""
object_type = type(value)
try:
name = object_type.__name__
module = object_type.__module__
if with_module:
return name + ' object of ' + module + ' module'
else:
return name
except:
type_str = to_text_string(object_type)
return type_str[1:-1]
|
python
|
{
"resource": ""
}
|
q11896
|
display_to_value
|
train
|
def display_to_value(value, default_value, ignore_errors=True):
"""Convert back to value"""
from qtpy.compat import from_qvariant
value = from_qvariant(value, to_text_string)
try:
np_dtype = get_numpy_dtype(default_value)
if isinstance(default_value, bool):
# We must test for boolean before NumPy data types
# because `bool` class derives from `int` class
try:
value = bool(float(value))
except ValueError:
value = value.lower() == "true"
elif np_dtype is not None:
if 'complex' in str(type(default_value)):
value = np_dtype(complex(value))
else:
value = np_dtype(value)
elif is_binary_string(default_value):
value = to_binary_string(value, 'utf8')
elif is_text_string(default_value):
value = to_text_string(value)
elif isinstance(default_value, complex):
value = complex(value)
elif isinstance(default_value, float):
value = float(value)
elif isinstance(default_value, int):
try:
value = int(value)
except ValueError:
value = float(value)
elif isinstance(default_value, datetime.datetime):
value = datestr_to_datetime(value)
elif isinstance(default_value, datetime.date):
value = datestr_to_datetime(value).date()
elif isinstance(default_value, datetime.timedelta):
value = str_to_timedelta(value)
elif ignore_errors:
value = try_to_eval(value)
else:
value = eval(value)
except (ValueError, SyntaxError):
if ignore_errors:
value = try_to_eval(value)
else:
return default_value
return value
|
python
|
{
"resource": ""
}
|
q11897
|
get_type_string
|
train
|
def get_type_string(item):
"""Return type string of an object."""
if isinstance(item, DataFrame):
return "DataFrame"
if isinstance(item, Index):
return type(item).__name__
if isinstance(item, Series):
return "Series"
found = re.findall(r"<(?:type|class) '(\S*)'>",
to_text_string(type(item)))
if found:
return found[0]
|
python
|
{
"resource": ""
}
|
q11898
|
get_human_readable_type
|
train
|
def get_human_readable_type(item):
"""Return human-readable type string of an item"""
if isinstance(item, (ndarray, MaskedArray)):
return item.dtype.name
elif isinstance(item, Image):
return "Image"
else:
text = get_type_string(item)
if text is None:
text = to_text_string('unknown')
else:
return text[text.find('.')+1:]
|
python
|
{
"resource": ""
}
|
q11899
|
is_supported
|
train
|
def is_supported(value, check_all=False, filters=None, iterate=False):
"""Return True if the value is supported, False otherwise"""
assert filters is not None
if value is None:
return True
if not is_editable_type(value):
return False
elif not isinstance(value, filters):
return False
elif iterate:
if isinstance(value, (list, tuple, set)):
valid_count = 0
for val in value:
if is_supported(val, filters=filters, iterate=check_all):
valid_count += 1
if not check_all:
break
return valid_count > 0
elif isinstance(value, dict):
for key, val in list(value.items()):
if not is_supported(key, filters=filters, iterate=check_all) \
or not is_supported(val, filters=filters,
iterate=check_all):
return False
if not check_all:
break
return True
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.