repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_qq_unf
def plot_qq_unf(fignum, D, title, subplot=False, degrees=True): """ plots data against a uniform distribution in 0=>360. Parameters _________ fignum : matplotlib figure number D : data title : title for plot subplot : if True, make this number one of two subplots degrees : if True, assume that these are degrees Return Mu : Mu statistic (Fisher et al., 1987) Mu_crit : critical value of Mu for uniform distribution Effect ______ makes a Quantile Quantile plot of data """ if subplot == True: plt.subplot(1, 2, fignum) else: plt.figure(num=fignum) X, Y, dpos, dneg = [], [], 0., 0. if degrees: D = (np.array(D)) % 360 X = D/D.max() X = np.sort(X) n = float(len(D)) i = np.arange(0, len(D)) Y = (i-0.5)/n ds = (i/n)-X dpos = ds.max() dneg = ds.min() plt.plot(Y, X, 'ro') v = dneg + dpos # kuiper's v # Mu of fisher et al. equation 5.16 Mu = v * (np.sqrt(n) - 0.567 + (old_div(1.623, (np.sqrt(n))))) plt.axis([0, 1., 0., 1.]) bounds = plt.axis() notestr = 'N: ' + '%i' % (n) plt.text(.1 * bounds[1], .9 * bounds[3], notestr) notestr = 'Mu: ' + '%7.3f' % (Mu) plt.text(.1 * bounds[1], .8 * bounds[3], notestr) if Mu > 1.347: notestr = "Non-uniform (99%)" elif Mu < 1.207: notestr = "Uniform (95%)" elif Mu > 1.207: notestr = "Uniform (99%)" plt.text(.1 * bounds[1], .7 * bounds[3], notestr) plt.text(.1 * bounds[1], .7 * bounds[3], notestr) plt.title(title) plt.xlabel('Uniform Quantile') plt.ylabel('Data Quantile') return Mu, 1.207
python
def plot_qq_unf(fignum, D, title, subplot=False, degrees=True): """ plots data against a uniform distribution in 0=>360. Parameters _________ fignum : matplotlib figure number D : data title : title for plot subplot : if True, make this number one of two subplots degrees : if True, assume that these are degrees Return Mu : Mu statistic (Fisher et al., 1987) Mu_crit : critical value of Mu for uniform distribution Effect ______ makes a Quantile Quantile plot of data """ if subplot == True: plt.subplot(1, 2, fignum) else: plt.figure(num=fignum) X, Y, dpos, dneg = [], [], 0., 0. if degrees: D = (np.array(D)) % 360 X = D/D.max() X = np.sort(X) n = float(len(D)) i = np.arange(0, len(D)) Y = (i-0.5)/n ds = (i/n)-X dpos = ds.max() dneg = ds.min() plt.plot(Y, X, 'ro') v = dneg + dpos # kuiper's v # Mu of fisher et al. equation 5.16 Mu = v * (np.sqrt(n) - 0.567 + (old_div(1.623, (np.sqrt(n))))) plt.axis([0, 1., 0., 1.]) bounds = plt.axis() notestr = 'N: ' + '%i' % (n) plt.text(.1 * bounds[1], .9 * bounds[3], notestr) notestr = 'Mu: ' + '%7.3f' % (Mu) plt.text(.1 * bounds[1], .8 * bounds[3], notestr) if Mu > 1.347: notestr = "Non-uniform (99%)" elif Mu < 1.207: notestr = "Uniform (95%)" elif Mu > 1.207: notestr = "Uniform (99%)" plt.text(.1 * bounds[1], .7 * bounds[3], notestr) plt.text(.1 * bounds[1], .7 * bounds[3], notestr) plt.title(title) plt.xlabel('Uniform Quantile') plt.ylabel('Data Quantile') return Mu, 1.207
plots data against a uniform distribution in 0=>360. Parameters _________ fignum : matplotlib figure number D : data title : title for plot subplot : if True, make this number one of two subplots degrees : if True, assume that these are degrees Return Mu : Mu statistic (Fisher et al., 1987) Mu_crit : critical value of Mu for uniform distribution Effect ______ makes a Quantile Quantile plot of data
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L362-L417
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): """ 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
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L420-L477
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_di
def plot_di(fignum, DIblock): global globals """ plots directions on equal area net Parameters _________ fignum : matplotlib figure number DIblock : nested list of dec, inc pairs """ X_down, X_up, Y_down, Y_up = [], [], [], [] # initialize some variables plt.figure(num=fignum) # # plot the data - separate upper and lower hemispheres # for rec in DIblock: Up, Down = 0, 0 XY = pmag.dimap(rec[0], rec[1]) if rec[1] >= 0: X_down.append(XY[0]) Y_down.append(XY[1]) else: X_up.append(XY[0]) Y_up.append(XY[1]) # if len(X_down) > 0: # plt.scatter(X_down,Y_down,marker='s',c='r') plt.scatter(X_down, Y_down, marker='o', c='blue') if globals != 0: globals.DIlist = X_down globals.DIlisty = Y_down if len(X_up) > 0: # plt.scatter(X_up,Y_up,marker='s',facecolor='none',edgecolor='black') plt.scatter(X_up, Y_up, marker='o', facecolor='white', edgecolor='blue') if globals != 0: globals.DIlist = X_up globals.DIlisty = Y_up
python
def plot_di(fignum, DIblock): global globals """ plots directions on equal area net Parameters _________ fignum : matplotlib figure number DIblock : nested list of dec, inc pairs """ X_down, X_up, Y_down, Y_up = [], [], [], [] # initialize some variables plt.figure(num=fignum) # # plot the data - separate upper and lower hemispheres # for rec in DIblock: Up, Down = 0, 0 XY = pmag.dimap(rec[0], rec[1]) if rec[1] >= 0: X_down.append(XY[0]) Y_down.append(XY[1]) else: X_up.append(XY[0]) Y_up.append(XY[1]) # if len(X_down) > 0: # plt.scatter(X_down,Y_down,marker='s',c='r') plt.scatter(X_down, Y_down, marker='o', c='blue') if globals != 0: globals.DIlist = X_down globals.DIlisty = Y_down if len(X_up) > 0: # plt.scatter(X_up,Y_up,marker='s',facecolor='none',edgecolor='black') plt.scatter(X_up, Y_up, marker='o', facecolor='white', edgecolor='blue') if globals != 0: globals.DIlist = X_up globals.DIlisty = Y_up
plots directions on equal area net Parameters _________ fignum : matplotlib figure number DIblock : nested list of dec, inc pairs
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L541-L577
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_di_sym
def plot_di_sym(fignum, DIblock, sym): global globals """ plots directions on equal area net Parameters _________ fignum : matplotlib figure number DIblock : nested list of dec, inc pairs sym : set matplotlib symbol (e.g., 'bo' for blue circles) """ X_down, X_up, Y_down, Y_up = [], [], [], [] # initialize some variables plt.figure(num=fignum) # # plot the data - separate upper and lower hemispheres # for rec in DIblock: Up, Down = 0, 0 XY = pmag.dimap(rec[0], rec[1]) if rec[1] >= 0: X_down.append(XY[0]) Y_down.append(XY[1]) else: X_up.append(XY[0]) Y_up.append(XY[1]) # if 'size' not in list(sym.keys()): size = 50 else: size = sym['size'] if 'edgecolor' not in list(sym.keys()): sym['edgecolor'] = 'k' if len(X_down) > 0: plt.scatter(X_down, Y_down, marker=sym['lower'][0], c=sym['lower'][1], s=size, edgecolor=sym['edgecolor']) if globals != 0: globals.DIlist = X_down globals.DIlisty = Y_down if len(X_up) > 0: plt.scatter(X_up, Y_up, marker=sym['upper'][0], c=sym['upper'][1], s=size, edgecolor=sym['edgecolor']) if globals != 0: globals.DIlist = X_up globals.DIlisty = Y_up
python
def plot_di_sym(fignum, DIblock, sym): global globals """ plots directions on equal area net Parameters _________ fignum : matplotlib figure number DIblock : nested list of dec, inc pairs sym : set matplotlib symbol (e.g., 'bo' for blue circles) """ X_down, X_up, Y_down, Y_up = [], [], [], [] # initialize some variables plt.figure(num=fignum) # # plot the data - separate upper and lower hemispheres # for rec in DIblock: Up, Down = 0, 0 XY = pmag.dimap(rec[0], rec[1]) if rec[1] >= 0: X_down.append(XY[0]) Y_down.append(XY[1]) else: X_up.append(XY[0]) Y_up.append(XY[1]) # if 'size' not in list(sym.keys()): size = 50 else: size = sym['size'] if 'edgecolor' not in list(sym.keys()): sym['edgecolor'] = 'k' if len(X_down) > 0: plt.scatter(X_down, Y_down, marker=sym['lower'][0], c=sym['lower'][1], s=size, edgecolor=sym['edgecolor']) if globals != 0: globals.DIlist = X_down globals.DIlisty = Y_down if len(X_up) > 0: plt.scatter(X_up, Y_up, marker=sym['upper'][0], c=sym['upper'][1], s=size, edgecolor=sym['edgecolor']) if globals != 0: globals.DIlist = X_up globals.DIlisty = Y_up
plots directions on equal area net Parameters _________ fignum : matplotlib figure number DIblock : nested list of dec, inc pairs sym : set matplotlib symbol (e.g., 'bo' for blue circles)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L580-L622
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_circ
def plot_circ(fignum, pole, ang, col): """ function to put a small circle on an equal area projection plot, fig,fignum Parameters __________ fignum : matplotlib figure number pole : dec,inc of center of circle ang : angle of circle col : """ plt.figure(num=fignum) D_c, I_c = pmag.circ(pole[0], pole[1], ang) X_c_up, Y_c_up = [], [] X_c_d, Y_c_d = [], [] for k in range(len(D_c)): XY = pmag.dimap(D_c[k], I_c[k]) if I_c[k] < 0: X_c_up.append(XY[0]) Y_c_up.append(XY[1]) else: X_c_d.append(XY[0]) Y_c_d.append(XY[1]) plt.plot(X_c_d, Y_c_d, col + '.', ms=5) plt.plot(X_c_up, Y_c_up, 'c.', ms=2)
python
def plot_circ(fignum, pole, ang, col): """ function to put a small circle on an equal area projection plot, fig,fignum Parameters __________ fignum : matplotlib figure number pole : dec,inc of center of circle ang : angle of circle col : """ plt.figure(num=fignum) D_c, I_c = pmag.circ(pole[0], pole[1], ang) X_c_up, Y_c_up = [], [] X_c_d, Y_c_d = [], [] for k in range(len(D_c)): XY = pmag.dimap(D_c[k], I_c[k]) if I_c[k] < 0: X_c_up.append(XY[0]) Y_c_up.append(XY[1]) else: X_c_d.append(XY[0]) Y_c_d.append(XY[1]) plt.plot(X_c_d, Y_c_d, col + '.', ms=5) plt.plot(X_c_up, Y_c_up, 'c.', ms=2)
function to put a small circle on an equal area projection plot, fig,fignum Parameters __________ fignum : matplotlib figure number pole : dec,inc of center of circle ang : angle of circle col :
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L625-L648
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_zij
def plot_zij(fignum, datablock, angle, s, norm=True): """ function to make Zijderveld diagrams Parameters __________ fignum : matplotlib figure number datablock : nested list of [step, dec, inc, M (Am2), type, quality] where type is a string, either 'ZI' or 'IZ' for IZZI experiments angle : desired rotation in the horizontal plane (0 puts X on X axis) s : specimen name norm : if True, normalize to initial magnetization = unity Effects _______ makes a zijderveld plot """ global globals plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) amin, amax = 0., -100. if norm == 0: fact = 1. else: fact = (1./datablock[0][3]) # normalize to NRM=1 # convert datablock to DataFrame data with dec,inc, int data = pd.DataFrame(datablock) if len(data.columns) == 5: data.columns = ['treat', 'dec', 'inc', 'int', 'quality'] if len(data.columns) == 6: data.columns = ['treat', 'dec', 'inc', 'int', 'type', 'quality'] elif len(data.columns) == 7: data.columns = ['treat', 'dec', 'inc', 'int', 'type', 'quality', 'y'] #print (len(data.columns)) data['int'] = data['int']*fact # normalize data['dec'] = (data['dec']-angle) % 360 # adjust X axis angle gdata = data[data['quality'].str.contains('g')] bdata = data[data['quality'].str.contains('b')] forVDS = gdata[['dec', 'inc', 'int']].values gXYZ = pd.DataFrame(pmag.dir2cart(forVDS)) gXYZ.columns = ['X', 'Y', 'Z'] amax = np.maximum(gXYZ.X.max(), gXYZ.Z.max()) amin = np.minimum(gXYZ.X.min(), gXYZ.Z.min()) if amin > 0: amin = 0 bXYZ = pmag.dir2cart(bdata[['dec', 'inc', 'int']].values).transpose() # plotting stuff if angle != 0: tempstr = "\n Declination rotated by: " + str(angle) + '\n' if globals != 0: globals.text.insert(globals.END, tempstr) globals.Zlist = gXYZ['x'].tolist() globals.Zlisty = gXYZ['y'].tolist() globals.Zlistz = gXYZ['z'].tolist() if len(bXYZ) > 0: plt.scatter(bXYZ[0], bXYZ[1], marker='d', c='y', s=30) plt.scatter(bXYZ[0], bXYZ[2], marker='d', c='y', s=30) plt.plot(gXYZ['X'], gXYZ['Y'], 'ro') plt.plot(gXYZ['X'], gXYZ['Z'], 'ws', markeredgecolor='blue') plt.plot(gXYZ['X'], gXYZ['Y'], 'r-') plt.plot(gXYZ['X'], gXYZ['Z'], 'b-') for k in range(len(gXYZ)): plt.annotate(str(k), (gXYZ['X'][k], gXYZ['Z'] [k]), ha='left', va='bottom') if amin > 0 and amax >0:amin=0 # complete the line if amin < 0 and amax <0:amax=0 # complete the line xline = [amin, amax] # yline=[-amax,-amin] yline = [amax, amin] zline = [0, 0] plt.plot(xline, zline, 'k-') plt.plot(zline, xline, 'k-') if angle != 0: xlab = "X: rotated to Dec = " + '%7.1f' % (angle) if angle == 0: xlab = "X: rotated to Dec = " + '%7.1f' % (angle) plt.xlabel(xlab) plt.ylabel("Circles: Y; Squares: Z") tstring = s + ': NRM = ' + '%9.2e' % (datablock[0][3]) plt.axis([amin, amax, amax, amin]) plt.axis("equal") plt.title(tstring)
python
def plot_zij(fignum, datablock, angle, s, norm=True): """ function to make Zijderveld diagrams Parameters __________ fignum : matplotlib figure number datablock : nested list of [step, dec, inc, M (Am2), type, quality] where type is a string, either 'ZI' or 'IZ' for IZZI experiments angle : desired rotation in the horizontal plane (0 puts X on X axis) s : specimen name norm : if True, normalize to initial magnetization = unity Effects _______ makes a zijderveld plot """ global globals plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) amin, amax = 0., -100. if norm == 0: fact = 1. else: fact = (1./datablock[0][3]) # normalize to NRM=1 # convert datablock to DataFrame data with dec,inc, int data = pd.DataFrame(datablock) if len(data.columns) == 5: data.columns = ['treat', 'dec', 'inc', 'int', 'quality'] if len(data.columns) == 6: data.columns = ['treat', 'dec', 'inc', 'int', 'type', 'quality'] elif len(data.columns) == 7: data.columns = ['treat', 'dec', 'inc', 'int', 'type', 'quality', 'y'] #print (len(data.columns)) data['int'] = data['int']*fact # normalize data['dec'] = (data['dec']-angle) % 360 # adjust X axis angle gdata = data[data['quality'].str.contains('g')] bdata = data[data['quality'].str.contains('b')] forVDS = gdata[['dec', 'inc', 'int']].values gXYZ = pd.DataFrame(pmag.dir2cart(forVDS)) gXYZ.columns = ['X', 'Y', 'Z'] amax = np.maximum(gXYZ.X.max(), gXYZ.Z.max()) amin = np.minimum(gXYZ.X.min(), gXYZ.Z.min()) if amin > 0: amin = 0 bXYZ = pmag.dir2cart(bdata[['dec', 'inc', 'int']].values).transpose() # plotting stuff if angle != 0: tempstr = "\n Declination rotated by: " + str(angle) + '\n' if globals != 0: globals.text.insert(globals.END, tempstr) globals.Zlist = gXYZ['x'].tolist() globals.Zlisty = gXYZ['y'].tolist() globals.Zlistz = gXYZ['z'].tolist() if len(bXYZ) > 0: plt.scatter(bXYZ[0], bXYZ[1], marker='d', c='y', s=30) plt.scatter(bXYZ[0], bXYZ[2], marker='d', c='y', s=30) plt.plot(gXYZ['X'], gXYZ['Y'], 'ro') plt.plot(gXYZ['X'], gXYZ['Z'], 'ws', markeredgecolor='blue') plt.plot(gXYZ['X'], gXYZ['Y'], 'r-') plt.plot(gXYZ['X'], gXYZ['Z'], 'b-') for k in range(len(gXYZ)): plt.annotate(str(k), (gXYZ['X'][k], gXYZ['Z'] [k]), ha='left', va='bottom') if amin > 0 and amax >0:amin=0 # complete the line if amin < 0 and amax <0:amax=0 # complete the line xline = [amin, amax] # yline=[-amax,-amin] yline = [amax, amin] zline = [0, 0] plt.plot(xline, zline, 'k-') plt.plot(zline, xline, 'k-') if angle != 0: xlab = "X: rotated to Dec = " + '%7.1f' % (angle) if angle == 0: xlab = "X: rotated to Dec = " + '%7.1f' % (angle) plt.xlabel(xlab) plt.ylabel("Circles: Y; Squares: Z") tstring = s + ': NRM = ' + '%9.2e' % (datablock[0][3]) plt.axis([amin, amax, amax, amin]) plt.axis("equal") plt.title(tstring)
function to make Zijderveld diagrams Parameters __________ fignum : matplotlib figure number datablock : nested list of [step, dec, inc, M (Am2), type, quality] where type is a string, either 'ZI' or 'IZ' for IZZI experiments angle : desired rotation in the horizontal plane (0 puts X on X axis) s : specimen name norm : if True, normalize to initial magnetization = unity Effects _______ makes a zijderveld plot
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L654-L738
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_mag
def plot_mag(fignum, datablock, s, num, units, norm): """ plots magnetization against (de)magnetizing temperature or field Parameters _________________ fignum : matplotlib figure number for plotting datablock : nested list of [step, 0, 0, magnetization, 1,quality] s : string for title num : matplotlib figure number, can set to 1 units : [T,K,U] for tesla, kelvin or arbitrary norm : [True,False] if True, normalize Effects ______ plots figure """ global globals, graphmenu Ints = [] for plotrec in datablock: Ints.append(plotrec[3]) Ints.sort() plt.figure(num=fignum) T, M, Tv, recnum = [], [], [], 0 Mex, Tex, Vdif = [], [], [] recbak = [] for rec in datablock: if rec[5] == 'g': if units == "T": T.append(rec[0] * 1e3) Tv.append(rec[0] * 1e3) if recnum > 0: Tv.append(rec[0] * 1e3) elif units == "U": T.append(rec[0]) Tv.append(rec[0]) if recnum > 0: Tv.append(rec[0]) elif units == "K": T.append(rec[0] - 273) Tv.append(rec[0] - 273) if recnum > 0: Tv.append(rec[0] - 273) elif "T" in units and "K" in units: if rec[0] < 1.: T.append(rec[0] * 1e3) Tv.append(rec[0] * 1e3) else: T.append(rec[0] - 273) Tv.append(rec[0] - 273) if recnum > 0: Tv.append(rec[0] - 273) else: T.append(rec[0]) Tv.append(rec[0]) if recnum > 0: Tv.append(rec[0]) if norm: M.append(old_div(rec[3], Ints[-1])) else: M.append(rec[3]) if recnum > 0 and len(rec) > 0 and len(recbak) > 0: v = [] if recbak[0] != rec[0]: V0 = pmag.dir2cart([recbak[1], recbak[2], recbak[3]]) V1 = pmag.dir2cart([rec[1], rec[2], rec[3]]) for el in range(3): v.append(abs(V1[el] - V0[el])) vdir = pmag.cart2dir(v) # append vector difference Vdif.append(old_div(vdir[2], Ints[-1])) Vdif.append(old_div(vdir[2], Ints[-1])) recbak = [] for el in rec: recbak.append(el) delta = .005 * M[0] if num == 1: if recnum % 2 == 0: plt.text(T[-1] + delta, M[-1], (' ' + str(recnum)), fontsize=9) recnum += 1 else: if rec[0] < 200: Tex.append(rec[0] * 1e3) if rec[0] >= 200: Tex.append(rec[0] - 273) Mex.append(old_div(rec[3], Ints[-1])) recnum += 1 if globals != 0: globals.MTlist = T globals.MTlisty = M if len(Mex) > 0 and len(Tex) > 0: plt.scatter(Tex, Mex, marker='d', color='k') if len(Vdif) > 0: Vdif.append(old_div(vdir[2], Ints[-1])) Vdif.append(0) if Tv: Tv.append(Tv[-1]) plt.plot(T, M) plt.plot(T, M, 'ro') if len(Tv) == len(Vdif) and norm: plt.plot(Tv, Vdif, 'g-') if units == "T": plt.xlabel("Step (mT)") elif units == "K": plt.xlabel("Step (C)") elif units == "J": plt.xlabel("Step (J)") else: plt.xlabel("Step [mT,C]") if norm == 1: plt.ylabel("Fractional Magnetization") if norm == 0: plt.ylabel("Magnetization") plt.axvline(0, color='k') plt.axhline(0, color='k') tstring = s plt.title(tstring) plt.draw()
python
def plot_mag(fignum, datablock, s, num, units, norm): """ plots magnetization against (de)magnetizing temperature or field Parameters _________________ fignum : matplotlib figure number for plotting datablock : nested list of [step, 0, 0, magnetization, 1,quality] s : string for title num : matplotlib figure number, can set to 1 units : [T,K,U] for tesla, kelvin or arbitrary norm : [True,False] if True, normalize Effects ______ plots figure """ global globals, graphmenu Ints = [] for plotrec in datablock: Ints.append(plotrec[3]) Ints.sort() plt.figure(num=fignum) T, M, Tv, recnum = [], [], [], 0 Mex, Tex, Vdif = [], [], [] recbak = [] for rec in datablock: if rec[5] == 'g': if units == "T": T.append(rec[0] * 1e3) Tv.append(rec[0] * 1e3) if recnum > 0: Tv.append(rec[0] * 1e3) elif units == "U": T.append(rec[0]) Tv.append(rec[0]) if recnum > 0: Tv.append(rec[0]) elif units == "K": T.append(rec[0] - 273) Tv.append(rec[0] - 273) if recnum > 0: Tv.append(rec[0] - 273) elif "T" in units and "K" in units: if rec[0] < 1.: T.append(rec[0] * 1e3) Tv.append(rec[0] * 1e3) else: T.append(rec[0] - 273) Tv.append(rec[0] - 273) if recnum > 0: Tv.append(rec[0] - 273) else: T.append(rec[0]) Tv.append(rec[0]) if recnum > 0: Tv.append(rec[0]) if norm: M.append(old_div(rec[3], Ints[-1])) else: M.append(rec[3]) if recnum > 0 and len(rec) > 0 and len(recbak) > 0: v = [] if recbak[0] != rec[0]: V0 = pmag.dir2cart([recbak[1], recbak[2], recbak[3]]) V1 = pmag.dir2cart([rec[1], rec[2], rec[3]]) for el in range(3): v.append(abs(V1[el] - V0[el])) vdir = pmag.cart2dir(v) # append vector difference Vdif.append(old_div(vdir[2], Ints[-1])) Vdif.append(old_div(vdir[2], Ints[-1])) recbak = [] for el in rec: recbak.append(el) delta = .005 * M[0] if num == 1: if recnum % 2 == 0: plt.text(T[-1] + delta, M[-1], (' ' + str(recnum)), fontsize=9) recnum += 1 else: if rec[0] < 200: Tex.append(rec[0] * 1e3) if rec[0] >= 200: Tex.append(rec[0] - 273) Mex.append(old_div(rec[3], Ints[-1])) recnum += 1 if globals != 0: globals.MTlist = T globals.MTlisty = M if len(Mex) > 0 and len(Tex) > 0: plt.scatter(Tex, Mex, marker='d', color='k') if len(Vdif) > 0: Vdif.append(old_div(vdir[2], Ints[-1])) Vdif.append(0) if Tv: Tv.append(Tv[-1]) plt.plot(T, M) plt.plot(T, M, 'ro') if len(Tv) == len(Vdif) and norm: plt.plot(Tv, Vdif, 'g-') if units == "T": plt.xlabel("Step (mT)") elif units == "K": plt.xlabel("Step (C)") elif units == "J": plt.xlabel("Step (J)") else: plt.xlabel("Step [mT,C]") if norm == 1: plt.ylabel("Fractional Magnetization") if norm == 0: plt.ylabel("Magnetization") plt.axvline(0, color='k') plt.axhline(0, color='k') tstring = s plt.title(tstring) plt.draw()
plots magnetization against (de)magnetizing temperature or field Parameters _________________ fignum : matplotlib figure number for plotting datablock : nested list of [step, 0, 0, magnetization, 1,quality] s : string for title num : matplotlib figure number, can set to 1 units : [T,K,U] for tesla, kelvin or arbitrary norm : [True,False] if True, normalize Effects ______ plots figure
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L743-L861
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): """ 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
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L867-L937
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_dir
def plot_dir(ZED, pars, datablock, angle): """ function to put the great circle on the equal area projection and plot start and end points of calculation DEPRECATED (used in zeq_magic) """ # # find start and end points from datablock # if pars["calculation_type"] == 'DE-FM': x, y = [], [] plt.figure(num=ZED['eqarea']) XY = pmag.dimap(pars["specimen_dec"], pars["specimen_inc"]) x.append(XY[0]) y.append(XY[1]) plt.scatter(x, y, marker='^', s=80, c='r') plt.show() return StartDir, EndDir = [0, 0, 1.], [0, 0, 1.] for rec in datablock: if rec[0] == pars["measurement_step_min"]: StartDir[0] = rec[1] StartDir[1] = rec[2] if pars["specimen_direction_type"] == 'l': StartDir[2] = rec[3]/datablock[0][3] if rec[0] == pars["measurement_step_max"]: EndDir[0] = rec[1] EndDir[1] = rec[2] if pars["specimen_direction_type"] == 'l': EndDir[2] = rec[3]/datablock[0][3] # # put them on the plots # x, y, z, pole = [], [], [], [] if pars["calculation_type"] != 'DE-BFP': plt.figure(num=ZED['eqarea']) XY = pmag.dimap(pars["specimen_dec"], pars["specimen_inc"]) x.append(XY[0]) y.append(XY[1]) plt.scatter(x, y, marker='d', s=80, c='b') x, y, z = [], [], [] StartDir[0] = StartDir[0] - angle EndDir[0] = EndDir[0] - angle XYZs = pmag.dir2cart(StartDir) x.append(XYZs[0]) y.append(XYZs[1]) z.append(XYZs[2]) XYZe = pmag.dir2cart(EndDir) x.append(XYZe[0]) y.append(XYZe[1]) z.append(XYZe[2]) plt.figure(num=ZED['zijd']) plt.scatter(x, y, marker='d', s=80, c='g') plt.scatter(x, z, marker='d', s=80, c='g') plt.scatter(x, y, marker='o', c='r', s=20) plt.scatter(x, z, marker='s', c='w', s=20) # # put on best fit line # new way (from Jeff Gee's favorite website http://GET THIS): # P1=pmag.dir2cart([(pars["specimen_dec"]-angle),pars["specimen_inc"],1.]) # princ comp. # P2=pmag.dir2cart([(pars["specimen_dec"]-angle-180.),-pars["specimen_inc"],1.]) # antipode of princ comp. # P21,Ps,Pe,Xs,Xe=[],[],[],[],[] # for i in range(3): # P21.append(P2[i]-P1[i]) # Ps.append(XYZs[i]-P1[i]) # Pe.append(XYZe[i]-P1[i]) # norm=pmag.cart2dir(P21)[2] # us=(Ps[0]*P21[0]+Ps[1]*P21[1]+Ps[2]*P21[2])/(norm**2) # ue=(Pe[0]*P21[0]+Pe[1]*P21[1]+Pe[2]*P21[2])/(norm**2) # px,py,pz=[],[],[] # for i in range(3): # Xs.append(P1[i]+us*(P2[i]-P1[i])) # Xe.append(P1[i]+ue*(P2[i]-P1[i])) # old way: cm = pars["center_of_mass"] if cm != [0., 0., 0.]: cm = np.array(pars["center_of_mass"])/datablock[0][3] cmDir = pmag.cart2dir(cm) cmDir[0] = cmDir[0] - angle cm = pmag.dir2cart(cmDir) diff = [] for i in range(3): diff.append(XYZe[i] - XYZs[i]) R = np.sqrt(diff[0]**2 + diff[1]**2 + diff[2]**2) P = pmag.dir2cart( ((pars["specimen_dec"] - angle), pars["specimen_inc"], R/2.5)) px, py, pz = [], [], [] px.append((cm[0] + P[0])) py.append((cm[1] + P[1])) pz.append((cm[2] + P[2])) px.append((cm[0] - P[0])) py.append((cm[1] - P[1])) pz.append((cm[2] - P[2])) plt.plot(px, py, 'g', linewidth=2) plt.plot(px, pz, 'g', linewidth=2) plt.axis("equal") else: plt.figure(num=ZED['eqarea']) XY = pmag.dimap(StartDir[0], StartDir[1]) x.append(XY[0]) y.append(XY[1]) XY = pmag.dimap(EndDir[0], EndDir[1]) x.append(XY[0]) y.append(XY[1]) plt.scatter(x, y, marker='d', s=80, c='b') pole.append(pars["specimen_dec"]) pole.append(pars["specimen_inc"]) plot_circ(ZED['eqarea'], pole, 90., 'g') plt.xlim((-1., 1.)) plt.ylim((-1., 1.)) plt.axis("equal")
python
def plot_dir(ZED, pars, datablock, angle): """ function to put the great circle on the equal area projection and plot start and end points of calculation DEPRECATED (used in zeq_magic) """ # # find start and end points from datablock # if pars["calculation_type"] == 'DE-FM': x, y = [], [] plt.figure(num=ZED['eqarea']) XY = pmag.dimap(pars["specimen_dec"], pars["specimen_inc"]) x.append(XY[0]) y.append(XY[1]) plt.scatter(x, y, marker='^', s=80, c='r') plt.show() return StartDir, EndDir = [0, 0, 1.], [0, 0, 1.] for rec in datablock: if rec[0] == pars["measurement_step_min"]: StartDir[0] = rec[1] StartDir[1] = rec[2] if pars["specimen_direction_type"] == 'l': StartDir[2] = rec[3]/datablock[0][3] if rec[0] == pars["measurement_step_max"]: EndDir[0] = rec[1] EndDir[1] = rec[2] if pars["specimen_direction_type"] == 'l': EndDir[2] = rec[3]/datablock[0][3] # # put them on the plots # x, y, z, pole = [], [], [], [] if pars["calculation_type"] != 'DE-BFP': plt.figure(num=ZED['eqarea']) XY = pmag.dimap(pars["specimen_dec"], pars["specimen_inc"]) x.append(XY[0]) y.append(XY[1]) plt.scatter(x, y, marker='d', s=80, c='b') x, y, z = [], [], [] StartDir[0] = StartDir[0] - angle EndDir[0] = EndDir[0] - angle XYZs = pmag.dir2cart(StartDir) x.append(XYZs[0]) y.append(XYZs[1]) z.append(XYZs[2]) XYZe = pmag.dir2cart(EndDir) x.append(XYZe[0]) y.append(XYZe[1]) z.append(XYZe[2]) plt.figure(num=ZED['zijd']) plt.scatter(x, y, marker='d', s=80, c='g') plt.scatter(x, z, marker='d', s=80, c='g') plt.scatter(x, y, marker='o', c='r', s=20) plt.scatter(x, z, marker='s', c='w', s=20) # # put on best fit line # new way (from Jeff Gee's favorite website http://GET THIS): # P1=pmag.dir2cart([(pars["specimen_dec"]-angle),pars["specimen_inc"],1.]) # princ comp. # P2=pmag.dir2cart([(pars["specimen_dec"]-angle-180.),-pars["specimen_inc"],1.]) # antipode of princ comp. # P21,Ps,Pe,Xs,Xe=[],[],[],[],[] # for i in range(3): # P21.append(P2[i]-P1[i]) # Ps.append(XYZs[i]-P1[i]) # Pe.append(XYZe[i]-P1[i]) # norm=pmag.cart2dir(P21)[2] # us=(Ps[0]*P21[0]+Ps[1]*P21[1]+Ps[2]*P21[2])/(norm**2) # ue=(Pe[0]*P21[0]+Pe[1]*P21[1]+Pe[2]*P21[2])/(norm**2) # px,py,pz=[],[],[] # for i in range(3): # Xs.append(P1[i]+us*(P2[i]-P1[i])) # Xe.append(P1[i]+ue*(P2[i]-P1[i])) # old way: cm = pars["center_of_mass"] if cm != [0., 0., 0.]: cm = np.array(pars["center_of_mass"])/datablock[0][3] cmDir = pmag.cart2dir(cm) cmDir[0] = cmDir[0] - angle cm = pmag.dir2cart(cmDir) diff = [] for i in range(3): diff.append(XYZe[i] - XYZs[i]) R = np.sqrt(diff[0]**2 + diff[1]**2 + diff[2]**2) P = pmag.dir2cart( ((pars["specimen_dec"] - angle), pars["specimen_inc"], R/2.5)) px, py, pz = [], [], [] px.append((cm[0] + P[0])) py.append((cm[1] + P[1])) pz.append((cm[2] + P[2])) px.append((cm[0] - P[0])) py.append((cm[1] - P[1])) pz.append((cm[2] - P[2])) plt.plot(px, py, 'g', linewidth=2) plt.plot(px, pz, 'g', linewidth=2) plt.axis("equal") else: plt.figure(num=ZED['eqarea']) XY = pmag.dimap(StartDir[0], StartDir[1]) x.append(XY[0]) y.append(XY[1]) XY = pmag.dimap(EndDir[0], EndDir[1]) x.append(XY[0]) y.append(XY[1]) plt.scatter(x, y, marker='d', s=80, c='b') pole.append(pars["specimen_dec"]) pole.append(pars["specimen_inc"]) plot_circ(ZED['eqarea'], pole, 90., 'g') plt.xlim((-1., 1.)) plt.ylim((-1., 1.)) plt.axis("equal")
function to put the great circle on the equal area projection and plot start and end points of calculation DEPRECATED (used in zeq_magic)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L940-L1053
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_arai
def plot_arai(fignum, indata, s, units): """ makes Arai plots for Thellier-Thellier type experiments Parameters __________ fignum : figure number of matplotlib plot object indata : nested list of data for Arai plots: the araiblock of data prepared by pmag.sortarai() s : specimen name units : [K, J, ""] (kelvin, joules, unknown) Effects _______ makes the Arai plot """ global globals plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) x, y, x_zi, y_zi, x_iz, y_iz, xptrm, yptrm, xptrmt, yptrmt = [ ], [], [], [], [], [], [], [], [], [] xzptrm, yzptrm = [], [] # zero field ptrm checks zptrm_check = [] first_Z, first_I, ptrm_check, ptrm_tail, zptrm_check = indata[ 0], indata[1], indata[2], indata[3], indata[4] if len(indata) > 6: if len(indata[-1]) > 1: s = s + ":PERP" # there are Delta checks, must be a LP-PI-M-S perp experiment recnum, yes, Nptrm, Nptrmt, diffcum = 0, 0, 0, 0, 0 # plot the NRM-pTRM data forVDS = [] for zrec in first_Z: forVDS.append([zrec[1], zrec[2], old_div(zrec[3], first_Z[0][3])]) ZI = zrec[4] if zrec[0] == '0': irec = ['0', 0, 0, 0] if zrec[0] == '273' and units == 'K': irec = ['273', 0, 0, 0] else: for irec in first_I: if irec[0] == zrec[0]: break # save the NRM data used for calculation in Vi x.append(old_div(irec[3], first_Z[0][3])) y.append(old_div(zrec[3], first_Z[0][3])) if ZI == 1: x_zi.append(old_div(irec[3], first_Z[0][3])) y_zi.append(old_div(zrec[3], first_Z[0][3])) else: x_iz.append(old_div(irec[3], first_Z[0][3])) y_iz.append(old_div(zrec[3], first_Z[0][3])) plt.text(x[-1], y[-1], (' ' + str(recnum)), fontsize=9) recnum += 1 # now deal with ptrm checks. if len(ptrm_check) != 0: for prec in ptrm_check: step = prec[0] for zrec in first_Z: if zrec[0] == step: break xptrm.append(old_div(prec[3], first_Z[0][3])) yptrm.append(old_div(zrec[3], first_Z[0][3])) # now deal with zptrm checks. if len(zptrm_check) != 0: for prec in zptrm_check: step = prec[0] for zrec in first_Z: if zrec[0] == step: break xzptrm.append(old_div(prec[3], first_Z[0][3])) yzptrm.append(old_div(zrec[3], first_Z[0][3])) # and the pTRM tails if len(ptrm_tail) != 0: for trec in ptrm_tail: step = trec[0] for irec in first_I: if irec[0] == step: break xptrmt.append(old_div(irec[3], first_Z[0][3])) yptrmt.append((old_div(trec[3], first_Z[0][3]))) # now plot stuff if len(x) == 0: print("Can't do nuttin for ya") return try: if len(x_zi) > 0: plt.scatter(x_zi, y_zi, marker='o', c='r', edgecolors="none") # zero field-infield if len(x_iz) > 0: plt.scatter(x_iz, y_iz, marker='s', c='b', faceted="True") # infield-zerofield except: if len(x_zi) > 0: plt.scatter(x_zi, y_zi, marker='o', c='r') # zero field-infield if len(x_iz) > 0: plt.scatter(x_iz, y_iz, marker='s', c='b') # infield-zerofield plt.plot(x, y, 'r') if globals != 0: globals.MTlist = x globals.MTlisty = y if len(xptrm) > 0: plt.scatter(xptrm, yptrm, marker='^', c='g', s=80) if len(xzptrm) > 0: plt.scatter(xzptrm, yzptrm, marker='v', c='c', s=80) if len(xptrmt) > 0: plt.scatter(xptrmt, yptrmt, marker='s', c='b', s=80) try: plt.axhline(0, color='k') plt.axvline(0, color='k') except: pass plt.xlabel("pTRM gained") plt.ylabel("NRM remaining") tstring = s + ': NRM = ' + '%9.2e' % (first_Z[0][3]) plt.title(tstring) # put on VDS vds = pmag.dovds(forVDS) plt.axhline(vds, color='b') plt.text(1., vds - .1, ('VDS '), fontsize=9)
python
def plot_arai(fignum, indata, s, units): """ makes Arai plots for Thellier-Thellier type experiments Parameters __________ fignum : figure number of matplotlib plot object indata : nested list of data for Arai plots: the araiblock of data prepared by pmag.sortarai() s : specimen name units : [K, J, ""] (kelvin, joules, unknown) Effects _______ makes the Arai plot """ global globals plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) x, y, x_zi, y_zi, x_iz, y_iz, xptrm, yptrm, xptrmt, yptrmt = [ ], [], [], [], [], [], [], [], [], [] xzptrm, yzptrm = [], [] # zero field ptrm checks zptrm_check = [] first_Z, first_I, ptrm_check, ptrm_tail, zptrm_check = indata[ 0], indata[1], indata[2], indata[3], indata[4] if len(indata) > 6: if len(indata[-1]) > 1: s = s + ":PERP" # there are Delta checks, must be a LP-PI-M-S perp experiment recnum, yes, Nptrm, Nptrmt, diffcum = 0, 0, 0, 0, 0 # plot the NRM-pTRM data forVDS = [] for zrec in first_Z: forVDS.append([zrec[1], zrec[2], old_div(zrec[3], first_Z[0][3])]) ZI = zrec[4] if zrec[0] == '0': irec = ['0', 0, 0, 0] if zrec[0] == '273' and units == 'K': irec = ['273', 0, 0, 0] else: for irec in first_I: if irec[0] == zrec[0]: break # save the NRM data used for calculation in Vi x.append(old_div(irec[3], first_Z[0][3])) y.append(old_div(zrec[3], first_Z[0][3])) if ZI == 1: x_zi.append(old_div(irec[3], first_Z[0][3])) y_zi.append(old_div(zrec[3], first_Z[0][3])) else: x_iz.append(old_div(irec[3], first_Z[0][3])) y_iz.append(old_div(zrec[3], first_Z[0][3])) plt.text(x[-1], y[-1], (' ' + str(recnum)), fontsize=9) recnum += 1 # now deal with ptrm checks. if len(ptrm_check) != 0: for prec in ptrm_check: step = prec[0] for zrec in first_Z: if zrec[0] == step: break xptrm.append(old_div(prec[3], first_Z[0][3])) yptrm.append(old_div(zrec[3], first_Z[0][3])) # now deal with zptrm checks. if len(zptrm_check) != 0: for prec in zptrm_check: step = prec[0] for zrec in first_Z: if zrec[0] == step: break xzptrm.append(old_div(prec[3], first_Z[0][3])) yzptrm.append(old_div(zrec[3], first_Z[0][3])) # and the pTRM tails if len(ptrm_tail) != 0: for trec in ptrm_tail: step = trec[0] for irec in first_I: if irec[0] == step: break xptrmt.append(old_div(irec[3], first_Z[0][3])) yptrmt.append((old_div(trec[3], first_Z[0][3]))) # now plot stuff if len(x) == 0: print("Can't do nuttin for ya") return try: if len(x_zi) > 0: plt.scatter(x_zi, y_zi, marker='o', c='r', edgecolors="none") # zero field-infield if len(x_iz) > 0: plt.scatter(x_iz, y_iz, marker='s', c='b', faceted="True") # infield-zerofield except: if len(x_zi) > 0: plt.scatter(x_zi, y_zi, marker='o', c='r') # zero field-infield if len(x_iz) > 0: plt.scatter(x_iz, y_iz, marker='s', c='b') # infield-zerofield plt.plot(x, y, 'r') if globals != 0: globals.MTlist = x globals.MTlisty = y if len(xptrm) > 0: plt.scatter(xptrm, yptrm, marker='^', c='g', s=80) if len(xzptrm) > 0: plt.scatter(xzptrm, yzptrm, marker='v', c='c', s=80) if len(xptrmt) > 0: plt.scatter(xptrmt, yptrmt, marker='s', c='b', s=80) try: plt.axhline(0, color='k') plt.axvline(0, color='k') except: pass plt.xlabel("pTRM gained") plt.ylabel("NRM remaining") tstring = s + ': NRM = ' + '%9.2e' % (first_Z[0][3]) plt.title(tstring) # put on VDS vds = pmag.dovds(forVDS) plt.axhline(vds, color='b') plt.text(1., vds - .1, ('VDS '), fontsize=9)
makes Arai plots for Thellier-Thellier type experiments Parameters __________ fignum : figure number of matplotlib plot object indata : nested list of data for Arai plots: the araiblock of data prepared by pmag.sortarai() s : specimen name units : [K, J, ""] (kelvin, joules, unknown) Effects _______ makes the Arai plot
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1057-L1176
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_np
def plot_np(fignum, indata, s, units): """ makes plot of de(re)magnetization data for Thellier-Thellier type experiment Parameters __________ fignum : matplotlib figure number indata : araiblock from, e.g., pmag.sortarai() s : specimen name units : [K, J, ""] (kelvin, joules, unknown) Effect _______ Makes a plot """ global globals first_Z, first_I, ptrm_check, ptrm_tail = indata[0], indata[1], indata[2], indata[3] plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) X, Y, recnum = [], [], 0 # for rec in first_Z: if units == "K": if rec[0] != 0: X.append(rec[0] - 273.) else: X.append(rec[0]) if (units == "J") or (not units) or (units == "T"): X.append(rec[0]) Y.append(old_div(rec[3], first_Z[0][3])) delta = .02 * Y[0] if recnum % 2 == 0: plt.text(X[-1] - delta, Y[-1] + delta, (' ' + str(recnum)), fontsize=9) recnum += 1 plt.plot(X, Y) plt.scatter(X, Y, marker='o', color='b') X, Y = [], [] for rec in first_I: if units == "K": if rec[0] != 0: X.append(rec[0] - 273) else: X.append(rec[0]) if (units == "J") or (not units) or (units == "T"): X.append(rec[0]) Y.append(old_div(rec[3], first_Z[0][3])) if globals != 0: globals.DIlist = X globals.DIlisty = Y plt.plot(X, Y) plt.scatter(X, Y, marker='s', color='r') plt.ylabel("Circles: NRM; Squares: pTRM") if units == "K": plt.xlabel("Temperature (C)") elif units == "J": plt.xlabel("Microwave Energy (J)") else: plt.xlabel("") title = s + ": NRM = " + '%9.2e' % (first_Z[0][3]) plt.title(title) plt.axhline(y=0, xmin=0, xmax=1, color='k') plt.axvline(x=0, ymin=0, ymax=1, color='k')
python
def plot_np(fignum, indata, s, units): """ makes plot of de(re)magnetization data for Thellier-Thellier type experiment Parameters __________ fignum : matplotlib figure number indata : araiblock from, e.g., pmag.sortarai() s : specimen name units : [K, J, ""] (kelvin, joules, unknown) Effect _______ Makes a plot """ global globals first_Z, first_I, ptrm_check, ptrm_tail = indata[0], indata[1], indata[2], indata[3] plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) X, Y, recnum = [], [], 0 # for rec in first_Z: if units == "K": if rec[0] != 0: X.append(rec[0] - 273.) else: X.append(rec[0]) if (units == "J") or (not units) or (units == "T"): X.append(rec[0]) Y.append(old_div(rec[3], first_Z[0][3])) delta = .02 * Y[0] if recnum % 2 == 0: plt.text(X[-1] - delta, Y[-1] + delta, (' ' + str(recnum)), fontsize=9) recnum += 1 plt.plot(X, Y) plt.scatter(X, Y, marker='o', color='b') X, Y = [], [] for rec in first_I: if units == "K": if rec[0] != 0: X.append(rec[0] - 273) else: X.append(rec[0]) if (units == "J") or (not units) or (units == "T"): X.append(rec[0]) Y.append(old_div(rec[3], first_Z[0][3])) if globals != 0: globals.DIlist = X globals.DIlisty = Y plt.plot(X, Y) plt.scatter(X, Y, marker='s', color='r') plt.ylabel("Circles: NRM; Squares: pTRM") if units == "K": plt.xlabel("Temperature (C)") elif units == "J": plt.xlabel("Microwave Energy (J)") else: plt.xlabel("") title = s + ": NRM = " + '%9.2e' % (first_Z[0][3]) plt.title(title) plt.axhline(y=0, xmin=0, xmax=1, color='k') plt.axvline(x=0, ymin=0, ymax=1, color='k')
makes plot of de(re)magnetization data for Thellier-Thellier type experiment Parameters __________ fignum : matplotlib figure number indata : araiblock from, e.g., pmag.sortarai() s : specimen name units : [K, J, ""] (kelvin, joules, unknown) Effect _______ Makes a plot
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1183-L1247
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): """ 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
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1250-L1286
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_b
def plot_b(Figs, araiblock, zijdblock, pars): """ deprecated (used in thellier_magic/microwave_magic) """ angle = zijdblock[0][1] plotblock = [] Dir, zx, zy, zz, ax, ay = [], [], [], [], [], [] zstart, zend = 0, len(zijdblock) first_Z, first_I = araiblock[0], araiblock[1] for rec in zijdblock: if rec[0] == pars["measurement_step_min"]: Dir.append((rec[1] - angle, rec[2], old_div(rec[3], zijdblock[0][3]))) if rec[0] == pars["measurement_step_max"]: Dir.append((rec[1] - angle, rec[2], old_div(rec[3], zijdblock[0][3]))) for drec in Dir: cart = pmag.dir2cart(drec) zx.append(cart[0]) # zy.append(-cart[1]) # zz.append(-cart[2]) zy.append(cart[1]) zz.append(cart[2]) if len(zx) > 0: plt.figure(num=Figs['zijd']) plt.scatter(zx, zy, marker='d', s=100, c='y') plt.scatter(zx, zz, marker='d', s=100, c='y') plt.axis("equal") ax.append(old_div(first_I[0][3], first_Z[0][3])) ax.append(old_div(first_I[-1][3], first_Z[0][3])) ay.append(old_div(first_Z[0][3], first_Z[0][3])) ay.append(old_div(first_Z[-1][3], first_Z[0][3])) for k in range(len(first_Z)): if first_Z[k][0] == pars["measurement_step_min"]: ay[0] = (old_div(first_Z[k][3], first_Z[0][3])) if first_Z[k][0] == pars["measurement_step_max"]: ay[1] = (old_div(first_Z[k][3], first_Z[0][3])) if first_I[k][0] == pars["measurement_step_min"]: ax[0] = (old_div(first_I[k][3], first_Z[0][3])) if first_I[k][0] == pars["measurement_step_max"]: ax[1] = (old_div(first_I[k][3], first_Z[0][3])) new_Z, new_I = [], [] for zrec in first_Z: if zrec[0] >= pars['measurement_step_min'] and zrec[0] <= pars['measurement_step_max']: new_Z.append(zrec) for irec in first_I: if irec[0] >= pars['measurement_step_min'] and irec[0] <= pars['measurement_step_max']: new_I.append(irec) newblock = [new_Z, new_I] plot_teq(Figs['eqarea'], newblock, "", pars) plt.figure(num=Figs['arai']) plt.scatter(ax, ay, marker='d', s=100, c='y') # # find midpoint between two endpoints # sy = [] sy.append((pars["specimen_b"] * ax[0] + old_div(pars["specimen_ytot"], first_Z[0][3]))) sy.append((pars["specimen_b"] * ax[1] + old_div(pars["specimen_ytot"], first_Z[0][3]))) plt.plot(ax, sy, 'g', linewidth=2) bounds = plt.axis() if pars['specimen_grade'] != '': notestr = 'Grade: ' + pars["specimen_grade"] plt.text(.7 * bounds[1], .9 * bounds[3], notestr) notestr = 'B: ' + '%6.2f' % (pars["specimen_int"] * 1e6) + ' uT' plt.text(.7 * bounds[1], .8 * bounds[3], notestr)
python
def plot_b(Figs, araiblock, zijdblock, pars): """ deprecated (used in thellier_magic/microwave_magic) """ angle = zijdblock[0][1] plotblock = [] Dir, zx, zy, zz, ax, ay = [], [], [], [], [], [] zstart, zend = 0, len(zijdblock) first_Z, first_I = araiblock[0], araiblock[1] for rec in zijdblock: if rec[0] == pars["measurement_step_min"]: Dir.append((rec[1] - angle, rec[2], old_div(rec[3], zijdblock[0][3]))) if rec[0] == pars["measurement_step_max"]: Dir.append((rec[1] - angle, rec[2], old_div(rec[3], zijdblock[0][3]))) for drec in Dir: cart = pmag.dir2cart(drec) zx.append(cart[0]) # zy.append(-cart[1]) # zz.append(-cart[2]) zy.append(cart[1]) zz.append(cart[2]) if len(zx) > 0: plt.figure(num=Figs['zijd']) plt.scatter(zx, zy, marker='d', s=100, c='y') plt.scatter(zx, zz, marker='d', s=100, c='y') plt.axis("equal") ax.append(old_div(first_I[0][3], first_Z[0][3])) ax.append(old_div(first_I[-1][3], first_Z[0][3])) ay.append(old_div(first_Z[0][3], first_Z[0][3])) ay.append(old_div(first_Z[-1][3], first_Z[0][3])) for k in range(len(first_Z)): if first_Z[k][0] == pars["measurement_step_min"]: ay[0] = (old_div(first_Z[k][3], first_Z[0][3])) if first_Z[k][0] == pars["measurement_step_max"]: ay[1] = (old_div(first_Z[k][3], first_Z[0][3])) if first_I[k][0] == pars["measurement_step_min"]: ax[0] = (old_div(first_I[k][3], first_Z[0][3])) if first_I[k][0] == pars["measurement_step_max"]: ax[1] = (old_div(first_I[k][3], first_Z[0][3])) new_Z, new_I = [], [] for zrec in first_Z: if zrec[0] >= pars['measurement_step_min'] and zrec[0] <= pars['measurement_step_max']: new_Z.append(zrec) for irec in first_I: if irec[0] >= pars['measurement_step_min'] and irec[0] <= pars['measurement_step_max']: new_I.append(irec) newblock = [new_Z, new_I] plot_teq(Figs['eqarea'], newblock, "", pars) plt.figure(num=Figs['arai']) plt.scatter(ax, ay, marker='d', s=100, c='y') # # find midpoint between two endpoints # sy = [] sy.append((pars["specimen_b"] * ax[0] + old_div(pars["specimen_ytot"], first_Z[0][3]))) sy.append((pars["specimen_b"] * ax[1] + old_div(pars["specimen_ytot"], first_Z[0][3]))) plt.plot(ax, sy, 'g', linewidth=2) bounds = plt.axis() if pars['specimen_grade'] != '': notestr = 'Grade: ' + pars["specimen_grade"] plt.text(.7 * bounds[1], .9 * bounds[3], notestr) notestr = 'B: ' + '%6.2f' % (pars["specimen_int"] * 1e6) + ' uT' plt.text(.7 * bounds[1], .8 * bounds[3], notestr)
deprecated (used in thellier_magic/microwave_magic)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1289-L1355
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_slnp
def plot_slnp(fignum, SiteRec, datablock, key): """ plots lines and planes on a great circle with alpha 95 and mean deprecated (used in pmagplotlib) """ # make the stereonet plt.figure(num=fignum) plot_net(fignum) s = SiteRec['er_site_name'] # # plot on the data # coord = SiteRec['site_tilt_correction'] title = '' if coord == '-1': title = s + ": specimen coordinates" if coord == '0': title = s + ": geographic coordinates" if coord == '100': title = s + ": tilt corrected coordinates" DIblock, GCblock = [], [] for plotrec in datablock: if plotrec[key + '_direction_type'] == 'p': # direction is pole to plane GCblock.append( (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"]))) else: # assume direction is a directed line DIblock.append( (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"]))) if len(DIblock) > 0: plot_di(fignum, DIblock) # plot directed lines if len(GCblock) > 0: for pole in GCblock: plot_circ(fignum, pole, 90., 'g') # plot directed lines # # put on the mean direction # x, y = [], [] XY = pmag.dimap(float(SiteRec["site_dec"]), float(SiteRec["site_inc"])) x.append(XY[0]) y.append(XY[1]) plt.scatter(x, y, marker='d', s=80, c='g') plt.title(title) # # get the alpha95 # Xcirc, Ycirc = [], [] Da95, Ia95 = pmag.circ(float(SiteRec["site_dec"]), float( SiteRec["site_inc"]), float(SiteRec["site_alpha95"])) for k in range(len(Da95)): XY = pmag.dimap(Da95[k], Ia95[k]) Xcirc.append(XY[0]) Ycirc.append(XY[1]) plt.plot(Xcirc, Ycirc, 'g')
python
def plot_slnp(fignum, SiteRec, datablock, key): """ plots lines and planes on a great circle with alpha 95 and mean deprecated (used in pmagplotlib) """ # make the stereonet plt.figure(num=fignum) plot_net(fignum) s = SiteRec['er_site_name'] # # plot on the data # coord = SiteRec['site_tilt_correction'] title = '' if coord == '-1': title = s + ": specimen coordinates" if coord == '0': title = s + ": geographic coordinates" if coord == '100': title = s + ": tilt corrected coordinates" DIblock, GCblock = [], [] for plotrec in datablock: if plotrec[key + '_direction_type'] == 'p': # direction is pole to plane GCblock.append( (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"]))) else: # assume direction is a directed line DIblock.append( (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"]))) if len(DIblock) > 0: plot_di(fignum, DIblock) # plot directed lines if len(GCblock) > 0: for pole in GCblock: plot_circ(fignum, pole, 90., 'g') # plot directed lines # # put on the mean direction # x, y = [], [] XY = pmag.dimap(float(SiteRec["site_dec"]), float(SiteRec["site_inc"])) x.append(XY[0]) y.append(XY[1]) plt.scatter(x, y, marker='d', s=80, c='g') plt.title(title) # # get the alpha95 # Xcirc, Ycirc = [], [] Da95, Ia95 = pmag.circ(float(SiteRec["site_dec"]), float( SiteRec["site_inc"]), float(SiteRec["site_alpha95"])) for k in range(len(Da95)): XY = pmag.dimap(Da95[k], Ia95[k]) Xcirc.append(XY[0]) Ycirc.append(XY[1]) plt.plot(Xcirc, Ycirc, 'g')
plots lines and planes on a great circle with alpha 95 and mean deprecated (used in pmagplotlib)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1358-L1410
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): """ 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')
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1413-L1476
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_eq
def plot_eq(fignum, DIblock, s): """ plots directions on eqarea projection Parameters __________ fignum : matplotlib figure number DIblock : nested list of dec/inc pairs s : specimen name """ # make the stereonet plt.figure(num=fignum) if len(DIblock) < 1: return # plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plot_net(fignum) # # put on the directions # plot_di(fignum, DIblock) # plot directions plt.axis("equal") plt.text(-1.1, 1.15, s) plt.draw()
python
def plot_eq(fignum, DIblock, s): """ plots directions on eqarea projection Parameters __________ fignum : matplotlib figure number DIblock : nested list of dec/inc pairs s : specimen name """ # make the stereonet plt.figure(num=fignum) if len(DIblock) < 1: return # plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plot_net(fignum) # # put on the directions # plot_di(fignum, DIblock) # plot directions plt.axis("equal") plt.text(-1.1, 1.15, s) plt.draw()
plots directions on eqarea projection Parameters __________ fignum : matplotlib figure number DIblock : nested list of dec/inc pairs s : specimen name
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1479-L1502
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_eq_sym
def plot_eq_sym(fignum, DIblock, s, sym): """ plots directions with specified symbol Parameters __________ fignum : matplotlib figure number DIblock : nested list of dec/inc pairs s : specimen name sym : matplotlib symbol (e.g., 'bo' for blue circle) """ # make the stereonet plt.figure(num=fignum) if len(DIblock) < 1: return # plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plot_net(fignum) # # put on the directions # plot_di_sym(fignum, DIblock, sym) # plot directions with symbols in sym plt.axis("equal") plt.text(-1.1, 1.15, s)
python
def plot_eq_sym(fignum, DIblock, s, sym): """ plots directions with specified symbol Parameters __________ fignum : matplotlib figure number DIblock : nested list of dec/inc pairs s : specimen name sym : matplotlib symbol (e.g., 'bo' for blue circle) """ # make the stereonet plt.figure(num=fignum) if len(DIblock) < 1: return # plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plot_net(fignum) # # put on the directions # plot_di_sym(fignum, DIblock, sym) # plot directions with symbols in sym plt.axis("equal") plt.text(-1.1, 1.15, s)
plots directions with specified symbol Parameters __________ fignum : matplotlib figure number DIblock : nested list of dec/inc pairs s : specimen name sym : matplotlib symbol (e.g., 'bo' for blue circle)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1505-L1528
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): """ 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)
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1532-L1590
PmagPy/PmagPy
pmagpy/pmagplotlib.py
save_plots
def save_plots(Figs, filenames, **kwargs): """ Parameters ---------- Figs : dict dictionary of plots, e.g. {'eqarea': 1, ...} filenames : dict dictionary of filenames, e.g. {'eqarea': 'mc01a_eqarea.svg', ...} dict keys should correspond with Figs """ saved = [] for key in list(Figs.keys()): try: plt.figure(num=Figs[key]) fname = filenames[key] if set_env.IS_WIN: # always truncate filenames if on Windows fname = os.path.split(fname)[1] if not isServer: # remove illegal ':' character for windows fname = fname.replace(':', '_') if 'incl_directory' in kwargs.keys() and not set_env.IS_WIN: if kwargs['incl_directory']: pass # do not flatten file name else: fname = fname.replace('/', '-') # flatten file name else: fname = fname.replace('/', '-') # flatten file name if 'dpi' in list(kwargs.keys()): plt.savefig(fname, dpi=kwargs['dpi']) elif isServer: plt.savefig(fname, dpi=240) else: plt.savefig(fname) if verbose: print(Figs[key], " saved in ", fname) saved.append(fname) plt.close(Figs[key]) except Exception as ex: print(type(ex), ex) print('could not save: ', Figs[key], filenames[key]) print("output file format not supported ") return saved
python
def save_plots(Figs, filenames, **kwargs): """ Parameters ---------- Figs : dict dictionary of plots, e.g. {'eqarea': 1, ...} filenames : dict dictionary of filenames, e.g. {'eqarea': 'mc01a_eqarea.svg', ...} dict keys should correspond with Figs """ saved = [] for key in list(Figs.keys()): try: plt.figure(num=Figs[key]) fname = filenames[key] if set_env.IS_WIN: # always truncate filenames if on Windows fname = os.path.split(fname)[1] if not isServer: # remove illegal ':' character for windows fname = fname.replace(':', '_') if 'incl_directory' in kwargs.keys() and not set_env.IS_WIN: if kwargs['incl_directory']: pass # do not flatten file name else: fname = fname.replace('/', '-') # flatten file name else: fname = fname.replace('/', '-') # flatten file name if 'dpi' in list(kwargs.keys()): plt.savefig(fname, dpi=kwargs['dpi']) elif isServer: plt.savefig(fname, dpi=240) else: plt.savefig(fname) if verbose: print(Figs[key], " saved in ", fname) saved.append(fname) plt.close(Figs[key]) except Exception as ex: print(type(ex), ex) print('could not save: ', Figs[key], filenames[key]) print("output file format not supported ") return saved
Parameters ---------- Figs : dict dictionary of plots, e.g. {'eqarea': 1, ...} filenames : dict dictionary of filenames, e.g. {'eqarea': 'mc01a_eqarea.svg', ...} dict keys should correspond with Figs
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1593-L1633
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): """ 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")
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1637-L1666
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_ell
def plot_ell(fignum, pars, col, lower, plot): """ function to calcualte/plot points on an ellipse about Pdec,Pdip with angle beta,gamma Parameters _________ fignum : matplotlib figure number pars : list of [Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc ] where P is direction, Bdec,Binc are beta direction, and Gdec,Ginc are gamma direction col : color for ellipse lower : boolean, if True, lower hemisphere projection plot : boolean, if False, return the points, if False, make the plot """ plt.figure(num=fignum) rad = old_div(np.pi, 180.) Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc = pars[0], pars[ 1], pars[2], pars[3], pars[4], pars[5], pars[6], pars[7] if beta > 90. or gamma > 90: beta = 180. - beta gamma = 180. - gamma Pdec = Pdec - 180. Pinc = -Pinc beta, gamma = beta * rad, gamma * rad # convert to radians X_ell, Y_ell, X_up, Y_up, PTS = [], [], [], [], [] nums = 201 xnum = old_div(float(nums - 1.), 2.) # set up t matrix t = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] X = pmag.dir2cart((Pdec, Pinc, 1.0)) # convert to cartesian coordintes if lower == 1 and X[2] < 0: for i in range(3): X[i] = -X[i] # set up rotation matrix t t[0][2] = X[0] t[1][2] = X[1] t[2][2] = X[2] X = pmag.dir2cart((Bdec, Binc, 1.0)) if lower == 1 and X[2] < 0: for i in range(3): X[i] = -X[i] t[0][0] = X[0] t[1][0] = X[1] t[2][0] = X[2] X = pmag.dir2cart((Gdec, Ginc, 1.0)) if lower == 1 and X[2] < 0: for i in range(3): X[i] = -X[i] t[0][1] = X[0] t[1][1] = X[1] t[2][1] = X[2] # set up v matrix v = [0, 0, 0] for i in range(nums): # incremental point along ellipse psi = float(i) * np.pi / xnum v[0] = np.sin(beta) * np.cos(psi) v[1] = np.sin(gamma) * np.sin(psi) v[2] = np.sqrt(1. - v[0]**2 - v[1]**2) elli = [0, 0, 0] # calculate points on the ellipse for j in range(3): for k in range(3): # cartesian coordinate j of ellipse elli[j] = elli[j] + t[j][k] * v[k] pts = pmag.cart2dir(elli) PTS.append([pts[0], pts[1]]) # put on an equal area projection R = old_div(np.sqrt( 1. - abs(elli[2])), (np.sqrt(elli[0]**2 + elli[1]**2))) if elli[2] <= 0: # for i in range(3): elli[i]=-elli[i] X_up.append(elli[1] * R) Y_up.append(elli[0] * R) else: X_ell.append(elli[1] * R) Y_ell.append(elli[0] * R) if plot == 1: col = col[0]+'.' if X_ell != []: plt.plot(X_ell, Y_ell, col, markersize=3) if X_up != []: plt.plot(X_up, Y_up, col, markersize=3) else: return PTS
python
def plot_ell(fignum, pars, col, lower, plot): """ function to calcualte/plot points on an ellipse about Pdec,Pdip with angle beta,gamma Parameters _________ fignum : matplotlib figure number pars : list of [Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc ] where P is direction, Bdec,Binc are beta direction, and Gdec,Ginc are gamma direction col : color for ellipse lower : boolean, if True, lower hemisphere projection plot : boolean, if False, return the points, if False, make the plot """ plt.figure(num=fignum) rad = old_div(np.pi, 180.) Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc = pars[0], pars[ 1], pars[2], pars[3], pars[4], pars[5], pars[6], pars[7] if beta > 90. or gamma > 90: beta = 180. - beta gamma = 180. - gamma Pdec = Pdec - 180. Pinc = -Pinc beta, gamma = beta * rad, gamma * rad # convert to radians X_ell, Y_ell, X_up, Y_up, PTS = [], [], [], [], [] nums = 201 xnum = old_div(float(nums - 1.), 2.) # set up t matrix t = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] X = pmag.dir2cart((Pdec, Pinc, 1.0)) # convert to cartesian coordintes if lower == 1 and X[2] < 0: for i in range(3): X[i] = -X[i] # set up rotation matrix t t[0][2] = X[0] t[1][2] = X[1] t[2][2] = X[2] X = pmag.dir2cart((Bdec, Binc, 1.0)) if lower == 1 and X[2] < 0: for i in range(3): X[i] = -X[i] t[0][0] = X[0] t[1][0] = X[1] t[2][0] = X[2] X = pmag.dir2cart((Gdec, Ginc, 1.0)) if lower == 1 and X[2] < 0: for i in range(3): X[i] = -X[i] t[0][1] = X[0] t[1][1] = X[1] t[2][1] = X[2] # set up v matrix v = [0, 0, 0] for i in range(nums): # incremental point along ellipse psi = float(i) * np.pi / xnum v[0] = np.sin(beta) * np.cos(psi) v[1] = np.sin(gamma) * np.sin(psi) v[2] = np.sqrt(1. - v[0]**2 - v[1]**2) elli = [0, 0, 0] # calculate points on the ellipse for j in range(3): for k in range(3): # cartesian coordinate j of ellipse elli[j] = elli[j] + t[j][k] * v[k] pts = pmag.cart2dir(elli) PTS.append([pts[0], pts[1]]) # put on an equal area projection R = old_div(np.sqrt( 1. - abs(elli[2])), (np.sqrt(elli[0]**2 + elli[1]**2))) if elli[2] <= 0: # for i in range(3): elli[i]=-elli[i] X_up.append(elli[1] * R) Y_up.append(elli[0] * R) else: X_ell.append(elli[1] * R) Y_ell.append(elli[0] * R) if plot == 1: col = col[0]+'.' if X_ell != []: plt.plot(X_ell, Y_ell, col, markersize=3) if X_up != []: plt.plot(X_up, Y_up, col, markersize=3) else: return PTS
function to calcualte/plot points on an ellipse about Pdec,Pdip with angle beta,gamma Parameters _________ fignum : matplotlib figure number pars : list of [Pdec, Pinc, beta, Bdec, Binc, gamma, Gdec, Ginc ] where P is direction, Bdec,Binc are beta direction, and Gdec,Ginc are gamma direction col : color for ellipse lower : boolean, if True, lower hemisphere projection plot : boolean, if False, return the points, if False, make the plot
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1670-L1751
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_strat
def plot_strat(fignum, data, labels): """ plots a time/depth series Parameters _________ fignum : matplotlib figure number data : nested list of [X,Y] pairs labels : [xlabel, ylabel, title] """ vertical_plot_init(fignum, 10, 3) xlab, ylab, title = labels[0], labels[1], labels[2] X, Y = [], [] for rec in data: X.append(rec[0]) Y.append(rec[1]) plt.plot(X, Y) plt.plot(X, Y, 'ro') plt.xlabel(xlab) plt.ylabel(ylab) plt.title(title)
python
def plot_strat(fignum, data, labels): """ plots a time/depth series Parameters _________ fignum : matplotlib figure number data : nested list of [X,Y] pairs labels : [xlabel, ylabel, title] """ vertical_plot_init(fignum, 10, 3) xlab, ylab, title = labels[0], labels[1], labels[2] X, Y = [], [] for rec in data: X.append(rec[0]) Y.append(rec[1]) plt.plot(X, Y) plt.plot(X, Y, 'ro') plt.xlabel(xlab) plt.ylabel(ylab) plt.title(title)
plots a time/depth series Parameters _________ fignum : matplotlib figure number data : nested list of [X,Y] pairs labels : [xlabel, ylabel, title]
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1771-L1790
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_cdf
def plot_cdf(fignum, data, xlab, sym, title, **kwargs): """ Makes a plot of the cumulative distribution function. Parameters __________ fignum : matplotlib figure number data : list of data to be plotted - doesn't need to be sorted sym : matplotlib symbol for plotting, e.g., 'r--' for a red dashed line **kwargs : optional dictionary with {'color': color, 'linewidth':linewidth} Returns __________ x : sorted list of data y : fraction of cdf """ # #if len(sym)==1:sym=sym+'-' fig = plt.figure(num=fignum) # sdata=np.array(data).sort() sdata = [] for d in data: sdata.append(d) # have to copy the data to avoid overwriting it! sdata.sort() X, Y = [], [] color = "" for j in range(len(sdata)): Y.append(old_div(float(j), float(len(sdata)))) X.append(sdata[j]) if 'color' in list(kwargs.keys()): color = kwargs['color'] if 'linewidth' in list(kwargs.keys()): lw = kwargs['linewidth'] else: lw = 1 if color != "": plt.plot(X, Y, color=sym, linewidth=lw) else: plt.plot(X, Y, sym, linewidth=lw) plt.xlabel(xlab) plt.ylabel('Cumulative Distribution') plt.title(title) return X, Y
python
def plot_cdf(fignum, data, xlab, sym, title, **kwargs): """ Makes a plot of the cumulative distribution function. Parameters __________ fignum : matplotlib figure number data : list of data to be plotted - doesn't need to be sorted sym : matplotlib symbol for plotting, e.g., 'r--' for a red dashed line **kwargs : optional dictionary with {'color': color, 'linewidth':linewidth} Returns __________ x : sorted list of data y : fraction of cdf """ # #if len(sym)==1:sym=sym+'-' fig = plt.figure(num=fignum) # sdata=np.array(data).sort() sdata = [] for d in data: sdata.append(d) # have to copy the data to avoid overwriting it! sdata.sort() X, Y = [], [] color = "" for j in range(len(sdata)): Y.append(old_div(float(j), float(len(sdata)))) X.append(sdata[j]) if 'color' in list(kwargs.keys()): color = kwargs['color'] if 'linewidth' in list(kwargs.keys()): lw = kwargs['linewidth'] else: lw = 1 if color != "": plt.plot(X, Y, color=sym, linewidth=lw) else: plt.plot(X, Y, sym, linewidth=lw) plt.xlabel(xlab) plt.ylabel('Cumulative Distribution') plt.title(title) return X, Y
Makes a plot of the cumulative distribution function. Parameters __________ fignum : matplotlib figure number data : list of data to be plotted - doesn't need to be sorted sym : matplotlib symbol for plotting, e.g., 'r--' for a red dashed line **kwargs : optional dictionary with {'color': color, 'linewidth':linewidth} Returns __________ x : sorted list of data y : fraction of cdf
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1796-L1837
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): """ 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)
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1841-L1855
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): """ 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)
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1859-L1874
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): """ 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
plot the geomagnetic polarity time scale Parameters __________ fignum : matplotlib figure number dates : bounding dates for plot ts : time scale ck95, gts04, or gts12
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L1877-L1918
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): """ 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)
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2045-L2067
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_d_delta_m
def plot_d_delta_m(fignum, Bdm, DdeltaM, s): """ function to plot d (Delta M)/dB curves Parameters __________ fignum : matplotlib figure number Bdm : change in field Ddelta M : change in delta M s : specimen name """ plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) start = len(Bdm) - len(DdeltaM) plt.plot(Bdm[start:], DdeltaM, 'b') plt.xlabel('B (T)') plt.ylabel('d (Delta M)/dB') plt.title(s)
python
def plot_d_delta_m(fignum, Bdm, DdeltaM, s): """ function to plot d (Delta M)/dB curves Parameters __________ fignum : matplotlib figure number Bdm : change in field Ddelta M : change in delta M s : specimen name """ plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) start = len(Bdm) - len(DdeltaM) plt.plot(Bdm[start:], DdeltaM, 'b') plt.xlabel('B (T)') plt.ylabel('d (Delta M)/dB') plt.title(s)
function to plot d (Delta M)/dB curves Parameters __________ fignum : matplotlib figure number Bdm : change in field Ddelta M : change in delta M s : specimen name
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2071-L2090
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_imag
def plot_imag(fignum, Bimag, Mimag, s): """ function to plot d (Delta M)/dB curves """ plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plt.plot(Bimag, Mimag, 'r') plt.xlabel('B (T)') plt.ylabel('M/Ms') plt.axvline(0, color='k') plt.title(s)
python
def plot_imag(fignum, Bimag, Mimag, s): """ function to plot d (Delta M)/dB curves """ plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plt.plot(Bimag, Mimag, 'r') plt.xlabel('B (T)') plt.ylabel('M/Ms') plt.axvline(0, color='k') plt.title(s)
function to plot d (Delta M)/dB curves
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2094-L2106
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_hdd
def plot_hdd(HDD, B, M, s): """ Function to make hysteresis, deltaM and DdeltaM plots Parameters: _______________ Input HDD : dictionary with figure numbers for the keys: 'hyst' : hysteresis plot normalized to maximum value 'deltaM' : Delta M plot 'DdeltaM' : differential of Delta M plot B : list of field values in tesla M : list of magnetizations in arbitrary units s : specimen name string Ouput hpars : dictionary of hysteresis parameters with keys: 'hysteresis_xhf', 'hysteresis_ms_moment', 'hysteresis_mr_moment', 'hysteresis_bc' """ hpars, deltaM, Bdm = plot_hys( HDD['hyst'], B, M, s) # Moff is the "fixed" loop data DdeltaM = [] Mhalf = "" for k in range(2, len(Bdm)): # differnential DdeltaM.append( old_div(abs(deltaM[k] - deltaM[k - 2]), (Bdm[k] - Bdm[k - 2]))) for k in range(len(deltaM)): if old_div(deltaM[k], deltaM[0]) < 0.5: Mhalf = k break try: Bhf = Bdm[Mhalf - 1:Mhalf + 1] Mhf = deltaM[Mhalf - 1:Mhalf + 1] # best fit line through two bounding points poly = np.polyfit(Bhf, Mhf, 1) Bcr = old_div((.5 * deltaM[0] - poly[1]), poly[0]) hpars['hysteresis_bcr'] = '%8.3e' % (Bcr) hpars['magic_method_codes'] = "LP-BCR-HDM" if HDD['deltaM'] != 0: plot_delta_m(HDD['deltaM'], Bdm, deltaM, Bcr, s) plt.axhline(0, color='k') plt.axvline(0, color='k') plot_d_delta_m(HDD['DdeltaM'], Bdm, DdeltaM, s) except: hpars['hysteresis_bcr'] = '0' hpars['magic_method_codes'] = "" return hpars
python
def plot_hdd(HDD, B, M, s): """ Function to make hysteresis, deltaM and DdeltaM plots Parameters: _______________ Input HDD : dictionary with figure numbers for the keys: 'hyst' : hysteresis plot normalized to maximum value 'deltaM' : Delta M plot 'DdeltaM' : differential of Delta M plot B : list of field values in tesla M : list of magnetizations in arbitrary units s : specimen name string Ouput hpars : dictionary of hysteresis parameters with keys: 'hysteresis_xhf', 'hysteresis_ms_moment', 'hysteresis_mr_moment', 'hysteresis_bc' """ hpars, deltaM, Bdm = plot_hys( HDD['hyst'], B, M, s) # Moff is the "fixed" loop data DdeltaM = [] Mhalf = "" for k in range(2, len(Bdm)): # differnential DdeltaM.append( old_div(abs(deltaM[k] - deltaM[k - 2]), (Bdm[k] - Bdm[k - 2]))) for k in range(len(deltaM)): if old_div(deltaM[k], deltaM[0]) < 0.5: Mhalf = k break try: Bhf = Bdm[Mhalf - 1:Mhalf + 1] Mhf = deltaM[Mhalf - 1:Mhalf + 1] # best fit line through two bounding points poly = np.polyfit(Bhf, Mhf, 1) Bcr = old_div((.5 * deltaM[0] - poly[1]), poly[0]) hpars['hysteresis_bcr'] = '%8.3e' % (Bcr) hpars['magic_method_codes'] = "LP-BCR-HDM" if HDD['deltaM'] != 0: plot_delta_m(HDD['deltaM'], Bdm, deltaM, Bcr, s) plt.axhline(0, color='k') plt.axvline(0, color='k') plot_d_delta_m(HDD['DdeltaM'], Bdm, DdeltaM, s) except: hpars['hysteresis_bcr'] = '0' hpars['magic_method_codes'] = "" return hpars
Function to make hysteresis, deltaM and DdeltaM plots Parameters: _______________ Input HDD : dictionary with figure numbers for the keys: 'hyst' : hysteresis plot normalized to maximum value 'deltaM' : Delta M plot 'DdeltaM' : differential of Delta M plot B : list of field values in tesla M : list of magnetizations in arbitrary units s : specimen name string Ouput hpars : dictionary of hysteresis parameters with keys: 'hysteresis_xhf', 'hysteresis_ms_moment', 'hysteresis_mr_moment', 'hysteresis_bc'
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2110-L2156
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): """ 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])
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]}
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2160-L2211
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): """ 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])
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)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2215-L2232
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): """ 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])
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)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2236-L2253
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): """ 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')
function to plot two estimates of Bcr against each other
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2257-L2265
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_hpars
def plot_hpars(HDD, hpars, sym): """ function to plot hysteresis parameters deprecated (used in hysteresis_magic) """ plt.figure(num=HDD['hyst']) X, Y = [], [] X.append(0) Y.append(old_div(float(hpars['hysteresis_mr_moment']), float( hpars['hysteresis_ms_moment']))) X.append(float(hpars['hysteresis_bc'])) Y.append(0) plt.plot(X, Y, sym) bounds = plt.axis() n4 = 'Ms: ' + '%8.2e' % (float(hpars['hysteresis_ms_moment'])) + ' Am^2' plt.text(bounds[1] - .9 * bounds[1], -.9, n4) n1 = 'Mr: ' + '%8.2e' % (float(hpars['hysteresis_mr_moment'])) + ' Am^2' plt.text(bounds[1] - .9 * bounds[1], -.7, n1) n2 = 'Bc: ' + '%8.2e' % (float(hpars['hysteresis_bc'])) + ' T' plt.text(bounds[1] - .9 * bounds[1], -.5, n2) if 'hysteresis_xhf' in list(hpars.keys()): n3 = r'Xhf: ' + '%8.2e' % (float(hpars['hysteresis_xhf'])) + ' m^3' plt.text(bounds[1] - .9 * bounds[1], -.3, n3) plt.figure(num=HDD['deltaM']) X, Y, Bcr = [], [], "" if 'hysteresis_bcr' in list(hpars.keys()): X.append(float(hpars['hysteresis_bcr'])) Y.append(0) Bcr = float(hpars['hysteresis_bcr']) plt.plot(X, Y, sym) bounds = plt.axis() if Bcr != "": n1 = 'Bcr: ' + '%8.2e' % (Bcr) + ' T' plt.text(bounds[1] - .5 * bounds[1], .9 * bounds[3], n1)
python
def plot_hpars(HDD, hpars, sym): """ function to plot hysteresis parameters deprecated (used in hysteresis_magic) """ plt.figure(num=HDD['hyst']) X, Y = [], [] X.append(0) Y.append(old_div(float(hpars['hysteresis_mr_moment']), float( hpars['hysteresis_ms_moment']))) X.append(float(hpars['hysteresis_bc'])) Y.append(0) plt.plot(X, Y, sym) bounds = plt.axis() n4 = 'Ms: ' + '%8.2e' % (float(hpars['hysteresis_ms_moment'])) + ' Am^2' plt.text(bounds[1] - .9 * bounds[1], -.9, n4) n1 = 'Mr: ' + '%8.2e' % (float(hpars['hysteresis_mr_moment'])) + ' Am^2' plt.text(bounds[1] - .9 * bounds[1], -.7, n1) n2 = 'Bc: ' + '%8.2e' % (float(hpars['hysteresis_bc'])) + ' T' plt.text(bounds[1] - .9 * bounds[1], -.5, n2) if 'hysteresis_xhf' in list(hpars.keys()): n3 = r'Xhf: ' + '%8.2e' % (float(hpars['hysteresis_xhf'])) + ' m^3' plt.text(bounds[1] - .9 * bounds[1], -.3, n3) plt.figure(num=HDD['deltaM']) X, Y, Bcr = [], [], "" if 'hysteresis_bcr' in list(hpars.keys()): X.append(float(hpars['hysteresis_bcr'])) Y.append(0) Bcr = float(hpars['hysteresis_bcr']) plt.plot(X, Y, sym) bounds = plt.axis() if Bcr != "": n1 = 'Bcr: ' + '%8.2e' % (Bcr) + ' T' plt.text(bounds[1] - .5 * bounds[1], .9 * bounds[3], n1)
function to plot hysteresis parameters deprecated (used in hysteresis_magic)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2268-L2301
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): """ 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
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2305-L2375
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_xtf
def plot_xtf(fignum, XTF, Fs, e, b): """ function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency """ plt.figure(num=fignum) plt.xlabel('Temperature (K)') plt.ylabel('Susceptibility (m^3/kg)') k = 0 Flab = [] for freq in XTF: T, X = [], [] for xt in freq: X.append(xt[0]) T.append(xt[1]) plt.plot(T, X) plt.text(T[-1], X[-1], str(int(Fs[k])) + ' Hz') # Flab.append(str(int(Fs[k]))+' Hz') k += 1 plt.title(e + ': B = ' + '%8.1e' % (b) + ' T')
python
def plot_xtf(fignum, XTF, Fs, e, b): """ function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency """ plt.figure(num=fignum) plt.xlabel('Temperature (K)') plt.ylabel('Susceptibility (m^3/kg)') k = 0 Flab = [] for freq in XTF: T, X = [], [] for xt in freq: X.append(xt[0]) T.append(xt[1]) plt.plot(T, X) plt.text(T[-1], X[-1], str(int(Fs[k])) + ' Hz') # Flab.append(str(int(Fs[k]))+' Hz') k += 1 plt.title(e + ': B = ' + '%8.1e' % (b) + ' T')
function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2378-L2396
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): """ 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')
function to plot series of chi measurements as a function of temperature, holding frequency constant and varying B
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2401-L2418
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_xft
def plot_xft(fignum, XF, T, e, b): """ function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency """ plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plt.xlabel('Frequency (Hz)') plt.ylabel('Susceptibility (m^3/kg)') k = 0 F, X = [], [] for xf in XF: X.append(xf[0]) F.append(xf[1]) plt.plot(F, X) plt.semilogx() plt.title(e + ': B = ' + '%8.1e' % (b) + ' T') plt.legend(['%i' % (int(T)) + ' K'])
python
def plot_xft(fignum, XF, T, e, b): """ function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency """ plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plt.xlabel('Frequency (Hz)') plt.ylabel('Susceptibility (m^3/kg)') k = 0 F, X = [], [] for xf in XF: X.append(xf[0]) F.append(xf[1]) plt.plot(F, X) plt.semilogx() plt.title(e + ': B = ' + '%8.1e' % (b) + ' T') plt.legend(['%i' % (int(T)) + ' K'])
function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2423-L2441
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_xbt
def plot_xbt(fignum, XB, T, e, b): """ function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency """ plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plt.xlabel('Field (T)') plt.ylabel('Susceptibility (m^3/kg)') k = 0 B, X = [], [] for xb in XB: X.append(xb[0]) B.append(xb[1]) plt.plot(B, X) plt.legend(['%i' % (int(T)) + ' K']) plt.title(e + ': f = ' + '%i' % (int(f)) + ' Hz')
python
def plot_xbt(fignum, XB, T, e, b): """ function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency """ plt.figure(num=fignum) plt.clf() if not isServer: plt.figtext(.02, .01, version_num) plt.xlabel('Field (T)') plt.ylabel('Susceptibility (m^3/kg)') k = 0 B, X = [], [] for xb in XB: X.append(xb[0]) B.append(xb[1]) plt.plot(B, X) plt.legend(['%i' % (int(T)) + ' K']) plt.title(e + ': f = ' + '%i' % (int(f)) + ' Hz')
function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2445-L2461
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): """ 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)
function to plot low temperature cycling experiments
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2465-L2489
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): """ 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)
plots directions and confidence ellipses
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2742-L2776
PmagPy/PmagPy
pmagpy/pmagplotlib.py
add_borders
def add_borders(Figs, titles, border_color='#000000', text_color='#800080', con_id=""): """ Formatting for generating plots on the server Default border color: black Default text color: purple """ def split_title(s): """ Add '\n's to split of overly long titles """ s_list = s.split(",") lines = [] tot = 0 line = [] for i in s_list: tot += len(i) if tot < 30: line.append(i + ",") else: lines.append(" ".join(line)) line = [i] tot = 0 lines.append(" ".join(line)) return "\n".join(lines).strip(',') # format contribution id if available if con_id: if not str(con_id).startswith("/"): con_id = "/" + str(con_id) import datetime now = datetime.datetime.utcnow() for key in list(Figs.keys()): fig = plt.figure(Figs[key]) plot_title = split_title(titles[key]).strip().strip('\n') fig.set_figheight(5.5) #get returns Bbox with x0, y0, x1, y1 pos = fig.gca().get_position() # tweak some of the default values w = pos.x1 - pos.x0 h = (pos.y1 - pos.y0) / 1.1 x = pos.x0 y = pos.y0 * 1.3 # set takes: left, bottom, width, height fig.gca().set_position([x, y, w, h]) # add an axis covering the entire figure border_ax = fig.add_axes([0, 0, 1, 1]) border_ax.set_frame_on(False) border_ax.set_xticks([]) border_ax.set_yticks([]) # add a border if "\n" in plot_title: y_val = 1.0 # lower border #fig.set_figheight(6.25) else: y_val = 1.04 # higher border #border_ax.text(-0.02, y_val, " # |", # horizontalalignment='left', # verticalalignment='top', # color=text_color, # bbox=dict(edgecolor=border_color, # facecolor='#FFFFFF', linewidth=0.25), # size=50) #border_ax.text(-0.02, 0, "| # |", # horizontalalignment='left', # verticalalignment='bottom', # color=text_color, # bbox=dict(edgecolor=border_color, # facecolor='#FFFFFF', linewidth=0.25), # size=20)#18) # add text border_ax.text((4. / fig.get_figwidth()) * 0.015, 0.03, now.strftime("%Y-%m-%d, %I:%M:%S {}".format('UT')), horizontalalignment='left', verticalalignment='top', color=text_color, size=10) border_ax.text(0.5, 0.98, plot_title, horizontalalignment='center', verticalalignment='top', color=text_color, size=20) border_ax.text(1 - (4. / fig.get_figwidth()) * 0.015, 0.03, 'earthref.org/MagIC{}'.format(con_id), horizontalalignment='right', verticalalignment='top', color=text_color, size=10) return Figs
python
def add_borders(Figs, titles, border_color='#000000', text_color='#800080', con_id=""): """ Formatting for generating plots on the server Default border color: black Default text color: purple """ def split_title(s): """ Add '\n's to split of overly long titles """ s_list = s.split(",") lines = [] tot = 0 line = [] for i in s_list: tot += len(i) if tot < 30: line.append(i + ",") else: lines.append(" ".join(line)) line = [i] tot = 0 lines.append(" ".join(line)) return "\n".join(lines).strip(',') # format contribution id if available if con_id: if not str(con_id).startswith("/"): con_id = "/" + str(con_id) import datetime now = datetime.datetime.utcnow() for key in list(Figs.keys()): fig = plt.figure(Figs[key]) plot_title = split_title(titles[key]).strip().strip('\n') fig.set_figheight(5.5) #get returns Bbox with x0, y0, x1, y1 pos = fig.gca().get_position() # tweak some of the default values w = pos.x1 - pos.x0 h = (pos.y1 - pos.y0) / 1.1 x = pos.x0 y = pos.y0 * 1.3 # set takes: left, bottom, width, height fig.gca().set_position([x, y, w, h]) # add an axis covering the entire figure border_ax = fig.add_axes([0, 0, 1, 1]) border_ax.set_frame_on(False) border_ax.set_xticks([]) border_ax.set_yticks([]) # add a border if "\n" in plot_title: y_val = 1.0 # lower border #fig.set_figheight(6.25) else: y_val = 1.04 # higher border #border_ax.text(-0.02, y_val, " # |", # horizontalalignment='left', # verticalalignment='top', # color=text_color, # bbox=dict(edgecolor=border_color, # facecolor='#FFFFFF', linewidth=0.25), # size=50) #border_ax.text(-0.02, 0, "| # |", # horizontalalignment='left', # verticalalignment='bottom', # color=text_color, # bbox=dict(edgecolor=border_color, # facecolor='#FFFFFF', linewidth=0.25), # size=20)#18) # add text border_ax.text((4. / fig.get_figwidth()) * 0.015, 0.03, now.strftime("%Y-%m-%d, %I:%M:%S {}".format('UT')), horizontalalignment='left', verticalalignment='top', color=text_color, size=10) border_ax.text(0.5, 0.98, plot_title, horizontalalignment='center', verticalalignment='top', color=text_color, size=20) border_ax.text(1 - (4. / fig.get_figwidth()) * 0.015, 0.03, 'earthref.org/MagIC{}'.format(con_id), horizontalalignment='right', verticalalignment='top', color=text_color, size=10) return Figs
Formatting for generating plots on the server Default border color: black Default text color: purple
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2872-L2964
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_map_basemap
def plot_map_basemap(fignum, lats, lons, Opts): """ plot_map_basemap(fignum, lats,lons,Opts) makes a basemap with lats/lons requires working installation of Basemap Parameters: _______________ fignum : matplotlib figure number lats : array or list of latitudes lons : array or list of longitudes Opts : dictionary of plotting options: Opts.keys= latmin : minimum latitude for plot latmax : maximum latitude for plot lonmin : minimum longitude for plot lonmax : maximum longitude lat_0 : central latitude lon_0 : central longitude proj : projection [basemap projections, e.g., moll=Mollweide, merc=Mercator, ortho=orthorhombic, lcc=Lambert Conformal] sym : matplotlib symbol symsize : symbol size in pts edge : markeredgecolor pltgrid : plot the grid [1,0] res : resolution [c,l,i,h] for crude, low, intermediate, high boundinglat : bounding latitude sym : matplotlib symbol for plotting symsize : matplotlib symbol size for plotting names : list of names for lats/lons (if empty, none will be plotted) pltgrd : if True, put on grid lines padlat : padding of latitudes padlon : padding of longitudes gridspace : grid line spacing details : dictionary with keys: coasts : if True, plot coastlines rivers : if True, plot rivers states : if True, plot states countries : if True, plot countries ocean : if True, plot ocean fancy : if True, plot etopo 20 grid NB: etopo must be installed if Opts keys not set :these are the defaults: Opts={'latmin':-90,'latmax':90,'lonmin':0,'lonmax':360,'lat_0':0,'lon_0':0,'proj':'moll','sym':'ro,'symsize':5,'pltgrid':1,'res':'c','boundinglat':0.,'padlon':0,'padlat':0,'gridspace':30,'details':all False,'edge':None} """ if not has_basemap: print('-W- Basemap must be installed to run plot_map_basemap') return fig = plt.figure(num=fignum) rgba_land = (255, 255, 150, 255) rgba_ocean = (200, 250, 255, 255) ExMer = ['sinus', 'moll', 'lcc'] # draw meridian labels on the bottom [left,right,top,bottom] mlabels = [0, 0, 0, 1] plabels = [1, 0, 0, 0] # draw parallel labels on the left # set default Options Opts_defaults = {'latmin': -90, 'latmax': 90, 'lonmin': 0, 'lonmax': 360, 'lat_0': 0, 'lon_0': 0, 'proj': 'moll', 'sym': 'ro', 'symsize': 5, 'edge': None, 'pltgrid': 1, 'res': 'c', 'boundinglat': 0., 'padlon': 0, 'padlat': 0, 'gridspace': 30, 'details': {'fancy': 0, 'coasts': 0, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 0}} for key in Opts_defaults.keys(): if key not in Opts.keys() and key != 'details': Opts[key] = Opts_defaults[key] if key == 'details': if key not in Opts.keys(): Opts[key] = Opts_defaults[key] for detail_key in Opts_defaults[key].keys(): if detail_key not in Opts[key].keys(): Opts[key][detail_key] = Opts_defaults[key][detail_key] if Opts['proj'] in ExMer: mlabels = [0, 0, 0, 0] if Opts['proj'] not in ExMer: m = Basemap(projection=Opts['proj'], lat_0=Opts['lat_0'], lon_0=Opts['lon_0'], resolution=Opts['res']) plabels = [0, 0, 0, 0] else: m = Basemap(llcrnrlon=Opts['lonmin'], llcrnrlat=Opts['latmin'], urcrnrlat=Opts['latmax'], urcrnrlon=Opts['lonmax'], projection=Opts['proj'], lat_0=Opts['lat_0'], lon_0=Opts['lon_0'], lat_ts=0., resolution=Opts['res'], boundinglat=Opts['boundinglat']) if 'details' in list(Opts.keys()): if Opts['details']['fancy'] == 1: from mpl_toolkits.basemap import basemap_datadir EDIR = basemap_datadir + "/" etopo = np.loadtxt(EDIR + 'etopo20data.gz') elons = np.loadtxt(EDIR + 'etopo20lons.gz') elats = np.loadtxt(EDIR + 'etopo20lats.gz') x, y = m(*np.meshgrid(elons, elats)) cs = m.contourf(x, y, etopo, 30, cmap=color_map.jet) if Opts['details']['coasts'] == 1: m.drawcoastlines(color='k') if Opts['details']['rivers'] == 1: m.drawrivers(color='b') if Opts['details']['states'] == 1: m.drawstates(color='r') if Opts['details']['countries'] == 1: m.drawcountries(color='g') if Opts['details']['ocean'] == 1: try: m.drawlsmask(land_color=rgba_land, ocean_color=rgba_ocean, lsmask_lats=None) except TypeError: # this is caused by basemap function: _readlsmask # interacting with numpy # (a float is provided, numpy wants an int). # hopefully will be fixed eventually. pass if Opts['pltgrid'] == 0.: circles = np.arange(Opts['latmin'], Opts['latmax'] + 15., 15.) meridians = np.arange(Opts['lonmin'], Opts['lonmax'] + 30., 30.) elif Opts['pltgrid'] > 0: if Opts['proj'] in ExMer or Opts['proj'] == 'lcc': circles = np.arange(-90, 180. + Opts['gridspace'], Opts['gridspace']) meridians = np.arange(0, 360., Opts['gridspace']) else: g = Opts['gridspace'] latmin, lonmin = g * \ int(old_div(Opts['latmin'], g)), g * \ int(old_div(Opts['lonmin'], g)) latmax, lonmax = g * \ int(old_div(Opts['latmax'], g)), g * \ int(old_div(Opts['lonmax'], g)) # circles=np.arange(latmin-2.*Opts['padlat'],latmax+2.*Opts['padlat'],Opts['gridspace']) # meridians=np.arange(lonmin-2.*Opts['padlon'],lonmax+2.*Opts['padlon'],Opts['gridspace']) meridians = np.arange(0, 360, 30) circles = np.arange(-90, 90, 30) if Opts['pltgrid'] >= 0: # m.drawparallels(circles,color='black',labels=plabels) # m.drawmeridians(meridians,color='black',labels=mlabels) # skip the labels - they are ugly m.drawparallels(circles, color='black') # skip the labels - they are ugly m.drawmeridians(meridians, color='black') m.drawmapboundary() prn_name, symsize = 0, 5 if 'names' in Opts.keys() and len(Opts['names']) > 0: names = Opts['names'] if len(names) > 0: prn_name = 1 # X, Y, T, k = [], [], [], 0 if 'symsize' in list(Opts.keys()): symsize = Opts['symsize'] if Opts['sym'][-1] != '-': # just plot points X, Y = m(lons, lats) if prn_name == 1: for pt in range(len(lats)): T.append(plt.text(X[pt] + 5000, Y[pt] - 5000, names[pt])) m.plot(X, Y, Opts['sym'], markersize=symsize, markeredgecolor=Opts['edge']) else: # for lines, need to separate chunks using lat==100. chunk = 1 while k < len(lats) - 1: if lats[k] <= 90: # part of string x, y = m(lons[k], lats[k]) if x < 1e20: X.append(x) if y < 1e20: Y.append(y) # exclude off the map points if prn_name == 1: T.append(plt.text(x + 5000, y - 5000, names[k])) k += 1 else: # need to skip 100.0s and move to next chunk # plot previous chunk m.plot(X, Y, Opts['sym'], markersize=symsize, markeredgecolor=Opts['edge']) chunk += 1 while lats[k] > 90. and k < len(lats) - 1: k += 1 # skip bad points X, Y, T = [], [], [] if len(X) > 0: m.plot(X, Y, Opts['sym'], markersize=symsize, markeredgecolor=Opts['edge'])
python
def plot_map_basemap(fignum, lats, lons, Opts): """ plot_map_basemap(fignum, lats,lons,Opts) makes a basemap with lats/lons requires working installation of Basemap Parameters: _______________ fignum : matplotlib figure number lats : array or list of latitudes lons : array or list of longitudes Opts : dictionary of plotting options: Opts.keys= latmin : minimum latitude for plot latmax : maximum latitude for plot lonmin : minimum longitude for plot lonmax : maximum longitude lat_0 : central latitude lon_0 : central longitude proj : projection [basemap projections, e.g., moll=Mollweide, merc=Mercator, ortho=orthorhombic, lcc=Lambert Conformal] sym : matplotlib symbol symsize : symbol size in pts edge : markeredgecolor pltgrid : plot the grid [1,0] res : resolution [c,l,i,h] for crude, low, intermediate, high boundinglat : bounding latitude sym : matplotlib symbol for plotting symsize : matplotlib symbol size for plotting names : list of names for lats/lons (if empty, none will be plotted) pltgrd : if True, put on grid lines padlat : padding of latitudes padlon : padding of longitudes gridspace : grid line spacing details : dictionary with keys: coasts : if True, plot coastlines rivers : if True, plot rivers states : if True, plot states countries : if True, plot countries ocean : if True, plot ocean fancy : if True, plot etopo 20 grid NB: etopo must be installed if Opts keys not set :these are the defaults: Opts={'latmin':-90,'latmax':90,'lonmin':0,'lonmax':360,'lat_0':0,'lon_0':0,'proj':'moll','sym':'ro,'symsize':5,'pltgrid':1,'res':'c','boundinglat':0.,'padlon':0,'padlat':0,'gridspace':30,'details':all False,'edge':None} """ if not has_basemap: print('-W- Basemap must be installed to run plot_map_basemap') return fig = plt.figure(num=fignum) rgba_land = (255, 255, 150, 255) rgba_ocean = (200, 250, 255, 255) ExMer = ['sinus', 'moll', 'lcc'] # draw meridian labels on the bottom [left,right,top,bottom] mlabels = [0, 0, 0, 1] plabels = [1, 0, 0, 0] # draw parallel labels on the left # set default Options Opts_defaults = {'latmin': -90, 'latmax': 90, 'lonmin': 0, 'lonmax': 360, 'lat_0': 0, 'lon_0': 0, 'proj': 'moll', 'sym': 'ro', 'symsize': 5, 'edge': None, 'pltgrid': 1, 'res': 'c', 'boundinglat': 0., 'padlon': 0, 'padlat': 0, 'gridspace': 30, 'details': {'fancy': 0, 'coasts': 0, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 0}} for key in Opts_defaults.keys(): if key not in Opts.keys() and key != 'details': Opts[key] = Opts_defaults[key] if key == 'details': if key not in Opts.keys(): Opts[key] = Opts_defaults[key] for detail_key in Opts_defaults[key].keys(): if detail_key not in Opts[key].keys(): Opts[key][detail_key] = Opts_defaults[key][detail_key] if Opts['proj'] in ExMer: mlabels = [0, 0, 0, 0] if Opts['proj'] not in ExMer: m = Basemap(projection=Opts['proj'], lat_0=Opts['lat_0'], lon_0=Opts['lon_0'], resolution=Opts['res']) plabels = [0, 0, 0, 0] else: m = Basemap(llcrnrlon=Opts['lonmin'], llcrnrlat=Opts['latmin'], urcrnrlat=Opts['latmax'], urcrnrlon=Opts['lonmax'], projection=Opts['proj'], lat_0=Opts['lat_0'], lon_0=Opts['lon_0'], lat_ts=0., resolution=Opts['res'], boundinglat=Opts['boundinglat']) if 'details' in list(Opts.keys()): if Opts['details']['fancy'] == 1: from mpl_toolkits.basemap import basemap_datadir EDIR = basemap_datadir + "/" etopo = np.loadtxt(EDIR + 'etopo20data.gz') elons = np.loadtxt(EDIR + 'etopo20lons.gz') elats = np.loadtxt(EDIR + 'etopo20lats.gz') x, y = m(*np.meshgrid(elons, elats)) cs = m.contourf(x, y, etopo, 30, cmap=color_map.jet) if Opts['details']['coasts'] == 1: m.drawcoastlines(color='k') if Opts['details']['rivers'] == 1: m.drawrivers(color='b') if Opts['details']['states'] == 1: m.drawstates(color='r') if Opts['details']['countries'] == 1: m.drawcountries(color='g') if Opts['details']['ocean'] == 1: try: m.drawlsmask(land_color=rgba_land, ocean_color=rgba_ocean, lsmask_lats=None) except TypeError: # this is caused by basemap function: _readlsmask # interacting with numpy # (a float is provided, numpy wants an int). # hopefully will be fixed eventually. pass if Opts['pltgrid'] == 0.: circles = np.arange(Opts['latmin'], Opts['latmax'] + 15., 15.) meridians = np.arange(Opts['lonmin'], Opts['lonmax'] + 30., 30.) elif Opts['pltgrid'] > 0: if Opts['proj'] in ExMer or Opts['proj'] == 'lcc': circles = np.arange(-90, 180. + Opts['gridspace'], Opts['gridspace']) meridians = np.arange(0, 360., Opts['gridspace']) else: g = Opts['gridspace'] latmin, lonmin = g * \ int(old_div(Opts['latmin'], g)), g * \ int(old_div(Opts['lonmin'], g)) latmax, lonmax = g * \ int(old_div(Opts['latmax'], g)), g * \ int(old_div(Opts['lonmax'], g)) # circles=np.arange(latmin-2.*Opts['padlat'],latmax+2.*Opts['padlat'],Opts['gridspace']) # meridians=np.arange(lonmin-2.*Opts['padlon'],lonmax+2.*Opts['padlon'],Opts['gridspace']) meridians = np.arange(0, 360, 30) circles = np.arange(-90, 90, 30) if Opts['pltgrid'] >= 0: # m.drawparallels(circles,color='black',labels=plabels) # m.drawmeridians(meridians,color='black',labels=mlabels) # skip the labels - they are ugly m.drawparallels(circles, color='black') # skip the labels - they are ugly m.drawmeridians(meridians, color='black') m.drawmapboundary() prn_name, symsize = 0, 5 if 'names' in Opts.keys() and len(Opts['names']) > 0: names = Opts['names'] if len(names) > 0: prn_name = 1 # X, Y, T, k = [], [], [], 0 if 'symsize' in list(Opts.keys()): symsize = Opts['symsize'] if Opts['sym'][-1] != '-': # just plot points X, Y = m(lons, lats) if prn_name == 1: for pt in range(len(lats)): T.append(plt.text(X[pt] + 5000, Y[pt] - 5000, names[pt])) m.plot(X, Y, Opts['sym'], markersize=symsize, markeredgecolor=Opts['edge']) else: # for lines, need to separate chunks using lat==100. chunk = 1 while k < len(lats) - 1: if lats[k] <= 90: # part of string x, y = m(lons[k], lats[k]) if x < 1e20: X.append(x) if y < 1e20: Y.append(y) # exclude off the map points if prn_name == 1: T.append(plt.text(x + 5000, y - 5000, names[k])) k += 1 else: # need to skip 100.0s and move to next chunk # plot previous chunk m.plot(X, Y, Opts['sym'], markersize=symsize, markeredgecolor=Opts['edge']) chunk += 1 while lats[k] > 90. and k < len(lats) - 1: k += 1 # skip bad points X, Y, T = [], [], [] if len(X) > 0: m.plot(X, Y, Opts['sym'], markersize=symsize, markeredgecolor=Opts['edge'])
plot_map_basemap(fignum, lats,lons,Opts) makes a basemap with lats/lons requires working installation of Basemap Parameters: _______________ fignum : matplotlib figure number lats : array or list of latitudes lons : array or list of longitudes Opts : dictionary of plotting options: Opts.keys= latmin : minimum latitude for plot latmax : maximum latitude for plot lonmin : minimum longitude for plot lonmax : maximum longitude lat_0 : central latitude lon_0 : central longitude proj : projection [basemap projections, e.g., moll=Mollweide, merc=Mercator, ortho=orthorhombic, lcc=Lambert Conformal] sym : matplotlib symbol symsize : symbol size in pts edge : markeredgecolor pltgrid : plot the grid [1,0] res : resolution [c,l,i,h] for crude, low, intermediate, high boundinglat : bounding latitude sym : matplotlib symbol for plotting symsize : matplotlib symbol size for plotting names : list of names for lats/lons (if empty, none will be plotted) pltgrd : if True, put on grid lines padlat : padding of latitudes padlon : padding of longitudes gridspace : grid line spacing details : dictionary with keys: coasts : if True, plot coastlines rivers : if True, plot rivers states : if True, plot states countries : if True, plot countries ocean : if True, plot ocean fancy : if True, plot etopo 20 grid NB: etopo must be installed if Opts keys not set :these are the defaults: Opts={'latmin':-90,'latmax':90,'lonmin':0,'lonmax':360,'lat_0':0,'lon_0':0,'proj':'moll','sym':'ro,'symsize':5,'pltgrid':1,'res':'c','boundinglat':0.,'padlon':0,'padlat':0,'gridspace':30,'details':all False,'edge':None}
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2967-L3140
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_map
def plot_map(fignum, lats, lons, Opts): """ makes a cartopy map with lats/lons Requires installation of cartopy Parameters: _______________ fignum : matplotlib figure number lats : array or list of latitudes lons : array or list of longitudes Opts : dictionary of plotting options: Opts.keys= proj : projection [supported cartopy projections: pc = Plate Carree aea = Albers Equal Area aeqd = Azimuthal Equidistant lcc = Lambert Conformal lcyl = Lambert Cylindrical merc = Mercator mill = Miller Cylindrical moll = Mollweide [default] ortho = Orthographic robin = Robinson sinu = Sinusoidal stere = Stereographic tmerc = Transverse Mercator utm = UTM [set zone and south keys in Opts] laea = Lambert Azimuthal Equal Area geos = Geostationary npstere = North-Polar Stereographic spstere = South-Polar Stereographic latmin : minimum latitude for plot latmax : maximum latitude for plot lonmin : minimum longitude for plot lonmax : maximum longitude lat_0 : central latitude lon_0 : central longitude sym : matplotlib symbol symsize : symbol size in pts edge : markeredgecolor cmap : matplotlib color map res : resolution [c,l,i,h] for low/crude, intermediate, high boundinglat : bounding latitude sym : matplotlib symbol for plotting symsize : matplotlib symbol size for plotting names : list of names for lats/lons (if empty, none will be plotted) pltgrd : if True, put on grid lines padlat : padding of latitudes padlon : padding of longitudes gridspace : grid line spacing global : global projection [default is True] oceancolor : 'azure' landcolor : 'bisque' [choose any of the valid color names for matplotlib see https://matplotlib.org/examples/color/named_colors.html details : dictionary with keys: coasts : if True, plot coastlines rivers : if True, plot rivers states : if True, plot states countries : if True, plot countries ocean : if True, plot ocean fancy : if True, plot etopo 20 grid NB: etopo must be installed if Opts keys not set :these are the defaults: Opts={'latmin':-90,'latmax':90,'lonmin':0,'lonmax':360,'lat_0':0,'lon_0':0,'proj':'moll','sym':'ro,'symsize':5,'edge':'black','pltgrid':1,'res':'c','boundinglat':0.,'padlon':0,'padlat':0,'gridspace':30,'details':all False,'edge':None,'cmap':'jet','fancy':0,'zone':'','south':False,'oceancolor':'azure','landcolor':'bisque'} """ if not has_cartopy: print('This function requires installation of cartopy') return from matplotlib import cm # draw meridian labels on the bottom [left,right,top,bottom] mlabels = [0, 0, 0, 1] plabels = [1, 0, 0, 0] # draw parallel labels on the left Opts_defaults = {'latmin': -90, 'latmax': 90, 'lonmin': 0, 'lonmax': 360, 'lat_0': 0, 'lon_0': 0, 'proj': 'moll', 'sym': 'ro', 'symsize': 5, 'edge': None, 'pltgrid': 1, 'res': 'c', 'boundinglat': 0., 'padlon': 0, 'padlat': 0, 'gridspace': 30, 'global': 1, 'cmap': 'jet','oceancolor':'azure','landcolor':'bisque', 'details': {'fancy': 0, 'coasts': 0, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 0}, 'edgecolor': 'face'} for key in Opts_defaults.keys(): if key not in Opts.keys() and key != 'details': Opts[key] = Opts_defaults[key] if key == 'details': if key not in Opts.keys(): Opts[key] = Opts_defaults[key] for detail_key in Opts_defaults[key].keys(): if detail_key not in Opts[key].keys(): Opts[key][detail_key] = Opts_defaults[key][detail_key] if Opts['proj'] == 'pc': ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([Opts['lonmin'], Opts['lonmax'], Opts['latmin'], Opts['latmax']], crs=ccrs.PlateCarree()) if Opts['proj'] == 'aea': ax = plt.axes(projection=ccrs.AlbersEqualArea( central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'], false_easting=0.0, false_northing=0.0, standard_parallels=(20.0, 50.0), globe=None)) if Opts['proj'] == 'lcc': proj = ccrs.LambertConformal(central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'],\ false_easting=0.0, false_northing=0.0, standard_parallels=(20.0, 50.0), globe=None) fig=plt.figure(fignum,figsize=(6,6),frameon=True) ax = plt.axes(projection=proj) ax.set_extent([Opts['lonmin'], Opts['lonmax'], Opts['latmin'], Opts['latmax']], crs=ccrs.PlateCarree()) if Opts['proj'] == 'lcyl': ax = plt.axes(projection=ccrs.LambertCylindrical( central_longitude=Opts['lon_0'])) if Opts['proj'] == 'merc': ax = plt.axes(projection=ccrs.Mercator( central_longitude=Opts['lon_0'], min_latitude=Opts['latmin'], max_latitude=Opts['latmax'], latitude_true_scale=0.0, globe=None)) ax.set_extent([Opts['lonmin'],Opts['lonmax'],\ Opts['latmin'],Opts['latmax']]) if Opts['proj'] == 'mill': ax = plt.axes(projection=ccrs.Miller( central_longitude=Opts['lon_0'])) if Opts['proj'] == 'moll': ax = plt.axes(projection=ccrs.Mollweide( central_longitude=Opts['lat_0'], globe=None)) if Opts['proj'] == 'ortho': ax = plt.axes(projection=ccrs.Orthographic( central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'])) if Opts['proj'] == 'robin': ax = plt.axes(projection=ccrs.Robinson( central_longitude=Opts['lon_0'], globe=None)) if Opts['proj'] == 'sinu': ax = plt.axes(projection=ccrs.Sinusoidal( central_longitude=Opts['lon_0'], false_easting=0.0, false_northing=0.0, globe=None)) if Opts['proj'] == 'stere': ax = plt.axes(projection=ccrs.Stereographic( central_longitude=Opts['lon_0'], false_easting=0.0, false_northing=0.0, true_scale_latitude=None, scale_factor=None, globe=None)) if Opts['proj'] == 'tmerc': ax = plt.axes(projection=ccrs.TransverseMercator( central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'], false_easting=0.0, false_northing=0.0, scale_factor=None, globe=None)) if Opts['proj'] == 'utm': ax = plt.axes(projection=ccrs.UTM( zone=Opts['zone'], southern_hemisphere=Opts['south'], globe=None)) if Opts['proj'] == 'geos': ax = plt.axes(projection=ccrs.Geostationary( central_longitude=Opts['lon_0'], false_easting=0.0, false_northing=0.0, satellite_height=35785831, sweep_axis='y', globe=None)) if Opts['proj'] == 'laea': ax = plt.axes(projection=ccrs.LambertAzimuthalEqualArea( central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'], false_easting=0.0, false_northing=0.0, globe=None)) if Opts['proj'] == 'npstere': ax = plt.axes(projection=ccrs.NorthPolarStereo( central_longitude=Opts['lon_0'], true_scale_latitude=None, globe=None)) if Opts['proj'] == 'spstere': ax = plt.axes(projection=ccrs.SouthPolarStereo( central_longitude=Opts['lon_0'], true_scale_latitude=None, globe=None)) if 'details' in list(Opts.keys()): if Opts['details']['fancy'] == 1: pmag_data_dir = find_pmag_dir.get_data_files_dir() EDIR = os.path.join(pmag_data_dir, "etopo20") etopo_path = os.path.join(EDIR, 'etopo20data.gz') etopo = np.loadtxt(os.path.join(EDIR, 'etopo20data.gz')) elons = np.loadtxt(os.path.join(EDIR, 'etopo20lons.gz')) elats = np.loadtxt(os.path.join(EDIR, 'etopo20lats.gz')) xx, yy = np.meshgrid(elons, elats) levels = np.arange(-10000, 8000, 500) # define contour intervals m = ax.contourf(xx, yy, etopo, levels, transform=ccrs.PlateCarree(), cmap=Opts['cmap']) cbar=plt.colorbar(m) if Opts['details']['coasts'] == 1: if Opts['res']=='c' or Opts['res']=='l': ax.coastlines(resolution='110m') elif Opts['res']=='i': ax.coastlines(resolution='50m') elif Opts['res']=='h': ax.coastlines(resolution='10m') if Opts['details']['rivers'] == 1: ax.add_feature(cfeature.RIVERS) if Opts['details']['states'] == 1: states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', edgecolor='black', facecolor='none', linestyle='dotted') ax.add_feature(states_provinces) if Opts['details']['countries'] == 1: ax.add_feature(BORDERS, linestyle='-', linewidth=2) if Opts['details']['ocean'] == 1: ax.add_feature(OCEAN, color=Opts['oceancolor']) ax.add_feature(LAND, color=Opts['landcolor']) ax.add_feature(LAKES, color=Opts['oceancolor']) if Opts['proj'] in ['merc', 'pc','lcc']: if Opts['pltgrid']: if Opts['proj']=='lcc': fig.canvas.draw() #xticks=list(np.arange(Opts['lonmin'],Opts['lonmax']+Opts['gridspace'],Opts['gridspace'])) #yticks=list(np.arange(Opts['latmin'],Opts['latmax']+Opts['gridspace'],Opts['gridspace'])) xticks=list(np.arange(-180,180,Opts['gridspace'])) yticks=list(np.arange(-90,90,Opts['gridspace'])) ax.gridlines(ylocs=yticks,xlocs=xticks,linewidth=2, linestyle='dotted') ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) # you need this here ax.yaxis.set_major_formatter(LATITUDE_FORMATTER)# you need this here, too try: import pmagpy.lcc_ticks as lcc_ticks lcc_ticks.lambert_xticks(ax, xticks) lcc_ticks.lambert_yticks(ax, yticks) except: print ('plotting of tick marks on Lambert Conformal requires the package "shapely".\n Try importing with "conda install -c conda-forge shapely"') else: gl = ax.gridlines(crs=ccrs.PlateCarree(), linewidth=2, linestyle='dotted', draw_labels=True) gl.ylocator = mticker.FixedLocator(np.arange(-80, 81, Opts['gridspace'])) gl.xlocator = mticker.FixedLocator(np.arange(-180, 181, Opts['gridspace'])) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabels_top = False else: gl = ax.gridlines(crs=ccrs.PlateCarree(), linewidth=2, linestyle='dotted') elif Opts['pltgrid']: print('gridlines only supported for PlateCarree, Lambert Conformal, and Mercator plots currently') prn_name, symsize = 0, 5 # if 'names' in list(Opts.keys()) > 0: # names = Opts['names'] # if len(names) > 0: # prn_name = 1 ## X, Y, T, k = [], [], [], 0 if 'symsize' in list(Opts.keys()): symsize = Opts['symsize'] if Opts['sym'][-1] != '-': # just plot points color, symbol = Opts['sym'][0], Opts['sym'][1] ax.scatter(lons, lats, s=Opts['symsize'], c=color, marker=symbol, transform=ccrs.Geodetic(), edgecolors=Opts['edgecolor']) if prn_name == 1: print('labels not yet implemented in plot_map') # for pt in range(len(lats)): # T.append(plt.text(X[pt] + 5000, Y[pt] - 5000, names[pt])) else: # for lines, need to separate chunks using lat==100. ax.plot(lons, lats, Opts['sym'], transform=ccrs.Geodetic()) if Opts['global']: ax.set_global()
python
def plot_map(fignum, lats, lons, Opts): """ makes a cartopy map with lats/lons Requires installation of cartopy Parameters: _______________ fignum : matplotlib figure number lats : array or list of latitudes lons : array or list of longitudes Opts : dictionary of plotting options: Opts.keys= proj : projection [supported cartopy projections: pc = Plate Carree aea = Albers Equal Area aeqd = Azimuthal Equidistant lcc = Lambert Conformal lcyl = Lambert Cylindrical merc = Mercator mill = Miller Cylindrical moll = Mollweide [default] ortho = Orthographic robin = Robinson sinu = Sinusoidal stere = Stereographic tmerc = Transverse Mercator utm = UTM [set zone and south keys in Opts] laea = Lambert Azimuthal Equal Area geos = Geostationary npstere = North-Polar Stereographic spstere = South-Polar Stereographic latmin : minimum latitude for plot latmax : maximum latitude for plot lonmin : minimum longitude for plot lonmax : maximum longitude lat_0 : central latitude lon_0 : central longitude sym : matplotlib symbol symsize : symbol size in pts edge : markeredgecolor cmap : matplotlib color map res : resolution [c,l,i,h] for low/crude, intermediate, high boundinglat : bounding latitude sym : matplotlib symbol for plotting symsize : matplotlib symbol size for plotting names : list of names for lats/lons (if empty, none will be plotted) pltgrd : if True, put on grid lines padlat : padding of latitudes padlon : padding of longitudes gridspace : grid line spacing global : global projection [default is True] oceancolor : 'azure' landcolor : 'bisque' [choose any of the valid color names for matplotlib see https://matplotlib.org/examples/color/named_colors.html details : dictionary with keys: coasts : if True, plot coastlines rivers : if True, plot rivers states : if True, plot states countries : if True, plot countries ocean : if True, plot ocean fancy : if True, plot etopo 20 grid NB: etopo must be installed if Opts keys not set :these are the defaults: Opts={'latmin':-90,'latmax':90,'lonmin':0,'lonmax':360,'lat_0':0,'lon_0':0,'proj':'moll','sym':'ro,'symsize':5,'edge':'black','pltgrid':1,'res':'c','boundinglat':0.,'padlon':0,'padlat':0,'gridspace':30,'details':all False,'edge':None,'cmap':'jet','fancy':0,'zone':'','south':False,'oceancolor':'azure','landcolor':'bisque'} """ if not has_cartopy: print('This function requires installation of cartopy') return from matplotlib import cm # draw meridian labels on the bottom [left,right,top,bottom] mlabels = [0, 0, 0, 1] plabels = [1, 0, 0, 0] # draw parallel labels on the left Opts_defaults = {'latmin': -90, 'latmax': 90, 'lonmin': 0, 'lonmax': 360, 'lat_0': 0, 'lon_0': 0, 'proj': 'moll', 'sym': 'ro', 'symsize': 5, 'edge': None, 'pltgrid': 1, 'res': 'c', 'boundinglat': 0., 'padlon': 0, 'padlat': 0, 'gridspace': 30, 'global': 1, 'cmap': 'jet','oceancolor':'azure','landcolor':'bisque', 'details': {'fancy': 0, 'coasts': 0, 'rivers': 0, 'states': 0, 'countries': 0, 'ocean': 0}, 'edgecolor': 'face'} for key in Opts_defaults.keys(): if key not in Opts.keys() and key != 'details': Opts[key] = Opts_defaults[key] if key == 'details': if key not in Opts.keys(): Opts[key] = Opts_defaults[key] for detail_key in Opts_defaults[key].keys(): if detail_key not in Opts[key].keys(): Opts[key][detail_key] = Opts_defaults[key][detail_key] if Opts['proj'] == 'pc': ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([Opts['lonmin'], Opts['lonmax'], Opts['latmin'], Opts['latmax']], crs=ccrs.PlateCarree()) if Opts['proj'] == 'aea': ax = plt.axes(projection=ccrs.AlbersEqualArea( central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'], false_easting=0.0, false_northing=0.0, standard_parallels=(20.0, 50.0), globe=None)) if Opts['proj'] == 'lcc': proj = ccrs.LambertConformal(central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'],\ false_easting=0.0, false_northing=0.0, standard_parallels=(20.0, 50.0), globe=None) fig=plt.figure(fignum,figsize=(6,6),frameon=True) ax = plt.axes(projection=proj) ax.set_extent([Opts['lonmin'], Opts['lonmax'], Opts['latmin'], Opts['latmax']], crs=ccrs.PlateCarree()) if Opts['proj'] == 'lcyl': ax = plt.axes(projection=ccrs.LambertCylindrical( central_longitude=Opts['lon_0'])) if Opts['proj'] == 'merc': ax = plt.axes(projection=ccrs.Mercator( central_longitude=Opts['lon_0'], min_latitude=Opts['latmin'], max_latitude=Opts['latmax'], latitude_true_scale=0.0, globe=None)) ax.set_extent([Opts['lonmin'],Opts['lonmax'],\ Opts['latmin'],Opts['latmax']]) if Opts['proj'] == 'mill': ax = plt.axes(projection=ccrs.Miller( central_longitude=Opts['lon_0'])) if Opts['proj'] == 'moll': ax = plt.axes(projection=ccrs.Mollweide( central_longitude=Opts['lat_0'], globe=None)) if Opts['proj'] == 'ortho': ax = plt.axes(projection=ccrs.Orthographic( central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'])) if Opts['proj'] == 'robin': ax = plt.axes(projection=ccrs.Robinson( central_longitude=Opts['lon_0'], globe=None)) if Opts['proj'] == 'sinu': ax = plt.axes(projection=ccrs.Sinusoidal( central_longitude=Opts['lon_0'], false_easting=0.0, false_northing=0.0, globe=None)) if Opts['proj'] == 'stere': ax = plt.axes(projection=ccrs.Stereographic( central_longitude=Opts['lon_0'], false_easting=0.0, false_northing=0.0, true_scale_latitude=None, scale_factor=None, globe=None)) if Opts['proj'] == 'tmerc': ax = plt.axes(projection=ccrs.TransverseMercator( central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'], false_easting=0.0, false_northing=0.0, scale_factor=None, globe=None)) if Opts['proj'] == 'utm': ax = plt.axes(projection=ccrs.UTM( zone=Opts['zone'], southern_hemisphere=Opts['south'], globe=None)) if Opts['proj'] == 'geos': ax = plt.axes(projection=ccrs.Geostationary( central_longitude=Opts['lon_0'], false_easting=0.0, false_northing=0.0, satellite_height=35785831, sweep_axis='y', globe=None)) if Opts['proj'] == 'laea': ax = plt.axes(projection=ccrs.LambertAzimuthalEqualArea( central_longitude=Opts['lon_0'], central_latitude=Opts['lat_0'], false_easting=0.0, false_northing=0.0, globe=None)) if Opts['proj'] == 'npstere': ax = plt.axes(projection=ccrs.NorthPolarStereo( central_longitude=Opts['lon_0'], true_scale_latitude=None, globe=None)) if Opts['proj'] == 'spstere': ax = plt.axes(projection=ccrs.SouthPolarStereo( central_longitude=Opts['lon_0'], true_scale_latitude=None, globe=None)) if 'details' in list(Opts.keys()): if Opts['details']['fancy'] == 1: pmag_data_dir = find_pmag_dir.get_data_files_dir() EDIR = os.path.join(pmag_data_dir, "etopo20") etopo_path = os.path.join(EDIR, 'etopo20data.gz') etopo = np.loadtxt(os.path.join(EDIR, 'etopo20data.gz')) elons = np.loadtxt(os.path.join(EDIR, 'etopo20lons.gz')) elats = np.loadtxt(os.path.join(EDIR, 'etopo20lats.gz')) xx, yy = np.meshgrid(elons, elats) levels = np.arange(-10000, 8000, 500) # define contour intervals m = ax.contourf(xx, yy, etopo, levels, transform=ccrs.PlateCarree(), cmap=Opts['cmap']) cbar=plt.colorbar(m) if Opts['details']['coasts'] == 1: if Opts['res']=='c' or Opts['res']=='l': ax.coastlines(resolution='110m') elif Opts['res']=='i': ax.coastlines(resolution='50m') elif Opts['res']=='h': ax.coastlines(resolution='10m') if Opts['details']['rivers'] == 1: ax.add_feature(cfeature.RIVERS) if Opts['details']['states'] == 1: states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', edgecolor='black', facecolor='none', linestyle='dotted') ax.add_feature(states_provinces) if Opts['details']['countries'] == 1: ax.add_feature(BORDERS, linestyle='-', linewidth=2) if Opts['details']['ocean'] == 1: ax.add_feature(OCEAN, color=Opts['oceancolor']) ax.add_feature(LAND, color=Opts['landcolor']) ax.add_feature(LAKES, color=Opts['oceancolor']) if Opts['proj'] in ['merc', 'pc','lcc']: if Opts['pltgrid']: if Opts['proj']=='lcc': fig.canvas.draw() #xticks=list(np.arange(Opts['lonmin'],Opts['lonmax']+Opts['gridspace'],Opts['gridspace'])) #yticks=list(np.arange(Opts['latmin'],Opts['latmax']+Opts['gridspace'],Opts['gridspace'])) xticks=list(np.arange(-180,180,Opts['gridspace'])) yticks=list(np.arange(-90,90,Opts['gridspace'])) ax.gridlines(ylocs=yticks,xlocs=xticks,linewidth=2, linestyle='dotted') ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) # you need this here ax.yaxis.set_major_formatter(LATITUDE_FORMATTER)# you need this here, too try: import pmagpy.lcc_ticks as lcc_ticks lcc_ticks.lambert_xticks(ax, xticks) lcc_ticks.lambert_yticks(ax, yticks) except: print ('plotting of tick marks on Lambert Conformal requires the package "shapely".\n Try importing with "conda install -c conda-forge shapely"') else: gl = ax.gridlines(crs=ccrs.PlateCarree(), linewidth=2, linestyle='dotted', draw_labels=True) gl.ylocator = mticker.FixedLocator(np.arange(-80, 81, Opts['gridspace'])) gl.xlocator = mticker.FixedLocator(np.arange(-180, 181, Opts['gridspace'])) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabels_top = False else: gl = ax.gridlines(crs=ccrs.PlateCarree(), linewidth=2, linestyle='dotted') elif Opts['pltgrid']: print('gridlines only supported for PlateCarree, Lambert Conformal, and Mercator plots currently') prn_name, symsize = 0, 5 # if 'names' in list(Opts.keys()) > 0: # names = Opts['names'] # if len(names) > 0: # prn_name = 1 ## X, Y, T, k = [], [], [], 0 if 'symsize' in list(Opts.keys()): symsize = Opts['symsize'] if Opts['sym'][-1] != '-': # just plot points color, symbol = Opts['sym'][0], Opts['sym'][1] ax.scatter(lons, lats, s=Opts['symsize'], c=color, marker=symbol, transform=ccrs.Geodetic(), edgecolors=Opts['edgecolor']) if prn_name == 1: print('labels not yet implemented in plot_map') # for pt in range(len(lats)): # T.append(plt.text(X[pt] + 5000, Y[pt] - 5000, names[pt])) else: # for lines, need to separate chunks using lat==100. ax.plot(lons, lats, Opts['sym'], transform=ccrs.Geodetic()) if Opts['global']: ax.set_global()
makes a cartopy map with lats/lons Requires installation of cartopy Parameters: _______________ fignum : matplotlib figure number lats : array or list of latitudes lons : array or list of longitudes Opts : dictionary of plotting options: Opts.keys= proj : projection [supported cartopy projections: pc = Plate Carree aea = Albers Equal Area aeqd = Azimuthal Equidistant lcc = Lambert Conformal lcyl = Lambert Cylindrical merc = Mercator mill = Miller Cylindrical moll = Mollweide [default] ortho = Orthographic robin = Robinson sinu = Sinusoidal stere = Stereographic tmerc = Transverse Mercator utm = UTM [set zone and south keys in Opts] laea = Lambert Azimuthal Equal Area geos = Geostationary npstere = North-Polar Stereographic spstere = South-Polar Stereographic latmin : minimum latitude for plot latmax : maximum latitude for plot lonmin : minimum longitude for plot lonmax : maximum longitude lat_0 : central latitude lon_0 : central longitude sym : matplotlib symbol symsize : symbol size in pts edge : markeredgecolor cmap : matplotlib color map res : resolution [c,l,i,h] for low/crude, intermediate, high boundinglat : bounding latitude sym : matplotlib symbol for plotting symsize : matplotlib symbol size for plotting names : list of names for lats/lons (if empty, none will be plotted) pltgrd : if True, put on grid lines padlat : padding of latitudes padlon : padding of longitudes gridspace : grid line spacing global : global projection [default is True] oceancolor : 'azure' landcolor : 'bisque' [choose any of the valid color names for matplotlib see https://matplotlib.org/examples/color/named_colors.html details : dictionary with keys: coasts : if True, plot coastlines rivers : if True, plot rivers states : if True, plot states countries : if True, plot countries ocean : if True, plot ocean fancy : if True, plot etopo 20 grid NB: etopo must be installed if Opts keys not set :these are the defaults: Opts={'latmin':-90,'latmax':90,'lonmin':0,'lonmax':360,'lat_0':0,'lon_0':0,'proj':'moll','sym':'ro,'symsize':5,'edge':'black','pltgrid':1,'res':'c','boundinglat':0.,'padlon':0,'padlat':0,'gridspace':30,'details':all False,'edge':None,'cmap':'jet','fancy':0,'zone':'','south':False,'oceancolor':'azure','landcolor':'bisque'}
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L3143-L3412
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_mag_map_basemap
def plot_mag_map_basemap(fignum, element, lons, lats, element_type, cmap='RdYlBu', lon_0=0, date=""): """ makes a color contour map of geomagnetic field element Parameters ____________ fignum : matplotlib figure number element : field element array from pmag.do_mag_map for plotting lons : longitude array from pmag.do_mag_map for plotting lats : latitude array from pmag.do_mag_map for plotting element_type : [B,Br,I,D] geomagnetic element type B : field intensity Br : radial field intensity I : inclinations D : declinations Optional _________ cmap : matplotlib color map lon_0 : central longitude of the Hammer projection date : date used for field evaluation, if custom ghfile was used, supply filename Effects ______________ plots a Hammer projection color contour with the desired field element """ if not has_basemap: print('-W- Basemap must be installed to run plot_mag_map_basemap') return from matplotlib import cm # matplotlib's color map module lincr = 1 if type(date) != str: date = str(date) fig = plt.figure(fignum) m = Basemap(projection='hammer', lon_0=lon_0) x, y = m(*meshgrid(lons, lats)) m.drawcoastlines() if element_type == 'B': levmax = element.max()+lincr levmin = round(element.min()-lincr) levels = np.arange(levmin, levmax, lincr) cs = m.contourf(x, y, element, levels=levels, cmap=cmap) plt.title('Field strength ($\mu$T): '+date) if element_type == 'Br': levmax = element.max()+lincr levmin = round(element.min()-lincr) cs = m.contourf(x, y, element, levels=np.arange( levmin, levmax, lincr), cmap=cmap) plt.title('Radial field strength ($\mu$T): '+date) if element_type == 'I': levmax = element.max()+lincr levmin = round(element.min()-lincr) cs = m.contourf( x, y, element, levels=np.arange(-90, 100, 20), cmap=cmap) m.contour(x, y, element, levels=np.arange(-80, 90, 10), colors='black') plt.title('Field inclination: '+date) if element_type == 'D': # cs=m.contourf(x,y,element,levels=np.arange(-180,180,10),cmap=cmap) cs = m.contourf( x, y, element, levels=np.arange(-180, 180, 10), cmap=cmap) m.contour(x, y, element, levels=np.arange(-180, 180, 10), colors='black') plt.title('Field declination: '+date) cbar = m.colorbar(cs, location='bottom')
python
def plot_mag_map_basemap(fignum, element, lons, lats, element_type, cmap='RdYlBu', lon_0=0, date=""): """ makes a color contour map of geomagnetic field element Parameters ____________ fignum : matplotlib figure number element : field element array from pmag.do_mag_map for plotting lons : longitude array from pmag.do_mag_map for plotting lats : latitude array from pmag.do_mag_map for plotting element_type : [B,Br,I,D] geomagnetic element type B : field intensity Br : radial field intensity I : inclinations D : declinations Optional _________ cmap : matplotlib color map lon_0 : central longitude of the Hammer projection date : date used for field evaluation, if custom ghfile was used, supply filename Effects ______________ plots a Hammer projection color contour with the desired field element """ if not has_basemap: print('-W- Basemap must be installed to run plot_mag_map_basemap') return from matplotlib import cm # matplotlib's color map module lincr = 1 if type(date) != str: date = str(date) fig = plt.figure(fignum) m = Basemap(projection='hammer', lon_0=lon_0) x, y = m(*meshgrid(lons, lats)) m.drawcoastlines() if element_type == 'B': levmax = element.max()+lincr levmin = round(element.min()-lincr) levels = np.arange(levmin, levmax, lincr) cs = m.contourf(x, y, element, levels=levels, cmap=cmap) plt.title('Field strength ($\mu$T): '+date) if element_type == 'Br': levmax = element.max()+lincr levmin = round(element.min()-lincr) cs = m.contourf(x, y, element, levels=np.arange( levmin, levmax, lincr), cmap=cmap) plt.title('Radial field strength ($\mu$T): '+date) if element_type == 'I': levmax = element.max()+lincr levmin = round(element.min()-lincr) cs = m.contourf( x, y, element, levels=np.arange(-90, 100, 20), cmap=cmap) m.contour(x, y, element, levels=np.arange(-80, 90, 10), colors='black') plt.title('Field inclination: '+date) if element_type == 'D': # cs=m.contourf(x,y,element,levels=np.arange(-180,180,10),cmap=cmap) cs = m.contourf( x, y, element, levels=np.arange(-180, 180, 10), cmap=cmap) m.contour(x, y, element, levels=np.arange(-180, 180, 10), colors='black') plt.title('Field declination: '+date) cbar = m.colorbar(cs, location='bottom')
makes a color contour map of geomagnetic field element Parameters ____________ fignum : matplotlib figure number element : field element array from pmag.do_mag_map for plotting lons : longitude array from pmag.do_mag_map for plotting lats : latitude array from pmag.do_mag_map for plotting element_type : [B,Br,I,D] geomagnetic element type B : field intensity Br : radial field intensity I : inclinations D : declinations Optional _________ cmap : matplotlib color map lon_0 : central longitude of the Hammer projection date : date used for field evaluation, if custom ghfile was used, supply filename Effects ______________ plots a Hammer projection color contour with the desired field element
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L3415-L3478
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_mag_map
def plot_mag_map(fignum, element, lons, lats, element_type, cmap='coolwarm', lon_0=0, date="", contours=False, proj='PlateCarree'): """ makes a color contour map of geomagnetic field element Parameters ____________ fignum : matplotlib figure number element : field element array from pmag.do_mag_map for plotting lons : longitude array from pmag.do_mag_map for plotting lats : latitude array from pmag.do_mag_map for plotting element_type : [B,Br,I,D] geomagnetic element type B : field intensity Br : radial field intensity I : inclinations D : declinations Optional _________ contours : plot the contour lines on top of the heat map if True proj : cartopy projection ['PlateCarree','Mollweide'] NB: The Mollweide projection can only be reliably with cartopy=0.17.0; otherwise use lon_0=0. Also, for declinations, PlateCarree is recommended. cmap : matplotlib color map - see https://matplotlib.org/examples/color/colormaps_reference.html for options lon_0 : central longitude of the Mollweide projection date : date used for field evaluation, if custom ghfile was used, supply filename Effects ______________ plots a color contour map with the desired field element """ if not has_cartopy: print('This function requires installation of cartopy') return from matplotlib import cm if lon_0 == 180: lon_0 = 179.99 if lon_0 > 180: lon_0 = lon_0-360. lincr = 1 if type(date) != str: date = str(date) if proj == 'PlateCarree': fig = plt.figure(fignum) ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=lon_0)) if proj == 'Mollweide': fig = plt.figure(fignum) # this issue is fixed in >=0.17 if not LooseVersion(Cartopy.__version__) > LooseVersion('0.16.0'): if lon_0 != 0: print('This projection requires lon_0=0') return ax = plt.axes(projection=ccrs.Mollweide(central_longitude=lon_0)) xx, yy = np.meshgrid(lons, lats) levmax = 5*round(element.max()/5)+5 levmin = 5*round(element.min()/5)-5 if element_type == 'Br' or element_type == 'B': plt.contourf(xx, yy, element, levels=np.arange(levmin, levmax, 1), cmap=cmap, transform=ccrs.PlateCarree()) cbar = plt.colorbar(orientation='horizontal') if contours: plt.contour(xx, yy, element, levels=np.arange(levmin, levmax, 10), colors='black', transform=ccrs.PlateCarree()) if element_type == 'Br': plt.title('Radial field strength ($\mu$T): '+date) else: plt.title('Total field strength ($\mu$T): '+date) if element_type == 'I': plt.contourf(xx, yy, element, levels=np.arange(-90, 90, lincr), cmap=cmap, transform=ccrs.PlateCarree()) cbar = plt.colorbar(orientation='horizontal') if contours: plt.contour(xx, yy, element, levels=np.arange(-80, 90, 10), colors='black', transform=ccrs.PlateCarree()) plt.title('Field inclination: '+date) if element_type == 'D': plt.contourf(xx, yy, element, levels=np.arange(-180, 180, 10), cmap=cmap, transform=ccrs.PlateCarree()) cbar = plt.colorbar(orientation='horizontal') if contours: plt.contour(xx, yy, element, levels=np.arange(-180, 180, 10), colors='black', transform=ccrs.PlateCarree()) plt.title('Field declination: '+date) ax.coastlines() ax.set_global() return ax
python
def plot_mag_map(fignum, element, lons, lats, element_type, cmap='coolwarm', lon_0=0, date="", contours=False, proj='PlateCarree'): """ makes a color contour map of geomagnetic field element Parameters ____________ fignum : matplotlib figure number element : field element array from pmag.do_mag_map for plotting lons : longitude array from pmag.do_mag_map for plotting lats : latitude array from pmag.do_mag_map for plotting element_type : [B,Br,I,D] geomagnetic element type B : field intensity Br : radial field intensity I : inclinations D : declinations Optional _________ contours : plot the contour lines on top of the heat map if True proj : cartopy projection ['PlateCarree','Mollweide'] NB: The Mollweide projection can only be reliably with cartopy=0.17.0; otherwise use lon_0=0. Also, for declinations, PlateCarree is recommended. cmap : matplotlib color map - see https://matplotlib.org/examples/color/colormaps_reference.html for options lon_0 : central longitude of the Mollweide projection date : date used for field evaluation, if custom ghfile was used, supply filename Effects ______________ plots a color contour map with the desired field element """ if not has_cartopy: print('This function requires installation of cartopy') return from matplotlib import cm if lon_0 == 180: lon_0 = 179.99 if lon_0 > 180: lon_0 = lon_0-360. lincr = 1 if type(date) != str: date = str(date) if proj == 'PlateCarree': fig = plt.figure(fignum) ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=lon_0)) if proj == 'Mollweide': fig = plt.figure(fignum) # this issue is fixed in >=0.17 if not LooseVersion(Cartopy.__version__) > LooseVersion('0.16.0'): if lon_0 != 0: print('This projection requires lon_0=0') return ax = plt.axes(projection=ccrs.Mollweide(central_longitude=lon_0)) xx, yy = np.meshgrid(lons, lats) levmax = 5*round(element.max()/5)+5 levmin = 5*round(element.min()/5)-5 if element_type == 'Br' or element_type == 'B': plt.contourf(xx, yy, element, levels=np.arange(levmin, levmax, 1), cmap=cmap, transform=ccrs.PlateCarree()) cbar = plt.colorbar(orientation='horizontal') if contours: plt.contour(xx, yy, element, levels=np.arange(levmin, levmax, 10), colors='black', transform=ccrs.PlateCarree()) if element_type == 'Br': plt.title('Radial field strength ($\mu$T): '+date) else: plt.title('Total field strength ($\mu$T): '+date) if element_type == 'I': plt.contourf(xx, yy, element, levels=np.arange(-90, 90, lincr), cmap=cmap, transform=ccrs.PlateCarree()) cbar = plt.colorbar(orientation='horizontal') if contours: plt.contour(xx, yy, element, levels=np.arange(-80, 90, 10), colors='black', transform=ccrs.PlateCarree()) plt.title('Field inclination: '+date) if element_type == 'D': plt.contourf(xx, yy, element, levels=np.arange(-180, 180, 10), cmap=cmap, transform=ccrs.PlateCarree()) cbar = plt.colorbar(orientation='horizontal') if contours: plt.contour(xx, yy, element, levels=np.arange(-180, 180, 10), colors='black', transform=ccrs.PlateCarree()) plt.title('Field declination: '+date) ax.coastlines() ax.set_global() return ax
makes a color contour map of geomagnetic field element Parameters ____________ fignum : matplotlib figure number element : field element array from pmag.do_mag_map for plotting lons : longitude array from pmag.do_mag_map for plotting lats : latitude array from pmag.do_mag_map for plotting element_type : [B,Br,I,D] geomagnetic element type B : field intensity Br : radial field intensity I : inclinations D : declinations Optional _________ contours : plot the contour lines on top of the heat map if True proj : cartopy projection ['PlateCarree','Mollweide'] NB: The Mollweide projection can only be reliably with cartopy=0.17.0; otherwise use lon_0=0. Also, for declinations, PlateCarree is recommended. cmap : matplotlib color map - see https://matplotlib.org/examples/color/colormaps_reference.html for options lon_0 : central longitude of the Mollweide projection date : date used for field evaluation, if custom ghfile was used, supply filename Effects ______________ plots a color contour map with the desired field element
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L3481-L3570
PmagPy/PmagPy
pmagpy/pmagplotlib.py
plot_eq_cont
def plot_eq_cont(fignum, DIblock, color_map='coolwarm'): """ plots dec inc block as a color contour Parameters __________________ Input: fignum : figure number DIblock : nested pairs of [Declination, Inclination] color_map : matplotlib color map [default is coolwarm] Output: figure """ import random plt.figure(num=fignum) plt.axis("off") XY = [] centres = [] counter = 0 for rec in DIblock: counter = counter + 1 X = pmag.dir2cart([rec[0], rec[1], 1.]) # from Collinson 1983 R = old_div(np.sqrt(1. - X[2]), (np.sqrt(X[0]**2 + X[1]**2))) XY.append([X[0] * R, X[1] * R]) # radius of the circle radius = (old_div(3., (np.sqrt(np.pi * (9. + float(counter)))))) + 0.01 num = 2. * (old_div(1., radius)) # number of circles # a,b are the extent of the grids over which the circles are equispaced a1, a2 = (0. - (radius * num / 2.)), (0. + (radius * num / 2.)) b1, b2 = (0. - (radius * num / 2.)), (0. + (radius * num / 2.)) # this is to get an array (a list of list wont do) of x,y values xlist = np.linspace(a1, a2, int(np.ceil(num))) ylist = np.linspace(b1, b2, int(np.ceil(num))) X, Y = np.meshgrid(xlist, ylist) # to put z in the array I just multiply both x,y with zero. I will add to # the zero values later Z = X * Y * 0. # keeping the centres of the circles as a separate list instead of in # array helps later for j in range(len(ylist)): for i in range(len(xlist)): centres.append([xlist[i], ylist[j]]) # the following lines are to figure out what happens at the edges where part of a circle might lie outside # a thousand random numbers are generated within the x,y limit of the circles and tested whether it is contained in # the eq area net space....their ratio gives the fraction of circle # contained in the net fraction = [] beta, alpha = 0.001, 0.001 # to avoid those 'division by float' thingy for i in range(0, int(np.ceil(num))**2): if np.sqrt(((centres[i][0])**2) + ((centres[i][1])**2)) - 1. < radius: for j in range(1, 1000): rnd1 = random.uniform( centres[i][0] - radius, centres[i][0] + radius) rnd2 = random.uniform( centres[i][1] - radius, centres[i][1] + radius) if ((centres[i][0] - rnd1)**2 + (centres[i][1] - rnd2)**2) <= radius**2: if (rnd1**2) + (rnd2**2) < 1.: alpha = alpha + 1. beta = beta + 1. else: alpha = alpha + 1. fraction.append(old_div(alpha, beta)) alpha, beta = 0.001, 0.001 else: fraction.append(1.) # if the whole circle lies in the net # for every circle count the number of points lying in it count = 0 dotspercircle = 0. for j in range(0, int(np.ceil(num))): for i in range(0, int(np.ceil(num))): for k in range(0, counter): if (XY[k][0] - centres[count][0])**2 + (XY[k][1] - centres[count][1])**2 <= radius**2: dotspercircle += 1. Z[i][j] = Z[i][j] + (dotspercircle * fraction[count]) count += 1 dotspercircle = 0. im = plt.imshow(Z, interpolation='bilinear', origin='lower', # cmap=plt.color_map.hot, extent=(-1., 1., -1., 1.)) cmap=color_map, extent=(-1., 1., -1., 1.)) plt.colorbar(shrink=0.5) x, y = [], [] # Draws the border for i in range(0, 360): x.append(np.sin((old_div(np.pi, 180.)) * float(i))) y.append(np.cos((old_div(np.pi, 180.)) * float(i))) plt.plot(x, y, 'w-') x, y = [], [] # the map will be a square of 1X1..this is how I erase the redundant area for j in range(1, 4): for i in range(0, 360): x.append(np.sin((old_div(np.pi, 180.)) * float(i)) * (1. + (old_div(float(j), 10.)))) y.append(np.cos((old_div(np.pi, 180.)) * float(i)) * (1. + (old_div(float(j), 10.)))) plt.plot(x, y, 'w-', linewidth=26) x, y = [], [] # the axes plt.axis("equal")
python
def plot_eq_cont(fignum, DIblock, color_map='coolwarm'): """ plots dec inc block as a color contour Parameters __________________ Input: fignum : figure number DIblock : nested pairs of [Declination, Inclination] color_map : matplotlib color map [default is coolwarm] Output: figure """ import random plt.figure(num=fignum) plt.axis("off") XY = [] centres = [] counter = 0 for rec in DIblock: counter = counter + 1 X = pmag.dir2cart([rec[0], rec[1], 1.]) # from Collinson 1983 R = old_div(np.sqrt(1. - X[2]), (np.sqrt(X[0]**2 + X[1]**2))) XY.append([X[0] * R, X[1] * R]) # radius of the circle radius = (old_div(3., (np.sqrt(np.pi * (9. + float(counter)))))) + 0.01 num = 2. * (old_div(1., radius)) # number of circles # a,b are the extent of the grids over which the circles are equispaced a1, a2 = (0. - (radius * num / 2.)), (0. + (radius * num / 2.)) b1, b2 = (0. - (radius * num / 2.)), (0. + (radius * num / 2.)) # this is to get an array (a list of list wont do) of x,y values xlist = np.linspace(a1, a2, int(np.ceil(num))) ylist = np.linspace(b1, b2, int(np.ceil(num))) X, Y = np.meshgrid(xlist, ylist) # to put z in the array I just multiply both x,y with zero. I will add to # the zero values later Z = X * Y * 0. # keeping the centres of the circles as a separate list instead of in # array helps later for j in range(len(ylist)): for i in range(len(xlist)): centres.append([xlist[i], ylist[j]]) # the following lines are to figure out what happens at the edges where part of a circle might lie outside # a thousand random numbers are generated within the x,y limit of the circles and tested whether it is contained in # the eq area net space....their ratio gives the fraction of circle # contained in the net fraction = [] beta, alpha = 0.001, 0.001 # to avoid those 'division by float' thingy for i in range(0, int(np.ceil(num))**2): if np.sqrt(((centres[i][0])**2) + ((centres[i][1])**2)) - 1. < radius: for j in range(1, 1000): rnd1 = random.uniform( centres[i][0] - radius, centres[i][0] + radius) rnd2 = random.uniform( centres[i][1] - radius, centres[i][1] + radius) if ((centres[i][0] - rnd1)**2 + (centres[i][1] - rnd2)**2) <= radius**2: if (rnd1**2) + (rnd2**2) < 1.: alpha = alpha + 1. beta = beta + 1. else: alpha = alpha + 1. fraction.append(old_div(alpha, beta)) alpha, beta = 0.001, 0.001 else: fraction.append(1.) # if the whole circle lies in the net # for every circle count the number of points lying in it count = 0 dotspercircle = 0. for j in range(0, int(np.ceil(num))): for i in range(0, int(np.ceil(num))): for k in range(0, counter): if (XY[k][0] - centres[count][0])**2 + (XY[k][1] - centres[count][1])**2 <= radius**2: dotspercircle += 1. Z[i][j] = Z[i][j] + (dotspercircle * fraction[count]) count += 1 dotspercircle = 0. im = plt.imshow(Z, interpolation='bilinear', origin='lower', # cmap=plt.color_map.hot, extent=(-1., 1., -1., 1.)) cmap=color_map, extent=(-1., 1., -1., 1.)) plt.colorbar(shrink=0.5) x, y = [], [] # Draws the border for i in range(0, 360): x.append(np.sin((old_div(np.pi, 180.)) * float(i))) y.append(np.cos((old_div(np.pi, 180.)) * float(i))) plt.plot(x, y, 'w-') x, y = [], [] # the map will be a square of 1X1..this is how I erase the redundant area for j in range(1, 4): for i in range(0, 360): x.append(np.sin((old_div(np.pi, 180.)) * float(i)) * (1. + (old_div(float(j), 10.)))) y.append(np.cos((old_div(np.pi, 180.)) * float(i)) * (1. + (old_div(float(j), 10.)))) plt.plot(x, y, 'w-', linewidth=26) x, y = [], [] # the axes plt.axis("equal")
plots dec inc block as a color contour Parameters __________________ Input: fignum : figure number DIblock : nested pairs of [Declination, Inclination] color_map : matplotlib color map [default is coolwarm] Output: figure
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L3573-L3671
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)"): """ 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])
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L3674-L3722
PmagPy/PmagPy
programs/quick_hyst2.py
main
def main(): """ NAME quick_hyst.py DESCRIPTION makes plots of hysteresis data SYNTAX quick_hyst.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specify input file, default is magic_measurements.txt -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg] """ args = sys.argv PLT = 1 plots = 0 user, meas_file = "", "magic_measurements.txt" pltspec = "" dir_path = '.' fmt = 'png' verbose = pmagplotlib.verbose version_num = pmag.get_version() if '-WD' in args: ind = args.index('-WD') dir_path = args[ind+1] if "-h" in args: print(main.__doc__) sys.exit() if "-usr" in args: ind = args.index("-usr") user = args[ind+1] if '-f' in args: ind = args.index("-f") meas_file = args[ind+1] if '-sav' in args: verbose = 0 plots = 1 if '-spc' in args: ind = args.index("-spc") pltspec = args[ind+1] verbose = 0 plots = 1 if '-fmt' in args: ind = args.index("-fmt") fmt = args[ind+1] meas_file = dir_path+'/'+meas_file # # meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(main.__doc__) print('bad file') sys.exit() # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs, RemRecs = [], [] HDD = {} HDD['hyst'] = 1 pmagplotlib.plot_init(HDD['hyst'], 5, 5) # # get list of unique experiment names and specimen names # experiment_names, sids = [], [] hyst_data = pmag.get_dictitem( meas_data, 'magic_method_codes', 'LP-HYS', 'has') # get all hysteresis data for rec in hyst_data: if 'er_synthetic_name' in rec.keys() and rec['er_synthetic_name'] != "": rec['er_specimen_name'] = rec['er_synthetic_name'] if rec['magic_experiment_name'] not in experiment_names: experiment_names.append(rec['magic_experiment_name']) if rec['er_specimen_name'] not in sids: sids.append(rec['er_specimen_name']) if 'measurement_temp' not in rec.keys(): # assume room T measurement unless otherwise specified rec['measurement_temp'] = '300' # k = 0 if pltspec != "": k = sids.index(pltspec) intlist = ['measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume', 'measurement_magn_mass'] while k < len(sids): locname, site, sample, synth = '', '', '', '' s = sids[k] hmeths = [] if verbose: print(s, k+1, 'out of ', len(sids)) # # B, M = [], [] # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data # get all measurements for this specimen spec = pmag.get_dictitem(hyst_data, 'er_specimen_name', s, 'T') if 'er_location_name' in spec[0].keys(): locname = spec[0]['er_location_name'] if 'er_site_name' in spec[0].keys(): site = spec[0]['er_site_name'] if 'er_sample_name' in spec[0].keys(): sample = spec[0]['er_sample_name'] if 'er_synthetic_name' in spec[0].keys(): synth = spec[0]['er_synthetic_name'] for m in intlist: # get all non-blank data for this specimen meas_data = pmag.get_dictitem(spec, m, '', 'F') if len(meas_data) > 0: break c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-'] cnum = 0 if len(meas_data) > 0: Temps = [] xlab, ylab, title = '', '', '' for rec in meas_data: if rec['measurement_temp'] not in Temps: Temps.append(rec['measurement_temp']) for t in Temps: print('working on t: ', t) t_data = pmag.get_dictitem( meas_data, 'measurement_temp', t, 'T') B, M = [], [] for rec in t_data: B.append(float(rec['measurement_lab_field_dc'])) M.append(float(rec[m])) # now plot the hysteresis curve(s) # if len(B) > 0: B = numpy.array(B) M = numpy.array(M) if t == Temps[-1]: xlab = 'Field (T)' ylab = m title = 'Hysteresis: '+s if t == Temps[0]: pmagplotlib.clearFIG(HDD['hyst']) pmagplotlib.plot_xy( HDD['hyst'], B, M, sym=c[cnum], xlab=xlab, ylab=ylab, title=title) pmagplotlib.plot_xy(HDD['hyst'], [ 1.1*B.min(), 1.1*B.max()], [0, 0], sym='k-', xlab=xlab, ylab=ylab, title=title) pmagplotlib.plot_xy(HDD['hyst'], [0, 0], [ 1.1*M.min(), 1.1*M.max()], sym='k-', xlab=xlab, ylab=ylab, title=title) if verbose: pmagplotlib.draw_figs(HDD) cnum += 1 if cnum == len(c): cnum = 0 # files = {} if plots: if pltspec != "": s = pltspec files = {} for key in HDD.keys(): if pmagplotlib.isServer: # use server plot naming convention if synth == '': filename = "LO:_"+locname+'_SI:_'+site + \ '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt else: filename = 'SY:_'+synth+'_TY:_'+key+'_.'+fmt files[key] = filename else: # use more readable plot naming convention if synth == '': filename = '' for item in [locname, site, sample, s, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) else: filename = synth+'_'+key+'.fmt' files[key] = filename pmagplotlib.save_plots(HDD, files) if pltspec != "": sys.exit() if verbose: pmagplotlib.draw_figs(HDD) ans = raw_input( "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ") if ans == "a": files = {} for key in HDD.keys(): if pmagplotlib.isServer: print('server') files[key] = "LO:_"+locname+'_SI:_'+site + \ '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt else: print('not server') filename = '' for item in [locname, site, sample, s, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) files[key] = filename print('files', files) pmagplotlib.save_plots(HDD, files) if ans == '': k += 1 if ans == "p": del HystRecs[-1] k -= 1 if ans == 'q': print("Good bye") sys.exit() if ans == 's': keepon = 1 specimen = raw_input( 'Enter desired specimen name (or first part there of): ') while keepon == 1: try: k = sids.index(specimen) keepon = 0 except: tmplist = [] for qq in range(len(sids)): if specimen in sids[qq]: tmplist.append(sids[qq]) print(specimen, " not found, but this was: ") print(tmplist) specimen = raw_input('Select one or try again\n ') k = sids.index(specimen) else: k += 1 if len(B) == 0: if verbose: print('skipping this one - no hysteresis data') k += 1
python
def main(): """ NAME quick_hyst.py DESCRIPTION makes plots of hysteresis data SYNTAX quick_hyst.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specify input file, default is magic_measurements.txt -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg] """ args = sys.argv PLT = 1 plots = 0 user, meas_file = "", "magic_measurements.txt" pltspec = "" dir_path = '.' fmt = 'png' verbose = pmagplotlib.verbose version_num = pmag.get_version() if '-WD' in args: ind = args.index('-WD') dir_path = args[ind+1] if "-h" in args: print(main.__doc__) sys.exit() if "-usr" in args: ind = args.index("-usr") user = args[ind+1] if '-f' in args: ind = args.index("-f") meas_file = args[ind+1] if '-sav' in args: verbose = 0 plots = 1 if '-spc' in args: ind = args.index("-spc") pltspec = args[ind+1] verbose = 0 plots = 1 if '-fmt' in args: ind = args.index("-fmt") fmt = args[ind+1] meas_file = dir_path+'/'+meas_file # # meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(main.__doc__) print('bad file') sys.exit() # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs, RemRecs = [], [] HDD = {} HDD['hyst'] = 1 pmagplotlib.plot_init(HDD['hyst'], 5, 5) # # get list of unique experiment names and specimen names # experiment_names, sids = [], [] hyst_data = pmag.get_dictitem( meas_data, 'magic_method_codes', 'LP-HYS', 'has') # get all hysteresis data for rec in hyst_data: if 'er_synthetic_name' in rec.keys() and rec['er_synthetic_name'] != "": rec['er_specimen_name'] = rec['er_synthetic_name'] if rec['magic_experiment_name'] not in experiment_names: experiment_names.append(rec['magic_experiment_name']) if rec['er_specimen_name'] not in sids: sids.append(rec['er_specimen_name']) if 'measurement_temp' not in rec.keys(): # assume room T measurement unless otherwise specified rec['measurement_temp'] = '300' # k = 0 if pltspec != "": k = sids.index(pltspec) intlist = ['measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume', 'measurement_magn_mass'] while k < len(sids): locname, site, sample, synth = '', '', '', '' s = sids[k] hmeths = [] if verbose: print(s, k+1, 'out of ', len(sids)) # # B, M = [], [] # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data # get all measurements for this specimen spec = pmag.get_dictitem(hyst_data, 'er_specimen_name', s, 'T') if 'er_location_name' in spec[0].keys(): locname = spec[0]['er_location_name'] if 'er_site_name' in spec[0].keys(): site = spec[0]['er_site_name'] if 'er_sample_name' in spec[0].keys(): sample = spec[0]['er_sample_name'] if 'er_synthetic_name' in spec[0].keys(): synth = spec[0]['er_synthetic_name'] for m in intlist: # get all non-blank data for this specimen meas_data = pmag.get_dictitem(spec, m, '', 'F') if len(meas_data) > 0: break c = ['k-', 'b-', 'c-', 'g-', 'm-', 'r-', 'y-'] cnum = 0 if len(meas_data) > 0: Temps = [] xlab, ylab, title = '', '', '' for rec in meas_data: if rec['measurement_temp'] not in Temps: Temps.append(rec['measurement_temp']) for t in Temps: print('working on t: ', t) t_data = pmag.get_dictitem( meas_data, 'measurement_temp', t, 'T') B, M = [], [] for rec in t_data: B.append(float(rec['measurement_lab_field_dc'])) M.append(float(rec[m])) # now plot the hysteresis curve(s) # if len(B) > 0: B = numpy.array(B) M = numpy.array(M) if t == Temps[-1]: xlab = 'Field (T)' ylab = m title = 'Hysteresis: '+s if t == Temps[0]: pmagplotlib.clearFIG(HDD['hyst']) pmagplotlib.plot_xy( HDD['hyst'], B, M, sym=c[cnum], xlab=xlab, ylab=ylab, title=title) pmagplotlib.plot_xy(HDD['hyst'], [ 1.1*B.min(), 1.1*B.max()], [0, 0], sym='k-', xlab=xlab, ylab=ylab, title=title) pmagplotlib.plot_xy(HDD['hyst'], [0, 0], [ 1.1*M.min(), 1.1*M.max()], sym='k-', xlab=xlab, ylab=ylab, title=title) if verbose: pmagplotlib.draw_figs(HDD) cnum += 1 if cnum == len(c): cnum = 0 # files = {} if plots: if pltspec != "": s = pltspec files = {} for key in HDD.keys(): if pmagplotlib.isServer: # use server plot naming convention if synth == '': filename = "LO:_"+locname+'_SI:_'+site + \ '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt else: filename = 'SY:_'+synth+'_TY:_'+key+'_.'+fmt files[key] = filename else: # use more readable plot naming convention if synth == '': filename = '' for item in [locname, site, sample, s, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) else: filename = synth+'_'+key+'.fmt' files[key] = filename pmagplotlib.save_plots(HDD, files) if pltspec != "": sys.exit() if verbose: pmagplotlib.draw_figs(HDD) ans = raw_input( "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ") if ans == "a": files = {} for key in HDD.keys(): if pmagplotlib.isServer: print('server') files[key] = "LO:_"+locname+'_SI:_'+site + \ '_SA:_'+sample+'_SP:_'+s+'_TY:_'+key+'_.'+fmt else: print('not server') filename = '' for item in [locname, site, sample, s, key]: if item: item = item.replace(' ', '_') filename += item + '_' if filename.endswith('_'): filename = filename[:-1] filename += ".{}".format(fmt) files[key] = filename print('files', files) pmagplotlib.save_plots(HDD, files) if ans == '': k += 1 if ans == "p": del HystRecs[-1] k -= 1 if ans == 'q': print("Good bye") sys.exit() if ans == 's': keepon = 1 specimen = raw_input( 'Enter desired specimen name (or first part there of): ') while keepon == 1: try: k = sids.index(specimen) keepon = 0 except: tmplist = [] for qq in range(len(sids)): if specimen in sids[qq]: tmplist.append(sids[qq]) print(specimen, " not found, but this was: ") print(tmplist) specimen = raw_input('Select one or try again\n ') k = sids.index(specimen) else: k += 1 if len(B) == 0: if verbose: print('skipping this one - no hysteresis data') k += 1
NAME quick_hyst.py DESCRIPTION makes plots of hysteresis data SYNTAX quick_hyst.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specify input file, default is magic_measurements.txt -spc SPEC: specify specimen name to plot and quit -sav save all plots and quit -fmt [png,svg,eps,jpg]
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/quick_hyst2.py#L13-L248
PmagPy/PmagPy
programs/conversion_scripts2/jr6_txt_magic2.py
main
def main(command_line=True, **kwargs): """ NAME jr6_txt_magic.py DESCRIPTION converts JR6 .txt format files to magic_measurements format files SYNTAX jr6_txt_magic.py [command line options] OPTIONS -h: prints the help message and quits. -f FILE: specify input file, or -F FILE: specify output file, default is magic_measurements.txt -Fsa: specify er_samples format file for appending, default is new er_samples.txt (Not working yet) -spc NUM : specify number of characters to designate a specimen, default = 1 -loc LOCNAME : specify location/study name -A: don't average replicate measurements -ncn NCON: specify sample naming convention (6 and 7 not yet implemented) -mcd [SO-MAG,SO-SUN,SO-SIGHT...] supply how these samples were oriented -v NUM : specify the volume of the sample, default 2.5cm^3. Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX [5] site name same as sample [6] site is entered under a separate column NOT CURRENTLY SUPPORTED [7-Z] [XXXX]YYY: XXXX is site designation with Z characters with sample name XXXXYYYY NB: all others you will have to customize your self or e-mail [email protected] for help. INPUT JR6 .txt format file """ # initialize some stuff noave=0 volume = 2.5 * 1e-6 # default volume is 2.5 cm^3 (2.5 * 1e-6 meters^3) inst="" samp_con,Z='1',"" missing=1 demag="N" er_location_name="unknown" citation='This study' args=sys.argv meth_code="LP-NO" specnum=-1 MagRecs=[] version_num=pmag.get_version() Samps=[] # keeps track of sample orientations user="" mag_file="" dir_path='.' ErSamps=[] SampOuts=[] samp_file = 'er_samples.txt' meas_file = 'magic_measurements.txt' # # get command line arguments # if command_line: if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path=sys.argv[ind+1] if '-ID' in sys.argv: ind = sys.argv.index('-ID') input_dir_path = sys.argv[ind+1] else: input_dir_path = dir_path output_dir_path = dir_path if "-h" in args: print(main.__doc__) return False if '-F' in args: ind=args.index("-F") meas_file = args[ind+1] if '-Fsa' in args: ind = args.index("-Fsa") samp_file = args[ind+1] #try: # open(samp_file,'r') # ErSamps,file_type=pmag.magic_read(samp_file) # print 'sample information will be appended to ', samp_file #except: # print samp_file,' not found: sample information will be stored in new er_samples.txt file' # samp_file = output_dir_path+'/er_samples.txt' if '-f' in args: ind = args.index("-f") mag_file= args[ind+1] if "-spc" in args: ind = args.index("-spc") specnum = int(args[ind+1]) if "-ncn" in args: ind=args.index("-ncn") samp_con=sys.argv[ind+1] if "-loc" in args: ind=args.index("-loc") er_location_name=args[ind+1] if "-A" in args: noave=1 if "-mcd" in args: ind=args.index("-mcd") meth_code=args[ind+1] if "-v" in args: ind=args.index("-v") volume=float(args[ind+1]) * 1e-6 if not command_line: dir_path = kwargs.get('dir_path', '.') input_dir_path = kwargs.get('input_dir_path', dir_path) output_dir_path = dir_path meas_file = kwargs.get('meas_file', 'magic_measurements.txt') mag_file = kwargs.get('mag_file') samp_file = kwargs.get('samp_file', 'er_samples.txt') specnum = kwargs.get('specnum', 1) samp_con = kwargs.get('samp_con', '1') er_location_name = kwargs.get('er_location_name', '') noave = kwargs.get('noave', 0) # default (0) means DO average meth_code = kwargs.get('meth_code', "LP-NO") volume = float(kwargs.get('volume', 0)) if not volume: volume = 2.5 * 1e-6 #default volume is a 2.5 cm cube, translated to meters cubed else: #convert cm^3 to m^3 volume *= 1e-6 # format variables mag_file = input_dir_path+"/" + mag_file meas_file = output_dir_path+"/" + meas_file samp_file = output_dir_path+"/" + samp_file if specnum!=0: specnum=-specnum if "4" in samp_con: if "-" not in samp_con: print("option [4] must be in form 4-Z where Z is an integer") return False, "option [4] must be in form 4-Z where Z is an integer" else: Z=samp_con.split("-")[1] samp_con="4" if "7" in samp_con: if "-" not in samp_con: print("option [7] must be in form 7-Z where Z is an integer") return False, "option [7] must be in form 7-Z where Z is an integer" else: Z=samp_con.split("-")[1] samp_con="7" ErSampRec,ErSiteRec={},{} # parse data data=open(mag_file,'r') line=data.readline() line=data.readline() line=data.readline() while line !='': parsedLine=line.split() sampleName=parsedLine[0] demagLevel=parsedLine[2] date=parsedLine[3] line=data.readline() line=data.readline() line=data.readline() line=data.readline() parsedLine=line.split() specimenAngleDec=parsedLine[1] specimenAngleInc=parsedLine[2] while parsedLine[0] != 'MEAN' : line=data.readline() parsedLine=line.split() if len(parsedLine) == 0: parsedLine=["Hello"] Mx=parsedLine[1] My=parsedLine[2] Mz=parsedLine[3] line=data.readline() line=data.readline() parsedLine=line.split() splitExp = parsedLine[2].split('A') intensityVolStr=parsedLine[1] + splitExp[0] intensityVol = float(intensityVolStr) # check and see if Prec is too big and messes with the parcing. precisionStr='' if len(parsedLine) == 6: #normal line precisionStr=parsedLine[5][0:-1] else: precisionStr=parsedLine[4][0:-1] precisionPer = float(precisionStr) precision=intensityVol*precisionPer/100 while parsedLine[0] != 'SPEC.' : line=data.readline() parsedLine=line.split() if len(parsedLine) == 0: parsedLine=["Hello"] specimenDec=parsedLine[2] specimenInc=parsedLine[3] line=data.readline() line=data.readline() parsedLine=line.split() geographicDec=parsedLine[1] geographicInc=parsedLine[2] # Add data to various MagIC data tables. er_specimen_name = sampleName if specnum!=0: er_sample_name=er_specimen_name[:specnum] else: er_sample_name=er_specimen_name if int(samp_con) in [1, 2, 3, 4, 5, 7]: er_site_name=pmag.parse_site(er_sample_name,samp_con,Z) else: print("-W- Using unreognized sample convention option: ", samp_con) # else: # if 'er_site_name' in ErSampRec.keys():er_site_name=ErSampRec['er_site_name'] # if 'er_location_name' in ErSampRec.keys():er_location_name=ErSampRec['er_location_name'] # check sample list(SampOuts) to see if sample already exists in list before adding new sample info sampleFlag=0 for sampRec in SampOuts: if sampRec['er_sample_name'] == er_sample_name: sampleFlag=1 break if sampleFlag == 0: ErSampRec['er_sample_name']=er_sample_name ErSampRec['sample_azimuth']=specimenAngleDec sample_dip=str(float(specimenAngleInc)-90.0) #convert to magic orientation ErSampRec['sample_dip']=sample_dip ErSampRec['magic_method_codes']=meth_code ErSampRec['er_location_name']=er_location_name ErSampRec['er_site_name']=er_site_name ErSampRec['er_citation_names']='This study' SampOuts.append(ErSampRec.copy()) MagRec={} MagRec['measurement_description']='Date: '+date MagRec["er_citation_names"]="This study" MagRec['er_location_name']=er_location_name MagRec['er_site_name']=er_site_name MagRec['er_sample_name']=er_sample_name MagRec['magic_software_packages']=version_num MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin MagRec["measurement_flag"]='g' MagRec["measurement_standard"]='u' MagRec["measurement_number"]='1' MagRec["er_specimen_name"]=er_specimen_name MagRec["treatment_ac_field"]='0' if demagLevel == 'NRM': meas_type="LT-NO" elif demagLevel[0] == 'A': meas_type="LT-AF-Z" treat=float(demagLevel[1:]) MagRec["treatment_ac_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla elif demagLevel[0] == 'T': meas_type="LT-T-Z" treat=float(demagLevel[1:]) MagRec["treatment_temp"]='%8.3e' % (treat+273.) # temp in kelvin else: print("measurement type unknown", demag_level) return False, "measurement type unknown" MagRec["measurement_magn_moment"]=str(intensityVol*volume) # Am^2 MagRec["measurement_magn_volume"]=intensityVolStr # A/m MagRec["measurement_dec"]=specimenDec MagRec["measurement_inc"]=specimenInc MagRec['magic_method_codes']=meas_type MagRecs.append(MagRec.copy()) #read lines till end of record line=data.readline() line=data.readline() line=data.readline() line=data.readline() line=data.readline() # read all the rest of the special characters. Some data files not consistantly formatted. while (len(line) <=3 and line!=''): line=data.readline() #end of data while loop MagOuts=pmag.measurements_methods(MagRecs,noave) pmag.magic_write(samp_file,SampOuts,'er_samples') print("sample orientations put in ",samp_file) pmag.magic_write(meas_file,MagOuts,'magic_measurements') print("results put in ",meas_file) return True, meas_file
python
def main(command_line=True, **kwargs): """ NAME jr6_txt_magic.py DESCRIPTION converts JR6 .txt format files to magic_measurements format files SYNTAX jr6_txt_magic.py [command line options] OPTIONS -h: prints the help message and quits. -f FILE: specify input file, or -F FILE: specify output file, default is magic_measurements.txt -Fsa: specify er_samples format file for appending, default is new er_samples.txt (Not working yet) -spc NUM : specify number of characters to designate a specimen, default = 1 -loc LOCNAME : specify location/study name -A: don't average replicate measurements -ncn NCON: specify sample naming convention (6 and 7 not yet implemented) -mcd [SO-MAG,SO-SUN,SO-SIGHT...] supply how these samples were oriented -v NUM : specify the volume of the sample, default 2.5cm^3. Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX [5] site name same as sample [6] site is entered under a separate column NOT CURRENTLY SUPPORTED [7-Z] [XXXX]YYY: XXXX is site designation with Z characters with sample name XXXXYYYY NB: all others you will have to customize your self or e-mail [email protected] for help. INPUT JR6 .txt format file """ # initialize some stuff noave=0 volume = 2.5 * 1e-6 # default volume is 2.5 cm^3 (2.5 * 1e-6 meters^3) inst="" samp_con,Z='1',"" missing=1 demag="N" er_location_name="unknown" citation='This study' args=sys.argv meth_code="LP-NO" specnum=-1 MagRecs=[] version_num=pmag.get_version() Samps=[] # keeps track of sample orientations user="" mag_file="" dir_path='.' ErSamps=[] SampOuts=[] samp_file = 'er_samples.txt' meas_file = 'magic_measurements.txt' # # get command line arguments # if command_line: if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path=sys.argv[ind+1] if '-ID' in sys.argv: ind = sys.argv.index('-ID') input_dir_path = sys.argv[ind+1] else: input_dir_path = dir_path output_dir_path = dir_path if "-h" in args: print(main.__doc__) return False if '-F' in args: ind=args.index("-F") meas_file = args[ind+1] if '-Fsa' in args: ind = args.index("-Fsa") samp_file = args[ind+1] #try: # open(samp_file,'r') # ErSamps,file_type=pmag.magic_read(samp_file) # print 'sample information will be appended to ', samp_file #except: # print samp_file,' not found: sample information will be stored in new er_samples.txt file' # samp_file = output_dir_path+'/er_samples.txt' if '-f' in args: ind = args.index("-f") mag_file= args[ind+1] if "-spc" in args: ind = args.index("-spc") specnum = int(args[ind+1]) if "-ncn" in args: ind=args.index("-ncn") samp_con=sys.argv[ind+1] if "-loc" in args: ind=args.index("-loc") er_location_name=args[ind+1] if "-A" in args: noave=1 if "-mcd" in args: ind=args.index("-mcd") meth_code=args[ind+1] if "-v" in args: ind=args.index("-v") volume=float(args[ind+1]) * 1e-6 if not command_line: dir_path = kwargs.get('dir_path', '.') input_dir_path = kwargs.get('input_dir_path', dir_path) output_dir_path = dir_path meas_file = kwargs.get('meas_file', 'magic_measurements.txt') mag_file = kwargs.get('mag_file') samp_file = kwargs.get('samp_file', 'er_samples.txt') specnum = kwargs.get('specnum', 1) samp_con = kwargs.get('samp_con', '1') er_location_name = kwargs.get('er_location_name', '') noave = kwargs.get('noave', 0) # default (0) means DO average meth_code = kwargs.get('meth_code', "LP-NO") volume = float(kwargs.get('volume', 0)) if not volume: volume = 2.5 * 1e-6 #default volume is a 2.5 cm cube, translated to meters cubed else: #convert cm^3 to m^3 volume *= 1e-6 # format variables mag_file = input_dir_path+"/" + mag_file meas_file = output_dir_path+"/" + meas_file samp_file = output_dir_path+"/" + samp_file if specnum!=0: specnum=-specnum if "4" in samp_con: if "-" not in samp_con: print("option [4] must be in form 4-Z where Z is an integer") return False, "option [4] must be in form 4-Z where Z is an integer" else: Z=samp_con.split("-")[1] samp_con="4" if "7" in samp_con: if "-" not in samp_con: print("option [7] must be in form 7-Z where Z is an integer") return False, "option [7] must be in form 7-Z where Z is an integer" else: Z=samp_con.split("-")[1] samp_con="7" ErSampRec,ErSiteRec={},{} # parse data data=open(mag_file,'r') line=data.readline() line=data.readline() line=data.readline() while line !='': parsedLine=line.split() sampleName=parsedLine[0] demagLevel=parsedLine[2] date=parsedLine[3] line=data.readline() line=data.readline() line=data.readline() line=data.readline() parsedLine=line.split() specimenAngleDec=parsedLine[1] specimenAngleInc=parsedLine[2] while parsedLine[0] != 'MEAN' : line=data.readline() parsedLine=line.split() if len(parsedLine) == 0: parsedLine=["Hello"] Mx=parsedLine[1] My=parsedLine[2] Mz=parsedLine[3] line=data.readline() line=data.readline() parsedLine=line.split() splitExp = parsedLine[2].split('A') intensityVolStr=parsedLine[1] + splitExp[0] intensityVol = float(intensityVolStr) # check and see if Prec is too big and messes with the parcing. precisionStr='' if len(parsedLine) == 6: #normal line precisionStr=parsedLine[5][0:-1] else: precisionStr=parsedLine[4][0:-1] precisionPer = float(precisionStr) precision=intensityVol*precisionPer/100 while parsedLine[0] != 'SPEC.' : line=data.readline() parsedLine=line.split() if len(parsedLine) == 0: parsedLine=["Hello"] specimenDec=parsedLine[2] specimenInc=parsedLine[3] line=data.readline() line=data.readline() parsedLine=line.split() geographicDec=parsedLine[1] geographicInc=parsedLine[2] # Add data to various MagIC data tables. er_specimen_name = sampleName if specnum!=0: er_sample_name=er_specimen_name[:specnum] else: er_sample_name=er_specimen_name if int(samp_con) in [1, 2, 3, 4, 5, 7]: er_site_name=pmag.parse_site(er_sample_name,samp_con,Z) else: print("-W- Using unreognized sample convention option: ", samp_con) # else: # if 'er_site_name' in ErSampRec.keys():er_site_name=ErSampRec['er_site_name'] # if 'er_location_name' in ErSampRec.keys():er_location_name=ErSampRec['er_location_name'] # check sample list(SampOuts) to see if sample already exists in list before adding new sample info sampleFlag=0 for sampRec in SampOuts: if sampRec['er_sample_name'] == er_sample_name: sampleFlag=1 break if sampleFlag == 0: ErSampRec['er_sample_name']=er_sample_name ErSampRec['sample_azimuth']=specimenAngleDec sample_dip=str(float(specimenAngleInc)-90.0) #convert to magic orientation ErSampRec['sample_dip']=sample_dip ErSampRec['magic_method_codes']=meth_code ErSampRec['er_location_name']=er_location_name ErSampRec['er_site_name']=er_site_name ErSampRec['er_citation_names']='This study' SampOuts.append(ErSampRec.copy()) MagRec={} MagRec['measurement_description']='Date: '+date MagRec["er_citation_names"]="This study" MagRec['er_location_name']=er_location_name MagRec['er_site_name']=er_site_name MagRec['er_sample_name']=er_sample_name MagRec['magic_software_packages']=version_num MagRec["treatment_temp"]='%8.3e' % (273) # room temp in kelvin MagRec["measurement_temp"]='%8.3e' % (273) # room temp in kelvin MagRec["measurement_flag"]='g' MagRec["measurement_standard"]='u' MagRec["measurement_number"]='1' MagRec["er_specimen_name"]=er_specimen_name MagRec["treatment_ac_field"]='0' if demagLevel == 'NRM': meas_type="LT-NO" elif demagLevel[0] == 'A': meas_type="LT-AF-Z" treat=float(demagLevel[1:]) MagRec["treatment_ac_field"]='%8.3e' %(treat*1e-3) # convert from mT to tesla elif demagLevel[0] == 'T': meas_type="LT-T-Z" treat=float(demagLevel[1:]) MagRec["treatment_temp"]='%8.3e' % (treat+273.) # temp in kelvin else: print("measurement type unknown", demag_level) return False, "measurement type unknown" MagRec["measurement_magn_moment"]=str(intensityVol*volume) # Am^2 MagRec["measurement_magn_volume"]=intensityVolStr # A/m MagRec["measurement_dec"]=specimenDec MagRec["measurement_inc"]=specimenInc MagRec['magic_method_codes']=meas_type MagRecs.append(MagRec.copy()) #read lines till end of record line=data.readline() line=data.readline() line=data.readline() line=data.readline() line=data.readline() # read all the rest of the special characters. Some data files not consistantly formatted. while (len(line) <=3 and line!=''): line=data.readline() #end of data while loop MagOuts=pmag.measurements_methods(MagRecs,noave) pmag.magic_write(samp_file,SampOuts,'er_samples') print("sample orientations put in ",samp_file) pmag.magic_write(meas_file,MagOuts,'magic_measurements') print("results put in ",meas_file) return True, meas_file
NAME jr6_txt_magic.py DESCRIPTION converts JR6 .txt format files to magic_measurements format files SYNTAX jr6_txt_magic.py [command line options] OPTIONS -h: prints the help message and quits. -f FILE: specify input file, or -F FILE: specify output file, default is magic_measurements.txt -Fsa: specify er_samples format file for appending, default is new er_samples.txt (Not working yet) -spc NUM : specify number of characters to designate a specimen, default = 1 -loc LOCNAME : specify location/study name -A: don't average replicate measurements -ncn NCON: specify sample naming convention (6 and 7 not yet implemented) -mcd [SO-MAG,SO-SUN,SO-SIGHT...] supply how these samples were oriented -v NUM : specify the volume of the sample, default 2.5cm^3. Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX [5] site name same as sample [6] site is entered under a separate column NOT CURRENTLY SUPPORTED [7-Z] [XXXX]YYY: XXXX is site designation with Z characters with sample name XXXXYYYY NB: all others you will have to customize your self or e-mail [email protected] for help. INPUT JR6 .txt format file
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/conversion_scripts2/jr6_txt_magic2.py#L7-L307
PmagPy/PmagPy
pmagpy/nlt.py
funk
def funk(p, x, y): """ Function misfit evaluation for best-fit tanh curve f(x[:]) = alpha*tanh(beta*x[:]) alpha = params[0] beta = params[1] funk(params) = sqrt(sum((y[:] - f(x[:]))**2)/len(y[:])) Output is RMS misfit x=xx[0][:] y=xx[1][:]q """ alpha=p[0] beta=p[1] dev=0 for i in range(len(x)): dev=dev+((y[i]-(alpha*math.tanh(beta*x[i])))**2) rms=math.sqrt(old_div(dev,float(len(y)))) return rms
python
def funk(p, x, y): """ Function misfit evaluation for best-fit tanh curve f(x[:]) = alpha*tanh(beta*x[:]) alpha = params[0] beta = params[1] funk(params) = sqrt(sum((y[:] - f(x[:]))**2)/len(y[:])) Output is RMS misfit x=xx[0][:] y=xx[1][:]q """ alpha=p[0] beta=p[1] dev=0 for i in range(len(x)): dev=dev+((y[i]-(alpha*math.tanh(beta*x[i])))**2) rms=math.sqrt(old_div(dev,float(len(y)))) return rms
Function misfit evaluation for best-fit tanh curve f(x[:]) = alpha*tanh(beta*x[:]) alpha = params[0] beta = params[1] funk(params) = sqrt(sum((y[:] - f(x[:]))**2)/len(y[:])) Output is RMS misfit x=xx[0][:] y=xx[1][:]q
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/nlt.py#L15-L32
PmagPy/PmagPy
pmagpy/nlt.py
compare
def compare(a, b): """ Compare items in 2 arrays. Returns sum(abs(a(i)-b(i))) """ s=0 for i in range(len(a)): s=s+abs(a[i]-b[i]) return s
python
def compare(a, b): """ Compare items in 2 arrays. Returns sum(abs(a(i)-b(i))) """ s=0 for i in range(len(a)): s=s+abs(a[i]-b[i]) return s
Compare items in 2 arrays. Returns sum(abs(a(i)-b(i)))
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/nlt.py#L34-L41
PmagPy/PmagPy
pmagpy/nlt.py
TRM
def TRM(f,a,b): """ Calculate TRM using tanh relationship TRM(f)=a*math.tanh(b*f) """ m = float(a) * math.tanh(float(b) * float(f)) return float(m)
python
def TRM(f,a,b): """ Calculate TRM using tanh relationship TRM(f)=a*math.tanh(b*f) """ m = float(a) * math.tanh(float(b) * float(f)) return float(m)
Calculate TRM using tanh relationship TRM(f)=a*math.tanh(b*f)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/nlt.py#L43-L49
PmagPy/PmagPy
pmagpy/nlt.py
TRMinv
def TRMinv(m,a,b): WARN = True # Warn, rather than stop if I encounter a NaN... """ Calculate applied field from TRM using tanh relationship TRMinv(m)=(1/b)*atanh(m/a) """ if float(a)==0: print('ERROR: TRMinv: a==0.') if not WARN : sys.exit() if float(b)==0: print('ERROR: TRMinv: b==0.') if not WARN : sys.exit() x = (old_div(float(m), float(a))) if (1-x)<=0: print('ERROR: TRMinv: (1-x)==0.') return -1 if not WARN : sys.exit() f = (old_div(1.,float(b))) * 0.5 * math.log (old_div((1+x), (1-x))) return float(f)
python
def TRMinv(m,a,b): WARN = True # Warn, rather than stop if I encounter a NaN... """ Calculate applied field from TRM using tanh relationship TRMinv(m)=(1/b)*atanh(m/a) """ if float(a)==0: print('ERROR: TRMinv: a==0.') if not WARN : sys.exit() if float(b)==0: print('ERROR: TRMinv: b==0.') if not WARN : sys.exit() x = (old_div(float(m), float(a))) if (1-x)<=0: print('ERROR: TRMinv: (1-x)==0.') return -1 if not WARN : sys.exit() f = (old_div(1.,float(b))) * 0.5 * math.log (old_div((1+x), (1-x))) return float(f)
Calculate applied field from TRM using tanh relationship TRMinv(m)=(1/b)*atanh(m/a)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/nlt.py#L52-L70
PmagPy/PmagPy
pmagpy/nlt.py
NRM
def NRM(f,a,b,best): WARN = True # Warn, rather than stop if I encounter a NaN... """ Calculate NRM expected lab field and estimated ancient field NRM(blab,best)= (best/blab)*TRM(blab) """ if float(f)==0: print('ERROR: NRM: f==0.') if not WARN : sys.exit() m = (old_div(float(best),float(f))) * TRM(f,a,b) return float(m)
python
def NRM(f,a,b,best): WARN = True # Warn, rather than stop if I encounter a NaN... """ Calculate NRM expected lab field and estimated ancient field NRM(blab,best)= (best/blab)*TRM(blab) """ if float(f)==0: print('ERROR: NRM: f==0.') if not WARN : sys.exit() m = (old_div(float(best),float(f))) * TRM(f,a,b) return float(m)
Calculate NRM expected lab field and estimated ancient field NRM(blab,best)= (best/blab)*TRM(blab)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/nlt.py#L72-L82
PmagPy/PmagPy
programs/plotdi_e.py
main
def main(): """ NAME plotdi_e.py DESCRIPTION plots equal area projection from dec inc data and cones of confidence (Fisher, kent or Bingham or bootstrap). INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX plotdi_e.py [command line options] OPTIONS -h prints help message and quits -i for interactive parameter entry -f FILE, sets input filename on command line -Fish plots unit vector mean direction, alpha95 -Bing plots Principal direction, Bingham confidence ellipse -Kent plots unit vector mean direction, confidence ellipse -Boot E plots unit vector mean direction, bootstrapped confidence ellipse -Boot V plots unit vector mean direction, distribution of bootstrapped means """ dist='F' # default distribution is Fisherian mode=1 title="" EQ={'eq':1} if len(sys.argv) > 0: if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file=input("Enter file name with dec, inc data: ") dist=input("Enter desired distrubution: [Fish]er, [Bing]ham, [Kent] [Boot] [default is Fisher]: ") if dist=="":dist="F" if dist=="Bing":dist="B" if dist=="Kent":dist="K" if dist=="Boot": type=input(" Ellipses or distribution of vectors? [E]/V ") if type=="" or type=="E": dist="BE" else: dist="BE" else: # if '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] else: print('you must specify a file name') print(main.__doc__) sys.exit() if '-Bing' in sys.argv:dist='B' if '-Kent' in sys.argv:dist='K' if '-Boot' in sys.argv: ind=sys.argv.index('-Boot') type=sys.argv[ind+1] if type=='E': dist='BE' elif type=='V': dist='BV' EQ['bdirs']=2 pmagplotlib.plot_init(EQ['bdirs'],5,5) else: print(main.__doc__) sys.exit() pmagplotlib.plot_init(EQ['eq'],5,5) # # get to work f=open(file,'r') data=f.readlines() # DIs= [] # set up list for dec inc data DiRecs=[] pars=[] nDIs,rDIs,npars,rpars=[],[],[],[] mode =1 for line in data: # read in the data from standard input DiRec={} rec=line.split() # split each line on space to get records DIs.append((float(rec[0]),float(rec[1]),1.)) DiRec['dec']=rec[0] DiRec['inc']=rec[1] DiRec['direction_type']='l' DiRecs.append(DiRec) # split into two modes ppars=pmag.doprinc(DIs) # get principal directions for rec in DIs: angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']]) if angle>90.: rDIs.append(rec) else: nDIs.append(rec) if dist=='B': # do on whole dataset title="Bingham confidence ellipse" bpars=pmag.dobingham(DIs) for key in list(bpars.keys()): if key!='n':print(" ",key, '%7.1f'%(bpars[key])) if key=='n':print(" ",key, ' %i'%(bpars[key])) npars.append(bpars['dec']) npars.append(bpars['inc']) npars.append(bpars['Zeta']) npars.append(bpars['Zdec']) npars.append(bpars['Zinc']) npars.append(bpars['Eta']) npars.append(bpars['Edec']) npars.append(bpars['Einc']) if dist=='F': title="Fisher confidence cone" if len(nDIs)>3: fpars=pmag.fisher_mean(nDIs) print("mode ",mode) for key in list(fpars.keys()): if key!='n':print(" ",key, '%7.1f'%(fpars[key])) if key=='n':print(" ",key, ' %i'%(fpars[key])) mode+=1 npars.append(fpars['dec']) npars.append(fpars['inc']) npars.append(fpars['alpha95']) # Beta npars.append(fpars['dec']) isign=abs(fpars['inc']) / fpars['inc'] npars.append(fpars['inc']-isign*90.) #Beta inc npars.append(fpars['alpha95']) # gamma npars.append(fpars['dec']+90.) # Beta dec npars.append(0.) #Beta inc if len(rDIs)>3: fpars=pmag.fisher_mean(rDIs) print("mode ",mode) for key in list(fpars.keys()): if key!='n':print(" ",key, '%7.1f'%(fpars[key])) if key=='n':print(" ",key, ' %i'%(fpars[key])) mode+=1 rpars.append(fpars['dec']) rpars.append(fpars['inc']) rpars.append(fpars['alpha95']) # Beta rpars.append(fpars['dec']) isign=abs(fpars['inc']) / fpars['inc'] rpars.append(fpars['inc']-isign*90.) #Beta inc rpars.append(fpars['alpha95']) # gamma rpars.append(fpars['dec']+90.) # Beta dec rpars.append(0.) #Beta inc if dist=='K': title="Kent confidence ellipse" if len(nDIs)>3: kpars=pmag.dokent(nDIs,len(nDIs)) print("mode ",mode) for key in list(kpars.keys()): if key!='n':print(" ",key, '%7.1f'%(kpars[key])) if key=='n':print(" ",key, ' %i'%(kpars[key])) mode+=1 npars.append(kpars['dec']) npars.append(kpars['inc']) npars.append(kpars['Zeta']) npars.append(kpars['Zdec']) npars.append(kpars['Zinc']) npars.append(kpars['Eta']) npars.append(kpars['Edec']) npars.append(kpars['Einc']) if len(rDIs)>3: kpars=pmag.dokent(rDIs,len(rDIs)) print("mode ",mode) for key in list(kpars.keys()): if key!='n':print(" ",key, '%7.1f'%(kpars[key])) if key=='n':print(" ",key, ' %i'%(kpars[key])) mode+=1 rpars.append(kpars['dec']) rpars.append(kpars['inc']) rpars.append(kpars['Zeta']) rpars.append(kpars['Zdec']) rpars.append(kpars['Zinc']) rpars.append(kpars['Eta']) rpars.append(kpars['Edec']) rpars.append(kpars['Einc']) else: # assume bootstrap if dist=='BE': if len(nDIs)>5: BnDIs=pmag.di_boot(nDIs) Bkpars=pmag.dokent(BnDIs,1.) print("mode ",mode) for key in list(Bkpars.keys()): if key!='n':print(" ",key, '%7.1f'%(Bkpars[key])) if key=='n':print(" ",key, ' %i'%(Bkpars[key])) mode+=1 npars.append(Bkpars['dec']) npars.append(Bkpars['inc']) npars.append(Bkpars['Zeta']) npars.append(Bkpars['Zdec']) npars.append(Bkpars['Zinc']) npars.append(Bkpars['Eta']) npars.append(Bkpars['Edec']) npars.append(Bkpars['Einc']) if len(rDIs)>5: BrDIs=pmag.di_boot(rDIs) Bkpars=pmag.dokent(BrDIs,1.) print("mode ",mode) for key in list(Bkpars.keys()): if key!='n':print(" ",key, '%7.1f'%(Bkpars[key])) if key=='n':print(" ",key, ' %i'%(Bkpars[key])) mode+=1 rpars.append(Bkpars['dec']) rpars.append(Bkpars['inc']) rpars.append(Bkpars['Zeta']) rpars.append(Bkpars['Zdec']) rpars.append(Bkpars['Zinc']) rpars.append(Bkpars['Eta']) rpars.append(Bkpars['Edec']) rpars.append(Bkpars['Einc']) title="Bootstrapped confidence ellipse" elif dist=='BV': if len(nDIs)>5: pmagplotlib.plot_eq(EQ['eq'],nDIs,'Data') BnDIs=pmag.di_boot(nDIs) pmagplotlib.plot_eq(EQ['bdirs'],BnDIs,'Bootstrapped Eigenvectors') if len(rDIs)>5: BrDIs=pmag.di_boot(rDIs) if len(nDIs)>5: # plot on existing plots pmagplotlib.plot_di(EQ['eq'],rDIs) pmagplotlib.plot_di(EQ['bdirs'],BrDIs) else: pmagplotlib.plot_eq(EQ['eq'],rDIs,'Data') pmagplotlib.plot_eq(EQ['bdirs'],BrDIs,'Bootstrapped Eigenvectors') pmagplotlib.draw_figs(EQ) ans=input('s[a]ve, [q]uit ') if ans=='q':sys.exit() if ans=='a': files={} for key in list(EQ.keys()): files[key]='BE_'+key+'.svg' pmagplotlib.save_plots(EQ,files) sys.exit() if len(nDIs)>5: pmagplotlib.plot_conf(EQ['eq'],title,DiRecs,npars,1) if len(rDIs)>5 and dist!='B': pmagplotlib.plot_conf(EQ['eq'],title,[],rpars,0) elif len(rDIs)>5 and dist!='B': pmagplotlib.plot_conf(EQ['eq'],title,DiRecs,rpars,1) pmagplotlib.draw_figs(EQ) ans=input('s[a]ve, [q]uit ') if ans=='q':sys.exit() if ans=='a': files={} for key in list(EQ.keys()): files[key]=key+'.svg' pmagplotlib.save_plots(EQ,files)
python
def main(): """ NAME plotdi_e.py DESCRIPTION plots equal area projection from dec inc data and cones of confidence (Fisher, kent or Bingham or bootstrap). INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX plotdi_e.py [command line options] OPTIONS -h prints help message and quits -i for interactive parameter entry -f FILE, sets input filename on command line -Fish plots unit vector mean direction, alpha95 -Bing plots Principal direction, Bingham confidence ellipse -Kent plots unit vector mean direction, confidence ellipse -Boot E plots unit vector mean direction, bootstrapped confidence ellipse -Boot V plots unit vector mean direction, distribution of bootstrapped means """ dist='F' # default distribution is Fisherian mode=1 title="" EQ={'eq':1} if len(sys.argv) > 0: if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file=input("Enter file name with dec, inc data: ") dist=input("Enter desired distrubution: [Fish]er, [Bing]ham, [Kent] [Boot] [default is Fisher]: ") if dist=="":dist="F" if dist=="Bing":dist="B" if dist=="Kent":dist="K" if dist=="Boot": type=input(" Ellipses or distribution of vectors? [E]/V ") if type=="" or type=="E": dist="BE" else: dist="BE" else: # if '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] else: print('you must specify a file name') print(main.__doc__) sys.exit() if '-Bing' in sys.argv:dist='B' if '-Kent' in sys.argv:dist='K' if '-Boot' in sys.argv: ind=sys.argv.index('-Boot') type=sys.argv[ind+1] if type=='E': dist='BE' elif type=='V': dist='BV' EQ['bdirs']=2 pmagplotlib.plot_init(EQ['bdirs'],5,5) else: print(main.__doc__) sys.exit() pmagplotlib.plot_init(EQ['eq'],5,5) # # get to work f=open(file,'r') data=f.readlines() # DIs= [] # set up list for dec inc data DiRecs=[] pars=[] nDIs,rDIs,npars,rpars=[],[],[],[] mode =1 for line in data: # read in the data from standard input DiRec={} rec=line.split() # split each line on space to get records DIs.append((float(rec[0]),float(rec[1]),1.)) DiRec['dec']=rec[0] DiRec['inc']=rec[1] DiRec['direction_type']='l' DiRecs.append(DiRec) # split into two modes ppars=pmag.doprinc(DIs) # get principal directions for rec in DIs: angle=pmag.angle([rec[0],rec[1]],[ppars['dec'],ppars['inc']]) if angle>90.: rDIs.append(rec) else: nDIs.append(rec) if dist=='B': # do on whole dataset title="Bingham confidence ellipse" bpars=pmag.dobingham(DIs) for key in list(bpars.keys()): if key!='n':print(" ",key, '%7.1f'%(bpars[key])) if key=='n':print(" ",key, ' %i'%(bpars[key])) npars.append(bpars['dec']) npars.append(bpars['inc']) npars.append(bpars['Zeta']) npars.append(bpars['Zdec']) npars.append(bpars['Zinc']) npars.append(bpars['Eta']) npars.append(bpars['Edec']) npars.append(bpars['Einc']) if dist=='F': title="Fisher confidence cone" if len(nDIs)>3: fpars=pmag.fisher_mean(nDIs) print("mode ",mode) for key in list(fpars.keys()): if key!='n':print(" ",key, '%7.1f'%(fpars[key])) if key=='n':print(" ",key, ' %i'%(fpars[key])) mode+=1 npars.append(fpars['dec']) npars.append(fpars['inc']) npars.append(fpars['alpha95']) # Beta npars.append(fpars['dec']) isign=abs(fpars['inc']) / fpars['inc'] npars.append(fpars['inc']-isign*90.) #Beta inc npars.append(fpars['alpha95']) # gamma npars.append(fpars['dec']+90.) # Beta dec npars.append(0.) #Beta inc if len(rDIs)>3: fpars=pmag.fisher_mean(rDIs) print("mode ",mode) for key in list(fpars.keys()): if key!='n':print(" ",key, '%7.1f'%(fpars[key])) if key=='n':print(" ",key, ' %i'%(fpars[key])) mode+=1 rpars.append(fpars['dec']) rpars.append(fpars['inc']) rpars.append(fpars['alpha95']) # Beta rpars.append(fpars['dec']) isign=abs(fpars['inc']) / fpars['inc'] rpars.append(fpars['inc']-isign*90.) #Beta inc rpars.append(fpars['alpha95']) # gamma rpars.append(fpars['dec']+90.) # Beta dec rpars.append(0.) #Beta inc if dist=='K': title="Kent confidence ellipse" if len(nDIs)>3: kpars=pmag.dokent(nDIs,len(nDIs)) print("mode ",mode) for key in list(kpars.keys()): if key!='n':print(" ",key, '%7.1f'%(kpars[key])) if key=='n':print(" ",key, ' %i'%(kpars[key])) mode+=1 npars.append(kpars['dec']) npars.append(kpars['inc']) npars.append(kpars['Zeta']) npars.append(kpars['Zdec']) npars.append(kpars['Zinc']) npars.append(kpars['Eta']) npars.append(kpars['Edec']) npars.append(kpars['Einc']) if len(rDIs)>3: kpars=pmag.dokent(rDIs,len(rDIs)) print("mode ",mode) for key in list(kpars.keys()): if key!='n':print(" ",key, '%7.1f'%(kpars[key])) if key=='n':print(" ",key, ' %i'%(kpars[key])) mode+=1 rpars.append(kpars['dec']) rpars.append(kpars['inc']) rpars.append(kpars['Zeta']) rpars.append(kpars['Zdec']) rpars.append(kpars['Zinc']) rpars.append(kpars['Eta']) rpars.append(kpars['Edec']) rpars.append(kpars['Einc']) else: # assume bootstrap if dist=='BE': if len(nDIs)>5: BnDIs=pmag.di_boot(nDIs) Bkpars=pmag.dokent(BnDIs,1.) print("mode ",mode) for key in list(Bkpars.keys()): if key!='n':print(" ",key, '%7.1f'%(Bkpars[key])) if key=='n':print(" ",key, ' %i'%(Bkpars[key])) mode+=1 npars.append(Bkpars['dec']) npars.append(Bkpars['inc']) npars.append(Bkpars['Zeta']) npars.append(Bkpars['Zdec']) npars.append(Bkpars['Zinc']) npars.append(Bkpars['Eta']) npars.append(Bkpars['Edec']) npars.append(Bkpars['Einc']) if len(rDIs)>5: BrDIs=pmag.di_boot(rDIs) Bkpars=pmag.dokent(BrDIs,1.) print("mode ",mode) for key in list(Bkpars.keys()): if key!='n':print(" ",key, '%7.1f'%(Bkpars[key])) if key=='n':print(" ",key, ' %i'%(Bkpars[key])) mode+=1 rpars.append(Bkpars['dec']) rpars.append(Bkpars['inc']) rpars.append(Bkpars['Zeta']) rpars.append(Bkpars['Zdec']) rpars.append(Bkpars['Zinc']) rpars.append(Bkpars['Eta']) rpars.append(Bkpars['Edec']) rpars.append(Bkpars['Einc']) title="Bootstrapped confidence ellipse" elif dist=='BV': if len(nDIs)>5: pmagplotlib.plot_eq(EQ['eq'],nDIs,'Data') BnDIs=pmag.di_boot(nDIs) pmagplotlib.plot_eq(EQ['bdirs'],BnDIs,'Bootstrapped Eigenvectors') if len(rDIs)>5: BrDIs=pmag.di_boot(rDIs) if len(nDIs)>5: # plot on existing plots pmagplotlib.plot_di(EQ['eq'],rDIs) pmagplotlib.plot_di(EQ['bdirs'],BrDIs) else: pmagplotlib.plot_eq(EQ['eq'],rDIs,'Data') pmagplotlib.plot_eq(EQ['bdirs'],BrDIs,'Bootstrapped Eigenvectors') pmagplotlib.draw_figs(EQ) ans=input('s[a]ve, [q]uit ') if ans=='q':sys.exit() if ans=='a': files={} for key in list(EQ.keys()): files[key]='BE_'+key+'.svg' pmagplotlib.save_plots(EQ,files) sys.exit() if len(nDIs)>5: pmagplotlib.plot_conf(EQ['eq'],title,DiRecs,npars,1) if len(rDIs)>5 and dist!='B': pmagplotlib.plot_conf(EQ['eq'],title,[],rpars,0) elif len(rDIs)>5 and dist!='B': pmagplotlib.plot_conf(EQ['eq'],title,DiRecs,rpars,1) pmagplotlib.draw_figs(EQ) ans=input('s[a]ve, [q]uit ') if ans=='q':sys.exit() if ans=='a': files={} for key in list(EQ.keys()): files[key]=key+'.svg' pmagplotlib.save_plots(EQ,files)
NAME plotdi_e.py DESCRIPTION plots equal area projection from dec inc data and cones of confidence (Fisher, kent or Bingham or bootstrap). INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX plotdi_e.py [command line options] OPTIONS -h prints help message and quits -i for interactive parameter entry -f FILE, sets input filename on command line -Fish plots unit vector mean direction, alpha95 -Bing plots Principal direction, Bingham confidence ellipse -Kent plots unit vector mean direction, confidence ellipse -Boot E plots unit vector mean direction, bootstrapped confidence ellipse -Boot V plots unit vector mean direction, distribution of bootstrapped means
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/plotdi_e.py#L11-L257
PmagPy/PmagPy
dialogs/demag_interpretation_editor.py
InterpretationEditorFrame.init_UI
def init_UI(self): """ Builds User Interface for the interpretation Editor """ #set fonts FONT_WEIGHT=1 if sys.platform.startswith('win'): FONT_WEIGHT=-1 font1 = wx.Font(9+FONT_WEIGHT, wx.SWISS, wx.NORMAL, wx.NORMAL, False, self.font_type) font2 = wx.Font(12+FONT_WEIGHT, wx.SWISS, wx.NORMAL, wx.NORMAL, False, self.font_type) #if you're on mac do some funny stuff to make it look okay is_mac = False if sys.platform.startswith("darwin"): is_mac = True self.search_bar = wx.SearchCtrl(self.panel, size=(350*self.GUI_RESOLUTION,25) ,style=wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB | wx.TE_NOHIDESEL) self.Bind(wx.EVT_TEXT_ENTER, self.on_enter_search_bar,self.search_bar) self.Bind(wx.EVT_SEARCHCTRL_SEARCH_BTN, self.on_enter_search_bar,self.search_bar) self.search_bar.SetHelpText(dieh.search_help) # self.Bind(wx.EVT_TEXT, self.on_complete_search_bar,self.search_bar) #build logger self.logger = wx.ListCtrl(self.panel, -1, size=(100*self.GUI_RESOLUTION,475*self.GUI_RESOLUTION),style=wx.LC_REPORT) self.logger.SetFont(font1) self.logger.InsertColumn(0, 'specimen',width=75*self.GUI_RESOLUTION) self.logger.InsertColumn(1, 'fit name',width=65*self.GUI_RESOLUTION) self.logger.InsertColumn(2, 'max',width=55*self.GUI_RESOLUTION) self.logger.InsertColumn(3, 'min',width=55*self.GUI_RESOLUTION) self.logger.InsertColumn(4, 'n',width=25*self.GUI_RESOLUTION) self.logger.InsertColumn(5, 'fit type',width=60*self.GUI_RESOLUTION) self.logger.InsertColumn(6, 'dec',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(7, 'inc',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(8, 'mad',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(9, 'dang',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(10, 'a95',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(11, 'K',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(12, 'R',width=45*self.GUI_RESOLUTION) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnClick_listctrl, self.logger) self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK,self.OnRightClickListctrl,self.logger) self.logger.SetHelpText(dieh.logger_help) #set fit attributes boxsizers self.display_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY, "display options"), wx.HORIZONTAL) self.name_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY, "fit name/color"), wx.VERTICAL) self.bounds_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY, "fit bounds"), wx.VERTICAL) self.buttons_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY), wx.VERTICAL) #logger display selection box UPPER_LEVEL = self.parent.level_box.GetValue() if UPPER_LEVEL=='sample': name_choices = self.parent.samples if UPPER_LEVEL=='site': name_choices = self.parent.sites if UPPER_LEVEL=='location': name_choices = self.parent.locations if UPPER_LEVEL=='study': name_choices = ['this study'] self.level_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=UPPER_LEVEL, choices=['sample','site','location','study'], style=wx.CB_DROPDOWN|wx.TE_READONLY) self.Bind(wx.EVT_COMBOBOX, self.on_select_high_level,self.level_box) self.level_box.SetHelpText(dieh.level_box_help) self.level_names = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=self.parent.level_names.GetValue(), choices=name_choices, style=wx.CB_DROPDOWN|wx.TE_READONLY) self.Bind(wx.EVT_COMBOBOX, self.on_select_level_name,self.level_names) self.level_names.SetHelpText(dieh.level_names_help) #mean type and plot display boxes self.mean_type_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=self.parent.mean_type_box.GetValue(), choices=['Fisher','Fisher by polarity','None'], style=wx.CB_DROPDOWN|wx.TE_READONLY, name="high_type") self.Bind(wx.EVT_COMBOBOX, self.on_select_mean_type_box,self.mean_type_box) self.mean_type_box.SetHelpText(dieh.mean_type_help) self.mean_fit_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=self.parent.mean_fit, choices=(['None','All'] + self.parent.fit_list), style=wx.CB_DROPDOWN|wx.TE_READONLY, name="high_type") self.Bind(wx.EVT_COMBOBOX, self.on_select_mean_fit_box,self.mean_fit_box) self.mean_fit_box.SetHelpText(dieh.mean_fit_help) #show box if UPPER_LEVEL == "study" or UPPER_LEVEL == "location": show_box_choices = ['specimens','samples','sites'] if UPPER_LEVEL == "site": show_box_choices = ['specimens','samples'] if UPPER_LEVEL == "sample": show_box_choices = ['specimens'] self.show_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value='specimens', choices=show_box_choices, style=wx.CB_DROPDOWN|wx.TE_READONLY,name="high_elements") self.Bind(wx.EVT_COMBOBOX, self.on_select_show_box,self.show_box) self.show_box.SetHelpText(dieh.show_help) #coordinates box self.coordinates_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), choices=self.parent.coordinate_list, value=self.parent.coordinates_box.GetValue(), style=wx.CB_DROPDOWN|wx.TE_READONLY, name="coordinates") self.Bind(wx.EVT_COMBOBOX, self.on_select_coordinates,self.coordinates_box) self.coordinates_box.SetHelpText(dieh.coordinates_box_help) #bounds select boxes self.tmin_box = wx.ComboBox(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), choices=[''] + self.parent.T_list, style=wx.CB_DROPDOWN|wx.TE_READONLY, name="lower bound") self.tmin_box.SetHelpText(dieh.tmin_box_help) self.tmax_box = wx.ComboBox(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), choices=[''] + self.parent.T_list, style=wx.CB_DROPDOWN|wx.TE_READONLY, name="upper bound") self.tmax_box.SetHelpText(dieh.tmax_box_help) #color box self.color_dict = self.parent.color_dict self.color_box = wx.ComboBox(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), choices=[''] + sorted(self.color_dict.keys()), style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER, name="color") self.Bind(wx.EVT_TEXT_ENTER, self.add_new_color, self.color_box) self.color_box.SetHelpText(dieh.color_box_help) #name box self.name_box = wx.TextCtrl(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), name="name") self.name_box.SetHelpText(dieh.name_box_help) #more mac stuff h_size_buttons,button_spacing = 25,5.5 if is_mac: h_size_buttons,button_spacing = 18,0. #buttons self.add_all_button = wx.Button(self.panel, id=-1, label='add new fit to all specimens',size=(160*self.GUI_RESOLUTION,h_size_buttons)) self.add_all_button.SetFont(font1) self.Bind(wx.EVT_BUTTON, self.add_fit_to_all, self.add_all_button) self.add_all_button.SetHelpText(dieh.add_all_help) self.add_fit_button = wx.Button(self.panel, id=-1, label='add fit to highlighted specimens',size=(160*self.GUI_RESOLUTION,h_size_buttons)) self.add_fit_button.SetFont(font1) self.Bind(wx.EVT_BUTTON, self.add_highlighted_fits, self.add_fit_button) self.add_fit_button.SetHelpText(dieh.add_fit_btn_help) self.delete_fit_button = wx.Button(self.panel, id=-1, label='delete highlighted fits',size=(160*self.GUI_RESOLUTION,h_size_buttons)) self.delete_fit_button.SetFont(font1) self.Bind(wx.EVT_BUTTON, self.delete_highlighted_fits, self.delete_fit_button) self.delete_fit_button.SetHelpText(dieh.delete_fit_btn_help) self.apply_changes_button = wx.Button(self.panel, id=-1, label='apply changes to highlighted fits',size=(160*self.GUI_RESOLUTION,h_size_buttons)) self.apply_changes_button.SetFont(font1) self.Bind(wx.EVT_BUTTON, self.apply_changes, self.apply_changes_button) self.apply_changes_button.SetHelpText(dieh.apply_changes_help) #windows display_window_0 = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) display_window_1 = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) display_window_2 = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) name_window = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) bounds_window = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) buttons1_window = wx.GridSizer(4, 1, 5*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) display_window_0.AddMany( [(self.coordinates_box, wx.ALIGN_LEFT), (self.show_box, wx.ALIGN_LEFT)] ) display_window_1.AddMany( [(self.level_box, wx.ALIGN_LEFT), (self.level_names, wx.ALIGN_LEFT)] ) display_window_2.AddMany( [(self.mean_type_box, wx.ALIGN_LEFT), (self.mean_fit_box, wx.ALIGN_LEFT)] ) name_window.AddMany( [(self.name_box, wx.ALIGN_LEFT), (self.color_box, wx.ALIGN_LEFT)] ) bounds_window.AddMany( [(self.tmin_box, wx.ALIGN_LEFT), (self.tmax_box, wx.ALIGN_LEFT)] ) buttons1_window.AddMany( [(self.add_fit_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0), (self.add_all_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0), (self.delete_fit_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0), (self.apply_changes_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0)]) self.display_sizer.Add(display_window_0, 1, wx.TOP|wx.EXPAND, 8) self.display_sizer.Add(display_window_1, 1, wx.TOP | wx.LEFT|wx.EXPAND, 8) self.display_sizer.Add(display_window_2, 1, wx.TOP | wx.LEFT|wx.EXPAND, 8) self.name_sizer.Add(name_window, 1, wx.TOP, 5.5) self.bounds_sizer.Add(bounds_window, 1, wx.TOP, 5.5) self.buttons_sizer.Add(buttons1_window, 1, wx.TOP, 0) #duplicate high levels plot self.fig = Figure((2.5*self.GUI_RESOLUTION, 2.5*self.GUI_RESOLUTION), dpi=100) self.canvas = FigCanvas(self.panel, -1, self.fig, ) self.toolbar = NavigationToolbar(self.canvas) self.toolbar.Hide() self.toolbar.zoom() self.high_EA_setting = "Zoom" self.canvas.Bind(wx.EVT_LEFT_DCLICK,self.on_equalarea_high_select) self.canvas.Bind(wx.EVT_MOTION,self.on_change_high_mouse_cursor) self.canvas.Bind(wx.EVT_MIDDLE_DOWN,self.home_high_equalarea) self.canvas.Bind(wx.EVT_RIGHT_DOWN,self.pan_zoom_high_equalarea) self.canvas.SetHelpText(dieh.eqarea_help) self.eqarea = self.fig.add_subplot(111) draw_net(self.eqarea) #Higher Level Statistics Box self.stats_sizer = wx.StaticBoxSizer( wx.StaticBox( self.panel, wx.ID_ANY,"mean statistics" ), wx.VERTICAL) for parameter in ['mean_type','dec','inc','alpha95','K','R','n_lines','n_planes']: COMMAND="self.%s_window=wx.TextCtrl(self.panel,style=wx.TE_CENTER|wx.TE_READONLY,size=(100*self.GUI_RESOLUTION,25))"%parameter exec(COMMAND) COMMAND="self.%s_window.SetBackgroundColour(wx.WHITE)"%parameter exec(COMMAND) COMMAND="self.%s_window.SetFont(font2)"%parameter exec(COMMAND) COMMAND="self.%s_outer_window = wx.GridSizer(1,2,5*self.GUI_RESOLUTION,15*self.GUI_RESOLUTION)"%parameter exec(COMMAND) COMMAND="""self.%s_outer_window.AddMany([ (wx.StaticText(self.panel,label='%s',style=wx.TE_CENTER),wx.EXPAND), (self.%s_window, wx.EXPAND)])"""%(parameter,parameter,parameter) exec(COMMAND) COMMAND="self.stats_sizer.Add(self.%s_outer_window, 1, wx.ALIGN_LEFT|wx.EXPAND, 0)"%parameter exec(COMMAND) self.switch_stats_button = wx.SpinButton(self.panel, id=wx.ID_ANY, style=wx.SP_HORIZONTAL|wx.SP_ARROW_KEYS|wx.SP_WRAP, name="change stats") self.Bind(wx.EVT_SPIN, self.on_select_stats_button,self.switch_stats_button) self.switch_stats_button.SetHelpText(dieh.switch_stats_btn_help) #construct panel hbox0 = wx.BoxSizer(wx.HORIZONTAL) hbox0.Add(self.name_sizer,flag=wx.ALIGN_TOP|wx.EXPAND,border=8) hbox0.Add(self.bounds_sizer,flag=wx.ALIGN_TOP|wx.EXPAND,border=8) vbox0 = wx.BoxSizer(wx.VERTICAL) vbox0.Add(hbox0,flag=wx.ALIGN_TOP,border=8) vbox0.Add(self.buttons_sizer,flag=wx.ALIGN_TOP,border=8) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox1.Add(vbox0,flag=wx.ALIGN_TOP,border=8) hbox1.Add(self.stats_sizer,flag=wx.ALIGN_TOP,border=8) hbox1.Add(self.switch_stats_button,flag=wx.ALIGN_TOP|wx.EXPAND,border=8) vbox1 = wx.BoxSizer(wx.VERTICAL) vbox1.Add(self.display_sizer,flag=wx.ALIGN_TOP,border=8) vbox1.Add(hbox1,flag=wx.ALIGN_TOP,border=8) vbox1.Add(self.canvas,proportion=1,flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,border=8) vbox2 = wx.BoxSizer(wx.VERTICAL) vbox2.Add(self.search_bar,proportion=.5,flag=wx.ALIGN_LEFT | wx.ALIGN_BOTTOM | wx.EXPAND, border=8) vbox2.Add(self.logger,proportion=1,flag=wx.ALIGN_LEFT|wx.EXPAND,border=8) hbox2 = wx.BoxSizer(wx.HORIZONTAL) hbox2.Add(vbox2,proportion=1,flag=wx.ALIGN_LEFT|wx.EXPAND) hbox2.Add(vbox1,flag=wx.ALIGN_TOP|wx.EXPAND) self.panel.SetSizerAndFit(hbox2) hbox2.Fit(self)
python
def init_UI(self): """ Builds User Interface for the interpretation Editor """ #set fonts FONT_WEIGHT=1 if sys.platform.startswith('win'): FONT_WEIGHT=-1 font1 = wx.Font(9+FONT_WEIGHT, wx.SWISS, wx.NORMAL, wx.NORMAL, False, self.font_type) font2 = wx.Font(12+FONT_WEIGHT, wx.SWISS, wx.NORMAL, wx.NORMAL, False, self.font_type) #if you're on mac do some funny stuff to make it look okay is_mac = False if sys.platform.startswith("darwin"): is_mac = True self.search_bar = wx.SearchCtrl(self.panel, size=(350*self.GUI_RESOLUTION,25) ,style=wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB | wx.TE_NOHIDESEL) self.Bind(wx.EVT_TEXT_ENTER, self.on_enter_search_bar,self.search_bar) self.Bind(wx.EVT_SEARCHCTRL_SEARCH_BTN, self.on_enter_search_bar,self.search_bar) self.search_bar.SetHelpText(dieh.search_help) # self.Bind(wx.EVT_TEXT, self.on_complete_search_bar,self.search_bar) #build logger self.logger = wx.ListCtrl(self.panel, -1, size=(100*self.GUI_RESOLUTION,475*self.GUI_RESOLUTION),style=wx.LC_REPORT) self.logger.SetFont(font1) self.logger.InsertColumn(0, 'specimen',width=75*self.GUI_RESOLUTION) self.logger.InsertColumn(1, 'fit name',width=65*self.GUI_RESOLUTION) self.logger.InsertColumn(2, 'max',width=55*self.GUI_RESOLUTION) self.logger.InsertColumn(3, 'min',width=55*self.GUI_RESOLUTION) self.logger.InsertColumn(4, 'n',width=25*self.GUI_RESOLUTION) self.logger.InsertColumn(5, 'fit type',width=60*self.GUI_RESOLUTION) self.logger.InsertColumn(6, 'dec',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(7, 'inc',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(8, 'mad',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(9, 'dang',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(10, 'a95',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(11, 'K',width=45*self.GUI_RESOLUTION) self.logger.InsertColumn(12, 'R',width=45*self.GUI_RESOLUTION) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnClick_listctrl, self.logger) self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK,self.OnRightClickListctrl,self.logger) self.logger.SetHelpText(dieh.logger_help) #set fit attributes boxsizers self.display_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY, "display options"), wx.HORIZONTAL) self.name_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY, "fit name/color"), wx.VERTICAL) self.bounds_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY, "fit bounds"), wx.VERTICAL) self.buttons_sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, wx.ID_ANY), wx.VERTICAL) #logger display selection box UPPER_LEVEL = self.parent.level_box.GetValue() if UPPER_LEVEL=='sample': name_choices = self.parent.samples if UPPER_LEVEL=='site': name_choices = self.parent.sites if UPPER_LEVEL=='location': name_choices = self.parent.locations if UPPER_LEVEL=='study': name_choices = ['this study'] self.level_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=UPPER_LEVEL, choices=['sample','site','location','study'], style=wx.CB_DROPDOWN|wx.TE_READONLY) self.Bind(wx.EVT_COMBOBOX, self.on_select_high_level,self.level_box) self.level_box.SetHelpText(dieh.level_box_help) self.level_names = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=self.parent.level_names.GetValue(), choices=name_choices, style=wx.CB_DROPDOWN|wx.TE_READONLY) self.Bind(wx.EVT_COMBOBOX, self.on_select_level_name,self.level_names) self.level_names.SetHelpText(dieh.level_names_help) #mean type and plot display boxes self.mean_type_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=self.parent.mean_type_box.GetValue(), choices=['Fisher','Fisher by polarity','None'], style=wx.CB_DROPDOWN|wx.TE_READONLY, name="high_type") self.Bind(wx.EVT_COMBOBOX, self.on_select_mean_type_box,self.mean_type_box) self.mean_type_box.SetHelpText(dieh.mean_type_help) self.mean_fit_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value=self.parent.mean_fit, choices=(['None','All'] + self.parent.fit_list), style=wx.CB_DROPDOWN|wx.TE_READONLY, name="high_type") self.Bind(wx.EVT_COMBOBOX, self.on_select_mean_fit_box,self.mean_fit_box) self.mean_fit_box.SetHelpText(dieh.mean_fit_help) #show box if UPPER_LEVEL == "study" or UPPER_LEVEL == "location": show_box_choices = ['specimens','samples','sites'] if UPPER_LEVEL == "site": show_box_choices = ['specimens','samples'] if UPPER_LEVEL == "sample": show_box_choices = ['specimens'] self.show_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), value='specimens', choices=show_box_choices, style=wx.CB_DROPDOWN|wx.TE_READONLY,name="high_elements") self.Bind(wx.EVT_COMBOBOX, self.on_select_show_box,self.show_box) self.show_box.SetHelpText(dieh.show_help) #coordinates box self.coordinates_box = wx.ComboBox(self.panel, -1, size=(110*self.GUI_RESOLUTION, 25), choices=self.parent.coordinate_list, value=self.parent.coordinates_box.GetValue(), style=wx.CB_DROPDOWN|wx.TE_READONLY, name="coordinates") self.Bind(wx.EVT_COMBOBOX, self.on_select_coordinates,self.coordinates_box) self.coordinates_box.SetHelpText(dieh.coordinates_box_help) #bounds select boxes self.tmin_box = wx.ComboBox(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), choices=[''] + self.parent.T_list, style=wx.CB_DROPDOWN|wx.TE_READONLY, name="lower bound") self.tmin_box.SetHelpText(dieh.tmin_box_help) self.tmax_box = wx.ComboBox(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), choices=[''] + self.parent.T_list, style=wx.CB_DROPDOWN|wx.TE_READONLY, name="upper bound") self.tmax_box.SetHelpText(dieh.tmax_box_help) #color box self.color_dict = self.parent.color_dict self.color_box = wx.ComboBox(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), choices=[''] + sorted(self.color_dict.keys()), style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER, name="color") self.Bind(wx.EVT_TEXT_ENTER, self.add_new_color, self.color_box) self.color_box.SetHelpText(dieh.color_box_help) #name box self.name_box = wx.TextCtrl(self.panel, -1, size=(80*self.GUI_RESOLUTION, 25), name="name") self.name_box.SetHelpText(dieh.name_box_help) #more mac stuff h_size_buttons,button_spacing = 25,5.5 if is_mac: h_size_buttons,button_spacing = 18,0. #buttons self.add_all_button = wx.Button(self.panel, id=-1, label='add new fit to all specimens',size=(160*self.GUI_RESOLUTION,h_size_buttons)) self.add_all_button.SetFont(font1) self.Bind(wx.EVT_BUTTON, self.add_fit_to_all, self.add_all_button) self.add_all_button.SetHelpText(dieh.add_all_help) self.add_fit_button = wx.Button(self.panel, id=-1, label='add fit to highlighted specimens',size=(160*self.GUI_RESOLUTION,h_size_buttons)) self.add_fit_button.SetFont(font1) self.Bind(wx.EVT_BUTTON, self.add_highlighted_fits, self.add_fit_button) self.add_fit_button.SetHelpText(dieh.add_fit_btn_help) self.delete_fit_button = wx.Button(self.panel, id=-1, label='delete highlighted fits',size=(160*self.GUI_RESOLUTION,h_size_buttons)) self.delete_fit_button.SetFont(font1) self.Bind(wx.EVT_BUTTON, self.delete_highlighted_fits, self.delete_fit_button) self.delete_fit_button.SetHelpText(dieh.delete_fit_btn_help) self.apply_changes_button = wx.Button(self.panel, id=-1, label='apply changes to highlighted fits',size=(160*self.GUI_RESOLUTION,h_size_buttons)) self.apply_changes_button.SetFont(font1) self.Bind(wx.EVT_BUTTON, self.apply_changes, self.apply_changes_button) self.apply_changes_button.SetHelpText(dieh.apply_changes_help) #windows display_window_0 = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) display_window_1 = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) display_window_2 = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) name_window = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) bounds_window = wx.GridSizer(2, 1, 10*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) buttons1_window = wx.GridSizer(4, 1, 5*self.GUI_RESOLUTION, 19*self.GUI_RESOLUTION) display_window_0.AddMany( [(self.coordinates_box, wx.ALIGN_LEFT), (self.show_box, wx.ALIGN_LEFT)] ) display_window_1.AddMany( [(self.level_box, wx.ALIGN_LEFT), (self.level_names, wx.ALIGN_LEFT)] ) display_window_2.AddMany( [(self.mean_type_box, wx.ALIGN_LEFT), (self.mean_fit_box, wx.ALIGN_LEFT)] ) name_window.AddMany( [(self.name_box, wx.ALIGN_LEFT), (self.color_box, wx.ALIGN_LEFT)] ) bounds_window.AddMany( [(self.tmin_box, wx.ALIGN_LEFT), (self.tmax_box, wx.ALIGN_LEFT)] ) buttons1_window.AddMany( [(self.add_fit_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0), (self.add_all_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0), (self.delete_fit_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0), (self.apply_changes_button, wx.ALL|wx.ALIGN_CENTER|wx.SHAPED, 0)]) self.display_sizer.Add(display_window_0, 1, wx.TOP|wx.EXPAND, 8) self.display_sizer.Add(display_window_1, 1, wx.TOP | wx.LEFT|wx.EXPAND, 8) self.display_sizer.Add(display_window_2, 1, wx.TOP | wx.LEFT|wx.EXPAND, 8) self.name_sizer.Add(name_window, 1, wx.TOP, 5.5) self.bounds_sizer.Add(bounds_window, 1, wx.TOP, 5.5) self.buttons_sizer.Add(buttons1_window, 1, wx.TOP, 0) #duplicate high levels plot self.fig = Figure((2.5*self.GUI_RESOLUTION, 2.5*self.GUI_RESOLUTION), dpi=100) self.canvas = FigCanvas(self.panel, -1, self.fig, ) self.toolbar = NavigationToolbar(self.canvas) self.toolbar.Hide() self.toolbar.zoom() self.high_EA_setting = "Zoom" self.canvas.Bind(wx.EVT_LEFT_DCLICK,self.on_equalarea_high_select) self.canvas.Bind(wx.EVT_MOTION,self.on_change_high_mouse_cursor) self.canvas.Bind(wx.EVT_MIDDLE_DOWN,self.home_high_equalarea) self.canvas.Bind(wx.EVT_RIGHT_DOWN,self.pan_zoom_high_equalarea) self.canvas.SetHelpText(dieh.eqarea_help) self.eqarea = self.fig.add_subplot(111) draw_net(self.eqarea) #Higher Level Statistics Box self.stats_sizer = wx.StaticBoxSizer( wx.StaticBox( self.panel, wx.ID_ANY,"mean statistics" ), wx.VERTICAL) for parameter in ['mean_type','dec','inc','alpha95','K','R','n_lines','n_planes']: COMMAND="self.%s_window=wx.TextCtrl(self.panel,style=wx.TE_CENTER|wx.TE_READONLY,size=(100*self.GUI_RESOLUTION,25))"%parameter exec(COMMAND) COMMAND="self.%s_window.SetBackgroundColour(wx.WHITE)"%parameter exec(COMMAND) COMMAND="self.%s_window.SetFont(font2)"%parameter exec(COMMAND) COMMAND="self.%s_outer_window = wx.GridSizer(1,2,5*self.GUI_RESOLUTION,15*self.GUI_RESOLUTION)"%parameter exec(COMMAND) COMMAND="""self.%s_outer_window.AddMany([ (wx.StaticText(self.panel,label='%s',style=wx.TE_CENTER),wx.EXPAND), (self.%s_window, wx.EXPAND)])"""%(parameter,parameter,parameter) exec(COMMAND) COMMAND="self.stats_sizer.Add(self.%s_outer_window, 1, wx.ALIGN_LEFT|wx.EXPAND, 0)"%parameter exec(COMMAND) self.switch_stats_button = wx.SpinButton(self.panel, id=wx.ID_ANY, style=wx.SP_HORIZONTAL|wx.SP_ARROW_KEYS|wx.SP_WRAP, name="change stats") self.Bind(wx.EVT_SPIN, self.on_select_stats_button,self.switch_stats_button) self.switch_stats_button.SetHelpText(dieh.switch_stats_btn_help) #construct panel hbox0 = wx.BoxSizer(wx.HORIZONTAL) hbox0.Add(self.name_sizer,flag=wx.ALIGN_TOP|wx.EXPAND,border=8) hbox0.Add(self.bounds_sizer,flag=wx.ALIGN_TOP|wx.EXPAND,border=8) vbox0 = wx.BoxSizer(wx.VERTICAL) vbox0.Add(hbox0,flag=wx.ALIGN_TOP,border=8) vbox0.Add(self.buttons_sizer,flag=wx.ALIGN_TOP,border=8) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox1.Add(vbox0,flag=wx.ALIGN_TOP,border=8) hbox1.Add(self.stats_sizer,flag=wx.ALIGN_TOP,border=8) hbox1.Add(self.switch_stats_button,flag=wx.ALIGN_TOP|wx.EXPAND,border=8) vbox1 = wx.BoxSizer(wx.VERTICAL) vbox1.Add(self.display_sizer,flag=wx.ALIGN_TOP,border=8) vbox1.Add(hbox1,flag=wx.ALIGN_TOP,border=8) vbox1.Add(self.canvas,proportion=1,flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,border=8) vbox2 = wx.BoxSizer(wx.VERTICAL) vbox2.Add(self.search_bar,proportion=.5,flag=wx.ALIGN_LEFT | wx.ALIGN_BOTTOM | wx.EXPAND, border=8) vbox2.Add(self.logger,proportion=1,flag=wx.ALIGN_LEFT|wx.EXPAND,border=8) hbox2 = wx.BoxSizer(wx.HORIZONTAL) hbox2.Add(vbox2,proportion=1,flag=wx.ALIGN_LEFT|wx.EXPAND) hbox2.Add(vbox1,flag=wx.ALIGN_TOP|wx.EXPAND) self.panel.SetSizerAndFit(hbox2) hbox2.Fit(self)
Builds User Interface for the interpretation Editor
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L55-L285
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): """ 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
updates the logger and plot on the interpretation editor window
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L408-L424
PmagPy/PmagPy
dialogs/demag_interpretation_editor.py
InterpretationEditorFrame.update_logger_entry
def update_logger_entry(self,i): """ helper function that given a index in this objects fit_list parameter inserts a entry at that index @param: i -> index in fit_list to find the (specimen_name,fit object) tup that determines all the data for this logger entry. """ if i < len(self.fit_list): tup = self.fit_list[i] elif i < self.logger.GetItemCount(): self.logger.DeleteItem(i) return else: return coordinate_system = self.parent.COORDINATE_SYSTEM fit = tup[0] pars = fit.get(coordinate_system) fmin,fmax,n,ftype,dec,inc,mad,dang,a95,sk,sr2 = "","","","","","","","","","","" specimen = tup[1] if coordinate_system=='geographic': block_key = 'zijdblock_geo' elif coordinate_system=='tilt-corrected': block_key = 'zijdblock_tilt' else: block_key = 'zijdblock' name = fit.name if pars == {} and self.parent.Data[specimen][block_key] != []: fit.put(specimen, coordinate_system, self.parent.get_PCA_parameters(specimen,fit,fit.tmin,fit.tmax,coordinate_system,fit.PCA_type)) pars = fit.get(coordinate_system) if self.parent.Data[specimen][block_key]==[]: spars = fit.get('specimen') fmin = fit.tmin fmax = fit.tmax if 'specimen_n' in list(spars.keys()): n = str(spars['specimen_n']) else: n = 'No Data' if 'calculation_type' in list(spars.keys()): ftype = spars['calculation_type'] else: ftype = 'No Data' dec = 'No Data' inc = 'No Data' mad = 'No Data' dang = 'No Data' a95 = 'No Data' sk = 'No Data' sr2 = 'No Data' else: if 'measurement_step_min' in list(pars.keys()): fmin = str(fit.tmin) else: fmin = "N/A" if 'measurement_step_max' in list(pars.keys()): fmax = str(fit.tmax) else: fmax = "N/A" if 'specimen_n' in list(pars.keys()): n = str(pars['specimen_n']) else: n = "N/A" if 'calculation_type' in list(pars.keys()): ftype = pars['calculation_type'] else: ftype = "N/A" if 'specimen_dec' in list(pars.keys()): dec = "%.1f"%pars['specimen_dec'] else: dec = "N/A" if 'specimen_inc' in list(pars.keys()): inc = "%.1f"%pars['specimen_inc'] else: inc = "N/A" if 'specimen_mad' in list(pars.keys()): mad = "%.1f"%pars['specimen_mad'] else: mad = "N/A" if 'specimen_dang' in list(pars.keys()): dang = "%.1f"%pars['specimen_dang'] else: dang = "N/A" if 'specimen_alpha95' in list(pars.keys()): a95 = "%.1f"%pars['specimen_alpha95'] else: a95 = "N/A" if 'specimen_k' in list(pars.keys()): sk = "%.1f"%pars['specimen_k'] else: sk = "N/A" if 'specimen_r' in list(pars.keys()): sr2 = "%.1f"%pars['specimen_r'] else: sr2 = "N/A" if self.search_query != "": entry = (specimen+name+fmin+fmax+n+ftype+dec+inc+mad+dang+a95+sk+sr2).replace(" ","").lower() if self.search_query not in entry: self.fit_list.pop(i) if i < self.logger.GetItemCount(): self.logger.DeleteItem(i) return "s" for e in (specimen,name,fmin,fmax,n,ftype,dec,inc,mad,dang,a95,sk,sr2): if e not in self.search_choices: self.search_choices.append(e) if i < self.logger.GetItemCount(): self.logger.DeleteItem(i) self.logger.InsertItem(i, str(specimen)) self.logger.SetItem(i, 1, name) self.logger.SetItem(i, 2, fmin) self.logger.SetItem(i, 3, fmax) self.logger.SetItem(i, 4, n) self.logger.SetItem(i, 5, ftype) self.logger.SetItem(i, 6, dec) self.logger.SetItem(i, 7, inc) self.logger.SetItem(i, 8, mad) self.logger.SetItem(i, 9, dang) self.logger.SetItem(i, 10, a95) self.logger.SetItem(i, 11, sk) self.logger.SetItem(i, 12, sr2) self.logger.SetItemBackgroundColour(i,"WHITE") a,b = False,False if fit in self.parent.bad_fits: self.logger.SetItemBackgroundColour(i,"red") b = True if self.parent.current_fit == fit: self.logger.SetItemBackgroundColour(i,"LIGHT BLUE") self.logger_focus(i) self.current_fit_index = i a = True if a and b: self.logger.SetItemBackgroundColour(i,"red")
python
def update_logger_entry(self,i): """ helper function that given a index in this objects fit_list parameter inserts a entry at that index @param: i -> index in fit_list to find the (specimen_name,fit object) tup that determines all the data for this logger entry. """ if i < len(self.fit_list): tup = self.fit_list[i] elif i < self.logger.GetItemCount(): self.logger.DeleteItem(i) return else: return coordinate_system = self.parent.COORDINATE_SYSTEM fit = tup[0] pars = fit.get(coordinate_system) fmin,fmax,n,ftype,dec,inc,mad,dang,a95,sk,sr2 = "","","","","","","","","","","" specimen = tup[1] if coordinate_system=='geographic': block_key = 'zijdblock_geo' elif coordinate_system=='tilt-corrected': block_key = 'zijdblock_tilt' else: block_key = 'zijdblock' name = fit.name if pars == {} and self.parent.Data[specimen][block_key] != []: fit.put(specimen, coordinate_system, self.parent.get_PCA_parameters(specimen,fit,fit.tmin,fit.tmax,coordinate_system,fit.PCA_type)) pars = fit.get(coordinate_system) if self.parent.Data[specimen][block_key]==[]: spars = fit.get('specimen') fmin = fit.tmin fmax = fit.tmax if 'specimen_n' in list(spars.keys()): n = str(spars['specimen_n']) else: n = 'No Data' if 'calculation_type' in list(spars.keys()): ftype = spars['calculation_type'] else: ftype = 'No Data' dec = 'No Data' inc = 'No Data' mad = 'No Data' dang = 'No Data' a95 = 'No Data' sk = 'No Data' sr2 = 'No Data' else: if 'measurement_step_min' in list(pars.keys()): fmin = str(fit.tmin) else: fmin = "N/A" if 'measurement_step_max' in list(pars.keys()): fmax = str(fit.tmax) else: fmax = "N/A" if 'specimen_n' in list(pars.keys()): n = str(pars['specimen_n']) else: n = "N/A" if 'calculation_type' in list(pars.keys()): ftype = pars['calculation_type'] else: ftype = "N/A" if 'specimen_dec' in list(pars.keys()): dec = "%.1f"%pars['specimen_dec'] else: dec = "N/A" if 'specimen_inc' in list(pars.keys()): inc = "%.1f"%pars['specimen_inc'] else: inc = "N/A" if 'specimen_mad' in list(pars.keys()): mad = "%.1f"%pars['specimen_mad'] else: mad = "N/A" if 'specimen_dang' in list(pars.keys()): dang = "%.1f"%pars['specimen_dang'] else: dang = "N/A" if 'specimen_alpha95' in list(pars.keys()): a95 = "%.1f"%pars['specimen_alpha95'] else: a95 = "N/A" if 'specimen_k' in list(pars.keys()): sk = "%.1f"%pars['specimen_k'] else: sk = "N/A" if 'specimen_r' in list(pars.keys()): sr2 = "%.1f"%pars['specimen_r'] else: sr2 = "N/A" if self.search_query != "": entry = (specimen+name+fmin+fmax+n+ftype+dec+inc+mad+dang+a95+sk+sr2).replace(" ","").lower() if self.search_query not in entry: self.fit_list.pop(i) if i < self.logger.GetItemCount(): self.logger.DeleteItem(i) return "s" for e in (specimen,name,fmin,fmax,n,ftype,dec,inc,mad,dang,a95,sk,sr2): if e not in self.search_choices: self.search_choices.append(e) if i < self.logger.GetItemCount(): self.logger.DeleteItem(i) self.logger.InsertItem(i, str(specimen)) self.logger.SetItem(i, 1, name) self.logger.SetItem(i, 2, fmin) self.logger.SetItem(i, 3, fmax) self.logger.SetItem(i, 4, n) self.logger.SetItem(i, 5, ftype) self.logger.SetItem(i, 6, dec) self.logger.SetItem(i, 7, inc) self.logger.SetItem(i, 8, mad) self.logger.SetItem(i, 9, dang) self.logger.SetItem(i, 10, a95) self.logger.SetItem(i, 11, sk) self.logger.SetItem(i, 12, sr2) self.logger.SetItemBackgroundColour(i,"WHITE") a,b = False,False if fit in self.parent.bad_fits: self.logger.SetItemBackgroundColour(i,"red") b = True if self.parent.current_fit == fit: self.logger.SetItemBackgroundColour(i,"LIGHT BLUE") self.logger_focus(i) self.current_fit_index = i a = True if a and b: self.logger.SetItemBackgroundColour(i,"red")
helper function that given a index in this objects fit_list parameter inserts a entry at that index @param: i -> index in fit_list to find the (specimen_name,fit object) tup that determines all the data for this logger entry.
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L426-L531
PmagPy/PmagPy
dialogs/demag_interpretation_editor.py
InterpretationEditorFrame.change_selected
def change_selected(self,new_fit): """ updates passed in fit or index as current fit for the editor (does not affect parent), if no parameters are passed in it sets first fit as current @param: new_fit -> fit object to highlight as selected """ if len(self.fit_list)==0: return if self.search_query and self.parent.current_fit not in [x[0] for x in self.fit_list]: return if self.current_fit_index == None: if not self.parent.current_fit: return for i,(fit,specimen) in enumerate(self.fit_list): if fit == self.parent.current_fit: self.current_fit_index = i break i = 0 if isinstance(new_fit, Fit): for i, (fit,speci) in enumerate(self.fit_list): if fit == new_fit: break elif type(new_fit) is int: i = new_fit elif new_fit != None: print(('cannot select fit of type: ' + str(type(new_fit)))) if self.current_fit_index != None and \ len(self.fit_list) > 0 and \ self.fit_list[self.current_fit_index][0] in self.parent.bad_fits: self.logger.SetItemBackgroundColour(self.current_fit_index,"") else: self.logger.SetItemBackgroundColour(self.current_fit_index,"WHITE") self.current_fit_index = i if self.fit_list[self.current_fit_index][0] in self.parent.bad_fits: self.logger.SetItemBackgroundColour(self.current_fit_index,"red") else: self.logger.SetItemBackgroundColour(self.current_fit_index,"LIGHT BLUE")
python
def change_selected(self,new_fit): """ updates passed in fit or index as current fit for the editor (does not affect parent), if no parameters are passed in it sets first fit as current @param: new_fit -> fit object to highlight as selected """ if len(self.fit_list)==0: return if self.search_query and self.parent.current_fit not in [x[0] for x in self.fit_list]: return if self.current_fit_index == None: if not self.parent.current_fit: return for i,(fit,specimen) in enumerate(self.fit_list): if fit == self.parent.current_fit: self.current_fit_index = i break i = 0 if isinstance(new_fit, Fit): for i, (fit,speci) in enumerate(self.fit_list): if fit == new_fit: break elif type(new_fit) is int: i = new_fit elif new_fit != None: print(('cannot select fit of type: ' + str(type(new_fit)))) if self.current_fit_index != None and \ len(self.fit_list) > 0 and \ self.fit_list[self.current_fit_index][0] in self.parent.bad_fits: self.logger.SetItemBackgroundColour(self.current_fit_index,"") else: self.logger.SetItemBackgroundColour(self.current_fit_index,"WHITE") self.current_fit_index = i if self.fit_list[self.current_fit_index][0] in self.parent.bad_fits: self.logger.SetItemBackgroundColour(self.current_fit_index,"red") else: self.logger.SetItemBackgroundColour(self.current_fit_index,"LIGHT BLUE")
updates passed in fit or index as current fit for the editor (does not affect parent), if no parameters are passed in it sets first fit as current @param: new_fit -> fit object to highlight as selected
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L540-L573
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): """ 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)
focuses the logger on an index 12 entries below i @param: i -> index to focus on
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L575-L584
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): """ 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()
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L586-L602
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): """ 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)
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L604-L625
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): """ 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()
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L669-L676
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): """ 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)
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L679-L706
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): """ 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()
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L708-L729
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): """ 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)
set parent Zeq_GUI to reflect change in this box and change the @param: event -> the wx.ComboBoxEvent that triggered this function
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L731-L740
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): """ 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)
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L742-L749
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): """ 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()
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L761-L782
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): """ 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()
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L818-L834
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): """ 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)
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L836-L857
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): """ 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()
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L859-L907
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): """ 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
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/demag_interpretation_editor.py#L935-L953
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(): """ 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]))
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)
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/tk03.py#L9-L74
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(): """ 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')
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/gaussian.py#L7-L54
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(): """ 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)
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/qqunf.py#L10-L68
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(): """ 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)
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).
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/qqplot.py#L11-L74
PmagPy/PmagPy
dialogs/grid_frame3.py
GridFrame.InitUI
def InitUI(self): """ initialize window """ self.main_sizer = wx.BoxSizer(wx.VERTICAL) if self.grid_type in self.contribution.tables: dataframe = self.contribution.tables[self.grid_type] else: dataframe = None self.grid_builder = GridBuilder(self.contribution, self.grid_type, self.panel, parent_type=self.parent_type, reqd_headers=self.reqd_headers, exclude_cols=self.exclude_cols, huge=self.huge) self.grid = self.grid_builder.make_grid() self.grid.InitUI() ## Column management buttons self.add_cols_button = wx.Button(self.panel, label="Add additional columns", name='add_cols_btn', size=(170, 20)) self.Bind(wx.EVT_BUTTON, self.on_add_cols, self.add_cols_button) self.remove_cols_button = wx.Button(self.panel, label="Remove columns", name='remove_cols_btn', size=(170, 20)) self.Bind(wx.EVT_BUTTON, self.on_remove_cols, self.remove_cols_button) ## Row management buttons self.remove_row_button = wx.Button(self.panel, label="Remove last row", name='remove_last_row_btn') self.Bind(wx.EVT_BUTTON, self.on_remove_row, self.remove_row_button) many_rows_box = wx.BoxSizer(wx.HORIZONTAL) self.add_many_rows_button = wx.Button(self.panel, label="Add row(s)", name='add_many_rows_btn') self.rows_spin_ctrl = wx.SpinCtrl(self.panel, value='1', initial=1, name='rows_spin_ctrl') many_rows_box.Add(self.add_many_rows_button, flag=wx.ALIGN_CENTRE) many_rows_box.Add(self.rows_spin_ctrl) self.Bind(wx.EVT_BUTTON, self.on_add_rows, self.add_many_rows_button) self.deleteRowButton = wx.Button(self.panel, id=-1, label='Delete selected row(s)', name='delete_row_btn') self.Bind(wx.EVT_BUTTON, lambda event: self.on_remove_row(event, False), self.deleteRowButton) self.deleteRowButton.Disable() # measurements table should not be able to add new rows # that should be done elsewhere if self.huge: self.add_many_rows_button.Disable() self.rows_spin_ctrl.Disable() self.remove_row_button.Disable() # can't remove cols (seg fault), but can add them #self.add_cols_button.Disable() self.remove_cols_button.Disable() ## Data management buttons self.importButton = wx.Button(self.panel, id=-1, label='Import MagIC-format file', name='import_btn') self.Bind(wx.EVT_BUTTON, self.onImport, self.importButton) self.exitButton = wx.Button(self.panel, id=-1, label='Save and close grid', name='save_and_quit_btn') self.Bind(wx.EVT_BUTTON, self.onSave, self.exitButton) self.cancelButton = wx.Button(self.panel, id=-1, label='Cancel', name='cancel_btn') self.Bind(wx.EVT_BUTTON, self.onCancelButton, self.cancelButton) self.Bind(wx.EVT_CLOSE, self.onCancelButton) ## Input/output buttons self.copyButton = wx.Button(self.panel, id=-1, label="Start copy mode", name="copy_mode_btn") self.Bind(wx.EVT_BUTTON, self.onCopyMode, self.copyButton) self.selectAllButton = wx.Button(self.panel, id=-1, label="Copy all cells", name="select_all_btn") self.Bind(wx.EVT_BUTTON, self.onSelectAll, self.selectAllButton) self.copySelectionButton = wx.Button(self.panel, id=-1, label="Copy selected cells", name="copy_selection_btn") self.Bind(wx.EVT_BUTTON, self.onCopySelection, self.copySelectionButton) self.copySelectionButton.Disable() ## Help message and button # button self.toggle_help_btn = wx.Button(self.panel, id=-1, label="Show help", name='toggle_help_btn') self.Bind(wx.EVT_BUTTON, self.toggle_help, self.toggle_help_btn) # message self.help_msg_boxsizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, name='help_msg_boxsizer'), wx.VERTICAL) if self.grid_type == 'measurements': self.default_msg_text = "Edit measurements here.\nIn general, measurements should be imported directly into Pmag GUI,\nwhich has protocols for converting many lab formats into the MagIC format.\nIf we are missing your particular lab format, please let us know: https://github.com/PmagPy/PmagPy/issues.\nThis grid is just meant for looking at your measurements and doing small edits.\nCurrently, you can't add/remove rows here. You can add columns and edit cell values." else: self.default_msg_text = 'Edit {} here.\nYou can add or remove both rows and columns, however required columns may not be deleted.\nControlled vocabularies are indicated by **, and will have drop-down-menus.\nSuggested vocabularies are indicated by ^^, and also have drop-down-menus.\nTo edit all values in a column, click the column header.\nYou can cut and paste a block of cells from an Excel-like file.\nJust click the top left cell and use command "v".'.format(self.grid_type) txt = '' if self.grid_type == 'locations': txt = '\n\nNote: you can fill in location start/end latitude/longitude here.\nHowever, if you add sites in step 2, the program will calculate those values automatically,\nbased on site latitudes/logitudes.\nThese values will be written to your upload file.' if self.grid_type == 'samples': txt = "\n\nNote: you can fill in lithology, class, and type for each sample here.\nHowever, if the sample's class, lithology, and type are the same as its parent site,\nthose values will propagate down, and will be written to your sample file automatically." if self.grid_type == 'specimens': txt = "\n\nNote: you can fill in lithology, class, and type for each specimen here.\nHowever, if the specimen's class, lithology, and type are the same as its parent sample,\nthose values will propagate down, and will be written to your specimen file automatically." if self.grid_type == 'ages': txt = "\n\nNote: only ages for which you provide data will be written to your upload file." self.default_msg_text += txt self.msg_text = wx.StaticText(self.panel, label=self.default_msg_text, style=wx.TE_CENTER, name='msg text') self.help_msg_boxsizer.Add(self.msg_text) self.help_msg_boxsizer.ShowItems(False) ## Code message and button # button self.toggle_codes_btn = wx.Button(self.panel, id=-1, label="Show method codes", name='toggle_codes_btn') self.Bind(wx.EVT_BUTTON, self.toggle_codes, self.toggle_codes_btn) # message self.code_msg_boxsizer = pw.MethodCodeDemystifier(self.panel, self.contribution.vocab) self.code_msg_boxsizer.ShowItems(False) ## Add content to sizers self.hbox = wx.BoxSizer(wx.HORIZONTAL) col_btn_vbox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='Columns', name='manage columns'), wx.VERTICAL) row_btn_vbox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='Rows', name='manage rows'), wx.VERTICAL) self.main_btn_vbox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='Manage data', name='manage data'), wx.VERTICAL) input_output_vbox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='In/Out', name='manage in out'), wx.VERTICAL) col_btn_vbox.Add(self.add_cols_button, flag=wx.ALL, border=5) col_btn_vbox.Add(self.remove_cols_button, flag=wx.ALL, border=5) row_btn_vbox.Add(many_rows_box, flag=wx.ALL, border=5) row_btn_vbox.Add(self.remove_row_button, flag=wx.ALL, border=5) row_btn_vbox.Add(self.deleteRowButton, flag=wx.ALL, border=5) self.main_btn_vbox.Add(self.importButton, flag=wx.ALL, border=5) self.main_btn_vbox.Add(self.exitButton, flag=wx.ALL, border=5) self.main_btn_vbox.Add(self.cancelButton, flag=wx.ALL, border=5) input_output_vbox.Add(self.copyButton, flag=wx.ALL, border=5) input_output_vbox.Add(self.selectAllButton, flag=wx.ALL, border=5) input_output_vbox.Add(self.copySelectionButton, flag=wx.ALL, border=5) self.hbox.Add(col_btn_vbox) self.hbox.Add(row_btn_vbox) self.hbox.Add(self.main_btn_vbox) self.hbox.Add(input_output_vbox) #self.panel.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid) self.grid.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid) # self.Bind(wx.EVT_KEY_DOWN, self.on_key_down) self.panel.Bind(wx.EVT_TEXT_PASTE, self.do_fit) # add actual data! self.grid_builder.add_data_to_grid(self.grid, self.grid_type) # fill in some default values self.grid_builder.fill_defaults() # set scrollbars self.grid.set_scrollbars() ## this would be a way to prevent editing ## some cells in age grid. ## with multiple types of ages, though, ## this doesn't make much sense #if self.grid_type == 'ages': # attr = wx.grid.GridCellAttr() # attr.SetReadOnly(True) # self.grid.SetColAttr(1, attr) self.drop_down_menu = drop_down_menus.Menus(self.grid_type, self.contribution, self.grid) self.grid_box = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, name='grid container'), wx.VERTICAL) self.grid_box.Add(self.grid, 1, flag=wx.ALL|wx.EXPAND, border=5) # final layout, set size self.main_sizer.Add(self.hbox, flag=wx.ALL|wx.ALIGN_CENTER,#|wx.SHAPED, border=20) self.main_sizer.Add(self.toggle_help_btn, 0, flag=wx.BOTTOM|wx.ALIGN_CENTRE,#|wx.SHAPED, border=5) self.main_sizer.Add(self.help_msg_boxsizer, 0, flag=wx.BOTTOM|wx.ALIGN_CENTRE, border=10) self.main_sizer.Add(self.toggle_codes_btn, 0, flag=wx.BOTTOM|wx.ALIGN_CENTRE,#|wx.SHAPED, border=5) self.main_sizer.Add(self.code_msg_boxsizer, 0, flag=wx.BOTTOM|wx.ALIGN_CENTRE,#|wx.SHAPED, border=5) self.main_sizer.Add(self.grid_box, 2, flag=wx.ALL|wx.ALIGN_CENTER|wx.EXPAND, border=10) self.panel.SetSizer(self.main_sizer) panel_sizer = wx.BoxSizer(wx.VERTICAL) panel_sizer.Add(self.panel, 1, wx.EXPAND) self.SetSizer(panel_sizer) panel_sizer.Fit(self) ## this keeps sizing correct if the user resizes the window manually #self.Bind(wx.EVT_SIZE, self.do_fit) # self.Centre() self.Show()
python
def InitUI(self): """ initialize window """ self.main_sizer = wx.BoxSizer(wx.VERTICAL) if self.grid_type in self.contribution.tables: dataframe = self.contribution.tables[self.grid_type] else: dataframe = None self.grid_builder = GridBuilder(self.contribution, self.grid_type, self.panel, parent_type=self.parent_type, reqd_headers=self.reqd_headers, exclude_cols=self.exclude_cols, huge=self.huge) self.grid = self.grid_builder.make_grid() self.grid.InitUI() ## Column management buttons self.add_cols_button = wx.Button(self.panel, label="Add additional columns", name='add_cols_btn', size=(170, 20)) self.Bind(wx.EVT_BUTTON, self.on_add_cols, self.add_cols_button) self.remove_cols_button = wx.Button(self.panel, label="Remove columns", name='remove_cols_btn', size=(170, 20)) self.Bind(wx.EVT_BUTTON, self.on_remove_cols, self.remove_cols_button) ## Row management buttons self.remove_row_button = wx.Button(self.panel, label="Remove last row", name='remove_last_row_btn') self.Bind(wx.EVT_BUTTON, self.on_remove_row, self.remove_row_button) many_rows_box = wx.BoxSizer(wx.HORIZONTAL) self.add_many_rows_button = wx.Button(self.panel, label="Add row(s)", name='add_many_rows_btn') self.rows_spin_ctrl = wx.SpinCtrl(self.panel, value='1', initial=1, name='rows_spin_ctrl') many_rows_box.Add(self.add_many_rows_button, flag=wx.ALIGN_CENTRE) many_rows_box.Add(self.rows_spin_ctrl) self.Bind(wx.EVT_BUTTON, self.on_add_rows, self.add_many_rows_button) self.deleteRowButton = wx.Button(self.panel, id=-1, label='Delete selected row(s)', name='delete_row_btn') self.Bind(wx.EVT_BUTTON, lambda event: self.on_remove_row(event, False), self.deleteRowButton) self.deleteRowButton.Disable() # measurements table should not be able to add new rows # that should be done elsewhere if self.huge: self.add_many_rows_button.Disable() self.rows_spin_ctrl.Disable() self.remove_row_button.Disable() # can't remove cols (seg fault), but can add them #self.add_cols_button.Disable() self.remove_cols_button.Disable() ## Data management buttons self.importButton = wx.Button(self.panel, id=-1, label='Import MagIC-format file', name='import_btn') self.Bind(wx.EVT_BUTTON, self.onImport, self.importButton) self.exitButton = wx.Button(self.panel, id=-1, label='Save and close grid', name='save_and_quit_btn') self.Bind(wx.EVT_BUTTON, self.onSave, self.exitButton) self.cancelButton = wx.Button(self.panel, id=-1, label='Cancel', name='cancel_btn') self.Bind(wx.EVT_BUTTON, self.onCancelButton, self.cancelButton) self.Bind(wx.EVT_CLOSE, self.onCancelButton) ## Input/output buttons self.copyButton = wx.Button(self.panel, id=-1, label="Start copy mode", name="copy_mode_btn") self.Bind(wx.EVT_BUTTON, self.onCopyMode, self.copyButton) self.selectAllButton = wx.Button(self.panel, id=-1, label="Copy all cells", name="select_all_btn") self.Bind(wx.EVT_BUTTON, self.onSelectAll, self.selectAllButton) self.copySelectionButton = wx.Button(self.panel, id=-1, label="Copy selected cells", name="copy_selection_btn") self.Bind(wx.EVT_BUTTON, self.onCopySelection, self.copySelectionButton) self.copySelectionButton.Disable() ## Help message and button # button self.toggle_help_btn = wx.Button(self.panel, id=-1, label="Show help", name='toggle_help_btn') self.Bind(wx.EVT_BUTTON, self.toggle_help, self.toggle_help_btn) # message self.help_msg_boxsizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, name='help_msg_boxsizer'), wx.VERTICAL) if self.grid_type == 'measurements': self.default_msg_text = "Edit measurements here.\nIn general, measurements should be imported directly into Pmag GUI,\nwhich has protocols for converting many lab formats into the MagIC format.\nIf we are missing your particular lab format, please let us know: https://github.com/PmagPy/PmagPy/issues.\nThis grid is just meant for looking at your measurements and doing small edits.\nCurrently, you can't add/remove rows here. You can add columns and edit cell values." else: self.default_msg_text = 'Edit {} here.\nYou can add or remove both rows and columns, however required columns may not be deleted.\nControlled vocabularies are indicated by **, and will have drop-down-menus.\nSuggested vocabularies are indicated by ^^, and also have drop-down-menus.\nTo edit all values in a column, click the column header.\nYou can cut and paste a block of cells from an Excel-like file.\nJust click the top left cell and use command "v".'.format(self.grid_type) txt = '' if self.grid_type == 'locations': txt = '\n\nNote: you can fill in location start/end latitude/longitude here.\nHowever, if you add sites in step 2, the program will calculate those values automatically,\nbased on site latitudes/logitudes.\nThese values will be written to your upload file.' if self.grid_type == 'samples': txt = "\n\nNote: you can fill in lithology, class, and type for each sample here.\nHowever, if the sample's class, lithology, and type are the same as its parent site,\nthose values will propagate down, and will be written to your sample file automatically." if self.grid_type == 'specimens': txt = "\n\nNote: you can fill in lithology, class, and type for each specimen here.\nHowever, if the specimen's class, lithology, and type are the same as its parent sample,\nthose values will propagate down, and will be written to your specimen file automatically." if self.grid_type == 'ages': txt = "\n\nNote: only ages for which you provide data will be written to your upload file." self.default_msg_text += txt self.msg_text = wx.StaticText(self.panel, label=self.default_msg_text, style=wx.TE_CENTER, name='msg text') self.help_msg_boxsizer.Add(self.msg_text) self.help_msg_boxsizer.ShowItems(False) ## Code message and button # button self.toggle_codes_btn = wx.Button(self.panel, id=-1, label="Show method codes", name='toggle_codes_btn') self.Bind(wx.EVT_BUTTON, self.toggle_codes, self.toggle_codes_btn) # message self.code_msg_boxsizer = pw.MethodCodeDemystifier(self.panel, self.contribution.vocab) self.code_msg_boxsizer.ShowItems(False) ## Add content to sizers self.hbox = wx.BoxSizer(wx.HORIZONTAL) col_btn_vbox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='Columns', name='manage columns'), wx.VERTICAL) row_btn_vbox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='Rows', name='manage rows'), wx.VERTICAL) self.main_btn_vbox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='Manage data', name='manage data'), wx.VERTICAL) input_output_vbox = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label='In/Out', name='manage in out'), wx.VERTICAL) col_btn_vbox.Add(self.add_cols_button, flag=wx.ALL, border=5) col_btn_vbox.Add(self.remove_cols_button, flag=wx.ALL, border=5) row_btn_vbox.Add(many_rows_box, flag=wx.ALL, border=5) row_btn_vbox.Add(self.remove_row_button, flag=wx.ALL, border=5) row_btn_vbox.Add(self.deleteRowButton, flag=wx.ALL, border=5) self.main_btn_vbox.Add(self.importButton, flag=wx.ALL, border=5) self.main_btn_vbox.Add(self.exitButton, flag=wx.ALL, border=5) self.main_btn_vbox.Add(self.cancelButton, flag=wx.ALL, border=5) input_output_vbox.Add(self.copyButton, flag=wx.ALL, border=5) input_output_vbox.Add(self.selectAllButton, flag=wx.ALL, border=5) input_output_vbox.Add(self.copySelectionButton, flag=wx.ALL, border=5) self.hbox.Add(col_btn_vbox) self.hbox.Add(row_btn_vbox) self.hbox.Add(self.main_btn_vbox) self.hbox.Add(input_output_vbox) #self.panel.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid) self.grid.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid) # self.Bind(wx.EVT_KEY_DOWN, self.on_key_down) self.panel.Bind(wx.EVT_TEXT_PASTE, self.do_fit) # add actual data! self.grid_builder.add_data_to_grid(self.grid, self.grid_type) # fill in some default values self.grid_builder.fill_defaults() # set scrollbars self.grid.set_scrollbars() ## this would be a way to prevent editing ## some cells in age grid. ## with multiple types of ages, though, ## this doesn't make much sense #if self.grid_type == 'ages': # attr = wx.grid.GridCellAttr() # attr.SetReadOnly(True) # self.grid.SetColAttr(1, attr) self.drop_down_menu = drop_down_menus.Menus(self.grid_type, self.contribution, self.grid) self.grid_box = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, name='grid container'), wx.VERTICAL) self.grid_box.Add(self.grid, 1, flag=wx.ALL|wx.EXPAND, border=5) # final layout, set size self.main_sizer.Add(self.hbox, flag=wx.ALL|wx.ALIGN_CENTER,#|wx.SHAPED, border=20) self.main_sizer.Add(self.toggle_help_btn, 0, flag=wx.BOTTOM|wx.ALIGN_CENTRE,#|wx.SHAPED, border=5) self.main_sizer.Add(self.help_msg_boxsizer, 0, flag=wx.BOTTOM|wx.ALIGN_CENTRE, border=10) self.main_sizer.Add(self.toggle_codes_btn, 0, flag=wx.BOTTOM|wx.ALIGN_CENTRE,#|wx.SHAPED, border=5) self.main_sizer.Add(self.code_msg_boxsizer, 0, flag=wx.BOTTOM|wx.ALIGN_CENTRE,#|wx.SHAPED, border=5) self.main_sizer.Add(self.grid_box, 2, flag=wx.ALL|wx.ALIGN_CENTER|wx.EXPAND, border=10) self.panel.SetSizer(self.main_sizer) panel_sizer = wx.BoxSizer(wx.VERTICAL) panel_sizer.Add(self.panel, 1, wx.EXPAND) self.SetSizer(panel_sizer) panel_sizer.Fit(self) ## this keeps sizing correct if the user resizes the window manually #self.Bind(wx.EVT_SIZE, self.do_fit) # self.Centre() self.Show()
initialize window
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L89-L291
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): """ 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)
If user does command v, re-size window in case pasting has changed the content size.
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L293-L302
PmagPy/PmagPy
dialogs/grid_frame3.py
GridFrame.do_fit
def do_fit(self, event, min_size=None): """ Re-fit the window to the size of the content. """ #self.grid.ShowScrollbars(wx.SHOW_SB_NEVER, wx.SHOW_SB_NEVER) if event: event.Skip() self.main_sizer.Fit(self) disp_size = wx.GetDisplaySize() actual_size = self.GetSize() # if there isn't enough room to display new content # resize the frame if disp_size[1] - 75 < actual_size[1]: self.SetSize((actual_size[0], disp_size[1] * .95)) # make sure you adhere to a minimum size if min_size: actual_size = self.GetSize() larger_width = max([actual_size[0], min_size[0]]) larger_height = max([actual_size[1], min_size[1]]) if larger_width > actual_size[0] or larger_height > actual_size[1]: self.SetSize((larger_width, larger_height)) self.Centre()
python
def do_fit(self, event, min_size=None): """ Re-fit the window to the size of the content. """ #self.grid.ShowScrollbars(wx.SHOW_SB_NEVER, wx.SHOW_SB_NEVER) if event: event.Skip() self.main_sizer.Fit(self) disp_size = wx.GetDisplaySize() actual_size = self.GetSize() # if there isn't enough room to display new content # resize the frame if disp_size[1] - 75 < actual_size[1]: self.SetSize((actual_size[0], disp_size[1] * .95)) # make sure you adhere to a minimum size if min_size: actual_size = self.GetSize() larger_width = max([actual_size[0], min_size[0]]) larger_height = max([actual_size[1], min_size[1]]) if larger_width > actual_size[0] or larger_height > actual_size[1]: self.SetSize((larger_width, larger_height)) self.Centre()
Re-fit the window to the size of the content.
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L304-L325
PmagPy/PmagPy
dialogs/grid_frame3.py
GridFrame.toggle_help
def toggle_help(self, event, mode=None): """ Show/hide help message on help button click. """ # if mode == 'open', show no matter what. # if mode == 'close', close. otherwise, change state btn = self.toggle_help_btn shown = self.help_msg_boxsizer.GetStaticBox().IsShown() # if mode is specified, do that mode if mode == 'open': self.help_msg_boxsizer.ShowItems(True) btn.SetLabel('Hide help') elif mode == 'close': self.help_msg_boxsizer.ShowItems(False) btn.SetLabel('Show help') # otherwise, simply toggle states else: if shown: self.help_msg_boxsizer.ShowItems(False) btn.SetLabel('Show help') else: self.help_msg_boxsizer.ShowItems(True) btn.SetLabel('Hide help') self.do_fit(None)
python
def toggle_help(self, event, mode=None): """ Show/hide help message on help button click. """ # if mode == 'open', show no matter what. # if mode == 'close', close. otherwise, change state btn = self.toggle_help_btn shown = self.help_msg_boxsizer.GetStaticBox().IsShown() # if mode is specified, do that mode if mode == 'open': self.help_msg_boxsizer.ShowItems(True) btn.SetLabel('Hide help') elif mode == 'close': self.help_msg_boxsizer.ShowItems(False) btn.SetLabel('Show help') # otherwise, simply toggle states else: if shown: self.help_msg_boxsizer.ShowItems(False) btn.SetLabel('Show help') else: self.help_msg_boxsizer.ShowItems(True) btn.SetLabel('Hide help') self.do_fit(None)
Show/hide help message on help button click.
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L327-L350
PmagPy/PmagPy
dialogs/grid_frame3.py
GridFrame.toggle_codes
def toggle_codes(self, event): """ Show/hide method code explanation widget on button click """ btn = event.GetEventObject() if btn.Label == 'Show method codes': self.code_msg_boxsizer.ShowItems(True) btn.SetLabel('Hide method codes') else: self.code_msg_boxsizer.ShowItems(False) btn.SetLabel('Show method codes') self.do_fit(None)
python
def toggle_codes(self, event): """ Show/hide method code explanation widget on button click """ btn = event.GetEventObject() if btn.Label == 'Show method codes': self.code_msg_boxsizer.ShowItems(True) btn.SetLabel('Hide method codes') else: self.code_msg_boxsizer.ShowItems(False) btn.SetLabel('Show method codes') self.do_fit(None)
Show/hide method code explanation widget on button click
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L353-L364
PmagPy/PmagPy
dialogs/grid_frame3.py
GridFrame.remove_col_label
def remove_col_label(self, event=None, col=None): """ check to see if column is required if it is not, delete it from grid """ if event: col = event.GetCol() if not col: return label = self.grid.GetColLabelValue(col) if '**' in label: label = label.strip('**') elif '^^' in label: label = label.strip('^^') if label in self.reqd_headers: pw.simple_warning("That header is required, and cannot be removed") return False else: print('That header is not required:', label) # remove column from wxPython grid self.grid.remove_col(col) # remove column from DataFrame if present if self.grid_type in self.contribution.tables: if label in self.contribution.tables[self.grid_type].df.columns: del self.contribution.tables[self.grid_type].df[label] # causes resize on each column header delete # can leave this out if we want..... self.main_sizer.Fit(self)
python
def remove_col_label(self, event=None, col=None): """ check to see if column is required if it is not, delete it from grid """ if event: col = event.GetCol() if not col: return label = self.grid.GetColLabelValue(col) if '**' in label: label = label.strip('**') elif '^^' in label: label = label.strip('^^') if label in self.reqd_headers: pw.simple_warning("That header is required, and cannot be removed") return False else: print('That header is not required:', label) # remove column from wxPython grid self.grid.remove_col(col) # remove column from DataFrame if present if self.grid_type in self.contribution.tables: if label in self.contribution.tables[self.grid_type].df.columns: del self.contribution.tables[self.grid_type].df[label] # causes resize on each column header delete # can leave this out if we want..... self.main_sizer.Fit(self)
check to see if column is required if it is not, delete it from grid
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L381-L408
PmagPy/PmagPy
dialogs/grid_frame3.py
GridFrame.on_add_cols
def on_add_cols(self, event): """ Show simple dialog that allows user to add a new column name """ col_labels = self.grid.col_labels dia = pw.ChooseOne(self, yes="Add single columns", no="Add groups") result1 = dia.ShowModal() if result1 == wx.ID_CANCEL: return elif result1 == wx.ID_YES: items = sorted([col_name for col_name in self.dm.index if col_name not in col_labels]) dia = pw.HeaderDialog(self, 'columns to add', items1=list(items), groups=[]) dia.Centre() result2 = dia.ShowModal() else: groups = self.dm['group'].unique() dia = pw.HeaderDialog(self, 'groups to add', items1=list(groups), groups=True) dia.Centre() result2 = dia.ShowModal() new_headers = [] if result2 == 5100: new_headers = dia.text_list # if there is nothing to add, quit if not new_headers: return if result1 == wx.ID_YES: # add individual headers errors = self.add_new_grid_headers(new_headers) else: # add header groups errors = self.add_new_header_groups(new_headers) if errors: errors_str = ', '.join(errors) pw.simple_warning('You are already using the following headers: {}\nSo they will not be added'.format(errors_str)) # problem: if widgets above the grid are too wide, # the grid does not re-size when adding columns # awkward solution (causes flashing): if self.grid.GetWindowStyle() != wx.DOUBLE_BORDER: self.grid.SetWindowStyle(wx.DOUBLE_BORDER) self.main_sizer.Fit(self) self.grid.SetWindowStyle(wx.NO_BORDER) self.Centre() self.main_sizer.Fit(self) # self.grid.changes = set(range(self.grid.GetNumberRows())) dia.Destroy()
python
def on_add_cols(self, event): """ Show simple dialog that allows user to add a new column name """ col_labels = self.grid.col_labels dia = pw.ChooseOne(self, yes="Add single columns", no="Add groups") result1 = dia.ShowModal() if result1 == wx.ID_CANCEL: return elif result1 == wx.ID_YES: items = sorted([col_name for col_name in self.dm.index if col_name not in col_labels]) dia = pw.HeaderDialog(self, 'columns to add', items1=list(items), groups=[]) dia.Centre() result2 = dia.ShowModal() else: groups = self.dm['group'].unique() dia = pw.HeaderDialog(self, 'groups to add', items1=list(groups), groups=True) dia.Centre() result2 = dia.ShowModal() new_headers = [] if result2 == 5100: new_headers = dia.text_list # if there is nothing to add, quit if not new_headers: return if result1 == wx.ID_YES: # add individual headers errors = self.add_new_grid_headers(new_headers) else: # add header groups errors = self.add_new_header_groups(new_headers) if errors: errors_str = ', '.join(errors) pw.simple_warning('You are already using the following headers: {}\nSo they will not be added'.format(errors_str)) # problem: if widgets above the grid are too wide, # the grid does not re-size when adding columns # awkward solution (causes flashing): if self.grid.GetWindowStyle() != wx.DOUBLE_BORDER: self.grid.SetWindowStyle(wx.DOUBLE_BORDER) self.main_sizer.Fit(self) self.grid.SetWindowStyle(wx.NO_BORDER) self.Centre() self.main_sizer.Fit(self) # self.grid.changes = set(range(self.grid.GetNumberRows())) dia.Destroy()
Show simple dialog that allows user to add a new column name
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L410-L458
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): """ 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
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
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L460-L488
PmagPy/PmagPy
dialogs/grid_frame3.py
GridFrame.add_new_grid_headers
def add_new_grid_headers(self, new_headers): """ Add in all user-added headers. If those new headers depend on other headers, add the other headers too. """ already_present = [] for name in new_headers: if name: if name not in self.grid.col_labels: col_number = self.grid.add_col(name) # add to appropriate headers list # add drop down menus for user-added column if name in self.contribution.vocab.vocabularies: self.drop_down_menu.add_drop_down(col_number, name) elif name in self.contribution.vocab.suggested: self.drop_down_menu.add_drop_down(col_number, name) elif name in ['specimen', 'sample', 'site', 'specimens', 'samples', 'sites']: self.drop_down_menu.add_drop_down(col_number, name) elif name == 'experiments': self.drop_down_menu.add_drop_down(col_number, name) if name == "method_codes": self.drop_down_menu.add_method_drop_down(col_number, name) else: already_present.append(name) #pw.simple_warning('You are already using column header: {}'.format(name)) return already_present
python
def add_new_grid_headers(self, new_headers): """ Add in all user-added headers. If those new headers depend on other headers, add the other headers too. """ already_present = [] for name in new_headers: if name: if name not in self.grid.col_labels: col_number = self.grid.add_col(name) # add to appropriate headers list # add drop down menus for user-added column if name in self.contribution.vocab.vocabularies: self.drop_down_menu.add_drop_down(col_number, name) elif name in self.contribution.vocab.suggested: self.drop_down_menu.add_drop_down(col_number, name) elif name in ['specimen', 'sample', 'site', 'specimens', 'samples', 'sites']: self.drop_down_menu.add_drop_down(col_number, name) elif name == 'experiments': self.drop_down_menu.add_drop_down(col_number, name) if name == "method_codes": self.drop_down_menu.add_method_drop_down(col_number, name) else: already_present.append(name) #pw.simple_warning('You are already using column header: {}'.format(name)) return already_present
Add in all user-added headers. If those new headers depend on other headers, add the other headers too.
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L490-L517
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): """ 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)
add rows to grid
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L545-L557
PmagPy/PmagPy
dialogs/grid_frame3.py
GridFrame.on_remove_row
def on_remove_row(self, event, row_num=-1): """ Remove specified grid row. If no row number is given, remove the last row. """ text = "Are you sure? If you select delete you won't be able to retrieve these rows..." dia = pw.ChooseOne(self, "Yes, delete rows", "Leave rows for now", text) dia.Centre() result = dia.ShowModal() if result == wx.ID_NO: return default = (255, 255, 255, 255) if row_num == -1: # unhighlight any selected rows: for row in self.selected_rows: attr = wx.grid.GridCellAttr() attr.SetBackgroundColour(default) self.grid.SetRowAttr(row, attr) row_num = self.grid.GetNumberRows() - 1 self.deleteRowButton.Disable() self.selected_rows = {row_num} # remove row(s) from the contribution df = self.contribution.tables[self.grid_type].df row_nums = list(range(len(df))) df = df.iloc[[i for i in row_nums if i not in self.selected_rows]] self.contribution.tables[self.grid_type].df = df # now remove row(s) from grid # delete rows, adjusting the row # appropriately as you delete for num, row in enumerate(self.selected_rows): row -= num if row < 0: row = 0 self.grid.remove_row(row) attr = wx.grid.GridCellAttr() attr.SetBackgroundColour(default) self.grid.SetRowAttr(row, attr) # reset the grid self.selected_rows = set() self.deleteRowButton.Disable() self.grid.Refresh() self.main_sizer.Fit(self)
python
def on_remove_row(self, event, row_num=-1): """ Remove specified grid row. If no row number is given, remove the last row. """ text = "Are you sure? If you select delete you won't be able to retrieve these rows..." dia = pw.ChooseOne(self, "Yes, delete rows", "Leave rows for now", text) dia.Centre() result = dia.ShowModal() if result == wx.ID_NO: return default = (255, 255, 255, 255) if row_num == -1: # unhighlight any selected rows: for row in self.selected_rows: attr = wx.grid.GridCellAttr() attr.SetBackgroundColour(default) self.grid.SetRowAttr(row, attr) row_num = self.grid.GetNumberRows() - 1 self.deleteRowButton.Disable() self.selected_rows = {row_num} # remove row(s) from the contribution df = self.contribution.tables[self.grid_type].df row_nums = list(range(len(df))) df = df.iloc[[i for i in row_nums if i not in self.selected_rows]] self.contribution.tables[self.grid_type].df = df # now remove row(s) from grid # delete rows, adjusting the row # appropriately as you delete for num, row in enumerate(self.selected_rows): row -= num if row < 0: row = 0 self.grid.remove_row(row) attr = wx.grid.GridCellAttr() attr.SetBackgroundColour(default) self.grid.SetRowAttr(row, attr) # reset the grid self.selected_rows = set() self.deleteRowButton.Disable() self.grid.Refresh() self.main_sizer.Fit(self)
Remove specified grid row. If no row number is given, remove the last row.
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L559-L599
PmagPy/PmagPy
dialogs/grid_frame3.py
GridFrame.onLeftClickLabel
def onLeftClickLabel(self, event): """ When user clicks on a grid label, determine if it is a row label or a col label. Pass along the event to the appropriate function. (It will either highlight a column for editing all values, or highlight a row for deletion). """ if event.Col == -1 and event.Row == -1: pass if event.Row < 0: if self.remove_cols_mode: self.remove_col_label(event) else: self.drop_down_menu.on_label_click(event) else: if event.Col < 0 and self.grid_type != 'age': self.onSelectRow(event)
python
def onLeftClickLabel(self, event): """ When user clicks on a grid label, determine if it is a row label or a col label. Pass along the event to the appropriate function. (It will either highlight a column for editing all values, or highlight a row for deletion). """ if event.Col == -1 and event.Row == -1: pass if event.Row < 0: if self.remove_cols_mode: self.remove_col_label(event) else: self.drop_down_menu.on_label_click(event) else: if event.Col < 0 and self.grid_type != 'age': self.onSelectRow(event)
When user clicks on a grid label, determine if it is a row label or a col label. Pass along the event to the appropriate function. (It will either highlight a column for editing all values, or highlight a row for deletion).
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L651-L668
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): """ 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
Import a MagIC-format file
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L672-L741
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): """ 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()
Quit grid with warning if unsaved changes present
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L743-L759
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): """ 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()
Save grid data
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L762-L777
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): """ 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]
Set self.df_slice based on user's selection
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L829-L849
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): """ Copy selection if control down and 'c' """ if event.CmdDown() or event.ControlDown(): if event.GetKeyCode() == 67: self.onCopySelection(None)
Copy selection if control down and 'c'
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L859-L865
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): """ 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.')
Selects full grid and copies it to the Clipboard
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L867-L881
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): """ 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.')
Copies self.df_slice to the Clipboard if slice exists
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L884-L894
PmagPy/PmagPy
dialogs/grid_frame3.py
GridBuilder.make_grid
def make_grid(self): """ return grid """ changes = None # if there is a MagicDataFrame, extract data from it if isinstance(self.magic_dataframe, cb.MagicDataFrame): # get columns and reorder slightly col_labels = list(self.magic_dataframe.df.columns) for ex_col in self.exclude_cols: col_labels.pop(ex_col) if self.grid_type == 'ages': levels = ['specimen', 'sample', 'site', 'location'] for label in levels[:]: if label in col_labels: col_labels.remove(label) else: levels.remove(label) col_labels[:0] = levels else: if self.parent_type: if self.parent_type[:-1] in col_labels: col_labels.remove(self.parent_type[:-1]) col_labels[:0] = [self.parent_type[:-1]] if self.grid_type[:-1] in col_labels: col_labels.remove(self.grid_type[:-1]) col_labels[:0] = (self.grid_type[:-1],) for col in col_labels: if col not in self.magic_dataframe.df.columns: self.magic_dataframe.df[col] = None self.magic_dataframe.df = self.magic_dataframe.df[col_labels] self.magic_dataframe.sort_dataframe_cols() col_labels = list(self.magic_dataframe.df.columns) row_labels = self.magic_dataframe.df.index # make sure minimum defaults are present for header in self.reqd_headers: if header not in col_labels: changes = set([1]) col_labels.append(header) # if there is no pre-existing MagicDataFrame, # make a blank grid with do some defaults: else: # default headers #col_labels = list(self.data_model.get_headers(self.grid_type, 'Names')) #col_labels[:0] = self.reqd_headers col_labels = list(self.reqd_headers) if self.grid_type in ['specimens', 'samples', 'sites']: col_labels.extend(['age', 'age_sigma']) ## use the following line if you want sorted column labels: #col_labels = sorted(set(col_labels)) # defaults are different for ages if self.grid_type == 'ages': levels = ['specimen', 'sample', 'site', 'location'] for label in levels: if label in col_labels: col_labels.remove(label) col_labels[:0] = levels else: if self.parent_type: col_labels.remove(self.parent_type[:-1]) col_labels[:0] = [self.parent_type[:-1]] col_labels.remove(self.grid_type[:-1]) col_labels[:0] = [self.grid_type[:-1]] # make sure all reqd cols are in magic_dataframe for col in col_labels: if col not in self.magic_dataframe.df.columns: self.magic_dataframe.df[col] = None # make the grid if not self.huge: grid = magic_grid.MagicGrid(parent=self.panel, name=self.grid_type, row_labels=[], col_labels=col_labels) # make the huge grid else: row_labels = self.magic_dataframe.df.index grid = magic_grid.HugeMagicGrid(parent=self.panel, name=self.grid_type, row_labels=row_labels, col_labels=col_labels) grid.do_event_bindings() grid.changes = changes self.grid = grid return grid
python
def make_grid(self): """ return grid """ changes = None # if there is a MagicDataFrame, extract data from it if isinstance(self.magic_dataframe, cb.MagicDataFrame): # get columns and reorder slightly col_labels = list(self.magic_dataframe.df.columns) for ex_col in self.exclude_cols: col_labels.pop(ex_col) if self.grid_type == 'ages': levels = ['specimen', 'sample', 'site', 'location'] for label in levels[:]: if label in col_labels: col_labels.remove(label) else: levels.remove(label) col_labels[:0] = levels else: if self.parent_type: if self.parent_type[:-1] in col_labels: col_labels.remove(self.parent_type[:-1]) col_labels[:0] = [self.parent_type[:-1]] if self.grid_type[:-1] in col_labels: col_labels.remove(self.grid_type[:-1]) col_labels[:0] = (self.grid_type[:-1],) for col in col_labels: if col not in self.magic_dataframe.df.columns: self.magic_dataframe.df[col] = None self.magic_dataframe.df = self.magic_dataframe.df[col_labels] self.magic_dataframe.sort_dataframe_cols() col_labels = list(self.magic_dataframe.df.columns) row_labels = self.magic_dataframe.df.index # make sure minimum defaults are present for header in self.reqd_headers: if header not in col_labels: changes = set([1]) col_labels.append(header) # if there is no pre-existing MagicDataFrame, # make a blank grid with do some defaults: else: # default headers #col_labels = list(self.data_model.get_headers(self.grid_type, 'Names')) #col_labels[:0] = self.reqd_headers col_labels = list(self.reqd_headers) if self.grid_type in ['specimens', 'samples', 'sites']: col_labels.extend(['age', 'age_sigma']) ## use the following line if you want sorted column labels: #col_labels = sorted(set(col_labels)) # defaults are different for ages if self.grid_type == 'ages': levels = ['specimen', 'sample', 'site', 'location'] for label in levels: if label in col_labels: col_labels.remove(label) col_labels[:0] = levels else: if self.parent_type: col_labels.remove(self.parent_type[:-1]) col_labels[:0] = [self.parent_type[:-1]] col_labels.remove(self.grid_type[:-1]) col_labels[:0] = [self.grid_type[:-1]] # make sure all reqd cols are in magic_dataframe for col in col_labels: if col not in self.magic_dataframe.df.columns: self.magic_dataframe.df[col] = None # make the grid if not self.huge: grid = magic_grid.MagicGrid(parent=self.panel, name=self.grid_type, row_labels=[], col_labels=col_labels) # make the huge grid else: row_labels = self.magic_dataframe.df.index grid = magic_grid.HugeMagicGrid(parent=self.panel, name=self.grid_type, row_labels=row_labels, col_labels=col_labels) grid.do_event_bindings() grid.changes = changes self.grid = grid return grid
return grid
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L948-L1028
PmagPy/PmagPy
dialogs/grid_frame3.py
GridBuilder.add_age_defaults
def add_age_defaults(self): """ Add columns as needed: age, age_unit, specimen, sample, site, location. """ if isinstance(self.magic_dataframe, cb.MagicDataFrame): for col in ['age', 'age_unit']: if col not in self.grid.col_labels: self.grid.add_col(col) for level in ['locations', 'sites', 'samples', 'specimens']: if level in self.contribution.tables: if level[:-1] not in self.grid.col_labels: self.grid.add_col(level[:-1])
python
def add_age_defaults(self): """ Add columns as needed: age, age_unit, specimen, sample, site, location. """ if isinstance(self.magic_dataframe, cb.MagicDataFrame): for col in ['age', 'age_unit']: if col not in self.grid.col_labels: self.grid.add_col(col) for level in ['locations', 'sites', 'samples', 'specimens']: if level in self.contribution.tables: if level[:-1] not in self.grid.col_labels: self.grid.add_col(level[:-1])
Add columns as needed: age, age_unit, specimen, sample, site, location.
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L1054-L1066
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): """ 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
Check to see if grid is empty except for default values
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame3.py#L1068-L1091