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