code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
if not self.user_warning("This feature is in ALPHA and still in development and testing. It is subject to bugs and will often create a LOT of new interpretations. This feature should only be used to get a general idea of the trend of the data before actually mannuely interpreting the data and the output of this function should certainly not be trusted as 100% accurate and useable for publication. Would you like to continue?"):
return
if not self.clear_interpretations():
return
print("Autointerpretation Start")
self.set_test_mode(True)
for specimen in self.specimens:
self.autointerpret_specimen(specimen, step_size, calculation_type)
self.set_test_mode(False)
if self.pmag_results_data['specimens'][self.s] != []:
self.current_fit = self.pmag_results_data['specimens'][self.s][-1]
else:
self.current_fit = None
print("Autointerpretation Complete")
self.update_selection()
if self.ie_open:
self.ie.update_editor()
|
def autointerpret(self, event, step_size=None, calculation_type="DE-BFL")
|
Clears current interpretations and adds interpretations to every
specimen of type = calculation_type by attempting fits of size =
step size and type = calculation_type and testing the mad or a95
then finding peaks in these to note areas of maximum error then fits
between these peaks excluding them.
Parameters
----------
step_size : int that is the size of fits to make while stepping
through data if None then step size = len(meas data for
specimen)/10 rounded up if that value is greater than 3 else it
is 3 (default: None)
calculation_type : type of fit to make (default: DE-BFL or line)
| 7.210937
| 6.809047
| 1.059023
|
if self.COORDINATE_SYSTEM == 'geographic':
block = self.Data[specimen]['zijdblock_geo']
elif self.COORDINATE_SYSTEM == 'tilt-corrected':
block = self.Data[specimen]['zijdblock_tilt']
else:
block = self.Data[specimen]['zijdblock']
if step_size == None:
step_size = int(len(block)/10 + .5)
if step_size < 3:
step_size = 3
temps = []
mads = []
for i in range(len(block)-step_size):
if block[i][5] == 'b':
return
try:
mpars = pmag.domean(block, i, i+step_size, calculation_type)
except (IndexError, TypeError) as e:
return
if 'specimen_mad' in list(mpars.keys()):
temps.append(block[i][0])
mads.append(mpars['specimen_mad'])
if mads == []:
return
peaks = find_peaks_cwt(array(mads), arange(5, 10))
len_temps = len(self.Data[specimen]['zijdblock_steps'])
peaks = [0] + peaks + [len(temps)]
prev_peak = peaks[0]
for peak in peaks[1:]:
if peak - prev_peak < 3:
prev_peak = peak
continue
tmin = self.Data[specimen]['zijdblock_steps'][prev_peak]
tmax = self.Data[specimen]['zijdblock_steps'][peak]
self.add_fit(specimen, None, tmin, tmax, calculation_type)
prev_peak = peak+1
|
def autointerpret_specimen(self, specimen, step_size, calculation_type)
|
In Dev
| 3.002048
| 3.001964
| 1.000028
|
elements_list = self.Data_hierarchy[high_level_type][high_level_name][elements_type]
pars_for_mean = {}
pars_for_mean["All"] = []
for element in elements_list:
if elements_type == 'specimens' and element in self.pmag_results_data['specimens']:
for fit in self.pmag_results_data['specimens'][element]:
if fit in self.bad_fits:
continue
if fit.name not in list(pars_for_mean.keys()):
pars_for_mean[fit.name] = []
try:
# is this fit to be included in mean
if mean_fit == 'All' or mean_fit == fit.name:
pars = fit.get(dirtype)
if pars == {} or pars == None:
pars = self.get_PCA_parameters(
element, fit, fit.tmin, fit.tmax, dirtype, fit.PCA_type)
if pars == {} or pars == None:
print(("cannot calculate parameters for element %s and fit %s in calculate_high_level_mean leaving out of fisher mean, please check this value." % (
element, fit.name)))
continue
fit.put(element, dirtype, pars)
else:
continue
if "calculation_type" in list(pars.keys()) and pars["calculation_type"] == 'DE-BFP':
dec, inc, direction_type = pars["specimen_dec"], pars["specimen_inc"], 'p'
elif "specimen_dec" in list(pars.keys()) and "specimen_inc" in list(pars.keys()):
dec, inc, direction_type = pars["specimen_dec"], pars["specimen_inc"], 'l'
elif "dec" in list(pars.keys()) and "inc" in list(pars.keys()):
dec, inc, direction_type = pars["dec"], pars["inc"], 'l'
else:
print(
("-E- ERROR: can't find mean for specimen interpertation: %s , %s" % (element, fit.name)))
print(pars)
continue
# add for calculation
pars_for_mean[fit.name].append({'dec': float(dec), 'inc': float(
inc), 'direction_type': direction_type, 'element_name': element})
pars_for_mean["All"].append({'dec': float(dec), 'inc': float(
inc), 'direction_type': direction_type, 'element_name': element})
except KeyError:
print(
("KeyError in calculate_high_level_mean for element: " + str(element)))
continue
else:
try:
pars = self.high_level_means[elements_type][element][mean_fit][dirtype]
if "dec" in list(pars.keys()) and "inc" in list(pars.keys()):
dec, inc, direction_type = pars["dec"], pars["inc"], 'l'
else:
# print "-E- ERROR: can't find mean for element %s"%element
continue
except KeyError:
# print("KeyError in calculate_high_level_mean for element: " + str(element) + " please report to a dev")
continue
return pars_for_mean
|
def get_high_level_mean_pars(self, high_level_type, high_level_name, calculation_type, elements_type, mean_fit, dirtype)
|
Gets the Parameters of a mean of lower level data such as a Site
level Fisher mean of Specimen interpretations
Parameters
----------
high_level_type : 'samples','sites','locations','study'
high_level_name : sample, site, location, or study whose
data to which to apply the mean
calculation_type : 'Bingham','Fisher','Fisher by polarity'
elements_type : what to average: 'specimens', 'samples',
'sites' (Ron. ToDo allow VGP and maybe locations?)
mean_fit : name of interpretation to average if All uses all
figure out what level to average,and what elements to average
(specimen, samples, sites, vgp)
| 2.94434
| 2.894614
| 1.017179
|
if len(pars_for_mean) == 0:
return({})
elif len(pars_for_mean) == 1:
return ({"dec": float(pars_for_mean[0]['dec']), "inc": float(pars_for_mean[0]['inc']), "calculation_type": calculation_type, "n": 1})
# elif calculation_type =='Bingham':
# data=[]
# for pars in pars_for_mean:
# # ignore great circle
# if 'direction_type' in pars.keys() and 'direction_type'=='p':
# continue
# else:
# data.append([pars['dec'],pars['inc']])
# mpars=pmag.dobingham(data)
elif calculation_type == 'Fisher':
mpars = pmag.dolnp(pars_for_mean, 'direction_type')
elif calculation_type == 'Fisher by polarity':
mpars = pmag.fisher_by_pol(pars_for_mean)
for key in list(mpars.keys()):
mpars[key]['n_planes'] = 0
mpars[key]['calculation_type'] = 'Fisher'
mpars['calculation_type'] = calculation_type
return mpars
|
def calculate_mean(self, pars_for_mean, calculation_type)
|
Uses pmag.dolnp or pmag.fisher_by_pol to do a fisher mean or fisher
mean by polarity on the list of dictionaries in pars for mean
Parameters
----------
pars_for_mean : list of dictionaries with all data to average
calculation_type : type of mean to take (options: Fisher,
Fisher by polarity)
Returns
-------
mpars : dictionary with information of mean or empty dictionary
TODO : put Bingham statistics back in once a method for displaying
them is figured out
| 3.740124
| 2.576951
| 1.451376
|
high_level_type = str(self.level_box.GetValue())
if high_level_type == 'sample':
high_level_type = 'samples'
if high_level_type == 'site':
high_level_type = 'sites'
if high_level_type == 'location':
high_level_type = 'locations'
high_level_name = str(self.level_names.GetValue())
calculation_type = str(self.mean_type_box.GetValue())
elements_type = self.UPPER_LEVEL_SHOW
if self.ie_open:
self.ie.mean_type_box.SetStringSelection(calculation_type)
self.calculate_high_level_mean(
high_level_type, high_level_name, calculation_type, elements_type, self.mean_fit)
|
def calculate_high_levels_data(self)
|
calculates high level mean data for the high level mean plot using
information in level_box, level_names, mean_type_box, and
mean_fit_box also updates the information in the ie to match high
level mean data in main GUI.
| 3.696377
| 2.799165
| 1.320529
|
new_Data_info = self.get_data_info()
new_Data, new_Data_hierarchy = self.get_data()
if not new_Data:
print("Data read in failed when reseting, aborting reset")
return
else:
self.Data, self.Data_hierarchy, self.Data_info = new_Data, new_Data_hierarchy, new_Data_info
if reset_interps:
self.pmag_results_data = {}
for level in ['specimens', 'samples', 'sites', 'locations', 'study']:
self.pmag_results_data[level] = {}
self.high_level_means = {}
high_level_means = {}
for high_level in ['samples', 'sites', 'locations', 'study']:
if high_level not in list(self.high_level_means.keys()):
self.high_level_means[high_level] = {}
# get list of sites
self.locations = list(self.Data_hierarchy['locations'].keys())
self.locations.sort() # get list of sites
# get list of sites
self.sites = list(self.Data_hierarchy['sites'].keys())
self.sites.sort(key=spec_key_func) # get list of sites
self.samples = [] # sort the samples within each site
for site in self.sites:
self.samples.extend(
sorted(self.Data_hierarchy['sites'][site]['samples'], key=spec_key_func))
self.specimens = [] # sort the specimens within each sample
for samp in self.samples:
self.specimens.extend(
sorted(self.Data_hierarchy['samples'][samp]['specimens'], key=spec_key_func))
# --------------------------------------------------------------------
# initialize first specimen in list as current specimen
# --------------------------------------------------------------------
if self.s in self.specimens:
pass
elif len(self.specimens) > 0:
self.select_specimen(str(self.specimens[0]))
else:
self.select_specimen("")
try:
self.sample = self.Data_hierarchy['sample_of_specimen'][self.s]
except KeyError:
self.sample = ""
try:
self.site = self.Data_hierarchy['site_of_specimen'][self.s]
except KeyError:
self.site = ""
if self.Data and reset_interps:
self.update_pmag_tables()
if self.ie_open:
self.ie.specimens_list = self.specimens
|
def quiet_reset_backend(self, reset_interps=True)
|
Doesn't update plots or logger or any visable data but resets all
measurement data, hierarchy data, and optionally resets
intepretations.
Parameters
----------
reset_interps : bool to tell the function to reset fits or
not.
| 2.764244
| 2.76741
| 0.998856
|
if warn_user and not self.data_loss_warning():
return False
# reset backend, including get_data(), get_data_info()
self.quiet_reset_backend(reset_interps=reset_interps)
# reset specimens box
self.specimens_box.SetItems(self.specimens)
self.specimens_box.SetStringSelection(str(self.s))
# reset site level means box
self.level_names.Clear()
self.level_names.AppendItems(self.sites)
if self.sites:
self.level_names.SetSelection(0)
# reset coordinate system
self.COORDINATE_SYSTEM, self.coordinate_list = self.get_coordinate_system()
self.coordinates_box.Clear()
self.coordinates_box.AppendItems(self.coordinate_list)
self.coordinates_box.SetStringSelection(self.COORDINATE_SYSTEM)
# get cart rot
self.initialize_CART_rot(str(self.s))
# draw everything
if self.Data:
if not self.current_fit:
self.draw_figure(self.s)
self.update_selection()
else:
self.Add_text()
self.update_fit_boxes()
if self.ie_open:
self.ie.update_editor()
|
def reset_backend(self, warn_user=True, reset_interps=True)
|
Resets GUI data and updates GUI displays such as plots, boxes, and
logger
Parameters
----------
warn_user : bool which decides if a warning dialog is displayed to
the user to ask about reseting data
reset_interps : bool which decides if interpretations are read in
for pmag tables or left alone
| 4.837227
| 4.876748
| 0.991896
|
self.initialize_CART_rot(self.s)
if str(self.s) in self.pmag_results_data['specimens']:
for fit in self.pmag_results_data['specimens'][self.s]:
if fit.get('specimen') and 'calculation_type' in fit.get('specimen'):
fit.put(self.s, 'specimen', self.get_PCA_parameters(
self.s, fit, fit.tmin, fit.tmax, 'specimen', fit.get('specimen')['calculation_type']))
if len(self.Data[self.s]['zijdblock_geo']) > 0 and fit.get('geographic') and 'calculation_type' in fit.get('geographic'):
fit.put(self.s, 'geographic', self.get_PCA_parameters(
self.s, fit, fit.tmin, fit.tmax, 'geographic', fit.get('geographic')['calculation_type']))
if len(self.Data[self.s]['zijdblock_tilt']) > 0 and fit.get('tilt-corrected') and 'calculation_type' in fit.get('tilt-corrected'):
fit.put(self.s, 'tilt-corrected', self.get_PCA_parameters(self.s, fit, fit.tmin,
fit.tmax, 'tilt-corrected', fit.get('tilt-corrected')['calculation_type']))
|
def recalculate_current_specimen_interpreatations(self)
|
recalculates all interpretations on all specimens for all coordinate
systems. Does not display recalcuated data.
| 2.69428
| 2.652231
| 1.015854
|
if specimen not in self.Data:
print(
("no measurement data found loaded for specimen %s and will be ignored" % (specimen)))
return (None, None)
if self.Data[specimen]['measurement_step_unit'] == "C":
if float(tmin0) == 0 or float(tmin0) == 273:
tmin = "0"
else:
tmin = "%.0fC" % (float(tmin0)-273)
if float(tmax0) == 0 or float(tmax0) == 273:
tmax = "0"
else:
tmax = "%.0fC" % (float(tmax0)-273)
elif self.Data[specimen]['measurement_step_unit'] == "mT":
if float(tmin0) == 0:
tmin = "0"
else:
tmin = "%.1fmT" % (float(tmin0)*1000)
if float(tmax0) == 0:
tmax = "0"
else:
tmax = "%.1fmT" % (float(tmax0)*1000)
else: # combimned experiment T:AF
if float(tmin0) == 0:
tmin = "0"
elif "%.0fC" % (float(tmin0)-273) in self.Data[specimen]['zijdblock_steps']:
tmin = "%.0fC" % (float(tmin0)-273)
elif "%.1fmT" % (float(tmin0)*1000) in self.Data[specimen]['zijdblock_steps']:
tmin = "%.1fmT" % (float(tmin0)*1000)
else:
tmin = None
if float(tmax0) == 0:
tmax = "0"
elif "%.0fC" % (float(tmax0)-273) in self.Data[specimen]['zijdblock_steps']:
tmax = "%.0fC" % (float(tmax0)-273)
elif "%.1fmT" % (float(tmax0)*1000) in self.Data[specimen]['zijdblock_steps']:
tmax = "%.1fmT" % (float(tmax0)*1000)
else:
tmax = None
return tmin, tmax
|
def parse_bound_data(self, tmin0, tmax0, specimen)
|
converts Kelvin/Tesla temperature/AF data from the MagIC/Redo format
to that of Celsius/milliTesla which is used by the GUI as it is
often more intuitive
Parameters
----------
tmin0 : the input temperature/AF lower bound value to convert
tmax0 : the input temperature/AF upper bound value to convert
specimen : the specimen these bounds are for
tmin : the converted lower bound temperature/AF or None if input
format was wrong
tmax : the converted upper bound temperature/AF or None if the input
format was wrong
| 1.774879
| 1.710535
| 1.037616
|
recs = {}
recs = deepcopy(old_recs)
headers = []
for rec in recs:
for key in list(rec.keys()):
if key not in headers:
headers.append(key)
for rec in recs:
for header in headers:
if header not in list(rec.keys()):
rec[header] = ""
return recs
|
def merge_pmag_recs(self, old_recs)
|
Takes in a list of dictionaries old_recs and returns a list of
dictionaries where every dictionary in the returned list has the
same keys as all the others.
Parameters
----------
old_recs : list of dictionaries to fix
Returns
-------
recs : list of dictionaries with same keys
| 2.210908
| 2.250975
| 0.9822
|
try:
fit_index = self.pmag_results_data['specimens'][self.s].index(
self.current_fit)
except KeyError:
fit_index = None
except ValueError:
fit_index = None
# sets self.s to specimen calculates params etc.
self.initialize_CART_rot(specimen)
self.list_bound_loc = 0
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.s != self.specimens_box.GetValue():
self.specimens_box.SetValue(self.s)
|
def select_specimen(self, specimen)
|
Goes through the calculations necessary to plot measurement data for
specimen and sets specimen as current GUI specimen, also attempts to
handle changing current fit.
| 4.126829
| 3.8148
| 1.081794
|
if self.total_num_of_interpertations() == 0:
print("There are no interpretations")
return True
if message == None:
message = "All interpretations will be deleted all unsaved data will be irretrievable, continue?"
dlg = wx.MessageDialog(self, caption="Delete?",
message=message, style=wx.OK | wx.CANCEL)
result = self.show_dlg(dlg)
dlg.Destroy()
if result != wx.ID_OK:
return False
for specimen in list(self.pmag_results_data['specimens'].keys()):
self.pmag_results_data['specimens'][specimen] = []
# later on when high level means are fixed remove the bellow loop and loop over pmag_results_data
for high_level_type in ['samples', 'sites', 'locations', 'study']:
self.high_level_means[high_level_type] = {}
self.current_fit = None
if self.ie_open:
self.ie.update_editor()
return True
|
def clear_interpretations(self, message=None)
|
Clears all specimen interpretations
Parameters
----------
message : message to display when warning the user that all
fits will be deleted. If None default message is used (None is
default)
| 5.609351
| 5.310627
| 1.05625
|
meas_index, ind_data = 0, []
for i, meas_data in enumerate(self.mag_meas_data):
if meas_data['er_specimen_name'] == self.s:
ind_data.append(i)
meas_index = ind_data[g_index]
self.Data[self.s]['measurement_flag'][g_index] = 'g'
if len(self.Data[self.s]['zijdblock'][g_index]) < 6:
self.Data[self.s]['zijdblock'][g_index].append('g')
self.Data[self.s]['zijdblock'][g_index][5] = 'g'
if 'zijdblock_geo' in self.Data[self.s] and g_index < len(self.Data[self.s]['zijdblock_geo']):
if len(self.Data[self.s]['zijdblock_geo'][g_index]) < 6:
self.Data[self.s]['zijdblock_geo'][g_index].append('g')
self.Data[self.s]['zijdblock_geo'][g_index][5] = 'g'
if 'zijdblock_tilt' in self.Data[self.s] and g_index < len(self.Data[self.s]['zijdblock_tilt']):
if len(self.Data[self.s]['zijdblock_tilt'][g_index]) < 6:
self.Data[self.s]['zijdblock_tilt'][g_index].append('g')
self.Data[self.s]['zijdblock_tilt'][g_index][5] = 'g'
self.mag_meas_data[meas_index]['measurement_flag'] = 'g'
if self.data_model == 3.0:
meas_name = str(self.Data[self.s]['measurement_names'][g_index])
mdf = self.con.tables['measurements'].df
# check for multiple measurements with the same name
if not isinstance(mdf.loc[meas_name], pd.Series):
res = self.user_warning("Your measurements table has non-unique measurement names.\nYou may end up marking more than one measurement as good.\nRight click this measurement again to undo.")
# mark measurement as good
mdf.loc[meas_name, 'quality'] = 'g'
|
def mark_meas_good(self, g_index)
|
Marks the g_index'th measuremnt of current specimen good
Parameters
----------
g_index : int that gives the index of the measurement to mark good,
indexed from 0
| 2.422352
| 2.427228
| 0.997991
|
if spec == None:
for spec, fits in list(self.pmag_results_data['specimens'].items()):
if fit in fits:
break
samp = self.Data_hierarchy['sample_of_specimen'][spec]
if 'sample_orientation_flag' not in self.Data_info['er_samples'][samp]:
self.Data_info['er_samples'][samp]['sample_orientation_flag'] = 'g'
samp_flag = self.Data_info['er_samples'][samp]['sample_orientation_flag']
if samp_flag == 'g':
self.bad_fits.remove(fit)
return True
else:
self.user_warning(
"Cannot mark this interpretation good its sample orientation has been marked bad")
return False
|
def mark_fit_good(self, fit, spec=None)
|
Marks fit good so it is used in high level means
Parameters
----------
fit : fit to mark good
spec : specimen of fit to mark good (optional though runtime will
increase if not provided)
| 5.010081
| 5.042799
| 0.993512
|
if fit not in self.bad_fits:
self.bad_fits.append(fit)
return True
else:
return False
|
def mark_fit_bad(self, fit)
|
Marks fit bad so it is excluded from high level means
Parameters
----------
fit : fit to mark bad
| 2.581602
| 2.970734
| 0.869012
|
if "specimen" not in self.spec_data.columns or \
"meas_step_min" not in self.spec_data.columns or \
"meas_step_max" not in self.spec_data.columns or \
"meas_step_unit" not in self.spec_data.columns or \
"method_codes" not in self.spec_data.columns:
return
if "dir_comp" in self.spec_data.columns:
fnames = 'dir_comp'
elif "dir_comp_name" in self.spec_data.columns:
fnames = 'dir_comp_name'
else:
fnames = 'dir_comp'
self.spec_data['dir_comp'] = 'Fit 1'
#print("No specimen interpretation name found in specimens.txt")
#return
if "result_quality" not in self.spec_data.columns:
self.spec_data["result_quality"] = "g"
if "dir_tilt_correction" not in self.spec_data.columns:
self.spec_data["dir_tilt_correction"] = ""
fdict = self.spec_data[['specimen', fnames, 'meas_step_min', 'meas_step_max', 'meas_step_unit',
'dir_tilt_correction', 'method_codes', 'result_quality']].to_dict("records")
for i in range(len(fdict)):
spec = fdict[i]['specimen']
if spec not in self.specimens:
print(("-E- specimen %s does not exist in measurement data" % (spec)))
continue
fname = fdict[i][fnames]
if fname == None or (spec in list(self.pmag_results_data['specimens'].keys()) and fname in [x.name for x in self.pmag_results_data['specimens'][spec]]):
continue
if fdict[i]['meas_step_unit'] == "K":
fmin = int(float(fdict[i]['meas_step_min'])-273)
fmax = int(float(fdict[i]['meas_step_max'])-273)
if fmin == 0:
fmin = str(fmin)
else:
fmin = str(fmin)+"C"
if fmax == 0:
fmax = str(fmax)
else:
fmax = str(fmax)+"C"
elif fdict[i]['meas_step_unit'] == "T":
fmin = float(fdict[i]['meas_step_min'])*1000
fmax = float(fdict[i]['meas_step_max'])*1000
if fmin == 0:
fmin = str(int(fmin))
else:
fmin = str(fmin)+"mT"
if fmax == 0:
fmax = str(int(fmax))
else:
fmax = str(fmax)+"mT"
else:
fmin = fdict[i]['meas_step_min']
fmax = fdict[i]['meas_step_max']
PCA_types = ["DE-BFL", "DE-BFL-A", "DE-BFL-O", "DE-FM", "DE-BFP"]
PCA_type_list = [x for x in str(fdict[i]['method_codes']).split(
':') if x.strip() in PCA_types]
if len(PCA_type_list) > 0:
PCA_type = PCA_type_list[0].strip()
else:
PCA_type = "DE-BFL"
fit = self.add_fit(spec, fname, fmin, fmax, PCA_type)
if fdict[i]['result_quality'] == 'b':
self.bad_fits.append(fit)
|
def get_interpretations3(self)
|
Used instead of update_pmag_tables in data model 3.0 to fetch
interpretations from contribution objects
| 2.308936
| 2.229665
| 1.035553
|
# default
preferences = {}
preferences['gui_resolution'] = 100.
preferences['show_Zij_treatments'] = True
preferences['show_Zij_treatments_steps'] = 2.
preferences['show_eqarea_treatments'] = False
preferences['auto_save'] = True
# preferences['show_statistics_on_gui']=["int_n","int_ptrm_n","frac","scat","gmax","b_beta","int_mad","dang","f","fvds","g","q","drats"]#,'ptrms_dec','ptrms_inc','ptrms_mad','ptrms_angle']
#
# try to read preferences file:
#user_data_dir = find_pmag_dir.find_user_data_dir("demag_gui")
# if not user_data_dir:
# return preferences
# if os.path.exists(user_data_dir):
# pref_file = os.path.join(user_data_dir, "demag_gui_preferences.json")
# if os.path.exists(pref_file):
# with open(pref_file, "r") as pfile:
# return json.load(pfile)
return preferences
|
def get_preferences(self)
|
Gets preferences for certain display variables from
zeq_gui_preferences.
| 6.469159
| 6.245807
| 1.03576
|
DATA = {}
try:
with open(path, 'r') as finput:
lines = list(finput.readlines()[1:])
except FileNotFoundError:
return []
# fin=open(path,'r')
# fin.readline()
line = lines[0]
header = line.strip('\n').split('\t')
error_strings = []
for line in lines[1:]:
tmp_data = {}
tmp_line = line.strip('\n').split('\t')
for i in range(len(tmp_line)):
tmp_data[header[i]] = tmp_line[i]
if tmp_data[sort_by_this_name] in list(DATA.keys()):
error_string = "-E- ERROR: magic file %s has more than one line for %s %s" % (
path, sort_by_this_name, tmp_data[sort_by_this_name])
# only print each error message once
if error_string not in error_strings:
print(error_string)
error_strings.append(error_string)
DATA[tmp_data[sort_by_this_name]] = tmp_data
# fin.close()
finput.close()
return(DATA)
|
def read_magic_file(self, path, sort_by_this_name)
|
reads a magic formated data file from path and sorts the keys
according to sort_by_this_name
Parameters
----------
path : path to file to read
sort_by_this_name : variable to sort data by
| 2.541956
| 2.559273
| 0.993234
|
cont = self.user_warning(
"LSQ import only works if all measurements are present and not averaged during import from magnetometer files to magic format. Do you wish to continue reading interpretations?")
if not cont:
return
self.clear_interpretations(
message=)
old_s = self.s
for specimen in self.specimens:
self.select_specimen(specimen)
for i in range(len(self.Data[specimen]['zijdblock'])):
self.mark_meas_good(i)
self.select_specimen(old_s)
print("Reading LSQ file")
interps = read_LSQ(LSQ_file)
for interp in interps:
specimen = interp['er_specimen_name']
if specimen not in self.specimens:
print(
("specimen %s has no registered measurement data, skipping interpretation import" % specimen))
continue
PCA_type = interp['magic_method_codes'].split(':')[0]
tmin = self.Data[specimen]['zijdblock_steps'][interp['measurement_min_index']]
tmax = self.Data[specimen]['zijdblock_steps'][interp['measurement_max_index']]
if 'specimen_comp_name' in list(interp.keys()):
name = interp['specimen_comp_name']
else:
name = None
new_fit = self.add_fit(specimen, name, tmin, tmax, PCA_type)
if 'bad_measurement_index' in list(interp.keys()):
old_s = self.s
self.select_specimen(specimen)
for bmi in interp["bad_measurement_index"]:
try:
self.mark_meas_bad(bmi)
except IndexError:
print(
"Magic Measurments length does not match that recorded in LSQ file")
self.select_specimen(old_s)
if self.ie_open:
self.ie.update_editor()
self.update_selection()
|
def read_from_LSQ(self, LSQ_file)
|
Clears all current interpretations and replaces them with
interpretations read from LSQ file.
Parameters
----------
LSQ_file : path to LSQ file to read in
| 4.682825
| 4.623401
| 1.012853
|
if not self.clear_interpretations():
return
print("-I- read redo file and processing new bounds")
fin = open(redo_file, 'r')
new_s = ""
for Line in fin.read().splitlines():
line = Line.split('\t')
specimen = line[0]
if specimen.startswith("current_"):
specimen = specimen.lstrip("current_")
new_s = specimen
if len(line) < 6:
continue
if len(line) < 6:
print(("insuffecent data for specimen %s and fit %s" %
(line[0], line[4])))
continue
if len(line) == 6:
line.append('g')
if specimen not in self.specimens:
print(
("specimen %s not found in this data set and will be ignored" % (specimen)))
continue
tmin, tmax = self.parse_bound_data(line[2], line[3], specimen)
new_fit = self.add_fit(
specimen, line[4], tmin, tmax, line[1], line[5])
if line[6] == 'b' and new_fit != None:
self.bad_fits.append(new_fit)
fin.close()
if new_s != "":
self.select_specimen(new_s)
if (self.s not in self.pmag_results_data['specimens']) or (not self.pmag_results_data['specimens'][self.s]):
self.current_fit = None
else:
self.current_fit = self.pmag_results_data['specimens'][self.s][-1]
self.calculate_high_levels_data()
if self.ie_open:
self.ie.update_editor()
self.update_selection()
|
def read_redo_file(self, redo_file)
|
Reads a .redo formated file and replaces all current interpretations
with interpretations taken from the .redo file
Parameters
----------
redo_file : path to .redo file to read
| 3.913979
| 3.929784
| 0.995978
|
new_WD = os.path.abspath(new_WD)
if not os.path.isdir(new_WD):
return
self.WD = new_WD
if not meas_file:
if self.data_model == None:
if os.path.isfile(os.path.join(self.WD, "measurements.txt")) and os.path.isfile(os.path.join(self.WD, "magic_measurements.txt")):
ui_dialog = demag_dialogs.user_input(self, ['data_model'], parse_funcs=[
float], heading="More than one measurement file found in CWD with different data models please input prefered data model (2.5,3.0)", values=[3])
self.show_dlg(ui_dialog)
ui_data = ui_dialog.get_values()
self.data_model = ui_data[1]['data_model']
elif os.path.isfile(os.path.join(self.WD, "measurements.txt")):
self.data_model = 3.0
elif os.path.isfile(os.path.join(self.WD, "magic_measurements.txt")):
self.data_model = 2.5
else:
self.user_warning(
"No measurement file found in chosen directory")
self.data_model = 3
try:
self.data_model = float(self.data_model)
if int(self.data_model) == 3:
meas_file = os.path.join(self.WD, "measurements.txt")
elif int(self.data_model) == 2:
meas_file = os.path.join(self.WD, "magic_measurements.txt")
else:
meas_file = ''
self.data_model = 3
except (ValueError, TypeError) as e:
self.user_warning(
"Provided data model is unrecognized or invalid, assuming you want data model 3")
self.data_model = 3
if os.path.isfile(meas_file):
self.magic_file = meas_file
else:
self.magic_file = self.choose_meas_file()
if not self.data_model:
self.data_model = 3
|
def change_WD(self, new_WD, meas_file="")
|
Changes Demag GUI's current WD to new_WD if possible
Parameters
----------
new_WD : WD to change to current GUI's WD
| 2.726296
| 2.744209
| 0.993472
|
# redirect terminal output
self.old_stdout = sys.stdout
sys.stdout = open(os.path.join(self.WD, "demag_gui.log"), 'w+')
|
def init_log_file(self)
|
redirects stdout to a log file to prevent printing to a hanging
terminal when dealing with the compiled binary.
| 6.857419
| 6.265401
| 1.09449
|
crit_list = list(self.acceptance_criteria.keys())
crit_list.sort()
rec = {}
rec['pmag_criteria_code'] = "ACCEPT"
# rec['criteria_definition']=""
rec['criteria_definition'] = "acceptance criteria for study"
rec['er_citation_names'] = "This study"
for crit in crit_list:
if type(self.acceptance_criteria[crit]['value']) == str:
if self.acceptance_criteria[crit]['value'] != "-999" and self.acceptance_criteria[crit]['value'] != "":
rec[crit] = self.acceptance_criteria[crit]['value']
elif type(self.acceptance_criteria[crit]['value']) == int:
if self.acceptance_criteria[crit]['value'] != -999:
rec[crit] = "%.i" % (
self.acceptance_criteria[crit]['value'])
elif type(self.acceptance_criteria[crit]['value']) == float:
if float(self.acceptance_criteria[crit]['value']) == -999:
continue
decimal_points = self.acceptance_criteria[crit]['decimal_points']
if decimal_points != -999:
command = "rec[crit]='%%.%sf'%%(self.acceptance_criteria[crit]['value'])" % (
decimal_points)
exec(command)
else:
rec[crit] = "%e" % (
self.acceptance_criteria[crit]['value'])
pmag.magic_write(os.path.join(self.WD, "pmag_criteria.txt"), [
rec], "pmag_criteria")
|
def write_acceptance_criteria_to_file(self)
|
Writes current GUI acceptance criteria to criteria.txt or
pmag_criteria.txt depending on data model
| 2.383583
| 2.281608
| 1.044694
|
if not self.test_mode:
dlg.Center()
return dlg.ShowModal()
else:
return dlg.GetAffirmativeId()
|
def show_dlg(self, dlg)
|
Abstraction function that is to be used instead of dlg.ShowModal
Parameters
----------
dlg : dialog to ShowModal if possible
| 4.740394
| 5.055752
| 0.937624
|
dlg = wx.DirDialog(self, "Choose a directory:", defaultPath=self.currentDirectory,
style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON | wx.DD_CHANGE_DIR)
ok = self.show_dlg(dlg)
if ok == wx.ID_OK:
new_WD = dlg.GetPath()
dlg.Destroy()
else:
new_WD = os.getcwd()
dlg.Destroy()
return new_WD
|
def get_DIR(self)
|
Dialog that allows user to choose a working directory
| 2.572845
| 2.354439
| 1.092764
|
dlg = wx.FileDialog(
self, message="Please choose a measurement file",
defaultDir=self.WD,
defaultFile="measurements.txt",
wildcard="measurement files (*.magic,*.txt)|*.magic;*.txt",
style=wx.FD_OPEN | wx.FD_CHANGE_DIR
)
if self.show_dlg(dlg) == wx.ID_OK:
meas_file = dlg.GetPath()
dlg.Destroy()
else:
meas_file = ''
self.data_model = 2.5
dlg.Destroy()
return meas_file
|
def choose_meas_file(self, event=None)
|
Opens a dialog allowing the user to pick a measurement file
| 3.049778
| 2.966636
| 1.028026
|
dlg = wx.MessageDialog(self, caption=caption,
message=message, style=wx.OK)
result = self.show_dlg(dlg)
dlg.Destroy()
|
def saved_dlg(self, message, caption='Saved:')
|
Shows a dialog that tells the user that a file has been saved
Parameters
----------
message : message to display to user
caption : title for dialog (default: "Saved:")
| 3.170097
| 4.269722
| 0.74246
|
dlg = wx.MessageDialog(self, message, caption,
wx.OK | wx.CANCEL | wx.ICON_WARNING)
if self.show_dlg(dlg) == wx.ID_OK:
continue_bool = True
else:
continue_bool = False
dlg.Destroy()
return continue_bool
|
def user_warning(self, message, caption='Warning!')
|
Shows a dialog that warns the user about some action
Parameters
----------
message : message to display to user
caption : title for dialog (default: "Warning!")
Returns
-------
continue_bool : True or False
| 2.495261
| 2.224019
| 1.12196
|
window_list_specimens = [
'specimen_n', 'specimen_mad', 'specimen_dang', 'specimen_alpha95']
window_list_samples = ['sample_n', 'sample_n_lines',
'sample_n_planes', 'sample_k', 'sample_r', 'sample_alpha95']
window_list_sites = ['site_n', 'site_n_lines',
'site_n_planes', 'site_k', 'site_r', 'site_alpha95']
demag_gui_supported_criteria = window_list_specimens + \
window_list_samples+window_list_sites
if self.data_model == 3:
new_crits = []
for crit in demag_gui_supported_criteria:
new_crit = {}
command = "dia.set_%s.GetValue()" % (crit)
new_value = pmag.execute(command, dia=dia)
if new_value == None or new_value == '':
continue
d = findall(r"[-+]?\d*\.\d+|\d+", new_value)
if len(d) > 0:
d = d[0]
comp = new_value.strip(str(d))
if comp == '':
comp = '>='
if 'specimen' in crit:
col = "specimens."+map_magic.spec_magic2_2_magic3_map[crit]
elif 'sample' in crit:
col = "samples."+map_magic.samp_magic2_2_magic3_map[crit]
elif 'site' in crit:
col = "sites."+map_magic.site_magic2_2_magic3_map[crit]
else:
print("no way this like is impossible")
continue
new_crit['criterion'] = "ACCEPT"
new_crit['criterion_value'] = d
new_crit['criterion_operation'] = comp
new_crit['table_column'] = col
new_crit['citations'] = "This study"
new_crit['description'] = ''
new_crits.append(new_crit)
cdf = DataFrame(new_crits)
cdf = cdf.set_index("table_column")
cdf["table_column"] = cdf.index
cdf = cdf.reindex_axis(sorted(cdf.columns), axis=1)
if 'criteria' not in self.con.tables:
cols = ['criterion', 'criterion_value', 'criterion_operation',
'table_column', 'citations', 'description']
self.con.add_empty_magic_table('criteria', col_names=cols)
self.con.tables['criteria'].df = cdf
self.con.tables['criteria'].write_magic_file(dir_path=self.WD)
else:
for crit in demag_gui_supported_criteria:
command = "new_value=dia.set_%s.GetValue()" % (crit)
exec(command)
# empty box
if new_value == "":
self.acceptance_criteria[crit]['value'] = -999
continue
# box with no valid number
try:
float(new_value)
except:
self.show_crit_window_err_messege(crit)
continue
self.acceptance_criteria[crit]['value'] = float(new_value)
# message dialog
self.saved_dlg(message="changes saved to criteria")
self.write_acceptance_criteria_to_file()
dia.Destroy()
|
def on_close_criteria_box(self, dia)
|
Function called on close of change acceptance criteria dialog that
writes new criteria to the hardrive and sets new criteria as GUI's
current criteria.
Parameters
----------
dia : closed change criteria dialog
| 3.407257
| 3.388718
| 1.005471
|
dlg = wx.MessageDialog(
self, caption="Error:", message="not a vaild value for statistic %s\n ignoring value" % crit, style=wx.OK)
result = self.show_dlg(dlg)
if result == wx.ID_OK:
dlg.Destroy()
|
def show_crit_window_err_messege(self, crit)
|
error message if a valid naumber is not entered to criteria dialog
boxes
| 6.067196
| 5.987052
| 1.013386
|
self.clear_boxes()
# commented out to allow propogation of higher level viewing state
self.clear_high_level_pars()
if self.UPPER_LEVEL_SHOW != "specimens":
self.mean_type_box.SetValue("None")
# --------------------------
# check if the coordinate system in the window exists (if not change to "specimen" coordinate system)
# --------------------------
coordinate_system = self.coordinates_box.GetValue()
if coordinate_system == 'tilt-corrected' and \
len(self.Data[self.s]['zijdblock_tilt']) == 0:
self.coordinates_box.SetStringSelection('specimen')
elif coordinate_system == 'geographic' and \
len(self.Data[self.s]['zijdblock_geo']) == 0:
self.coordinates_box.SetStringSelection("specimen")
if coordinate_system != self.coordinates_box.GetValue() and self.ie_open:
self.ie.coordinates_box.SetStringSelection(
self.coordinates_box.GetValue())
self.ie.update_editor()
coordinate_system = self.coordinates_box.GetValue()
self.COORDINATE_SYSTEM = coordinate_system
# --------------------------
# update treatment list
# --------------------------
self.update_bounds_boxes()
# --------------------------
# update high level boxes
# --------------------------
high_level = self.level_box.GetValue()
old_string = self.level_names.GetValue()
new_string = old_string
if high_level == 'sample':
if self.s in self.Data_hierarchy['sample_of_specimen']:
new_string = self.Data_hierarchy['sample_of_specimen'][self.s]
else:
new_string = ''
if high_level == 'site':
if self.s in self.Data_hierarchy['site_of_specimen']:
new_string = self.Data_hierarchy['site_of_specimen'][self.s]
else:
new_string = ''
if high_level == 'location':
if self.s in self.Data_hierarchy['location_of_specimen']:
new_string = self.Data_hierarchy['location_of_specimen'][self.s]
else:
new_string = ''
self.level_names.SetValue(new_string)
if self.ie_open and new_string != old_string:
self.ie.level_names.SetValue(new_string)
self.ie.on_select_level_name(-1, True)
# --------------------------
# update PCA box
# --------------------------
self.update_PCA_box()
# update warning
self.generate_warning_text()
self.update_warning_box()
# update choices in the fit box
self.update_fit_boxes()
self.update_mean_fit_box()
# measurements text box
self.Add_text()
# draw figures
if self.current_fit:
self.draw_figure(self.s, False)
else:
self.draw_figure(self.s, True)
# update high level stats
self.update_high_level_stats()
# redraw interpretations
self.update_GUI_with_new_interpretation()
|
def update_selection(self)
|
Convenience function update display (figures, text boxes and
statistics windows) with a new selection of specimen
| 3.522596
| 3.446462
| 1.02209
|
self.warning_box.Clear()
if self.warning_text == "":
self.warning_box.AppendText("No Problems")
else:
self.warning_box.AppendText(self.warning_text)
|
def update_warning_box(self)
|
updates the warning box with whatever the warning_text variable
contains for this specimen
| 2.749197
| 2.353881
| 1.167942
|
self.update_fit_bounds_and_statistics()
self.draw_interpretations()
self.calculate_high_levels_data()
self.plot_high_levels_data()
|
def update_GUI_with_new_interpretation(self)
|
update statistics boxes and figures with a new interpretatiom when
selecting new temperature bound
| 9.716073
| 7.7774
| 1.24927
|
self.clear_high_level_pars()
dirtype = str(self.coordinates_box.GetValue())
if dirtype == 'specimen':
dirtype = 'DA-DIR'
elif dirtype == 'geographic':
dirtype = 'DA-DIR-GEO'
elif dirtype == 'tilt-corrected':
dirtype = 'DA-DIR-TILT'
if str(self.level_box.GetValue()) == 'sample':
high_level_type = 'samples'
elif str(self.level_box.GetValue()) == 'site':
high_level_type = 'sites'
elif str(self.level_box.GetValue()) == 'location':
high_level_type = 'locations'
elif str(self.level_box.GetValue()) == 'study':
high_level_type = 'study'
high_level_name = str(self.level_names.GetValue())
elements_type = self.UPPER_LEVEL_SHOW
if high_level_name in list(self.high_level_means[high_level_type].keys()):
mpars = []
for mf in list(self.high_level_means[high_level_type][high_level_name].keys()):
if mf in list(self.high_level_means[high_level_type][high_level_name].keys()) and self.mean_fit == 'All' or mf == self.mean_fit:
if dirtype in list(self.high_level_means[high_level_type][high_level_name][mf].keys()):
mpar = deepcopy(
self.high_level_means[high_level_type][high_level_name][mf][dirtype])
if 'n' in mpar and mpar['n'] == 1:
mpar['calculation_type'] = "Fisher:"+mf
mpars.append(mpar)
elif mpar['calculation_type'] == 'Fisher by polarity':
for k in list(mpar.keys()):
if k == 'color' or k == 'calculation_type':
continue
mpar[k]['calculation_type'] += ':'+k+':'+mf
mpar[k]['color'] = mpar['color']
if 'K' not in mpar[k] and 'k' in mpar[k]:
mpar[k]['K'] = mpar[k]['k']
if 'R' not in mpar[k] and 'r' in mpar[k]:
mpar[k]['R'] = mpar[k]['r']
if 'n_lines' not in mpar[k] and 'n' in mpar[k]:
mpar[k]['n_lines'] = mpar[k]['n']
mpars.append(mpar[k])
else:
mpar['calculation_type'] += ":"+mf
mpars.append(mpar)
self.switch_stats_button.SetRange(0, len(mpars)-1)
self.show_high_levels_pars(mpars)
if self.ie_open:
self.ie.switch_stats_button.SetRange(0, len(mpars)-1)
|
def update_high_level_stats(self)
|
updates high level statistics in bottom left of GUI.
| 2.608974
| 2.587101
| 1.008455
|
if self.s not in list(self.Data.keys()):
self.select_specimen(list(self.Data.keys())[0])
self.T_list = self.Data[self.s]['zijdblock_steps']
if self.current_fit:
self.tmin_box.SetItems(self.T_list)
self.tmax_box.SetItems(self.T_list)
if type(self.current_fit.tmin) == str and type(self.current_fit.tmax) == str:
self.tmin_box.SetStringSelection(self.current_fit.tmin)
self.tmax_box.SetStringSelection(self.current_fit.tmax)
if self.ie_open:
self.ie.update_bounds_boxes(self.T_list)
|
def update_bounds_boxes(self)
|
updates bounds boxes with bounds of current specimen and fit
| 3.173556
| 2.936481
| 1.080734
|
if self.s in list(self.pmag_results_data['specimens'].keys()):
if self.current_fit:
tmin = self.current_fit.tmin
tmax = self.current_fit.tmax
calculation_type = self.current_fit.PCA_type
else:
calculation_type = self.PCA_type_box.GetValue()
PCA_type = "None"
# update calculation type windows
if calculation_type == "DE-BFL":
PCA_type = "line"
elif calculation_type == "DE-BFL-A":
PCA_type = "line-anchored"
elif calculation_type == "DE-BFL-O":
PCA_type = "line-with-origin"
elif calculation_type == "DE-FM":
PCA_type = "Fisher"
elif calculation_type == "DE-BFP":
PCA_type = "plane"
else:
print("no PCA type found setting to line")
PCA_type = "line"
self.PCA_type_box.SetStringSelection(PCA_type)
|
def update_PCA_box(self)
|
updates PCA box with current fit's PCA type
| 3.892303
| 3.750348
| 1.037851
|
# update the fit box
self.update_fit_box(new_fit)
# select new fit
self.on_select_fit(None)
# update the high level fits box
self.update_mean_fit_box()
|
def update_fit_boxes(self, new_fit=False)
|
alters fit_box and mean_fit_box lists to match with changes in
specimen or new/removed interpretations
Parameters
----------
new_fit : boolean representing if there is a new fit
Alters
------
fit_box selection, tmin_box selection, tmax_box selection,
mean_fit_box selection, current_fit
| 5.896425
| 5.586118
| 1.05555
|
# get new fit data
if self.s in list(self.pmag_results_data['specimens'].keys()):
self.fit_list = list(
[x.name for x in self.pmag_results_data['specimens'][self.s]])
else:
self.fit_list = []
# find new index to set fit_box to
if not self.fit_list:
new_index = 'None'
elif new_fit:
new_index = len(self.fit_list) - 1
else:
if self.fit_box.GetValue() in self.fit_list:
new_index = self.fit_list.index(self.fit_box.GetValue())
else:
new_index = 'None'
# clear old box
self.fit_box.Clear()
# update fit box
self.fit_box.SetItems(self.fit_list)
fit_index = None
# select defaults
if new_index == 'None':
self.fit_box.SetStringSelection('None')
else:
self.fit_box.SetSelection(new_index)
|
def update_fit_box(self, new_fit=False)
|
alters fit_box lists to match with changes in specimen or new/
removed interpretations
Parameters
----------
new_fit : boolean representing if there is a new fit
Alters
------
fit_box selection and choices, current_fit
| 2.641599
| 2.7052
| 0.976489
|
self.mean_fit_box.Clear()
# update high level mean fit box
fit_index = None
if self.mean_fit in self.all_fits_list:
fit_index = self.all_fits_list.index(self.mean_fit)
self.all_fits_list = []
for specimen in self.specimens:
if specimen in self.pmag_results_data['specimens']:
for name in [x.name for x in self.pmag_results_data['specimens'][specimen]]:
if name not in self.all_fits_list:
self.all_fits_list.append(name)
self.mean_fit_box.SetItems(['None', 'All'] + self.all_fits_list)
# select defaults
if not isinstance(fit_index, type(None)):
self.mean_fit_box.SetValue(self.all_fits_list[fit_index])
elif self.mean_fit == 'All':
self.mean_fit_box.SetValue('All')
else:
self.mean_fit_box.SetValue('None')
self.mean_type_box.SetValue('None')
self.clear_high_level_pars()
self.update_toggleable_means_menu()
if self.ie_open:
self.ie.mean_fit_box.Clear()
self.ie.mean_fit_box.SetItems(['None', 'All'] + self.all_fits_list)
if fit_index:
self.ie.mean_fit_box.SetValue(self.all_fits_list[fit_index])
elif self.mean_fit == 'All':
self.ie.mean_fit_box.SetValue('All')
else:
self.ie.mean_fit_box.SetValue('None')
self.ie.mean_type_box.SetValue('None')
|
def update_mean_fit_box(self)
|
alters mean_fit_box list to match with changes in specimen or new/
removed interpretations
Alters
------
mean_fit_box selection and choices, mean_types_box string selection
| 2.268753
| 2.165225
| 1.047814
|
FONT_WEIGHT = self.GUI_RESOLUTION+(self.GUI_RESOLUTION-1)*5
font2 = wx.Font(12+min(1, FONT_WEIGHT), wx.SWISS,
wx.NORMAL, wx.NORMAL, False, self.font_type)
if self.mean_type_box.GetValue() != "None" and self.mean_fit_box.GetValue() != "None" and mpars:
if isinstance(mpars, list):
i = self.switch_stats_button.GetValue()
if i >= len(mpars):
print(("Cannot display statistics as mpars does not have index %d. Was given mpars %s, aborting." % (
i, str(mpars))))
return
self.show_high_levels_pars(mpars[i])
elif mpars["calculation_type"].startswith('Fisher'):
if "alpha95" in list(mpars.keys()):
for val in ['mean_type:calculation_type', 'dec:dec', 'inc:inc', 'alpha95:alpha95', 'K:K', 'R:R', 'n_lines:n_lines', 'n_planes:n_planes']:
val, ind = val.split(":")
COMMAND = % (
val, ind)
exec(COMMAND)
if self.ie_open:
ie = self.ie
if "alpha95" in list(mpars.keys()):
for val in ['mean_type:calculation_type', 'dec:dec', 'inc:inc', 'alpha95:alpha95', 'K:K', 'R:R', 'n_lines:n_lines', 'n_planes:n_planes']:
val, ind = val.split(":")
COMMAND = % (
val, ind)
exec(COMMAND)
elif mpars["calculation_type"].startswith('Fisher by polarity'):
i = self.switch_stats_button.GetValue()
keys = list(mpars.keys())
keys.remove('calculation_type')
if 'color' in keys:
keys.remove('color')
keys.sort()
name = keys[i % len(keys)]
mpars = mpars[name]
if type(mpars) != dict:
print(
("error in showing high level mean, reseaved %s" % str(mpars)))
return
if mpars["calculation_type"] == 'Fisher' and "alpha95" in list(mpars.keys()):
for val in ['mean_type:calculation_type', 'dec:dec', 'inc:inc', 'alpha95:alpha95', 'K:k', 'R:r', 'n_lines:n', 'n_planes:n_planes']:
val, ind = val.split(":")
if val == 'mean_type':
COMMAND = % (
val, mpars[ind] + ":" + name)
else:
COMMAND = % (
val, ind)
exec(COMMAND)
if self.ie_open:
ie = self.ie
if mpars["calculation_type"] == 'Fisher' and "alpha95" in list(mpars.keys()):
for val in ['mean_type:calculation_type', 'dec:dec', 'inc:inc', 'alpha95:alpha95', 'K:k', 'R:r', 'n_lines:n', 'n_planes:n_planes']:
val, ind = val.split(":")
if val == 'mean_type':
COMMAND = % (
val, mpars[ind] + ":" + name)
else:
COMMAND = % (
val, ind)
exec(COMMAND)
self.set_mean_stats_color()
|
def show_high_levels_pars(self, mpars)
|
shows in the high level mean display area in the bottom left of the
GUI the data in mpars.
| 2.786693
| 2.742781
| 1.01601
|
self.tmin_box.Clear()
self.tmin_box.SetStringSelection("")
if self.current_fit:
self.tmin_box.SetItems(self.T_list)
self.tmin_box.SetSelection(-1)
self.tmax_box.Clear()
self.tmax_box.SetStringSelection("")
if self.current_fit:
self.tmax_box.SetItems(self.T_list)
self.tmax_box.SetSelection(-1)
self.fit_box.Clear()
self.fit_box.SetStringSelection("")
if self.s in self.pmag_results_data['specimens'] and self.pmag_results_data['specimens'][self.s]:
self.fit_box.SetItems(
list([x.name for x in self.pmag_results_data['specimens'][self.s]]))
for parameter in ['dec', 'inc', 'n', 'mad', 'dang', 'alpha95']:
COMMAND = "self.s%s_window.SetValue('')" % parameter
exec(COMMAND)
COMMAND = "self.s%s_window.SetBackgroundColour(wx.Colour('grey'))" % parameter
exec(COMMAND)
|
def clear_boxes(self)
|
Clear all boxes
| 2.949156
| 2.926047
| 1.007898
|
for val in ['mean_type', 'dec', 'inc', 'alpha95', 'K', 'R', 'n_lines', 'n_planes']:
COMMAND = % (val)
exec(COMMAND)
if self.ie_open:
for val in ['mean_type', 'dec', 'inc', 'alpha95', 'K', 'R', 'n_lines', 'n_planes']:
COMMAND = % (val)
exec(COMMAND)
self.set_mean_stats_color()
|
def clear_high_level_pars(self)
|
clears all high level pars display boxes
| 5.819535
| 5.512957
| 1.05561
|
# use new measurement file and corresponding WD
meas_file = self.choose_meas_file()
WD = os.path.split(meas_file)[0]
self.WD = WD
self.magic_file = meas_file
# reset backend with new files
self.reset_backend()
|
def on_menu_import_meas_file(self, event)
|
Open measurement file, reset self.magic_file
and self.WD, and reset everything.
| 6.585809
| 4.139573
| 1.590939
|
if self.data_model == 3:
default_file = "criteria.txt"
else:
default_file = "pmag_criteria.txt"
read_sucsess = False
dlg = wx.FileDialog(
self, message="choose pmag criteria file",
defaultDir=self.WD,
defaultFile=default_file,
style=wx.FD_OPEN | wx.FD_CHANGE_DIR
)
if self.show_dlg(dlg) == wx.ID_OK:
criteria_file = dlg.GetPath()
print(("-I- Read new criteria file: %s" % criteria_file))
# check if this is a valid pmag_criteria file
try:
mag_meas_data, file_type = pmag.magic_read(criteria_file)
except:
dlg = wx.MessageDialog(
self, caption="Error", message="not a valid pmag_criteria file", style=wx.OK)
result = self.show_dlg(dlg)
if result == wx.ID_OK:
dlg.Destroy()
dlg.Destroy()
return
# initialize criteria
self.acceptance_criteria = self.read_criteria_file(criteria_file)
read_sucsess = True
dlg.Destroy()
if read_sucsess:
self.on_menu_change_criteria(None)
|
def on_menu_criteria_file(self, event)
|
read pmag_criteria.txt file
and open changecriteria dialog
| 2.913476
| 2.66693
| 1.092446
|
if event.LeftIsDown() or event.ButtonDClick():
return
elif self.zijderveld_setting == "Zoom":
self.zijderveld_setting = "Pan"
try:
self.toolbar1.pan('off')
except TypeError:
pass
elif self.zijderveld_setting == "Pan":
self.zijderveld_setting = "Zoom"
try:
self.toolbar1.zoom()
except TypeError:
pass
|
def right_click_zijderveld(self, event)
|
toggles between zoom and pan effects for the zijderveld on right
click
Parameters
----------
event : the wx.MouseEvent that triggered the call of this function
Alters
------
zijderveld_setting, toolbar1 setting
| 2.887792
| 2.247282
| 1.285015
|
if not array(self.CART_rot).any():
return
pos = event.GetPosition()
width, height = self.canvas1.get_width_height()
pos[1] = height - pos[1]
xpick_data, ypick_data = pos
xdata_org = list(self.CART_rot[:, 0]) + list(self.CART_rot[:, 0])
ydata_org = list(-1*self.CART_rot[:, 1]) + list(-1*self.CART_rot[:, 2])
data_corrected = self.zijplot.transData.transform(
vstack([xdata_org, ydata_org]).T)
xdata, ydata = data_corrected.T
xdata = list(map(float, xdata))
ydata = list(map(float, ydata))
e = 4e0
if self.zijderveld_setting == "Zoom":
self.canvas1.SetCursor(wx.Cursor(wx.CURSOR_CROSS))
else:
self.canvas1.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
for i, (x, y) in enumerate(zip(xdata, ydata)):
if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
self.canvas1.SetCursor(wx.Cursor(wx.CURSOR_HAND))
break
event.Skip()
|
def on_change_zijd_mouse_cursor(self, event)
|
If mouse is over data point making it selectable change the shape of
the cursor
Parameters
----------
event : the wx Mouseevent for that click
| 3.130604
| 3.208063
| 0.975855
|
if not array(self.CART_rot_good).any():
return
pos = event.GetPosition()
width, height = self.canvas1.get_width_height()
pos[1] = height - pos[1]
xpick_data, ypick_data = pos
xdata_org = list(
self.CART_rot_good[:, 0]) + list(self.CART_rot_good[:, 0])
ydata_org = list(-1*self.CART_rot_good[:, 1]) + \
list(-1*self.CART_rot_good[:, 2])
data_corrected = self.zijplot.transData.transform(
vstack([xdata_org, ydata_org]).T)
xdata, ydata = data_corrected.T
xdata = list(map(float, xdata))
ydata = list(map(float, ydata))
e = 4.0
index = None
for i, (x, y) in enumerate(zip(xdata, ydata)):
if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
index = i
break
if index != None:
steps = self.Data[self.s]['zijdblock_steps']
bad_count = self.Data[self.s]['measurement_flag'][:index].count(
'b')
if index > len(steps):
bad_count *= 2
if not self.current_fit:
self.on_btn_add_fit(event)
self.select_bounds_in_logger((index+bad_count) % len(steps))
|
def on_zijd_select(self, event)
|
Get mouse position on double click find the nearest interpretation
to the mouse
position then select that interpretation
Parameters
----------
event : the wx Mouseevent for that click
Alters
------
current_fit
| 4.230834
| 4.215012
| 1.003754
|
if not array(self.CART_rot).any():
return
pos = event.GetPosition()
width, height = self.canvas1.get_width_height()
pos[1] = height - pos[1]
xpick_data, ypick_data = pos
xdata_org = list(self.CART_rot[:, 0]) + list(self.CART_rot[:, 0])
ydata_org = list(-1*self.CART_rot[:, 1]) + list(-1*self.CART_rot[:, 2])
data_corrected = self.zijplot.transData.transform(
vstack([xdata_org, ydata_org]).T)
xdata, ydata = data_corrected.T
xdata = list(map(float, xdata))
ydata = list(map(float, ydata))
e = 4e0
index = None
for i, (x, y) in enumerate(zip(xdata, ydata)):
if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
index = i
break
if index != None:
steps = self.Data[self.s]['zijdblock']
if self.Data[self.s]['measurement_flag'][index % len(steps)] == "g":
self.mark_meas_bad(index % len(steps))
else:
self.mark_meas_good(index % len(steps))
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()
|
def on_zijd_mark(self, event)
|
Get mouse position on double right click find the interpretation in
range of mouse
position then mark that interpretation bad or good
Parameters
----------
event : the wx Mouseevent for that click
Alters
------
current_fit
| 4.331367
| 4.182798
| 1.035519
|
if event.LeftIsDown() or event.ButtonDClick():
return
elif self.specimen_EA_setting == "Zoom":
self.specimen_EA_setting = "Pan"
try:
self.toolbar2.pan('off')
except TypeError:
pass
elif self.specimen_EA_setting == "Pan":
self.specimen_EA_setting = "Zoom"
try:
self.toolbar2.zoom()
except TypeError:
pass
|
def right_click_specimen_equalarea(self, event)
|
toggles between zoom and pan effects for the specimen equal area on
right click
Parameters
----------
event : the wx.MouseEvent that triggered the call of this function
Alters
------
specimen_EA_setting, toolbar2 setting
| 3.296185
| 2.364549
| 1.394002
|
if not self.specimen_EA_xdata or not self.specimen_EA_ydata:
return
pos = event.GetPosition()
width, height = self.canvas2.get_width_height()
pos[1] = height - pos[1]
xpick_data, ypick_data = pos
xdata_org = self.specimen_EA_xdata
ydata_org = self.specimen_EA_ydata
data_corrected = self.specimen_eqarea.transData.transform(
vstack([xdata_org, ydata_org]).T)
xdata, ydata = data_corrected.T
xdata = list(map(float, xdata))
ydata = list(map(float, ydata))
e = 4e0
if self.specimen_EA_setting == "Zoom":
self.canvas2.SetCursor(wx.Cursor(wx.CURSOR_CROSS))
else:
self.canvas2.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
for i, (x, y) in enumerate(zip(xdata, ydata)):
if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
self.canvas2.SetCursor(wx.Cursor(wx.CURSOR_HAND))
break
event.Skip()
|
def on_change_specimen_mouse_cursor(self, event)
|
If mouse is over data point making it selectable change the shape of
the cursor
Parameters
----------
event : the wx Mouseevent for that click
| 2.919144
| 2.911278
| 1.002702
|
if not self.specimen_EA_xdata or not self.specimen_EA_ydata:
return
pos = event.GetPosition()
width, height = self.canvas2.get_width_height()
pos[1] = height - pos[1]
xpick_data, ypick_data = pos
xdata_org = self.specimen_EA_xdata
ydata_org = self.specimen_EA_ydata
data_corrected = self.specimen_eqarea.transData.transform(
vstack([xdata_org, ydata_org]).T)
xdata, ydata = data_corrected.T
xdata = list(map(float, xdata))
ydata = list(map(float, ydata))
e = 4e0
index = None
for i, (x, y) in enumerate(zip(xdata, ydata)):
if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
index = i
break
if index != None:
self.fit_box.SetSelection(index)
self.draw_figure(self.s, True)
self.on_select_fit(event)
|
def on_equalarea_specimen_select(self, event)
|
Get mouse position on double click find the nearest interpretation
to the mouse
position then select that interpretation
Parameters
----------
event : the wx Mouseevent for that click
Alters
------
current_fit
| 3.432068
| 3.461814
| 0.991407
|
if event.LeftIsDown():
return
elif self.high_EA_setting == "Zoom":
self.high_EA_setting = "Pan"
try:
self.toolbar4.pan('off')
except TypeError:
pass
elif self.high_EA_setting == "Pan":
self.high_EA_setting = "Zoom"
try:
self.toolbar4.zoom()
except TypeError:
pass
|
def right_click_high_equalarea(self, event)
|
toggles between zoom and pan effects for the high equal area on
right click
Parameters
----------
event : the wx.MouseEvent that triggered the call of this function
Alters
------
high_EA_setting, toolbar4 setting
| 3.573699
| 2.355994
| 1.516854
|
if self.ie_open and self.ie.show_box.GetValue() != "specimens":
return
pos = event.GetPosition()
width, height = self.canvas4.get_width_height()
pos[1] = height - pos[1]
xpick_data, ypick_data = pos
xdata_org = self.high_EA_xdata
ydata_org = self.high_EA_ydata
data_corrected = self.high_level_eqarea.transData.transform(
vstack([xdata_org, ydata_org]).T)
xdata, ydata = data_corrected.T
xdata = list(map(float, xdata))
ydata = list(map(float, ydata))
e = 4e0
if self.high_EA_setting == "Zoom":
self.canvas4.SetCursor(wx.Cursor(wx.CURSOR_CROSS))
else:
self.canvas4.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
if not self.high_EA_xdata or not self.high_EA_ydata:
return
for i, (x, y) in enumerate(zip(xdata, ydata)):
if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
self.canvas4.SetCursor(wx.Cursor(wx.CURSOR_HAND))
break
event.Skip()
|
def on_change_high_mouse_cursor(self, event)
|
If mouse is over data point making it selectable change the shape of
the cursor
Parameters
----------
event : the wx Mouseevent for that click
| 3.591825
| 3.557468
| 1.009658
|
if self.ie_open and self.ie.show_box.GetValue() != "specimens":
return
if not self.high_EA_xdata or not self.high_EA_ydata:
return
if fig == None:
fig = self.high_level_eqarea
if canvas == None:
canvas = self.canvas4
pos = event.GetPosition()
width, height = canvas.get_width_height()
pos[1] = height - pos[1]
xpick_data, ypick_data = pos
xdata_org = self.high_EA_xdata
ydata_org = self.high_EA_ydata
data_corrected = fig.transData.transform(
vstack([xdata_org, ydata_org]).T)
xdata, ydata = data_corrected.T
xdata = list(map(float, xdata))
ydata = list(map(float, ydata))
e = 4e0
index = None
for i, (x, y) in enumerate(zip(xdata, ydata)):
if 0 < sqrt((x-xpick_data)**2. + (y-ypick_data)**2.) < e:
index = i
break
if index != None:
disp_fit_name = self.mean_fit_box.GetValue()
if self.level_box.GetValue() == 'sample':
high_level_type = 'samples'
if self.level_box.GetValue() == 'site':
high_level_type = 'sites'
if self.level_box.GetValue() == 'location':
high_level_type = 'locations'
if self.level_box.GetValue() == 'study':
high_level_type = 'study'
high_level_name = str(self.level_names.GetValue())
calculation_type = str(self.mean_type_box.GetValue())
elements_type = self.UPPER_LEVEL_SHOW
elements_list = self.Data_hierarchy[high_level_type][high_level_name][elements_type]
new_fit_index = 0
for i, specimen in enumerate(elements_list):
if disp_fit_name == "All" and \
specimen in self.pmag_results_data[elements_type]:
l = 0
for fit in self.pmag_results_data[elements_type][specimen]:
l += 1
else:
try:
disp_fit_index = map(
lambda x: x.name, self.pmag_results_data[elements_type][specimen]).index(disp_fit_name)
if self.pmag_results_data[elements_type][specimen][disp_fit_index] in self.bad_fits:
l = 0
else:
l = 1
except IndexError:
l = 0
except KeyError:
l = 0
except ValueError:
l = 0
if index < l:
self.specimens_box.SetStringSelection(specimen)
self.select_specimen(specimen)
self.draw_figure(specimen, False)
if disp_fit_name == "All":
new_fit_index = index
else:
new_fit_index = disp_fit_index
break
index -= l
self.update_fit_box()
self.fit_box.SetSelection(new_fit_index)
self.on_select_fit(event)
if disp_fit_name != "All":
self.mean_fit = self.current_fit.name
self.mean_fit_box.SetSelection(2+new_fit_index)
self.update_selection()
else:
self.Add_text()
if self.ie_open:
self.ie.change_selected(self.current_fit)
|
def on_equalarea_high_select(self, event, fig=None, canvas=None)
|
Get mouse position on double click find the nearest interpretation
to the mouse position then select that interpretation
Parameters
----------
event : the wx Mouseevent for that click
Alters
------
current_fit, s, mean_fit, fit_box selection, mean_fit_box selection,
specimens_box selection, tmin_box selection, tmax_box selection
| 3.175258
| 3.113331
| 1.019891
|
self.selected_meas = []
if self.COORDINATE_SYSTEM == 'geographic':
zijdblock = self.Data[self.s]['zijdblock_geo']
elif self.COORDINATE_SYSTEM == 'tilt-corrected':
zijdblock = self.Data[self.s]['zijdblock_tilt']
else:
zijdblock = self.Data[self.s]['zijdblock']
tmin_index, tmax_index = -1, -1
if self.current_fit and self.current_fit.tmin and self.current_fit.tmax:
tmin_index, tmax_index = self.get_indices(self.current_fit)
TEXT = ""
self.logger.DeleteAllItems()
for i in range(len(zijdblock)):
lab_treatment = self.Data[self.s]['zijdblock_lab_treatments'][i]
Step = ""
methods = lab_treatment.split('-')
if "NO" in methods:
Step = "N"
elif "AF" in methods:
Step = "AF"
elif "ARM" in methods:
Step = "ARM"
elif "IRM" in methods:
Step = "IRM"
elif "T" in methods:
Step = "T"
elif "LT" in methods:
Step = "LT"
Tr = zijdblock[i][0]
Dec = zijdblock[i][1]
Inc = zijdblock[i][2]
Int = zijdblock[i][3]
csd = self.Data[self.s]['csds'][i]
self.logger.InsertItem(i, "%i" % i)
self.logger.SetItem(i, 1, Step)
self.logger.SetItem(i, 2, "%.1f" % Tr)
self.logger.SetItem(i, 3, "%.1f" % Dec)
self.logger.SetItem(i, 4, "%.1f" % Inc)
self.logger.SetItem(i, 5, "%.2e" % Int)
self.logger.SetItem(i, 6, csd)
self.logger.SetItemBackgroundColour(i, "WHITE")
if i >= tmin_index and i <= tmax_index:
self.logger.SetItemBackgroundColour(i, "LIGHT BLUE")
if self.Data[self.s]['measurement_flag'][i] == 'b':
self.logger.SetItemBackgroundColour(i, "red")
|
def Add_text(self)
|
Add measurement data lines to the text window.
| 2.496396
| 2.438685
| 1.023665
|
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 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
# if tmin_index=="" or index<tmin_index:
# if tmax_index=="" and tmin_index!="":
# self.tmax_box.SetSelection(tmin_index)
# self.tmin_box.SetSelection(index)
# elif tmax_index=="" or index>tmax_index:
# self.tmax_box.SetSelection(index)
# else:
# self.tmin_box.SetSelection(index)
# self.tmax_box.SetValue("")
self.logger.Select(index, on=0)
self.get_new_PCA_parameters(-1)
|
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.
Parameters
----------
index : index of the step to select in the logger
| 1.932477
| 1.946723
| 0.992682
|
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()
|
def on_right_click_listctrl(self, event)
|
right click on the listctrl toggles measurement bad
| 7.090694
| 6.212803
| 1.141303
|
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()
|
def onSelect_specimen(self, event)
|
update figures and text when a new specimen is selected
| 7.70979
| 7.205476
| 1.06999
|
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()
|
def on_enter_specimen(self, event)
|
upon enter on the specimen box it makes that specimen the current
specimen
| 4.638671
| 4.471255
| 1.037443
|
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()
|
def get_new_PCA_parameters(self, event)
|
calculate statistics when temperatures are selected
or PCA type is changed
| 3.502592
| 3.362661
| 1.041613
|
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)
|
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
| 3.323043
| 3.109566
| 1.068652
|
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()
|
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
| 3.903219
| 3.899111
| 1.001054
|
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
|
def on_save_interpretation_button(self, event)
|
on the save button the interpretation is saved to pmag_results_table
data in all coordinate systems
| 3.156344
| 2.934453
| 1.075616
|
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)
|
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
| 6.468585
| 6.444594
| 1.003723
|
self.delete_fit(self.current_fit, specimen=self.s)
|
def on_btn_delete_fit(self, event)
|
removes the current interpretation
Parameters
----------
event : the wx.ButtonEvent that triggered this function
| 13.0864
| 15.325476
| 0.853898
|
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)
|
def do_auto_save(self)
|
Delete current fit if auto_save==False,
unless current fit has explicitly been saved.
| 6.58018
| 4.866964
| 1.352009
|
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()
|
def on_next_button(self, event)
|
update figures and text when a next button is selected
| 3.886039
| 3.782025
| 1.027502
|
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)
|
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
| 3.342486
| 2.557777
| 1.306793
|
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))
|
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
| 3.01921
| 2.717876
| 1.110871
|
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}
|
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.
| 3.373563
| 3.231963
| 1.043812
|
# 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
|
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
| 2.224866
| 2.189515
| 1.016145
|
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
|
def in_SCAT_box(x, y, low_bound, high_bound, x_max, y_max)
|
determines if a particular point falls within a box
| 2.254458
| 2.478075
| 0.909762
|
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
|
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
| 2.25241
| 2.241683
| 1.004786
|
# 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
|
def get_SCAT(points, low_bound, high_bound, x_max, y_max)
|
runs SCAT test and returns boolean
| 4.462074
| 4.254678
| 1.048745
|
# 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
|
def fancy_SCAT(points, low_bound, high_bound, x_max, y_max)
|
runs SCAT test and returns 'Pass' or 'Fail'
| 4.499412
| 4.167097
| 1.079747
|
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
|
def get_FRAC(vds, vector_diffs_segment)
|
input: vds, vector_diffs_segment
output: FRAC
| 3.836953
| 3.775029
| 1.016404
|
def get_R_corr2(x_avg, y_avg, x_segment, y_segment): #
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
| null | null | null |
|
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')
|
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
| 2.769619
| 2.820405
| 0.981993
|
if x == 0:
b_wiggle = 0
else:
b_wiggle = old_div((y_int - y), x)
return 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
| 2.544989
| 2.394455
| 1.062868
|
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
|
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)
| 4.447175
| 4.487487
| 0.991017
|
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
|
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))
| 4.704333
| 4.591464
| 1.024582
|
def get_normed_points(point_array, norm): # good to go
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
| null | null | null |
|
xy_array = []
for num, x in enumerate(x_segment):
xy_array.append((x, y_segment[num]))
return 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])]
| 2.563184
| 2.639132
| 0.971222
|
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 + " ")
|
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)
| 3.016075
| 2.644711
| 1.140418
|
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')
|
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
| 2.703352
| 2.24294
| 1.205272
|
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]))
|
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
| 3.241581
| 2.791282
| 1.161323
|
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]))
|
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
| 3.840178
| 3.584687
| 1.071273
|
sp = Spline(x1, y1)
return sp(x2)
|
def spline_interpolate(x1, y1, x2)
|
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
| 4.949915
| 4.503877
| 1.099034
|
sp = Spline(log(x1), log(y1))
return exp(sp(log(x2)))
|
def logspline_interpolate(x1, y1, x2)
|
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
| 4.607142
| 4.773898
| 0.965069
|
li = LinInt(x1, y1)
return li(x2)
|
def linear_interpolate(x1, y1, x2)
|
Given a function at a set of points (x1, y1), interpolate to
evaluate it at points x2.
| 10.799295
| 8.910544
| 1.211968
|
# 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]
|
def call(self, x)
|
Evaluate the interpolant, assuming x is a scalar.
| 2.575765
| 2.489247
| 1.034757
|
# 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)
|
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)
| 3.479231
| 2.475604
| 1.405407
|
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)
|
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
| 3.55212
| 2.752818
| 1.290358
|
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")
|
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
| 3.727334
| 3.446703
| 1.08142
|
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()
|
def get_DIR(self, WD=None)
|
open dialog box for choosing a working directory
| 2.963221
| 2.816449
| 1.052112
|
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
|
def on_save_interpretation_button(self, event)
|
save the current interpretation temporarily (not to a file)
| 2.707129
| 2.710548
| 0.998739
|
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
|
def on_delete_interpretation_button(self, event)
|
delete the current interpretation temporarily (not to a file)
| 2.537848
| 2.532061
| 1.002286
|
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)
|
def write_acceptance_criteria_to_boxes(self)
|
Update paleointensity statistics in acceptance criteria boxes.
(after changing temperature bounds or changing specimen)
| 2.593892
| 2.533627
| 1.023786
|
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)
|
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
| 2.763357
| 2.726321
| 1.013585
|
# 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()
|
def update_selection(self)
|
update figures and statistics windows with a new selection of specimen
| 4.353745
| 4.112885
| 1.058562
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.