code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
new_s = self.specimens_box.GetValue() if self.select_specimen(new_s): self.update_selection() else: self.specimens_box.SetValue(self.s) self.user_warning( "no specimen %s reverting to old specimen %s" % (new_s, self.s))
def onSelect_specimen(self, event)
update figures and text when a new specimen is selected
4.490066
4.417257
1.016483
def on_close(event, wind): wind.Close() wind.Destroy() event.Skip() wind = wx.PopupTransientWindow(self, wx.RAISED_BORDER) if self.auto_save.GetValue(): info = "'auto-save' is currently selected. Temperature bounds will be saved when you click 'next' or 'back'." else: info = "'auto-save' is not selected. Temperature bounds will only be saved when you click 'save'." text = wx.StaticText(wind, -1, info) box = wx.StaticBox(wind, -1, 'Info:') boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL) boxSizer.Add(text, 5, wx.ALL | wx.CENTER) exit_btn = wx.Button(wind, wx.ID_EXIT, 'Close') wind.Bind(wx.EVT_BUTTON, lambda evt: on_close(evt, wind), exit_btn) boxSizer.Add(exit_btn, 5, wx.ALL | wx.CENTER) wind.SetSizer(boxSizer) wind.Layout() wind.Popup()
def on_info_click(self, event)
Show popup info window when user clicks "?"
3.060084
2.943279
1.039685
if 'saved' not in self.Data[self.s]['pars'] or self.Data[self.s]['pars']['saved'] != True: # check preferences if self.auto_save.GetValue(): self.on_save_interpretation_button(None) else: del self.Data[self.s]['pars'] self.Data[self.s]['pars'] = {} self.Data[self.s]['pars']['lab_dc_field'] = self.Data[self.s]['lab_dc_field'] self.Data[self.s]['pars']['er_specimen_name'] = self.Data[self.s]['er_specimen_name'] self.Data[self.s]['pars']['er_sample_name'] = self.Data[self.s]['er_sample_name'] # return to last saved interpretation if exist if 'er_specimen_name' in list(self.last_saved_pars.keys()) and self.last_saved_pars['er_specimen_name'] == self.s: for key in list(self.last_saved_pars.keys()): self.Data[self.s]['pars'][key] = self.last_saved_pars[key] self.last_saved_pars = {} index = self.specimens.index(self.s) if index == 0: index = len(self.specimens) index -= 1 self.s = self.specimens[index] self.specimens_box.SetStringSelection(self.s) self.update_selection()
def on_prev_button(self, event)
update figures and text when a previous button is selected
2.573492
2.567863
1.002192
self.tmin_box.Clear() self.tmin_box.SetItems(self.T_list) self.tmin_box.SetSelection(-1) self.tmax_box.Clear() self.tmax_box.SetItems(self.T_list) self.tmax_box.SetSelection(-1) self.Blab_window.SetValue("") self.Banc_window.SetValue("") self.Banc_window.SetBackgroundColour(wx.Colour('grey')) self.Aniso_factor_window.SetValue("") self.Aniso_factor_window.SetBackgroundColour(wx.Colour('grey')) self.NLT_factor_window.SetValue("") self.NLT_factor_window.SetBackgroundColour(wx.Colour('grey')) self.CR_factor_window.SetValue("") self.CR_factor_window.SetBackgroundColour(wx.Colour('grey')) self.declination_window.SetValue("") self.declination_window.SetBackgroundColour(wx.Colour('grey')) self.inclination_window.SetValue("") self.inclination_window.SetBackgroundColour(wx.Colour('grey')) window_list = ['sample_int_n', 'sample_int_uT', 'sample_int_sigma', 'sample_int_sigma_perc'] for key in window_list: command = "self.%s_window.SetValue(\"\")" % key exec(command) command = "self.%s_window.SetBackgroundColour(wx.Colour('grey'))" % key exec(command) # window_list=['int_n','int_ptrm_n','frac','scat','gmax','f','fvds','b_beta','g','q','int_mad','int_dang','drats','md','ptrms_dec','ptrms_inc','ptrms_mad','ptrms_angle'] # for key in window_list: for key in self.preferences['show_statistics_on_gui']: self.stat_windows[key].SetValue("") self.stat_windows[key].SetBackgroundColour(wx.Colour('grey'))
def clear_boxes(self)
Clear all boxes
3.339829
3.319988
1.005976
user_data_dir = find_pmag_dir.find_user_data_dir("thellier_gui") if not user_data_dir: return {} if os.path.exists(user_data_dir): pref_file = os.path.join(user_data_dir, "thellier_gui_preferences.json") if os.path.exists(pref_file): with open(pref_file, "r") as pfile: return json.load(pfile) return {}
def read_preferences_file(self)
If json preferences file exists, read it in.
2.864276
2.790879
1.026299
user_data_dir = find_pmag_dir.find_user_data_dir("thellier_gui") if not os.path.exists(user_data_dir): find_pmag_dir.make_user_data_dir(user_data_dir) pref_file = os.path.join(user_data_dir, "thellier_gui_preferences.json") with open(pref_file, "w+") as pfile: print('-I- writing preferences to {}'.format(pref_file)) json.dump(self.preferences, pfile)
def write_preferences_file(self)
Write json preferences file to (platform specific) user data directory, or PmagPy directory if appdirs module is missing.
3.244171
2.93858
1.103993
if self.close_warning: TEXT = "Data is not saved to a file yet!\nTo properly save your data:\n1) Analysis --> Save current interpretations to a redo file.\nor\n1) File --> Save MagIC tables.\n\n Press OK to exit without saving." dlg1 = wx.MessageDialog( None, caption="Warning:", message=TEXT, style=wx.OK | wx.CANCEL | wx.ICON_EXCLAMATION) if self.show_dlg(dlg1) == wx.ID_OK: dlg1.Destroy() self.GUI_log.close() self.Destroy() # if a custom quit event is specified, fire it if self.evt_quit: event = self.evt_quit(self.GetId()) self.GetEventHandler().ProcessEvent(event) if self.standalone: sys.exit() else: self.GUI_log.close() self.Destroy() # if a custom quit event is specified, fire it if self.evt_quit: event = self.evt_quit(self.GetId()) self.GetEventHandler().ProcessEvent(event) if self.standalone: sys.exit()
def on_menu_exit(self, event)
Runs whenever Thellier GUI exits
4.319815
4.251365
1.016101
save_current_specimen = self.s dlg = wx.FileDialog( self, message="choose a file in a pmagpy redo format", defaultDir=self.WD, defaultFile="thellier_GUI.redo", wildcard="*.redo", style=wx.FD_OPEN | wx.FD_CHANGE_DIR ) if self.show_dlg(dlg) == wx.ID_OK: redo_file = dlg.GetPath() if self.test_mode: redo_file = "thellier_GUI.redo" else: redo_file = None dlg.Destroy() print("redo_file", redo_file) if redo_file: self.read_redo_file(redo_file)
def on_menu_previous_interpretation(self, event)
Create and show the Open FileDialog for upload previous interpretation input should be a valid "redo file": [specimen name] [tmin(kelvin)] [tmax(kelvin)]
4.062302
3.620765
1.121946
dia = thellier_gui_dialogs.Criteria_Dialog( None, self.acceptance_criteria, self.preferences, title='Set Acceptance Criteria') dia.Center() result = self.show_dlg(dia) if result == wx.ID_OK: # Until the user clicks OK, show the message self.On_close_criteria_box(dia)
def on_menu_criteria(self, event)
Change acceptance criteria and save it to the criteria file (data_model=2: pmag_criteria.txt; data_model=3: criteria.txt)
9.423625
8.224225
1.145837
criteria_list = list(self.acceptance_criteria.keys()) criteria_list.sort() #--------------------------------------- # check if averaging by sample or by site # and intialize sample/site criteria #--------------------------------------- avg_by = dia.set_average_by_sample_or_site.GetValue() if avg_by == 'sample': for crit in ['site_int_n', 'site_int_sigma', 'site_int_sigma_perc', 'site_aniso_mean', 'site_int_n_outlier_check']: self.acceptance_criteria[crit]['value'] = -999 if avg_by == 'site': for crit in ['sample_int_n', 'sample_int_sigma', 'sample_int_sigma_perc', 'sample_aniso_mean', 'sample_int_n_outlier_check']: self.acceptance_criteria[crit]['value'] = -999 #--------- # get value for each criterion for i in range(len(criteria_list)): crit = criteria_list[i] value, accept = dia.get_value_for_crit(crit, self.acceptance_criteria) if accept: self.acceptance_criteria.update(accept) #--------- # thellier interpreter calculation type if dia.set_stdev_opt.GetValue() == True: self.acceptance_criteria['interpreter_method']['value'] = 'stdev_opt' elif dia.set_bs.GetValue() == True: self.acceptance_criteria['interpreter_method']['value'] = 'bs' elif dia.set_bs_par.GetValue() == True: self.acceptance_criteria['interpreter_method']['value'] = 'bs_par' # message dialog dlg1 = wx.MessageDialog( self, caption="Warning:", message="changes are saved to the criteria file\n ", style=wx.OK) result = self.show_dlg(dlg1) if result == wx.ID_OK: try: self.clear_boxes() except IndexError: pass try: self.write_acceptance_criteria_to_boxes() except IOError: pass if self.data_model == 3: crit_file = 'criteria.txt' else: crit_file = 'pmag_criteria.txt' try: pmag.write_criteria_to_file(os.path.join( self.WD, crit_file), self.acceptance_criteria, data_model=self.data_model, prior_crits=self.crit_data) except AttributeError as ex: print(ex) print("no criteria given to save") dlg1.Destroy() dia.Destroy() self.fig4.texts[0].remove() txt = "{} data".format(avg_by).capitalize() self.fig4.text(0.02, 0.96, txt, { 'family': self.font_type, 'fontsize': 10, 'style': 'normal', 'va': 'center', 'ha': 'left'}) self.recalculate_satistics() try: self.update_GUI_with_new_interpretation() except KeyError: pass
def On_close_criteria_box(self, dia)
after criteria dialog window is closed. Take the acceptance criteria values and update self.acceptance_criteria
3.760449
3.683677
1.020841
''' update self.Data[specimen]['pars'] for all specimens. ''' gframe = wx.BusyInfo( "Re-calculating statistics for all specimens\n Please wait..", self) for specimen in list(self.Data.keys()): if 'pars' not in list(self.Data[specimen].keys()): continue if 'specimen_int_uT' not in list(self.Data[specimen]['pars'].keys()): continue tmin = self.Data[specimen]['pars']['measurement_step_min'] tmax = self.Data[specimen]['pars']['measurement_step_max'] pars = thellier_gui_lib.get_PI_parameters( self.Data, self.acceptance_criteria, self.preferences, specimen, tmin, tmax, self.GUI_log, THERMAL, MICROWAVE) self.Data[specimen]['pars'] = pars self.Data[specimen]['pars']['lab_dc_field'] = self.Data[specimen]['lab_dc_field'] self.Data[specimen]['pars']['er_specimen_name'] = self.Data[specimen]['er_specimen_name'] self.Data[specimen]['pars']['er_sample_name'] = self.Data[specimen]['er_sample_name'] del gframe
def recalculate_satistics(self)
update self.Data[specimen]['pars'] for all specimens.
3.717183
3.127777
1.188442
''' read criteria file. initialize self.acceptance_criteria try to guess if averaging by sample or by site. ''' if self.data_model == 3: self.acceptance_criteria = pmag.initialize_acceptance_criteria( data_model=self.data_model) self.add_thellier_gui_criteria() fnames = {'criteria': criteria_file} contribution = cb.Contribution( self.WD, custom_filenames=fnames, read_tables=['criteria']) if 'criteria' in contribution.tables: crit_container = contribution.tables['criteria'] crit_data = crit_container.df crit_data['definition'] = 'acceptance criteria for study' # convert to list of dictionaries self.crit_data = crit_data.to_dict('records') for crit in self.crit_data: # step through and rename every f-ing one # magic2[magic3.index(crit['table_column'])] # find data # model 2.5 name m2_name = map_magic.convert_intensity_criteria( 'magic2', crit['table_column']) if not m2_name: pass elif m2_name not in self.acceptance_criteria: print('-W- Your criteria file contains {}, which is not currently supported in Thellier GUI.'.format(m2_name)) print(' This record will be skipped:\n {}'.format(crit)) else: if m2_name != crit['table_column'] and 'scat' not in m2_name != "": self.acceptance_criteria[m2_name]['value'] = float( crit['criterion_value']) self.acceptance_criteria[m2_name]['pmag_criteria_code'] = crit['criterion'] if m2_name != crit['table_column'] and 'scat' in m2_name != "": if crit['criterion_value'] == 'True': self.acceptance_criteria[m2_name]['value'] = 1 else: self.acceptance_criteria[m2_name]['value'] = 0 else: print("-E- Can't read criteria file") else: # Do it the data model 2.5 way: self.crit_data = {} try: self.acceptance_criteria = pmag.read_criteria_from_file( criteria_file, self.acceptance_criteria) except: print("-E- Can't read pmag criteria file") # guesss if average by site or sample: by_sample = True flag = False for crit in ['sample_int_n', 'sample_int_sigma_perc', 'sample_int_sigma']: if self.acceptance_criteria[crit]['value'] == -999: flag = True if flag: for crit in ['site_int_n', 'site_int_sigma_perc', 'site_int_sigma']: if self.acceptance_criteria[crit]['value'] != -999: by_sample = False if not by_sample: self.acceptance_criteria['average_by_sample_or_site']['value'] = 'site'
def read_criteria_file(self, criteria_file)
read criteria file. initialize self.acceptance_criteria try to guess if averaging by sample or by site.
4.232895
3.836937
1.103196
''' save interpretations to a redo file ''' thellier_gui_redo_file = open( os.path.join(self.WD, "thellier_GUI.redo"), 'w') #-------------------------------------------------- # write interpretations to thellier_GUI.redo #-------------------------------------------------- spec_list = list(self.Data.keys()) spec_list.sort() redo_specimens_list = [] for sp in spec_list: if 'saved' not in self.Data[sp]['pars']: continue if not self.Data[sp]['pars']['saved']: continue redo_specimens_list.append(sp) thellier_gui_redo_file.write("%s %.0f %.0f\n" % ( sp, self.Data[sp]['pars']['measurement_step_min'], self.Data[sp]['pars']['measurement_step_max'])) dlg1 = wx.MessageDialog( self, caption="Saved:", message="File thellier_GUI.redo is saved in MagIC working folder", style=wx.OK) result = self.show_dlg(dlg1) if result == wx.ID_OK: dlg1.Destroy() thellier_gui_redo_file.close() return thellier_gui_redo_file.close() self.close_warning = False
def on_menu_save_interpretation(self, event)
save interpretations to a redo file
3.813371
3.548681
1.074588
''' clear all current interpretations. ''' # delete all previous interpretation for sp in list(self.Data.keys()): del self.Data[sp]['pars'] self.Data[sp]['pars'] = {} self.Data[sp]['pars']['lab_dc_field'] = self.Data[sp]['lab_dc_field'] self.Data[sp]['pars']['er_specimen_name'] = self.Data[sp]['er_specimen_name'] self.Data[sp]['pars']['er_sample_name'] = self.Data[sp]['er_sample_name'] self.Data_samples = {} self.Data_sites = {} self.tmin_box.SetValue("") self.tmax_box.SetValue("") self.clear_boxes() self.draw_figure(self.s)
def on_menu_clear_interpretation(self, event)
clear all current interpretations.
3.980333
3.76505
1.057179
''' read er_ages, sort it by site or sample (the header that is not empty) and convert ages to calendar year ''' DATA = {} fin = open(path, 'r') # ignore first lines for i in range(ignore_lines_n): fin.readline() # header line = fin.readline() header = line.strip('\n').split('\t') # print header for line in fin.readlines(): if line[0] == "#": continue tmp_data = {} tmp_line = line.strip('\n').split('\t') for i in range(len(tmp_line)): if i >= len(header): continue tmp_data[header[i]] = tmp_line[i] for name in sort_by_these_names: if name in list(tmp_data.keys()) and tmp_data[name] != "": er_ages_rec = self.convert_ages_to_calendar_year(tmp_data) DATA[tmp_data[name]] = er_ages_rec fin.close() return(DATA)
def read_er_ages_file(self, path, ignore_lines_n, sort_by_these_names)
read er_ages, sort it by site or sample (the header that is not empty) and convert ages to calendar year
3.107933
2.224028
1.397434
''' convert all age units to calendar year ''' if ("age" not in list(er_ages_rec.keys())) or (cb.is_null(er_ages_rec['age'], False)): return(er_ages_rec) if ("age_unit" not in list(er_ages_rec.keys())) or (cb.is_null(er_ages_rec['age_unit'])): return(er_ages_rec) if cb.is_null(er_ages_rec["age"], False): if "age_range_high" in list(er_ages_rec.keys()) and "age_range_low" in list(er_ages_rec.keys()): if cb.not_null(er_ages_rec["age_range_high"], False) and cb.not_null(er_ages_rec["age_range_low"], False): er_ages_rec["age"] = np.mean( [float(er_ages_rec["age_range_high"]), float(er_ages_rec["age_range_low"])]) if cb.is_null(er_ages_rec["age"], False): return(er_ages_rec) # age_descriptier_ages_recon=er_ages_rec["age_description"] age_unit = er_ages_rec["age_unit"] # Fix 'age': mutliplier = 1 if age_unit == "Ga": mutliplier = -1e9 if age_unit == "Ma": mutliplier = -1e6 if age_unit == "Ka": mutliplier = -1e3 if age_unit == "Years AD (+/-)" or age_unit == "Years Cal AD (+/-)": mutliplier = 1 if age_unit == "Years BP" or age_unit == "Years Cal BP": mutliplier = 1 age = float(er_ages_rec["age"]) * mutliplier if age_unit == "Years BP" or age_unit == "Years Cal BP": age = 1950 - age er_ages_rec['age_cal_year'] = age # Fix 'age_range_low': age_range_low = age age_range_high = age age_sigma = 0 if "age_sigma" in list(er_ages_rec.keys()) and cb.not_null(er_ages_rec["age_sigma"], False): age_sigma = float(er_ages_rec["age_sigma"]) * mutliplier if age_unit == "Years BP" or age_unit == "Years Cal BP": age_sigma = 1950 - age_sigma age_range_low = age - age_sigma age_range_high = age + age_sigma if "age_range_high" in list(er_ages_rec.keys()) and "age_range_low" in list(er_ages_rec.keys()): if cb.not_null(er_ages_rec["age_range_high"], False) and cb.not_null(er_ages_rec["age_range_low"], False): age_range_high = float( er_ages_rec["age_range_high"]) * mutliplier if age_unit == "Years BP" or age_unit == "Years Cal BP": age_range_high = 1950 - age_range_high age_range_low = float( er_ages_rec["age_range_low"]) * mutliplier if age_unit == "Years BP" or age_unit == "Years Cal BP": age_range_low = 1950 - age_range_low er_ages_rec['age_cal_year_range_low'] = age_range_low er_ages_rec['age_cal_year_range_high'] = age_range_high return(er_ages_rec)
def convert_ages_to_calendar_year(self, er_ages_rec)
convert all age units to calendar year
1.803456
1.77898
1.013759
# remember the last saved interpretation if "saved" in list(self.pars.keys()): if self.pars['saved']: self.last_saved_pars = {} for key in list(self.pars.keys()): self.last_saved_pars[key] = self.pars[key] self.pars['saved'] = False t1 = self.tmin_box.GetValue() t2 = self.tmax_box.GetValue() if (t1 == "" or t2 == ""): print("empty interpretation bounds") return if float(t2) < float(t1): print("upper bound less than lower bound") return index_1 = self.T_list.index(t1) index_2 = self.T_list.index(t2) # if (index_2-index_1)+1 >= self.acceptance_criteria['specimen_int_n']: if (index_2 - index_1) + 1 >= 3: if self.Data[self.s]['T_or_MW'] != "MW": self.pars = thellier_gui_lib.get_PI_parameters(self.Data, self.acceptance_criteria, self.preferences, self.s, float( t1) + 273., float(t2) + 273., self.GUI_log, THERMAL, MICROWAVE) self.Data[self.s]['pars'] = self.pars else: self.pars = thellier_gui_lib.get_PI_parameters( self.Data, self.acceptance_criteria, self.preferences, self.s, float(t1), float(t2), self.GUI_log, THERMAL, MICROWAVE) self.Data[self.s]['pars'] = self.pars self.update_GUI_with_new_interpretation() self.Add_text(self.s)
def get_new_T_PI_parameters(self, event)
calcualte statisics when temperatures are selected
3.401291
3.298187
1.031261
'''criteria used only in thellier gui these criteria are not written to pmag_criteria.txt ''' category = "thellier_gui" for crit in ['sample_int_n_outlier_check', 'site_int_n_outlier_check']: self.acceptance_criteria[crit] = {} self.acceptance_criteria[crit]['category'] = category self.acceptance_criteria[crit]['criterion_name'] = crit self.acceptance_criteria[crit]['value'] = -999 self.acceptance_criteria[crit]['threshold_type'] = "low" self.acceptance_criteria[crit]['decimal_points'] = 0 for crit in ['sample_int_interval_uT', 'sample_int_interval_perc', 'site_int_interval_uT', 'site_int_interval_perc', 'sample_int_BS_68_uT', 'sample_int_BS_95_uT', 'sample_int_BS_68_perc', 'sample_int_BS_95_perc', 'specimen_int_max_slope_diff']: self.acceptance_criteria[crit] = {} self.acceptance_criteria[crit]['category'] = category self.acceptance_criteria[crit]['criterion_name'] = crit self.acceptance_criteria[crit]['value'] = -999 self.acceptance_criteria[crit]['threshold_type'] = "high" if crit in ['specimen_int_max_slope_diff']: self.acceptance_criteria[crit]['decimal_points'] = -999 else: self.acceptance_criteria[crit]['decimal_points'] = 1 self.acceptance_criteria[crit]['comments'] = "thellier_gui_only" for crit in ['average_by_sample_or_site', 'interpreter_method']: self.acceptance_criteria[crit] = {} self.acceptance_criteria[crit]['category'] = category self.acceptance_criteria[crit]['criterion_name'] = crit if crit in ['average_by_sample_or_site']: self.acceptance_criteria[crit]['value'] = 'sample' if crit in ['interpreter_method']: self.acceptance_criteria[crit]['value'] = 'stdev_opt' self.acceptance_criteria[crit]['threshold_type'] = "flag" self.acceptance_criteria[crit]['decimal_points'] = -999 for crit in ['include_nrm']: self.acceptance_criteria[crit] = {} self.acceptance_criteria[crit]['category'] = category self.acceptance_criteria[crit]['criterion_name'] = crit self.acceptance_criteria[crit]['value'] = True self.acceptance_criteria[crit]['threshold_type'] = "bool" self.acceptance_criteria[crit]['decimal_points'] = -999 # define internal Thellier-GUI definitions: self.average_by_sample_or_site = 'sample' self.stdev_opt = True self.bs = False self.bs_par = False
def add_thellier_gui_criteria(self)
criteria used only in thellier gui these criteria are not written to pmag_criteria.txt
2.32166
2.165104
1.072309
ofile="" if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-F' in sys.argv: ind=sys.argv.index('-F') ofile=sys.argv[ind+1] outfile=open(ofile,'w') if '-i' in sys.argv: cont=1 while cont==1: cart=[] try: ans=input('X: [ctrl-D to quit] ') cart.append(float(ans)) ans=input('Y: ') cart.append(float(ans)) ans=input('Z: ') cart.append(float(ans)) except: print("\n Good-bye \n") sys.exit() dir= pmag.cart2dir(cart) # send dir to dir2cart and spit out result print('%7.1f %7.1f %10.3e'%(dir[0],dir[1],dir[2])) elif '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] inp=numpy.loadtxt(file) # read from a file else: inp = numpy.loadtxt(sys.stdin,dtype=numpy.float) # read from standard input dir=pmag.cart2dir(inp) if len(dir.shape)==1: line=dir print('%7.1f %7.1f %10.3e'%(line[0],line[1],line[2])) if ofile!="": outstring='%7.1f %7.1f %10.8e\n' %(line[0],line[1],line[2]) outfile.write(outstring) else: for line in dir: print('%7.1f %7.1f %10.3e'%(line[0],line[1],line[2])) if ofile!="": outstring='%7.1f %7.1f %10.8e\n' %(line[0],line[1],line[2]) outfile.write(outstring)
def main()
NAME cart_dir.py DESCRIPTION converts cartesian coordinates to geomagnetic elements INPUT (COMMAND LINE ENTRY) x1 x2 x3 if only two columns, assumes magnitude of unity OUTPUT declination inclination magnitude SYNTAX cart_dir.py [command line options] [< filename] OPTIONS -h prints help message and quits -i for interactive data entry -f FILE to specify input filename -F OFILE to specify output filename (also prints to screen)
2.508028
2.345521
1.069284
save_plots = False if '-sav' in sys.argv: save_plots = True interactive = False if '-h' in sys.argv: print(main.__doc__) sys.exit() fmt = pmag.get_named_arg('-fmt', 'svg') fname = pmag.get_named_arg('-f', '') outfile = pmag.get_named_arg("-F", "") norm = 1 if '-N' in sys.argv: norm = 0 if '-twin' in sys.argv: norm = - 1 binsize = pmag.get_named_arg('-b', 0) if '-xlab' in sys.argv: ind = sys.argv.index('-xlab') xlab = sys.argv[ind+1] else: xlab = 'x' data = [] if not fname: print('-I- Trying to read from stdin... <ctrl>-c to quit') data = np.loadtxt(sys.stdin, dtype=np.float) ipmag.histplot(fname, data, outfile, xlab, binsize, norm, fmt, save_plots, interactive)
def main()
NAME histplot.py DESCRIPTION makes histograms for data OPTIONS -h prints help message and quits -f input file name -b binsize -fmt [svg,png,pdf,eps,jpg] specify format for image, default is svg -sav save figure and quit -F output file name, default is hist.fmt -N don't normalize -twin plot both normalized and un-normalized y axes -xlab Label of X axis -ylab Label of Y axis INPUT FORMAT single variable SYNTAX histplot.py [command line options] [<file]
3.841636
3.06535
1.253245
string = " ".join(argv) string = string.split(' -') program = string[0] arguments = [s.split() for s in string[1:]] return arguments
def extract_args(argv)
take sys.argv that is used to call a command-line script and return a correctly split list of arguments for example, this input: ["eqarea.py", "-f", "infile", "-F", "outfile", "-A"] will return this output: [['f', 'infile'], ['F', 'outfile'], ['A']]
4.747918
4.573614
1.038111
stripped_args = [a[0] for a in arguments] df = data_frame.df # first make sure all args are valid for a in arguments: if a[0] not in df.index: print("-I- ignoring invalid argument: {}".format(a[0])) print("-") # next make sure required arguments are present condition = df['reqd'] reqd_args = df[condition] for arg in reqd_args['arg_name']: if arg not in stripped_args: raise pmag.MissingCommandLineArgException("-"+arg) #next, assign any default values as needed #condition = df['default'] != '' # don't need this, and sometimes the correct default argument IS '' default_args = df #[condition] using_defaults = [] for arg_name, row in default_args.iterrows(): default = row['default'] if arg_name not in stripped_args: using_defaults.append(arg_name) arguments.append([arg_name, default]) using_defaults = ["-" + arg for arg in using_defaults] print('Using default arguments for: {}'.format(', '.join(using_defaults))) return arguments
def check_args(arguments, data_frame)
check arguments against a command_line_dataframe. checks that: all arguments are valid all required arguments are present default values are used where needed
5.286992
5.065573
1.043711
if self.data_type in ['orient', 'ages']: belongs_to = [] else: parent_table_name = self.parent_type + "s" if parent_table_name in self.contribution.tables: belongs_to = sorted(self.contribution.tables[parent_table_name].df.index.unique()) else: belongs_to = [] self.choices = {} if self.data_type in ['specimens', 'samples', 'sites']: self.choices = {1: (belongs_to, False)} if self.data_type == 'orient': self.choices = {1: (['g', 'b'], False)} if self.data_type == 'ages': for level in ['specimen', 'sample', 'site', 'location']: if level in self.grid.col_labels: level_names = [] if level + "s" in self.contribution.tables: level_names = list(self.contribution.tables[level+"s"].df.index.unique()) num = self.grid.col_labels.index(level) self.choices[num] = (level_names, False) # Bind left click to drop-down menu popping out self.grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, lambda event: self.on_left_click(event, self.grid, self.choices)) cols = self.grid.GetNumberCols() col_labels = [self.grid.GetColLabelValue(col) for col in range(cols)] # check if any additional columns have controlled vocabularies # if so, get the vocabulary list for col_number, label in enumerate(col_labels): self.add_drop_down(col_number, label)
def InitUI(self)
Initialize interface for drop down menu
3.514145
3.424714
1.026113
if col_label.endswith('**') or col_label.endswith('^^'): col_label = col_label[:-2] # add drop-down for experiments if col_label == "experiments": if 'measurements' in self.contribution.tables: meas_table = self.contribution.tables['measurements'].df if 'experiment' in meas_table.columns: exps = meas_table['experiment'].unique() self.choices[col_number] = (sorted(exps), False) self.grid.SetColLabelValue(col_number, col_label + "**") return # if col_label == 'method_codes': self.add_method_drop_down(col_number, col_label) elif col_label == 'magic_method_codes': self.add_method_drop_down(col_number, 'method_codes') elif col_label in ['specimens', 'samples', 'sites', 'locations']: if col_label in self.contribution.tables: item_df = self.contribution.tables[col_label].df item_names = item_df.index.unique() #[col_label[:-1]].unique() self.choices[col_number] = (sorted(item_names), False) elif col_label in ['specimen', 'sample', 'site', 'location']: if col_label + "s" in self.contribution.tables: item_df = self.contribution.tables[col_label + "s"].df item_names = item_df.index.unique() #[col_label[:-1]].unique() self.choices[col_number] = (sorted(item_names), False) # add vocabularies if col_label in self.contribution.vocab.suggested: typ = 'suggested' elif col_label in self.contribution.vocab.vocabularies: typ = 'controlled' else: return # add menu, if not already set if col_number not in list(self.choices.keys()): if typ == 'suggested': self.grid.SetColLabelValue(col_number, col_label + "^^") controlled_vocabulary = self.contribution.vocab.suggested[col_label] else: self.grid.SetColLabelValue(col_number, col_label + "**") controlled_vocabulary = self.contribution.vocab.vocabularies[col_label] # stripped_list = [] for item in controlled_vocabulary: try: stripped_list.append(str(item)) except UnicodeEncodeError: # skips items with non ASCII characters pass if len(stripped_list) > 100: # split out the list alphabetically, into a dict of lists {'A': ['alpha', 'artist'], 'B': ['beta', 'beggar']...} dictionary = {} for item in stripped_list: letter = item[0].upper() if letter not in list(dictionary.keys()): dictionary[letter] = [] dictionary[letter].append(item) stripped_list = dictionary two_tiered = True if isinstance(stripped_list, dict) else False self.choices[col_number] = (stripped_list, two_tiered) return
def add_drop_down(self, col_number, col_label)
Add a correctly formatted drop-down-menu for given col_label, if required or suggested. Otherwise do nothing. Parameters ---------- col_number : int grid position at which to add a drop down menu col_label : str column name
2.696846
2.66526
1.011851
if self.data_type == 'ages': method_list = self.contribution.vocab.age_methods else: method_list = self.contribution.vocab.age_methods.copy() method_list.update(self.contribution.vocab.methods) self.choices[col_number] = (method_list, True)
def add_method_drop_down(self, col_number, col_label)
Add drop-down-menu options for magic_method_codes columns
4.719932
4.565778
1.033763
if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-F' in sys.argv: ind=sys.argv.index('-F') ofile=sys.argv[ind+1] out=open(ofile,'w') print(ofile, ' opened for output') else: ofile="" if '-i' in sys.argv: # interactive flag while 1: try: Dec=float(input("Declination: <cntl-D> to quit ")) except: print("\n Good-bye\n") sys.exit() Inc=float(input("Inclination: ")) Dip_dir=float(input("Dip direction: ")) Dip=float(input("Dip: ")) print('%7.1f %7.1f'%(pmag.dotilt(Dec,Inc,Dip_dir,Dip))) elif '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] data=numpy.loadtxt(file) else: data=numpy.loadtxt(sys.stdin,dtype=numpy.float) # read in the data from the datafile D,I=pmag.dotilt_V(data) for k in range(len(D)): if ofile=="": print('%7.1f %7.1f'%(D[k],I[k])) else: out.write('%7.1f %7.1f\n'%(D[k],I[k]))
def main()
NAME di_tilt.py DESCRIPTION rotates geographic coordinate dec, inc data to stratigraphic coordinates using the dip and dip direction (strike+90, dip if dip to right of strike) INPUT FORMAT declination inclination dip_direction dip SYNTAX di_tilt.py [-h][-i][-f FILE] [< filename ] OPTIONS -h prints help message and quits -i for interactive data entry -f FILE command line entry of file name -F OFILE, specify output file, default is standard output OUTPUT: declination inclination
3.339096
2.860859
1.167165
if '-h' in sys.argv: print(main.__doc__) sys.exit() file=sys.argv[1] f=open(file,'r') Input=f.readlines() f.close() out=open(file,'w') for line in Input: out.write(line) out.close()
def main()
NAME convert2unix.py DESCRIPTION converts mac or dos formatted file to unix file in place SYNTAX convert2unix.py FILE OPTIONS -h prints help and quits
2.800563
2.735354
1.023839
if len(sys.argv) > 0: if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') data=f.readlines() elif '-i' in sys.argv: # ask for filename file=input("Enter file name with dec, inc data: ") f=open(file,'r') data=f.readlines() else: # data=sys.stdin.readlines() # read in data from standard input ofile = "" if '-F' in sys.argv: ind = sys.argv.index('-F') ofile= sys.argv[ind+1] out = open(ofile, 'w + a') DIs= [] # set up list for dec inc data for line in data: # read in the data from standard input if '\t' in line: rec=line.split('\t') # split each line on space to get records else: rec=line.split() # split each line on space to get records DIs.append((float(rec[0]),float(rec[1]))) # kpars=pmag.dokent(DIs,len(DIs)) output = '%7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %i' % (kpars["dec"],kpars["inc"],kpars["Eta"],kpars["Edec"],kpars["Einc"],kpars["Zeta"],kpars["Zdec"],kpars["Zinc"],kpars["n"]) if ofile == "": print(output) else: out.write(output+'\n')
def main()
NAME gokent.py DESCRIPTION calculates Kent parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX gokent.py [options] OPTIONS -h prints help message and quits -i for interactive filename entry -f FILE, specify filename -F FILE, specifies output file name < filename for reading from standard input OUTPUT mean dec, mean inc, Eta, Deta, Ieta, Zeta, Zdec, Zinc, N
3.192029
2.537621
1.257883
is_win = True if sys.platform in ['win32', 'win64'] else False if not is_win: plt.ion() for fig in list(FIGS.keys()): plt.draw() plt.show() plt.ioff() if is_win: # this style basically works for Windows plt.draw() print("You must manually close all plots to continue") plt.show()
def draw_figs(FIGS)
Can only be used if matplotlib backend is set to TKAgg Does not play well with wxPython Parameters _________ FIGS : dictionary of figure names as keys and numbers as values
5.545396
5.205434
1.065309
locs = fig.xaxis.get_ticklocs() nlocs = np.delete(locs, list(range(0, len(locs), 2))) fig.set_xticks(nlocs)
def delticks(fig)
deletes half the x-axis tick marks Parameters ___________ fig : matplotlib figure number
3.875775
4.119704
0.94079
global fig_x_pos, fig_y_pos, plt_num dpi = 80 if isServer: dpi = 240 # plt.ion() plt_num += 1 fig = plt.figure(num=fignum, figsize=(w, h), dpi=dpi) if (not isServer) and (not set_env.IS_NOTEBOOK): plt.get_current_fig_manager().show() # plt.get_current_fig_manager().window.wm_geometry('+%d+%d' % # (fig_x_pos,fig_y_pos)) # this only works with matplotlib.use('TKAgg') fig_x_pos = fig_x_pos + dpi * (w) + 25 if plt_num == 3: plt_num = 0 fig_x_pos = 25 fig_y_pos = fig_y_pos + dpi * (h) + 25 plt.figtext(.02, .01, version_num) # plt.connect('button_press_event',click) # # plt.ioff() return fig
def plot_init(fignum, w, h)
initializes plot number fignum with width w and height h Parameters __________ fignum : matplotlib figure number w : width h : height
3.556712
3.695532
0.962436
from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(fignum) ax = fig.add_subplot(111, projection='3d') return ax
def plot3d_init(fignum)
initializes 3D plot
1.554652
1.571612
0.989208
x = old_div((y - ybar), (np.sqrt(2.) * sigma)) t = old_div(1.0, (1.0 + .3275911 * abs(x))) erf = 1.0 - np.exp(-x * x) * t * (.254829592 - t * (.284496736 - t * (1.421413741 - t * (1.453152027 - t * 1.061405429)))) erf = abs(erf) sign = old_div(x, abs(x)) return 0.5 * (1.0 + sign * erf)
def gaussfunc(y, ybar, sigma)
cumulative normal distribution function of the variable y with mean ybar,standard deviation sigma uses expression 7.1.26 from Abramowitz & Stegun accuracy better than 1.5e-7 absolute Parameters _________ y : input variable ybar : mean sigma : standard deviation
3.057264
3.03014
1.008951
xbar, sigma = pmag.gausspars(X) d, f = 0, 0. for i in range(1, len(X) + 1): b = old_div(float(i), float(len(X))) a = gaussfunc(X[i - 1], xbar, sigma) if abs(f - a) > abs(b - a): delta = abs(f - a) else: delta = abs(b - a) if delta > d: d = delta f = b return d, xbar, sigma
def k_s(X)
Kolmorgorov-Smirnov statistic. Finds the probability that the data are distributed as func - used method of Numerical Recipes (Press et al., 1986)
4.046488
4.131951
0.979317
d = p if d < 0. or d > 1.: print('d not in (1,1) ') sys.exit() x = 0. if (d - 0.5) > 0: d = 1. - d if (d - 0.5) < 0: t2 = -2. * np.log(d) t = np.sqrt(t2) x = t - old_div((2.515517 + .802853 * t + .010328 * t2), (1. + 1.432788 * t + .189269 * t2 + .001308 * t * t2)) if p < 0.5: x = -x return x
def qsnorm(p)
rational approximation for x where q(x)=d, q being the cumulative normal distribution function. taken from Abramowitz & Stegun p. 933 |error(x)| < 4.5*10**-4
3.49406
3.52011
0.9926
plt.figure(num=fignum) # if 'poly' in kwargs.keys(): # coeffs=np.polyfit(X,Y,kwargs['poly']) # polynomial=np.poly1d(coeffs) # xs=np.arange(np.min(X),np.max(X)) # ys=polynomial(xs) # plt.plot(xs,ys) # print coefs # print polynomial if 'sym' in list(kwargs.keys()): sym = kwargs['sym'] else: sym = 'ro' if 'lw' in list(kwargs.keys()): lw = kwargs['lw'] else: lw = 1 if 'xerr' in list(kwargs.keys()): plt.errorbar(X, Y, fmt=sym, xerr=kwargs['xerr']) if 'yerr' in list(kwargs.keys()): plt.errorbar(X, Y, fmt=sym, yerr=kwargs['yerr']) if 'axis' in list(kwargs.keys()): if kwargs['axis'] == 'semilogx': plt.semilogx(X, Y, marker=sym[1], markerfacecolor=sym[0]) if kwargs['axis'] == 'semilogy': plt.semilogy(X, Y, marker=sym[1], markerfacecolor=sym[0]) if kwargs['axis'] == 'loglog': plt.loglog(X, Y, marker=sym[1], markerfacecolor=sym[0]) else: plt.plot(X, Y, sym, linewidth=lw) if 'xlab' in list(kwargs.keys()): plt.xlabel(kwargs['xlab']) if 'ylab' in list(kwargs.keys()): plt.ylabel(kwargs['ylab']) if 'title' in list(kwargs.keys()): plt.title(kwargs['title']) if 'xmin' in list(kwargs.keys()): plt.axis([kwargs['xmin'], kwargs['xmax'], kwargs['ymin'], kwargs['ymax']]) if 'notes' in list(kwargs.keys()): for note in kwargs['notes']: plt.text(note[0], note[1], note[2])
def plot_xy(fignum, X, Y, **kwargs)
deprecated, used in curie
1.728546
1.723958
1.002661
print('Site mean data: ') print(' dec inc n_lines n_planes kappa R alpha_95 comp coord') print(SiteRec['site_dec'], SiteRec['site_inc'], SiteRec['site_n_lines'], SiteRec['site_n_planes'], SiteRec['site_k'], SiteRec['site_r'], SiteRec['site_alpha95'], SiteRec['site_comp_name'], SiteRec['site_tilt_correction']) print('sample/specimen, dec, inc, n_specs/a95,| method codes ') for i in range(len(data)): print('%s: %s %s %s / %s | %s' % (data[i]['er_' + key + '_name'], data[i][key + '_dec'], data[i] [key + '_inc'], data[i][key + '_n'], data[i][key + '_alpha95'], data[i]['magic_method_codes'])) plot_slnp(fignum, SiteRec, data, key) plot = input("s[a]ve plot, [q]uit or <return> to continue: ") if plot == 'q': print("CUL8R") sys.exit() if plot == 'a': files = {} for key in list(EQ.keys()): files[key] = site + '_' + key + '.' + fmt save_plots(EQ, files)
def plot_site(fignum, SiteRec, data, key)
deprecated (used in ipmag)
6.165533
5.753166
1.071677
plt.figure(num=fignum) if type(Y) == list: Y = np.array(Y) Y = np.sort(Y) # sort the data n = len(Y) d, mean, sigma = k_s(Y) dc = old_div(0.886, np.sqrt(float(n))) X = [] # list for normal quantile for i in range(1, n + 1): p = old_div(float(i), float(n + 1)) X.append(qsnorm(p)) plt.plot(X, Y, 'ro') plt.title(title) plt.xlabel('Normal Quantile') plt.ylabel('Data Quantile') bounds = plt.axis() notestr = 'N: ' + '%i' % (n) plt.text(-.9 * bounds[1], .9 * bounds[3], notestr) notestr = 'mean: ' + '%8.3e' % (mean) plt.text(-.9 * bounds[1], .8 * bounds[3], notestr) notestr = 'std dev: ' + '%8.3e' % (sigma) plt.text(-.9 * bounds[1], .7 * bounds[3], notestr) notestr = 'D: ' + '%8.3e' % (d) plt.text(-.9 * bounds[1], .6 * bounds[3], notestr) notestr = 'Dc: ' + '%8.3e' % (dc) plt.text(-.9 * bounds[1], .5 * bounds[3], notestr) return d, dc
def plot_qq_norm(fignum, Y, title)
makes a Quantile-Quantile plot for data Parameters _________ fignum : matplotlib figure number Y : list or array of data title : title string for plot Returns ___________ d,dc : the values for D and Dc (the critical value) if d>dc, likely to be normally distributed (95\% confidence)
2.445369
2.314647
1.056476
if subplot == True: plt.subplot(1, 2, fignum) else: plt.figure(num=fignum) X, Y, dpos, dneg = [], [], 0., 0. if degrees: D = (np.array(D)) % 360 X = D/D.max() X = np.sort(X) n = float(len(D)) i = np.arange(0, len(D)) Y = (i-0.5)/n ds = (i/n)-X dpos = ds.max() dneg = ds.min() plt.plot(Y, X, 'ro') v = dneg + dpos # kuiper's v # Mu of fisher et al. equation 5.16 Mu = v * (np.sqrt(n) - 0.567 + (old_div(1.623, (np.sqrt(n))))) plt.axis([0, 1., 0., 1.]) bounds = plt.axis() notestr = 'N: ' + '%i' % (n) plt.text(.1 * bounds[1], .9 * bounds[3], notestr) notestr = 'Mu: ' + '%7.3f' % (Mu) plt.text(.1 * bounds[1], .8 * bounds[3], notestr) if Mu > 1.347: notestr = "Non-uniform (99%)" elif Mu < 1.207: notestr = "Uniform (95%)" elif Mu > 1.207: notestr = "Uniform (99%)" plt.text(.1 * bounds[1], .7 * bounds[3], notestr) plt.text(.1 * bounds[1], .7 * bounds[3], notestr) plt.title(title) plt.xlabel('Uniform Quantile') plt.ylabel('Data Quantile') return Mu, 1.207
def plot_qq_unf(fignum, D, title, subplot=False, degrees=True)
plots data against a uniform distribution in 0=>360. Parameters _________ fignum : matplotlib figure number D : data title : title for plot subplot : if True, make this number one of two subplots degrees : if True, assume that these are degrees Return Mu : Mu statistic (Fisher et al., 1987) Mu_crit : critical value of Mu for uniform distribution Effect ______ makes a Quantile Quantile plot of data
3.673193
3.471359
1.058143
if subplot == True: plt.subplot(1, 2, fignum) else: plt.figure(num=fignum) X, Y, dpos, dneg = [], [], 0., 0. rad = old_div(np.pi, 180.) xsum = 0 for i in I: theta = (90. - i) * rad X.append(1. - np.cos(theta)) xsum += X[-1] X.sort() n = float(len(X)) kappa = old_div((n - 1.), xsum) for i in range(len(X)): p = old_div((float(i) - 0.5), n) Y.append(-np.log(1. - p)) f = 1. - np.exp(-kappa * X[i]) ds = old_div(float(i), n) - f if dpos < ds: dpos = ds ds = f - old_div((float(i) - 1.), n) if dneg < ds: dneg = ds if dneg > dpos: ds = dneg else: ds = dpos Me = (ds - (old_div(0.2, n))) * (np.sqrt(n) + 0.26 + (old_div(0.5, (np.sqrt(n))))) # Eq. 5.15 from Fisher et al. (1987) plt.plot(Y, X, 'ro') bounds = plt.axis() plt.axis([0, bounds[1], 0., bounds[3]]) notestr = 'N: ' + '%i' % (n) plt.text(.1 * bounds[1], .9 * bounds[3], notestr) notestr = 'Me: ' + '%7.3f' % (Me) plt.text(.1 * bounds[1], .8 * bounds[3], notestr) if Me > 1.094: notestr = "Not Exponential" else: notestr = "Exponential (95%)" plt.text(.1 * bounds[1], .7 * bounds[3], notestr) plt.title(title) plt.xlabel('Exponential Quantile') plt.ylabel('Data Quantile') return Me, 1.094
def plot_qq_exp(fignum, I, title, subplot=False)
plots data against an exponential distribution in 0=>90. Parameters _________ fignum : matplotlib figure number I : data title : plot title subplot : boolean, if True plot as subplot with 1 row, two columns with fignum the plot number
3.254929
3.315306
0.981788
global globals X_down, X_up, Y_down, Y_up = [], [], [], [] # initialize some variables plt.figure(num=fignum) # # plot the data - separate upper and lower hemispheres # for rec in DIblock: Up, Down = 0, 0 XY = pmag.dimap(rec[0], rec[1]) if rec[1] >= 0: X_down.append(XY[0]) Y_down.append(XY[1]) else: X_up.append(XY[0]) Y_up.append(XY[1]) # if len(X_down) > 0: # plt.scatter(X_down,Y_down,marker='s',c='r') plt.scatter(X_down, Y_down, marker='o', c='blue') if globals != 0: globals.DIlist = X_down globals.DIlisty = Y_down if len(X_up) > 0: # plt.scatter(X_up,Y_up,marker='s',facecolor='none',edgecolor='black') plt.scatter(X_up, Y_up, marker='o', facecolor='white', edgecolor='blue') if globals != 0: globals.DIlist = X_up globals.DIlisty = Y_up
def plot_di(fignum, DIblock)
plots directions on equal area net Parameters _________ fignum : matplotlib figure number DIblock : nested list of dec, inc pairs
2.824502
2.980893
0.947536
global globals X_down, X_up, Y_down, Y_up = [], [], [], [] # initialize some variables plt.figure(num=fignum) # # plot the data - separate upper and lower hemispheres # for rec in DIblock: Up, Down = 0, 0 XY = pmag.dimap(rec[0], rec[1]) if rec[1] >= 0: X_down.append(XY[0]) Y_down.append(XY[1]) else: X_up.append(XY[0]) Y_up.append(XY[1]) # if 'size' not in list(sym.keys()): size = 50 else: size = sym['size'] if 'edgecolor' not in list(sym.keys()): sym['edgecolor'] = 'k' if len(X_down) > 0: plt.scatter(X_down, Y_down, marker=sym['lower'][0], c=sym['lower'][1], s=size, edgecolor=sym['edgecolor']) if globals != 0: globals.DIlist = X_down globals.DIlisty = Y_down if len(X_up) > 0: plt.scatter(X_up, Y_up, marker=sym['upper'][0], c=sym['upper'][1], s=size, edgecolor=sym['edgecolor']) if globals != 0: globals.DIlist = X_up globals.DIlisty = Y_up
def plot_di_sym(fignum, DIblock, sym)
plots directions on equal area net Parameters _________ fignum : matplotlib figure number DIblock : nested list of dec, inc pairs sym : set matplotlib symbol (e.g., 'bo' for blue circles)
2.679223
2.686686
0.997222
plt.figure(num=fignum) D_c, I_c = pmag.circ(pole[0], pole[1], ang) X_c_up, Y_c_up = [], [] X_c_d, Y_c_d = [], [] for k in range(len(D_c)): XY = pmag.dimap(D_c[k], I_c[k]) if I_c[k] < 0: X_c_up.append(XY[0]) Y_c_up.append(XY[1]) else: X_c_d.append(XY[0]) Y_c_d.append(XY[1]) plt.plot(X_c_d, Y_c_d, col + '.', ms=5) plt.plot(X_c_up, Y_c_up, 'c.', ms=2)
def plot_circ(fignum, pole, ang, col)
function to put a small circle on an equal area projection plot, fig,fignum Parameters __________ fignum : matplotlib figure number pole : dec,inc of center of circle ang : angle of circle col :
2.188902
2.268562
0.964885
for fignum in list(ZED.keys()): fig = plt.figure(num=ZED[fignum]) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) DIbad, DIgood = [], [] for rec in datablock: if cb.is_null(rec[1],zero_as_null=False): print('-W- You are missing a declination for specimen', s, ', skipping this row') continue if cb.is_null(rec[2],zero_as_null=False): print('-W- You are missing an inclination for specimen', s, ', skipping this row') continue if rec[5] == 'b': DIbad.append((rec[1], rec[2])) else: DIgood.append((rec[1], rec[2])) badsym = {'lower': ['+', 'g'], 'upper': ['x', 'c']} if len(DIgood) > 0: plot_eq(ZED['eqarea'], DIgood, s) if len(DIbad) > 0: plot_di_sym(ZED['eqarea'], DIbad, badsym) elif len(DIbad) > 0: plot_eq_sym(ZED['eqarea'], DIbad, s, badsym) AngleX, AngleY = [], [] XY = pmag.dimap(angle, 90.) AngleX.append(XY[0]) AngleY.append(XY[1]) XY = pmag.dimap(angle, 0.) AngleX.append(XY[0]) AngleY.append(XY[1]) plt.figure(num=ZED['eqarea']) # Draw a line for Zijderveld horizontal axis plt.plot(AngleX, AngleY, 'r-') if AngleX[-1] == 0: AngleX[-1] = 0.01 plt.text(AngleX[-1] + (old_div(AngleX[-1], abs(AngleX[-1]))) * .1, AngleY[-1] + (old_div(AngleY[-1], abs(AngleY[-1]))) * .1, 'X') norm = 1 #if units=="U": norm=0 # if there are NO good points, don't try to plot if DIgood: plot_mag(ZED['demag'], datablock, s, 1, units, norm) plot_zij(ZED['zijd'], datablock, angle, s, norm) else: ZED.pop('demag') ZED.pop('zijd') return ZED
def plot_zed(ZED, datablock, angle, s, units)
function to make equal area plot and zijderveld plot Parameters _________ ZED : dictionary with keys for plots eqarea : figure number for equal area projection zijd : figure number for zijderveld plot demag : figure number for magnetization against demag step datablock : nested list of [step, dec, inc, M (Am2), quality] step : units assumed in SI M : units assumed Am2 quality : [g,b], good or bad measurement; if bad will be marked as such angle : angle for X axis in horizontal plane, if 0, x will be 0 declination s : specimen name units : SI units ['K','T','U'] for kelvin, tesla or undefined Effects _______ calls plotting functions for equal area, zijderveld and demag figures
3.858377
3.359087
1.148639
global globals first_Z, first_I, ptrm_check, ptrm_tail = indata[0], indata[1], indata[2], indata[3] plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) X, Y, recnum = [], [], 0 # for rec in first_Z: if units == "K": if rec[0] != 0: X.append(rec[0] - 273.) else: X.append(rec[0]) if (units == "J") or (not units) or (units == "T"): X.append(rec[0]) Y.append(old_div(rec[3], first_Z[0][3])) delta = .02 * Y[0] if recnum % 2 == 0: plt.text(X[-1] - delta, Y[-1] + delta, (' ' + str(recnum)), fontsize=9) recnum += 1 plt.plot(X, Y) plt.scatter(X, Y, marker='o', color='b') X, Y = [], [] for rec in first_I: if units == "K": if rec[0] != 0: X.append(rec[0] - 273) else: X.append(rec[0]) if (units == "J") or (not units) or (units == "T"): X.append(rec[0]) Y.append(old_div(rec[3], first_Z[0][3])) if globals != 0: globals.DIlist = X globals.DIlisty = Y plt.plot(X, Y) plt.scatter(X, Y, marker='s', color='r') plt.ylabel("Circles: NRM; Squares: pTRM") if units == "K": plt.xlabel("Temperature (C)") elif units == "J": plt.xlabel("Microwave Energy (J)") else: plt.xlabel("") title = s + ": NRM = " + '%9.2e' % (first_Z[0][3]) plt.title(title) plt.axhline(y=0, xmin=0, xmax=1, color='k') plt.axvline(x=0, ymin=0, ymax=1, color='k')
def plot_np(fignum, indata, s, units)
makes plot of de(re)magnetization data for Thellier-Thellier type experiment Parameters __________ fignum : matplotlib figure number indata : araiblock from, e.g., pmag.sortarai() s : specimen name units : [K, J, ""] (kelvin, joules, unknown) Effect _______ Makes a plot
3.043601
3.089247
0.985224
angle = zijdblock[0][1] norm = 1 if units == "U": norm = 0 plot_arai(ZED['arai'], araiblock, s, units) plot_teq(ZED['eqarea'], araiblock, s, "") plot_zij(ZED['zijd'], zijdblock, angle, s, norm) plot_np(ZED['deremag'], araiblock, s, units) return ZED
def plot_arai_zij(ZED, araiblock, zijdblock, s, units)
calls the four plotting programs for Thellier-Thellier experiments Parameters __________ ZED : dictionary with plotting figure keys: deremag : figure for de (re) magnezation plots arai : figure for the Arai diagram eqarea : equal area projection of data, color coded by red circles: ZI steps blue squares: IZ steps yellow triangles : pTRM steps zijd : Zijderveld diagram color coded by ZI, IZ steps deremag : demagnetization and remagnetization versus temperature araiblock : nested list of required data from Arai plots zijdblock : nested list of required data for Zijderveld plots s : specimen name units : units for the arai and zijderveld plots Effects ________ Makes four plots from the data by calling plot_arai : Arai plots plot_teq : equal area projection for Thellier data plotZ : Zijderveld diagram plot_np : de (re) magnetization diagram
5.006914
2.97594
1.682465
# make the stereonet plt.figure(num=fignum) plot_net(fignum) s = SiteRec['er_site_name'] # # plot on the data # coord = SiteRec['site_tilt_correction'] title = '' if coord == '-1': title = s + ": specimen coordinates" if coord == '0': title = s + ": geographic coordinates" if coord == '100': title = s + ": tilt corrected coordinates" DIblock, GCblock = [], [] for plotrec in datablock: if plotrec[key + '_direction_type'] == 'p': # direction is pole to plane GCblock.append( (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"]))) else: # assume direction is a directed line DIblock.append( (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"]))) if len(DIblock) > 0: plot_di(fignum, DIblock) # plot directed lines if len(GCblock) > 0: for pole in GCblock: plot_circ(fignum, pole, 90., 'g') # plot directed lines # # put on the mean direction # x, y = [], [] XY = pmag.dimap(float(SiteRec["site_dec"]), float(SiteRec["site_inc"])) x.append(XY[0]) y.append(XY[1]) plt.scatter(x, y, marker='d', s=80, c='g') plt.title(title) # # get the alpha95 # Xcirc, Ycirc = [], [] Da95, Ia95 = pmag.circ(float(SiteRec["site_dec"]), float( SiteRec["site_inc"]), float(SiteRec["site_alpha95"])) for k in range(len(Da95)): XY = pmag.dimap(Da95[k], Ia95[k]) Xcirc.append(XY[0]) Ycirc.append(XY[1]) plt.plot(Xcirc, Ycirc, 'g')
def plot_slnp(fignum, SiteRec, datablock, key)
plots lines and planes on a great circle with alpha 95 and mean deprecated (used in pmagplotlib)
3.623951
3.335131
1.086599
# make the stereonet plot_net(fignum) # # plot on the data # dec_key, inc_key, tilt_key = 'dec', 'inc', 'tilt_correction' if 'dir_dec' in datablock[0].keys(): # this is data model 3.0 dec_key, inc_key, tilt_key = 'dir_dec', 'dir_inc', 'dir_tilt_correction' coord = datablock[0][tilt_key] title = s if coord == '-1': title = title + ": specimen coordinates" if coord == '0': title = title + ": geographic coordinates" if coord == '100': title = title + ": tilt corrected coordinates" DIblock, GCblock = [], [] for plotrec in datablock: if plotrec[direction_type_key] == 'p': # direction is pole to plane GCblock.append((float(plotrec[dec_key]), float(plotrec[inc_key]))) else: # assume direction is a directed line DIblock.append((float(plotrec[dec_key]), float(plotrec[inc_key]))) if len(DIblock) > 0: plot_di(fignum, DIblock) # plot directed lines if len(GCblock) > 0: for pole in GCblock: plot_circ(fignum, pole, 90., 'g') # plot directed lines # # put on the mean direction # x, y = [], [] XY = pmag.dimap(float(fpars["dec"]), float(fpars["inc"])) x.append(XY[0]) y.append(XY[1]) plt.figure(num=fignum) plt.scatter(x, y, marker='d', s=80, c='g') plt.title(title) # # get the alpha95 # Xcirc, Ycirc = [], [] Da95, Ia95 = pmag.circ(float(fpars["dec"]), float( fpars["inc"]), float(fpars["alpha95"])) for k in range(len(Da95)): XY = pmag.dimap(Da95[k], Ia95[k]) Xcirc.append(XY[0]) Ycirc.append(XY[1]) plt.plot(Xcirc, Ycirc, 'g')
def plot_lnp(fignum, s, datablock, fpars, direction_type_key)
plots lines and planes on a great circle with alpha 95 and mean Parameters _________ fignum : number of plt.figure() object datablock : nested list of dictionaries with keys in 3.0 or 2.5 format 3.0 keys: dir_dec, dir_inc, dir_tilt_correction = [-1,0,100], direction_type_key =['p','l'] 2.5 keys: dec, inc, tilt_correction = [-1,0,100],direction_type_key =['p','l'] fpars : Fisher parameters calculated by, e.g., pmag.dolnp() or pmag.dolnp3_0() direction_type_key : key for dictionary direction_type ('specimen_direction_type') Effects _______ plots the site level figure
3.434572
2.973796
1.154945
# make the stereonet plt.figure(num=fignum) if len(DIblock) < 1: return # plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plot_net(fignum) # # put on the directions # plot_di(fignum, DIblock) # plot directions plt.axis("equal") plt.text(-1.1, 1.15, s) plt.draw()
def plot_eq(fignum, DIblock, s)
plots directions on eqarea projection Parameters __________ fignum : matplotlib figure number DIblock : nested list of dec/inc pairs s : specimen name
6.419535
6.239197
1.028904
# make the stereonet plt.figure(num=fignum) if len(DIblock) < 1: return # plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plot_net(fignum) # # put on the directions # plot_di_sym(fignum, DIblock, sym) # plot directions with symbols in sym plt.axis("equal") plt.text(-1.1, 1.15, s)
def plot_eq_sym(fignum, DIblock, s, sym)
plots directions with specified symbol Parameters __________ fignum : matplotlib figure number DIblock : nested list of dec/inc pairs s : specimen name sym : matplotlib symbol (e.g., 'bo' for blue circle)
6.96787
6.889377
1.011393
first_Z, first_I = araiblock[0], araiblock[1] # make the stereonet plt.figure(num=fignum) plt.clf() ZIblock, IZblock, pTblock = [], [], [] for zrec in first_Z: # sort out the zerofield steps if zrec[4] == 1: # this is a ZI step ZIblock.append([zrec[1], zrec[2]]) else: IZblock.append([zrec[1], zrec[2]]) plot_net(fignum) if pars != "": min, max = float(pars["measurement_step_min"]), float( pars["measurement_step_max"]) else: min, max = first_I[0][0], first_I[-1][0] for irec in first_I: if irec[1] != 0 and irec[1] != 0 and irec[0] >= min and irec[0] <= max: pTblock.append([irec[1], irec[2]]) if len(ZIblock) < 1 and len(IZblock) < 1 and len(pTblock) < 1: return if not isServer: plt.figtext(.02, .01, version_num) # # put on the directions # sym = {'lower': ['o', 'r'], 'upper': ['o', 'm']} if len(ZIblock) > 0: plot_di_sym(fignum, ZIblock, sym) # plot ZI directions sym = {'lower': ['s', 'b'], 'upper': ['s', 'c']} if len(IZblock) > 0: plot_di_sym(fignum, IZblock, sym) # plot IZ directions sym = {'lower': ['^', 'g'], 'upper': ['^', 'y']} if len(pTblock) > 0: plot_di_sym(fignum, pTblock, sym) # plot pTRM directions plt.axis("equal") plt.text(-1.1, 1.15, s)
def plot_teq(fignum, araiblock, s, pars)
plots directions of pTRM steps and zero field steps Parameters __________ fignum : figure number for matplotlib object araiblock : nested list of data from pmag.sortarai() s : specimen name pars : default is "", otherwise is dictionary with keys: 'measurement_step_min' and 'measurement_step_max' Effects _______ makes the equal area projection with color coded symbols red circles: ZI steps blue squares: IZ steps yellow : pTRM steps
3.340593
2.672311
1.250076
saved = [] for key in list(Figs.keys()): try: plt.figure(num=Figs[key]) fname = filenames[key] if set_env.IS_WIN: # always truncate filenames if on Windows fname = os.path.split(fname)[1] if not isServer: # remove illegal ':' character for windows fname = fname.replace(':', '_') if 'incl_directory' in kwargs.keys() and not set_env.IS_WIN: if kwargs['incl_directory']: pass # do not flatten file name else: fname = fname.replace('/', '-') # flatten file name else: fname = fname.replace('/', '-') # flatten file name if 'dpi' in list(kwargs.keys()): plt.savefig(fname, dpi=kwargs['dpi']) elif isServer: plt.savefig(fname, dpi=240) else: plt.savefig(fname) if verbose: print(Figs[key], " saved in ", fname) saved.append(fname) plt.close(Figs[key]) except Exception as ex: print(type(ex), ex) print('could not save: ', Figs[key], filenames[key]) print("output file format not supported ") return saved
def save_plots(Figs, filenames, **kwargs)
Parameters ---------- Figs : dict dictionary of plots, e.g. {'eqarea': 1, ...} filenames : dict dictionary of filenames, e.g. {'eqarea': 'mc01a_eqarea.svg', ...} dict keys should correspond with Figs
3.778818
4.067344
0.929063
# plt.figure(num=fignum) plt.text(-1.1, 1.15, title) # plot V1s as squares, V2s as triangles and V3s as circles symb, symkey = ['s', 'v', 'o'], 0 col = ['r', 'b', 'k'] # plot V1s rec, V2s blue, V3s black for VEC in range(3): X, Y = [], [] for Vdirs in Vs: # # # plot the V1 data first # XY = pmag.dimap(Vdirs[VEC][0], Vdirs[VEC][1]) X.append(XY[0]) Y.append(XY[1]) plt.scatter(X, Y, s=symsize, marker=symb[VEC], c=col[VEC], edgecolors='none') plt.axis("equal")
def plot_evec(fignum, Vs, symsize, title)
plots eigenvector directions of S vectors Paramters ________ fignum : matplotlib figure number Vs : nested list of eigenvectors symsize : size in pts for symbol title : title for plot
4.948416
4.968727
0.995912
vertical_plot_init(fignum, 10, 3) xlab, ylab, title = labels[0], labels[1], labels[2] X, Y = [], [] for rec in data: X.append(rec[0]) Y.append(rec[1]) plt.plot(X, Y) plt.plot(X, Y, 'ro') plt.xlabel(xlab) plt.ylabel(ylab) plt.title(title)
def plot_strat(fignum, data, labels)
plots a time/depth series Parameters _________ fignum : matplotlib figure number data : nested list of [X,Y] pairs labels : [xlabel, ylabel, title]
2.497602
2.712602
0.92074
# #if len(sym)==1:sym=sym+'-' fig = plt.figure(num=fignum) # sdata=np.array(data).sort() sdata = [] for d in data: sdata.append(d) # have to copy the data to avoid overwriting it! sdata.sort() X, Y = [], [] color = "" for j in range(len(sdata)): Y.append(old_div(float(j), float(len(sdata)))) X.append(sdata[j]) if 'color' in list(kwargs.keys()): color = kwargs['color'] if 'linewidth' in list(kwargs.keys()): lw = kwargs['linewidth'] else: lw = 1 if color != "": plt.plot(X, Y, color=sym, linewidth=lw) else: plt.plot(X, Y, sym, linewidth=lw) plt.xlabel(xlab) plt.ylabel('Cumulative Distribution') plt.title(title) return X, Y
def plot_cdf(fignum, data, xlab, sym, title, **kwargs)
Makes a plot of the cumulative distribution function. Parameters __________ fignum : matplotlib figure number data : list of data to be plotted - doesn't need to be sorted sym : matplotlib symbol for plotting, e.g., 'r--' for a red dashed line **kwargs : optional dictionary with {'color': color, 'linewidth':linewidth} Returns __________ x : sorted list of data y : fraction of cdf
3.084618
2.891106
1.066933
fig = plt.figure(num=fignum) for yv in Ys: bounds = plt.axis() plt.axhline(y=yv, xmin=0, xmax=1, linewidth=1, color=c, linestyle=ls)
def plot_hs(fignum, Ys, c, ls)
plots horizontal lines at Ys values Parameters _________ fignum : matplotlib figure number Ys : list of Y values for lines c : color for lines ls : linestyle for lines
3.186734
3.263655
0.976431
fig = plt.figure(num=fignum) for xv in Xs: bounds = plt.axis() plt.axvline( x=xv, ymin=bounds[2], ymax=bounds[3], linewidth=1, color=c, linestyle=ls)
def plot_vs(fignum, Xs, c, ls)
plots vertical lines at Xs values Parameters _________ fignum : matplotlib figure number Xs : list of X values for lines c : color for lines ls : linestyle for lines
3.183945
3.157213
1.008467
vertical_plot_init(fignum, 10, 3) TS, Chrons = pmag.get_ts(ts) p = 1 X, Y = [], [] for d in TS: if d <= dates[1]: if d >= dates[0]: if len(X) == 0: ind = TS.index(d) X.append(TS[ind - 1]) Y.append(p % 2) X.append(d) Y.append(p % 2) p += 1 X.append(d) Y.append(p % 2) else: X.append(dates[1]) Y.append(p % 2) plt.plot(X, Y, 'k') plot_vs(fignum, dates, 'w', '-') plot_hs(fignum, [1.1, -.1], 'w', '-') plt.xlabel("Age (Ma): " + ts) isign = -1 for c in Chrons: off = -.1 isign = -1 * isign if isign > 0: off = 1.05 if c[1] >= X[0] and c[1] < X[-1]: plt.text(c[1] - .2, off, c[0]) return
def plot_ts(fignum, dates, ts)
plot the geomagnetic polarity time scale Parameters __________ fignum : matplotlib figure number dates : bounding dates for plot ts : time scale ck95, gts04, or gts12
4.241539
4.359239
0.973
plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plt.plot(B, DM, 'b') plt.xlabel('B (T)') plt.ylabel('Delta M') linex = [0, Bcr, Bcr] liney = [old_div(DM[0], 2.), old_div(DM[0], 2.), 0] plt.plot(linex, liney, 'r') plt.title(s)
def plot_delta_m(fignum, B, DM, Bcr, s)
function to plot Delta M curves Parameters __________ fignum : matplotlib figure number B : array of field values DM : array of difference between top and bottom curves in hysteresis loop Bcr : coercivity of remanence s : specimen name
3.181018
3.17708
1.001239
plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) start = len(Bdm) - len(DdeltaM) plt.plot(Bdm[start:], DdeltaM, 'b') plt.xlabel('B (T)') plt.ylabel('d (Delta M)/dB') plt.title(s)
def plot_d_delta_m(fignum, Bdm, DdeltaM, s)
function to plot d (Delta M)/dB curves Parameters __________ fignum : matplotlib figure number Bdm : change in field Ddelta M : change in delta M s : specimen name
4.166682
3.614629
1.152728
plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plt.plot(Bimag, Mimag, 'r') plt.xlabel('B (T)') plt.ylabel('M/Ms') plt.axvline(0, color='k') plt.title(s)
def plot_imag(fignum, Bimag, Mimag, s)
function to plot d (Delta M)/dB curves
3.694815
3.787439
0.975544
hpars, deltaM, Bdm = plot_hys( HDD['hyst'], B, M, s) # Moff is the "fixed" loop data DdeltaM = [] Mhalf = "" for k in range(2, len(Bdm)): # differnential DdeltaM.append( old_div(abs(deltaM[k] - deltaM[k - 2]), (Bdm[k] - Bdm[k - 2]))) for k in range(len(deltaM)): if old_div(deltaM[k], deltaM[0]) < 0.5: Mhalf = k break try: Bhf = Bdm[Mhalf - 1:Mhalf + 1] Mhf = deltaM[Mhalf - 1:Mhalf + 1] # best fit line through two bounding points poly = np.polyfit(Bhf, Mhf, 1) Bcr = old_div((.5 * deltaM[0] - poly[1]), poly[0]) hpars['hysteresis_bcr'] = '%8.3e' % (Bcr) hpars['magic_method_codes'] = "LP-BCR-HDM" if HDD['deltaM'] != 0: plot_delta_m(HDD['deltaM'], Bdm, deltaM, Bcr, s) plt.axhline(0, color='k') plt.axvline(0, color='k') plot_d_delta_m(HDD['DdeltaM'], Bdm, DdeltaM, s) except: hpars['hysteresis_bcr'] = '0' hpars['magic_method_codes'] = "" return hpars
def plot_hdd(HDD, B, M, s)
Function to make hysteresis, deltaM and DdeltaM plots Parameters: _______________ Input HDD : dictionary with figure numbers for the keys: 'hyst' : hysteresis plot normalized to maximum value 'deltaM' : Delta M plot 'DdeltaM' : differential of Delta M plot B : list of field values in tesla M : list of magnetizations in arbitrary units s : specimen name string Ouput hpars : dictionary of hysteresis parameters with keys: 'hysteresis_xhf', 'hysteresis_ms_moment', 'hysteresis_mr_moment', 'hysteresis_bc'
4.436451
3.922061
1.131153
plt.figure(num=fignum) plt.plot(BcrBc, S, sym) plt.axhline(0, color='k') plt.axhline(.05, color='k') plt.axhline(.5, color='k') plt.axvline(1, color='k') plt.axvline(4, color='k') plt.xlabel('Bcr/Bc') plt.ylabel('Mr/Ms') plt.title('Day Plot') plt.xlim(0, 6) #bounds= plt.axis() #plt.axis([0, bounds[1],0, 1]) mu_o = 4. * np.pi * 1e-7 Bc_sd = 46e-3 # (MV1H) dunlop and carter-stiglitz 2006 (in T) Bc_md = 5.56e-3 # (041183) dunlop and carter-stiglitz 2006 (in T) chi_sd = 5.20e6 * mu_o # now in T chi_md = 4.14e6 * mu_o # now in T chi_r_sd = 4.55e6 * mu_o # now in T chi_r_md = 0.88e6 * mu_o # now in T Bcr_sd, Bcr_md = 52.5e-3, 26.1e-3 # (MV1H and 041183 in DC06 in tesla) Ms = 480e3 # A/m p = .1 # from Dunlop 2002 N = old_div(1., 3.) # demagnetizing factor f_sd = np.arange(1., 0., -.01) # fraction of sd f_md = 1. - f_sd # fraction of md f_sp = 1. - f_sd # fraction of sp # Mr/Ms ratios for USD,MD and Jax shaped sdrat, mdrat, cbrat = 0.498, 0.048, 0.6 Mrat = f_sd * sdrat + f_md * mdrat # linear mixing - eq. 9 in Dunlop 2002 Bc = old_div((f_sd * chi_sd * Bc_sd + f_md * chi_md * Bc_md), (f_sd * chi_sd + f_md * chi_md)) # eq. 10 in Dunlop 2002 Bcr = old_div((f_sd * chi_r_sd * Bcr_sd + f_md * chi_r_md * Bcr_md), (f_sd * chi_r_sd + f_md * chi_r_md)) # eq. 11 in Dunlop 2002 chi_sps = np.arange(1, 5) * chi_sd plt.plot(old_div(Bcr, Bc), Mrat, 'r-') if 'names' in list(kwargs.keys()): names = kwargs['names'] for k in range(len(names)): plt.text(BcrBc[k], S[k], names[k])
def plot_day(fignum, BcrBc, S, sym, **kwargs)
function to plot Day plots Parameters _________ fignum : matplotlib figure number BcrBc : list or array ratio of coercivity of remenance to coercivity S : list or array ratio of saturation remanence to saturation magnetization (squareness) sym : matplotlib symbol (e.g., 'rs' for red squares) **kwargs : dictionary with {'names':[list of names for symbols]}
3.672791
3.55058
1.03442
plt.figure(num=fignum) plt.plot(Bc, S, sym) plt.xlabel('Bc') plt.ylabel('Mr/Ms') plt.title('Squareness-Coercivity Plot') bounds = plt.axis() plt.axis([0, bounds[1], 0, 1])
def plot_s_bc(fignum, Bc, S, sym)
function to plot Squareness,Coercivity Parameters __________ fignum : matplotlib figure number Bc : list or array coercivity values S : list or array of ratio of saturation remanence to saturation sym : matplotlib symbol (e.g., 'g^' for green triangles)
4.340255
3.063436
1.416793
plt.figure(num=fignum) plt.plot(Bcr, S, sym) plt.xlabel('Bcr') plt.ylabel('Mr/Ms') plt.title('Squareness-Bcr Plot') bounds = plt.axis() plt.axis([0, bounds[1], 0, 1])
def plot_s_bcr(fignum, Bcr, S, sym)
function to plot Squareness,Coercivity of remanence Parameters __________ fignum : matplotlib figure number Bcr : list or array coercivity of remenence values S : list or array of ratio of saturation remanence to saturation sym : matplotlib symbol (e.g., 'g^' for green triangles)
3.752566
3.316596
1.131451
plt.figure(num=fignum) plt.plot(Bcr1, Bcr2, 'ro') plt.xlabel('Bcr1') plt.ylabel('Bcr2') plt.title('Compare coercivity of remanence')
def plot_bcr(fignum, Bcr1, Bcr2)
function to plot two estimates of Bcr against each other
3.501506
3.408567
1.027266
plt.figure(num=HDD['hyst']) X, Y = [], [] X.append(0) Y.append(old_div(float(hpars['hysteresis_mr_moment']), float( hpars['hysteresis_ms_moment']))) X.append(float(hpars['hysteresis_bc'])) Y.append(0) plt.plot(X, Y, sym) bounds = plt.axis() n4 = 'Ms: ' + '%8.2e' % (float(hpars['hysteresis_ms_moment'])) + ' Am^2' plt.text(bounds[1] - .9 * bounds[1], -.9, n4) n1 = 'Mr: ' + '%8.2e' % (float(hpars['hysteresis_mr_moment'])) + ' Am^2' plt.text(bounds[1] - .9 * bounds[1], -.7, n1) n2 = 'Bc: ' + '%8.2e' % (float(hpars['hysteresis_bc'])) + ' T' plt.text(bounds[1] - .9 * bounds[1], -.5, n2) if 'hysteresis_xhf' in list(hpars.keys()): n3 = r'Xhf: ' + '%8.2e' % (float(hpars['hysteresis_xhf'])) + ' m^3' plt.text(bounds[1] - .9 * bounds[1], -.3, n3) plt.figure(num=HDD['deltaM']) X, Y, Bcr = [], [], "" if 'hysteresis_bcr' in list(hpars.keys()): X.append(float(hpars['hysteresis_bcr'])) Y.append(0) Bcr = float(hpars['hysteresis_bcr']) plt.plot(X, Y, sym) bounds = plt.axis() if Bcr != "": n1 = 'Bcr: ' + '%8.2e' % (Bcr) + ' T' plt.text(bounds[1] - .5 * bounds[1], .9 * bounds[3], n1)
def plot_hpars(HDD, hpars, sym)
function to plot hysteresis parameters deprecated (used in hysteresis_magic)
2.36584
2.306731
1.025625
rpars = {} Mnorm = [] backfield = 0 X, Y = [], [] for k in range(len(B)): if M[k] < 0: break if k <= 5: kmin = 0 else: kmin = k - 5 for k in range(kmin, k + 1): X.append(B[k]) if B[k] < 0: backfield = 1 Y.append(M[k]) if backfield == 1: poly = np.polyfit(X, Y, 1) if poly[0] != 0: bcr = (old_div(-poly[1], poly[0])) else: bcr = 0 rpars['remanence_mr_moment'] = '%8.3e' % (M[0]) rpars['remanence_bcr'] = '%8.3e' % (-bcr) rpars['magic_method_codes'] = 'LP-BCR-BF' if M[0] != 0: for m in M: Mnorm.append(old_div(m, M[0])) # normalize to unity Msat title = title + ':' + '%8.3e' % (M[0]) else: if M[-1] != 0: for m in M: Mnorm.append(old_div(m, M[-1])) # normalize to unity Msat title = title + ':' + '%8.3e' % (M[-1]) # do plots if desired if fignum != 0 and M[0] != 0: # skip plot for fignum = 0 plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plt.plot(B, Mnorm) plt.axhline(0, color='k') plt.axvline(0, color='k') plt.xlabel('B (T)') plt.ylabel('M/Mr') plt.title(title) if backfield == 1: plt.scatter([bcr], [0], marker='s', c='b') bounds = plt.axis() n1 = 'Bcr: ' + '%8.2e' % (-bcr) + ' T' plt.figtext(.2, .5, n1) n2 = 'Mr: ' + '%8.2e' % (M[0]) + ' Am^2' plt.figtext(.2, .45, n2) elif fignum != 0: plt.figure(num=fignum) # plt.clf() if not isServer: plt.figtext(.02, .01, version_num) print('M[0]=0, skipping specimen') return rpars
def plot_irm(fignum, B, M, title)
function to plot IRM backfield curves Parameters _________ fignum : matplotlib figure number B : list or array of field values M : list or array of magnetizations title : string title for plot
3.13213
3.12559
1.002093
plt.figure(num=fignum) plt.xlabel('Temperature (K)') plt.ylabel('Susceptibility (m^3/kg)') k = 0 Flab = [] for freq in XTF: T, X = [], [] for xt in freq: X.append(xt[0]) T.append(xt[1]) plt.plot(T, X) plt.text(T[-1], X[-1], str(int(Fs[k])) + ' Hz') # Flab.append(str(int(Fs[k]))+' Hz') k += 1 plt.title(e + ': B = ' + '%8.1e' % (b) + ' T')
def plot_xtf(fignum, XTF, Fs, e, b)
function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
3.63775
3.42593
1.061829
plt.figure(num=fignum) plt.xlabel('Temperature (K)') plt.ylabel('Susceptibility (m^3/kg)') k = 0 Blab = [] for field in XTB: T, X = [], [] for xt in field: X.append(xt[0]) T.append(xt[1]) plt.plot(T, X) plt.text(T[-1], X[-1], '%8.2e' % (Bs[k]) + ' T') # Blab.append('%8.1e'%(Bs[k])+' T') k += 1 plt.title(e + ': f = ' + '%i' % (int(f)) + ' Hz')
def plot_xtb(fignum, XTB, Bs, e, f)
function to plot series of chi measurements as a function of temperature, holding frequency constant and varying B
3.894216
3.693744
1.054273
plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plt.xlabel('Frequency (Hz)') plt.ylabel('Susceptibility (m^3/kg)') k = 0 F, X = [], [] for xf in XF: X.append(xf[0]) F.append(xf[1]) plt.plot(F, X) plt.semilogx() plt.title(e + ': B = ' + '%8.1e' % (b) + ' T') plt.legend(['%i' % (int(T)) + ' K'])
def plot_xft(fignum, XF, T, e, b)
function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
4.412078
4.288207
1.028887
plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plt.xlabel('Field (T)') plt.ylabel('Susceptibility (m^3/kg)') k = 0 B, X = [], [] for xb in XB: X.append(xb[0]) B.append(xb[1]) plt.plot(B, X) plt.legend(['%i' % (int(T)) + ' K']) plt.title(e + ': f = ' + '%i' % (int(f)) + ' Hz')
def plot_xbt(fignum, XB, T, e, b)
function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
4.158126
3.883226
1.070792
leglist, init = [], 0 if len(LTC_CM) > 2: if init == 0: plot_init(1, 5, 5) plt.plot(LTC_CT, LTC_CM, 'b') leglist.append('RT SIRM, measured while cooling') init = 1 if len(LTC_WM) > 2: if init == 0: plot_init(1, 5, 5) plt.plot(LTC_WT, LTC_WM, 'r') leglist.append('RT SIRM, measured while warming') if init != 0: plt.legend(leglist, 'lower left') plt.xlabel('Temperature (K)') plt.ylabel('Magnetization (Am^2/kg)') if len(LTC_CM) > 2: plt.plot(LTC_CT, LTC_CM, 'bo') if len(LTC_WM) > 2: plt.plot(LTC_WT, LTC_WM, 'ro') plt.title(e)
def plot_ltc(LTC_CM, LTC_CT, LTC_WM, LTC_WT, e)
function to plot low temperature cycling experiments
2.641211
2.613533
1.01059
# make the stereonet if new == 1: plot_net(fignum) # # plot the data # DIblock = [] for plotrec in datablock: DIblock.append((float(plotrec["dec"]), float(plotrec["inc"]))) if len(DIblock) > 0: plot_di(fignum, DIblock) # plot directed lines # # put on the mean direction # x, y = [], [] XY = pmag.dimap(float(pars[0]), float(pars[1])) x.append(XY[0]) y.append(XY[1]) plt.figure(num=fignum) if new == 1: plt.scatter(x, y, marker='d', s=80, c='r') else: if float(pars[1] > 0): plt.scatter(x, y, marker='^', s=100, c='r') else: plt.scatter(x, y, marker='^', s=100, c='y') plt.title(s) # # plot the ellipse # plot_ell(fignum, pars, 'r-,', 0, 1)
def plot_conf(fignum, s, datablock, pars, new)
plots directions and confidence ellipses
3.884861
3.736116
1.039813
def split_title(s): s_list = s.split(",") lines = [] tot = 0 line = [] for i in s_list: tot += len(i) if tot < 30: line.append(i + ",") else: lines.append(" ".join(line)) line = [i] tot = 0 lines.append(" ".join(line)) return "\n".join(lines).strip(',') # format contribution id if available if con_id: if not str(con_id).startswith("/"): con_id = "/" + str(con_id) import datetime now = datetime.datetime.utcnow() for key in list(Figs.keys()): fig = plt.figure(Figs[key]) plot_title = split_title(titles[key]).strip().strip('\n') fig.set_figheight(5.5) #get returns Bbox with x0, y0, x1, y1 pos = fig.gca().get_position() # tweak some of the default values w = pos.x1 - pos.x0 h = (pos.y1 - pos.y0) / 1.1 x = pos.x0 y = pos.y0 * 1.3 # set takes: left, bottom, width, height fig.gca().set_position([x, y, w, h]) # add an axis covering the entire figure border_ax = fig.add_axes([0, 0, 1, 1]) border_ax.set_frame_on(False) border_ax.set_xticks([]) border_ax.set_yticks([]) # add a border if "\n" in plot_title: y_val = 1.0 # lower border #fig.set_figheight(6.25) else: y_val = 1.04 # higher border #border_ax.text(-0.02, y_val, " # |", # horizontalalignment='left', # verticalalignment='top', # color=text_color, # bbox=dict(edgecolor=border_color, # facecolor='#FFFFFF', linewidth=0.25), # size=50) #border_ax.text(-0.02, 0, "| # |", # horizontalalignment='left', # verticalalignment='bottom', # color=text_color, # bbox=dict(edgecolor=border_color, # facecolor='#FFFFFF', linewidth=0.25), # size=20)#18) # add text border_ax.text((4. / fig.get_figwidth()) * 0.015, 0.03, now.strftime("%Y-%m-%d, %I:%M:%S {}".format('UT')), horizontalalignment='left', verticalalignment='top', color=text_color, size=10) border_ax.text(0.5, 0.98, plot_title, horizontalalignment='center', verticalalignment='top', color=text_color, size=20) border_ax.text(1 - (4. / fig.get_figwidth()) * 0.015, 0.03, 'earthref.org/MagIC{}'.format(con_id), horizontalalignment='right', verticalalignment='top', color=text_color, size=10) return Figs
def add_borders(Figs, titles, border_color='#000000', text_color='#800080', con_id="")
Formatting for generating plots on the server Default border color: black Default text color: purple
2.934691
2.932965
1.000588
if not has_basemap: print('-W- Basemap must be installed to run plot_mag_map_basemap') return from matplotlib import cm # matplotlib's color map module lincr = 1 if type(date) != str: date = str(date) fig = plt.figure(fignum) m = Basemap(projection='hammer', lon_0=lon_0) x, y = m(*meshgrid(lons, lats)) m.drawcoastlines() if element_type == 'B': levmax = element.max()+lincr levmin = round(element.min()-lincr) levels = np.arange(levmin, levmax, lincr) cs = m.contourf(x, y, element, levels=levels, cmap=cmap) plt.title('Field strength ($\mu$T): '+date) if element_type == 'Br': levmax = element.max()+lincr levmin = round(element.min()-lincr) cs = m.contourf(x, y, element, levels=np.arange( levmin, levmax, lincr), cmap=cmap) plt.title('Radial field strength ($\mu$T): '+date) if element_type == 'I': levmax = element.max()+lincr levmin = round(element.min()-lincr) cs = m.contourf( x, y, element, levels=np.arange(-90, 100, 20), cmap=cmap) m.contour(x, y, element, levels=np.arange(-80, 90, 10), colors='black') plt.title('Field inclination: '+date) if element_type == 'D': # cs=m.contourf(x,y,element,levels=np.arange(-180,180,10),cmap=cmap) cs = m.contourf( x, y, element, levels=np.arange(-180, 180, 10), cmap=cmap) m.contour(x, y, element, levels=np.arange(-180, 180, 10), colors='black') plt.title('Field declination: '+date) cbar = m.colorbar(cs, location='bottom')
def plot_mag_map_basemap(fignum, element, lons, lats, element_type, cmap='RdYlBu', lon_0=0, date="")
makes a color contour map of geomagnetic field element Parameters ____________ fignum : matplotlib figure number element : field element array from pmag.do_mag_map for plotting lons : longitude array from pmag.do_mag_map for plotting lats : latitude array from pmag.do_mag_map for plotting element_type : [B,Br,I,D] geomagnetic element type B : field intensity Br : radial field intensity I : inclinations D : declinations Optional _________ cmap : matplotlib color map lon_0 : central longitude of the Hammer projection date : date used for field evaluation, if custom ghfile was used, supply filename Effects ______________ plots a Hammer projection color contour with the desired field element
2.072617
1.973885
1.050019
ax.set_title(timescale.upper()) ax.axis([-.25, 1.5, agemax, agemin]) ax.axes.get_xaxis().set_visible(False) # get dates and chron names for timescale TS, Chrons = pmag.get_ts(timescale) X, Y, Y2 = [0, 1], [], [] cnt = 0 if agemin < TS[1]: # in the Brunhes Y = [agemin, agemin] # minimum age Y1 = [TS[1], TS[1]] # age of the B/M boundary ax.fill_between(X, Y, Y1, facecolor='black') # color in Brunhes, black for d in TS[1:]: pol = cnt % 2 cnt += 1 if d <= agemax and d >= agemin: ind = TS.index(d) Y = [TS[ind], TS[ind]] Y1 = [TS[ind+1], TS[ind+1]] if pol: # fill in every other time ax.fill_between(X, Y, Y1, facecolor='black') ax.plot([0, 1, 1, 0, 0], [agemin, agemin, agemax, agemax, agemin], 'k-') plt.yticks(np.arange(agemin, agemax+1, 1)) if ylabel != "": ax.set_ylabel(ylabel) ax2 = ax.twinx() ax2.axis('off') for k in range(len(Chrons)-1): c = Chrons[k] cnext = Chrons[k+1] d = cnext[1]-(cnext[1]-c[1])/3. if d >= agemin and d < agemax: # make the Chron boundary tick ax2.plot([1, 1.5], [c[1], c[1]], 'k-') ax2.text(1.05, d, c[0]) ax2.axis([-.25, 1.5, agemax, agemin])
def plot_ts(ax, agemin, agemax, timescale='gts12', ylabel="Age (Ma)")
Make a time scale plot between specified ages. Parameters: ------------ ax : figure object agemin : Minimum age for timescale agemax : Maximum age for timescale timescale : Time Scale [ default is Gradstein et al., (2012)] for other options see pmag.get_ts() ylabel : if set, plot as ylabel
3.359207
3.311104
1.014528
alpha=p[0] beta=p[1] dev=0 for i in range(len(x)): dev=dev+((y[i]-(alpha*math.tanh(beta*x[i])))**2) rms=math.sqrt(old_div(dev,float(len(y)))) return rms
def funk(p, x, y)
Function misfit evaluation for best-fit tanh curve f(x[:]) = alpha*tanh(beta*x[:]) alpha = params[0] beta = params[1] funk(params) = sqrt(sum((y[:] - f(x[:]))**2)/len(y[:])) Output is RMS misfit x=xx[0][:] y=xx[1][:]q
3.439156
2.917957
1.178618
s=0 for i in range(len(a)): s=s+abs(a[i]-b[i]) return s
def compare(a, b)
Compare items in 2 arrays. Returns sum(abs(a(i)-b(i)))
2.510305
2.019953
1.242754
m = float(a) * math.tanh(float(b) * float(f)) return float(m)
def TRM(f,a,b)
Calculate TRM using tanh relationship TRM(f)=a*math.tanh(b*f)
5.662018
4.146589
1.365464
WARN = True # Warn, rather than stop if I encounter a NaN... if float(a)==0: print('ERROR: TRMinv: a==0.') if not WARN : sys.exit() if float(b)==0: print('ERROR: TRMinv: b==0.') if not WARN : sys.exit() x = (old_div(float(m), float(a))) if (1-x)<=0: print('ERROR: TRMinv: (1-x)==0.') return -1 if not WARN : sys.exit() f = (old_div(1.,float(b))) * 0.5 * math.log (old_div((1+x), (1-x))) return float(f)
def TRMinv(m,a,b)
Calculate applied field from TRM using tanh relationship TRMinv(m)=(1/b)*atanh(m/a)
4.656066
4.891677
0.951834
WARN = True # Warn, rather than stop if I encounter a NaN... if float(f)==0: print('ERROR: NRM: f==0.') if not WARN : sys.exit() m = (old_div(float(best),float(f))) * TRM(f,a,b) return float(m)
def NRM(f,a,b,best)
Calculate NRM expected lab field and estimated ancient field NRM(blab,best)= (best/blab)*TRM(blab)
13.125024
12.431874
1.055756
self.fit_list = [] self.search_choices = [] for specimen in self.specimens_list: if specimen not in self.parent.pmag_results_data['specimens']: continue self.fit_list += [(fit,specimen) for fit in self.parent.pmag_results_data['specimens'][specimen]] self.logger.DeleteAllItems() offset = 0 for i in range(len(self.fit_list)): i -= offset v = self.update_logger_entry(i) if v == "s": offset += 1
def update_editor(self)
updates the logger and plot on the interpretation editor window
5.435047
4.57331
1.188427
if len(self.fit_list)==0: return if self.search_query and self.parent.current_fit not in [x[0] for x in self.fit_list]: return if self.current_fit_index == None: if not self.parent.current_fit: return for i,(fit,specimen) in enumerate(self.fit_list): if fit == self.parent.current_fit: self.current_fit_index = i break i = 0 if isinstance(new_fit, Fit): for i, (fit,speci) in enumerate(self.fit_list): if fit == new_fit: break elif type(new_fit) is int: i = new_fit elif new_fit != None: print(('cannot select fit of type: ' + str(type(new_fit)))) if self.current_fit_index != None and \ len(self.fit_list) > 0 and \ self.fit_list[self.current_fit_index][0] in self.parent.bad_fits: self.logger.SetItemBackgroundColour(self.current_fit_index,"") else: self.logger.SetItemBackgroundColour(self.current_fit_index,"WHITE") self.current_fit_index = i if self.fit_list[self.current_fit_index][0] in self.parent.bad_fits: self.logger.SetItemBackgroundColour(self.current_fit_index,"red") else: self.logger.SetItemBackgroundColour(self.current_fit_index,"LIGHT BLUE")
def change_selected(self,new_fit)
updates passed in fit or index as current fit for the editor (does not affect parent), if no parameters are passed in it sets first fit as current @param: new_fit -> fit object to highlight as selected
2.449597
2.389126
1.025311
if self.logger.GetItemCount()-1 > i+focus_shift: i += focus_shift else: i = self.logger.GetItemCount()-1 self.logger.Focus(i)
def logger_focus(self,i,focus_shift=16)
focuses the logger on an index 12 entries below i @param: i -> index to focus on
3.471251
3.780576
0.91818
i = event.GetIndex() if self.parent.current_fit == self.fit_list[i][0]: return self.parent.initialize_CART_rot(self.fit_list[i][1]) si = self.parent.specimens.index(self.fit_list[i][1]) self.parent.specimens_box.SetSelection(si) self.parent.select_specimen(self.fit_list[i][1]) self.change_selected(i) fi = 0 while (self.parent.s == self.fit_list[i][1] and i >= 0): i,fi = (i-1,fi+1) self.parent.update_fit_box() self.parent.fit_box.SetSelection(fi-1) self.parent.update_selection()
def OnClick_listctrl(self, event)
Edits the logger and the Zeq_GUI parent object to select the fit that was newly selected by a double click @param: event -> wx.ListCtrlEvent that triggered this function
4.066854
3.972847
1.023663
i = event.GetIndex() fit,spec = self.fit_list[i][0],self.fit_list[i][1] if fit in self.parent.bad_fits: if not self.parent.mark_fit_good(fit,spec=spec): return if i == self.current_fit_index: self.logger.SetItemBackgroundColour(i,"LIGHT BLUE") else: self.logger.SetItemBackgroundColour(i,"WHITE") else: if not self.parent.mark_fit_bad(fit): return if i == self.current_fit_index: self.logger.SetItemBackgroundColour(i,"red") else: self.logger.SetItemBackgroundColour(i,"red") self.parent.calculate_high_levels_data() self.parent.plot_high_levels_data() self.logger_focus(i)
def OnRightClickListctrl(self, event)
Edits the logger and the Zeq_GUI parent object so that the selected interpretation is now marked as bad @param: event -> wx.ListCtrlEvent that triggered this function
3.500022
3.079378
1.1366
self.parent.UPPER_LEVEL_SHOW=self.show_box.GetValue() self.parent.calculate_high_levels_data() self.parent.plot_high_levels_data()
def on_select_show_box(self,event)
Changes the type of mean shown on the high levels mean plot so that single dots represent one of whatever the value of this box is. @param: event -> the wx.COMBOBOXEVENT that triggered this function
7.172154
5.333875
1.344642
UPPER_LEVEL=self.level_box.GetValue() if UPPER_LEVEL=='sample': self.level_names.SetItems(self.parent.samples) self.level_names.SetStringSelection(self.parent.Data_hierarchy['sample_of_specimen'][self.parent.s]) if UPPER_LEVEL=='site': self.level_names.SetItems(self.parent.sites) self.level_names.SetStringSelection(self.parent.Data_hierarchy['site_of_specimen'][self.parent.s]) if UPPER_LEVEL=='location': self.level_names.SetItems(self.parent.locations) self.level_names.SetStringSelection(self.parent.Data_hierarchy['location_of_specimen'][self.parent.s]) if UPPER_LEVEL=='study': self.level_names.SetItems(['this study']) self.level_names.SetStringSelection('this study') if not called_by_parent: self.parent.level_box.SetStringSelection(UPPER_LEVEL) self.parent.onSelect_high_level(event,True) self.on_select_level_name(event)
def on_select_high_level(self,event,called_by_parent=False)
alters the possible entries in level_names combobox to give the user selections for which specimen interpretations to display in the logger @param: event -> the wx.COMBOBOXEVENT that triggered this function
2.4516
2.309491
1.061532
high_level_name=str(self.level_names.GetValue()) if self.level_box.GetValue()=='sample': self.specimens_list=self.parent.Data_hierarchy['samples'][high_level_name]['specimens'] elif self.level_box.GetValue()=='site': self.specimens_list=self.parent.Data_hierarchy['sites'][high_level_name]['specimens'] elif self.level_box.GetValue()=='location': self.specimens_list=self.parent.Data_hierarchy['locations'][high_level_name]['specimens'] elif self.level_box.GetValue()=='study': self.specimens_list=self.parent.Data_hierarchy['study']['this study']['specimens'] if not called_by_parent: self.parent.level_names.SetStringSelection(high_level_name) self.parent.onSelect_level_name(event,True) self.specimens_list.sort(key=spec_key_func) self.update_editor()
def on_select_level_name(self,event,called_by_parent=False)
change this objects specimens_list to control which specimen interpretatoins are displayed in this objects logger @param: event -> the wx.ComboBoxEvent that triggered this function
2.499676
2.493646
1.002418
new_mean_type = self.mean_type_box.GetValue() if new_mean_type == "None": self.parent.clear_high_level_pars() self.parent.mean_type_box.SetStringSelection(new_mean_type) self.parent.onSelect_mean_type_box(event)
def on_select_mean_type_box(self, event)
set parent Zeq_GUI to reflect change in this box and change the @param: event -> the wx.ComboBoxEvent that triggered this function
3.441218
3.276595
1.050242
new_mean_fit = self.mean_fit_box.GetValue() self.parent.mean_fit_box.SetStringSelection(new_mean_fit) self.parent.onSelect_mean_fit_box(event)
def on_select_mean_fit_box(self, event)
set parent Zeq_GUI to reflect the change in this box then replot the high level means plot @param: event -> the wx.COMBOBOXEVENT that triggered this function
3.186801
2.898237
1.099565
specimens = [] next_i = self.logger.GetNextSelected(-1) if next_i == -1: return while next_i != -1: fit,specimen = self.fit_list[next_i] if specimen in specimens: next_i = self.logger.GetNextSelected(next_i) continue else: specimens.append(specimen) next_i = self.logger.GetNextSelected(next_i) for specimen in specimens: self.add_fit_to_specimen(specimen) self.update_editor() self.parent.update_selection()
def add_highlighted_fits(self, evnet)
adds a new interpretation to each specimen highlighted in logger if multiple interpretations are highlighted of the same specimen only one new interpretation is added @param: event -> the wx.ButtonEvent that triggered this function
3.072921
2.806568
1.094903
next_i = -1 deleted_items = [] while True: next_i = self.logger.GetNextSelected(next_i) if next_i == -1: break deleted_items.append(next_i) deleted_items.sort(reverse=True) for item in deleted_items: self.delete_entry(index=item) self.parent.update_selection()
def delete_highlighted_fits(self, event)
iterates through all highlighted fits in the logger of this object and removes them from the logger and the Zeq_GUI parent object @param: event -> the wx.ButtonEvent that triggered this function
3.839249
3.490382
1.099951
if type(index) == int and not fit: fit,specimen = self.fit_list[index] if fit and type(index) == int: for i, (f,s) in enumerate(self.fit_list): if fit == f: index,specimen = i,s break if index == self.current_fit_index: self.current_fit_index = None if fit not in self.parent.pmag_results_data['specimens'][specimen]: print(("cannot remove item (entry #: " + str(index) + ") as it doesn't exist, this is a dumb bug contact devs")) self.logger.DeleteItem(index) return self.parent.pmag_results_data['specimens'][specimen].remove(fit) del self.fit_list[index] self.logger.DeleteItem(index)
def delete_entry(self, fit = None, index = None)
deletes the single item from the logger of this object that corrisponds to either the passed in fit or index. Note this function mutaits the logger of this object if deleting more than one entry be sure to pass items to delete in from highest index to lowest or else odd things can happen. @param: fit -> Fit object to delete from this objects logger @param: index -> integer index of the entry to delete from this objects logger
4.28707
4.209414
1.018448
new_name = self.name_box.GetLineText(0) new_color = self.color_box.GetValue() new_tmin = self.tmin_box.GetValue() new_tmax = self.tmax_box.GetValue() next_i = -1 changed_i = [] while True: next_i = self.logger.GetNextSelected(next_i) if next_i == -1: break specimen = self.fit_list[next_i][1] fit = self.fit_list[next_i][0] if new_name: if new_name not in [x.name for x in self.parent.pmag_results_data['specimens'][specimen]]: fit.name = new_name if new_color: fit.color = self.color_dict[new_color] #testing not_both = True if new_tmin and new_tmax: if fit == self.parent.current_fit: self.parent.tmin_box.SetStringSelection(new_tmin) self.parent.tmax_box.SetStringSelection(new_tmax) fit.put(specimen,self.parent.COORDINATE_SYSTEM, self.parent.get_PCA_parameters(specimen,fit,new_tmin,new_tmax,self.parent.COORDINATE_SYSTEM,fit.PCA_type)) not_both = False if new_tmin and not_both: if fit == self.parent.current_fit: self.parent.tmin_box.SetStringSelection(new_tmin) fit.put(specimen,self.parent.COORDINATE_SYSTEM, self.parent.get_PCA_parameters(specimen,fit,new_tmin,fit.tmax,self.parent.COORDINATE_SYSTEM,fit.PCA_type)) if new_tmax and not_both: if fit == self.parent.current_fit: self.parent.tmax_box.SetStringSelection(new_tmax) fit.put(specimen,self.parent.COORDINATE_SYSTEM, self.parent.get_PCA_parameters(specimen,fit,fit.tmin,new_tmax,self.parent.COORDINATE_SYSTEM,fit.PCA_type)) changed_i.append(next_i) offset = 0 for i in changed_i: i -= offset v = self.update_logger_entry(i) if v == "s": offset += 1 self.parent.update_selection()
def apply_changes(self, event)
applies the changes in the various attribute boxes of this object to all highlighted fit objects in the logger, these changes are reflected both in this object and in the Zeq_GUI parent object. @param: event -> the wx.ButtonEvent that triggered this function
2.420719
2.330041
1.038917
if event.LeftIsDown() or event.ButtonDClick(): return elif self.high_EA_setting == "Zoom": self.high_EA_setting = "Pan" try: self.toolbar.pan('off') except TypeError: pass elif self.high_EA_setting == "Pan": self.high_EA_setting = "Zoom" try: self.toolbar.zoom() except TypeError: pass else: self.high_EA_setting = "Zoom" try: self.toolbar.zoom() except TypeError: pass
def pan_zoom_high_equalarea(self,event)
Uses the toolbar for the canvas to change the function from zoom to pan or pan to zoom @param: event -> the wx.MouseEvent that triggered this funciton
2.71629
2.754874
0.985995
N, L, D, R = 100, 0., 0., 0 G2, G3 = 0., 0. cnt = 1 Imax = 0 if len(sys.argv) != 0 and '-h' in sys.argv: print(main.__doc__) sys.exit() else: if '-n' in sys.argv: ind = sys.argv.index('-n') N = int(sys.argv[ind + 1]) if '-d' in sys.argv: ind = sys.argv.index('-d') D = float(sys.argv[ind + 1]) if '-lat' in sys.argv: ind = sys.argv.index('-lat') L = float(sys.argv[ind + 1]) if '-t' in sys.argv: ind = sys.argv.index('-t') Imax = 1e3 * float(sys.argv[ind + 1]) if '-rev' in sys.argv: R = 1 if '-G2' in sys.argv: ind = sys.argv.index('-G2') G2 = float(sys.argv[ind + 1]) if '-G3' in sys.argv: ind = sys.argv.index('-G3') G3 = float(sys.argv[ind + 1]) for k in range(N): gh = pmag.mktk03(8, k, G2, G3) # terms and random seed # get a random longitude, between 0 and 359 lon = random.randint(0, 360) vec = pmag.getvec(gh, L, lon) # send field model and lat to getvec if vec[2] >= Imax: vec[0] += D if k % 2 == 0 and R == 1: vec[0] += 180. vec[1] = -vec[1] if vec[0] >= 360.: vec[0] -= 360. print('%7.1f %7.1f %8.2f ' % (vec[0], vec[1], vec[2]))
def main()
NAME tk03.py DESCRIPTION generates set of vectors drawn from TK03.gad at given lat and rotated about vertical axis by given Dec INPUT (COMMAND LINE ENTRY) OUTPUT dec, inc, int SYNTAX tk03.py [command line options] [> OutputFileName] OPTIONS -n N specify N, default is 100 -d D specify mean Dec, default is 0 -lat LAT specify latitude, default is 0 -rev include reversals -t INT truncates intensities to >INT uT -G2 FRAC specify average g_2^0 fraction (default is 0) -G3 FRAC specify average g_3^0 fraction (default is 0)
2.712615
2.370049
1.144539
N,mean,sigma=100,0,1. outfile="" if '-h' in sys.argv: print(main.__doc__) sys.exit() else: if '-s' in sys.argv: ind=sys.argv.index('-s') sigma=float(sys.argv[ind+1]) if '-n' in sys.argv: ind=sys.argv.index('-n') N=int(sys.argv[ind+1]) if '-m' in sys.argv: ind=sys.argv.index('-m') mean=float(sys.argv[ind+1]) if '-F' in sys.argv: ind=sys.argv.index('-F') outfile=sys.argv[ind+1] out=open(outfile,'w') for k in range(N): x='%f'%(pmag.gaussdev(mean,sigma)) # send kappa to fshdev if outfile=="": print(x) else: out.write(x+'\n')
def main()
NAME gaussian.py DESCRIPTION generates set of normally distribed data from specified distribution INPUT (COMMAND LINE ENTRY) OUTPUT x SYNTAX gaussian.py [command line options] OPTIONS -h prints help message and quits -s specify standard deviation as next argument, default is 1 -n specify N as next argument, default is 100 -m specify mean as next argument, default is 0 -F specify output file
2.803825
2.58318
1.085416
fmt,plot='svg',0 if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit elif '-f' in sys.argv: # ask for filename ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') input=f.readlines() Data=[] for line in input: line.replace('\n','') if '\t' in line: # read in the data from standard input rec=line.split('\t') # split each line on space to get records else: rec=line.split() # split each line on space to get records Data.append(float(rec[0])) # if len(Data) >=10: QQ={'unf1':1} pmagplotlib.plot_init(QQ['unf1'],5,5) pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot else: print('you need N> 10') sys.exit() pmagplotlib.draw_figs(QQ) files={} for key in list(QQ.keys()): files[key]=key+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='Equal Area Plot' EQ = pmagplotlib.add_borders(EQ,titles,black,purple) pmagplotlib.save_plots(QQ,files) elif plot==1: files['qq']=file+'.'+fmt pmagplotlib.save_plots(QQ,files) else: ans=input(" S[a]ve to save plot, [q]uit without saving: ") if ans=="a": pmagplotlib.save_plots(QQ,files)
def main()
NAME qqunf.py DESCRIPTION makes qq plot from input data against uniform distribution SYNTAX qqunf.py [command line options] OPTIONS -h help message -f FILE, specify file on command line
4.277654
4.08717
1.046605