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