repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
PmagPy/PmagPy | programs/demag_gui.py | Demag_GUI.on_right_click_listctrl | def on_right_click_listctrl(self, event):
"""
right click on the listctrl toggles measurement bad
"""
g_index = event.GetIndex()
if self.Data[self.s]['measurement_flag'][g_index] == 'g':
self.mark_meas_bad(g_index)
else:
self.mark_meas_good(g_index)
if self.data_model == 3.0:
self.con.tables['measurements'].write_magic_file(dir_path=self.WD)
else:
pmag.magic_write(os.path.join(
self.WD, "magic_measurements.txt"), self.mag_meas_data, "magic_measurements")
self.recalculate_current_specimen_interpreatations()
if self.ie_open:
self.ie.update_current_fit_data()
self.calculate_high_levels_data()
self.update_selection() | python | def on_right_click_listctrl(self, event):
"""
right click on the listctrl toggles measurement bad
"""
g_index = event.GetIndex()
if self.Data[self.s]['measurement_flag'][g_index] == 'g':
self.mark_meas_bad(g_index)
else:
self.mark_meas_good(g_index)
if self.data_model == 3.0:
self.con.tables['measurements'].write_magic_file(dir_path=self.WD)
else:
pmag.magic_write(os.path.join(
self.WD, "magic_measurements.txt"), self.mag_meas_data, "magic_measurements")
self.recalculate_current_specimen_interpreatations()
if self.ie_open:
self.ie.update_current_fit_data()
self.calculate_high_levels_data()
self.update_selection() | right click on the listctrl toggles measurement bad | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L8115-L8137 |
PmagPy/PmagPy | programs/demag_gui.py | Demag_GUI.onSelect_specimen | def onSelect_specimen(self, event):
"""
update figures and text when a new specimen is selected
"""
self.selected_meas = []
self.select_specimen(str(self.specimens_box.GetValue()))
if self.ie_open:
self.ie.change_selected(self.current_fit)
self.update_selection() | python | def onSelect_specimen(self, event):
"""
update figures and text when a new specimen is selected
"""
self.selected_meas = []
self.select_specimen(str(self.specimens_box.GetValue()))
if self.ie_open:
self.ie.change_selected(self.current_fit)
self.update_selection() | update figures and text when a new specimen is selected | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L8160-L8168 |
PmagPy/PmagPy | programs/demag_gui.py | Demag_GUI.on_enter_specimen | def on_enter_specimen(self, event):
"""
upon enter on the specimen box it makes that specimen the current
specimen
"""
new_specimen = self.specimens_box.GetValue()
if new_specimen not in self.specimens:
self.user_warning(
"%s is not a valid specimen with measurement data, aborting" % (new_specimen))
self.specimens_box.SetValue(self.s)
return
self.select_specimen(new_specimen)
if self.ie_open:
self.ie.change_selected(self.current_fit)
self.update_selection() | python | def on_enter_specimen(self, event):
"""
upon enter on the specimen box it makes that specimen the current
specimen
"""
new_specimen = self.specimens_box.GetValue()
if new_specimen not in self.specimens:
self.user_warning(
"%s is not a valid specimen with measurement data, aborting" % (new_specimen))
self.specimens_box.SetValue(self.s)
return
self.select_specimen(new_specimen)
if self.ie_open:
self.ie.change_selected(self.current_fit)
self.update_selection() | upon enter on the specimen box it makes that specimen the current
specimen | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L8170-L8184 |
PmagPy/PmagPy | programs/demag_gui.py | Demag_GUI.get_new_PCA_parameters | def get_new_PCA_parameters(self, event):
"""
calculate statistics when temperatures are selected
or PCA type is changed
"""
tmin = str(self.tmin_box.GetValue())
tmax = str(self.tmax_box.GetValue())
if tmin == "" or tmax == "":
return
if tmin in self.T_list and tmax in self.T_list and \
(self.T_list.index(tmax) <= self.T_list.index(tmin)):
return
PCA_type = self.PCA_type_box.GetValue()
if PCA_type == "line":
calculation_type = "DE-BFL"
elif PCA_type == "line-anchored":
calculation_type = "DE-BFL-A"
elif PCA_type == "line-with-origin":
calculation_type = "DE-BFL-O"
elif PCA_type == "Fisher":
calculation_type = "DE-FM"
elif PCA_type == "plane":
calculation_type = "DE-BFP"
coordinate_system = self.COORDINATE_SYSTEM
if self.current_fit:
self.current_fit.put(self.s, coordinate_system, self.get_PCA_parameters(
self.s, self.current_fit, tmin, tmax, coordinate_system, calculation_type))
if self.ie_open:
self.ie.update_current_fit_data()
self.update_GUI_with_new_interpretation() | python | def get_new_PCA_parameters(self, event):
"""
calculate statistics when temperatures are selected
or PCA type is changed
"""
tmin = str(self.tmin_box.GetValue())
tmax = str(self.tmax_box.GetValue())
if tmin == "" or tmax == "":
return
if tmin in self.T_list and tmax in self.T_list and \
(self.T_list.index(tmax) <= self.T_list.index(tmin)):
return
PCA_type = self.PCA_type_box.GetValue()
if PCA_type == "line":
calculation_type = "DE-BFL"
elif PCA_type == "line-anchored":
calculation_type = "DE-BFL-A"
elif PCA_type == "line-with-origin":
calculation_type = "DE-BFL-O"
elif PCA_type == "Fisher":
calculation_type = "DE-FM"
elif PCA_type == "plane":
calculation_type = "DE-BFP"
coordinate_system = self.COORDINATE_SYSTEM
if self.current_fit:
self.current_fit.put(self.s, coordinate_system, self.get_PCA_parameters(
self.s, self.current_fit, tmin, tmax, coordinate_system, calculation_type))
if self.ie_open:
self.ie.update_current_fit_data()
self.update_GUI_with_new_interpretation() | calculate statistics when temperatures are selected
or PCA type is changed | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L8221-L8253 |
PmagPy/PmagPy | programs/demag_gui.py | Demag_GUI.on_select_fit | def on_select_fit(self, event):
"""
Picks out the fit selected in the fit combobox and sets it to the
current fit of the GUI then calls the select function of the fit to
set the GUI's bounds boxes and alter other such parameters
Parameters
----------
event : the wx.ComboBoxEvent that triggers this function
Alters
------
current_fit, fit_box selection, tmin_box selection, tmax_box
selection
"""
fit_val = self.fit_box.GetValue()
if self.s not in self.pmag_results_data['specimens'] or not self.pmag_results_data['specimens'][self.s] or fit_val == 'None':
self.clear_boxes()
self.current_fit = None
self.fit_box.SetStringSelection('None')
self.tmin_box.SetStringSelection('')
self.tmax_box.SetStringSelection('')
else:
try:
fit_num = list(
map(lambda x: x.name, self.pmag_results_data['specimens'][self.s])).index(fit_val)
except ValueError:
fit_num = -1
self.pmag_results_data['specimens'][self.s][fit_num].select()
if self.ie_open:
self.ie.change_selected(self.current_fit) | python | def on_select_fit(self, event):
"""
Picks out the fit selected in the fit combobox and sets it to the
current fit of the GUI then calls the select function of the fit to
set the GUI's bounds boxes and alter other such parameters
Parameters
----------
event : the wx.ComboBoxEvent that triggers this function
Alters
------
current_fit, fit_box selection, tmin_box selection, tmax_box
selection
"""
fit_val = self.fit_box.GetValue()
if self.s not in self.pmag_results_data['specimens'] or not self.pmag_results_data['specimens'][self.s] or fit_val == 'None':
self.clear_boxes()
self.current_fit = None
self.fit_box.SetStringSelection('None')
self.tmin_box.SetStringSelection('')
self.tmax_box.SetStringSelection('')
else:
try:
fit_num = list(
map(lambda x: x.name, self.pmag_results_data['specimens'][self.s])).index(fit_val)
except ValueError:
fit_num = -1
self.pmag_results_data['specimens'][self.s][fit_num].select()
if self.ie_open:
self.ie.change_selected(self.current_fit) | Picks out the fit selected in the fit combobox and sets it to the
current fit of the GUI then calls the select function of the fit to
set the GUI's bounds boxes and alter other such parameters
Parameters
----------
event : the wx.ComboBoxEvent that triggers this function
Alters
------
current_fit, fit_box selection, tmin_box selection, tmax_box
selection | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L8362-L8392 |
PmagPy/PmagPy | programs/demag_gui.py | Demag_GUI.on_enter_fit_name | def on_enter_fit_name(self, event):
"""
Allows the entering of new fit names in the fit combobox
Parameters
----------
event : the wx.ComboBoxEvent that triggers this function
Alters
------
current_fit.name
"""
if self.current_fit == None:
self.on_btn_add_fit(event)
value = self.fit_box.GetValue()
if ':' in value:
name, color = value.split(':')
else:
name, color = value, None
if name in [x.name for x in self.pmag_results_data['specimens'][self.s]]:
print('bad name')
return
self.current_fit.name = name
if color in list(self.color_dict.keys()):
self.current_fit.color = self.color_dict[color]
self.update_fit_boxes()
self.plot_high_levels_data() | python | def on_enter_fit_name(self, event):
"""
Allows the entering of new fit names in the fit combobox
Parameters
----------
event : the wx.ComboBoxEvent that triggers this function
Alters
------
current_fit.name
"""
if self.current_fit == None:
self.on_btn_add_fit(event)
value = self.fit_box.GetValue()
if ':' in value:
name, color = value.split(':')
else:
name, color = value, None
if name in [x.name for x in self.pmag_results_data['specimens'][self.s]]:
print('bad name')
return
self.current_fit.name = name
if color in list(self.color_dict.keys()):
self.current_fit.color = self.color_dict[color]
self.update_fit_boxes()
self.plot_high_levels_data() | Allows the entering of new fit names in the fit combobox
Parameters
----------
event : the wx.ComboBoxEvent that triggers this function
Alters
------
current_fit.name | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L8394-L8420 |
PmagPy/PmagPy | programs/demag_gui.py | Demag_GUI.on_save_interpretation_button | def on_save_interpretation_button(self, event):
"""
on the save button the interpretation is saved to pmag_results_table
data in all coordinate systems
"""
if self.current_fit:
self.current_fit.saved = True
calculation_type = self.current_fit.get(self.COORDINATE_SYSTEM)[
'calculation_type']
tmin = str(self.tmin_box.GetValue())
tmax = str(self.tmax_box.GetValue())
self.current_fit.put(self.s, 'specimen', self.get_PCA_parameters(
self.s, self.current_fit, tmin, tmax, 'specimen', calculation_type))
if len(self.Data[self.s]['zijdblock_geo']) > 0:
self.current_fit.put(self.s, 'geographic', self.get_PCA_parameters(
self.s, self.current_fit, tmin, tmax, 'geographic', calculation_type))
if len(self.Data[self.s]['zijdblock_tilt']) > 0:
self.current_fit.put(self.s, 'tilt-corrected', self.get_PCA_parameters(
self.s, self.current_fit, tmin, tmax, 'tilt-corrected', calculation_type))
# calculate high level data
self.calculate_high_levels_data()
self.plot_high_levels_data()
self.on_menu_save_interpretation(event)
self.update_selection()
self.close_warning = True | python | def on_save_interpretation_button(self, event):
"""
on the save button the interpretation is saved to pmag_results_table
data in all coordinate systems
"""
if self.current_fit:
self.current_fit.saved = True
calculation_type = self.current_fit.get(self.COORDINATE_SYSTEM)[
'calculation_type']
tmin = str(self.tmin_box.GetValue())
tmax = str(self.tmax_box.GetValue())
self.current_fit.put(self.s, 'specimen', self.get_PCA_parameters(
self.s, self.current_fit, tmin, tmax, 'specimen', calculation_type))
if len(self.Data[self.s]['zijdblock_geo']) > 0:
self.current_fit.put(self.s, 'geographic', self.get_PCA_parameters(
self.s, self.current_fit, tmin, tmax, 'geographic', calculation_type))
if len(self.Data[self.s]['zijdblock_tilt']) > 0:
self.current_fit.put(self.s, 'tilt-corrected', self.get_PCA_parameters(
self.s, self.current_fit, tmin, tmax, 'tilt-corrected', calculation_type))
# calculate high level data
self.calculate_high_levels_data()
self.plot_high_levels_data()
self.on_menu_save_interpretation(event)
self.update_selection()
self.close_warning = True | on the save button the interpretation is saved to pmag_results_table
data in all coordinate systems | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L8426-L8453 |
PmagPy/PmagPy | programs/demag_gui.py | Demag_GUI.on_btn_add_fit | def on_btn_add_fit(self, event):
"""
add a new interpretation to the current specimen
Parameters
----------
event : the wx.ButtonEvent that triggered this function
Alters
------
pmag_results_data
"""
if self.auto_save.GetValue():
self.current_fit = self.add_fit(self.s, None, None, None, saved=True)
else:
self.current_fit = self.add_fit(self.s, None, None, None, saved=False)
self.generate_warning_text()
self.update_warning_box()
if self.ie_open:
self.ie.update_editor()
self.update_fit_boxes(True)
# Draw figures and add text
self.get_new_PCA_parameters(event) | python | def on_btn_add_fit(self, event):
"""
add a new interpretation to the current specimen
Parameters
----------
event : the wx.ButtonEvent that triggered this function
Alters
------
pmag_results_data
"""
if self.auto_save.GetValue():
self.current_fit = self.add_fit(self.s, None, None, None, saved=True)
else:
self.current_fit = self.add_fit(self.s, None, None, None, saved=False)
self.generate_warning_text()
self.update_warning_box()
if self.ie_open:
self.ie.update_editor()
self.update_fit_boxes(True)
# Draw figures and add text
self.get_new_PCA_parameters(event) | add a new interpretation to the current specimen
Parameters
----------
event : the wx.ButtonEvent that triggered this function
Alters
------
pmag_results_data | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L8455-L8479 |
PmagPy/PmagPy | programs/demag_gui.py | Demag_GUI.on_btn_delete_fit | 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 | 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) | removes the current interpretation
Parameters
----------
event : the wx.ButtonEvent that triggered this function | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L8481-L8489 |
PmagPy/PmagPy | programs/demag_gui.py | Demag_GUI.do_auto_save | 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 | 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) | Delete current fit if auto_save==False,
unless current fit has explicitly been saved. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L8516-L8524 |
PmagPy/PmagPy | programs/demag_gui.py | Demag_GUI.on_next_button | 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 | 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() | update figures and text when a next button is selected | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L8527-L8557 |
PmagPy/PmagPy | programs/chi_magic.py | main | def main():
"""
NAME
chi_magic.py
DESCRIPTION
plots magnetic susceptibility as a function of frequency and temperature and AC field
SYNTAX
chi_magic.py [command line options]
OPTIONS
-h prints help message and quits
-f FILE, specify measurements format file, default "measurements.txt"
-T IND, specify temperature step to plot -- NOT IMPLEMENTED
-e EXP, specify experiment name to plot
-fmt [svg,jpg,png,pdf] set figure format [default is svg]
-sav save figure and quit
"""
if "-h" in sys.argv:
print(main.__doc__)
return
infile = pmag.get_named_arg("-f", "measurements.txt")
dir_path = pmag.get_named_arg("-WD", ".")
infile = pmag.resolve_file_name(infile, dir_path)
fmt = pmag.get_named_arg("-fmt", "svg")
save_plots = False
interactive = True
if "-sav" in sys.argv:
interactive = False
save_plots = True
experiments = pmag.get_named_arg("-e", "")
ipmag.chi_magic(infile, dir_path, experiments, fmt, save_plots, interactive) | python | def main():
"""
NAME
chi_magic.py
DESCRIPTION
plots magnetic susceptibility as a function of frequency and temperature and AC field
SYNTAX
chi_magic.py [command line options]
OPTIONS
-h prints help message and quits
-f FILE, specify measurements format file, default "measurements.txt"
-T IND, specify temperature step to plot -- NOT IMPLEMENTED
-e EXP, specify experiment name to plot
-fmt [svg,jpg,png,pdf] set figure format [default is svg]
-sav save figure and quit
"""
if "-h" in sys.argv:
print(main.__doc__)
return
infile = pmag.get_named_arg("-f", "measurements.txt")
dir_path = pmag.get_named_arg("-WD", ".")
infile = pmag.resolve_file_name(infile, dir_path)
fmt = pmag.get_named_arg("-fmt", "svg")
save_plots = False
interactive = True
if "-sav" in sys.argv:
interactive = False
save_plots = True
experiments = pmag.get_named_arg("-e", "")
ipmag.chi_magic(infile, dir_path, experiments, fmt, save_plots, interactive) | NAME
chi_magic.py
DESCRIPTION
plots magnetic susceptibility as a function of frequency and temperature and AC field
SYNTAX
chi_magic.py [command line options]
OPTIONS
-h prints help message and quits
-f FILE, specify measurements format file, default "measurements.txt"
-T IND, specify temperature step to plot -- NOT IMPLEMENTED
-e EXP, specify experiment name to plot
-fmt [svg,jpg,png,pdf] set figure format [default is svg]
-sav save figure and quit | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/chi_magic.py#L10-L43 |
PmagPy/PmagPy | programs/watsons_f.py | main | 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 | 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)) | 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 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/watsons_f.py#L11-L83 |
PmagPy/PmagPy | programs/deprecated/thellier_magic_redo.py | main | def main():
"""
NAME
thellier_magic_redo.py
DESCRIPTION
Calculates paleointensity parameters for thellier-thellier type data using bounds
stored in the "redo" file
SYNTAX
thellier_magic_redo [command line options]
OPTIONS
-h prints help message
-usr USER: identify user, default is ""
-fcr CRIT, set criteria for grading
-f IN: specify input file, default is magic_measurements.txt
-fre REDO: specify redo file, default is "thellier_redo"
-F OUT: specify output file, default is thellier_specimens.txt
-leg: attaches "Recalculated from original measurements; supercedes published results. " to comment field
-CR PERC TYPE: apply a blanket cooling rate correction if none supplied in the er_samples.txt file
PERC should be a percentage of original (say reduce to 90%)
TYPE should be one of the following:
EG (for educated guess); PS (based on pilots); TRM (based on comparison of two TRMs)
-ANI: perform anisotropy correction
-fsa SAMPFILE: er_samples.txt file with cooling rate correction information, default is NO CORRECTION
-Fcr CRout: specify pmag_specimen format file for cooling rate corrected data
-fan ANIFILE: specify rmag_anisotropy format file, default is rmag_anisotropy.txt
-Fac ACout: specify pmag_specimen format file for anisotropy corrected data
default is AC_specimens.txt
-fnl NLTFILE: specify magic_measurments format file, default is magic_measurements.txt
-Fnl NLTout: specify pmag_specimen format file for non-linear trm corrected data
default is NLT_specimens.txt
-z use z component differenences for pTRM calculation
INPUT
a thellier_redo file is Specimen_name Tmin Tmax (where Tmin and Tmax are in Centigrade)
"""
dir_path='.'
critout=""
version_num=pmag.get_version()
field,first_save=-1,1
spec,recnum,start,end=0,0,0,0
crfrac=0
NltRecs,PmagSpecs,AniSpecRecs,NltSpecRecs,CRSpecs=[],[],[],[],[]
meas_file,pmag_file,mk_file="magic_measurements.txt","thellier_specimens.txt","thellier_redo"
anis_file="rmag_anisotropy.txt"
anisout,nltout="AC_specimens.txt","NLT_specimens.txt"
crout="CR_specimens.txt"
nlt_file=""
samp_file=""
comment,user="","unknown"
anis,nltrm=0,0
jackknife=0 # maybe in future can do jackknife
args=sys.argv
Zdiff=0
if '-WD' in args:
ind=args.index('-WD')
dir_path=args[ind+1]
if "-h" in args:
print(main.__doc__)
sys.exit()
if "-usr" in args:
ind=args.index("-usr")
user=sys.argv[ind+1]
if "-leg" in args: comment="Recalculated from original measurements; supercedes published results. "
cool=0
if "-CR" in args:
cool=1
ind=args.index("-CR")
crfrac=.01*float(sys.argv[ind+1])
crtype='DA-CR-'+sys.argv[ind+2]
if "-Fcr" in args:
ind=args.index("-Fcr")
crout=sys.argv[ind+1]
if "-f" in args:
ind=args.index("-f")
meas_file=sys.argv[ind+1]
if "-F" in args:
ind=args.index("-F")
pmag_file=sys.argv[ind+1]
if "-fre" in args:
ind=args.index("-fre")
mk_file=args[ind+1]
if "-fsa" in args:
ind=args.index("-fsa")
samp_file=dir_path+'/'+args[ind+1]
Samps,file_type=pmag.magic_read(samp_file)
SampCRs=pmag.get_dictitem(Samps,'cooling_rate_corr','','F') # get samples cooling rate corrections
cool=1
if file_type!='er_samples':
print('not a valid er_samples.txt file')
sys.exit()
#
#
if "-ANI" in args:
anis=1
ind=args.index("-ANI")
if "-Fac" in args:
ind=args.index("-Fac")
anisout=args[ind+1]
if "-fan" in args:
ind=args.index("-fan")
anis_file=args[ind+1]
#
if "-NLT" in args:
if "-Fnl" in args:
ind=args.index("-Fnl")
nltout=args[ind+1]
if "-fnl" in args:
ind=args.index("-fnl")
nlt_file=args[ind+1]
if "-z" in args: Zdiff=1
if '-fcr' in sys.argv:
ind=args.index("-fcr")
critout=sys.argv[ind+1]
#
# start reading in data:
#
meas_file=dir_path+"/"+meas_file
mk_file=dir_path+"/"+mk_file
accept=pmag.default_criteria(1)[0] # set criteria to none
if critout!="":
critout=dir_path+"/"+critout
crit_data,file_type=pmag.magic_read(critout)
if file_type!='pmag_criteria':
print('bad pmag_criteria file, using no acceptance criteria')
print("Acceptance criteria read in from ", critout)
for critrec in crit_data:
if 'sample_int_sigma_uT' in list(critrec.keys()): # accommodate Shaar's new criterion
critrec['sample_int_sigma']='%10.3e'%(eval(critrec['sample_int_sigma_uT'])*1e-6)
for key in list(critrec.keys()):
if key not in list(accept.keys()) and critrec[key]!='':
accept[key]=critrec[key]
meas_data,file_type=pmag.magic_read(meas_file)
if file_type != 'magic_measurements':
print(file_type)
print(file_type,"This is not a valid magic_measurements file ")
sys.exit()
try:
mk_f=open(mk_file,'r')
except:
print("Bad redo file")
sys.exit()
mkspec=[]
speclist=[]
for line in mk_f.readlines():
tmp=line.split()
mkspec.append(tmp)
speclist.append(tmp[0])
if anis==1:
anis_file=dir_path+"/"+anis_file
anis_data,file_type=pmag.magic_read(anis_file)
if file_type != 'rmag_anisotropy':
print(file_type)
print(file_type,"This is not a valid rmag_anisotropy file ")
sys.exit()
if nlt_file=="":
nlt_data=pmag.get_dictitem(meas_data,'magic_method_codes','LP-TRM','has') # look for trm acquisition data in the meas_data file
else:
nlt_file=dir_path+"/"+nlt_file
nlt_data,file_type=pmag.magic_read(nlt_file)
if len(nlt_data)>0:
nltrm=1
#
# sort the specimen names and step through one by one
#
sids=pmag.get_specs(meas_data)
#
print('Processing ',len(speclist),' specimens - please wait ')
while spec < len(speclist):
s=speclist[spec]
recnum=0
datablock=[]
PmagSpecRec={}
PmagSpecRec["er_analyst_mail_names"]=user
PmagSpecRec["er_citation_names"]="This study"
PmagSpecRec["magic_software_packages"]=version_num
methcodes,inst_code=[],""
#
# find the data from the meas_data file for this specimen
#
datablock=pmag.get_dictitem(meas_data,'er_specimen_name',s,'T')
datablock=pmag.get_dictitem(datablock,'magic_method_codes','LP-PI-TRM','has') #pick out the thellier experiment data
if len(datablock)>0:
for rec in datablock:
if "magic_instrument_codes" not in list(rec.keys()): rec["magic_instrument_codes"]="unknown"
#
# collect info for the PmagSpecRec dictionary
#
rec=datablock[0]
PmagSpecRec["er_specimen_name"]=s
PmagSpecRec["er_sample_name"]=rec["er_sample_name"]
PmagSpecRec["er_site_name"]=rec["er_site_name"]
PmagSpecRec["er_location_name"]=rec["er_location_name"]
PmagSpecRec["measurement_step_unit"]="K"
PmagSpecRec["specimen_correction"]='u'
if "er_expedition_name" in list(rec.keys()):PmagSpecRec["er_expedition_name"]=rec["er_expedition_name"]
if "magic_instrument_codes" not in list(rec.keys()):
PmagSpecRec["magic_instrument_codes"]="unknown"
else:
PmagSpecRec["magic_instrument_codes"]=rec["magic_instrument_codes"]
if "magic_experiment_name" not in list(rec.keys()):
rec["magic_experiment_name"]=""
else:
PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"]
meths=rec["magic_experiment_name"].split(":")
for meth in meths:
if meth.strip() not in methcodes and "LP-" in meth:methcodes.append(meth.strip())
#
# sort out the data into first_Z, first_I, ptrm_check, ptrm_tail
#
araiblock,field=pmag.sortarai(datablock,s,Zdiff)
first_Z=araiblock[0]
first_I=araiblock[1]
ptrm_check=araiblock[2]
ptrm_tail=araiblock[3]
if len(first_I)<3 or len(first_Z)<4:
spec+=1
print('skipping specimen ', s)
else:
#
# get start, end
#
for redospec in mkspec:
if redospec[0]==s:
b,e=float(redospec[1]),float(redospec[2])
break
if e > float(first_Z[-1][0]):e=float(first_Z[-1][0])
for recnum in range(len(first_Z)):
if first_Z[recnum][0]==b:start=recnum
if first_Z[recnum][0]==e:end=recnum
nsteps=end-start
if nsteps>2:
zijdblock,units=pmag.find_dmag_rec(s,meas_data)
pars,errcode=pmag.PintPars(datablock,araiblock,zijdblock,start,end,accept)
if 'specimen_scat' in list(pars.keys()): PmagSpecRec['specimen_scat']=pars['specimen_scat']
if 'specimen_frac' in list(pars.keys()): PmagSpecRec['specimen_frac']='%5.3f'%(pars['specimen_frac'])
if 'specimen_gmax' in list(pars.keys()): PmagSpecRec['specimen_gmax']='%5.3f'%(pars['specimen_gmax'])
pars['measurement_step_unit']=units
pars["specimen_lab_field_dc"]=field
pars["specimen_int"]=-1*field*pars["specimen_b"]
PmagSpecRec["measurement_step_min"]='%8.3e' % (pars["measurement_step_min"])
PmagSpecRec["measurement_step_max"]='%8.3e' % (pars["measurement_step_max"])
PmagSpecRec["specimen_int_n"]='%i'%(pars["specimen_int_n"])
PmagSpecRec["specimen_lab_field_dc"]='%8.3e'%(pars["specimen_lab_field_dc"])
PmagSpecRec["specimen_int"]='%9.4e '%(pars["specimen_int"])
PmagSpecRec["specimen_b"]='%5.3f '%(pars["specimen_b"])
PmagSpecRec["specimen_q"]='%5.1f '%(pars["specimen_q"])
PmagSpecRec["specimen_f"]='%5.3f '%(pars["specimen_f"])
PmagSpecRec["specimen_fvds"]='%5.3f'%(pars["specimen_fvds"])
PmagSpecRec["specimen_b_beta"]='%5.3f'%(pars["specimen_b_beta"])
PmagSpecRec["specimen_int_mad"]='%7.1f'%(pars["specimen_int_mad"])
PmagSpecRec["specimen_gamma"]='%7.1f'%(pars["specimen_gamma"])
if pars["magic_method_codes"]!="" and pars["magic_method_codes"] not in methcodes: methcodes.append(pars["magic_method_codes"])
PmagSpecRec["specimen_dec"]='%7.1f'%(pars["specimen_dec"])
PmagSpecRec["specimen_inc"]='%7.1f'%(pars["specimen_inc"])
PmagSpecRec["specimen_tilt_correction"]='-1'
PmagSpecRec["specimen_direction_type"]='l'
PmagSpecRec["direction_type"]='l' # this is redudant, but helpful - won't be imported
PmagSpecRec["specimen_dang"]='%7.1f '%(pars["specimen_dang"])
PmagSpecRec["specimen_drats"]='%7.1f '%(pars["specimen_drats"])
PmagSpecRec["specimen_drat"]='%7.1f '%(pars["specimen_drat"])
PmagSpecRec["specimen_int_ptrm_n"]='%i '%(pars["specimen_int_ptrm_n"])
PmagSpecRec["specimen_rsc"]='%6.4f '%(pars["specimen_rsc"])
PmagSpecRec["specimen_md"]='%i '%(int(pars["specimen_md"]))
if PmagSpecRec["specimen_md"]=='-1':PmagSpecRec["specimen_md"]=""
PmagSpecRec["specimen_b_sigma"]='%5.3f '%(pars["specimen_b_sigma"])
if "IE-TT" not in methcodes:methcodes.append("IE-TT")
methods=""
for meth in methcodes:
methods=methods+meth+":"
PmagSpecRec["magic_method_codes"]=methods.strip(':')
PmagSpecRec["magic_software_packages"]=version_num
PmagSpecRec["specimen_description"]=comment
if critout!="":
kill=pmag.grade(PmagSpecRec,accept,'specimen_int')
if len(kill)>0:
Grade='F' # fails
else:
Grade='A' # passes
PmagSpecRec["specimen_grade"]=Grade
else:
PmagSpecRec["specimen_grade"]="" # not graded
if nltrm==0 and anis==0 and cool!=0: # apply cooling rate correction
SCR=pmag.get_dictitem(SampCRs,'er_sample_name',PmagSpecRec['er_sample_name'],'T') # get this samples, cooling rate correction
CrSpecRec=pmag.cooling_rate(PmagSpecRec,SCR,crfrac,crtype)
if CrSpecRec['er_specimen_name']!='none':CrSpecs.append(CrSpecRec)
PmagSpecs.append(PmagSpecRec)
NltSpecRec=""
#
# check on non-linear TRM correction
#
if nltrm==1:
#
# find the data from the nlt_data list for this specimen
#
TRMs,Bs=[],[]
NltSpecRec=""
NltRecs=pmag.get_dictitem(nlt_data,'er_specimen_name',PmagSpecRec['er_specimen_name'],'has') # fish out all the NLT data for this specimen
if len(NltRecs) > 2:
for NltRec in NltRecs:
Bs.append(float(NltRec['treatment_dc_field']))
TRMs.append(float(NltRec['measurement_magn_moment']))
NLTpars=nlt.NLtrm(Bs,TRMs,float(PmagSpecRec['specimen_int']),float(PmagSpecRec['specimen_lab_field_dc']),0)
if NLTpars['banc']>0:
NltSpecRec={}
for key in list(PmagSpecRec.keys()):
NltSpecRec[key]=PmagSpecRec[key]
NltSpecRec['specimen_int']='%9.4e'%(NLTpars['banc'])
NltSpecRec['magic_method_codes']=PmagSpecRec["magic_method_codes"]+":DA-NL"
NltSpecRec["specimen_correction"]='c'
NltSpecRec['specimen_grade']=PmagSpecRec['specimen_grade']
NltSpecRec["magic_software_packages"]=version_num
print(NltSpecRec['er_specimen_name'], ' Banc= ',float(NLTpars['banc'])*1e6)
if anis==0 and cool!=0:
SCR=pmag.get_dictitem(SampCRs,'er_sample_name',NltSpecRec['er_sample_name'],'T') # get this samples, cooling rate correction
CrSpecRec=pmag.cooling_rate(NltSpecRec,SCR,crfrac,crtype)
if CrSpecRec['er_specimen_name']!='none':CrSpecs.append(CrSpecRec)
NltSpecRecs.append(NltSpecRec)
#
# check on anisotropy correction
if anis==1:
if NltSpecRec!="":
Spc=NltSpecRec
else: # find uncorrected data
Spc=PmagSpecRec
AniSpecs=pmag.get_dictitem(anis_data,'er_specimen_name',PmagSpecRec['er_specimen_name'],'T')
if len(AniSpecs)>0:
AniSpec=AniSpecs[0]
AniSpecRec=pmag.doaniscorr(Spc,AniSpec)
AniSpecRec['specimen_grade']=PmagSpecRec['specimen_grade']
AniSpecRec["magic_instrument_codes"]=PmagSpecRec['magic_instrument_codes']
AniSpecRec["specimen_correction"]='c'
AniSpecRec["magic_software_packages"]=version_num
if cool!=0:
SCR=pmag.get_dictitem(SampCRs,'er_sample_name',AniSpecRec['er_sample_name'],'T') # get this samples, cooling rate correction
CrSpecRec=pmag.cooling_rate(AniSpecRec,SCR,crfrac,crtype)
if CrSpecRec['er_specimen_name']!='none':CrSpecs.append(CrSpecRec)
AniSpecRecs.append(AniSpecRec)
elif anis==1:
AniSpecs=pmag.get_dictitem(anis_data,'er_specimen_name',PmagSpecRec['er_specimen_name'],'T')
if len(AniSpecs)>0:
AniSpec=AniSpecs[0]
AniSpecRec=pmag.doaniscorr(PmagSpecRec,AniSpec)
AniSpecRec['specimen_grade']=PmagSpecRec['specimen_grade']
AniSpecRec["magic_instrument_codes"]=PmagSpecRec["magic_instrument_codes"]
AniSpecRec["specimen_correction"]='c'
AniSpecRec["magic_software_packages"]=version_num
if crfrac!=0:
CrSpecRec={}
for key in list(AniSpecRec.keys()):CrSpecRec[key]=AniSpecRec[key]
inten=frac*float(CrSpecRec['specimen_int'])
CrSpecRec["specimen_int"]='%9.4e '%(inten) # adjust specimen intensity by cooling rate correction
CrSpecRec['magic_method_codes'] = CrSpecRec['magic_method_codes']+':DA-CR-'+crtype
CRSpecs.append(CrSpecRec)
AniSpecRecs.append(AniSpecRec)
spec +=1
else:
print("skipping ",s)
spec+=1
pmag_file=dir_path+'/'+pmag_file
pmag.magic_write(pmag_file,PmagSpecs,'pmag_specimens')
print('uncorrected thellier data saved in: ',pmag_file)
if anis==1 and len(AniSpecRecs)>0:
anisout=dir_path+'/'+anisout
pmag.magic_write(anisout,AniSpecRecs,'pmag_specimens')
print('anisotropy corrected data saved in: ',anisout)
if nltrm==1 and len(NltSpecRecs)>0:
nltout=dir_path+'/'+nltout
pmag.magic_write(nltout,NltSpecRecs,'pmag_specimens')
print('non-linear TRM corrected data saved in: ',nltout)
if crfrac!=0:
crout=dir_path+'/'+crout
pmag.magic_write(crout,CRSpecs,'pmag_specimens')
print('cooling rate corrected data saved in: ',crout) | python | def main():
"""
NAME
thellier_magic_redo.py
DESCRIPTION
Calculates paleointensity parameters for thellier-thellier type data using bounds
stored in the "redo" file
SYNTAX
thellier_magic_redo [command line options]
OPTIONS
-h prints help message
-usr USER: identify user, default is ""
-fcr CRIT, set criteria for grading
-f IN: specify input file, default is magic_measurements.txt
-fre REDO: specify redo file, default is "thellier_redo"
-F OUT: specify output file, default is thellier_specimens.txt
-leg: attaches "Recalculated from original measurements; supercedes published results. " to comment field
-CR PERC TYPE: apply a blanket cooling rate correction if none supplied in the er_samples.txt file
PERC should be a percentage of original (say reduce to 90%)
TYPE should be one of the following:
EG (for educated guess); PS (based on pilots); TRM (based on comparison of two TRMs)
-ANI: perform anisotropy correction
-fsa SAMPFILE: er_samples.txt file with cooling rate correction information, default is NO CORRECTION
-Fcr CRout: specify pmag_specimen format file for cooling rate corrected data
-fan ANIFILE: specify rmag_anisotropy format file, default is rmag_anisotropy.txt
-Fac ACout: specify pmag_specimen format file for anisotropy corrected data
default is AC_specimens.txt
-fnl NLTFILE: specify magic_measurments format file, default is magic_measurements.txt
-Fnl NLTout: specify pmag_specimen format file for non-linear trm corrected data
default is NLT_specimens.txt
-z use z component differenences for pTRM calculation
INPUT
a thellier_redo file is Specimen_name Tmin Tmax (where Tmin and Tmax are in Centigrade)
"""
dir_path='.'
critout=""
version_num=pmag.get_version()
field,first_save=-1,1
spec,recnum,start,end=0,0,0,0
crfrac=0
NltRecs,PmagSpecs,AniSpecRecs,NltSpecRecs,CRSpecs=[],[],[],[],[]
meas_file,pmag_file,mk_file="magic_measurements.txt","thellier_specimens.txt","thellier_redo"
anis_file="rmag_anisotropy.txt"
anisout,nltout="AC_specimens.txt","NLT_specimens.txt"
crout="CR_specimens.txt"
nlt_file=""
samp_file=""
comment,user="","unknown"
anis,nltrm=0,0
jackknife=0 # maybe in future can do jackknife
args=sys.argv
Zdiff=0
if '-WD' in args:
ind=args.index('-WD')
dir_path=args[ind+1]
if "-h" in args:
print(main.__doc__)
sys.exit()
if "-usr" in args:
ind=args.index("-usr")
user=sys.argv[ind+1]
if "-leg" in args: comment="Recalculated from original measurements; supercedes published results. "
cool=0
if "-CR" in args:
cool=1
ind=args.index("-CR")
crfrac=.01*float(sys.argv[ind+1])
crtype='DA-CR-'+sys.argv[ind+2]
if "-Fcr" in args:
ind=args.index("-Fcr")
crout=sys.argv[ind+1]
if "-f" in args:
ind=args.index("-f")
meas_file=sys.argv[ind+1]
if "-F" in args:
ind=args.index("-F")
pmag_file=sys.argv[ind+1]
if "-fre" in args:
ind=args.index("-fre")
mk_file=args[ind+1]
if "-fsa" in args:
ind=args.index("-fsa")
samp_file=dir_path+'/'+args[ind+1]
Samps,file_type=pmag.magic_read(samp_file)
SampCRs=pmag.get_dictitem(Samps,'cooling_rate_corr','','F') # get samples cooling rate corrections
cool=1
if file_type!='er_samples':
print('not a valid er_samples.txt file')
sys.exit()
#
#
if "-ANI" in args:
anis=1
ind=args.index("-ANI")
if "-Fac" in args:
ind=args.index("-Fac")
anisout=args[ind+1]
if "-fan" in args:
ind=args.index("-fan")
anis_file=args[ind+1]
#
if "-NLT" in args:
if "-Fnl" in args:
ind=args.index("-Fnl")
nltout=args[ind+1]
if "-fnl" in args:
ind=args.index("-fnl")
nlt_file=args[ind+1]
if "-z" in args: Zdiff=1
if '-fcr' in sys.argv:
ind=args.index("-fcr")
critout=sys.argv[ind+1]
#
# start reading in data:
#
meas_file=dir_path+"/"+meas_file
mk_file=dir_path+"/"+mk_file
accept=pmag.default_criteria(1)[0] # set criteria to none
if critout!="":
critout=dir_path+"/"+critout
crit_data,file_type=pmag.magic_read(critout)
if file_type!='pmag_criteria':
print('bad pmag_criteria file, using no acceptance criteria')
print("Acceptance criteria read in from ", critout)
for critrec in crit_data:
if 'sample_int_sigma_uT' in list(critrec.keys()): # accommodate Shaar's new criterion
critrec['sample_int_sigma']='%10.3e'%(eval(critrec['sample_int_sigma_uT'])*1e-6)
for key in list(critrec.keys()):
if key not in list(accept.keys()) and critrec[key]!='':
accept[key]=critrec[key]
meas_data,file_type=pmag.magic_read(meas_file)
if file_type != 'magic_measurements':
print(file_type)
print(file_type,"This is not a valid magic_measurements file ")
sys.exit()
try:
mk_f=open(mk_file,'r')
except:
print("Bad redo file")
sys.exit()
mkspec=[]
speclist=[]
for line in mk_f.readlines():
tmp=line.split()
mkspec.append(tmp)
speclist.append(tmp[0])
if anis==1:
anis_file=dir_path+"/"+anis_file
anis_data,file_type=pmag.magic_read(anis_file)
if file_type != 'rmag_anisotropy':
print(file_type)
print(file_type,"This is not a valid rmag_anisotropy file ")
sys.exit()
if nlt_file=="":
nlt_data=pmag.get_dictitem(meas_data,'magic_method_codes','LP-TRM','has') # look for trm acquisition data in the meas_data file
else:
nlt_file=dir_path+"/"+nlt_file
nlt_data,file_type=pmag.magic_read(nlt_file)
if len(nlt_data)>0:
nltrm=1
#
# sort the specimen names and step through one by one
#
sids=pmag.get_specs(meas_data)
#
print('Processing ',len(speclist),' specimens - please wait ')
while spec < len(speclist):
s=speclist[spec]
recnum=0
datablock=[]
PmagSpecRec={}
PmagSpecRec["er_analyst_mail_names"]=user
PmagSpecRec["er_citation_names"]="This study"
PmagSpecRec["magic_software_packages"]=version_num
methcodes,inst_code=[],""
#
# find the data from the meas_data file for this specimen
#
datablock=pmag.get_dictitem(meas_data,'er_specimen_name',s,'T')
datablock=pmag.get_dictitem(datablock,'magic_method_codes','LP-PI-TRM','has') #pick out the thellier experiment data
if len(datablock)>0:
for rec in datablock:
if "magic_instrument_codes" not in list(rec.keys()): rec["magic_instrument_codes"]="unknown"
#
# collect info for the PmagSpecRec dictionary
#
rec=datablock[0]
PmagSpecRec["er_specimen_name"]=s
PmagSpecRec["er_sample_name"]=rec["er_sample_name"]
PmagSpecRec["er_site_name"]=rec["er_site_name"]
PmagSpecRec["er_location_name"]=rec["er_location_name"]
PmagSpecRec["measurement_step_unit"]="K"
PmagSpecRec["specimen_correction"]='u'
if "er_expedition_name" in list(rec.keys()):PmagSpecRec["er_expedition_name"]=rec["er_expedition_name"]
if "magic_instrument_codes" not in list(rec.keys()):
PmagSpecRec["magic_instrument_codes"]="unknown"
else:
PmagSpecRec["magic_instrument_codes"]=rec["magic_instrument_codes"]
if "magic_experiment_name" not in list(rec.keys()):
rec["magic_experiment_name"]=""
else:
PmagSpecRec["magic_experiment_names"]=rec["magic_experiment_name"]
meths=rec["magic_experiment_name"].split(":")
for meth in meths:
if meth.strip() not in methcodes and "LP-" in meth:methcodes.append(meth.strip())
#
# sort out the data into first_Z, first_I, ptrm_check, ptrm_tail
#
araiblock,field=pmag.sortarai(datablock,s,Zdiff)
first_Z=araiblock[0]
first_I=araiblock[1]
ptrm_check=araiblock[2]
ptrm_tail=araiblock[3]
if len(first_I)<3 or len(first_Z)<4:
spec+=1
print('skipping specimen ', s)
else:
#
# get start, end
#
for redospec in mkspec:
if redospec[0]==s:
b,e=float(redospec[1]),float(redospec[2])
break
if e > float(first_Z[-1][0]):e=float(first_Z[-1][0])
for recnum in range(len(first_Z)):
if first_Z[recnum][0]==b:start=recnum
if first_Z[recnum][0]==e:end=recnum
nsteps=end-start
if nsteps>2:
zijdblock,units=pmag.find_dmag_rec(s,meas_data)
pars,errcode=pmag.PintPars(datablock,araiblock,zijdblock,start,end,accept)
if 'specimen_scat' in list(pars.keys()): PmagSpecRec['specimen_scat']=pars['specimen_scat']
if 'specimen_frac' in list(pars.keys()): PmagSpecRec['specimen_frac']='%5.3f'%(pars['specimen_frac'])
if 'specimen_gmax' in list(pars.keys()): PmagSpecRec['specimen_gmax']='%5.3f'%(pars['specimen_gmax'])
pars['measurement_step_unit']=units
pars["specimen_lab_field_dc"]=field
pars["specimen_int"]=-1*field*pars["specimen_b"]
PmagSpecRec["measurement_step_min"]='%8.3e' % (pars["measurement_step_min"])
PmagSpecRec["measurement_step_max"]='%8.3e' % (pars["measurement_step_max"])
PmagSpecRec["specimen_int_n"]='%i'%(pars["specimen_int_n"])
PmagSpecRec["specimen_lab_field_dc"]='%8.3e'%(pars["specimen_lab_field_dc"])
PmagSpecRec["specimen_int"]='%9.4e '%(pars["specimen_int"])
PmagSpecRec["specimen_b"]='%5.3f '%(pars["specimen_b"])
PmagSpecRec["specimen_q"]='%5.1f '%(pars["specimen_q"])
PmagSpecRec["specimen_f"]='%5.3f '%(pars["specimen_f"])
PmagSpecRec["specimen_fvds"]='%5.3f'%(pars["specimen_fvds"])
PmagSpecRec["specimen_b_beta"]='%5.3f'%(pars["specimen_b_beta"])
PmagSpecRec["specimen_int_mad"]='%7.1f'%(pars["specimen_int_mad"])
PmagSpecRec["specimen_gamma"]='%7.1f'%(pars["specimen_gamma"])
if pars["magic_method_codes"]!="" and pars["magic_method_codes"] not in methcodes: methcodes.append(pars["magic_method_codes"])
PmagSpecRec["specimen_dec"]='%7.1f'%(pars["specimen_dec"])
PmagSpecRec["specimen_inc"]='%7.1f'%(pars["specimen_inc"])
PmagSpecRec["specimen_tilt_correction"]='-1'
PmagSpecRec["specimen_direction_type"]='l'
PmagSpecRec["direction_type"]='l' # this is redudant, but helpful - won't be imported
PmagSpecRec["specimen_dang"]='%7.1f '%(pars["specimen_dang"])
PmagSpecRec["specimen_drats"]='%7.1f '%(pars["specimen_drats"])
PmagSpecRec["specimen_drat"]='%7.1f '%(pars["specimen_drat"])
PmagSpecRec["specimen_int_ptrm_n"]='%i '%(pars["specimen_int_ptrm_n"])
PmagSpecRec["specimen_rsc"]='%6.4f '%(pars["specimen_rsc"])
PmagSpecRec["specimen_md"]='%i '%(int(pars["specimen_md"]))
if PmagSpecRec["specimen_md"]=='-1':PmagSpecRec["specimen_md"]=""
PmagSpecRec["specimen_b_sigma"]='%5.3f '%(pars["specimen_b_sigma"])
if "IE-TT" not in methcodes:methcodes.append("IE-TT")
methods=""
for meth in methcodes:
methods=methods+meth+":"
PmagSpecRec["magic_method_codes"]=methods.strip(':')
PmagSpecRec["magic_software_packages"]=version_num
PmagSpecRec["specimen_description"]=comment
if critout!="":
kill=pmag.grade(PmagSpecRec,accept,'specimen_int')
if len(kill)>0:
Grade='F' # fails
else:
Grade='A' # passes
PmagSpecRec["specimen_grade"]=Grade
else:
PmagSpecRec["specimen_grade"]="" # not graded
if nltrm==0 and anis==0 and cool!=0: # apply cooling rate correction
SCR=pmag.get_dictitem(SampCRs,'er_sample_name',PmagSpecRec['er_sample_name'],'T') # get this samples, cooling rate correction
CrSpecRec=pmag.cooling_rate(PmagSpecRec,SCR,crfrac,crtype)
if CrSpecRec['er_specimen_name']!='none':CrSpecs.append(CrSpecRec)
PmagSpecs.append(PmagSpecRec)
NltSpecRec=""
#
# check on non-linear TRM correction
#
if nltrm==1:
#
# find the data from the nlt_data list for this specimen
#
TRMs,Bs=[],[]
NltSpecRec=""
NltRecs=pmag.get_dictitem(nlt_data,'er_specimen_name',PmagSpecRec['er_specimen_name'],'has') # fish out all the NLT data for this specimen
if len(NltRecs) > 2:
for NltRec in NltRecs:
Bs.append(float(NltRec['treatment_dc_field']))
TRMs.append(float(NltRec['measurement_magn_moment']))
NLTpars=nlt.NLtrm(Bs,TRMs,float(PmagSpecRec['specimen_int']),float(PmagSpecRec['specimen_lab_field_dc']),0)
if NLTpars['banc']>0:
NltSpecRec={}
for key in list(PmagSpecRec.keys()):
NltSpecRec[key]=PmagSpecRec[key]
NltSpecRec['specimen_int']='%9.4e'%(NLTpars['banc'])
NltSpecRec['magic_method_codes']=PmagSpecRec["magic_method_codes"]+":DA-NL"
NltSpecRec["specimen_correction"]='c'
NltSpecRec['specimen_grade']=PmagSpecRec['specimen_grade']
NltSpecRec["magic_software_packages"]=version_num
print(NltSpecRec['er_specimen_name'], ' Banc= ',float(NLTpars['banc'])*1e6)
if anis==0 and cool!=0:
SCR=pmag.get_dictitem(SampCRs,'er_sample_name',NltSpecRec['er_sample_name'],'T') # get this samples, cooling rate correction
CrSpecRec=pmag.cooling_rate(NltSpecRec,SCR,crfrac,crtype)
if CrSpecRec['er_specimen_name']!='none':CrSpecs.append(CrSpecRec)
NltSpecRecs.append(NltSpecRec)
#
# check on anisotropy correction
if anis==1:
if NltSpecRec!="":
Spc=NltSpecRec
else: # find uncorrected data
Spc=PmagSpecRec
AniSpecs=pmag.get_dictitem(anis_data,'er_specimen_name',PmagSpecRec['er_specimen_name'],'T')
if len(AniSpecs)>0:
AniSpec=AniSpecs[0]
AniSpecRec=pmag.doaniscorr(Spc,AniSpec)
AniSpecRec['specimen_grade']=PmagSpecRec['specimen_grade']
AniSpecRec["magic_instrument_codes"]=PmagSpecRec['magic_instrument_codes']
AniSpecRec["specimen_correction"]='c'
AniSpecRec["magic_software_packages"]=version_num
if cool!=0:
SCR=pmag.get_dictitem(SampCRs,'er_sample_name',AniSpecRec['er_sample_name'],'T') # get this samples, cooling rate correction
CrSpecRec=pmag.cooling_rate(AniSpecRec,SCR,crfrac,crtype)
if CrSpecRec['er_specimen_name']!='none':CrSpecs.append(CrSpecRec)
AniSpecRecs.append(AniSpecRec)
elif anis==1:
AniSpecs=pmag.get_dictitem(anis_data,'er_specimen_name',PmagSpecRec['er_specimen_name'],'T')
if len(AniSpecs)>0:
AniSpec=AniSpecs[0]
AniSpecRec=pmag.doaniscorr(PmagSpecRec,AniSpec)
AniSpecRec['specimen_grade']=PmagSpecRec['specimen_grade']
AniSpecRec["magic_instrument_codes"]=PmagSpecRec["magic_instrument_codes"]
AniSpecRec["specimen_correction"]='c'
AniSpecRec["magic_software_packages"]=version_num
if crfrac!=0:
CrSpecRec={}
for key in list(AniSpecRec.keys()):CrSpecRec[key]=AniSpecRec[key]
inten=frac*float(CrSpecRec['specimen_int'])
CrSpecRec["specimen_int"]='%9.4e '%(inten) # adjust specimen intensity by cooling rate correction
CrSpecRec['magic_method_codes'] = CrSpecRec['magic_method_codes']+':DA-CR-'+crtype
CRSpecs.append(CrSpecRec)
AniSpecRecs.append(AniSpecRec)
spec +=1
else:
print("skipping ",s)
spec+=1
pmag_file=dir_path+'/'+pmag_file
pmag.magic_write(pmag_file,PmagSpecs,'pmag_specimens')
print('uncorrected thellier data saved in: ',pmag_file)
if anis==1 and len(AniSpecRecs)>0:
anisout=dir_path+'/'+anisout
pmag.magic_write(anisout,AniSpecRecs,'pmag_specimens')
print('anisotropy corrected data saved in: ',anisout)
if nltrm==1 and len(NltSpecRecs)>0:
nltout=dir_path+'/'+nltout
pmag.magic_write(nltout,NltSpecRecs,'pmag_specimens')
print('non-linear TRM corrected data saved in: ',nltout)
if crfrac!=0:
crout=dir_path+'/'+crout
pmag.magic_write(crout,CRSpecs,'pmag_specimens')
print('cooling rate corrected data saved in: ',crout) | NAME
thellier_magic_redo.py
DESCRIPTION
Calculates paleointensity parameters for thellier-thellier type data using bounds
stored in the "redo" file
SYNTAX
thellier_magic_redo [command line options]
OPTIONS
-h prints help message
-usr USER: identify user, default is ""
-fcr CRIT, set criteria for grading
-f IN: specify input file, default is magic_measurements.txt
-fre REDO: specify redo file, default is "thellier_redo"
-F OUT: specify output file, default is thellier_specimens.txt
-leg: attaches "Recalculated from original measurements; supercedes published results. " to comment field
-CR PERC TYPE: apply a blanket cooling rate correction if none supplied in the er_samples.txt file
PERC should be a percentage of original (say reduce to 90%)
TYPE should be one of the following:
EG (for educated guess); PS (based on pilots); TRM (based on comparison of two TRMs)
-ANI: perform anisotropy correction
-fsa SAMPFILE: er_samples.txt file with cooling rate correction information, default is NO CORRECTION
-Fcr CRout: specify pmag_specimen format file for cooling rate corrected data
-fan ANIFILE: specify rmag_anisotropy format file, default is rmag_anisotropy.txt
-Fac ACout: specify pmag_specimen format file for anisotropy corrected data
default is AC_specimens.txt
-fnl NLTFILE: specify magic_measurments format file, default is magic_measurements.txt
-Fnl NLTout: specify pmag_specimen format file for non-linear trm corrected data
default is NLT_specimens.txt
-z use z component differenences for pTRM calculation
INPUT
a thellier_redo file is Specimen_name Tmin Tmax (where Tmin and Tmax are in Centigrade) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/deprecated/thellier_magic_redo.py#L8-L383 |
PmagPy/PmagPy | programs/conversion_scripts2/pmd_magic2.py | main | def main(command_line=True, **kwargs):
"""
NAME
pmd_magic.py
DESCRIPTION
converts PMD (Enkin) format files to magic_measurements format files
SYNTAX
pmd_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify input file, or
-F FILE: specify output file, default is magic_measurements.txt
-Fsa: specify er_samples format file for appending, default is new er_samples.txt
-spc NUM : specify number of characters to designate a specimen, default = 1
-loc LOCNAME : specify location/study name
-A: don't average replicate measurements
-ncn NCON: specify naming convention
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
-lat: Lattitude of site (if no value given assumes 0)
-lon: Longitude of site (if no value given assumes 0)
-mcd [SO-MAG,SO-SUN,SO-SIGHT...] supply how these samples were oriented
NB: all others you will have to customize your self
or e-mail [email protected] for help.
INPUT
PMD format files
"""
# initialize some stuff
noave=0
inst=""
samp_con,Z='1',""
missing=1
demag="N"
er_location_name="unknown"
citation='This study'
args=sys.argv
meth_code="LP-NO"
specnum=-1
MagRecs=[]
version_num=pmag.get_version()
Samps=[] # keeps track of sample orientations
DIspec=[]
MagFiles=[]
user=""
mag_file=""
dir_path='.'
ErSamps=[]
SampOuts=[]
samp_file = 'er_samples.txt'
meas_file = 'magic_measurements.txt'
#
# get command line arguments
#
if command_line:
if '-WD' in sys.argv:
ind = sys.argv.index('-WD')
dir_path=sys.argv[ind+1]
if '-ID' in sys.argv:
ind = sys.argv.index('-ID')
input_dir_path = sys.argv[ind+1]
else:
input_dir_path = dir_path
output_dir_path = dir_path
if "-h" in args:
print(main.__doc__)
return False
if '-F' in args:
ind=args.index("-F")
meas_file = args[ind+1]
if '-Fsa' in args:
ind = args.index("-Fsa")
samp_file = args[ind+1]
#try:
# open(samp_file,'r')
# ErSamps,file_type=pmag.magic_read(samp_file)
# print 'sample information will be appended to ', samp_file
#except:
# print samp_file,' not found: sample information will be stored in new er_samples.txt file'
# samp_file = output_dir_path+'/er_samples.txt'
if '-f' in args:
ind = args.index("-f")
mag_file= args[ind+1]
if "-spc" in args:
ind = args.index("-spc")
specnum = int(args[ind+1])
if "-ncn" in args:
ind=args.index("-ncn")
samp_con=sys.argv[ind+1]
if "-loc" in args:
ind=args.index("-loc")
er_location_name=args[ind+1]
if "-A" in args: noave=1
if "-mcd" in args:
ind=args.index("-mcd")
meth_code=args[ind+1]
if "-lat" in args:
ind=args.index("-lat")
site_lat=args[ind+1]
if "-lon" in args:
ind=args.index("-lon")
site_lon=args[ind+1]
if not command_line:
dir_path = kwargs.get('dir_path', '.')
input_dir_path = kwargs.get('input_dir_path', dir_path)
output_dir_path = dir_path
meas_file = kwargs.get('meas_file', 'magic_measurements.txt')
mag_file = kwargs.get('mag_file')
spec_file = kwargs.get('spec_file', 'er_specimens.txt')
samp_file = kwargs.get('samp_file', 'er_samples.txt')
site_file = kwargs.get('site_file', 'er_sites.txt')
site_lat = kwargs.get('site_lat', 0)
site_lon = kwargs.get('site_lon', 0)
specnum = kwargs.get('specnum', 0)
samp_con = kwargs.get('samp_con', '1')
er_location_name = kwargs.get('er_location_name', '')
noave = kwargs.get('noave', 0) # default (0) means DO average
meth_code = kwargs.get('meth_code', "LP-NO")
print(samp_con)
# format variables
mag_file = os.path.join(input_dir_path,mag_file)
meas_file = os.path.join(output_dir_path,meas_file)
spec_file = os.path.join(output_dir_path,spec_file)
samp_file = os.path.join(output_dir_path,samp_file)
site_file = os.path.join(output_dir_path,site_file)
if specnum!=0:specnum=-specnum
if "4" in samp_con:
if "-" not in samp_con:
print("naming convention option [4] must be in form 4-Z where Z is an integer")
return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
else:
Z=samp_con.split("-")[1]
samp_con="4"
if "7" in samp_con:
if "-" not in samp_con:
print("option [7] must be in form 7-Z where Z is an integer")
return False, "naming convention option [7] must be in form 7-Z where Z is an integer"
else:
Z=samp_con.split("-")[1]
samp_con="7"
# parse data
data=open(mag_file,'r').readlines() # read in data from file
comment=data[0]
line=data[1].strip()
line=line.replace("=","= ") # make finding orientations easier
rec=line.split() # read in sample orientation, etc.
er_specimen_name=rec[0]
ErSpecRec,ErSampRec,ErSiteRec={},{},{} # make a sample record
if specnum!=0:
er_sample_name=rec[0][:specnum]
else:
er_sample_name=rec[0]
if len(ErSamps)>0: # need to copy existing
for samp in ErSamps:
if samp['er_sample_name']==er_sample_name:
ErSampRec=samp # we'll ammend this one
else:
SampOuts.append(samp) # keep all the others
if int(samp_con)<6:
er_site_name=pmag.parse_site(er_sample_name,samp_con,Z)
else:
if 'er_site_name' in list(ErSampRec.keys()):er_site_name=ErSampREc['er_site_name']
if 'er_location_name' in list(ErSampRec.keys()):er_location_name=ErSampREc['er_location_name']
az_ind=rec.index('a=')+1
ErSampRec['er_sample_name']=er_sample_name
ErSampRec['er_sample_description']=comment
ErSampRec['sample_azimuth']=rec[az_ind]
dip_ind=rec.index('b=')+1
dip=-float(rec[dip_ind])
ErSampRec['sample_dip']='%7.1f'%(dip)
strike_ind=rec.index('s=')+1
ErSampRec['sample_bed_dip_direction']='%7.1f'%(float(rec[strike_ind])+90.)
bd_ind=rec.index('d=')+1
ErSampRec['sample_bed_dip']=rec[bd_ind]
v_ind=rec.index('v=')+1
vol=rec[v_ind][:-3]
date=rec[-2]
time=rec[-1]
ErSampRec['magic_method_codes']=meth_code
if 'er_location_name' not in list(ErSampRec.keys()):ErSampRec['er_location_name']=er_location_name
if 'er_site_name' not in list(ErSampRec.keys()):ErSampRec['er_site_name']=er_site_name
if 'er_citation_names' not in list(ErSampRec.keys()):ErSampRec['er_citation_names']='This study'
if 'magic_method_codes' not in list(ErSampRec.keys()):ErSampRec['magic_method_codes']='SO-NO'
ErSpecRec['er_specimen_name'] = er_specimen_name
ErSpecRec['er_sample_name'] = er_sample_name
ErSpecRec['er_site_name'] = er_site_name
ErSpecRec['er_location_name'] = er_location_name
ErSpecRec['er_citation_names']='This study'
ErSiteRec['er_site_name'] = er_site_name
ErSiteRec['er_location_name'] = er_location_name
ErSiteRec['er_citation_names']='This study'
ErSiteRec['site_lat'] = site_lat
ErSiteRec['site_lon']= site_lon
SpecOuts.append(ErSpecRec)
SampOuts.append(ErSampRec)
SiteOuts.append(ErSiteRec)
for k in range(3,len(data)): # read in data
line=data[k]
rec=line.split()
if len(rec)>1: # skip blank lines at bottom
MagRec={}
MagRec['measurement_description']='Date: '+date+' '+time
MagRec["er_citation_names"]="This study"
MagRec['er_location_name']=er_location_name
MagRec['er_site_name']=er_site_name
MagRec['er_sample_name']=er_sample_name
MagRec['magic_software_packages']=version_num
MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
MagRec["measurement_flag"]='g'
MagRec["measurement_standard"]='u'
MagRec["measurement_number"]='1'
MagRec["er_specimen_name"]=er_specimen_name
if rec[0]=='NRM':
meas_type="LT-NO"
elif rec[0][0]=='M' or rec[0][0]=='H':
meas_type="LT-AF-Z"
elif rec[0][0]=='T':
meas_type="LT-T-Z"
else:
print("measurement type unknown")
return False, "measurement type unknown"
X=[float(rec[1]),float(rec[2]),float(rec[3])]
Vec=pmag.cart2dir(X)
MagRec["measurement_magn_moment"]='%10.3e'% (Vec[2]) # Am^2
MagRec["measurement_magn_volume"]=rec[4] # A/m
MagRec["measurement_dec"]='%7.1f'%(Vec[0])
MagRec["measurement_inc"]='%7.1f'%(Vec[1])
MagRec["treatment_ac_field"]='0'
if meas_type!='LT-NO':
treat=float(rec[0][1:])
else:
treat=0
if meas_type=="LT-AF-Z":
MagRec["treatment_ac_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla
elif meas_type=="LT-T-Z":
MagRec["treatment_temp"]='%8.3e' % (treat+273.) # temp in kelvin
MagRec['magic_method_codes']=meas_type
MagRecs.append(MagRec)
MagOuts=pmag.measurements_methods(MagRecs,noave)
pmag.magic_write(meas_file,MagOuts,'magic_measurements')
print("results put in ",meas_file)
pmag.magic_write(samp_file,SpecOuts,'er_specimens')
pmag.magic_write(samp_file,SampOuts,'er_samples')
pmag.magic_write(samp_file,SiteOuts,'er_sites')
return True, meas_file | python | def main(command_line=True, **kwargs):
"""
NAME
pmd_magic.py
DESCRIPTION
converts PMD (Enkin) format files to magic_measurements format files
SYNTAX
pmd_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify input file, or
-F FILE: specify output file, default is magic_measurements.txt
-Fsa: specify er_samples format file for appending, default is new er_samples.txt
-spc NUM : specify number of characters to designate a specimen, default = 1
-loc LOCNAME : specify location/study name
-A: don't average replicate measurements
-ncn NCON: specify naming convention
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
-lat: Lattitude of site (if no value given assumes 0)
-lon: Longitude of site (if no value given assumes 0)
-mcd [SO-MAG,SO-SUN,SO-SIGHT...] supply how these samples were oriented
NB: all others you will have to customize your self
or e-mail [email protected] for help.
INPUT
PMD format files
"""
# initialize some stuff
noave=0
inst=""
samp_con,Z='1',""
missing=1
demag="N"
er_location_name="unknown"
citation='This study'
args=sys.argv
meth_code="LP-NO"
specnum=-1
MagRecs=[]
version_num=pmag.get_version()
Samps=[] # keeps track of sample orientations
DIspec=[]
MagFiles=[]
user=""
mag_file=""
dir_path='.'
ErSamps=[]
SampOuts=[]
samp_file = 'er_samples.txt'
meas_file = 'magic_measurements.txt'
#
# get command line arguments
#
if command_line:
if '-WD' in sys.argv:
ind = sys.argv.index('-WD')
dir_path=sys.argv[ind+1]
if '-ID' in sys.argv:
ind = sys.argv.index('-ID')
input_dir_path = sys.argv[ind+1]
else:
input_dir_path = dir_path
output_dir_path = dir_path
if "-h" in args:
print(main.__doc__)
return False
if '-F' in args:
ind=args.index("-F")
meas_file = args[ind+1]
if '-Fsa' in args:
ind = args.index("-Fsa")
samp_file = args[ind+1]
#try:
# open(samp_file,'r')
# ErSamps,file_type=pmag.magic_read(samp_file)
# print 'sample information will be appended to ', samp_file
#except:
# print samp_file,' not found: sample information will be stored in new er_samples.txt file'
# samp_file = output_dir_path+'/er_samples.txt'
if '-f' in args:
ind = args.index("-f")
mag_file= args[ind+1]
if "-spc" in args:
ind = args.index("-spc")
specnum = int(args[ind+1])
if "-ncn" in args:
ind=args.index("-ncn")
samp_con=sys.argv[ind+1]
if "-loc" in args:
ind=args.index("-loc")
er_location_name=args[ind+1]
if "-A" in args: noave=1
if "-mcd" in args:
ind=args.index("-mcd")
meth_code=args[ind+1]
if "-lat" in args:
ind=args.index("-lat")
site_lat=args[ind+1]
if "-lon" in args:
ind=args.index("-lon")
site_lon=args[ind+1]
if not command_line:
dir_path = kwargs.get('dir_path', '.')
input_dir_path = kwargs.get('input_dir_path', dir_path)
output_dir_path = dir_path
meas_file = kwargs.get('meas_file', 'magic_measurements.txt')
mag_file = kwargs.get('mag_file')
spec_file = kwargs.get('spec_file', 'er_specimens.txt')
samp_file = kwargs.get('samp_file', 'er_samples.txt')
site_file = kwargs.get('site_file', 'er_sites.txt')
site_lat = kwargs.get('site_lat', 0)
site_lon = kwargs.get('site_lon', 0)
specnum = kwargs.get('specnum', 0)
samp_con = kwargs.get('samp_con', '1')
er_location_name = kwargs.get('er_location_name', '')
noave = kwargs.get('noave', 0) # default (0) means DO average
meth_code = kwargs.get('meth_code', "LP-NO")
print(samp_con)
# format variables
mag_file = os.path.join(input_dir_path,mag_file)
meas_file = os.path.join(output_dir_path,meas_file)
spec_file = os.path.join(output_dir_path,spec_file)
samp_file = os.path.join(output_dir_path,samp_file)
site_file = os.path.join(output_dir_path,site_file)
if specnum!=0:specnum=-specnum
if "4" in samp_con:
if "-" not in samp_con:
print("naming convention option [4] must be in form 4-Z where Z is an integer")
return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
else:
Z=samp_con.split("-")[1]
samp_con="4"
if "7" in samp_con:
if "-" not in samp_con:
print("option [7] must be in form 7-Z where Z is an integer")
return False, "naming convention option [7] must be in form 7-Z where Z is an integer"
else:
Z=samp_con.split("-")[1]
samp_con="7"
# parse data
data=open(mag_file,'r').readlines() # read in data from file
comment=data[0]
line=data[1].strip()
line=line.replace("=","= ") # make finding orientations easier
rec=line.split() # read in sample orientation, etc.
er_specimen_name=rec[0]
ErSpecRec,ErSampRec,ErSiteRec={},{},{} # make a sample record
if specnum!=0:
er_sample_name=rec[0][:specnum]
else:
er_sample_name=rec[0]
if len(ErSamps)>0: # need to copy existing
for samp in ErSamps:
if samp['er_sample_name']==er_sample_name:
ErSampRec=samp # we'll ammend this one
else:
SampOuts.append(samp) # keep all the others
if int(samp_con)<6:
er_site_name=pmag.parse_site(er_sample_name,samp_con,Z)
else:
if 'er_site_name' in list(ErSampRec.keys()):er_site_name=ErSampREc['er_site_name']
if 'er_location_name' in list(ErSampRec.keys()):er_location_name=ErSampREc['er_location_name']
az_ind=rec.index('a=')+1
ErSampRec['er_sample_name']=er_sample_name
ErSampRec['er_sample_description']=comment
ErSampRec['sample_azimuth']=rec[az_ind]
dip_ind=rec.index('b=')+1
dip=-float(rec[dip_ind])
ErSampRec['sample_dip']='%7.1f'%(dip)
strike_ind=rec.index('s=')+1
ErSampRec['sample_bed_dip_direction']='%7.1f'%(float(rec[strike_ind])+90.)
bd_ind=rec.index('d=')+1
ErSampRec['sample_bed_dip']=rec[bd_ind]
v_ind=rec.index('v=')+1
vol=rec[v_ind][:-3]
date=rec[-2]
time=rec[-1]
ErSampRec['magic_method_codes']=meth_code
if 'er_location_name' not in list(ErSampRec.keys()):ErSampRec['er_location_name']=er_location_name
if 'er_site_name' not in list(ErSampRec.keys()):ErSampRec['er_site_name']=er_site_name
if 'er_citation_names' not in list(ErSampRec.keys()):ErSampRec['er_citation_names']='This study'
if 'magic_method_codes' not in list(ErSampRec.keys()):ErSampRec['magic_method_codes']='SO-NO'
ErSpecRec['er_specimen_name'] = er_specimen_name
ErSpecRec['er_sample_name'] = er_sample_name
ErSpecRec['er_site_name'] = er_site_name
ErSpecRec['er_location_name'] = er_location_name
ErSpecRec['er_citation_names']='This study'
ErSiteRec['er_site_name'] = er_site_name
ErSiteRec['er_location_name'] = er_location_name
ErSiteRec['er_citation_names']='This study'
ErSiteRec['site_lat'] = site_lat
ErSiteRec['site_lon']= site_lon
SpecOuts.append(ErSpecRec)
SampOuts.append(ErSampRec)
SiteOuts.append(ErSiteRec)
for k in range(3,len(data)): # read in data
line=data[k]
rec=line.split()
if len(rec)>1: # skip blank lines at bottom
MagRec={}
MagRec['measurement_description']='Date: '+date+' '+time
MagRec["er_citation_names"]="This study"
MagRec['er_location_name']=er_location_name
MagRec['er_site_name']=er_site_name
MagRec['er_sample_name']=er_sample_name
MagRec['magic_software_packages']=version_num
MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin
MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin
MagRec["measurement_flag"]='g'
MagRec["measurement_standard"]='u'
MagRec["measurement_number"]='1'
MagRec["er_specimen_name"]=er_specimen_name
if rec[0]=='NRM':
meas_type="LT-NO"
elif rec[0][0]=='M' or rec[0][0]=='H':
meas_type="LT-AF-Z"
elif rec[0][0]=='T':
meas_type="LT-T-Z"
else:
print("measurement type unknown")
return False, "measurement type unknown"
X=[float(rec[1]),float(rec[2]),float(rec[3])]
Vec=pmag.cart2dir(X)
MagRec["measurement_magn_moment"]='%10.3e'% (Vec[2]) # Am^2
MagRec["measurement_magn_volume"]=rec[4] # A/m
MagRec["measurement_dec"]='%7.1f'%(Vec[0])
MagRec["measurement_inc"]='%7.1f'%(Vec[1])
MagRec["treatment_ac_field"]='0'
if meas_type!='LT-NO':
treat=float(rec[0][1:])
else:
treat=0
if meas_type=="LT-AF-Z":
MagRec["treatment_ac_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla
elif meas_type=="LT-T-Z":
MagRec["treatment_temp"]='%8.3e' % (treat+273.) # temp in kelvin
MagRec['magic_method_codes']=meas_type
MagRecs.append(MagRec)
MagOuts=pmag.measurements_methods(MagRecs,noave)
pmag.magic_write(meas_file,MagOuts,'magic_measurements')
print("results put in ",meas_file)
pmag.magic_write(samp_file,SpecOuts,'er_specimens')
pmag.magic_write(samp_file,SampOuts,'er_samples')
pmag.magic_write(samp_file,SiteOuts,'er_sites')
return True, meas_file | NAME
pmd_magic.py
DESCRIPTION
converts PMD (Enkin) format files to magic_measurements format files
SYNTAX
pmd_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify input file, or
-F FILE: specify output file, default is magic_measurements.txt
-Fsa: specify er_samples format file for appending, default is new er_samples.txt
-spc NUM : specify number of characters to designate a specimen, default = 1
-loc LOCNAME : specify location/study name
-A: don't average replicate measurements
-ncn NCON: specify naming convention
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
-lat: Lattitude of site (if no value given assumes 0)
-lon: Longitude of site (if no value given assumes 0)
-mcd [SO-MAG,SO-SUN,SO-SIGHT...] supply how these samples were oriented
NB: all others you will have to customize your self
or e-mail [email protected] for help.
INPUT
PMD format files | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/conversion_scripts2/pmd_magic2.py#L7-L276 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | York_Regression | def York_Regression(x_segment, y_segment, x_mean, y_mean, n, lab_dc_field, steps_Arai):
"""
input: x_segment, y_segment, x_mean, y_mean, n, lab_dc_field, steps_Arai
output: x_err, y_err, x_tag, y_tag, b, b_sigma, specimen_b_beta, y_intercept,
x_intercept, x_prime, y_prime, delta_x_prime, delta_y_prime, f_Coe,
g_Coe, g_lim, specimen_q, specimen_w, count_IZ, count_ZI, B_lab, B_anc,
B_anc_sigma, specimen_int
"""
x_err = x_segment - x_mean
y_err = y_segment - y_mean
york_b = -1* numpy.sqrt(old_div(sum(y_err**2), sum(x_err**2)) ) # averaged slope
b = numpy.sign(sum(x_err * y_err)) * numpy.std(y_segment, ddof=1)/numpy.std(x_segment, ddof=1) # ddof is degrees of freedom
if b == 0:
york_b = 1e-10
else:
york_b = b
york_sigma= numpy.sqrt( old_div((2 * sum(y_err**2) - 2*york_b* sum(x_err*y_err)), ( (n-2) * sum(x_err**2) )) )
if york_sigma == 0: # prevent divide by zero
york_sigma = 1e-10
beta_Coe = abs(old_div(york_sigma,york_b))
# y_T is the intercept of the extrepolated line
# through the center of mass (see figure 7 in Coe (1978))
y_T = y_mean - (york_b* x_mean)
x_T = old_div((-1 * y_T), york_b) # x intercept
# # calculate the extrarpolated data points for f and fvds
x_tag = old_div((y_segment - y_T ), york_b) # returns array of y points minus the y intercept, divided by slope
y_tag = york_b*x_segment + y_T
# intersect of the dashed square and the horizontal dahed line next to delta-y-5 in figure 7, Coe (1978)
x_prime = old_div((x_segment+x_tag), 2)
y_prime = old_div((y_segment+y_tag), 2)
delta_x_prime = abs(max(x_prime) - min(x_prime)) # TRM length of best fit line
delta_y_prime = abs(max(y_prime) - min(y_prime)) # NRM length of best fit line
f_Coe = old_div(delta_y_prime, abs(y_T))
if delta_y_prime:
g_Coe = 1 - (old_div(sum((y_prime[:-1]-y_prime[1:])**2), delta_y_prime ** 2)) # gap factor
else:
g_Coe = float('nan')
g_lim = old_div((float(n) - 2), (float(n) - 1))
q_Coe = abs(york_b)*f_Coe*g_Coe/york_sigma
w_Coe = old_div(q_Coe, numpy.sqrt(n - 2))
count_IZ = steps_Arai.count('IZ')
count_ZI = steps_Arai.count('ZI')
B_lab = lab_dc_field * 1e6
B_anc = abs(york_b) * B_lab # in microtesla
B_anc_sigma = york_sigma * B_lab
specimen_int = -1* lab_dc_field * york_b # in tesla
specimen_int_sigma = york_sigma * lab_dc_field
return {'x_err': x_err, 'y_err': y_err, 'x_tag': x_tag, 'y_tag': y_tag,
'specimen_b': york_b, 'specimen_b_sigma': york_sigma, 'specimen_b_beta': beta_Coe,
'y_int': y_T, 'x_int': x_T, 'x_prime': x_prime, 'y_prime': y_prime,
'delta_x_prime': delta_x_prime, 'delta_y_prime': delta_y_prime, 'specimen_f': f_Coe,
'specimen_g': g_Coe, 'specimen_g_lim': g_lim, 'specimen_q': q_Coe, 'specimen_w': w_Coe,
'count_IZ': count_IZ, 'count_ZI': count_ZI, 'B_lab': B_lab, 'B_anc': B_anc,
'B_anc_sigma': B_anc_sigma, 'specimen_int': specimen_int, 'specimen_int_sigma': specimen_int_sigma} | python | def York_Regression(x_segment, y_segment, x_mean, y_mean, n, lab_dc_field, steps_Arai):
"""
input: x_segment, y_segment, x_mean, y_mean, n, lab_dc_field, steps_Arai
output: x_err, y_err, x_tag, y_tag, b, b_sigma, specimen_b_beta, y_intercept,
x_intercept, x_prime, y_prime, delta_x_prime, delta_y_prime, f_Coe,
g_Coe, g_lim, specimen_q, specimen_w, count_IZ, count_ZI, B_lab, B_anc,
B_anc_sigma, specimen_int
"""
x_err = x_segment - x_mean
y_err = y_segment - y_mean
york_b = -1* numpy.sqrt(old_div(sum(y_err**2), sum(x_err**2)) ) # averaged slope
b = numpy.sign(sum(x_err * y_err)) * numpy.std(y_segment, ddof=1)/numpy.std(x_segment, ddof=1) # ddof is degrees of freedom
if b == 0:
york_b = 1e-10
else:
york_b = b
york_sigma= numpy.sqrt( old_div((2 * sum(y_err**2) - 2*york_b* sum(x_err*y_err)), ( (n-2) * sum(x_err**2) )) )
if york_sigma == 0: # prevent divide by zero
york_sigma = 1e-10
beta_Coe = abs(old_div(york_sigma,york_b))
# y_T is the intercept of the extrepolated line
# through the center of mass (see figure 7 in Coe (1978))
y_T = y_mean - (york_b* x_mean)
x_T = old_div((-1 * y_T), york_b) # x intercept
# # calculate the extrarpolated data points for f and fvds
x_tag = old_div((y_segment - y_T ), york_b) # returns array of y points minus the y intercept, divided by slope
y_tag = york_b*x_segment + y_T
# intersect of the dashed square and the horizontal dahed line next to delta-y-5 in figure 7, Coe (1978)
x_prime = old_div((x_segment+x_tag), 2)
y_prime = old_div((y_segment+y_tag), 2)
delta_x_prime = abs(max(x_prime) - min(x_prime)) # TRM length of best fit line
delta_y_prime = abs(max(y_prime) - min(y_prime)) # NRM length of best fit line
f_Coe = old_div(delta_y_prime, abs(y_T))
if delta_y_prime:
g_Coe = 1 - (old_div(sum((y_prime[:-1]-y_prime[1:])**2), delta_y_prime ** 2)) # gap factor
else:
g_Coe = float('nan')
g_lim = old_div((float(n) - 2), (float(n) - 1))
q_Coe = abs(york_b)*f_Coe*g_Coe/york_sigma
w_Coe = old_div(q_Coe, numpy.sqrt(n - 2))
count_IZ = steps_Arai.count('IZ')
count_ZI = steps_Arai.count('ZI')
B_lab = lab_dc_field * 1e6
B_anc = abs(york_b) * B_lab # in microtesla
B_anc_sigma = york_sigma * B_lab
specimen_int = -1* lab_dc_field * york_b # in tesla
specimen_int_sigma = york_sigma * lab_dc_field
return {'x_err': x_err, 'y_err': y_err, 'x_tag': x_tag, 'y_tag': y_tag,
'specimen_b': york_b, 'specimen_b_sigma': york_sigma, 'specimen_b_beta': beta_Coe,
'y_int': y_T, 'x_int': x_T, 'x_prime': x_prime, 'y_prime': y_prime,
'delta_x_prime': delta_x_prime, 'delta_y_prime': delta_y_prime, 'specimen_f': f_Coe,
'specimen_g': g_Coe, 'specimen_g_lim': g_lim, 'specimen_q': q_Coe, 'specimen_w': w_Coe,
'count_IZ': count_IZ, 'count_ZI': count_ZI, 'B_lab': B_lab, 'B_anc': B_anc,
'B_anc_sigma': B_anc_sigma, 'specimen_int': specimen_int, 'specimen_int_sigma': specimen_int_sigma} | input: x_segment, y_segment, x_mean, y_mean, n, lab_dc_field, steps_Arai
output: x_err, y_err, x_tag, y_tag, b, b_sigma, specimen_b_beta, y_intercept,
x_intercept, x_prime, y_prime, delta_x_prime, delta_y_prime, f_Coe,
g_Coe, g_lim, specimen_q, specimen_w, count_IZ, count_ZI, B_lab, B_anc,
B_anc_sigma, specimen_int | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L10-L68 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_vds | def get_vds(zdata, delta_y_prime, start, end):
"""takes zdata array: [[1, 2, 3], [3, 4, 5]],
delta_y_prime: 1, start value, and end value. gets vds and f_vds, etc. """
vector_diffs = []
for k in range(len(zdata)-1): # gets diff between two vectors
vector_diffs.append(numpy.sqrt(sum((numpy.array(zdata[k+1]) - numpy.array(zdata[k]))**2) ))
last_vector = numpy.linalg.norm(zdata[-1])
vector_diffs.append(last_vector)
vds = sum(vector_diffs)
f_vds = abs(old_div(delta_y_prime, vds)) # fvds varies, because of delta_y_prime, but vds does not.
vector_diffs_segment = vector_diffs[start:end]
partial_vds = sum(vector_diffs_segment)
max_diff = max(vector_diffs_segment)
GAP_MAX = old_div(max_diff, partial_vds) #
return {'max_diff': max_diff, 'vector_diffs': vector_diffs, 'specimen_vds': vds,
'specimen_fvds': f_vds, 'vector_diffs_segment': vector_diffs_segment,
'partial_vds': partial_vds, 'GAP-MAX': GAP_MAX} | python | def get_vds(zdata, delta_y_prime, start, end):
"""takes zdata array: [[1, 2, 3], [3, 4, 5]],
delta_y_prime: 1, start value, and end value. gets vds and f_vds, etc. """
vector_diffs = []
for k in range(len(zdata)-1): # gets diff between two vectors
vector_diffs.append(numpy.sqrt(sum((numpy.array(zdata[k+1]) - numpy.array(zdata[k]))**2) ))
last_vector = numpy.linalg.norm(zdata[-1])
vector_diffs.append(last_vector)
vds = sum(vector_diffs)
f_vds = abs(old_div(delta_y_prime, vds)) # fvds varies, because of delta_y_prime, but vds does not.
vector_diffs_segment = vector_diffs[start:end]
partial_vds = sum(vector_diffs_segment)
max_diff = max(vector_diffs_segment)
GAP_MAX = old_div(max_diff, partial_vds) #
return {'max_diff': max_diff, 'vector_diffs': vector_diffs, 'specimen_vds': vds,
'specimen_fvds': f_vds, 'vector_diffs_segment': vector_diffs_segment,
'partial_vds': partial_vds, 'GAP-MAX': GAP_MAX} | takes zdata array: [[1, 2, 3], [3, 4, 5]],
delta_y_prime: 1, start value, and end value. gets vds and f_vds, etc. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L70-L86 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_SCAT_box | def get_SCAT_box(slope, x_mean, y_mean, beta_threshold = .1):
"""
takes in data and returns information about SCAT box:
the largest possible x_value, the largest possible y_value,
and functions for the two bounding lines of the box
"""
# if beta_threshold is -999, that means null
if beta_threshold == -999:
beta_threshold = .1
slope_err_threshold = abs(slope) * beta_threshold
x, y = x_mean, y_mean
# get lines that pass through mass center, with opposite slope
slope1 = slope + (2* slope_err_threshold)
line1_y_int = y - (slope1 * x)
line1_x_int = -1 * (old_div(line1_y_int, slope1))
slope2 = slope - (2 * slope_err_threshold)
line2_y_int = y - (slope2 * x)
line2_x_int = -1 * (old_div(line2_y_int, slope2))
# l1_y_int and l2_x_int form the bottom line of the box
# l2_y_int and l1_x_int form the top line of the box
# print "_diagonal line1:", (0, line2_y_int), (line2_x_int, 0), (x, y)
# print "_diagonal line2:", (0, line1_y_int), (line1_x_int, 0), (x, y)
# print "_bottom line:", [(0, line1_y_int), (line2_x_int, 0)]
# print "_top line:", [(0, line2_y_int), (line1_x_int, 0)]
low_bound = [(0, line1_y_int), (line2_x_int, 0)]
high_bound = [(0, line2_y_int), (line1_x_int, 0)]
x_max = high_bound[1][0]#
y_max = high_bound[0][1]
# function for low_bound
low_slope = old_div((low_bound[0][1] - low_bound[1][1]), (low_bound[0][0] - low_bound[1][0])) #
low_y_int = low_bound[0][1]
def low_bound(x):
y = low_slope * x + low_y_int
return y
# function for high_bound
high_slope = old_div((high_bound[0][1] - high_bound[1][1]), (high_bound[0][0] - high_bound[1][0])) # y_0-y_1/x_0-x_1
high_y_int = high_bound[0][1]
def high_bound(x):
y = high_slope * x + high_y_int
return y
high_line = [high_y_int, high_slope]
low_line = [low_y_int, low_slope]
return low_bound, high_bound, x_max, y_max, low_line, high_line | python | def get_SCAT_box(slope, x_mean, y_mean, beta_threshold = .1):
"""
takes in data and returns information about SCAT box:
the largest possible x_value, the largest possible y_value,
and functions for the two bounding lines of the box
"""
# if beta_threshold is -999, that means null
if beta_threshold == -999:
beta_threshold = .1
slope_err_threshold = abs(slope) * beta_threshold
x, y = x_mean, y_mean
# get lines that pass through mass center, with opposite slope
slope1 = slope + (2* slope_err_threshold)
line1_y_int = y - (slope1 * x)
line1_x_int = -1 * (old_div(line1_y_int, slope1))
slope2 = slope - (2 * slope_err_threshold)
line2_y_int = y - (slope2 * x)
line2_x_int = -1 * (old_div(line2_y_int, slope2))
# l1_y_int and l2_x_int form the bottom line of the box
# l2_y_int and l1_x_int form the top line of the box
# print "_diagonal line1:", (0, line2_y_int), (line2_x_int, 0), (x, y)
# print "_diagonal line2:", (0, line1_y_int), (line1_x_int, 0), (x, y)
# print "_bottom line:", [(0, line1_y_int), (line2_x_int, 0)]
# print "_top line:", [(0, line2_y_int), (line1_x_int, 0)]
low_bound = [(0, line1_y_int), (line2_x_int, 0)]
high_bound = [(0, line2_y_int), (line1_x_int, 0)]
x_max = high_bound[1][0]#
y_max = high_bound[0][1]
# function for low_bound
low_slope = old_div((low_bound[0][1] - low_bound[1][1]), (low_bound[0][0] - low_bound[1][0])) #
low_y_int = low_bound[0][1]
def low_bound(x):
y = low_slope * x + low_y_int
return y
# function for high_bound
high_slope = old_div((high_bound[0][1] - high_bound[1][1]), (high_bound[0][0] - high_bound[1][0])) # y_0-y_1/x_0-x_1
high_y_int = high_bound[0][1]
def high_bound(x):
y = high_slope * x + high_y_int
return y
high_line = [high_y_int, high_slope]
low_line = [low_y_int, low_slope]
return low_bound, high_bound, x_max, y_max, low_line, high_line | takes in data and returns information about SCAT box:
the largest possible x_value, the largest possible y_value,
and functions for the two bounding lines of the box | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L88-L130 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | in_SCAT_box | 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 | 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 | determines if a particular point falls within a box | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L132-L145 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_SCAT_points | 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 | 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 | returns relevant points for a SCAT test | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L147-L181 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_SCAT | 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 | 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 | runs SCAT test and returns boolean | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L183-L194 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | fancy_SCAT | 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 | 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 | runs SCAT test and returns 'Pass' or 'Fail' | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L196-L216 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_FRAC | def get_FRAC(vds, vector_diffs_segment):
"""
input: vds, vector_diffs_segment
output: FRAC
"""
for num in vector_diffs_segment:
if num < 0:
raise ValueError('vector diffs should not be negative')
if vds == 0:
raise ValueError('attempting to divide by zero. vds should be a positive number')
FRAC = old_div(sum(vector_diffs_segment), vds)
return FRAC | python | def get_FRAC(vds, vector_diffs_segment):
"""
input: vds, vector_diffs_segment
output: FRAC
"""
for num in vector_diffs_segment:
if num < 0:
raise ValueError('vector diffs should not be negative')
if vds == 0:
raise ValueError('attempting to divide by zero. vds should be a positive number')
FRAC = old_div(sum(vector_diffs_segment), vds)
return FRAC | input: vds, vector_diffs_segment
output: FRAC | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L219-L230 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_R_corr2 | def get_R_corr2(x_avg, y_avg, x_segment, y_segment): #
"""
input: x_avg, y_avg, x_segment, y_segment
output: R_corr2
"""
xd = x_segment - x_avg # detrend x_segment
yd = y_segment - y_avg # detrend y_segment
if sum(xd**2) * sum(yd**2) == 0: # prevent divide by zero error
return float('nan')
rcorr = old_div(sum((xd * yd))**2, (sum(xd**2) * sum(yd**2)))
return rcorr | python | def get_R_corr2(x_avg, y_avg, x_segment, y_segment): #
"""
input: x_avg, y_avg, x_segment, y_segment
output: R_corr2
"""
xd = x_segment - x_avg # detrend x_segment
yd = y_segment - y_avg # detrend y_segment
if sum(xd**2) * sum(yd**2) == 0: # prevent divide by zero error
return float('nan')
rcorr = old_div(sum((xd * yd))**2, (sum(xd**2) * sum(yd**2)))
return rcorr | input: x_avg, y_avg, x_segment, y_segment
output: R_corr2 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L232-L242 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_R_det2 | 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 | 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') | takes in an array of y values, the mean of those values, and the array of y prime values.
returns R_det2 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L244-L255 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_b_wiggle | 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 | 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 | returns instantaneous slope from the ratio of NRM lost to TRM gained at the ith step | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L257-L263 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_Z | def get_Z(x_segment, y_segment, x_int, y_int, slope):
"""
input: x_segment, y_segment, x_int, y_int, slope
output: Z (Arai plot zigzag parameter)
"""
Z = 0
first_time = True
for num, x in enumerate(x_segment):
b_wiggle = get_b_wiggle(x, y_segment[num], y_int)
z = old_div((x * abs(b_wiggle - abs(slope)) ), abs(x_int))
Z += z
first_time = False
return Z | python | def get_Z(x_segment, y_segment, x_int, y_int, slope):
"""
input: x_segment, y_segment, x_int, y_int, slope
output: Z (Arai plot zigzag parameter)
"""
Z = 0
first_time = True
for num, x in enumerate(x_segment):
b_wiggle = get_b_wiggle(x, y_segment[num], y_int)
z = old_div((x * abs(b_wiggle - abs(slope)) ), abs(x_int))
Z += z
first_time = False
return Z | input: x_segment, y_segment, x_int, y_int, slope
output: Z (Arai plot zigzag parameter) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L265-L277 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_Zstar | def get_Zstar(x_segment, y_segment, x_int, y_int, slope, n):
"""
input: x_segment, y_segment, x_int, y_int, slope, n
output: Z* (Arai plot zigzag parameter (alternate))
"""
total = 0
first_time = True
for num, x in enumerate(x_segment):
b_wiggle = get_b_wiggle(x, y_segment[num], y_int)
result = 100 * ( old_div((x * abs(b_wiggle - abs(slope)) ), abs(y_int)) )
total += result
first_time = False
Zstar = (old_div(1., (n - 1.))) * total
return Zstar | python | def get_Zstar(x_segment, y_segment, x_int, y_int, slope, n):
"""
input: x_segment, y_segment, x_int, y_int, slope, n
output: Z* (Arai plot zigzag parameter (alternate))
"""
total = 0
first_time = True
for num, x in enumerate(x_segment):
b_wiggle = get_b_wiggle(x, y_segment[num], y_int)
result = 100 * ( old_div((x * abs(b_wiggle - abs(slope)) ), abs(y_int)) )
total += result
first_time = False
Zstar = (old_div(1., (n - 1.))) * total
return Zstar | input: x_segment, y_segment, x_int, y_int, slope, n
output: Z* (Arai plot zigzag parameter (alternate)) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L279-L292 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_normed_points | def get_normed_points(point_array, norm): # good to go
"""
input: point_array, norm
output: normed array
"""
norm = float(norm)
#floated_array = []
#for p in point_array: # need to make sure each point is a float
#floated_array.append(float(p))
points = old_div(numpy.array(point_array), norm)
return points | python | def get_normed_points(point_array, norm): # good to go
"""
input: point_array, norm
output: normed array
"""
norm = float(norm)
#floated_array = []
#for p in point_array: # need to make sure each point is a float
#floated_array.append(float(p))
points = old_div(numpy.array(point_array), norm)
return points | input: point_array, norm
output: normed array | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L297-L307 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | get_xy_array | def get_xy_array(x_segment, y_segment):
"""
input: x_segment, y_segment
output: xy_segment, ( format: [(x[0], y[0]), (x[1], y[1])]
"""
xy_array = []
for num, x in enumerate(x_segment):
xy_array.append((x, y_segment[num]))
return xy_array | python | def get_xy_array(x_segment, y_segment):
"""
input: x_segment, y_segment
output: xy_segment, ( format: [(x[0], y[0]), (x[1], y[1])]
"""
xy_array = []
for num, x in enumerate(x_segment):
xy_array.append((x, y_segment[num]))
return xy_array | input: x_segment, y_segment
output: xy_segment, ( format: [(x[0], y[0]), (x[1], y[1])] | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L309-L317 |
PmagPy/PmagPy | programs/stats.py | main | 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 | 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 + " ") | 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) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/stats.py#L7-L65 |
PmagPy/PmagPy | programs/magic_select.py | main | 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 | 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') | 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 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/magic_select.py#L7-L93 |
PmagPy/PmagPy | programs/aniso_magic2.py | main | def main():
"""
NAME
aniso_magic.py
DESCRIPTION
plots anisotropy data with either bootstrap or hext ellipses
SYNTAX
aniso_magic.py [-h] [command line options]
OPTIONS
-h plots help message and quits
-usr USER: set the user name
-f AFILE, specify rmag_anisotropy formatted file for input
-F RFILE, specify rmag_results formatted file for output
-x Hext [1963] and bootstrap
-B DON'T do bootstrap, do Hext
-par Tauxe [1998] parametric bootstrap
-v plot bootstrap eigenvectors instead of ellipses
-sit plot by site instead of entire file
-crd [s,g,t] coordinate system, default is specimen (g=geographic, t=tilt corrected)
-P don't make any plots - just make rmag_results table
-sav don't make the rmag_results table - just save all the plots
-fmt [svg, jpg, eps] format for output images, pdf default
-gtc DEC INC dec,inc of pole to great circle [down(up) in green (cyan)
-d Vi DEC INC; Vi (1,2,3) to compare to direction DEC INC
-n N; specifies the number of bootstraps - default is 1000
DEFAULTS
AFILE: rmag_anisotropy.txt
RFILE: rmag_results.txt
plot bootstrap ellipses of Constable & Tauxe [1987]
NOTES
minor axis: circles
major axis: triangles
principal axis: squares
directions are plotted on the lower hemisphere
for bootstrapped eigenvector components: Xs: blue, Ys: red, Zs: black
"""
#
dir_path = "."
version_num = pmag.get_version()
verbose = pmagplotlib.verbose
args = sys.argv
ipar, ihext, ivec, iboot, imeas, isite, iplot, vec = 0, 0, 0, 1, 1, 0, 1, 0
hpars, bpars, PDir = [], [], []
CS, crd = '-1', 's'
nb = 1000
fmt = 'pdf'
ResRecs = []
orlist = []
outfile, comp, Dir, gtcirc, PDir = 'rmag_results.txt', 0, [], 0, []
infile = 'rmag_anisotropy.txt'
if "-h" in args:
print(main.__doc__)
sys.exit()
if '-WD' in args:
ind = args.index('-WD')
dir_path = args[ind+1]
if '-n' in args:
ind = args.index('-n')
nb = int(args[ind+1])
if '-usr' in args:
ind = args.index('-usr')
user = args[ind+1]
else:
user = ""
if '-B' in args:
iboot, ihext = 0, 1
if '-par' in args:
ipar = 1
if '-x' in args:
ihext = 1
if '-v' in args:
ivec = 1
if '-sit' in args:
isite = 1
if '-P' in args:
iplot = 0
if '-f' in args:
ind = args.index('-f')
infile = args[ind+1]
if '-F' in args:
ind = args.index('-F')
outfile = args[ind+1]
if '-crd' in sys.argv:
ind = sys.argv.index('-crd')
crd = sys.argv[ind+1]
if crd == 'g':
CS = '0'
if crd == 't':
CS = '100'
if '-fmt' in args:
ind = args.index('-fmt')
fmt = args[ind+1]
if '-sav' in args:
plots = 1
verbose = 0
else:
plots = 0
if '-gtc' in args:
ind = args.index('-gtc')
d, i = float(args[ind+1]), float(args[ind+2])
PDir.append(d)
PDir.append(i)
if '-d' in args:
comp = 1
ind = args.index('-d')
vec = int(args[ind+1])-1
Dir = [float(args[ind+2]), float(args[ind+3])]
#
# set up plots
#
if infile[0] != '/':
infile = dir_path+'/'+infile
if outfile[0] != '/':
outfile = dir_path+'/'+outfile
ANIS = {}
initcdf, inittcdf = 0, 0
ANIS['data'], ANIS['conf'] = 1, 2
if iboot == 1:
ANIS['tcdf'] = 3
if iplot == 1:
inittcdf = 1
pmagplotlib.plot_init(ANIS['tcdf'], 5, 5)
if comp == 1 and iplot == 1:
initcdf = 1
ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6
pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5)
pmagplotlib.plot_init(ANIS['vycdf'], 5, 5)
pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5)
if iplot == 1:
pmagplotlib.plot_init(ANIS['conf'], 5, 5)
pmagplotlib.plot_init(ANIS['data'], 5, 5)
# read in the data
data, ifiletype = pmag.magic_read(infile)
for rec in data: # find all the orientation systems
if 'anisotropy_tilt_correction' not in rec.keys():
rec['anisotropy_tilt_correction'] = '-1'
if rec['anisotropy_tilt_correction'] not in orlist:
orlist.append(rec['anisotropy_tilt_correction'])
if CS not in orlist:
if len(orlist) > 0:
CS = orlist[0]
else:
CS = '-1'
if CS == '-1':
crd = 's'
if CS == '0':
crd = 'g'
if CS == '100':
crd = 't'
if verbose:
print("desired coordinate system not available, using available: ", crd)
if isite == 1:
sitelist = []
for rec in data:
if rec['er_site_name'] not in sitelist:
sitelist.append(rec['er_site_name'])
sitelist.sort()
plt = len(sitelist)
else:
plt = 1
k = 0
while k < plt:
site = ""
sdata, Ss = [], [] # list of S format data
Locs, Sites, Samples, Specimens, Cits = [], [], [], [], []
if isite == 0:
sdata = data
else:
site = sitelist[k]
for rec in data:
if rec['er_site_name'] == site:
sdata.append(rec)
anitypes = []
csrecs = pmag.get_dictitem(
sdata, 'anisotropy_tilt_correction', CS, 'T')
for rec in csrecs:
if rec['anisotropy_type'] not in anitypes:
anitypes.append(rec['anisotropy_type'])
if rec['er_location_name'] not in Locs:
Locs.append(rec['er_location_name'])
if rec['er_site_name'] not in Sites:
Sites.append(rec['er_site_name'])
if rec['er_sample_name'] not in Samples:
Samples.append(rec['er_sample_name'])
if rec['er_specimen_name'] not in Specimens:
Specimens.append(rec['er_specimen_name'])
if rec['er_citation_names'] not in Cits:
Cits.append(rec['er_citation_names'])
s = []
s.append(float(rec["anisotropy_s1"]))
s.append(float(rec["anisotropy_s2"]))
s.append(float(rec["anisotropy_s3"]))
s.append(float(rec["anisotropy_s4"]))
s.append(float(rec["anisotropy_s5"]))
s.append(float(rec["anisotropy_s6"]))
if s[0] <= 1.0:
Ss.append(s) # protect against crap
# tau,Vdirs=pmag.doseigs(s)
ResRec = {}
ResRec['er_location_names'] = rec['er_location_name']
ResRec['er_citation_names'] = rec['er_citation_names']
ResRec['er_site_names'] = rec['er_site_name']
ResRec['er_sample_names'] = rec['er_sample_name']
ResRec['er_specimen_names'] = rec['er_specimen_name']
ResRec['rmag_result_name'] = rec['er_specimen_name'] + \
":"+rec['anisotropy_type']
ResRec["er_analyst_mail_names"] = user
ResRec["tilt_correction"] = CS
ResRec["anisotropy_type"] = rec['anisotropy_type']
if "anisotropy_n" not in rec.keys():
rec["anisotropy_n"] = "6"
if "anisotropy_sigma" not in rec.keys():
rec["anisotropy_sigma"] = "0"
fpars = pmag.dohext(
int(rec["anisotropy_n"])-6, float(rec["anisotropy_sigma"]), s)
ResRec["anisotropy_v1_dec"] = '%7.1f' % (fpars['v1_dec'])
ResRec["anisotropy_v2_dec"] = '%7.1f' % (fpars['v2_dec'])
ResRec["anisotropy_v3_dec"] = '%7.1f' % (fpars['v3_dec'])
ResRec["anisotropy_v1_inc"] = '%7.1f' % (fpars['v1_inc'])
ResRec["anisotropy_v2_inc"] = '%7.1f' % (fpars['v2_inc'])
ResRec["anisotropy_v3_inc"] = '%7.1f' % (fpars['v3_inc'])
ResRec["anisotropy_t1"] = '%10.8f' % (fpars['t1'])
ResRec["anisotropy_t2"] = '%10.8f' % (fpars['t2'])
ResRec["anisotropy_t3"] = '%10.8f' % (fpars['t3'])
ResRec["anisotropy_ftest"] = '%10.3f' % (fpars['F'])
ResRec["anisotropy_ftest12"] = '%10.3f' % (fpars['F12'])
ResRec["anisotropy_ftest23"] = '%10.3f' % (fpars['F23'])
ResRec["result_description"] = 'F_crit: ' + \
fpars['F_crit']+'; F12,F23_crit: '+fpars['F12_crit']
ResRec['anisotropy_type'] = pmag.makelist(anitypes)
ResRecs.append(ResRec)
if len(Ss) > 1:
if pmagplotlib.isServer:
title = "LO:_"+ResRec['er_location_names'] + \
'_SI:_'+site+'_SA:__SP:__CO:_'+crd
else:
title = ResRec['er_location_names']
if site:
title += "_{}".format(site)
title += '_{}'.format(crd)
ResRec['er_location_names'] = pmag.makelist(Locs)
bpars, hpars = pmagplotlib.plot_anis(
ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb)
if len(PDir) > 0:
pmagplotlib.plot_circ(ANIS['data'], PDir, 90., 'g')
pmagplotlib.plot_circ(ANIS['conf'], PDir, 90., 'g')
if verbose and plots == 0:
pmagplotlib.draw_figs(ANIS)
ResRec['er_location_names'] = pmag.makelist(Locs)
if plots == 1:
save(ANIS, fmt, title)
ResRec = {}
ResRec['er_citation_names'] = pmag.makelist(Cits)
ResRec['er_location_names'] = pmag.makelist(Locs)
ResRec['er_site_names'] = pmag.makelist(Sites)
ResRec['er_sample_names'] = pmag.makelist(Samples)
ResRec['er_specimen_names'] = pmag.makelist(Specimens)
ResRec['rmag_result_name'] = pmag.makelist(
Sites)+":"+pmag.makelist(anitypes)
ResRec['anisotropy_type'] = pmag.makelist(anitypes)
ResRec["er_analyst_mail_names"] = user
ResRec["tilt_correction"] = CS
if isite == "0":
ResRec['result_description'] = "Study average using coordinate system: " + CS
if isite == "1":
ResRec['result_description'] = "Site average using coordinate system: " + CS
if hpars != [] and ihext == 1:
HextRec = {}
for key in ResRec.keys():
HextRec[key] = ResRec[key] # copy over stuff
HextRec["anisotropy_v1_dec"] = '%7.1f' % (hpars["v1_dec"])
HextRec["anisotropy_v2_dec"] = '%7.1f' % (hpars["v2_dec"])
HextRec["anisotropy_v3_dec"] = '%7.1f' % (hpars["v3_dec"])
HextRec["anisotropy_v1_inc"] = '%7.1f' % (hpars["v1_inc"])
HextRec["anisotropy_v2_inc"] = '%7.1f' % (hpars["v2_inc"])
HextRec["anisotropy_v3_inc"] = '%7.1f' % (hpars["v3_inc"])
HextRec["anisotropy_t1"] = '%10.8f' % (hpars["t1"])
HextRec["anisotropy_t2"] = '%10.8f' % (hpars["t2"])
HextRec["anisotropy_t3"] = '%10.8f' % (hpars["t3"])
HextRec["anisotropy_hext_F"] = '%7.1f ' % (hpars["F"])
HextRec["anisotropy_hext_F12"] = '%7.1f ' % (hpars["F12"])
HextRec["anisotropy_hext_F23"] = '%7.1f ' % (hpars["F23"])
HextRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % (
hpars["e12"])
HextRec["anisotropy_v1_eta_dec"] = '%7.1f ' % (hpars["v2_dec"])
HextRec["anisotropy_v1_eta_inc"] = '%7.1f ' % (hpars["v2_inc"])
HextRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % (
hpars["e13"])
HextRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % (
hpars["v3_dec"])
HextRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % (
hpars["v3_inc"])
HextRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % (
hpars["e12"])
HextRec["anisotropy_v2_eta_dec"] = '%7.1f ' % (hpars["v1_dec"])
HextRec["anisotropy_v2_eta_inc"] = '%7.1f ' % (hpars["v1_inc"])
HextRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % (
hpars["e23"])
HextRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % (
hpars["v3_dec"])
HextRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % (
hpars["v3_inc"])
HextRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % (
hpars["e12"])
HextRec["anisotropy_v3_eta_dec"] = '%7.1f ' % (hpars["v1_dec"])
HextRec["anisotropy_v3_eta_inc"] = '%7.1f ' % (hpars["v1_inc"])
HextRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % (
hpars["e23"])
HextRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % (
hpars["v2_dec"])
HextRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % (
hpars["v2_inc"])
HextRec["magic_method_codes"] = 'LP-AN:AE-H'
if verbose:
print("Hext Statistics: ")
print(
" tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I")
print(HextRec["anisotropy_t1"], HextRec["anisotropy_v1_dec"], HextRec["anisotropy_v1_inc"], HextRec["anisotropy_v1_eta_semi_angle"], HextRec["anisotropy_v1_eta_dec"],
HextRec["anisotropy_v1_eta_inc"], HextRec["anisotropy_v1_zeta_semi_angle"], HextRec["anisotropy_v1_zeta_dec"], HextRec["anisotropy_v1_zeta_inc"])
print(HextRec["anisotropy_t2"], HextRec["anisotropy_v2_dec"], HextRec["anisotropy_v2_inc"], HextRec["anisotropy_v2_eta_semi_angle"], HextRec["anisotropy_v2_eta_dec"],
HextRec["anisotropy_v2_eta_inc"], HextRec["anisotropy_v2_zeta_semi_angle"], HextRec["anisotropy_v2_zeta_dec"], HextRec["anisotropy_v2_zeta_inc"])
print(HextRec["anisotropy_t3"], HextRec["anisotropy_v3_dec"], HextRec["anisotropy_v3_inc"], HextRec["anisotropy_v3_eta_semi_angle"], HextRec["anisotropy_v3_eta_dec"],
HextRec["anisotropy_v3_eta_inc"], HextRec["anisotropy_v3_zeta_semi_angle"], HextRec["anisotropy_v3_zeta_dec"], HextRec["anisotropy_v3_zeta_inc"])
HextRec['magic_software_packages'] = version_num
ResRecs.append(HextRec)
if bpars != []:
BootRec = {}
for key in ResRec.keys():
BootRec[key] = ResRec[key] # copy over stuff
BootRec["anisotropy_v1_dec"] = '%7.1f' % (bpars["v1_dec"])
BootRec["anisotropy_v2_dec"] = '%7.1f' % (bpars["v2_dec"])
BootRec["anisotropy_v3_dec"] = '%7.1f' % (bpars["v3_dec"])
BootRec["anisotropy_v1_inc"] = '%7.1f' % (bpars["v1_inc"])
BootRec["anisotropy_v2_inc"] = '%7.1f' % (bpars["v2_inc"])
BootRec["anisotropy_v3_inc"] = '%7.1f' % (bpars["v3_inc"])
BootRec["anisotropy_t1"] = '%10.8f' % (bpars["t1"])
BootRec["anisotropy_t2"] = '%10.8f' % (bpars["t2"])
BootRec["anisotropy_t3"] = '%10.8f' % (bpars["t3"])
BootRec["anisotropy_v1_eta_inc"] = '%7.1f ' % (
bpars["v1_eta_inc"])
BootRec["anisotropy_v1_eta_dec"] = '%7.1f ' % (
bpars["v1_eta_dec"])
BootRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % (
bpars["v1_eta"])
BootRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % (
bpars["v1_zeta_inc"])
BootRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % (
bpars["v1_zeta_dec"])
BootRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % (
bpars["v1_zeta"])
BootRec["anisotropy_v2_eta_inc"] = '%7.1f ' % (
bpars["v2_eta_inc"])
BootRec["anisotropy_v2_eta_dec"] = '%7.1f ' % (
bpars["v2_eta_dec"])
BootRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % (
bpars["v2_eta"])
BootRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % (
bpars["v2_zeta_inc"])
BootRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % (
bpars["v2_zeta_dec"])
BootRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % (
bpars["v2_zeta"])
BootRec["anisotropy_v3_eta_inc"] = '%7.1f ' % (
bpars["v3_eta_inc"])
BootRec["anisotropy_v3_eta_dec"] = '%7.1f ' % (
bpars["v3_eta_dec"])
BootRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % (
bpars["v3_eta"])
BootRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % (
bpars["v3_zeta_inc"])
BootRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % (
bpars["v3_zeta_dec"])
BootRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % (
bpars["v3_zeta"])
BootRec["anisotropy_hext_F"] = ''
BootRec["anisotropy_hext_F12"] = ''
BootRec["anisotropy_hext_F23"] = ''
# regular bootstrap
BootRec["magic_method_codes"] = 'LP-AN:AE-H:AE-BS'
if ipar == 1:
# parametric bootstrap
BootRec["magic_method_codes"] = 'LP-AN:AE-H:AE-BS-P'
if verbose:
print("Boostrap Statistics: ")
print(
" tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I")
print(BootRec["anisotropy_t1"], BootRec["anisotropy_v1_dec"], BootRec["anisotropy_v1_inc"], BootRec["anisotropy_v1_eta_semi_angle"], BootRec["anisotropy_v1_eta_dec"],
BootRec["anisotropy_v1_eta_inc"], BootRec["anisotropy_v1_zeta_semi_angle"], BootRec["anisotropy_v1_zeta_dec"], BootRec["anisotropy_v1_zeta_inc"])
print(BootRec["anisotropy_t2"], BootRec["anisotropy_v2_dec"], BootRec["anisotropy_v2_inc"], BootRec["anisotropy_v2_eta_semi_angle"], BootRec["anisotropy_v2_eta_dec"],
BootRec["anisotropy_v2_eta_inc"], BootRec["anisotropy_v2_zeta_semi_angle"], BootRec["anisotropy_v2_zeta_dec"], BootRec["anisotropy_v2_zeta_inc"])
print(BootRec["anisotropy_t3"], BootRec["anisotropy_v3_dec"], BootRec["anisotropy_v3_inc"], BootRec["anisotropy_v3_eta_semi_angle"], BootRec["anisotropy_v3_eta_dec"],
BootRec["anisotropy_v3_eta_inc"], BootRec["anisotropy_v3_zeta_semi_angle"], BootRec["anisotropy_v3_zeta_dec"], BootRec["anisotropy_v3_zeta_inc"])
BootRec['magic_software_packages'] = version_num
ResRecs.append(BootRec)
k += 1
goon = 1
while goon == 1 and iplot == 1 and verbose:
if iboot == 1:
print("compare with [d]irection ")
print(
" plot [g]reat circle, change [c]oord. system, change [e]llipse calculation, s[a]ve plots, [q]uit ")
if isite == 1:
print(" [p]revious, [s]ite, [q]uit, <return> for next ")
ans = input("")
if ans == "q":
sys.exit()
if ans == "e":
iboot, ipar, ihext, ivec = 1, 0, 0, 0
e = input("Do Hext Statistics 1/[0]: ")
if e == "1":
ihext = 1
e = input("Suppress bootstrap 1/[0]: ")
if e == "1":
iboot = 0
if iboot == 1:
e = input("Parametric bootstrap 1/[0]: ")
if e == "1":
ipar = 1
e = input("Plot bootstrap eigenvectors: 1/[0]: ")
if e == "1":
ivec = 1
if iplot == 1:
if inittcdf == 0:
ANIS['tcdf'] = 3
pmagplotlib.plot_init(ANIS['tcdf'], 5, 5)
inittcdf = 1
bpars, hpars = pmagplotlib.plot_anis(
ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb)
if verbose and plots == 0:
pmagplotlib.draw_figs(ANIS)
if ans == "c":
print("Current Coordinate system is: ")
if CS == '-1':
print(" Specimen")
if CS == '0':
print(" Geographic")
if CS == '100':
print(" Tilt corrected")
key = input(
" Enter desired coordinate system: [s]pecimen, [g]eographic, [t]ilt corrected ")
if key == 's':
CS = '-1'
if key == 'g':
CS = '0'
if key == 't':
CS = '100'
if CS not in orlist:
if len(orlist) > 0:
CS = orlist[0]
else:
CS = '-1'
if CS == '-1':
crd = 's'
if CS == '0':
crd = 'g'
if CS == '100':
crd = 't'
print(
"desired coordinate system not available, using available: ", crd)
k -= 1
goon = 0
if ans == "":
if isite == 1:
goon = 0
else:
print("Good bye ")
sys.exit()
if ans == 'd':
if initcdf == 0:
initcdf = 1
ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6
pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5)
pmagplotlib.plot_init(ANIS['vycdf'], 5, 5)
pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5)
Dir, comp = [], 1
print("""
Input: Vi D I to compare eigenvector Vi with direction D/I
where Vi=1: principal
Vi=2: major
Vi=3: minor
D= declination of comparison direction
I= inclination of comparison direction""")
con = 1
while con == 1:
try:
vdi = input("Vi D I: ").split()
vec = int(vdi[0])-1
Dir = [float(vdi[1]), float(vdi[2])]
con = 0
except IndexError:
print(" Incorrect entry, try again ")
bpars, hpars = pmagplotlib.plot_anis(
ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb)
Dir, comp = [], 0
if ans == 'g':
con, cnt = 1, 0
while con == 1:
try:
print(
" Input: input pole to great circle ( D I) to plot a great circle: ")
di = input(" D I: ").split()
PDir.append(float(di[0]))
PDir.append(float(di[1]))
con = 0
except:
cnt += 1
if cnt < 10:
print(
" enter the dec and inc of the pole on one line ")
else:
print(
"ummm - you are doing something wrong - i give up")
sys.exit()
pmagplotlib.plot_circ(ANIS['data'], PDir, 90., 'g')
pmagplotlib.plot_circ(ANIS['conf'], PDir, 90., 'g')
if verbose and plots == 0:
pmagplotlib.draw_figs(ANIS)
if ans == "p":
k -= 2
goon = 0
if ans == "q":
k = plt
goon = 0
if ans == "s":
keepon = 1
site = input(" print site or part of site desired: ")
while keepon == 1:
try:
k = sitelist.index(site)
keepon = 0
except:
tmplist = []
for qq in range(len(sitelist)):
if site in sitelist[qq]:
tmplist.append(sitelist[qq])
print(site, " not found, but this was: ")
print(tmplist)
site = input('Select one or try again\n ')
k = sitelist.index(site)
goon, ans = 0, ""
if ans == "a":
locs = pmag.makelist(Locs)
if pmagplotlib.isServer: # use server plot naming convention
title = "LO:_"+locs+'_SI:__'+'_SA:__SP:__CO:_'+crd
else: # use more readable plot naming convention
title = "{}_{}".format(locs, crd)
save(ANIS, fmt, title)
goon = 0
else:
if verbose:
print('skipping plot - not enough data points')
k += 1
# put rmag_results stuff here
if len(ResRecs) > 0:
ResOut, keylist = pmag.fillkeys(ResRecs)
pmag.magic_write(outfile, ResOut, 'rmag_results')
if verbose:
print(" Good bye ") | python | def main():
"""
NAME
aniso_magic.py
DESCRIPTION
plots anisotropy data with either bootstrap or hext ellipses
SYNTAX
aniso_magic.py [-h] [command line options]
OPTIONS
-h plots help message and quits
-usr USER: set the user name
-f AFILE, specify rmag_anisotropy formatted file for input
-F RFILE, specify rmag_results formatted file for output
-x Hext [1963] and bootstrap
-B DON'T do bootstrap, do Hext
-par Tauxe [1998] parametric bootstrap
-v plot bootstrap eigenvectors instead of ellipses
-sit plot by site instead of entire file
-crd [s,g,t] coordinate system, default is specimen (g=geographic, t=tilt corrected)
-P don't make any plots - just make rmag_results table
-sav don't make the rmag_results table - just save all the plots
-fmt [svg, jpg, eps] format for output images, pdf default
-gtc DEC INC dec,inc of pole to great circle [down(up) in green (cyan)
-d Vi DEC INC; Vi (1,2,3) to compare to direction DEC INC
-n N; specifies the number of bootstraps - default is 1000
DEFAULTS
AFILE: rmag_anisotropy.txt
RFILE: rmag_results.txt
plot bootstrap ellipses of Constable & Tauxe [1987]
NOTES
minor axis: circles
major axis: triangles
principal axis: squares
directions are plotted on the lower hemisphere
for bootstrapped eigenvector components: Xs: blue, Ys: red, Zs: black
"""
#
dir_path = "."
version_num = pmag.get_version()
verbose = pmagplotlib.verbose
args = sys.argv
ipar, ihext, ivec, iboot, imeas, isite, iplot, vec = 0, 0, 0, 1, 1, 0, 1, 0
hpars, bpars, PDir = [], [], []
CS, crd = '-1', 's'
nb = 1000
fmt = 'pdf'
ResRecs = []
orlist = []
outfile, comp, Dir, gtcirc, PDir = 'rmag_results.txt', 0, [], 0, []
infile = 'rmag_anisotropy.txt'
if "-h" in args:
print(main.__doc__)
sys.exit()
if '-WD' in args:
ind = args.index('-WD')
dir_path = args[ind+1]
if '-n' in args:
ind = args.index('-n')
nb = int(args[ind+1])
if '-usr' in args:
ind = args.index('-usr')
user = args[ind+1]
else:
user = ""
if '-B' in args:
iboot, ihext = 0, 1
if '-par' in args:
ipar = 1
if '-x' in args:
ihext = 1
if '-v' in args:
ivec = 1
if '-sit' in args:
isite = 1
if '-P' in args:
iplot = 0
if '-f' in args:
ind = args.index('-f')
infile = args[ind+1]
if '-F' in args:
ind = args.index('-F')
outfile = args[ind+1]
if '-crd' in sys.argv:
ind = sys.argv.index('-crd')
crd = sys.argv[ind+1]
if crd == 'g':
CS = '0'
if crd == 't':
CS = '100'
if '-fmt' in args:
ind = args.index('-fmt')
fmt = args[ind+1]
if '-sav' in args:
plots = 1
verbose = 0
else:
plots = 0
if '-gtc' in args:
ind = args.index('-gtc')
d, i = float(args[ind+1]), float(args[ind+2])
PDir.append(d)
PDir.append(i)
if '-d' in args:
comp = 1
ind = args.index('-d')
vec = int(args[ind+1])-1
Dir = [float(args[ind+2]), float(args[ind+3])]
#
# set up plots
#
if infile[0] != '/':
infile = dir_path+'/'+infile
if outfile[0] != '/':
outfile = dir_path+'/'+outfile
ANIS = {}
initcdf, inittcdf = 0, 0
ANIS['data'], ANIS['conf'] = 1, 2
if iboot == 1:
ANIS['tcdf'] = 3
if iplot == 1:
inittcdf = 1
pmagplotlib.plot_init(ANIS['tcdf'], 5, 5)
if comp == 1 and iplot == 1:
initcdf = 1
ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6
pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5)
pmagplotlib.plot_init(ANIS['vycdf'], 5, 5)
pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5)
if iplot == 1:
pmagplotlib.plot_init(ANIS['conf'], 5, 5)
pmagplotlib.plot_init(ANIS['data'], 5, 5)
# read in the data
data, ifiletype = pmag.magic_read(infile)
for rec in data: # find all the orientation systems
if 'anisotropy_tilt_correction' not in rec.keys():
rec['anisotropy_tilt_correction'] = '-1'
if rec['anisotropy_tilt_correction'] not in orlist:
orlist.append(rec['anisotropy_tilt_correction'])
if CS not in orlist:
if len(orlist) > 0:
CS = orlist[0]
else:
CS = '-1'
if CS == '-1':
crd = 's'
if CS == '0':
crd = 'g'
if CS == '100':
crd = 't'
if verbose:
print("desired coordinate system not available, using available: ", crd)
if isite == 1:
sitelist = []
for rec in data:
if rec['er_site_name'] not in sitelist:
sitelist.append(rec['er_site_name'])
sitelist.sort()
plt = len(sitelist)
else:
plt = 1
k = 0
while k < plt:
site = ""
sdata, Ss = [], [] # list of S format data
Locs, Sites, Samples, Specimens, Cits = [], [], [], [], []
if isite == 0:
sdata = data
else:
site = sitelist[k]
for rec in data:
if rec['er_site_name'] == site:
sdata.append(rec)
anitypes = []
csrecs = pmag.get_dictitem(
sdata, 'anisotropy_tilt_correction', CS, 'T')
for rec in csrecs:
if rec['anisotropy_type'] not in anitypes:
anitypes.append(rec['anisotropy_type'])
if rec['er_location_name'] not in Locs:
Locs.append(rec['er_location_name'])
if rec['er_site_name'] not in Sites:
Sites.append(rec['er_site_name'])
if rec['er_sample_name'] not in Samples:
Samples.append(rec['er_sample_name'])
if rec['er_specimen_name'] not in Specimens:
Specimens.append(rec['er_specimen_name'])
if rec['er_citation_names'] not in Cits:
Cits.append(rec['er_citation_names'])
s = []
s.append(float(rec["anisotropy_s1"]))
s.append(float(rec["anisotropy_s2"]))
s.append(float(rec["anisotropy_s3"]))
s.append(float(rec["anisotropy_s4"]))
s.append(float(rec["anisotropy_s5"]))
s.append(float(rec["anisotropy_s6"]))
if s[0] <= 1.0:
Ss.append(s) # protect against crap
# tau,Vdirs=pmag.doseigs(s)
ResRec = {}
ResRec['er_location_names'] = rec['er_location_name']
ResRec['er_citation_names'] = rec['er_citation_names']
ResRec['er_site_names'] = rec['er_site_name']
ResRec['er_sample_names'] = rec['er_sample_name']
ResRec['er_specimen_names'] = rec['er_specimen_name']
ResRec['rmag_result_name'] = rec['er_specimen_name'] + \
":"+rec['anisotropy_type']
ResRec["er_analyst_mail_names"] = user
ResRec["tilt_correction"] = CS
ResRec["anisotropy_type"] = rec['anisotropy_type']
if "anisotropy_n" not in rec.keys():
rec["anisotropy_n"] = "6"
if "anisotropy_sigma" not in rec.keys():
rec["anisotropy_sigma"] = "0"
fpars = pmag.dohext(
int(rec["anisotropy_n"])-6, float(rec["anisotropy_sigma"]), s)
ResRec["anisotropy_v1_dec"] = '%7.1f' % (fpars['v1_dec'])
ResRec["anisotropy_v2_dec"] = '%7.1f' % (fpars['v2_dec'])
ResRec["anisotropy_v3_dec"] = '%7.1f' % (fpars['v3_dec'])
ResRec["anisotropy_v1_inc"] = '%7.1f' % (fpars['v1_inc'])
ResRec["anisotropy_v2_inc"] = '%7.1f' % (fpars['v2_inc'])
ResRec["anisotropy_v3_inc"] = '%7.1f' % (fpars['v3_inc'])
ResRec["anisotropy_t1"] = '%10.8f' % (fpars['t1'])
ResRec["anisotropy_t2"] = '%10.8f' % (fpars['t2'])
ResRec["anisotropy_t3"] = '%10.8f' % (fpars['t3'])
ResRec["anisotropy_ftest"] = '%10.3f' % (fpars['F'])
ResRec["anisotropy_ftest12"] = '%10.3f' % (fpars['F12'])
ResRec["anisotropy_ftest23"] = '%10.3f' % (fpars['F23'])
ResRec["result_description"] = 'F_crit: ' + \
fpars['F_crit']+'; F12,F23_crit: '+fpars['F12_crit']
ResRec['anisotropy_type'] = pmag.makelist(anitypes)
ResRecs.append(ResRec)
if len(Ss) > 1:
if pmagplotlib.isServer:
title = "LO:_"+ResRec['er_location_names'] + \
'_SI:_'+site+'_SA:__SP:__CO:_'+crd
else:
title = ResRec['er_location_names']
if site:
title += "_{}".format(site)
title += '_{}'.format(crd)
ResRec['er_location_names'] = pmag.makelist(Locs)
bpars, hpars = pmagplotlib.plot_anis(
ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb)
if len(PDir) > 0:
pmagplotlib.plot_circ(ANIS['data'], PDir, 90., 'g')
pmagplotlib.plot_circ(ANIS['conf'], PDir, 90., 'g')
if verbose and plots == 0:
pmagplotlib.draw_figs(ANIS)
ResRec['er_location_names'] = pmag.makelist(Locs)
if plots == 1:
save(ANIS, fmt, title)
ResRec = {}
ResRec['er_citation_names'] = pmag.makelist(Cits)
ResRec['er_location_names'] = pmag.makelist(Locs)
ResRec['er_site_names'] = pmag.makelist(Sites)
ResRec['er_sample_names'] = pmag.makelist(Samples)
ResRec['er_specimen_names'] = pmag.makelist(Specimens)
ResRec['rmag_result_name'] = pmag.makelist(
Sites)+":"+pmag.makelist(anitypes)
ResRec['anisotropy_type'] = pmag.makelist(anitypes)
ResRec["er_analyst_mail_names"] = user
ResRec["tilt_correction"] = CS
if isite == "0":
ResRec['result_description'] = "Study average using coordinate system: " + CS
if isite == "1":
ResRec['result_description'] = "Site average using coordinate system: " + CS
if hpars != [] and ihext == 1:
HextRec = {}
for key in ResRec.keys():
HextRec[key] = ResRec[key] # copy over stuff
HextRec["anisotropy_v1_dec"] = '%7.1f' % (hpars["v1_dec"])
HextRec["anisotropy_v2_dec"] = '%7.1f' % (hpars["v2_dec"])
HextRec["anisotropy_v3_dec"] = '%7.1f' % (hpars["v3_dec"])
HextRec["anisotropy_v1_inc"] = '%7.1f' % (hpars["v1_inc"])
HextRec["anisotropy_v2_inc"] = '%7.1f' % (hpars["v2_inc"])
HextRec["anisotropy_v3_inc"] = '%7.1f' % (hpars["v3_inc"])
HextRec["anisotropy_t1"] = '%10.8f' % (hpars["t1"])
HextRec["anisotropy_t2"] = '%10.8f' % (hpars["t2"])
HextRec["anisotropy_t3"] = '%10.8f' % (hpars["t3"])
HextRec["anisotropy_hext_F"] = '%7.1f ' % (hpars["F"])
HextRec["anisotropy_hext_F12"] = '%7.1f ' % (hpars["F12"])
HextRec["anisotropy_hext_F23"] = '%7.1f ' % (hpars["F23"])
HextRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % (
hpars["e12"])
HextRec["anisotropy_v1_eta_dec"] = '%7.1f ' % (hpars["v2_dec"])
HextRec["anisotropy_v1_eta_inc"] = '%7.1f ' % (hpars["v2_inc"])
HextRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % (
hpars["e13"])
HextRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % (
hpars["v3_dec"])
HextRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % (
hpars["v3_inc"])
HextRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % (
hpars["e12"])
HextRec["anisotropy_v2_eta_dec"] = '%7.1f ' % (hpars["v1_dec"])
HextRec["anisotropy_v2_eta_inc"] = '%7.1f ' % (hpars["v1_inc"])
HextRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % (
hpars["e23"])
HextRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % (
hpars["v3_dec"])
HextRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % (
hpars["v3_inc"])
HextRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % (
hpars["e12"])
HextRec["anisotropy_v3_eta_dec"] = '%7.1f ' % (hpars["v1_dec"])
HextRec["anisotropy_v3_eta_inc"] = '%7.1f ' % (hpars["v1_inc"])
HextRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % (
hpars["e23"])
HextRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % (
hpars["v2_dec"])
HextRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % (
hpars["v2_inc"])
HextRec["magic_method_codes"] = 'LP-AN:AE-H'
if verbose:
print("Hext Statistics: ")
print(
" tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I")
print(HextRec["anisotropy_t1"], HextRec["anisotropy_v1_dec"], HextRec["anisotropy_v1_inc"], HextRec["anisotropy_v1_eta_semi_angle"], HextRec["anisotropy_v1_eta_dec"],
HextRec["anisotropy_v1_eta_inc"], HextRec["anisotropy_v1_zeta_semi_angle"], HextRec["anisotropy_v1_zeta_dec"], HextRec["anisotropy_v1_zeta_inc"])
print(HextRec["anisotropy_t2"], HextRec["anisotropy_v2_dec"], HextRec["anisotropy_v2_inc"], HextRec["anisotropy_v2_eta_semi_angle"], HextRec["anisotropy_v2_eta_dec"],
HextRec["anisotropy_v2_eta_inc"], HextRec["anisotropy_v2_zeta_semi_angle"], HextRec["anisotropy_v2_zeta_dec"], HextRec["anisotropy_v2_zeta_inc"])
print(HextRec["anisotropy_t3"], HextRec["anisotropy_v3_dec"], HextRec["anisotropy_v3_inc"], HextRec["anisotropy_v3_eta_semi_angle"], HextRec["anisotropy_v3_eta_dec"],
HextRec["anisotropy_v3_eta_inc"], HextRec["anisotropy_v3_zeta_semi_angle"], HextRec["anisotropy_v3_zeta_dec"], HextRec["anisotropy_v3_zeta_inc"])
HextRec['magic_software_packages'] = version_num
ResRecs.append(HextRec)
if bpars != []:
BootRec = {}
for key in ResRec.keys():
BootRec[key] = ResRec[key] # copy over stuff
BootRec["anisotropy_v1_dec"] = '%7.1f' % (bpars["v1_dec"])
BootRec["anisotropy_v2_dec"] = '%7.1f' % (bpars["v2_dec"])
BootRec["anisotropy_v3_dec"] = '%7.1f' % (bpars["v3_dec"])
BootRec["anisotropy_v1_inc"] = '%7.1f' % (bpars["v1_inc"])
BootRec["anisotropy_v2_inc"] = '%7.1f' % (bpars["v2_inc"])
BootRec["anisotropy_v3_inc"] = '%7.1f' % (bpars["v3_inc"])
BootRec["anisotropy_t1"] = '%10.8f' % (bpars["t1"])
BootRec["anisotropy_t2"] = '%10.8f' % (bpars["t2"])
BootRec["anisotropy_t3"] = '%10.8f' % (bpars["t3"])
BootRec["anisotropy_v1_eta_inc"] = '%7.1f ' % (
bpars["v1_eta_inc"])
BootRec["anisotropy_v1_eta_dec"] = '%7.1f ' % (
bpars["v1_eta_dec"])
BootRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % (
bpars["v1_eta"])
BootRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % (
bpars["v1_zeta_inc"])
BootRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % (
bpars["v1_zeta_dec"])
BootRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % (
bpars["v1_zeta"])
BootRec["anisotropy_v2_eta_inc"] = '%7.1f ' % (
bpars["v2_eta_inc"])
BootRec["anisotropy_v2_eta_dec"] = '%7.1f ' % (
bpars["v2_eta_dec"])
BootRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % (
bpars["v2_eta"])
BootRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % (
bpars["v2_zeta_inc"])
BootRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % (
bpars["v2_zeta_dec"])
BootRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % (
bpars["v2_zeta"])
BootRec["anisotropy_v3_eta_inc"] = '%7.1f ' % (
bpars["v3_eta_inc"])
BootRec["anisotropy_v3_eta_dec"] = '%7.1f ' % (
bpars["v3_eta_dec"])
BootRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % (
bpars["v3_eta"])
BootRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % (
bpars["v3_zeta_inc"])
BootRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % (
bpars["v3_zeta_dec"])
BootRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % (
bpars["v3_zeta"])
BootRec["anisotropy_hext_F"] = ''
BootRec["anisotropy_hext_F12"] = ''
BootRec["anisotropy_hext_F23"] = ''
# regular bootstrap
BootRec["magic_method_codes"] = 'LP-AN:AE-H:AE-BS'
if ipar == 1:
# parametric bootstrap
BootRec["magic_method_codes"] = 'LP-AN:AE-H:AE-BS-P'
if verbose:
print("Boostrap Statistics: ")
print(
" tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I")
print(BootRec["anisotropy_t1"], BootRec["anisotropy_v1_dec"], BootRec["anisotropy_v1_inc"], BootRec["anisotropy_v1_eta_semi_angle"], BootRec["anisotropy_v1_eta_dec"],
BootRec["anisotropy_v1_eta_inc"], BootRec["anisotropy_v1_zeta_semi_angle"], BootRec["anisotropy_v1_zeta_dec"], BootRec["anisotropy_v1_zeta_inc"])
print(BootRec["anisotropy_t2"], BootRec["anisotropy_v2_dec"], BootRec["anisotropy_v2_inc"], BootRec["anisotropy_v2_eta_semi_angle"], BootRec["anisotropy_v2_eta_dec"],
BootRec["anisotropy_v2_eta_inc"], BootRec["anisotropy_v2_zeta_semi_angle"], BootRec["anisotropy_v2_zeta_dec"], BootRec["anisotropy_v2_zeta_inc"])
print(BootRec["anisotropy_t3"], BootRec["anisotropy_v3_dec"], BootRec["anisotropy_v3_inc"], BootRec["anisotropy_v3_eta_semi_angle"], BootRec["anisotropy_v3_eta_dec"],
BootRec["anisotropy_v3_eta_inc"], BootRec["anisotropy_v3_zeta_semi_angle"], BootRec["anisotropy_v3_zeta_dec"], BootRec["anisotropy_v3_zeta_inc"])
BootRec['magic_software_packages'] = version_num
ResRecs.append(BootRec)
k += 1
goon = 1
while goon == 1 and iplot == 1 and verbose:
if iboot == 1:
print("compare with [d]irection ")
print(
" plot [g]reat circle, change [c]oord. system, change [e]llipse calculation, s[a]ve plots, [q]uit ")
if isite == 1:
print(" [p]revious, [s]ite, [q]uit, <return> for next ")
ans = input("")
if ans == "q":
sys.exit()
if ans == "e":
iboot, ipar, ihext, ivec = 1, 0, 0, 0
e = input("Do Hext Statistics 1/[0]: ")
if e == "1":
ihext = 1
e = input("Suppress bootstrap 1/[0]: ")
if e == "1":
iboot = 0
if iboot == 1:
e = input("Parametric bootstrap 1/[0]: ")
if e == "1":
ipar = 1
e = input("Plot bootstrap eigenvectors: 1/[0]: ")
if e == "1":
ivec = 1
if iplot == 1:
if inittcdf == 0:
ANIS['tcdf'] = 3
pmagplotlib.plot_init(ANIS['tcdf'], 5, 5)
inittcdf = 1
bpars, hpars = pmagplotlib.plot_anis(
ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb)
if verbose and plots == 0:
pmagplotlib.draw_figs(ANIS)
if ans == "c":
print("Current Coordinate system is: ")
if CS == '-1':
print(" Specimen")
if CS == '0':
print(" Geographic")
if CS == '100':
print(" Tilt corrected")
key = input(
" Enter desired coordinate system: [s]pecimen, [g]eographic, [t]ilt corrected ")
if key == 's':
CS = '-1'
if key == 'g':
CS = '0'
if key == 't':
CS = '100'
if CS not in orlist:
if len(orlist) > 0:
CS = orlist[0]
else:
CS = '-1'
if CS == '-1':
crd = 's'
if CS == '0':
crd = 'g'
if CS == '100':
crd = 't'
print(
"desired coordinate system not available, using available: ", crd)
k -= 1
goon = 0
if ans == "":
if isite == 1:
goon = 0
else:
print("Good bye ")
sys.exit()
if ans == 'd':
if initcdf == 0:
initcdf = 1
ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6
pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5)
pmagplotlib.plot_init(ANIS['vycdf'], 5, 5)
pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5)
Dir, comp = [], 1
print("""
Input: Vi D I to compare eigenvector Vi with direction D/I
where Vi=1: principal
Vi=2: major
Vi=3: minor
D= declination of comparison direction
I= inclination of comparison direction""")
con = 1
while con == 1:
try:
vdi = input("Vi D I: ").split()
vec = int(vdi[0])-1
Dir = [float(vdi[1]), float(vdi[2])]
con = 0
except IndexError:
print(" Incorrect entry, try again ")
bpars, hpars = pmagplotlib.plot_anis(
ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, nb)
Dir, comp = [], 0
if ans == 'g':
con, cnt = 1, 0
while con == 1:
try:
print(
" Input: input pole to great circle ( D I) to plot a great circle: ")
di = input(" D I: ").split()
PDir.append(float(di[0]))
PDir.append(float(di[1]))
con = 0
except:
cnt += 1
if cnt < 10:
print(
" enter the dec and inc of the pole on one line ")
else:
print(
"ummm - you are doing something wrong - i give up")
sys.exit()
pmagplotlib.plot_circ(ANIS['data'], PDir, 90., 'g')
pmagplotlib.plot_circ(ANIS['conf'], PDir, 90., 'g')
if verbose and plots == 0:
pmagplotlib.draw_figs(ANIS)
if ans == "p":
k -= 2
goon = 0
if ans == "q":
k = plt
goon = 0
if ans == "s":
keepon = 1
site = input(" print site or part of site desired: ")
while keepon == 1:
try:
k = sitelist.index(site)
keepon = 0
except:
tmplist = []
for qq in range(len(sitelist)):
if site in sitelist[qq]:
tmplist.append(sitelist[qq])
print(site, " not found, but this was: ")
print(tmplist)
site = input('Select one or try again\n ')
k = sitelist.index(site)
goon, ans = 0, ""
if ans == "a":
locs = pmag.makelist(Locs)
if pmagplotlib.isServer: # use server plot naming convention
title = "LO:_"+locs+'_SI:__'+'_SA:__SP:__CO:_'+crd
else: # use more readable plot naming convention
title = "{}_{}".format(locs, crd)
save(ANIS, fmt, title)
goon = 0
else:
if verbose:
print('skipping plot - not enough data points')
k += 1
# put rmag_results stuff here
if len(ResRecs) > 0:
ResOut, keylist = pmag.fillkeys(ResRecs)
pmag.magic_write(outfile, ResOut, 'rmag_results')
if verbose:
print(" Good bye ") | NAME
aniso_magic.py
DESCRIPTION
plots anisotropy data with either bootstrap or hext ellipses
SYNTAX
aniso_magic.py [-h] [command line options]
OPTIONS
-h plots help message and quits
-usr USER: set the user name
-f AFILE, specify rmag_anisotropy formatted file for input
-F RFILE, specify rmag_results formatted file for output
-x Hext [1963] and bootstrap
-B DON'T do bootstrap, do Hext
-par Tauxe [1998] parametric bootstrap
-v plot bootstrap eigenvectors instead of ellipses
-sit plot by site instead of entire file
-crd [s,g,t] coordinate system, default is specimen (g=geographic, t=tilt corrected)
-P don't make any plots - just make rmag_results table
-sav don't make the rmag_results table - just save all the plots
-fmt [svg, jpg, eps] format for output images, pdf default
-gtc DEC INC dec,inc of pole to great circle [down(up) in green (cyan)
-d Vi DEC INC; Vi (1,2,3) to compare to direction DEC INC
-n N; specifies the number of bootstraps - default is 1000
DEFAULTS
AFILE: rmag_anisotropy.txt
RFILE: rmag_results.txt
plot bootstrap ellipses of Constable & Tauxe [1987]
NOTES
minor axis: circles
major axis: triangles
principal axis: squares
directions are plotted on the lower hemisphere
for bootstrapped eigenvector components: Xs: blue, Ys: red, Zs: black | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/aniso_magic2.py#L20-L579 |
PmagPy/PmagPy | programs/di_geo.py | main | 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 | 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])) | 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 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/di_geo.py#L9-L64 |
PmagPy/PmagPy | programs/eqarea_ell.py | main | def main():
"""
NAME
eqarea_ell.py
DESCRIPTION
makes equal area projections from declination/inclination data
and plot ellipses
SYNTAX
eqarea_ell.py -h [command line options]
INPUT
takes space delimited Dec/Inc data
OPTIONS
-h prints help message and quits
-f FILE
-fmt [svg,png,jpg] format for output plots
-sav saves figures and quits
-ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
"""
FIG={} # plot dictionary
FIG['eq']=1 # eqarea is figure 1
fmt,dist,mode,plot='svg','F',1,0
sym={'lower':['o','r'],'upper':['o','w'],'size':10}
plotE=0
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if not set_env.IS_WIN:
pmagplotlib.plot_init(FIG['eq'],5,5)
if '-sav' in sys.argv:plot=1
if '-f' in sys.argv:
ind=sys.argv.index("-f")
title=sys.argv[ind+1]
data=numpy.loadtxt(title).transpose()
if '-ell' in sys.argv:
plotE=1
ind=sys.argv.index('-ell')
ell_type=sys.argv[ind+1]
if ell_type=='F':dist='F'
if ell_type=='K':dist='K'
if ell_type=='B':dist='B'
if ell_type=='Be':dist='BE'
if ell_type=='Bv':
dist='BV'
FIG['bdirs']=2
pmagplotlib.plot_init(FIG['bdirs'],5,5)
if '-fmt' in sys.argv:
ind=sys.argv.index("-fmt")
fmt=sys.argv[ind+1]
DIblock=numpy.array([data[0],data[1]]).transpose()
if len(DIblock)>0:
pmagplotlib.plot_eq_sym(FIG['eq'],DIblock,title,sym)
#if plot==0:pmagplotlib.draw_figs(FIG)
else:
print("no data to plot")
sys.exit()
if plotE==1:
ppars=pmag.doprinc(DIblock) # get principal directions
nDIs,rDIs,npars,rpars=[],[],[],[]
for rec in DIblock:
angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
if angle>90.:
rDIs.append(rec)
else:
nDIs.append(rec)
if dist=='B': # do on whole dataset
etitle="Bingham confidence ellipse"
bpars=pmag.dobingham(DIblock)
for key in list(bpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(bpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(bpars[key]))
npars.append(bpars['dec'])
npars.append(bpars['inc'])
npars.append(bpars['Zeta'])
npars.append(bpars['Zdec'])
npars.append(bpars['Zinc'])
npars.append(bpars['Eta'])
npars.append(bpars['Edec'])
npars.append(bpars['Einc'])
if dist=='F':
etitle="Fisher confidence cone"
if len(nDIs)>3:
fpars=pmag.fisher_mean(nDIs)
for key in list(fpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(fpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(fpars[key]))
mode+=1
npars.append(fpars['dec'])
npars.append(fpars['inc'])
npars.append(fpars['alpha95']) # Beta
npars.append(fpars['dec'])
isign=abs(fpars['inc']) / fpars['inc']
npars.append(fpars['inc']-isign*90.) #Beta inc
npars.append(fpars['alpha95']) # gamma
npars.append(fpars['dec']+90.) # Beta dec
npars.append(0.) #Beta inc
if len(rDIs)>3:
fpars=pmag.fisher_mean(rDIs)
if pmagplotlib.verbose:print("mode ",mode)
for key in list(fpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(fpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(fpars[key]))
mode+=1
rpars.append(fpars['dec'])
rpars.append(fpars['inc'])
rpars.append(fpars['alpha95']) # Beta
rpars.append(fpars['dec'])
isign=abs(fpars['inc']) / fpars['inc']
rpars.append(fpars['inc']-isign*90.) #Beta inc
rpars.append(fpars['alpha95']) # gamma
rpars.append(fpars['dec']+90.) # Beta dec
rpars.append(0.) #Beta inc
if dist=='K':
etitle="Kent confidence ellipse"
if len(nDIs)>3:
kpars=pmag.dokent(nDIs,len(nDIs))
if pmagplotlib.verbose:print("mode ",mode)
for key in list(kpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(kpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(kpars[key]))
mode+=1
npars.append(kpars['dec'])
npars.append(kpars['inc'])
npars.append(kpars['Zeta'])
npars.append(kpars['Zdec'])
npars.append(kpars['Zinc'])
npars.append(kpars['Eta'])
npars.append(kpars['Edec'])
npars.append(kpars['Einc'])
if len(rDIs)>3:
kpars=pmag.dokent(rDIs,len(rDIs))
if pmagplotlib.verbose:print("mode ",mode)
for key in list(kpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(kpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(kpars[key]))
mode+=1
rpars.append(kpars['dec'])
rpars.append(kpars['inc'])
rpars.append(kpars['Zeta'])
rpars.append(kpars['Zdec'])
rpars.append(kpars['Zinc'])
rpars.append(kpars['Eta'])
rpars.append(kpars['Edec'])
rpars.append(kpars['Einc'])
else: # assume bootstrap
if len(nDIs)<10 and len(rDIs)<10:
print('too few data points for bootstrap')
sys.exit()
if dist=='BE':
print('Be patient for bootstrap...')
if len(nDIs)>=10:
BnDIs=pmag.di_boot(nDIs)
Bkpars=pmag.dokent(BnDIs,1.)
if pmagplotlib.verbose:print("mode ",mode)
for key in list(Bkpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(Bkpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(Bkpars[key]))
mode+=1
npars.append(Bkpars['dec'])
npars.append(Bkpars['inc'])
npars.append(Bkpars['Zeta'])
npars.append(Bkpars['Zdec'])
npars.append(Bkpars['Zinc'])
npars.append(Bkpars['Eta'])
npars.append(Bkpars['Edec'])
npars.append(Bkpars['Einc'])
if len(rDIs)>=10:
BrDIs=pmag.di_boot(rDIs)
Bkpars=pmag.dokent(BrDIs,1.)
if pmagplotlib.verbose:print("mode ",mode)
for key in list(Bkpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(Bkpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(Bkpars[key]))
mode+=1
rpars.append(Bkpars['dec'])
rpars.append(Bkpars['inc'])
rpars.append(Bkpars['Zeta'])
rpars.append(Bkpars['Zdec'])
rpars.append(Bkpars['Zinc'])
rpars.append(Bkpars['Eta'])
rpars.append(Bkpars['Edec'])
rpars.append(Bkpars['Einc'])
etitle="Bootstrapped confidence ellipse"
elif dist=='BV':
print('Be patient for bootstrap...')
vsym={'lower':['+','k'],'upper':['x','k'],'size':5}
if len(nDIs)>5:
BnDIs=pmag.di_boot(nDIs)
pmagplotlib.plot_eq_sym(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors',vsym)
if len(rDIs)>5:
BrDIs=pmag.di_boot(rDIs)
if len(nDIs)>5: # plot on existing plots
pmagplotlib.plot_di_sym(FIG['bdirs'],BrDIs,vsym)
else:
pmagplotlib.plot_eq(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors',vsym)
if dist=='B':
if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plot_conf(FIG['eq'],etitle,[],npars,0)
elif len(nDIs)>3 and dist!='BV':
pmagplotlib.plot_conf(FIG['eq'],etitle,[],npars,0)
if len(rDIs)>3:
pmagplotlib.plot_conf(FIG['eq'],etitle,[],rpars,0)
elif len(rDIs)>3 and dist!='BV':
pmagplotlib.plot_conf(FIG['eq'],etitle,[],rpars,0)
#if plot==0:pmagplotlib.draw_figs(FIG)
if plot==0:pmagplotlib.draw_figs(FIG)
#
files={}
for key in list(FIG.keys()):
files[key]=title+'_'+key+'.'+fmt
if pmagplotlib.isServer:
black = '#000000'
purple = '#800080'
titles={}
titles['eq']='Equal Area Plot'
FIG = pmagplotlib.add_borders(FIG,titles,black,purple)
pmagplotlib.save_plots(FIG,files)
elif plot==0:
ans=input(" S[a]ve to save plot, [q]uit, Return to continue: ")
if ans=="q": sys.exit()
if ans=="a":
pmagplotlib.save_plots(FIG,files)
else:
pmagplotlib.save_plots(FIG,files) | python | def main():
"""
NAME
eqarea_ell.py
DESCRIPTION
makes equal area projections from declination/inclination data
and plot ellipses
SYNTAX
eqarea_ell.py -h [command line options]
INPUT
takes space delimited Dec/Inc data
OPTIONS
-h prints help message and quits
-f FILE
-fmt [svg,png,jpg] format for output plots
-sav saves figures and quits
-ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors
"""
FIG={} # plot dictionary
FIG['eq']=1 # eqarea is figure 1
fmt,dist,mode,plot='svg','F',1,0
sym={'lower':['o','r'],'upper':['o','w'],'size':10}
plotE=0
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if not set_env.IS_WIN:
pmagplotlib.plot_init(FIG['eq'],5,5)
if '-sav' in sys.argv:plot=1
if '-f' in sys.argv:
ind=sys.argv.index("-f")
title=sys.argv[ind+1]
data=numpy.loadtxt(title).transpose()
if '-ell' in sys.argv:
plotE=1
ind=sys.argv.index('-ell')
ell_type=sys.argv[ind+1]
if ell_type=='F':dist='F'
if ell_type=='K':dist='K'
if ell_type=='B':dist='B'
if ell_type=='Be':dist='BE'
if ell_type=='Bv':
dist='BV'
FIG['bdirs']=2
pmagplotlib.plot_init(FIG['bdirs'],5,5)
if '-fmt' in sys.argv:
ind=sys.argv.index("-fmt")
fmt=sys.argv[ind+1]
DIblock=numpy.array([data[0],data[1]]).transpose()
if len(DIblock)>0:
pmagplotlib.plot_eq_sym(FIG['eq'],DIblock,title,sym)
#if plot==0:pmagplotlib.draw_figs(FIG)
else:
print("no data to plot")
sys.exit()
if plotE==1:
ppars=pmag.doprinc(DIblock) # get principal directions
nDIs,rDIs,npars,rpars=[],[],[],[]
for rec in DIblock:
angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']])
if angle>90.:
rDIs.append(rec)
else:
nDIs.append(rec)
if dist=='B': # do on whole dataset
etitle="Bingham confidence ellipse"
bpars=pmag.dobingham(DIblock)
for key in list(bpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(bpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(bpars[key]))
npars.append(bpars['dec'])
npars.append(bpars['inc'])
npars.append(bpars['Zeta'])
npars.append(bpars['Zdec'])
npars.append(bpars['Zinc'])
npars.append(bpars['Eta'])
npars.append(bpars['Edec'])
npars.append(bpars['Einc'])
if dist=='F':
etitle="Fisher confidence cone"
if len(nDIs)>3:
fpars=pmag.fisher_mean(nDIs)
for key in list(fpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(fpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(fpars[key]))
mode+=1
npars.append(fpars['dec'])
npars.append(fpars['inc'])
npars.append(fpars['alpha95']) # Beta
npars.append(fpars['dec'])
isign=abs(fpars['inc']) / fpars['inc']
npars.append(fpars['inc']-isign*90.) #Beta inc
npars.append(fpars['alpha95']) # gamma
npars.append(fpars['dec']+90.) # Beta dec
npars.append(0.) #Beta inc
if len(rDIs)>3:
fpars=pmag.fisher_mean(rDIs)
if pmagplotlib.verbose:print("mode ",mode)
for key in list(fpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(fpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(fpars[key]))
mode+=1
rpars.append(fpars['dec'])
rpars.append(fpars['inc'])
rpars.append(fpars['alpha95']) # Beta
rpars.append(fpars['dec'])
isign=abs(fpars['inc']) / fpars['inc']
rpars.append(fpars['inc']-isign*90.) #Beta inc
rpars.append(fpars['alpha95']) # gamma
rpars.append(fpars['dec']+90.) # Beta dec
rpars.append(0.) #Beta inc
if dist=='K':
etitle="Kent confidence ellipse"
if len(nDIs)>3:
kpars=pmag.dokent(nDIs,len(nDIs))
if pmagplotlib.verbose:print("mode ",mode)
for key in list(kpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(kpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(kpars[key]))
mode+=1
npars.append(kpars['dec'])
npars.append(kpars['inc'])
npars.append(kpars['Zeta'])
npars.append(kpars['Zdec'])
npars.append(kpars['Zinc'])
npars.append(kpars['Eta'])
npars.append(kpars['Edec'])
npars.append(kpars['Einc'])
if len(rDIs)>3:
kpars=pmag.dokent(rDIs,len(rDIs))
if pmagplotlib.verbose:print("mode ",mode)
for key in list(kpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(kpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(kpars[key]))
mode+=1
rpars.append(kpars['dec'])
rpars.append(kpars['inc'])
rpars.append(kpars['Zeta'])
rpars.append(kpars['Zdec'])
rpars.append(kpars['Zinc'])
rpars.append(kpars['Eta'])
rpars.append(kpars['Edec'])
rpars.append(kpars['Einc'])
else: # assume bootstrap
if len(nDIs)<10 and len(rDIs)<10:
print('too few data points for bootstrap')
sys.exit()
if dist=='BE':
print('Be patient for bootstrap...')
if len(nDIs)>=10:
BnDIs=pmag.di_boot(nDIs)
Bkpars=pmag.dokent(BnDIs,1.)
if pmagplotlib.verbose:print("mode ",mode)
for key in list(Bkpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(Bkpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(Bkpars[key]))
mode+=1
npars.append(Bkpars['dec'])
npars.append(Bkpars['inc'])
npars.append(Bkpars['Zeta'])
npars.append(Bkpars['Zdec'])
npars.append(Bkpars['Zinc'])
npars.append(Bkpars['Eta'])
npars.append(Bkpars['Edec'])
npars.append(Bkpars['Einc'])
if len(rDIs)>=10:
BrDIs=pmag.di_boot(rDIs)
Bkpars=pmag.dokent(BrDIs,1.)
if pmagplotlib.verbose:print("mode ",mode)
for key in list(Bkpars.keys()):
if key!='n' and pmagplotlib.verbose:print(" ",key, '%7.1f'%(Bkpars[key]))
if key=='n' and pmagplotlib.verbose:print(" ",key, ' %i'%(Bkpars[key]))
mode+=1
rpars.append(Bkpars['dec'])
rpars.append(Bkpars['inc'])
rpars.append(Bkpars['Zeta'])
rpars.append(Bkpars['Zdec'])
rpars.append(Bkpars['Zinc'])
rpars.append(Bkpars['Eta'])
rpars.append(Bkpars['Edec'])
rpars.append(Bkpars['Einc'])
etitle="Bootstrapped confidence ellipse"
elif dist=='BV':
print('Be patient for bootstrap...')
vsym={'lower':['+','k'],'upper':['x','k'],'size':5}
if len(nDIs)>5:
BnDIs=pmag.di_boot(nDIs)
pmagplotlib.plot_eq_sym(FIG['bdirs'],BnDIs,'Bootstrapped Eigenvectors',vsym)
if len(rDIs)>5:
BrDIs=pmag.di_boot(rDIs)
if len(nDIs)>5: # plot on existing plots
pmagplotlib.plot_di_sym(FIG['bdirs'],BrDIs,vsym)
else:
pmagplotlib.plot_eq(FIG['bdirs'],BrDIs,'Bootstrapped Eigenvectors',vsym)
if dist=='B':
if len(nDIs)> 3 or len(rDIs)>3: pmagplotlib.plot_conf(FIG['eq'],etitle,[],npars,0)
elif len(nDIs)>3 and dist!='BV':
pmagplotlib.plot_conf(FIG['eq'],etitle,[],npars,0)
if len(rDIs)>3:
pmagplotlib.plot_conf(FIG['eq'],etitle,[],rpars,0)
elif len(rDIs)>3 and dist!='BV':
pmagplotlib.plot_conf(FIG['eq'],etitle,[],rpars,0)
#if plot==0:pmagplotlib.draw_figs(FIG)
if plot==0:pmagplotlib.draw_figs(FIG)
#
files={}
for key in list(FIG.keys()):
files[key]=title+'_'+key+'.'+fmt
if pmagplotlib.isServer:
black = '#000000'
purple = '#800080'
titles={}
titles['eq']='Equal Area Plot'
FIG = pmagplotlib.add_borders(FIG,titles,black,purple)
pmagplotlib.save_plots(FIG,files)
elif plot==0:
ans=input(" S[a]ve to save plot, [q]uit, Return to continue: ")
if ans=="q": sys.exit()
if ans=="a":
pmagplotlib.save_plots(FIG,files)
else:
pmagplotlib.save_plots(FIG,files) | NAME
eqarea_ell.py
DESCRIPTION
makes equal area projections from declination/inclination data
and plot ellipses
SYNTAX
eqarea_ell.py -h [command line options]
INPUT
takes space delimited Dec/Inc data
OPTIONS
-h prints help message and quits
-f FILE
-fmt [svg,png,jpg] format for output plots
-sav saves figures and quits
-ell [F,K,B,Be,Bv] plot Fisher, Kent, Bingham, Bootstrap ellipses or Boostrap eigenvectors | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/eqarea_ell.py#L12-L237 |
PmagPy/PmagPy | programs/di_eq.py | main | def main():
"""
NAME
di_eq.py
DESCRIPTION
converts dec, inc pairs to x,y pairs using equal area projection
NB: do only upper or lower hemisphere at a time: does not distinguish between up and down.
SYNTAX
di_eq.py [command line options] [< filename]
OPTIONS
-h prints help message and quits
-f FILE, input file
"""
out=""
UP=0
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
DI=numpy.loadtxt(file,dtype=numpy.float)
else:
DI = numpy.loadtxt(sys.stdin,dtype=numpy.float) # read from standard input
Ds=DI.transpose()[0]
Is=DI.transpose()[1]
if len(DI)>1: #array of data
XY=pmag.dimap_V(Ds,Is)
for xy in XY:
print('%f %f'%(xy[0],xy[1]))
else: # single data point
XY=pmag.dimap(Ds,Is)
print('%f %f'%(XY[0],XY[1])) | python | def main():
"""
NAME
di_eq.py
DESCRIPTION
converts dec, inc pairs to x,y pairs using equal area projection
NB: do only upper or lower hemisphere at a time: does not distinguish between up and down.
SYNTAX
di_eq.py [command line options] [< filename]
OPTIONS
-h prints help message and quits
-f FILE, input file
"""
out=""
UP=0
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
DI=numpy.loadtxt(file,dtype=numpy.float)
else:
DI = numpy.loadtxt(sys.stdin,dtype=numpy.float) # read from standard input
Ds=DI.transpose()[0]
Is=DI.transpose()[1]
if len(DI)>1: #array of data
XY=pmag.dimap_V(Ds,Is)
for xy in XY:
print('%f %f'%(xy[0],xy[1]))
else: # single data point
XY=pmag.dimap(Ds,Is)
print('%f %f'%(XY[0],XY[1])) | NAME
di_eq.py
DESCRIPTION
converts dec, inc pairs to x,y pairs using equal area projection
NB: do only upper or lower hemisphere at a time: does not distinguish between up and down.
SYNTAX
di_eq.py [command line options] [< filename]
OPTIONS
-h prints help message and quits
-f FILE, input file | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/di_eq.py#L7-L42 |
PmagPy/PmagPy | pmagpy/spline.py | spline_interpolate | def spline_interpolate(x1, y1, x2):
"""
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
"""
sp = Spline(x1, y1)
return sp(x2) | python | def spline_interpolate(x1, y1, x2):
"""
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
"""
sp = Spline(x1, y1)
return sp(x2) | Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/spline.py#L163-L169 |
PmagPy/PmagPy | pmagpy/spline.py | logspline_interpolate | def logspline_interpolate(x1, y1, x2):
"""
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
"""
sp = Spline(log(x1), log(y1))
return exp(sp(log(x2))) | python | def logspline_interpolate(x1, y1, x2):
"""
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
"""
sp = Spline(log(x1), log(y1))
return exp(sp(log(x2))) | Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/spline.py#L171-L177 |
PmagPy/PmagPy | pmagpy/spline.py | linear_interpolate | def linear_interpolate(x1, y1, x2):
"""
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
"""
li = LinInt(x1, y1)
return li(x2) | python | def linear_interpolate(x1, y1, x2):
"""
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
"""
li = LinInt(x1, y1)
return li(x2) | Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/spline.py#L180-L186 |
PmagPy/PmagPy | pmagpy/spline.py | LinInt.call | 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 | 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] | Evaluate the interpolant, assuming x is a scalar. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/spline.py#L143-L161 |
PmagPy/PmagPy | programs/aarm_magic.py | main | 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 | 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) | 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) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/aarm_magic.py#L7-L75 |
PmagPy/PmagPy | programs/dmag_magic2.py | main | def main():
"""
NAME
dmag_magic2.py
DESCRIPTION
plots intensity decay curves for demagnetization experiments
SYNTAX
dmag_magic -h [command line options]
INPUT
takes magic formatted magic_measurements.txt files
OPTIONS
-h prints help message and quits
-f FILE: specify input file, default is: magic_measurements.txt
-obj OBJ: specify object [loc, sit, sam, spc] for plot, default is by location
-LT [AF,T,M]: specify lab treatment type, default AF
-XLP [PI]: exclude specific lab protocols (for example, method codes like LP-PI)
-N do not normalize by NRM magnetization
-sav save plots silently and quit
-fmt [svg,jpg,png,pdf] set figure format [default is svg]
NOTE
loc: location (study); sit: site; sam: sample; spc: specimen
"""
FIG = {} # plot dictionary
FIG['demag'] = 1 # demag is figure 1
in_file, plot_key, LT = 'magic_measurements.txt', 'er_location_name', "LT-AF-Z"
XLP = ""
norm = 1
LT = 'LT-AF-Z'
units, dmag_key = 'T', 'treatment_ac_field'
plot = 0
fmt = 'svg'
if len(sys.argv) > 1:
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-N' in sys.argv:
norm = 0
if '-sav' in sys.argv:
plot = 1
if '-f' in sys.argv:
ind = sys.argv.index("-f")
in_file = sys.argv[ind+1]
if '-fmt' in sys.argv:
ind = sys.argv.index("-fmt")
fmt = sys.argv[ind+1]
if '-obj' in sys.argv:
ind = sys.argv.index('-obj')
plot_by = sys.argv[ind+1]
if plot_by == 'sit':
plot_key = 'er_site_name'
if plot_by == 'sam':
plot_key = 'er_sample_name'
if plot_by == 'spc':
plot_key = 'er_specimen_name'
if '-XLP' in sys.argv:
ind = sys.argv.index("-XLP")
XLP = sys.argv[ind+1] # get lab protocol for excluding
if '-LT' in sys.argv:
ind = sys.argv.index("-LT")
LT = 'LT-'+sys.argv[ind+1]+'-Z' # get lab treatment for plotting
if LT == 'LT-T-Z':
units, dmag_key = 'K', 'treatment_temp'
elif LT == 'LT-AF-Z':
units, dmag_key = 'T', 'treatment_ac_field'
elif LT == 'LT-M-Z':
units, dmag_key = 'J', 'treatment_mw_energy'
else:
units = 'U'
data, file_type = pmag.magic_read(in_file)
sids = pmag.get_specs(data)
pmagplotlib.plot_init(FIG['demag'], 5, 5)
print(len(data), ' records read from ', in_file)
#
#
# find desired intensity data
#
#
plotlist, intlist = [], ['measurement_magnitude', 'measurement_magn_moment',
'measurement_magn_volume', 'measurement_magn_mass']
IntMeths = []
FixData = []
for rec in data:
meths = []
methcodes = rec['magic_method_codes'].split(':')
for meth in methcodes:
meths.append(meth.strip())
for key in rec.keys():
if key in intlist and rec[key] != "":
if key not in IntMeths:
IntMeths.append(key)
if rec[plot_key] not in plotlist and LT in meths:
plotlist.append(rec[plot_key])
if 'measurement_flag' not in rec.keys():
rec['measurement_flag'] = 'g'
FixData.append(rec)
plotlist.sort()
if len(IntMeths) == 0:
print('No intensity information found')
sys.exit()
data = FixData
# plot first intensity method found - normalized to initial value anyway - doesn't matter which used
int_key = IntMeths[0]
for plt in plotlist:
if plot == 0:
print(plt, 'plotting by: ', plot_key)
# fish out all the data for this type of plot
PLTblock = pmag.get_dictitem(data, plot_key, plt, 'T')
# fish out all the dmag for this experiment type
PLTblock = pmag.get_dictitem(PLTblock, 'magic_method_codes', LT, 'has')
# get all with this intensity key non-blank
PLTblock = pmag.get_dictitem(PLTblock, int_key, '', 'F')
if XLP != "":
# reject data with XLP in method_code
PLTblock = pmag.get_dictitem(
PLTblock, 'magic_method_codes', XLP, 'not')
if len(PLTblock) > 2:
title = PLTblock[0][plot_key]
spcs = []
for rec in PLTblock:
if rec['er_specimen_name'] not in spcs:
spcs.append(rec['er_specimen_name'])
for spc in spcs:
# plot specimen by specimen
SPCblock = pmag.get_dictitem(
PLTblock, 'er_specimen_name', spc, 'T')
INTblock = []
for rec in SPCblock:
INTblock.append([float(rec[dmag_key]), 0, 0, float(
rec[int_key]), 1, rec['measurement_flag']])
if len(INTblock) > 2:
pmagplotlib.plot_mag(
FIG['demag'], INTblock, title, 0, units, norm)
if plot == 1:
files = {}
for key in FIG.keys():
files[key] = title+'_'+LT+'.'+fmt
pmagplotlib.save_plots(FIG, files)
sys.exit()
else:
pmagplotlib.draw_figs(FIG)
ans = input(
" S[a]ve to save plot, [q]uit, Return to continue: ")
if ans == 'q':
sys.exit()
if ans == "a":
files = {}
for key in FIG.keys():
files[key] = title+'_'+LT+'.'+fmt
pmagplotlib.save_plots(FIG, files)
pmagplotlib.clearFIG(FIG['demag']) | python | def main():
"""
NAME
dmag_magic2.py
DESCRIPTION
plots intensity decay curves for demagnetization experiments
SYNTAX
dmag_magic -h [command line options]
INPUT
takes magic formatted magic_measurements.txt files
OPTIONS
-h prints help message and quits
-f FILE: specify input file, default is: magic_measurements.txt
-obj OBJ: specify object [loc, sit, sam, spc] for plot, default is by location
-LT [AF,T,M]: specify lab treatment type, default AF
-XLP [PI]: exclude specific lab protocols (for example, method codes like LP-PI)
-N do not normalize by NRM magnetization
-sav save plots silently and quit
-fmt [svg,jpg,png,pdf] set figure format [default is svg]
NOTE
loc: location (study); sit: site; sam: sample; spc: specimen
"""
FIG = {} # plot dictionary
FIG['demag'] = 1 # demag is figure 1
in_file, plot_key, LT = 'magic_measurements.txt', 'er_location_name', "LT-AF-Z"
XLP = ""
norm = 1
LT = 'LT-AF-Z'
units, dmag_key = 'T', 'treatment_ac_field'
plot = 0
fmt = 'svg'
if len(sys.argv) > 1:
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-N' in sys.argv:
norm = 0
if '-sav' in sys.argv:
plot = 1
if '-f' in sys.argv:
ind = sys.argv.index("-f")
in_file = sys.argv[ind+1]
if '-fmt' in sys.argv:
ind = sys.argv.index("-fmt")
fmt = sys.argv[ind+1]
if '-obj' in sys.argv:
ind = sys.argv.index('-obj')
plot_by = sys.argv[ind+1]
if plot_by == 'sit':
plot_key = 'er_site_name'
if plot_by == 'sam':
plot_key = 'er_sample_name'
if plot_by == 'spc':
plot_key = 'er_specimen_name'
if '-XLP' in sys.argv:
ind = sys.argv.index("-XLP")
XLP = sys.argv[ind+1] # get lab protocol for excluding
if '-LT' in sys.argv:
ind = sys.argv.index("-LT")
LT = 'LT-'+sys.argv[ind+1]+'-Z' # get lab treatment for plotting
if LT == 'LT-T-Z':
units, dmag_key = 'K', 'treatment_temp'
elif LT == 'LT-AF-Z':
units, dmag_key = 'T', 'treatment_ac_field'
elif LT == 'LT-M-Z':
units, dmag_key = 'J', 'treatment_mw_energy'
else:
units = 'U'
data, file_type = pmag.magic_read(in_file)
sids = pmag.get_specs(data)
pmagplotlib.plot_init(FIG['demag'], 5, 5)
print(len(data), ' records read from ', in_file)
#
#
# find desired intensity data
#
#
plotlist, intlist = [], ['measurement_magnitude', 'measurement_magn_moment',
'measurement_magn_volume', 'measurement_magn_mass']
IntMeths = []
FixData = []
for rec in data:
meths = []
methcodes = rec['magic_method_codes'].split(':')
for meth in methcodes:
meths.append(meth.strip())
for key in rec.keys():
if key in intlist and rec[key] != "":
if key not in IntMeths:
IntMeths.append(key)
if rec[plot_key] not in plotlist and LT in meths:
plotlist.append(rec[plot_key])
if 'measurement_flag' not in rec.keys():
rec['measurement_flag'] = 'g'
FixData.append(rec)
plotlist.sort()
if len(IntMeths) == 0:
print('No intensity information found')
sys.exit()
data = FixData
# plot first intensity method found - normalized to initial value anyway - doesn't matter which used
int_key = IntMeths[0]
for plt in plotlist:
if plot == 0:
print(plt, 'plotting by: ', plot_key)
# fish out all the data for this type of plot
PLTblock = pmag.get_dictitem(data, plot_key, plt, 'T')
# fish out all the dmag for this experiment type
PLTblock = pmag.get_dictitem(PLTblock, 'magic_method_codes', LT, 'has')
# get all with this intensity key non-blank
PLTblock = pmag.get_dictitem(PLTblock, int_key, '', 'F')
if XLP != "":
# reject data with XLP in method_code
PLTblock = pmag.get_dictitem(
PLTblock, 'magic_method_codes', XLP, 'not')
if len(PLTblock) > 2:
title = PLTblock[0][plot_key]
spcs = []
for rec in PLTblock:
if rec['er_specimen_name'] not in spcs:
spcs.append(rec['er_specimen_name'])
for spc in spcs:
# plot specimen by specimen
SPCblock = pmag.get_dictitem(
PLTblock, 'er_specimen_name', spc, 'T')
INTblock = []
for rec in SPCblock:
INTblock.append([float(rec[dmag_key]), 0, 0, float(
rec[int_key]), 1, rec['measurement_flag']])
if len(INTblock) > 2:
pmagplotlib.plot_mag(
FIG['demag'], INTblock, title, 0, units, norm)
if plot == 1:
files = {}
for key in FIG.keys():
files[key] = title+'_'+LT+'.'+fmt
pmagplotlib.save_plots(FIG, files)
sys.exit()
else:
pmagplotlib.draw_figs(FIG)
ans = input(
" S[a]ve to save plot, [q]uit, Return to continue: ")
if ans == 'q':
sys.exit()
if ans == "a":
files = {}
for key in FIG.keys():
files[key] = title+'_'+LT+'.'+fmt
pmagplotlib.save_plots(FIG, files)
pmagplotlib.clearFIG(FIG['demag']) | NAME
dmag_magic2.py
DESCRIPTION
plots intensity decay curves for demagnetization experiments
SYNTAX
dmag_magic -h [command line options]
INPUT
takes magic formatted magic_measurements.txt files
OPTIONS
-h prints help message and quits
-f FILE: specify input file, default is: magic_measurements.txt
-obj OBJ: specify object [loc, sit, sam, spc] for plot, default is by location
-LT [AF,T,M]: specify lab treatment type, default AF
-XLP [PI]: exclude specific lab protocols (for example, method codes like LP-PI)
-N do not normalize by NRM magnetization
-sav save plots silently and quit
-fmt [svg,jpg,png,pdf] set figure format [default is svg]
NOTE
loc: location (study); sit: site; sam: sample; spc: specimen | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/dmag_magic2.py#L11-L164 |
PmagPy/PmagPy | programs/deprecated/mini_magic.py | main | 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 | 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) | 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 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/deprecated/mini_magic.py#L7-L78 |
PmagPy/PmagPy | programs/deprecated/customize_criteria.py | main | def main():
"""
NAME
customize_criteria.py
NB: This program has been deprecated - use demag_gui or thellier_gui
to customize acceptance criteria - OR pandas from within a jupyter notebook
DESCRIPTION
Allows user to specify acceptance criteria, saves them in pmag_criteria.txt
SYNTAX
customize_criteria.py [-h][command line options]
OPTIONS
-h prints help message and quits
-f IFILE, reads in existing criteria
-F OFILE, writes to pmag_criteria format file
DEFAULTS
IFILE: pmag_criteria.txt
OFILE: pmag_criteria.txt
OUTPUT
creates a pmag_criteria.txt formatted output file
"""
infile,critout="","pmag_criteria.txt"
# parse command line options
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]
crit_data,file_type=pmag.magic_read(infile)
if file_type!='pmag_criteria':
print('bad input file')
print(main.__doc__)
sys.exit()
print("Acceptance criteria read in from ", infile)
if '-F' in sys.argv:
ind=sys.argv.index('-F')
critout=sys.argv[ind+1]
Dcrit,Icrit,nocrit=0,0,0
custom='1'
crit=input(" [0] Use no acceptance criteria?\n [1] Use default criteria\n [2] customize criteria \n ")
if crit=='0':
print('Very very loose criteria saved in ',critout)
crit_data=pmag.default_criteria(1)
pmag.magic_write(critout,crit_data,'pmag_criteria')
sys.exit()
crit_data=pmag.default_criteria(0)
if crit=='1':
print('Default criteria saved in ',critout)
pmag.magic_write(critout,crit_data,'pmag_criteria')
sys.exit()
CritRec=crit_data[0]
crit_keys=list(CritRec.keys())
crit_keys.sort()
print("Enter new threshold value.\n Return to keep default.\n Leave blank to not use as a criterion\n ")
for key in crit_keys:
if key!='pmag_criteria_code' and key!='er_citation_names' and key!='criteria_definition' and CritRec[key]!="":
print(key, CritRec[key])
new=input('new value: ')
if new != "": CritRec[key]=(new)
pmag.magic_write(critout,[CritRec],'pmag_criteria')
print("Criteria saved in pmag_criteria.txt") | python | def main():
"""
NAME
customize_criteria.py
NB: This program has been deprecated - use demag_gui or thellier_gui
to customize acceptance criteria - OR pandas from within a jupyter notebook
DESCRIPTION
Allows user to specify acceptance criteria, saves them in pmag_criteria.txt
SYNTAX
customize_criteria.py [-h][command line options]
OPTIONS
-h prints help message and quits
-f IFILE, reads in existing criteria
-F OFILE, writes to pmag_criteria format file
DEFAULTS
IFILE: pmag_criteria.txt
OFILE: pmag_criteria.txt
OUTPUT
creates a pmag_criteria.txt formatted output file
"""
infile,critout="","pmag_criteria.txt"
# parse command line options
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]
crit_data,file_type=pmag.magic_read(infile)
if file_type!='pmag_criteria':
print('bad input file')
print(main.__doc__)
sys.exit()
print("Acceptance criteria read in from ", infile)
if '-F' in sys.argv:
ind=sys.argv.index('-F')
critout=sys.argv[ind+1]
Dcrit,Icrit,nocrit=0,0,0
custom='1'
crit=input(" [0] Use no acceptance criteria?\n [1] Use default criteria\n [2] customize criteria \n ")
if crit=='0':
print('Very very loose criteria saved in ',critout)
crit_data=pmag.default_criteria(1)
pmag.magic_write(critout,crit_data,'pmag_criteria')
sys.exit()
crit_data=pmag.default_criteria(0)
if crit=='1':
print('Default criteria saved in ',critout)
pmag.magic_write(critout,crit_data,'pmag_criteria')
sys.exit()
CritRec=crit_data[0]
crit_keys=list(CritRec.keys())
crit_keys.sort()
print("Enter new threshold value.\n Return to keep default.\n Leave blank to not use as a criterion\n ")
for key in crit_keys:
if key!='pmag_criteria_code' and key!='er_citation_names' and key!='criteria_definition' and CritRec[key]!="":
print(key, CritRec[key])
new=input('new value: ')
if new != "": CritRec[key]=(new)
pmag.magic_write(critout,[CritRec],'pmag_criteria')
print("Criteria saved in pmag_criteria.txt") | NAME
customize_criteria.py
NB: This program has been deprecated - use demag_gui or thellier_gui
to customize acceptance criteria - OR pandas from within a jupyter notebook
DESCRIPTION
Allows user to specify acceptance criteria, saves them in pmag_criteria.txt
SYNTAX
customize_criteria.py [-h][command line options]
OPTIONS
-h prints help message and quits
-f IFILE, reads in existing criteria
-F OFILE, writes to pmag_criteria format file
DEFAULTS
IFILE: pmag_criteria.txt
OFILE: pmag_criteria.txt
OUTPUT
creates a pmag_criteria.txt formatted output file | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/deprecated/customize_criteria.py#L7-L72 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.get_DIR | 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 | 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() | open dialog box for choosing a working directory | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L465-L495 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.Main_Frame | def Main_Frame(self):
"""
Build main frame od panel: buttons, etc.
choose the first specimen and display data
"""
#--------------------------------------------------------------------
# initialize first specimen in list as current specimen
#--------------------------------------------------------------------
try:
self.s = self.specimens[0]
except:
self.s = ""
print("No specimens during UI build")
#--------------------------------------------------------------------
# create main panel in the right size
#--------------------------------------------------------------------
dw, dh = wx.DisplaySize()
w, h = self.GetSize()
r1 = dw / 1250.
r2 = dw / 750.
GUI_RESOLUTION = min(r1, r2, 1.3)
if 'gui_resolution' in list(self.preferences.keys()):
if float(self.preferences['gui_resolution']) != 1:
self.GUI_RESOLUTION = float(
self.preferences['gui_resolution']) / 100
else:
self.GUI_RESOLUTION = min(r1, r2, 1.3)
else:
self.GUI_RESOLUTION = min(r1, r2, 1.3)
#--------------------------------------------------------------------
# adjust font size
#--------------------------------------------------------------------
self.font_type = "Arial"
if sys.platform.startswith("linux"):
self.font_type = "Liberation Serif"
if self.GUI_RESOLUTION >= 1.1 and self.GUI_RESOLUTION <= 1.3:
font2 = wx.Font(13, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
elif self.GUI_RESOLUTION <= 0.9 and self.GUI_RESOLUTION < 1.0:
font2 = wx.Font(11, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
elif self.GUI_RESOLUTION <= 0.9:
font2 = wx.Font(10, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
else:
font2 = wx.Font(12, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
print(" self.GUI_RESOLUTION", self.GUI_RESOLUTION)
h_space = 4
v_space = 4
# set font size and style
#font1 = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Comic Sans MS')
FONT_RATIO = self.GUI_RESOLUTION + (self.GUI_RESOLUTION - 1) * 5
font1 = wx.Font(9 + FONT_RATIO, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
# GUI headers
font3 = wx.Font(11 + FONT_RATIO, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
font.SetPointSize(10 + FONT_RATIO)
#--------------------------------------------------------------------
# Create Figures and FigCanvas objects.
#--------------------------------------------------------------------
self.fig1 = Figure((5. * self.GUI_RESOLUTION, 5. *
self.GUI_RESOLUTION), dpi=self.dpi)
self.canvas1 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig1)
self.fig1.text(0.01, 0.98, "Arai plot", {
'family': self.font_type, 'fontsize': 10, 'style': 'normal', 'va': 'center', 'ha': 'left'})
self.toolbar1 = NavigationToolbar(self.canvas1)
self.toolbar1.Hide()
self.fig1_setting = "Zoom"
self.toolbar1.zoom()
self.canvas1.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
self.canvas1.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)
self.fig2 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
self.GUI_RESOLUTION), dpi=self.dpi)
self.canvas2 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig2)
self.fig2.text(0.02, 0.96, "Zijderveld", {
'family': self.font_type, 'fontsize': 10, 'style': 'normal', 'va': 'center', 'ha': 'left'})
self.toolbar2 = NavigationToolbar(self.canvas2)
self.toolbar2.Hide()
self.fig2_setting = "Zoom"
self.toolbar2.zoom()
self.canvas2.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
self.canvas2.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)
self.fig3 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
self.GUI_RESOLUTION), dpi=self.dpi)
self.canvas3 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig3)
#self.fig3.text(0.02,0.96,"Equal area",{'family':self.font_type, 'fontsize':10*self.GUI_RESOLUTION, 'style':'normal','va':'center', 'ha':'left' })
self.toolbar3 = NavigationToolbar(self.canvas3)
self.toolbar3.Hide()
self.fig3_setting = "Zoom"
self.toolbar3.zoom()
self.canvas3.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
self.canvas3.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)
self.fig4 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
self.GUI_RESOLUTION), dpi=self.dpi)
self.canvas4 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig4)
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'site':
TEXT = "Site data"
else:
TEXT = "Sample data"
self.fig4.text(0.02, 0.96, TEXT, {
'family': self.font_type, 'fontsize': 10, 'style': 'normal', 'va': 'center', 'ha': 'left'})
self.toolbar4 = NavigationToolbar(self.canvas4)
self.toolbar4.Hide()
self.fig4_setting = "Zoom"
self.toolbar4.zoom()
self.canvas4.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
self.canvas4.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)
self.fig5 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
self.GUI_RESOLUTION), dpi=self.dpi)
self.canvas5 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig5)
#self.fig5.text(0.02,0.96,"M/M0",{'family':self.font_type, 'fontsize':10, 'style':'normal','va':'center', 'ha':'left' })
self.toolbar5 = NavigationToolbar(self.canvas5)
self.toolbar5.Hide()
self.fig5_setting = "Zoom"
self.toolbar5.zoom()
self.canvas5.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
self.canvas5.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)
# make axes of the figures
self.araiplot = self.fig1.add_axes([0.1, 0.1, 0.8, 0.8])
self.zijplot = self.fig2.add_subplot(111)
self.eqplot = self.fig3.add_subplot(111)
self.sampleplot = self.fig4.add_axes(
[0.2, 0.3, 0.7, 0.6], frameon=True, facecolor='None')
self.mplot = self.fig5.add_axes(
[0.2, 0.15, 0.7, 0.7], frameon=True, facecolor='None')
#--------------------------------------------------------------------
# text box displaying measurement data
#--------------------------------------------------------------------
self.logger = wx.ListCtrl(self.side_panel, id=wx.ID_ANY, size=(
100 * self.GUI_RESOLUTION, 100 * self.GUI_RESOLUTION), style=wx.LC_REPORT)
self.logger.SetFont(font1)
self.logger.InsertColumn(0, 'i', width=45 * self.GUI_RESOLUTION)
self.logger.InsertColumn(1, 'Step', width=45 * self.GUI_RESOLUTION)
self.logger.InsertColumn(2, 'Tr', width=65 * self.GUI_RESOLUTION)
self.logger.InsertColumn(3, 'Dec', width=65 * self.GUI_RESOLUTION)
self.logger.InsertColumn(4, 'Inc', width=65 * self.GUI_RESOLUTION)
self.logger.InsertColumn(5, 'M', width=75 * self.GUI_RESOLUTION)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED,
self.on_click_listctrl, self.logger)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK,
self.on_right_click_listctrl, self.logger)
#--------------------------------------------------------------------
# select a specimen box
#--------------------------------------------------------------------
# Combo-box with a list of specimen
self.specimens_box = wx.ComboBox(self.top_panel, wx.ID_ANY, self.s, (250 * self.GUI_RESOLUTION, 25),
wx.DefaultSize, self.specimens, wx.CB_DROPDOWN | wx.TE_PROCESS_ENTER, name="specimen")
self.specimens_box.SetFont(font2)
self.Bind(wx.EVT_COMBOBOX, self.onSelect_specimen, self.specimens_box)
self.Bind(wx.EVT_TEXT_ENTER, self.onSelect_specimen,
self.specimens_box)
# buttons to move forward and backwards from specimens
nextbutton = wx.Button(self.top_panel, id=wx.ID_ANY, label='next', size=(
75 * self.GUI_RESOLUTION, 25)) # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
self.Bind(wx.EVT_BUTTON, self.on_next_button, nextbutton)
nextbutton.SetFont(font2)
prevbutton = wx.Button(self.top_panel, id=wx.ID_ANY, label='previous', size=(
75 * self.GUI_RESOLUTION, 25)) # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
prevbutton.SetFont(font2)
self.Bind(wx.EVT_BUTTON, self.on_prev_button, prevbutton)
#--------------------------------------------------------------------
# select temperature bounds
#--------------------------------------------------------------------
try:
if self.Data[self.s]['T_or_MW'] == "T":
self.temperatures = np.array(
self.Data[self.s]['t_Arai']) - 273.
self.T_list = ["%.0f" % T for T in self.temperatures]
elif self.Data[self.s]['T_or_MW'] == "MW":
self.temperatures = np.array(self.Data[self.s]['t_Arai'])
self.T_list = ["%.0f" % T for T in self.temperatures]
except (ValueError, TypeError, KeyError) as e:
self.T_list = []
self.tmin_box = wx.ComboBox(self.top_panel, wx.ID_ANY, size=(
100 * self.GUI_RESOLUTION, 25), choices=self.T_list, style=wx.CB_DROPDOWN | wx.TE_READONLY)
self.Bind(wx.EVT_COMBOBOX, self.get_new_T_PI_parameters, self.tmin_box)
self.tmax_box = wx.ComboBox(self.top_panel, -1, size=(100 * self.GUI_RESOLUTION, 25),
choices=self.T_list, style=wx.CB_DROPDOWN | wx.TE_READONLY)
self.Bind(wx.EVT_COMBOBOX, self.get_new_T_PI_parameters, self.tmax_box)
#--------------------------------------------------------------------
# save/delete buttons
#--------------------------------------------------------------------
# save/delete interpretation buttons
self.save_interpretation_button = wx.Button(self.top_panel, id=-1, label='save', size=(
75 * self.GUI_RESOLUTION, 25)) # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
self.save_interpretation_button.SetFont(font2)
self.delete_interpretation_button = wx.Button(self.top_panel, id=-1, label='delete', size=(
75 * self.GUI_RESOLUTION, 25)) # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
self.delete_interpretation_button.SetFont(font2)
self.Bind(wx.EVT_BUTTON, self.on_save_interpretation_button,
self.save_interpretation_button)
self.Bind(wx.EVT_BUTTON, self.on_delete_interpretation_button,
self.delete_interpretation_button)
self.auto_save = wx.CheckBox(self.top_panel, wx.ID_ANY, 'auto-save')
self.auto_save_info = wx.Button(self.top_panel, wx.ID_ANY, "?")
self.Bind(wx.EVT_BUTTON, self.on_info_click, self.auto_save_info)
#self.auto_save_text = wx.StaticText(self.top_panel, wx.ID_ANY, label="(saves with 'next')")
#--------------------------------------------------------------------
# specimen interpretation and statistics window (Blab; Banc, Dec, Inc, correction factors etc.)
#--------------------------------------------------------------------
self.Blab_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.Banc_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.Aniso_factor_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.NLT_factor_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.CR_factor_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.declination_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.inclination_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
for stat in ['Blab', 'Banc', 'Aniso_factor', 'NLT_factor', 'CR_factor', 'declination', 'inclination']:
exec("self.%s_window.SetBackgroundColour(wx.WHITE)" % stat)
self.Blab_label = wx.StaticText(
self.top_panel, label="\nB_lab", style=wx.ALIGN_CENTRE)
self.Blab_label.SetFont(font2)
self.Banc_label = wx.StaticText(
self.top_panel, label="\nB_anc", style=wx.ALIGN_CENTRE)
self.Banc_label.SetFont(font2)
self.aniso_corr_label = wx.StaticText(
self.top_panel, label="Aniso\ncorr", style=wx.ALIGN_CENTRE)
self.aniso_corr_label.SetFont(font2)
self.nlt_corr_label = wx.StaticText(
self.top_panel, label="NLT\ncorr", style=wx.ALIGN_CENTRE)
self.nlt_corr_label.SetFont(font2)
self.cr_corr_label = wx.StaticText(
self.top_panel, label="CR\ncorr", style=wx.ALIGN_CENTRE)
self.cr_corr_label.SetFont(font2)
self.dec_label = wx.StaticText(
self.top_panel, label="\nDec", style=wx.ALIGN_CENTRE)
self.dec_label.SetFont(font2)
self.inc_label = wx.StaticText(
self.top_panel, label="\nInc", style=wx.ALIGN_CENTRE)
self.inc_label.SetFont(font2)
# handle Specimen Results Sizer
sizer_specimen_results = wx.StaticBoxSizer(wx.StaticBox(
self.top_panel, wx.ID_ANY, "specimen results"), wx.HORIZONTAL)
specimen_stat_window = wx.GridSizer(2, 7, h_space, v_space)
specimen_stat_window.AddMany([(self.Blab_label, 1, wx.ALIGN_BOTTOM),
((self.Banc_label), 1, wx.ALIGN_BOTTOM),
((self.aniso_corr_label), 1, wx.ALIGN_BOTTOM),
((self.nlt_corr_label), 1, wx.ALIGN_BOTTOM),
((self.cr_corr_label), 1, wx.ALIGN_BOTTOM),
((self.dec_label), 1,
wx.TE_CENTER | wx.ALIGN_BOTTOM),
((self.inc_label), 1, wx.ALIGN_BOTTOM),
(self.Blab_window, 1, wx.EXPAND),
(self.Banc_window, 1, wx.EXPAND),
(self.Aniso_factor_window, 1, wx.EXPAND),
(self.NLT_factor_window, 1, wx.EXPAND),
(self.CR_factor_window, 1, wx.EXPAND),
(self.declination_window, 1, wx.EXPAND),
(self.inclination_window, 1, wx.EXPAND)])
sizer_specimen_results.Add(
specimen_stat_window, 1, wx.EXPAND | wx.ALIGN_LEFT, 0)
#--------------------------------------------------------------------
# Sample interpretation window
#--------------------------------------------------------------------
for key in ["sample_int_n", "sample_int_uT", "sample_int_sigma", "sample_int_sigma_perc"]:
command = "self.%s_window=wx.TextCtrl(self.top_panel,style=wx.TE_CENTER|wx.TE_READONLY,size=(50*self.GUI_RESOLUTION,25))" % key
exec(command)
exec("self.%s_window.SetBackgroundColour(wx.WHITE)" % key)
sample_mean_label = wx.StaticText(
self.top_panel, label="\nmean", style=wx.TE_CENTER)
sample_mean_label.SetFont(font2)
sample_N_label = wx.StaticText(
self.top_panel, label="\nN ", style=wx.TE_CENTER)
sample_N_label.SetFont(font2)
sample_std_label = wx.StaticText(
self.top_panel, label="\nstd uT", style=wx.TE_CENTER)
sample_std_label.SetFont(font2)
sample_std_per_label = wx.StaticText(
self.top_panel, label="\nstd %", style=wx.TE_CENTER)
sample_std_per_label.SetFont(font2)
# handle samples/sites results sizers
sizer_sample_results = wx.StaticBoxSizer(wx.StaticBox(
self.top_panel, wx.ID_ANY, "sample/site results"), wx.HORIZONTAL)
sample_stat_window = wx.GridSizer(2, 4, h_space, v_space)
sample_stat_window.AddMany([(sample_mean_label, 1, wx.ALIGN_BOTTOM),
(sample_N_label, 1, wx.ALIGN_BOTTOM),
(sample_std_label, 1, wx.ALIGN_BOTTOM),
(sample_std_per_label, 1, wx.ALIGN_BOTTOM),
(self.sample_int_uT_window, 1, wx.EXPAND),
(self.sample_int_n_window, 1, wx.EXPAND),
(self.sample_int_sigma_window, 1, wx.EXPAND),
(self.sample_int_sigma_perc_window, 1, wx.EXPAND)])
sizer_sample_results.Add(
sample_stat_window, 1, wx.EXPAND | wx.ALIGN_LEFT, 0)
#--------------------------------------------------------------------
label_0 = wx.StaticText(
self.bottom_panel, label=" ", style=wx.ALIGN_CENTER, size=(180, 25))
label_1 = wx.StaticText(
self.bottom_panel, label="Acceptance criteria:", style=wx.ALIGN_CENTER, size=(180, 25))
label_2 = wx.StaticText(
self.bottom_panel, label="Specimen statistics:", style=wx.ALIGN_CENTER, size=(180, 25))
for statistic in self.preferences['show_statistics_on_gui']:
self.stat_windows[statistic] = wx.TextCtrl(
self.bottom_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.stat_windows[statistic].SetBackgroundColour(wx.WHITE)
self.stat_windows[statistic].SetFont(font2)
self.threshold_windows[statistic] = wx.TextCtrl(
self.bottom_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.threshold_windows[statistic].SetFont(font2)
self.threshold_windows[statistic].SetBackgroundColour(wx.WHITE)
label = statistic.replace("specimen_", "").replace("int_", "")
self.stat_labels[statistic] = wx.StaticText(
self.bottom_panel, label=label, style=wx.ALIGN_CENTRE_HORIZONTAL | wx.ALIGN_BOTTOM)
self.stat_labels[statistic].SetFont(font2)
#-------------------------------------------------------------------
# Design the panels
#-------------------------------------------------------------------
# Plots Panel--------------------------------------------------------
sizer_grid_plots = wx.GridSizer(2, 2, 0, 0)
sizer_grid_plots.AddMany([(self.canvas2, 1, wx.EXPAND),
(self.canvas4, 1, wx.EXPAND),
(self.canvas3, 1, wx.EXPAND),
(self.canvas5, 1, wx.EXPAND)])
sizer_plots_outer = wx.BoxSizer(wx.HORIZONTAL)
sizer_plots_outer.Add(self.canvas1, 1, wx.EXPAND)
sizer_plots_outer.Add(sizer_grid_plots, 1, wx.EXPAND)
# Top Bar Sizer-------------------------------------------------------
#-------------Specimens Sizer----------------------------------------
sizer_prev_next_btns = wx.BoxSizer(wx.HORIZONTAL)
sizer_prev_next_btns.Add(prevbutton, 1, wx.EXPAND | wx.RIGHT, h_space)
sizer_prev_next_btns.Add(nextbutton, 1, wx.EXPAND | wx.LEFT, h_space)
sizer_select_specimen = wx.StaticBoxSizer(wx.StaticBox(
self.top_panel, wx.ID_ANY, "specimen"), wx.VERTICAL)
sizer_select_specimen.Add(
self.specimens_box, 1, wx.EXPAND | wx.BOTTOM, v_space)
sizer_select_specimen.Add(
sizer_prev_next_btns, 1, wx.EXPAND | wx.TOP, v_space)
#-------------Bounds Sizer----------------------------------------
sizer_grid_bounds_btns = wx.GridSizer(2, 3, 2 * h_space, 2 * v_space)
sizer_grid_bounds_btns.AddMany([(self.tmin_box, 1, wx.EXPAND),
(self.save_interpretation_button,
1, wx.EXPAND), (self.auto_save, 1, wx.EXPAND),
(self.tmax_box, 1, wx.EXPAND),
(self.delete_interpretation_button, 1, wx.EXPAND),
(self.auto_save_info, 1, wx.EXPAND)])
if self.s in list(self.Data.keys()) and self.Data[self.s]['T_or_MW'] == "T":
sizer_select_temp = wx.StaticBoxSizer(wx.StaticBox(
self.top_panel, wx.ID_ANY, "temperatures"), wx.HORIZONTAL)
else:
sizer_select_temp = wx.StaticBoxSizer(wx.StaticBox(
self.top_panel, wx.ID_ANY, "MW power"), wx.HORIZONTAL)
sizer_select_temp.Add(sizer_grid_bounds_btns, 1, wx.EXPAND)
#-------------Top Bar Outer Sizer------------------------------------
sizer_top_bar = wx.BoxSizer(wx.HORIZONTAL)
sizer_top_bar.AddMany([(sizer_select_specimen, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.RIGHT, 2 * h_space),
(sizer_select_temp, 1, wx.EXPAND |
wx.ALIGN_LEFT | wx.RIGHT, 2 * h_space),
(sizer_specimen_results, 2, wx.EXPAND |
wx.ALIGN_LEFT | wx.RIGHT, 2 * h_space),
(sizer_sample_results, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.RIGHT, 0)])
# Bottom Bar Sizer----------------------------------------------------
#----------------Criteria Labels Sizer-------------------------------
sizer_criteria_labels = wx.BoxSizer(wx.HORIZONTAL)
sizer_criteria_labels.Add(label_0, 3, wx.EXPAND | wx.LEFT, 2 * h_space)
sizer_criteria_boxes = wx.BoxSizer(wx.HORIZONTAL)
sizer_criteria_boxes.Add(label_1, 3, wx.EXPAND | wx.LEFT, 2 * h_space)
sizer_stats_boxes = wx.BoxSizer(wx.HORIZONTAL)
sizer_stats_boxes.Add(label_2, 3, wx.EXPAND | wx.LEFT, 2 * h_space)
for statistic in self.preferences['show_statistics_on_gui']:
sizer_criteria_labels.Add(
self.stat_labels[statistic], 1, wx.ALIGN_BOTTOM, 0)
#----------------Acceptance Criteria Boxes---------------------------
sizer_criteria_boxes.Add(
self.threshold_windows[statistic], 1, wx.EXPAND | wx.LEFT, h_space)
#----------------Specimen Statistics Boxes---------------------------
sizer_stats_boxes.Add(
self.stat_windows[statistic], 1, wx.EXPAND | wx.LEFT, h_space)
#----------------Bottom Outer Sizer----------------------------------
sizer_bottom_bar = wx.BoxSizer(wx.VERTICAL)
sizer_bottom_bar.AddMany([(sizer_criteria_labels, 1, wx.EXPAND | wx.ALIGN_BOTTOM | wx.BOTTOM, v_space),
(sizer_criteria_boxes, 1, wx.EXPAND |
wx.BOTTOM | wx.ALIGN_TOP, v_space),
(sizer_stats_boxes, 1, wx.EXPAND | wx.ALIGN_TOP)])
# Logger Sizer--------------------------------------------------------
sizer_logger = wx.BoxSizer(wx.HORIZONTAL)
sizer_logger.Add(self.logger, 1, wx.EXPAND)
# Set Panel Sizers----------------------------------------------------
self.plot_panel.SetSizer(sizer_plots_outer)
self.side_panel.SetSizerAndFit(sizer_logger)
self.top_panel.SetSizerAndFit(sizer_top_bar)
self.bottom_panel.SetSizerAndFit(sizer_bottom_bar)
# Outer Sizer for Frame-----------------------------------------------
sizer_logger_plots = wx.BoxSizer(wx.HORIZONTAL)
sizer_logger_plots.Add(self.side_panel, 1, wx.EXPAND | wx.ALIGN_LEFT)
sizer_logger_plots.Add(self.plot_panel, 3, wx.EXPAND | wx.ALIGN_LEFT)
sizer_outer = wx.BoxSizer(wx.VERTICAL)
sizer_outer.AddMany([(self.top_panel, 1, wx.EXPAND | wx.ALIGN_TOP | wx.BOTTOM, v_space / 2),
(sizer_logger_plots, 4, wx.EXPAND |
wx.ALIGN_TOP | wx.BOTTOM, v_space / 2),
(self.bottom_panel, 1, wx.EXPAND | wx.ALIGN_TOP)])
self.SetSizer(sizer_outer)
sizer_outer.Fit(self)
self.Layout() | python | def Main_Frame(self):
"""
Build main frame od panel: buttons, etc.
choose the first specimen and display data
"""
#--------------------------------------------------------------------
# initialize first specimen in list as current specimen
#--------------------------------------------------------------------
try:
self.s = self.specimens[0]
except:
self.s = ""
print("No specimens during UI build")
#--------------------------------------------------------------------
# create main panel in the right size
#--------------------------------------------------------------------
dw, dh = wx.DisplaySize()
w, h = self.GetSize()
r1 = dw / 1250.
r2 = dw / 750.
GUI_RESOLUTION = min(r1, r2, 1.3)
if 'gui_resolution' in list(self.preferences.keys()):
if float(self.preferences['gui_resolution']) != 1:
self.GUI_RESOLUTION = float(
self.preferences['gui_resolution']) / 100
else:
self.GUI_RESOLUTION = min(r1, r2, 1.3)
else:
self.GUI_RESOLUTION = min(r1, r2, 1.3)
#--------------------------------------------------------------------
# adjust font size
#--------------------------------------------------------------------
self.font_type = "Arial"
if sys.platform.startswith("linux"):
self.font_type = "Liberation Serif"
if self.GUI_RESOLUTION >= 1.1 and self.GUI_RESOLUTION <= 1.3:
font2 = wx.Font(13, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
elif self.GUI_RESOLUTION <= 0.9 and self.GUI_RESOLUTION < 1.0:
font2 = wx.Font(11, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
elif self.GUI_RESOLUTION <= 0.9:
font2 = wx.Font(10, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
else:
font2 = wx.Font(12, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
print(" self.GUI_RESOLUTION", self.GUI_RESOLUTION)
h_space = 4
v_space = 4
# set font size and style
#font1 = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Comic Sans MS')
FONT_RATIO = self.GUI_RESOLUTION + (self.GUI_RESOLUTION - 1) * 5
font1 = wx.Font(9 + FONT_RATIO, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
# GUI headers
font3 = wx.Font(11 + FONT_RATIO, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
font.SetPointSize(10 + FONT_RATIO)
#--------------------------------------------------------------------
# Create Figures and FigCanvas objects.
#--------------------------------------------------------------------
self.fig1 = Figure((5. * self.GUI_RESOLUTION, 5. *
self.GUI_RESOLUTION), dpi=self.dpi)
self.canvas1 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig1)
self.fig1.text(0.01, 0.98, "Arai plot", {
'family': self.font_type, 'fontsize': 10, 'style': 'normal', 'va': 'center', 'ha': 'left'})
self.toolbar1 = NavigationToolbar(self.canvas1)
self.toolbar1.Hide()
self.fig1_setting = "Zoom"
self.toolbar1.zoom()
self.canvas1.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
self.canvas1.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)
self.fig2 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
self.GUI_RESOLUTION), dpi=self.dpi)
self.canvas2 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig2)
self.fig2.text(0.02, 0.96, "Zijderveld", {
'family': self.font_type, 'fontsize': 10, 'style': 'normal', 'va': 'center', 'ha': 'left'})
self.toolbar2 = NavigationToolbar(self.canvas2)
self.toolbar2.Hide()
self.fig2_setting = "Zoom"
self.toolbar2.zoom()
self.canvas2.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
self.canvas2.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)
self.fig3 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
self.GUI_RESOLUTION), dpi=self.dpi)
self.canvas3 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig3)
#self.fig3.text(0.02,0.96,"Equal area",{'family':self.font_type, 'fontsize':10*self.GUI_RESOLUTION, 'style':'normal','va':'center', 'ha':'left' })
self.toolbar3 = NavigationToolbar(self.canvas3)
self.toolbar3.Hide()
self.fig3_setting = "Zoom"
self.toolbar3.zoom()
self.canvas3.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
self.canvas3.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)
self.fig4 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
self.GUI_RESOLUTION), dpi=self.dpi)
self.canvas4 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig4)
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'site':
TEXT = "Site data"
else:
TEXT = "Sample data"
self.fig4.text(0.02, 0.96, TEXT, {
'family': self.font_type, 'fontsize': 10, 'style': 'normal', 'va': 'center', 'ha': 'left'})
self.toolbar4 = NavigationToolbar(self.canvas4)
self.toolbar4.Hide()
self.fig4_setting = "Zoom"
self.toolbar4.zoom()
self.canvas4.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
self.canvas4.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)
self.fig5 = Figure((2.5 * self.GUI_RESOLUTION, 2.5 *
self.GUI_RESOLUTION), dpi=self.dpi)
self.canvas5 = FigCanvas(self.plot_panel, wx.ID_ANY, self.fig5)
#self.fig5.text(0.02,0.96,"M/M0",{'family':self.font_type, 'fontsize':10, 'style':'normal','va':'center', 'ha':'left' })
self.toolbar5 = NavigationToolbar(self.canvas5)
self.toolbar5.Hide()
self.fig5_setting = "Zoom"
self.toolbar5.zoom()
self.canvas5.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click_fig)
self.canvas5.Bind(wx.EVT_MIDDLE_DOWN, self.on_home_fig)
# make axes of the figures
self.araiplot = self.fig1.add_axes([0.1, 0.1, 0.8, 0.8])
self.zijplot = self.fig2.add_subplot(111)
self.eqplot = self.fig3.add_subplot(111)
self.sampleplot = self.fig4.add_axes(
[0.2, 0.3, 0.7, 0.6], frameon=True, facecolor='None')
self.mplot = self.fig5.add_axes(
[0.2, 0.15, 0.7, 0.7], frameon=True, facecolor='None')
#--------------------------------------------------------------------
# text box displaying measurement data
#--------------------------------------------------------------------
self.logger = wx.ListCtrl(self.side_panel, id=wx.ID_ANY, size=(
100 * self.GUI_RESOLUTION, 100 * self.GUI_RESOLUTION), style=wx.LC_REPORT)
self.logger.SetFont(font1)
self.logger.InsertColumn(0, 'i', width=45 * self.GUI_RESOLUTION)
self.logger.InsertColumn(1, 'Step', width=45 * self.GUI_RESOLUTION)
self.logger.InsertColumn(2, 'Tr', width=65 * self.GUI_RESOLUTION)
self.logger.InsertColumn(3, 'Dec', width=65 * self.GUI_RESOLUTION)
self.logger.InsertColumn(4, 'Inc', width=65 * self.GUI_RESOLUTION)
self.logger.InsertColumn(5, 'M', width=75 * self.GUI_RESOLUTION)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED,
self.on_click_listctrl, self.logger)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK,
self.on_right_click_listctrl, self.logger)
#--------------------------------------------------------------------
# select a specimen box
#--------------------------------------------------------------------
# Combo-box with a list of specimen
self.specimens_box = wx.ComboBox(self.top_panel, wx.ID_ANY, self.s, (250 * self.GUI_RESOLUTION, 25),
wx.DefaultSize, self.specimens, wx.CB_DROPDOWN | wx.TE_PROCESS_ENTER, name="specimen")
self.specimens_box.SetFont(font2)
self.Bind(wx.EVT_COMBOBOX, self.onSelect_specimen, self.specimens_box)
self.Bind(wx.EVT_TEXT_ENTER, self.onSelect_specimen,
self.specimens_box)
# buttons to move forward and backwards from specimens
nextbutton = wx.Button(self.top_panel, id=wx.ID_ANY, label='next', size=(
75 * self.GUI_RESOLUTION, 25)) # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
self.Bind(wx.EVT_BUTTON, self.on_next_button, nextbutton)
nextbutton.SetFont(font2)
prevbutton = wx.Button(self.top_panel, id=wx.ID_ANY, label='previous', size=(
75 * self.GUI_RESOLUTION, 25)) # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
prevbutton.SetFont(font2)
self.Bind(wx.EVT_BUTTON, self.on_prev_button, prevbutton)
#--------------------------------------------------------------------
# select temperature bounds
#--------------------------------------------------------------------
try:
if self.Data[self.s]['T_or_MW'] == "T":
self.temperatures = np.array(
self.Data[self.s]['t_Arai']) - 273.
self.T_list = ["%.0f" % T for T in self.temperatures]
elif self.Data[self.s]['T_or_MW'] == "MW":
self.temperatures = np.array(self.Data[self.s]['t_Arai'])
self.T_list = ["%.0f" % T for T in self.temperatures]
except (ValueError, TypeError, KeyError) as e:
self.T_list = []
self.tmin_box = wx.ComboBox(self.top_panel, wx.ID_ANY, size=(
100 * self.GUI_RESOLUTION, 25), choices=self.T_list, style=wx.CB_DROPDOWN | wx.TE_READONLY)
self.Bind(wx.EVT_COMBOBOX, self.get_new_T_PI_parameters, self.tmin_box)
self.tmax_box = wx.ComboBox(self.top_panel, -1, size=(100 * self.GUI_RESOLUTION, 25),
choices=self.T_list, style=wx.CB_DROPDOWN | wx.TE_READONLY)
self.Bind(wx.EVT_COMBOBOX, self.get_new_T_PI_parameters, self.tmax_box)
#--------------------------------------------------------------------
# save/delete buttons
#--------------------------------------------------------------------
# save/delete interpretation buttons
self.save_interpretation_button = wx.Button(self.top_panel, id=-1, label='save', size=(
75 * self.GUI_RESOLUTION, 25)) # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
self.save_interpretation_button.SetFont(font2)
self.delete_interpretation_button = wx.Button(self.top_panel, id=-1, label='delete', size=(
75 * self.GUI_RESOLUTION, 25)) # ,style=wx.BU_EXACTFIT)#, size=(175, 28))
self.delete_interpretation_button.SetFont(font2)
self.Bind(wx.EVT_BUTTON, self.on_save_interpretation_button,
self.save_interpretation_button)
self.Bind(wx.EVT_BUTTON, self.on_delete_interpretation_button,
self.delete_interpretation_button)
self.auto_save = wx.CheckBox(self.top_panel, wx.ID_ANY, 'auto-save')
self.auto_save_info = wx.Button(self.top_panel, wx.ID_ANY, "?")
self.Bind(wx.EVT_BUTTON, self.on_info_click, self.auto_save_info)
#self.auto_save_text = wx.StaticText(self.top_panel, wx.ID_ANY, label="(saves with 'next')")
#--------------------------------------------------------------------
# specimen interpretation and statistics window (Blab; Banc, Dec, Inc, correction factors etc.)
#--------------------------------------------------------------------
self.Blab_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.Banc_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.Aniso_factor_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.NLT_factor_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.CR_factor_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.declination_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.inclination_window = wx.TextCtrl(
self.top_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
for stat in ['Blab', 'Banc', 'Aniso_factor', 'NLT_factor', 'CR_factor', 'declination', 'inclination']:
exec("self.%s_window.SetBackgroundColour(wx.WHITE)" % stat)
self.Blab_label = wx.StaticText(
self.top_panel, label="\nB_lab", style=wx.ALIGN_CENTRE)
self.Blab_label.SetFont(font2)
self.Banc_label = wx.StaticText(
self.top_panel, label="\nB_anc", style=wx.ALIGN_CENTRE)
self.Banc_label.SetFont(font2)
self.aniso_corr_label = wx.StaticText(
self.top_panel, label="Aniso\ncorr", style=wx.ALIGN_CENTRE)
self.aniso_corr_label.SetFont(font2)
self.nlt_corr_label = wx.StaticText(
self.top_panel, label="NLT\ncorr", style=wx.ALIGN_CENTRE)
self.nlt_corr_label.SetFont(font2)
self.cr_corr_label = wx.StaticText(
self.top_panel, label="CR\ncorr", style=wx.ALIGN_CENTRE)
self.cr_corr_label.SetFont(font2)
self.dec_label = wx.StaticText(
self.top_panel, label="\nDec", style=wx.ALIGN_CENTRE)
self.dec_label.SetFont(font2)
self.inc_label = wx.StaticText(
self.top_panel, label="\nInc", style=wx.ALIGN_CENTRE)
self.inc_label.SetFont(font2)
# handle Specimen Results Sizer
sizer_specimen_results = wx.StaticBoxSizer(wx.StaticBox(
self.top_panel, wx.ID_ANY, "specimen results"), wx.HORIZONTAL)
specimen_stat_window = wx.GridSizer(2, 7, h_space, v_space)
specimen_stat_window.AddMany([(self.Blab_label, 1, wx.ALIGN_BOTTOM),
((self.Banc_label), 1, wx.ALIGN_BOTTOM),
((self.aniso_corr_label), 1, wx.ALIGN_BOTTOM),
((self.nlt_corr_label), 1, wx.ALIGN_BOTTOM),
((self.cr_corr_label), 1, wx.ALIGN_BOTTOM),
((self.dec_label), 1,
wx.TE_CENTER | wx.ALIGN_BOTTOM),
((self.inc_label), 1, wx.ALIGN_BOTTOM),
(self.Blab_window, 1, wx.EXPAND),
(self.Banc_window, 1, wx.EXPAND),
(self.Aniso_factor_window, 1, wx.EXPAND),
(self.NLT_factor_window, 1, wx.EXPAND),
(self.CR_factor_window, 1, wx.EXPAND),
(self.declination_window, 1, wx.EXPAND),
(self.inclination_window, 1, wx.EXPAND)])
sizer_specimen_results.Add(
specimen_stat_window, 1, wx.EXPAND | wx.ALIGN_LEFT, 0)
#--------------------------------------------------------------------
# Sample interpretation window
#--------------------------------------------------------------------
for key in ["sample_int_n", "sample_int_uT", "sample_int_sigma", "sample_int_sigma_perc"]:
command = "self.%s_window=wx.TextCtrl(self.top_panel,style=wx.TE_CENTER|wx.TE_READONLY,size=(50*self.GUI_RESOLUTION,25))" % key
exec(command)
exec("self.%s_window.SetBackgroundColour(wx.WHITE)" % key)
sample_mean_label = wx.StaticText(
self.top_panel, label="\nmean", style=wx.TE_CENTER)
sample_mean_label.SetFont(font2)
sample_N_label = wx.StaticText(
self.top_panel, label="\nN ", style=wx.TE_CENTER)
sample_N_label.SetFont(font2)
sample_std_label = wx.StaticText(
self.top_panel, label="\nstd uT", style=wx.TE_CENTER)
sample_std_label.SetFont(font2)
sample_std_per_label = wx.StaticText(
self.top_panel, label="\nstd %", style=wx.TE_CENTER)
sample_std_per_label.SetFont(font2)
# handle samples/sites results sizers
sizer_sample_results = wx.StaticBoxSizer(wx.StaticBox(
self.top_panel, wx.ID_ANY, "sample/site results"), wx.HORIZONTAL)
sample_stat_window = wx.GridSizer(2, 4, h_space, v_space)
sample_stat_window.AddMany([(sample_mean_label, 1, wx.ALIGN_BOTTOM),
(sample_N_label, 1, wx.ALIGN_BOTTOM),
(sample_std_label, 1, wx.ALIGN_BOTTOM),
(sample_std_per_label, 1, wx.ALIGN_BOTTOM),
(self.sample_int_uT_window, 1, wx.EXPAND),
(self.sample_int_n_window, 1, wx.EXPAND),
(self.sample_int_sigma_window, 1, wx.EXPAND),
(self.sample_int_sigma_perc_window, 1, wx.EXPAND)])
sizer_sample_results.Add(
sample_stat_window, 1, wx.EXPAND | wx.ALIGN_LEFT, 0)
#--------------------------------------------------------------------
label_0 = wx.StaticText(
self.bottom_panel, label=" ", style=wx.ALIGN_CENTER, size=(180, 25))
label_1 = wx.StaticText(
self.bottom_panel, label="Acceptance criteria:", style=wx.ALIGN_CENTER, size=(180, 25))
label_2 = wx.StaticText(
self.bottom_panel, label="Specimen statistics:", style=wx.ALIGN_CENTER, size=(180, 25))
for statistic in self.preferences['show_statistics_on_gui']:
self.stat_windows[statistic] = wx.TextCtrl(
self.bottom_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.stat_windows[statistic].SetBackgroundColour(wx.WHITE)
self.stat_windows[statistic].SetFont(font2)
self.threshold_windows[statistic] = wx.TextCtrl(
self.bottom_panel, style=wx.TE_CENTER | wx.TE_READONLY, size=(50 * self.GUI_RESOLUTION, 25))
self.threshold_windows[statistic].SetFont(font2)
self.threshold_windows[statistic].SetBackgroundColour(wx.WHITE)
label = statistic.replace("specimen_", "").replace("int_", "")
self.stat_labels[statistic] = wx.StaticText(
self.bottom_panel, label=label, style=wx.ALIGN_CENTRE_HORIZONTAL | wx.ALIGN_BOTTOM)
self.stat_labels[statistic].SetFont(font2)
#-------------------------------------------------------------------
# Design the panels
#-------------------------------------------------------------------
# Plots Panel--------------------------------------------------------
sizer_grid_plots = wx.GridSizer(2, 2, 0, 0)
sizer_grid_plots.AddMany([(self.canvas2, 1, wx.EXPAND),
(self.canvas4, 1, wx.EXPAND),
(self.canvas3, 1, wx.EXPAND),
(self.canvas5, 1, wx.EXPAND)])
sizer_plots_outer = wx.BoxSizer(wx.HORIZONTAL)
sizer_plots_outer.Add(self.canvas1, 1, wx.EXPAND)
sizer_plots_outer.Add(sizer_grid_plots, 1, wx.EXPAND)
# Top Bar Sizer-------------------------------------------------------
#-------------Specimens Sizer----------------------------------------
sizer_prev_next_btns = wx.BoxSizer(wx.HORIZONTAL)
sizer_prev_next_btns.Add(prevbutton, 1, wx.EXPAND | wx.RIGHT, h_space)
sizer_prev_next_btns.Add(nextbutton, 1, wx.EXPAND | wx.LEFT, h_space)
sizer_select_specimen = wx.StaticBoxSizer(wx.StaticBox(
self.top_panel, wx.ID_ANY, "specimen"), wx.VERTICAL)
sizer_select_specimen.Add(
self.specimens_box, 1, wx.EXPAND | wx.BOTTOM, v_space)
sizer_select_specimen.Add(
sizer_prev_next_btns, 1, wx.EXPAND | wx.TOP, v_space)
#-------------Bounds Sizer----------------------------------------
sizer_grid_bounds_btns = wx.GridSizer(2, 3, 2 * h_space, 2 * v_space)
sizer_grid_bounds_btns.AddMany([(self.tmin_box, 1, wx.EXPAND),
(self.save_interpretation_button,
1, wx.EXPAND), (self.auto_save, 1, wx.EXPAND),
(self.tmax_box, 1, wx.EXPAND),
(self.delete_interpretation_button, 1, wx.EXPAND),
(self.auto_save_info, 1, wx.EXPAND)])
if self.s in list(self.Data.keys()) and self.Data[self.s]['T_or_MW'] == "T":
sizer_select_temp = wx.StaticBoxSizer(wx.StaticBox(
self.top_panel, wx.ID_ANY, "temperatures"), wx.HORIZONTAL)
else:
sizer_select_temp = wx.StaticBoxSizer(wx.StaticBox(
self.top_panel, wx.ID_ANY, "MW power"), wx.HORIZONTAL)
sizer_select_temp.Add(sizer_grid_bounds_btns, 1, wx.EXPAND)
#-------------Top Bar Outer Sizer------------------------------------
sizer_top_bar = wx.BoxSizer(wx.HORIZONTAL)
sizer_top_bar.AddMany([(sizer_select_specimen, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.RIGHT, 2 * h_space),
(sizer_select_temp, 1, wx.EXPAND |
wx.ALIGN_LEFT | wx.RIGHT, 2 * h_space),
(sizer_specimen_results, 2, wx.EXPAND |
wx.ALIGN_LEFT | wx.RIGHT, 2 * h_space),
(sizer_sample_results, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.RIGHT, 0)])
# Bottom Bar Sizer----------------------------------------------------
#----------------Criteria Labels Sizer-------------------------------
sizer_criteria_labels = wx.BoxSizer(wx.HORIZONTAL)
sizer_criteria_labels.Add(label_0, 3, wx.EXPAND | wx.LEFT, 2 * h_space)
sizer_criteria_boxes = wx.BoxSizer(wx.HORIZONTAL)
sizer_criteria_boxes.Add(label_1, 3, wx.EXPAND | wx.LEFT, 2 * h_space)
sizer_stats_boxes = wx.BoxSizer(wx.HORIZONTAL)
sizer_stats_boxes.Add(label_2, 3, wx.EXPAND | wx.LEFT, 2 * h_space)
for statistic in self.preferences['show_statistics_on_gui']:
sizer_criteria_labels.Add(
self.stat_labels[statistic], 1, wx.ALIGN_BOTTOM, 0)
#----------------Acceptance Criteria Boxes---------------------------
sizer_criteria_boxes.Add(
self.threshold_windows[statistic], 1, wx.EXPAND | wx.LEFT, h_space)
#----------------Specimen Statistics Boxes---------------------------
sizer_stats_boxes.Add(
self.stat_windows[statistic], 1, wx.EXPAND | wx.LEFT, h_space)
#----------------Bottom Outer Sizer----------------------------------
sizer_bottom_bar = wx.BoxSizer(wx.VERTICAL)
sizer_bottom_bar.AddMany([(sizer_criteria_labels, 1, wx.EXPAND | wx.ALIGN_BOTTOM | wx.BOTTOM, v_space),
(sizer_criteria_boxes, 1, wx.EXPAND |
wx.BOTTOM | wx.ALIGN_TOP, v_space),
(sizer_stats_boxes, 1, wx.EXPAND | wx.ALIGN_TOP)])
# Logger Sizer--------------------------------------------------------
sizer_logger = wx.BoxSizer(wx.HORIZONTAL)
sizer_logger.Add(self.logger, 1, wx.EXPAND)
# Set Panel Sizers----------------------------------------------------
self.plot_panel.SetSizer(sizer_plots_outer)
self.side_panel.SetSizerAndFit(sizer_logger)
self.top_panel.SetSizerAndFit(sizer_top_bar)
self.bottom_panel.SetSizerAndFit(sizer_bottom_bar)
# Outer Sizer for Frame-----------------------------------------------
sizer_logger_plots = wx.BoxSizer(wx.HORIZONTAL)
sizer_logger_plots.Add(self.side_panel, 1, wx.EXPAND | wx.ALIGN_LEFT)
sizer_logger_plots.Add(self.plot_panel, 3, wx.EXPAND | wx.ALIGN_LEFT)
sizer_outer = wx.BoxSizer(wx.VERTICAL)
sizer_outer.AddMany([(self.top_panel, 1, wx.EXPAND | wx.ALIGN_TOP | wx.BOTTOM, v_space / 2),
(sizer_logger_plots, 4, wx.EXPAND |
wx.ALIGN_TOP | wx.BOTTOM, v_space / 2),
(self.bottom_panel, 1, wx.EXPAND | wx.ALIGN_TOP)])
self.SetSizer(sizer_outer)
sizer_outer.Fit(self)
self.Layout() | Build main frame od panel: buttons, etc.
choose the first specimen and display data | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L497-L961 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.on_save_interpretation_button | def on_save_interpretation_button(self, event):
"""
save the current interpretation temporarily (not to a file)
"""
if "specimen_int_uT" not in self.Data[self.s]['pars']:
return
if 'deleted' in self.Data[self.s]['pars']:
self.Data[self.s]['pars'].pop('deleted')
self.Data[self.s]['pars']['saved'] = True
# collect all interpretation by sample
sample = self.Data_hierarchy['specimens'][self.s]
if sample not in list(self.Data_samples.keys()):
self.Data_samples[sample] = {}
if self.s not in list(self.Data_samples[sample].keys()):
self.Data_samples[sample][self.s] = {}
self.Data_samples[sample][self.s]['B'] = self.Data[self.s]['pars']["specimen_int_uT"]
# collect all interpretation by site
# site=thellier_gui_lib.get_site_from_hierarchy(sample,self.Data_hierarchy)
site = thellier_gui_lib.get_site_from_hierarchy(
sample, self.Data_hierarchy)
if site not in list(self.Data_sites.keys()):
self.Data_sites[site] = {}
if self.s not in list(self.Data_sites[site].keys()):
self.Data_sites[site][self.s] = {}
self.Data_sites[site][self.s]['B'] = self.Data[self.s]['pars']["specimen_int_uT"]
self.draw_sample_mean()
self.write_sample_box()
self.close_warning = True | python | def on_save_interpretation_button(self, event):
"""
save the current interpretation temporarily (not to a file)
"""
if "specimen_int_uT" not in self.Data[self.s]['pars']:
return
if 'deleted' in self.Data[self.s]['pars']:
self.Data[self.s]['pars'].pop('deleted')
self.Data[self.s]['pars']['saved'] = True
# collect all interpretation by sample
sample = self.Data_hierarchy['specimens'][self.s]
if sample not in list(self.Data_samples.keys()):
self.Data_samples[sample] = {}
if self.s not in list(self.Data_samples[sample].keys()):
self.Data_samples[sample][self.s] = {}
self.Data_samples[sample][self.s]['B'] = self.Data[self.s]['pars']["specimen_int_uT"]
# collect all interpretation by site
# site=thellier_gui_lib.get_site_from_hierarchy(sample,self.Data_hierarchy)
site = thellier_gui_lib.get_site_from_hierarchy(
sample, self.Data_hierarchy)
if site not in list(self.Data_sites.keys()):
self.Data_sites[site] = {}
if self.s not in list(self.Data_sites[site].keys()):
self.Data_sites[site][self.s] = {}
self.Data_sites[site][self.s]['B'] = self.Data[self.s]['pars']["specimen_int_uT"]
self.draw_sample_mean()
self.write_sample_box()
self.close_warning = True | save the current interpretation temporarily (not to a file) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L963-L993 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.on_delete_interpretation_button | def on_delete_interpretation_button(self, event):
"""
delete the current interpretation temporarily (not to a file)
"""
del self.Data[self.s]['pars']
self.Data[self.s]['pars'] = {}
self.Data[self.s]['pars']['deleted'] = True
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']
self.Data[self.s]['pars']['er_sample_name'] = self.Data[self.s]['er_sample_name']
sample = self.Data_hierarchy['specimens'][self.s]
if sample in list(self.Data_samples.keys()):
if self.s in list(self.Data_samples[sample].keys()):
if 'B' in list(self.Data_samples[sample][self.s].keys()):
del self.Data_samples[sample][self.s]['B']
site = thellier_gui_lib.get_site_from_hierarchy(
sample, self.Data_hierarchy)
if site in list(self.Data_sites.keys()):
if self.s in list(self.Data_sites[site].keys()):
del self.Data_sites[site][self.s]['B']
# if 'B' in self.Data_sites[site][self.s].keys():
# del self.Data_sites[site][self.s]['B']
self.tmin_box.SetValue("")
self.tmax_box.SetValue("")
self.clear_boxes()
self.draw_figure(self.s)
self.draw_sample_mean()
self.write_sample_box()
self.close_warning = True | python | def on_delete_interpretation_button(self, event):
"""
delete the current interpretation temporarily (not to a file)
"""
del self.Data[self.s]['pars']
self.Data[self.s]['pars'] = {}
self.Data[self.s]['pars']['deleted'] = True
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']
self.Data[self.s]['pars']['er_sample_name'] = self.Data[self.s]['er_sample_name']
sample = self.Data_hierarchy['specimens'][self.s]
if sample in list(self.Data_samples.keys()):
if self.s in list(self.Data_samples[sample].keys()):
if 'B' in list(self.Data_samples[sample][self.s].keys()):
del self.Data_samples[sample][self.s]['B']
site = thellier_gui_lib.get_site_from_hierarchy(
sample, self.Data_hierarchy)
if site in list(self.Data_sites.keys()):
if self.s in list(self.Data_sites[site].keys()):
del self.Data_sites[site][self.s]['B']
# if 'B' in self.Data_sites[site][self.s].keys():
# del self.Data_sites[site][self.s]['B']
self.tmin_box.SetValue("")
self.tmax_box.SetValue("")
self.clear_boxes()
self.draw_figure(self.s)
self.draw_sample_mean()
self.write_sample_box()
self.close_warning = True | delete the current interpretation temporarily (not to a file) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L995-L1027 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.write_acceptance_criteria_to_boxes | def write_acceptance_criteria_to_boxes(self):
"""
Update paleointensity statistics in acceptance criteria boxes.
(after changing temperature bounds or changing specimen)
"""
self.ignore_parameters, value = {}, ''
for crit_short_name in self.preferences['show_statistics_on_gui']:
crit = "specimen_" + crit_short_name
if self.acceptance_criteria[crit]['value'] == -999:
self.threshold_windows[crit_short_name].SetValue("")
self.threshold_windows[crit_short_name].SetBackgroundColour(
wx.Colour(128, 128, 128))
self.ignore_parameters[crit] = True
continue
elif crit == "specimen_scat":
if self.acceptance_criteria[crit]['value'] in ['g', 1, '1', True, "True", "t"]:
value = "True"
value = "t"
#self.scat_threshold_window.SetBackgroundColour(wx.SetBackgroundColour(128, 128, 128))
else:
value = ""
value = "f"
self.threshold_windows['scat'].SetBackgroundColour(
(128, 128, 128))
#self.scat_threshold_window.SetBackgroundColour((128, 128, 128))
elif type(self.acceptance_criteria[crit]['value']) == int:
value = "%i" % self.acceptance_criteria[crit]['value']
elif type(self.acceptance_criteria[crit]['value']) == float:
if self.acceptance_criteria[crit]['decimal_points'] == -999:
value = "%.3e" % self.acceptance_criteria[crit]['value']
else:
value = "{:.{}f}".format(self.acceptance_criteria[crit]['value'],
self.acceptance_criteria[crit]['decimal_points'])
else:
continue
self.threshold_windows[crit_short_name].SetValue(value)
self.threshold_windows[crit_short_name].SetBackgroundColour(
wx.WHITE) | python | def write_acceptance_criteria_to_boxes(self):
"""
Update paleointensity statistics in acceptance criteria boxes.
(after changing temperature bounds or changing specimen)
"""
self.ignore_parameters, value = {}, ''
for crit_short_name in self.preferences['show_statistics_on_gui']:
crit = "specimen_" + crit_short_name
if self.acceptance_criteria[crit]['value'] == -999:
self.threshold_windows[crit_short_name].SetValue("")
self.threshold_windows[crit_short_name].SetBackgroundColour(
wx.Colour(128, 128, 128))
self.ignore_parameters[crit] = True
continue
elif crit == "specimen_scat":
if self.acceptance_criteria[crit]['value'] in ['g', 1, '1', True, "True", "t"]:
value = "True"
value = "t"
#self.scat_threshold_window.SetBackgroundColour(wx.SetBackgroundColour(128, 128, 128))
else:
value = ""
value = "f"
self.threshold_windows['scat'].SetBackgroundColour(
(128, 128, 128))
#self.scat_threshold_window.SetBackgroundColour((128, 128, 128))
elif type(self.acceptance_criteria[crit]['value']) == int:
value = "%i" % self.acceptance_criteria[crit]['value']
elif type(self.acceptance_criteria[crit]['value']) == float:
if self.acceptance_criteria[crit]['decimal_points'] == -999:
value = "%.3e" % self.acceptance_criteria[crit]['value']
else:
value = "{:.{}f}".format(self.acceptance_criteria[crit]['value'],
self.acceptance_criteria[crit]['decimal_points'])
else:
continue
self.threshold_windows[crit_short_name].SetValue(value)
self.threshold_windows[crit_short_name].SetBackgroundColour(
wx.WHITE) | Update paleointensity statistics in acceptance criteria boxes.
(after changing temperature bounds or changing specimen) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L1079-L1119 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.Add_text | def Add_text(self, s):
"""
Add text to measurement data window.
"""
self.logger.DeleteAllItems()
FONT_RATIO = self.GUI_RESOLUTION + (self.GUI_RESOLUTION - 1) * 5
if self.GUI_RESOLUTION > 1.1:
font1 = wx.Font(11, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
elif self.GUI_RESOLUTION <= 0.9:
font1 = wx.Font(8, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
else:
font1 = wx.Font(10, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
# get temperature indecies to display current interp steps in logger
t1 = self.tmin_box.GetValue()
t2 = self.tmax_box.GetValue()
# microwave or thermal
if "LP-PI-M" in self.Data[s]['datablock'][0]['magic_method_codes']:
MICROWAVE = True
THERMAL = False
steps_tr = []
for rec in self.Data[s]['datablock']:
if "measurement_description" in rec:
MW_step = rec["measurement_description"].strip(
'\n').split(":")
for STEP in MW_step:
if "Number" in STEP:
temp = float(STEP.split("-")[-1])
steps_tr.append(temp)
else:
power = rec['treatment_mw_power']
if '-' in str(power):
power = power.split('-')[-1]
steps_tr.append(int(power))
#steps_tr = [float(d['treatment_mw_power'].split("-")[-1])
# for d in self.Data[s]['datablock']]
else:
MICROWAVE = False
THERMAL = True
steps_tr = [float(d['treatment_temp']) -
273 for d in self.Data[s]['datablock']]
if (t1 == "" or t2 == "") or float(t2) < float(t1):
tmin_index, tmax_index = -1, -1
else:
tmin_index = steps_tr.index(int(t1))
tmax_index = steps_tr.index(int(t2))
self.logger.SetFont(font1)
for i, rec in enumerate(self.Data[s]['datablock']):
if "LT-NO" in rec['magic_method_codes']:
step = "N"
elif "LT-AF-Z" in rec['magic_method_codes']:
step = "AFD"
elif "LT-T-Z" in rec['magic_method_codes'] or 'LT-M-Z' in rec['magic_method_codes']:
step = "Z"
elif "LT-T-I" in rec['magic_method_codes'] or 'LT-M-I' in rec['magic_method_codes']:
step = "I"
elif "LT-PTRM-I" in rec['magic_method_codes'] or "LT-PMRM-I" in rec['magic_method_codes']:
step = "P"
elif "LT-PTRM-MD" in rec['magic_method_codes'] or "LT-PMRM-MD" in rec['magic_method_codes']:
step = "T"
elif "LT-PTRM-AC" in rec['magic_method_codes'] or "LT-PMRM-AC" in rec['magic_method_codes']:
step = "A"
else:
print(("unrecognized step in specimen %s Method codes: %s" %
(str(rec['magic_method_codes']), s)))
if THERMAL:
self.logger.InsertItem(i, "%i" % i)
self.logger.SetItem(i, 1, step)
self.logger.SetItem(i, 2, "%1.0f" %
(float(rec['treatment_temp']) - 273.))
self.logger.SetItem(i, 3, "%.1f" %
float(rec['measurement_dec']))
self.logger.SetItem(i, 4, "%.1f" %
float(rec['measurement_inc']))
self.logger.SetItem(i, 5, "%.2e" %
float(rec['measurement_magn_moment']))
elif MICROWAVE: # mcrowave
if "measurement_description" in list(rec.keys()):
MW_step = rec["measurement_description"].strip(
'\n').split(":")
for STEP in MW_step:
if "Number" not in STEP:
continue
temp = float(STEP.split("-")[-1])
self.logger.InsertItem(i, "%i" % i)
self.logger.SetItem(i, 1, step)
self.logger.SetItem(i, 2, "%1.0f" % temp)
self.logger.SetItem(i, 3, "%.1f" %
float(rec['measurement_dec']))
self.logger.SetItem(i, 4, "%.1f" %
float(rec['measurement_inc']))
self.logger.SetItem(i, 5, "%.2e" % float(
rec['measurement_magn_moment']))
self.logger.SetItemBackgroundColour(i, "WHITE")
if i >= tmin_index and i <= tmax_index:
self.logger.SetItemBackgroundColour(i, "LIGHT BLUE")
if 'measurement_flag' not in list(rec.keys()):
rec['measurement_flag'] = 'g' | python | def Add_text(self, s):
"""
Add text to measurement data window.
"""
self.logger.DeleteAllItems()
FONT_RATIO = self.GUI_RESOLUTION + (self.GUI_RESOLUTION - 1) * 5
if self.GUI_RESOLUTION > 1.1:
font1 = wx.Font(11, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
elif self.GUI_RESOLUTION <= 0.9:
font1 = wx.Font(8, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
else:
font1 = wx.Font(10, wx.SWISS, wx.NORMAL,
wx.NORMAL, False, self.font_type)
# get temperature indecies to display current interp steps in logger
t1 = self.tmin_box.GetValue()
t2 = self.tmax_box.GetValue()
# microwave or thermal
if "LP-PI-M" in self.Data[s]['datablock'][0]['magic_method_codes']:
MICROWAVE = True
THERMAL = False
steps_tr = []
for rec in self.Data[s]['datablock']:
if "measurement_description" in rec:
MW_step = rec["measurement_description"].strip(
'\n').split(":")
for STEP in MW_step:
if "Number" in STEP:
temp = float(STEP.split("-")[-1])
steps_tr.append(temp)
else:
power = rec['treatment_mw_power']
if '-' in str(power):
power = power.split('-')[-1]
steps_tr.append(int(power))
#steps_tr = [float(d['treatment_mw_power'].split("-")[-1])
# for d in self.Data[s]['datablock']]
else:
MICROWAVE = False
THERMAL = True
steps_tr = [float(d['treatment_temp']) -
273 for d in self.Data[s]['datablock']]
if (t1 == "" or t2 == "") or float(t2) < float(t1):
tmin_index, tmax_index = -1, -1
else:
tmin_index = steps_tr.index(int(t1))
tmax_index = steps_tr.index(int(t2))
self.logger.SetFont(font1)
for i, rec in enumerate(self.Data[s]['datablock']):
if "LT-NO" in rec['magic_method_codes']:
step = "N"
elif "LT-AF-Z" in rec['magic_method_codes']:
step = "AFD"
elif "LT-T-Z" in rec['magic_method_codes'] or 'LT-M-Z' in rec['magic_method_codes']:
step = "Z"
elif "LT-T-I" in rec['magic_method_codes'] or 'LT-M-I' in rec['magic_method_codes']:
step = "I"
elif "LT-PTRM-I" in rec['magic_method_codes'] or "LT-PMRM-I" in rec['magic_method_codes']:
step = "P"
elif "LT-PTRM-MD" in rec['magic_method_codes'] or "LT-PMRM-MD" in rec['magic_method_codes']:
step = "T"
elif "LT-PTRM-AC" in rec['magic_method_codes'] or "LT-PMRM-AC" in rec['magic_method_codes']:
step = "A"
else:
print(("unrecognized step in specimen %s Method codes: %s" %
(str(rec['magic_method_codes']), s)))
if THERMAL:
self.logger.InsertItem(i, "%i" % i)
self.logger.SetItem(i, 1, step)
self.logger.SetItem(i, 2, "%1.0f" %
(float(rec['treatment_temp']) - 273.))
self.logger.SetItem(i, 3, "%.1f" %
float(rec['measurement_dec']))
self.logger.SetItem(i, 4, "%.1f" %
float(rec['measurement_inc']))
self.logger.SetItem(i, 5, "%.2e" %
float(rec['measurement_magn_moment']))
elif MICROWAVE: # mcrowave
if "measurement_description" in list(rec.keys()):
MW_step = rec["measurement_description"].strip(
'\n').split(":")
for STEP in MW_step:
if "Number" not in STEP:
continue
temp = float(STEP.split("-")[-1])
self.logger.InsertItem(i, "%i" % i)
self.logger.SetItem(i, 1, step)
self.logger.SetItem(i, 2, "%1.0f" % temp)
self.logger.SetItem(i, 3, "%.1f" %
float(rec['measurement_dec']))
self.logger.SetItem(i, 4, "%.1f" %
float(rec['measurement_inc']))
self.logger.SetItem(i, 5, "%.2e" % float(
rec['measurement_magn_moment']))
self.logger.SetItemBackgroundColour(i, "WHITE")
if i >= tmin_index and i <= tmax_index:
self.logger.SetItemBackgroundColour(i, "LIGHT BLUE")
if 'measurement_flag' not in list(rec.keys()):
rec['measurement_flag'] = 'g' | Add text to measurement data window. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L1123-L1233 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.select_bounds_in_logger | def select_bounds_in_logger(self, index):
"""
sets index as the upper or lower bound of a fit based on what the other bound is and selects it in the logger. Requires 2 calls to completely update a interpretation. NOTE: Requires an interpretation to exist before it is called.
@param: index - index of the step to select in the logger
"""
tmin_index, tmax_index = "", ""
if str(self.tmin_box.GetValue()) != "":
tmin_index = self.tmin_box.GetSelection()
if str(self.tmax_box.GetValue()) != "":
tmax_index = self.tmax_box.GetSelection()
# if there is no prior interpretation, assume first click is
# tmin and set highest possible temp as tmax
if not tmin_index and not tmax_index:
tmin_index = index
self.tmin_box.SetSelection(index)
# set to the highest step
max_step_data = self.Data[self.s]['datablock'][-1]
step_key = 'treatment_temp'
if MICROWAVE:
step_key = 'treatment_mw_power'
max_step = max_step_data[step_key]
tmax_index = self.tmax_box.GetCount() - 1
self.tmax_box.SetSelection(tmax_index)
elif self.list_bound_loc != 0:
if self.list_bound_loc == 1:
if index < tmin_index:
self.tmin_box.SetSelection(index)
self.tmax_box.SetSelection(tmin_index)
elif index == tmin_index:
pass
else:
self.tmax_box.SetSelection(index)
else:
if index > tmax_index:
self.tmin_box.SetSelection(tmax_index)
self.tmax_box.SetSelection(index)
elif index == tmax_index:
pass
else:
self.tmin_box.SetSelection(index)
self.list_bound_loc = 0
else:
if index < tmax_index:
self.tmin_box.SetSelection(index)
self.list_bound_loc = 1
else:
self.tmax_box.SetSelection(index)
self.list_bound_loc = 2
self.logger.Select(index, on=0)
self.get_new_T_PI_parameters(-1) | python | def select_bounds_in_logger(self, index):
"""
sets index as the upper or lower bound of a fit based on what the other bound is and selects it in the logger. Requires 2 calls to completely update a interpretation. NOTE: Requires an interpretation to exist before it is called.
@param: index - index of the step to select in the logger
"""
tmin_index, tmax_index = "", ""
if str(self.tmin_box.GetValue()) != "":
tmin_index = self.tmin_box.GetSelection()
if str(self.tmax_box.GetValue()) != "":
tmax_index = self.tmax_box.GetSelection()
# if there is no prior interpretation, assume first click is
# tmin and set highest possible temp as tmax
if not tmin_index and not tmax_index:
tmin_index = index
self.tmin_box.SetSelection(index)
# set to the highest step
max_step_data = self.Data[self.s]['datablock'][-1]
step_key = 'treatment_temp'
if MICROWAVE:
step_key = 'treatment_mw_power'
max_step = max_step_data[step_key]
tmax_index = self.tmax_box.GetCount() - 1
self.tmax_box.SetSelection(tmax_index)
elif self.list_bound_loc != 0:
if self.list_bound_loc == 1:
if index < tmin_index:
self.tmin_box.SetSelection(index)
self.tmax_box.SetSelection(tmin_index)
elif index == tmin_index:
pass
else:
self.tmax_box.SetSelection(index)
else:
if index > tmax_index:
self.tmin_box.SetSelection(tmax_index)
self.tmax_box.SetSelection(index)
elif index == tmax_index:
pass
else:
self.tmin_box.SetSelection(index)
self.list_bound_loc = 0
else:
if index < tmax_index:
self.tmin_box.SetSelection(index)
self.list_bound_loc = 1
else:
self.tmax_box.SetSelection(index)
self.list_bound_loc = 2
self.logger.Select(index, on=0)
self.get_new_T_PI_parameters(-1) | sets index as the upper or lower bound of a fit based on what the other bound is and selects it in the logger. Requires 2 calls to completely update a interpretation. NOTE: Requires an interpretation to exist before it is called.
@param: index - index of the step to select in the logger | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L1246-L1296 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.create_menu | def create_menu(self):
"""
Create menu bar
"""
self.menubar = wx.MenuBar()
menu_preferences = wx.Menu()
m_preferences_apperance = menu_preferences.Append(
-1, "&Appearence preferences", "")
self.Bind(wx.EVT_MENU, self.on_menu_appearance_preferences,
m_preferences_apperance)
m_preferences_spd = menu_preferences.Append(
-1, "&Specimen paleointensity statistics (from SPD list)", "")
self.Bind(wx.EVT_MENU, self.on_menu_m_preferences_spd,
m_preferences_spd)
#m_preferences_stat = menu_preferences.Append(-1, "&Statistical preferences", "")
#self.Bind(wx.EVT_MENU, self.on_menu_preferences_stat, m_preferences_stat)
#m_save_preferences = menu_preferences.Append(-1, "&Save preferences", "")
#self.Bind(wx.EVT_MENU, self.on_menu_save_preferences, m_save_preferences)
menu_file = wx.Menu()
m_change_working_directory = menu_file.Append(
-1, "&Change project directory", "")
self.Bind(wx.EVT_MENU, self.on_menu_change_working_directory,
m_change_working_directory)
#m_add_working_directory = menu_file.Append(-1, "&Add a MagIC project directory", "")
#self.Bind(wx.EVT_MENU, self.on_menu_add_working_directory, m_add_working_directory)
m_open_magic_file = menu_file.Append(-1,
"&Open MagIC measurement file", "")
self.Bind(wx.EVT_MENU, self.on_menu_open_magic_file, m_open_magic_file)
m_open_magic_tree = menu_file.Append(
-1, "&Open all MagIC project directories in path", "")
self.Bind(wx.EVT_MENU, self.on_menu_m_open_magic_tree,
m_open_magic_tree)
menu_file.AppendSeparator()
m_prepare_MagIC_results_tables = menu_file.Append(
-1, "&Save MagIC tables", "")
self.Bind(wx.EVT_MENU, self.on_menu_prepare_magic_results_tables,
m_prepare_MagIC_results_tables)
submenu_save_plots = wx.Menu()
m_save_Arai_plot = submenu_save_plots.Append(-1, "&Save Arai plot", "")
self.Bind(wx.EVT_MENU, self.on_save_Arai_plot, m_save_Arai_plot)
m_save_zij_plot = submenu_save_plots.Append(
-1, "&Save Zijderveld plot", "")
self.Bind(wx.EVT_MENU, self.on_save_Zij_plot, m_save_zij_plot, "Zij")
m_save_eq_plot = submenu_save_plots.Append(
-1, "&Save equal area plot", "")
self.Bind(wx.EVT_MENU, self.on_save_Eq_plot, m_save_eq_plot, "Eq")
m_save_M_t_plot = submenu_save_plots.Append(-1, "&Save M-t plot", "")
self.Bind(wx.EVT_MENU, self.on_save_M_t_plot, m_save_M_t_plot, "M_t")
m_save_NLT_plot = submenu_save_plots.Append(-1, "&Save NLT plot", "")
self.Bind(wx.EVT_MENU, self.on_save_NLT_plot, m_save_NLT_plot, "NLT")
m_save_CR_plot = submenu_save_plots.Append(
-1, "&Save cooling rate plot", "")
self.Bind(wx.EVT_MENU, self.on_save_CR_plot, m_save_CR_plot, "CR")
m_save_sample_plot = submenu_save_plots.Append(
-1, "&Save sample plot", "")
self.Bind(wx.EVT_MENU, self.on_save_sample_plot,
m_save_sample_plot, "Samp")
#m_save_all_plots = submenu_save_plots.Append(-1, "&Save all plots", "")
#self.Bind(wx.EVT_MENU, self.on_save_all_plots, m_save_all_plots)
menu_file.AppendSeparator()
m_new_sub_plots = menu_file.AppendSubMenu(submenu_save_plots,
"&Save plot")
menu_file.AppendSeparator()
m_exit = menu_file.Append(wx.ID_EXIT, "Quit", "Quit application")
self.Bind(wx.EVT_MENU, self.on_menu_exit, m_exit)
menu_anisotropy = wx.Menu()
m_calculate_aniso_tensor = menu_anisotropy.Append(
-1, "&Calculate anisotropy tensors", "")
self.Bind(wx.EVT_MENU, self.on_menu_calculate_aniso_tensor,
m_calculate_aniso_tensor)
m_show_anisotropy_errors = menu_anisotropy.Append(
-1, "&Show anisotropy calculation Warnings/Errors", "")
self.Bind(wx.EVT_MENU, self.on_show_anisotropy_errors,
m_show_anisotropy_errors)
menu_Analysis = wx.Menu()
submenu_criteria = wx.Menu()
# m_set_criteria_to_default = submenu_criteria.Append(-1, "&Set acceptance criteria to default", "")
# self.Bind(wx.EVT_MENU, self.on_menu_default_criteria, m_set_criteria_to_default)
m_change_criteria_file = submenu_criteria.Append(
-1, "&Change acceptance criteria", "")
self.Bind(wx.EVT_MENU, self.on_menu_criteria, m_change_criteria_file)
m_import_criteria_file = submenu_criteria.Append(
-1, "&Import criteria file", "")
self.Bind(wx.EVT_MENU, self.on_menu_criteria_file,
m_import_criteria_file)
m_new_sub = menu_Analysis.AppendSubMenu(submenu_criteria,
"Acceptance criteria")
m_previous_interpretation = menu_Analysis.Append(
-1, "&Import previous interpretation from a 'redo' file", "")
self.Bind(wx.EVT_MENU, self.on_menu_previous_interpretation,
m_previous_interpretation)
m_save_interpretation = menu_Analysis.Append(
-1, "&Save current interpretations to a 'redo' file", "")
self.Bind(wx.EVT_MENU, self.on_menu_save_interpretation,
m_save_interpretation)
m_delete_interpretation = menu_Analysis.Append(
-1, "&Clear all current interpretations", "")
self.Bind(wx.EVT_MENU, self.on_menu_clear_interpretation,
m_delete_interpretation)
menu_Tools = wx.Menu()
#m_prev_interpretation = menu_file.Append(-1, "&Save plot\tCtrl-S", "Save plot to file")
menu_Auto_Interpreter = wx.Menu()
m_interpreter = menu_Auto_Interpreter.Append(
-1, "&Run Thellier auto interpreter", "Run auto interpter")
self.Bind(wx.EVT_MENU, self.on_menu_run_interpreter, m_interpreter)
m_open_interpreter_file = menu_Auto_Interpreter.Append(
-1, "&Open auto-interpreter output files", "")
self.Bind(wx.EVT_MENU, self.on_menu_open_interpreter_file,
m_open_interpreter_file)
m_open_interpreter_log = menu_Auto_Interpreter.Append(
-1, "&Open auto-interpreter Warnings/Errors", "")
self.Bind(wx.EVT_MENU, self.on_menu_open_interpreter_log,
m_open_interpreter_log)
#menu_consistency_test = wx.Menu()
#m_run_consistency_test = menu_consistency_test.Append(
# -1, "&Run Consistency test", "")
#self.Bind(wx.EVT_MENU, self.on_menu_run_consistency_test,
# m_run_consistency_test)
#m_run_consistency_test_b = menu_Optimizer.Append(-1, "&Run Consistency test beta version", "")
#self.Bind(wx.EVT_MENU, self.on_menu_run_consistency_test_b, m_run_consistency_test_b)
menu_Plot = wx.Menu()
m_plot_data = menu_Plot.Append(-1, "&Plot paleointensity curve", "")
self.Bind(wx.EVT_MENU, self.on_menu_plot_data, m_plot_data)
menu_Help = wx.Menu()
m_cookbook = menu_Help.Append(-1, "&PmagPy Cookbook\tCtrl-Shift-W", "")
self.Bind(wx.EVT_MENU, self.on_menu_cookbook, m_cookbook)
m_docs = menu_Help.Append(-1, "&Open Docs\tCtrl-Shift-H", "")
self.Bind(wx.EVT_MENU, self.on_menu_docs, m_docs)
m_git = menu_Help.Append(-1, "&Github Page\tCtrl-Shift-G", "")
self.Bind(wx.EVT_MENU, self.on_menu_git, m_git)
m_debug = menu_Help.Append(-1, "&Open Debugger\tCtrl-Shift-D", "")
self.Bind(wx.EVT_MENU, self.on_menu_debug, m_debug)
#menu_results_table= wx.Menu()
#m_make_results_table = menu_results_table.Append(-1, "&Make results table", "")
#self.Bind(wx.EVT_MENU, self.on_menu_results_data, m_make_results_table)
#menu_MagIC= wx.Menu()
#m_convert_to_magic= menu_MagIC.Append(-1, "&Convert generic files to MagIC format", "")
#self.Bind(wx.EVT_MENU, self.on_menu_convert_to_magic, m_convert_to_magic)
#m_build_magic_model= menu_MagIC.Append(-1, "&Run MagIC model builder", "")
#self.Bind(wx.EVT_MENU, self.on_menu_MagIC_model_builder, m_build_magic_model)
#m_prepare_MagIC_results_tables= menu_MagIC.Append(-1, "&Make MagIC results Table", "")
#self.Bind(wx.EVT_MENU, self.on_menu_prepare_magic_results_tables, m_prepare_MagIC_results_tables)
#menu_help = wx.Menu()
#m_about = menu_help.Append(-1, "&About\tF1", "About this program")
self.menubar.Append(menu_preferences, "& Preferences")
self.menubar.Append(menu_file, "&File")
self.menubar.Append(menu_anisotropy, "&Anisotropy")
self.menubar.Append(menu_Analysis, "&Analysis")
self.menubar.Append(menu_Auto_Interpreter, "&Auto Interpreter")
#self.menubar.Append(menu_consistency_test, "&Consistency Test")
self.menubar.Append(menu_Plot, "&Plot")
self.menubar.Append(menu_Help, "&Help")
#self.menubar.Append(menu_results_table, "&Table")
#self.menubar.Append(menu_MagIC, "&MagIC")
self.SetMenuBar(self.menubar) | python | def create_menu(self):
"""
Create menu bar
"""
self.menubar = wx.MenuBar()
menu_preferences = wx.Menu()
m_preferences_apperance = menu_preferences.Append(
-1, "&Appearence preferences", "")
self.Bind(wx.EVT_MENU, self.on_menu_appearance_preferences,
m_preferences_apperance)
m_preferences_spd = menu_preferences.Append(
-1, "&Specimen paleointensity statistics (from SPD list)", "")
self.Bind(wx.EVT_MENU, self.on_menu_m_preferences_spd,
m_preferences_spd)
#m_preferences_stat = menu_preferences.Append(-1, "&Statistical preferences", "")
#self.Bind(wx.EVT_MENU, self.on_menu_preferences_stat, m_preferences_stat)
#m_save_preferences = menu_preferences.Append(-1, "&Save preferences", "")
#self.Bind(wx.EVT_MENU, self.on_menu_save_preferences, m_save_preferences)
menu_file = wx.Menu()
m_change_working_directory = menu_file.Append(
-1, "&Change project directory", "")
self.Bind(wx.EVT_MENU, self.on_menu_change_working_directory,
m_change_working_directory)
#m_add_working_directory = menu_file.Append(-1, "&Add a MagIC project directory", "")
#self.Bind(wx.EVT_MENU, self.on_menu_add_working_directory, m_add_working_directory)
m_open_magic_file = menu_file.Append(-1,
"&Open MagIC measurement file", "")
self.Bind(wx.EVT_MENU, self.on_menu_open_magic_file, m_open_magic_file)
m_open_magic_tree = menu_file.Append(
-1, "&Open all MagIC project directories in path", "")
self.Bind(wx.EVT_MENU, self.on_menu_m_open_magic_tree,
m_open_magic_tree)
menu_file.AppendSeparator()
m_prepare_MagIC_results_tables = menu_file.Append(
-1, "&Save MagIC tables", "")
self.Bind(wx.EVT_MENU, self.on_menu_prepare_magic_results_tables,
m_prepare_MagIC_results_tables)
submenu_save_plots = wx.Menu()
m_save_Arai_plot = submenu_save_plots.Append(-1, "&Save Arai plot", "")
self.Bind(wx.EVT_MENU, self.on_save_Arai_plot, m_save_Arai_plot)
m_save_zij_plot = submenu_save_plots.Append(
-1, "&Save Zijderveld plot", "")
self.Bind(wx.EVT_MENU, self.on_save_Zij_plot, m_save_zij_plot, "Zij")
m_save_eq_plot = submenu_save_plots.Append(
-1, "&Save equal area plot", "")
self.Bind(wx.EVT_MENU, self.on_save_Eq_plot, m_save_eq_plot, "Eq")
m_save_M_t_plot = submenu_save_plots.Append(-1, "&Save M-t plot", "")
self.Bind(wx.EVT_MENU, self.on_save_M_t_plot, m_save_M_t_plot, "M_t")
m_save_NLT_plot = submenu_save_plots.Append(-1, "&Save NLT plot", "")
self.Bind(wx.EVT_MENU, self.on_save_NLT_plot, m_save_NLT_plot, "NLT")
m_save_CR_plot = submenu_save_plots.Append(
-1, "&Save cooling rate plot", "")
self.Bind(wx.EVT_MENU, self.on_save_CR_plot, m_save_CR_plot, "CR")
m_save_sample_plot = submenu_save_plots.Append(
-1, "&Save sample plot", "")
self.Bind(wx.EVT_MENU, self.on_save_sample_plot,
m_save_sample_plot, "Samp")
#m_save_all_plots = submenu_save_plots.Append(-1, "&Save all plots", "")
#self.Bind(wx.EVT_MENU, self.on_save_all_plots, m_save_all_plots)
menu_file.AppendSeparator()
m_new_sub_plots = menu_file.AppendSubMenu(submenu_save_plots,
"&Save plot")
menu_file.AppendSeparator()
m_exit = menu_file.Append(wx.ID_EXIT, "Quit", "Quit application")
self.Bind(wx.EVT_MENU, self.on_menu_exit, m_exit)
menu_anisotropy = wx.Menu()
m_calculate_aniso_tensor = menu_anisotropy.Append(
-1, "&Calculate anisotropy tensors", "")
self.Bind(wx.EVT_MENU, self.on_menu_calculate_aniso_tensor,
m_calculate_aniso_tensor)
m_show_anisotropy_errors = menu_anisotropy.Append(
-1, "&Show anisotropy calculation Warnings/Errors", "")
self.Bind(wx.EVT_MENU, self.on_show_anisotropy_errors,
m_show_anisotropy_errors)
menu_Analysis = wx.Menu()
submenu_criteria = wx.Menu()
# m_set_criteria_to_default = submenu_criteria.Append(-1, "&Set acceptance criteria to default", "")
# self.Bind(wx.EVT_MENU, self.on_menu_default_criteria, m_set_criteria_to_default)
m_change_criteria_file = submenu_criteria.Append(
-1, "&Change acceptance criteria", "")
self.Bind(wx.EVT_MENU, self.on_menu_criteria, m_change_criteria_file)
m_import_criteria_file = submenu_criteria.Append(
-1, "&Import criteria file", "")
self.Bind(wx.EVT_MENU, self.on_menu_criteria_file,
m_import_criteria_file)
m_new_sub = menu_Analysis.AppendSubMenu(submenu_criteria,
"Acceptance criteria")
m_previous_interpretation = menu_Analysis.Append(
-1, "&Import previous interpretation from a 'redo' file", "")
self.Bind(wx.EVT_MENU, self.on_menu_previous_interpretation,
m_previous_interpretation)
m_save_interpretation = menu_Analysis.Append(
-1, "&Save current interpretations to a 'redo' file", "")
self.Bind(wx.EVT_MENU, self.on_menu_save_interpretation,
m_save_interpretation)
m_delete_interpretation = menu_Analysis.Append(
-1, "&Clear all current interpretations", "")
self.Bind(wx.EVT_MENU, self.on_menu_clear_interpretation,
m_delete_interpretation)
menu_Tools = wx.Menu()
#m_prev_interpretation = menu_file.Append(-1, "&Save plot\tCtrl-S", "Save plot to file")
menu_Auto_Interpreter = wx.Menu()
m_interpreter = menu_Auto_Interpreter.Append(
-1, "&Run Thellier auto interpreter", "Run auto interpter")
self.Bind(wx.EVT_MENU, self.on_menu_run_interpreter, m_interpreter)
m_open_interpreter_file = menu_Auto_Interpreter.Append(
-1, "&Open auto-interpreter output files", "")
self.Bind(wx.EVT_MENU, self.on_menu_open_interpreter_file,
m_open_interpreter_file)
m_open_interpreter_log = menu_Auto_Interpreter.Append(
-1, "&Open auto-interpreter Warnings/Errors", "")
self.Bind(wx.EVT_MENU, self.on_menu_open_interpreter_log,
m_open_interpreter_log)
#menu_consistency_test = wx.Menu()
#m_run_consistency_test = menu_consistency_test.Append(
# -1, "&Run Consistency test", "")
#self.Bind(wx.EVT_MENU, self.on_menu_run_consistency_test,
# m_run_consistency_test)
#m_run_consistency_test_b = menu_Optimizer.Append(-1, "&Run Consistency test beta version", "")
#self.Bind(wx.EVT_MENU, self.on_menu_run_consistency_test_b, m_run_consistency_test_b)
menu_Plot = wx.Menu()
m_plot_data = menu_Plot.Append(-1, "&Plot paleointensity curve", "")
self.Bind(wx.EVT_MENU, self.on_menu_plot_data, m_plot_data)
menu_Help = wx.Menu()
m_cookbook = menu_Help.Append(-1, "&PmagPy Cookbook\tCtrl-Shift-W", "")
self.Bind(wx.EVT_MENU, self.on_menu_cookbook, m_cookbook)
m_docs = menu_Help.Append(-1, "&Open Docs\tCtrl-Shift-H", "")
self.Bind(wx.EVT_MENU, self.on_menu_docs, m_docs)
m_git = menu_Help.Append(-1, "&Github Page\tCtrl-Shift-G", "")
self.Bind(wx.EVT_MENU, self.on_menu_git, m_git)
m_debug = menu_Help.Append(-1, "&Open Debugger\tCtrl-Shift-D", "")
self.Bind(wx.EVT_MENU, self.on_menu_debug, m_debug)
#menu_results_table= wx.Menu()
#m_make_results_table = menu_results_table.Append(-1, "&Make results table", "")
#self.Bind(wx.EVT_MENU, self.on_menu_results_data, m_make_results_table)
#menu_MagIC= wx.Menu()
#m_convert_to_magic= menu_MagIC.Append(-1, "&Convert generic files to MagIC format", "")
#self.Bind(wx.EVT_MENU, self.on_menu_convert_to_magic, m_convert_to_magic)
#m_build_magic_model= menu_MagIC.Append(-1, "&Run MagIC model builder", "")
#self.Bind(wx.EVT_MENU, self.on_menu_MagIC_model_builder, m_build_magic_model)
#m_prepare_MagIC_results_tables= menu_MagIC.Append(-1, "&Make MagIC results Table", "")
#self.Bind(wx.EVT_MENU, self.on_menu_prepare_magic_results_tables, m_prepare_MagIC_results_tables)
#menu_help = wx.Menu()
#m_about = menu_help.Append(-1, "&About\tF1", "About this program")
self.menubar.Append(menu_preferences, "& Preferences")
self.menubar.Append(menu_file, "&File")
self.menubar.Append(menu_anisotropy, "&Anisotropy")
self.menubar.Append(menu_Analysis, "&Analysis")
self.menubar.Append(menu_Auto_Interpreter, "&Auto Interpreter")
#self.menubar.Append(menu_consistency_test, "&Consistency Test")
self.menubar.Append(menu_Plot, "&Plot")
self.menubar.Append(menu_Help, "&Help")
#self.menubar.Append(menu_results_table, "&Table")
#self.menubar.Append(menu_MagIC, "&MagIC")
self.SetMenuBar(self.menubar) | Create menu bar | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L1353-L1559 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.update_selection | 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 | 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() | update figures and statistics windows with a new selection of specimen | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L1564-L1590 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.onSelect_specimen | def onSelect_specimen(self, event):
"""
update figures and text when a new specimen is selected
"""
new_s = self.specimens_box.GetValue()
if self.select_specimen(new_s):
self.update_selection()
else:
self.specimens_box.SetValue(self.s)
self.user_warning(
"no specimen %s reverting to old specimen %s" % (new_s, self.s)) | python | def onSelect_specimen(self, event):
"""
update figures and text when a new specimen is selected
"""
new_s = self.specimens_box.GetValue()
if self.select_specimen(new_s):
self.update_selection()
else:
self.specimens_box.SetValue(self.s)
self.user_warning(
"no specimen %s reverting to old specimen %s" % (new_s, self.s)) | update figures and text when a new specimen is selected | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L1615-L1625 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.on_info_click | 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 | 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() | Show popup info window when user clicks "?" | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L1683-L1705 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.on_prev_button | 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 | 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() | update figures and text when a previous button is selected | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L1707-L1733 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.clear_boxes | def clear_boxes(self):
"""
Clear all boxes
"""
self.tmin_box.Clear()
self.tmin_box.SetItems(self.T_list)
self.tmin_box.SetSelection(-1)
self.tmax_box.Clear()
self.tmax_box.SetItems(self.T_list)
self.tmax_box.SetSelection(-1)
self.Blab_window.SetValue("")
self.Banc_window.SetValue("")
self.Banc_window.SetBackgroundColour(wx.Colour('grey'))
self.Aniso_factor_window.SetValue("")
self.Aniso_factor_window.SetBackgroundColour(wx.Colour('grey'))
self.NLT_factor_window.SetValue("")
self.NLT_factor_window.SetBackgroundColour(wx.Colour('grey'))
self.CR_factor_window.SetValue("")
self.CR_factor_window.SetBackgroundColour(wx.Colour('grey'))
self.declination_window.SetValue("")
self.declination_window.SetBackgroundColour(wx.Colour('grey'))
self.inclination_window.SetValue("")
self.inclination_window.SetBackgroundColour(wx.Colour('grey'))
window_list = ['sample_int_n', 'sample_int_uT',
'sample_int_sigma', 'sample_int_sigma_perc']
for key in window_list:
command = "self.%s_window.SetValue(\"\")" % key
exec(command)
command = "self.%s_window.SetBackgroundColour(wx.Colour('grey'))" % key
exec(command)
# window_list=['int_n','int_ptrm_n','frac','scat','gmax','f','fvds','b_beta','g','q','int_mad','int_dang','drats','md','ptrms_dec','ptrms_inc','ptrms_mad','ptrms_angle']
# for key in window_list:
for key in self.preferences['show_statistics_on_gui']:
self.stat_windows[key].SetValue("")
self.stat_windows[key].SetBackgroundColour(wx.Colour('grey')) | python | def clear_boxes(self):
"""
Clear all boxes
"""
self.tmin_box.Clear()
self.tmin_box.SetItems(self.T_list)
self.tmin_box.SetSelection(-1)
self.tmax_box.Clear()
self.tmax_box.SetItems(self.T_list)
self.tmax_box.SetSelection(-1)
self.Blab_window.SetValue("")
self.Banc_window.SetValue("")
self.Banc_window.SetBackgroundColour(wx.Colour('grey'))
self.Aniso_factor_window.SetValue("")
self.Aniso_factor_window.SetBackgroundColour(wx.Colour('grey'))
self.NLT_factor_window.SetValue("")
self.NLT_factor_window.SetBackgroundColour(wx.Colour('grey'))
self.CR_factor_window.SetValue("")
self.CR_factor_window.SetBackgroundColour(wx.Colour('grey'))
self.declination_window.SetValue("")
self.declination_window.SetBackgroundColour(wx.Colour('grey'))
self.inclination_window.SetValue("")
self.inclination_window.SetBackgroundColour(wx.Colour('grey'))
window_list = ['sample_int_n', 'sample_int_uT',
'sample_int_sigma', 'sample_int_sigma_perc']
for key in window_list:
command = "self.%s_window.SetValue(\"\")" % key
exec(command)
command = "self.%s_window.SetBackgroundColour(wx.Colour('grey'))" % key
exec(command)
# window_list=['int_n','int_ptrm_n','frac','scat','gmax','f','fvds','b_beta','g','q','int_mad','int_dang','drats','md','ptrms_dec','ptrms_inc','ptrms_mad','ptrms_angle']
# for key in window_list:
for key in self.preferences['show_statistics_on_gui']:
self.stat_windows[key].SetValue("")
self.stat_windows[key].SetBackgroundColour(wx.Colour('grey')) | Clear all boxes | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L1737-L1775 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.read_preferences_file | 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 | 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 {} | If json preferences file exists, read it in. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2174-L2186 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.write_preferences_file | def write_preferences_file(self):
"""
Write json preferences file to (platform specific) user data directory,
or PmagPy directory if appdirs module is missing.
"""
user_data_dir = find_pmag_dir.find_user_data_dir("thellier_gui")
if not os.path.exists(user_data_dir):
find_pmag_dir.make_user_data_dir(user_data_dir)
pref_file = os.path.join(user_data_dir, "thellier_gui_preferences.json")
with open(pref_file, "w+") as pfile:
print('-I- writing preferences to {}'.format(pref_file))
json.dump(self.preferences, pfile) | python | def write_preferences_file(self):
"""
Write json preferences file to (platform specific) user data directory,
or PmagPy directory if appdirs module is missing.
"""
user_data_dir = find_pmag_dir.find_user_data_dir("thellier_gui")
if not os.path.exists(user_data_dir):
find_pmag_dir.make_user_data_dir(user_data_dir)
pref_file = os.path.join(user_data_dir, "thellier_gui_preferences.json")
with open(pref_file, "w+") as pfile:
print('-I- writing preferences to {}'.format(pref_file))
json.dump(self.preferences, pfile) | Write json preferences file to (platform specific) user data directory,
or PmagPy directory if appdirs module is missing. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2188-L2199 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.on_menu_exit | 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 | 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() | Runs whenever Thellier GUI exits | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2283-L2309 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.on_menu_previous_interpretation | def on_menu_previous_interpretation(self, event):
"""
Create and show the Open FileDialog for upload previous interpretation
input should be a valid "redo file":
[specimen name] [tmin(kelvin)] [tmax(kelvin)]
"""
save_current_specimen = self.s
dlg = wx.FileDialog(
self, message="choose a file in a pmagpy redo format",
defaultDir=self.WD,
defaultFile="thellier_GUI.redo",
wildcard="*.redo",
style=wx.FD_OPEN | wx.FD_CHANGE_DIR
)
if self.show_dlg(dlg) == wx.ID_OK:
redo_file = dlg.GetPath()
if self.test_mode:
redo_file = "thellier_GUI.redo"
else:
redo_file = None
dlg.Destroy()
print("redo_file", redo_file)
if redo_file:
self.read_redo_file(redo_file) | python | def on_menu_previous_interpretation(self, event):
"""
Create and show the Open FileDialog for upload previous interpretation
input should be a valid "redo file":
[specimen name] [tmin(kelvin)] [tmax(kelvin)]
"""
save_current_specimen = self.s
dlg = wx.FileDialog(
self, message="choose a file in a pmagpy redo format",
defaultDir=self.WD,
defaultFile="thellier_GUI.redo",
wildcard="*.redo",
style=wx.FD_OPEN | wx.FD_CHANGE_DIR
)
if self.show_dlg(dlg) == wx.ID_OK:
redo_file = dlg.GetPath()
if self.test_mode:
redo_file = "thellier_GUI.redo"
else:
redo_file = None
dlg.Destroy()
print("redo_file", redo_file)
if redo_file:
self.read_redo_file(redo_file) | Create and show the Open FileDialog for upload previous interpretation
input should be a valid "redo file":
[specimen name] [tmin(kelvin)] [tmax(kelvin)] | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2420-L2444 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.on_menu_criteria_file | def on_menu_criteria_file(self, event):
"""
read pmag_criteria.txt file
and open change criteria dialog
"""
if self.data_model == 3:
dlg = wx.FileDialog(
self, message="choose a file in MagIC Data Model 3.0 format",
defaultDir=self.WD,
defaultFile="criteria.txt",
style=wx.FD_OPEN | wx.FD_CHANGE_DIR
)
else:
dlg = wx.FileDialog(
self, message="choose a file in a MagIC Data Model 2.5 pmagpy format",
defaultDir=self.WD,
defaultFile="pmag_criteria.txt",
# wildcard=wildcard,
style=wx.FD_OPEN | wx.FD_CHANGE_DIR
)
if self.show_dlg(dlg) == wx.ID_OK:
criteria_file = dlg.GetPath()
self.GUI_log.write(
"-I- Read new criteria file: %s\n" % criteria_file)
dlg.Destroy()
replace_acceptance_criteria = pmag.initialize_acceptance_criteria(
data_model=self.data_model)
try:
if self.data_model == 3:
self.read_criteria_file(criteria_file)
replace_acceptance_criteria = self.acceptance_criteria
# replace_acceptance_criteria=pmag.read_criteria_from_file(criteria_file,replace_acceptance_criteria,data_model=self.data_model)
# # just to see if file exists
print(replace_acceptance_criteria)
else:
replace_acceptance_criteria = pmag.read_criteria_from_file(
criteria_file, replace_acceptance_criteria, data_model=self.data_model) # just to see if file exists
except Exception as ex:
print('-W-', ex)
dlg1 = wx.MessageDialog(
self, caption="Error:", message="error in reading file", style=wx.OK)
result = self.show_dlg(dlg1)
if result == wx.ID_OK:
dlg1.Destroy()
return
self.add_thellier_gui_criteria()
self.read_criteria_file(criteria_file)
# check if some statistics are in the new criteria but not in old. If
# yes, add to self.preferences['show_statistics_on_gui']
crit_list_not_in_pref = []
for crit in list(self.acceptance_criteria.keys()):
if self.acceptance_criteria[crit]['category'] == "IE-SPEC":
if self.acceptance_criteria[crit]['value'] != -999:
short_crit = crit.split('specimen_')[-1]
if short_crit not in self.preferences['show_statistics_on_gui']:
print("-I- statistic %s is not in your preferences" % crit)
self.preferences['show_statistics_on_gui'].append(
short_crit)
crit_list_not_in_pref.append(crit)
if len(crit_list_not_in_pref) > 0:
stat_list = ":".join(crit_list_not_in_pref)
dlg1 = wx.MessageDialog(self, caption="WARNING:",
message="statistics '%s' is in the imported criteria file but not in your appearence preferences.\nThis statistic will not appear on the gui panel.\n The program will exit after saving new acceptance criteria, and it will be added automatically the next time you open it " % stat_list,
style=wx.OK | wx.ICON_INFORMATION)
self.show_dlg(dlg1)
dlg1.Destroy()
dia = thellier_gui_dialogs.Criteria_Dialog(
None, self.acceptance_criteria, self.preferences, title='Acceptance Criteria')
dia.Center()
result = self.show_dlg(dia)
if result == wx.ID_OK: # Until the user clicks OK, show the message
self.On_close_criteria_box(dia)
if len(crit_list_not_in_pref) > 0:
dlg1 = wx.MessageDialog(self, caption="WARNING:",
message="Exiting now! When you restart the gui all the new statistics will be added.",
style=wx.OK | wx.ICON_INFORMATION)
self.show_dlg(dlg1)
dlg1.Destroy()
self.on_menu_exit(None)
# self.Destroy()
# sys.exit()
if result == wx.ID_CANCEL: # Until the user clicks OK, show the message
for crit in crit_list_not_in_pref:
short_crit = crit.split('specimen_')[-1]
self.preferences['show_statistics_on_gui'].remove(short_crit) | python | def on_menu_criteria_file(self, event):
"""
read pmag_criteria.txt file
and open change criteria dialog
"""
if self.data_model == 3:
dlg = wx.FileDialog(
self, message="choose a file in MagIC Data Model 3.0 format",
defaultDir=self.WD,
defaultFile="criteria.txt",
style=wx.FD_OPEN | wx.FD_CHANGE_DIR
)
else:
dlg = wx.FileDialog(
self, message="choose a file in a MagIC Data Model 2.5 pmagpy format",
defaultDir=self.WD,
defaultFile="pmag_criteria.txt",
# wildcard=wildcard,
style=wx.FD_OPEN | wx.FD_CHANGE_DIR
)
if self.show_dlg(dlg) == wx.ID_OK:
criteria_file = dlg.GetPath()
self.GUI_log.write(
"-I- Read new criteria file: %s\n" % criteria_file)
dlg.Destroy()
replace_acceptance_criteria = pmag.initialize_acceptance_criteria(
data_model=self.data_model)
try:
if self.data_model == 3:
self.read_criteria_file(criteria_file)
replace_acceptance_criteria = self.acceptance_criteria
# replace_acceptance_criteria=pmag.read_criteria_from_file(criteria_file,replace_acceptance_criteria,data_model=self.data_model)
# # just to see if file exists
print(replace_acceptance_criteria)
else:
replace_acceptance_criteria = pmag.read_criteria_from_file(
criteria_file, replace_acceptance_criteria, data_model=self.data_model) # just to see if file exists
except Exception as ex:
print('-W-', ex)
dlg1 = wx.MessageDialog(
self, caption="Error:", message="error in reading file", style=wx.OK)
result = self.show_dlg(dlg1)
if result == wx.ID_OK:
dlg1.Destroy()
return
self.add_thellier_gui_criteria()
self.read_criteria_file(criteria_file)
# check if some statistics are in the new criteria but not in old. If
# yes, add to self.preferences['show_statistics_on_gui']
crit_list_not_in_pref = []
for crit in list(self.acceptance_criteria.keys()):
if self.acceptance_criteria[crit]['category'] == "IE-SPEC":
if self.acceptance_criteria[crit]['value'] != -999:
short_crit = crit.split('specimen_')[-1]
if short_crit not in self.preferences['show_statistics_on_gui']:
print("-I- statistic %s is not in your preferences" % crit)
self.preferences['show_statistics_on_gui'].append(
short_crit)
crit_list_not_in_pref.append(crit)
if len(crit_list_not_in_pref) > 0:
stat_list = ":".join(crit_list_not_in_pref)
dlg1 = wx.MessageDialog(self, caption="WARNING:",
message="statistics '%s' is in the imported criteria file but not in your appearence preferences.\nThis statistic will not appear on the gui panel.\n The program will exit after saving new acceptance criteria, and it will be added automatically the next time you open it " % stat_list,
style=wx.OK | wx.ICON_INFORMATION)
self.show_dlg(dlg1)
dlg1.Destroy()
dia = thellier_gui_dialogs.Criteria_Dialog(
None, self.acceptance_criteria, self.preferences, title='Acceptance Criteria')
dia.Center()
result = self.show_dlg(dia)
if result == wx.ID_OK: # Until the user clicks OK, show the message
self.On_close_criteria_box(dia)
if len(crit_list_not_in_pref) > 0:
dlg1 = wx.MessageDialog(self, caption="WARNING:",
message="Exiting now! When you restart the gui all the new statistics will be added.",
style=wx.OK | wx.ICON_INFORMATION)
self.show_dlg(dlg1)
dlg1.Destroy()
self.on_menu_exit(None)
# self.Destroy()
# sys.exit()
if result == wx.ID_CANCEL: # Until the user clicks OK, show the message
for crit in crit_list_not_in_pref:
short_crit = crit.split('specimen_')[-1]
self.preferences['show_statistics_on_gui'].remove(short_crit) | read pmag_criteria.txt file
and open change criteria dialog | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2617-L2704 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.on_menu_criteria | def on_menu_criteria(self, event):
"""
Change acceptance criteria
and save it to the criteria file (data_model=2: pmag_criteria.txt; data_model=3: criteria.txt)
"""
dia = thellier_gui_dialogs.Criteria_Dialog(
None, self.acceptance_criteria, self.preferences, title='Set Acceptance Criteria')
dia.Center()
result = self.show_dlg(dia)
if result == wx.ID_OK: # Until the user clicks OK, show the message
self.On_close_criteria_box(dia) | python | def on_menu_criteria(self, event):
"""
Change acceptance criteria
and save it to the criteria file (data_model=2: pmag_criteria.txt; data_model=3: criteria.txt)
"""
dia = thellier_gui_dialogs.Criteria_Dialog(
None, self.acceptance_criteria, self.preferences, title='Set Acceptance Criteria')
dia.Center()
result = self.show_dlg(dia)
if result == wx.ID_OK: # Until the user clicks OK, show the message
self.On_close_criteria_box(dia) | Change acceptance criteria
and save it to the criteria file (data_model=2: pmag_criteria.txt; data_model=3: criteria.txt) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2708-L2720 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.On_close_criteria_box | 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 | 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 | after criteria dialog window is closed.
Take the acceptance criteria values and update
self.acceptance_criteria | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2722-L2794 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.recalculate_satistics | def recalculate_satistics(self):
'''
update self.Data[specimen]['pars'] for all specimens.
'''
gframe = wx.BusyInfo(
"Re-calculating statistics for all specimens\n Please wait..", self)
for specimen in list(self.Data.keys()):
if 'pars' not in list(self.Data[specimen].keys()):
continue
if 'specimen_int_uT' not in list(self.Data[specimen]['pars'].keys()):
continue
tmin = self.Data[specimen]['pars']['measurement_step_min']
tmax = self.Data[specimen]['pars']['measurement_step_max']
pars = thellier_gui_lib.get_PI_parameters(
self.Data, self.acceptance_criteria, self.preferences, specimen, tmin, tmax, self.GUI_log, THERMAL, MICROWAVE)
self.Data[specimen]['pars'] = pars
self.Data[specimen]['pars']['lab_dc_field'] = self.Data[specimen]['lab_dc_field']
self.Data[specimen]['pars']['er_specimen_name'] = self.Data[specimen]['er_specimen_name']
self.Data[specimen]['pars']['er_sample_name'] = self.Data[specimen]['er_sample_name']
del gframe | python | def recalculate_satistics(self):
'''
update self.Data[specimen]['pars'] for all specimens.
'''
gframe = wx.BusyInfo(
"Re-calculating statistics for all specimens\n Please wait..", self)
for specimen in list(self.Data.keys()):
if 'pars' not in list(self.Data[specimen].keys()):
continue
if 'specimen_int_uT' not in list(self.Data[specimen]['pars'].keys()):
continue
tmin = self.Data[specimen]['pars']['measurement_step_min']
tmax = self.Data[specimen]['pars']['measurement_step_max']
pars = thellier_gui_lib.get_PI_parameters(
self.Data, self.acceptance_criteria, self.preferences, specimen, tmin, tmax, self.GUI_log, THERMAL, MICROWAVE)
self.Data[specimen]['pars'] = pars
self.Data[specimen]['pars']['lab_dc_field'] = self.Data[specimen]['lab_dc_field']
self.Data[specimen]['pars']['er_specimen_name'] = self.Data[specimen]['er_specimen_name']
self.Data[specimen]['pars']['er_sample_name'] = self.Data[specimen]['er_sample_name']
del gframe | update self.Data[specimen]['pars'] for all specimens. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2800-L2820 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.read_criteria_file | 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 | 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' | read criteria file.
initialize self.acceptance_criteria
try to guess if averaging by sample or by site. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2824-L2884 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.on_menu_save_interpretation | 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 | 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 | save interpretations to a redo file | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2886-L2918 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.on_menu_clear_interpretation | 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 | 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) | clear all current interpretations. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2920-L2937 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.read_redo_file | def read_redo_file(self, redo_file):
"""
Read previous interpretation from a redo file
and update gui with the new interpretation
"""
self.GUI_log.write(
"-I- reading redo file and processing new temperature bounds")
self.redo_specimens = {}
# first 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']
# print sp
# print self.Data[sp]['pars']
self.Data_samples = {}
self.Data_sites = {}
fin = open(redo_file, 'r')
lines = fin.readlines()
fin.close()
for Line in lines:
line = Line.strip('\n').split()
specimen = line[0]
tmin_kelvin = float(line[1])
tmax_kelvin = float(line[2])
if specimen not in list(self.redo_specimens.keys()):
self.redo_specimens[specimen] = {}
self.redo_specimens[specimen]['t_min'] = float(tmin_kelvin)
self.redo_specimens[specimen]['t_max'] = float(tmax_kelvin)
if specimen in list(self.Data.keys()):
if tmin_kelvin not in self.Data[specimen]['t_Arai'] or tmax_kelvin not in self.Data[specimen]['t_Arai']:
self.GUI_log.write(
"-W- WARNING: can't fit temperature bounds in the redo file to the actual measurement. specimen %s\n" % specimen)
else:
self.Data[specimen]['pars'] = thellier_gui_lib.get_PI_parameters(
self.Data, self.acceptance_criteria, self.preferences, specimen, float(tmin_kelvin), float(tmax_kelvin), self.GUI_log, THERMAL, MICROWAVE)
try:
self.Data[specimen]['pars'] = thellier_gui_lib.get_PI_parameters(
self.Data, self.acceptance_criteria, self.preferences, specimen, float(tmin_kelvin), float(tmax_kelvin), self.GUI_log, THERMAL, MICROWAVE)
self.Data[specimen]['pars']['saved'] = True
# write intrepretation into sample data
sample = self.Data_hierarchy['specimens'][specimen]
if sample not in list(self.Data_samples.keys()):
self.Data_samples[sample] = {}
if specimen not in list(self.Data_samples[sample].keys()):
self.Data_samples[sample][specimen] = {}
self.Data_samples[sample][specimen]['B'] = self.Data[specimen]['pars']['specimen_int_uT']
site = thellier_gui_lib.get_site_from_hierarchy(
sample, self.Data_hierarchy)
if site not in list(self.Data_sites.keys()):
self.Data_sites[site] = {}
if specimen not in list(self.Data_sites[site].keys()):
self.Data_sites[site][specimen] = {}
self.Data_sites[site][specimen]['B'] = self.Data[specimen]['pars']['specimen_int_uT']
except:
print("-E- ERROR 1")
self.GUI_log.write(
"-E- ERROR. Can't calculate PI paremeters for specimen %s using redo file. Check!\n" % (specimen))
else:
self.GUI_log.write(
"-W- WARNING: Can't find specimen %s from redo file in measurement file!\n" % specimen)
print(
"-W- WARNING: Can't find specimen %s from redo file in measurement file!\n" % specimen)
if not fin.closed:
fin.close()
self.pars = self.Data[self.s]['pars']
self.clear_boxes()
self.draw_figure(self.s)
self.update_GUI_with_new_interpretation() | python | def read_redo_file(self, redo_file):
"""
Read previous interpretation from a redo file
and update gui with the new interpretation
"""
self.GUI_log.write(
"-I- reading redo file and processing new temperature bounds")
self.redo_specimens = {}
# first 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']
# print sp
# print self.Data[sp]['pars']
self.Data_samples = {}
self.Data_sites = {}
fin = open(redo_file, 'r')
lines = fin.readlines()
fin.close()
for Line in lines:
line = Line.strip('\n').split()
specimen = line[0]
tmin_kelvin = float(line[1])
tmax_kelvin = float(line[2])
if specimen not in list(self.redo_specimens.keys()):
self.redo_specimens[specimen] = {}
self.redo_specimens[specimen]['t_min'] = float(tmin_kelvin)
self.redo_specimens[specimen]['t_max'] = float(tmax_kelvin)
if specimen in list(self.Data.keys()):
if tmin_kelvin not in self.Data[specimen]['t_Arai'] or tmax_kelvin not in self.Data[specimen]['t_Arai']:
self.GUI_log.write(
"-W- WARNING: can't fit temperature bounds in the redo file to the actual measurement. specimen %s\n" % specimen)
else:
self.Data[specimen]['pars'] = thellier_gui_lib.get_PI_parameters(
self.Data, self.acceptance_criteria, self.preferences, specimen, float(tmin_kelvin), float(tmax_kelvin), self.GUI_log, THERMAL, MICROWAVE)
try:
self.Data[specimen]['pars'] = thellier_gui_lib.get_PI_parameters(
self.Data, self.acceptance_criteria, self.preferences, specimen, float(tmin_kelvin), float(tmax_kelvin), self.GUI_log, THERMAL, MICROWAVE)
self.Data[specimen]['pars']['saved'] = True
# write intrepretation into sample data
sample = self.Data_hierarchy['specimens'][specimen]
if sample not in list(self.Data_samples.keys()):
self.Data_samples[sample] = {}
if specimen not in list(self.Data_samples[sample].keys()):
self.Data_samples[sample][specimen] = {}
self.Data_samples[sample][specimen]['B'] = self.Data[specimen]['pars']['specimen_int_uT']
site = thellier_gui_lib.get_site_from_hierarchy(
sample, self.Data_hierarchy)
if site not in list(self.Data_sites.keys()):
self.Data_sites[site] = {}
if specimen not in list(self.Data_sites[site].keys()):
self.Data_sites[site][specimen] = {}
self.Data_sites[site][specimen]['B'] = self.Data[specimen]['pars']['specimen_int_uT']
except:
print("-E- ERROR 1")
self.GUI_log.write(
"-E- ERROR. Can't calculate PI paremeters for specimen %s using redo file. Check!\n" % (specimen))
else:
self.GUI_log.write(
"-W- WARNING: Can't find specimen %s from redo file in measurement file!\n" % specimen)
print(
"-W- WARNING: Can't find specimen %s from redo file in measurement file!\n" % specimen)
if not fin.closed:
fin.close()
self.pars = self.Data[self.s]['pars']
self.clear_boxes()
self.draw_figure(self.s)
self.update_GUI_with_new_interpretation() | Read previous interpretation from a redo file
and update gui with the new interpretation | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L3683-L3755 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.on_menu_prepare_magic_results_tables | def on_menu_prepare_magic_results_tables(self, event):
"""
Menubar --> File --> Save MagIC tables
"""
# write a redo file
try:
self.on_menu_save_interpretation(None)
except Exception as ex:
print('-W-', ex)
pass
if self.data_model != 3: # data model 3 data already read in to contribution
#------------------
# read existing pmag results data and sort out the directional data.
# The directional data will be merged to one combined pmag table.
# these data will be merged later
#-----------------------.
PmagRecsOld = {}
for FILE in ['pmag_specimens.txt', 'pmag_samples.txt', 'pmag_sites.txt', 'pmag_results.txt']:
PmagRecsOld[FILE], meas_data = [], []
try:
meas_data, file_type = pmag.magic_read(
os.path.join(self.WD, FILE))
self.GUI_log.write(
"-I- Read existing magic file %s\n" % (os.path.join(self.WD, FILE)))
# if FILE !='pmag_specimens.txt':
os.rename(os.path.join(self.WD, FILE),
os.path.join(self.WD, FILE + ".backup"))
self.GUI_log.write(
"-I- rename old magic file %s.backup\n" % (os.path.join(self.WD, FILE)))
except:
self.GUI_log.write(
"-I- Can't read existing magic file %s\n" % (os.path.join(self.WD, FILE)))
continue
for rec in meas_data:
if "magic_method_codes" in list(rec.keys()):
if "LP-PI" not in rec['magic_method_codes'] and "IE-" not in rec['magic_method_codes']:
PmagRecsOld[FILE].append(rec)
pmag_specimens_header_1 = [
"er_location_name", "er_site_name", "er_sample_name", "er_specimen_name"]
pmag_specimens_header_2 = [
'measurement_step_min', 'measurement_step_max', 'specimen_int']
pmag_specimens_header_3 = ["specimen_correction", "specimen_int_corr_anisotropy",
"specimen_int_corr_nlt", "specimen_int_corr_cooling_rate"]
pmag_specimens_header_4 = []
for short_stat in self.preferences['show_statistics_on_gui']:
stat = "specimen_" + short_stat
pmag_specimens_header_4.append(stat)
pmag_specimens_header_5 = [
"magic_experiment_names", "magic_method_codes", "measurement_step_unit", "specimen_lab_field_dc"]
pmag_specimens_header_6 = ["er_citation_names"]
specimens_list = []
for specimen in list(self.Data.keys()):
if 'pars' in list(self.Data[specimen].keys()):
if 'saved' in self.Data[specimen]['pars'] and self.Data[specimen]['pars']['saved']:
specimens_list.append(specimen)
elif 'deleted' in self.Data[specimen]['pars'] and self.Data[specimen]['pars']['deleted']:
specimens_list.append(specimen)
# Empty pmag tables:
MagIC_results_data = {}
MagIC_results_data['pmag_specimens'] = {}
MagIC_results_data['pmag_samples_or_sites'] = {}
MagIC_results_data['pmag_results'] = {}
# write down pmag_specimens.txt
specimens_list.sort()
for specimen in specimens_list:
if 'pars' in self.Data[specimen] and 'deleted' in self.Data[specimen]['pars'] and self.Data[specimen]['pars']['deleted']:
print('-I- Deleting interpretation for {}'.format(specimen))
this_spec_data = self.spec_data.loc[specimen]
# there are multiple rows for this specimen
if isinstance(this_spec_data, pd.DataFrame):
# delete the intensity rows for specimen
cond1 = self.spec_container.df.specimen == specimen
cond2 = self.spec_container.df.int_abs.notnull()
cond = cond1 & cond2
self.spec_container.df = self.spec_container.df[-cond]
# there is only one record for this specimen
else:
# delete all intensity data for that specimen
columns = list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity'))
columns.extend(list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity pTRM Check Statistics')))
columns.extend(list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity pTRM Tail Check Statistics')))
columns.extend(list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity pTRM Additivity Check Statistics')))
columns.extend(list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity Arai Statistics')))
columns.extend(list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity Directional Statistics')))
int_columns = set(columns).intersection(self.spec_data.columns)
int_columns.update(['method_codes', 'result_quality', 'meas_step_max', 'meas_step_min', 'software_packages', 'meas_step_unit', 'experiments'])
new_data = {col: "" for col in int_columns}
cond1 = self.spec_container.df.specimen == specimen
for col in int_columns:
self.spec_container.df.loc[specimen, col] = ""
elif 'pars' in self.Data[specimen] and 'saved' in self.Data[specimen]['pars'] and self.Data[specimen]['pars']['saved']:
sample_name = self.Data_hierarchy['specimens'][specimen]
site_name = thellier_gui_lib.get_site_from_hierarchy(
sample_name, self.Data_hierarchy)
location_name = thellier_gui_lib.get_location_from_hierarchy(
site_name, self.Data_hierarchy)
MagIC_results_data['pmag_specimens'][specimen] = {}
if version != "unknown":
MagIC_results_data['pmag_specimens'][specimen]['magic_software_packages'] = version
MagIC_results_data['pmag_specimens'][specimen]['er_citation_names'] = "This study"
# MagIC_results_data['pmag_specimens'][specimen]['er_analyst_mail_names']="unknown"
MagIC_results_data['pmag_specimens'][specimen]['er_specimen_name'] = specimen
MagIC_results_data['pmag_specimens'][specimen]['er_sample_name'] = sample_name
MagIC_results_data['pmag_specimens'][specimen]['er_site_name'] = site_name
MagIC_results_data['pmag_specimens'][specimen]['er_location_name'] = location_name
MagIC_results_data['pmag_specimens'][specimen]['magic_method_codes'] = self.Data[
specimen]['pars']['magic_method_codes'] + ":IE-TT"
tmp = MagIC_results_data['pmag_specimens'][specimen]['magic_method_codes'].split(
":")
# magic_experiment_names=specimen
magic_experiment_names = ""
# for m in tmp: # this is incorrect - it should be a concatenated list of the experiment names from the measurement table.
# if "LP-" in m:
# magic_experiment_names=magic_experiment_names+":" + m
MagIC_results_data['pmag_specimens'][specimen]['magic_experiment_names'] = magic_experiment_names
MagIC_results_data['pmag_specimens'][specimen]['measurement_step_unit'] = 'K'
MagIC_results_data['pmag_specimens'][specimen]['specimen_lab_field_dc'] = "%.2e" % (
self.Data[specimen]['pars']['lab_dc_field'])
MagIC_results_data['pmag_specimens'][specimen]['specimen_correction'] = self.Data[specimen]['pars']['specimen_correction']
for key in pmag_specimens_header_4:
if key in ['specimen_int_ptrm_n', 'specimen_int_n']:
MagIC_results_data['pmag_specimens'][specimen][key] = "%i" % (
self.Data[specimen]['pars'][key])
elif key in ['specimen_scat'] and self.Data[specimen]['pars'][key] in ["Fail", 'f']:
MagIC_results_data['pmag_specimens'][specimen][key] = "f"
elif key in ['specimen_scat'] and self.Data[specimen]['pars'][key] in ["Pass", 't']:
MagIC_results_data['pmag_specimens'][specimen][key] = "t"
else:
MagIC_results_data['pmag_specimens'][specimen][key] = "%.2f" % (
self.Data[specimen]['pars'][key])
MagIC_results_data['pmag_specimens'][specimen]['specimen_int'] = "%.2e" % (
self.Data[specimen]['pars']['specimen_int'])
MagIC_results_data['pmag_specimens'][specimen]['measurement_step_min'] = "%i" % (
self.Data[specimen]['pars']['measurement_step_min'])
MagIC_results_data['pmag_specimens'][specimen]['measurement_step_max'] = "%i" % (
self.Data[specimen]['pars']['measurement_step_max'])
if "specimen_int_corr_anisotropy" in list(self.Data[specimen]['pars'].keys()):
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_anisotropy'] = "%.2f" % (
self.Data[specimen]['pars']['specimen_int_corr_anisotropy'])
else:
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_anisotropy'] = ""
if "specimen_int_corr_nlt" in list(self.Data[specimen]['pars'].keys()):
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_nlt'] = "%.2f" % (
self.Data[specimen]['pars']['specimen_int_corr_nlt'])
else:
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_nlt'] = ""
if "specimen_int_corr_cooling_rate" in list(self.Data[specimen]['pars'].keys()) and self.Data[specimen]['pars']['specimen_int_corr_cooling_rate'] != -999:
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_cooling_rate'] = "%.2f" % (
self.Data[specimen]['pars']['specimen_int_corr_cooling_rate'])
else:
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_cooling_rate'] = ""
MagIC_results_data['pmag_specimens'][specimen]['criteria'] = "IE-SPEC"
if self.data_model == 3: # convert pmag_specimen format to data model 3 and replace existing specimen record or add new & delete blank records
new_spec_data = MagIC_results_data['pmag_specimens'][specimen]
# turn new_specimen data to 3.0
new_data = map_magic.convert_spec('magic3', new_spec_data)
# check if interpretation passes criteria and set flag
spec_pars = thellier_gui_lib.check_specimen_PI_criteria(
self.Data[specimen]['pars'], self.acceptance_criteria)
if len(spec_pars['specimen_fail_criteria']) > 0:
new_data['result_quality'] = 'b'
else:
new_data['result_quality'] = 'g'
# reformat all the keys
cond1 = self.spec_container.df['specimen'].str.contains(
specimen + "$") == True
if 'int_abs' not in self.spec_container.df.columns:
self.spec_container.df['int_abs'] = None
print("-W- No intensity data found for specimens")
cond2 = self.spec_container.df['int_abs'].apply(lambda x: cb.not_null(x, False)) #notnull() == True
condition = (cond1 & cond2)
# update intensity records
self.spec_data = self.spec_container.update_record(
specimen, new_data, condition)
## delete essentially blank records
#condition = self.spec_data['method_codes'].isnull().astype(
#bool) # find the blank records
#info_str = "specimen rows with blank method codes"
#self.spec_data = self.spec_container.delete_rows(
# condition, info_str) # delete them
if self.data_model != 3: # write out pmag_specimens.txt file
fout = open(os.path.join(self.WD, "pmag_specimens.txt"), 'w')
fout.write("tab\tpmag_specimens\n")
headers = pmag_specimens_header_1 + pmag_specimens_header_2 + pmag_specimens_header_3 + \
pmag_specimens_header_4 + pmag_specimens_header_5 + pmag_specimens_header_6
String = ""
for key in headers:
String = String + key + "\t"
fout.write(String[:-1] + "\n")
for specimen in specimens_list:
String = ""
for key in headers:
String = String + \
MagIC_results_data['pmag_specimens'][specimen][key] + "\t"
fout.write(String[:-1] + "\n")
fout.close()
# merge with non-intensity data
# read the new pmag_specimens.txt
meas_data, file_type = pmag.magic_read(
os.path.join(self.WD, "pmag_specimens.txt"))
# add the old non-PI lines from pmag_specimens.txt
for rec in PmagRecsOld["pmag_specimens.txt"]:
meas_data.append(rec)
# fix headers, so all headers in all lines
meas_data = self.converge_pmag_rec_headers(meas_data)
# write the combined pmag_specimens.txt
pmag.magic_write(os.path.join(
self.WD, "pmag_specimens.txt"), meas_data, 'pmag_specimens')
try:
os.remove(os.path.join(self.WD, "pmag_specimens.txt.backup"))
except:
pass
#-------------
# message dialog
#-------------
TEXT = "specimens interpretations are saved in pmag_specimens.txt.\nPress OK for pmag_samples/pmag_sites/pmag_results tables."
else: # data model 3, so merge with spec_data and save as specimens.txt file
# remove unwanted columns (site, location).
for col in ['site', 'location']:
if col in self.spec_data.columns:
del self.spec_data[col]
self.spec_container.drop_duplicate_rows()
# write out the data
self.spec_container.write_magic_file(dir_path=self.WD)
TEXT = "specimens interpretations are saved in specimens.txt.\nPress OK for samples/sites tables."
dlg = wx.MessageDialog(self, caption="Saved",
message=TEXT, style=wx.OK | wx.CANCEL)
result = self.show_dlg(dlg)
if result == wx.ID_OK:
dlg.Destroy()
if result == wx.ID_CANCEL:
dlg.Destroy()
return()
#-------------
# pmag_samples.txt or pmag_sites.txt
#-------------
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
BY_SITES = False
BY_SAMPLES = True
else:
BY_SITES = True
BY_SAMPLES = False
pmag_samples_header_1 = ["er_location_name", "er_site_name"]
if BY_SAMPLES:
pmag_samples_header_1.append("er_sample_name")
if BY_SAMPLES:
pmag_samples_header_2 = ["er_specimen_names", "sample_int", "sample_int_n",
"sample_int_sigma", "sample_int_sigma_perc", "sample_description"]
else:
pmag_samples_header_2 = ["er_specimen_names", "site_int", "site_int_n",
"site_int_sigma", "site_int_sigma_perc", "site_description"]
pmag_samples_header_3 = [
"magic_method_codes", "magic_software_packages"]
pmag_samples_header_4 = ["er_citation_names"]
pmag_samples_or_sites_list = []
if BY_SAMPLES:
samples_or_sites = list(self.Data_samples.keys())
Data_samples_or_sites = copy.deepcopy(self.Data_samples)
else:
samples_or_sites = list(self.Data_sites.keys())
Data_samples_or_sites = copy.deepcopy(self.Data_sites)
samples_or_sites.sort()
for sample_or_site in samples_or_sites:
if True:
specimens_names = ""
B = []
specimens_LP_codes = []
for specimen in list(Data_samples_or_sites[sample_or_site].keys()):
B.append(Data_samples_or_sites[sample_or_site][specimen])
if specimen not in MagIC_results_data['pmag_specimens']:
continue
magic_codes = MagIC_results_data['pmag_specimens'][specimen]['magic_method_codes']
codes = magic_codes.replace(" ", "").split(":")
for code in codes:
if "LP-" in code and code not in specimens_LP_codes:
specimens_LP_codes.append(code)
specimens_names = specimens_names + specimen + ":"
magic_codes = ":".join(specimens_LP_codes) + ":IE-TT"
specimens_names = specimens_names[:-1]
if specimens_names != "":
# sample_pass_criteria=False
sample_or_site_pars = self.calculate_sample_mean(
Data_samples_or_sites[sample_or_site])
if sample_or_site_pars['pass_or_fail'] == 'fail':
continue
N = sample_or_site_pars['N']
B_uT = sample_or_site_pars['B_uT']
B_std_uT = sample_or_site_pars['B_std_uT']
B_std_perc = sample_or_site_pars['B_std_perc']
pmag_samples_or_sites_list.append(sample_or_site)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site] = {
}
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['er_specimen_names'] = specimens_names
if BY_SAMPLES:
name = "sample_"
else:
name = "site_"
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][name +
'int'] = "%.2e" % (B_uT * 1e-6)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][name +
'int_n'] = "%i" % (N)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][name +
'int_sigma'] = "%.2e" % (B_std_uT * 1e-6)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][name +
'int_sigma_perc'] = "%.2f" % (B_std_perc)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][name +
'description'] = "paleointensity mean"
if BY_SAMPLES:
sample_name = sample_or_site
site_name = thellier_gui_lib.get_site_from_hierarchy(
sample_name, self.Data_hierarchy)
location_name = thellier_gui_lib.get_location_from_hierarchy(
site_name, self.Data_hierarchy)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['er_sample_name'] = sample_name
if BY_SITES:
site_name = sample_or_site
location_name = thellier_gui_lib.get_location_from_hierarchy(
site_name, self.Data_hierarchy)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['er_site_name'] = site_name
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['er_location_name'] = location_name
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["pmag_criteria_codes"] = ""
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['magic_method_codes'] = magic_codes
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["magic_software_packages"] = version
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["er_citation_names"] = "This study"
# prepare pmag_samples.txt
pmag_samples_or_sites_list.sort()
if self.data_model != 3: # save 2.5 way
if BY_SAMPLES:
fout = open(os.path.join(self.WD, "pmag_samples.txt"), 'w')
fout.write("tab\tpmag_samples\n")
else:
fout = open(os.path.join(self.WD, "pmag_sites.txt"), 'w')
fout.write("tab\tpmag_sites\n")
headers = pmag_samples_header_1 + pmag_samples_header_2 + \
pmag_samples_header_3 + pmag_samples_header_4
String = ""
for key in headers:
String = String + key + "\t"
fout.write(String[:-1] + "\n")
for sample_or_site in pmag_samples_or_sites_list:
String = ""
for key in headers:
String = String + \
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][key] + "\t"
fout.write(String[:-1] + "\n")
fout.close()
# merge with non-intensity data
if BY_SAMPLES:
meas_data, file_type = pmag.magic_read(
os.path.join(self.WD, "pmag_samples.txt"))
for rec in PmagRecsOld["pmag_samples.txt"]:
meas_data.append(rec)
meas_data = self.converge_pmag_rec_headers(meas_data)
pmag.magic_write(os.path.join(
self.WD, "pmag_samples.txt"), meas_data, 'pmag_samples')
try:
os.remove(os.path.join(self.WD, "pmag_samples.txt.backup"))
except:
pass
pmag.magic_write(os.path.join(
self.WD, "pmag_sites.txt"), PmagRecsOld["pmag_sites.txt"], 'pmag_sites')
try:
os.remove(os.path.join(self.WD, "pmag_sites.txt.backup"))
except:
pass
else:
meas_data, file_type = pmag.magic_read(
os.path.join(self.WD, "pmag_sites.txt"))
for rec in PmagRecsOld["pmag_sites.txt"]:
meas_data.append(rec)
meas_data = self.converge_pmag_rec_headers(meas_data)
pmag.magic_write(os.path.join(
self.WD, "pmag_sites.txt"), meas_data, 'pmag_sites')
try:
os.remove(os.path.join(self.WD, "pmag_sites.txt.backup"))
except:
pass
pmag.magic_write(os.path.join(
self.WD, "pmag_samples.txt"), PmagRecsOld["pmag_samples.txt"], 'pmag_samples')
try:
os.remove(os.path.join(self.WD, "pmag_samples.txt.backup"))
except:
pass
else: # don't do anything yet = need vdm data
pass
#-------------
# pmag_results.txt
#-------------
pmag_results_header_1 = ["er_location_names", "er_site_names"]
if BY_SAMPLES:
pmag_results_header_1.append("er_sample_names")
pmag_results_header_1.append("er_specimen_names")
pmag_results_header_2 = ["average_lat", "average_lon", ]
pmag_results_header_3 = [
"average_int_n", "average_int", "average_int_sigma", "average_int_sigma_perc"]
if self.preferences['VDM_or_VADM'] == "VDM":
pmag_results_header_4 = ["vdm", "vdm_sigma"]
else:
pmag_results_header_4 = ["vadm", "vadm_sigma"]
pmag_results_header_5 = ["data_type", "pmag_result_name", "magic_method_codes",
"result_description", "er_citation_names", "magic_software_packages", "pmag_criteria_codes"]
for sample_or_site in pmag_samples_or_sites_list:
if sample_or_site is None:
continue
if isinstance(sample_or_site, type(np.nan)):
continue
MagIC_results_data['pmag_results'][sample_or_site] = {}
if self.data_model == 3:
if BY_SAMPLES:
if len(self.test_for_criteria()):
MagIC_results_data['pmag_results'][sample_or_site]['pmag_criteria_codes'] = "IE-SPEC:IE-SAMP"
if BY_SITES:
if len(self.test_for_criteria()):
MagIC_results_data['pmag_results'][sample_or_site]['pmag_criteria_codes'] = "IE-SPEC:IE-SITE"
else:
MagIC_results_data['pmag_results'][sample_or_site]['pmag_criteria_codes'] = "ACCEPT"
MagIC_results_data['pmag_results'][sample_or_site]["er_location_names"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site]['er_location_name']
MagIC_results_data['pmag_results'][sample_or_site]["er_site_names"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site]['er_site_name']
MagIC_results_data['pmag_results'][sample_or_site]["er_specimen_names"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site]['er_specimen_names']
if BY_SAMPLES:
MagIC_results_data['pmag_results'][sample_or_site]["er_sample_names"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site]['er_sample_name']
site = MagIC_results_data['pmag_results'][sample_or_site]["er_site_names"]
lat, lon = "", ""
if site in list(self.Data_info["er_sites"].keys()) and "site_lat" in list(self.Data_info["er_sites"][site].keys()):
# MagIC_results_data['pmag_results'][sample_or_site]["average_lat"]=self.Data_info["er_sites"][site]["site_lat"]
lat = self.Data_info["er_sites"][site]["site_lat"]
if site in list(self.Data_info["er_sites"].keys()) and "site_lon" in list(self.Data_info["er_sites"][site].keys()):
# MagIC_results_data['pmag_results'][sample_or_site]["average_lon"]=self.Data_info["er_sites"][site]["site_lon"]
lon = self.Data_info["er_sites"][site]["site_lon"]
MagIC_results_data['pmag_results'][sample_or_site]["average_lat"] = lat
MagIC_results_data['pmag_results'][sample_or_site]["average_lon"] = lon
if BY_SAMPLES:
name = 'sample'
else:
name = 'site'
MagIC_results_data['pmag_results'][sample_or_site]["average_int_n"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site][name + '_int_n']
MagIC_results_data['pmag_results'][sample_or_site]["average_int"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site][name + '_int']
MagIC_results_data['pmag_results'][sample_or_site]["average_int_sigma"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site][name + '_int_sigma']
MagIC_results_data['pmag_results'][sample_or_site]["average_int_sigma_perc"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site][name + '_int_sigma_perc']
if self.preferences['VDM_or_VADM'] == "VDM":
pass
# to be done
else:
if lat != "":
lat = float(lat)
# B=float(MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['sample_int'])
B = float(
MagIC_results_data['pmag_results'][sample_or_site]["average_int"])
# B_sigma=float(MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['sample_int_sigma'])
B_sigma = float(
MagIC_results_data['pmag_results'][sample_or_site]["average_int_sigma"])
VADM = pmag.b_vdm(B, lat)
VADM_plus = pmag.b_vdm(B + B_sigma, lat)
VADM_minus = pmag.b_vdm(B - B_sigma, lat)
VADM_sigma = (VADM_plus - VADM_minus) / 2
MagIC_results_data['pmag_results'][sample_or_site]["vadm"] = "%.2e" % VADM
MagIC_results_data['pmag_results'][sample_or_site]["vadm_sigma"] = "%.2e" % VADM_sigma
if self.data_model == 3: # stick vadm into site_or_sample record
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["vadm"] = "%.2e" % VADM
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["vadm_sigma"] = "%.2e" % VADM_sigma
else:
MagIC_results_data['pmag_results'][sample_or_site]["vadm"] = ""
MagIC_results_data['pmag_results'][sample_or_site]["vadm_sigma"] = ""
if self.data_model == 3: # stick vadm into site_or_sample record
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["vadm"] = ""
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["vadm_sigma"] = ""
if MagIC_results_data['pmag_results'][sample_or_site]["vadm"] != "":
MagIC_results_data['pmag_results'][sample_or_site]["pmag_result_name"] = "Paleointensity;V[A]DM;" + sample_or_site
MagIC_results_data['pmag_results'][sample_or_site]["result_description"] = "Paleointensity; V[A]DM"
else:
MagIC_results_data['pmag_results'][sample_or_site]["pmag_result_name"] = "Paleointensity;" + sample_or_site
MagIC_results_data['pmag_results'][sample_or_site]["result_description"] = "Paleointensity"
MagIC_results_data['pmag_results'][sample_or_site]["magic_software_packages"] = version
MagIC_results_data['pmag_results'][sample_or_site]["magic_method_codes"] = magic_codes
# try to make a more meaningful name
MagIC_results_data['pmag_results'][sample_or_site]["data_type"] = "i"
MagIC_results_data['pmag_results'][sample_or_site]["er_citation_names"] = "This study"
if self.data_model != 3: # look for ages in er_ages - otherwise they are in sites.txt already
# add ages
found_age = False
site = MagIC_results_data['pmag_results'][sample_or_site]["er_site_names"]
if sample_or_site in list(self.Data_info["er_ages"].keys()):
sample_or_site_with_age = sample_or_site
found_age = True
elif site in list(self.Data_info["er_ages"].keys()):
sample_or_site_with_age = site
found_age = True
if found_age:
for header in ["age", "age_unit", "age_sigma", "age_range_low", "age_range_high"]:
if sample_or_site_with_age in list(self.Data_info["er_ages"].keys()) and header in list(self.Data_info["er_ages"][sample_or_site_with_age].keys()):
if self.Data_info["er_ages"][sample_or_site_with_age][header] != "":
value = self.Data_info["er_ages"][sample_or_site_with_age][header]
header_result = "average_" + header
if header_result == "average_age_range_high":
header_result = "average_age_high"
if header_result == "average_age_range_low":
header_result = "average_age_low"
MagIC_results_data['pmag_results'][sample_or_site][header_result] = value
if header_result not in pmag_results_header_4:
pmag_results_header_4.append(header_result)
else:
found_age = False
if BY_SAMPLES and sample_or_site in list(self.Data_info["er_ages"].keys()):
element_with_age = sample_or_site
found_age = True
elif BY_SAMPLES and sample_or_site not in list(self.Data_info["er_ages"].keys()):
site = self.Data_hierarchy['site_of_sample'][sample_or_site]
if site in list(self.Data_info["er_ages"].keys()):
element_with_age = site
found_age = True
elif BY_SITES and sample_or_site in list(self.Data_info["er_ages"].keys()):
element_with_age = sample_or_site
found_age = True
else:
continue
if not found_age:
continue
foundkeys = False
# print "element_with_age",element_with_age
for key in ['age', 'age_sigma', 'age_range_low', 'age_range_high', 'age_unit']:
# print "Ron debug"
# print element_with_age
# print sample_or_site
if "er_ages" in list(self.Data_info.keys()) and element_with_age in list(self.Data_info["er_ages"].keys()):
if key in list(self.Data_info["er_ages"][element_with_age].keys()):
if self.Data_info["er_ages"][element_with_age][key] != "":
# print self.Data_info["er_ages"][element_with_age]
# print self.Data_info["er_ages"][element_with_age][key]
# print
# MagIC_results_data['pmag_results'][sample_or_site]
MagIC_results_data['pmag_results'][sample_or_site][
key] = self.Data_info["er_ages"][element_with_age][key]
foundkeys = True
if foundkeys == True:
if "er_ages" in list(self.Data_info.keys()) and element_with_age in list(self.Data_info["er_ages"].keys()):
if 'magic_method_codes' in list(self.Data_info["er_ages"][element_with_age].keys()):
methods = self.Data_info["er_ages"][element_with_age]['magic_method_codes'].replace(
" ", "").strip('\n').split(":")
for meth in methods:
MagIC_results_data['pmag_results'][sample_or_site]["magic_method_codes"] = MagIC_results_data[
'pmag_results'][sample_or_site]["magic_method_codes"] + ":" + meth
if self.data_model != 3:
# write pmag_results.txt
fout = open(os.path.join(self.WD, "pmag_results.txt"), 'w')
fout.write("tab\tpmag_results\n")
headers = pmag_results_header_1 + pmag_results_header_2 + \
pmag_results_header_3 + pmag_results_header_4 + pmag_results_header_5
String = ""
for key in headers:
String = String + key + "\t"
fout.write(String[:-1] + "\n")
# pmag_samples_list.sort()
for sample_or_site in pmag_samples_or_sites_list:
if sample_or_site is None:
continue
if isinstance(sample_or_site, type(np.nan)):
continue
String = ""
for key in headers:
if key in list(MagIC_results_data['pmag_results'][sample_or_site].keys()):
String = String + \
MagIC_results_data['pmag_results'][sample_or_site][key] + "\t"
else:
String = String + "" + "\t"
fout.write(String[:-1] + "\n")
fout.close()
# merge with non-intensity data
meas_data, file_type = pmag.magic_read(
os.path.join(self.WD, "pmag_results.txt"))
for rec in PmagRecsOld["pmag_results.txt"]:
meas_data.append(rec)
meas_data = self.converge_pmag_rec_headers(meas_data)
pmag.magic_write(os.path.join(
self.WD, "pmag_results.txt"), meas_data, 'pmag_results')
try:
os.remove(os.path.join(self.WD, "pmag_results.txt.backup"))
except:
pass
else: # write out samples/sites in data model 3.0
for sample_or_site in pmag_samples_or_sites_list:
if sample_or_site is None:
continue
if isinstance(sample_or_site, type(np.nan)):
continue
# convert, delete, add and save
new_sample_or_site_data = MagIC_results_data['pmag_samples_or_sites'][sample_or_site]
if BY_SAMPLES:
new_data = map_magic.convert_samp(
'magic3', new_sample_or_site_data) # convert to 3.0
if len(self.test_for_criteria()):
new_data['criteria'] = 'IE-SPEC:IE-SAMP'
new_data['result_quality'] = 'g'
self.samp_data = self.samp_container.df
cond1 = self.samp_data['sample'].str.contains(
sample_or_site + "$") == True
if 'int_abs' not in self.samp_data.columns:
self.samp_data['int_abs'] = None
print('-W- No intensity data found for samples')
cond2 = self.samp_data['int_abs'].notnull() == True
condition = (cond1 & cond2)
# update record
self.samp_data = self.samp_container.update_record(
sample_or_site, new_data, condition)
self.site_data = self.site_container.df
# remove intensity data from site level.
if 'int_abs' not in self.site_data.columns:
self.site_data['int_abs'] = None
print('-W- No intensity data found for sites')
site = self.Data_hierarchy['site_of_sample'][sample_or_site]
try: # if site name is blank will skip
cond1 = self.site_data['site'].str.contains(
site + "$") == True
cond2 = self.site_data['int_abs'].notnull() == True
condition = (cond1 & cond2)
site_keys = ['samples', 'int_abs', 'int_sigma', 'int_n_samples', 'int_sigma_perc', 'specimens',
'int_abs_sigma', 'int_abs_sigma_perc', 'vadm'] # zero these out but keep the rest
blank_data = {}
for key in site_keys:
blank_data[key] = ""
self.site_data = self.site_container.update_record(
site, blank_data, condition, update_only=True)
# add record for sample in the site table
cond1 = self.site_data['site'].str.contains(
sample_or_site + "$") == True
cond2 = self.site_data['int_abs'].notnull() == True
condition = (cond1 & cond2)
# change 'site' column to reflect sample name,
# since we are putting this sample at the site level
new_data['site'] = sample_or_site
new_data['samples'] = sample_or_site
new_data['int_n_samples'] = '1'
# get rid of this key for site table
del new_data['sample']
new_data['vadm'] = MagIC_results_data['pmag_results'][sample_or_site]["vadm"]
new_data['vadm_sigma'] = MagIC_results_data['pmag_results'][sample_or_site]["vadm_sigma"]
new_data['result_quality'] = 'g'
self.site_data = self.site_container.update_record(
sample_or_site, new_data, condition, debug=True)
except:
pass # no site
else: # do this by site and not by sample START HERE
cond1 = self.site_data['site'].str.contains(
sample_or_site + "$") == True
if 'int_abs' not in self.site_data.columns:
self.site_data['int_abs'] = None
cond2 = self.site_data['int_abs'].notnull() == True
condition = (cond1 & cond2)
loc = None
locs = self.site_data[cond1]['location']
if any(locs):
loc = locs.values[0]
new_data['site'] = sample_or_site
new_data['location'] = loc
self.site_data = self.site_container.update_record(
sample_or_site, new_data, condition)
# remove intensity data from sample level. # need to look
# up samples from this site
cond1 = self.samp_data['site'].str.contains(
sample_or_site + "$") == True
if 'int_abs' not in self.samp_data.columns:
self.samp_data['int_abs'] = None
cond2 = self.samp_data['int_abs'].notnull() == True
condition = (cond1 & cond2)
new_data = {} # zero these out but keep the rest
# zero these out but keep the rest
samp_keys = ['int_abs', 'int_sigma',
'int_n_specimens', 'int_sigma_perc']
for key in samp_keys:
new_data[key] = ""
samples = self.samp_data[condition].index.unique()
for samp_name in samples:
self.samp_container.update_record(
samp_name, new_data, cond2)
for col in ['location']:
if col in list(self.samp_data.keys()):
del self.samp_data[col]
# if BY_SAMPLES: # replace 'site' with 'sample'
# self.samp_data['site']=self.samp_data['sample']
# condition= self.samp_container.df['specimens'].notnull()==True # find all the blank specimens rows
# self.samp_container.df = self.samp_container.df.loc[condition]
# remove sample only columns that have been put into sites
if BY_SAMPLES:
#ignore = ['cooling_rate_corr', 'cooling_rate_mcd']
self.site_container.remove_non_magic_cols_from_table(ignore_cols=[]) #ignore)
# write out the data
self.samp_container.write_magic_file(dir_path=self.WD)
self.site_container.write_magic_file(dir_path=self.WD)
#-------------
# MagIC_methods.txt
#-------------
# search for all magic_methods in all files:
magic_method_codes = []
for F in ["magic_measurements.txt", "rmag_anisotropy.txt", "rmag_results.txt", "rmag_results.txt", "pmag_samples.txt", "pmag_specimens.txt", "pmag_sites.txt", "er_ages.txt"]:
try:
fin = open(os.path.join(self.WD, F), 'r')
except:
continue
line = fin.readline()
line = fin.readline()
header = line.strip('\n').split('\t')
if "magic_method_codes" not in header:
continue
else:
index = header.index("magic_method_codes")
for line in fin.readlines():
tmp = line.strip('\n').split('\t')
if len(tmp) >= index:
codes = tmp[index].replace(" ", "").split(":")
for code in codes:
if code != "" and code not in magic_method_codes:
magic_method_codes.append(code)
fin.close()
if self.data_model == 2:
magic_method_codes.sort()
# print magic_method_codes
magic_methods_header_1 = ["magic_method_code"]
fout = open(os.path.join(self.WD, "magic_methods.txt"), 'w')
fout.write("tab\tmagic_methods\n")
fout.write("magic_method_code\n")
for code in magic_method_codes:
fout.write("%s\n" % code)
fout.close
# make pmag_criteria.txt if it does not exist
if not os.path.isfile(os.path.join(self.WD, "pmag_criteria.txt")):
Fout = open(os.path.join(self.WD, "pmag_criteria.txt"), 'w')
Fout.write("tab\tpmag_criteria\n")
Fout.write("er_citation_names\tpmag_criteria_code\n")
Fout.write("This study\tACCEPT\n")
dlg1 = wx.MessageDialog(
self, caption="Message:", message="MagIC files are saved in MagIC project folder", style=wx.OK | wx.ICON_INFORMATION)
self.show_dlg(dlg1)
dlg1.Destroy()
self.close_warning = False | python | def on_menu_prepare_magic_results_tables(self, event):
"""
Menubar --> File --> Save MagIC tables
"""
# write a redo file
try:
self.on_menu_save_interpretation(None)
except Exception as ex:
print('-W-', ex)
pass
if self.data_model != 3: # data model 3 data already read in to contribution
#------------------
# read existing pmag results data and sort out the directional data.
# The directional data will be merged to one combined pmag table.
# these data will be merged later
#-----------------------.
PmagRecsOld = {}
for FILE in ['pmag_specimens.txt', 'pmag_samples.txt', 'pmag_sites.txt', 'pmag_results.txt']:
PmagRecsOld[FILE], meas_data = [], []
try:
meas_data, file_type = pmag.magic_read(
os.path.join(self.WD, FILE))
self.GUI_log.write(
"-I- Read existing magic file %s\n" % (os.path.join(self.WD, FILE)))
# if FILE !='pmag_specimens.txt':
os.rename(os.path.join(self.WD, FILE),
os.path.join(self.WD, FILE + ".backup"))
self.GUI_log.write(
"-I- rename old magic file %s.backup\n" % (os.path.join(self.WD, FILE)))
except:
self.GUI_log.write(
"-I- Can't read existing magic file %s\n" % (os.path.join(self.WD, FILE)))
continue
for rec in meas_data:
if "magic_method_codes" in list(rec.keys()):
if "LP-PI" not in rec['magic_method_codes'] and "IE-" not in rec['magic_method_codes']:
PmagRecsOld[FILE].append(rec)
pmag_specimens_header_1 = [
"er_location_name", "er_site_name", "er_sample_name", "er_specimen_name"]
pmag_specimens_header_2 = [
'measurement_step_min', 'measurement_step_max', 'specimen_int']
pmag_specimens_header_3 = ["specimen_correction", "specimen_int_corr_anisotropy",
"specimen_int_corr_nlt", "specimen_int_corr_cooling_rate"]
pmag_specimens_header_4 = []
for short_stat in self.preferences['show_statistics_on_gui']:
stat = "specimen_" + short_stat
pmag_specimens_header_4.append(stat)
pmag_specimens_header_5 = [
"magic_experiment_names", "magic_method_codes", "measurement_step_unit", "specimen_lab_field_dc"]
pmag_specimens_header_6 = ["er_citation_names"]
specimens_list = []
for specimen in list(self.Data.keys()):
if 'pars' in list(self.Data[specimen].keys()):
if 'saved' in self.Data[specimen]['pars'] and self.Data[specimen]['pars']['saved']:
specimens_list.append(specimen)
elif 'deleted' in self.Data[specimen]['pars'] and self.Data[specimen]['pars']['deleted']:
specimens_list.append(specimen)
# Empty pmag tables:
MagIC_results_data = {}
MagIC_results_data['pmag_specimens'] = {}
MagIC_results_data['pmag_samples_or_sites'] = {}
MagIC_results_data['pmag_results'] = {}
# write down pmag_specimens.txt
specimens_list.sort()
for specimen in specimens_list:
if 'pars' in self.Data[specimen] and 'deleted' in self.Data[specimen]['pars'] and self.Data[specimen]['pars']['deleted']:
print('-I- Deleting interpretation for {}'.format(specimen))
this_spec_data = self.spec_data.loc[specimen]
# there are multiple rows for this specimen
if isinstance(this_spec_data, pd.DataFrame):
# delete the intensity rows for specimen
cond1 = self.spec_container.df.specimen == specimen
cond2 = self.spec_container.df.int_abs.notnull()
cond = cond1 & cond2
self.spec_container.df = self.spec_container.df[-cond]
# there is only one record for this specimen
else:
# delete all intensity data for that specimen
columns = list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity'))
columns.extend(list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity pTRM Check Statistics')))
columns.extend(list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity pTRM Tail Check Statistics')))
columns.extend(list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity pTRM Additivity Check Statistics')))
columns.extend(list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity Arai Statistics')))
columns.extend(list(self.contribution.data_model.get_group_headers('specimens', 'Paleointensity Directional Statistics')))
int_columns = set(columns).intersection(self.spec_data.columns)
int_columns.update(['method_codes', 'result_quality', 'meas_step_max', 'meas_step_min', 'software_packages', 'meas_step_unit', 'experiments'])
new_data = {col: "" for col in int_columns}
cond1 = self.spec_container.df.specimen == specimen
for col in int_columns:
self.spec_container.df.loc[specimen, col] = ""
elif 'pars' in self.Data[specimen] and 'saved' in self.Data[specimen]['pars'] and self.Data[specimen]['pars']['saved']:
sample_name = self.Data_hierarchy['specimens'][specimen]
site_name = thellier_gui_lib.get_site_from_hierarchy(
sample_name, self.Data_hierarchy)
location_name = thellier_gui_lib.get_location_from_hierarchy(
site_name, self.Data_hierarchy)
MagIC_results_data['pmag_specimens'][specimen] = {}
if version != "unknown":
MagIC_results_data['pmag_specimens'][specimen]['magic_software_packages'] = version
MagIC_results_data['pmag_specimens'][specimen]['er_citation_names'] = "This study"
# MagIC_results_data['pmag_specimens'][specimen]['er_analyst_mail_names']="unknown"
MagIC_results_data['pmag_specimens'][specimen]['er_specimen_name'] = specimen
MagIC_results_data['pmag_specimens'][specimen]['er_sample_name'] = sample_name
MagIC_results_data['pmag_specimens'][specimen]['er_site_name'] = site_name
MagIC_results_data['pmag_specimens'][specimen]['er_location_name'] = location_name
MagIC_results_data['pmag_specimens'][specimen]['magic_method_codes'] = self.Data[
specimen]['pars']['magic_method_codes'] + ":IE-TT"
tmp = MagIC_results_data['pmag_specimens'][specimen]['magic_method_codes'].split(
":")
# magic_experiment_names=specimen
magic_experiment_names = ""
# for m in tmp: # this is incorrect - it should be a concatenated list of the experiment names from the measurement table.
# if "LP-" in m:
# magic_experiment_names=magic_experiment_names+":" + m
MagIC_results_data['pmag_specimens'][specimen]['magic_experiment_names'] = magic_experiment_names
MagIC_results_data['pmag_specimens'][specimen]['measurement_step_unit'] = 'K'
MagIC_results_data['pmag_specimens'][specimen]['specimen_lab_field_dc'] = "%.2e" % (
self.Data[specimen]['pars']['lab_dc_field'])
MagIC_results_data['pmag_specimens'][specimen]['specimen_correction'] = self.Data[specimen]['pars']['specimen_correction']
for key in pmag_specimens_header_4:
if key in ['specimen_int_ptrm_n', 'specimen_int_n']:
MagIC_results_data['pmag_specimens'][specimen][key] = "%i" % (
self.Data[specimen]['pars'][key])
elif key in ['specimen_scat'] and self.Data[specimen]['pars'][key] in ["Fail", 'f']:
MagIC_results_data['pmag_specimens'][specimen][key] = "f"
elif key in ['specimen_scat'] and self.Data[specimen]['pars'][key] in ["Pass", 't']:
MagIC_results_data['pmag_specimens'][specimen][key] = "t"
else:
MagIC_results_data['pmag_specimens'][specimen][key] = "%.2f" % (
self.Data[specimen]['pars'][key])
MagIC_results_data['pmag_specimens'][specimen]['specimen_int'] = "%.2e" % (
self.Data[specimen]['pars']['specimen_int'])
MagIC_results_data['pmag_specimens'][specimen]['measurement_step_min'] = "%i" % (
self.Data[specimen]['pars']['measurement_step_min'])
MagIC_results_data['pmag_specimens'][specimen]['measurement_step_max'] = "%i" % (
self.Data[specimen]['pars']['measurement_step_max'])
if "specimen_int_corr_anisotropy" in list(self.Data[specimen]['pars'].keys()):
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_anisotropy'] = "%.2f" % (
self.Data[specimen]['pars']['specimen_int_corr_anisotropy'])
else:
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_anisotropy'] = ""
if "specimen_int_corr_nlt" in list(self.Data[specimen]['pars'].keys()):
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_nlt'] = "%.2f" % (
self.Data[specimen]['pars']['specimen_int_corr_nlt'])
else:
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_nlt'] = ""
if "specimen_int_corr_cooling_rate" in list(self.Data[specimen]['pars'].keys()) and self.Data[specimen]['pars']['specimen_int_corr_cooling_rate'] != -999:
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_cooling_rate'] = "%.2f" % (
self.Data[specimen]['pars']['specimen_int_corr_cooling_rate'])
else:
MagIC_results_data['pmag_specimens'][specimen]['specimen_int_corr_cooling_rate'] = ""
MagIC_results_data['pmag_specimens'][specimen]['criteria'] = "IE-SPEC"
if self.data_model == 3: # convert pmag_specimen format to data model 3 and replace existing specimen record or add new & delete blank records
new_spec_data = MagIC_results_data['pmag_specimens'][specimen]
# turn new_specimen data to 3.0
new_data = map_magic.convert_spec('magic3', new_spec_data)
# check if interpretation passes criteria and set flag
spec_pars = thellier_gui_lib.check_specimen_PI_criteria(
self.Data[specimen]['pars'], self.acceptance_criteria)
if len(spec_pars['specimen_fail_criteria']) > 0:
new_data['result_quality'] = 'b'
else:
new_data['result_quality'] = 'g'
# reformat all the keys
cond1 = self.spec_container.df['specimen'].str.contains(
specimen + "$") == True
if 'int_abs' not in self.spec_container.df.columns:
self.spec_container.df['int_abs'] = None
print("-W- No intensity data found for specimens")
cond2 = self.spec_container.df['int_abs'].apply(lambda x: cb.not_null(x, False)) #notnull() == True
condition = (cond1 & cond2)
# update intensity records
self.spec_data = self.spec_container.update_record(
specimen, new_data, condition)
## delete essentially blank records
#condition = self.spec_data['method_codes'].isnull().astype(
#bool) # find the blank records
#info_str = "specimen rows with blank method codes"
#self.spec_data = self.spec_container.delete_rows(
# condition, info_str) # delete them
if self.data_model != 3: # write out pmag_specimens.txt file
fout = open(os.path.join(self.WD, "pmag_specimens.txt"), 'w')
fout.write("tab\tpmag_specimens\n")
headers = pmag_specimens_header_1 + pmag_specimens_header_2 + pmag_specimens_header_3 + \
pmag_specimens_header_4 + pmag_specimens_header_5 + pmag_specimens_header_6
String = ""
for key in headers:
String = String + key + "\t"
fout.write(String[:-1] + "\n")
for specimen in specimens_list:
String = ""
for key in headers:
String = String + \
MagIC_results_data['pmag_specimens'][specimen][key] + "\t"
fout.write(String[:-1] + "\n")
fout.close()
# merge with non-intensity data
# read the new pmag_specimens.txt
meas_data, file_type = pmag.magic_read(
os.path.join(self.WD, "pmag_specimens.txt"))
# add the old non-PI lines from pmag_specimens.txt
for rec in PmagRecsOld["pmag_specimens.txt"]:
meas_data.append(rec)
# fix headers, so all headers in all lines
meas_data = self.converge_pmag_rec_headers(meas_data)
# write the combined pmag_specimens.txt
pmag.magic_write(os.path.join(
self.WD, "pmag_specimens.txt"), meas_data, 'pmag_specimens')
try:
os.remove(os.path.join(self.WD, "pmag_specimens.txt.backup"))
except:
pass
#-------------
# message dialog
#-------------
TEXT = "specimens interpretations are saved in pmag_specimens.txt.\nPress OK for pmag_samples/pmag_sites/pmag_results tables."
else: # data model 3, so merge with spec_data and save as specimens.txt file
# remove unwanted columns (site, location).
for col in ['site', 'location']:
if col in self.spec_data.columns:
del self.spec_data[col]
self.spec_container.drop_duplicate_rows()
# write out the data
self.spec_container.write_magic_file(dir_path=self.WD)
TEXT = "specimens interpretations are saved in specimens.txt.\nPress OK for samples/sites tables."
dlg = wx.MessageDialog(self, caption="Saved",
message=TEXT, style=wx.OK | wx.CANCEL)
result = self.show_dlg(dlg)
if result == wx.ID_OK:
dlg.Destroy()
if result == wx.ID_CANCEL:
dlg.Destroy()
return()
#-------------
# pmag_samples.txt or pmag_sites.txt
#-------------
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
BY_SITES = False
BY_SAMPLES = True
else:
BY_SITES = True
BY_SAMPLES = False
pmag_samples_header_1 = ["er_location_name", "er_site_name"]
if BY_SAMPLES:
pmag_samples_header_1.append("er_sample_name")
if BY_SAMPLES:
pmag_samples_header_2 = ["er_specimen_names", "sample_int", "sample_int_n",
"sample_int_sigma", "sample_int_sigma_perc", "sample_description"]
else:
pmag_samples_header_2 = ["er_specimen_names", "site_int", "site_int_n",
"site_int_sigma", "site_int_sigma_perc", "site_description"]
pmag_samples_header_3 = [
"magic_method_codes", "magic_software_packages"]
pmag_samples_header_4 = ["er_citation_names"]
pmag_samples_or_sites_list = []
if BY_SAMPLES:
samples_or_sites = list(self.Data_samples.keys())
Data_samples_or_sites = copy.deepcopy(self.Data_samples)
else:
samples_or_sites = list(self.Data_sites.keys())
Data_samples_or_sites = copy.deepcopy(self.Data_sites)
samples_or_sites.sort()
for sample_or_site in samples_or_sites:
if True:
specimens_names = ""
B = []
specimens_LP_codes = []
for specimen in list(Data_samples_or_sites[sample_or_site].keys()):
B.append(Data_samples_or_sites[sample_or_site][specimen])
if specimen not in MagIC_results_data['pmag_specimens']:
continue
magic_codes = MagIC_results_data['pmag_specimens'][specimen]['magic_method_codes']
codes = magic_codes.replace(" ", "").split(":")
for code in codes:
if "LP-" in code and code not in specimens_LP_codes:
specimens_LP_codes.append(code)
specimens_names = specimens_names + specimen + ":"
magic_codes = ":".join(specimens_LP_codes) + ":IE-TT"
specimens_names = specimens_names[:-1]
if specimens_names != "":
# sample_pass_criteria=False
sample_or_site_pars = self.calculate_sample_mean(
Data_samples_or_sites[sample_or_site])
if sample_or_site_pars['pass_or_fail'] == 'fail':
continue
N = sample_or_site_pars['N']
B_uT = sample_or_site_pars['B_uT']
B_std_uT = sample_or_site_pars['B_std_uT']
B_std_perc = sample_or_site_pars['B_std_perc']
pmag_samples_or_sites_list.append(sample_or_site)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site] = {
}
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['er_specimen_names'] = specimens_names
if BY_SAMPLES:
name = "sample_"
else:
name = "site_"
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][name +
'int'] = "%.2e" % (B_uT * 1e-6)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][name +
'int_n'] = "%i" % (N)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][name +
'int_sigma'] = "%.2e" % (B_std_uT * 1e-6)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][name +
'int_sigma_perc'] = "%.2f" % (B_std_perc)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][name +
'description'] = "paleointensity mean"
if BY_SAMPLES:
sample_name = sample_or_site
site_name = thellier_gui_lib.get_site_from_hierarchy(
sample_name, self.Data_hierarchy)
location_name = thellier_gui_lib.get_location_from_hierarchy(
site_name, self.Data_hierarchy)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['er_sample_name'] = sample_name
if BY_SITES:
site_name = sample_or_site
location_name = thellier_gui_lib.get_location_from_hierarchy(
site_name, self.Data_hierarchy)
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['er_site_name'] = site_name
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['er_location_name'] = location_name
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["pmag_criteria_codes"] = ""
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['magic_method_codes'] = magic_codes
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["magic_software_packages"] = version
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["er_citation_names"] = "This study"
# prepare pmag_samples.txt
pmag_samples_or_sites_list.sort()
if self.data_model != 3: # save 2.5 way
if BY_SAMPLES:
fout = open(os.path.join(self.WD, "pmag_samples.txt"), 'w')
fout.write("tab\tpmag_samples\n")
else:
fout = open(os.path.join(self.WD, "pmag_sites.txt"), 'w')
fout.write("tab\tpmag_sites\n")
headers = pmag_samples_header_1 + pmag_samples_header_2 + \
pmag_samples_header_3 + pmag_samples_header_4
String = ""
for key in headers:
String = String + key + "\t"
fout.write(String[:-1] + "\n")
for sample_or_site in pmag_samples_or_sites_list:
String = ""
for key in headers:
String = String + \
MagIC_results_data['pmag_samples_or_sites'][sample_or_site][key] + "\t"
fout.write(String[:-1] + "\n")
fout.close()
# merge with non-intensity data
if BY_SAMPLES:
meas_data, file_type = pmag.magic_read(
os.path.join(self.WD, "pmag_samples.txt"))
for rec in PmagRecsOld["pmag_samples.txt"]:
meas_data.append(rec)
meas_data = self.converge_pmag_rec_headers(meas_data)
pmag.magic_write(os.path.join(
self.WD, "pmag_samples.txt"), meas_data, 'pmag_samples')
try:
os.remove(os.path.join(self.WD, "pmag_samples.txt.backup"))
except:
pass
pmag.magic_write(os.path.join(
self.WD, "pmag_sites.txt"), PmagRecsOld["pmag_sites.txt"], 'pmag_sites')
try:
os.remove(os.path.join(self.WD, "pmag_sites.txt.backup"))
except:
pass
else:
meas_data, file_type = pmag.magic_read(
os.path.join(self.WD, "pmag_sites.txt"))
for rec in PmagRecsOld["pmag_sites.txt"]:
meas_data.append(rec)
meas_data = self.converge_pmag_rec_headers(meas_data)
pmag.magic_write(os.path.join(
self.WD, "pmag_sites.txt"), meas_data, 'pmag_sites')
try:
os.remove(os.path.join(self.WD, "pmag_sites.txt.backup"))
except:
pass
pmag.magic_write(os.path.join(
self.WD, "pmag_samples.txt"), PmagRecsOld["pmag_samples.txt"], 'pmag_samples')
try:
os.remove(os.path.join(self.WD, "pmag_samples.txt.backup"))
except:
pass
else: # don't do anything yet = need vdm data
pass
#-------------
# pmag_results.txt
#-------------
pmag_results_header_1 = ["er_location_names", "er_site_names"]
if BY_SAMPLES:
pmag_results_header_1.append("er_sample_names")
pmag_results_header_1.append("er_specimen_names")
pmag_results_header_2 = ["average_lat", "average_lon", ]
pmag_results_header_3 = [
"average_int_n", "average_int", "average_int_sigma", "average_int_sigma_perc"]
if self.preferences['VDM_or_VADM'] == "VDM":
pmag_results_header_4 = ["vdm", "vdm_sigma"]
else:
pmag_results_header_4 = ["vadm", "vadm_sigma"]
pmag_results_header_5 = ["data_type", "pmag_result_name", "magic_method_codes",
"result_description", "er_citation_names", "magic_software_packages", "pmag_criteria_codes"]
for sample_or_site in pmag_samples_or_sites_list:
if sample_or_site is None:
continue
if isinstance(sample_or_site, type(np.nan)):
continue
MagIC_results_data['pmag_results'][sample_or_site] = {}
if self.data_model == 3:
if BY_SAMPLES:
if len(self.test_for_criteria()):
MagIC_results_data['pmag_results'][sample_or_site]['pmag_criteria_codes'] = "IE-SPEC:IE-SAMP"
if BY_SITES:
if len(self.test_for_criteria()):
MagIC_results_data['pmag_results'][sample_or_site]['pmag_criteria_codes'] = "IE-SPEC:IE-SITE"
else:
MagIC_results_data['pmag_results'][sample_or_site]['pmag_criteria_codes'] = "ACCEPT"
MagIC_results_data['pmag_results'][sample_or_site]["er_location_names"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site]['er_location_name']
MagIC_results_data['pmag_results'][sample_or_site]["er_site_names"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site]['er_site_name']
MagIC_results_data['pmag_results'][sample_or_site]["er_specimen_names"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site]['er_specimen_names']
if BY_SAMPLES:
MagIC_results_data['pmag_results'][sample_or_site]["er_sample_names"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site]['er_sample_name']
site = MagIC_results_data['pmag_results'][sample_or_site]["er_site_names"]
lat, lon = "", ""
if site in list(self.Data_info["er_sites"].keys()) and "site_lat" in list(self.Data_info["er_sites"][site].keys()):
# MagIC_results_data['pmag_results'][sample_or_site]["average_lat"]=self.Data_info["er_sites"][site]["site_lat"]
lat = self.Data_info["er_sites"][site]["site_lat"]
if site in list(self.Data_info["er_sites"].keys()) and "site_lon" in list(self.Data_info["er_sites"][site].keys()):
# MagIC_results_data['pmag_results'][sample_or_site]["average_lon"]=self.Data_info["er_sites"][site]["site_lon"]
lon = self.Data_info["er_sites"][site]["site_lon"]
MagIC_results_data['pmag_results'][sample_or_site]["average_lat"] = lat
MagIC_results_data['pmag_results'][sample_or_site]["average_lon"] = lon
if BY_SAMPLES:
name = 'sample'
else:
name = 'site'
MagIC_results_data['pmag_results'][sample_or_site]["average_int_n"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site][name + '_int_n']
MagIC_results_data['pmag_results'][sample_or_site]["average_int"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site][name + '_int']
MagIC_results_data['pmag_results'][sample_or_site]["average_int_sigma"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site][name + '_int_sigma']
MagIC_results_data['pmag_results'][sample_or_site]["average_int_sigma_perc"] = MagIC_results_data[
'pmag_samples_or_sites'][sample_or_site][name + '_int_sigma_perc']
if self.preferences['VDM_or_VADM'] == "VDM":
pass
# to be done
else:
if lat != "":
lat = float(lat)
# B=float(MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['sample_int'])
B = float(
MagIC_results_data['pmag_results'][sample_or_site]["average_int"])
# B_sigma=float(MagIC_results_data['pmag_samples_or_sites'][sample_or_site]['sample_int_sigma'])
B_sigma = float(
MagIC_results_data['pmag_results'][sample_or_site]["average_int_sigma"])
VADM = pmag.b_vdm(B, lat)
VADM_plus = pmag.b_vdm(B + B_sigma, lat)
VADM_minus = pmag.b_vdm(B - B_sigma, lat)
VADM_sigma = (VADM_plus - VADM_minus) / 2
MagIC_results_data['pmag_results'][sample_or_site]["vadm"] = "%.2e" % VADM
MagIC_results_data['pmag_results'][sample_or_site]["vadm_sigma"] = "%.2e" % VADM_sigma
if self.data_model == 3: # stick vadm into site_or_sample record
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["vadm"] = "%.2e" % VADM
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["vadm_sigma"] = "%.2e" % VADM_sigma
else:
MagIC_results_data['pmag_results'][sample_or_site]["vadm"] = ""
MagIC_results_data['pmag_results'][sample_or_site]["vadm_sigma"] = ""
if self.data_model == 3: # stick vadm into site_or_sample record
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["vadm"] = ""
MagIC_results_data['pmag_samples_or_sites'][sample_or_site]["vadm_sigma"] = ""
if MagIC_results_data['pmag_results'][sample_or_site]["vadm"] != "":
MagIC_results_data['pmag_results'][sample_or_site]["pmag_result_name"] = "Paleointensity;V[A]DM;" + sample_or_site
MagIC_results_data['pmag_results'][sample_or_site]["result_description"] = "Paleointensity; V[A]DM"
else:
MagIC_results_data['pmag_results'][sample_or_site]["pmag_result_name"] = "Paleointensity;" + sample_or_site
MagIC_results_data['pmag_results'][sample_or_site]["result_description"] = "Paleointensity"
MagIC_results_data['pmag_results'][sample_or_site]["magic_software_packages"] = version
MagIC_results_data['pmag_results'][sample_or_site]["magic_method_codes"] = magic_codes
# try to make a more meaningful name
MagIC_results_data['pmag_results'][sample_or_site]["data_type"] = "i"
MagIC_results_data['pmag_results'][sample_or_site]["er_citation_names"] = "This study"
if self.data_model != 3: # look for ages in er_ages - otherwise they are in sites.txt already
# add ages
found_age = False
site = MagIC_results_data['pmag_results'][sample_or_site]["er_site_names"]
if sample_or_site in list(self.Data_info["er_ages"].keys()):
sample_or_site_with_age = sample_or_site
found_age = True
elif site in list(self.Data_info["er_ages"].keys()):
sample_or_site_with_age = site
found_age = True
if found_age:
for header in ["age", "age_unit", "age_sigma", "age_range_low", "age_range_high"]:
if sample_or_site_with_age in list(self.Data_info["er_ages"].keys()) and header in list(self.Data_info["er_ages"][sample_or_site_with_age].keys()):
if self.Data_info["er_ages"][sample_or_site_with_age][header] != "":
value = self.Data_info["er_ages"][sample_or_site_with_age][header]
header_result = "average_" + header
if header_result == "average_age_range_high":
header_result = "average_age_high"
if header_result == "average_age_range_low":
header_result = "average_age_low"
MagIC_results_data['pmag_results'][sample_or_site][header_result] = value
if header_result not in pmag_results_header_4:
pmag_results_header_4.append(header_result)
else:
found_age = False
if BY_SAMPLES and sample_or_site in list(self.Data_info["er_ages"].keys()):
element_with_age = sample_or_site
found_age = True
elif BY_SAMPLES and sample_or_site not in list(self.Data_info["er_ages"].keys()):
site = self.Data_hierarchy['site_of_sample'][sample_or_site]
if site in list(self.Data_info["er_ages"].keys()):
element_with_age = site
found_age = True
elif BY_SITES and sample_or_site in list(self.Data_info["er_ages"].keys()):
element_with_age = sample_or_site
found_age = True
else:
continue
if not found_age:
continue
foundkeys = False
# print "element_with_age",element_with_age
for key in ['age', 'age_sigma', 'age_range_low', 'age_range_high', 'age_unit']:
# print "Ron debug"
# print element_with_age
# print sample_or_site
if "er_ages" in list(self.Data_info.keys()) and element_with_age in list(self.Data_info["er_ages"].keys()):
if key in list(self.Data_info["er_ages"][element_with_age].keys()):
if self.Data_info["er_ages"][element_with_age][key] != "":
# print self.Data_info["er_ages"][element_with_age]
# print self.Data_info["er_ages"][element_with_age][key]
# print
# MagIC_results_data['pmag_results'][sample_or_site]
MagIC_results_data['pmag_results'][sample_or_site][
key] = self.Data_info["er_ages"][element_with_age][key]
foundkeys = True
if foundkeys == True:
if "er_ages" in list(self.Data_info.keys()) and element_with_age in list(self.Data_info["er_ages"].keys()):
if 'magic_method_codes' in list(self.Data_info["er_ages"][element_with_age].keys()):
methods = self.Data_info["er_ages"][element_with_age]['magic_method_codes'].replace(
" ", "").strip('\n').split(":")
for meth in methods:
MagIC_results_data['pmag_results'][sample_or_site]["magic_method_codes"] = MagIC_results_data[
'pmag_results'][sample_or_site]["magic_method_codes"] + ":" + meth
if self.data_model != 3:
# write pmag_results.txt
fout = open(os.path.join(self.WD, "pmag_results.txt"), 'w')
fout.write("tab\tpmag_results\n")
headers = pmag_results_header_1 + pmag_results_header_2 + \
pmag_results_header_3 + pmag_results_header_4 + pmag_results_header_5
String = ""
for key in headers:
String = String + key + "\t"
fout.write(String[:-1] + "\n")
# pmag_samples_list.sort()
for sample_or_site in pmag_samples_or_sites_list:
if sample_or_site is None:
continue
if isinstance(sample_or_site, type(np.nan)):
continue
String = ""
for key in headers:
if key in list(MagIC_results_data['pmag_results'][sample_or_site].keys()):
String = String + \
MagIC_results_data['pmag_results'][sample_or_site][key] + "\t"
else:
String = String + "" + "\t"
fout.write(String[:-1] + "\n")
fout.close()
# merge with non-intensity data
meas_data, file_type = pmag.magic_read(
os.path.join(self.WD, "pmag_results.txt"))
for rec in PmagRecsOld["pmag_results.txt"]:
meas_data.append(rec)
meas_data = self.converge_pmag_rec_headers(meas_data)
pmag.magic_write(os.path.join(
self.WD, "pmag_results.txt"), meas_data, 'pmag_results')
try:
os.remove(os.path.join(self.WD, "pmag_results.txt.backup"))
except:
pass
else: # write out samples/sites in data model 3.0
for sample_or_site in pmag_samples_or_sites_list:
if sample_or_site is None:
continue
if isinstance(sample_or_site, type(np.nan)):
continue
# convert, delete, add and save
new_sample_or_site_data = MagIC_results_data['pmag_samples_or_sites'][sample_or_site]
if BY_SAMPLES:
new_data = map_magic.convert_samp(
'magic3', new_sample_or_site_data) # convert to 3.0
if len(self.test_for_criteria()):
new_data['criteria'] = 'IE-SPEC:IE-SAMP'
new_data['result_quality'] = 'g'
self.samp_data = self.samp_container.df
cond1 = self.samp_data['sample'].str.contains(
sample_or_site + "$") == True
if 'int_abs' not in self.samp_data.columns:
self.samp_data['int_abs'] = None
print('-W- No intensity data found for samples')
cond2 = self.samp_data['int_abs'].notnull() == True
condition = (cond1 & cond2)
# update record
self.samp_data = self.samp_container.update_record(
sample_or_site, new_data, condition)
self.site_data = self.site_container.df
# remove intensity data from site level.
if 'int_abs' not in self.site_data.columns:
self.site_data['int_abs'] = None
print('-W- No intensity data found for sites')
site = self.Data_hierarchy['site_of_sample'][sample_or_site]
try: # if site name is blank will skip
cond1 = self.site_data['site'].str.contains(
site + "$") == True
cond2 = self.site_data['int_abs'].notnull() == True
condition = (cond1 & cond2)
site_keys = ['samples', 'int_abs', 'int_sigma', 'int_n_samples', 'int_sigma_perc', 'specimens',
'int_abs_sigma', 'int_abs_sigma_perc', 'vadm'] # zero these out but keep the rest
blank_data = {}
for key in site_keys:
blank_data[key] = ""
self.site_data = self.site_container.update_record(
site, blank_data, condition, update_only=True)
# add record for sample in the site table
cond1 = self.site_data['site'].str.contains(
sample_or_site + "$") == True
cond2 = self.site_data['int_abs'].notnull() == True
condition = (cond1 & cond2)
# change 'site' column to reflect sample name,
# since we are putting this sample at the site level
new_data['site'] = sample_or_site
new_data['samples'] = sample_or_site
new_data['int_n_samples'] = '1'
# get rid of this key for site table
del new_data['sample']
new_data['vadm'] = MagIC_results_data['pmag_results'][sample_or_site]["vadm"]
new_data['vadm_sigma'] = MagIC_results_data['pmag_results'][sample_or_site]["vadm_sigma"]
new_data['result_quality'] = 'g'
self.site_data = self.site_container.update_record(
sample_or_site, new_data, condition, debug=True)
except:
pass # no site
else: # do this by site and not by sample START HERE
cond1 = self.site_data['site'].str.contains(
sample_or_site + "$") == True
if 'int_abs' not in self.site_data.columns:
self.site_data['int_abs'] = None
cond2 = self.site_data['int_abs'].notnull() == True
condition = (cond1 & cond2)
loc = None
locs = self.site_data[cond1]['location']
if any(locs):
loc = locs.values[0]
new_data['site'] = sample_or_site
new_data['location'] = loc
self.site_data = self.site_container.update_record(
sample_or_site, new_data, condition)
# remove intensity data from sample level. # need to look
# up samples from this site
cond1 = self.samp_data['site'].str.contains(
sample_or_site + "$") == True
if 'int_abs' not in self.samp_data.columns:
self.samp_data['int_abs'] = None
cond2 = self.samp_data['int_abs'].notnull() == True
condition = (cond1 & cond2)
new_data = {} # zero these out but keep the rest
# zero these out but keep the rest
samp_keys = ['int_abs', 'int_sigma',
'int_n_specimens', 'int_sigma_perc']
for key in samp_keys:
new_data[key] = ""
samples = self.samp_data[condition].index.unique()
for samp_name in samples:
self.samp_container.update_record(
samp_name, new_data, cond2)
for col in ['location']:
if col in list(self.samp_data.keys()):
del self.samp_data[col]
# if BY_SAMPLES: # replace 'site' with 'sample'
# self.samp_data['site']=self.samp_data['sample']
# condition= self.samp_container.df['specimens'].notnull()==True # find all the blank specimens rows
# self.samp_container.df = self.samp_container.df.loc[condition]
# remove sample only columns that have been put into sites
if BY_SAMPLES:
#ignore = ['cooling_rate_corr', 'cooling_rate_mcd']
self.site_container.remove_non_magic_cols_from_table(ignore_cols=[]) #ignore)
# write out the data
self.samp_container.write_magic_file(dir_path=self.WD)
self.site_container.write_magic_file(dir_path=self.WD)
#-------------
# MagIC_methods.txt
#-------------
# search for all magic_methods in all files:
magic_method_codes = []
for F in ["magic_measurements.txt", "rmag_anisotropy.txt", "rmag_results.txt", "rmag_results.txt", "pmag_samples.txt", "pmag_specimens.txt", "pmag_sites.txt", "er_ages.txt"]:
try:
fin = open(os.path.join(self.WD, F), 'r')
except:
continue
line = fin.readline()
line = fin.readline()
header = line.strip('\n').split('\t')
if "magic_method_codes" not in header:
continue
else:
index = header.index("magic_method_codes")
for line in fin.readlines():
tmp = line.strip('\n').split('\t')
if len(tmp) >= index:
codes = tmp[index].replace(" ", "").split(":")
for code in codes:
if code != "" and code not in magic_method_codes:
magic_method_codes.append(code)
fin.close()
if self.data_model == 2:
magic_method_codes.sort()
# print magic_method_codes
magic_methods_header_1 = ["magic_method_code"]
fout = open(os.path.join(self.WD, "magic_methods.txt"), 'w')
fout.write("tab\tmagic_methods\n")
fout.write("magic_method_code\n")
for code in magic_method_codes:
fout.write("%s\n" % code)
fout.close
# make pmag_criteria.txt if it does not exist
if not os.path.isfile(os.path.join(self.WD, "pmag_criteria.txt")):
Fout = open(os.path.join(self.WD, "pmag_criteria.txt"), 'w')
Fout.write("tab\tpmag_criteria\n")
Fout.write("er_citation_names\tpmag_criteria_code\n")
Fout.write("This study\tACCEPT\n")
dlg1 = wx.MessageDialog(
self, caption="Message:", message="MagIC files are saved in MagIC project folder", style=wx.OK | wx.ICON_INFORMATION)
self.show_dlg(dlg1)
dlg1.Destroy()
self.close_warning = False | Menubar --> File --> Save MagIC tables | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L3791-L4588 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.read_er_ages_file | def read_er_ages_file(self, path, ignore_lines_n, sort_by_these_names):
'''
read er_ages, sort it by site or sample (the header that is not empty)
and convert ages to calendar year
'''
DATA = {}
fin = open(path, 'r')
# ignore first lines
for i in range(ignore_lines_n):
fin.readline()
# header
line = fin.readline()
header = line.strip('\n').split('\t')
# print header
for line in fin.readlines():
if line[0] == "#":
continue
tmp_data = {}
tmp_line = line.strip('\n').split('\t')
for i in range(len(tmp_line)):
if i >= len(header):
continue
tmp_data[header[i]] = tmp_line[i]
for name in sort_by_these_names:
if name in list(tmp_data.keys()) and tmp_data[name] != "":
er_ages_rec = self.convert_ages_to_calendar_year(tmp_data)
DATA[tmp_data[name]] = er_ages_rec
fin.close()
return(DATA) | python | def read_er_ages_file(self, path, ignore_lines_n, sort_by_these_names):
'''
read er_ages, sort it by site or sample (the header that is not empty)
and convert ages to calendar year
'''
DATA = {}
fin = open(path, 'r')
# ignore first lines
for i in range(ignore_lines_n):
fin.readline()
# header
line = fin.readline()
header = line.strip('\n').split('\t')
# print header
for line in fin.readlines():
if line[0] == "#":
continue
tmp_data = {}
tmp_line = line.strip('\n').split('\t')
for i in range(len(tmp_line)):
if i >= len(header):
continue
tmp_data[header[i]] = tmp_line[i]
for name in sort_by_these_names:
if name in list(tmp_data.keys()) and tmp_data[name] != "":
er_ages_rec = self.convert_ages_to_calendar_year(tmp_data)
DATA[tmp_data[name]] = er_ages_rec
fin.close()
return(DATA) | read er_ages, sort it by site or sample (the header that is not empty)
and convert ages to calendar year | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L4629-L4658 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.calculate_sample_mean | def calculate_sample_mean(self, Data_sample_or_site):
'''
Data_sample_or_site is a dictonary holding the samples_or_sites mean
Data_sample_or_site ={}
Data_sample_or_site[specimen]=B (in units of microT)
'''
pars = {}
tmp_B = []
for spec in list(Data_sample_or_site.keys()):
if 'B' in list(Data_sample_or_site[spec].keys()):
tmp_B.append(Data_sample_or_site[spec]['B'])
if len(tmp_B) < 1:
pars['N'] = 0
pars['pass_or_fail'] = 'fail'
return pars
tmp_B = np.array(tmp_B)
pars['pass_or_fail'] = 'pass'
pars['N'] = len(tmp_B)
pars['B_uT'] = np.mean(tmp_B)
if len(tmp_B) > 1:
pars['B_std_uT'] = np.std(tmp_B, ddof=1)
pars['B_std_perc'] = 100 * (pars['B_std_uT'] / pars['B_uT'])
else:
pars['B_std_uT'] = 0
pars['B_std_perc'] = 0
pars['sample_int_interval_uT'] = (max(tmp_B) - min(tmp_B))
pars['sample_int_interval_perc'] = 100 * \
(pars['sample_int_interval_uT'] / pars['B_uT'])
pars['fail_list'] = []
# check if pass criteria
#----------
# int_n
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
average_by_sample_or_site = 'sample'
else:
average_by_sample_or_site = 'site'
if average_by_sample_or_site == 'sample':
cutoff_value = self.acceptance_criteria['sample_int_n']['value']
else:
cutoff_value = self.acceptance_criteria['site_int_n']['value']
if cutoff_value != -999:
if pars['N'] < cutoff_value:
pars['pass_or_fail'] = 'fail'
pars['fail_list'].append("int_n")
#----------
# int_sigma ; int_sigma_perc
pass_sigma, pass_sigma_perc = False, False
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
sigma_cutoff_value = self.acceptance_criteria['sample_int_sigma']['value']
else:
sigma_cutoff_value = self.acceptance_criteria['site_int_sigma']['value']
if sigma_cutoff_value != -999:
if pars['B_std_uT'] * 1e-6 <= sigma_cutoff_value:
pass_sigma = True
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
sigma_perc_cutoff_value = self.acceptance_criteria['sample_int_sigma_perc']['value']
else:
sigma_perc_cutoff_value = self.acceptance_criteria['site_int_sigma_perc']['value']
if sigma_perc_cutoff_value != -999:
if pars['B_std_perc'] <= sigma_perc_cutoff_value:
pass_sigma_perc = True
if not (sigma_cutoff_value == -999 and sigma_perc_cutoff_value == -999):
if not (pass_sigma or pass_sigma_perc):
pars['pass_or_fail'] = 'fail'
pars['fail_list'].append("int_sigma")
pass_int_interval, pass_int_interval_perc = False, False
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
cutoff_value = self.acceptance_criteria['sample_int_interval_uT']['value']
if cutoff_value != -999:
if pars['sample_int_interval_uT'] <= cutoff_value:
pass_int_interval = True
cutoff_value_perc = self.acceptance_criteria['sample_int_interval_perc']['value']
if cutoff_value_perc != -999:
if pars['sample_int_interval_perc'] <= cutoff_value_perc:
pass_int_interval_perc = True
if not (cutoff_value == -999 and cutoff_value_perc == -999):
if not (pass_int_interval or pass_int_interval_perc):
pars['pass_or_fail'] = 'fail'
pars['fail_list'].append("int_interval")
# if cutoff_value != -999 or cutoff_value_perc != -999:
# if not (pass_int_interval or pass_int_interval_perc):
# pars['pass_or_fail']='fail'
# pars['fail_list'].append("int_interval")
#
#
#
#
# if (acceptance_criteria['sample_int_sigma_uT']==0 and acceptance_criteria['sample_int_sigma_perc']==0) or\
# (pars['B_uT'] <= acceptance_criteria['sample_int_sigma_uT'] or pars['B_std_perc'] <= acceptance_criteria['sample_int_sigma_perc']):
# if ( pars['sample_int_interval_uT'] <= acceptance_criteria['sample_int_interval_uT'] or pars['sample_int_interval_perc'] <= acceptance_criteria['sample_int_interval_perc']):
# pars['pass_or_fail']='pass'
return(pars) | python | def calculate_sample_mean(self, Data_sample_or_site):
'''
Data_sample_or_site is a dictonary holding the samples_or_sites mean
Data_sample_or_site ={}
Data_sample_or_site[specimen]=B (in units of microT)
'''
pars = {}
tmp_B = []
for spec in list(Data_sample_or_site.keys()):
if 'B' in list(Data_sample_or_site[spec].keys()):
tmp_B.append(Data_sample_or_site[spec]['B'])
if len(tmp_B) < 1:
pars['N'] = 0
pars['pass_or_fail'] = 'fail'
return pars
tmp_B = np.array(tmp_B)
pars['pass_or_fail'] = 'pass'
pars['N'] = len(tmp_B)
pars['B_uT'] = np.mean(tmp_B)
if len(tmp_B) > 1:
pars['B_std_uT'] = np.std(tmp_B, ddof=1)
pars['B_std_perc'] = 100 * (pars['B_std_uT'] / pars['B_uT'])
else:
pars['B_std_uT'] = 0
pars['B_std_perc'] = 0
pars['sample_int_interval_uT'] = (max(tmp_B) - min(tmp_B))
pars['sample_int_interval_perc'] = 100 * \
(pars['sample_int_interval_uT'] / pars['B_uT'])
pars['fail_list'] = []
# check if pass criteria
#----------
# int_n
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
average_by_sample_or_site = 'sample'
else:
average_by_sample_or_site = 'site'
if average_by_sample_or_site == 'sample':
cutoff_value = self.acceptance_criteria['sample_int_n']['value']
else:
cutoff_value = self.acceptance_criteria['site_int_n']['value']
if cutoff_value != -999:
if pars['N'] < cutoff_value:
pars['pass_or_fail'] = 'fail'
pars['fail_list'].append("int_n")
#----------
# int_sigma ; int_sigma_perc
pass_sigma, pass_sigma_perc = False, False
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
sigma_cutoff_value = self.acceptance_criteria['sample_int_sigma']['value']
else:
sigma_cutoff_value = self.acceptance_criteria['site_int_sigma']['value']
if sigma_cutoff_value != -999:
if pars['B_std_uT'] * 1e-6 <= sigma_cutoff_value:
pass_sigma = True
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
sigma_perc_cutoff_value = self.acceptance_criteria['sample_int_sigma_perc']['value']
else:
sigma_perc_cutoff_value = self.acceptance_criteria['site_int_sigma_perc']['value']
if sigma_perc_cutoff_value != -999:
if pars['B_std_perc'] <= sigma_perc_cutoff_value:
pass_sigma_perc = True
if not (sigma_cutoff_value == -999 and sigma_perc_cutoff_value == -999):
if not (pass_sigma or pass_sigma_perc):
pars['pass_or_fail'] = 'fail'
pars['fail_list'].append("int_sigma")
pass_int_interval, pass_int_interval_perc = False, False
if self.acceptance_criteria['average_by_sample_or_site']['value'] == 'sample':
cutoff_value = self.acceptance_criteria['sample_int_interval_uT']['value']
if cutoff_value != -999:
if pars['sample_int_interval_uT'] <= cutoff_value:
pass_int_interval = True
cutoff_value_perc = self.acceptance_criteria['sample_int_interval_perc']['value']
if cutoff_value_perc != -999:
if pars['sample_int_interval_perc'] <= cutoff_value_perc:
pass_int_interval_perc = True
if not (cutoff_value == -999 and cutoff_value_perc == -999):
if not (pass_int_interval or pass_int_interval_perc):
pars['pass_or_fail'] = 'fail'
pars['fail_list'].append("int_interval")
# if cutoff_value != -999 or cutoff_value_perc != -999:
# if not (pass_int_interval or pass_int_interval_perc):
# pars['pass_or_fail']='fail'
# pars['fail_list'].append("int_interval")
#
#
#
#
# if (acceptance_criteria['sample_int_sigma_uT']==0 and acceptance_criteria['sample_int_sigma_perc']==0) or\
# (pars['B_uT'] <= acceptance_criteria['sample_int_sigma_uT'] or pars['B_std_perc'] <= acceptance_criteria['sample_int_sigma_perc']):
# if ( pars['sample_int_interval_uT'] <= acceptance_criteria['sample_int_interval_uT'] or pars['sample_int_interval_perc'] <= acceptance_criteria['sample_int_interval_perc']):
# pars['pass_or_fail']='pass'
return(pars) | Data_sample_or_site is a dictonary holding the samples_or_sites mean
Data_sample_or_site ={}
Data_sample_or_site[specimen]=B (in units of microT) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L4673-L4775 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.convert_ages_to_calendar_year | def convert_ages_to_calendar_year(self, er_ages_rec):
'''
convert all age units to calendar year
'''
if ("age" not in list(er_ages_rec.keys())) or (cb.is_null(er_ages_rec['age'], False)):
return(er_ages_rec)
if ("age_unit" not in list(er_ages_rec.keys())) or (cb.is_null(er_ages_rec['age_unit'])):
return(er_ages_rec)
if cb.is_null(er_ages_rec["age"], False):
if "age_range_high" in list(er_ages_rec.keys()) and "age_range_low" in list(er_ages_rec.keys()):
if cb.not_null(er_ages_rec["age_range_high"], False) and cb.not_null(er_ages_rec["age_range_low"], False):
er_ages_rec["age"] = np.mean(
[float(er_ages_rec["age_range_high"]), float(er_ages_rec["age_range_low"])])
if cb.is_null(er_ages_rec["age"], False):
return(er_ages_rec)
# age_descriptier_ages_recon=er_ages_rec["age_description"]
age_unit = er_ages_rec["age_unit"]
# Fix 'age':
mutliplier = 1
if age_unit == "Ga":
mutliplier = -1e9
if age_unit == "Ma":
mutliplier = -1e6
if age_unit == "Ka":
mutliplier = -1e3
if age_unit == "Years AD (+/-)" or age_unit == "Years Cal AD (+/-)":
mutliplier = 1
if age_unit == "Years BP" or age_unit == "Years Cal BP":
mutliplier = 1
age = float(er_ages_rec["age"]) * mutliplier
if age_unit == "Years BP" or age_unit == "Years Cal BP":
age = 1950 - age
er_ages_rec['age_cal_year'] = age
# Fix 'age_range_low':
age_range_low = age
age_range_high = age
age_sigma = 0
if "age_sigma" in list(er_ages_rec.keys()) and cb.not_null(er_ages_rec["age_sigma"], False):
age_sigma = float(er_ages_rec["age_sigma"]) * mutliplier
if age_unit == "Years BP" or age_unit == "Years Cal BP":
age_sigma = 1950 - age_sigma
age_range_low = age - age_sigma
age_range_high = age + age_sigma
if "age_range_high" in list(er_ages_rec.keys()) and "age_range_low" in list(er_ages_rec.keys()):
if cb.not_null(er_ages_rec["age_range_high"], False) and cb.not_null(er_ages_rec["age_range_low"], False):
age_range_high = float(
er_ages_rec["age_range_high"]) * mutliplier
if age_unit == "Years BP" or age_unit == "Years Cal BP":
age_range_high = 1950 - age_range_high
age_range_low = float(
er_ages_rec["age_range_low"]) * mutliplier
if age_unit == "Years BP" or age_unit == "Years Cal BP":
age_range_low = 1950 - age_range_low
er_ages_rec['age_cal_year_range_low'] = age_range_low
er_ages_rec['age_cal_year_range_high'] = age_range_high
return(er_ages_rec) | python | def convert_ages_to_calendar_year(self, er_ages_rec):
'''
convert all age units to calendar year
'''
if ("age" not in list(er_ages_rec.keys())) or (cb.is_null(er_ages_rec['age'], False)):
return(er_ages_rec)
if ("age_unit" not in list(er_ages_rec.keys())) or (cb.is_null(er_ages_rec['age_unit'])):
return(er_ages_rec)
if cb.is_null(er_ages_rec["age"], False):
if "age_range_high" in list(er_ages_rec.keys()) and "age_range_low" in list(er_ages_rec.keys()):
if cb.not_null(er_ages_rec["age_range_high"], False) and cb.not_null(er_ages_rec["age_range_low"], False):
er_ages_rec["age"] = np.mean(
[float(er_ages_rec["age_range_high"]), float(er_ages_rec["age_range_low"])])
if cb.is_null(er_ages_rec["age"], False):
return(er_ages_rec)
# age_descriptier_ages_recon=er_ages_rec["age_description"]
age_unit = er_ages_rec["age_unit"]
# Fix 'age':
mutliplier = 1
if age_unit == "Ga":
mutliplier = -1e9
if age_unit == "Ma":
mutliplier = -1e6
if age_unit == "Ka":
mutliplier = -1e3
if age_unit == "Years AD (+/-)" or age_unit == "Years Cal AD (+/-)":
mutliplier = 1
if age_unit == "Years BP" or age_unit == "Years Cal BP":
mutliplier = 1
age = float(er_ages_rec["age"]) * mutliplier
if age_unit == "Years BP" or age_unit == "Years Cal BP":
age = 1950 - age
er_ages_rec['age_cal_year'] = age
# Fix 'age_range_low':
age_range_low = age
age_range_high = age
age_sigma = 0
if "age_sigma" in list(er_ages_rec.keys()) and cb.not_null(er_ages_rec["age_sigma"], False):
age_sigma = float(er_ages_rec["age_sigma"]) * mutliplier
if age_unit == "Years BP" or age_unit == "Years Cal BP":
age_sigma = 1950 - age_sigma
age_range_low = age - age_sigma
age_range_high = age + age_sigma
if "age_range_high" in list(er_ages_rec.keys()) and "age_range_low" in list(er_ages_rec.keys()):
if cb.not_null(er_ages_rec["age_range_high"], False) and cb.not_null(er_ages_rec["age_range_low"], False):
age_range_high = float(
er_ages_rec["age_range_high"]) * mutliplier
if age_unit == "Years BP" or age_unit == "Years Cal BP":
age_range_high = 1950 - age_range_high
age_range_low = float(
er_ages_rec["age_range_low"]) * mutliplier
if age_unit == "Years BP" or age_unit == "Years Cal BP":
age_range_low = 1950 - age_range_low
er_ages_rec['age_cal_year_range_low'] = age_range_low
er_ages_rec['age_cal_year_range_high'] = age_range_high
return(er_ages_rec) | convert all age units to calendar year | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L4777-L4839 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.get_new_T_PI_parameters | 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 | 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) | calcualte statisics when temperatures are selected | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L6066-L6102 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.add_thellier_gui_criteria | def add_thellier_gui_criteria(self):
'''criteria used only in thellier gui
these criteria are not written to pmag_criteria.txt
'''
category = "thellier_gui"
for crit in ['sample_int_n_outlier_check', 'site_int_n_outlier_check']:
self.acceptance_criteria[crit] = {}
self.acceptance_criteria[crit]['category'] = category
self.acceptance_criteria[crit]['criterion_name'] = crit
self.acceptance_criteria[crit]['value'] = -999
self.acceptance_criteria[crit]['threshold_type'] = "low"
self.acceptance_criteria[crit]['decimal_points'] = 0
for crit in ['sample_int_interval_uT', 'sample_int_interval_perc',
'site_int_interval_uT', 'site_int_interval_perc',
'sample_int_BS_68_uT', 'sample_int_BS_95_uT', 'sample_int_BS_68_perc', 'sample_int_BS_95_perc', 'specimen_int_max_slope_diff']:
self.acceptance_criteria[crit] = {}
self.acceptance_criteria[crit]['category'] = category
self.acceptance_criteria[crit]['criterion_name'] = crit
self.acceptance_criteria[crit]['value'] = -999
self.acceptance_criteria[crit]['threshold_type'] = "high"
if crit in ['specimen_int_max_slope_diff']:
self.acceptance_criteria[crit]['decimal_points'] = -999
else:
self.acceptance_criteria[crit]['decimal_points'] = 1
self.acceptance_criteria[crit]['comments'] = "thellier_gui_only"
for crit in ['average_by_sample_or_site', 'interpreter_method']:
self.acceptance_criteria[crit] = {}
self.acceptance_criteria[crit]['category'] = category
self.acceptance_criteria[crit]['criterion_name'] = crit
if crit in ['average_by_sample_or_site']:
self.acceptance_criteria[crit]['value'] = 'sample'
if crit in ['interpreter_method']:
self.acceptance_criteria[crit]['value'] = 'stdev_opt'
self.acceptance_criteria[crit]['threshold_type'] = "flag"
self.acceptance_criteria[crit]['decimal_points'] = -999
for crit in ['include_nrm']:
self.acceptance_criteria[crit] = {}
self.acceptance_criteria[crit]['category'] = category
self.acceptance_criteria[crit]['criterion_name'] = crit
self.acceptance_criteria[crit]['value'] = True
self.acceptance_criteria[crit]['threshold_type'] = "bool"
self.acceptance_criteria[crit]['decimal_points'] = -999
# define internal Thellier-GUI definitions:
self.average_by_sample_or_site = 'sample'
self.stdev_opt = True
self.bs = False
self.bs_par = False | python | def add_thellier_gui_criteria(self):
'''criteria used only in thellier gui
these criteria are not written to pmag_criteria.txt
'''
category = "thellier_gui"
for crit in ['sample_int_n_outlier_check', 'site_int_n_outlier_check']:
self.acceptance_criteria[crit] = {}
self.acceptance_criteria[crit]['category'] = category
self.acceptance_criteria[crit]['criterion_name'] = crit
self.acceptance_criteria[crit]['value'] = -999
self.acceptance_criteria[crit]['threshold_type'] = "low"
self.acceptance_criteria[crit]['decimal_points'] = 0
for crit in ['sample_int_interval_uT', 'sample_int_interval_perc',
'site_int_interval_uT', 'site_int_interval_perc',
'sample_int_BS_68_uT', 'sample_int_BS_95_uT', 'sample_int_BS_68_perc', 'sample_int_BS_95_perc', 'specimen_int_max_slope_diff']:
self.acceptance_criteria[crit] = {}
self.acceptance_criteria[crit]['category'] = category
self.acceptance_criteria[crit]['criterion_name'] = crit
self.acceptance_criteria[crit]['value'] = -999
self.acceptance_criteria[crit]['threshold_type'] = "high"
if crit in ['specimen_int_max_slope_diff']:
self.acceptance_criteria[crit]['decimal_points'] = -999
else:
self.acceptance_criteria[crit]['decimal_points'] = 1
self.acceptance_criteria[crit]['comments'] = "thellier_gui_only"
for crit in ['average_by_sample_or_site', 'interpreter_method']:
self.acceptance_criteria[crit] = {}
self.acceptance_criteria[crit]['category'] = category
self.acceptance_criteria[crit]['criterion_name'] = crit
if crit in ['average_by_sample_or_site']:
self.acceptance_criteria[crit]['value'] = 'sample'
if crit in ['interpreter_method']:
self.acceptance_criteria[crit]['value'] = 'stdev_opt'
self.acceptance_criteria[crit]['threshold_type'] = "flag"
self.acceptance_criteria[crit]['decimal_points'] = -999
for crit in ['include_nrm']:
self.acceptance_criteria[crit] = {}
self.acceptance_criteria[crit]['category'] = category
self.acceptance_criteria[crit]['criterion_name'] = crit
self.acceptance_criteria[crit]['value'] = True
self.acceptance_criteria[crit]['threshold_type'] = "bool"
self.acceptance_criteria[crit]['decimal_points'] = -999
# define internal Thellier-GUI definitions:
self.average_by_sample_or_site = 'sample'
self.stdev_opt = True
self.bs = False
self.bs_par = False | criteria used only in thellier gui
these criteria are not written to pmag_criteria.txt | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L6383-L6433 |
PmagPy/PmagPy | programs/thellier_gui.py | Arai_GUI.sortarai | def sortarai(self, datablock, s, Zdiff):
"""
sorts data block in to first_Z, first_I, etc.
"""
first_Z, first_I, zptrm_check, ptrm_check, ptrm_tail = [], [], [], [], []
field, phi, theta = "", "", ""
starthere = 0
Treat_I, Treat_Z, Treat_PZ, Treat_PI, Treat_M, Treat_AC = [], [], [], [], [], []
ISteps, ZSteps, PISteps, PZSteps, MSteps, ACSteps = [], [], [], [], [], []
GammaChecks = [] # comparison of pTRM direction acquired and lab field
Mkeys = ['measurement_magn_moment', 'measurement_magn_volume',
'measurement_magn_mass', 'measurement_magnitude']
rec = datablock[0]
for key in Mkeys:
if key in list(rec.keys()) and rec[key] != "":
momkey = key
break
# first find all the steps
for k in range(len(datablock)):
rec = datablock[k]
if "treatment_temp" in list(rec.keys()) and rec["treatment_temp"] != "":
temp = float(rec["treatment_temp"])
THERMAL = True
MICROWAVE = False
elif "treatment_mw_power" in list(rec.keys()) and rec["treatment_mw_power"] != "":
THERMAL = False
MICROWAVE = True
if "measurement_description" in list(rec.keys()):
MW_step = rec["measurement_description"].strip(
'\n').split(":")
for STEP in MW_step:
if "Number" in STEP:
temp = float(STEP.split("-")[-1])
methcodes = []
tmp = rec["magic_method_codes"].split(":")
for meth in tmp:
methcodes.append(meth.strip())
# for thellier-thellier
if 'LT-T-I' in methcodes and 'LP-PI-TRM' in methcodes and 'LP-TRM' not in methcodes:
Treat_I.append(temp)
ISteps.append(k)
if field == "":
field = float(rec["treatment_dc_field"])
if phi == "":
phi = float(rec['treatment_dc_field_phi'])
theta = float(rec['treatment_dc_field_theta'])
# for Microwave
if 'LT-M-I' in methcodes and 'LP-PI-M' in methcodes:
Treat_I.append(temp)
ISteps.append(k)
if field == "":
field = float(rec["treatment_dc_field"])
if phi == "":
phi = float(rec['treatment_dc_field_phi'])
theta = float(rec['treatment_dc_field_theta'])
# stick first zero field stuff into first_Z
if 'LT-NO' in methcodes:
Treat_Z.append(temp)
ZSteps.append(k)
if "LT-AF-Z" in methcodes and 'treatment_ac_field' in list(rec.keys()):
if rec['treatment_ac_field'] != "":
AFD_after_NRM = True
# consider AFD before T-T experiment ONLY if it comes before
# the experiment
for i in range(len(first_I)):
# check if there was an infield step before the AFD
if float(first_I[i][3]) != 0:
AFD_after_NRM = False
if AFD_after_NRM:
AF_field = 0
if 'treatment_ac_field' in rec:
try:
AF_field = float(rec['treatment_ac_field']) * 1000
except ValueError:
pass
dec = float(rec["measurement_dec"])
inc = float(rec["measurement_inc"])
intensity = float(rec[momkey])
first_I.append([273. - AF_field, 0., 0., 0., 1])
first_Z.append(
[273. - AF_field, dec, inc, intensity, 1]) # NRM step
if 'LT-T-Z' in methcodes or 'LT-M-Z' in methcodes:
Treat_Z.append(temp)
ZSteps.append(k)
if 'LT-PTRM-Z':
Treat_PZ.append(temp)
PZSteps.append(k)
if 'LT-PTRM-I' in methcodes or 'LT-PMRM-I' in methcodes:
Treat_PI.append(temp)
PISteps.append(k)
if 'LT-PTRM-MD' in methcodes or 'LT-PMRM-MD' in methcodes:
Treat_M.append(temp)
MSteps.append(k)
if 'LT-PTRM-AC' in methcodes or 'LT-PMRM-AC' in methcodes:
Treat_AC.append(temp)
ACSteps.append(k)
if 'LT-NO' in methcodes:
dec = float(rec["measurement_dec"])
inc = float(rec["measurement_inc"])
moment = float(rec["measurement_magn_moment"])
if 'LP-PI-M' not in methcodes:
first_I.append([273, 0., 0., 0., 1])
first_Z.append([273, dec, inc, moment, 1]) # NRM step
else:
first_I.append([0, 0., 0., 0., 1])
first_Z.append([0, dec, inc, moment, 1]) # NRM step
#---------------------
# find IZ and ZI
#---------------------
for temp in Treat_I: # look through infield steps and find matching Z step
if temp in Treat_Z: # found a match
istep = ISteps[Treat_I.index(temp)]
irec = datablock[istep]
methcodes = []
tmp = irec["magic_method_codes"].split(":")
for meth in tmp:
methcodes.append(meth.strip())
# take last record as baseline to subtract
brec = datablock[istep - 1]
zstep = ZSteps[Treat_Z.index(temp)]
zrec = datablock[zstep]
# sort out first_Z records
# check if ZI/IZ in in method codes:
ZI = ""
if "LP-PI-TRM-IZ" in methcodes or "LP-PI-M-IZ" in methcodes or "LP-PI-IZ" in methcodes:
ZI = 0
elif "LP-PI-TRM-ZI" in methcodes or "LP-PI-M-ZI" in methcodes or "LP-PI-ZI" in methcodes:
ZI = 1
elif "LP-PI-BT-IZZI" in methcodes:
ZI == ""
i_intex, z_intex = 0, 0
foundit = False
for i in range(len(datablock)):
if THERMAL:
if ('treatment_temp' in list(datablock[i].keys()) and float(temp) == float(datablock[i]['treatment_temp'])):
foundit = True
if MICROWAVE:
if ('measurement_description' in list(datablock[i].keys())):
MW_step = datablock[i]["measurement_description"].strip(
'\n').split(":")
for STEP in MW_step:
if "Number" in STEP:
ThisStep = float(STEP.split("-")[-1])
if ThisStep == float(temp):
foundit = True
if foundit:
if "LT-T-Z" in datablock[i]['magic_method_codes'].split(":") or "LT-M-Z" in datablock[i]['magic_method_codes'].split(":"):
z_intex = i
if "LT-T-I" in datablock[i]['magic_method_codes'].split(":") or "LT-M-I" in datablock[i]['magic_method_codes'].split(":"):
i_intex = i
foundit = False
if z_intex < i_intex:
ZI = 1
else:
ZI = 0
dec = float(zrec["measurement_dec"])
inc = float(zrec["measurement_inc"])
str = float(zrec[momkey])
first_Z.append([temp, dec, inc, str, ZI])
# sort out first_I records
idec = float(irec["measurement_dec"])
iinc = float(irec["measurement_inc"])
istr = float(irec[momkey])
X = pmag.dir2cart([idec, iinc, istr])
BL = pmag.dir2cart([dec, inc, str])
I = []
for c in range(3):
I.append((X[c] - BL[c]))
if I[2] != 0:
iDir = pmag.cart2dir(I)
if Zdiff == 0:
first_I.append([temp, iDir[0], iDir[1], iDir[2], ZI])
else:
first_I.append([temp, 0., 0., I[2], ZI])
# gamma=angle([iDir[0],iDir[1]],[phi,theta])
else:
first_I.append([temp, 0., 0., 0., ZI])
# gamma=0.0
# put in Gamma check (infield trm versus lab field)
# if 180.-gamma<gamma:
# gamma=180.-gamma
# GammaChecks.append([temp-273.,gamma])
#---------------------
# find Thellier Thellier protocol
#---------------------
if 'LP-PI-II'in methcodes or 'LP-PI-T-II' in methcodes or 'LP-PI-M-II' in methcodes:
# look through infield steps and find matching Z step
for i in range(1, len(Treat_I)):
if Treat_I[i] == Treat_I[i - 1]:
# ignore, if there are more than
temp = Treat_I[i]
irec1 = datablock[ISteps[i - 1]]
dec1 = float(irec1["measurement_dec"])
inc1 = float(irec1["measurement_inc"])
moment1 = float(irec1["measurement_magn_moment"])
if len(first_I) < 2:
dec_initial = dec1
inc_initial = inc1
cart1 = np.array(pmag.dir2cart([dec1, inc1, moment1]))
irec2 = datablock[ISteps[i]]
dec2 = float(irec2["measurement_dec"])
inc2 = float(irec2["measurement_inc"])
moment2 = float(irec2["measurement_magn_moment"])
cart2 = np.array(pmag.dir2cart([dec2, inc2, moment2]))
# check if its in the same treatment
if Treat_I[i] == Treat_I[i - 2] and dec2 != dec_initial and inc2 != inc_initial:
continue
if dec1 != dec2 and inc1 != inc2:
zerofield = (cart2 + cart1) / 2
infield = (cart2 - cart1) / 2
DIR_zerofield = pmag.cart2dir(zerofield)
DIR_infield = pmag.cart2dir(infield)
first_Z.append(
[temp, DIR_zerofield[0], DIR_zerofield[1], DIR_zerofield[2], 0])
first_I.append(
[temp, DIR_infield[0], DIR_infield[1], DIR_infield[2], 0])
#---------------------
# find pTRM checks
#---------------------
for i in range(len(Treat_PI)): # look through infield steps and find matching Z step
temp = Treat_PI[i]
k = PISteps[i]
rec = datablock[k]
dec = float(rec["measurement_dec"])
inc = float(rec["measurement_inc"])
moment = float(rec["measurement_magn_moment"])
phi = float(rec["treatment_dc_field_phi"])
theta = float(rec["treatment_dc_field_theta"])
M = np.array(pmag.dir2cart([dec, inc, moment]))
foundit = False
if 'LP-PI-II' not in methcodes:
# Important: suport several pTRM checks in a row, but
# does not support pTRM checks after infield step
for j in range(k, 1, -1):
if "LT-M-I" in datablock[j]['magic_method_codes'] or "LT-T-I" in datablock[j]['magic_method_codes']:
after_zerofield = 0.
foundit = True
prev_rec = datablock[j]
zerofield_index = j
break
if float(datablock[j]['treatment_dc_field']) == 0:
after_zerofield = 1.
foundit = True
prev_rec = datablock[j]
zerofield_index = j
break
else: # Thellier-Thellier protocol
foundit = True
prev_rec = datablock[k - 1]
zerofield_index = k - 1
if foundit:
prev_dec = float(prev_rec["measurement_dec"])
prev_inc = float(prev_rec["measurement_inc"])
prev_moment = float(prev_rec["measurement_magn_moment"])
prev_phi = float(prev_rec["treatment_dc_field_phi"])
prev_theta = float(prev_rec["treatment_dc_field_theta"])
prev_M = np.array(pmag.dir2cart(
[prev_dec, prev_inc, prev_moment]))
if 'LP-PI-II' not in methcodes:
diff_cart = M - prev_M
diff_dir = pmag.cart2dir(diff_cart)
if after_zerofield == 0:
ptrm_check.append(
[temp, diff_dir[0], diff_dir[1], diff_dir[2], zerofield_index, after_zerofield])
else:
ptrm_check.append(
[temp, diff_dir[0], diff_dir[1], diff_dir[2], zerofield_index, after_zerofield])
else:
# health check for T-T protocol:
if theta != prev_theta:
diff = (M - prev_M) / 2
diff_dir = pmag.cart2dir(diff)
ptrm_check.append(
[temp, diff_dir[0], diff_dir[1], diff_dir[2], zerofield_index, ""])
else:
print(
"-W- WARNING: specimen. pTRM check not in place in Thellier Thellier protocol. step please check")
#---------------------
# find Tail checks
#---------------------
for temp in Treat_M:
# print temp
step = MSteps[Treat_M.index(temp)]
rec = datablock[step]
dec = float(rec["measurement_dec"])
inc = float(rec["measurement_inc"])
moment = float(rec["measurement_magn_moment"])
foundit = False
for i in range(1, len(datablock)):
if 'LT-T-Z' in datablock[i]['magic_method_codes'] or 'LT-M-Z' in datablock[i]['magic_method_codes']:
if (THERMAL and "treatment_temp" in list(datablock[i].keys()) and float(datablock[i]["treatment_temp"]) == float(temp))\
or (MICROWAVE and "measurement_description" in list(datablock[i].keys()) and "Step Number-%.0f" % float(temp) in datablock[i]["measurement_description"]):
prev_rec = datablock[i]
prev_dec = float(prev_rec["measurement_dec"])
prev_inc = float(prev_rec["measurement_inc"])
prev_moment = float(
prev_rec["measurement_magn_moment"])
foundit = True
break
if foundit:
ptrm_tail.append([temp, 0, 0, moment - prev_moment])
#
# final check
#
if len(first_Z) != len(first_I):
print(len(first_Z), len(first_I))
print(" Something wrong with this specimen! Better fix it or delete it ")
input(" press return to acknowledge message")
#---------------------
# find Additivity (patch by rshaar)
#---------------------
additivity_check = []
for i in range(len(Treat_AC)):
step_0 = ACSteps[i]
temp = Treat_AC[i]
dec0 = float(datablock[step_0]["measurement_dec"])
inc0 = float(datablock[step_0]["measurement_inc"])
moment0 = float(datablock[step_0]['measurement_magn_moment'])
V0 = pmag.dir2cart([dec0, inc0, moment0])
# find the infield step that comes before the additivity check
foundit = False
for j in range(step_0, 1, -1):
if "LT-T-I" in datablock[j]['magic_method_codes']:
foundit = True
break
if foundit:
dec1 = float(datablock[j]["measurement_dec"])
inc1 = float(datablock[j]["measurement_inc"])
moment1 = float(datablock[j]['measurement_magn_moment'])
V1 = pmag.dir2cart([dec1, inc1, moment1])
# print "additivity check: ",s
# print j
# print "ACC=V1-V0:"
# print "V1=",[dec1,inc1,moment1],pmag.dir2cart([dec1,inc1,moment1])/float(datablock[0]["measurement_magn_moment"])
# print "V1=",pmag.dir2cart([dec1,inc1,moment1])/float(datablock[0]["measurement_magn_moment"])
# print "V0=",[dec0,inc0,moment0],pmag.dir2cart([dec0,inc0,moment0])/float(datablock[0]["measurement_magn_moment"])
# print "NRM=",float(datablock[0]["measurement_magn_moment"])
# print "-------"
I = []
for c in range(3):
I.append(V1[c] - V0[c])
dir1 = pmag.cart2dir(I)
additivity_check.append([temp, dir1[0], dir1[1], dir1[2]])
# print
# "I",np.array(I)/float(datablock[0]["measurement_magn_moment"]),dir1,"(dir1
# unnormalized)"
X = np.array(I) / \
float(datablock[0]["measurement_magn_moment"])
# print "I",np.sqrt(sum(X**2))
araiblock = (first_Z, first_I, ptrm_check, ptrm_tail,
zptrm_check, GammaChecks, additivity_check)
return araiblock, field | python | def sortarai(self, datablock, s, Zdiff):
"""
sorts data block in to first_Z, first_I, etc.
"""
first_Z, first_I, zptrm_check, ptrm_check, ptrm_tail = [], [], [], [], []
field, phi, theta = "", "", ""
starthere = 0
Treat_I, Treat_Z, Treat_PZ, Treat_PI, Treat_M, Treat_AC = [], [], [], [], [], []
ISteps, ZSteps, PISteps, PZSteps, MSteps, ACSteps = [], [], [], [], [], []
GammaChecks = [] # comparison of pTRM direction acquired and lab field
Mkeys = ['measurement_magn_moment', 'measurement_magn_volume',
'measurement_magn_mass', 'measurement_magnitude']
rec = datablock[0]
for key in Mkeys:
if key in list(rec.keys()) and rec[key] != "":
momkey = key
break
# first find all the steps
for k in range(len(datablock)):
rec = datablock[k]
if "treatment_temp" in list(rec.keys()) and rec["treatment_temp"] != "":
temp = float(rec["treatment_temp"])
THERMAL = True
MICROWAVE = False
elif "treatment_mw_power" in list(rec.keys()) and rec["treatment_mw_power"] != "":
THERMAL = False
MICROWAVE = True
if "measurement_description" in list(rec.keys()):
MW_step = rec["measurement_description"].strip(
'\n').split(":")
for STEP in MW_step:
if "Number" in STEP:
temp = float(STEP.split("-")[-1])
methcodes = []
tmp = rec["magic_method_codes"].split(":")
for meth in tmp:
methcodes.append(meth.strip())
# for thellier-thellier
if 'LT-T-I' in methcodes and 'LP-PI-TRM' in methcodes and 'LP-TRM' not in methcodes:
Treat_I.append(temp)
ISteps.append(k)
if field == "":
field = float(rec["treatment_dc_field"])
if phi == "":
phi = float(rec['treatment_dc_field_phi'])
theta = float(rec['treatment_dc_field_theta'])
# for Microwave
if 'LT-M-I' in methcodes and 'LP-PI-M' in methcodes:
Treat_I.append(temp)
ISteps.append(k)
if field == "":
field = float(rec["treatment_dc_field"])
if phi == "":
phi = float(rec['treatment_dc_field_phi'])
theta = float(rec['treatment_dc_field_theta'])
# stick first zero field stuff into first_Z
if 'LT-NO' in methcodes:
Treat_Z.append(temp)
ZSteps.append(k)
if "LT-AF-Z" in methcodes and 'treatment_ac_field' in list(rec.keys()):
if rec['treatment_ac_field'] != "":
AFD_after_NRM = True
# consider AFD before T-T experiment ONLY if it comes before
# the experiment
for i in range(len(first_I)):
# check if there was an infield step before the AFD
if float(first_I[i][3]) != 0:
AFD_after_NRM = False
if AFD_after_NRM:
AF_field = 0
if 'treatment_ac_field' in rec:
try:
AF_field = float(rec['treatment_ac_field']) * 1000
except ValueError:
pass
dec = float(rec["measurement_dec"])
inc = float(rec["measurement_inc"])
intensity = float(rec[momkey])
first_I.append([273. - AF_field, 0., 0., 0., 1])
first_Z.append(
[273. - AF_field, dec, inc, intensity, 1]) # NRM step
if 'LT-T-Z' in methcodes or 'LT-M-Z' in methcodes:
Treat_Z.append(temp)
ZSteps.append(k)
if 'LT-PTRM-Z':
Treat_PZ.append(temp)
PZSteps.append(k)
if 'LT-PTRM-I' in methcodes or 'LT-PMRM-I' in methcodes:
Treat_PI.append(temp)
PISteps.append(k)
if 'LT-PTRM-MD' in methcodes or 'LT-PMRM-MD' in methcodes:
Treat_M.append(temp)
MSteps.append(k)
if 'LT-PTRM-AC' in methcodes or 'LT-PMRM-AC' in methcodes:
Treat_AC.append(temp)
ACSteps.append(k)
if 'LT-NO' in methcodes:
dec = float(rec["measurement_dec"])
inc = float(rec["measurement_inc"])
moment = float(rec["measurement_magn_moment"])
if 'LP-PI-M' not in methcodes:
first_I.append([273, 0., 0., 0., 1])
first_Z.append([273, dec, inc, moment, 1]) # NRM step
else:
first_I.append([0, 0., 0., 0., 1])
first_Z.append([0, dec, inc, moment, 1]) # NRM step
#---------------------
# find IZ and ZI
#---------------------
for temp in Treat_I: # look through infield steps and find matching Z step
if temp in Treat_Z: # found a match
istep = ISteps[Treat_I.index(temp)]
irec = datablock[istep]
methcodes = []
tmp = irec["magic_method_codes"].split(":")
for meth in tmp:
methcodes.append(meth.strip())
# take last record as baseline to subtract
brec = datablock[istep - 1]
zstep = ZSteps[Treat_Z.index(temp)]
zrec = datablock[zstep]
# sort out first_Z records
# check if ZI/IZ in in method codes:
ZI = ""
if "LP-PI-TRM-IZ" in methcodes or "LP-PI-M-IZ" in methcodes or "LP-PI-IZ" in methcodes:
ZI = 0
elif "LP-PI-TRM-ZI" in methcodes or "LP-PI-M-ZI" in methcodes or "LP-PI-ZI" in methcodes:
ZI = 1
elif "LP-PI-BT-IZZI" in methcodes:
ZI == ""
i_intex, z_intex = 0, 0
foundit = False
for i in range(len(datablock)):
if THERMAL:
if ('treatment_temp' in list(datablock[i].keys()) and float(temp) == float(datablock[i]['treatment_temp'])):
foundit = True
if MICROWAVE:
if ('measurement_description' in list(datablock[i].keys())):
MW_step = datablock[i]["measurement_description"].strip(
'\n').split(":")
for STEP in MW_step:
if "Number" in STEP:
ThisStep = float(STEP.split("-")[-1])
if ThisStep == float(temp):
foundit = True
if foundit:
if "LT-T-Z" in datablock[i]['magic_method_codes'].split(":") or "LT-M-Z" in datablock[i]['magic_method_codes'].split(":"):
z_intex = i
if "LT-T-I" in datablock[i]['magic_method_codes'].split(":") or "LT-M-I" in datablock[i]['magic_method_codes'].split(":"):
i_intex = i
foundit = False
if z_intex < i_intex:
ZI = 1
else:
ZI = 0
dec = float(zrec["measurement_dec"])
inc = float(zrec["measurement_inc"])
str = float(zrec[momkey])
first_Z.append([temp, dec, inc, str, ZI])
# sort out first_I records
idec = float(irec["measurement_dec"])
iinc = float(irec["measurement_inc"])
istr = float(irec[momkey])
X = pmag.dir2cart([idec, iinc, istr])
BL = pmag.dir2cart([dec, inc, str])
I = []
for c in range(3):
I.append((X[c] - BL[c]))
if I[2] != 0:
iDir = pmag.cart2dir(I)
if Zdiff == 0:
first_I.append([temp, iDir[0], iDir[1], iDir[2], ZI])
else:
first_I.append([temp, 0., 0., I[2], ZI])
# gamma=angle([iDir[0],iDir[1]],[phi,theta])
else:
first_I.append([temp, 0., 0., 0., ZI])
# gamma=0.0
# put in Gamma check (infield trm versus lab field)
# if 180.-gamma<gamma:
# gamma=180.-gamma
# GammaChecks.append([temp-273.,gamma])
#---------------------
# find Thellier Thellier protocol
#---------------------
if 'LP-PI-II'in methcodes or 'LP-PI-T-II' in methcodes or 'LP-PI-M-II' in methcodes:
# look through infield steps and find matching Z step
for i in range(1, len(Treat_I)):
if Treat_I[i] == Treat_I[i - 1]:
# ignore, if there are more than
temp = Treat_I[i]
irec1 = datablock[ISteps[i - 1]]
dec1 = float(irec1["measurement_dec"])
inc1 = float(irec1["measurement_inc"])
moment1 = float(irec1["measurement_magn_moment"])
if len(first_I) < 2:
dec_initial = dec1
inc_initial = inc1
cart1 = np.array(pmag.dir2cart([dec1, inc1, moment1]))
irec2 = datablock[ISteps[i]]
dec2 = float(irec2["measurement_dec"])
inc2 = float(irec2["measurement_inc"])
moment2 = float(irec2["measurement_magn_moment"])
cart2 = np.array(pmag.dir2cart([dec2, inc2, moment2]))
# check if its in the same treatment
if Treat_I[i] == Treat_I[i - 2] and dec2 != dec_initial and inc2 != inc_initial:
continue
if dec1 != dec2 and inc1 != inc2:
zerofield = (cart2 + cart1) / 2
infield = (cart2 - cart1) / 2
DIR_zerofield = pmag.cart2dir(zerofield)
DIR_infield = pmag.cart2dir(infield)
first_Z.append(
[temp, DIR_zerofield[0], DIR_zerofield[1], DIR_zerofield[2], 0])
first_I.append(
[temp, DIR_infield[0], DIR_infield[1], DIR_infield[2], 0])
#---------------------
# find pTRM checks
#---------------------
for i in range(len(Treat_PI)): # look through infield steps and find matching Z step
temp = Treat_PI[i]
k = PISteps[i]
rec = datablock[k]
dec = float(rec["measurement_dec"])
inc = float(rec["measurement_inc"])
moment = float(rec["measurement_magn_moment"])
phi = float(rec["treatment_dc_field_phi"])
theta = float(rec["treatment_dc_field_theta"])
M = np.array(pmag.dir2cart([dec, inc, moment]))
foundit = False
if 'LP-PI-II' not in methcodes:
# Important: suport several pTRM checks in a row, but
# does not support pTRM checks after infield step
for j in range(k, 1, -1):
if "LT-M-I" in datablock[j]['magic_method_codes'] or "LT-T-I" in datablock[j]['magic_method_codes']:
after_zerofield = 0.
foundit = True
prev_rec = datablock[j]
zerofield_index = j
break
if float(datablock[j]['treatment_dc_field']) == 0:
after_zerofield = 1.
foundit = True
prev_rec = datablock[j]
zerofield_index = j
break
else: # Thellier-Thellier protocol
foundit = True
prev_rec = datablock[k - 1]
zerofield_index = k - 1
if foundit:
prev_dec = float(prev_rec["measurement_dec"])
prev_inc = float(prev_rec["measurement_inc"])
prev_moment = float(prev_rec["measurement_magn_moment"])
prev_phi = float(prev_rec["treatment_dc_field_phi"])
prev_theta = float(prev_rec["treatment_dc_field_theta"])
prev_M = np.array(pmag.dir2cart(
[prev_dec, prev_inc, prev_moment]))
if 'LP-PI-II' not in methcodes:
diff_cart = M - prev_M
diff_dir = pmag.cart2dir(diff_cart)
if after_zerofield == 0:
ptrm_check.append(
[temp, diff_dir[0], diff_dir[1], diff_dir[2], zerofield_index, after_zerofield])
else:
ptrm_check.append(
[temp, diff_dir[0], diff_dir[1], diff_dir[2], zerofield_index, after_zerofield])
else:
# health check for T-T protocol:
if theta != prev_theta:
diff = (M - prev_M) / 2
diff_dir = pmag.cart2dir(diff)
ptrm_check.append(
[temp, diff_dir[0], diff_dir[1], diff_dir[2], zerofield_index, ""])
else:
print(
"-W- WARNING: specimen. pTRM check not in place in Thellier Thellier protocol. step please check")
#---------------------
# find Tail checks
#---------------------
for temp in Treat_M:
# print temp
step = MSteps[Treat_M.index(temp)]
rec = datablock[step]
dec = float(rec["measurement_dec"])
inc = float(rec["measurement_inc"])
moment = float(rec["measurement_magn_moment"])
foundit = False
for i in range(1, len(datablock)):
if 'LT-T-Z' in datablock[i]['magic_method_codes'] or 'LT-M-Z' in datablock[i]['magic_method_codes']:
if (THERMAL and "treatment_temp" in list(datablock[i].keys()) and float(datablock[i]["treatment_temp"]) == float(temp))\
or (MICROWAVE and "measurement_description" in list(datablock[i].keys()) and "Step Number-%.0f" % float(temp) in datablock[i]["measurement_description"]):
prev_rec = datablock[i]
prev_dec = float(prev_rec["measurement_dec"])
prev_inc = float(prev_rec["measurement_inc"])
prev_moment = float(
prev_rec["measurement_magn_moment"])
foundit = True
break
if foundit:
ptrm_tail.append([temp, 0, 0, moment - prev_moment])
#
# final check
#
if len(first_Z) != len(first_I):
print(len(first_Z), len(first_I))
print(" Something wrong with this specimen! Better fix it or delete it ")
input(" press return to acknowledge message")
#---------------------
# find Additivity (patch by rshaar)
#---------------------
additivity_check = []
for i in range(len(Treat_AC)):
step_0 = ACSteps[i]
temp = Treat_AC[i]
dec0 = float(datablock[step_0]["measurement_dec"])
inc0 = float(datablock[step_0]["measurement_inc"])
moment0 = float(datablock[step_0]['measurement_magn_moment'])
V0 = pmag.dir2cart([dec0, inc0, moment0])
# find the infield step that comes before the additivity check
foundit = False
for j in range(step_0, 1, -1):
if "LT-T-I" in datablock[j]['magic_method_codes']:
foundit = True
break
if foundit:
dec1 = float(datablock[j]["measurement_dec"])
inc1 = float(datablock[j]["measurement_inc"])
moment1 = float(datablock[j]['measurement_magn_moment'])
V1 = pmag.dir2cart([dec1, inc1, moment1])
# print "additivity check: ",s
# print j
# print "ACC=V1-V0:"
# print "V1=",[dec1,inc1,moment1],pmag.dir2cart([dec1,inc1,moment1])/float(datablock[0]["measurement_magn_moment"])
# print "V1=",pmag.dir2cart([dec1,inc1,moment1])/float(datablock[0]["measurement_magn_moment"])
# print "V0=",[dec0,inc0,moment0],pmag.dir2cart([dec0,inc0,moment0])/float(datablock[0]["measurement_magn_moment"])
# print "NRM=",float(datablock[0]["measurement_magn_moment"])
# print "-------"
I = []
for c in range(3):
I.append(V1[c] - V0[c])
dir1 = pmag.cart2dir(I)
additivity_check.append([temp, dir1[0], dir1[1], dir1[2]])
# print
# "I",np.array(I)/float(datablock[0]["measurement_magn_moment"]),dir1,"(dir1
# unnormalized)"
X = np.array(I) / \
float(datablock[0]["measurement_magn_moment"])
# print "I",np.sqrt(sum(X**2))
araiblock = (first_Z, first_I, ptrm_check, ptrm_tail,
zptrm_check, GammaChecks, additivity_check)
return araiblock, field | sorts data block in to first_Z, first_I, etc. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L7913-L8290 |
PmagPy/PmagPy | programs/cart_dir.py | main | def main():
"""
NAME
cart_dir.py
DESCRIPTION
converts cartesian coordinates to geomagnetic elements
INPUT (COMMAND LINE ENTRY)
x1 x2 x3
if only two columns, assumes magnitude of unity
OUTPUT
declination inclination magnitude
SYNTAX
cart_dir.py [command line options] [< filename]
OPTIONS
-h prints help message and quits
-i for interactive data entry
-f FILE to specify input filename
-F OFILE to specify output filename (also prints to screen)
"""
ofile=""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-F' in sys.argv:
ind=sys.argv.index('-F')
ofile=sys.argv[ind+1]
outfile=open(ofile,'w')
if '-i' in sys.argv:
cont=1
while cont==1:
cart=[]
try:
ans=input('X: [ctrl-D to quit] ')
cart.append(float(ans))
ans=input('Y: ')
cart.append(float(ans))
ans=input('Z: ')
cart.append(float(ans))
except:
print("\n Good-bye \n")
sys.exit()
dir= pmag.cart2dir(cart) # send dir to dir2cart and spit out result
print('%7.1f %7.1f %10.3e'%(dir[0],dir[1],dir[2]))
elif '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
inp=numpy.loadtxt(file) # read from a file
else:
inp = numpy.loadtxt(sys.stdin,dtype=numpy.float) # read from standard input
dir=pmag.cart2dir(inp)
if len(dir.shape)==1:
line=dir
print('%7.1f %7.1f %10.3e'%(line[0],line[1],line[2]))
if ofile!="":
outstring='%7.1f %7.1f %10.8e\n' %(line[0],line[1],line[2])
outfile.write(outstring)
else:
for line in dir:
print('%7.1f %7.1f %10.3e'%(line[0],line[1],line[2]))
if ofile!="":
outstring='%7.1f %7.1f %10.8e\n' %(line[0],line[1],line[2])
outfile.write(outstring) | python | def main():
"""
NAME
cart_dir.py
DESCRIPTION
converts cartesian coordinates to geomagnetic elements
INPUT (COMMAND LINE ENTRY)
x1 x2 x3
if only two columns, assumes magnitude of unity
OUTPUT
declination inclination magnitude
SYNTAX
cart_dir.py [command line options] [< filename]
OPTIONS
-h prints help message and quits
-i for interactive data entry
-f FILE to specify input filename
-F OFILE to specify output filename (also prints to screen)
"""
ofile=""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-F' in sys.argv:
ind=sys.argv.index('-F')
ofile=sys.argv[ind+1]
outfile=open(ofile,'w')
if '-i' in sys.argv:
cont=1
while cont==1:
cart=[]
try:
ans=input('X: [ctrl-D to quit] ')
cart.append(float(ans))
ans=input('Y: ')
cart.append(float(ans))
ans=input('Z: ')
cart.append(float(ans))
except:
print("\n Good-bye \n")
sys.exit()
dir= pmag.cart2dir(cart) # send dir to dir2cart and spit out result
print('%7.1f %7.1f %10.3e'%(dir[0],dir[1],dir[2]))
elif '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
inp=numpy.loadtxt(file) # read from a file
else:
inp = numpy.loadtxt(sys.stdin,dtype=numpy.float) # read from standard input
dir=pmag.cart2dir(inp)
if len(dir.shape)==1:
line=dir
print('%7.1f %7.1f %10.3e'%(line[0],line[1],line[2]))
if ofile!="":
outstring='%7.1f %7.1f %10.8e\n' %(line[0],line[1],line[2])
outfile.write(outstring)
else:
for line in dir:
print('%7.1f %7.1f %10.3e'%(line[0],line[1],line[2]))
if ofile!="":
outstring='%7.1f %7.1f %10.8e\n' %(line[0],line[1],line[2])
outfile.write(outstring) | NAME
cart_dir.py
DESCRIPTION
converts cartesian coordinates to geomagnetic elements
INPUT (COMMAND LINE ENTRY)
x1 x2 x3
if only two columns, assumes magnitude of unity
OUTPUT
declination inclination magnitude
SYNTAX
cart_dir.py [command line options] [< filename]
OPTIONS
-h prints help message and quits
-i for interactive data entry
-f FILE to specify input filename
-F OFILE to specify output filename (also prints to screen) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/cart_dir.py#L8-L74 |
PmagPy/PmagPy | programs/deprecated/susar4_asc_magic.py | main | def main():
"""
NAME
susar4-asc_magic.py
DESCRIPTION
converts ascii files generated by SUSAR ver.4.0 to MagIC formated
files for use with PmagPy plotting software
SYNTAX
susar4-asc_magic.py -h [command line options]
OPTIONS
-h: prints the help message and quits
-f FILE: specify .asc input file name
-F MFILE: specify magic_measurements output file
-Fa AFILE: specify rmag_anisotropy output file
-Fr RFILE: specify rmag_results output file
-Fs SFILE: specify er_specimens output file with location, sample, site, etc. information
-usr USER: specify who made the measurements
-loc LOC: specify location name for study
-ins INST: specify instrument used
-spc SPEC: specify number of characters to specify specimen from sample
-ncn NCON: specify naming convention: default is #2 below
-k15 : specify static 15 position mode - default is spinning
-new : replace all existing magic files
DEFAULTS
AFILE: rmag_anisotropy.txt
RFILE: rmag_results.txt
SFILE: default is to create new er_specimen.txt file
USER: ""
LOC: "unknown"
INST: ""
SPEC: 0 sample name is same as site (if SPEC is 1, sample is all but last character)
appends to 'er_specimens.txt, er_samples.txt, er_sites.txt' files
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 [email protected] for help.
"""
citation='This study'
cont=0
samp_con,Z="1",1
AniRecSs,AniRecs,SpecRecs,SampRecs,SiteRecs,MeasRecs=[],[],[],[],[],[]
user,locname,specfile="","unknown","er_specimens.txt"
isspec,inst,specnum='0',"",0
spin,new=1,0
dir_path='.'
if '-WD' in sys.argv:
ind=sys.argv.index('-WD')
dir_path=sys.argv[ind+1]
aoutput,routput,moutput=dir_path+'/rmag_anisotropy.txt',dir_path+'/rmag_results.txt',dir_path+'/magic_measurements.txt'
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-usr' in sys.argv:
ind=sys.argv.index('-usr')
user=sys.argv[ind+1]
if "-ncn" in sys.argv:
ind=sys.argv.index("-ncn")
samp_con=sys.argv[ind+1]
if "4" in samp_con:
if "-" not in samp_con:
print("option [4] must be in form 4-Z where Z is an integer")
sys.exit()
else:
Z=samp_con.split("-")[1]
samp_con="4"
if "7" in samp_con:
if "-" not in samp_con:
print("option [7] must be in form 7-Z where Z is an integer")
sys.exit()
else:
Z=samp_con.split("-")[1]
samp_con="7"
if '-k15' in sys.argv:spin=0
if '-f' in sys.argv:
ind=sys.argv.index('-f')
ascfile=dir_path+'/'+sys.argv[ind+1]
if '-F' in sys.argv:
ind=sys.argv.index('-F')
moutput=dir_path+'/'+sys.argv[ind+1]
if '-Fa' in sys.argv:
ind=sys.argv.index('-Fa')
aoutput=dir_path+'/'+sys.argv[ind+1]
if '-Fr' in sys.argv:
ind=sys.argv.index('-Fr')
routput=dir_path+'/'+sys.argv[ind+1]
if '-Fs' in sys.argv:
ind=sys.argv.index('-Fs')
specfile=dir_path+'/'+sys.argv[ind+1]
isspec='1'
elif '-loc' in sys.argv:
ind=sys.argv.index('-loc')
locname=sys.argv[ind+1]
if '-spc' in sys.argv:
ind=sys.argv.index('-spc')
specnum=-(int(sys.argv[ind+1]))
if specnum!=0:specnum=-specnum
if isspec=="1":
specs,file_type=pmag.magic_read(specfile)
specnames,sampnames,sitenames=[],[],[]
if '-new' not in sys.argv: # see if there are already specimen,sample, site files lying around
try:
SpecRecs,file_type=pmag.magic_read(dir_path+'/er_specimens.txt')
for spec in SpecRecs:
if spec['er_specimen_name'] not in specnames:specnames.append(samp['er_specimen_name'])
except:
SpecRecs,specs=[],[]
try:
SampRecs,file_type=pmag.magic_read(dir_path+'/er_samples.txt')
for samp in SampRecs:
if samp['er_sample_name'] not in sampnames:sampnames.append(samp['er_sample_name'])
except:
sampnames,SampRecs=[],[]
try:
SiteRecs,file_type=pmag.magic_read(dir_path+'/er_sites.txt')
for site in SiteRecs:
if site['er_site_names'] not in sitenames:sitenames.append(site['er_site_name'])
except:
sitenames,SiteRecs=[],[]
try:
input=open(ascfile,'r')
except:
print('Error opening file: ', ascfile)
Data=input.readlines()
k=0
while k<len(Data):
line = Data[k]
words=line.split()
if "ANISOTROPY" in words: # first line of data for the spec
MeasRec,AniRec,SpecRec,SampRec,SiteRec={},{},{},{},{}
specname=words[0]
AniRec['er_specimen_name']=specname
if isspec=="1":
for spec in specs:
if spec['er_specimen_name']==specname:
AniRec['er_sample_name']=spec['er_sample_name']
AniRec['er_site_name']=spec['er_site_name']
AniRec['er_location_name']=spec['er_location_name']
break
elif isspec=="0":
if specnum!=0:
sampname=specname[:specnum]
else:
sampname=specname
AniRec['er_sample_name']=sampname
SpecRec['er_specimen_name']=specname
SpecRec['er_sample_name']=sampname
SampRec['er_sample_name']=sampname
SiteRec['er_sample_name']=sampname
SiteRec['site_description']='s'
AniRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
SpecRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
SampRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
SiteRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
AniRec['er_location_name']=locname
SpecRec['er_location_name']=locname
SampRec['er_location_name']=locname
SiteRec['er_location_name']=locname
AniRec['er_citation_names']="This study"
SpecRec['er_citation_names']="This study"
SampRec['er_citation_names']="This study"
SiteRec['er_citation_names']="This study"
AniRec['er_citation_names']="This study"
AniRec['magic_instrument_codes']=inst
AniRec['magic_method_codes']="LP-X:AE-H:LP-AN-MS"
AniRec['magic_experiment_names']=specname+":"+"LP-AN-MS"
AniRec['er_analyst_mail_names']=user
for key in list(AniRec.keys()):MeasRec[key]=AniRec[key]
MeasRec['measurement_flag']='g'
AniRec['anisotropy_flag']='g'
MeasRec['measurement_standard']='u'
MeasRec['measurement_description']='Bulk sucsecptibility measurement'
AniRec['anisotropy_type']="AMS"
AniRec['anisotropy_unit']="Normalized by trace"
if spin==1:
AniRec['anisotropy_n']="192"
else:
AniRec['anisotropy_n']="15"
if 'Azi' in words and isspec=='0':
SampRec['sample_azimuth']=words[1]
labaz=float(words[1])
if 'Dip' in words:
SampRec['sample_dip']='%7.1f'%(-float(words[1]))
SpecRec['specimen_vol']='%8.3e'%(float(words[10])*1e-6) # convert actual volume to m^3 from cm^3
labdip=float(words[1])
if 'T1' in words and 'F1' in words:
k+=2 # read in fourth line down
line=Data[k]
rec=line.split()
dd=rec[1].split('/')
dip_direction=int(dd[0])+90
SampRec['sample_bed_dip_direction']='%i'%(dip_direction)
SampRec['sample_bed_dip']=dd[1]
bed_dip=float(dd[1])
if "Mean" in words:
k+=4 # read in fourth line down
line=Data[k]
rec=line.split()
MeasRec['measurement_chi_volume']=rec[1]
sigma=.01*float(rec[2])/3.
AniRec['anisotropy_sigma']='%7.4f'%(sigma)
AniRec['anisotropy_unit']='SI'
if "factors" in words:
k+=4 # read in second line down
line=Data[k]
rec=line.split()
if "Specimen" in words: # first part of specimen data
AniRec['anisotropy_s1']='%7.4f'%(old_div(float(words[5]),3.)) # eigenvalues sum to unity - not 3
AniRec['anisotropy_s2']='%7.4f'%(old_div(float(words[6]),3.))
AniRec['anisotropy_s3']='%7.4f'%(old_div(float(words[7]),3.))
k+=1
line=Data[k]
rec=line.split()
AniRec['anisotropy_s4']='%7.4f'%(old_div(float(rec[5]),3.)) # eigenvalues sum to unity - not 3
AniRec['anisotropy_s5']='%7.4f'%(old_div(float(rec[6]),3.))
AniRec['anisotropy_s6']='%7.4f'%(old_div(float(rec[7]),3.))
AniRec['anisotropy_tilt_correction']='-1'
AniRecs.append(AniRec)
AniRecG,AniRecT={},{}
for key in list(AniRec.keys()):AniRecG[key]=AniRec[key]
for key in list(AniRec.keys()):AniRecT[key]=AniRec[key]
sbar=[]
sbar.append(float(AniRec['anisotropy_s1']))
sbar.append(float(AniRec['anisotropy_s2']))
sbar.append(float(AniRec['anisotropy_s3']))
sbar.append(float(AniRec['anisotropy_s4']))
sbar.append(float(AniRec['anisotropy_s5']))
sbar.append(float(AniRec['anisotropy_s6']))
sbarg=pmag.dosgeo(sbar,labaz,labdip)
AniRecG["anisotropy_s1"]='%12.10f'%(sbarg[0])
AniRecG["anisotropy_s2"]='%12.10f'%(sbarg[1])
AniRecG["anisotropy_s3"]='%12.10f'%(sbarg[2])
AniRecG["anisotropy_s4"]='%12.10f'%(sbarg[3])
AniRecG["anisotropy_s5"]='%12.10f'%(sbarg[4])
AniRecG["anisotropy_s6"]='%12.10f'%(sbarg[5])
AniRecG["anisotropy_tilt_correction"]='0'
AniRecs.append(AniRecG)
if bed_dip!="" and bed_dip!=0: # have tilt correction
sbart=pmag.dostilt(sbarg,dip_direction,bed_dip)
AniRecT["anisotropy_s1"]='%12.10f'%(sbart[0])
AniRecT["anisotropy_s2"]='%12.10f'%(sbart[1])
AniRecT["anisotropy_s3"]='%12.10f'%(sbart[2])
AniRecT["anisotropy_s4"]='%12.10f'%(sbart[3])
AniRecT["anisotropy_s5"]='%12.10f'%(sbart[4])
AniRecT["anisotropy_s6"]='%12.10f'%(sbart[5])
AniRecT["anisotropy_tilt_correction"]='100'
AniRecs.append(AniRecT)
MeasRecs.append(MeasRec)
if SpecRec['er_specimen_name'] not in specnames:
SpecRecs.append(SpecRec)
specnames.append(SpecRec['er_specimen_name'])
if SampRec['er_sample_name'] not in sampnames:
SampRecs.append(SampRec)
sampnames.append(SampRec['er_sample_name'])
if SiteRec['er_site_name'] not in sitenames:
SiteRecs.append(SiteRec)
sitenames.append(SiteRec['er_site_name'])
k+=1 # skip to next specimen
pmag.magic_write(aoutput,AniRecs,'rmag_anisotropy')
print("anisotropy tensors put in ",aoutput)
pmag.magic_write(moutput,MeasRecs,'magic_measurements')
print("bulk measurements put in ",moutput)
if isspec=="0":
SpecOut,keys=pmag.fillkeys(SpecRecs)
output=dir_path+"/er_specimens.txt"
pmag.magic_write(output,SpecOut,'er_specimens')
print("specimen info put in ",output)
output=dir_path+"/er_samples.txt"
SampOut,keys=pmag.fillkeys(SampRecs)
pmag.magic_write(output,SampOut,'er_samples')
print("sample info put in ",output)
output=dir_path+"/er_sites.txt"
SiteOut,keys=pmag.fillkeys(SiteRecs)
pmag.magic_write(output,SiteOut,'er_sites')
print("site info put in ",output)
print(""""
You can now import your data into the Magic Console and complete data entry,
for example the site locations, lithologies, etc. plotting can be done with aniso_magic.py
""") | python | def main():
"""
NAME
susar4-asc_magic.py
DESCRIPTION
converts ascii files generated by SUSAR ver.4.0 to MagIC formated
files for use with PmagPy plotting software
SYNTAX
susar4-asc_magic.py -h [command line options]
OPTIONS
-h: prints the help message and quits
-f FILE: specify .asc input file name
-F MFILE: specify magic_measurements output file
-Fa AFILE: specify rmag_anisotropy output file
-Fr RFILE: specify rmag_results output file
-Fs SFILE: specify er_specimens output file with location, sample, site, etc. information
-usr USER: specify who made the measurements
-loc LOC: specify location name for study
-ins INST: specify instrument used
-spc SPEC: specify number of characters to specify specimen from sample
-ncn NCON: specify naming convention: default is #2 below
-k15 : specify static 15 position mode - default is spinning
-new : replace all existing magic files
DEFAULTS
AFILE: rmag_anisotropy.txt
RFILE: rmag_results.txt
SFILE: default is to create new er_specimen.txt file
USER: ""
LOC: "unknown"
INST: ""
SPEC: 0 sample name is same as site (if SPEC is 1, sample is all but last character)
appends to 'er_specimens.txt, er_samples.txt, er_sites.txt' files
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 [email protected] for help.
"""
citation='This study'
cont=0
samp_con,Z="1",1
AniRecSs,AniRecs,SpecRecs,SampRecs,SiteRecs,MeasRecs=[],[],[],[],[],[]
user,locname,specfile="","unknown","er_specimens.txt"
isspec,inst,specnum='0',"",0
spin,new=1,0
dir_path='.'
if '-WD' in sys.argv:
ind=sys.argv.index('-WD')
dir_path=sys.argv[ind+1]
aoutput,routput,moutput=dir_path+'/rmag_anisotropy.txt',dir_path+'/rmag_results.txt',dir_path+'/magic_measurements.txt'
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-usr' in sys.argv:
ind=sys.argv.index('-usr')
user=sys.argv[ind+1]
if "-ncn" in sys.argv:
ind=sys.argv.index("-ncn")
samp_con=sys.argv[ind+1]
if "4" in samp_con:
if "-" not in samp_con:
print("option [4] must be in form 4-Z where Z is an integer")
sys.exit()
else:
Z=samp_con.split("-")[1]
samp_con="4"
if "7" in samp_con:
if "-" not in samp_con:
print("option [7] must be in form 7-Z where Z is an integer")
sys.exit()
else:
Z=samp_con.split("-")[1]
samp_con="7"
if '-k15' in sys.argv:spin=0
if '-f' in sys.argv:
ind=sys.argv.index('-f')
ascfile=dir_path+'/'+sys.argv[ind+1]
if '-F' in sys.argv:
ind=sys.argv.index('-F')
moutput=dir_path+'/'+sys.argv[ind+1]
if '-Fa' in sys.argv:
ind=sys.argv.index('-Fa')
aoutput=dir_path+'/'+sys.argv[ind+1]
if '-Fr' in sys.argv:
ind=sys.argv.index('-Fr')
routput=dir_path+'/'+sys.argv[ind+1]
if '-Fs' in sys.argv:
ind=sys.argv.index('-Fs')
specfile=dir_path+'/'+sys.argv[ind+1]
isspec='1'
elif '-loc' in sys.argv:
ind=sys.argv.index('-loc')
locname=sys.argv[ind+1]
if '-spc' in sys.argv:
ind=sys.argv.index('-spc')
specnum=-(int(sys.argv[ind+1]))
if specnum!=0:specnum=-specnum
if isspec=="1":
specs,file_type=pmag.magic_read(specfile)
specnames,sampnames,sitenames=[],[],[]
if '-new' not in sys.argv: # see if there are already specimen,sample, site files lying around
try:
SpecRecs,file_type=pmag.magic_read(dir_path+'/er_specimens.txt')
for spec in SpecRecs:
if spec['er_specimen_name'] not in specnames:specnames.append(samp['er_specimen_name'])
except:
SpecRecs,specs=[],[]
try:
SampRecs,file_type=pmag.magic_read(dir_path+'/er_samples.txt')
for samp in SampRecs:
if samp['er_sample_name'] not in sampnames:sampnames.append(samp['er_sample_name'])
except:
sampnames,SampRecs=[],[]
try:
SiteRecs,file_type=pmag.magic_read(dir_path+'/er_sites.txt')
for site in SiteRecs:
if site['er_site_names'] not in sitenames:sitenames.append(site['er_site_name'])
except:
sitenames,SiteRecs=[],[]
try:
input=open(ascfile,'r')
except:
print('Error opening file: ', ascfile)
Data=input.readlines()
k=0
while k<len(Data):
line = Data[k]
words=line.split()
if "ANISOTROPY" in words: # first line of data for the spec
MeasRec,AniRec,SpecRec,SampRec,SiteRec={},{},{},{},{}
specname=words[0]
AniRec['er_specimen_name']=specname
if isspec=="1":
for spec in specs:
if spec['er_specimen_name']==specname:
AniRec['er_sample_name']=spec['er_sample_name']
AniRec['er_site_name']=spec['er_site_name']
AniRec['er_location_name']=spec['er_location_name']
break
elif isspec=="0":
if specnum!=0:
sampname=specname[:specnum]
else:
sampname=specname
AniRec['er_sample_name']=sampname
SpecRec['er_specimen_name']=specname
SpecRec['er_sample_name']=sampname
SampRec['er_sample_name']=sampname
SiteRec['er_sample_name']=sampname
SiteRec['site_description']='s'
AniRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
SpecRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
SampRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
SiteRec['er_site_name']=pmag.parse_site(AniRec['er_sample_name'],samp_con,Z)
AniRec['er_location_name']=locname
SpecRec['er_location_name']=locname
SampRec['er_location_name']=locname
SiteRec['er_location_name']=locname
AniRec['er_citation_names']="This study"
SpecRec['er_citation_names']="This study"
SampRec['er_citation_names']="This study"
SiteRec['er_citation_names']="This study"
AniRec['er_citation_names']="This study"
AniRec['magic_instrument_codes']=inst
AniRec['magic_method_codes']="LP-X:AE-H:LP-AN-MS"
AniRec['magic_experiment_names']=specname+":"+"LP-AN-MS"
AniRec['er_analyst_mail_names']=user
for key in list(AniRec.keys()):MeasRec[key]=AniRec[key]
MeasRec['measurement_flag']='g'
AniRec['anisotropy_flag']='g'
MeasRec['measurement_standard']='u'
MeasRec['measurement_description']='Bulk sucsecptibility measurement'
AniRec['anisotropy_type']="AMS"
AniRec['anisotropy_unit']="Normalized by trace"
if spin==1:
AniRec['anisotropy_n']="192"
else:
AniRec['anisotropy_n']="15"
if 'Azi' in words and isspec=='0':
SampRec['sample_azimuth']=words[1]
labaz=float(words[1])
if 'Dip' in words:
SampRec['sample_dip']='%7.1f'%(-float(words[1]))
SpecRec['specimen_vol']='%8.3e'%(float(words[10])*1e-6) # convert actual volume to m^3 from cm^3
labdip=float(words[1])
if 'T1' in words and 'F1' in words:
k+=2 # read in fourth line down
line=Data[k]
rec=line.split()
dd=rec[1].split('/')
dip_direction=int(dd[0])+90
SampRec['sample_bed_dip_direction']='%i'%(dip_direction)
SampRec['sample_bed_dip']=dd[1]
bed_dip=float(dd[1])
if "Mean" in words:
k+=4 # read in fourth line down
line=Data[k]
rec=line.split()
MeasRec['measurement_chi_volume']=rec[1]
sigma=.01*float(rec[2])/3.
AniRec['anisotropy_sigma']='%7.4f'%(sigma)
AniRec['anisotropy_unit']='SI'
if "factors" in words:
k+=4 # read in second line down
line=Data[k]
rec=line.split()
if "Specimen" in words: # first part of specimen data
AniRec['anisotropy_s1']='%7.4f'%(old_div(float(words[5]),3.)) # eigenvalues sum to unity - not 3
AniRec['anisotropy_s2']='%7.4f'%(old_div(float(words[6]),3.))
AniRec['anisotropy_s3']='%7.4f'%(old_div(float(words[7]),3.))
k+=1
line=Data[k]
rec=line.split()
AniRec['anisotropy_s4']='%7.4f'%(old_div(float(rec[5]),3.)) # eigenvalues sum to unity - not 3
AniRec['anisotropy_s5']='%7.4f'%(old_div(float(rec[6]),3.))
AniRec['anisotropy_s6']='%7.4f'%(old_div(float(rec[7]),3.))
AniRec['anisotropy_tilt_correction']='-1'
AniRecs.append(AniRec)
AniRecG,AniRecT={},{}
for key in list(AniRec.keys()):AniRecG[key]=AniRec[key]
for key in list(AniRec.keys()):AniRecT[key]=AniRec[key]
sbar=[]
sbar.append(float(AniRec['anisotropy_s1']))
sbar.append(float(AniRec['anisotropy_s2']))
sbar.append(float(AniRec['anisotropy_s3']))
sbar.append(float(AniRec['anisotropy_s4']))
sbar.append(float(AniRec['anisotropy_s5']))
sbar.append(float(AniRec['anisotropy_s6']))
sbarg=pmag.dosgeo(sbar,labaz,labdip)
AniRecG["anisotropy_s1"]='%12.10f'%(sbarg[0])
AniRecG["anisotropy_s2"]='%12.10f'%(sbarg[1])
AniRecG["anisotropy_s3"]='%12.10f'%(sbarg[2])
AniRecG["anisotropy_s4"]='%12.10f'%(sbarg[3])
AniRecG["anisotropy_s5"]='%12.10f'%(sbarg[4])
AniRecG["anisotropy_s6"]='%12.10f'%(sbarg[5])
AniRecG["anisotropy_tilt_correction"]='0'
AniRecs.append(AniRecG)
if bed_dip!="" and bed_dip!=0: # have tilt correction
sbart=pmag.dostilt(sbarg,dip_direction,bed_dip)
AniRecT["anisotropy_s1"]='%12.10f'%(sbart[0])
AniRecT["anisotropy_s2"]='%12.10f'%(sbart[1])
AniRecT["anisotropy_s3"]='%12.10f'%(sbart[2])
AniRecT["anisotropy_s4"]='%12.10f'%(sbart[3])
AniRecT["anisotropy_s5"]='%12.10f'%(sbart[4])
AniRecT["anisotropy_s6"]='%12.10f'%(sbart[5])
AniRecT["anisotropy_tilt_correction"]='100'
AniRecs.append(AniRecT)
MeasRecs.append(MeasRec)
if SpecRec['er_specimen_name'] not in specnames:
SpecRecs.append(SpecRec)
specnames.append(SpecRec['er_specimen_name'])
if SampRec['er_sample_name'] not in sampnames:
SampRecs.append(SampRec)
sampnames.append(SampRec['er_sample_name'])
if SiteRec['er_site_name'] not in sitenames:
SiteRecs.append(SiteRec)
sitenames.append(SiteRec['er_site_name'])
k+=1 # skip to next specimen
pmag.magic_write(aoutput,AniRecs,'rmag_anisotropy')
print("anisotropy tensors put in ",aoutput)
pmag.magic_write(moutput,MeasRecs,'magic_measurements')
print("bulk measurements put in ",moutput)
if isspec=="0":
SpecOut,keys=pmag.fillkeys(SpecRecs)
output=dir_path+"/er_specimens.txt"
pmag.magic_write(output,SpecOut,'er_specimens')
print("specimen info put in ",output)
output=dir_path+"/er_samples.txt"
SampOut,keys=pmag.fillkeys(SampRecs)
pmag.magic_write(output,SampOut,'er_samples')
print("sample info put in ",output)
output=dir_path+"/er_sites.txt"
SiteOut,keys=pmag.fillkeys(SiteRecs)
pmag.magic_write(output,SiteOut,'er_sites')
print("site info put in ",output)
print(""""
You can now import your data into the Magic Console and complete data entry,
for example the site locations, lithologies, etc. plotting can be done with aniso_magic.py
""") | NAME
susar4-asc_magic.py
DESCRIPTION
converts ascii files generated by SUSAR ver.4.0 to MagIC formated
files for use with PmagPy plotting software
SYNTAX
susar4-asc_magic.py -h [command line options]
OPTIONS
-h: prints the help message and quits
-f FILE: specify .asc input file name
-F MFILE: specify magic_measurements output file
-Fa AFILE: specify rmag_anisotropy output file
-Fr RFILE: specify rmag_results output file
-Fs SFILE: specify er_specimens output file with location, sample, site, etc. information
-usr USER: specify who made the measurements
-loc LOC: specify location name for study
-ins INST: specify instrument used
-spc SPEC: specify number of characters to specify specimen from sample
-ncn NCON: specify naming convention: default is #2 below
-k15 : specify static 15 position mode - default is spinning
-new : replace all existing magic files
DEFAULTS
AFILE: rmag_anisotropy.txt
RFILE: rmag_results.txt
SFILE: default is to create new er_specimen.txt file
USER: ""
LOC: "unknown"
INST: ""
SPEC: 0 sample name is same as site (if SPEC is 1, sample is all but last character)
appends to 'er_specimens.txt, er_samples.txt, er_sites.txt' files
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 [email protected] for help. | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/deprecated/susar4_asc_magic.py#L6-L297 |
PmagPy/PmagPy | programs/histplot.py | main | 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 | 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) | 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] | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/histplot.py#L14-L69 |
PmagPy/PmagPy | pmagpy/command_line_extractor.py | extract_args | def extract_args(argv):
"""
take sys.argv that is used to call a command-line script and return a correctly split list of arguments
for example, this input: ["eqarea.py", "-f", "infile", "-F", "outfile", "-A"]
will return this output: [['f', 'infile'], ['F', 'outfile'], ['A']]
"""
string = " ".join(argv)
string = string.split(' -')
program = string[0]
arguments = [s.split() for s in string[1:]]
return arguments | python | def extract_args(argv):
"""
take sys.argv that is used to call a command-line script and return a correctly split list of arguments
for example, this input: ["eqarea.py", "-f", "infile", "-F", "outfile", "-A"]
will return this output: [['f', 'infile'], ['F', 'outfile'], ['A']]
"""
string = " ".join(argv)
string = string.split(' -')
program = string[0]
arguments = [s.split() for s in string[1:]]
return arguments | take sys.argv that is used to call a command-line script and return a correctly split list of arguments
for example, this input: ["eqarea.py", "-f", "infile", "-F", "outfile", "-A"]
will return this output: [['f', 'infile'], ['F', 'outfile'], ['A']] | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/command_line_extractor.py#L38-L48 |
PmagPy/PmagPy | pmagpy/command_line_extractor.py | check_args | def check_args(arguments, data_frame):
"""
check arguments against a command_line_dataframe.
checks that:
all arguments are valid
all required arguments are present
default values are used where needed
"""
stripped_args = [a[0] for a in arguments]
df = data_frame.df
# first make sure all args are valid
for a in arguments:
if a[0] not in df.index:
print("-I- ignoring invalid argument: {}".format(a[0]))
print("-")
# next make sure required arguments are present
condition = df['reqd']
reqd_args = df[condition]
for arg in reqd_args['arg_name']:
if arg not in stripped_args:
raise pmag.MissingCommandLineArgException("-"+arg)
#next, assign any default values as needed
#condition = df['default'] != '' # don't need this, and sometimes the correct default argument IS ''
default_args = df #[condition]
using_defaults = []
for arg_name, row in default_args.iterrows():
default = row['default']
if arg_name not in stripped_args:
using_defaults.append(arg_name)
arguments.append([arg_name, default])
using_defaults = ["-" + arg for arg in using_defaults]
print('Using default arguments for: {}'.format(', '.join(using_defaults)))
return arguments | python | def check_args(arguments, data_frame):
"""
check arguments against a command_line_dataframe.
checks that:
all arguments are valid
all required arguments are present
default values are used where needed
"""
stripped_args = [a[0] for a in arguments]
df = data_frame.df
# first make sure all args are valid
for a in arguments:
if a[0] not in df.index:
print("-I- ignoring invalid argument: {}".format(a[0]))
print("-")
# next make sure required arguments are present
condition = df['reqd']
reqd_args = df[condition]
for arg in reqd_args['arg_name']:
if arg not in stripped_args:
raise pmag.MissingCommandLineArgException("-"+arg)
#next, assign any default values as needed
#condition = df['default'] != '' # don't need this, and sometimes the correct default argument IS ''
default_args = df #[condition]
using_defaults = []
for arg_name, row in default_args.iterrows():
default = row['default']
if arg_name not in stripped_args:
using_defaults.append(arg_name)
arguments.append([arg_name, default])
using_defaults = ["-" + arg for arg in using_defaults]
print('Using default arguments for: {}'.format(', '.join(using_defaults)))
return arguments | check arguments against a command_line_dataframe.
checks that:
all arguments are valid
all required arguments are present
default values are used where needed | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/command_line_extractor.py#L50-L83 |
PmagPy/PmagPy | dialogs/drop_down_menus3.py | Menus.InitUI | 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 | 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) | Initialize interface for drop down menu | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/drop_down_menus3.py#L51-L87 |
PmagPy/PmagPy | dialogs/drop_down_menus3.py | Menus.add_drop_down | 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 | 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 | 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 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/drop_down_menus3.py#L96-L172 |
PmagPy/PmagPy | dialogs/drop_down_menus3.py | Menus.add_method_drop_down | def add_method_drop_down(self, col_number, col_label):
"""
Add drop-down-menu options for magic_method_codes columns
"""
if self.data_type == 'ages':
method_list = self.contribution.vocab.age_methods
else:
method_list = self.contribution.vocab.age_methods.copy()
method_list.update(self.contribution.vocab.methods)
self.choices[col_number] = (method_list, True) | python | def add_method_drop_down(self, col_number, col_label):
"""
Add drop-down-menu options for magic_method_codes columns
"""
if self.data_type == 'ages':
method_list = self.contribution.vocab.age_methods
else:
method_list = self.contribution.vocab.age_methods.copy()
method_list.update(self.contribution.vocab.methods)
self.choices[col_number] = (method_list, True) | Add drop-down-menu options for magic_method_codes columns | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/drop_down_menus3.py#L174-L183 |
PmagPy/PmagPy | dialogs/drop_down_menus3.py | Menus.on_left_click | def on_left_click(self, event, grid, choices):
"""
creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values
"""
row, col = event.GetRow(), event.GetCol()
if col == 0 and self.grid.name != 'ages':
default_val = self.grid.GetCellValue(row, col)
msg = "Choose a new name for {}.\nThe new value will propagate throughout the contribution.".format(default_val)
dia = wx.TextEntryDialog(self.grid, msg,
"Rename {}".format(self.grid.name, default_val),
default_val)
res = dia.ShowModal()
if res == wx.ID_OK:
new_val = dia.GetValue()
# update the contribution with new name
self.contribution.rename_item(self.grid.name,
default_val, new_val)
# don't propagate changes if we are just assigning a new name
# and not really renaming
# (i.e., if a blank row was added then named)
if default_val == '':
self.grid.SetCellValue(row, 0, new_val)
return
# update the current grid with new name
for row in range(self.grid.GetNumberRows()):
cell_value = self.grid.GetCellValue(row, 0)
if cell_value == default_val:
self.grid.SetCellValue(row, 0, new_val)
else:
continue
return
color = self.grid.GetCellBackgroundColour(event.GetRow(), event.GetCol())
# allow user to cherry-pick cells for editing.
# gets selection of meta key for mac, ctrl key for pc
if event.ControlDown() or event.MetaDown():
row, col = event.GetRow(), event.GetCol()
if (row, col) not in self.dispersed_selection:
self.dispersed_selection.append((row, col))
self.grid.SetCellBackgroundColour(row, col, 'light blue')
else:
self.dispersed_selection.remove((row, col))
self.grid.SetCellBackgroundColour(row, col, color)# 'white'
self.grid.ForceRefresh()
return
if event.ShiftDown(): # allow user to highlight multiple consecutive cells in a column
previous_col = self.grid.GetGridCursorCol()
previous_row = self.grid.GetGridCursorRow()
col = event.GetCol()
row = event.GetRow()
if col != previous_col:
return
else:
if row > previous_row:
row_range = list(range(previous_row, row+1))
else:
row_range = list(range(row, previous_row+1))
for r in row_range:
self.grid.SetCellBackgroundColour(r, col, 'light blue')
self.selection.append((r, col))
self.grid.ForceRefresh()
return
selection = False
if self.dispersed_selection:
is_dispersed = True
selection = self.dispersed_selection
if self.selection:
is_dispersed = False
selection = self.selection
try:
col = event.GetCol()
row = event.GetRow()
except AttributeError:
row, col = selection[0][0], selection[0][1]
self.grid.SetGridCursor(row, col)
if col in list(choices.keys()): # column should have a pop-up menu
menu = wx.Menu()
two_tiered = choices[col][1]
choices = choices[col][0]
if not two_tiered: # menu is one tiered
if 'CLEAR cell of all values' not in choices:
choices.insert(0, 'CLEAR cell of all values')
for choice in choices:
if not choice:
choice = " " # prevents error if choice is an empty string
menuitem = menu.Append(wx.ID_ANY, str(choice))
self.window.Bind(wx.EVT_MENU, lambda event: self.on_select_menuitem(event, grid, row, col, selection), menuitem)
self.show_menu(event, menu)
else: # menu is two_tiered
clear = menu.Append(-1, 'CLEAR cell of all values')
self.window.Bind(wx.EVT_MENU, lambda event: self.on_select_menuitem(event, grid, row, col, selection), clear)
for choice in sorted(choices.items()):
submenu = wx.Menu()
for item in choice[1]:
menuitem = submenu.Append(-1, str(item))
self.window.Bind(wx.EVT_MENU, lambda event: self.on_select_menuitem(event, grid, row, col, selection), menuitem)
menu.Append(-1, choice[0], submenu)
self.show_menu(event, menu)
if selection:
# re-whiten the cells that were previously highlighted
for row, col in selection:
self.grid.SetCellBackgroundColour(row, col, self.col_color)
self.dispersed_selection = []
self.selection = []
self.grid.ForceRefresh() | python | def on_left_click(self, event, grid, choices):
"""
creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values
"""
row, col = event.GetRow(), event.GetCol()
if col == 0 and self.grid.name != 'ages':
default_val = self.grid.GetCellValue(row, col)
msg = "Choose a new name for {}.\nThe new value will propagate throughout the contribution.".format(default_val)
dia = wx.TextEntryDialog(self.grid, msg,
"Rename {}".format(self.grid.name, default_val),
default_val)
res = dia.ShowModal()
if res == wx.ID_OK:
new_val = dia.GetValue()
# update the contribution with new name
self.contribution.rename_item(self.grid.name,
default_val, new_val)
# don't propagate changes if we are just assigning a new name
# and not really renaming
# (i.e., if a blank row was added then named)
if default_val == '':
self.grid.SetCellValue(row, 0, new_val)
return
# update the current grid with new name
for row in range(self.grid.GetNumberRows()):
cell_value = self.grid.GetCellValue(row, 0)
if cell_value == default_val:
self.grid.SetCellValue(row, 0, new_val)
else:
continue
return
color = self.grid.GetCellBackgroundColour(event.GetRow(), event.GetCol())
# allow user to cherry-pick cells for editing.
# gets selection of meta key for mac, ctrl key for pc
if event.ControlDown() or event.MetaDown():
row, col = event.GetRow(), event.GetCol()
if (row, col) not in self.dispersed_selection:
self.dispersed_selection.append((row, col))
self.grid.SetCellBackgroundColour(row, col, 'light blue')
else:
self.dispersed_selection.remove((row, col))
self.grid.SetCellBackgroundColour(row, col, color)# 'white'
self.grid.ForceRefresh()
return
if event.ShiftDown(): # allow user to highlight multiple consecutive cells in a column
previous_col = self.grid.GetGridCursorCol()
previous_row = self.grid.GetGridCursorRow()
col = event.GetCol()
row = event.GetRow()
if col != previous_col:
return
else:
if row > previous_row:
row_range = list(range(previous_row, row+1))
else:
row_range = list(range(row, previous_row+1))
for r in row_range:
self.grid.SetCellBackgroundColour(r, col, 'light blue')
self.selection.append((r, col))
self.grid.ForceRefresh()
return
selection = False
if self.dispersed_selection:
is_dispersed = True
selection = self.dispersed_selection
if self.selection:
is_dispersed = False
selection = self.selection
try:
col = event.GetCol()
row = event.GetRow()
except AttributeError:
row, col = selection[0][0], selection[0][1]
self.grid.SetGridCursor(row, col)
if col in list(choices.keys()): # column should have a pop-up menu
menu = wx.Menu()
two_tiered = choices[col][1]
choices = choices[col][0]
if not two_tiered: # menu is one tiered
if 'CLEAR cell of all values' not in choices:
choices.insert(0, 'CLEAR cell of all values')
for choice in choices:
if not choice:
choice = " " # prevents error if choice is an empty string
menuitem = menu.Append(wx.ID_ANY, str(choice))
self.window.Bind(wx.EVT_MENU, lambda event: self.on_select_menuitem(event, grid, row, col, selection), menuitem)
self.show_menu(event, menu)
else: # menu is two_tiered
clear = menu.Append(-1, 'CLEAR cell of all values')
self.window.Bind(wx.EVT_MENU, lambda event: self.on_select_menuitem(event, grid, row, col, selection), clear)
for choice in sorted(choices.items()):
submenu = wx.Menu()
for item in choice[1]:
menuitem = submenu.Append(-1, str(item))
self.window.Bind(wx.EVT_MENU, lambda event: self.on_select_menuitem(event, grid, row, col, selection), menuitem)
menu.Append(-1, choice[0], submenu)
self.show_menu(event, menu)
if selection:
# re-whiten the cells that were previously highlighted
for row, col in selection:
self.grid.SetCellBackgroundColour(row, col, self.col_color)
self.dispersed_selection = []
self.selection = []
self.grid.ForceRefresh() | creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/drop_down_menus3.py#L284-L397 |
PmagPy/PmagPy | programs/di_tilt.py | main | 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 | 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])) | 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 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/di_tilt.py#L9-L65 |
PmagPy/PmagPy | programs/convert2unix.py | main | 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 | 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() | 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 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/convert2unix.py#L5-L30 |
PmagPy/PmagPy | programs/igrf.py | main | def main():
"""
NAME
igrf.py
DESCRIPTION
This program calculates igrf field values
using the routine of Malin and Barraclough (1981)
based on d/igrfs from 1900 to 2010.
between 1900 and 1000BCE, it uses CALS3K.4, ARCH3K.1
Prior to 1000BCE, it uses PFM9k or CALS10k-4b
Calculates reference field vector at specified location and time.
SYNTAX
igrf.py [-h] [-i] -f FILE [< filename]
OPTIONS:
-h prints help message and quits
-i for interactive data entry
-f FILE specify file name with input data
-fgh FILE specify file with custom field coefficients in format: l m g h
-F FILE specify output file name
-ages MIN MAX INCR: specify age minimum in years (+/- AD), maximum and increment, default is line by line
-loc LAT LON; specify location, default is line by line
-alt ALT; specify altitude in km, default is sealevel (0)
-plt; make a plot of the time series
-sav, saves plot and quits
-fmt [pdf,jpg,eps,svg] specify format for output figure (default is svg)
-mod [arch3k,cals3k,pfm9k,hfm10k,cals10k.2,shadif14k,cals10k.1b] specify model for 3ka to 1900 AD, default is cals10k
NB: program uses IGRF12 for dates 1900 to 2015.
INPUT FORMAT
interactive entry:
date: decimal year
alt: altitude in km
lat: positive north
lon: positive east
for file entry:
space delimited string: date alt lat long
OUTPUT FORMAT
Declination Inclination Intensity (nT) date alt lat long
MODELS: ARCH3K: (Korte et al., 2009);CALS3K (Korte & Contable, 2011); CALS10k (is .1b of Korte et al., 2011); PFM9K (Nilsson et al., 2014); HFM10k (is HFM.OL1.A1 of Constable et al., 2016); CALS10k_2 (is cals10k.2 of Constable et al., 2016), SHADIF14k (SHA.DIF.14K of Pavon-Carrasco et al., 2014).
"""
plot, fmt = 0, 'svg'
mod, alt, make_plot, lat, lon = 'cals10k', 0, 0, 0, 0
if '-loc' in sys.argv:
ind = sys.argv.index('-loc')
lat = float(sys.argv[ind+1])
lon = float(sys.argv[ind+2])
if '-alt' in sys.argv:
ind = sys.argv.index('-alt')
alt = float(sys.argv[ind+1])
if '-fmt' in sys.argv:
ind = sys.argv.index('-fmt')
fmt = sys.argv[ind+1]
if len(sys.argv) != 0 and '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-mod' in sys.argv:
ind = sys.argv.index('-mod')
mod = sys.argv[ind+1]
if '-fgh' in sys.argv:
ind = sys.argv.index('-fgh')
ghfile = sys.argv[ind+1]
lmgh = numpy.loadtxt(ghfile)
gh = []
lmgh = numpy.loadtxt(ghfile).transpose()
gh.append(lmgh[2][0])
for i in range(1, lmgh.shape[1]):
gh.append(lmgh[2][i])
gh.append(lmgh[3][i])
mod = 'custom'
inp = [[0, alt, lat, lon]]
elif '-f' in sys.argv:
ind = sys.argv.index('-f')
file = sys.argv[ind+1]
inp = numpy.loadtxt(file)
elif '-i' in sys.argv:
while 1:
try:
line = []
if mod != 'custom':
line.append(
float(input("Decimal year: <cntrl-D to quit> ")))
else:
line.append(0)
alt = input("Elevation in km [0] ")
if alt == "":
alt = "0"
line.append(float(alt))
line.append(float(input("Latitude (positive north) ")))
line.append(float(input("Longitude (positive east) ")))
if mod == '':
x, y, z, f = pmag.doigrf(
line[3] % 360., line[2], line[1], line[0])
elif mod == 'custom':
x, y, z, f = pmag.docustom(
line[3] % 360., line[2], line[1], gh)
else:
x, y, z, f = pmag.doigrf(
line[3] % 360., line[2], line[1], line[0], mod=mod)
Dir = pmag.cart2dir((x, y, z))
print('%8.2f %8.2f %8.0f' % (Dir[0], Dir[1], f))
except EOFError:
print("\n Good-bye\n")
sys.exit()
elif '-ages' in sys.argv:
ind = sys.argv.index('-ages')
agemin = float(sys.argv[ind+1])
agemax = float(sys.argv[ind+2])
ageincr = float(sys.argv[ind+3])
ages = numpy.arange(agemin, agemax, ageincr)
lats = numpy.ones(len(ages))*lat
lons = numpy.ones(len(ages))*lon
alts = numpy.ones(len(ages))*alt
inp = numpy.array([ages, alts, lats, lons]).transpose()
else:
inp = numpy.loadtxt(sys.stdin, dtype=numpy.float)
if '-F' in sys.argv:
ind = sys.argv.index('-F')
outfile = sys.argv[ind+1]
out = open(outfile, 'w')
else:
outfile = ""
if '-sav' in sys.argv:
plot = 1
if '-plt' in sys.argv:
make_plot = 1
Ages, Decs, Incs, Ints, VADMs = [], [], [], [], []
for line in inp:
if mod != 'custom':
x, y, z, f = pmag.doigrf(
line[3] % 360., line[2], line[1], line[0], mod=mod)
else:
x, y, z, f = pmag.docustom(line[3] % 360., line[2], line[1], gh)
Dir = pmag.cart2dir((x, y, z))
if outfile != "":
out.write('%8.2f %8.2f %8.0f %7.1f %7.1f %7.1f %7.1f\n' %
(Dir[0], Dir[1], f, line[0], line[1], line[2], line[3]))
elif make_plot:
Ages.append(line[0])
if Dir[0] > 180:
Dir[0] = Dir[0]-360.0
Decs.append(Dir[0])
Incs.append(Dir[1])
Ints.append(f*1e-3)
VADMs.append(pmag.b_vdm(f*1e-9, line[2])*1e-21)
else:
print('%8.2f %8.2f %8.0f %7.1f %7.1f %7.1f %7.1f' %
(Dir[0], Dir[1], f, line[0], line[1], line[2], line[3]))
if make_plot:
pmagplotlib.plot_init(1, 7, 9)
fig = plt.figure(num=1, figsize=(7, 9))
fig.add_subplot(411)
plt.plot(Ages, Decs)
plt.ylabel('Declination ($^{\circ}$)')
fig.add_subplot(412)
plt.plot(Ages, Incs)
plt.ylabel('Inclination ($^{\circ}$)')
fig.add_subplot(413)
plt.plot(Ages, Ints)
plt.ylabel('Intensity ($\mu$T)')
fig.add_subplot(414)
plt.plot(Ages, VADMs)
plt.ylabel('VADMs (ZAm$^2$)')
plt.xlabel('Ages')
# show plot
if plot == 0:
pmagplotlib.draw_figs({'time series': 1})
ans = input("S[a]ve to save figure, <Return> to quit ")
if ans == 'a':
plt.savefig('igrf.'+fmt)
print('Figure saved as: ', 'igrf.'+fmt)
# save plot without showing
else:
plt.savefig('igrf.'+fmt)
print('Figure saved as: ', 'igrf.'+fmt)
sys.exit() | python | def main():
"""
NAME
igrf.py
DESCRIPTION
This program calculates igrf field values
using the routine of Malin and Barraclough (1981)
based on d/igrfs from 1900 to 2010.
between 1900 and 1000BCE, it uses CALS3K.4, ARCH3K.1
Prior to 1000BCE, it uses PFM9k or CALS10k-4b
Calculates reference field vector at specified location and time.
SYNTAX
igrf.py [-h] [-i] -f FILE [< filename]
OPTIONS:
-h prints help message and quits
-i for interactive data entry
-f FILE specify file name with input data
-fgh FILE specify file with custom field coefficients in format: l m g h
-F FILE specify output file name
-ages MIN MAX INCR: specify age minimum in years (+/- AD), maximum and increment, default is line by line
-loc LAT LON; specify location, default is line by line
-alt ALT; specify altitude in km, default is sealevel (0)
-plt; make a plot of the time series
-sav, saves plot and quits
-fmt [pdf,jpg,eps,svg] specify format for output figure (default is svg)
-mod [arch3k,cals3k,pfm9k,hfm10k,cals10k.2,shadif14k,cals10k.1b] specify model for 3ka to 1900 AD, default is cals10k
NB: program uses IGRF12 for dates 1900 to 2015.
INPUT FORMAT
interactive entry:
date: decimal year
alt: altitude in km
lat: positive north
lon: positive east
for file entry:
space delimited string: date alt lat long
OUTPUT FORMAT
Declination Inclination Intensity (nT) date alt lat long
MODELS: ARCH3K: (Korte et al., 2009);CALS3K (Korte & Contable, 2011); CALS10k (is .1b of Korte et al., 2011); PFM9K (Nilsson et al., 2014); HFM10k (is HFM.OL1.A1 of Constable et al., 2016); CALS10k_2 (is cals10k.2 of Constable et al., 2016), SHADIF14k (SHA.DIF.14K of Pavon-Carrasco et al., 2014).
"""
plot, fmt = 0, 'svg'
mod, alt, make_plot, lat, lon = 'cals10k', 0, 0, 0, 0
if '-loc' in sys.argv:
ind = sys.argv.index('-loc')
lat = float(sys.argv[ind+1])
lon = float(sys.argv[ind+2])
if '-alt' in sys.argv:
ind = sys.argv.index('-alt')
alt = float(sys.argv[ind+1])
if '-fmt' in sys.argv:
ind = sys.argv.index('-fmt')
fmt = sys.argv[ind+1]
if len(sys.argv) != 0 and '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-mod' in sys.argv:
ind = sys.argv.index('-mod')
mod = sys.argv[ind+1]
if '-fgh' in sys.argv:
ind = sys.argv.index('-fgh')
ghfile = sys.argv[ind+1]
lmgh = numpy.loadtxt(ghfile)
gh = []
lmgh = numpy.loadtxt(ghfile).transpose()
gh.append(lmgh[2][0])
for i in range(1, lmgh.shape[1]):
gh.append(lmgh[2][i])
gh.append(lmgh[3][i])
mod = 'custom'
inp = [[0, alt, lat, lon]]
elif '-f' in sys.argv:
ind = sys.argv.index('-f')
file = sys.argv[ind+1]
inp = numpy.loadtxt(file)
elif '-i' in sys.argv:
while 1:
try:
line = []
if mod != 'custom':
line.append(
float(input("Decimal year: <cntrl-D to quit> ")))
else:
line.append(0)
alt = input("Elevation in km [0] ")
if alt == "":
alt = "0"
line.append(float(alt))
line.append(float(input("Latitude (positive north) ")))
line.append(float(input("Longitude (positive east) ")))
if mod == '':
x, y, z, f = pmag.doigrf(
line[3] % 360., line[2], line[1], line[0])
elif mod == 'custom':
x, y, z, f = pmag.docustom(
line[3] % 360., line[2], line[1], gh)
else:
x, y, z, f = pmag.doigrf(
line[3] % 360., line[2], line[1], line[0], mod=mod)
Dir = pmag.cart2dir((x, y, z))
print('%8.2f %8.2f %8.0f' % (Dir[0], Dir[1], f))
except EOFError:
print("\n Good-bye\n")
sys.exit()
elif '-ages' in sys.argv:
ind = sys.argv.index('-ages')
agemin = float(sys.argv[ind+1])
agemax = float(sys.argv[ind+2])
ageincr = float(sys.argv[ind+3])
ages = numpy.arange(agemin, agemax, ageincr)
lats = numpy.ones(len(ages))*lat
lons = numpy.ones(len(ages))*lon
alts = numpy.ones(len(ages))*alt
inp = numpy.array([ages, alts, lats, lons]).transpose()
else:
inp = numpy.loadtxt(sys.stdin, dtype=numpy.float)
if '-F' in sys.argv:
ind = sys.argv.index('-F')
outfile = sys.argv[ind+1]
out = open(outfile, 'w')
else:
outfile = ""
if '-sav' in sys.argv:
plot = 1
if '-plt' in sys.argv:
make_plot = 1
Ages, Decs, Incs, Ints, VADMs = [], [], [], [], []
for line in inp:
if mod != 'custom':
x, y, z, f = pmag.doigrf(
line[3] % 360., line[2], line[1], line[0], mod=mod)
else:
x, y, z, f = pmag.docustom(line[3] % 360., line[2], line[1], gh)
Dir = pmag.cart2dir((x, y, z))
if outfile != "":
out.write('%8.2f %8.2f %8.0f %7.1f %7.1f %7.1f %7.1f\n' %
(Dir[0], Dir[1], f, line[0], line[1], line[2], line[3]))
elif make_plot:
Ages.append(line[0])
if Dir[0] > 180:
Dir[0] = Dir[0]-360.0
Decs.append(Dir[0])
Incs.append(Dir[1])
Ints.append(f*1e-3)
VADMs.append(pmag.b_vdm(f*1e-9, line[2])*1e-21)
else:
print('%8.2f %8.2f %8.0f %7.1f %7.1f %7.1f %7.1f' %
(Dir[0], Dir[1], f, line[0], line[1], line[2], line[3]))
if make_plot:
pmagplotlib.plot_init(1, 7, 9)
fig = plt.figure(num=1, figsize=(7, 9))
fig.add_subplot(411)
plt.plot(Ages, Decs)
plt.ylabel('Declination ($^{\circ}$)')
fig.add_subplot(412)
plt.plot(Ages, Incs)
plt.ylabel('Inclination ($^{\circ}$)')
fig.add_subplot(413)
plt.plot(Ages, Ints)
plt.ylabel('Intensity ($\mu$T)')
fig.add_subplot(414)
plt.plot(Ages, VADMs)
plt.ylabel('VADMs (ZAm$^2$)')
plt.xlabel('Ages')
# show plot
if plot == 0:
pmagplotlib.draw_figs({'time series': 1})
ans = input("S[a]ve to save figure, <Return> to quit ")
if ans == 'a':
plt.savefig('igrf.'+fmt)
print('Figure saved as: ', 'igrf.'+fmt)
# save plot without showing
else:
plt.savefig('igrf.'+fmt)
print('Figure saved as: ', 'igrf.'+fmt)
sys.exit() | NAME
igrf.py
DESCRIPTION
This program calculates igrf field values
using the routine of Malin and Barraclough (1981)
based on d/igrfs from 1900 to 2010.
between 1900 and 1000BCE, it uses CALS3K.4, ARCH3K.1
Prior to 1000BCE, it uses PFM9k or CALS10k-4b
Calculates reference field vector at specified location and time.
SYNTAX
igrf.py [-h] [-i] -f FILE [< filename]
OPTIONS:
-h prints help message and quits
-i for interactive data entry
-f FILE specify file name with input data
-fgh FILE specify file with custom field coefficients in format: l m g h
-F FILE specify output file name
-ages MIN MAX INCR: specify age minimum in years (+/- AD), maximum and increment, default is line by line
-loc LAT LON; specify location, default is line by line
-alt ALT; specify altitude in km, default is sealevel (0)
-plt; make a plot of the time series
-sav, saves plot and quits
-fmt [pdf,jpg,eps,svg] specify format for output figure (default is svg)
-mod [arch3k,cals3k,pfm9k,hfm10k,cals10k.2,shadif14k,cals10k.1b] specify model for 3ka to 1900 AD, default is cals10k
NB: program uses IGRF12 for dates 1900 to 2015.
INPUT FORMAT
interactive entry:
date: decimal year
alt: altitude in km
lat: positive north
lon: positive east
for file entry:
space delimited string: date alt lat long
OUTPUT FORMAT
Declination Inclination Intensity (nT) date alt lat long
MODELS: ARCH3K: (Korte et al., 2009);CALS3K (Korte & Contable, 2011); CALS10k (is .1b of Korte et al., 2011); PFM9K (Nilsson et al., 2014); HFM10k (is HFM.OL1.A1 of Constable et al., 2016); CALS10k_2 (is cals10k.2 of Constable et al., 2016), SHADIF14k (SHA.DIF.14K of Pavon-Carrasco et al., 2014). | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/igrf.py#L15-L190 |
PmagPy/PmagPy | programs/vgpmap_magic2.py | main | def main():
"""
NAME
vgpmap_magic.py
DESCRIPTION
makes a map of vgps and a95/dp,dm for site means in a pmag_results table
SYNTAX
vgpmap_magic.py [command line options]
OPTIONS
-h prints help and quits
-eye ELAT ELON [specify eyeball location], default is 90., 0.
-f FILE pmag_results format file, [default is pmag_results.txt]
-res [c,l,i,h] specify resolution (crude, low, intermediate, high]
-etp plot the etopo20 topographpy data (requires high resolution data set)
-prj PROJ, specify one of the following:
ortho = orthographic
lcc = lambert conformal
moll = molweide
merc = mercator
-sym SYM SIZE: choose a symbol and size, examples:
ro 5 : small red circles
bs 10 : intermediate blue squares
g^ 20 : large green triangles
-ell plot dp/dm or a95 ellipses
-rev RSYM RSIZE : flip reverse poles to normal antipode
-S: plot antipodes of all poles
-age : plot the ages next to the poles
-crd [g,t] : choose coordinate system, default is to plot all site VGPs
-fmt [pdf, png, eps...] specify output format, default is pdf
-sav save and quit
DEFAULTS
FILE: pmag_results.txt
res: c
prj: ortho
ELAT,ELON = 0,0
SYM SIZE: ro 8
RSYM RSIZE: g^ 8
"""
dir_path = '.'
res, ages = 'c', 0
plot = 0
proj = 'ortho'
results_file = 'pmag_results.txt'
ell, flip = 0, 0
lat_0, lon_0 = 90., 0.
fmt = 'pdf'
sym, size = 'ro', 8
rsym, rsize = 'g^', 8
anti = 0
fancy = 0
coord = ""
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 '-S' in sys.argv:
anti = 1
if '-fmt' in sys.argv:
ind = sys.argv.index('-fmt')
fmt = sys.argv[ind+1]
if '-sav' in sys.argv:
plot = 1
if '-res' in sys.argv:
ind = sys.argv.index('-res')
res = sys.argv[ind+1]
if '-etp' in sys.argv:
fancy = 1
if '-prj' in sys.argv:
ind = sys.argv.index('-prj')
proj = sys.argv[ind+1]
if '-rev' in sys.argv:
flip = 1
ind = sys.argv.index('-rev')
rsym = (sys.argv[ind+1])
rsize = int(sys.argv[ind+2])
if '-sym' in sys.argv:
ind = sys.argv.index('-sym')
sym = (sys.argv[ind+1])
size = int(sys.argv[ind+2])
if '-eye' in sys.argv:
ind = sys.argv.index('-eye')
lat_0 = float(sys.argv[ind+1])
lon_0 = float(sys.argv[ind+2])
if '-ell' in sys.argv:
ell = 1
if '-age' in sys.argv:
ages = 1
if '-f' in sys.argv:
ind = sys.argv.index('-f')
results_file = sys.argv[ind+1]
if '-crd' in sys.argv:
ind = sys.argv.index('-crd')
crd = sys.argv[ind+1]
if crd == 'g':
coord = '0'
if crd == 't':
coord = '100'
results_file = dir_path+'/'+results_file
data, file_type = pmag.magic_read(results_file)
if file_type != 'pmag_results':
print("bad results file")
sys.exit()
FIG = {'map': 1}
pmagplotlib.plot_init(FIG['map'], 6, 6)
# read in er_sites file
lats, lons, dp, dm, a95 = [], [], [], [], []
Pars = []
dates, rlats, rlons = [], [], []
if 'data_type' in data[0].keys():
# get all site level data
Results = pmag.get_dictitem(data, 'data_type', 'i', 'T')
else:
Results = data
# get all non-blank latitudes
Results = pmag.get_dictitem(Results, 'vgp_lat', '', 'F')
# get all non-blank longitudes
Results = pmag.get_dictitem(Results, 'vgp_lon', '', 'F')
if coord != "":
# get specified coordinate system
Results = pmag.get_dictitem(Results, 'tilt_correction', coord, 'T')
location = ""
for rec in Results:
if rec['er_location_names'] not in location:
location = location+':'+rec['er_location_names']
if 'average_age' in rec.keys() and rec['average_age'] != "" and ages == 1:
dates.append(rec['average_age'])
lat = float(rec['vgp_lat'])
lon = float(rec['vgp_lon'])
if flip == 0:
lats.append(lat)
lons.append(lon)
elif flip == 1:
if lat < 0:
rlats.append(-lat)
lon = lon+180.
if lon > 360:
lon = lon-360.
rlons.append(lon)
else:
lats.append(lat)
lons.append(lon)
elif anti == 1:
lats.append(-lat)
lon = lon+180.
if lon > 360:
lon = lon-360.
lons.append(lon)
ppars = []
ppars.append(lon)
ppars.append(lat)
ell1, ell2 = "", ""
if 'vgp_dm' in rec.keys() and rec['vgp_dm'] != "":
ell1 = float(rec['vgp_dm'])
if 'vgp_dp' in rec.keys() and rec['vgp_dp'] != "":
ell2 = float(rec['vgp_dp'])
if 'vgp_alpha95' in rec.keys() and rec['vgp_alpha95'] != "":
ell1, ell2 = float(rec['vgp_alpha95']), float(rec['vgp_alpha95'])
if ell1 != "" and ell2 != "":
ppars = []
ppars.append(lons[-1])
ppars.append(lats[-1])
ppars.append(ell1)
ppars.append(lons[-1])
isign = abs(lats[-1])/lats[-1]
ppars.append(lats[-1]-isign*90.)
ppars.append(ell2)
ppars.append(lons[-1]+90.)
ppars.append(0.)
Pars.append(ppars)
location = location.strip(':')
Opts = {'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360., 'lat_0': lat_0, 'lon_0': lon_0,
'proj': proj, 'sym': 'bs', 'symsize': 3, 'pltgrid': 0, 'res': res, 'boundinglat': 0.}
Opts['details'] = {'coasts': 1, 'rivers': 0, 'states': 0,
'countries': 0, 'ocean': 1, 'fancy': fancy}
# make the base map with a blue triangle at the pole`
pmagplotlib.plot_map(FIG['map'], [90.], [0.], Opts)
Opts['pltgrid'] = -1
Opts['sym'] = sym
Opts['symsize'] = size
if len(dates) > 0:
Opts['names'] = dates
if len(lats) > 0:
# add the lats and lons of the poles
pmagplotlib.plot_map(FIG['map'], lats, lons, Opts)
Opts['names'] = []
if len(rlats) > 0:
Opts['sym'] = rsym
Opts['symsize'] = rsize
# add the lats and lons of the poles
pmagplotlib.plot_map(FIG['map'], rlats, rlons, Opts)
if plot == 0:
pmagplotlib.draw_figs(FIG)
if ell == 1: # add ellipses if desired.
Opts['details'] = {'coasts': 0, 'rivers': 0,
'states': 0, 'countries': 0, 'ocean': 0}
Opts['pltgrid'] = -1 # turn off meridian replotting
Opts['symsize'] = 2
Opts['sym'] = 'g-'
for ppars in Pars:
if ppars[2] != 0:
PTS = pmagplotlib.plot_ell(FIG['map'], ppars, 'g.', 0, 0)
elats, elons = [], []
for pt in PTS:
elons.append(pt[0])
elats.append(pt[1])
# make the base map with a blue triangle at the pole`
pmagplotlib.plot_map(FIG['map'], elats, elons, Opts)
if plot == 0:
pmagplotlib.draw_figs(FIG)
files = {}
for key in FIG.keys():
if pmagplotlib.isServer: # use server plot naming convention
files[key] = 'LO:_'+location+'_VGP_map.'+fmt
else: # use more readable plot naming convention
files[key] = '{}_VGP_map.{}'.format(
location.replace(' ', '_'), fmt)
if pmagplotlib.isServer:
black = '#000000'
purple = '#800080'
titles = {}
titles['eq'] = 'LO:_'+location+'_VGP_map'
FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
pmagplotlib.save_plots(FIG, files)
elif plot == 0:
pmagplotlib.draw_figs(FIG)
ans = input(" S[a]ve to save plot, Return to quit: ")
if ans == "a":
pmagplotlib.save_plots(FIG, files)
else:
print("Good bye")
sys.exit()
else:
pmagplotlib.save_plots(FIG, files) | python | def main():
"""
NAME
vgpmap_magic.py
DESCRIPTION
makes a map of vgps and a95/dp,dm for site means in a pmag_results table
SYNTAX
vgpmap_magic.py [command line options]
OPTIONS
-h prints help and quits
-eye ELAT ELON [specify eyeball location], default is 90., 0.
-f FILE pmag_results format file, [default is pmag_results.txt]
-res [c,l,i,h] specify resolution (crude, low, intermediate, high]
-etp plot the etopo20 topographpy data (requires high resolution data set)
-prj PROJ, specify one of the following:
ortho = orthographic
lcc = lambert conformal
moll = molweide
merc = mercator
-sym SYM SIZE: choose a symbol and size, examples:
ro 5 : small red circles
bs 10 : intermediate blue squares
g^ 20 : large green triangles
-ell plot dp/dm or a95 ellipses
-rev RSYM RSIZE : flip reverse poles to normal antipode
-S: plot antipodes of all poles
-age : plot the ages next to the poles
-crd [g,t] : choose coordinate system, default is to plot all site VGPs
-fmt [pdf, png, eps...] specify output format, default is pdf
-sav save and quit
DEFAULTS
FILE: pmag_results.txt
res: c
prj: ortho
ELAT,ELON = 0,0
SYM SIZE: ro 8
RSYM RSIZE: g^ 8
"""
dir_path = '.'
res, ages = 'c', 0
plot = 0
proj = 'ortho'
results_file = 'pmag_results.txt'
ell, flip = 0, 0
lat_0, lon_0 = 90., 0.
fmt = 'pdf'
sym, size = 'ro', 8
rsym, rsize = 'g^', 8
anti = 0
fancy = 0
coord = ""
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 '-S' in sys.argv:
anti = 1
if '-fmt' in sys.argv:
ind = sys.argv.index('-fmt')
fmt = sys.argv[ind+1]
if '-sav' in sys.argv:
plot = 1
if '-res' in sys.argv:
ind = sys.argv.index('-res')
res = sys.argv[ind+1]
if '-etp' in sys.argv:
fancy = 1
if '-prj' in sys.argv:
ind = sys.argv.index('-prj')
proj = sys.argv[ind+1]
if '-rev' in sys.argv:
flip = 1
ind = sys.argv.index('-rev')
rsym = (sys.argv[ind+1])
rsize = int(sys.argv[ind+2])
if '-sym' in sys.argv:
ind = sys.argv.index('-sym')
sym = (sys.argv[ind+1])
size = int(sys.argv[ind+2])
if '-eye' in sys.argv:
ind = sys.argv.index('-eye')
lat_0 = float(sys.argv[ind+1])
lon_0 = float(sys.argv[ind+2])
if '-ell' in sys.argv:
ell = 1
if '-age' in sys.argv:
ages = 1
if '-f' in sys.argv:
ind = sys.argv.index('-f')
results_file = sys.argv[ind+1]
if '-crd' in sys.argv:
ind = sys.argv.index('-crd')
crd = sys.argv[ind+1]
if crd == 'g':
coord = '0'
if crd == 't':
coord = '100'
results_file = dir_path+'/'+results_file
data, file_type = pmag.magic_read(results_file)
if file_type != 'pmag_results':
print("bad results file")
sys.exit()
FIG = {'map': 1}
pmagplotlib.plot_init(FIG['map'], 6, 6)
# read in er_sites file
lats, lons, dp, dm, a95 = [], [], [], [], []
Pars = []
dates, rlats, rlons = [], [], []
if 'data_type' in data[0].keys():
# get all site level data
Results = pmag.get_dictitem(data, 'data_type', 'i', 'T')
else:
Results = data
# get all non-blank latitudes
Results = pmag.get_dictitem(Results, 'vgp_lat', '', 'F')
# get all non-blank longitudes
Results = pmag.get_dictitem(Results, 'vgp_lon', '', 'F')
if coord != "":
# get specified coordinate system
Results = pmag.get_dictitem(Results, 'tilt_correction', coord, 'T')
location = ""
for rec in Results:
if rec['er_location_names'] not in location:
location = location+':'+rec['er_location_names']
if 'average_age' in rec.keys() and rec['average_age'] != "" and ages == 1:
dates.append(rec['average_age'])
lat = float(rec['vgp_lat'])
lon = float(rec['vgp_lon'])
if flip == 0:
lats.append(lat)
lons.append(lon)
elif flip == 1:
if lat < 0:
rlats.append(-lat)
lon = lon+180.
if lon > 360:
lon = lon-360.
rlons.append(lon)
else:
lats.append(lat)
lons.append(lon)
elif anti == 1:
lats.append(-lat)
lon = lon+180.
if lon > 360:
lon = lon-360.
lons.append(lon)
ppars = []
ppars.append(lon)
ppars.append(lat)
ell1, ell2 = "", ""
if 'vgp_dm' in rec.keys() and rec['vgp_dm'] != "":
ell1 = float(rec['vgp_dm'])
if 'vgp_dp' in rec.keys() and rec['vgp_dp'] != "":
ell2 = float(rec['vgp_dp'])
if 'vgp_alpha95' in rec.keys() and rec['vgp_alpha95'] != "":
ell1, ell2 = float(rec['vgp_alpha95']), float(rec['vgp_alpha95'])
if ell1 != "" and ell2 != "":
ppars = []
ppars.append(lons[-1])
ppars.append(lats[-1])
ppars.append(ell1)
ppars.append(lons[-1])
isign = abs(lats[-1])/lats[-1]
ppars.append(lats[-1]-isign*90.)
ppars.append(ell2)
ppars.append(lons[-1]+90.)
ppars.append(0.)
Pars.append(ppars)
location = location.strip(':')
Opts = {'latmin': -90, 'latmax': 90, 'lonmin': 0., 'lonmax': 360., 'lat_0': lat_0, 'lon_0': lon_0,
'proj': proj, 'sym': 'bs', 'symsize': 3, 'pltgrid': 0, 'res': res, 'boundinglat': 0.}
Opts['details'] = {'coasts': 1, 'rivers': 0, 'states': 0,
'countries': 0, 'ocean': 1, 'fancy': fancy}
# make the base map with a blue triangle at the pole`
pmagplotlib.plot_map(FIG['map'], [90.], [0.], Opts)
Opts['pltgrid'] = -1
Opts['sym'] = sym
Opts['symsize'] = size
if len(dates) > 0:
Opts['names'] = dates
if len(lats) > 0:
# add the lats and lons of the poles
pmagplotlib.plot_map(FIG['map'], lats, lons, Opts)
Opts['names'] = []
if len(rlats) > 0:
Opts['sym'] = rsym
Opts['symsize'] = rsize
# add the lats and lons of the poles
pmagplotlib.plot_map(FIG['map'], rlats, rlons, Opts)
if plot == 0:
pmagplotlib.draw_figs(FIG)
if ell == 1: # add ellipses if desired.
Opts['details'] = {'coasts': 0, 'rivers': 0,
'states': 0, 'countries': 0, 'ocean': 0}
Opts['pltgrid'] = -1 # turn off meridian replotting
Opts['symsize'] = 2
Opts['sym'] = 'g-'
for ppars in Pars:
if ppars[2] != 0:
PTS = pmagplotlib.plot_ell(FIG['map'], ppars, 'g.', 0, 0)
elats, elons = [], []
for pt in PTS:
elons.append(pt[0])
elats.append(pt[1])
# make the base map with a blue triangle at the pole`
pmagplotlib.plot_map(FIG['map'], elats, elons, Opts)
if plot == 0:
pmagplotlib.draw_figs(FIG)
files = {}
for key in FIG.keys():
if pmagplotlib.isServer: # use server plot naming convention
files[key] = 'LO:_'+location+'_VGP_map.'+fmt
else: # use more readable plot naming convention
files[key] = '{}_VGP_map.{}'.format(
location.replace(' ', '_'), fmt)
if pmagplotlib.isServer:
black = '#000000'
purple = '#800080'
titles = {}
titles['eq'] = 'LO:_'+location+'_VGP_map'
FIG = pmagplotlib.add_borders(FIG, titles, black, purple)
pmagplotlib.save_plots(FIG, files)
elif plot == 0:
pmagplotlib.draw_figs(FIG)
ans = input(" S[a]ve to save plot, Return to quit: ")
if ans == "a":
pmagplotlib.save_plots(FIG, files)
else:
print("Good bye")
sys.exit()
else:
pmagplotlib.save_plots(FIG, files) | NAME
vgpmap_magic.py
DESCRIPTION
makes a map of vgps and a95/dp,dm for site means in a pmag_results table
SYNTAX
vgpmap_magic.py [command line options]
OPTIONS
-h prints help and quits
-eye ELAT ELON [specify eyeball location], default is 90., 0.
-f FILE pmag_results format file, [default is pmag_results.txt]
-res [c,l,i,h] specify resolution (crude, low, intermediate, high]
-etp plot the etopo20 topographpy data (requires high resolution data set)
-prj PROJ, specify one of the following:
ortho = orthographic
lcc = lambert conformal
moll = molweide
merc = mercator
-sym SYM SIZE: choose a symbol and size, examples:
ro 5 : small red circles
bs 10 : intermediate blue squares
g^ 20 : large green triangles
-ell plot dp/dm or a95 ellipses
-rev RSYM RSIZE : flip reverse poles to normal antipode
-S: plot antipodes of all poles
-age : plot the ages next to the poles
-crd [g,t] : choose coordinate system, default is to plot all site VGPs
-fmt [pdf, png, eps...] specify output format, default is pdf
-sav save and quit
DEFAULTS
FILE: pmag_results.txt
res: c
prj: ortho
ELAT,ELON = 0,0
SYM SIZE: ro 8
RSYM RSIZE: g^ 8 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/vgpmap_magic2.py#L13-L251 |
PmagPy/PmagPy | programs/gokent.py | main | 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 | 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') | 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 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/gokent.py#L7-L65 |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | draw_figs | def draw_figs(FIGS):
"""
Can only be used if matplotlib backend is set to TKAgg
Does not play well with wxPython
Parameters
_________
FIGS : dictionary of figure names as keys and numbers as values
"""
is_win = True if sys.platform in ['win32', 'win64'] else False
if not is_win:
plt.ion()
for fig in list(FIGS.keys()):
plt.draw()
plt.show()
plt.ioff()
if is_win:
# this style basically works for Windows
plt.draw()
print("You must manually close all plots to continue")
plt.show() | python | def draw_figs(FIGS):
"""
Can only be used if matplotlib backend is set to TKAgg
Does not play well with wxPython
Parameters
_________
FIGS : dictionary of figure names as keys and numbers as values
"""
is_win = True if sys.platform in ['win32', 'win64'] else False
if not is_win:
plt.ion()
for fig in list(FIGS.keys()):
plt.draw()
plt.show()
plt.ioff()
if is_win:
# this style basically works for Windows
plt.draw()
print("You must manually close all plots to continue")
plt.show() | Can only be used if matplotlib backend is set to TKAgg
Does not play well with wxPython
Parameters
_________
FIGS : dictionary of figure names as keys and numbers as values | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L63-L83 |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | delticks | def delticks(fig):
"""
deletes half the x-axis tick marks
Parameters
___________
fig : matplotlib figure number
"""
locs = fig.xaxis.get_ticklocs()
nlocs = np.delete(locs, list(range(0, len(locs), 2)))
fig.set_xticks(nlocs) | python | def delticks(fig):
"""
deletes half the x-axis tick marks
Parameters
___________
fig : matplotlib figure number
"""
locs = fig.xaxis.get_ticklocs()
nlocs = np.delete(locs, list(range(0, len(locs), 2)))
fig.set_xticks(nlocs) | deletes half the x-axis tick marks
Parameters
___________
fig : matplotlib figure number | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L105-L115 |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | plot_init | def plot_init(fignum, w, h):
"""
initializes plot number fignum with width w and height h
Parameters
__________
fignum : matplotlib figure number
w : width
h : height
"""
global fig_x_pos, fig_y_pos, plt_num
dpi = 80
if isServer:
dpi = 240
# plt.ion()
plt_num += 1
fig = plt.figure(num=fignum, figsize=(w, h), dpi=dpi)
if (not isServer) and (not set_env.IS_NOTEBOOK):
plt.get_current_fig_manager().show()
# plt.get_current_fig_manager().window.wm_geometry('+%d+%d' %
# (fig_x_pos,fig_y_pos)) # this only works with matplotlib.use('TKAgg')
fig_x_pos = fig_x_pos + dpi * (w) + 25
if plt_num == 3:
plt_num = 0
fig_x_pos = 25
fig_y_pos = fig_y_pos + dpi * (h) + 25
plt.figtext(.02, .01, version_num)
# plt.connect('button_press_event',click)
#
# plt.ioff()
return fig | python | def plot_init(fignum, w, h):
"""
initializes plot number fignum with width w and height h
Parameters
__________
fignum : matplotlib figure number
w : width
h : height
"""
global fig_x_pos, fig_y_pos, plt_num
dpi = 80
if isServer:
dpi = 240
# plt.ion()
plt_num += 1
fig = plt.figure(num=fignum, figsize=(w, h), dpi=dpi)
if (not isServer) and (not set_env.IS_NOTEBOOK):
plt.get_current_fig_manager().show()
# plt.get_current_fig_manager().window.wm_geometry('+%d+%d' %
# (fig_x_pos,fig_y_pos)) # this only works with matplotlib.use('TKAgg')
fig_x_pos = fig_x_pos + dpi * (w) + 25
if plt_num == 3:
plt_num = 0
fig_x_pos = 25
fig_y_pos = fig_y_pos + dpi * (h) + 25
plt.figtext(.02, .01, version_num)
# plt.connect('button_press_event',click)
#
# plt.ioff()
return fig | initializes plot number fignum with width w and height h
Parameters
__________
fignum : matplotlib figure number
w : width
h : height | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L123-L152 |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | plot3d_init | 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 | 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 | initializes 3D plot | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L155-L162 |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | gaussfunc | def gaussfunc(y, ybar, sigma):
"""
cumulative normal distribution function of the variable y
with mean ybar,standard deviation sigma
uses expression 7.1.26 from Abramowitz & Stegun
accuracy better than 1.5e-7 absolute
Parameters
_________
y : input variable
ybar : mean
sigma : standard deviation
"""
x = old_div((y - ybar), (np.sqrt(2.) * sigma))
t = old_div(1.0, (1.0 + .3275911 * abs(x)))
erf = 1.0 - np.exp(-x * x) * t * (.254829592 - t * (.284496736 -
t * (1.421413741 - t * (1.453152027 - t * 1.061405429))))
erf = abs(erf)
sign = old_div(x, abs(x))
return 0.5 * (1.0 + sign * erf) | python | def gaussfunc(y, ybar, sigma):
"""
cumulative normal distribution function of the variable y
with mean ybar,standard deviation sigma
uses expression 7.1.26 from Abramowitz & Stegun
accuracy better than 1.5e-7 absolute
Parameters
_________
y : input variable
ybar : mean
sigma : standard deviation
"""
x = old_div((y - ybar), (np.sqrt(2.) * sigma))
t = old_div(1.0, (1.0 + .3275911 * abs(x)))
erf = 1.0 - np.exp(-x * x) * t * (.254829592 - t * (.284496736 -
t * (1.421413741 - t * (1.453152027 - t * 1.061405429))))
erf = abs(erf)
sign = old_div(x, abs(x))
return 0.5 * (1.0 + sign * erf) | cumulative normal distribution function of the variable y
with mean ybar,standard deviation sigma
uses expression 7.1.26 from Abramowitz & Stegun
accuracy better than 1.5e-7 absolute
Parameters
_________
y : input variable
ybar : mean
sigma : standard deviation | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L176-L195 |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | k_s | def k_s(X):
"""
Kolmorgorov-Smirnov statistic. Finds the
probability that the data are distributed
as func - used method of Numerical Recipes (Press et al., 1986)
"""
xbar, sigma = pmag.gausspars(X)
d, f = 0, 0.
for i in range(1, len(X) + 1):
b = old_div(float(i), float(len(X)))
a = gaussfunc(X[i - 1], xbar, sigma)
if abs(f - a) > abs(b - a):
delta = abs(f - a)
else:
delta = abs(b - a)
if delta > d:
d = delta
f = b
return d, xbar, sigma | python | def k_s(X):
"""
Kolmorgorov-Smirnov statistic. Finds the
probability that the data are distributed
as func - used method of Numerical Recipes (Press et al., 1986)
"""
xbar, sigma = pmag.gausspars(X)
d, f = 0, 0.
for i in range(1, len(X) + 1):
b = old_div(float(i), float(len(X)))
a = gaussfunc(X[i - 1], xbar, sigma)
if abs(f - a) > abs(b - a):
delta = abs(f - a)
else:
delta = abs(b - a)
if delta > d:
d = delta
f = b
return d, xbar, sigma | Kolmorgorov-Smirnov statistic. Finds the
probability that the data are distributed
as func - used method of Numerical Recipes (Press et al., 1986) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L198-L216 |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | qsnorm | def qsnorm(p):
"""
rational approximation for x where q(x)=d, q being the cumulative
normal distribution function. taken from Abramowitz & Stegun p. 933
|error(x)| < 4.5*10**-4
"""
d = p
if d < 0. or d > 1.:
print('d not in (1,1) ')
sys.exit()
x = 0.
if (d - 0.5) > 0:
d = 1. - d
if (d - 0.5) < 0:
t2 = -2. * np.log(d)
t = np.sqrt(t2)
x = t - old_div((2.515517 + .802853 * t + .010328 * t2),
(1. + 1.432788 * t + .189269 * t2 + .001308 * t * t2))
if p < 0.5:
x = -x
return x | python | def qsnorm(p):
"""
rational approximation for x where q(x)=d, q being the cumulative
normal distribution function. taken from Abramowitz & Stegun p. 933
|error(x)| < 4.5*10**-4
"""
d = p
if d < 0. or d > 1.:
print('d not in (1,1) ')
sys.exit()
x = 0.
if (d - 0.5) > 0:
d = 1. - d
if (d - 0.5) < 0:
t2 = -2. * np.log(d)
t = np.sqrt(t2)
x = t - old_div((2.515517 + .802853 * t + .010328 * t2),
(1. + 1.432788 * t + .189269 * t2 + .001308 * t * t2))
if p < 0.5:
x = -x
return x | rational approximation for x where q(x)=d, q being the cumulative
normal distribution function. taken from Abramowitz & Stegun p. 933
|error(x)| < 4.5*10**-4 | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L219-L239 |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | plot_xy | 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 | 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]) | deprecated, used in curie | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L247-L292 |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | plot_site | def plot_site(fignum, SiteRec, data, key):
"""
deprecated (used in ipmag)
"""
print('Site mean data: ')
print(' dec inc n_lines n_planes kappa R alpha_95 comp coord')
print(SiteRec['site_dec'], SiteRec['site_inc'], SiteRec['site_n_lines'], SiteRec['site_n_planes'], SiteRec['site_k'],
SiteRec['site_r'], SiteRec['site_alpha95'], SiteRec['site_comp_name'], SiteRec['site_tilt_correction'])
print('sample/specimen, dec, inc, n_specs/a95,| method codes ')
for i in range(len(data)):
print('%s: %s %s %s / %s | %s' % (data[i]['er_' + key + '_name'], data[i][key + '_dec'], data[i]
[key + '_inc'], data[i][key + '_n'], data[i][key + '_alpha95'], data[i]['magic_method_codes']))
plot_slnp(fignum, SiteRec, data, key)
plot = input("s[a]ve plot, [q]uit or <return> to continue: ")
if plot == 'q':
print("CUL8R")
sys.exit()
if plot == 'a':
files = {}
for key in list(EQ.keys()):
files[key] = site + '_' + key + '.' + fmt
save_plots(EQ, files) | python | def plot_site(fignum, SiteRec, data, key):
"""
deprecated (used in ipmag)
"""
print('Site mean data: ')
print(' dec inc n_lines n_planes kappa R alpha_95 comp coord')
print(SiteRec['site_dec'], SiteRec['site_inc'], SiteRec['site_n_lines'], SiteRec['site_n_planes'], SiteRec['site_k'],
SiteRec['site_r'], SiteRec['site_alpha95'], SiteRec['site_comp_name'], SiteRec['site_tilt_correction'])
print('sample/specimen, dec, inc, n_specs/a95,| method codes ')
for i in range(len(data)):
print('%s: %s %s %s / %s | %s' % (data[i]['er_' + key + '_name'], data[i][key + '_dec'], data[i]
[key + '_inc'], data[i][key + '_n'], data[i][key + '_alpha95'], data[i]['magic_method_codes']))
plot_slnp(fignum, SiteRec, data, key)
plot = input("s[a]ve plot, [q]uit or <return> to continue: ")
if plot == 'q':
print("CUL8R")
sys.exit()
if plot == 'a':
files = {}
for key in list(EQ.keys()):
files[key] = site + '_' + key + '.' + fmt
save_plots(EQ, files) | deprecated (used in ipmag) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L295-L316 |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | plot_qq_norm | def plot_qq_norm(fignum, Y, title):
"""
makes a Quantile-Quantile plot for data
Parameters
_________
fignum : matplotlib figure number
Y : list or array of data
title : title string for plot
Returns
___________
d,dc : the values for D and Dc (the critical value)
if d>dc, likely to be normally distributed (95\% confidence)
"""
plt.figure(num=fignum)
if type(Y) == list:
Y = np.array(Y)
Y = np.sort(Y) # sort the data
n = len(Y)
d, mean, sigma = k_s(Y)
dc = old_div(0.886, np.sqrt(float(n)))
X = [] # list for normal quantile
for i in range(1, n + 1):
p = old_div(float(i), float(n + 1))
X.append(qsnorm(p))
plt.plot(X, Y, 'ro')
plt.title(title)
plt.xlabel('Normal Quantile')
plt.ylabel('Data Quantile')
bounds = plt.axis()
notestr = 'N: ' + '%i' % (n)
plt.text(-.9 * bounds[1], .9 * bounds[3], notestr)
notestr = 'mean: ' + '%8.3e' % (mean)
plt.text(-.9 * bounds[1], .8 * bounds[3], notestr)
notestr = 'std dev: ' + '%8.3e' % (sigma)
plt.text(-.9 * bounds[1], .7 * bounds[3], notestr)
notestr = 'D: ' + '%8.3e' % (d)
plt.text(-.9 * bounds[1], .6 * bounds[3], notestr)
notestr = 'Dc: ' + '%8.3e' % (dc)
plt.text(-.9 * bounds[1], .5 * bounds[3], notestr)
return d, dc | python | def plot_qq_norm(fignum, Y, title):
"""
makes a Quantile-Quantile plot for data
Parameters
_________
fignum : matplotlib figure number
Y : list or array of data
title : title string for plot
Returns
___________
d,dc : the values for D and Dc (the critical value)
if d>dc, likely to be normally distributed (95\% confidence)
"""
plt.figure(num=fignum)
if type(Y) == list:
Y = np.array(Y)
Y = np.sort(Y) # sort the data
n = len(Y)
d, mean, sigma = k_s(Y)
dc = old_div(0.886, np.sqrt(float(n)))
X = [] # list for normal quantile
for i in range(1, n + 1):
p = old_div(float(i), float(n + 1))
X.append(qsnorm(p))
plt.plot(X, Y, 'ro')
plt.title(title)
plt.xlabel('Normal Quantile')
plt.ylabel('Data Quantile')
bounds = plt.axis()
notestr = 'N: ' + '%i' % (n)
plt.text(-.9 * bounds[1], .9 * bounds[3], notestr)
notestr = 'mean: ' + '%8.3e' % (mean)
plt.text(-.9 * bounds[1], .8 * bounds[3], notestr)
notestr = 'std dev: ' + '%8.3e' % (sigma)
plt.text(-.9 * bounds[1], .7 * bounds[3], notestr)
notestr = 'D: ' + '%8.3e' % (d)
plt.text(-.9 * bounds[1], .6 * bounds[3], notestr)
notestr = 'Dc: ' + '%8.3e' % (dc)
plt.text(-.9 * bounds[1], .5 * bounds[3], notestr)
return d, dc | makes a Quantile-Quantile plot for data
Parameters
_________
fignum : matplotlib figure number
Y : list or array of data
title : title string for plot
Returns
___________
d,dc : the values for D and Dc (the critical value)
if d>dc, likely to be normally distributed (95\% confidence) | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L319-L359 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.