repo_name
stringlengths
6
67
path
stringlengths
5
185
copies
stringlengths
1
3
size
stringlengths
4
6
content
stringlengths
1.02k
962k
license
stringclasses
15 values
youprofit/shogun
examples/undocumented/python_modular/graphical/so_multiclass_BMRM.py
16
2853
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from modshogun import RealFeatures from modshogun import MulticlassModel, MulticlassSOLabels, RealNumber, DualLibQPBMSOSVM from modshogun import BMRM, PPBMRM, P3BMRM from modshogun import StructuredAccuracy def fill_data(cnt, minv, maxv): x1 = np.linspace(minv, maxv, cnt) a, b = np.meshgrid(x1, x1) X = np.array((np.ravel(a), np.ravel(b))) y = np.zeros((1, cnt*cnt)) tmp = cnt*cnt; y[0, tmp/3:(tmp/3)*2]=1 y[0, tmp/3*2:(tmp/3)*3]=2 return X, y.flatten() def gen_data(): covs = np.array([[[0., -1. ], [2.5, .7]], [[3., -1.5], [1.2, .3]], [[ 2, 0 ], [ .0, 1.5 ]]]) X = np.r_[np.dot(np.random.randn(N, dim), covs[0]) + np.array([0, 10]), np.dot(np.random.randn(N, dim), covs[1]) + np.array([-10, -10]), np.dot(np.random.randn(N, dim), covs[2]) + np.array([10, -10])]; Y = np.hstack((np.zeros(N), np.ones(N), 2*np.ones(N))) return X, Y def get_so_labels(out): N = out.get_num_labels() l = np.zeros(N) for i in xrange(N): l[i] = RealNumber.obtain_from_generic(out.get_label(i)).value return l # Number of classes M = 3 # Number of samples of each class N = 1000 # Dimension of the data dim = 2 X, y = gen_data() cnt = 250 X2, y2 = fill_data(cnt, np.min(X), np.max(X)) labels = MulticlassSOLabels(y) features = RealFeatures(X.T) model = MulticlassModel(features, labels) lambda_ = 1e1 sosvm = DualLibQPBMSOSVM(model, labels, lambda_) sosvm.set_cleanAfter(10) # number of iterations that cutting plane has to be inactive for to be removed sosvm.set_cleanICP(True) # enables inactive cutting plane removal feature sosvm.set_TolRel(0.001) # set relative tolerance sosvm.set_verbose(True) # enables verbosity of the solver sosvm.set_cp_models(16) # set number of cutting plane models sosvm.set_solver(BMRM) # select training algorithm #sosvm.set_solver(PPBMRM) #sosvm.set_solver(P3BMRM) sosvm.train() res = sosvm.get_result() Fps = np.array(res.get_hist_Fp_vector()) Fds = np.array(res.get_hist_Fp_vector()) wdists = np.array(res.get_hist_wdist_vector()) plt.figure() plt.subplot(221) plt.title('Fp and Fd history') plt.plot(xrange(res.get_n_iters()), Fps, hold=True) plt.plot(xrange(res.get_n_iters()), Fds, hold=True) plt.subplot(222) plt.title('w dist history') plt.plot(xrange(res.get_n_iters()), wdists) # Evaluation out = sosvm.apply() Evaluation = StructuredAccuracy() acc = Evaluation.evaluate(out, labels) print "Correct classification rate: %0.4f%%" % ( 100.0*acc ) # show figure Z = get_so_labels(sosvm.apply(RealFeatures(X2))) x = (X2[0,:]).reshape(cnt, cnt) y = (X2[1,:]).reshape(cnt, cnt) z = Z.reshape(cnt, cnt) plt.subplot(223) plt.pcolor(x, y, z, shading='interp') plt.contour(x, y, z, linewidths=1, colors='black', hold=True) plt.plot(X[:,0], X[:,1], 'yo') plt.axis('tight') plt.title('Classification') plt.show()
gpl-3.0
arokem/scipy
doc/source/tutorial/stats/plots/kde_plot3.py
132
1229
import numpy as np import matplotlib.pyplot as plt from scipy import stats np.random.seed(12456) x1 = np.random.normal(size=200) # random data, normal distribution xs = np.linspace(x1.min()-1, x1.max()+1, 200) kde1 = stats.gaussian_kde(x1) kde2 = stats.gaussian_kde(x1, bw_method='silverman') fig = plt.figure(figsize=(8, 6)) ax1 = fig.add_subplot(211) ax1.plot(x1, np.zeros(x1.shape), 'b+', ms=12) # rug plot ax1.plot(xs, kde1(xs), 'k-', label="Scott's Rule") ax1.plot(xs, kde2(xs), 'b-', label="Silverman's Rule") ax1.plot(xs, stats.norm.pdf(xs), 'r--', label="True PDF") ax1.set_xlabel('x') ax1.set_ylabel('Density') ax1.set_title("Normal (top) and Student's T$_{df=5}$ (bottom) distributions") ax1.legend(loc=1) x2 = stats.t.rvs(5, size=200) # random data, T distribution xs = np.linspace(x2.min() - 1, x2.max() + 1, 200) kde3 = stats.gaussian_kde(x2) kde4 = stats.gaussian_kde(x2, bw_method='silverman') ax2 = fig.add_subplot(212) ax2.plot(x2, np.zeros(x2.shape), 'b+', ms=12) # rug plot ax2.plot(xs, kde3(xs), 'k-', label="Scott's Rule") ax2.plot(xs, kde4(xs), 'b-', label="Silverman's Rule") ax2.plot(xs, stats.t.pdf(xs, 5), 'r--', label="True PDF") ax2.set_xlabel('x') ax2.set_ylabel('Density') plt.show()
bsd-3-clause
ywcui1990/nupic
external/linux32/lib/python2.6/site-packages/matplotlib/cm.py
70
5385
""" This module contains the instantiations of color mapping classes """ import numpy as np from numpy import ma import matplotlib as mpl import matplotlib.colors as colors import matplotlib.cbook as cbook from matplotlib._cm import * def get_cmap(name=None, lut=None): """ Get a colormap instance, defaulting to rc values if *name* is None """ if name is None: name = mpl.rcParams['image.cmap'] if lut is None: lut = mpl.rcParams['image.lut'] assert(name in datad.keys()) return colors.LinearSegmentedColormap(name, datad[name], lut) class ScalarMappable: """ This is a mixin class to support scalar -> RGBA mapping. Handles normalization and colormapping """ def __init__(self, norm=None, cmap=None): """ *norm* is an instance of :class:`colors.Normalize` or one of its subclasses, used to map luminance to 0-1. *cmap* is a :mod:`cm` colormap instance, for example :data:`cm.jet` """ self.callbacksSM = cbook.CallbackRegistry(( 'changed',)) if cmap is None: cmap = get_cmap() if norm is None: norm = colors.Normalize() self._A = None self.norm = norm self.cmap = cmap self.colorbar = None self.update_dict = {'array':False} def set_colorbar(self, im, ax): 'set the colorbar image and axes associated with mappable' self.colorbar = im, ax def to_rgba(self, x, alpha=1.0, bytes=False): '''Return a normalized rgba array corresponding to *x*. If *x* is already an rgb array, insert *alpha*; if it is already rgba, return it unchanged. If *bytes* is True, return rgba as 4 uint8s instead of 4 floats. ''' try: if x.ndim == 3: if x.shape[2] == 3: if x.dtype == np.uint8: alpha = np.array(alpha*255, np.uint8) m, n = x.shape[:2] xx = np.empty(shape=(m,n,4), dtype = x.dtype) xx[:,:,:3] = x xx[:,:,3] = alpha elif x.shape[2] == 4: xx = x else: raise ValueError("third dimension must be 3 or 4") if bytes and xx.dtype != np.uint8: xx = (xx * 255).astype(np.uint8) return xx except AttributeError: pass x = ma.asarray(x) x = self.norm(x) x = self.cmap(x, alpha=alpha, bytes=bytes) return x def set_array(self, A): 'Set the image array from numpy array *A*' self._A = A self.update_dict['array'] = True def get_array(self): 'Return the array' return self._A def get_cmap(self): 'return the colormap' return self.cmap def get_clim(self): 'return the min, max of the color limits for image scaling' return self.norm.vmin, self.norm.vmax def set_clim(self, vmin=None, vmax=None): """ set the norm limits for image scaling; if *vmin* is a length2 sequence, interpret it as ``(vmin, vmax)`` which is used to support setp ACCEPTS: a length 2 sequence of floats """ if (vmin is not None and vmax is None and cbook.iterable(vmin) and len(vmin)==2): vmin, vmax = vmin if vmin is not None: self.norm.vmin = vmin if vmax is not None: self.norm.vmax = vmax self.changed() def set_cmap(self, cmap): """ set the colormap for luminance data ACCEPTS: a colormap """ if cmap is None: cmap = get_cmap() self.cmap = cmap self.changed() def set_norm(self, norm): 'set the normalization instance' if norm is None: norm = colors.Normalize() self.norm = norm self.changed() def autoscale(self): """ Autoscale the scalar limits on the norm instance using the current array """ if self._A is None: raise TypeError('You must first set_array for mappable') self.norm.autoscale(self._A) self.changed() def autoscale_None(self): """ Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None """ if self._A is None: raise TypeError('You must first set_array for mappable') self.norm.autoscale_None(self._A) self.changed() def add_checker(self, checker): """ Add an entry to a dictionary of boolean flags that are set to True when the mappable is changed. """ self.update_dict[checker] = False def check_update(self, checker): """ If mappable has changed since the last check, return True; else return False """ if self.update_dict[checker]: self.update_dict[checker] = False return True return False def changed(self): """ Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal """ self.callbacksSM.process('changed', self) for key in self.update_dict: self.update_dict[key] = True
agpl-3.0
lfairchild/PmagPy
pmagpy/ipmag.py
1
476806
# /usr/bin/env/pythonw from past.utils import old_div import codecs import copy import numpy as np import pandas as pd from scipy import stats import random import matplotlib.pyplot as plt from matplotlib.patches import Polygon from matplotlib.pylab import polyfit import matplotlib.ticker as mtick import os import sys import time import re #from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas #from matplotlib.backends.backend_wx import NavigationToolbar2Wx from .mapping import map_magic from pmagpy import contribution_builder as cb from pmagpy import spline from pmag_env import set_env from . import pmag from . import pmagplotlib from . import data_model3 as data_model from .contribution_builder import Contribution from . import validate_upload3 as val_up3 has_basemap, Basemap = pmag.import_basemap() has_cartopy, cartopy = pmag.import_cartopy() if has_cartopy == True: import cartopy.crs as ccrs def igrf(input_list, mod='', ghfile=""): """ Determine Declination, Inclination and Intensity from the IGRF model. (http://www.ngdc.noaa.gov/IAGA/vmod/igrf.html) Parameters ---------- input_list : list with format [Date, Altitude, Latitude, Longitude] date must be in decimal year format XXXX.XXXX (Common Era) mod : desired model "" : Use the IGRF custom : use values supplied in ghfile or choose from this list ['arch3k','cals3k','pfm9k','hfm10k','cals10k.2','cals10k.1b'] where: arch3k (Korte et al., 2009) cals3k (Korte and Constable, 2011) cals10k.1b (Korte et al., 2011) pfm9k (Nilsson et al., 2014) hfm10k is the hfm.OL1.A1 of Constable et al. (2016) cals10k.2 (Constable et al., 2016) the first four of these models, are constrained to agree with gufm1 (Jackson et al., 2000) for the past four centuries gh : path to file with l m g h data Returns ------- igrf_array : array of IGRF values (0: dec; 1: inc; 2: intensity (in nT)) Examples -------- >>> local_field = ipmag.igrf([2013.6544, .052, 37.87, -122.27]) >>> local_field array([ 1.39489916e+01, 6.13532008e+01, 4.87452644e+04]) >>> ipmag.igrf_print(local_field) Declination: 13.949 Inclination: 61.353 Intensity: 48745.264 nT """ if ghfile != "": lmgh = numpy.loadtxt(ghfile) gh = [] lmgh = numpy.loadtxt(ghfile).transpose() gh.append(lmgh[2][0]) for i in range(1, lmgh.shape[1]): gh.append(lmgh[2][i]) gh.append(lmgh[3][i]) if len(gh) == 0: print('no valid gh file') return mod = 'custom' if mod == "": x, y, z, f = pmag.doigrf( input_list[3] % 360., input_list[2], input_list[1], input_list[0]) elif mod != 'custom': x, y, z, f = pmag.doigrf( input_list[3] % 360., input_list[2], input_list[1], input_list[0], mod=mod) else: x, y, z, f = pmag.docustom( input_list[3] % 360., input_list[2], input_list[1], gh) igrf_array = pmag.cart2dir((x, y, z)) return igrf_array def igrf_print(igrf_array): """ Print out Declination, Inclination, Intensity from an array returned from the igrf function. Parameters ---------- igrf_array : array that is output from ipmag.igrf function Examples -------- An array generated by the ``ipmag.igrf`` function is passed to ``ipmag.igrf_print`` >>> local_field = ipmag.igrf([2013.6544, .052, 37.87, -122.27]) >>> ipmag.igrf_print(local_field) Declination: 13.949 Inclination: 61.353 Intensity: 48745.264 nT """ print("Declination: %0.3f" % (igrf_array[0])) print("Inclination: %0.3f" % (igrf_array[1])) print("Intensity: %0.3f nT" % (igrf_array[2])) def dms2dd(degrees, minutes, seconds): """ Convert latitude/longitude of a location that is in degrees, minutes, seconds to decimal degrees Parameters ---------- degrees : degrees of latitude/longitude minutes : minutes of latitude/longitude seconds : seconds of latitude/longitude Returns ------- degrees : decimal degrees of location Examples -------- Convert 180 degrees 4 minutes 23 seconds to decimal degrees: >>> ipmag.dms2dd(180,4,23) 180.07305555555556 """ dd = float(degrees) + old_div(float(minutes), 60) + \ old_div(float(seconds), (60 * 60)) return dd def fisher_mean(dec=None, inc=None, di_block=None): """ Calculates the Fisher mean and associated parameters from either a list of declination values and a separate list of inclination values or from a di_block (a nested list a nested list of [dec,inc,1.0]). Returns a dictionary with the Fisher mean and statistical parameters. Parameters ---------- dec : list of declinations or longitudes inc : list of inclinations or latitudes di_block : a nested list of [dec,inc,1.0] A di_block can be provided instead of dec, inc lists in which case it will be used. Either dec, inc lists or a di_block need to be provided. Returns ------- fisher_mean : dictionary containing the Fisher mean parameters Examples -------- Use lists of declination and inclination to calculate a Fisher mean: >>> ipmag.fisher_mean(dec=[140,127,142,136],inc=[21,23,19,22]) {'alpha95': 7.292891411309177, 'csd': 6.4097743211340896, 'dec': 136.30838974272072, 'inc': 21.347784026899987, 'k': 159.69251473636305, 'n': 4, 'r': 3.9812138971889026} Use a di_block to calculate a Fisher mean (will give the same output as the example with the lists): >>> ipmag.fisher_mean(di_block=[[140,21],[127,23],[142,19],[136,22]]) """ if di_block is None: di_block = make_di_block(dec, inc) return pmag.fisher_mean(di_block) else: return pmag.fisher_mean(di_block) def fisher_angular_deviation(dec=None, inc=None, di_block=None, confidence=95): ''' The angle from the true mean within which a chosen percentage of directions lie can be calculated from the Fisher distribution. This function uses the calculated Fisher concentration parameter to estimate this angle from directional data. The 63 percent confidence interval is often called the angular standard deviation. Parameters ---------- dec : list of declinations or longitudes inc : list of inclinations or latitudes di_block : a nested list of [dec,inc,1.0] A di_block can be provided instead of dec, inc lists in which case it will be used. Either dec, inc lists or a di_block need to be provided. confidence : 50 percent, 63 percent or 95 percent Returns ------- theta : critical angle of interest from the mean which contains the percentage of directions specified by the confidence parameter ''' if di_block is None: di_block = make_di_block(dec, inc) mean = pmag.fisher_mean(di_block) else: mean = pmag.fisher_mean(di_block) if confidence == 50: theta = old_div(67.5, np.sqrt(mean['k'])) if confidence == 63: theta = old_div(81, np.sqrt(mean['k'])) if confidence == 95: theta = old_div(140, np.sqrt(mean['k'])) return theta def bingham_mean(dec=None, inc=None, di_block=None): """ Calculates the Bingham mean and associated statistical parameters from either a list of declination values and a separate list of inclination values or from a di_block (a nested list a nested list of [dec,inc,1.0]). Returns a dictionary with the Bingham mean and statistical parameters. Parameters ---------- dec: list of declinations inc: list of inclinations or di_block: a nested list of [dec,inc,1.0] A di_block can be provided instead of dec, inc lists in which case it will be used. Either dec, inc lists or a di_block need to passed to the function. Returns --------- bpars : dictionary containing the Bingham mean and associated statistics. Examples -------- Use lists of declination and inclination to calculate a Bingham mean: >>> ipmag.bingham_mean(dec=[140,127,142,136],inc=[21,23,19,22]) {'Edec': 220.84075754194598, 'Einc': -13.745780972597291, 'Eta': 9.9111522306938742, 'Zdec': 280.38894136954474, 'Zeta': 9.8653370276451113, 'Zinc': 64.23509410796224, 'dec': 136.32637167111312, 'inc': 21.34518678073179, 'n': 4} Use a di_block to calculate a Bingham mean (will give the same output as the example with the lists): >>> ipmag.bingham_mean(di_block=[[140,21],[127,23],[142,19],[136,22]]) """ if di_block is None: di_block = make_di_block(dec, inc) return pmag.dobingham(di_block) else: return pmag.dobingham(di_block) def kent_mean(dec=None, inc=None, di_block=None): """ Calculates the Kent mean and associated statistical parameters from either a list of declination values and a separate list of inclination values or from a di_block (a nested list a nested list of [dec,inc,1.0]). Returns a dictionary with the Kent mean and statistical parameters. Parameters ---------- dec: list of declinations inc: list of inclinations or di_block: a nested list of [dec,inc,1.0] A di_block can be provided instead of dec, inc lists in which case it will be used. Either dec, inc lists or a di_block need to passed to the function. Returns ---------- kpars : dictionary containing Kent mean and associated statistics. Examples -------- Use lists of declination and inclination to calculate a Kent mean: >>> ipmag.kent_mean(dec=[140,127,142,136],inc=[21,23,19,22]) {'Edec': 280.38683553668795, 'Einc': 64.236598921744289, 'Eta': 0.72982112760919715, 'Zdec': 40.824690028412761, 'Zeta': 6.7896823241008795, 'Zinc': 13.739412321974067, 'dec': 136.30838974272072, 'inc': 21.347784026899987, 'n': 4} Use a di_block to calculate a Kent mean (will give the same output as the example with the lists): >>> ipmag.kent_mean(di_block=[[140,21],[127,23],[142,19],[136,22]]) """ if di_block is None: di_block = make_di_block(dec, inc) return pmag.dokent(di_block, len(di_block)) else: return pmag.dokent(di_block, len(di_block)) def print_direction_mean(mean_dictionary): """ Does a pretty job printing a Fisher mean and associated statistics for directional data. Parameters ---------- mean_dictionary: output dictionary of pmag.fisher_mean Examples -------- Generate a Fisher mean using ``ipmag.fisher_mean`` and then print it nicely using ``ipmag.print_direction_mean`` >>> my_mean = ipmag.fisher_mean(di_block=[[140,21],[127,23],[142,19],[136,22]]) >>> ipmag.print_direction_mean(my_mean) Dec: 136.3 Inc: 21.3 Number of directions in mean (n): 4 Angular radius of 95% confidence (a_95): 7.3 Precision parameter (k) estimate: 159.7 """ print('Dec: ' + str(round(mean_dictionary['dec'], 1)) + ' Inc: ' + str(round(mean_dictionary['inc'], 1))) print('Number of directions in mean (n): ' + str(mean_dictionary['n'])) print('Angular radius of 95% confidence (a_95): ' + str(round(mean_dictionary['alpha95'], 1))) print('Precision parameter (k) estimate: ' + str(round(mean_dictionary['k'], 1))) def print_pole_mean(mean_dictionary): """ Does a pretty job printing a Fisher mean and associated statistics for mean paleomagnetic poles. Parameters ---------- mean_dictionary: output dictionary of pmag.fisher_mean Examples -------- Generate a Fisher mean using ``ipmag.fisher_mean`` and then print it nicely using ``ipmag.print_pole_mean`` >>> my_mean = ipmag.fisher_mean(di_block=[[140,21],[127,23],[142,19],[136,22]]) >>> ipmag.print_pole_mean(my_mean) Plon: 136.3 Plat: 21.3 Number of directions in mean (n): 4 Angular radius of 95% confidence (A_95): 7.3 Precision parameter (k) estimate: 159.7 """ print('Plon: ' + str(round(mean_dictionary['dec'], 1)) + ' Plat: ' + str(round(mean_dictionary['inc'], 1))) print('Number of directions in mean (n): ' + str(mean_dictionary['n'])) print('Angular radius of 95% confidence (A_95): ' + str(round(mean_dictionary['alpha95'], 1))) print('Precision parameter (k) estimate: ' + str(round(mean_dictionary['k'], 1))) def fishrot(k=20, n=100, dec=0, inc=90, di_block=True): """ Generates Fisher distributed unit vectors from a specified distribution using the pmag.py fshdev and dodirot functions. Parameters ---------- k : kappa precision parameter (default is 20) n : number of vectors to determine (default is 100) dec : mean declination of distribution (default is 0) inc : mean inclination of distribution (default is 90) di_block : this function returns a nested list of [dec,inc,1.0] as the default if di_block = False it will return a list of dec and a list of inc Returns --------- di_block : a nested list of [dec,inc,1.0] (default) dec, inc : a list of dec and a list of inc (if di_block = False) Examples -------- >>> ipmag.fishrot(k=20, n=5, dec=40, inc=60) [[44.766285502555775, 37.440866867657235, 1.0], [33.866315796883725, 64.732532250463436, 1.0], [47.002912770597163, 54.317853800896977, 1.0], [36.762165614432547, 56.857240672884252, 1.0], [71.43950604474395, 59.825830945715431, 1.0]] """ directions = [] declinations = [] inclinations = [] if di_block == True: for data in range(n): d, i = pmag.fshdev(k) drot, irot = pmag.dodirot(d, i, dec, inc) directions.append([drot, irot, 1.]) return directions else: for data in range(n): d, i = pmag.fshdev(k) drot, irot = pmag.dodirot(d, i, dec, inc) declinations.append(drot) inclinations.append(irot) return declinations, inclinations def tk03(n=100, dec=0, lat=0, rev='no', G2=0, G3=0): """ Generates vectors drawn from the TK03.gad model of secular variation (Tauxe and Kent, 2004) at given latitude and rotated about a vertical axis by the given declination. Return a nested list of of [dec,inc,intensity]. Parameters ---------- n : number of vectors to determine (default is 100) dec : mean declination of data set (default is 0) lat : latitude at which secular variation is simulated (default is 0) rev : if reversals are to be included this should be 'yes' (default is 'no') G2 : specify average g_2^0 fraction (default is 0) G3 : specify average g_3^0 fraction (default is 0) Returns ---------- tk_03_output : a nested list of declination, inclination, and intensity (in nT) Examples -------- >>> ipmag.tk03(n=5, dec=0, lat=0) [[14.752502674158681, -36.189370642603834, 16584.848620957589], [9.2859465437113311, -10.064247301056071, 17383.950391596223], [2.4278460589582913, 4.8079990844938019, 18243.679003572055], [352.93759572283585, 0.086693343935840397, 18524.551174838372], [352.48366219759953, 11.579098286352332, 24928.412830772766]] """ tk_03_output = [] 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, lat, lon) # send field model and lat to getvec vec[0] += dec if vec[0] >= 360.: vec[0] -= 360. if k % 2 == 0 and rev == 'yes': vec[0] += 180. vec[1] = -vec[1] tk_03_output.append([vec[0], vec[1], vec[2]]) return tk_03_output def unsquish(incs, f): """ This function applies uses a flattening factor (f) to unflatten inclination data (incs) and returns 'unsquished' values. Parameters ---------- incs : list of inclination values or a single value f : unflattening factor (between 0.0 and 1.0) Returns ---------- incs_unsquished : List of unflattened inclinations (in degrees) Examples -------- Take a list of inclinations, flatten them using ``ipmag.squish`` and then use ``ipmag.squish`` and the flattening factor to unflatten them. >>> inclinations = [43,47,41] >>> squished_incs = ipmag.squish(inclinations,0.4) >>> ipmag.unsquish(squished_incs,0.4) [43.0, 47.0, 41.0] """ try: length = len(incs) incs_unsquished = [] for n in range(0, length): inc_rad = np.deg2rad(incs[n]) # convert to radians inc_new_rad = (old_div(1., f)) * np.tan(inc_rad) # convert back to degrees inc_new = np.rad2deg(np.arctan(inc_new_rad)) incs_unsquished.append(inc_new) return incs_unsquished except: inc_rad = np.deg2rad(incs) # convert to radians inc_new_rad = (old_div(1., f)) * np.tan(inc_rad) inc_new = np.rad2deg(np.arctan(inc_new_rad)) # convert back to degrees return inc_new def squish(incs, f): """ This function applies an flattening factor (f) to inclination data (incs) and returns 'squished' values. Parameters ---------- incs : list of inclination values or a single value f : flattening factor (between 0.0 and 1.0) Returns --------- incs_squished : List of flattened directions (in degrees) Examples -------- Take a list of inclinations, flatten them. >>> inclinations = [43,47,41] >>> ipmag.squish(inclinations,0.4) [20.455818908027187, 23.216791019112204, 19.173314360172309] """ try: length = len(incs) incs_squished = [] for n in range(0, length): inc_rad = incs[n] * np.pi / 180. # convert to radians inc_new_rad = f * np.tan(inc_rad) inc_new = np.arctan(inc_new_rad) * 180. / \ np.pi # convert back to degrees incs_squished.append(inc_new) return incs_squished except: inc_rad = incs * np.pi / 180. # convert to radians inc_new_rad = f * np.tan(inc_rad) inc_new = np.arctan(inc_new_rad) * 180. / \ np.pi # convert back to degrees return inc_new def do_flip(dec=None, inc=None, di_block=None): """ This function returns the antipode (i.e. it flips) of directions. The function can take dec and inc as seperate lists if they are of equal length and explicitly specified or are the first two arguments. It will then return a list of flipped decs and a list of flipped incs. If a di_block (a nested list of [dec, inc, 1.0]) is specified then it is used and the function returns a di_block with the flipped directions. Parameters ---------- dec: list of declinations inc: list of inclinations or di_block: a nested list of [dec, inc, 1.0] A di_block can be provided instead of dec, inc lists in which case it will be used. Either dec, inc lists or a di_block need to passed to the function. Returns ---------- dec_flip, inc_flip : list of flipped declinations and inclinations or dflip : a nested list of [dec, inc, 1.0] Examples ---------- Lists of declination and inclination can be flipped to their antipodes: >>> decs = [1.0, 358.0, 2.0] >>> incs = [10.0, 12.0, 8.0] >>> ipmag.do_flip(decs, incs) ([181.0, 178.0, 182.0], [-10.0, -12.0, -8.0]) The function can also take a di_block and returns a flipped di_block: >>> directions = [[1.0,10.0],[358.0,12.0,],[2.0,8.0]] >>> ipmag.do_flip(di_block=directions) [[181.0, -10.0, 1.0], [178.0, -12.0, 1.0], [182.0, -8.0, 1.0]] """ if di_block is None: dec_flip = [] inc_flip = [] for n in range(0, len(dec)): dec_flip.append((dec[n] - 180.) % 360.0) inc_flip.append(-inc[n]) return dec_flip, inc_flip else: dflip = [] for rec in di_block: d, i = (rec[0] - 180.) % 360., -rec[1] dflip.append([d, i, 1.0]) return dflip def bootstrap_fold_test(Data, num_sims=1000, min_untilt=-10, max_untilt=120, bedding_error=0, save=False, save_folder='.', fmt='svg', ninety_nine=False): """ Conduct a bootstrap fold test (Tauxe and Watson, 1994) Three plots are generated: 1) equal area plot of uncorrected data; 2) tilt-corrected equal area plot; 3) bootstrap results showing the trend of the largest eigenvalues for a selection of the pseudo-samples (red dashed lines), the cumulative distribution of the eigenvalue maximum (green line) and the confidence bounds that enclose 95% of the pseudo-sample maxima. If the confidence bounds enclose 100% unfolding, the data "pass" the fold test. Parameters ---------- Data : a numpy array of directional data [dec, inc, dip_direction, dip] num_sims : number of bootstrap samples (default is 1000) min_untilt : minimum percent untilting applied to the data (default is -10%) max_untilt : maximum percent untilting applied to the data (default is 120%) bedding_error : (circular standard deviation) for uncertainty on bedding poles save : optional save of plots (default is False) save_folder : path to directory where plots should be saved fmt : format of figures to be saved (default is 'svg') ninety_nine : changes confidence bounds from 95 percent to 99 if True Returns ------- three plots : uncorrected data equal area plot, tilt-corrected data equal area plot, bootstrap results and CDF of the eigenvalue maximum Examples -------- Data in separate lists of dec, inc, dip_direction, dip data can be made into the needed array using the ``ipmag.make_diddd_array`` function. >>> dec = [132.5,124.3,142.7,130.3,163.2] >>> inc = [12.1,23.2,34.2,37.7,32.6] >>> dip_direction = [265.0,265.0,265.0,164.0,164.0] >>> dip = [20.0,20.0,20.0,72.0,72.0] >>> data_array = ipmag.make_diddd_array(dec,inc,dip_direction,dip) >>> data_array array([[ 132.5, 12.1, 265. , 20. ], [ 124.3, 23.2, 265. , 20. ], [ 142.7, 34.2, 265. , 20. ], [ 130.3, 37.7, 164. , 72. ], [ 163.2, 32.6, 164. , 72. ]]) This array can then be passed to the function: >>> ipmag.bootstrap_fold_test(data_array) """ if bedding_error != 0: kappa = (old_div(81., bedding_error))**2 else: kappa = 0 plt.figure(figsize=[5, 5]) plot_net(1) pmagplotlib.plot_di(1, Data) # plot directions plt.text(-1.1, 1.15, 'Geographic') if save == True: plt.savefig(os.path.join(save_folder, 'eq_geo') + '.' + fmt) D, I = pmag.dotilt_V(Data) TCs = np.array([D, I]).transpose() plt.figure(figsize=[5, 5]) plot_net(2) pmagplotlib.plot_di(2, TCs) # plot directions plt.text(-1.1, 1.15, 'Tilt-corrected') if save == True: plt.savefig(os.path.join(save_folder, 'eq_tc') + '.' + fmt) plt.show() print('doing ', num_sims, ' iterations...please be patient.....') Percs = list(range(min_untilt, max_untilt)) Cdf = [] Untilt = [] plt.figure() for n in range(num_sims): # do bootstrap data sets - plot first 25 as dashed red line # if n%50==0:print n Taus = [] # set up lists for taus PDs = pmag.pseudo(Data) if kappa != 0: for k in range(len(PDs)): d, i = pmag.fshdev(kappa) dipdir, dip = pmag.dodirot(d, i, PDs[k][2], PDs[k][3]) PDs[k][2] = dipdir PDs[k][3] = dip for perc in Percs: tilt = np.array([1., 1., 1., 0.01 * perc]) D, I = pmag.dotilt_V(PDs * tilt) TCs = np.array([D, I]).transpose() ppars = pmag.doprinc(TCs) # get principal directions Taus.append(ppars['tau1']) if n < 25: plt.plot(Percs, Taus, 'r--') # tilt that gives maximum tau Untilt.append(Percs[Taus.index(np.max(Taus))]) Cdf.append(old_div(float(n), float(num_sims))) plt.plot(Percs, Taus, 'k') plt.xlabel('% Untilting') plt.ylabel('tau_1 (red), CDF (green)') Untilt.sort() # now for CDF of tilt of maximum tau plt.plot(Untilt, Cdf, 'g') lower = int(.025 * num_sims) upper = int(.975 * num_sims) plt.axvline(x=Untilt[lower], ymin=0, ymax=1, linewidth=1, linestyle='--') plt.axvline(x=Untilt[upper], ymin=0, ymax=1, linewidth=1, linestyle='--') title = '%i - %i %s' % (Untilt[lower], Untilt[upper], 'percent unfolding') if ninety_nine is True: print('tightest grouping of vectors obtained at (99% confidence bounds):') print(int(.005 * num_sims), ' - ', int(.995 * num_sims), 'percent unfolding') print("") print('tightest grouping of vectors obtained at (95% confidence bounds):') print(title) print('range of all bootstrap samples: ') print(Untilt[0], ' - ', Untilt[-1], 'percent unfolding') plt.title(title) if save == True: plt.savefig(os.path.join(save_folder, 'bootstrap_CDF') + '.' + fmt) plt.show() def common_mean_bootstrap(Data1, Data2, NumSims=1000, save=False, save_folder='.', fmt='svg', figsize=(7, 2.3), x_tick_bins=4): """ Conduct a bootstrap test (Tauxe, 2010) for a common mean on two declination, inclination data sets. Plots are generated of the cumulative distributions of the Cartesian coordinates of the means of the pseudo-samples (one for x, one for y and one for z). If the 95 percent confidence bounds for each component overlap, the two directions are not significantly different. Parameters ---------- Data1 : a nested list of directional data [dec,inc] (a di_block) Data2 : a nested list of directional data [dec,inc] (a di_block) if Data2 is length of 1, treat as single direction NumSims : number of bootstrap samples (default is 1000) save : optional save of plots (default is False) save_folder : path to directory where plots should be saved fmt : format of figures to be saved (default is 'svg') figsize : optionally adjust figure size (default is (7, 2.3)) x_tick_bins : because they occasionally overlap depending on the data, this argument allows you adjust number of tick marks on the x axis of graphs (default is 4) Returns ------- three plots : cumulative distributions of the X, Y, Z of bootstrapped means Examples -------- Develop two populations of directions using ``ipmag.fishrot``. Use the function to determine if they share a common mean (through visual inspection of resulting plots). >>> directions_A = ipmag.fishrot(k=20, n=30, dec=40, inc=60) >>> directions_B = ipmag.fishrot(k=35, n=25, dec=42, inc=57) >>> ipmag.common_mean_bootstrap(directions_A, directions_B) """ counter = 0 BDI1 = pmag.di_boot(Data1) cart1 = pmag.dir2cart(BDI1).transpose() X1, Y1, Z1 = cart1[0], cart1[1], cart1[2] if np.array(Data2).shape[0] > 2: BDI2 = pmag.di_boot(Data2) cart2 = pmag.dir2cart(BDI2).transpose() X2, Y2, Z2 = cart2[0], cart2[1], cart2[2] else: cart = pmag.dir2cart(Data2).transpose() fignum = 1 fig = plt.figure(figsize=figsize) fig = plt.subplot(1, 3, 1) minimum = int(0.025 * len(X1)) maximum = int(0.975 * len(X1)) X1, y = pmagplotlib.plot_cdf(fignum, X1, "X component", 'r', "") bounds1 = [X1[minimum], X1[maximum]] pmagplotlib.plot_vs(fignum, bounds1, 'r', '-') if np.array(Data2).shape[0] > 2: X2, y = pmagplotlib.plot_cdf(fignum, X2, "X component", 'b', "") bounds2 = [X2[minimum], X2[maximum]] pmagplotlib.plot_vs(fignum, bounds2, 'b', '--') else: pmagplotlib.plot_vs(fignum, [cart[0]], 'k', '--') plt.ylim(0, 1) plt.locator_params(nbins=x_tick_bins) plt.subplot(1, 3, 2) Y1, y = pmagplotlib.plot_cdf(fignum, Y1, "Y component", 'r', "") bounds1 = [Y1[minimum], Y1[maximum]] pmagplotlib.plot_vs(fignum, bounds1, 'r', '-') if np.array(Data2).shape[0] > 2: Y2, y = pmagplotlib.plot_cdf(fignum, Y2, "Y component", 'b', "") bounds2 = [Y2[minimum], Y2[maximum]] pmagplotlib.plot_vs(fignum, bounds2, 'b', '--') else: pmagplotlib.plot_vs(fignum, [cart[1]], 'k', '--') plt.ylim(0, 1) plt.subplot(1, 3, 3) Z1, y = pmagplotlib.plot_cdf(fignum, Z1, "Z component", 'r', "") bounds1 = [Z1[minimum], Z1[maximum]] pmagplotlib.plot_vs(fignum, bounds1, 'r', '-') if np.array(Data2).shape[0] > 2: Z2, y = pmagplotlib.plot_cdf(fignum, Z2, "Z component", 'b', "") bounds2 = [Z2[minimum], Z2[maximum]] pmagplotlib.plot_vs(fignum, bounds2, 'b', '--') else: pmagplotlib.plot_vs(fignum, [cart[2]], 'k', '--') plt.ylim(0, 1) plt.locator_params(nbins=x_tick_bins) plt.tight_layout() if save == True: plt.savefig(os.path.join( save_folder, 'common_mean_bootstrap') + '.' + fmt) plt.show() def common_mean_watson(Data1, Data2, NumSims=5000, print_result=True, plot='no', save=False, save_folder='.', fmt='svg'): """ Conduct a Watson V test for a common mean on two directional data sets. This function calculates Watson's V statistic from input files through Monte Carlo simulation in order to test whether two populations of directional data could have been drawn from a common mean. The critical angle between the two sample mean directions and the corresponding McFadden and McElhinny (1990) classification is printed. Parameters ---------- Data1 : a nested list of directional data [dec,inc] (a di_block) Data2 : a nested list of directional data [dec,inc] (a di_block) NumSims : number of Monte Carlo simulations (default is 5000) print_result : default is to print the test result (True) plot : the default is no plot ('no'). Putting 'yes' will the plot the CDF from the Monte Carlo simulations. save : optional save of plots (default is False) save_folder : path to where plots will be saved (default is current) fmt : format of figures to be saved (default is 'svg') Returns ------- printed text : text describing the test result is printed result : a boolean where 0 is fail and 1 is pass angle : angle between the Fisher means of the two data sets critical_angle : critical angle for the test to pass Examples -------- Develop two populations of directions using ``ipmag.fishrot``. Use the function to determine if they share a common mean. >>> directions_A = ipmag.fishrot(k=20, n=30, dec=40, inc=60) >>> directions_B = ipmag.fishrot(k=35, n=25, dec=42, inc=57) >>> ipmag.common_mean_watson(directions_A, directions_B) """ pars_1 = pmag.fisher_mean(Data1) pars_2 = pmag.fisher_mean(Data2) cart_1 = pmag.dir2cart([pars_1["dec"], pars_1["inc"], pars_1["r"]]) cart_2 = pmag.dir2cart([pars_2['dec'], pars_2['inc'], pars_2["r"]]) Sw = pars_1['k'] * pars_1['r'] + pars_2['k'] * pars_2['r'] # k1*r1+k2*r2 xhat_1 = pars_1['k'] * cart_1[0] + pars_2['k'] * cart_2[0] # k1*x1+k2*x2 xhat_2 = pars_1['k'] * cart_1[1] + pars_2['k'] * cart_2[1] # k1*y1+k2*y2 xhat_3 = pars_1['k'] * cart_1[2] + pars_2['k'] * cart_2[2] # k1*z1+k2*z2 Rw = np.sqrt(xhat_1**2 + xhat_2**2 + xhat_3**2) V = 2 * (Sw - Rw) # keep weighted sum for later when determining the "critical angle" # let's save it as Sr (notation of McFadden and McElhinny, 1990) Sr = Sw # do monte carlo simulation of datasets with same kappas as data, # but a common mean counter = 0 Vp = [] # set of Vs from simulations for k in range(NumSims): # get a set of N1 fisher distributed vectors with k1, # calculate fisher stats Dirp = [] for i in range(pars_1["n"]): Dirp.append(pmag.fshdev(pars_1["k"])) pars_p1 = pmag.fisher_mean(Dirp) # get a set of N2 fisher distributed vectors with k2, # calculate fisher stats Dirp = [] for i in range(pars_2["n"]): Dirp.append(pmag.fshdev(pars_2["k"])) pars_p2 = pmag.fisher_mean(Dirp) # get the V for these Vk = pmag.vfunc(pars_p1, pars_p2) Vp.append(Vk) # sort the Vs, get Vcrit (95th percentile one) Vp.sort() k = int(.95 * NumSims) Vcrit = Vp[k] # equation 18 of McFadden and McElhinny, 1990 calculates the critical # value of R (Rwc) Rwc = Sr - (old_div(Vcrit, 2)) # following equation 19 of McFadden and McElhinny (1990) the critical # angle is calculated. If the observed angle (also calculated below) # between the data set means exceeds the critical angle the hypothesis # of a common mean direction may be rejected at the 95% confidence # level. The critical angle is simply a different way to present # Watson's V parameter so it makes sense to use the Watson V parameter # in comparison with the critical value of V for considering the test # results. What calculating the critical angle allows for is the # classification of McFadden and McElhinny (1990) to be made # for data sets that are consistent with sharing a common mean. k1 = pars_1['k'] k2 = pars_2['k'] R1 = pars_1['r'] R2 = pars_2['r'] critical_angle = np.degrees(np.arccos(old_div(((Rwc**2) - ((k1 * R1)**2) - ((k2 * R2)**2)), (2 * k1 * R1 * k2 * R2)))) D1 = (pars_1['dec'], pars_1['inc']) D2 = (pars_2['dec'], pars_2['inc']) angle = pmag.angle(D1, D2) if print_result == True: print("Results of Watson V test: ") print("") print("Watson's V: " '%.1f' % (V)) print("Critical value of V: " '%.1f' % (Vcrit)) if V < Vcrit: if print_result == True: print('"Pass": Since V is less than Vcrit, the null hypothesis') print('that the two populations are drawn from distributions') print('that share a common mean direction can not be rejected.') result = 1 elif V > Vcrit: if print_result == True: print('"Fail": Since V is greater than Vcrit, the two means can') print('be distinguished at the 95% confidence level.') result = 0 if print_result == True: print("") print("M&M1990 classification:") print("") print("Angle between data set means: " '%.1f' % (angle)) print("Critical angle for M&M1990: " '%.1f' % (critical_angle)) if print_result == True: if V > Vcrit: print("") elif V < Vcrit: if critical_angle < 5: print("The McFadden and McElhinny (1990) classification for") print("this test is: 'A'") elif critical_angle < 10: print("The McFadden and McElhinny (1990) classification for") print("this test is: 'B'") elif critical_angle < 20: print("The McFadden and McElhinny (1990) classification for") print("this test is: 'C'") else: print("The McFadden and McElhinny (1990) classification for") print("this test is: 'INDETERMINATE;") if plot == 'yes': CDF = {'cdf': 1} # pmagplotlib.plot_init(CDF['cdf'],5,5) plt.figure(figsize=(3.5, 2.5)) p1 = pmagplotlib.plot_cdf(CDF['cdf'], Vp, "Watson's V", 'r', "") p2 = pmagplotlib.plot_vs(CDF['cdf'], [V], 'g', '-') p3 = pmagplotlib.plot_vs(CDF['cdf'], [Vp[k]], 'b', '--') # pmagplotlib.draw_figs(CDF) if save == True: plt.savefig(os.path.join( save_folder, 'common_mean_watson') + '.' + fmt) pmagplotlib.show_fig(CDF['cdf']) return result, angle[0], critical_angle def reversal_test_bootstrap(dec=None, inc=None, di_block=None, plot_stereo=False, save=False, save_folder='.', fmt='svg'): """ Conduct a reversal test using bootstrap statistics (Tauxe, 2010) to determine whether two populations of directions could be from an antipodal common mean. Parameters ---------- dec: list of declinations inc: list of inclinations or di_block: a nested list of [dec,inc] A di_block can be provided in which case it will be used instead of dec, inc lists. plot_stereo : before plotting the CDFs, plot stereonet with the bidirectionally separated data (default is False) save : boolean argument to save plots (default is False) save_folder : directory where plots will be saved (default is current directory, '.') fmt : format of saved figures (default is 'svg') Returns ------- plots : Plots of the cumulative distribution of Cartesian components are shown as is an equal area plot if plot_stereo = True Examples -------- Populations of roughly antipodal directions are developed here using ``ipmag.fishrot``. These directions are combined into a single di_block given that the function determines the principal component and splits the data accordingly by polarity. >>> directions_n = ipmag.fishrot(k=20, n=30, dec=5, inc=-60) >>> directions_r = ipmag.fishrot(k=35, n=25, dec=182, inc=57) >>> directions = directions_n + directions_r >>> ipmag.reversal_test_bootstrap(di_block=directions, plot_stereo = True) Data can also be input to the function as separate lists of dec and inc. In this example, the di_block from above is split into lists of dec and inc which are then used in the function: >>> direction_dec, direction_inc, direction_moment = ipmag.unpack_di_block(directions) >>> ipmag.reversal_test_bootstrap(dec=direction_dec,inc=direction_inc, plot_stereo = True) """ if di_block is None: all_dirs = make_di_block(dec, inc) else: all_dirs = di_block directions1, directions2 = pmag.flip(all_dirs) if plot_stereo == True: # plot equal area with two modes plt.figure(num=0, figsize=(4, 4)) plot_net(0) plot_di(di_block=directions1, color='b'), plot_di(di_block=do_flip(di_block=directions2), color='r') common_mean_bootstrap(directions1, directions2, save=save, save_folder=save_folder, fmt=fmt) def reversal_test_MM1990(dec=None, inc=None, di_block=None, plot_CDF=False, plot_stereo=False, save=False, save_folder='.', fmt='svg'): """ Calculates Watson's V statistic from input files through Monte Carlo simulation in order to test whether normal and reversed populations could have been drawn from a common mean (equivalent to watsonV.py). Also provides the critical angle between the two sample mean directions and the corresponding McFadden and McElhinny (1990) classification. Parameters ---------- dec: list of declinations inc: list of inclinations or di_block: a nested list of [dec,inc] A di_block can be provided in which case it will be used instead of dec, inc lists. plot_CDF : plot the CDF accompanying the printed results (default is False) plot_stereo : plot stereonet with the bidirectionally separated data (default is False) save : boolean argument to save plots (default is False) save_folder : relative directory where plots will be saved (default is current directory, '.') fmt : format of saved figures (default is 'svg') Examples -------- Populations of roughly antipodal directions are developed here using ``ipmag.fishrot``. These directions are combined into a single di_block given that the function determines the principal component and splits the data accordingly by polarity. >>> directions_n = ipmag.fishrot(k=20, n=30, dec=5, inc=-60) >>> directions_r = ipmag.fishrot(k=35, n=25, dec=182, inc=57) >>> directions = directions_n + directions_r >>> ipmag.reversal_test_MM1990(di_block=directions, plot_stereo = True) Data can also be input to the function as separate lists of dec and inc. In this example, the di_block from above is split into lists of dec and inc which are then used in the function: >>> direction_dec, direction_inc, direction_moment = ipmag.unpack_di_block(directions) >>> ipmag.reversal_test_MM1990(dec=direction_dec,inc=direction_inc, plot_stereo = True) """ if di_block is None: all_dirs = make_di_block(dec, inc) else: all_dirs = di_block directions1, directions2 = pmag.flip(all_dirs) if plot_stereo == True: # plot equal area with two modes plt.figure(num=0, figsize=(4, 4)) plot_net(0) plot_di(di_block=directions1, color='b'), plot_di(di_block=do_flip(di_block=directions2), color='r') if plot_CDF == False: common_mean_watson(directions1, directions2, save=save, save_folder=save_folder, fmt=fmt) else: common_mean_watson(directions1, directions2, plot='yes', save=save, save_folder=save_folder, fmt=fmt) def conglomerate_test_Watson(R, n): """ The Watson (1956) test of a directional data set for randomness compares the resultant vector (R) of a group of directions to values of Ro. If R exceeds Ro, the null-hypothesis of randomness is rejected. If R is less than Ro, the null-hypothesis is considered to not be disproved. Parameters ---------- R : the resultant vector length of the directions n : the number of directions Returns ------- printed text : text describing test result result : a dictionary with the Watson (1956) R values """ Ro_values = {5: {95: 3.50, 99: 4.02}, 6: {95: 3.85, 99: 4.48}, 7: {95: 4.18, 99: 4.89}, 8: {95: 4.48, 99: 5.26}, 9: {95: 4.76, 99: 5.61}, 10: {95: 5.03, 99: 5.94}, 11: {95: 5.29, 99: 6.25}, 12: {95: 5.52, 99: 6.55}, 13: {95: 5.75, 99: 6.84}, 14: {95: 5.98, 99: 7.11}, 15: {95: 6.19, 99: 7.36}, 16: {95: 6.40, 99: 7.60}, 17: {95: 6.60, 99: 7.84}, 18: {95: 6.79, 99: 8.08}, 19: {95: 6.98, 99: 8.33}, 20: {95: 7.17, 99: 8.55}} if n < 5: print('too few directions for a conglomerate test') return elif n < 21: Ro_95 = Ro_values[n][95] Ro_99 = Ro_values[n][99] else: Ro_95 = np.sqrt(7.815*(n/3)) Ro_99 = np.sqrt(11.345*(n/3)) print('R = ' + str(R)) print('Ro_95 = ' + str(Ro_95)) print('Ro_99 = ' + str(Ro_99)) if R < Ro_95: print('This population "passes" a conglomerate test as the null hypothesis of randomness cannot be rejected at the 95% confidence level') if R > Ro_95: print( 'The null hypothesis of randomness can be rejected at the 95% confidence level') if R > Ro_99: print( 'The null hypothesis of randomness can be rejected at the 99% confidence level') result = {'n': n, 'R': R, 'Ro_95': Ro_95, 'Ro_99': Ro_99} return result def fishqq(lon=None, lat=None, di_block=None): """ Test whether a distribution is Fisherian and make a corresponding Q-Q plot. The Q-Q plot shows the data plotted against the value expected from a Fisher distribution. The first plot is the uniform plot which is the Fisher model distribution in terms of longitude (declination). The second plot is the exponential plot which is the Fisher model distribution in terms of latitude (inclination). In addition to the plots, the test statistics Mu (uniform) and Me (exponential) are calculated and compared against the critical test values. If Mu or Me are too large in comparision to the test statistics, the hypothesis that the distribution is Fisherian is rejected (see Fisher et al., 1987). Parameters: ----------- lon : longitude or declination of the data lat : latitude or inclination of the data or di_block: a nested list of [dec,inc] A di_block can be provided in which case it will be used instead of dec, inc lists. Output: ----------- dictionary containing lon : mean longitude (or declination) lat : mean latitude (or inclination) N : number of vectors Mu : Mu test statistic value for the data Mu_critical : critical value for Mu Me : Me test statistic value for the data Me_critical : critical value for Me if the data has two modes with N >=10 (N and R) two of these dictionaries will be returned Examples -------- In this example, directions are sampled from a Fisher distribution using ``ipmag.fishrot`` and then the ``ipmag.fishqq`` function is used to test whether that distribution is Fisherian: >>> directions = ipmag.fishrot(k=40, n=50, dec=200, inc=50) >>> ipmag.fishqq(di_block = directions) {'Dec': 199.73564290371894, 'Inc': 49.017612342358298, 'Me': 0.78330310031220352, 'Me_critical': 1.094, 'Mode': 'Mode 1', 'Mu': 0.69915926146177099, 'Mu_critical': 1.207, 'N': 50, 'Test_result': 'consistent with Fisherian model'} The above example passed a di_block to the function as an input. Lists of paired declination and inclination can also be used as inputs. Here the directions di_block is unpacked to separate declination and inclination lists using the ``ipmag.unpack_di_block`` functionwhich are then used as input to fishqq: >>> dec_list, inc_list = ipmag.unpack_di_block(directions) >>> ipmag.fishqq(lon=dec_list, lat=inc_list) """ if di_block is None: all_dirs = make_di_block(lon, lat) else: all_dirs = di_block ppars = pmag.doprinc(all_dirs) # get principal directions rDIs = [] nDIs = [] QQ_dict1 = {} QQ_dict2 = {} for rec in all_dirs: angle = pmag.angle([rec[0], rec[1]], [ppars['dec'], ppars['inc']]) if angle > 90.: rDIs.append(rec) else: nDIs.append(rec) if len(rDIs) >= 10 or len(nDIs) >= 10: D1, I1 = [], [] QQ = {'unf': 1, 'exp': 2} if len(nDIs) < 10: ppars = pmag.doprinc(rDIs) # get principal directions Drbar, Irbar = ppars['dec'] - 180., -ppars['inc'] Nr = len(rDIs) for di in rDIs: d, irot = pmag.dotilt( di[0], di[1], Drbar - 180., 90. - Irbar) # rotate to mean drot = d - 180. if drot < 0: drot = drot + 360. D1.append(drot) I1.append(irot) Dtit = 'Mode 2 Declinations' Itit = 'Mode 2 Inclinations' else: ppars = pmag.doprinc(nDIs) # get principal directions Dnbar, Inbar = ppars['dec'], ppars['inc'] Nn = len(nDIs) for di in nDIs: d, irot = pmag.dotilt( di[0], di[1], Dnbar - 180., 90. - Inbar) # rotate to mean drot = d - 180. if drot < 0: drot = drot + 360. D1.append(drot) I1.append(irot) Dtit = 'Mode 1 Declinations' Itit = 'Mode 1 Inclinations' plt.figure(figsize=(6, 3)) Mu_n, Mu_ncr = pmagplotlib.plot_qq_unf( QQ['unf'], D1, Dtit, subplot=True) # make plot Me_n, Me_ncr = pmagplotlib.plot_qq_exp( QQ['exp'], I1, Itit, subplot=True) # make plot plt.tight_layout() if Mu_n <= Mu_ncr and Me_n <= Me_ncr: F_n = 'consistent with Fisherian model' else: F_n = 'Fisherian model rejected' QQ_dict1['Mode'] = 'Mode 1' QQ_dict1['Dec'] = Dnbar QQ_dict1['Inc'] = Inbar QQ_dict1['N'] = Nn QQ_dict1['Mu'] = Mu_n QQ_dict1['Mu_critical'] = Mu_ncr QQ_dict1['Me'] = Me_n QQ_dict1['Me_critical'] = Me_ncr QQ_dict1['Test_result'] = F_n if len(rDIs) > 10 and len(nDIs) > 10: D2, I2 = [], [] ppars = pmag.doprinc(rDIs) # get principal directions Drbar, Irbar = ppars['dec'] - 180., -ppars['inc'] Nr = len(rDIs) for di in rDIs: d, irot = pmag.dotilt( di[0], di[1], Drbar - 180., 90. - Irbar) # rotate to mean drot = d - 180. if drot < 0: drot = drot + 360. D2.append(drot) I2.append(irot) Dtit = 'Mode 2 Declinations' Itit = 'Mode 2 Inclinations' plt.figure(figsize=(6, 3)) Mu_r, Mu_rcr = pmagplotlib.plot_qq_unf( QQ['unf'], D2, Dtit, subplot=True) # make plot Me_r, Me_rcr = pmagplotlib.plot_qq_exp( QQ['exp'], I2, Itit, subplot=True) # make plot plt.tight_layout() if Mu_r <= Mu_rcr and Me_r <= Me_rcr: F_r = 'consistent with Fisherian model' else: F_r = 'Fisherian model rejected' QQ_dict2['Mode'] = 'Mode 2' QQ_dict2['Dec'] = Drbar QQ_dict2['Inc'] = Irbar QQ_dict2['N'] = Nr QQ_dict2['Mu'] = Mu_r QQ_dict2['Mu_critical'] = Mu_rcr QQ_dict2['Me'] = Me_r QQ_dict2['Me_critical'] = Me_rcr QQ_dict2['Test_result'] = F_r if QQ_dict2: return QQ_dict1, QQ_dict2 elif QQ_dict1: return QQ_dict1 else: print('you need N> 10 for at least one mode') def lat_from_inc(inc, a95=None): """ Calculate paleolatitude from inclination using the dipole equation Required Parameter ---------- inc: (paleo)magnetic inclination in degrees Optional Parameter ---------- a95: 95% confidence interval from Fisher mean Returns ---------- if a95 is provided paleo_lat, paleo_lat_max, paleo_lat_min are returned otherwise, it just returns paleo_lat """ rad = old_div(np.pi, 180.) paleo_lat = old_div(np.arctan(0.5 * np.tan(inc * rad)), rad) if a95 is not None: paleo_lat_max = old_div( np.arctan(0.5 * np.tan((inc + a95) * rad)), rad) paleo_lat_min = old_div( np.arctan(0.5 * np.tan((inc - a95) * rad)), rad) return paleo_lat, paleo_lat_max, paleo_lat_min else: return paleo_lat def lat_from_pole(ref_loc_lon, ref_loc_lat, pole_plon, pole_plat): """ Calculate paleolatitude for a reference location based on a paleomagnetic pole Required Parameters ---------- ref_loc_lon: longitude of reference location in degrees ref_loc_lat: latitude of reference location pole_plon: paleopole longitude in degrees pole_plat: paleopole latitude in degrees """ ref_loc = (ref_loc_lon, ref_loc_lat) pole = (pole_plon, pole_plat) paleo_lat = 90 - pmag.angle(pole, ref_loc) return float(paleo_lat) def inc_from_lat(lat): """ Calculate inclination predicted from latitude using the dipole equation Parameter ---------- lat : latitude in degrees Returns ------- inc : inclination calculated using the dipole equation """ rad = old_div(np.pi, 180.) inc = old_div(np.arctan(2 * np.tan(lat * rad)), rad) return inc def plot_net(fignum): """ Draws circle and tick marks for equal area projection. """ # make the perimeter plt.figure(num=fignum) plt.clf() plt.axis("off") Dcirc = np.arange(0, 361.) Icirc = np.zeros(361, 'f') Xcirc, Ycirc = [], [] for k in range(361): XY = pmag.dimap(Dcirc[k], Icirc[k]) Xcirc.append(XY[0]) Ycirc.append(XY[1]) plt.plot(Xcirc, Ycirc, 'k') # put on the tick marks Xsym, Ysym = [], [] for I in range(10, 100, 10): XY = pmag.dimap(0., I) Xsym.append(XY[0]) Ysym.append(XY[1]) plt.plot(Xsym, Ysym, 'k+') Xsym, Ysym = [], [] for I in range(10, 90, 10): XY = pmag.dimap(90., I) Xsym.append(XY[0]) Ysym.append(XY[1]) plt.plot(Xsym, Ysym, 'k+') Xsym, Ysym = [], [] for I in range(10, 90, 10): XY = pmag.dimap(180., I) Xsym.append(XY[0]) Ysym.append(XY[1]) plt.plot(Xsym, Ysym, 'k+') Xsym, Ysym = [], [] for I in range(10, 90, 10): XY = pmag.dimap(270., I) Xsym.append(XY[0]) Ysym.append(XY[1]) plt.plot(Xsym, Ysym, 'k+') for D in range(0, 360, 10): Xtick, Ytick = [], [] for I in range(4): XY = pmag.dimap(D, I) Xtick.append(XY[0]) Ytick.append(XY[1]) plt.plot(Xtick, Ytick, 'k') plt.axis("equal") plt.axis((-1.05, 1.05, -1.05, 1.05)) def plot_XY(X=None, Y=None, sym='ro'): plt.plot(X, Y, sym) def plot_di(dec=None, inc=None, di_block=None, color='k', marker='o', markersize=20, legend='no', label='', title='', edge=''): """ Plot declination, inclination data on an equal area plot. Before this function is called a plot needs to be initialized with code that looks something like: >fignum = 1 >plt.figure(num=fignum,figsize=(10,10),dpi=160) >ipmag.plot_net(fignum) Required Parameters ----------- dec : declination being plotted inc : inclination being plotted or di_block: a nested list of [dec,inc,1.0] (di_block can be provided instead of dec, inc in which case it will be used) Optional Parameters (defaults are used if not specified) ----------- color : the default color is black. Other colors can be chosen (e.g. 'r') marker : the default marker is a circle ('o') markersize : default size is 20 label : the default label is blank ('') legend : the default is no legend ('no'). Putting 'yes' will plot a legend. edge : marker edge color - if blank, is color of marker """ X_down = [] X_up = [] Y_down = [] Y_up = [] color_down = [] color_up = [] if di_block is not None: di_lists = unpack_di_block(di_block) if len(di_lists) == 3: dec, inc, intensity = di_lists if len(di_lists) == 2: dec, inc = di_lists try: length = len(dec) for n in range(len(dec)): XY = pmag.dimap(dec[n], inc[n]) if inc[n] >= 0: X_down.append(XY[0]) Y_down.append(XY[1]) if type(color) == list: color_down.append(color[n]) else: color_down.append(color) else: X_up.append(XY[0]) Y_up.append(XY[1]) if type(color) == list: color_up.append(color[n]) else: color_up.append(color) except: XY = pmag.dimap(dec, inc) if inc >= 0: X_down.append(XY[0]) Y_down.append(XY[1]) color_down.append(color) else: X_up.append(XY[0]) Y_up.append(XY[1]) color_up.append(color) if len(X_up) > 0: plt.scatter(X_up, Y_up, facecolors='none', edgecolors=color_up, s=markersize, marker=marker, label=label) if len(X_down) > 0: plt.scatter(X_down, Y_down, facecolors=color_down, edgecolors=edge, s=markersize, marker=marker, label=label) if legend == 'yes': plt.legend(loc=2) plt.tight_layout() if title != "": plt.title(title) def plot_di_mean(dec, inc, a95, color='k', marker='o', markersize=20, label='', legend='no'): """ Plot a mean direction (declination, inclination) with alpha_95 ellipse on an equal area plot. Before this function is called, a plot needs to be initialized with code that looks something like: >fignum = 1 >plt.figure(num=fignum,figsize=(10,10),dpi=160) >ipmag.plot_net(fignum) Required Parameters ----------- dec : declination of mean being plotted inc : inclination of mean being plotted a95 : a95 confidence ellipse of mean being plotted Optional Parameters (defaults are used if not specified) ----------- color : the default color is black. Other colors can be chosen (e.g. 'r'). marker : the default is a circle. Other symbols can be chosen (e.g. 's'). markersize : the default is 20. Other sizes can be chosen. label : the default is no label. Labels can be assigned. legend : the default is no legend ('no'). Putting 'yes' will plot a legend. """ DI_dimap = pmag.dimap(dec, inc) if inc < 0: plt.scatter(DI_dimap[0], DI_dimap[1], edgecolors=color, facecolors='white', marker=marker, s=markersize, label=label) if inc >= 0: plt.scatter(DI_dimap[0], DI_dimap[1], edgecolors=color, facecolors=color, marker=marker, s=markersize, label=label) Xcirc, Ycirc = [], [] Da95, Ia95 = pmag.circ(dec, inc, a95) if legend == 'yes': plt.legend(loc=2) 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, c=color) plt.tight_layout() def plot_di_mean_bingham(bingham_dictionary, fignum=1, color='k', marker='o', markersize=20, label='', legend='no'): """ see plot_di_mean_ellipse """ plot_di_mean_ellipse(bingham_dictionary, fignum=fignum, color=color, marker=marker, markersize=markersize, label=label, legend=legend) def plot_di_mean_ellipse(dictionary, fignum=1, color='k', marker='o', markersize=20, label='', legend='no'): """ Plot a mean direction (declination, inclination) confidence ellipse. Parameters ----------- dictionary : a dictionary generated by the pmag.dobingham or pmag.dokent funcitons """ pars = [] pars.append(dictionary['dec']) pars.append(dictionary['inc']) pars.append(dictionary['Zeta']) pars.append(dictionary['Zdec']) pars.append(dictionary['Zinc']) pars.append(dictionary['Eta']) pars.append(dictionary['Edec']) pars.append(dictionary['Einc']) DI_dimap = pmag.dimap(dictionary['dec'], dictionary['inc']) if dictionary['inc'] < 0: plt.scatter(DI_dimap[0], DI_dimap[1], edgecolors=color, facecolors='white', marker=marker, s=markersize, label=label) if dictionary['inc'] >= 0: plt.scatter(DI_dimap[0], DI_dimap[1], edgecolors=color, facecolors=color, marker=marker, s=markersize, label=label) pmagplotlib.plot_ell(fignum, pars, color, 0, 1) def make_orthographic_map(central_longitude=0, central_latitude=0, figsize=(8, 8), add_land=True, land_color='tan', add_ocean=False, ocean_color='lightblue', grid_lines=True, lat_grid=[-80., -60., -30., 0., 30., 60., 80.], lon_grid=[-180., -150., -120., -90., -60., -30., 0., 30., 60., 90., 120., 150., 180.]): ''' Function creates and returns an orthographic map projection using cartopy Example ------- >>> map_axis = make_orthographic_map(central_longitude=200,central_latitude=30) Optional Parameters ----------- central_longitude : central longitude of projection (default is 0) central_latitude : central latitude of projection (default is 0) figsize : size of the figure (default is 8x8) add_land : chose whether land is plotted on map (default is true) land_color : specify land color (default is 'tan') add_ocean : chose whether land is plotted on map (default is False, change to True to plot) ocean_color : specify ocean color (default is 'lightblue') grid_lines : chose whether gird lines are plotted on map (default is true) lat_grid : specify the latitude grid (default is 30 degree spacing) lon_grid : specify the longitude grid (default is 30 degree spacing) ''' if not has_cartopy: print('-W- cartopy must be installed to run ipmag.make_orthographic_map') return fig = plt.figure(figsize=figsize) map_projection = ccrs.Orthographic( central_longitude=central_longitude, central_latitude=central_latitude) ax = plt.axes(projection=map_projection) ax.set_global() if add_ocean == True: ax.add_feature(cartopy.feature.OCEAN, zorder=0, facecolor=ocean_color) if add_land == True: ax.add_feature(cartopy.feature.LAND, zorder=0, facecolor=land_color, edgecolor='black') if grid_lines == True: ax.gridlines(xlocs=lon_grid, ylocs=lat_grid, linewidth=1, color='black', linestyle='dotted') return ax def make_mollweide_map(central_longitude=0, figsize=(8, 8), add_land=True, land_color='tan', add_ocean=False, ocean_color='lightblue', grid_lines=True, lat_grid=[-180., -150., -120., -90., -60., -30., 0., 30., 60., 90., 120., 150., 180.], lon_grid=[-180., -150., -120., -90., -60., -30., 0., 30., 60., 90., 120., 150., 180.]): ''' Function creates and returns a Mollweide map projection using cartopy Example ------- >>> map_axis = make_mollweide_map(central_longitude=200) Optional Parameters ----------- central_longitude : central longitude of projection (default is 0) central_latitude : central latitude of projection (default is 0) figsize : size of the figure (default is 8x8) add_land : chose whether land is plotted on map (default is True) land_color : specify land color (default is 'tan') add_ocean : chose whether land is plotted on map (default is False, change to True to plot) ocean_color : specify ocean color (default is 'lightblue') grid_lines : chose whether gird lines are plotted on map (default is true) lat_grid : specify the latitude grid (default is 30 degree spacing) lon_grid : specify the longitude grid (default is 30 degree spacing) ''' if not has_cartopy: print('-W- cartopy must be installed to run ipmag.make_molleweide_map') return fig = plt.figure(figsize=figsize) map_projection = ccrs.Mollweide(central_longitude=central_longitude) ax = plt.axes(projection=map_projection) if add_ocean == True: ax.add_feature(cartopy.feature.OCEAN, zorder=0, facecolor=ocean_color) if add_land == True: ax.add_feature(cartopy.feature.LAND, zorder=0, facecolor=land_color, edgecolor='black') ax.set_global() if grid_lines == True: ax.gridlines(xlocs=lon_grid, ylocs=lat_grid) return ax def make_robinson_map(central_longitude=0, figsize=(8, 8), add_land=True, land_color='tan', add_ocean=False, ocean_color='lightblue', grid_lines=True, lat_grid=[-180., -150., -120., -90., -60., -30., 0., 30., 60., 90., 120., 150., 180.], lon_grid=[-180., -150., -120., -90., -60., -30., 0., 30., 60., 90., 120., 150., 180.]): ''' Function creates and returns a Robinson map projection using cartopy Example ------- >>> map_axis = make_Robinson_map(central_longitude=200) Optional Parameters ----------- central_longitude : central longitude of projection (default is 0) central_latitude : central latitude of projection (default is 0) figsize : size of the figure (default is 8x8) add_land : chose whether land is plotted on map (default is True) land_color : specify land color (default is 'tan') add_ocean : chose whether land is plotted on map (default is False, change to True to plot) ocean_color : specify ocean color (default is 'lightblue') grid_lines : chose whether gird lines are plotted on map (default is true) lat_grid : specify the latitude grid (default is 30 degree spacing) lon_grid : specify the longitude grid (default is 30 degree spacing) ''' if not has_cartopy: print('-W- cartopy must be installed to run ipmag.make_robinson_map') return fig = plt.figure(figsize=figsize) map_projection = ccrs.Robinson(central_longitude=central_longitude) ax = plt.axes(projection=map_projection) if add_ocean == True: ax.add_feature(cartopy.feature.OCEAN, zorder=0, facecolor=ocean_color) if add_land == True: ax.add_feature(cartopy.feature.LAND, zorder=0, facecolor=land_color, edgecolor='black') ax.set_global() if grid_lines == True: ax.gridlines(xlocs=lon_grid, ylocs=lat_grid) return ax def plot_pole(map_axis, plon, plat, A95, label='', color='k', edgecolor='k', marker='o', markersize=20, legend='no'): """ This function plots a paleomagnetic pole and A95 error ellipse on a cartopy map axis. Before this function is called, a plot needs to be initialized with code such as that in the make_orthographic_map function. Example ------- >>> plon = 200 >>> plat = 60 >>> A95 = 6 >>> map_axis = make_orthographic_map(central_longitude=200,central_latitude=30) >>> plot_pole(map_axis, plon, plat, A95 ,color='red',markersize=40) Required Parameters ----------- map_axis : the name of the current map axis that has been developed using cartopy plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) A95 : the A_95 confidence ellipse of the paleomagnetic pole (in degrees) Optional Parameters (defaults are used if not specified) ----------- color : the default color is black. Other colors can be chosen (e.g. 'r') marker : the default is a circle. Other symbols can be chosen (e.g. 's') markersize : the default is 20. Other size can be chosen label : the default is no label. Labels can be assigned. legend : the default is no legend ('no'). Putting 'yes' will plot a legend. """ if not has_cartopy: print('-W- cartopy must be installed to run ipmag.plot_pole') return A95_km = A95 * 111.32 map_axis.scatter(plon, plat, marker=marker, color=color, edgecolors=edgecolor, s=markersize, label=label, zorder=101, transform=ccrs.Geodetic()) equi(map_axis, plon, plat, A95_km, color) if legend == 'yes': plt.legend(loc=2) def plot_pole_basemap(mapname, plon, plat, A95, label='', color='k', edgecolor='k', marker='o', markersize=20, legend='no'): """ This function plots a paleomagnetic pole and A95 error ellipse on whatever current map projection has been set using the basemap plotting library. Before this function is called, a plot needs to be initialized with code that looks something like: >from mpl_toolkits.basemap import Basemap >mapname = Basemap(projection='ortho',lat_0=35,lon_0=200) >plt.figure(figsize=(6, 6)) >mapname.drawcoastlines(linewidth=0.25) >mapname.fillcontinents(color='bisque',lake_color='white',zorder=1) >mapname.drawmapboundary(fill_color='white') >mapname.drawmeridians(np.arange(0,360,30)) >mapname.drawparallels(np.arange(-90,90,30)) Required Parameters ----------- mapname : the name of the current map that has been developed using basemap plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) A95 : the A_95 confidence ellipse of the paleomagnetic pole (in degrees) Optional Parameters (defaults are used if not specified) ----------- color : the default color is black. Other colors can be chosen (e.g. 'r') marker : the default is a circle. Other symbols can be chosen (e.g. 's') markersize : the default is 20. Other size can be chosen label : the default is no label. Labels can be assigned. legend : the default is no legend ('no'). Putting 'yes' will plot a legend. """ centerlon, centerlat = mapname(plon, plat) A95_km = A95 * 111.32 mapname.scatter(centerlon, centerlat, marker=marker, color=color, edgecolors=edgecolor, s=markersize, label=label, zorder=101) equi_basemap(mapname, plon, plat, A95_km, color) if legend == 'yes': plt.legend(loc=2) def plot_pole_dp_dm(map_axis, plon, plat, slon, slat, dp, dm, pole_label='pole', site_label='site', pole_color='k', pole_edgecolor='k', pole_marker='o', site_color='r', site_edgecolor='r', site_marker='s', markersize=20, legend=True): """ This function plots a paleomagnetic pole and a dp/dm confidence ellipse on a cartopy map axis. Before this function is called, a plot needs to be initialized with code such as that in the make_orthographic_map function. Example ------- >>> dec = 280 >>> inc = 45 >>> a95 = 5 >>> site_lat = 45 >>> site_lon = -100 >>> pole = pmag.dia_vgp(dec, inc, a95, site_lat, site_lon) >>> pole_lon = pole[0] >>> pole_lat = pole[1] >>> dp = pole[2] >>> dm = pole[3] >>> map_axis = make_orthographic_map(central_longitude=200,central_latitude=30) >>> plot_pole_dp_dm(map_axis,pole_lon,pole_lat,site_lon,site_lat,dp,dm) Required Parameters ----------- map_axis : the name of the current map axis that has been developed using cartopy plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) slon : the longitude of the site (in degrees E) slat : the latitude of the site (in degrees) dp : the semi-minor axis of the confidence ellipse (in degrees) dm : the semi-major axis of the confidence ellipse (in degrees) Optional Parameters (defaults are used if not specified) ----------- pole_color : the default color is black. Other colors can be chosen (e.g. 'g') site_color : the default color is red. Other colors can be chosen (e.g. 'g') pole_marker : the default is a circle. Other symbols can be chosen (e.g. 's') site_marker : the default is a square. Other symbols can be chosen (e.g. '^') markersize : the default is 20. Other size can be chosen pole_label : string that labels the pole. site_label : string that labels the site legend : the default is a legend (True). Putting False will suppress legend plotting. """ if not has_cartopy: print('-W- cartopy must be installed to run ipmag.plot_pole_dp_dm') return dp_km = dp*111.32 dm_km = dm*111.32 map_axis.scatter(plon, plat, marker=pole_marker, color=pole_color, edgecolors=pole_edgecolor, s=markersize, label=pole_label, zorder=101, transform=ccrs.Geodetic()) map_axis.scatter(slon, slat, marker=site_marker, color=site_color, edgecolors=site_edgecolor, s=markersize, label=site_label, zorder=101, transform=ccrs.Geodetic()) # the orientation of the ellipse needs to be determined using the # two laws of cosines for spherical triangles where the triangle is # A: site, B: north pole, C: paleomagnetic pole (see Fig. A.2 of Butler) site_lon_rad = np.deg2rad(slon) site_lat_rad = np.deg2rad(slat) c_rad = np.deg2rad(90-slat) pole_lon_rad = np.deg2rad(plon) pole_lat_rad = np.deg2rad(plat) a_rad = np.deg2rad(90-plat) B_rad = np.abs(pole_lon_rad-site_lon_rad) cos_b = np.cos(c_rad)*np.cos(a_rad) + np.sin(c_rad) * \ np.sin(a_rad)*np.cos(B_rad) b_rad = np.arccos(cos_b) sin_C = (np.sin(B_rad)/np.sin(b_rad))*np.sin(c_rad) C_rad = np.arcsin(sin_C) # need to make the rotation of the ellipse go the right way if slon-plon > 180: if plon >= slon and plat >= slat: C_deg = -np.abs(np.rad2deg(C_rad)) elif plon <= slon and plat >= slat: C_deg = np.abs(np.rad2deg(C_rad)) elif plon >= slon and plat <= slat: C_deg = np.abs(np.rad2deg(C_rad)) elif plon <= slon and plat <= slat: C_deg = -np.abs(np.rad2deg(C_rad)) elif slon-plon <= 180: if plon >= slon and plat >= slat: C_deg = np.abs(np.rad2deg(C_rad)) elif plon <= slon and plat >= slat: C_deg = -np.abs(np.rad2deg(C_rad)) elif plon >= slon and plat <= slat: C_deg = -np.abs(np.rad2deg(C_rad)) elif plon <= slon and plat <= slat: C_deg = np.abs(np.rad2deg(C_rad)) print(C_deg) ellipse(map_axis, plon, plat, dp_km, dm_km, C_deg) if legend == True: plt.legend(loc=2) def plot_pole_colorbar(map_axis, plon, plat, A95, colorvalue, vmin, vmax, label='', colormap='viridis', color='k', marker='o', markersize='20', alpha=1.0, legend=False): """ This function plots a paleomagnetic pole and A95 error ellipse on a cartopy map axis. The color of the pole is set by a colormap. Before this function is called, a plot needs to be initialized with code such as that in the make_orthographic_map function. Example ------- >>> plon = 200 >>> plat = 60 >>> A95 = 6 >>> pole_age = 350 >>> map_axis = make_orthographic_map(central_longitude=200,central_latitude=30) >>> plot_pole_colorbar(map_axis, plon, plat, A95 , pole_age, 0, 500,markersize=40) Required Parameters ----------- map_axis : the name of the current map axis that has been developed using cartopy plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) A95 : the A_95 confidence ellipse of the paleomagnetic pole (in degrees) colorvalue : what attribute is being used to determine the colors vmin : what is the minimum range for the colormap vmax : what is the maximum range for the colormap Optional Parameters (defaults are used if not specified) ----------- colormap : the colormap used (default is 'viridis'; others should be put as a string with quotes, e.g. 'plasma') label : a string that is the label for the paleomagnetic pole being plotted color : the color desired for the symbol outline and its A95 ellipse (default is 'k' aka black) marker : the marker shape desired for the pole mean symbol (default is 'o' aka a circle) legend : the default is no legend (False). Putting True will plot a legend. """ if not has_cartopy: print('-W- cartopy must be installed to run ipmag.plot_pole_colorbar') return A95_km = A95 * 111.32 map_axis.scatter(plon, plat, c=colorvalue, vmin=vmin, vmax=vmax, cmap=colormap, s=markersize, marker=marker, alpha=alpha, label=label, zorder=101, transform=ccrs.Geodetic()) equi(map_axis, plon, plat, A95_km, color, alpha) if legend == True: plt.legend(loc=2) def plot_poles_colorbar(map_axis, plon, plat, A95, colorvalue, vmin, vmax, colormap='viridis', color='k', marker='o', markersize='20', alpha=1.0, colorbar=True, colorbar_label='pole age (Ma)'): """ This function plots multiple paleomagnetic pole and A95 error ellipse on a cartopy map axis. The poles are colored by the defined colormap. Before this function is called, a plot needs to be initialized with code such as that in the make_orthographic_map function. Example ------- >>> Laurentia_APWP_T2012 = pd.read_csv('./data/Laurentia_Mean_APWP.txt') >>> map_axis = make_orthographic_map(central_longitude=-60,central_latitude=-60) >>> plot_poles_colorbar(map_axis,Laurentia_APWP_T2012['Plon_RM'], Laurentia_APWP_T2012['Plat_RM'], Laurentia_APWP_T2012['A95_RM'], Laurentia_APWP_T2012['Age'], 0, 540, colormap='viridis', markersize=80, color="k", alpha=1) Required Parameters ----------- map_axis : the name of the current map axis that has been developed using cartopy plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) A95 : the A_95 confidence ellipse of the paleomagnetic pole (in degrees) colorvalue : what attribute is being used to determine the colors vmin : what is the minimum range for the colormap vmax : what is the maximum range for the colormap Optional Parameters (defaults are used if not specified) ----------- colormap : the colormap used (default is 'viridis'; others should be put as a string with quotes, e.g. 'plasma') label : a string that is the label for the paleomagnetic pole being plotted color : the color desired for the symbol outline and its A95 ellipse (default is 'k' aka black) marker : the marker shape desired for the pole mean symbol (default is 'o' aka a circle) colorbar : the default is to include a colorbar (True). Putting False will make it so no legend is plotted. colorbar_label : label for the colorbar """ if not has_cartopy: print('-W- cartopy must be installed to run ipmag.plot_poles_colorbar') return for n in range(0, len(plon)): plot_pole_colorbar(map_axis, plon[n], plat[n], A95[n], colorvalue[n], vmin, vmax, colormap=colormap, color=color, marker=marker, markersize=markersize, alpha=alpha) sm = plt.cm.ScalarMappable( cmap=colormap, norm=plt.Normalize(vmin=vmin, vmax=vmax)) sm._A = [] plt.colorbar(sm, orientation='horizontal', shrink=0.8, pad=0.05, label=colorbar_label) def plot_vgp(map_axis, vgp_lon=None, vgp_lat=None, di_block=None, label='', color='k', marker='o', edge='black', markersize=20, legend=False): """ This function plots a paleomagnetic pole position on a cartopy map axis. Before this function is called, a plot needs to be initialized with code such as that in the make_orthographic_map function. Example ------- >>> vgps = fishrot(dec=200,inc=30) >>> map_axis = make_orthographic_map(central_longitude=200,central_latitude=30) >>> plot_vgp(map_axis,vgp_lon=vgp_lon_list,vgp_lat=vgp_lat_list,color='red',markersize=40) Required Parameters ----------- map_axis : the name of the current map axis that has been developed using cartopy plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) Optional Parameters (defaults are used if not specified) ----------- color : the color desired for the symbol (default is 'k' aka black) marker : the marker shape desired for the pole mean symbol (default is 'o' aka a circle) edge : the color of the edge of the marker (default is black) markersize : size of the marker in pt (default is 20) label : the default is no label. Labels can be assigned. legend : the default is no legend (False). Putting True will plot a legend. """ if not has_cartopy: print('-W- cartopy must be installed to run ipmag.plot_vgp') return if di_block != None: di_lists = unpack_di_block(di_block) if len(di_lists) == 3: vgp_lon, vgp_lat, intensity = di_lists if len(di_lists) == 2: vgp_lon, vgp_lat = di_lists map_axis.scatter(vgp_lon, vgp_lat, marker=marker, edgecolors=[edge], s=markersize, color=color, label=label, zorder=100, transform=ccrs.Geodetic()) map_axis.set_global() if legend == True: plt.legend(loc=2) def plot_vgp_basemap(mapname, vgp_lon=None, vgp_lat=None, di_block=None, label='', color='k', marker='o', markersize=20, legend='no'): """ This function plots a paleomagnetic pole on whatever current map projection has been set using the basemap plotting library. Before this function is called, a plot needs to be initialized with code that looks something like: >from mpl_toolkits.basemap import Basemap >mapname = Basemap(projection='ortho',lat_0=35,lon_0=200) >plt.figure(figsize=(6, 6)) >mapname.drawcoastlines(linewidth=0.25) >mapname.fillcontinents(color='bisque',lake_color='white',zorder=1) >mapname.drawmapboundary(fill_color='white') >mapname.drawmeridians(np.arange(0,360,30)) >mapname.drawparallels(np.arange(-90,90,30)) Required Parameters ----------- mapname : the name of the current map that has been developed using basemap plon : the longitude of the paleomagnetic pole being plotted (in degrees E) plat : the latitude of the paleomagnetic pole being plotted (in degrees) Optional Parameters (defaults are used if not specified) ----------- color : the color desired for the symbol and its A95 ellipse (default is 'k' aka black) marker : the marker shape desired for the pole mean symbol (default is 'o' aka a circle) label : the default is no label. Labels can be assigned. legend : the default is no legend ('no'). Putting 'yes' will plot a legend. """ if di_block != None: di_lists = unpack_di_block(di_block) if len(di_lists) == 3: vgp_lon, vgp_lat, intensity = di_lists if len(di_lists) == 2: vgp_lon, vgp_lat = di_lists centerlon, centerlat = mapname(vgp_lon, vgp_lat) mapname.scatter(centerlon, centerlat, marker=marker, s=markersize, color=color, label=label, zorder=100) if legend == 'yes': plt.legend(loc=2) def vgp_calc(dataframe, tilt_correction='yes', site_lon='site_lon', site_lat='site_lat', dec_is='dec_is', inc_is='inc_is', dec_tc='dec_tc', inc_tc='inc_tc'): """ This function calculates paleomagnetic poles using directional data and site location data within a pandas.DataFrame. The function adds the columns 'paleolatitude', 'vgp_lat', 'vgp_lon', 'vgp_lat_rev', and 'vgp_lon_rev' to the dataframe. The '_rev' columns allow for subsequent choice as to which polarity will be used for the VGPs. Parameters ----------- dataframe : the name of the pandas.DataFrame containing the data tilt-correction : 'yes' is the default and uses tilt-corrected data (dec_tc, inc_tc), 'no' uses data that is not tilt-corrected and is in geographic coordinates dataframe['site_lat'] : the name of the Dataframe column containing the latitude of the site dataframe['site_lon'] : the name of the Dataframe column containing the longitude of the site dataframe['inc_tc'] : the name of the Dataframe column containing the tilt-corrected inclination (used by default tilt-correction='yes') dataframe['dec_tc'] : the name of the Dataframe column containing the tilt-corrected declination (used by default tilt-correction='yes') dataframe['inc_is'] : the name of the Dataframe column containing the insitu inclination (used when tilt-correction='no') dataframe['dec_is'] : the name of the Dataframe column containing the insitu declination (used when tilt-correction='no') Returns ------- dataframe['paleolatitude'] dataframe['colatitude'] dataframe['vgp_lat'] dataframe['vgp_lon'] dataframe['vgp_lat_rev'] dataframe['vgp_lon_rev'] """ dataframe.is_copy = False if tilt_correction == 'yes': # calculate the paleolatitude/colatitude dataframe['paleolatitude'] = np.degrees( np.arctan(0.5 * np.tan(np.radians(dataframe[inc_tc])))) dataframe['colatitude'] = 90 - dataframe['paleolatitude'] # calculate the latitude of the pole dataframe['vgp_lat'] = np.degrees(np.arcsin(np.sin(np.radians(dataframe[site_lat])) * np.cos(np.radians(dataframe['colatitude'])) + np.cos(np.radians(dataframe[site_lat])) * np.sin(np.radians(dataframe['colatitude'])) * np.cos(np.radians(dataframe[dec_tc])))) # calculate the longitudinal difference between the pole and the site # (beta) dataframe['beta'] = np.degrees(np.arcsin(old_div((np.sin(np.radians(dataframe['colatitude'])) * np.sin(np.radians(dataframe[dec_tc]))), (np.cos(np.radians(dataframe['vgp_lat'])))))) # generate a boolean array (mask) to use to distinguish between the two possibilities for pole longitude # and then calculate pole longitude using the site location and # calculated beta mask = np.cos(np.radians(dataframe['colatitude'])) > np.sin( np.radians(dataframe[site_lat])) * np.sin(np.radians(dataframe['vgp_lat'])) dataframe['vgp_lon'] = np.where(mask, (dataframe[site_lon] + dataframe['beta']) % 360., (dataframe[site_lon] + 180 - dataframe['beta']) % 360.) # calculate the antipode of the poles dataframe['vgp_lat_rev'] = -dataframe['vgp_lat'] dataframe['vgp_lon_rev'] = (dataframe['vgp_lon'] - 180.) % 360. # the 'colatitude' and 'beta' columns were created for the purposes of the pole calculations # but aren't of further use and are deleted del dataframe['colatitude'] del dataframe['beta'] if tilt_correction == 'no': # calculate the paleolatitude/colatitude dataframe['paleolatitude'] = np.degrees( np.arctan(0.5 * np.tan(np.radians(dataframe[inc_is])))) dataframe['colatitude'] = 90 - dataframe['paleolatitude'] # calculate the latitude of the pole dataframe['vgp_lat'] = np.degrees(np.arcsin(np.sin(np.radians(dataframe[site_lat])) * np.cos(np.radians(dataframe['colatitude'])) + np.cos(np.radians(dataframe[site_lat])) * np.sin(np.radians(dataframe['colatitude'])) * np.cos(np.radians(dataframe[dec_is])))) # calculate the longitudinal difference between the pole and the site # (beta) dataframe['beta'] = np.degrees(np.arcsin(old_div((np.sin(np.radians(dataframe['colatitude'])) * np.sin(np.radians(dataframe[dec_is]))), (np.cos(np.radians(dataframe['vgp_lat'])))))) # generate a boolean array (mask) to use to distinguish between the two possibilities for pole longitude # and then calculate pole longitude using the site location and # calculated beta mask = np.cos(np.radians(dataframe['colatitude'])) > np.sin( np.radians(dataframe[site_lat])) * np.sin(np.radians(dataframe['vgp_lat'])) dataframe['vgp_lon'] = np.where(mask, (dataframe[site_lon] + dataframe['beta']) % 360., (dataframe[site_lon] + 180 - dataframe['beta']) % 360.) # calculate the antipode of the poles dataframe['vgp_lat_rev'] = -dataframe['vgp_lat'] dataframe['vgp_lon_rev'] = (dataframe['vgp_lon'] - 180.) % 360. # the 'colatitude' and 'beta' columns were created for the purposes of the pole calculations # but aren't of further use and are deleted del dataframe['colatitude'] del dataframe['beta'] return(dataframe) def sb_vgp_calc(dataframe, site_correction='yes', dec_tc='dec_tc', inc_tc='inc_tc'): """ This function calculates the angular dispersion of VGPs and corrects for within site dispersion (unless site_correction = 'no') to return a value S_b. The input data needs to be within a pandas Dataframe. Parameters ----------- dataframe : the name of the pandas.DataFrame containing the data the data frame needs to contain these columns: dataframe['site_lat'] : latitude of the site dataframe['site_lon'] : longitude of the site dataframe['k'] : fisher precision parameter for directions dataframe['vgp_lat'] : VGP latitude dataframe['vgp_lon'] : VGP longitude ----- the following default parameters can be changes by keyword argument ----- dataframe['inc_tc'] : tilt-corrected inclination dataframe['dec_tc'] : tilt-corrected declination plot : default is 'no', will make a plot of poles if 'yes' """ # calculate the mean from the directional data dataframe_dirs = [] for n in range(0, len(dataframe)): dataframe_dirs.append([dataframe[dec_tc][n], dataframe[inc_tc][n], 1.]) dataframe_dir_mean = pmag.fisher_mean(dataframe_dirs) # calculate the mean from the vgp data dataframe_poles = [] dataframe_pole_lats = [] dataframe_pole_lons = [] for n in range(0, len(dataframe)): dataframe_poles.append([dataframe['vgp_lon'][n], dataframe['vgp_lat'][n], 1.]) dataframe_pole_lats.append(dataframe['vgp_lat'][n]) dataframe_pole_lons.append(dataframe['vgp_lon'][n]) dataframe_pole_mean = pmag.fisher_mean(dataframe_poles) # calculate mean paleolatitude from the directional data dataframe['paleolatitude'] = lat_from_inc(dataframe_dir_mean['inc']) angle_list = [] for n in range(0, len(dataframe)): angle = pmag.angle([dataframe['vgp_lon'][n], dataframe['vgp_lat'][n]], [dataframe_pole_mean['dec'], dataframe_pole_mean['inc']]) angle_list.append(angle[0]) dataframe['delta_mean_pole'] = angle_list if site_correction == 'yes': # use eq. 2 of Cox (1970) to translate the directional precision parameter # into pole coordinates using the assumption of a Fisherian distribution in # directional coordinates and the paleolatitude as calculated from mean # inclination using the dipole equation dataframe['K'] = old_div(dataframe['k'], (0.125 * (5 + 18 * np.sin(np.deg2rad(dataframe['paleolatitude']))**2 + 9 * np.sin(np.deg2rad(dataframe['paleolatitude']))**4))) dataframe['Sw'] = old_div(81, (dataframe['K']**0.5)) summation = 0 N = 0 for n in range(0, len(dataframe)): quantity = dataframe['delta_mean_pole'][n]**2 - \ old_div(dataframe['Sw'][n]**2, dataframe['n'][n]) summation += quantity N += 1 Sb = ((old_div(1.0, (N - 1.0))) * summation)**0.5 if site_correction == 'no': summation = 0 N = 0 for n in range(0, len(dataframe)): quantity = dataframe['delta_mean_pole'][n]**2 summation += quantity N += 1 Sb = ((old_div(1.0, (N - 1.0))) * summation)**0.5 return Sb def make_di_block(dec, inc): """ Some pmag.py and ipmag.py functions require or will take a list of unit vectors [dec,inc,1.] as input. This function takes declination and inclination data and make it into such a nest list of lists. Parameters ----------- dec : list of declinations inc : list of inclinations Returns ----------- di_block : nested list of declination, inclination lists Example ----------- >>> decs = [180.3, 179.2, 177.2] >>> incs = [12.1, 13.7, 11.9] >>> ipmag.make_di_block(decs,incs) [[180.3, 12.1, 1.0], [179.2, 13.7, 1.0], [177.2, 11.9, 1.0]] """ di_block = [] for n in range(0, len(dec)): di_block.append([dec[n], inc[n], 1.0]) return di_block def unpack_di_block(di_block): """ This function unpacks a nested list of [dec,inc,mag_moment] into a list of declination values, a list of inclination values and a list of magnetic moment values. Mag_moment values are optional, while dec and inc values are required. Parameters ----------- di_block : nested list of declination, inclination lists Returns ----------- dec : list of declinations inc : list of inclinations mag_moment : list of magnetic moment (if present in di_block) Example ----------- The di_block nested lists of lists can be unpacked using the function >>> directions = [[180.3, 12.1, 1.0], [179.2, 13.7, 1.0], [177.2, 11.9, 1.0]] >>> ipmag.unpack_di_block(directions) ([180.3, 179.2, 177.2], [12.1, 13.7, 11.9], [1.0, 1.0, 1.0]) These unpacked values can be assigned to variables: >>> dec, inc, moment = ipmag.unpack_di_block(directions) """ dec_list = [] inc_list = [] moment_list = [] for n in range(0, len(di_block)): dec = di_block[n][0] inc = di_block[n][1] dec_list.append(dec) inc_list.append(inc) if len(di_block[n]) > 2: moment = di_block[n][2] moment_list.append(moment) return dec_list, inc_list, moment_list def make_diddd_array(dec, inc, dip_direction, dip): """ Some pmag.py functions such as the bootstrap fold test require a numpy array of dec, inc, dip direction, dip [dec, inc, dd, dip] as input. This function makes such an array. Parameters ----------- dec : paleomagnetic declination in degrees inc : paleomagnetic inclination in degrees dip_direction : the dip direction of bedding (in degrees between 0 and 360) dip: dip of bedding (in degrees) Returns ------- array : an array of [dec, inc, dip_direction, dip] Examples -------- Data in separate lists of dec, inc, dip_direction, dip data can be made into an array. >>> dec = [132.5,124.3,142.7,130.3,163.2] >>> inc = [12.1,23.2,34.2,37.7,32.6] >>> dip_direction = [265.0,265.0,265.0,164.0,164.0] >>> dip = [20.0,20.0,20.0,72.0,72.0] >>> data_array = ipmag.make_diddd_array(dec,inc,dip_direction,dip) >>> data_array array([[ 132.5, 12.1, 265. , 20. ], [ 124.3, 23.2, 265. , 20. ], [ 142.7, 34.2, 265. , 20. ], [ 130.3, 37.7, 164. , 72. ], [ 163.2, 32.6, 164. , 72. ]]) """ diddd_block = [] for n in range(0, len(dec)): diddd_block.append([dec[n], inc[n], dip_direction[n], dip[n]]) diddd_array = np.array(diddd_block) return diddd_array def shoot(lon, lat, azimuth, maxdist=None): """ This function enables A95 error ellipses to be drawn around paleomagnetic poles in conjunction with equi (from: http://www.geophysique.be/2011/02/20/matplotlib-basemap-tutorial-09-drawing-circles/) """ glat1 = lat * np.pi / 180. glon1 = lon * np.pi / 180. s = old_div(maxdist, 1.852) faz = azimuth * np.pi / 180. EPS = 0.00000000005 # if ((np.abs(np.cos(glat1)) < EPS) and not (np.abs(np.sin(faz)) < EPS)): #why was this ever a thing? it works fine at the north pole # raise ValueError("Only N-S courses are meaningful, starting at a pole!") a = old_div(6378.13, 1.852) f = old_div(1, 298.257223563) r = 1 - f tu = r * np.tan(glat1) sf = np.sin(faz) cf = np.cos(faz) if (cf == 0): b = 0. else: b = 2. * np.arctan2(tu, cf) cu = old_div(1., np.sqrt(1 + tu * tu)) su = tu * cu sa = cu * sf c2a = 1 - sa * sa x = 1. + np.sqrt(1. + c2a * (old_div(1., (r * r)) - 1.)) x = old_div((x - 2.), x) c = 1. - x c = old_div((x * x / 4. + 1.), c) d = (0.375 * x * x - 1.) * x tu = old_div(s, (r * a * c)) y = tu c = y + 1 while (np.abs(y - c) > EPS): sy = np.sin(y) cy = np.cos(y) cz = np.cos(b + y) e = 2. * cz * cz - 1. c = y x = e * cy y = e + e - 1. y = (((sy * sy * 4. - 3.) * y * cz * d / 6. + x) * d / 4. - cz) * sy * d + tu b = cu * cy * cf - su * sy c = r * np.sqrt(sa * sa + b * b) d = su * cy + cu * sy * cf glat2 = (np.arctan2(d, c) + np.pi) % (2 * np.pi) - np.pi c = cu * cy - su * sy * cf x = np.arctan2(sy * sf, c) c = ((-3. * c2a + 4.) * f + 4.) * c2a * f / 16. d = ((e * cy * c + cz) * sy * c + y) * sa glon2 = ((glon1 + x - (1. - c) * d * f + np.pi) % (2 * np.pi)) - np.pi baz = (np.arctan2(sa, b) + np.pi) % (2 * np.pi) glon2 *= old_div(180., np.pi) glat2 *= old_div(180., np.pi) baz *= old_div(180., np.pi) return (glon2, glat2, baz) def equi(map_axis, centerlon, centerlat, radius, color, alpha=1.0): """ This function enables A95 error ellipses to be drawn in cartopy around paleomagnetic poles in conjunction with shoot (modified from: http://www.geophysique.be/2011/02/20/matplotlib-basemap-tutorial-09-drawing-circles/). """ if not has_cartopy: print('-W- cartopy must be installed to run ipmag.equi') return glon1 = centerlon glat1 = centerlat X = [] Y = [] for azimuth in range(0, 360): glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius) X.append(glon2) Y.append(glat2) X.append(X[0]) Y.append(Y[0]) plt.plot(X[::-1], Y[::-1], color=color, transform=ccrs.Geodetic(), alpha=alpha) def equi_basemap(m, centerlon, centerlat, radius, color): """ This function enables A95 error ellipses to be drawn in basemap around paleomagnetic poles in conjunction with shoot (from: http://www.geophysique.be/2011/02/20/matplotlib-basemap-tutorial-09-drawing-circles/). """ glon1 = centerlon glat1 = centerlat X = [] Y = [] for azimuth in range(0, 360): glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius) X.append(glon2) Y.append(glat2) X.append(X[0]) Y.append(Y[0]) X, Y = m(X, Y) plt.plot(X, Y, color) def ellipse(map_axis, centerlon, centerlat, major_axis, minor_axis, angle, n=360, filled=False, **kwargs): """ This function enables general error ellipses to be drawn on the cartopy projection of the input map axis using a center and a set of major and minor axes and a rotation angle east of north. (Adapted from equi). Parameters ----------- map_axis : cartopy axis centerlon : longitude of the center of the ellipse centerlat : latitude of the center of the ellipse major_axis : Major axis of ellipse minor_axis : Minor axis of ellipse angle : angle of major axis in degrees east of north n : number of points with which to apporximate the ellipse filled : boolean specifying if the ellipse should be plotted as a filled polygon or as a set of line segments (Doesn't work right now) kwargs : any other key word arguments can be passed for the line Returns --------- The map object with the ellipse plotted on it """ if not has_cartopy: print('-W- cartopy must be installed to run ipmag.ellipse') return False angle = angle*(np.pi/180) glon1 = centerlon glat1 = centerlat X = [] Y = [] for azimuth in np.linspace(0, 360, n): az_rad = azimuth*(np.pi/180) radius = ((major_axis*minor_axis)/(((minor_axis*np.cos(az_rad-angle)) ** 2 + (major_axis*np.sin(az_rad-angle))**2)**.5)) glon2, glat2, baz = shoot(glon1, glat1, azimuth, radius) X.append((360+glon2) % 360) Y.append(glat2) X.append(X[0]) Y.append(Y[0]) if filled: ellip = np.array((X, Y)).T ellip = map_axis.projection.transform_points( ccrs.PlateCarree(), ellip[:, 0], ellip[:, 1]) poly = Polygon(ellip[:, :2], **kwargs) map_axis.add_patch(poly) else: try: map_axis.plot(X, Y, transform=ccrs.Geodetic(), **kwargs) return True except ValueError: return False def combine_magic(filenames, outfile, data_model=3, magic_table='measurements'): """ Takes a list of magic-formatted files, concatenates them, and creates a single file. Returns output filename if the operation was successful. Parameters ----------- filenames : list of MagIC formatted files outfile : name of output file data_model : data model number (2.5 or 3), default 3 magic_table : name of magic table, default 'measurements' Returns ---------- outfile name if success, False if failure """ if float(data_model) == 3.0: outfile = pmag.resolve_file_name('.', outfile) output_dir_path, file_name = os.path.split(outfile) con = cb.Contribution(output_dir_path, read_tables=[]) # make sure files actually exist filenames = [os.path.realpath(f) for f in filenames] filenames = [f for f in filenames if os.path.exists(f)] if not filenames: print("You have provided no valid file paths, so nothing will be combined".format( magic_table)) return False # figure out file type from first of files to join with open(filenames[0]) as f: file_type = f.readline().split()[1] if file_type in ['er_specimens', 'er_samples', 'er_sites', 'er_locations', 'er_ages', 'pmag_specimens', 'pmag_samples', 'pmag_sites', 'pmag_results', 'magic_measurements', 'rmag_anisotropy', 'rmag_results', 'rmag_specimens']: print( '-W- You are working in MagIC 3 but have provided a MagIC 2.5 file: {}'.format(file_type)) return False if file_type not in con.table_names: file_type = magic_table infiles = [pd.read_csv(infile, sep='\t', header=1) for infile in filenames] df = pd.concat(infiles, ignore_index=True, sort=True) # drop any fully duplicated rows df.drop_duplicates(inplace=True) con.add_magic_table(dtype=file_type, df=df) # drop any mostly empty rows IF they have duplicate index parent, child = con.get_parent_and_child(file_type) ignore_cols = [col[:-1] for col in [file_type, parent] if col] ignore_cols.extend(['software_packages', 'citations']) con.tables[file_type].drop_duplicate_rows(ignore_cols) # write table to file, use custom name res = con.write_table_to_file(file_type, custom_name=file_name) return res else: datasets = [] if not filenames: print("You must provide at least one file") return False for infile in filenames: if not os.path.isfile(infile): print("{} is not a valid file name".format(infile)) return False try: dataset, file_type = pmag.magic_read(infile) except IndexError: print('-W- Could not get records from {}'.format(infile)) print(' Skipping...') continue print("File ", infile, " read in with ", len(dataset), " records") for rec in dataset: datasets.append(rec) Recs, keys = pmag.fillkeys(datasets) if Recs: pmag.magic_write(outfile, Recs, file_type) print("All records stored in ", outfile) return outfile print("No file could be created") return False def ani_depthplot2(ani_file='rmag_anisotropy.txt', meas_file='magic_measurements.txt', samp_file='er_samples.txt', age_file=None, sum_file=None, fmt='svg', dmin=-1, dmax=-1, depth_scale='sample_core_depth', dir_path='.'): """ returns matplotlib figure with anisotropy data plotted against depth available depth scales: 'sample_composite_depth', 'sample_core_depth', or 'age' (you must provide an age file to use this option) """ pcol = 4 tint = 9 plots = 0 # format files to use full path # os.path.join(dir_path, ani_file) ani_file = pmag.resolve_file_name(ani_file, dir_path) if not os.path.isfile(ani_file): print("Could not find rmag_anisotropy type file: {}.\nPlease provide a valid file path and try again".format(ani_file)) return False, "Could not find rmag_anisotropy type file: {}.\nPlease provide a valid file path and try again".format(ani_file) # os.path.join(dir_path, meas_file) meas_file = pmag.resolve_file_name(meas_file, dir_path) if age_file: if not os.path.isfile(age_file): print( 'Warning: you have provided an invalid age file. Attempting to use sample file instead') age_file = None depth_scale = 'sample_core_depth' # os.path.join(dir_path, samp_file) samp_file = pmag.resolve_file_name(samp_file, dir_path) else: # os.path.join(dir_path, age_file) samp_file = pmag.resolve_file_name(samp_file, dir_path) depth_scale = 'age' print( 'Warning: you have provided an er_ages format file, which will take precedence over er_samples') else: samp_file = pmag.resolve_file_name(samp_file, dir_path) label = 1 if sum_file: sum_file = os.path.join(dir_path, sum_file) dmin, dmax = float(dmin), float(dmax) # get data read in isbulk = 0 # tests if there are bulk susceptibility measurements AniData, file_type = pmag.magic_read(ani_file) # read in tensor elements if not age_file: # read in sample depth info from er_sample.txt format file Samps, file_type = pmag.magic_read(samp_file) else: # read in sample age info from er_ages.txt format file Samps, file_type = pmag.magic_read(samp_file) age_unit = Samps[0]['age_unit'] for s in Samps: # change to upper case for every sample name s['er_sample_name'] = s['er_sample_name'].upper() Meas, file_type = pmag.magic_read(meas_file) # print 'meas_file', meas_file # print 'file_type', file_type if file_type == 'magic_measurements': isbulk = 1 Data = [] Bulks = [] BulkDepths = [] for rec in AniData: # look for depth record for this sample samprecs = pmag.get_dictitem(Samps, 'er_sample_name', rec['er_sample_name'].upper(), 'T') # see if there are non-blank depth data sampdepths = pmag.get_dictitem(samprecs, depth_scale, '', 'F') if dmax != -1: # fishes out records within depth bounds sampdepths = pmag.get_dictitem( sampdepths, depth_scale, dmax, 'max') sampdepths = pmag.get_dictitem( sampdepths, depth_scale, dmin, 'min') if len(sampdepths) > 0: # if there are any.... # set the core depth of this record rec['core_depth'] = sampdepths[0][depth_scale] Data.append(rec) # fish out data with core_depth if isbulk: # if there are bulk data chis = pmag.get_dictitem( Meas, 'er_specimen_name', rec['er_specimen_name'], 'T') # get the non-zero values for this specimen chis = pmag.get_dictitem( chis, 'measurement_chi_volume', '', 'F') if len(chis) > 0: # if there are any.... # put in microSI Bulks.append( 1e6 * float(chis[0]['measurement_chi_volume'])) BulkDepths.append(float(sampdepths[0][depth_scale])) if len(Bulks) > 0: # set min and max bulk values bmin = min(Bulks) bmax = max(Bulks) xlab = "Depth (m)" if len(Data) > 0: location = Data[0]['er_location_name'] else: return False, 'no data to plot' # collect the data for plotting tau V3_inc and V1_dec Depths, Tau1, Tau2, Tau3, V3Incs, P, V1Decs = [], [], [], [], [], [], [] F23s = [] Axs = [] # collect the plot ids # START HERE if len(Bulks) > 0: pcol += 1 # get all the s1 values from Data as floats s1 = pmag.get_dictkey(Data, 'anisotropy_s1', 'f') s2 = pmag.get_dictkey(Data, 'anisotropy_s2', 'f') s3 = pmag.get_dictkey(Data, 'anisotropy_s3', 'f') s4 = pmag.get_dictkey(Data, 'anisotropy_s4', 'f') s5 = pmag.get_dictkey(Data, 'anisotropy_s5', 'f') s6 = pmag.get_dictkey(Data, 'anisotropy_s6', 'f') nmeas = pmag.get_dictkey(Data, 'anisotropy_n', 'int') sigma = pmag.get_dictkey(Data, 'anisotropy_sigma', 'f') Depths = pmag.get_dictkey(Data, 'core_depth', 'f') # Ss=np.array([s1,s4,s5,s4,s2,s6,s5,s6,s3]).transpose() # make an array Ss = np.array([s1, s2, s3, s4, s5, s6]).transpose() # make an array # Ts=np.reshape(Ss,(len(Ss),3,-1)) # and re-shape to be n-length array of # 3x3 sub-arrays for k in range(len(Depths)): # tau,Evecs= pmag.tauV(Ts[k]) # get the sorted eigenvalues and eigenvectors # v3=pmag.cart2dir(Evecs[2])[1] # convert to inclination of the minimum # eigenvector fpars = pmag.dohext(nmeas[k] - 6, sigma[k], Ss[k]) V3Incs.append(fpars['v3_inc']) V1Decs.append(fpars['v1_dec']) Tau1.append(fpars['t1']) Tau2.append(fpars['t2']) Tau3.append(fpars['t3']) P.append(old_div(Tau1[-1], Tau3[-1])) F23s.append(fpars['F23']) if len(Depths) > 0: if dmax == -1: dmax = max(Depths) dmin = min(Depths) tau_min = 1 for t in Tau3: if t > 0 and t < tau_min: tau_min = t tau_max = max(Tau1) # tau_min=min(Tau3) P_max = max(P) P_min = min(P) # dmax=dmax+.05*dmax # dmin=dmin-.05*dmax main_plot = plt.figure(1, figsize=(10, 8)) # make the figure version_num = pmag.get_version() plt.figtext(.02, .01, version_num) # attach the pmagpy version number ax = plt.subplot(1, pcol, 1) # make the first column Axs.append(ax) ax.plot(Tau1, Depths, 'rs') ax.plot(Tau2, Depths, 'b^') ax.plot(Tau3, Depths, 'ko') if sum_file: core_depth_key, core_label_key, Cores = read_core_csv_file( sum_file) for core in Cores: depth = float(core[core_depth_key]) if depth > dmin and depth < dmax: plt.plot([0, 90], [depth, depth], 'b--') ax.axis([tau_min, tau_max, dmax, dmin]) ax.set_xlabel('Eigenvalues') if depth_scale == 'sample_core_depth': ax.set_ylabel('Depth (mbsf)') elif depth_scale == 'age': ax.set_ylabel('Age (' + age_unit + ')') else: ax.set_ylabel('Depth (mcd)') ax2 = plt.subplot(1, pcol, 2) # make the second column ax2.plot(P, Depths, 'rs') ax2.axis([P_min, P_max, dmax, dmin]) ax2.set_xlabel('P') ax2.set_title(location) if sum_file: for core in Cores: depth = float(core[core_depth_key]) if depth > dmin and depth < dmax: plt.plot([0, 90], [depth, depth], 'b--') Axs.append(ax2) ax3 = plt.subplot(1, pcol, 3) Axs.append(ax3) ax3.plot(V3Incs, Depths, 'ko') ax3.axis([0, 90, dmax, dmin]) ax3.set_xlabel('V3 Inclination') if sum_file: for core in Cores: depth = float(core[core_depth_key]) if depth > dmin and depth < dmax: plt.plot([0, 90], [depth, depth], 'b--') ax4 = plt.subplot(1, np.abs(pcol), 4) Axs.append(ax4) ax4.plot(V1Decs, Depths, 'rs') ax4.axis([0, 360, dmax, dmin]) ax4.set_xlabel('V1 Declination') if sum_file: for core in Cores: depth = float(core[core_depth_key]) if depth >= dmin and depth <= dmax: plt.plot([0, 360], [depth, depth], 'b--') if pcol == 4 and label == 1: plt.text(360, depth + tint, core[core_label_key]) # ax5=plt.subplot(1,np.abs(pcol),5) # Axs.append(ax5) # ax5.plot(F23s,Depths,'rs') # bounds=ax5.axis() # ax5.axis([bounds[0],bounds[1],dmax,dmin]) # ax5.set_xlabel('F_23') # ax5.semilogx() # if sum_file: # for core in Cores: # depth=float(core[core_depth_key]) # if depth>=dmin and depth<=dmax: # plt.plot([bounds[0],bounds[1]],[depth,depth],'b--') # if pcol==5 and label==1:plt.text(bounds[1],depth+tint,core[core_label_key]) # if pcol==6: if pcol == 5: # ax6=plt.subplot(1,pcol,6) ax6 = plt.subplot(1, pcol, 5) Axs.append(ax6) ax6.plot(Bulks, BulkDepths, 'bo') ax6.axis([bmin - 1, 1.1 * bmax, dmax, dmin]) ax6.set_xlabel('Bulk Susc. (uSI)') if sum_file: for core in Cores: depth = float(core[core_depth_key]) if depth >= dmin and depth <= dmax: plt.plot([0, bmax], [depth, depth], 'b--') if label == 1: plt.text(1.1 * bmax, depth + tint, core[core_label_key]) for x in Axs: # this makes the x-tick labels more reasonable - they were # overcrowded using the defaults pmagplotlib.delticks(x) fig_name = location + '_ani_depthplot.' + fmt return main_plot, fig_name else: return False, "No data to plot" def ani_depthplot(spec_file='specimens.txt', samp_file='samples.txt', meas_file='measurements.txt', site_file='sites.txt', age_file=None, sum_file=None, fmt='svg', dmin=-1, dmax=-1, depth_scale='core_depth', dir_path='.'): """ returns matplotlib figure with anisotropy data plotted against depth available depth scales: 'composite_depth', 'core_depth' or 'age' (you must provide an age file to use this option) """ if depth_scale == 'sample_core_depth': depth_scale = 'core_depth' if depth_scale == 'sample_composite_depth': depth_scale = 'composite_depth' pcol = 4 tint = 9 plots = 0 # format files to use full path meas_file = pmag.resolve_file_name(meas_file, dir_path) spec_file = pmag.resolve_file_name(spec_file, dir_path) samp_file = pmag.resolve_file_name(samp_file, dir_path) site_file = pmag.resolve_file_name(site_file, dir_path) if age_file: age_file = pmag.resolve_file_name(age_file, dir_path) if not os.path.isfile(age_file): print( 'Warning: you have provided an invalid age file. Attempting to use sample file instead') age_file = None depth_scale = 'core_depth' else: samp_file = age_file depth_scale = 'age' print( 'Warning: you have provided an ages format file, which will take precedence over samples') samp_file = pmag.resolve_file_name(samp_file, dir_path) for (ftype, fname) in [('specimen', spec_file), ('sample', samp_file), ('site', site_file)]: if not os.path.exists(fname): print("-W- This function requires a {} file to run.".format(ftype)) print(" Make sure you include one in your working directory") return False, "missing required file type: {}".format(ftype) label = 1 if sum_file: sum_file = pmag.resolve_file_name(sum_file, dir_path) dmin, dmax = float(dmin), float(dmax) # contribution dir_path = os.path.split(spec_file)[0] tables = ['measurements', 'specimens', 'samples', 'sites'] con = cb.Contribution(dir_path, read_tables=tables, custom_filenames={'measurements': meas_file, 'specimens': spec_file, 'samples': samp_file, 'sites': site_file}) con.propagate_cols(['core_depth'], 'samples', 'sites') con.propagate_location_to_specimens() # get data read in isbulk = 0 # tests if there are bulk susceptibility measurements ani_file = spec_file SampData = con.tables['samples'].df AniData = con.tables['specimens'].df # add sample into specimens (AniData) AniData = pd.merge( AniData, SampData[['sample', depth_scale]], how='inner', on='sample') # trim down AniData cond = AniData[depth_scale].astype(bool) AniData = AniData[cond] if dmin != -1: AniData = AniData[AniData[depth_scale] < dmax] if dmax != -1: AniData = AniData[AniData[depth_scale] > dmin] AniData['core_depth'] = AniData[depth_scale] if not age_file: Samps = con.tables['samples'].convert_to_pmag_data_list() else: con.add_magic_table(dtype='ages', fname=age_file) Samps = con.tables['ages'].convert_to_pmag_data_list() # get age unit age_unit = con.tables['ages'].df['age_unit'][0] # propagate ages down to sample level for s in Samps: # change to upper case for every sample name s['sample'] = s['sample'].upper() if 'measurements' in con.tables: isbulk = 1 Meas = con.tables['measurements'].df # convert_to_pmag_data_list() if isbulk: Meas = Meas[Meas['specimen'].astype('bool')] Meas = Meas[Meas['susc_chi_volume'].astype(bool)] # add core_depth into Measurements dataframe Meas = pd.merge(Meas[['susc_chi_volume', 'specimen']], AniData[[ 'specimen', 'core_depth']], how='inner', on='specimen') Bulks = list(Meas['susc_chi_volume'] * 1e6) BulkDepths = list(Meas['core_depth']) else: Bulks, BulkDepths = [], [] # now turn Data from pandas dataframe to a list of dicts Data = list(AniData.T.apply(dict)) if len(Bulks) > 0: # set min and max bulk values bmin = min(Bulks) bmax = max(Bulks) xlab = "Depth (m)" # if len(Data) > 0: location = Data[0].get('location', 'unknown') if cb.is_null(location): location = 'unknown' try: location = con.tables['sites'].df['location'][0] except KeyError: pass else: return False, 'no data to plot' # collect the data for plotting tau V3_inc and V1_dec Depths, Tau1, Tau2, Tau3, V3Incs, P, V1Decs = [], [], [], [], [], [], [] F23s = [] Axs = [] # collect the plot ids # START HERE if len(Bulks) > 0: pcol += 1 Data = pmag.get_dictitem(Data, 'aniso_s', '', 'not_null') # get all the s1 values from Data as floats aniso_s = pmag.get_dictkey(Data, 'aniso_s', '') aniso_s = [a.split(':') for a in aniso_s if a is not None] #print('aniso_s', aniso_s) s1 = [float(a[0]) for a in aniso_s] s2 = [float(a[1]) for a in aniso_s] s3 = [float(a[2]) for a in aniso_s] s4 = [float(a[3]) for a in aniso_s] s5 = [float(a[4]) for a in aniso_s] s6 = [float(a[5]) for a in aniso_s] # we are good with s1 - s2 nmeas = pmag.get_dictkey(Data, 'aniso_s_n_measurements', 'int') sigma = pmag.get_dictkey(Data, 'aniso_s_sigma', 'f') Depths = pmag.get_dictkey(Data, 'core_depth', 'f') # Ss=np.array([s1,s4,s5,s4,s2,s6,s5,s6,s3]).transpose() # make an array Ss = np.array([s1, s2, s3, s4, s5, s6]).transpose() # make an array # Ts=np.reshape(Ss,(len(Ss),3,-1)) # and re-shape to be n-length array of # 3x3 sub-arrays for k in range(len(Depths)): # tau,Evecs= pmag.tauV(Ts[k]) # get the sorted eigenvalues and eigenvectors # v3=pmag.cart2dir(Evecs[2])[1] # convert to inclination of the minimum # eigenvector fpars = pmag.dohext(nmeas[k] - 6, sigma[k], Ss[k]) V3Incs.append(fpars['v3_inc']) V1Decs.append(fpars['v1_dec']) Tau1.append(fpars['t1']) Tau2.append(fpars['t2']) Tau3.append(fpars['t3']) P.append(old_div(Tau1[-1], Tau3[-1])) F23s.append(fpars['F23']) if len(Depths) > 0: if dmax == -1: dmax = max(Depths) dmin = min(Depths) tau_min = 1 for t in Tau3: if t > 0 and t < tau_min: tau_min = t tau_max = max(Tau1) # tau_min=min(Tau3) P_max = max(P) P_min = min(P) # dmax=dmax+.05*dmax # dmin=dmin-.05*dmax main_plot = plt.figure(1, figsize=(11, 7)) # make the figure # main_plot = plt.figure(1, figsize=(10, 8)) # make the figure version_num = pmag.get_version() plt.figtext(.02, .01, version_num) # attach the pmagpy version number ax = plt.subplot(1, pcol, 1) # make the first column Axs.append(ax) ax.plot(Tau1, Depths, 'rs') ax.plot(Tau2, Depths, 'b^') ax.plot(Tau3, Depths, 'ko') if sum_file: core_depth_key, core_label_key, Cores = read_core_csv_file( sum_file) for core in Cores: try: depth = float(core[core_depth_key]) except ValueError: continue if depth > dmin and depth < dmax: plt.plot([0, 90], [depth, depth], 'b--') ax.axis([tau_min, tau_max, dmax, dmin]) ax.set_xlabel('Eigenvalues') if depth_scale == 'core_depth': ax.set_ylabel('Depth (mbsf)') elif depth_scale == 'age': ax.set_ylabel('Age (' + age_unit + ')') else: ax.set_ylabel('Depth (mcd)') ax2 = plt.subplot(1, pcol, 2) # make the second column ax2.plot(P, Depths, 'rs') ax2.axis([P_min, P_max, dmax, dmin]) ax2.set_xlabel('P') ax2.set_title(location) if sum_file: for core in Cores: try: depth = float(core[core_depth_key]) except ValueError: continue if depth > dmin and depth < dmax: plt.plot([0, 90], [depth, depth], 'b--') Axs.append(ax2) ax3 = plt.subplot(1, pcol, 3) Axs.append(ax3) ax3.plot(V3Incs, Depths, 'ko') ax3.axis([0, 90, dmax, dmin]) ax3.set_xlabel('V3 Inclination') if sum_file: for core in Cores: try: depth = float(core[core_depth_key]) except ValueError: continue if depth > dmin and depth < dmax: plt.plot([0, 90], [depth, depth], 'b--') ax4 = plt.subplot(1, np.abs(pcol), 4) Axs.append(ax4) ax4.plot(V1Decs, Depths, 'rs') ax4.axis([0, 360, dmax, dmin]) ax4.set_xlabel('V1 Declination') if sum_file: for core in Cores: try: depth = float(core[core_depth_key]) except ValueError: continue if depth >= dmin and depth <= dmax: plt.plot([0, 360], [depth, depth], 'b--') if pcol == 4 and label == 1: plt.text(360, depth + tint, core[core_label_key]) # ax5=plt.subplot(1,np.abs(pcol),5) # Axs.append(ax5) # ax5.plot(F23s,Depths,'rs') # bounds=ax5.axis() # ax5.axis([bounds[0],bounds[1],dmax,dmin]) # ax5.set_xlabel('F_23') # ax5.semilogx() # if sum_file: # for core in Cores: # depth=float(core[core_depth_key]) # if depth>=dmin and depth<=dmax: # plt.plot([bounds[0],bounds[1]],[depth,depth],'b--') # if pcol==5 and label==1:plt.text(bounds[1],depth+tint,core[core_label_key]) # if pcol==6: if pcol == 5: # ax6=plt.subplot(1,pcol,6) ax6 = plt.subplot(1, pcol, 5) Axs.append(ax6) ax6.plot(Bulks, BulkDepths, 'bo') ax6.axis([bmin - 1, 1.1 * bmax, dmax, dmin]) ax6.set_xlabel('Bulk Susc. (uSI)') if sum_file: for core in Cores: try: depth = float(core[core_depth_key]) except ValueError: continue if depth >= dmin and depth <= dmax: plt.plot([0, bmax], [depth, depth], 'b--') if label == 1: plt.text(1.1 * bmax, depth + tint, core[core_label_key]) for x in Axs: # this makes the x-tick labels more reasonable - they were # overcrowded using the defaults pmagplotlib.delticks(x) fig_name = location + '_ani_depthplot.' + fmt return main_plot, fig_name else: return False, "No data to plot" def core_depthplot(input_dir_path='.', meas_file='measurements.txt', spc_file='', samp_file='', age_file='', sum_file='', wt_file='', depth_scale='core_depth', dmin=-1, dmax=-1, sym='bo', size=5, spc_sym='ro', spc_size=5, meth='', step=0, fmt='svg', pltDec=True, pltInc=True, pltMag=True, pltLine=True, pltSus=True, logit=False, pltTime=False, timescale=None, amin=-1, amax=-1, norm=False, data_model_num=3): """ depth scale can be 'sample_core_depth' or 'sample_composite_depth' if age file is provided, depth_scale will be set to 'age' by defaula """ #print('input_dir_path', input_dir_path, 'meas_file', meas_file, 'spc_file', spc_file) #print('samp_file', samp_file, 'age_file', age_file, 'depth_scale', depth_scale) #print('dmin', dmin, 'dmax', dmax, 'sym', sym, 'size', size, 'spc_sym', spc_sym, 'spc_size', spc_size) #print('meth', meth, 'step', step, 'fmt', fmt, 'pltDec', pltDec, 'pltInc', pltInc, 'pltMag', pltMag) #print('pltLine', pltLine, 'pltSus', pltSus, 'logit', logit, 'timescale', timescale, 'amin', amin, 'amax', amax) # print 'pltTime', pltTime # print 'norm', norm data_model_num = int(data_model_num) # replace MagIC 3 defaults with MagIC 2.5 defaults if needed if data_model_num == 2 and meas_file == 'measurements.txt': meas_file = 'magic_measurements.txt' if data_model_num == 2 and samp_file == 'samples.txt': samp_file = 'er_samples.txt' if data_model_num == 2 and age_file == 'ages.txt': age_file = 'er_ages.txt' if data_model_num == 2 and depth_scale == "core_depth": depth_scale = "sample_core_depth" # initialize MagIC 3.0 vs 2.5 column names loc_col_name = "location" if data_model_num == 3 else "er_location_name" site_col_name = "site" if data_model_num == 3 else "er_site_name" samp_col_name = "sample" if data_model_num == 3 else "er_sample_name" spec_col_name = "specimen" if data_model_num == 3 else "er_specimen_name" meth_col_name = "method_codes" if data_model_num == 3 else "magic_method_codes" spec_dec_col_name = "dir_dec" if data_model_num == 3 else "specimen_dec" spec_inc_col_name = "dir_inc" if data_model_num == 3 else "specimen_inc" avg_weight_col_name = "weight" if data_model_num == 3 else "average_weight" spec_weight_col_name = "weight" if data_model_num == 3 else "specimen_weight" age_col_name = "age" if data_model_num == 3 else "average_age" height_col_name = "height" if data_model_num == 3 else "average_height" average_dec_col_name = "dir_dec" if data_model_num == 3 else "average_dec" average_inc_col_name = "dir_inc" if data_model_num == 3 else "average_inc" # initialize other variables width = 10 Ssym, Ssize = 'cs', 5 pcol = 3 pel = 3 maxInt = -1000 minInt = 1e10 maxSuc = -1000 minSuc = 10000 main_plot = None if size: size = int(size) if spc_size: spc_size = int(spc_size) title, location = "", "" # file formats not supported for the moment ngr_file = "" # nothing needed, not implemented fully in original script suc_file = "" # nothing else needed, also was not implemented in original script res_file = "" # need also res_sym, res_size wig_file = "" # if wig_file: pcol+=1; width+=2 # which plots to make if not pltDec: pcol -= 1 pel -= 1 width -= 2 if not pltInc: pcol -= 1 pel -= 1 width -= 2 if not pltMag: pcol -= 1 pel -= 1 width -= 2 # method and step if not step or meth == 'LT-NO': step = 0 method = 'LT-NO' elif meth == "AF": step = round(float(step) * 1e-3, 6) method = 'LT-AF-Z' elif meth == 'T': step = round(float(step) + 273, 6) method = 'LT-T-Z' elif meth == 'ARM': method = 'LT-AF-I' step = round(float(step) * 1e-3, 6) elif meth == 'IRM': method = 'LT-IRM' step = round(float(step) * 1e-3, 6) # not supporting susceptibility at the moment LJ elif meth == 'X': method = 'LP-X' pcol += 1 ind = sys.argv.index('-LP') if sys.argv[ind+2] == 'mass': if data_model_num != 3: suc_key = 'measurement_chi_mass' else: suc_key = 'susc_chi_mass' elif sys.argv[ind+2] == 'vol': if data_model_num != 3: suc_key = 'measurement_chi_volume' else: suc_key = 'susc_chi_volume' else: print('error in susceptibility units') return False, 'error in susceptibility units' else: print('method: {} not supported'.format(meth)) return False, 'method: "{}" not supported'.format(meth) if wt_file: norm = True if dmin and dmax: dmin, dmax = float(dmin), float(dmax) else: dmin, dmax = -1, -1 if pltTime: amin = float(amin) amax = float(amax) pcol += 1 width += 2 if not (amax and timescale): return False, "To plot time, you must provide amin, amax, and timescale" # # # read in 3.0 data and translate to 2.5 if meas_file: meas_file = pmag.resolve_file_name(meas_file, input_dir_path) if spc_file: spc_file = pmag.resolve_file_name(spc_file, input_dir_path) if samp_file: samp_file = pmag.resolve_file_name(samp_file, input_dir_path) if age_file: age_file = pmag.resolve_file_name(age_file, input_dir_path) if data_model_num == 3: fnames = {'specimens': spc_file, 'samples': samp_file, 'ages': age_file, 'measurements': meas_file} fnames = {k: v for (k, v) in fnames.items() if v} con = cb.Contribution(input_dir_path, custom_filenames=fnames) for dtype in ['measurements', 'specimens']: if dtype not in con.tables: print( '-E- You must have a {} file in your input directory ({}) to run core_depthplot'.format(dtype, input_dir_path)) print(' If needed, you can specify your input directory on the command line with "core_depthplot.py -ID dirname ... "') print(' Or with ipmag.core_depthplot(input_dir_path=dirname, ...)') # return False, '-E- You must have a {} file in your input directory ({}) to run core_depthplot'.format(dtype, input_dir_path) # propagate data to measurements con.propagate_name_down('sample', 'measurements') con.propagate_name_down('site', 'measurements') con.propagate_location_to_measurements() # propagate depth info from sites --> samples con.propagate_cols( ['core_depth', 'composite_depth'], 'samples', 'sites') if age_file == "": # get sample data straight from the contribution Samps = [] if 'samples' in con.tables: Samps = con.tables['samples'].convert_to_pmag_data_list() else: depth_scale = 'age' Samps = [] # get age data from contribution if 'ages' in con.tables: # we need to get sample in here # this doesn't do the trick by itself con.propagate_ages() con.propagate_cols(['age', 'age_unit'], 'samples', 'sites') Samps = con.tables['samples'].convert_to_pmag_data_list() age_unit = "" if spc_file: Specs3 = [] # get specimen data from contribution Specs = [] if 'specimens' in con.tables: Specs = con.tables['specimens'].convert_to_pmag_data_list() if res_file: warn = '-W- result file option is not currently available for MagIC data model 3' print(warn) return False, warn #Results, file_type = pmag.magic_read(res_file) if norm: #warn = '-W- norm option is not currently available for MagIC data model 3' # print(warn) # return False, warn Specs3, file_type = pmag.magic_read(wt_file) # translate specimen records to 2.5 ErSpecs = [] # for spec in Specs3: # ErSpecs.append(map_magic.mapping(spec, spec_magic3_2_magic2_map)) ErSpecs = Specs3 print(len(ErSpecs), ' specimens read in from ', wt_file) if not os.path.isfile(spc_file): if not os.path.isfile(meas_file): return False, "You must provide either a magic_measurements file or a pmag_specimens file" if not age_file and not samp_file: print('-W- You must provide either an age file or a sample file') return False, '-W- You must provide either an age file or a sample file' # read in 2.5 data elif data_model_num == 2: if age_file == "": if samp_file: samp_file = os.path.join(input_dir_path, samp_file) Samps, file_type = pmag.magic_read(samp_file) else: depth_scale = 'age' if age_file: age_file = os.path.join(input_dir_path, age_file) Samps, file_type = pmag.magic_read(age_file) age_unit = "" if spc_file: Specs, file_type = pmag.magic_read(spc_file) if res_file: Results, file_type = pmag.magic_read(res_file) if norm: ErSpecs, file_type = pmag.magic_read(wt_file) print(len(ErSpecs), ' specimens read in from ', wt_file) if not os.path.isfile(spc_file): if not os.path.isfile(meas_file): return False, "You must provide either a magic_measurements file or a pmag_specimens file" else: return False, "Invalid data model number: {}".format(str(data_model_num)) Cores = [] core_depth_key = "Top depth cored CSF (m)" if sum_file: # os.path.join(input_dir_path, sum_file) sum_file = pmag.resolve_file_name(sum_file, input_dir_path) with open(sum_file, 'r') as fin: indat = fin.readlines() if "Core Summary" in indat[0]: headline = 1 else: headline = 0 keys = indat[headline].replace('\n', '').split(',') if "Core Top (m)" in keys: core_depth_key = "Core Top (m)" if "Top depth cored CSF (m)" in keys: core_dpeth_key = "Top depth cored CSF (m)" if "Core Label" in keys: core_label_key = "Core Label" if "Core label" in keys: core_label_key = "Core label" for line in indat[2:]: if 'TOTALS' not in line: CoreRec = {} for k in range(len(keys)): CoreRec[keys[k]] = line.split(',')[k] Cores.append(CoreRec) if len(Cores) == 0: print('no Core depth information available: import core summary file') sum_file = "" Data = [] if 'core_depth' in depth_scale or depth_scale == 'mbsf': ylab = "Depth (mbsf)" depth_scale = 'core_depth' elif depth_scale == 'age': ylab = "Age" elif 'composite_depth' in depth_scale or depth_scale == 'mcd': ylab = "Depth (mcd)" depth_scale = 'composite_depth' else: print('Warning: You have provided unsupported depth scale: {}.\nUsing default (mbsf) instead.'.format( depth_scale)) depth_scale = 'core_depth' ylab = "Depth (mbsf)" # fix depth scale for data model 2 if needed if data_model_num == 2 and not depth_scale.startswith('sample_'): if depth_scale != "age": depth_scale = "sample_" + depth_scale # collect the data for plotting declination Depths, Decs, Incs, Ints = [], [], [], [] SDepths, SDecs, SIncs, SInts = [], [], [], [] SSucs = [] samples = [] methods, steps, m2 = [], [], [] if os.path.isfile(meas_file): # plot the bulk measurement data if data_model_num == 3: Meas = [] if 'measurements' in con.tables: Meas = con.tables['measurements'].convert_to_pmag_data_list() # has measurement_magn_mass .... dec_key, inc_key = 'dir_dec', 'dir_inc' meth_key, temp_key, ac_key, dc_key = 'method_codes', 'treat_temp', 'treat_ac_field', 'treat_dc_field' intlist = ['magnitude', 'magn_moment', 'magn_volume', 'magn_mass'] meas_key = "magn_moment" elif data_model_num == 2: intlist = ['measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume', 'measurement_magn_mass'] temp_key, ac_key, dc_key = 'treatment_temp', 'treatment_ac_field', 'treatment_dc_field' dec_key, inc_key = 'measurement_dec', 'measurement_inc' Meas, file_type = pmag.magic_read(meas_file) meas_key = 'measurement_magn_moment' # print(len(Meas), ' measurements read in from ', meas_file) # for m in intlist: # find the intensity key with data # get all non-blank data for this specimen meas_data = pmag.get_dictitem(Meas, m, '', 'F') if len(meas_data) > 0: print('using intensity key:', m) meas_key = m break # fish out the desired method code m1 = pmag.get_dictitem(Meas, meth_col_name, method, 'has') if method == 'LT-T-Z': m2 = pmag.get_dictitem(m1, temp_key, str( step), 'eval') # fish out the desired step elif 'LT-AF' in method: m2 = pmag.get_dictitem(m1, ac_key, str(step), 'eval') elif 'LT-IRM' in method: m2 = pmag.get_dictitem(m1, dc_key, str(step), 'eval') elif 'LP-X' in method: m2 = pmag.get_dictitem(m1, suc_key, '', 'F') if len(m2) > 0: for rec in m2: # fish out depths and weights D = pmag.get_dictitem( Samps, samp_col_name, rec[samp_col_name], 'T') if not D: # if using an age_file, you may need to sort by site D = pmag.get_dictitem( Samps, site_col_name, rec[site_col_name], 'T') depth = pmag.get_dictitem(D, depth_scale, '', 'F') if len(depth) > 0: if ylab == 'Age': # get units of ages - assume they are all the same! ylab = ylab + ' (' + depth[0]['age_unit'] + ')' rec[depth_scale] = float(depth[0][depth_scale]) rec[meth_col_name] = rec[meth_col_name] + \ ':' + depth[0][meth_col_name] if norm: specrecs = pmag.get_dictitem( ErSpecs, spec_col_name, rec[spec_col_name], 'T') specwts = pmag.get_dictitem( specrecs, spec_weight_col_name, "", 'F') if len(specwts) > 0: rec[weight_col_name] = specwts[0][spec_weight_col_name] # fish out data with core_depth and (if needed) # weights Data.append(rec) else: # fish out data with core_depth and (if needed) weights Data.append(rec) if title == "": pieces = rec[samp_col_name].split('-') location = rec.get(loc_col_name, '') title = location SData = pmag.sort_diclist(Data, depth_scale) for rec in SData: # fish out bulk measurement data from desired depths if dmax == -1 or float(rec[depth_scale]) < dmax and float(rec[depth_scale]) > dmin: Depths.append((rec[depth_scale])) if method == "LP-X": SSucs.append(float(rec[suc_key])) else: if pltDec: Decs.append(float(rec[dec_key])) if pltInc: Incs.append(float(rec[inc_key])) if not norm and pltMag: Ints.append(float(rec[meas_key])) if norm and pltMag: Ints.append( float(rec[meas_key]) / float(rec[spec_weight_col_name])) if len(SSucs) > 0: maxSuc = max(SSucs) minSuc = min(SSucs) if len(Ints) > 1: maxInt = max(Ints) minInt = min(Ints) if len(Depths) == 0: print('no bulk measurement data matched your request') else: print(len(Depths), "depths found") SpecDepths, SpecDecs, SpecIncs = [], [], [] FDepths, FDecs, FIncs = [], [], [] if spc_file: # add depths to spec data # get all the discrete data with best fit lines BFLs = pmag.get_dictitem(Specs, meth_col_name, 'DE-BFL', 'has') for spec in BFLs: if location == "": location = spec.get(loc_col_name, "") samp = pmag.get_dictitem( Samps, samp_col_name, spec[samp_col_name], 'T') if len(samp) > 0 and depth_scale in list(samp[0].keys()) and samp[0][depth_scale] != "": if ylab == 'Age': # get units of ages - assume they are all the same! ylab = ylab + ' (' + samp[0]['age_unit'] + ')' # filter for depth if dmax == -1 or float(samp[0][depth_scale]) < dmax and float(samp[0][depth_scale]) > dmin: # fish out data with core_depth SpecDepths.append(float(samp[0][depth_scale])) # fish out data with core_depth SpecDecs.append(float(spec[spec_dec_col_name])) # fish out data with core_depth SpecIncs.append(float(spec[spec_inc_col_name])) else: print('no core_depth found for: ', spec[spec_col_name]) # get all the discrete data with best fit lines FMs = pmag.get_dictitem(Specs, meth_col_name, 'DE-FM', 'has') for spec in FMs: if location == "": location = spec.get(loc_col_name, "") samp = pmag.get_dictitem( Samps, samp_col_name, spec[samp_col_name], 'T') if len(samp) > 0 and depth_scale in list(samp[0].keys()) and samp[0][depth_scale] != "": if ylab == 'Age': # get units of ages - assume they are all the same! ylab = ylab + ' (' + samp[0]['age_unit'] + ')' # filter for depth if dmax == -1 or float(samp[0][depth_scale]) < dmax and float(samp[0][depth_scale]) > dmin: # fish out data with core_depth FDepths.append(float(samp[0][depth_scale])) # fish out data with core_depth FDecs.append(float(spec[spec_dec_col])) # fish out data with core_depth FIncs.append(float(spec[spec_inc_col])) else: print('no core_depth found for: ', spec[spec_col_name]) ResDepths, ResDecs, ResIncs = [], [], [] if 'age' in depth_scale: # set y-key res_scale = age_col_name else: res_scale = height_col_name if res_file: # creates lists of Result Data for res in Results: meths = res[meth_col_name].split(":") if 'DE-FM' in meths: # filter for depth if dmax == -1 or float(res[res_scale]) < dmax and float(res[res_scale]) > dmin: # fish out data with core_depth ResDepths.append(float(res[res_scale])) # fish out data with core_depth ResDecs.append(float(res['average_dec'])) # fish out data with core_depth ResIncs.append(float(res['average_inc'])) Susc, Sus_depths = [], [] if dmin == -1: if len(Depths) > 0: dmin, dmax = Depths[0], Depths[-1] if len(FDepths) > 0: dmin, dmax = FDepths[0], FDepths[-1] if pltSus and len(SDepths) > 0: if SDepths[0] < dmin: dmin = SDepths[0] if SDepths[-1] > dmax: dmax = SDepths[-1] if len(SpecDepths) > 0: if min(SpecDepths) < dmin: dmin = min(SpecDepths) if max(SpecDepths) > dmax: dmax = max(SpecDepths) if len(ResDepths) > 0: if min(ResDepths) < dmin: dmin = min(ResDepths) if max(ResDepths) > dmax: dmax = max(ResDepths) # wig_file and suc_file not currently supported options # if suc_file: # with open(suc_file, 'r') as s_file: # sucdat = s_file.readlines() # keys = sucdat[0].replace('\n', '').split(',') # splits on underscores # for line in sucdat[1:]: # SucRec = {} # for k in range(len(keys)): # SucRec[keys[k]] = line.split(',')[k] # if float(SucRec['Top Depth (m)']) < dmax and float(SucRec['Top Depth (m)']) > dmin and SucRec['Magnetic Susceptibility (80 mm)'] != "": # Susc.append(float(SucRec['Magnetic Susceptibility (80 mm)'])) # if Susc[-1] > maxSuc: # maxSuc = Susc[-1] # if Susc[-1] < minSuc: # minSuc = Susc[-1] # Sus_depths.append(float(SucRec['Top Depth (m)'])) #WIG, WIG_depths = [], [] # if wig_file: # wigdat, file_type = pmag.magic_read(wig_file) # swigdat = pmag.sort_diclist(wigdat, depth_scale) # keys = list(wigdat[0].keys()) # for key in keys: # if key != depth_scale: # plt_key = key # break # for wig in swigdat: # if float(wig[depth_scale]) < dmax and float(wig[depth_scale]) > dmin: # WIG.append(float(wig[plt_key])) # WIG_depths.append(float(wig[depth_scale])) tint = 4.5 plot = 1 #print('Decs', len(Decs)) #print('Depths', len(Depths), 'SpecDecs', len(SpecDecs)) #print('SpecDepths', len(SpecDepths), 'ResDecs', len(ResDecs)) #print('ResDepths', len(ResDepths), 'SDecs', len(SDecs)) #print('SDepths', len(SDepths), 'SIincs', len(SIncs)) #print('Incs', len(Incs)) if (Decs and Depths) or (SpecDecs and SpecDepths) or (ResDecs and ResDepths) or (SDecs and SDepths) or (SInts and SDepths) or (SIncs and SDepths) or (Incs and Depths): main_plot = plt.figure(1, figsize=(width, 8)) # this works # pylab.figure(1,figsize=(width,8)) version_num = pmag.get_version() plt.figtext(.02, .01, version_num) if pltDec: ax = plt.subplot(1, pcol, plot) if pltLine: plt.plot(Decs, Depths, 'k') if len(Decs) > 0: plt.plot(Decs, Depths, sym, markersize=size) if len(Decs) == 0 and pltLine and len(SDecs) > 0: plt.plot(SDecs, SDepths, 'k') if len(SDecs) > 0: plt.plot(SDecs, SDepths, Ssym, markersize=Ssize) if spc_file: plt.plot(SpecDecs, SpecDepths, spc_sym, markersize=spc_size) if spc_file and len(FDepths) > 0: plt.scatter( FDecs, FDepths, marker=spc_sym[-1], edgecolor=spc_sym[0], facecolor='white', s=spc_size**2) if res_file: plt.plot(ResDecs, ResDepths, res_sym, markersize=res_size) if sum_file: for core in Cores: depth = float(core[core_depth_key]) if depth > dmin and depth < dmax: plt.plot([0, 360.], [depth, depth], 'b--') if pel == plt: plt.text(360, depth + tint, core[core_label_key]) if pel == plot: plt.axis([0, 400, dmax, dmin]) else: plt.axis([0, 360., dmax, dmin]) plt.xlabel('Declination') plt.ylabel(ylab) plot += 1 pmagplotlib.delticks(ax) # dec xticks are too crowded otherwise else: print('no data!') return False, 'No data found to plot\nTry again with different parameters' if pltInc: plt.subplot(1, pcol, plot) if pltLine: plt.plot(Incs, Depths, 'k') if len(Incs) > 0: plt.plot(Incs, Depths, sym, markersize=size) if len(Incs) == 0 and pltLine and len(SIncs) > 0: plt.plot(SIncs, SDepths, 'k') if len(SIncs) > 0: plt.plot(SIncs, SDepths, Ssym, markersize=Ssize) if spc_file and len(SpecDepths) > 0: plt.plot(SpecIncs, SpecDepths, spc_sym, markersize=spc_size) if spc_file and len(FDepths) > 0: plt.scatter( FIncs, FDepths, marker=spc_sym[-1], edgecolor=spc_sym[0], facecolor='white', s=spc_size**2) if res_file: plt.plot(ResIncs, ResDepths, res_sym, markersize=res_size) if sum_file: for core in Cores: depth = float(core[core_depth_key]) if depth > dmin and depth < dmax: if pel == plot: plt.text(90, depth + tint, core[core_label_key]) plt.plot([-90, 90], [depth, depth], 'b--') plt.plot([0, 0], [dmax, dmin], 'k-') if pel == plot: plt.axis([-90, 110, dmax, dmin]) else: plt.axis([-90, 90, dmax, dmin]) plt.xlabel('Inclination') plt.ylabel('') plot += 1 if pltMag and len(Ints) > 0 or len(SInts) > 0: plt.subplot(1, pcol, plot) for pow in range(-10, 10): if maxInt * 10**pow > 1: break if not logit: for k in range(len(Ints)): Ints[k] = Ints[k] * 10**pow for k in range(len(SInts)): SInts[k] = SInts[k] * 10**pow if pltLine and len(Ints) > 0: plt.plot(Ints, Depths, 'k') if len(Ints) > 0: plt.plot(Ints, Depths, sym, markersize=size) if len(Ints) == 0 and pltLine and len(SInts) > 0: plt.plot(SInts, SDepths, 'k-') if len(SInts) > 0: plt.plot(SInts, SDepths, Ssym, markersize=Ssize) if sum_file: for core in Cores: depth = float(core[core_depth_key]) plt.plot([0, maxInt * 10**pow + .1], [depth, depth], 'b--') if depth > dmin and depth < dmax: plt.text(maxInt * 10**pow - .2 * maxInt * 10 ** pow, depth + tint, core[core_label_key]) plt.axis([0, maxInt * 10**pow + .1, dmax, dmin]) if not norm: plt.xlabel('%s %i %s' % ('Intensity (10^-', pow, ' Am^2)')) else: plt.xlabel('%s %i %s' % ('Intensity (10^-', pow, ' Am^2/kg)')) else: if pltLine: plt.semilogx(Ints, Depths, 'k') if len(Ints) > 0: plt.semilogx(Ints, Depths, sym, markersize=size) if len(Ints) == 0 and pltLine and len(SInts) > 0: plt.semilogx(SInts, SDepths, 'k') if len(Ints) == 0 and pltLine == 1 and len(SInts) > 0: plt.semilogx(SInts, SDepths, 'k') if len(SInts) > 0: plt.semilogx(SInts, SDepths, Ssym, markersize=Ssize) if sum_file: for core in Cores: depth = float(core[core_depth_key]) plt.semilogx([minInt, maxInt], [depth, depth], 'b--') if depth > dmin and depth < dmax: plt.text(maxInt - .2 * maxInt, depth + tint, core[core_label_key]) minInt = plt.axis()[0] plt.axis([minInt, maxInt, dmax, dmin]) if not norm: plt.xlabel('Intensity (Am^2)') else: plt.xlabel('Intensity (Am^2/kg)') plot += 1 if suc_file or len(SSucs) > 0: plt.subplot(1, pcol, plot) if len(Susc) > 0: if pltLine: plt.plot(Susc, Sus_depths, 'k') if not logit: plt.plot(Susc, Sus_depths, sym, markersize=size) if logit: plt.semilogx(Susc, Sus_depths, sym, markersize=size) if len(SSucs) > 0: if not logit: plt.plot(SSucs, SDepths, sym, markersize=size) if logit: plt.semilogx(SSucs, SDepths, sym, markersize=size) if sum_file: for core in Cores: depth = float(core[core_depth_key]) if not logit: plt.plot([minSuc, maxSuc], [depth, depth], 'b--') if logit: plt.semilogx([minSuc, maxSuc], [depth, depth], 'b--') plt.axis([minSuc, maxSuc, dmax, dmin]) plt.xlabel('Susceptibility') plot += 1 # if wig_file: # plt.subplot(1, pcol, plot) # plt.plot(WIG, WIG_depths, 'k') # if sum_file: # for core in Cores: # depth = float(core[core_depth_key]) # plt.plot([WIG[0], WIG[-1]], [depth, depth], 'b--') # plt.axis([min(WIG), max(WIG), dmax, dmin]) # plt.xlabel(plt_key) # plot += 1 if pltTime: ax1 = plt.subplot(1, pcol, plot) ax1.axis([-.25, 1.5, amax, amin]) plot += 1 TS, Chrons = pmag.get_ts(timescale) X, Y, Y2 = [0, 1], [], [] cnt = 0 if amin < TS[1]: # in the Brunhes Y = [amin, amin] # minimum age Y1 = [TS[1], TS[1]] # age of the B/M boundary # color in Brunhes, black ax1.fill_between(X, Y, Y1, facecolor='black') for d in TS[1:]: pol = cnt % 2 cnt += 1 if d <= amax and d >= amin: ind = TS.index(d) Y = [TS[ind], TS[ind]] Y1 = [TS[ind + 1], TS[ind + 1]] if pol: # fill in every other time ax1.fill_between(X, Y, Y1, facecolor='black') ax1.plot([0, 1, 1, 0, 0], [amin, amin, amax, amax, amin], 'k-') ax2 = ax1.twinx() plt.ylabel("Age (Ma): " + timescale) for k in range(len(Chrons) - 1): c = Chrons[k] cnext = Chrons[k + 1] d = cnext[1] - old_div((cnext[1] - c[1]), 3.) if d >= amin and d < amax: # 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, amax, amin]) figname = location + '_m:_' + method + '_core-depthplot.' + fmt plt.title(location) return main_plot, figname def download_magic(infile, dir_path='.', input_dir_path='.', overwrite=False, print_progress=True, data_model=3., separate_locs=False): """ takes the name of a text file downloaded from the MagIC database and unpacks it into magic-formatted files. by default, download_magic assumes that you are doing everything in your current directory. if not, you may provide optional arguments dir_path (where you want the results to go) and input_dir_path (where the downloaded file is). Parameters ---------- infile : str MagIC-format file to unpack dir_path : str output directory (default ".") input_dir : str input directory (default ".") overwrite: bool overwrite current directory (default False) print_progress: bool verbose output (default True) data_model : float MagIC data model 2.5 or 3 (default 3) separate_locs : bool create a separate directory for each location (Location_*) (default False) """ if data_model == 2.5: method_col = "magic_method_codes" else: method_col = "method_codes" infile = pmag.resolve_file_name(infile, input_dir_path) # try to deal reasonably with unicode errors try: f = codecs.open(infile, 'r', "utf-8") infile = f.readlines() except UnicodeDecodeError: f = codecs.open(infile, 'r', "Latin-1") infile = f.readlines() f.close() File = [] # will contain all non-blank lines from downloaded file for line in infile: line = line.replace('\n', '') if line[0:4] == '>>>>' or len(line.strip()) > 0: # skip blank lines File.append(line) LN = 0 # tracks our progress iterating through File type_list = [] filenum = 0 while LN < len(File) - 1: line = File[LN] if ">>>>" in line: LN += 1 continue file_type = line.split('\t')[1] file_type = file_type.lower() if file_type[-1] == "\n": file_type = file_type[:-1] if print_progress == True: print('working on: ', repr(file_type)) if file_type not in type_list: type_list.append(file_type) else: filenum += 1 LN += 1 line = File[LN] # skip empty tables if line == ">>>>>>>>>>": LN += 1 continue keys = line.replace('\n', '').split('\t') if keys[0][0] == '.': keys = line.replace('\n', '').replace('.', '').split('\t') keys.append('RecNo') # cludge for new MagIC download format LN += 1 Recs = [] while LN < len(File): line = File[LN] # finish up one file type and then break if ">>>>" in line and len(Recs) > 0: if filenum == 0: outfile = dir_path + "/" + file_type.strip() + '.txt' else: outfile = dir_path + "/" + file_type.strip() + '_' + str(filenum) + '.txt' NewRecs = [] for rec in Recs: if method_col in list(rec.keys()): meths = rec[method_col].split(":") if len(meths) > 0: methods = "" for meth in meths: methods = methods + meth.strip() + ":" # get rid of nasty spaces!!!!!! rec[method_col] = methods[:-1] NewRecs.append(rec) pmag.magic_write(outfile, Recs, file_type) if print_progress == True: print(file_type, " data put in ", outfile) Recs = [] LN += 1 break # keep adding records of the same file type else: rec = line.split('\t') Rec = {} if len(rec) == len(keys): for k in range(len(rec)): Rec[keys[k]] = rec[k] Recs.append(Rec) # in case of magic_search_results.txt, which has an extra # column: elif len(rec) - len(keys) == 1: for k in range(len(rec))[:-1]: Rec[keys[k]] = rec[k] Recs.append(Rec) elif len(rec) < len(keys): for k in range(len(rec)): Rec[keys[k]] = rec[k] for k in range(len(rec), len(keys)): Rec[keys[k]] = "" Recs.append(Rec) else: print('WARNING: problem in file with line: ') print(line) print('skipping....') LN += 1 if len(Recs) > 0: if filenum == 0: outfile = dir_path + "/" + file_type.strip() + '.txt' else: outfile = dir_path + "/" + file_type.strip() + '_' + str(filenum) + '.txt' NewRecs = [] for rec in Recs: if method_col in list(rec.keys()): meths = rec[method_col].split(":") if len(meths) > 0: methods = "" for meth in meths: methods = methods + meth.strip() + ":" # get rid of nasty spaces!!!!!! rec[method_col] = methods[:-1] NewRecs.append(rec) pmag.magic_write(outfile, Recs, file_type) if print_progress == True: print(file_type, " data put in ", outfile) # look through locations table and create separate directories for each # location if separate_locs: con = cb.Contribution(dir_path) con.propagate_location_to_measurements() con.propagate_name_down('location', 'samples') for dtype in con.tables: con.write_table_to_file(dtype) locs, locnum = [], 1 if 'locations' in type_list: locs, file_type = pmag.magic_read( os.path.join(dir_path, 'locations.txt')) if len(locs) > 0: # at least one location # go through unique location names for loc_name in set([loc.get('location') for loc in locs]): if print_progress == True: print('location_' + str(locnum) + ": ", loc_name) lpath = dir_path + '/Location_' + str(locnum) locnum += 1 try: os.mkdir(lpath) except: print('directory ', lpath, ' already exists - overwriting everything: {}'.format(overwrite)) if not overwrite: print("-W- download_magic encountered a duplicate subdirectory ({}) and could not finish.\nRerun with overwrite=True, or unpack this file in a different directory.".format(lpath)) return False for f in type_list: if print_progress == True: print('unpacking: ', dir_path + '/' + f + '.txt') recs, file_type = pmag.magic_read( dir_path + '/' + f + '.txt') if print_progress == True: print(len(recs), ' read in') lrecs = pmag.get_dictitem(recs, 'location', loc_name, 'T') if len(lrecs) > 0: pmag.magic_write(lpath + '/' + f + '.txt', lrecs, file_type) if print_progress == True: print(len(lrecs), ' stored in ', lpath + '/' + f + '.txt') return True def upload_magic2(concat=0, dir_path='.', data_model=None): """ Finds all magic files in a given directory, and compiles them into an upload.txt file which can be uploaded into the MagIC database. Returns a tuple of either: (False, error_message, errors) if there was a problem creating/validating the upload file or: (filename, '', None) if the upload was fully successful. """ SpecDone = [] locations = [] concat = int(concat) files_list = ["er_expeditions.txt", "er_locations.txt", "er_samples.txt", "er_specimens.txt", "er_sites.txt", "er_ages.txt", "er_citations.txt", "er_mailinglist.txt", "magic_measurements.txt", "rmag_hysteresis.txt", "rmag_anisotropy.txt", "rmag_remanence.txt", "rmag_results.txt", "pmag_specimens.txt", "pmag_samples.txt", "pmag_sites.txt", "pmag_results.txt", "pmag_criteria.txt", "magic_instruments.txt"] file_names = [os.path.join(dir_path, f) for f in files_list] # begin the upload process up = os.path.join(dir_path, "upload.txt") if os.path.exists(up): os.remove(up) RmKeys = ['citation_label', 'compilation', 'calculation_type', 'average_n_lines', 'average_n_planes', 'specimen_grade', 'site_vgp_lat', 'site_vgp_lon', 'direction_type', 'specimen_Z', 'magic_instrument_codes', 'cooling_rate_corr', 'cooling_rate_mcd', 'anisotropy_atrm_alt', 'anisotropy_apar_perc', 'anisotropy_F', 'anisotropy_F_crit', 'specimen_scat', 'specimen_gmax', 'specimen_frac', 'site_vadm', 'site_lon', 'site_vdm', 'site_lat', 'measurement_chi', 'specimen_k_prime', 'specimen_k_prime_sse', 'external_database_names', 'external_database_ids', 'Further Notes', 'Typology', 'Notes (Year/Area/Locus/Level)', 'Site', 'Object Number', 'dir_n_specimens'] print("-I- Removing: ", RmKeys) CheckDec = ['_dec', '_lon', '_azimuth', 'dip_direction'] CheckSign = ['specimen_b_beta'] last = file_names[-1] methods, first_file = [], 1 for File in file_names: # read in the data Data, file_type = pmag.magic_read(File) if (file_type != "bad_file") and (file_type != "empty_file"): print("-I- file", File, " successfully read in") if len(RmKeys) > 0: for rec in Data: # remove unwanted keys for key in RmKeys: if key == 'specimen_Z' and key in list(rec.keys()): # change # change this to lower case rec[key] = 'specimen_z' if key in list(rec.keys()): del rec[key] # get rid of unwanted keys # make sure b_beta is positive # ignore blanks if 'specimen_b_beta' in list(rec.keys()) and rec['specimen_b_beta'] != "": if float(rec['specimen_b_beta']) < 0: # make sure value is positive rec['specimen_b_beta'] = str( -float(rec['specimen_b_beta'])) print('-I- adjusted to positive: ', 'specimen_b_beta', rec['specimen_b_beta']) # make all declinations/azimuths/longitudes in range # 0=>360. rec = pmag.adjust_all_to_360(rec) if file_type == 'er_locations': for rec in Data: locations.append(rec['er_location_name']) if file_type in ['pmag_samples', 'pmag_sites', 'pmag_specimens']: # if there is NO pmag data for specimens (samples/sites), # do not try to write it to file # (this causes validation errors, elsewise) ignore = True for rec in Data: if ignore == False: break keys = list(rec.keys()) exclude_keys = ['er_citation_names', 'er_site_name', 'er_sample_name', 'er_location_name', 'er_specimen_names', 'er_sample_names'] for key in exclude_keys: if key in keys: keys.remove(key) for key in keys: if rec[key]: ignore = False break if ignore: continue if file_type == 'er_samples': # check to only upload top priority orientation record! NewSamps, Done = [], [] for rec in Data: if rec['er_sample_name'] not in Done: orient, az_type = pmag.get_orient( Data, rec['er_sample_name']) NewSamps.append(orient) Done.append(rec['er_sample_name']) Data = NewSamps print( 'only highest priority orientation record from er_samples.txt read in ') if file_type == 'er_specimens': # only specimens that have sample names NewData, SpecDone = [], [] for rec in Data: if rec['er_sample_name'] in Done: NewData.append(rec) SpecDone.append(rec['er_specimen_name']) else: print('no valid sample record found for: ') print(rec) Data = NewData # print 'only measurements that have specimen/sample info' if file_type == 'magic_measurements': # only measurements that have specimen names no_specs = [] NewData = [] for rec in Data: if rec['er_specimen_name'] in SpecDone: NewData.append(rec) else: print('no valid specimen record found for: ') print(rec) no_specs.append(rec) # print set([record['er_specimen_name'] for record in # no_specs]) Data = NewData # write out the data if len(Data) > 0: if first_file == 1: keystring = pmag.first_rec(up, Data[0], file_type) first_file = 0 else: keystring = pmag.first_up(up, Data[0], file_type) for rec in Data: # collect the method codes if "magic_method_codes" in list(rec.keys()): meths = rec["magic_method_codes"].split(':') for meth in meths: if meth.strip() not in methods: if meth.strip() != "LP-DIR-": methods.append(meth.strip()) try: pmag.putout(up, keystring, rec) except IOError: print('-W- File input error: slowing down') time.sleep(1) pmag.putout(up, keystring, rec) # write out the file separator f = open(up, 'a') f.write('>>>>>>>>>>\n') f.close() print(file_type, 'written to ', up) else: print('File:', File) print(file_type, 'is bad or non-existent - skipping ') # write out the methods table first_rec, MethRec = 1, {} for meth in methods: MethRec["magic_method_code"] = meth if first_rec == 1: meth_keys = pmag.first_up(up, MethRec, "magic_methods") first_rec = 0 try: pmag.putout(up, meth_keys, MethRec) except IOError: print('-W- File input error: slowing down') time.sleep(1) pmag.putout(up, meth_keys, MethRec) if concat == 1: f = open(up, 'a') f.write('>>>>>>>>>>\n') f.close() if os.path.isfile(up): from . import validate_upload2 as validate_upload validated = False validated, errors = validate_upload.read_upload(up, data_model) else: print("no data found, upload file not created") return False, "no data found, upload file not created", None # rename upload.txt according to location + timestamp format_string = "%d.%b.%Y" if locations: location = locations[0].replace(' ', '_') new_up = location + '_' + time.strftime(format_string) + '.txt' else: new_up = 'unknown_location_' + time.strftime(format_string) + '.txt' new_up = os.path.join(dir_path, new_up) if os.path.isfile(new_up): fname, extension = os.path.splitext(new_up) for i in range(1, 100): if os.path.isfile(fname + "_" + str(i) + extension): continue else: new_up = fname + "_" + str(i) + extension break os.rename(up, new_up) print("Finished preparing upload file: {} ".format(new_up)) if not validated: print("-W- validation of upload file has failed.\nPlease fix above errors and try again.\nYou may run into problems if you try to upload this file to the MagIC database") return False, "file validation has failed. You may run into problems if you try to upload this file.", errors return new_up, '', None def upload_magic3(concat=1, dir_path='.', dmodel=None, vocab="", contribution=None): print('-W- ipmag.upload_magic3 is deprecated, please switch to using ipmag.upload_magic') return upload_magic(concat, dir_path, dmodel, vocab, contribution) def upload_magic(concat=False, dir_path='.', dmodel=None, vocab="", contribution=None): """ Finds all magic files in a given directory, and compiles them into an upload.txt file which can be uploaded into the MagIC database. Parameters ---------- concat : boolean where True means do concatenate to upload.txt file in dir_path, False means write a new file (default is False) dir_path : string for input/output directory (default ".") dmodel : pmagpy data_model.DataModel object, if not provided will be created (default None) vocab : pmagpy controlled_vocabularies3.Vocabulary object, if not provided will be created (default None) contribution : pmagpy contribution_builder.Contribution object, if not provided will be created in directory (default None) Returns ---------- tuple of either: (False, error_message, errors, all_failing_items) if there was a problem creating/validating the upload file or: (filename, '', None, None) if the file creation was fully successful. """ dir_path = os.path.realpath(dir_path) locations = [] concat = int(concat) dtypes = ["locations", "samples", "specimens", "sites", "ages", "measurements", "criteria", "contribution", "images"] fnames = [os.path.join(dir_path, dtype + ".txt") for dtype in dtypes] file_names = [fname for fname in fnames if os.path.exists(fname)] error_fnames = [dtype + "_errors.txt" for dtype in dtypes] error_full_fnames = [os.path.join( dir_path, fname) for fname in error_fnames if os.path.exists(os.path.join(dir_path, fname))] print('-I- Removing old error files from {}: {}'.format(dir_path, ", ".join(error_fnames))) for error in error_full_fnames: os.remove(error) if isinstance(contribution, cb.Contribution): # if contribution object provided, use it con = contribution for table_name in con.tables: con.tables[table_name].write_magic_file() elif file_names: # otherwise create a new Contribution in dir_path con = Contribution(dir_path, vocabulary=vocab) else: # if no contribution is provided and no contribution could be created, # you are out of luck print("-W- No 3.0 files found in your directory: {}, upload file not created".format(dir_path)) return False, "no 3.0 files found, upload file not created", None, None # if the contribution has no tables, you can't make an upload file if not con.tables.keys(): print("-W- No tables found in your contribution, file not created".format(dir_path)) return False, "-W- No tables found in your contribution, file not created", None, None con.propagate_cols(['core_depth', 'composite_depth'], 'sites', 'samples', down=False) # take out any extra added columns # con.remove_non_magic_cols() # begin the upload process up = os.path.join(dir_path, "upload.txt") if os.path.exists(up): os.remove(up) RmKeys = ('citation_label', 'compilation', 'calculation_type', 'average_n_lines', 'average_n_planes', 'specimen_grade', 'site_vgp_lat', 'site_vgp_lon', 'direction_type', 'specimen_Z', 'magic_instrument_codes', 'cooling_rate_corr', 'cooling_rate_mcd', 'anisotropy_atrm_alt', 'anisotropy_apar_perc', 'anisotropy_F', 'anisotropy_F_crit', 'specimen_scat', 'specimen_gmax', 'specimen_frac', 'site_vadm', 'site_lon', 'site_vdm', 'site_lat', 'measurement_chi', 'specimen_k_prime', 'specimen_k_prime_sse', 'external_database_names', 'external_database_ids', 'Further Notes', 'Typology', 'Notes (Year/Area/Locus/Level)', 'Site', 'Object Number', 'version', 'site_definition') #print("-I- Removing: ", RmKeys) extra_RmKeys = {'measurements': ['sample', 'site', 'location'], 'specimens': ['site', 'location', 'age', 'age_unit', 'age_high', 'age_low', 'age_sigma', 'specimen_core_depth'], 'samples': ['location', 'age', 'age_unit', 'age_high', 'age_low', 'age_sigma', 'core_depth', 'composite_depth'], 'sites': ['texture', 'azimuth', 'azimuth_dec_correction', 'dip', 'orientation_quality', 'sample_alternatives', 'timestamp'], 'ages': ['level']} failing = [] all_failing_items = {} if not dmodel: dmodel = data_model.DataModel() last_file_type = sorted(con.tables.keys())[-1] for file_type in sorted(con.tables.keys()): container = con.tables[file_type] df = container.df if len(df): print("-I- {} file successfully read in".format(file_type)) # make some adjustments to clean up data # drop non MagIC keys #DropKeys = set(RmKeys).intersection(df.columns) DropKeys = list(RmKeys) + extra_RmKeys.get(file_type, []) DropKeys = set(DropKeys).intersection(df.columns) if DropKeys: print( '-I- dropping these columns: {} from the {} table'.format(', '.join(DropKeys), file_type)) df.drop(DropKeys, axis=1, inplace=True) container.df = df unrecognized_cols = container.get_non_magic_cols() if unrecognized_cols: print('-W- {} table still has some unrecognized columns: {}'.format(file_type.title(), ", ".join(unrecognized_cols))) # make sure int_b_beta is positive if 'int_b_beta' in df.columns: # get rid of empty strings df = df.replace(r'\s+( +\.)|#', np.nan, regex=True).replace('', np.nan) try: df['int_b_beta'] = df['int_b_beta'].astype( float).apply(abs) except ValueError: "-W- Non numeric values found in int_b_beta column.\n Could not apply absolute value." # make all declinations/azimuths/longitudes in range 0=>360. relevant_cols = val_up3.get_degree_cols(df) for col in relevant_cols: df[col] = df[col].apply(pmag.adjust_val_to_360) # get list of location names if file_type == 'locations': locations = sorted(df['location'].unique()) # LJ: need to deal with this # use only highest priority orientation -- not sure how this works elif file_type == 'samples': # orient,az_type=pmag.get_orient(Data,rec['sample']) pass # include only specimen records with samples elif file_type == 'specimens': df = df[df['sample'].notnull()] if 'samples' in con.tables: samp_df = con.tables['samples'].df df = df[df['sample'].isin(samp_df.index.unique())] # include only measurements with specmiens elif file_type == 'measurements': df = df[df['specimen'].notnull()] if 'specimens' in con.tables: spec_df = con.tables['specimens'].df df = df[df['specimen'].isin(spec_df.index.unique())] # run validations res = val_up3.validate_table( con, file_type, output_dir=dir_path) # , verbose=True) if res: dtype, bad_rows, bad_cols, missing_cols, missing_groups, failing_items = res if dtype not in all_failing_items: all_failing_items[dtype] = {} all_failing_items[dtype]["rows"] = failing_items all_failing_items[dtype]["missing_columns"] = missing_cols all_failing_items[dtype]["missing_groups"] = missing_groups failing.append(dtype) # write out the data if len(df): container.write_magic_file(up, append=True, multi_type=True) # write out the file separator if last_file_type != file_type: f = open(up, 'a') f.write('>>>>>>>>>>\n') f.close() print("-I-", file_type, 'written to ', up) else: # last file, no newline at end of file #f = open(up, 'a') # f.write('>>>>>>>>>>') # f.close() print("-I-", file_type, 'written to ', up) # if there was no understandable data else: print(file_type, 'is bad or non-existent - skipping ') # add to existing file if concat: f = open(up, 'a') f.write('>>>>>>>>>>\n') f.close() if not os.path.isfile(up): print("no data found, upload file not created") return False, "no data found, upload file not created", None, None # rename upload.txt according to location + timestamp format_string = "%d.%b.%Y" if locations: locs = set(locations) locs = sorted(locs)[:3] #location = locations[0].replace(' ', '_') try: locs = [loc.replace(' ', '-') for loc in locs] except AttributeError: locs = ["unknown_location"] location = "_".join(locs) new_up = location + '_' + time.strftime(format_string) + '.txt' else: new_up = 'unknown_location_' + time.strftime(format_string) + '.txt' new_up = os.path.join(dir_path, new_up) if os.path.isfile(new_up): fname, extension = os.path.splitext(new_up) for i in range(1, 100): if os.path.isfile(fname + "_" + str(i) + extension): continue else: new_up = fname + "_" + str(i) + extension break if not up: print("-W- Could not create an upload file") return False, "Could not create an upload file", None, None os.rename(up, new_up) print("Finished preparing upload file: {} ".format(new_up)) if failing: print("-W- validation of upload file has failed.") print("These tables have errors: {}".format(", ".join(failing))) print("Please fix above errors and try again.") print("You may run into problems if you try to upload this file to the MagIC database.") return False, "file validation has failed. You may run into problems if you try to upload this file.", failing, all_failing_items else: print("-I- Your file has passed validation. You should be able to upload it to the MagIC database without trouble!") return new_up, '', None, None def specimens_results_magic(infile='pmag_specimens.txt', measfile='magic_measurements.txt', sampfile='er_samples.txt', sitefile='er_sites.txt', agefile='er_ages.txt', specout='er_specimens.txt', sampout='pmag_samples.txt', siteout='pmag_sites.txt', resout='pmag_results.txt', critout='pmag_criteria.txt', instout='magic_instruments.txt', plotsites=False, fmt='svg', dir_path='.', cors=[], priorities=['DA-AC-ARM', 'DA-AC-TRM'], coord='g', user='', vgps_level='site', do_site_intensity=True, DefaultAge=["none"], avg_directions_by_sample=False, avg_intensities_by_sample=False, avg_all_components=False, avg_by_polarity=False, skip_directions=False, skip_intensities=False, use_sample_latitude=False, use_paleolatitude=False, use_criteria='default'): """ Writes magic_instruments, er_specimens, pmag_samples, pmag_sites, pmag_criteria, and pmag_results. The data used to write this is obtained by reading a pmag_speciemns, a magic_measurements, a er_samples, a er_sites, a er_ages. @param -> infile: path from the WD to the pmag speciemns table @param -> measfile: path from the WD to the magic measurement file @param -> sampfile: path from the WD to the er sample file @param -> sitefile: path from the WD to the er sites data file @param -> agefile: path from the WD to the er ages data file @param -> specout: path from the WD to the place to write the er specimens data file @param -> sampout: path from the WD to the place to write the pmag samples data file @param -> siteout: path from the WD to the place to write the pmag sites data file @param -> resout: path from the WD to the place to write the pmag results data file @param -> critout: path from the WD to the place to write the pmag criteria file @param -> instout: path from th WD to the place to write the magic instruments file @param -> documentation incomplete if you know more about the purpose of the parameters in this function and it's side effects please extend and complete this string """ # initialize some variables plotsites = False # cannot use draw_figs from within ipmag Comps = [] # list of components version_num = pmag.get_version() args = sys.argv model_lat_file = "" Dcrit, Icrit, nocrit = 0, 0, 0 corrections = [] nocorrection = ['DA-NL', 'DA-AC', 'DA-CR'] # do some data adjustments for cor in cors: nocorrection.remove('DA-' + cor) corrections.append('DA-' + cor) for p in priorities: if not p.startswith('DA-AC-'): p = 'DA-AC-' + p # translate coord into coords if coord == 's': coords = ['-1'] if coord == 'g': coords = ['0'] if coord == 't': coords = ['100'] if coord == 'b': coords = ['0', '100'] if vgps_level == 'sample': vgps = 1 # save sample level VGPS/VADMs else: vgps = 0 # site level if do_site_intensity: nositeints = 0 else: nositeints = 1 # chagne these all to True/False instead of 1/0 if not skip_intensities: # set model lat and if use_sample_latitude and use_paleolatitude: print("you should set a paleolatitude file OR use present day lat - not both") return False elif use_sample_latitude: get_model_lat = 1 elif use_paleolatitude: get_model_lat = 2 try: model_lat_file = dir_path + '/' + args[ind + 1] get_model_lat = 2 mlat = open(model_lat_file, 'r') ModelLats = [] for line in mlat.readlines(): ModelLat = {} tmp = line.split() ModelLat["er_site_name"] = tmp[0] ModelLat["site_model_lat"] = tmp[1] ModelLat["er_sample_name"] = tmp[0] ModelLat["sample_lat"] = tmp[1] ModelLats.append(ModelLat) mlat.clos() except: print("use_paleolatitude option requires a valid paleolatitude file") else: get_model_lat = 0 # skips VADM calculation entirely if plotsites and not skip_directions: # plot by site - set up plot window EQ = {} EQ['eqarea'] = 1 # define figure 1 as equal area projection pmagplotlib.plot_init(EQ['eqarea'], 5, 5) # I don't know why this has to be here, but otherwise the first plot # never plots... pmagplotlib.plot_net(EQ['eqarea']) pmagplotlib.draw_figs(EQ) infile = os.path.join(dir_path, infile) measfile = os.path.join(dir_path, measfile) instout = os.path.join(dir_path, instout) sampfile = os.path.join(dir_path, sampfile) sitefile = os.path.join(dir_path, sitefile) agefile = os.path.join(dir_path, agefile) specout = os.path.join(dir_path, specout) sampout = os.path.join(dir_path, sampout) siteout = os.path.join(dir_path, siteout) resout = os.path.join(dir_path, resout) critout = os.path.join(dir_path, critout) if use_criteria == 'none': Dcrit, Icrit, nocrit = 1, 1, 1 # no selection criteria crit_data = pmag.default_criteria(nocrit) elif use_criteria == 'default': crit_data = pmag.default_criteria(nocrit) # use default criteria elif use_criteria == 'existing': crit_data, file_type = pmag.magic_read( critout) # use pmag_criteria file print("Acceptance criteria read in from ", critout) accept = {} for critrec in crit_data: for key in list(critrec.keys()): # need to migrate specimen_dang to specimen_int_dang for intensity # data using old format if 'IE-SPEC' in list(critrec.keys()) and 'specimen_dang' in list(critrec.keys()) and 'specimen_int_dang' not in list(critrec.keys()): critrec['specimen_int_dang'] = critrec['specimen_dang'] del critrec['specimen_dang'] # need to get rid of ron shaars sample_int_sigma_uT if 'sample_int_sigma_uT' in list(critrec.keys()): critrec['sample_int_sigma'] = '%10.3e' % ( eval(critrec['sample_int_sigma_uT']) * 1e-6) if key not in list(accept.keys()) and critrec[key] != '': accept[key] = critrec[key] if use_criteria == 'default': pmag.magic_write(critout, [accept], 'pmag_criteria') print("\n Pmag Criteria stored in ", critout, '\n') # now we're done slow dancing # read in site data - has the lats and lons SiteNFO, file_type = pmag.magic_read(sitefile) # read in site data - has the lats and lons SampNFO, file_type = pmag.magic_read(sampfile) # find all the sites with height info. height_nfo = pmag.get_dictitem(SiteNFO, 'site_height', '', 'F') if agefile: AgeNFO, file_type = pmag.magic_read( agefile) # read in the age information # read in specimen interpretations Data, file_type = pmag.magic_read(infile) # retrieve specimens with intensity data IntData = pmag.get_dictitem(Data, 'specimen_int', '', 'F') comment, orient = "", [] samples, sites = [], [] for rec in Data: # run through the data filling in missing keys and finding all components, coordinates available # fill in missing fields, collect unique sample and site names if 'er_sample_name' not in list(rec.keys()): rec['er_sample_name'] = "" elif rec['er_sample_name'] not in samples: samples.append(rec['er_sample_name']) if 'er_site_name' not in list(rec.keys()): rec['er_site_name'] = "" elif rec['er_site_name'] not in sites: sites.append(rec['er_site_name']) if 'specimen_int' not in list(rec.keys()): rec['specimen_int'] = '' if 'specimen_comp_name' not in list(rec.keys()) or rec['specimen_comp_name'] == "": rec['specimen_comp_name'] = 'A' if rec['specimen_comp_name'] not in Comps: Comps.append(rec['specimen_comp_name']) rec['specimen_tilt_correction'] = rec['specimen_tilt_correction'].strip( '\n') if "specimen_tilt_correction" not in list(rec.keys()): rec["specimen_tilt_correction"] = "-1" # assume sample coordinates if rec["specimen_tilt_correction"] not in orient: # collect available coordinate systems orient.append(rec["specimen_tilt_correction"]) if "specimen_direction_type" not in list(rec.keys()): # assume direction is line - not plane rec["specimen_direction_type"] = 'l' if "specimen_dec" not in list(rec.keys()): # if no declination, set direction type to blank rec["specimen_direction_type"] = '' if "specimen_n" not in list(rec.keys()): rec["specimen_n"] = '' # put in n if "specimen_alpha95" not in list(rec.keys()): rec["specimen_alpha95"] = '' # put in alpha95 if "magic_method_codes" not in list(rec.keys()): rec["magic_method_codes"] = '' # start parsing data into SpecDirs, SpecPlanes, SpecInts SpecInts, SpecDirs, SpecPlanes = [], [], [] samples.sort() # get sorted list of samples and sites sites.sort() if not skip_intensities: # don't skip intensities # retrieve specimens with intensity data IntData = pmag.get_dictitem(Data, 'specimen_int', '', 'F') if nocrit == 0: # use selection criteria for rec in IntData: # do selection criteria kill = pmag.grade(rec, accept, 'specimen_int') if len(kill) == 0: # intensity record to be included in sample, site # calculations SpecInts.append(rec) else: SpecInts = IntData[:] # take everything - no selection criteria # check for required data adjustments if len(corrections) > 0 and len(SpecInts) > 0: for cor in corrections: # only take specimens with the required corrections SpecInts = pmag.get_dictitem( SpecInts, 'magic_method_codes', cor, 'has') if len(nocorrection) > 0 and len(SpecInts) > 0: for cor in nocorrection: # exclude the corrections not specified for inclusion SpecInts = pmag.get_dictitem( SpecInts, 'magic_method_codes', cor, 'not') # take top priority specimen of its name in remaining specimens (only one # per customer) PrioritySpecInts = [] specimens = pmag.get_specs(SpecInts) # get list of uniq specimen names for spec in specimens: # all the records for this specimen ThisSpecRecs = pmag.get_dictitem( SpecInts, 'er_specimen_name', spec, 'T') if len(ThisSpecRecs) == 1: PrioritySpecInts.append(ThisSpecRecs[0]) elif len(ThisSpecRecs) > 1: # more than one prec = [] for p in priorities: # all the records for this specimen ThisSpecRecs = pmag.get_dictitem( SpecInts, 'magic_method_codes', p, 'has') if len(ThisSpecRecs) > 0: prec.append(ThisSpecRecs[0]) PrioritySpecInts.append(prec[0]) # take the best one SpecInts = PrioritySpecInts # this has the first specimen record if not skip_directions: # don't skip directions # retrieve specimens with directed lines and planes AllDirs = pmag.get_dictitem(Data, 'specimen_direction_type', '', 'F') # get all specimens with specimen_n information Ns = pmag.get_dictitem(AllDirs, 'specimen_n', '', 'F') if nocrit != 1: # use selection criteria for rec in Ns: # look through everything with specimen_n for "good" data kill = pmag.grade(rec, accept, 'specimen_dir') if len(kill) == 0: # nothing killed it SpecDirs.append(rec) else: # no criteria SpecDirs = AllDirs[:] # take them all # SpecDirs is now the list of all specimen directions (lines and planes) # that pass muster # list of all sample data and list of those that pass the DE-SAMP criteria PmagSamps, SampDirs = [], [] PmagSites, PmagResults = [], [] # list of all site data and selected results SampInts = [] for samp in samples: # run through the sample names if avg_directions_by_sample: # average by sample if desired # get all the directional data for this sample SampDir = pmag.get_dictitem(SpecDirs, 'er_sample_name', samp, 'T') if len(SampDir) > 0: # there are some directions for coord in coords: # step through desired coordinate systems # get all the directions for this sample CoordDir = pmag.get_dictitem( SampDir, 'specimen_tilt_correction', coord, 'T') if len(CoordDir) > 0: # there are some with this coordinate system if not avg_all_components: # look component by component for comp in Comps: # get all directions from this component CompDir = pmag.get_dictitem( CoordDir, 'specimen_comp_name', comp, 'T') if len(CompDir) > 0: # there are some # get a sample average from all specimens PmagSampRec = pmag.lnpbykey( CompDir, 'sample', 'specimen') # decorate the sample record PmagSampRec["er_location_name"] = CompDir[0]['er_location_name'] PmagSampRec["er_site_name"] = CompDir[0]['er_site_name'] PmagSampRec["er_sample_name"] = samp PmagSampRec["er_citation_names"] = "This study" PmagSampRec["er_analyst_mail_names"] = user PmagSampRec['magic_software_packages'] = version_num if CompDir[0]['specimen_flag'] == 'g': PmagSampRec['sample_flag'] = 'g' else: PmagSampRec['sample_flag'] = 'b' if nocrit != 1: PmagSampRec['pmag_criteria_codes'] = "ACCEPT" if agefile != "": PmagSampRec = pmag.get_age( PmagSampRec, "er_site_name", "sample_inferred_", AgeNFO, DefaultAge) site_height = pmag.get_dictitem( height_nfo, 'er_site_name', PmagSampRec['er_site_name'], 'T') if len(site_height) > 0: # add in height if available PmagSampRec["sample_height"] = site_height[0]['site_height'] PmagSampRec['sample_comp_name'] = comp PmagSampRec['sample_tilt_correction'] = coord PmagSampRec['er_specimen_names'] = pmag.get_list( CompDir, 'er_specimen_name') # get a list of the specimen names used PmagSampRec['magic_method_codes'] = pmag.get_list( CompDir, 'magic_method_codes') # get a list of the methods used if nocrit != 1: # apply selection criteria kill = pmag.grade( PmagSampRec, accept, 'sample_dir') else: kill = [] if len(kill) == 0: SampDirs.append(PmagSampRec) if vgps == 1: # if sample level VGP info desired, do that now PmagResRec = pmag.getsampVGP( PmagSampRec, SiteNFO) if PmagResRec != "": PmagResults.append(PmagResRec) # print(PmagSampRec) PmagSamps.append(PmagSampRec) if avg_all_components: # average all components together basically same as above PmagSampRec = pmag.lnpbykey( CoordDir, 'sample', 'specimen') PmagSampRec["er_location_name"] = CoordDir[0]['er_location_name'] PmagSampRec["er_site_name"] = CoordDir[0]['er_site_name'] PmagSampRec["er_sample_name"] = samp PmagSampRec["er_citation_names"] = "This study" PmagSampRec["er_analyst_mail_names"] = user PmagSampRec['magic_software_packages'] = version_num if all(i['specimen_flag'] == 'g' for i in CoordDir): PmagSampRec['sample_flag'] = 'g' else: PmagSampRec['sample_flag'] = 'b' if nocrit != 1: PmagSampRec['pmag_criteria_codes'] = "" if agefile != "": PmagSampRec = pmag.get_age( PmagSampRec, "er_site_name", "sample_inferred_", AgeNFO, DefaultAge) site_height = pmag.get_dictitem( height_nfo, 'er_site_name', site, 'T') if len(site_height) > 0: # add in height if available PmagSampRec["sample_height"] = site_height[0]['site_height'] PmagSampRec['sample_tilt_correction'] = coord PmagSampRec['sample_comp_name'] = pmag.get_list( CoordDir, 'specimen_comp_name') # get components used PmagSampRec['er_specimen_names'] = pmag.get_list( CoordDir, 'er_specimen_name') # get specimne names averaged PmagSampRec['magic_method_codes'] = pmag.get_list( CoordDir, 'magic_method_codes') # assemble method codes if nocrit != 1: # apply selection criteria kill = pmag.grade( PmagSampRec, accept, 'sample_dir') if len(kill) == 0: # passes the mustard SampDirs.append(PmagSampRec) if vgps == 1: PmagResRec = pmag.getsampVGP( PmagSampRec, SiteNFO) if PmagResRec != "": PmagResults.append(PmagResRec) else: # take everything SampDirs.append(PmagSampRec) if vgps == 1: PmagResRec = pmag.getsampVGP( PmagSampRec, SiteNFO) if PmagResRec != "": PmagResults.append(PmagResRec) PmagSamps.append(PmagSampRec) if avg_intensities_by_sample: # average by sample if desired # get all the intensity data for this sample SampI = pmag.get_dictitem(SpecInts, 'er_sample_name', samp, 'T') if len(SampI) > 0: # there are some # get average intensity stuff PmagSampRec = pmag.average_int(SampI, 'specimen', 'sample') # decorate sample record PmagSampRec["sample_description"] = "sample intensity" PmagSampRec["sample_direction_type"] = "" PmagSampRec['er_site_name'] = SampI[0]["er_site_name"] PmagSampRec['er_sample_name'] = samp PmagSampRec['er_location_name'] = SampI[0]["er_location_name"] PmagSampRec["er_citation_names"] = "This study" PmagSampRec["er_analyst_mail_names"] = user if agefile != "": PmagSampRec = pmag.get_age( PmagSampRec, "er_site_name", "sample_inferred_", AgeNFO, DefaultAge) site_height = pmag.get_dictitem( height_nfo, 'er_site_name', PmagSampRec['er_site_name'], 'T') if len(site_height) > 0: # add in height if available PmagSampRec["sample_height"] = site_height[0]['site_height'] PmagSampRec['er_specimen_names'] = pmag.get_list( SampI, 'er_specimen_name') PmagSampRec['magic_method_codes'] = pmag.get_list( SampI, 'magic_method_codes') if nocrit != 1: # apply criteria! kill = pmag.grade(PmagSampRec, accept, 'sample_int') if len(kill) == 0: PmagSampRec['pmag_criteria_codes'] = "ACCEPT" SampInts.append(PmagSampRec) PmagSamps.append(PmagSampRec) else: PmagSampRec = {} # sample rejected else: # no criteria SampInts.append(PmagSampRec) PmagSamps.append(PmagSampRec) PmagSampRec['pmag_criteria_codes'] = "" if vgps == 1 and get_model_lat != 0 and PmagSampRec != {}: if get_model_lat == 1: # use sample latitude PmagResRec = pmag.getsampVDM(PmagSampRec, SampNFO) # get rid of the model lat key del(PmagResRec['model_lat']) elif get_model_lat == 2: # use model latitude PmagResRec = pmag.getsampVDM(PmagSampRec, ModelLats) if PmagResRec != {}: PmagResRec['magic_method_codes'] = PmagResRec['magic_method_codes'] + ":IE-MLAT" if PmagResRec != {}: PmagResRec['er_specimen_names'] = PmagSampRec['er_specimen_names'] PmagResRec['er_sample_names'] = PmagSampRec['er_sample_name'] PmagResRec['pmag_criteria_codes'] = 'ACCEPT' PmagResRec['average_int_sigma_perc'] = PmagSampRec['sample_int_sigma_perc'] PmagResRec['average_int_sigma'] = PmagSampRec['sample_int_sigma'] PmagResRec['average_int_n'] = PmagSampRec['sample_int_n'] PmagResRec['vadm_n'] = PmagSampRec['sample_int_n'] PmagResRec['data_type'] = 'i' PmagResults.append(PmagResRec) if len(PmagSamps) > 0: # fill in missing keys from different types of records TmpSamps, keylist = pmag.fillkeys(PmagSamps) # save in sample output file pmag.magic_write(sampout, TmpSamps, 'pmag_samples') print(' sample averages written to ', sampout) # # create site averages from specimens or samples as specified # for site in sites: for coord in coords: if not avg_directions_by_sample: key, dirlist = 'specimen', SpecDirs # if specimen averages at site level desired if avg_directions_by_sample: key, dirlist = 'sample', SampDirs # if sample averages at site level desired # get all the sites with directions tmp = pmag.get_dictitem(dirlist, 'er_site_name', site, 'T') # use only the last coordinate if avg_all_components==False tmp1 = pmag.get_dictitem(tmp, key + '_tilt_correction', coord, 'T') # fish out site information (lat/lon, etc.) sd = pmag.get_dictitem(SiteNFO, 'er_site_name', site, 'T') if len(sd) > 0: sitedat = sd[0] if not avg_all_components: # do component wise averaging for comp in Comps: # get all components comp siteD = pmag.get_dictitem( tmp1, key + '_comp_name', comp, 'T') # remove bad data from means quality_siteD = [] # remove any records for which specimen_flag or sample_flag are 'b' # assume 'g' if flag is not provided for rec in siteD: spec_quality = rec.get('specimen_flag', 'g') samp_quality = rec.get('sample_flag', 'g') if (spec_quality == 'g') and (samp_quality == 'g'): quality_siteD.append(rec) siteD = quality_siteD if len(siteD) > 0: # there are some for this site and component name # get an average for this site PmagSiteRec = pmag.lnpbykey(siteD, 'site', key) # decorate the site record PmagSiteRec['site_comp_name'] = comp PmagSiteRec["er_location_name"] = siteD[0]['er_location_name'] PmagSiteRec["er_site_name"] = siteD[0]['er_site_name'] PmagSiteRec['site_tilt_correction'] = coord PmagSiteRec['site_comp_name'] = pmag.get_list( siteD, key + '_comp_name') if avg_directions_by_sample: PmagSiteRec['er_sample_names'] = pmag.get_list( siteD, 'er_sample_name') else: PmagSiteRec['er_specimen_names'] = pmag.get_list( siteD, 'er_specimen_name') # determine the demagnetization code (DC3,4 or 5) for this site AFnum = len(pmag.get_dictitem( siteD, 'magic_method_codes', 'LP-DIR-AF', 'has')) Tnum = len(pmag.get_dictitem( siteD, 'magic_method_codes', 'LP-DIR-T', 'has')) DC = 3 if AFnum > 0: DC += 1 if Tnum > 0: DC += 1 PmagSiteRec['magic_method_codes'] = pmag.get_list( siteD, 'magic_method_codes') + ':' + 'LP-DC' + str(DC) PmagSiteRec['magic_method_codes'].strip(":") if plotsites: print(PmagSiteRec['er_site_name']) # plot and list the data pmagplotlib.plot_site( EQ['eqarea'], PmagSiteRec, siteD, key) pmagplotlib.draw_figs(EQ) PmagSites.append(PmagSiteRec) else: # last component only # get the last orientation system specified siteD = tmp1[:] if len(siteD) > 0: # there are some # get the average for this site PmagSiteRec = pmag.lnpbykey(siteD, 'site', key) # decorate the record PmagSiteRec["er_location_name"] = siteD[0]['er_location_name'] PmagSiteRec["er_site_name"] = siteD[0]['er_site_name'] PmagSiteRec['site_comp_name'] = comp PmagSiteRec['site_tilt_correction'] = coord PmagSiteRec['site_comp_name'] = pmag.get_list( siteD, key + '_comp_name') PmagSiteRec['er_specimen_names'] = pmag.get_list( siteD, 'er_specimen_name') PmagSiteRec['er_sample_names'] = pmag.get_list( siteD, 'er_sample_name') AFnum = len(pmag.get_dictitem( siteD, 'magic_method_codes', 'LP-DIR-AF', 'has')) Tnum = len(pmag.get_dictitem( siteD, 'magic_method_codes', 'LP-DIR-T', 'has')) DC = 3 if AFnum > 0: DC += 1 if Tnum > 0: DC += 1 PmagSiteRec['magic_method_codes'] = pmag.get_list( siteD, 'magic_method_codes') + ':' + 'LP-DC' + str(DC) PmagSiteRec['magic_method_codes'].strip(":") if not avg_directions_by_sample: PmagSiteRec['site_comp_name'] = pmag.get_list( siteD, key + '_comp_name') if plotsites: pmagplotlib.plot_site( EQ['eqarea'], PmagSiteRec, siteD, key) pmagplotlib.draw_figs(EQ) PmagSites.append(PmagSiteRec) else: print('site information not found in er_sites for site, ', site, ' site will be skipped') for PmagSiteRec in PmagSites: # now decorate each dictionary some more, and calculate VGPs etc. for results table PmagSiteRec["er_citation_names"] = "This study" PmagSiteRec["er_analyst_mail_names"] = user PmagSiteRec['magic_software_packages'] = version_num if agefile != "": PmagSiteRec = pmag.get_age( PmagSiteRec, "er_site_name", "site_inferred_", AgeNFO, DefaultAge) PmagSiteRec['pmag_criteria_codes'] = 'ACCEPT' if 'site_n_lines' in list(PmagSiteRec.keys()) and 'site_n_planes' in list(PmagSiteRec.keys()) and PmagSiteRec['site_n_lines'] != "" and PmagSiteRec['site_n_planes'] != "": if int(PmagSiteRec["site_n_planes"]) > 0: PmagSiteRec["magic_method_codes"] = PmagSiteRec['magic_method_codes'] + ":DE-FM-LP" elif int(PmagSiteRec["site_n_lines"]) > 2: PmagSiteRec["magic_method_codes"] = PmagSiteRec['magic_method_codes'] + ":DE-FM" kill = pmag.grade(PmagSiteRec, accept, 'site_dir') if len(kill) == 0: PmagResRec = {} # set up dictionary for the pmag_results table entry PmagResRec['data_type'] = 'i' # decorate it a bit PmagResRec['magic_software_packages'] = version_num PmagSiteRec['site_description'] = 'Site direction included in results table' PmagResRec['pmag_criteria_codes'] = 'ACCEPT' dec = float(PmagSiteRec["site_dec"]) inc = float(PmagSiteRec["site_inc"]) if 'site_alpha95' in list(PmagSiteRec.keys()) and PmagSiteRec['site_alpha95'] != "": a95 = float(PmagSiteRec["site_alpha95"]) else: a95 = 180. sitedat = pmag.get_dictitem(SiteNFO, 'er_site_name', PmagSiteRec['er_site_name'], 'T')[ 0] # fish out site information (lat/lon, etc.) lat = float(sitedat['site_lat']) lon = float(sitedat['site_lon']) plon, plat, dp, dm = pmag.dia_vgp( dec, inc, a95, lat, lon) # get the VGP for this site if PmagSiteRec['site_tilt_correction'] == '-1': C = ' (spec coord) ' if PmagSiteRec['site_tilt_correction'] == '0': C = ' (geog. coord) ' if PmagSiteRec['site_tilt_correction'] == '100': C = ' (strat. coord) ' PmagResRec["pmag_result_name"] = "VGP Site: " + \ PmagSiteRec["er_site_name"] # decorate some more PmagResRec["result_description"] = "Site VGP, coord system = " + \ str(coord) + ' component: ' + comp PmagResRec['er_site_names'] = PmagSiteRec['er_site_name'] PmagResRec['pmag_criteria_codes'] = 'ACCEPT' PmagResRec['er_citation_names'] = 'This study' PmagResRec['er_analyst_mail_names'] = user PmagResRec["er_location_names"] = PmagSiteRec["er_location_name"] if avg_directions_by_sample: PmagResRec["er_sample_names"] = PmagSiteRec["er_sample_names"] else: PmagResRec["er_specimen_names"] = PmagSiteRec["er_specimen_names"] PmagResRec["tilt_correction"] = PmagSiteRec['site_tilt_correction'] PmagResRec["pole_comp_name"] = PmagSiteRec['site_comp_name'] PmagResRec["average_dec"] = PmagSiteRec["site_dec"] PmagResRec["average_inc"] = PmagSiteRec["site_inc"] PmagResRec["average_alpha95"] = PmagSiteRec["site_alpha95"] PmagResRec["average_n"] = PmagSiteRec["site_n"] PmagResRec["average_n_lines"] = PmagSiteRec["site_n_lines"] PmagResRec["average_n_planes"] = PmagSiteRec["site_n_planes"] PmagResRec["vgp_n"] = PmagSiteRec["site_n"] PmagResRec["average_k"] = PmagSiteRec["site_k"] PmagResRec["average_r"] = PmagSiteRec["site_r"] PmagResRec["average_lat"] = '%10.4f ' % (lat) PmagResRec["average_lon"] = '%10.4f ' % (lon) if agefile != "": PmagResRec = pmag.get_age( PmagResRec, "er_site_names", "average_", AgeNFO, DefaultAge) site_height = pmag.get_dictitem( height_nfo, 'er_site_name', site, 'T') if len(site_height) > 0: PmagResRec["average_height"] = site_height[0]['site_height'] PmagResRec["vgp_lat"] = '%7.1f ' % (plat) PmagResRec["vgp_lon"] = '%7.1f ' % (plon) PmagResRec["vgp_dp"] = '%7.1f ' % (dp) PmagResRec["vgp_dm"] = '%7.1f ' % (dm) PmagResRec["magic_method_codes"] = PmagSiteRec["magic_method_codes"] if '0' in PmagSiteRec['site_tilt_correction'] and "DA-DIR-GEO" not in PmagSiteRec['magic_method_codes']: PmagSiteRec['magic_method_codes'] = PmagSiteRec['magic_method_codes'] + ":DA-DIR-GEO" if '100' in PmagSiteRec['site_tilt_correction'] and "DA-DIR-TILT" not in PmagSiteRec['magic_method_codes']: PmagSiteRec['magic_method_codes'] = PmagSiteRec['magic_method_codes'] + ":DA-DIR-TILT" PmagSiteRec['site_polarity'] = "" if avg_by_polarity: # assign polarity based on angle of pole lat to spin axis - may want to re-think this sometime angle = pmag.angle([0, 0], [0, (90 - plat)]) if angle <= 55.: PmagSiteRec["site_polarity"] = 'n' if angle > 55. and angle < 125.: PmagSiteRec["site_polarity"] = 't' if angle >= 125.: PmagSiteRec["site_polarity"] = 'r' PmagResults.append(PmagResRec) if avg_by_polarity: # find the tilt corrected data crecs = pmag.get_dictitem( PmagSites, 'site_tilt_correction', '100', 'T') if len(crecs) < 2: # if there aren't any, find the geographic corrected data crecs = pmag.get_dictitem( PmagSites, 'site_tilt_correction', '0', 'T') if len(crecs) > 2: # if there are some, comp = pmag.get_list(crecs, 'site_comp_name').split(':')[ 0] # find the first component # fish out all of the first component crecs = pmag.get_dictitem(crecs, 'site_comp_name', comp, 'T') precs = [] for rec in crecs: precs.append({'dec': rec['site_dec'], 'inc': rec['site_inc'], 'name': rec['er_site_name'], 'loc': rec['er_location_name']}) # calculate average by polarity polpars = pmag.fisher_by_pol(precs) # hunt through all the modes (normal=A, reverse=B, all=ALL) for mode in list(polpars.keys()): PolRes = {} PolRes['er_citation_names'] = 'This study' PolRes["pmag_result_name"] = "Polarity Average: Polarity " + mode PolRes["data_type"] = "a" PolRes["average_dec"] = '%7.1f' % (polpars[mode]['dec']) PolRes["average_inc"] = '%7.1f' % (polpars[mode]['inc']) PolRes["average_n"] = '%i' % (polpars[mode]['n']) PolRes["average_r"] = '%5.4f' % (polpars[mode]['r']) PolRes["average_k"] = '%6.0f' % (polpars[mode]['k']) PolRes["average_alpha95"] = '%7.1f' % ( polpars[mode]['alpha95']) PolRes['er_site_names'] = polpars[mode]['sites'] PolRes['er_location_names'] = polpars[mode]['locs'] PolRes['magic_software_packages'] = version_num PmagResults.append(PolRes) if not skip_intensities and nositeints != 1: for site in sites: # now do intensities for each site if plotsites: print(site) if not avg_intensities_by_sample: key, intlist = 'specimen', SpecInts # if using specimen level data if avg_intensities_by_sample: key, intlist = 'sample', PmagSamps # if using sample level data # get all the intensities for this site Ints = pmag.get_dictitem(intlist, 'er_site_name', site, 'T') if len(Ints) > 0: # there are some # get average intensity stuff for site table PmagSiteRec = pmag.average_int(Ints, key, 'site') # get average intensity stuff for results table PmagResRec = pmag.average_int(Ints, key, 'average') if plotsites: # if site by site examination requested - print this site out to the screen for rec in Ints: print(rec['er_' + key + '_name'], ' %7.1f' % (1e6 * float(rec[key + '_int']))) if len(Ints) > 1: print('Average: ', '%7.1f' % ( 1e6 * float(PmagResRec['average_int'])), 'N: ', len(Ints)) print('Sigma: ', '%7.1f' % ( 1e6 * float(PmagResRec['average_int_sigma'])), 'Sigma %: ', PmagResRec['average_int_sigma_perc']) input('Press any key to continue\n') er_location_name = Ints[0]["er_location_name"] # decorate the records PmagSiteRec["er_location_name"] = er_location_name PmagSiteRec["er_citation_names"] = "This study" PmagResRec["er_location_names"] = er_location_name PmagResRec["er_citation_names"] = "This study" PmagSiteRec["er_analyst_mail_names"] = user PmagResRec["er_analyst_mail_names"] = user PmagResRec["data_type"] = 'i' if not avg_intensities_by_sample: PmagSiteRec['er_specimen_names'] = pmag.get_list( Ints, 'er_specimen_name') # list of all specimens used PmagResRec['er_specimen_names'] = pmag.get_list( Ints, 'er_specimen_name') PmagSiteRec['er_sample_names'] = pmag.get_list( Ints, 'er_sample_name') # list of all samples used PmagResRec['er_sample_names'] = pmag.get_list( Ints, 'er_sample_name') PmagSiteRec['er_site_name'] = site PmagResRec['er_site_names'] = site PmagSiteRec['magic_method_codes'] = pmag.get_list( Ints, 'magic_method_codes') PmagResRec['magic_method_codes'] = pmag.get_list( Ints, 'magic_method_codes') kill = pmag.grade(PmagSiteRec, accept, 'site_int') if nocrit == 1 or len(kill) == 0: b, sig = float(PmagResRec['average_int']), "" if(PmagResRec['average_int_sigma']) != "": sig = float(PmagResRec['average_int_sigma']) # fish out site direction sdir = pmag.get_dictitem( PmagResults, 'er_site_names', site, 'T') # get the VDM for this record using last average # inclination (hope it is the right one!) if len(sdir) > 0 and sdir[-1]['average_inc'] != "": inc = float(sdir[0]['average_inc']) # get magnetic latitude using dipole formula mlat = pmag.magnetic_lat(inc) # get VDM with magnetic latitude PmagResRec["vdm"] = '%8.3e ' % (pmag.b_vdm(b, mlat)) PmagResRec["vdm_n"] = PmagResRec['average_int_n'] if 'average_int_sigma' in list(PmagResRec.keys()) and PmagResRec['average_int_sigma'] != "": vdm_sig = pmag.b_vdm( float(PmagResRec['average_int_sigma']), mlat) PmagResRec["vdm_sigma"] = '%8.3e ' % (vdm_sig) else: PmagResRec["vdm_sigma"] = "" mlat = "" # define a model latitude if get_model_lat == 1: # use present site latitude mlats = pmag.get_dictitem( SiteNFO, 'er_site_name', site, 'T') if len(mlats) > 0: mlat = mlats[0]['site_lat'] # use a model latitude from some plate reconstruction model # (or something) elif get_model_lat == 2: mlats = pmag.get_dictitem( ModelLats, 'er_site_name', site, 'T') if len(mlats) > 0: PmagResRec['model_lat'] = mlats[0]['site_model_lat'] mlat = PmagResRec['model_lat'] if mlat != "": # get the VADM using the desired latitude PmagResRec["vadm"] = '%8.3e ' % ( pmag.b_vdm(b, float(mlat))) if sig != "": vdm_sig = pmag.b_vdm( float(PmagResRec['average_int_sigma']), float(mlat)) PmagResRec["vadm_sigma"] = '%8.3e ' % (vdm_sig) PmagResRec["vadm_n"] = PmagResRec['average_int_n'] else: PmagResRec["vadm_sigma"] = "" # fish out site information (lat/lon, etc.) sitedat = pmag.get_dictitem( SiteNFO, 'er_site_name', PmagSiteRec['er_site_name'], 'T') if len(sitedat) > 0: sitedat = sitedat[0] PmagResRec['average_lat'] = sitedat['site_lat'] PmagResRec['average_lon'] = sitedat['site_lon'] else: PmagResRec['average_lon'] = 'UNKNOWN' PmagResRec['average_lon'] = 'UNKNOWN' PmagResRec['magic_software_packages'] = version_num PmagResRec["pmag_result_name"] = "V[A]DM: Site " + site PmagResRec["result_description"] = "V[A]DM of site" PmagResRec["pmag_criteria_codes"] = "ACCEPT" if agefile != "": PmagResRec = pmag.get_age( PmagResRec, "er_site_names", "average_", AgeNFO, DefaultAge) site_height = pmag.get_dictitem( height_nfo, 'er_site_name', site, 'T') if len(site_height) > 0: PmagResRec["average_height"] = site_height[0]['site_height'] PmagSites.append(PmagSiteRec) PmagResults.append(PmagResRec) if len(PmagSites) > 0: Tmp, keylist = pmag.fillkeys(PmagSites) pmag.magic_write(siteout, Tmp, 'pmag_sites') print(' sites written to ', siteout) else: print("No Site level table") if len(PmagResults) > 0: TmpRes, keylist = pmag.fillkeys(PmagResults) pmag.magic_write(resout, TmpRes, 'pmag_results') print(' results written to ', resout) else: print("No Results level table") def orientation_magic(or_con=1, dec_correction_con=1, dec_correction=0, bed_correction=True, samp_con='1', hours_from_gmt=0, method_codes='', average_bedding=False, orient_file='orient.txt', samp_file='samples.txt', site_file='sites.txt', output_dir_path='.', input_dir_path='.', append=False, data_model=3): """ use this function to convert tab delimited field notebook information to MagIC formatted tables (er_samples and er_sites) INPUT FORMAT Input files must be tab delimited and have in the first line: tab location_name Note: The "location_name" will facilitate searching in the MagIC database. Data from different "locations" should be put in separate files. The definition of a "location" is rather loose. Also this is the word 'tab' not a tab, which will be indicated by '\t'. The second line has the names of the columns (tab delimited), e.g.: site_name sample_name mag_azimuth field_dip date lat long sample_lithology sample_type sample_class shadow_angle hhmm stratigraphic_height bedding_dip_direction bedding_dip GPS_baseline image_name image_look image_photographer participants method_codes site_description sample_description GPS_Az, sample_igsn, sample_texture, sample_cooling_rate, cooling_rate_corr, cooling_rate_mcd Notes: 1) column order doesn't matter but the NAMES do. 2) sample_name, sample_lithology, sample_type, sample_class, lat and long are required. all others are optional. 3) If subsequent data are the same (e.g., date, bedding orientation, participants, stratigraphic_height), you can leave the field blank and the program will fill in the last recorded information. BUT if you really want a blank stratigraphic_height, enter a '-1'. These will not be inherited and must be specified for each entry: image_name, look, photographer or method_codes 4) hhmm must be in the format: hh:mm and the hh must be in 24 hour time. date must be mm/dd/yy (years < 50 will be converted to 20yy and >50 will be assumed 19yy). hours_from_gmt is the number of hours to SUBTRACT from hh to get to GMT. 5) image_name, image_look and image_photographer are colon delimited lists of file name (e.g., IMG_001.jpg) image look direction and the name of the photographer respectively. If all images had same look and photographer, just enter info once. The images will be assigned to the site for which they were taken - not at the sample level. 6) participants: Names of who helped take the samples. These must be a colon delimited list. 7) method_codes: Special method codes on a sample level, e.g., SO-GT5 which means the orientation is has an uncertainty of >5 degrees for example if it broke off before orienting.... 8) GPS_Az is the place to put directly determined GPS Azimuths, using, e.g., points along the drill direction. 9) sample_cooling_rate is the cooling rate in K per Ma 10) int_corr_cooling_rate 11) cooling_rate_mcd: data adjustment method code for cooling rate correction; DA-CR-EG is educated guess; DA-CR-PS is percent estimated from pilot samples; DA-CR-TRM is comparison between 2 TRMs acquired with slow and rapid cooling rates. is the percent cooling rate factor to apply to specimens from this sample, DA-CR-XX is the method code defaults: orientation_magic(or_con=1, dec_correction_con=1, dec_correction=0, bed_correction=True, samp_con='1', hours_from_gmt=0, method_codes='', average_bedding=False, orient_file='orient.txt', samp_file='er_samples.txt', site_file='er_sites.txt', output_dir_path='.', input_dir_path='.', append=False): orientation conventions: [1] Standard Pomeroy convention of azimuth and hade (degrees from vertical down) of the drill direction (field arrow). lab arrow azimuth= sample_azimuth = mag_azimuth; lab arrow dip = sample_dip =-field_dip. i.e. the lab arrow dip is minus the hade. [2] Field arrow is the strike of the plane orthogonal to the drill direction, Field dip is the hade of the drill direction. Lab arrow azimuth = mag_azimuth-90 Lab arrow dip = -field_dip [3] Lab arrow is the same as the drill direction; hade was measured in the field. Lab arrow azimuth = mag_azimuth; Lab arrow dip = 90-field_dip [4] lab azimuth and dip are same as mag_azimuth, field_dip : use this for unoriented samples too [5] Same as AZDIP convention explained below - azimuth and inclination of the drill direction are mag_azimuth and field_dip; lab arrow is as in [1] above. lab azimuth is same as mag_azimuth,lab arrow dip=field_dip-90 [6] Lab arrow azimuth = mag_azimuth-90; Lab arrow dip = 90-field_dip [7] see http://earthref.org/PmagPy/cookbook/#field_info for more information. You can customize other format yourself, or email ltauxe@ucsd.edu for help. Magnetic declination convention: [1] Use the IGRF value at the lat/long and date supplied [default] [2] Will supply declination correction [3] mag_az is already corrected in file [4] Correct mag_az but not bedding_dip_dir 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 = sample name [6] site name entered in site_name column in the orient.txt format input file -- NOT CURRENTLY SUPPORTED [7-Z] [XXX]YYY: XXX is site designation with Z characters from samples XXXYYY NB: all others you will have to either customize your self or e-mail ltauxe@ucsd.edu for help. """ # initialize some variables # bed_correction used to be BedCorr # dec_correction_con used to be corr # dec_correction used to be DecCorr # meths is now method_codes # delta_u is now hours_from_gmt or_con, dec_correction_con, dec_correction = int( or_con), int(dec_correction_con), float(dec_correction) hours_from_gmt = float(hours_from_gmt) stratpos = "" # date of sampling, latitude (pos North), longitude (pos East) date, lat, lon = "", "", "" bed_dip, bed_dip_dir = "", "" Lats, Lons = [], [] # list of latitudes and longitudes # lists of Sample records and Site records SampOuts, SiteOuts, ImageOuts = [], [], [] samplelist, sitelist, imagelist = [], [], [] Z = 1 newbaseline, newbeddir, newbeddip = "", "", "" fpars = [] sclass, lithology, sample_type = "", "", "" newclass, newlith, newtype = '', '', '' BPs = [] # bedding pole declinations, bedding pole inclinations image_file = "er_images.txt" # # use 3.0. default filenames when in 3.0. # but, still allow for custom names data_model = int(data_model) if data_model == 3: if samp_file == "er_samples.txt": samp_file = "samples.txt" if site_file == "er_sites.txt": site_file = "sites.txt" image_file = "images.txt" orient_file = pmag.resolve_file_name(orient_file, input_dir_path) if not os.path.exists(orient_file): return False, "No such file: {}. If the orientation file is not in your current working directory, make sure you have specified the correct input directory.".format(orient_file) samp_file = os.path.join(output_dir_path, samp_file) site_file = os.path.join(output_dir_path, site_file) image_file = os.path.join(output_dir_path, image_file) # validate input if '4' in samp_con[0]: pattern = re.compile('[4][-]\d') result = pattern.match(samp_con) if not result: raise Exception( "If using sample naming convention 4, you must provide the number of characters with which to distinguish sample from site. [4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX)") if '7' in samp_con[0]: pattern = re.compile('[7][-]\d') result = pattern.match(samp_con) if not result: raise Exception( "If using sample naming convention 7, you must provide the number of characters with which to distinguish sample from site. [7-Z] [XXX]YYY: XXX is site designation with Z characters from samples XXXYYY") if dec_correction_con == 2 and not dec_correction: raise Exception( "If using magnetic declination convention 2, you must also provide a declincation correction in degrees") SampRecs, SiteRecs, ImageRecs = [], [], [] SampRecs_sorted, SiteRecs_sorted = {}, {} if append: try: SampRecs, file_type = pmag.magic_read(samp_file) # convert 3.0. sample file to 2.5 format if data_model == 3: SampRecs3 = SampRecs SampRecs = [] for samp_rec in SampRecs3: rec = map_magic.mapping( samp_rec, map_magic.samp_magic3_2_magic2_map) SampRecs.append(rec) # magic_data dictionary sorted by sample_name SampRecs_sorted = pmag.sort_magic_data(SampRecs, 'er_sample_name') print('sample data to be appended to: ', samp_file) except Exception as ex: print(ex) print('problem with existing file: ', samp_file, ' will create new.') try: SiteRecs, file_type = pmag.magic_read(site_file) # convert 3.0. site file to 2.5 format if data_model == 3: SiteRecs3 = SiteRecs SiteRecs = [] for site_rec in SiteRecs3: SiteRecs.append(map_magic.mapping( site_rec, map_magic.site_magic3_2_magic2_map)) # magic_data dictionary sorted by site_name SiteRecs_sorted = pmag.sort_magic_data(SiteRecs, 'er_site_name') print('site data to be appended to: ', site_file) except Exception as ex: print(ex) print('problem with existing file: ', site_file, ' will create new.') try: ImageRecs, file_type = pmag.magic_read(image_file) # convert from 3.0. --> 2.5 if data_model == 3: ImageRecs3 = ImageRecs ImageRecs = [] for image_rec in ImageRecs3: ImageRecs.append(map_magic.mapping( image_rec, map_magic.image_magic3_2_magic2_map)) print('image data to be appended to: ', image_file) except: print('problem with existing file: ', image_file, ' will create new.') # # read in file to convert # OrData, location_name = pmag.magic_read(orient_file) if location_name == "demag_orient": location_name = "" # # step through the data sample by sample # # use map_magic in here... for OrRec in OrData: if 'mag_azimuth' not in list(OrRec.keys()): OrRec['mag_azimuth'] = "" if 'field_dip' not in list(OrRec.keys()): OrRec['field_dip'] = "" if OrRec['mag_azimuth'] == " ": OrRec["mag_azimuth"] = "" if OrRec['field_dip'] == " ": OrRec["field_dip"] = "" if 'sample_description' in list(OrRec.keys()): sample_description = OrRec['sample_description'] else: sample_description = "" if 'cooling_rate_corr' in list(OrRec.keys()): if 'cooling_rate_mcd' not in list(OrRec.keys()): OrRec['cooling_rate_mcd'] = 'DA-CR' sample_orientation_flag = 'g' if 'sample_orientation_flag' in list(OrRec.keys()): if OrRec['sample_orientation_flag'] == 'b' or OrRec["mag_azimuth"] == "": sample_orientation_flag = 'b' methcodes = method_codes # initialize method codes if methcodes: if 'method_codes' in list(OrRec.keys()) and OrRec['method_codes'].strip() != "": methcodes = methcodes + ":" + \ OrRec['method_codes'] # add notes else: if 'method_codes' in list(OrRec.keys()) and OrRec['method_codes'].strip() != "": methcodes = OrRec['method_codes'] # add notes codes = methcodes.replace(" ", "").split(":") sample_name = OrRec["sample_name"] # patch added by rshaar 7/2016 # if sample_name already exists in er_samples.txt: # merge the new data colmuns calculated by orientation_magic with the existing data colmuns # this is done to make sure no previous data in er_samples.txt and # er_sites.txt is lost. if sample_name in list(SampRecs_sorted.keys()): Prev_MagRec = SampRecs_sorted[sample_name][-1] MagRec = Prev_MagRec else: Prev_MagRec = {} MagRec = {} MagRec["er_citation_names"] = "This study" # the following keys were calculated or defined in the code above: for key in ['sample_igsn', 'sample_texture', 'sample_cooling_rate', 'cooling_rate_corr', 'cooling_rate_mcd']: val = OrRec.get(key, '') if val: MagRec[key] = val elif key in list(Prev_MagRec.keys()): MagRec[key] = Prev_MagRec[key] else: MagRec[key] = "" if location_name != "": MagRec["er_location_name"] = location_name elif "er_location_name" in list(Prev_MagRec.keys()): MagRec["er_location_name"] = Prev_MagRec["er_location_name"] else: MagRec["er_location_name"] = "" # the following keys are taken directly from OrRec dictionary: for key in ["sample_height", "er_sample_alternatives", "sample_orientation_flag"]: if key in list(OrRec.keys()) and OrRec[key] != "": MagRec[key] = OrRec[key] elif key in list(Prev_MagRec.keys()): MagRec[key] = Prev_MagRec[key] else: MagRec[key] = "" # the following keys, if blank, used to be defined here as "Not Specified" : for key in ["sample_class", "sample_lithology", "sample_type"]: if key in list(OrRec.keys()) and OrRec[key] != "" and OrRec[key] != "Not Specified": MagRec[key] = OrRec[key] elif key in list(Prev_MagRec.keys()) and Prev_MagRec[key] != "" and Prev_MagRec[key] != "Not Specified": MagRec[key] = Prev_MagRec[key] else: MagRec[key] = "" # "Not Specified" # (rshaar) From here parse new information and replace previous, if exists: # # parse information common to all orientation methods # MagRec["er_sample_name"] = OrRec["sample_name"] if "IGSN" in list(OrRec.keys()): MagRec["sample_igsn"] = OrRec["IGSN"] else: MagRec["sample_igsn"] = "" # MagRec["sample_height"],MagRec["sample_bed_dip_direction"],MagRec["sample_bed_dip"]="","","" MagRec["sample_bed_dip_direction"], MagRec["sample_bed_dip"] = "", "" # if "er_sample_alternatives" in OrRec.keys(): # MagRec["er_sample_alternatives"]=OrRec["sample_alternatives"] sample = OrRec["sample_name"] if OrRec['mag_azimuth'] == "" and OrRec['field_dip'] != "": OrRec['mag_azimuth'] = '999' if OrRec["mag_azimuth"] != "": labaz, labdip = pmag.orient( float(OrRec["mag_azimuth"]), float(OrRec["field_dip"]), or_con) if labaz < 0: labaz += 360. else: labaz, labdip = "", "" if OrRec['mag_azimuth'] == '999': labaz = "" if "GPS_baseline" in list(OrRec.keys()) and OrRec['GPS_baseline'] != "": newbaseline = OrRec["GPS_baseline"] if newbaseline != "": baseline = float(newbaseline) MagRec['er_scientist_mail_names'] = OrRec.get('participants', '') newlat = OrRec["lat"] if newlat != "": lat = float(newlat) if lat == "": print("No latitude specified for ! ", sample, ". Latitude is required for all samples.") return False, "No latitude specified for ! " + sample + ". Latitude is required for all samples." MagRec["sample_lat"] = '%11.5f' % (lat) newlon = OrRec["long"] if newlon != "": lon = float(newlon) if lon == "": print("No longitude specified for ! ", sample, ". Longitude is required for all samples.") return False, str("No longitude specified for ! " + sample + ". Longitude is required for all samples.") MagRec["sample_lon"] = '%11.5f' % (lon) if 'bedding_dip_direction' in list(OrRec.keys()): newbeddir = OrRec["bedding_dip_direction"] if newbeddir != "": bed_dip_dir = OrRec['bedding_dip_direction'] if 'bedding_dip' in list(OrRec.keys()): newbeddip = OrRec["bedding_dip"] if newbeddip != "": bed_dip = OrRec['bedding_dip'] MagRec["sample_bed_dip"] = bed_dip MagRec["sample_bed_dip_direction"] = bed_dip_dir # MagRec["sample_type"]=sample_type if labdip != "": MagRec["sample_dip"] = '%7.1f' % labdip else: MagRec["sample_dip"] = "" if "date" in list(OrRec.keys()) and OrRec["date"] != "": newdate = OrRec["date"] if newdate != "": date = newdate mmddyy = date.split('/') yy = int(mmddyy[2]) if yy > 50: yy = 1900 + yy else: yy = 2000 + yy decimal_year = yy + old_div(float(mmddyy[0]), 12) sample_date = '%i:%s:%s' % (yy, mmddyy[0], mmddyy[1]) time = OrRec['hhmm'] if time: sample_date += (':' + time) MagRec["sample_date"] = sample_date.strip(':') if labaz != "": MagRec["sample_azimuth"] = '%7.1f' % (labaz) else: MagRec["sample_azimuth"] = "" if "stratigraphic_height" in list(OrRec.keys()): if OrRec["stratigraphic_height"] != "": MagRec["sample_height"] = OrRec["stratigraphic_height"] stratpos = OrRec["stratigraphic_height"] elif OrRec["stratigraphic_height"] == '-1': MagRec["sample_height"] = "" # make empty elif stratpos != "": # keep last record if blank MagRec["sample_height"] = stratpos # # get magnetic declination (corrected with igrf value) if dec_correction_con == 1 and MagRec['sample_azimuth'] != "": x, y, z, f = pmag.doigrf(lon, lat, 0, decimal_year) Dir = pmag.cart2dir((x, y, z)) dec_correction = Dir[0] if "bedding_dip" in list(OrRec.keys()): if OrRec["bedding_dip"] != "": MagRec["sample_bed_dip"] = OrRec["bedding_dip"] bed_dip = OrRec["bedding_dip"] else: MagRec["sample_bed_dip"] = bed_dip else: MagRec["sample_bed_dip"] = '0' if "bedding_dip_direction" in list(OrRec.keys()): if OrRec["bedding_dip_direction"] != "" and bed_correction == 1: dd = float(OrRec["bedding_dip_direction"]) + dec_correction if dd > 360.: dd = dd - 360. MagRec["sample_bed_dip_direction"] = '%7.1f' % (dd) dip_dir = MagRec["sample_bed_dip_direction"] else: MagRec["sample_bed_dip_direction"] = OrRec['bedding_dip_direction'] else: MagRec["sample_bed_dip_direction"] = '0' if average_bedding: if str(MagRec["sample_bed_dip_direction"]) and str(MagRec["sample_bed_dip"]): BPs.append([float(MagRec["sample_bed_dip_direction"]), float(MagRec["sample_bed_dip"]) - 90., 1.]) if MagRec['sample_azimuth'] == "" and MagRec['sample_dip'] == "": MagRec["sample_declination_correction"] = '' methcodes = methcodes + ':SO-NO' MagRec["magic_method_codes"] = methcodes MagRec['sample_description'] = sample_description # # work on the site stuff too if 'site_name' in list(OrRec.keys()) and OrRec['site_name'] != "": site = OrRec['site_name'] elif 'site_name' in list(Prev_MagRec.keys()) and Prev_MagRec['site_name'] != "": site = Prev_MagRec['site_name'] else: # parse out the site name site = pmag.parse_site(OrRec["sample_name"], samp_con, Z) MagRec["er_site_name"] = site site_description = "" # overwrite any prior description if 'site_description' in list(OrRec.keys()) and OrRec['site_description'] != "": site_description = OrRec['site_description'].replace(",", ";") if "image_name" in list(OrRec.keys()): images = OrRec["image_name"].split(":") if "image_look" in list(OrRec.keys()): looks = OrRec['image_look'].split(":") else: looks = [] if "image_photographer" in list(OrRec.keys()): photographers = OrRec['image_photographer'].split(":") else: photographers = [] for image in images: if image != "" and image not in imagelist: imagelist.append(image) ImageRec = {} ImageRec['er_image_name'] = image ImageRec['image_type'] = "outcrop" ImageRec['image_date'] = sample_date ImageRec['er_citation_names'] = "This study" ImageRec['er_location_name'] = location_name ImageRec['er_site_name'] = MagRec['er_site_name'] k = images.index(image) if len(looks) > k: ImageRec['er_image_description'] = "Look direction: " + looks[k] elif len(looks) >= 1: ImageRec['er_image_description'] = "Look direction: " + looks[-1] else: ImageRec['er_image_description'] = "Look direction: unknown" if len(photographers) > k: ImageRec['er_photographer_mail_names'] = photographers[k] elif len(photographers) >= 1: ImageRec['er_photographer_mail_names'] = photographers[-1] else: ImageRec['er_photographer_mail_names'] = "unknown" ImageOuts.append(ImageRec) if site not in sitelist: sitelist.append(site) # collect unique site names # patch added by rshaar 7/2016 # if sample_name already exists in er_samples.txt: # merge the new data colmuns calculated by orientation_magic with the existing data colmuns # this is done to make sure no previous data in er_samples.txt and # er_sites.txt is lost. if site in list(SiteRecs_sorted.keys()): Prev_MagRec = SiteRecs_sorted[site][-1] SiteRec = Prev_MagRec else: Prev_MagRec = {} SiteRec = {} SiteRec["er_citation_names"] = "This study" SiteRec["er_site_name"] = site SiteRec["site_definition"] = "s" if "er_location_name" in SiteRec and SiteRec.get("er_location_name"): pass elif key in list(Prev_MagRec.keys()) and Prev_MagRec[key] != "": SiteRec[key] = Prev_MagRec[key] else: print('setting location name to ""') SiteRec[key] = "" for key in ["lat", "lon", "height"]: if "site_" + key in list(Prev_MagRec.keys()) and Prev_MagRec["site_" + key] != "": SiteRec["site_" + key] = Prev_MagRec["site_" + key] else: SiteRec["site_" + key] = MagRec["sample_" + key] # SiteRec["site_lat"]=MagRec["sample_lat"] # SiteRec["site_lon"]=MagRec["sample_lon"] # SiteRec["site_height"]=MagRec["sample_height"] for key in ["class", "lithology", "type"]: if "site_" + key in list(Prev_MagRec.keys()) and Prev_MagRec["site_" + key] != "Not Specified": SiteRec["site_" + key] = Prev_MagRec["site_" + key] else: SiteRec["site_" + key] = MagRec["sample_" + key] # SiteRec["site_class"]=MagRec["sample_class"] # SiteRec["site_lithology"]=MagRec["sample_lithology"] # SiteRec["site_type"]=MagRec["sample_type"] if site_description != "": # overwrite only if site_description has something SiteRec["site_description"] = site_description SiteOuts.append(SiteRec) if sample not in samplelist: samplelist.append(sample) if MagRec['sample_azimuth'] != "": # assume magnetic compass only MagRec['magic_method_codes'] = MagRec['magic_method_codes'] + ':SO-MAG' MagRec['magic_method_codes'] = MagRec['magic_method_codes'].strip( ":") SampOuts.append(MagRec) if MagRec['sample_azimuth'] != "" and dec_correction_con != 3: az = labaz + dec_correction if az > 360.: az = az - 360. CMDRec = {} for key in list(MagRec.keys()): CMDRec[key] = MagRec[key] # make a copy of MagRec CMDRec["sample_azimuth"] = '%7.1f' % (az) CMDRec["magic_method_codes"] = methcodes + ':SO-CMD-NORTH' CMDRec["magic_method_codes"] = CMDRec['magic_method_codes'].strip( ':') CMDRec["sample_declination_correction"] = '%7.1f' % ( dec_correction) if dec_correction_con == 1: CMDRec['sample_description'] = sample_description + \ ':Declination correction calculated from IGRF' else: CMDRec['sample_description'] = sample_description + \ ':Declination correction supplied by user' CMDRec["sample_description"] = CMDRec['sample_description'].strip( ':') SampOuts.append(CMDRec) if "mag_az_bs" in list(OrRec.keys()) and OrRec["mag_az_bs"] != "" and OrRec["mag_az_bs"] != " ": SRec = {} for key in list(MagRec.keys()): SRec[key] = MagRec[key] # make a copy of MagRec labaz = float(OrRec["mag_az_bs"]) az = labaz + dec_correction if az > 360.: az = az - 360. SRec["sample_azimuth"] = '%7.1f' % (az) SRec["sample_declination_correction"] = '%7.1f' % ( dec_correction) SRec["magic_method_codes"] = methcodes + \ ':SO-SIGHT-BACK:SO-CMD-NORTH' SampOuts.append(SRec) # # check for suncompass data # # there are sun compass data if "shadow_angle" in list(OrRec.keys()) and OrRec["shadow_angle"] != "": if hours_from_gmt == "": #hours_from_gmt=raw_input("Enter hours to subtract from time for GMT: [0] ") hours_from_gmt = 0 SunRec, sundata = {}, {} shad_az = float(OrRec["shadow_angle"]) if not OrRec["hhmm"]: print('If using the column shadow_angle for sun compass data, you must also provide the time for each sample. Sample ', sample, ' has shadow_angle but is missing the "hh:mm" column.') else: # calculate sun declination sundata["date"] = '%i:%s:%s:%s' % ( yy, mmddyy[0], mmddyy[1], OrRec["hhmm"]) sundata["delta_u"] = hours_from_gmt sundata["lon"] = lon # do not truncate! sundata["lat"] = lat # do not truncate! sundata["shadow_angle"] = OrRec["shadow_angle"] # now you can truncate sundec = '%7.1f' % (pmag.dosundec(sundata)) for key in list(MagRec.keys()): SunRec[key] = MagRec[key] # make a copy of MagRec SunRec["sample_azimuth"] = sundec # do not truncate! SunRec["sample_declination_correction"] = '' SunRec["magic_method_codes"] = methcodes + ':SO-SUN' SunRec["magic_method_codes"] = SunRec['magic_method_codes'].strip( ':') SampOuts.append(SunRec) # # check for differential GPS data # # there are diff GPS data if "prism_angle" in list(OrRec.keys()) and OrRec["prism_angle"] != "": GPSRec = {} for key in list(MagRec.keys()): GPSRec[key] = MagRec[key] # make a copy of MagRec prism_angle = float(OrRec["prism_angle"]) sundata["shadow_angle"] = OrRec["shadow_angle"] sundec = pmag.dosundec(sundata) for key in list(MagRec.keys()): SunRec[key] = MagRec[key] # make a copy of MagRec SunRec["sample_azimuth"] = '%7.1f' % (sundec) SunRec["sample_declination_correction"] = '' SunRec["magic_method_codes"] = methcodes + ':SO-SUN' SunRec["magic_method_codes"] = SunRec['magic_method_codes'].strip( ':') SampOuts.append(SunRec) # # check for differential GPS data # # there are diff GPS data if "prism_angle" in list(OrRec.keys()) and OrRec["prism_angle"] != "": GPSRec = {} for key in list(MagRec.keys()): GPSRec[key] = MagRec[key] # make a copy of MagRec prism_angle = float(OrRec["prism_angle"]) laser_angle = float(OrRec["laser_angle"]) if OrRec["GPS_baseline"] != "": baseline = float(OrRec["GPS_baseline"]) # new baseline gps_dec = baseline + laser_angle + prism_angle - 90. while gps_dec > 360.: gps_dec = gps_dec - 360. while gps_dec < 0: gps_dec = gps_dec + 360. for key in list(MagRec.keys()): GPSRec[key] = MagRec[key] # make a copy of MagRec GPSRec["sample_azimuth"] = '%7.1f' % (gps_dec) GPSRec["sample_declination_correction"] = '' GPSRec["magic_method_codes"] = methcodes + ':SO-GPS-DIFF' SampOuts.append(GPSRec) # there are differential GPS Azimuth data if "GPS_Az" in list(OrRec.keys()) and OrRec["GPS_Az"] != "": GPSRec = {} for key in list(MagRec.keys()): GPSRec[key] = MagRec[key] # make a copy of MagRec GPSRec["sample_azimuth"] = '%7.1f' % (float(OrRec["GPS_Az"])) GPSRec["sample_declination_correction"] = '' GPSRec["magic_method_codes"] = methcodes + ':SO-GPS-DIFF' SampOuts.append(GPSRec) if average_bedding != "0" and fpars: fpars = pmag.fisher_mean(BPs) print('over-writing all bedding with average ') Samps = [] for rec in SampOuts: if average_bedding != "0" and fpars: rec['sample_bed_dip_direction'] = '%7.1f' % (fpars['dec']) rec['sample_bed_dip'] = '%7.1f' % (fpars['inc'] + 90.) Samps.append(rec) else: Samps.append(rec) for rec in SampRecs: if rec['er_sample_name'] not in samplelist: # overwrite prior for this sample Samps.append(rec) for rec in SiteRecs: if rec['er_site_name'] not in sitelist: # overwrite prior for this sample SiteOuts.append(rec) for rec in ImageRecs: if rec['er_image_name'] not in imagelist: # overwrite prior for this sample ImageOuts.append(rec) print('saving data...') SampsOut, keys = pmag.fillkeys(Samps) Sites, keys = pmag.fillkeys(SiteOuts) if data_model == 3: SampsOut3 = [] Sites3 = [] for samp_rec in SampsOut: new_rec = map_magic.mapping( samp_rec, map_magic.samp_magic2_2_magic3_map) SampsOut3.append(new_rec) for site_rec in Sites: new_rec = map_magic.mapping( site_rec, map_magic.site_magic2_2_magic3_map) Sites3.append(new_rec) wrote_samps = pmag.magic_write(samp_file, SampsOut3, "samples") wrote_sites = pmag.magic_write(site_file, Sites3, "sites") else: wrote_samps = pmag.magic_write(samp_file, SampsOut, "er_samples") wrote_sites = pmag.magic_write(site_file, Sites, "er_sites") if wrote_samps: print("Data saved in ", samp_file, ' and ', site_file) else: print("No data found") if len(ImageOuts) > 0: # need to do conversion here 3.0. --> 2.5 Images, keys = pmag.fillkeys(ImageOuts) image_type = "er_images" if data_model == 3: # convert 2.5 --> 3.0. image_type = "images" Images2 = Images Images = [] for image_rec in Images2: Images.append(map_magic.mapping( image_rec, map_magic.image_magic2_2_magic3_map)) pmag.magic_write(image_file, Images, image_type) print("Image info saved in ", image_file) return True, None def azdip_magic(orient_file='orient.txt', samp_file="samples.txt", samp_con="1", Z=1, method_codes='FS-FD', location_name='unknown', append=False, output_dir='.', input_dir='.', data_model=3): """ takes space delimited AzDip file and converts to MagIC formatted tables Parameters __________ orient_file : name of azdip formatted input file samp_file : name of samples.txt formatted output file samp_con : integer of sample orientation 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 name entered in site_name column in the orient.txt format input file -- NOT CURRENTLY SUPPORTED [7-Z] [XXXX]YYY: XXXX is site designation with Z characters with sample name XXXXYYYY method_codes : colon delimited string with the following as desired FS-FD field sampling done with a drill FS-H field sampling done with hand samples FS-LOC-GPS field location done with GPS FS-LOC-MAP field location done with map SO-POM a Pomeroy orientation device was used SO-ASC an ASC orientation device was used SO-MAG orientation with magnetic compass location_name : location of samples append : boolean. if True, append to the output file output_dir : path to output file directory input_dir : path to input file directory data_model : MagIC data model. INPUT FORMAT Input files must be space delimited: Samp Az Dip Strike Dip Orientation convention: Lab arrow azimuth = mag_azimuth; Lab arrow dip = 90-field_dip e.g. field_dip is degrees from horizontal of drill direction Magnetic declination convention: Az is already corrected in file """ # # initialize variables # data_model = int(data_model) if (data_model != 3) and (samp_file == "samples.txt"): samp_file = "er_samples.txt" if (data_model == 2) and (samp_file == "er_samples.txt"): samp_file = "samples.txt" DEBUG = 0 version_num = pmag.get_version() or_con, corr = "3", "1" # date of sampling, latitude (pos North), longitude (pos East) date, lat, lon = "", "", "" bed_dip, bed_dip_dir = "", "" participantlist = "" sites = [] # list of site names Lats, Lons = [], [] # list of latitudes and longitudes # lists of Sample records and Site records SampRecs, SiteRecs, ImageRecs, imagelist = [], [], [], [] average_bedding = "1", 1, "0" newbaseline, newbeddir, newbeddip = "", "", "" delta_u = "0" sclass, lithology, type = "", "", "" newclass, newlith, newtype = '', '', '' user = "" corr == "3" DecCorr = 0. samp_file = pmag.resolve_file_name(samp_file, output_dir) orient_file = pmag.resolve_file_name(orient_file, input_dir) input_dir = os.path.split(orient_file)[0] output_dir = os.path.split(samp_file)[0] # # if append: try: SampRecs, file_type = pmag.magic_read(samp_file) print("sample data to be appended to: ", samp_file) except: print('problem with existing samp file: ', samp_file, ' will create new') # # read in file to convert # azfile = open(orient_file, 'r') AzDipDat = azfile.readlines() azfile.close() if not AzDipDat: return False, 'No data in orientation file, please try again' azfile.close() SampOut, samplist = [], [] for line in AzDipDat: orec = line.split() if len(orec) > 2: labaz, labdip = pmag.orient(float(orec[1]), float(orec[2]), or_con) bed_dip = float(orec[4]) if bed_dip != 0: bed_dip_dir = float(orec[3]) - \ 90. # assume dip to right of strike else: bed_dip_dir = float(orec[3]) # assume dip to right of strike MagRec = {} MagRec["er_location_name"] = location_name MagRec["er_citation_names"] = "This study" # # parse information common to all orientation methods # MagRec["er_sample_name"] = orec[0] MagRec["sample_bed_dip"] = '%7.1f' % (bed_dip) MagRec["sample_bed_dip_direction"] = '%7.1f' % (bed_dip_dir) MagRec["sample_dip"] = '%7.1f' % (labdip) MagRec["sample_azimuth"] = '%7.1f' % (labaz) methods = method_codes.replace(" ", "").split(":") OR = 0 for method in methods: method_type = method.split("-") if "SO" in method_type: OR = 1 if OR == 0: method_codes = method_codes + ":SO-NO" MagRec["magic_method_codes"] = method_codes # parse out the site name site = pmag.parse_site(orec[0], samp_con, Z) MagRec["er_site_name"] = site MagRec['magic_software_packages'] = version_num SampOut.append(MagRec) if MagRec['er_sample_name'] not in samplist: samplist.append(MagRec['er_sample_name']) for samp in SampRecs: if samp not in samplist: SampOut.append(samp) Samps, keys = pmag.fillkeys(SampOut) if data_model == 2: # write to file pmag.magic_write(samp_file, Samps, "er_samples") else: # translate sample records to MagIC 3 Samps3 = [] for samp in Samps: Samps3.append(map_magic.mapping( samp, map_magic.samp_magic2_2_magic3_map)) # write to file pmag.magic_write(samp_file, Samps3, "samples") print("Data saved in ", samp_file) return True, None def read_core_csv_file(sum_file): Cores = [] core_depth_key = "Top depth cored CSF (m)" if os.path.isfile(sum_file): fin = open(sum_file, 'r') indat = fin.readlines() if "Core Summary" in indat[0]: headline = 1 else: headline = 0 keys = indat[headline].replace('\n', '').split(',') if "Core Top (m)" in keys: core_depth_key = "Core Top (m)" if "Top depth cored CSF (m)" in keys: core_depth_key = "Top depth cored CSF (m)" if 'Top depth cored (m)' in keys: core_depth_key = 'Top depth cored (m)' if "Core Label" in keys: core_label_key = "Core Label" if "Core label" in keys: core_label_key = "Core label" if "Label ID" in keys: core_label_key = "Label ID" for line in indat[2:]: if 'TOTALS' not in line: CoreRec = {} for k in range(len(keys)): CoreRec[keys[k]] = line.split(',')[k] Cores.append(CoreRec) fin.close() if len(Cores) == 0: print('no Core depth information available: import core summary file') return False, False, [] else: return core_depth_key, core_label_key, Cores else: return False, False, [] class Site(object): ''' This Site class is for use within Jupyter/IPython notebooks. It reads in MagIC-formatted data (text files) and compiles fits, separates them by type, and plots equal-area projections inline. If means were not taken and output within the Demag GUI, it should automatically compute the Fisher mean for each fit type. Code is still a work in progress, but it is currently useful for succinctly computing/displaying data in notebook format. ''' def __init__(self, site_name, data_path, data_format="MagIC"): ''' site_name: the name of the site data_path: put all MagIC data (text files) in a single directory and provide its path data_format: MagIC-formatted data is necessary in this code, but future compatability with other formats possible (built-in CIT_magic conversion?) *other keyword arguments not necessary* ''' # import necessary functions to be used in the notebook import os from matplotlib import pyplot as plt import pandas as pd global pd global plt global os import re dir_name = os.path.relpath(data_path) self.all_file_names = os.listdir(dir_name) os.path.join self.file_names = [] for file_name in self.all_file_names: if re.match('.*txt', file_name) != None: self.file_names.append(file_name) for i in self.file_names: path_to_open = os.path.join(dir_name, i) text_file = open(path_to_open, 'r') first_line = text_file.readlines()[0] text_file.close() if 'er_sites' in first_line: self.er_sites_path = path_to_open elif 'pmag_sites' in first_line: self.mean_path = path_to_open elif 'pmag_specimens' in first_line: self.data_path = path_to_open self.name = site_name # self.data_path = data_path # default name of 'pmag_specimens' self.data_format = data_format # default name of 'pmag_sites' # self.mean_path = mean_path # default name of 'er_sites' #self.er_sites_path = er_sites_path if self.data_format == "MagIC": self.fits = pd.read_csv(self.data_path, sep="\t", skiprows=1) if self.mean_path != None: self.means = pd.read_csv(self.mean_path, sep="\t", skiprows=1) if self.er_sites_path != None: self.location = pd.read_csv( self.er_sites_path, sep="\t", skiprows=1) else: raise Exception("Please convert data to MagIC format") self.parse_all_fits() self.lat = float(self.location.site_lat) self.lon = float(self.location.site_lon) # the following exception won't be necessary if parse_all_fits is # working properly if self.mean_path == None: raise Exception( 'Make fisher means within the demag GUI - functionality for handling this is in progress') def parse_fits(self, fit_name): '''USE PARSE_ALL_FITS unless otherwise necessary Isolate fits by the name of the fit; we also set 'specimen_tilt_correction' to zero in order to only include data in geographic coordinates - THIS NEEDS TO BE GENERALIZED ''' fits = self.fits.loc[self.fits.specimen_comp_name == fit_name].loc[self.fits.specimen_tilt_correction == 0] fits.reset_index(inplace=True) means = self.means.loc[self.means.site_comp_name == fit_name].loc[self.means.site_tilt_correction == 0] means.reset_index(inplace=True) mean_name = str(fit_name) + "_mean" setattr(self, fit_name, fits) setattr(self, mean_name, means) def parse_all_fits(self): # This is run upon initialization of the Site class self.fit_types = self.fits.specimen_comp_name.unique().tolist() for fit_type in self.fit_types: self.parse_fits(fit_type) print("Data separated by ", self.fit_types, "fits and can be accessed by <site_name>.<fit_name>") def get_fit_names(self): return self.fit_types def get_fisher_mean(self, fit_name): mean_name = str(fit_name) + "_mean" if self.mean_path != None: self.fisher_dict = {'dec': float(getattr(self, mean_name).site_dec), 'inc': float(getattr(self, mean_name).site_inc), 'alpha95': float(getattr(self, mean_name).site_alpha95), 'k': float(getattr(self, mean_name).site_k), 'r': float(getattr(self, mean_name).site_r), 'n': float(getattr(self, mean_name).site_n)} return self.fisher_dict else: self.directions = [] for fit_num in range(0, len(getattr(self, fit_name))): self.directions.append([list(getattr(self, fit_name).specimen_dec)[fit_num], list(getattr(self, fit_name).specimen_inc)[fit_num], 1.]) #fish_mean = pmag.fisher_mean(directions) self.fisher_dict = pmag.fisher_mean(self.directions) # setattr(self,fisher_dict,fish_mean) #self.fisher_dict = getattr(self,mean_name) return self.fisher_dict def get_lat(self): return self.lat def get_lon(self): return self.lon def get_site_coor(self): return [self.lat, self.lon] def get_name(self): return self def eq_plot_everything(self, title=None, clrs=None, size=(5, 5), **kwargs): fignum = 0 plt.figure(num=fignum, figsize=size, dpi=200) plot_net(fignum) clr_idx = 0 for fits in self.fit_types: mean_code = str(fits) + "_mean" print(mean_code) if clrs is not None: plot_di(getattr(self, fits).specimen_dec, getattr(self, fits).specimen_inc, color=clrs[clr_idx], label=fits + ' directions') print(float(getattr(self, mean_code).site_dec), float(getattr(self, mean_code).site_inc)) plot_di_mean(float(getattr(self, mean_code).site_dec), float(getattr(self, mean_code).site_inc), float(getattr(self, mean_code).site_alpha95), color=clrs[clr_idx], marker='s', label=fits + ' mean') clr_idx += 1 else: self.random_color = np.random.rand(3) plot_di(getattr(self, fits).specimen_dec, getattr(self, fits).specimen_inc, color=self.random_color, label=fits + ' directions') print(float(getattr(self, mean_code).site_dec), float(getattr(self, mean_code).site_inc)) plot_di_mean(float(getattr(self, mean_code).site_dec), float(getattr(self, mean_code).site_inc), float(getattr(self, mean_code).site_alpha95), color=self.random_color, marker='s', label=fits + ' mean') plt.legend(**kwargs) if title != None: plt.title(title) plt.show() def eq_plot(self, fit_name, title=None, clr=None, size=(5, 5), **kwargs): fignum = 0 plt.figure(num=fignum, figsize=size, dpi=200) plot_net(fignum) mean_code = str(fit_name) + "_mean" if clr is not None: self.random_color = clr else: self.random_color = np.random.rand(3) plot_di(getattr(self, fit_name).specimen_dec, getattr(self, fit_name).specimen_inc, color=self.random_color, label=fit_name + ' directions') plot_di_mean(float(getattr(self, mean_code).site_dec), float(getattr(self, mean_code).site_inc), float(getattr(self, mean_code).site_alpha95), marker='s', label=fit_name + ' mean') plt.legend(**kwargs) if title != None: plt.title(title) plt.show() # def eq_plot_sidebyside(self, fit_name): # fig,ax = plt.subplots(1,2) # ax[0].plot(self.eq_plot_everything()) # ax[1].plot(self.eq_plot(fit_name)) # plt.show() def get_site_data(self, description, fit_name, demag_type='Thermal', cong_test_result=None): self.site_data = pd.Series({'site_type': str(description), 'site_lat': self.get_lat(), 'site_lon': self.get_lon(), 'demag_type': demag_type, 'dec': float(self.get_fisher_mean(fit_name)['dec']), 'inc': float(self.get_fisher_mean(fit_name)['inc']), 'a_95': float(self.get_fisher_mean(fit_name)['alpha95']), 'n': int(self.get_fisher_mean(fit_name)['n']), 'kappa': float(self.get_fisher_mean(fit_name)['k']), 'R': float(self.get_fisher_mean(fit_name)['r']), 'cong_test_result': cong_test_result}, name=str(self.name)) return self.site_data def dayplot(path_to_file='.', hyst_file="specimens.txt", rem_file='', save=False, save_folder='.', fmt='pdf', data_model=3): """ Makes 'day plots' (Day et al. 1977) and squareness/coercivity plots (Neel, 1955; plots after Tauxe et al., 2002); plots 'linear mixing' curve from Dunlop and Carter-Stiglitz (2006). Optional Parameters (defaults are used if not specified) ---------- path_to_file : path to directory that contains files (default is current directory, '.') the default input file is 'specimens.txt' (data_model=3 if data_model = 2, then must these are the defaults: hyst_file : hysteresis file (default is 'rmag_hysteresis.txt') rem_file : remanence file (default is 'rmag_remanence.txt') save : boolean argument to save plots (default is False) save_folder : relative directory where plots will be saved (default is current directory, '.') fmt : format of saved figures (default is 'pdf') """ args = sys.argv hyst_path = os.path.join(path_to_file, hyst_file) if data_model == 2 and rem_file != '': rem_path = os.path.join(path_to_file, rem_file) # hyst_file,rem_file="rmag_hysteresis.txt","rmag_remanence.txt" dir_path = path_to_file verbose = pmagplotlib.verbose # initialize some variables # define figure numbers for Day,S-Bc,S-Bcr DSC = {} DSC['day'], DSC['S-Bc'], DSC['S-Bcr'], DSC['bcr1-bcr2'] = 1, 2, 3, 4 plt.figure(num=DSC['day'], figsize=(5, 5)) plt.figure(num=DSC['S-Bc'], figsize=(5, 5)) plt.figure(num=DSC['S-Bcr'], figsize=(5, 5)) plt.figure(num=DSC['bcr1-bcr2'], figsize=(5, 5)) hyst_data, file_type = pmag.magic_read(hyst_path) rem_data = [] if data_model == 2 and rem_file != "": rem_data, file_type = pmag.magic_read(rem_path) S, BcrBc, Bcr2, Bc, hsids, Bcr = [], [], [], [], [], [] Ms, Bcr1, Bcr1Bc, S1 = [], [], [], [] locations = '' if data_model == 2: for rec in hyst_data: if 'er_location_name' in list(rec.keys()) and rec['er_location_name'] not in locations: locations = locations + rec['er_location_name'] + '_' if rec['hysteresis_bcr'] != "" and rec['hysteresis_mr_moment'] != "": S.append(old_div(float(rec['hysteresis_mr_moment']), float( rec['hysteresis_ms_moment']))) Bcr.append(float(rec['hysteresis_bcr'])) Bc.append(float(rec['hysteresis_bc'])) BcrBc.append(old_div(Bcr[-1], Bc[-1])) if 'er_synthetic_name' in list(rec.keys()) and rec['er_synthetic_name'] != "": rec['er_specimen_name'] = rec['er_synthetic_name'] hsids.append(rec['er_specimen_name']) if len(rem_data) > 0: for rec in rem_data: if rec['remanence_bcr'] != "" and float(rec['remanence_bcr']) > 0: try: ind = hsids.index(rec['er_specimen_name']) Bcr1.append(float(rec['remanence_bcr'])) Bcr1Bc.append(old_div(Bcr1[-1], Bc[ind])) S1.append(S[ind]) Bcr2.append(Bcr[ind]) except ValueError: if verbose: print('hysteresis data for ', rec['er_specimen_name'], ' not found') else: fnames = {'specimens': hyst_file} con = cb.Contribution(dir_path, read_tables=['specimens'], custom_filenames=fnames) spec_container = con.tables['specimens'] spec_df = spec_container.df locations = [] if 'location' in spec_df.columns: locations = spec_df['location'].unique() do_rem = bool('rem_bcr' in spec_df.columns) for ind, row in spec_df.iterrows(): if row['hyst_bcr'] and row['hyst_mr_moment']: S.append( old_div(float(row['hyst_mr_moment']), float(row['hyst_ms_moment']))) Bcr.append(float(row['hyst_bcr'])) Bc.append(float(row['hyst_bc'])) BcrBc.append(old_div(Bcr[-1], Bc[-1])) hsids.append(row['specimen']) if do_rem: if row['rem_bcr'] and float(row['rem_bcr']) > 0: try: Bcr1.append(float(row['rem_bcr'])) Bcr1Bc.append(old_div(Bcr1[-1], Bc[-1])) S1.append(S[-1]) Bcr2.append(Bcr[-1]) except ValueError: if verbose: print('hysteresis data for ', row['specimen'], end=' ') print(' not found') # # now plot the day and S-Bc, S-Bcr plots # if len(Bcr1) > 0: pmagplotlib.plot_day(DSC['day'], Bcr1Bc, S1, 'ro') pmagplotlib.plot_s_bcr(DSC['S-Bcr'], Bcr1, S1, 'ro') pmagplotlib.plot_init(DSC['bcr1-bcr2'], 5, 5) pmagplotlib.plot_bcr(DSC['bcr1-bcr2'], Bcr1, Bcr2) plt.show() else: del DSC['bcr1-bcr2'] if save == True: pmagplotlib.plot_day(DSC['day'], BcrBc, S, 'bs') plt.savefig(os.path.join(save_folder, 'Day.' + fmt)) pmagplotlib.plot_s_bcr(DSC['S-Bcr'], Bcr, S, 'bs') plt.savefig(os.path.join(save_folder, 'S-Bcr.' + fmt)) pmagplotlib.plot_s_bc(DSC['S-Bc'], Bc, S, 'bs') plt.savefig(os.path.join(save_folder, 'S-Bc.' + fmt)) else: pmagplotlib.plot_day(DSC['day'], BcrBc, S, 'bs') pmagplotlib.plot_s_bcr(DSC['S-Bcr'], Bcr, S, 'bs') pmagplotlib.plot_s_bc(DSC['S-Bc'], Bc, S, 'bs') plt.show() def smooth(x, window_len, window='bartlett'): """ Smooth the data using a sliding window with requested size - meant to be used with the ipmag function curie(). This method is based on the convolution of a scaled window with the signal. The signal is prepared by padding the beginning and the end of the signal with average of the first (last) ten values of the signal, to evoid jumps at the beggining/end. Output is an array of the smoothed signal. Required Parameters ---------- x : the input signal, equaly spaced! window_len : the dimension of the smoothing window Optional Parameters (defaults are used if not specified) ---------- window : type of window from numpy library ['flat','hanning','hamming','bartlett','blackman'] (default is Bartlett) -flat window will produce a moving average smoothing. -Bartlett window is very similar to triangular window, but always ends with zeros at points 1 and n. -hanning,hamming,blackman are used for smoothing the Fourier transfrom """ if x.ndim != 1: raise ValueError("smooth only accepts 1 dimension arrays.") if x.size < window_len: raise ValueError("Input vector needs to be bigger than window size.") if window_len < 3: return x # numpy available windows if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError( "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'") # padding the beggining and the end of the signal with an average value to # evoid edge effect start = [np.average(x[0:10])] * window_len end = [np.average(x[-10:])] * window_len s = start + list(x) + end # s=numpy.r_[2*x[0]-x[window_len:1:-1],x,2*x[-1]-x[-1:-window_len:-1]] if window == 'flat': # moving average w = ones(window_len, 'd') else: w = eval('np.' + window + '(window_len)') y = np.convolve(old_div(w, w.sum()), s, mode='same') return np.array(y[window_len:-window_len]) def deriv1(x, y, i, n): """ Alternative way to smooth the derivative of a noisy signal using least square fit. In this method the slope in position 'i' is calculated by least square fit of 'n' points before and after position. Required Parameters ---------- x : array of x axis y : array of y axis n : smoothing factor i : position """ m_, x_, y_, xy_, x_2 = 0., 0., 0., 0., 0. for ix in range(i, i + n, 1): x_ = x_ + x[ix] y_ = y_ + y[ix] xy_ = xy_ + x[ix] * y[ix] x_2 = x_2 + x[ix]**2 m = old_div(((n * xy_) - (x_ * y_)), (n * x_2 - (x_)**2)) return(m) def curie(path_to_file='.', file_name='', magic=False, window_length=3, save=False, save_folder='.', fmt='svg', t_begin="", t_end=""): """ Plots and interprets curie temperature data. *** The 1st derivative is calculated from smoothed M-T curve (convolution with trianfular window with width= <-w> degrees) *** The 2nd derivative is calculated from smoothed 1st derivative curve (using the same sliding window width) *** The estimated curie temp. is the maximum of the 2nd derivative. Temperature steps should be in multiples of 1.0 degrees. Parameters __________ file_name : name of file to be opened Optional Parameters (defaults are used if not specified) ---------- path_to_file : path to directory that contains file (default is current directory, '.') window_length : dimension of smoothing window (input to smooth() function) save : boolean argument to save plots (default is False) save_folder : relative directory where plots will be saved (default is current directory, '.') fmt : format of saved figures t_begin: start of truncated window for search t_end: end of truncated window for search magic : True if MagIC formated measurements.txt file """ plot = 0 window_len = window_length # read data from file complete_path = os.path.join(path_to_file, file_name) if magic: data_df = pd.read_csv(complete_path, sep='\t', header=1) T = data_df['meas_temp'].values-273 magn_key = cb.get_intensity_col(data_df) M = data_df[magn_key].values else: Data = np.loadtxt(complete_path, dtype=np.float) T = Data.transpose()[0] M = Data.transpose()[1] T = list(T) M = list(M) # cut the data if -t is one of the flags if t_begin != "": while T[0] < t_begin: M.pop(0) T.pop(0) while T[-1] > t_end: M.pop(-1) T.pop(-1) # prepare the signal: # from M(T) array with unequal deltaT # to M(T) array with deltaT=(1 degree). # if delataT is larger, then points are added using linear fit between # consecutive data points. # exit if deltaT is not integer i = 0 while i < (len(T) - 1): if (T[i + 1] - T[i]) % 1 > 0.001: print("delta T should be integer, this program will not work!") print("temperature range:", T[i], T[i + 1]) sys.exit() if (T[i + 1] - T[i]) == 0.: M[i] = np.average([M[i], M[i + 1]]) M.pop(i + 1) T.pop(i + 1) elif (T[i + 1] - T[i]) < 0.: M.pop(i + 1) T.pop(i + 1) print("check data in T=%.0f ,M[T] is ignored" % (T[i])) elif (T[i + 1] - T[i]) > 1.: slope, b = np.polyfit([T[i], T[i + 1]], [M[i], M[i + 1]], 1) for j in range(int(T[i + 1]) - int(T[i]) - 1): M.insert(i + 1, slope * (T[i] + 1.) + b) T.insert(i + 1, (T[i] + 1.)) i = i + 1 i = i + 1 # calculate the smoothed signal M = np.array(M, 'f') T = np.array(T, 'f') M_smooth = [] M_smooth = smooth(M, window_len) # plot the original data and the smooth data PLT = {'M_T': 1, 'der1': 2, 'der2': 3, 'Curie': 4} plt.figure(num=PLT['M_T'], figsize=(5, 5)) string = 'M-T (sliding window=%i)' % int(window_len) pmagplotlib.plot_xy(PLT['M_T'], T, M_smooth, sym='-') pmagplotlib.plot_xy(PLT['M_T'], T, M, sym='--', xlab='Temperature C', ylab='Magnetization', title=string) # calculate first derivative d1, T_d1 = [], [] for i in range(len(M_smooth) - 1): Dy = M_smooth[i - 1] - M_smooth[i + 1] Dx = T[i - 1] - T[i + 1] d1.append(old_div(Dy, Dx)) T_d1 = T[1:len(T - 1)] d1 = np.array(d1, 'f') d1_smooth = smooth(d1, window_len) # plot the first derivative plt.figure(num=PLT['der1'], figsize=(5, 5)) string = '1st derivative (sliding window=%i)' % int(window_len) pmagplotlib.plot_xy(PLT['der1'], T_d1, d1_smooth, sym='-', xlab='Temperature C', title=string) pmagplotlib.plot_xy(PLT['der1'], T_d1, d1, sym='b--') # calculate second derivative d2, T_d2 = [], [] for i in range(len(d1_smooth) - 1): Dy = d1_smooth[i - 1] - d1_smooth[i + 1] Dx = T[i - 1] - T[i + 1] # print Dy/Dx d2.append(old_div(Dy, Dx)) T_d2 = T[2:len(T - 2)] d2 = np.array(d2, 'f') d2_smooth = smooth(d2, window_len) # plot the second derivative plt.figure(num=PLT['der2'], figsize=(5, 5)) string = '2nd derivative (sliding window=%i)' % int(window_len) pmagplotlib.plot_xy(PLT['der2'], T_d2, d2, sym='-', xlab='Temperature C', title=string) d2 = list(d2) print('second derivative maximum is at T=%i' % int(T_d2[d2.index(max(d2))])) # calculate Curie temperature for different width of sliding windows curie, curie_1 = [], [] wn = list(range(5, 50, 1)) for win in wn: # calculate the smoothed signal M_smooth = [] M_smooth = smooth(M, win) # calculate first derivative d1, T_d1 = [], [] for i in range(len(M_smooth) - 1): Dy = M_smooth[i - 1] - M_smooth[i + 1] Dx = T[i - 1] - T[i + 1] d1.append(old_div(Dy, Dx)) T_d1 = T[1:len(T - 1)] d1 = np.array(d1, 'f') d1_smooth = smooth(d1, win) # calculate second derivative d2, T_d2 = [], [] for i in range(len(d1_smooth) - 1): Dy = d1_smooth[i - 1] - d1_smooth[i + 1] Dx = T[i - 1] - T[i + 1] d2.append(old_div(Dy, Dx)) T_d2 = T[2:len(T - 2)] d2 = np.array(d2, 'f') d2_smooth = smooth(d2, win) d2 = list(d2) d2_smooth = list(d2_smooth) curie.append(T_d2[d2.index(max(d2))]) curie_1.append(T_d2[d2_smooth.index(max(d2_smooth))]) # plot Curie temp for different sliding window length plt.figure(num=PLT['Curie'], figsize=(5, 5)) pmagplotlib.plot_xy(PLT['Curie'], wn, curie, sym='.', xlab='Sliding Window Width (degrees)', ylab='Curie Temp', title='Curie Statistics') files = {} for key in list(PLT.keys()): files[key] = str(key) + '.' + fmt if save == True: for key in list(PLT.keys()): try: plt.figure(num=PLT[key]) plt.savefig(save_folder + '/' + files[key].replace('/', '-')) except: print('could not save: ', PLT[key], files[key]) print("output file format not supported ") plt.show() def chi_magic(path_to_file='.', file_name='magic_measurements.txt', save=False, save_folder='.', fmt='svg'): """ Generates plots that compare susceptibility to temperature at different frequencies. Optional Parameters (defaults are used if not specified) ---------- path_to_file : path to directory that contains file (default is current directory, '.') file_name : name of file to be opened (default is 'magic_measurements.txt') save : boolean argument to save plots (default is False) save_folder : relative directory where plots will be saved (default is current directory, '.') """ cont, FTinit, BTinit, k = "", 0, 0, 0 complete_path = os.path.join(path_to_file, file_name) Tind, cont = 0, "" EXP = "" # meas_data, file_type = pmag.magic_read(complete_path) # # get list of unique experiment names # # initialize some variables (a continuation flag, plot initialization # flags and the experiment counter experiment_names = [] for rec in meas_data: if rec['magic_experiment_name'] not in experiment_names: experiment_names.append(rec['magic_experiment_name']) # # hunt through by experiment name if EXP != "": try: k = experiment_names.index(EXP) except: print("Bad experiment name") sys.exit() while k < len(experiment_names): e = experiment_names[k] if EXP == "": print(e, k + 1, 'out of ', len(experiment_names)) # # initialize lists of data, susceptibility, temperature, frequency and # field X, T, F, B = [], [], [], [] for rec in meas_data: methcodes = rec['magic_method_codes'] meths = methcodes.strip().split(':') if rec['magic_experiment_name'] == e and "LP-X" in meths: # looking for chi measurement if 'measurement_temp' not in list(rec.keys()): rec['measurement_temp'] = '300' # set defaults if 'measurement_freq' not in list(rec.keys()): rec['measurement_freq'] = '0' # set defaults if 'measurement_lab_field_ac' not in list(rec.keys()): rec['measurement_lab_field_ac'] = '0' # set default X.append(float(rec['measurement_x'])) T.append(float(rec['measurement_temp'])) F.append(float(rec['measurement_freq'])) B.append(float(rec['measurement_lab_field_ac'])) # # get unique list of Ts,Fs, and Bs # Ts, Fs, Bs = [], [], [] for k in range(len(X)): # hunt through all the measurements if T[k] not in Ts: Ts.append(T[k]) # append if not in list if F[k] not in Fs: Fs.append(F[k]) if B[k] not in Bs: Bs.append(B[k]) Ts.sort() # sort list of temperatures, frequencies and fields Fs.sort() Bs.sort() if '-x' in sys.argv: k = len(experiment_names) + 1 # just plot the one else: k += 1 # increment experiment number # # plot chi versus T and F holding B constant # plotnum = 1 # initialize plot number to 1 if len(X) > 2: # if there are any data to plot, continue b = Bs[-1] # keeping field constant and at maximum XTF = [] # initialize list of chi versus Temp and freq for f in Fs: # step through frequencies sequentially XT = [] # initialize list of chi versus temp for kk in range(len(X)): # hunt through all the data if F[kk] == f and B[kk] == b: # select data with given freq and field XT.append([X[kk], T[kk]]) # append to list XTF.append(XT) # append list to list of frequencies if len(XT) > 1: # if there are any temperature dependent data plt.figure(num=plotnum, figsize=(5, 5)) # initialize plot # call the plotting function pmagplotlib.plot_xtf(plotnum, XTF, Fs, e, b) pmagplotlib.show_fig(plotnum) plotnum += 1 # increment plot number f = Fs[0] # set frequency to minimum XTB = [] # initialize list if chi versus Temp and field for b in Bs: # step through field values XT = [] # initial chi versus temp list for this field for kk in range(len(X)): # hunt through all the data if F[kk] == f and B[kk] == b: # select data with given freq and field XT.append([X[kk], T[kk]]) # append to list XTB.append(XT) if len(XT) > 1: # if there are any temperature dependent data plt.figure(num=plotnum, figsize=(5, 5)) # set up plot # call the plotting function pmagplotlib.plot_xtb(plotnum, XTB, Bs, e, f) pmagplotlib.show_fig(plotnum) plotnum += 1 # increment plot number if save == True: files = {} PLTS = {} for p in range(1, plotnum): key = str(p) files[key] = e + '_' + key + '.' + fmt PLTS[key] = p for key in list(PLTS.keys()): try: plt.figure(num=PLTS[key]) plt.savefig(save_folder + '/' + files[key].replace('/', '-')) except: print('could not save: ', PLTS[key], files[key]) print("output file format not supported ") def pmag_results_extract(res_file="pmag_results.txt", crit_file="", spec_file="", age_file="", latex=False, grade=False, WD="."): """ Generate tab delimited output file(s) with result data. Save output files and return True if successful. Possible output files: Directions, Intensities, SiteNfo, Criteria, Specimens Optional Parameters (defaults are used if not specified) ---------- res_file : name of pmag_results file (default is "pmag_results.txt") crit_file : name of criteria file (default is "pmag_criteria.txt") spec_file : name of specimen file (default is "pmag_specimens.txt") age_file : name of age file (default is "er_ages.txt") latex : boolean argument to output in LaTeX (default is False) WD : path to directory that contains input files and takes output (default is current directory, '.') """ # format outfiles if latex: latex = 1 file_type = '.tex' else: latex = 0 file_type = '.txt' dir_path = os.path.realpath(WD) outfile = os.path.join(dir_path, 'Directions' + file_type) Ioutfile = os.path.join(dir_path, 'Intensities' + file_type) Soutfile = os.path.join(dir_path, 'SiteNfo' + file_type) Specout = os.path.join(dir_path, 'Specimens' + file_type) Critout = os.path.join(dir_path, 'Criteria' + file_type) # format infiles res_file = os.path.join(dir_path, res_file) if crit_file: crit_file = os.path.join(dir_path, crit_file) if spec_file: spec_file = os.path.join(dir_path, spec_file) else: grade = False # open output files f = open(outfile, 'w') sf = open(Soutfile, 'w') fI = open(Ioutfile, 'w') if crit_file: cr = open(Critout, 'w') # set up column headers Sites, file_type = pmag.magic_read(res_file) if crit_file: Crits, file_type = pmag.magic_read(crit_file) else: Crits = [] SiteCols = ["Site", "Location", "Lat. (N)", "Long. (E)", "Age ", "Age sigma", "Units"] SiteKeys = ["er_site_names", "average_lat", "average_lon", "average_age", "average_age_sigma", "average_age_unit"] DirCols = ["Site", 'Comp.', "perc TC", "Dec.", "Inc.", "Nl", "Np", "k ", "R", "a95", "PLat", "PLong"] DirKeys = ["er_site_names", "pole_comp_name", "tilt_correction", "average_dec", "average_inc", "average_n_lines", "average_n_planes", "average_k", "average_r", "average_alpha95", "vgp_lat", "vgp_lon"] IntCols = ["Site", "N", "B (uT)", "sigma", "sigma perc", "VADM", "VADM sigma"] IntKeys = ["er_site_names", "average_int_n", "average_int", "average_int_sigma", 'average_int_sigma_perc', "vadm", "vadm_sigma"] AllowedKeys = ['specimen_frac', 'specimen_scat', 'specimen_gap_max', 'measurement_step_min', 'measurement_step_max', 'measurement_step_unit', 'specimen_polarity', 'specimen_nrm', 'specimen_direction_type', 'specimen_comp_nmb', 'specimen_mad', 'specimen_alpha95', 'specimen_n', 'specimen_int_sigma', 'specimen_int_sigma_perc', 'specimen_int_rel_sigma', 'specimen_int_rel_sigma_perc', 'specimen_int_mad', 'specimen_int_n', 'specimen_w', 'specimen_q', 'specimen_f', 'specimen_fvds', 'specimen_b_sigma', 'specimen_b_beta', 'specimen_g', 'specimen_dang', 'specimen_md', 'specimen_ptrm', 'specimen_drat', 'specimen_drats', 'specimen_rsc', 'specimen_viscosity_index', 'specimen_magn_moment', 'specimen_magn_volume', 'specimen_magn_mass', 'specimen_int_ptrm_n', 'specimen_delta', 'specimen_theta', 'specimen_gamma', 'sample_polarity', 'sample_nrm', 'sample_direction_type', 'sample_comp_nmb', 'sample_sigma', 'sample_alpha95', 'sample_n', 'sample_n_lines', 'sample_n_planes', 'sample_k', 'sample_r', 'sample_tilt_correction', 'sample_int_sigma', 'sample_int_sigma_perc', 'sample_int_rel_sigma', 'sample_int_rel_sigma_perc', 'sample_int_n', 'sample_magn_moment', 'sample_magn_volume', 'sample_magn_mass', 'site_polarity', 'site_nrm', 'site_direction_type', 'site_comp_nmb', 'site_sigma', 'site_alpha95', 'site_n', 'site_n_lines', 'site_n_planes', 'site_k', 'site_r', 'site_tilt_correction', 'site_int_sigma', 'site_int_sigma_perc', 'site_int_rel_sigma', 'site_int_rel_sigma_perc', 'site_int_n', 'site_magn_moment', 'site_magn_volume', 'site_magn_mass', 'average_age_min', 'average_age_max', 'average_age_sigma', 'average_age_unit', 'average_sigma', 'average_alpha95', 'average_n', 'average_nn', 'average_k', 'average_r', 'average_int_sigma', 'average_int_rel_sigma', 'average_int_rel_sigma_perc', 'average_int_n', 'average_int_nn', 'vgp_dp', 'vgp_dm', 'vgp_sigma', 'vgp_alpha95', 'vgp_n', 'vdm_sigma', 'vdm_n', 'vadm_sigma', 'vadm_n'] if crit_file: crit = Crits[0] # get a list of useful keys for key in list(crit.keys()): if key not in AllowedKeys: del(crit[key]) for key in list(crit.keys()): if (not crit[key]) or (eval(crit[key]) > 1000) or (eval(crit[key]) == 0): # get rid of all blank or too big ones or too little ones del(crit[key]) CritKeys = list(crit.keys()) if spec_file: Specs, file_type = pmag.magic_read(spec_file) fsp = open(Specout, 'w') # including specimen intensities if desired SpecCols = ["Site", "Specimen", "B (uT)", "MAD", "Beta", "N", "Q", "DANG", "f-vds", "DRATS", "T (C)"] SpecKeys = ['er_site_name', 'er_specimen_name', 'specimen_int', 'specimen_int_mad', 'specimen_b_beta', 'specimen_int_n', 'specimen_q', 'specimen_dang', 'specimen_fvds', 'specimen_drats', 'trange'] Xtra = ['specimen_frac', 'specimen_scat', 'specimen_gmax'] if grade: SpecCols.append('Grade') SpecKeys.append('specimen_grade') for x in Xtra: # put in the new intensity keys if present if x in list(Specs[0].keys()): SpecKeys.append(x) newkey = "" for k in x.split('_')[1:]: newkey = newkey + k + '_' SpecCols.append(newkey.strip('_')) SpecCols.append('Corrections') SpecKeys.append('corrections') # these should be multiplied by 1e6 Micro = ['specimen_int', 'average_int', 'average_int_sigma'] Zeta = ['vadm', 'vadm_sigma'] # these should be multiplied by 1e21 # write out the header information for each output file if latex: # write out the latex header stuff sep = ' & ' end = '\\\\' f.write('\\documentclass{article}\n') f.write('\\usepackage[margin=1in]{geometry}\n') f.write('\\usepackage{longtable}\n') f.write('\\begin{document}\n') sf.write('\\documentclass{article}\n') sf.write('\\usepackage[margin=1in]{geometry}\n') sf.write('\\usepackage{longtable}\n') sf.write('\\begin{document}\n') fI.write('\\documentclass{article}\n') fI.write('\\usepackage[margin=1in]{geometry}\n') fI.write('\\usepackage{longtable}\n') fI.write('\\begin{document}\n') if crit_file: cr.write('\\documentclass{article}\n') cr.write('\\usepackage[margin=1in]{geometry}\n') cr.write('\\usepackage{longtable}\n') cr.write('\\begin{document}\n') if spec_file: fsp.write('\\documentclass{article}\n') fsp.write('\\usepackage[margin=1in]{geometry}\n') fsp.write('\\usepackage{longtable}\n') fsp.write('\\begin{document}\n') tabstring = '\\begin{longtable}{' fstring = tabstring for k in range(len(SiteCols)): fstring = fstring + 'r' sf.write(fstring + '}\n') sf.write('\hline\n') fstring = tabstring for k in range(len(DirCols)): fstring = fstring + 'r' f.write(fstring + '}\n') f.write('\hline\n') fstring = tabstring for k in range(len(IntCols)): fstring = fstring + 'r' fI.write(fstring + '}\n') fI.write('\hline\n') fstring = tabstring if crit_file: for k in range(len(CritKeys)): fstring = fstring + 'r' cr.write(fstring + '}\n') cr.write('\hline\n') if spec_file: fstring = tabstring for k in range(len(SpecCols)): fstring = fstring + 'r' fsp.write(fstring + '}\n') fsp.write('\hline\n') else: # just set the tab and line endings for tab delimited sep = ' \t ' end = '' # now write out the actual column headers Soutstring, Doutstring, Ioutstring, Spoutstring, Croutstring = "", "", "", "", "" for k in range(len(SiteCols)): Soutstring = Soutstring + SiteCols[k] + sep Soutstring = Soutstring.strip(sep) Soutstring = Soutstring + end + '\n' sf.write(Soutstring) for k in range(len(DirCols)): Doutstring = Doutstring + DirCols[k] + sep Doutstring = Doutstring.strip(sep) Doutstring = Doutstring + end + '\n' f.write(Doutstring) for k in range(len(IntCols)): Ioutstring = Ioutstring + IntCols[k] + sep Ioutstring = Ioutstring.strip(sep) Ioutstring = Ioutstring + end + '\n' fI.write(Ioutstring) if crit_file: for k in range(len(CritKeys)): Croutstring = Croutstring + CritKeys[k] + sep Croutstring = Croutstring.strip(sep) Croutstring = Croutstring + end + '\n' cr.write(Croutstring) if spec_file: for k in range(len(SpecCols)): Spoutstring = Spoutstring + SpecCols[k] + sep Spoutstring = Spoutstring.strip(sep) Spoutstring = Spoutstring + end + "\n" fsp.write(Spoutstring) if latex: # put in a horizontal line in latex file f.write('\hline\n') sf.write('\hline\n') fI.write('\hline\n') if crit_file: cr.write('\hline\n') if spec_file: fsp.write('\hline\n') # do criteria if crit_file: for crit in Crits: Croutstring = "" for key in CritKeys: Croutstring = Croutstring + crit[key] + sep Croutstring = Croutstring.strip(sep) + end cr.write(Croutstring + '\n') # do directions # get all results with VGPs VGPs = pmag.get_dictitem(Sites, 'vgp_lat', '', 'F') VGPs = pmag.get_dictitem(VGPs, 'data_type', 'i', 'T') # get site level stuff for site in VGPs: if len(site['er_site_names'].split(":")) == 1: if 'er_sample_names' not in list(site.keys()): site['er_sample_names'] = '' if 'pole_comp_name' not in list(site.keys()): site['pole_comp_name'] = "A" if 'average_nn' not in list(site.keys()) and 'average_n' in list(site.keys()): site['average_nn'] = site['average_n'] if 'average_n_lines' not in list(site.keys()): site['average_n_lines'] = site['average_nn'] if 'average_n_planes' not in list(site.keys()): site['average_n_planes'] = "" Soutstring, Doutstring = "", "" for key in SiteKeys: if key in list(site.keys()): Soutstring = Soutstring + site[key] + sep Soutstring = Soutstring.strip(sep) + end sf.write(Soutstring + '\n') for key in DirKeys: if key in list(site.keys()): Doutstring = Doutstring + site[key] + sep Doutstring = Doutstring.strip(sep) + end f.write(Doutstring + '\n') # now do intensities VADMs = pmag.get_dictitem(Sites, 'vadm', '', 'F') VADMs = pmag.get_dictitem(VADMs, 'data_type', 'i', 'T') for site in VADMs: # do results level stuff if site not in VGPs: Soutstring = "" for key in SiteKeys: if key in list(site.keys()): Soutstring = Soutstring + site[key] + sep else: Soutstring = Soutstring + " " + sep Soutstring = Soutstring.strip(sep) + end sf.write(Soutstring + '\n') if len(site['er_site_names'].split(":")) == 1 and site['data_type'] == 'i': if 'average_int_sigma_perc' not in list(site.keys()): site['average_int_sigma_perc'] = "0" if site["average_int_sigma"] == "": site["average_int_sigma"] = "0" if site["average_int_sigma_perc"] == "": site["average_int_sigma_perc"] = "0" if site["vadm"] == "": site["vadm"] = "0" if site["vadm_sigma"] == "": site["vadm_sigma"] = "0" for key in list(site.keys()): # reformat vadms, intensities if key in Micro: site[key] = '%7.1f' % (float(site[key]) * 1e6) if key in Zeta: site[key] = '%7.1f' % (float(site[key]) * 1e-21) outstring = "" for key in IntKeys: if key not in list(site.keys()): site[key] = "" outstring = outstring + site[key] + sep outstring = outstring.strip(sep) + end + '\n' fI.write(outstring) # VDMs=pmag.get_dictitem(Sites,'vdm','','F') # get non-blank VDMs # for site in VDMs: # do results level stuff # if len(site['er_site_names'].split(":"))==1: # if 'average_int_sigma_perc' not in site.keys():site['average_int_sigma_perc']="0" # if site["average_int_sigma"]=="":site["average_int_sigma"]="0" # if site["average_int_sigma_perc"]=="":site["average_int_sigma_perc"]="0" # if site["vadm"]=="":site["vadm"]="0" # if site["vadm_sigma"]=="":site["vadm_sigma"]="0" # for key in site.keys(): # reformat vadms, intensities # if key in Micro: site[key]='%7.1f'%(float(site[key])*1e6) # if key in Zeta: site[key]='%7.1f'%(float(site[key])*1e-21) # outstring="" # for key in IntKeys: # outstring=outstring+site[key]+sep # fI.write(outstring.strip(sep)+'\n') if spec_file: SpecsInts = pmag.get_dictitem(Specs, 'specimen_int', '', 'F') for spec in SpecsInts: spec['trange'] = '%i' % (int(float(spec['measurement_step_min']) - 273)) + \ '-' + '%i' % (int(float(spec['measurement_step_max']) - 273)) meths = spec['magic_method_codes'].split(':') corrections = '' for meth in meths: if 'DA' in meth: corrections = corrections + meth[3:] + ':' corrections = corrections.strip(':') if corrections.strip() == "": corrections = "None" spec['corrections'] = corrections outstring = "" for key in SpecKeys: if key in Micro: spec[key] = '%7.1f' % (float(spec[key]) * 1e6) if key in Zeta: spec[key] = '%7.1f' % (float(spec[key]) * 1e-21) outstring = outstring + spec[key] + sep fsp.write(outstring.strip(sep) + end + '\n') # if latex: # write out the tail stuff f.write('\hline\n') sf.write('\hline\n') fI.write('\hline\n') f.write('\end{longtable}\n') sf.write('\end{longtable}\n') fI.write('\end{longtable}\n') f.write('\end{document}\n') sf.write('\end{document}\n') fI.write('\end{document}\n') if spec_file: fsp.write('\hline\n') fsp.write('\end{longtable}\n') fsp.write('\end{document}\n') if crit_file: cr.write('\hline\n') cr.write('\end{longtable}\n') cr.write('\end{document}\n') f.close() sf.close() fI.close() print('data saved in: ', outfile, Ioutfile, Soutfile) outfiles = [outfile, Ioutfile, Soutfile] if spec_file: fsp.close() print('specimen data saved in: ', Specout) outfiles.append(Specout) if crit_file: cr.close() print('Selection criteria saved in: ', Critout) outfiles.append(Critout) return True, outfiles def demag_magic(path_to_file='.', file_name='magic_measurements.txt', save=False, save_folder='.', fmt='svg', plot_by='loc', treat=None, XLP="", individual=None, average_measurements=False, single_plot=False): ''' Takes demagnetization data (from magic_measurements file) and outputs intensity plots (with optional save). Parameters ----------- path_to_file : path to directory that contains files (default is current directory, '.') file_name : name of measurements file (default is 'magic_measurements.txt') save : boolean argument to save plots (default is False) save_folder : relative directory where plots will be saved (default is current directory, '.') fmt : format of saved figures (default is 'svg') plot_by : specifies what sampling level you wish to plot the data at ('loc' -- plots all samples of the same location on the same plot 'exp' -- plots all samples of the same expedition on the same plot 'site' -- plots all samples of the same site on the same plot 'sample' -- plots all measurements of the same sample on the same plot 'spc' -- plots each specimen individually) treat : treatment step 'T' = thermal demagnetization 'AF' = alternating field demagnetization 'M' = microwave radiation demagnetization (default is 'AF') XLP : filter data by a particular method individual : This function outputs all plots by default. If plotting by sample or specimen, you may not wish to see (or wait for) every single plot. You can therefore specify a particular plot by setting this keyword argument to a string of the site/sample/specimen name. average_measurements : Option to average demagnetization measurements by the grouping specified with the 'plot_by' keyword argument (default is False) single_plot : Option to output a single plot with all measurements (default is False) ''' FIG = {} # plot dictionary FIG['demag'] = 1 # demag is figure 1 in_file, plot_key, LT = os.path.join( path_to_file, file_name), 'er_location_name', "LT-AF-Z" XLP = "" norm = 1 units, dmag_key = 'T', 'treatment_ac_field' plot_num = 0 if plot_by == 'loc': plot_key = 'er_location_name' elif plot_by == 'exp': plot_key = 'er_expedition_name' elif plot_by == 'site': plot_key = 'er_site_name' elif plot_by == 'sam': plot_key = 'er_sample_name' elif plot_by == 'spc': plot_key = 'er_specimen_name' if treat != None: LT = 'LT-' + treat + '-Z' # get lab treatment for plotting if LT == 'LT-T-Z': units, dmag_key = 'K', 'treatment_temp' elif LT == 'LT-AF-Z': units, dmag_key = 'T', 'treatment_ac_field' elif LT == 'LT-M-Z': units, dmag_key = 'J', 'treatment_mw_energy' else: units = 'U' else: LT = 'LT-AF-Z' plot_dict = {} data, file_type = pmag.magic_read(in_file) sids = pmag.get_specs(data) plt.figure(num=FIG['demag'], figsize=(5, 5)) print(len(data), ' records read from ', in_file) # # # find desired intensity data # # get plotlist # plotlist, intlist = [], ['measurement_magnitude', 'measurement_magn_moment', 'measurement_magn_volume', 'measurement_magn_mass'] IntMeths = [] FixData = [] for rec in data: meths = [] methcodes = rec['magic_method_codes'].split(':') for meth in methcodes: meths.append(meth.strip()) for key in list(rec.keys()): if key in intlist and rec[key] != "": if key not in IntMeths: IntMeths.append(key) if rec[plot_key] not in plotlist and LT in meths: plotlist.append(rec[plot_key]) if 'measurement_flag' not in list(rec.keys()): rec['measurement_flag'] = 'g' FixData.append(rec) plotlist.sort() if len(IntMeths) == 0: print('No intensity information found') data = FixData # plot first intensity method found - normalized to initial value anyway - # doesn't matter which used int_key = IntMeths[0] # print plotlist if individual is not None: if type(individual) == list or type(individual) == tuple: plotlist = list(individual) else: plotlist = [] plotlist.append(individual) for plot in plotlist: print(plot, 'plotting by: ', plot_key) # fish out all the data for this type of plot PLTblock = pmag.get_dictitem(data, plot_key, plot, 'T') # fish out all the dmag for this experiment type PLTblock = pmag.get_dictitem(PLTblock, 'magic_method_codes', LT, 'has') # get all with this intensity key non-blank PLTblock = pmag.get_dictitem(PLTblock, int_key, '', 'F') if XLP != "": # reject data with XLP in method_code PLTblock = pmag.get_dictitem( PLTblock, 'magic_method_codes', XLP, 'not') # for plot in plotlist: if len(PLTblock) > 2: title = PLTblock[0][plot_key] spcs = [] for rec in PLTblock: if rec['er_specimen_name'] not in spcs: spcs.append(rec['er_specimen_name']) if average_measurements is False: for spc in spcs: # plot specimen by specimen SPCblock = pmag.get_dictitem( PLTblock, 'er_specimen_name', spc, 'T') INTblock = [] for rec in SPCblock: INTblock.append([float(rec[dmag_key]), 0, 0, float( rec[int_key]), 1, rec['measurement_flag']]) if len(INTblock) > 2: pmagplotlib.plot_mag( FIG['demag'], INTblock, title, 0, units, norm) else: AVGblock = {} for spc in spcs: # plot specimen by specimen SPCblock = pmag.get_dictitem( PLTblock, 'er_specimen_name', spc, 'T') for rec in SPCblock: if rec['measurement_flag'] == 'g': if float(rec[dmag_key]) not in list(AVGblock.keys()): AVGblock[float(rec[dmag_key])] = [ float(rec[int_key])] else: AVGblock[float(rec[dmag_key])].append( float(rec[int_key])) INTblock = [] for step in sorted(AVGblock.keys()): INTblock.append([float(step), 0, 0, old_div( float(sum(AVGblock[step])), float(len(AVGblock[step]))), 1, 'g']) pmagplotlib.plot_mag(FIG['demag'], INTblock, title, 0, units, norm) if save == True: plt.savefig(os.path.join(save_folder, title) + '.' + fmt) if single_plot is False: plt.show() if single_plot is True: plt.show() def iplot_hys(fignum, B, M, s): """ function to plot hysteresis data This function has been adapted from pmagplotlib.iplot_hys for specific use within a Jupyter notebook. Parameters ----------- fignum : reference number for matplotlib figure being created B : list of B (flux density) values of hysteresis experiment M : list of M (magnetization) values of hysteresis experiment s : specimen name """ if fignum != 0: plt.figure(num=fignum) plt.clf() hpars = {} # close up loop Npts = len(M) B70 = 0.7 * B[0] # 70 percent of maximum field for b in B: if b < B70: break Nint = B.index(b) - 1 if Nint > 30: Nint = 30 if Nint < 10: Nint = 10 Bzero, Mzero, Mfix, Mnorm, Madj, MadjN = "", "", [], [], [], [] Mazero = "" m_init = 0.5 * (M[0] + M[1]) m_fin = 0.5 * (M[-1] + M[-2]) diff = m_fin - m_init Bmin = 0. for k in range(Npts): frac = old_div(float(k), float(Npts - 1)) Mfix.append((M[k] - diff * frac)) if Bzero == "" and B[k] < 0: Bzero = k if B[k] < Bmin: Bmin = B[k] kmin = k # adjust slope with first 30 data points (throwing out first 3) Bslop = B[2:Nint + 2] Mslop = Mfix[2:Nint + 2] polyU = polyfit(Bslop, Mslop, 1) # best fit line to high field points # adjust slope with first 30 points of ascending branch Bslop = B[kmin:kmin + (Nint + 1)] Mslop = Mfix[kmin:kmin + (Nint + 1)] polyL = polyfit(Bslop, Mslop, 1) # best fit line to high field points xhf = 0.5 * (polyU[0] + polyL[0]) # mean of two slopes # convert B to A/m, high field slope in m^3 hpars['hysteresis_xhf'] = '%8.2e' % (xhf * 4 * np.pi * 1e-7) meanint = 0.5 * (polyU[1] + polyL[1]) # mean of two intercepts Msat = 0.5 * (polyU[1] - polyL[1]) # mean of saturation remanence Moff = [] for k in range(Npts): # take out linear slope and offset (makes symmetric about origin) Moff.append((Mfix[k] - xhf * B[k] - meanint)) if Mzero == "" and Moff[k] < 0: Mzero = k if Mzero != "" and Mazero == "" and Moff[k] > 0: Mazero = k hpars['hysteresis_ms_moment'] = '%8.3e' % (Msat) # Ms in Am^2 # # split into upper and lower loops for splining Mupper, Bupper, Mlower, Blower = [], [], [], [] deltaM, Bdm = [], [] # diff between upper and lower curves at Bdm for k in range(kmin - 2, 0, -2): Mupper.append(old_div(Moff[k], Msat)) Bupper.append(B[k]) for k in range(kmin + 2, len(B)-1): Mlower.append(Moff[k] / Msat) Blower.append(B[k]) Iupper = spline.Spline(Bupper, Mupper) # get splines for upper up and down Ilower = spline.Spline(Blower, Mlower) # get splines for lower for b in np.arange(B[0]): # get range of field values Mpos = ((Iupper(b) - Ilower(b))) # evaluate on both sides of B Mneg = ((Iupper(-b) - Ilower(-b))) Bdm.append(b) deltaM.append(0.5 * (Mpos + Mneg)) # take average delta M print('whew') for k in range(Npts): MadjN.append(old_div(Moff[k], Msat)) Mnorm.append(old_div(M[k], Msat)) # find Mr : average of two spline fits evaluted at B=0 (times Msat) Mr = Msat * 0.5 * (Iupper(0.) - Ilower(0.)) hpars['hysteresis_mr_moment'] = '%8.3e' % (Mr) # find Bc (x intercept), interpolate between two bounding points Bz = B[Mzero - 1:Mzero + 1] Mz = Moff[Mzero - 1:Mzero + 1] Baz = B[Mazero - 1:Mazero + 1] Maz = Moff[Mazero - 1:Mazero + 1] try: poly = polyfit(Bz, Mz, 1) # best fit line through two bounding points Bc = old_div(-poly[1], poly[0]) # x intercept # best fit line through two bounding points poly = polyfit(Baz, Maz, 1) Bac = old_div(-poly[1], poly[0]) # x intercept hpars['hysteresis_bc'] = '%8.3e' % (0.5 * (abs(Bc) + abs(Bac))) except: hpars['hysteresis_bc'] = '0' return hpars, deltaM, Bdm, B, Mnorm, MadjN def hysteresis_magic2(path_to_file='.', hyst_file="rmag_hysteresis.txt", save=False, save_folder='.', fmt="svg", plots=True): """ Calculates hysteresis parameters, saves them in rmag_hysteresis format file. If selected, this function also plots hysteresis loops, delta M curves, d (Delta M)/dB curves, and IRM backfield curves. Parameters (defaults are used if not specified) ---------- path_to_file : path to directory that contains files (default is current directory, '.') hyst_file : hysteresis file (default is 'rmag_hysteresis.txt') save : boolean argument to save plots (default is False) save_folder : relative directory where plots will be saved (default is current directory, '.') fmt : format of saved figures (default is 'pdf') plots: whether or not to display the plots (default is true) """ user, meas_file, rmag_out, rmag_file = "", "agm_measurements.txt", "rmag_hysteresis.txt", "" pltspec = "" dir_path = save_folder verbose = pmagplotlib.verbose version_num = pmag.get_version() rmag_out = save_folder + '/' + rmag_out meas_file = path_to_file + '/' + hyst_file rmag_rem = save_folder + "/rmag_remanence.txt" # # meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(hysteresis_magic.__doc__) print('bad file') return # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs, RemRecs = [], [] HDD = {} HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'] = 1, 2, 3 experiment_names, sids = [], [] for rec in meas_data: meths = rec['magic_method_codes'].split(':') methods = [] for meth in meths: methods.append(meth.strip()) if 'LP-HYS' in methods: if 'er_synthetic_name' in list(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']) # fignum = 1 sample_num = 0 # initialize variables to record some bulk info in first loop first_dcd_rec, first_rec, first_imag_rec = 1, 1, 1 while sample_num < len(sids): sample = sids[sample_num] print(sample, sample_num + 1, 'out of ', len(sids)) # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data B, M, Bdcd, Mdcd = [], [], [], [] Bimag, Mimag = [], [] # Bimag,Mimag for initial magnetization curves for rec in meas_data: methcodes = rec['magic_method_codes'].split(':') meths = [] for meth in methcodes: meths.append(meth.strip()) if rec['er_specimen_name'] == sample and "LP-HYS" in meths: B.append(float(rec['measurement_lab_field_dc'])) M.append(float(rec['measurement_magn_moment'])) if first_rec == 1: e = rec['magic_experiment_name'] HystRec = {} first_rec = 0 if "er_location_name" in list(rec.keys()): HystRec["er_location_name"] = rec["er_location_name"] locname = rec['er_location_name'].replace('/', '-') if "er_sample_name" in list(rec.keys()): HystRec["er_sample_name"] = rec["er_sample_name"] if "er_site_name" in list(rec.keys()): HystRec["er_site_name"] = rec["er_site_name"] if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name'] != "": HystRec["er_synthetic_name"] = rec["er_synthetic_name"] else: HystRec["er_specimen_name"] = rec["er_specimen_name"] if rec['er_specimen_name'] == sample and "LP-IRM-DCD" in meths: Bdcd.append(float(rec['treatment_dc_field'])) Mdcd.append(float(rec['measurement_magn_moment'])) if first_dcd_rec == 1: RemRec = {} irm_exp = rec['magic_experiment_name'] first_dcd_rec = 0 if "er_location_name" in list(rec.keys()): RemRec["er_location_name"] = rec["er_location_name"] if "er_sample_name" in list(rec.keys()): RemRec["er_sample_name"] = rec["er_sample_name"] if "er_site_name" in list(rec.keys()): RemRec["er_site_name"] = rec["er_site_name"] if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name'] != "": RemRec["er_synthetic_name"] = rec["er_synthetic_name"] else: RemRec["er_specimen_name"] = rec["er_specimen_name"] if rec['er_specimen_name'] == sample and "LP-IMAG" in meths: if first_imag_rec == 1: imag_exp = rec['magic_experiment_name'] first_imag_rec = 0 Bimag.append(float(rec['measurement_lab_field_dc'])) Mimag.append(float(rec['measurement_magn_moment'])) if len(B) > 0: hmeths = [] for meth in meths: hmeths.append(meth) # fignum = 1 fig = plt.figure(figsize=(8, 8)) hpars, deltaM, Bdm, B, Mnorm, MadjN = iplot_hys(1, B, M, sample) ax1 = fig.add_subplot(2, 2, 1) ax1.axhline(0, color='k') ax1.axvline(0, color='k') ax1.plot(B, Mnorm, 'r') ax1.plot(B, MadjN, 'b') ax1.set_xlabel('B (T)') ax1.set_ylabel("M/Msat") # ax1.set_title(sample) ax1.set_xlim(-1, 1) ax1.set_ylim(-1, 1) bounds = ax1.axis() n4 = 'Ms: ' + \ '%8.2e' % (float(hpars['hysteresis_ms_moment'])) + ' Am^2' ax1.text(bounds[1] - .9 * bounds[1], -.9, n4, fontsize=9) n1 = 'Mr: ' + \ '%8.2e' % (float(hpars['hysteresis_mr_moment'])) + ' Am^2' ax1.text(bounds[1] - .9 * bounds[1], -.7, n1, fontsize=9) n2 = 'Bc: ' + '%8.2e' % (float(hpars['hysteresis_bc'])) + ' T' ax1.text(bounds[1] - .9 * bounds[1], -.5, n2, fontsize=9) if 'hysteresis_xhf' in list(hpars.keys()): n3 = r'Xhf: ' + \ '%8.2e' % (float(hpars['hysteresis_xhf'])) + ' m^3' ax1.text(bounds[1] - .9 * bounds[1], -.3, n3, fontsize=9) # plt.subplot(1,2,2) # plt.subplot(1,3,3) 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 = 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: ax2 = fig.add_subplot(2, 2, 2) ax2.plot(Bdm, deltaM, 'b') ax2.set_xlabel('B (T)') ax2.set_ylabel('Delta M') linex = [0, Bcr, Bcr] liney = [old_div(deltaM[0], 2.), old_div(deltaM[0], 2.), 0] ax2.plot(linex, liney, 'r') # ax2.set_title(sample) ax3 = fig.add_subplot(2, 2, 3) ax3.plot(Bdm[(len(Bdm) - len(DdeltaM)):], DdeltaM, 'b') ax3.set_xlabel('B (T)') ax3.set_ylabel('d (Delta M)/dB') # ax3.set_title(sample) ax4 = fig.add_subplot(2, 2, 4) ax4.plot(Bdcd, Mdcd) ax4.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e')) ax4.axhline(0, color='k') ax4.axvline(0, color='k') ax4.set_xlabel('B (T)') ax4.set_ylabel('M/Mr') except: print("not doing it") hpars['hysteresis_bcr'] = '0' hpars['magic_method_codes'] = "" plt.gcf() plt.gca() plt.tight_layout() if save: plt.savefig(save_folder + '/' + sample + '_hysteresis.' + fmt) plt.show() sample_num += 1 def find_ei(data, nb=1000, save=False, save_folder='.', fmt='svg', site_correction=False, return_new_dirs=False): """ Applies series of assumed flattening factor and "unsquishes" inclinations assuming tangent function. Finds flattening factor that gives elongation/inclination pair consistent with TK03; or, if correcting by site instead of for study-level secular variation, finds flattening factor that minimizes elongation and most resembles a Fisherian distribution. Finds bootstrap confidence bounds Required Parameter ----------- data: a nested list of dec/inc pairs Optional Parameters (defaults are used unless specified) ----------- nb: number of bootstrapped pseudo-samples (default is 1000) save: Boolean argument to save plots (default is False) save_folder: path to folder in which plots should be saved (default is current directory) fmt: specify format of saved plots (default is 'svg') site_correction: Boolean argument to specify whether to "unsquish" data to 1) the elongation/inclination pair consistent with TK03 secular variation model (site_correction = False) or 2) a Fisherian distribution (site_correction = True). Default is FALSE. Note that many directions (~ 100) are needed for this correction to be reliable. return_new_dirs: optional return of newly "unflattened" directions (default is False) Returns ----------- four plots: 1) equal area plot of original directions 2) Elongation/inclination pairs as a function of f, data plus 25 bootstrap samples 3) Cumulative distribution of bootstrapped optimal inclinations plus uncertainties. Estimate from original data set plotted as solid line 4) Orientation of principle direction through unflattening NOTE: If distribution does not have a solution, plot labeled: Pathological. Some bootstrap samples may have valid solutions and those are plotted in the CDFs and E/I plot. """ print("Bootstrapping.... be patient") print("") sys.stdout.flush() upper, lower = int(round(.975 * nb)), int(round(.025 * nb)) E, I = [], [] plt.figure(num=1, figsize=(4, 4)) plot_net(1) plot_di(di_block=data) plt.title('Original') ppars = pmag.doprinc(data) Io = ppars['inc'] n = ppars["N"] Es, Is, Fs, V2s = pmag.find_f(data) if site_correction == True: Inc, Elong = Is[Es.index(min(Es))], Es[Es.index(min(Es))] flat_f = Fs[Es.index(min(Es))] else: Inc, Elong = Is[-1], Es[-1] flat_f = Fs[-1] plt.figure(num=2, figsize=(4, 4)) plt.plot(Is, Es, 'r') plt.xlabel("Inclination") plt.ylabel("Elongation") plt.text(Inc, Elong, ' %3.1f' % (flat_f)) plt.text(Is[0] - 2, Es[0], ' %s' % ('f=1')) b = 0 while b < nb: bdata = pmag.pseudo(data) Esb, Isb, Fsb, V2sb = pmag.find_f(bdata) if b < 25: plt.plot(Isb, Esb, 'y') if Esb[-1] != 0: ppars = pmag.doprinc(bdata) if site_correction == True: I.append(abs(Isb[Esb.index(min(Esb))])) E.append(Esb[Esb.index(min(Esb))]) else: I.append(abs(Isb[-1])) E.append(Esb[-1]) b += 1 I.sort() E.sort() Eexp = [] for i in I: Eexp.append(pmag.EI(i)) plt.plot(I, Eexp, 'g-') if Inc == 0: title = 'Pathological Distribution: ' + \ '[%7.1f, %7.1f]' % (I[lower], I[upper]) else: title = '%7.1f [%7.1f, %7.1f]' % (Inc, I[lower], I[upper]) cdf_fig_num = 3 plt.figure(num=cdf_fig_num, figsize=(4, 4)) pmagplotlib.plot_cdf(cdf_fig_num, I, 'Inclinations', 'r', title) pmagplotlib.plot_vs(cdf_fig_num, [I[lower], I[upper]], 'b', '--') pmagplotlib.plot_vs(cdf_fig_num, [Inc], 'g', '-') pmagplotlib.plot_vs(cdf_fig_num, [Io], 'k', '-') # plot corrected directional data di_lists = unpack_di_block(data) if len(di_lists) == 3: decs, incs, intensity = di_lists if len(di_lists) == 2: decs, incs = di_lists if flat_f: unsquished_incs = unsquish(incs, flat_f) plt.figure(num=4, figsize=(4, 4)) plot_net(4) plot_di(decs, unsquished_incs) plt.title('Corrected for flattening') else: plt.figure(num=4, figsize=(4, 4)) plot_net(4) plot_di(decs, incs) plt.title('Corrected for flattening') if (Inc, Elong, flat_f) == (0, 0, 0): print("PATHOLOGICAL DISTRIBUTION") print("The original inclination was: " + str(Io)) print("") print("The corrected inclination is: " + str(Inc)) print("with bootstrapped confidence bounds of: " + str(I[lower]) + ' to ' + str(I[upper])) print("and elongation parameter of: " + str(Elong)) print("The flattening factor is: " + str(flat_f)) if return_new_dirs is True: return make_di_block(decs, unsquished_incs) def plate_rate_mc(pole1_plon, pole1_plat, pole1_kappa, pole1_N, pole1_age, pole1_age_error, pole2_plon, pole2_plat, pole2_kappa, pole2_N, pole2_age, pole2_age_error, ref_loc_lon, ref_loc_lat, samplesize=10000, random_seed=None, plot=True, savefig=True, save_directory='./', figure_name=''): """ Determine the latitudinal motion implied by a pair of poles and utilize the Monte Carlo sampling method of Swanson-Hysell (2014) to determine the associated uncertainty. Parameters: ------------ plon : longitude of pole plat : latitude of pole kappa : Fisher precision parameter for VPGs in pole N : number of VGPs in pole age : age assigned to pole in Ma age_error : 1 sigma age uncertainty in million years ref_loc_lon : longitude of reference location ref_loc_lat : latitude of reference location samplesize : number of draws from pole and age distributions (default set to 10000) random_seed : set random seed for reproducible number generation (default is None) plot : whether to make figures (default is True, optional) savefig : whether to save figures (default is True, optional) save_directory = default is local directory (optional) figure_name = prefix for file names (optional) Returns -------- rate : rate of latitudinal motion in cm/yr along with estimated 2.5 and 97.5 percentile rate estimates """ ref_loc = [ref_loc_lon, ref_loc_lat] pole1 = (pole1_plon, pole1_plat) pole1_paleolat = 90 - pmag.angle(pole1, ref_loc) pole2 = (pole2_plon, pole2_plat) pole2_paleolat = 90 - pmag.angle(pole2, ref_loc) print("The paleolatitude for ref_loc resulting from pole 1 is:" + str(pole1_paleolat)) print("The paleolatitude for ref_loc resulting from pole 2 is:" + str(pole2_paleolat)) rate = old_div(((pole1_paleolat - pole2_paleolat) * 111 * 100000), ((pole1_age - pole2_age) * 1000000)) print("The rate of paleolatitudinal change implied by the poles pairs in cm/yr is:" + str(rate)) if random_seed != None: np.random.seed(random_seed) pole1_MCages = np.random.normal(pole1_age, pole1_age_error, samplesize) pole2_MCages = np.random.normal(pole2_age, pole2_age_error, samplesize) plt.hist(pole1_MCages, 100, histtype='stepfilled', color='darkred', label='Pole 1 ages') plt.hist(pole2_MCages, 100, histtype='stepfilled', color='darkblue', label='Pole 2 ages') plt.xlabel('Age (Ma)') plt.ylabel('n') plt.legend(loc=3) if savefig == True: plot_extension = '_1.svg' plt.savefig(save_directory + figure_name + plot_extension) plt.show() pole1_MCpoles = [] pole1_MCpole_lat = [] pole1_MCpole_long = [] pole1_MCpaleolat = [] for n in range(samplesize): vgp_samples = [] for vgp in range(pole1_N): # pmag.dev returns a direction from a fisher distribution with # specified kappa direction_atN = pmag.fshdev(pole1_kappa) # this direction is centered at latitude of 90 degrees and needs to be rotated # to be centered on the mean pole position tilt_direction = pole1_plon tilt_amount = 90 - pole1_plat direction = pmag.dotilt( direction_atN[0], direction_atN[1], tilt_direction, tilt_amount) vgp_samples.append([direction[0], direction[1], 1.]) mean = pmag.fisher_mean(vgp_samples) mean_pole_position = (mean['dec'], mean['inc']) pole1_MCpoles.append([mean['dec'], mean['inc'], 1.]) pole1_MCpole_lat.append(mean['inc']) pole1_MCpole_long.append(mean['dec']) paleolat = 90 - pmag.angle(mean_pole_position, ref_loc) pole1_MCpaleolat.append(paleolat[0]) pole2_MCpoles = [] pole2_MCpole_lat = [] pole2_MCpole_long = [] pole2_MCpaleolat = [] for n in range(samplesize): vgp_samples = [] for vgp in range(pole2_N): # pmag.dev returns a direction from a fisher distribution with # specified kappa direction_atN = pmag.fshdev(pole2_kappa) # this direction is centered at latitude of 90 degrees and needs to be rotated # to be centered on the mean pole position tilt_direction = pole2_plon tilt_amount = 90 - pole2_plat direction = pmag.dotilt( direction_atN[0], direction_atN[1], tilt_direction, tilt_amount) vgp_samples.append([direction[0], direction[1], 1.]) mean = pmag.fisher_mean(vgp_samples) mean_pole_position = (mean['dec'], mean['inc']) pole2_MCpoles.append([mean['dec'], mean['inc'], 1.]) pole2_MCpole_lat.append(mean['inc']) pole2_MCpole_long.append(mean['dec']) paleolat = 90 - pmag.angle(mean_pole_position, ref_loc) pole2_MCpaleolat.append(paleolat[0]) if plot is True: plt.figure(figsize=(5, 5)) map_axis = make_mollweide_map() plot_vgp(map_axis, pole1_MCpole_long, pole1_MCpole_lat, color='b') plot_vgp(map_axis, pole2_MCpole_long, pole2_MCpole_lat, color='g') if savefig == True: plot_extension = '_2.svg' plt.savefig(save_directory + figure_name + plot_extension) plt.show() # calculating the change in paleolatitude between the Monte Carlo pairs pole1_pole2_Delta_degrees = [] pole1_pole2_Delta_kilometers = [] pole1_pole2_Delta_myr = [] pole1_pole2_degrees_per_myr = [] pole1_pole2_cm_per_yr = [] for n in range(samplesize): Delta_degrees = pole1_MCpaleolat[n] - pole2_MCpaleolat[n] Delta_Myr = pole1_MCages[n] - pole2_MCages[n] pole1_pole2_Delta_degrees.append(Delta_degrees) degrees_per_myr = old_div(Delta_degrees, Delta_Myr) cm_per_yr = old_div(((Delta_degrees * 111) * 100000), (Delta_Myr * 1000000)) pole1_pole2_degrees_per_myr.append(degrees_per_myr) pole1_pole2_cm_per_yr.append(cm_per_yr) if plot is True: plotnumber = 100 plt.figure(num=None, figsize=(10, 4)) plt.subplot(1, 2, 1) for n in range(plotnumber): plt.plot([pole1_MCpaleolat[n], pole2_MCpaleolat[n]], [pole1_MCages[n], pole2_MCages[n]], 'k-', linewidth=0.1, alpha=0.3) plt.scatter(pole1_MCpaleolat[:plotnumber], pole1_MCages[:plotnumber], color='b', s=3) plt.scatter(pole1_paleolat, pole1_age, color='lightblue', s=100, edgecolor='w', zorder=10000) plt.scatter(pole2_MCpaleolat[:plotnumber], pole2_MCages[:plotnumber], color='g', s=3) plt.scatter(pole2_paleolat, pole2_age, color='lightgreen', s=100, edgecolor='w', zorder=10000) plt.plot([pole1_paleolat, pole2_paleolat], [ pole1_age, pole2_age], 'w-', linewidth=2) plt.gca().invert_yaxis() plt.xlabel('paleolatitude (degrees)', size=14) plt.ylabel('time (Ma)', size=14) plt.subplot(1, 2, 2) plt.hist(pole1_pole2_cm_per_yr, bins=600) plt.ylabel('n', size=14) plt.xlabel('latitudinal drift rate (cm/yr)', size=14) # plt.xlim([0,90]) if savefig == True: plot_extension = '_3.svg' plt.savefig(save_directory + figure_name + plot_extension) plt.show() twopointfive_percentile = stats.scoreatpercentile( pole1_pole2_cm_per_yr, 2.5) fifty_percentile = stats.scoreatpercentile(pole1_pole2_cm_per_yr, 50) ninetysevenpointfive_percentile = stats.scoreatpercentile( pole1_pole2_cm_per_yr, 97.5) print("2.5th percentile is: " + str(round(twopointfive_percentile, 2)) + " cm/yr") print("50th percentile is: " + str(round(fifty_percentile, 2)) + " cm/yr") print("97.5th percentile is: " + str(round(ninetysevenpointfive_percentile, 2)) + " cm/yr") return rate[0], twopointfive_percentile, ninetysevenpointfive_percentile def zeq(path_to_file='.', file='', data="", units='U', calculation_type="DE-BFL", save=False, save_folder='.', fmt='svg', begin_pca="", end_pca="", angle=0): """ NAME zeq.py DESCRIPTION plots demagnetization data for a single specimen: - The solid (open) symbols in the Zijderveld diagram are X,Y (X,Z) pairs. The demagnetization diagram plots the fractional remanence remaining after each step. The green line is the fraction of the total remaence removed between each step. If the principle direction is desired, specify begin_pca and end_pca steps as bounds for calculation. -The equal area projection has the X direction (usually North in geographic coordinates) to the top. The red line is the X axis of the Zijderveld diagram. Solid symbols are lower hemisphere. - red dots and blue line is the remanence remaining after each step. The green line is the partial TRM removed in each interval INPUT FORMAT reads from file_name or takes a Pandas DataFrame data with specimen treatment intensity declination inclination as columns Keywords: file= FILE a space or tab delimited file with specimen treatment declination inclination intensity units= [mT,C] specify units of mT OR C, default is unscaled save=[True,False] save figure and quit, default is False fmt [svg,jpg,png,pdf] set figure format [default is svg] begin_pca [step number] treatment step for beginning of PCA calculation, default end_pca [step number] treatment step for end of PCA calculation, last step is default calculation_type [DE-BFL,DE-BFP,DE-FM] Calculation Type: best-fit line, plane or fisher mean; line is default angle=[0-360]: angle to subtract from declination to rotate in horizontal plane, default is 0 """ if units == "C": SIunits = "K" if units == "mT": SIunits = "T" if units == "U": SIunits = "U" if file != "": f = pd.read_csv(os.path.join(path_to_file, file), delim_whitespace=True, header=None) f.columns = ['specimen', 'treatment', 'intensity', 'declination', 'inclination'] # adjust for angle rotation f['declination'] = (f['declination']-angle) % 360 f['quality'] = 'g' f['type'] = '' # s = f['specimen'].tolist()[0] if units == 'mT': f['treatment'] = f['treatment']*1e-3 if units == 'C': f['treatment'] = f['treatment']+273 data = f[['treatment', 'declination', 'inclination', 'intensity', 'type', 'quality']] print(s) datablock = data.values.tolist() # define figure numbers in a dictionary for equal area, zijderveld, # and intensity vs. demagnetiztion step respectively ZED = {} ZED['eqarea'], ZED['zijd'], ZED['demag'] = 2, 1, 3 plt.figure(num=ZED['zijd'], figsize=(5, 5)) plt.figure(num=ZED['eqarea'], figsize=(5, 5)) plt.figure(num=ZED['demag'], figsize=(5, 5)) # # pmagplotlib.plot_zed(ZED, datablock, angle, s, SIunits) # plot the data # # print out data for this sample to screen # recnum = 0 print('step treat intensity dec inc') for plotrec in datablock: if units == 'mT': print('%i %7.1f %8.3e %7.1f %7.1f ' % (recnum, plotrec[0]*1e3, plotrec[3], plotrec[1], plotrec[2])) if units == 'C': print('%i %7.1f %8.3e %7.1f %7.1f ' % (recnum, plotrec[0]-273., plotrec[3], plotrec[1], plotrec[2])) if units == 'U': print('%i %7.1f %8.3e %7.1f %7.1f ' % (recnum, plotrec[0], plotrec[3], plotrec[1], plotrec[2])) recnum += 1 pmagplotlib.draw_figs(ZED) if begin_pca != "" and end_pca != "" and calculation_type != "": pmagplotlib.plot_zed(ZED, datablock, angle, s, SIunits) # plot the data # get best-fit direction/great circle mpars = pmag.domean(datablock, begin_pca, end_pca, calculation_type) # plot the best-fit direction/great circle pmagplotlib.plot_dir(ZED, mpars, datablock, angle) print('Specimen, calc_type, N, min, max, MAD, dec, inc') if units == 'mT': print('%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"]*1e3, mpars["measurement_step_max"]*1e3, mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) if units == 'C': print('%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"]-273, mpars["measurement_step_max"]-273, mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) if units == 'U': print('%s %s %i %6.2f %6.2f %6.1f %7.1f %7.1f' % (s, calculation_type, mpars["specimen_n"], mpars["measurement_step_min"], mpars["measurement_step_max"], mpars["specimen_mad"], mpars["specimen_dec"], mpars["specimen_inc"])) if save: files = {} for key in list(ZED.keys()): files[key] = s+'_'+key+'.'+fmt pmagplotlib.save_plots(ZED, files) def aniso_magic(infile='specimens.txt', samp_file='samples.txt', site_file='sites.txt', ipar=1, ihext=1, ivec=1, iplot=0, isite=1, iboot=1, vec=0, Dir=[], PDir=[], comp=0, user="", fmt="png", crd="s", verbose=True, plots=0, num_bootstraps=1000, dir_path=".", input_dir_path=""): def save(ANIS, fmt, title): files = {} for key in list(ANIS.keys()): if pmagplotlib.isServer: files[key] = title + '_TY:_aniso-' + key + '_.' + fmt else: files[key] = title.replace( '__', '_') + "_aniso-" + key + "." + fmt pmagplotlib.save_plots(ANIS, files) if not input_dir_path: input_dir_path = dir_path input_dir_path = os.path.realpath(input_dir_path) dir_path = os.path.realpath(dir_path) print('input dir path', input_dir_path) print('dir path', dir_path) # initialize some variables version_num = pmag.get_version() hpars, bpars = [], [] ResRecs = [] if crd == 'g': CS = 0 elif crd == 't': CS = 100 else: CS = -1 # specimen # # set up plots # ANIS = {} initcdf, inittcdf = 0, 0 ANIS['data'], ANIS['conf'] = 1, 2 if iboot == 1: ANIS['tcdf'] = 3 if iplot == 1: inittcdf = 1 pmagplotlib.plot_init(ANIS['tcdf'], 5, 5) if comp == 1 and iplot == 1: initcdf = 1 ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6 pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5) pmagplotlib.plot_init(ANIS['vycdf'], 5, 5) pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5) if iplot == 1: pmagplotlib.plot_init(ANIS['conf'], 5, 5) pmagplotlib.plot_init(ANIS['data'], 5, 5) # read in the data fnames = {'specimens': infile, 'samples': samp_file, 'sites': site_file} con = cb.Contribution(input_dir_path, read_tables=['specimens', 'samples', 'sites'], custom_filenames=fnames) con.propagate_location_to_specimens() if isite: con.propagate_name_down('site', 'specimens') spec_container = con.tables['specimens'] #spec_df = spec_container.get_records_for_code('AE-', strict_match=False) spec_df = spec_container.df # get only anisotropy records spec_df = spec_df.dropna(subset=['aniso_s']).copy() if 'aniso_tilt_correction' not in spec_df.columns: spec_df['aniso_tilt_correction'] = -1 # assume specimen coordinates orlist = spec_df['aniso_tilt_correction'].dropna().unique() if CS not in orlist: if len(orlist) > 0: CS = orlist[0] else: CS = -1 if CS == -1: crd = 's' if CS == 0: crd = 'g' if CS == 100: crd = 't' if verbose: print("desired coordinate system not available, using available: ", crd) if isite == 1: if 'site' not in spec_df.columns: print( "cannot plot by site -- make sure you have a samples and site table available") print("plotting all data instead") isite = 0 plot = 1 else: sitelist = spec_df['site'].unique() sitelist.sort() plot = len(sitelist) else: plot = 1 k = 0 while k < plot: site = "" loc_name = "" sdata, Ss = [], [] # list of S format data if isite == 0: sdata = spec_df if 'location' in sdata.columns: try: loc_name = ':'.join(sdata['location'].unique()) except TypeError: loc_name = "" else: site = sitelist[k] sdata = spec_df[spec_df['site'] == site] if 'location' in sdata.columns: loc_name = sdata['location'].tolist()[0] csrecs = sdata[sdata['aniso_tilt_correction'] == CS] anitypes = csrecs['aniso_type'].unique() for name in ['citations', 'location', 'site', 'sample']: if name not in csrecs: csrecs[name] = "" Locs = csrecs['location'].unique() #Sites = csrecs['site'].unique() #Samples = csrecs['sample'].unique() #Specimens = csrecs['specimen'].unique() #Cits = csrecs['citations'].unique() for ind, rec in csrecs.iterrows(): s = [float(i.strip()) for i in rec['aniso_s'].split(':')] if s[0] <= 1.0: Ss.append(s) # protect against crap ResRec = {} ResRec['specimen'] = rec['specimen'] ResRec['sample'] = rec['sample'] ResRec['analysts'] = user ResRec['citations'] = rec['citations'] ResRec['software_packages'] = version_num ResRec['dir_tilt_correction'] = CS ResRec["aniso_type"] = rec["aniso_type"] # tau,Vdirs=pmag.doseigs(s) if "aniso_s_n_measurements" not in rec.keys(): rec["aniso_s_n_measurements"] = "6" if "aniso_s_sigma" not in rec.keys(): rec["aniso_s_sigma"] = "0" fpars = pmag.dohext( int(rec["aniso_s_n_measurements"]) - 6, float(rec["aniso_s_sigma"]), s) aniso_v1 = " : ".join( [str(i) for i in [fpars['t1'], fpars['v1_dec'], fpars['v1_inc']]]) aniso_v2 = " : ".join( [str(i) for i in [fpars['t2'], fpars['v2_dec'], fpars['v2_inc']]]) aniso_v3 = " : ".join( [str(i) for i in [fpars['t3'], fpars['v3_dec'], fpars['v3_inc']]]) ResRec['aniso_v1'] = aniso_v1 ResRec['aniso_v2'] = aniso_v2 ResRec['aniso_v3'] = aniso_v3 ResRec['aniso_ftest'] = fpars['F'] ResRec['aniso_ftest12'] = fpars['F12'] ResRec['aniso_ftest23'] = fpars['F23'] ResRec['description'] = 'F_crit: '+fpars['F_crit'] + \ '; F12,F23_crit: '+fpars['F12_crit'] ResRec['aniso_type'] = pmag.makelist(anitypes) ResRecs.append(ResRec) if len(Ss) > 1: if pmagplotlib.isServer: # use server plot naming convention title = "LO:_" + loc_name + '_SI:_' + site + '_SA:__SP:__CO:_' + crd else: # use more readable plot naming convention title = "{}_{}_{}".format(loc_name, site, crd) bpars, hpars = pmagplotlib.plot_anis(ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, num_bootstraps) if len(PDir) > 0: pmagplotlib.plot_circ(ANIS['data'], PDir, 90., 'g') pmagplotlib.plot_circ(ANIS['conf'], PDir, 90., 'g') if verbose and plots == 0: pmagplotlib.draw_figs(ANIS) if plots == 1: save(ANIS, fmt, title) if hpars != [] and ihext == 1: HextRec = {} for key in ResRec.keys(): HextRec[key] = ResRec[key] # copy over stuff # group these into HextRec['aniso_v1'] anisotropy_t1 = hpars["t1"] anisotropy_v1_dec = hpars["v1_dec"] anisotropy_v1_inc = hpars["v1_inc"] eta_zeta = "eta/zeta" anisotropy_v1_eta_dec = hpars["v2_dec"] anisotropy_v1_eta_inc = hpars["v2_inc"] anisotropy_v1_eta_semi_angle = hpars["e12"] anisotropy_v1_zeta_dec = hpars["v3_dec"] anisotropy_v1_zeta_inc = hpars["v3_inc"] anisotropy_v1_zeta_semi_angle = hpars["e13"] aniso_v1_list = [anisotropy_t1, anisotropy_v1_dec, anisotropy_v1_inc, eta_zeta, anisotropy_v1_eta_dec, anisotropy_v1_eta_inc, anisotropy_v1_eta_semi_angle, anisotropy_v1_zeta_dec, anisotropy_v1_zeta_inc, anisotropy_v1_zeta_semi_angle] aniso_v1 = " : ".join([str(i) for i in aniso_v1_list]) HextRec['aniso_v1'] = aniso_v1 # for printing HextRec["anisotropy_t1"] = '%10.8f' % (hpars["t1"]) HextRec["anisotropy_v1_dec"] = '%7.1f' % (hpars["v1_dec"]) HextRec["anisotropy_v1_inc"] = '%7.1f' % (hpars["v1_inc"]) HextRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars["e12"]) HextRec["anisotropy_v1_eta_dec"] = '%7.1f ' % (hpars["v2_dec"]) HextRec["anisotropy_v1_eta_inc"] = '%7.1f ' % (hpars["v2_inc"]) HextRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars["e13"]) HextRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars["v3_dec"]) HextRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars["v3_inc"]) # group these into HextRec['aniso_v2'] aniso_v2 = " : ".join( [str(i) for i in [hpars["t2"], hpars["v2_dec"], hpars["v2_inc"]]]) aniso_v2 += " : eta/zeta : " aniso_v2 += " : ".join([str(i) for i in [hpars['v1_dec'], hpars['v1_inc'], hpars['e12'], hpars['v3_dec'], hpars['v3_inc'], hpars['e23']]]) HextRec["aniso_v2"] = aniso_v2 # for printing HextRec["anisotropy_v2_dec"] = '%7.1f' % (hpars["v2_dec"]) HextRec["anisotropy_v2_inc"] = '%7.1f' % (hpars["v2_inc"]) HextRec["anisotropy_t2"] = '%10.8f' % (hpars["t2"]) HextRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars["e12"]) HextRec["anisotropy_v2_eta_dec"] = '%7.1f ' % (hpars["v1_dec"]) HextRec["anisotropy_v2_eta_inc"] = '%7.1f ' % (hpars["v1_inc"]) HextRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars["e23"]) HextRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars["v3_dec"]) HextRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars["v3_inc"]) # group these into HextRec['aniso_v3'] aniso_v3 = " : ".join( [str(i) for i in [hpars["t3"], hpars["v3_dec"], hpars["v3_inc"]]]) aniso_v3 += " : eta/zeta : " aniso_v3 += " : ".join([str(i) for i in [hpars["v1_dec"], hpars["v1_inc"], hpars["e12"], hpars["v2_dec"], hpars["v2_inc"], hpars["e23"]]]) HextRec["aniso_v3"] = aniso_v3 # for printing HextRec["anisotropy_v3_dec"] = '%7.1f' % (hpars["v3_dec"]) HextRec["anisotropy_v3_inc"] = '%7.1f' % (hpars["v3_inc"]) HextRec["anisotropy_t3"] = '%10.8f' % (hpars["t3"]) HextRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars["e12"]) HextRec["anisotropy_v3_eta_dec"] = '%7.1f ' % (hpars["v1_dec"]) HextRec["anisotropy_v3_eta_inc"] = '%7.1f ' % (hpars["v1_inc"]) HextRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars["e23"]) HextRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars["v2_dec"]) HextRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars["v2_inc"]) # not valid MagIC columns (2.5 or 3) HextRec["anisotropy_hext_F"] = '%7.1f ' % (hpars["F"]) HextRec["anisotropy_hext_F12"] = '%7.1f ' % (hpars["F12"]) HextRec["anisotropy_hext_F23"] = '%7.1f ' % (hpars["F23"]) # HextRec["method_codes"] = 'LP-AN:AE-H' if verbose: print("Hext Statistics: ") print( " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I") print(HextRec["anisotropy_t1"], HextRec["anisotropy_v1_dec"], end=' ') print(HextRec["anisotropy_v1_inc"], HextRec["anisotropy_v1_eta_semi_angle"], end=' ') print(HextRec["anisotropy_v1_eta_dec"], HextRec["anisotropy_v1_eta_inc"], end=' ') print(HextRec["anisotropy_v1_zeta_semi_angle"], HextRec["anisotropy_v1_zeta_dec"], end=' ') print(HextRec["anisotropy_v1_zeta_inc"]) # print(HextRec["anisotropy_t2"], HextRec["anisotropy_v2_dec"], end=' ') print(HextRec["anisotropy_v2_inc"], HextRec["anisotropy_v2_eta_semi_angle"], end=' ') print(HextRec["anisotropy_v2_eta_dec"], HextRec["anisotropy_v2_eta_inc"], end=' ') print(HextRec["anisotropy_v2_zeta_semi_angle"], HextRec["anisotropy_v2_zeta_dec"], end=' ') print(HextRec["anisotropy_v2_zeta_inc"]) # print(HextRec["anisotropy_t3"], HextRec["anisotropy_v3_dec"], end=' ') print(HextRec["anisotropy_v3_inc"], HextRec["anisotropy_v3_eta_semi_angle"], end=' ') print(HextRec["anisotropy_v3_eta_dec"], HextRec["anisotropy_v3_eta_inc"], end=' ') print(HextRec["anisotropy_v3_zeta_semi_angle"], HextRec["anisotropy_v3_zeta_dec"], end=' ') print(HextRec["anisotropy_v3_zeta_inc"]) HextRec['software_packages'] = version_num # strip out invalid keys for key in HextRec.copy(): if key.startswith('anisotropy_'): # and 'hext' not in key: HextRec.pop(key) ResRecs.append(HextRec) if bpars != []: BootRec = {} for key in ResRec.keys(): BootRec[key] = ResRec[key] # copy over stuff aniso_v1 = " : ".join([str(i) for i in [bpars['t1'], bpars['v1_dec'], bpars['v1_inc']]]) aniso_v1 += " : eta/zeta : " aniso_v1 += " : ".join([str(i) for i in [bpars['v1_eta_dec'], bpars['v1_eta_inc'], bpars['v1_eta'], bpars['v1_zeta_dec'], bpars['v1_zeta_inc'], bpars['v1_zeta']]]) BootRec['aniso_v1'] = aniso_v1 # for printing BootRec["anisotropy_v1_dec"] = '%7.1f' % (bpars["v1_dec"]) BootRec["anisotropy_v2_dec"] = '%7.1f' % (bpars["v2_dec"]) BootRec["anisotropy_v3_dec"] = '%7.1f' % (bpars["v3_dec"]) BootRec["anisotropy_v1_inc"] = '%7.1f' % (bpars["v1_inc"]) BootRec["anisotropy_v2_inc"] = '%7.1f' % (bpars["v2_inc"]) BootRec["anisotropy_v3_inc"] = '%7.1f' % (bpars["v3_inc"]) BootRec["anisotropy_t1"] = '%10.8f' % (bpars["t1"]) BootRec["anisotropy_t2"] = '%10.8f' % (bpars["t2"]) BootRec["anisotropy_t3"] = '%10.8f' % (bpars["t3"]) BootRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( bpars["v1_eta_inc"]) BootRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( bpars["v1_eta_dec"]) BootRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( bpars["v1_eta"]) BootRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( bpars["v1_zeta_inc"]) BootRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( bpars["v1_zeta_dec"]) BootRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( bpars["v1_zeta"]) # group these into aniso_v2 aniso_v2 = " : ".join( [str(i) for i in [bpars["t2"], bpars["v2_dec"], bpars["v2_inc"]]]) aniso_v2 += " : eta/zeta : " aniso_v2 += " : ".join([str(i) for i in [bpars['v2_eta_dec'], bpars['v2_eta_inc'], bpars['v2_eta'], bpars['v2_zeta_dec'], bpars['v2_zeta_inc'], bpars['v2_zeta']]]) BootRec['aniso_v2'] = aniso_v2 # for printing BootRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( bpars["v2_eta_inc"]) BootRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( bpars["v2_eta_dec"]) BootRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( bpars["v2_eta"]) BootRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( bpars["v2_zeta_inc"]) BootRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( bpars["v2_zeta_dec"]) BootRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( bpars["v2_zeta"]) # group into aniso_v3 aniso_v3 = " : ".join( [str(i) for i in [bpars["t3"], bpars["v3_dec"], bpars["v3_inc"]]]) aniso_v3 += " : eta/zeta : " aniso_v3 += " : ".join([str(i) for i in [bpars["v3_eta_dec"], bpars["v3_eta_inc"], bpars["v3_eta"], bpars["v3_zeta_dec"], bpars["v3_zeta_inc"], bpars["v3_zeta"]]]) BootRec["aniso_v3"] = aniso_v3 # for printing BootRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( bpars["v3_eta_inc"]) BootRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( bpars["v3_eta_dec"]) BootRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( bpars["v3_eta"]) BootRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( bpars["v3_zeta_inc"]) BootRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( bpars["v3_zeta_dec"]) BootRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( bpars["v3_zeta"]) # not valid MagIC columns BootRec["anisotropy_hext_F"] = '' BootRec["anisotropy_hext_F12"] = '' BootRec["anisotropy_hext_F23"] = '' # # regular bootstrap BootRec["method_codes"] = 'LP-AN:AE-H:AE-BS' if ipar == 1: # parametric bootstrap BootRec["method_codes"] = 'LP-AN:AE-H:AE-BS-P' if verbose: print("Bootstrap Statistics: ") print( " tau_i, V_i_D, V_i_I, V_i_zeta, V_i_zeta_D, V_i_zeta_I, V_i_eta, V_i_eta_D, V_i_eta_I") print(BootRec["anisotropy_t1"], BootRec["anisotropy_v1_dec"], end=' ') print(BootRec["anisotropy_v1_inc"], BootRec["anisotropy_v1_eta_semi_angle"], end=' ') print(BootRec["anisotropy_v1_eta_dec"], BootRec["anisotropy_v1_eta_inc"], end=' ') print(BootRec["anisotropy_v1_zeta_semi_angle"], BootRec["anisotropy_v1_zeta_dec"], end=' ') print(BootRec["anisotropy_v1_zeta_inc"]) # print(BootRec["anisotropy_t2"], BootRec["anisotropy_v2_dec"], BootRec["anisotropy_v2_inc"], end=' ') print(BootRec["anisotropy_v2_eta_semi_angle"], BootRec["anisotropy_v2_eta_dec"], end=' ') print(BootRec["anisotropy_v2_eta_inc"], BootRec["anisotropy_v2_zeta_semi_angle"], end=' ') print(BootRec["anisotropy_v2_zeta_dec"], BootRec["anisotropy_v2_zeta_inc"]) # print(BootRec["anisotropy_t3"], BootRec["anisotropy_v3_dec"], BootRec["anisotropy_v3_inc"], end=' ') print(BootRec["anisotropy_v3_eta_semi_angle"], BootRec["anisotropy_v3_eta_dec"], end=' ') print(BootRec["anisotropy_v3_eta_inc"], BootRec["anisotropy_v3_zeta_semi_angle"], end=' ') print(BootRec["anisotropy_v3_zeta_dec"], BootRec["anisotropy_v3_zeta_inc"]) BootRec['software_packages'] = version_num # strip out invalid keys for key in BootRec.copy(): if key.startswith('anisotropy_'): # and 'hext' not in key: BootRec.pop(key) # THESE SHOULD BE AT A DIFFERENT LEVEL??? MAYBE SITE? ResRecs.append(BootRec) k += 1 goon = 1 while goon == 1 and iplot == 1 and verbose: if iboot == 1: print("compare with [d]irection ") print( " plot [g]reat circle, change [c]oord. system, change [e]llipse calculation, s[a]ve plots, [q]uit ") if isite == 1: print(" [p]revious, [s]ite, [q]uit, <return> for next ") ans = input("") if ans == "q": sys.exit() if ans == "e": iboot, ipar, ihext, ivec = 1, 0, 0, 0 e = input("Do Hext Statistics 1/[0]: ") if e == "1": ihext = 1 e = input("Suppress bootstrap 1/[0]: ") if e == "1": iboot = 0 if iboot == 1: e = input("Parametric bootstrap 1/[0]: ") if e == "1": ipar = 1 e = input("Plot bootstrap eigenvectors: 1/[0]: ") if e == "1": ivec = 1 if iplot == 1: if inittcdf == 0: ANIS['tcdf'] = 3 pmagplotlib.plot_init(ANIS['tcdf'], 5, 5) inittcdf = 1 bpars, hpars = pmagplotlib.plot_anis(ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, num_bootstraps) if verbose and plots == 0: pmagplotlib.draw_figs(ANIS) if ans == "c": print("Current Coordinate system is: ") if CS == -1: print(" Specimen") if CS == 0: print(" Geographic") if CS == 100: print(" Tilt corrected") key = input( " Enter desired coordinate system: [s]pecimen, [g]eographic, [t]ilt corrected ") if key == 's': CS = -1 if key == 'g': CS = 0 if key == 't': CS = 100 if CS not in orlist: if len(orlist) > 0: CS = orlist[0] else: CS = -1 if CS == -1: crd = 's' if CS == 0: crd = 'g' if CS == 100: crd = 't' print( "desired coordinate system not available, using available: ", crd) k -= 1 goon = 0 if ans == "": if isite == 1: goon = 0 else: print("Good bye ") sys.exit() if ans == 'd': if initcdf == 0: initcdf = 1 ANIS['vxcdf'], ANIS['vycdf'], ANIS['vzcdf'] = 4, 5, 6 pmagplotlib.plot_init(ANIS['vxcdf'], 5, 5) pmagplotlib.plot_init(ANIS['vycdf'], 5, 5) pmagplotlib.plot_init(ANIS['vzcdf'], 5, 5) Dir, comp = [], 1 print(""" Input: Vi D I to compare eigenvector Vi with direction D/I where Vi=1: principal Vi=2: major Vi=3: minor D= declination of comparison direction I= inclination of comparison direction example input: 1 15 20""") con = 1 while con == 1: try: vdi = input("Vi D I: ").split() vec = int(vdi[0])-1 Dir = [float(vdi[1]), float(vdi[2])] con = 0 except IndexError: print(" Incorrect entry, try again ") bpars, hpars = pmagplotlib.plot_anis(ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, num_bootstraps) Dir, comp = [], 0 if verbose and plots == 0: pmagplotlib.draw_figs(ANIS) if ans == 'g': con, cnt = 1, 0 while con == 1: try: print( " Input: input pole to great circle ( D I) to plot a great circle: ") di = input(" D I: ").split() PDir.append(float(di[0])) PDir.append(float(di[1])) con = 0 except: cnt += 1 if cnt < 10: print( " enter the dec and inc of the pole on one line ") else: print( "ummm - you are doing something wrong - i give up") sys.exit() if set_env.IS_WIN: # if windows, must re-draw everything pmagplotlib.plot_anis(ANIS, Ss, iboot, ihext, ivec, ipar, title, iplot, comp, vec, Dir, num_bootstraps) pmagplotlib.plot_circ(ANIS['data'], PDir, 90., 'g') pmagplotlib.plot_circ(ANIS['conf'], PDir, 90., 'g') if verbose and plots == 0: pmagplotlib.draw_figs(ANIS) if ans == "p": k -= 2 goon = 0 if ans == "q": k = plot goon = 0 if ans == "s": keepon = 1 site = input(" print site or part of site desired: ") while keepon == 1: try: k = sitelist.index(site) keepon = 0 except: tmplist = [] for qq in range(len(sitelist)): if site in sitelist[qq]: tmplist.append(sitelist[qq]) print(site, " not found, but this was: ") print(tmplist) site = input('Select one or try again\n ') k = sitelist.index(site) goon, ans = 0, "" if ans == "a": locs = pmag.makelist(Locs) site_name = "_" if isite: site_name = site if pmagplotlib.isServer: # use server plot naming convention title = "LO:_" + locs + '_SI:_' + site_name + '_SA:__SP:__CO:_' + crd else: # use more readable plot naming convention title = "{}_{}_{}".format(locs, site_name, crd) save(ANIS, fmt, title) goon = 0 else: if verbose: print('skipping plot - not enough data points') k += 1 # put rmag_results stuff here if len(ResRecs) > 0: # for rec in ResRecs: # con.add_item('specimens', rec, rec['specimen']) # sort records so that they are grouped by specimen ? #con.write_table_to_file('specimens', 'custom_specimens.txt') # ResOut,keylist=pmag.fillkeys(ResRecs) # just make a fresh one con.add_magic_table_from_data('specimens', ResRecs) # con.write_table_to_file('specimens', 'anisotropy_specimens.txt') # pmag.magic_write(outfile,ResOut,'rmag_results') if verbose: print(" Good bye ") def aniso_magic_nb(infile='specimens.txt', samp_file='', site_file='', verbose=1, ipar=0, ihext=1, ivec=0, isite=0, iloc=0, iboot=0, vec=0, Dir=[], PDir=[], crd="s", num_bootstraps=1000, dir_path=".", fignum=1): """ Makes plots of anisotropy eigenvectors, eigenvalues and confidence bounds All directions are on the lower hemisphere. Parameters __________ verbose : if True, print messages to output dir_path : input directory path Data Model 3.0 only formated files: infile : specimens formatted file with aniso_s data samp_file : samples formatted file with sample => site relationship site_file : sites formatted file with site => location relationship isite : if True plot by site, requires non-blank samp_file iloc : if True plot by location, requires non-blank samp_file, and site_file Dir : [Dec,Inc] list for comparison direction vec : eigenvector for comparison with Dir PDir : [Pole_dec, Pole_Inc] for pole to plane for comparison green dots are on the lower hemisphere, cyan are on the upper hemisphere fignum : matplotlib figure number crd : ['s','g','t'], coordinate system for plotting whereby: s : specimen coordinates, aniso_tile_correction = -1, or unspecified g : geographic coordinates, aniso_tile_correction = 0 t : tilt corrected coordinates, aniso_tile_correction = 100 confidence bounds options: ihext : if True - Hext ellipses iboot : if True - bootstrap ellipses ivec : if True - plot bootstrapped eigenvectors instead of ellipses ipar : if True - perform parametric bootstrap - requires non-blank aniso_s_sigma """ # initialize some variables version_num = pmag.get_version() hpars, bpars = [], [] # set aniso_tilt_correction value CS = -1 # specimen if crd == 'g': CS = 0 if crd == 't': CS = 100 # # # read in the data fnames = {'specimens': infile, 'samples': samp_file, 'sites': site_file} dir_path = os.path.realpath(dir_path) con = cb.Contribution(dir_path, read_tables=['specimens', 'samples', 'sites'], custom_filenames=fnames) con.propagate_location_to_specimens() spec_container = con.tables['specimens'] spec_df = spec_container.df # get only anisotropy records spec_df = spec_df.dropna(subset=['aniso_s']).copy() if 'aniso_tilt_correction' not in spec_df.columns: spec_df['aniso_tilt_correction'] = -1 # assume specimen coordinates if "aniso_s_n_measurements" not in spec_df.columns: spec_df["aniso_s_n_measurements"] = "6" if "aniso_s_sigma" not in spec_df.columns: spec_df["aniso_sigma"] = "0" orlist = spec_df['aniso_tilt_correction'].dropna().unique() if CS not in orlist: if len(orlist) > 0: CS = orlist[0] else: CS = -1 if CS == -1: crd = 's' if CS == 0: crd = 'g' if CS == 100: crd = 't' if verbose: print("desired coordinate system not available, using available: ", crd) cs_df = spec_df[spec_df['aniso_tilt_correction'] == CS] if isite: sites = cs_df['site'].unique() for site in list(sites): site_df = cs_df[cs_df.site == site] plot_aniso(fignum, site_df, PDir=PDir, ipar=ipar, ihext=ihext, ivec=ivec, iboot=iboot, vec=vec, num_bootstraps=num_bootstraps, title=site) fignum += 2 if iboot: fignum += 1 if len(Dir) > 0: fignum += 1 else: plot_aniso(fignum, cs_df, PDir=PDir, ipar=ipar, ihext=ihext, ivec=ivec, iboot=iboot, vec=vec, num_bootstraps=num_bootstraps) def plot_dmag(data="", title="", fignum=1, norm=1): """ plots demagenetization data versus step for all specimens in pandas dataframe datablock Parameters ______________ data : Pandas dataframe with MagIC data model 3 columns: fignum : figure number specimen : specimen name demag_key : one of these: ['treat_temp','treat_ac_field','treat_mw_energy'] selected using method_codes : ['LT_T-Z','LT-AF-Z','LT-M-Z'] respectively intensity : one of these: ['magn_moment', 'magn_volume', 'magn_mass'] quality : the quality column of the DataFrame title : title for plot norm : if True, normalize data to first step Output : matptlotlib plot """ plt.figure(num=fignum, figsize=(5, 5)) intlist = ['magn_moment', 'magn_volume', 'magn_mass'] # get which key we have IntMeths = [col_name for col_name in data.columns if col_name in intlist] int_key = IntMeths[0] data = data[data[int_key].notnull()] # fish out all data with this key units = "U" # this sets the units for plotting to undefined if 'treat_temp' in data.columns: units = "K" # kelvin dmag_key = 'treat_temp' elif 'treat_ac_field' in data.columns: units = "T" # tesla dmag_key = 'treat_ac_field' elif 'treat_mw_energy' in data.columns: units = "J" # joules dmag_key = 'treat_mw_energy' else: print('no data for plotting') return spcs = data.specimen.unique() # get a list of all specimens in DataFrame data # step through specimens to put on plot for spc in spcs: spec_data = data[data.specimen.str.contains(spc)] INTblock = [] for ind, rec in spec_data.iterrows(): INTblock.append([float(rec[dmag_key]), 0, 0, float(rec[int_key]), 1, rec['quality']]) if len(INTblock) > 2: pmagplotlib.plot_mag(fignum, INTblock, title, 0, units, norm) def eigs_s(infile="", dir_path='.'): """ Converts eigenparamters format data to s format Parameters ___________________ Input: file : input file name with eigenvalues (tau) and eigenvectors (V) with format: tau_1 V1_dec V1_inc tau_2 V2_dec V2_inc tau_3 V3_dec V3_inc Output the six tensor elements as a nested array [[x11,x22,x33,x12,x23,x13],....] """ file = os.path.join(dir_path, infile) eigs_data = np.loadtxt(file) Ss = [] for ind in range(eigs_data.shape[0]): tau, Vdirs = [], [] for k in range(0, 9, 3): tau.append(eigs_data[ind][k]) Vdirs.append([eigs_data[ind][k+1], eigs_data[ind][k+2]]) s = list(pmag.doeigs_s(tau, Vdirs)) Ss.append(s) return Ss def plot_gc(poles, color='g', fignum=1): """ plots a great circle on an equal area projection Parameters ____________________ Input fignum : number of matplotlib object poles : nested list of [Dec,Inc] pairs of poles color : color of lower hemisphere dots for great circle - must be in form: 'g','r','y','k',etc. upper hemisphere is always cyan """ for pole in poles: pmagplotlib.plot_circ(fignum, pole, 90., color) def plot_aniso(fignum, aniso_df, Dir=[], PDir=[], ipar=0, ihext=1, ivec=0, iboot=0, vec=0, num_bootstraps=1000, title=""): Ss, V1, V2, V3 = [], [], [], [] for ind, rec in aniso_df.iterrows(): s = [float(i.strip()) for i in rec['aniso_s'].split(':')] if s[0] <= 1.0: Ss.append(s) # protect against crap tau, Vdir = pmag.doseigs(s) V1.append([Vdir[0][0], Vdir[0][1]]) V2.append([Vdir[1][0], Vdir[1][1]]) V3.append([Vdir[2][0], Vdir[2][1]]) Ss = np.array(Ss) if Ss.shape[0] > 1: # plot the data plot_net(fignum) plt.title(title+':'+' V1=squares,V2=triangles,V3=circles') plot_di(di_block=V1, color='r', marker='s', markersize=20) plot_di(di_block=V2, color='b', marker='^', markersize=20) plot_di(di_block=V3, color='k', marker='o', markersize=20) # plot the confidence nf, sigma, avs = pmag.sbar(Ss) hpars = pmag.dohext(nf, sigma, avs) # get the Hext parameters if len(PDir) > 0: pmagplotlib.plot_circ(fignum+1, PDir, 90., 'g') plot_net(fignum+1) plt.title(title+':'+'Confidence Ellipses') plot_di(dec=hpars['v1_dec'], inc=hpars['v1_inc'], color='r', marker='s', markersize=30) plot_di(dec=hpars['v2_dec'], inc=hpars['v2_inc'], color='b', marker='^', markersize=30) plot_di(dec=hpars['v3_dec'], inc=hpars['v3_inc'], color='k', marker='o', markersize=30) if len(PDir) > 0: pmagplotlib.plot_circ(fignum+1, PDir, 90., 'g') # plot the confidence ellipses or vectors as desired if ihext: # plot the Hext ellipses ellpars = [hpars["v1_dec"], hpars["v1_inc"], hpars["e12"], hpars["v2_dec"], hpars["v2_inc"], hpars["e13"], hpars["v3_dec"], hpars["v3_inc"]] pmagplotlib.plot_ell(fignum+1, ellpars, 'r-,', 1, 1) ellpars = [hpars["v2_dec"], hpars["v2_inc"], hpars["e23"], hpars["v3_dec"], hpars["v3_inc"], hpars["e12"], hpars["v1_dec"], hpars["v1_inc"]] pmagplotlib.plot_ell(fignum+1, ellpars, 'b-,', 1, 1) ellpars = [hpars["v3_dec"], hpars["v3_inc"], hpars["e13"], hpars["v1_dec"], hpars["v1_inc"], hpars["e23"], hpars["v2_dec"], hpars["v2_inc"]] pmagplotlib.plot_ell(fignum+1, ellpars, 'k-,', 1, 1) if len(Dir) > 0: # plot the comparison direction components # put in dimap and plot as white symbol with axis color? plot_di(di_block=[Dir], color='green', marker='*', markersize=200) if iboot: # put on the bootstrapped confidence bounds Tmean, Vmean, Taus, BVs = pmag.s_boot( Ss, ipar, num_bootstraps) # get eigenvectors of mean tensor BVs_trans = np.array(BVs).transpose() if ivec: plot_di(dec=BVs_trans[0][0], inc=BVs_trans[1] [0], color='r', marker='.') plot_di(dec=BVs_trans[0][1], inc=BVs_trans[1] [1], color='b', marker='.') plot_di(dec=BVs_trans[0][2], inc=BVs_trans[1] [2], color='k', marker='.') # put in dimap and plot as white symbol with axis color? if len(Dir) > 0: # plot the comparison direction components plot_di(di_block=[Dir], color='green', marker='*', markersize=200) # do the eigenvalue cdfs Taus = np.array(Taus).transpose() colors = ['r', 'b', 'k'] styles = ['dotted', 'dashed', 'solid'] for t in range(3): # step through eigenvalues # get a sorted list of this eigenvalue ts = np.sort(Taus[t]) pmagplotlib.plot_cdf( fignum+2, ts, "", colors[t], "") # plot the CDF # minimum 95% conf bound plt.axvline(ts[int(0.025*len(ts))], color=colors[t], linestyle=styles[t]) # max 95% conf bound plt.axvline(ts[int(0.975*len(ts))], color=colors[t], linestyle=styles[t]) plt.xlabel('Eigenvalues') # do cartesian coordinates of selected eigenvectori [using vec] vs Dir if len(Dir) > 0: V = [row[vec-1] for row in BVs] X = pmag.dir2cart(V) comp_X = pmag.dir2cart(Dir) for i in range(3): xs = np.sort(np.array([row[i] for row in X])) pmagplotlib.plot_cdf( fignum+i+3, xs, "", colors[i], "") # plot the CDF # minimum 95% conf bound plt.axvline(xs[int(0.025*len(xs))], color=colors[vec-1], linestyle=styles[i]) # max 95% conf bound plt.axvline(xs[int(0.975*len(xs))], color=colors[vec-1], linestyle=styles[i]) # put on the comparison direction plt.axvline( comp_X[0][i], color='lightgreen', linewidth=3) else: bpars = pmag.sbootpars(Taus, BVs) ellpars = [hpars["v1_dec"], hpars["v1_inc"], bpars["v1_zeta"], bpars["v1_zeta_dec"], bpars["v1_zeta_inc"], bpars["v1_eta"], bpars["v1_eta_dec"], bpars["v1_eta_inc"]] pmagplotlib.plot_ell(fignum+1, ellpars, 'r-,', 1, 1) ellpars = [hpars["v2_dec"], hpars["v2_inc"], bpars["v2_zeta"], bpars["v2_zeta_dec"], bpars["v2_zeta_inc"], bpars["v2_eta"], bpars["v2_eta_dec"], bpars["v2_eta_inc"]] pmagplotlib.plot_ell(fignum+1, ellpars, 'b-,', 1, 1) ellpars = [hpars["v3_dec"], hpars["v3_inc"], bpars["v3_zeta"], bpars["v3_zeta_dec"], bpars["v3_zeta_inc"], bpars["v3_eta"], bpars["v3_eta_dec"], bpars["v3_eta_inc"]] pmagplotlib.plot_ell(fignum+1, ellpars, 'k-,', 1, 1) if len(Dir) > 0: # plot the comparison direction components plot_di(di_block=[Dir], color='green', marker='*', markersize=200) def aarm_magic(infile, dir_path=".", input_dir_path="", spec_file='specimens.txt', samp_file="samples.txt", data_model_num=3, coord='s'): """ Converts AARM data to best-fit tensor (6 elements plus sigma) Parameters ---------- infile : str input measurement file dir_path : str output directory, default "." input_dir_path : str input file directory IF different from dir_path, default "" spec_file : str input/output specimen file name, default "specimens.txt" samp_file : str input sample file name, default "samples.txt" data_model_num : number MagIC data model [2, 3], default 3 coord : str coordinate system specimen/geographic/tilt-corrected, ['s', 'g', 't'], default 's' Returns --------- Tuple : (True or False indicating if conversion was sucessful, output file name written) Info --------- Input for is a series of baseline, ARM pairs. The baseline should be the AF demagnetized state (3 axis demag is preferable) for the following ARM acquisition. The order of the measurements is: positions 1,2,3, 6,7,8, 11,12,13 (for 9 positions) positions 1,2,3,4, 6,7,8,9, 11,12,13,14 (for 12 positions) positions 1-15 (for 15 positions) """ data_model_num = int(float(data_model_num)) dir_path = os.path.realpath(dir_path) if not input_dir_path: input_dir_path = dir_path # get full file names meas_file = pmag.resolve_file_name(infile, input_dir_path) spec_file = pmag.resolve_file_name(spec_file, input_dir_path) samp_file = pmag.resolve_file_name(samp_file, input_dir_path) # get coordinate system coords = {'s': '-1', 'g': '0', 't': '100'} if coord not in coords.values(): coord = coords.get(str(coord), '-1') if data_model_num == 3: meas_data = [] meas_data3, file_type = pmag.magic_read(meas_file) if file_type != 'measurements': print(file_type, "This is not a valid MagIC 3.0. measurements file ") return False, "{} is not a valid MagIC 3.0. measurements file ".format(meas_file) # convert meas_data to 2.5 for rec in meas_data3: meas_map = map_magic.meas_magic3_2_magic2_map meas_data.append(map_magic.mapping(rec, meas_map)) spec_data = [] spec_data3, file_type = pmag.magic_read(spec_file) for rec in spec_data3: spec_map = map_magic.spec_magic3_2_magic2_map spec_data.append(map_magic.mapping(rec, spec_map)) else: # data model 2 rmag_anis = "rmag_anisotropy.txt" rmag_res = "rmag_results.txt" rmag_anis = pmag.resolve_file_name(rmag_anis, input_dir_path) rmag_res = pmag.resolve_file_name(rmag_res, input_dir_path) meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print(file_type, "This is not a valid MagIC 2.5 magic_measurements file ") return False, "{} is not a valid MagIC 2.5. measurements file ".format(meas_file) # fish out relevant data meas_data = pmag.get_dictitem( meas_data, 'magic_method_codes', 'LP-AN-ARM', 'has') if coord != '-1': # need to read in sample data if data_model_num == 3: samp_data3, file_type = pmag.magic_read(samp_file) if file_type != 'samples': print(file_type, "This is not a valid samples file ") print("Only specimen coordinates will be calculated") coord = '-1' else: # translate to 2 samp_data = [] samp_map = map_magic.samp_magic3_2_magic2_map for rec in samp_data3: samp_data.append(map_magic.mapping(rec, samp_map)) else: samp_data, file_type = pmag.magic_read(samp_file) if file_type != 'er_samples': print(file_type, "This is not a valid er_samples file ") print("Only specimen coordinates will be calculated") coord = '-1' # # sort the specimen names # ssort = [] for rec in meas_data: spec = rec["er_specimen_name"] if spec not in ssort: ssort.append(spec) if len(ssort) > 1: sids = sorted(ssort) else: sids = ssort # # work on each specimen # specimen = 0 RmagSpecRecs, RmagResRecs = [], [] SpecRecs, SpecRecs3 = [], [] while specimen < len(sids): s = sids[specimen] RmagSpecRec = {} RmagResRec = {} # get old specrec here if applicable if data_model_num == 3: if spec_data: try: RmagResRec = pmag.get_dictitem( spec_data, 'er_specimen_name', s, 'T')[0] RmagSpecRec = pmag.get_dictitem( spec_data, 'er_specimen_name', s, 'T')[0] except IndexError: pass data = [] method_codes = [] # # find the data from the meas_data file for this sample # data = pmag.get_dictitem(meas_data, 'er_specimen_name', s, 'T') # # find out the number of measurements (9, 12 or 15) # npos = int(len(data) / 2) if npos == 9: # # get dec, inc, int and convert to x,y,z # # B matrix made from design matrix for positions B, H, tmpH = pmag.designAARM(npos) X = [] for rec in data: Dir = [] Dir.append(float(rec["measurement_dec"])) Dir.append(float(rec["measurement_inc"])) Dir.append(float(rec["measurement_magn_moment"])) X.append(pmag.dir2cart(Dir)) # # subtract baseline and put in a work array # work = np.zeros((npos, 3), 'f') for i in range(npos): for j in range(3): work[i][j] = X[2 * i + 1][j] - X[2 * i][j] # # calculate tensor elements # first put ARM components in w vector # w = np.zeros((npos * 3), 'f') index = 0 for i in range(npos): for j in range(3): w[index] = work[i][j] index += 1 s = np.zeros((6), 'f') # initialize the s matrix for i in range(6): for j in range(len(w)): s[i] += B[i][j] * w[j] trace = s[0] + s[1] + s[2] # normalize by the trace for i in range(6): s[i] = s[i] / trace a = pmag.s2a(s) # ------------------------------------------------------------ # Calculating dels is different than in the Kappabridge # routine. Use trace normalized tensor (a) and the applied # unit field directions (tmpH) to generate model X,Y,Z # components. Then compare these with the measured values. # ------------------------------------------------------------ S = 0. comp = np.zeros((npos * 3), 'f') for i in range(npos): for j in range(3): index = i * 3 + j compare = a[j][0] * tmpH[i][0] + a[j][1] * \ tmpH[i][1] + a[j][2] * tmpH[i][2] comp[index] = compare for i in range(npos * 3): d = (w[i] / trace) - comp[i] # del values S += d * d nf = float(npos * 3 - 6) # number of degrees of freedom if S > 0: sigma = np.sqrt(S / nf) else: sigma = 0 RmagSpecRec["rmag_anisotropy_name"] = data[0]["er_specimen_name"] RmagSpecRec["er_location_name"] = data[0].get( "er_location_name", "") RmagSpecRec["er_specimen_name"] = data[0]["er_specimen_name"] if not "er_sample_name" in RmagSpecRec: RmagSpecRec["er_sample_name"] = data[0].get( "er_sample_name", "") RmagSpecRec["er_site_name"] = data[0].get("er_site_name", "") RmagSpecRec["magic_experiment_names"] = RmagSpecRec["rmag_anisotropy_name"] + ":AARM" RmagSpecRec["er_citation_names"] = "This study" RmagResRec["rmag_result_name"] = data[0]["er_specimen_name"] + ":AARM" RmagResRec["er_location_names"] = data[0].get( "er_location_name", "") RmagResRec["er_specimen_names"] = data[0]["er_specimen_name"] if not "er_sample_name" not in RmagResRec: RmagResRec["er_sample_names"] = data[0].get( "er_sample_name", "") RmagResRec["er_site_names"] = data[0].get("er_site_name", "") RmagResRec["magic_experiment_names"] = RmagSpecRec["rmag_anisotropy_name"] + ":AARM" RmagResRec["er_citation_names"] = "This study" if "magic_instrument_codes" in list(data[0].keys()): RmagSpecRec["magic_instrument_codes"] = data[0]["magic_instrument_codes"] else: RmagSpecRec["magic_instrument_codes"] = "" RmagSpecRec["anisotropy_type"] = "AARM" RmagSpecRec["anisotropy_description"] = "Hext statistics adapted to AARM" if coord != '-1': # need to rotate s # set orientation priorities SO_methods = [] for rec in samp_data: if "magic_method_codes" not in rec: rec['magic_method_codes'] = 'SO-NO' if "magic_method_codes" in rec: methlist = rec["magic_method_codes"] for meth in methlist.split(":"): if "SO" in meth and "SO-POM" not in meth.strip(): if meth.strip() not in SO_methods: SO_methods.append(meth.strip()) SO_priorities = pmag.set_priorities(SO_methods, 0) # continue here redo, p = 1, 0 if len(SO_methods) <= 1: az_type = SO_methods[0] orient = pmag.find_samp_rec( RmagSpecRec["er_sample_name"], samp_data, az_type) if orient["sample_azimuth"] != "": method_codes.append(az_type) redo = 0 while redo == 1: if p >= len(SO_priorities): print("no orientation data for ", s) orient["sample_azimuth"] = "" orient["sample_dip"] = "" method_codes.append("SO-NO") redo = 0 else: az_type = SO_methods[SO_methods.index( SO_priorities[p])] orient = pmag.find_samp_rec( RmagSpecRec["er_sample_name"], samp_data, az_type) if orient["sample_azimuth"] != "": method_codes.append(az_type) redo = 0 p += 1 az, pl = orient['sample_azimuth'], orient['sample_dip'] s = pmag.dosgeo(s, az, pl) # rotate to geographic coordinates if coord == '100': sample_bed_dir, sample_bed_dip = orient['sample_bed_dip_direction'], orient['sample_bed_dip'] # rotate to geographic coordinates s = pmag.dostilt(s, sample_bed_dir, sample_bed_dip) hpars = pmag.dohext(nf, sigma, s) # # prepare for output # RmagSpecRec["anisotropy_s1"] = '%8.6f' % (s[0]) RmagSpecRec["anisotropy_s2"] = '%8.6f' % (s[1]) RmagSpecRec["anisotropy_s3"] = '%8.6f' % (s[2]) RmagSpecRec["anisotropy_s4"] = '%8.6f' % (s[3]) RmagSpecRec["anisotropy_s5"] = '%8.6f' % (s[4]) RmagSpecRec["anisotropy_s6"] = '%8.6f' % (s[5]) RmagSpecRec["anisotropy_mean"] = '%8.3e' % (trace / 3) RmagSpecRec["anisotropy_sigma"] = '%8.6f' % (sigma) RmagSpecRec["anisotropy_unit"] = "Am^2" RmagSpecRec["anisotropy_n"] = '%i' % (npos) RmagSpecRec["anisotropy_tilt_correction"] = coord # used by thellier_gui - must be taken out for uploading RmagSpecRec["anisotropy_F"] = '%7.1f ' % (hpars["F"]) # used by thellier_gui - must be taken out for uploading RmagSpecRec["anisotropy_F_crit"] = hpars["F_crit"] RmagResRec["anisotropy_t1"] = '%8.6f ' % (hpars["t1"]) RmagResRec["anisotropy_t2"] = '%8.6f ' % (hpars["t2"]) RmagResRec["anisotropy_t3"] = '%8.6f ' % (hpars["t3"]) RmagResRec["anisotropy_v1_dec"] = '%7.1f ' % (hpars["v1_dec"]) RmagResRec["anisotropy_v2_dec"] = '%7.1f ' % (hpars["v2_dec"]) RmagResRec["anisotropy_v3_dec"] = '%7.1f ' % (hpars["v3_dec"]) RmagResRec["anisotropy_v1_inc"] = '%7.1f ' % (hpars["v1_inc"]) RmagResRec["anisotropy_v2_inc"] = '%7.1f ' % (hpars["v2_inc"]) RmagResRec["anisotropy_v3_inc"] = '%7.1f ' % (hpars["v3_inc"]) RmagResRec["anisotropy_ftest"] = '%7.1f ' % (hpars["F"]) RmagResRec["anisotropy_ftest12"] = '%7.1f ' % (hpars["F12"]) RmagResRec["anisotropy_ftest23"] = '%7.1f ' % (hpars["F23"]) RmagResRec["result_description"] = 'Critical F: ' + \ hpars["F_crit"] + ';Critical F12/F13: ' + hpars["F12_crit"] if hpars["e12"] > hpars["e13"]: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) if hpars["e23"] > hpars['e12']: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["tilt_correction"] = '-1' RmagResRec["anisotropy_type"] = 'AARM' RmagResRec["magic_method_codes"] = 'LP-AN-ARM:AE-H' RmagSpecRec["magic_method_codes"] = 'LP-AN-ARM:AE-H' RmagResRec["magic_software_packages"] = pmag.get_version() RmagSpecRec["magic_software_packages"] = pmag.get_version() specimen += 1 RmagSpecRecs.append(RmagSpecRec) RmagResRecs.append(RmagResRec) if data_model_num == 3: SpecRec = RmagResRec.copy() SpecRec.update(RmagSpecRec) SpecRecs.append(SpecRec) else: print('skipping specimen ', s, ' only 9 positions supported', '; this has ', npos) specimen += 1 if data_model_num == 3: # translate records for rec in SpecRecs: rec3 = map_magic.convert_aniso('magic3', rec) SpecRecs3.append(rec3) # write output to 3.0 specimens file pmag.magic_write(spec_file, SpecRecs3, 'specimens') print("specimen data stored in {}".format(spec_file)) return True, spec_file else: if rmag_anis == "": rmag_anis = "rmag_anisotropy.txt" pmag.magic_write(rmag_anis, RmagSpecRecs, 'rmag_anisotropy') print("specimen tensor elements stored in ", rmag_anis) if rmag_res == "": rmag_res = "rmag_results.txt" pmag.magic_write(rmag_res, RmagResRecs, 'rmag_results') print("specimen statistics and eigenparameters stored in ", rmag_res) return True, rmag_anis def atrm_magic(meas_file, dir_path=".", input_dir_path="", input_spec_file='specimens.txt', output_spec_file='specimens.txt', data_model_num=3): """ Converts ATRM data to best-fit tensor (6 elements plus sigma) Parameters ---------- meas_file : str input measurement file dir_path : str output directory, default "." input_dir_path : str input file directory IF different from dir_path, default "" input_spec_file : str input specimen file name, default "specimens.txt" output_spec_file : str output specimen file name, default "specimens.txt" data_model_num : number MagIC data model [2, 3], default 3 Returns --------- Tuple : (True or False indicating if conversion was sucessful, output file name written) """ # fix up file names meas_file = pmag.resolve_file_name(meas_file, dir_path) rmag_anis = os.path.join(dir_path, 'rmag_anisotropy.txt') rmag_res = os.path.join(dir_path, 'rmag_results.txt') input_spec_file = pmag.resolve_file_name(input_spec_file, dir_path) output_spec_file = pmag.resolve_file_name(output_spec_file, dir_path) # read in data if data_model_num == 3: meas_data = [] meas_data3, file_type = pmag.magic_read(meas_file) if file_type != 'measurements': print( "-E- {} is not a valid measurements file, {}".format(meas_file, file_type)) return False # convert meas_data to 2.5 for rec in meas_data3: meas_map = map_magic.meas_magic3_2_magic2_map meas_data.append(map_magic.mapping(rec, meas_map)) old_spec_recs, file_type = pmag.magic_read(input_spec_file) if file_type != 'specimens': print("-W- {} is not a valid specimens file ".format(input_spec_file)) old_spec_recs = [] spec_recs = [] for rec in old_spec_recs: spec_map = map_magic.spec_magic3_2_magic2_map spec_recs.append(map_magic.mapping(rec, spec_map)) else: meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'magic_measurements': print("-E- {} is is not a valid magic_measurements file ".format(file_type)) return False, "{} is not a valid magic_measurements file, {}".format(meas_file, file_type) meas_data = pmag.get_dictitem( meas_data, 'magic_method_codes', 'LP-AN-TRM', 'has') if not len(meas_data): print("-E- No measurement records found with code LP-AN-TRM") return False, "No measurement records found with code LP-AN-TRM" # # # get sorted list of unique specimen names ssort = [] for rec in meas_data: spec = rec["er_specimen_name"] if spec not in ssort: ssort.append(spec) sids = sorted(ssort) # # # work on each specimen # specimen, npos = 0, 6 RmagSpecRecs, RmagResRecs = [], [] SpecRecs, SpecRecs3 = [], [] while specimen < len(sids): nmeas = 0 s = sids[specimen] RmagSpecRec = {} RmagResRec = {} # get old specrec here if applicable if data_model_num == 3: if spec_recs: try: RmagResRec = pmag.get_dictitem( spec_recs, 'er_specimen_name', s, 'T')[0] RmagSpecRec = pmag.get_dictitem( spec_recs, 'er_specimen_name', s, 'T')[0] except IndexError: pass BX, X = [], [] method_codes = [] Spec0 = "" # # find the data from the meas_data file for this sample # and get dec, inc, int and convert to x,y,z # # fish out data for this specimen name data = pmag.get_dictitem(meas_data, 'er_specimen_name', s, 'T') if len(data) > 5: RmagSpecRec["rmag_anisotropy_name"] = data[0]["er_specimen_name"] RmagSpecRec["er_location_name"] = data[0].get( "er_location_name", "") RmagSpecRec["er_specimen_name"] = data[0]["er_specimen_name"] if not "er_sample_name" in RmagSpecRec: RmagSpecRec["er_sample_name"] = data[0].get( "er_sample_name", "") RmagSpecRec["er_site_name"] = data[0].get("er_site_name", "") RmagSpecRec["magic_experiment_names"] = RmagSpecRec["rmag_anisotropy_name"] + ":ATRM" RmagSpecRec["er_citation_names"] = "This study" RmagResRec["rmag_result_name"] = data[0]["er_specimen_name"] + ":ATRM" RmagResRec["er_location_names"] = data[0].get( "er_location_names", "") RmagResRec["er_specimen_names"] = data[0]["er_specimen_name"] if data_model_num == 2: RmagResRec["er_sample_names"] = data[0].get( "er_sample_name", "") RmagResRec["er_site_names"] = data[0].get("er_site_name", "") RmagResRec["magic_experiment_names"] = RmagSpecRec["rmag_anisotropy_name"] + ":ATRM" RmagResRec["er_citation_names"] = "This study" RmagSpecRec["anisotropy_type"] = "ATRM" if "magic_instrument_codes" in list(data[0].keys()): RmagSpecRec["magic_instrument_codes"] = data[0]["magic_instrument_codes"] else: RmagSpecRec["magic_instrument_codes"] = "" RmagSpecRec["anisotropy_description"] = "Hext statistics adapted to ATRM" for rec in data: meths = rec['magic_method_codes'].strip().split(':') Dir = [] Dir.append(float(rec["measurement_dec"])) Dir.append(float(rec["measurement_inc"])) Dir.append(float(rec["measurement_magn_moment"])) if "LT-T-Z" in meths: BX.append(pmag.dir2cart(Dir)) # append baseline steps elif "LT-T-I" in meths: X.append(pmag.dir2cart(Dir)) nmeas += 1 # if len(BX) == 1: for i in range(len(X) - 1): BX.append(BX[0]) # assume first 0 field step as baseline elif len(BX) == 0: # assume baseline is zero for i in range(len(X)): BX.append([0., 0., 0.]) # assume baseline of 0 elif len(BX) != len(X): # if BX isn't just one measurement or one in between every infield step, just assume it is zero print('something odd about the baselines - just assuming zero') for i in range(len(X)): BX.append([0., 0., 0.]) # assume baseline of 0 if nmeas < 6: # must have at least 6 measurements right now - print('skipping specimen ', s, ' too few measurements') specimen += 1 else: # B matrix made from design matrix for positions B, H, tmpH = pmag.designATRM(npos) # # subtract optional baseline and put in a work array # work = np.zeros((nmeas, 3), 'f') for i in range(nmeas): for j in range(3): # subtract baseline, if available work[i][j] = X[i][j] - BX[i][j] # # calculate tensor elements # first put ARM components in w vector # w = np.zeros((npos * 3), 'f') index = 0 for i in range(npos): for j in range(3): w[index] = work[i][j] index += 1 s = np.zeros((6), 'f') # initialize the s matrix for i in range(6): for j in range(len(w)): s[i] += B[i][j] * w[j] trace = s[0] + s[1] + s[2] # normalize by the trace for i in range(6): s[i] = s[i] / trace a = pmag.s2a(s) # ------------------------------------------------------------ # Calculating dels is different than in the Kappabridge # routine. Use trace normalized tensor (a) and the applied # unit field directions (tmpH) to generate model X,Y,Z # components. Then compare these with the measured values. # ------------------------------------------------------------ S = 0. comp = np.zeros((npos * 3), 'f') for i in range(npos): for j in range(3): index = i * 3 + j compare = a[j][0] * tmpH[i][0] + a[j][1] * \ tmpH[i][1] + a[j][2] * tmpH[i][2] comp[index] = compare for i in range(npos * 3): d = (w[i] / trace) - comp[i] # del values S += d * d nf = float(npos * 3. - 6.) # number of degrees of freedom if S > 0: sigma = np.sqrt(S / nf) else: sigma = 0 hpars = pmag.dohext(nf, sigma, s) # # prepare for output # RmagSpecRec["anisotropy_s1"] = '%8.6f' % (s[0]) RmagSpecRec["anisotropy_s2"] = '%8.6f' % (s[1]) RmagSpecRec["anisotropy_s3"] = '%8.6f' % (s[2]) RmagSpecRec["anisotropy_s4"] = '%8.6f' % (s[3]) RmagSpecRec["anisotropy_s5"] = '%8.6f' % (s[4]) RmagSpecRec["anisotropy_s6"] = '%8.6f' % (s[5]) RmagSpecRec["anisotropy_mean"] = '%8.3e' % (trace / 3) RmagSpecRec["anisotropy_sigma"] = '%8.6f' % (sigma) RmagSpecRec["anisotropy_unit"] = "Am^2" RmagSpecRec["anisotropy_n"] = '%i' % (npos) RmagSpecRec["anisotropy_tilt_correction"] = '-1' # used by thellier_gui - must be taken out for uploading RmagSpecRec["anisotropy_F"] = '%7.1f ' % (hpars["F"]) # used by thellier_gui - must be taken out for uploading RmagSpecRec["anisotropy_F_crit"] = hpars["F_crit"] RmagResRec["anisotropy_t1"] = '%8.6f ' % (hpars["t1"]) RmagResRec["anisotropy_t2"] = '%8.6f ' % (hpars["t2"]) RmagResRec["anisotropy_t3"] = '%8.6f ' % (hpars["t3"]) RmagResRec["anisotropy_v1_dec"] = '%7.1f ' % (hpars["v1_dec"]) RmagResRec["anisotropy_v2_dec"] = '%7.1f ' % (hpars["v2_dec"]) RmagResRec["anisotropy_v3_dec"] = '%7.1f ' % (hpars["v3_dec"]) RmagResRec["anisotropy_v1_inc"] = '%7.1f ' % (hpars["v1_inc"]) RmagResRec["anisotropy_v2_inc"] = '%7.1f ' % (hpars["v2_inc"]) RmagResRec["anisotropy_v3_inc"] = '%7.1f ' % (hpars["v3_inc"]) RmagResRec["anisotropy_ftest"] = '%7.1f ' % (hpars["F"]) RmagResRec["anisotropy_ftest12"] = '%7.1f ' % (hpars["F12"]) RmagResRec["anisotropy_ftest23"] = '%7.1f ' % (hpars["F23"]) RmagResRec["result_description"] = 'Critical F: ' + \ hpars["F_crit"] + ';Critical F12/F13: ' + hpars["F12_crit"] if hpars["e12"] > hpars["e13"]: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v1_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v1_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v1_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v1_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v1_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v1_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) if hpars["e23"] > hpars['e12']: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v1_inc']) else: RmagResRec["anisotropy_v2_zeta_semi_angle"] = '%7.1f ' % ( hpars['e12']) RmagResRec["anisotropy_v2_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v2_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v3_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v3_eta_dec"] = '%7.1f ' % ( hpars['v2_dec']) RmagResRec["anisotropy_v3_eta_inc"] = '%7.1f ' % ( hpars['v2_inc']) RmagResRec["anisotropy_v3_zeta_semi_angle"] = '%7.1f ' % ( hpars['e13']) RmagResRec["anisotropy_v3_zeta_dec"] = '%7.1f ' % ( hpars['v1_dec']) RmagResRec["anisotropy_v3_zeta_inc"] = '%7.1f ' % ( hpars['v1_inc']) RmagResRec["anisotropy_v2_eta_semi_angle"] = '%7.1f ' % ( hpars['e23']) RmagResRec["anisotropy_v2_eta_dec"] = '%7.1f ' % ( hpars['v3_dec']) RmagResRec["anisotropy_v2_eta_inc"] = '%7.1f ' % ( hpars['v3_inc']) RmagResRec["tilt_correction"] = '-1' RmagResRec["anisotropy_type"] = 'ATRM' RmagResRec["magic_method_codes"] = 'LP-AN-TRM:AE-H' RmagSpecRec["magic_method_codes"] = 'LP-AN-TRM:AE-H' RmagResRec["magic_software_packages"] = pmag.get_version() RmagSpecRec["magic_software_packages"] = pmag.get_version() RmagSpecRecs.append(RmagSpecRec) RmagResRecs.append(RmagResRec) specimen += 1 if data_model_num == 3: SpecRec = RmagResRec.copy() SpecRec.update(RmagSpecRec) SpecRecs.append(SpecRec) # finished iterating through specimens, # now we need to write out the data to files if data_model_num == 3: # translate records for rec in SpecRecs: rec3 = map_magic.convert_aniso('magic3', rec) SpecRecs3.append(rec3) # write output to 3.0 specimens file pmag.magic_write(output_spec_file, SpecRecs3, 'specimens') print("specimen data stored in {}".format(output_spec_file)) return True, output_spec_file else: # write output to 2.5 rmag_ files pmag.magic_write(rmag_anis, RmagSpecRecs, 'rmag_anisotropy') print("specimen tensor elements stored in ", rmag_anis) pmag.magic_write(rmag_res, RmagResRecs, 'rmag_results') print("specimen statistics and eigenparameters stored in ", rmag_res) return True, rmag_anis def zeq_magic(meas_file='measurements.txt', input_dir_path='./', angle=0): """ zeq_magic makes zijderveld and equal area plots for magic formatted measurements files Parameters ---------- meas_file : str input measurement file input_dir_path : str input directory of meas_file, default "." angle : float angle of X direction with respect to specimen X """ # read in MagIC foramatted data file_path = pmag.resolve_file_name(meas_file, input_dir_path) # read in magic formatted data meas_df = pd.read_csv(file_path, sep='\t', header=1) meas_df['blank'] = "" # this is a dummy variable expected by plotZED specimens = meas_df.specimen.unique() # list of specimen names if len(specimens) == 0: print('there are no data for plotting') return cnt = 1 for s in specimens: # we can make the figure dictionary that pmagplotlib likes: ZED = {'eqarea': cnt, 'zijd': cnt+1, 'demag': cnt+2} # make datablock cnt += 3 spec_df = meas_df[meas_df.specimen == s] spec_df_nrm = spec_df[spec_df.method_codes.str.contains( 'LT-NO')] # get the NRM data spec_df_th = spec_df[spec_df.method_codes.str.contains( 'LT-T-Z')] # zero field thermal demag steps spec_df_th = spec_df_th[spec_df.method_codes.str.contains( 'LT-PTRM') == False] # get rid of some pTRM steps spec_df_af = spec_df[spec_df.method_codes.str.contains('LT-AF-Z')] if len(spec_df_th.index) > 1: # this is a thermal run spec_df = pd.concat([spec_df_nrm, spec_df_th]) units = 'K' # units are kelvin datablock = spec_df[['treat_temp', 'dir_dec', 'dir_inc', 'magn_moment', 'blank', 'quality']].values.tolist() pmagplotlib.plot_zed(ZED, datablock, angle, s, units) if len(spec_df_af.index) > 1: # this is an af run spec_df = pd.concat([spec_df_nrm, spec_df_af]) units = 'T' # these are AF data datablock = spec_df[['treat_ac_field', 'dir_dec', 'dir_inc', 'magn_moment', 'blank', 'quality']].values.tolist() pmagplotlib.plot_zed(ZED, datablock, angle, s, units) def thellier_magic(meas_file="measurements.txt", dir_path=".", input_dir_path="", spec="", n_specs="all", save_plots=True, fmt="svg"): """ thellier_magic plots arai and other useful plots for Thellier-type experimental data Parameters ---------- meas_file : str input measurement file, default "measurements.txt" dir_path : str output directory, default "." Note: if using Windows, all figures will be saved to working directly *not* dir_path input_dir_path : str input file directory IF different from dir_path, default "" spec : str default "", specimen to plot n_specs : int default "all", otherwise number of specimens to plot save_plots : bool, default True if True, non-interactively save plots fmt : str format of saved figures (default is 'svg') """ # get proper paths if not input_dir_path: input_dir_path = dir_path input_dir_path = os.path.realpath(input_dir_path) dir_path = os.path.realpath(dir_path) file_path = pmag.resolve_file_name(meas_file, input_dir_path) # read in magic formatted data meas_df = pd.read_csv(file_path, sep='\t', header=1) int_key = cb.get_intensity_col(meas_df) # list for saved figs saved = [] # get all the records with measurement data meas_data = meas_df[meas_df[int_key].notnull()] thel_data = meas_data[meas_data['method_codes'].str.contains( 'LP-PI-TRM')] # get all the Thellier data specimens = meas_data.specimen.unique() # list of specimen names if len(specimens) == 0: print('there are no data for plotting') return False, [] if spec: if spec not in specimens: print('could not find specimen {}'.format(spec)) return False, [] specimens = [spec] elif n_specs != "all": try: specimens = specimens[:n_specs] except Exception as ex: pass cnt = 1 # set the figure counter to 1 for this_specimen in specimens: # step through the specimens list if pmagplotlib.verbose: print(this_specimen) # make the figure dictionary that pmagplotlib likes: AZD = {'arai': 1, 'zijd': 2, 'eqarea': 3, 'deremag': 4} # make datablock #if save_plots: # AZD = {'arai': 1, 'zijd': 2, 'eqarea': 3, 'deremag': 4} # make datablock #else: # AZD = {'arai': cnt, 'zijd': cnt+1, 'eqarea': cnt + # 2, 'deremag': cnt+3} # make datablock #cnt += 4 # increment the figure counter spec_df = thel_data[thel_data.specimen == this_specimen] # get data for this specimen # get the data block for Arai plot if len(spec_df)>0: if not save_plots: for key, val in AZD.items(): pmagplotlib.plot_init(val, 5, 5) araiblock, field = pmag.sortarai(spec_df, this_specimen, 0, version=3) # get the datablock for Zijderveld plot zijdblock, units = pmag.find_dmag_rec( this_specimen, spec_df, version=3) if not len(units): unit_string = "" else: unit_string = units[-1] zed = pmagplotlib.plot_arai_zij( AZD, araiblock, zijdblock, this_specimen, unit_string) # make the plots if not save_plots: pmagplotlib.draw_figs(zed) ans = input( "S[a]ve plots, [q]uit, <return> to continue\n ") if ans == 'q': return True, [] if ans == 'a': files = {key : this_specimen + "_" + key + "." + fmt for (key, value) in zed.items()} if not set_env.IS_WIN: files = {key: os.path.join(dir_path, value) for (key, value) in files.items()} incl_directory = True saved.append(pmagplotlib.save_plots(zed, files, incl_directory=incl_directory)) if save_plots: files = {key : this_specimen + "_" + key + "." + fmt for (key, value) in zed.items()} incl_directory = False if not pmagplotlib.isServer: if not set_env.IS_WIN: files = {key: os.path.join(dir_path, value) for (key, value) in files.items()} incl_directory = True else: # fix plot titles, formatting, and file names for server for key, value in files.copy().items(): files[key] = "SP:_{}_TY:_{}_.{}".format(this_specimen, key, fmt) black = '#000000' purple = '#800080' titles = {} titles['deremag'] = 'DeReMag Plot' titles['zijd'] = 'Zijderveld Plot' titles['arai'] = 'Arai Plot' titles['TRM'] = 'TRM Acquisition data' titles['eqarea'] = 'Equal Area Plot' zed = pmagplotlib.add_borders( zed, titles, black, purple) saved.append(pmagplotlib.save_plots(zed, files, incl_directory=incl_directory)) else: print ('no data for ',this_specimen) print ('skipping') return True, saved def hysteresis_magic(output_dir_path=".", input_dir_path="", spec_file="specimens.txt", meas_file="measurements.txt", fmt="svg", save_plots=True, make_plots=True, pltspec=""): """ Calculate hysteresis parameters and plot hysteresis data. Plotting may be called interactively with save_plots==False, or be suppressed entirely with make_plots==False. Parameters ---------- output_dir_path : str, default "." Note: if using Windows, all figures will be saved to working directly *not* dir_path input_dir_path : str path for intput file if different from output_dir_path (default is same) spec_file : str, default "specimens.txt" output file to save hysteresis data meas_file : str, default "measurements.txt" input measurement file fmt : str, default "svg" format for figures, [svg, jpg, pdf, png] save_plots : bool, default True if True, non-interactively save plots make_plots : bool, default True if False, skip making plots and just save hysteresis data pltspec : str, default "" specimen name to plot, otherwise will plot all specimens Returns --------- Tuple : (True or False indicating if conversion was sucessful, output file names written) """ # put plots in output_dir_path, unless isServer incl_directory = True if pmagplotlib.isServer or set_env.IS_WIN: incl_directory = False # figure out directory/file paths if not input_dir_path: input_dir_path = output_dir_path input_dir_path = os.path.realpath(input_dir_path) output_dir_path = os.path.realpath(output_dir_path) spec_file = pmag.resolve_file_name(spec_file, input_dir_path) meas_file = pmag.resolve_file_name(meas_file, input_dir_path) # format and initialize variables verbose = pmagplotlib.verbose version_num = pmag.get_version() if not make_plots: irm_init, imag_init = -1, -1 if save_plots: verbose = False if pltspec: pass SpecRecs = [] # # meas_data, file_type = pmag.magic_read(meas_file) if file_type != 'measurements': print('bad file', meas_file) return False, [] # # initialize some variables # define figure numbers for hyst,deltaM,DdeltaM curves HystRecs, RemRecs = [], [] HDD = {} if verbose and make_plots: print("Plots may be on top of each other - use mouse to place ") if make_plots: HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'] = 1, 2, 3 if make_plots and (not save_plots): pmagplotlib.plot_init(HDD['DdeltaM'], 5, 5) pmagplotlib.plot_init(HDD['deltaM'], 5, 5) pmagplotlib.plot_init(HDD['hyst'], 5, 5) imag_init = 0 irm_init = 0 else: HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'], HDD['irm'], HDD['imag'] = 0, 0, 0, 0, 0 # if spec_file: prior_data, file_type = pmag.magic_read(spec_file) # # get list of unique experiment names and specimen names # experiment_names, sids = [], [] hys_data = pmag.get_dictitem(meas_data, 'method_codes', 'LP-HYS', 'has') dcd_data = pmag.get_dictitem( meas_data, 'method_codes', 'LP-IRM-DCD', 'has') imag_data = pmag.get_dictitem(meas_data, 'method_codes', 'LP-IMAG', 'has') for rec in hys_data: if rec['experiment'] not in experiment_names: experiment_names.append(rec['experiment']) if rec['specimen'] not in sids: sids.append(rec['specimen']) # k = 0 if pltspec: k = sids.index(pltspec) while k < len(sids): specimen = sids[k] if pltspec: if specimen != pltspec: k += 1 continue # initialize a new specimen hysteresis record HystRec = {'specimen': specimen, 'experiment': ""} if verbose and make_plots: print(specimen, k+1, 'out of ', len(sids)) # # # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data B, M, Bdcd, Mdcd = [], [], [], [] Bimag, Mimag = [], [] # Bimag,Mimag for initial magnetization curves # fish out all the LP-HYS data for this specimen spec_data = pmag.get_dictitem(hys_data, 'specimen', specimen, 'T') if len(spec_data) > 0: meths = spec_data[0]['method_codes'].split(':') e = spec_data[0]['experiment'] HystRec['experiment'] = spec_data[0]['experiment'] for rec in spec_data: B.append(float(rec['meas_field_dc'])) M.append(float(rec['magn_moment'])) # fish out all the data for this specimen spec_data = pmag.get_dictitem(dcd_data, 'specimen', specimen, 'T') if len(spec_data) > 0: HystRec['experiment'] = HystRec['experiment'] + \ ':'+spec_data[0]['experiment'] irm_exp = spec_data[0]['experiment'] for rec in spec_data: Bdcd.append(float(rec['treat_dc_field'])) Mdcd.append(float(rec['magn_moment'])) # fish out all the data for this specimen spec_data = pmag.get_dictitem(imag_data, 'specimen', specimen, 'T') if len(spec_data) > 0: imag_exp = spec_data[0]['experiment'] for rec in spec_data: Bimag.append(float(rec['meas_field_dc'])) Mimag.append(float(rec['magn_moment'])) # # now plot the hysteresis curve # if len(B) > 0: hmeths = [] for meth in meths: hmeths.append(meth) hpars = pmagplotlib.plot_hdd(HDD, B, M, e) if make_plots: if not set_env.IS_WIN: pmagplotlib.draw_figs(HDD) # if make_plots: pmagplotlib.plot_hpars(HDD, hpars, 'bs') HystRec['hyst_mr_moment'] = hpars['hysteresis_mr_moment'] HystRec['hyst_ms_moment'] = hpars['hysteresis_ms_moment'] HystRec['hyst_bc'] = hpars['hysteresis_bc'] HystRec['hyst_bcr'] = hpars['hysteresis_bcr'] HystRec['hyst_xhf'] = hpars['hysteresis_xhf'] HystRec['experiments'] = e HystRec['software_packages'] = version_num if hpars["magic_method_codes"] not in hmeths: hmeths.append(hpars["magic_method_codes"]) methods = "" for meth in hmeths: methods = methods+meth.strip()+":" HystRec["method_codes"] = methods[:-1] HystRec["citations"] = "This study" # if len(Bdcd) > 0: rmeths = [] for meth in meths: rmeths.append(meth) if verbose and make_plots: print('plotting IRM') if irm_init == 0: HDD['irm'] = 5 if 'imag' in HDD else 4 if make_plots and (not save_plots): pmagplotlib.plot_init(HDD['irm'], 5, 5) irm_init = 1 rpars = pmagplotlib.plot_irm(HDD['irm'], Bdcd, Mdcd, irm_exp) HystRec['rem_mr_moment'] = rpars['remanence_mr_moment'] HystRec['rem_bcr'] = rpars['remanence_bcr'] HystRec['experiments'] = specimen+':'+irm_exp if rpars["magic_method_codes"] not in meths: meths.append(rpars["magic_method_codes"]) methods = "" for meth in rmeths: methods = methods+meth.strip()+":" HystRec["method_codes"] = HystRec['method_codes']+':'+methods[:-1] HystRec["citations"] = "This study" else: if irm_init: pmagplotlib.clearFIG(HDD['irm']) if len(Bimag) > 0: if verbose and make_plots: print('plotting initial magnetization curve') # first normalize by Ms Mnorm = [] for m in Mimag: Mnorm.append(m / float(hpars['hysteresis_ms_moment'])) if imag_init == 0: HDD['imag'] = 4 if make_plots and (not save_plots): pmagplotlib.plot_init(HDD['imag'], 5, 5) imag_init = 1 pmagplotlib.plot_imag(HDD['imag'], Bimag, Mnorm, imag_exp) else: if imag_init: pmagplotlib.clearFIG(HDD['imag']) if len(list(HystRec.keys())) > 0: HystRecs.append(HystRec) # files = {} if save_plots and make_plots: if pltspec: s = pltspec else: s = specimen files = {} for key in list(HDD.keys()): if incl_directory: files[key] = os.path.join(output_dir_path, s+'_'+key+'.'+fmt) else: files[key] = s+'_'+key+'.'+fmt if make_plots and save_plots: pmagplotlib.save_plots(HDD, files, incl_directory=incl_directory) #if pltspec: # return True, [] if make_plots and (not save_plots): pmagplotlib.draw_figs(HDD) ans = input( "S[a]ve plots, [s]pecimen name, [q]uit, <return> to continue\n ") if ans == "a": files = {} for key in list(HDD.keys()): if incl_directory: files[key] = os.path.join(output_dir_path, specimen+'_'+key+'.'+fmt) else: files[key] = specimen+'_'+key+'.'+fmt pmagplotlib.save_plots(HDD, files, incl_directory=incl_directory) if ans == '': k += 1 if ans == "p": del HystRecs[-1] k -= 1 if ans == 'q': print("Good bye") return True, [] if ans == 's': keepon = 1 specimen = 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 = input('Select one or try again\n ') k = sids.index(specimen) else: k += 1 if len(B) == 0 and len(Bdcd) == 0: if verbose: print('skipping this one - no hysteresis data') k += 1 if k < len(sids): # must re-init figs for Windows to keep size if make_plots and set_env.IS_WIN: if not save_plots: pmagplotlib.plot_init(HDD['DdeltaM'], 5, 5) pmagplotlib.plot_init(HDD['deltaM'], 5, 5) pmagplotlib.plot_init(HDD['hyst'], 5, 5) if len(Bimag) > 0: HDD['imag'] = 4 if not save_plots: pmagplotlib.plot_init(HDD['imag'], 5, 5) if len(Bdcd) > 0: HDD['irm'] = 5 if 'imag' in HDD else 4 if not save_plots: pmagplotlib.plot_init(HDD['irm'], 5, 5) elif not make_plots and set_env.IS_WIN: HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'], HDD['irm'], HDD['imag'] = 0, 0, 0, 0, 0 if len(HystRecs) > 0: # go through prior_data, clean out prior results and save combined file as spec_file SpecRecs, keys = [], list(HystRecs[0].keys()) if len(prior_data) > 0: prior_keys = list(prior_data[0].keys()) else: prior_keys = [] for rec in prior_data: for key in keys: if key not in list(rec.keys()): rec[key] = "" if 'LP-HYS' not in rec['method_codes']: SpecRecs.append(rec) for rec in HystRecs: for key in prior_keys: if key not in list(rec.keys()): rec[key] = "" prior = pmag.get_dictitem( prior_data, 'specimen', rec['specimen'], 'T') if len(prior) > 0 and 'sample' in list(prior[0].keys()): # pull sample name from prior specimens table rec['sample'] = prior[0]['sample'] SpecRecs.append(rec) # drop unnecessary/duplicate rows #dir_path = os.path.split(spec_file)[0] con = cb.Contribution(input_dir_path, read_tables=[]) con.add_magic_table_from_data('specimens', SpecRecs) con.tables['specimens'].drop_duplicate_rows( ignore_cols=['specimen', 'sample', 'citations', 'software_packages']) con.tables['specimens'].df = con.tables['specimens'].df.drop_duplicates() spec_file = os.path.join(output_dir_path, os.path.split(spec_file)[1]) con.write_table_to_file('specimens', custom_name=spec_file) if verbose: print("hysteresis parameters saved in ", spec_file) return True, [spec_file] def sites_extract(site_file='sites.txt', directions_file='directions.xls', intensity_file='intensity.xls', info_file='site_info.xls', output_dir_path='./', input_dir_path='', latex=False): """ Extracts directional and/or intensity data from a MagIC 3.0 format sites.txt file. Default output format is an Excel file. Optional latex format longtable file which can be uploaded to Overleaf or typeset with latex on your own computer. Parameters ___________ site_file : str input file name directions_file : str output file name for directional data intensity_file : str output file name for intensity data site_info : str output file name for site information (lat, lon, location, age....) output_dir_path : str path for output files input_dir_path : str path for intput file if different from output_dir_path (default is same) latex : boolean if True, output file should be latex formatted table with a .tex ending Return : [True,False], error type : True if successful Effects : writes Excel or LaTeX formatted tables for use in publications """ # initialize outfile names if not input_dir_path: input_dir_path = output_dir_path try: fname = pmag.resolve_file_name(site_file, input_dir_path) except IOError: print("bad site file name") return False, "bad site file name" sites_df = pd.read_csv(fname, sep='\t', header=1) dir_df = map_magic.convert_site_dm3_table_directions(sites_df) dir_file = pmag.resolve_file_name(directions_file, output_dir_path) if len(dir_df): if latex: if dir_file.endswith('.xls'): dir_file = dir_file[:-4] + ".tex" directions_out = open(dir_file, 'w+', errors="backslashreplace") directions_out.write('\documentclass{article}\n') directions_out.write('\\usepackage{booktabs}\n') directions_out.write('\\usepackage{longtable}\n') directions_out.write('\\begin{document}') directions_out.write(dir_df.to_latex( index=False, longtable=True, multicolumn=False)) directions_out.write('\end{document}\n') directions_out.close() else: dir_df.to_excel(dir_file, index=False) else: print("No directional data for ouput.") dir_file = None intensity_file = pmag.resolve_file_name(intensity_file, output_dir_path) int_df = map_magic.convert_site_dm3_table_intensity(sites_df) if len(int_df): if latex: if intensity_file.endswith('.xls'): intensity_file = intensity_file[:-4] + ".tex" intensities_out = open(intensity_file, 'w+', errors="backslashreplace") intensities_out.write('\documentclass{article}\n') intensities_out.write('\\usepackage{booktabs}\n') intensities_out.write('\\usepackage{longtable}\n') intensities_out.write('\\begin{document}') intensities_out.write(int_df.to_latex( index=False, longtable=True, multicolumn=False)) intensities_out.write('\end{document}\n') intensities_out.close() else: int_df.to_excel(intensity_file, index=False) else: print("No intensity data for ouput.") intensity_file = None # site info nfo_df = sites_df.dropna(subset=['lat', 'lon']) # delete blank locations if len(nfo_df) > 0: SiteCols = ["Site", "Location", "Lat. (N)", "Long. (E)"] info_file = pmag.resolve_file_name(info_file, output_dir_path) age_cols = ['age', 'age_sigma', 'age_unit'] for col in age_cols: if col not in nfo_df: nfo_df[col] = None test_age = nfo_df.dropna(subset=['age', 'age_sigma', 'age_unit']) if len(test_age) > 0: SiteCols.append("Age ") SiteCols.append("Age sigma") SiteCols.append("Units") nfo_df = nfo_df[['site', 'location', 'lat', 'lon', 'age', 'age_sigma', 'age_unit']] else: nfo_df = nfo_df[['site', 'location', 'lat', 'lon']] nfo_df.drop_duplicates(inplace=True) nfo_df.columns = SiteCols nfo_df.fillna(value='', inplace=True) if latex: if info_file.endswith('.xls'): info_file = info_file[:-4] + ".tex" info_out = open(info_file, 'w+', errors="backslashreplace") info_out.write('\documentclass{article}\n') info_out.write('\\usepackage{booktabs}\n') info_out.write('\\usepackage{longtable}\n') info_out.write('\\begin{document}') info_out.write(nfo_df.to_latex( index=False, longtable=True, multicolumn=False)) info_out.write('\end{document}\n') info_out.close() else: nfo_df.to_excel(info_file, index=False) else: print("No location information for ouput.") info_file = None return True, [fname for fname in [info_file, intensity_file, dir_file] if fname] def specimens_extract(spec_file='specimens.txt', output_file='specimens.xls', landscape=False, longtable=False, output_dir_path='./', input_dir_path='', latex=False): """ Extracts specimen results from a MagIC 3.0 format specimens.txt file. Default output format is an Excel file. typeset with latex on your own computer. Parameters ___________ spec_file : str input file name input_dir_path : str path for intput file if different from output_dir_path (default is same) latex : boolean if True, output file should be latex formatted table with a .tex ending longtable : boolean if True output latex longtable landscape : boolean if True output latex landscape table Return : [True,False], data table error type : True if successful Effects : writes xls or latex formatted tables for use in publications """ if not input_dir_path: input_dir_path = output_dir_path try: fname = pmag.resolve_file_name(spec_file, input_dir_path) except IOError: print("bad specimen file name") return False, "bad specimen file name" spec_df = pd.read_csv(fname, sep='\t', header=1) spec_df.dropna('columns', how='all', inplace=True) if 'int_abs' in spec_df.columns: spec_df.dropna(subset=['int_abs'], inplace=True) if len(spec_df) > 0: table_df = map_magic.convert_specimen_dm3_table(spec_df) out_file = pmag.resolve_file_name(output_file, output_dir_path) if latex: if out_file.endswith('.xls'): out_file = out_file.rsplit('.')[0] + ".tex" info_out = open(out_file, 'w+', errors="backslashreplace") info_out.write('\documentclass{article}\n') info_out.write('\\usepackage{booktabs}\n') if landscape: info_out.write('\\usepackage{lscape}') if longtable: info_out.write('\\usepackage{longtable}\n') info_out.write('\\begin{document}\n') if landscape: info_out.write('\\begin{landscape}\n') info_out.write(table_df.to_latex(index=False, longtable=longtable, escape=True, multicolumn=False)) if landscape: info_out.write('\end{landscape}\n') info_out.write('\end{document}\n') info_out.close() else: table_df.to_excel(out_file, index=False) else: print("No specimen data for ouput.") return True, [out_file] def criteria_extract(crit_file='criteria.txt', output_file='criteria.xls', output_dir_path='./', input_dir_path='', latex=False): """ Extracts criteria from a MagIC 3.0 format criteria.txt file. Default output format is an Excel file. typeset with latex on your own computer. Parameters ___________ crit_file : str input file name input_dir_path : str path for intput file if different from output_dir_path (default is same) latex : boolean if True, output file should be latex formatted table with a .tex ending Return : [True,False], data table error type : True if successful Effects : writes xls or latex formatted tables for use in publications """ if not input_dir_path: input_dir_path = output_dir_path try: fname = pmag.resolve_file_name(crit_file, input_dir_path) except IOError: print("bad criteria file name") return False, "bad site file name" crit_df = pd.read_csv(fname, sep='\t', header=1) if len(crit_df) > 0: out_file = pmag.resolve_file_name(output_file, output_dir_path) s = crit_df['table_column'].str.split(pat='.', expand=True) crit_df['table'] = s[0] crit_df['column'] = s[1] crit_df = crit_df[['table', 'column', 'criterion_value', 'criterion_operation']] crit_df.columns = ['Table', 'Statistic', 'Threshold', 'Operation'] if latex: if out_file.endswith('.xls'): out_file = out_file.rsplit('.')[0] + ".tex" crit_df.loc[crit_df['Operation'].str.contains( '<'), 'operation'] = 'maximum' crit_df.loc[crit_df['Operation'].str.contains( '>'), 'operation'] = 'minimum' crit_df.loc[crit_df['Operation'] == '=', 'operation'] = 'equal to' info_out = open(out_file, 'w+', errors="backslashreplace") info_out.write('\documentclass{article}\n') info_out.write('\\usepackage{booktabs}\n') # info_out.write('\\usepackage{longtable}\n') # T1 will ensure that symbols like '<' are formatted correctly info_out.write("\\usepackage[T1]{fontenc}\n") info_out.write('\\begin{document}') info_out.write(crit_df.to_latex(index=False, longtable=False, escape=True, multicolumn=False)) info_out.write('\end{document}\n') info_out.close() else: crit_df.to_excel(out_file, index=False) else: print("No criteria for ouput.") return True, [out_file]
bsd-3-clause
henry0312/LightGBM
examples/python-guide/dask/prediction.py
2
1325
import dask.array as da from distributed import Client, LocalCluster from sklearn.datasets import make_regression from sklearn.metrics import mean_squared_error import lightgbm as lgb if __name__ == "__main__": print("loading data") X, y = make_regression(n_samples=1000, n_features=50) print("initializing a Dask cluster") cluster = LocalCluster(n_workers=2) client = Client(cluster) print("created a Dask LocalCluster") print("distributing training data on the Dask cluster") dX = da.from_array(X, chunks=(100, 50)) dy = da.from_array(y, chunks=(100,)) print("beginning training") dask_model = lgb.DaskLGBMRegressor(n_estimators=10) dask_model.fit(dX, dy) assert dask_model.fitted_ print("done training") print("predicting on the training data") preds = dask_model.predict(dX) # the code below uses sklearn.metrics, but this requires pulling all of the # predictions and target values back from workers to the client # # for larger datasets, consider the metrics from dask-ml instead # https://ml.dask.org/modules/api.html#dask-ml-metrics-metrics print("computing MSE") preds_local = preds.compute() actuals_local = dy.compute() mse = mean_squared_error(actuals_local, preds_local) print(f"MSE: {mse}")
mit
jonyroda97/redbot-amigosprovaveis
lib/matplotlib/tests/test_rcparams.py
2
18156
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import io import os import warnings from collections import OrderedDict from cycler import cycler, Cycler import pytest try: from unittest import mock except ImportError: import mock import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.colors as mcolors from itertools import chain import numpy as np from matplotlib.rcsetup import (validate_bool_maybe_none, validate_stringlist, validate_colorlist, validate_color, validate_bool, validate_nseq_int, validate_nseq_float, validate_cycler, validate_hatch, validate_hist_bins, _validate_linestyle) mpl.rc('text', usetex=False) mpl.rc('lines', linewidth=22) fname = os.path.join(os.path.dirname(__file__), 'test_rcparams.rc') def test_rcparams(): usetex = mpl.rcParams['text.usetex'] linewidth = mpl.rcParams['lines.linewidth'] # test context given dictionary with mpl.rc_context(rc={'text.usetex': not usetex}): assert mpl.rcParams['text.usetex'] == (not usetex) assert mpl.rcParams['text.usetex'] == usetex # test context given filename (mpl.rc sets linewdith to 33) with mpl.rc_context(fname=fname): assert mpl.rcParams['lines.linewidth'] == 33 assert mpl.rcParams['lines.linewidth'] == linewidth # test context given filename and dictionary with mpl.rc_context(fname=fname, rc={'lines.linewidth': 44}): assert mpl.rcParams['lines.linewidth'] == 44 assert mpl.rcParams['lines.linewidth'] == linewidth # test rc_file try: mpl.rc_file(fname) assert mpl.rcParams['lines.linewidth'] == 33 finally: mpl.rcParams['lines.linewidth'] = linewidth def test_RcParams_class(): rc = mpl.RcParams({'font.cursive': ['Apple Chancery', 'Textile', 'Zapf Chancery', 'cursive'], 'font.family': 'sans-serif', 'font.weight': 'normal', 'font.size': 12}) if six.PY3: expected_repr = """ RcParams({'font.cursive': ['Apple Chancery', 'Textile', 'Zapf Chancery', 'cursive'], 'font.family': ['sans-serif'], 'font.size': 12.0, 'font.weight': 'normal'})""".lstrip() else: expected_repr = """ RcParams({u'font.cursive': [u'Apple Chancery', u'Textile', u'Zapf Chancery', u'cursive'], u'font.family': [u'sans-serif'], u'font.size': 12.0, u'font.weight': u'normal'})""".lstrip() assert expected_repr == repr(rc) if six.PY3: expected_str = """ font.cursive: ['Apple Chancery', 'Textile', 'Zapf Chancery', 'cursive'] font.family: ['sans-serif'] font.size: 12.0 font.weight: normal""".lstrip() else: expected_str = """ font.cursive: [u'Apple Chancery', u'Textile', u'Zapf Chancery', u'cursive'] font.family: [u'sans-serif'] font.size: 12.0 font.weight: normal""".lstrip() assert expected_str == str(rc) # test the find_all functionality assert ['font.cursive', 'font.size'] == sorted(rc.find_all('i[vz]')) assert ['font.family'] == list(rc.find_all('family')) def test_rcparams_update(): rc = mpl.RcParams({'figure.figsize': (3.5, 42)}) bad_dict = {'figure.figsize': (3.5, 42, 1)} # make sure validation happens on input with pytest.raises(ValueError): with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='.*(validate)', category=UserWarning) rc.update(bad_dict) def test_rcparams_init(): with pytest.raises(ValueError): with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='.*(validate)', category=UserWarning) mpl.RcParams({'figure.figsize': (3.5, 42, 1)}) def test_Bug_2543(): # Test that it possible to add all values to itself / deepcopy # This was not possible because validate_bool_maybe_none did not # accept None as an argument. # https://github.com/matplotlib/matplotlib/issues/2543 # We filter warnings at this stage since a number of them are raised # for deprecated rcparams as they should. We dont want these in the # printed in the test suite. with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='.*(deprecated|obsolete)', category=UserWarning) with mpl.rc_context(): _copy = mpl.rcParams.copy() for key in _copy: mpl.rcParams[key] = _copy[key] mpl.rcParams['text.dvipnghack'] = None with mpl.rc_context(): from copy import deepcopy _deep_copy = deepcopy(mpl.rcParams) # real test is that this does not raise assert validate_bool_maybe_none(None) is None assert validate_bool_maybe_none("none") is None _fonttype = mpl.rcParams['svg.fonttype'] assert _fonttype == mpl.rcParams['svg.embed_char_paths'] with mpl.rc_context(): mpl.rcParams['svg.embed_char_paths'] = False assert mpl.rcParams['svg.fonttype'] == "none" with pytest.raises(ValueError): validate_bool_maybe_none("blah") with pytest.raises(ValueError): validate_bool(None) with pytest.raises(ValueError): with mpl.rc_context(): mpl.rcParams['svg.fonttype'] = True legend_color_tests = [ ('face', {'color': 'r'}, mcolors.to_rgba('r')), ('face', {'color': 'inherit', 'axes.facecolor': 'r'}, mcolors.to_rgba('r')), ('face', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')), ('edge', {'color': 'r'}, mcolors.to_rgba('r')), ('edge', {'color': 'inherit', 'axes.edgecolor': 'r'}, mcolors.to_rgba('r')), ('edge', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')) ] legend_color_test_ids = [ 'same facecolor', 'inherited facecolor', 'different facecolor', 'same edgecolor', 'inherited edgecolor', 'different facecolor', ] @pytest.mark.parametrize('color_type, param_dict, target', legend_color_tests, ids=legend_color_test_ids) def test_legend_colors(color_type, param_dict, target): param_dict['legend.%scolor' % (color_type, )] = param_dict.pop('color') get_func = 'get_%scolor' % (color_type, ) with mpl.rc_context(param_dict): _, ax = plt.subplots() ax.plot(range(3), label='test') leg = ax.legend() assert getattr(leg.legendPatch, get_func)() == target def test_Issue_1713(): utf32_be = os.path.join(os.path.dirname(__file__), 'test_utf32_be_rcparams.rc') import locale with mock.patch('locale.getpreferredencoding', return_value='UTF-32-BE'): rc = mpl.rc_params_from_file(utf32_be, True, False) assert rc.get('timezone') == 'UTC' def generate_validator_testcases(valid): validation_tests = ( {'validator': validate_bool, 'success': chain(((_, True) for _ in ('t', 'y', 'yes', 'on', 'true', '1', 1, True)), ((_, False) for _ in ('f', 'n', 'no', 'off', 'false', '0', 0, False))), 'fail': ((_, ValueError) for _ in ('aardvark', 2, -1, [], ))}, {'validator': validate_stringlist, 'success': (('', []), ('a,b', ['a', 'b']), ('aardvark', ['aardvark']), ('aardvark, ', ['aardvark']), ('aardvark, ,', ['aardvark']), (['a', 'b'], ['a', 'b']), (('a', 'b'), ['a', 'b']), (iter(['a', 'b']), ['a', 'b']), (np.array(['a', 'b']), ['a', 'b']), ((1, 2), ['1', '2']), (np.array([1, 2]), ['1', '2']), ), 'fail': ((dict(), ValueError), (1, ValueError), ) }, {'validator': validate_nseq_int(2), 'success': ((_, [1, 2]) for _ in ('1, 2', [1.5, 2.5], [1, 2], (1, 2), np.array((1, 2)))), 'fail': ((_, ValueError) for _ in ('aardvark', ('a', 1), (1, 2, 3) )) }, {'validator': validate_nseq_float(2), 'success': ((_, [1.5, 2.5]) for _ in ('1.5, 2.5', [1.5, 2.5], [1.5, 2.5], (1.5, 2.5), np.array((1.5, 2.5)))), 'fail': ((_, ValueError) for _ in ('aardvark', ('a', 1), (1, 2, 3) )) }, {'validator': validate_cycler, 'success': (('cycler("color", "rgb")', cycler("color", 'rgb')), (cycler('linestyle', ['-', '--']), cycler('linestyle', ['-', '--'])), ("""(cycler("color", ["r", "g", "b"]) + cycler("mew", [2, 3, 5]))""", (cycler("color", 'rgb') + cycler("markeredgewidth", [2, 3, 5]))), ("cycler(c='rgb', lw=[1, 2, 3])", cycler('color', 'rgb') + cycler('linewidth', [1, 2, 3])), ("cycler('c', 'rgb') * cycler('linestyle', ['-', '--'])", (cycler('color', 'rgb') * cycler('linestyle', ['-', '--']))), (cycler('ls', ['-', '--']), cycler('linestyle', ['-', '--'])), (cycler(mew=[2, 5]), cycler('markeredgewidth', [2, 5])), ), # This is *so* incredibly important: validate_cycler() eval's # an arbitrary string! I think I have it locked down enough, # and that is what this is testing. # TODO: Note that these tests are actually insufficient, as it may # be that they raised errors, but still did an action prior to # raising the exception. We should devise some additional tests # for that... 'fail': ((4, ValueError), # Gotta be a string or Cycler object ('cycler("bleh, [])', ValueError), # syntax error ('Cycler("linewidth", [1, 2, 3])', ValueError), # only 'cycler()' function is allowed ('1 + 2', ValueError), # doesn't produce a Cycler object ('os.system("echo Gotcha")', ValueError), # os not available ('import os', ValueError), # should not be able to import ('def badjuju(a): return a; badjuju(cycler("color", "rgb"))', ValueError), # Should not be able to define anything # even if it does return a cycler ('cycler("waka", [1, 2, 3])', ValueError), # not a property ('cycler(c=[1, 2, 3])', ValueError), # invalid values ("cycler(lw=['a', 'b', 'c'])", ValueError), # invalid values (cycler('waka', [1, 3, 5]), ValueError), # not a property (cycler('color', ['C1', 'r', 'g']), ValueError) # no CN ) }, {'validator': validate_hatch, 'success': (('--|', '--|'), ('\\oO', '\\oO'), ('/+*/.x', '/+*/.x'), ('', '')), 'fail': (('--_', ValueError), (8, ValueError), ('X', ValueError)), }, {'validator': validate_colorlist, 'success': (('r,g,b', ['r', 'g', 'b']), (['r', 'g', 'b'], ['r', 'g', 'b']), ('r, ,', ['r']), (['', 'g', 'blue'], ['g', 'blue']), ([np.array([1, 0, 0]), np.array([0, 1, 0])], np.array([[1, 0, 0], [0, 1, 0]])), (np.array([[1, 0, 0], [0, 1, 0]]), np.array([[1, 0, 0], [0, 1, 0]])), ), 'fail': (('fish', ValueError), ), }, {'validator': validate_color, 'success': (('None', 'none'), ('none', 'none'), ('AABBCC', '#AABBCC'), # RGB hex code ('AABBCC00', '#AABBCC00'), # RGBA hex code ('tab:blue', 'tab:blue'), # named color ('C0', 'C0'), # color from cycle ('(0, 1, 0)', [0.0, 1.0, 0.0]), # RGB tuple ((0, 1, 0), (0, 1, 0)), # non-string version ('(0, 1, 0, 1)', [0.0, 1.0, 0.0, 1.0]), # RGBA tuple ((0, 1, 0, 1), (0, 1, 0, 1)), # non-string version ('(0, 1, "0.5")', [0.0, 1.0, 0.5]), # unusual but valid ), 'fail': (('tab:veryblue', ValueError), # invalid name ('C123', ValueError), # invalid RGB(A) code and cycle index ('(0, 1)', ValueError), # tuple with length < 3 ('(0, 1, 0, 1, 0)', ValueError), # tuple with length > 4 ('(0, 1, none)', ValueError), # cannot cast none to float ), }, {'validator': validate_hist_bins, 'success': (('auto', 'auto'), ('10', 10), ('1, 2, 3', [1, 2, 3]), ([1, 2, 3], [1, 2, 3]), (np.arange(15), np.arange(15)) ), 'fail': (('aardvark', ValueError), ) } ) # The behavior of _validate_linestyle depends on the version of Python. # ASCII-compliant bytes arguments should pass on Python 2 because of the # automatic conversion between bytes and strings. Python 3 does not # perform such a conversion, so the same cases should raise an exception. # # Common cases: ls_test = {'validator': _validate_linestyle, 'success': (('-', '-'), ('solid', 'solid'), ('--', '--'), ('dashed', 'dashed'), ('-.', '-.'), ('dashdot', 'dashdot'), (':', ':'), ('dotted', 'dotted'), ('', ''), (' ', ' '), ('None', 'none'), ('none', 'none'), ('DoTtEd', 'dotted'), # case-insensitive (['1.23', '4.56'], (None, [1.23, 4.56])), ([1.23, 456], (None, [1.23, 456.0])), ([1, 2, 3, 4], (None, [1.0, 2.0, 3.0, 4.0])), ), 'fail': (('aardvark', ValueError), # not a valid string ('dotted'.encode('utf-16'), ValueError), # even on PY2 ((None, [1, 2]), ValueError), # (offset, dashes) != OK ((0, [1, 2]), ValueError), # idem ((-1, [1, 2]), ValueError), # idem ([1, 2, 3], ValueError), # sequence with odd length (1.23, ValueError), # not a sequence ) } # Add some cases of bytes arguments that Python 2 can convert silently: ls_bytes_args = (b'dotted', 'dotted'.encode('ascii')) if six.PY3: ls_test['fail'] += tuple((arg, ValueError) for arg in ls_bytes_args) else: ls_test['success'] += tuple((arg, 'dotted') for arg in ls_bytes_args) # Update the validation test sequence. validation_tests += (ls_test,) for validator_dict in validation_tests: validator = validator_dict['validator'] if valid: for arg, target in validator_dict['success']: yield validator, arg, target else: for arg, error_type in validator_dict['fail']: yield validator, arg, error_type @pytest.mark.parametrize('validator, arg, target', generate_validator_testcases(True)) def test_validator_valid(validator, arg, target): res = validator(arg) if isinstance(target, np.ndarray): assert np.all(res == target) elif not isinstance(target, Cycler): assert res == target else: # Cyclers can't simply be asserted equal. They don't implement __eq__ assert list(res) == list(target) @pytest.mark.parametrize('validator, arg, exception_type', generate_validator_testcases(False)) def test_validator_invalid(validator, arg, exception_type): with pytest.raises(exception_type): validator(arg) def test_keymaps(): key_list = [k for k in mpl.rcParams if 'keymap' in k] for k in key_list: assert isinstance(mpl.rcParams[k], list) def test_rcparams_reset_after_fail(): # There was previously a bug that meant that if rc_context failed and # raised an exception due to issues in the supplied rc parameters, the # global rc parameters were left in a modified state. with mpl.rc_context(rc={'text.usetex': False}): assert mpl.rcParams['text.usetex'] is False with pytest.raises(KeyError): with mpl.rc_context(rc=OrderedDict([('text.usetex', True),('test.blah', True)])): pass assert mpl.rcParams['text.usetex'] is False
gpl-3.0
jseabold/scikit-learn
sklearn/tree/tree.py
23
40423
""" This module gathers tree-based methods, including decision, regression and randomized trees. Single and multi-output problems are both handled. """ # Authors: Gilles Louppe <g.louppe@gmail.com> # Peter Prettenhofer <peter.prettenhofer@gmail.com> # Brian Holt <bdholt1@gmail.com> # Noel Dawe <noel@dawe.me> # Satrajit Gosh <satrajit.ghosh@gmail.com> # Joly Arnaud <arnaud.v.joly@gmail.com> # Fares Hedayati <fares.hedayati@gmail.com> # # Licence: BSD 3 clause from __future__ import division import numbers from abc import ABCMeta from abc import abstractmethod from math import ceil import numpy as np from scipy.sparse import issparse from ..base import BaseEstimator from ..base import ClassifierMixin from ..base import RegressorMixin from ..externals import six from ..feature_selection.from_model import _LearntSelectorMixin from ..utils import check_array from ..utils import check_random_state from ..utils import compute_sample_weight from ..utils.multiclass import check_classification_targets from ..exceptions import NotFittedError from ._criterion import Criterion from ._splitter import Splitter from ._tree import DepthFirstTreeBuilder from ._tree import BestFirstTreeBuilder from ._tree import Tree from . import _tree, _splitter, _criterion __all__ = ["DecisionTreeClassifier", "DecisionTreeRegressor", "ExtraTreeClassifier", "ExtraTreeRegressor"] # ============================================================================= # Types and constants # ============================================================================= DTYPE = _tree.DTYPE DOUBLE = _tree.DOUBLE CRITERIA_CLF = {"gini": _criterion.Gini, "entropy": _criterion.Entropy} CRITERIA_REG = {"mse": _criterion.MSE, "friedman_mse": _criterion.FriedmanMSE} DENSE_SPLITTERS = {"best": _splitter.BestSplitter, "random": _splitter.RandomSplitter} SPARSE_SPLITTERS = {"best": _splitter.BestSparseSplitter, "random": _splitter.RandomSparseSplitter} # ============================================================================= # Base decision tree # ============================================================================= class BaseDecisionTree(six.with_metaclass(ABCMeta, BaseEstimator, _LearntSelectorMixin)): """Base class for decision trees. Warning: This class should not be used directly. Use derived classes instead. """ @abstractmethod def __init__(self, criterion, splitter, max_depth, min_samples_split, min_samples_leaf, min_weight_fraction_leaf, max_features, max_leaf_nodes, random_state, class_weight=None, presort=False): self.criterion = criterion self.splitter = splitter self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.random_state = random_state self.max_leaf_nodes = max_leaf_nodes self.class_weight = class_weight self.presort = presort self.n_features_ = None self.n_outputs_ = None self.classes_ = None self.n_classes_ = None self.tree_ = None self.max_features_ = None def fit(self, X, y, sample_weight=None, check_input=True, X_idx_sorted=None): """Build a decision tree from the training set (X, y). Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The training input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csc_matrix``. y : array-like, shape = [n_samples] or [n_samples, n_outputs] The target values (class labels in classification, real numbers in regression). In the regression case, use ``dtype=np.float64`` and ``order='C'`` for maximum efficiency. sample_weight : array-like, shape = [n_samples] or None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. check_input : boolean, (default=True) Allow to bypass several input checking. Don't use this parameter unless you know what you do. X_idx_sorted : array-like, shape = [n_samples, n_features], optional The indexes of the sorted training input samples. If many tree are grown on the same dataset, this allows the ordering to be cached between trees. If None, the data will be sorted here. Don't use this parameter unless you know what to do. Returns ------- self : object Returns self. """ random_state = check_random_state(self.random_state) if check_input: X = check_array(X, dtype=DTYPE, accept_sparse="csc") y = check_array(y, ensure_2d=False, dtype=None) if issparse(X): X.sort_indices() if X.indices.dtype != np.intc or X.indptr.dtype != np.intc: raise ValueError("No support for np.int64 index based " "sparse matrices") # Determine output settings n_samples, self.n_features_ = X.shape is_classification = isinstance(self, ClassifierMixin) y = np.atleast_1d(y) expanded_class_weight = None if y.ndim == 1: # reshape is necessary to preserve the data contiguity against vs # [:, np.newaxis] that does not. y = np.reshape(y, (-1, 1)) self.n_outputs_ = y.shape[1] if is_classification: check_classification_targets(y) y = np.copy(y) self.classes_ = [] self.n_classes_ = [] if self.class_weight is not None: y_original = np.copy(y) y_encoded = np.zeros(y.shape, dtype=np.int) for k in range(self.n_outputs_): classes_k, y_encoded[:, k] = np.unique(y[:, k], return_inverse=True) self.classes_.append(classes_k) self.n_classes_.append(classes_k.shape[0]) y = y_encoded if self.class_weight is not None: expanded_class_weight = compute_sample_weight( self.class_weight, y_original) else: self.classes_ = [None] * self.n_outputs_ self.n_classes_ = [1] * self.n_outputs_ self.n_classes_ = np.array(self.n_classes_, dtype=np.intp) if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous: y = np.ascontiguousarray(y, dtype=DOUBLE) # Check parameters max_depth = ((2 ** 31) - 1 if self.max_depth is None else self.max_depth) max_leaf_nodes = (-1 if self.max_leaf_nodes is None else self.max_leaf_nodes) if isinstance(self.min_samples_leaf, (numbers.Integral, np.integer)): min_samples_leaf = self.min_samples_leaf else: # float min_samples_leaf = int(ceil(self.min_samples_leaf * n_samples)) if isinstance(self.min_samples_split, (numbers.Integral, np.integer)): min_samples_split = self.min_samples_split else: # float min_samples_split = int(ceil(self.min_samples_split * n_samples)) min_samples_split = max(2, min_samples_split) min_samples_split = max(min_samples_split, 2 * min_samples_leaf) if isinstance(self.max_features, six.string_types): if self.max_features == "auto": if is_classification: max_features = max(1, int(np.sqrt(self.n_features_))) else: max_features = self.n_features_ elif self.max_features == "sqrt": max_features = max(1, int(np.sqrt(self.n_features_))) elif self.max_features == "log2": max_features = max(1, int(np.log2(self.n_features_))) else: raise ValueError( 'Invalid value for max_features. Allowed string ' 'values are "auto", "sqrt" or "log2".') elif self.max_features is None: max_features = self.n_features_ elif isinstance(self.max_features, (numbers.Integral, np.integer)): max_features = self.max_features else: # float if self.max_features > 0.0: max_features = max(1, int(self.max_features * self.n_features_)) else: max_features = 0 self.max_features_ = max_features if len(y) != n_samples: raise ValueError("Number of labels=%d does not match " "number of samples=%d" % (len(y), n_samples)) if not (0. < self.min_samples_split <= 1. or 2 <= self.min_samples_split): raise ValueError("min_samples_split must be in at least 2" " or in (0, 1], got %s" % min_samples_split) if not (0. < self.min_samples_leaf <= 0.5 or 1 <= self.min_samples_leaf): raise ValueError("min_samples_leaf must be at least than 1 " "or in (0, 0.5], got %s" % min_samples_leaf) if not 0 <= self.min_weight_fraction_leaf <= 0.5: raise ValueError("min_weight_fraction_leaf must in [0, 0.5]") if max_depth <= 0: raise ValueError("max_depth must be greater than zero. ") if not (0 < max_features <= self.n_features_): raise ValueError("max_features must be in (0, n_features]") if not isinstance(max_leaf_nodes, (numbers.Integral, np.integer)): raise ValueError("max_leaf_nodes must be integral number but was " "%r" % max_leaf_nodes) if -1 < max_leaf_nodes < 2: raise ValueError(("max_leaf_nodes {0} must be either smaller than " "0 or larger than 1").format(max_leaf_nodes)) if sample_weight is not None: if (getattr(sample_weight, "dtype", None) != DOUBLE or not sample_weight.flags.contiguous): sample_weight = np.ascontiguousarray( sample_weight, dtype=DOUBLE) if len(sample_weight.shape) > 1: raise ValueError("Sample weights array has more " "than one dimension: %d" % len(sample_weight.shape)) if len(sample_weight) != n_samples: raise ValueError("Number of weights=%d does not match " "number of samples=%d" % (len(sample_weight), n_samples)) if expanded_class_weight is not None: if sample_weight is not None: sample_weight = sample_weight * expanded_class_weight else: sample_weight = expanded_class_weight # Set min_weight_leaf from min_weight_fraction_leaf if self.min_weight_fraction_leaf != 0. and sample_weight is not None: min_weight_leaf = (self.min_weight_fraction_leaf * np.sum(sample_weight)) else: min_weight_leaf = 0. presort = self.presort # Allow presort to be 'auto', which means True if the dataset is dense, # otherwise it will be False. if self.presort == 'auto' and issparse(X): presort = False elif self.presort == 'auto': presort = True if presort is True and issparse(X): raise ValueError("Presorting is not supported for sparse " "matrices.") # If multiple trees are built on the same dataset, we only want to # presort once. Splitters now can accept presorted indices if desired, # but do not handle any presorting themselves. Ensemble algorithms # which desire presorting must do presorting themselves and pass that # matrix into each tree. if X_idx_sorted is None and presort: X_idx_sorted = np.asfortranarray(np.argsort(X, axis=0), dtype=np.int32) if presort and X_idx_sorted.shape != X.shape: raise ValueError("The shape of X (X.shape = {}) doesn't match " "the shape of X_idx_sorted (X_idx_sorted" ".shape = {})".format(X.shape, X_idx_sorted.shape)) # Build tree criterion = self.criterion if not isinstance(criterion, Criterion): if is_classification: criterion = CRITERIA_CLF[self.criterion](self.n_outputs_, self.n_classes_) else: criterion = CRITERIA_REG[self.criterion](self.n_outputs_) SPLITTERS = SPARSE_SPLITTERS if issparse(X) else DENSE_SPLITTERS splitter = self.splitter if not isinstance(self.splitter, Splitter): splitter = SPLITTERS[self.splitter](criterion, self.max_features_, min_samples_leaf, min_weight_leaf, random_state, self.presort) self.tree_ = Tree(self.n_features_, self.n_classes_, self.n_outputs_) # Use BestFirst if max_leaf_nodes given; use DepthFirst otherwise if max_leaf_nodes < 0: builder = DepthFirstTreeBuilder(splitter, min_samples_split, min_samples_leaf, min_weight_leaf, max_depth) else: builder = BestFirstTreeBuilder(splitter, min_samples_split, min_samples_leaf, min_weight_leaf, max_depth, max_leaf_nodes) builder.build(self.tree_, X, y, sample_weight, X_idx_sorted) if self.n_outputs_ == 1: self.n_classes_ = self.n_classes_[0] self.classes_ = self.classes_[0] return self def _validate_X_predict(self, X, check_input): """Validate X whenever one tries to predict, apply, predict_proba""" if self.tree_ is None: raise NotFittedError("Estimator not fitted, " "call `fit` before exploiting the model.") if check_input: X = check_array(X, dtype=DTYPE, accept_sparse="csr") if issparse(X) and (X.indices.dtype != np.intc or X.indptr.dtype != np.intc): raise ValueError("No support for np.int64 index based " "sparse matrices") n_features = X.shape[1] if self.n_features_ != n_features: raise ValueError("Number of features of the model must " "match the input. Model n_features is %s and " "input n_features is %s " % (self.n_features_, n_features)) return X def predict(self, X, check_input=True): """Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. check_input : boolean, (default=True) Allow to bypass several input checking. Don't use this parameter unless you know what you do. Returns ------- y : array of shape = [n_samples] or [n_samples, n_outputs] The predicted classes, or the predict values. """ X = self._validate_X_predict(X, check_input) proba = self.tree_.predict(X) n_samples = X.shape[0] # Classification if isinstance(self, ClassifierMixin): if self.n_outputs_ == 1: return self.classes_.take(np.argmax(proba, axis=1), axis=0) else: predictions = np.zeros((n_samples, self.n_outputs_)) for k in range(self.n_outputs_): predictions[:, k] = self.classes_[k].take( np.argmax(proba[:, k], axis=1), axis=0) return predictions # Regression else: if self.n_outputs_ == 1: return proba[:, 0] else: return proba[:, :, 0] def apply(self, X, check_input=True): """ Returns the index of the leaf that each sample is predicted as. .. versionadded:: 0.17 Parameters ---------- X : array_like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. check_input : boolean, (default=True) Allow to bypass several input checking. Don't use this parameter unless you know what you do. Returns ------- X_leaves : array_like, shape = [n_samples,] For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within ``[0; self.tree_.node_count)``, possibly with gaps in the numbering. """ X = self._validate_X_predict(X, check_input) return self.tree_.apply(X) def decision_path(self, X, check_input=True): """Return the decision path in the tree Parameters ---------- X : array_like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. check_input : boolean, (default=True) Allow to bypass several input checking. Don't use this parameter unless you know what you do. Returns ------- indicator : sparse csr array, shape = [n_samples, n_nodes] Return a node indicator matrix where non zero elements indicates that the samples goes through the nodes. """ X = self._validate_X_predict(X, check_input) return self.tree_.decision_path(X) @property def feature_importances_(self): """Return the feature importances. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Returns ------- feature_importances_ : array, shape = [n_features] """ if self.tree_ is None: raise NotFittedError("Estimator not fitted, call `fit` before" " `feature_importances_`.") return self.tree_.compute_feature_importances() # ============================================================================= # Public estimators # ============================================================================= class DecisionTreeClassifier(BaseDecisionTree, ClassifierMixin): """A decision tree classifier. Read more in the :ref:`User Guide <tree>`. Parameters ---------- criterion : string, optional (default="gini") The function to measure the quality of a split. Supported criteria are "gini" for the Gini impurity and "entropy" for the information gain. splitter : string, optional (default="best") The strategy used to choose the split at each node. Supported strategies are "best" to choose the best split and "random" to choose the best random split. max_features : int, float, string or None, optional (default=None) The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a percentage and `int(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=sqrt(n_features)`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_depth : int or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. Ignored if ``max_leaf_nodes`` is not None. min_samples_split : int, float, optional (default=2) The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a percentage and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. min_samples_leaf : int, float, optional (default=1) The minimum number of samples required to be at a leaf node: - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a percentage and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. min_weight_fraction_leaf : float, optional (default=0.) The minimum weighted fraction of the input samples required to be at a leaf node. max_leaf_nodes : int or None, optional (default=None) Grow a tree with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. If not None then ``max_depth`` will be ignored. class_weight : dict, list of dicts, "balanced" or None, optional (default=None) Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. presort : bool, optional (default=False) Whether to presort the data to speed up the finding of best splits in fitting. For the default settings of a decision tree on large datasets, setting this to true may slow down the training process. When using either a smaller dataset or a restricted depth, this may speed up the training. Attributes ---------- classes_ : array of shape = [n_classes] or a list of such arrays The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). feature_importances_ : array of shape = [n_features] The feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance [4]_. max_features_ : int, The inferred value of max_features. n_classes_ : int or list The number of classes (for single output problems), or a list containing the number of classes for each output (for multi-output problems). n_features_ : int The number of features when ``fit`` is performed. n_outputs_ : int The number of outputs when ``fit`` is performed. tree_ : Tree object The underlying Tree object. See also -------- DecisionTreeRegressor References ---------- .. [1] http://en.wikipedia.org/wiki/Decision_tree_learning .. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification and Regression Trees", Wadsworth, Belmont, CA, 1984. .. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical Learning", Springer, 2009. .. [4] L. Breiman, and A. Cutler, "Random Forests", http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm Examples -------- >>> from sklearn.datasets import load_iris >>> from sklearn.model_selection import cross_val_score >>> from sklearn.tree import DecisionTreeClassifier >>> clf = DecisionTreeClassifier(random_state=0) >>> iris = load_iris() >>> cross_val_score(clf, iris.data, iris.target, cv=10) ... # doctest: +SKIP ... array([ 1. , 0.93..., 0.86..., 0.93..., 0.93..., 0.93..., 0.93..., 1. , 0.93..., 1. ]) """ def __init__(self, criterion="gini", splitter="best", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features=None, random_state=None, max_leaf_nodes=None, class_weight=None, presort=False): super(DecisionTreeClassifier, self).__init__( criterion=criterion, splitter=splitter, max_depth=max_depth, min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf, min_weight_fraction_leaf=min_weight_fraction_leaf, max_features=max_features, max_leaf_nodes=max_leaf_nodes, class_weight=class_weight, random_state=random_state, presort=presort) def predict_proba(self, X, check_input=True): """Predict class probabilities of the input samples X. The predicted class probability is the fraction of samples of the same class in a leaf. check_input : boolean, (default=True) Allow to bypass several input checking. Don't use this parameter unless you know what you do. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- p : array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute `classes_`. """ X = self._validate_X_predict(X, check_input) proba = self.tree_.predict(X) if self.n_outputs_ == 1: proba = proba[:, :self.n_classes_] normalizer = proba.sum(axis=1)[:, np.newaxis] normalizer[normalizer == 0.0] = 1.0 proba /= normalizer return proba else: all_proba = [] for k in range(self.n_outputs_): proba_k = proba[:, k, :self.n_classes_[k]] normalizer = proba_k.sum(axis=1)[:, np.newaxis] normalizer[normalizer == 0.0] = 1.0 proba_k /= normalizer all_proba.append(proba_k) return all_proba def predict_log_proba(self, X): """Predict class log-probabilities of the input samples X. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- p : array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1. The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute `classes_`. """ proba = self.predict_proba(X) if self.n_outputs_ == 1: return np.log(proba) else: for k in range(self.n_outputs_): proba[k] = np.log(proba[k]) return proba class DecisionTreeRegressor(BaseDecisionTree, RegressorMixin): """A decision tree regressor. Read more in the :ref:`User Guide <tree>`. Parameters ---------- criterion : string, optional (default="mse") The function to measure the quality of a split. The only supported criterion is "mse" for the mean squared error, which is equal to variance reduction as feature selection criterion. splitter : string, optional (default="best") The strategy used to choose the split at each node. Supported strategies are "best" to choose the best split and "random" to choose the best random split. max_features : int, float, string or None, optional (default=None) The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a percentage and `int(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=n_features`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_depth : int or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. Ignored if ``max_leaf_nodes`` is not None. min_samples_split : int, float, optional (default=2) The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a percentage and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. min_samples_leaf : int, float, optional (default=1) The minimum number of samples required to be at a leaf node: - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a percentage and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. min_weight_fraction_leaf : float, optional (default=0.) The minimum weighted fraction of the input samples required to be at a leaf node. max_leaf_nodes : int or None, optional (default=None) Grow a tree with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. If not None then ``max_depth`` will be ignored. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. presort : bool, optional (default=False) Whether to presort the data to speed up the finding of best splits in fitting. For the default settings of a decision tree on large datasets, setting this to true may slow down the training process. When using either a smaller dataset or a restricted depth, this may speed up the training. Attributes ---------- feature_importances_ : array of shape = [n_features] The feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance [4]_. max_features_ : int, The inferred value of max_features. n_features_ : int The number of features when ``fit`` is performed. n_outputs_ : int The number of outputs when ``fit`` is performed. tree_ : Tree object The underlying Tree object. See also -------- DecisionTreeClassifier References ---------- .. [1] http://en.wikipedia.org/wiki/Decision_tree_learning .. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification and Regression Trees", Wadsworth, Belmont, CA, 1984. .. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical Learning", Springer, 2009. .. [4] L. Breiman, and A. Cutler, "Random Forests", http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm Examples -------- >>> from sklearn.datasets import load_boston >>> from sklearn.model_selection import cross_val_score >>> from sklearn.tree import DecisionTreeRegressor >>> boston = load_boston() >>> regressor = DecisionTreeRegressor(random_state=0) >>> cross_val_score(regressor, boston.data, boston.target, cv=10) ... # doctest: +SKIP ... array([ 0.61..., 0.57..., -0.34..., 0.41..., 0.75..., 0.07..., 0.29..., 0.33..., -1.42..., -1.77...]) """ def __init__(self, criterion="mse", splitter="best", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features=None, random_state=None, max_leaf_nodes=None, presort=False): super(DecisionTreeRegressor, self).__init__( criterion=criterion, splitter=splitter, max_depth=max_depth, min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf, min_weight_fraction_leaf=min_weight_fraction_leaf, max_features=max_features, max_leaf_nodes=max_leaf_nodes, random_state=random_state, presort=presort) class ExtraTreeClassifier(DecisionTreeClassifier): """An extremely randomized tree classifier. Extra-trees differ from classic decision trees in the way they are built. When looking for the best split to separate the samples of a node into two groups, random splits are drawn for each of the `max_features` randomly selected features and the best split among those is chosen. When `max_features` is set 1, this amounts to building a totally random decision tree. Warning: Extra-trees should only be used within ensemble methods. Read more in the :ref:`User Guide <tree>`. See also -------- ExtraTreeRegressor, ExtraTreesClassifier, ExtraTreesRegressor References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. """ def __init__(self, criterion="gini", splitter="random", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", random_state=None, max_leaf_nodes=None, class_weight=None): super(ExtraTreeClassifier, self).__init__( criterion=criterion, splitter=splitter, max_depth=max_depth, min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf, min_weight_fraction_leaf=min_weight_fraction_leaf, max_features=max_features, max_leaf_nodes=max_leaf_nodes, class_weight=class_weight, random_state=random_state) class ExtraTreeRegressor(DecisionTreeRegressor): """An extremely randomized tree regressor. Extra-trees differ from classic decision trees in the way they are built. When looking for the best split to separate the samples of a node into two groups, random splits are drawn for each of the `max_features` randomly selected features and the best split among those is chosen. When `max_features` is set 1, this amounts to building a totally random decision tree. Warning: Extra-trees should only be used within ensemble methods. Read more in the :ref:`User Guide <tree>`. See also -------- ExtraTreeClassifier, ExtraTreesClassifier, ExtraTreesRegressor References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. """ def __init__(self, criterion="mse", splitter="random", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", random_state=None, max_leaf_nodes=None): super(ExtraTreeRegressor, self).__init__( criterion=criterion, splitter=splitter, max_depth=max_depth, min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf, min_weight_fraction_leaf=min_weight_fraction_leaf, max_features=max_features, max_leaf_nodes=max_leaf_nodes, random_state=random_state)
bsd-3-clause
dkriegner/xrayutilities
examples/xrayutilities_experiment_Powder_example_Iron.py
1
2057
# This file is part of xrayutilities. # # xrayutilities is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. # # Copyright (C) 2016 Dominik Kriegner <dominik.kriegner@gmail.com> from multiprocessing import freeze_support import matplotlib.pyplot as plt import numpy import xrayutilities as xu from mpl_toolkits.axes_grid1 import make_axes_locatable def main(): """dummy main function to enable multiprocessing on windows""" cryst_size = 40e-9 # meter # create Fe BCC (space group nr. 229 Im3m) with a = 2.87 angstrom although # this is already predefined as xu.materials.Fe we will repeat here for # educational purposes FeBCC = xu.materials.Crystal( "Fe", xu.materials.SGLattice(229, 2.87, atoms=[xu.materials.elements.Fe, ], pos=['2a', ])) print("Creating Fe powder ...") Fe_powder = xu.simpack.Powder(FeBCC, 1, crystallite_size_gauss=cryst_size) pm = xu.simpack.PowderModel(Fe_powder) tt = numpy.arange(5, 120, 0.01) inte = pm.simulate(tt) print(pm) # # to create a mixed powder sample one would use # Co_powder = xu.simpack.Powder(xu.materials.Co, 5) # 5 times more Co # pmix = xu.simpack.PowderModel(Fe_powder + Co_powder, I0=100) # inte = pmix.simulate(tt) # pmix.close() # after end-of-use for cleanup ax = pm.plot(tt) ax.set_xlim(5, 120) pm.close() if __name__ == '__main__': freeze_support() main()
gpl-2.0
kjung/scikit-learn
sklearn/svm/tests/test_sparse.py
35
13182
from nose.tools import assert_raises, assert_true, assert_false import numpy as np from scipy import sparse from numpy.testing import (assert_array_almost_equal, assert_array_equal, assert_equal) from sklearn import datasets, svm, linear_model, base from sklearn.datasets import make_classification, load_digits, make_blobs from sklearn.svm.tests import test_svm from sklearn.exceptions import ConvergenceWarning from sklearn.utils.extmath import safe_sparse_dot from sklearn.utils.testing import assert_warns, assert_raise_message # test sample 1 X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]) X_sp = sparse.lil_matrix(X) Y = [1, 1, 1, 2, 2, 2] T = np.array([[-1, -1], [2, 2], [3, 2]]) true_result = [1, 2, 2] # test sample 2 X2 = np.array([[0, 0, 0], [1, 1, 1], [2, 0, 0, ], [0, 0, 2], [3, 3, 3]]) X2_sp = sparse.dok_matrix(X2) Y2 = [1, 2, 2, 2, 3] T2 = np.array([[-1, -1, -1], [1, 1, 1], [2, 2, 2]]) true_result2 = [1, 2, 3] iris = datasets.load_iris() # permute rng = np.random.RandomState(0) perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] # sparsify iris.data = sparse.csr_matrix(iris.data) def check_svm_model_equal(dense_svm, sparse_svm, X_train, y_train, X_test): dense_svm.fit(X_train.toarray(), y_train) if sparse.isspmatrix(X_test): X_test_dense = X_test.toarray() else: X_test_dense = X_test sparse_svm.fit(X_train, y_train) assert_true(sparse.issparse(sparse_svm.support_vectors_)) assert_true(sparse.issparse(sparse_svm.dual_coef_)) assert_array_almost_equal(dense_svm.support_vectors_, sparse_svm.support_vectors_.toarray()) assert_array_almost_equal(dense_svm.dual_coef_, sparse_svm.dual_coef_.toarray()) if dense_svm.kernel == "linear": assert_true(sparse.issparse(sparse_svm.coef_)) assert_array_almost_equal(dense_svm.coef_, sparse_svm.coef_.toarray()) assert_array_almost_equal(dense_svm.support_, sparse_svm.support_) assert_array_almost_equal(dense_svm.predict(X_test_dense), sparse_svm.predict(X_test)) assert_array_almost_equal(dense_svm.decision_function(X_test_dense), sparse_svm.decision_function(X_test)) assert_array_almost_equal(dense_svm.decision_function(X_test_dense), sparse_svm.decision_function(X_test_dense)) if isinstance(dense_svm, svm.OneClassSVM): msg = "cannot use sparse input in 'OneClassSVM' trained on dense data" else: assert_array_almost_equal(dense_svm.predict_proba(X_test_dense), sparse_svm.predict_proba(X_test), 4) msg = "cannot use sparse input in 'SVC' trained on dense data" if sparse.isspmatrix(X_test): assert_raise_message(ValueError, msg, dense_svm.predict, X_test) def test_svc(): """Check that sparse SVC gives the same result as SVC""" # many class dataset: X_blobs, y_blobs = make_blobs(n_samples=100, centers=10, random_state=0) X_blobs = sparse.csr_matrix(X_blobs) datasets = [[X_sp, Y, T], [X2_sp, Y2, T2], [X_blobs[:80], y_blobs[:80], X_blobs[80:]], [iris.data, iris.target, iris.data]] kernels = ["linear", "poly", "rbf", "sigmoid"] for dataset in datasets: for kernel in kernels: clf = svm.SVC(kernel=kernel, probability=True, random_state=0, decision_function_shape='ovo') sp_clf = svm.SVC(kernel=kernel, probability=True, random_state=0, decision_function_shape='ovo') check_svm_model_equal(clf, sp_clf, *dataset) def test_unsorted_indices(): # test that the result with sorted and unsorted indices in csr is the same # we use a subset of digits as iris, blobs or make_classification didn't # show the problem digits = load_digits() X, y = digits.data[:50], digits.target[:50] X_test = sparse.csr_matrix(digits.data[50:100]) X_sparse = sparse.csr_matrix(X) coef_dense = svm.SVC(kernel='linear', probability=True, random_state=0).fit(X, y).coef_ sparse_svc = svm.SVC(kernel='linear', probability=True, random_state=0).fit(X_sparse, y) coef_sorted = sparse_svc.coef_ # make sure dense and sparse SVM give the same result assert_array_almost_equal(coef_dense, coef_sorted.toarray()) X_sparse_unsorted = X_sparse[np.arange(X.shape[0])] X_test_unsorted = X_test[np.arange(X_test.shape[0])] # make sure we scramble the indices assert_false(X_sparse_unsorted.has_sorted_indices) assert_false(X_test_unsorted.has_sorted_indices) unsorted_svc = svm.SVC(kernel='linear', probability=True, random_state=0).fit(X_sparse_unsorted, y) coef_unsorted = unsorted_svc.coef_ # make sure unsorted indices give same result assert_array_almost_equal(coef_unsorted.toarray(), coef_sorted.toarray()) assert_array_almost_equal(sparse_svc.predict_proba(X_test_unsorted), sparse_svc.predict_proba(X_test)) def test_svc_with_custom_kernel(): kfunc = lambda x, y: safe_sparse_dot(x, y.T) clf_lin = svm.SVC(kernel='linear').fit(X_sp, Y) clf_mylin = svm.SVC(kernel=kfunc).fit(X_sp, Y) assert_array_equal(clf_lin.predict(X_sp), clf_mylin.predict(X_sp)) def test_svc_iris(): # Test the sparse SVC with the iris dataset for k in ('linear', 'poly', 'rbf'): sp_clf = svm.SVC(kernel=k).fit(iris.data, iris.target) clf = svm.SVC(kernel=k).fit(iris.data.toarray(), iris.target) assert_array_almost_equal(clf.support_vectors_, sp_clf.support_vectors_.toarray()) assert_array_almost_equal(clf.dual_coef_, sp_clf.dual_coef_.toarray()) assert_array_almost_equal( clf.predict(iris.data.toarray()), sp_clf.predict(iris.data)) if k == 'linear': assert_array_almost_equal(clf.coef_, sp_clf.coef_.toarray()) def test_sparse_decision_function(): #Test decision_function #Sanity check, test that decision_function implemented in python #returns the same as the one in libsvm # multi class: svc = svm.SVC(kernel='linear', C=0.1, decision_function_shape='ovo') clf = svc.fit(iris.data, iris.target) dec = safe_sparse_dot(iris.data, clf.coef_.T) + clf.intercept_ assert_array_almost_equal(dec, clf.decision_function(iris.data)) # binary: clf.fit(X, Y) dec = np.dot(X, clf.coef_.T) + clf.intercept_ prediction = clf.predict(X) assert_array_almost_equal(dec.ravel(), clf.decision_function(X)) assert_array_almost_equal( prediction, clf.classes_[(clf.decision_function(X) > 0).astype(np.int).ravel()]) expected = np.array([-1., -0.66, -1., 0.66, 1., 1.]) assert_array_almost_equal(clf.decision_function(X), expected, 2) def test_error(): # Test that it gives proper exception on deficient input # impossible value of C assert_raises(ValueError, svm.SVC(C=-1).fit, X, Y) # impossible value of nu clf = svm.NuSVC(nu=0.0) assert_raises(ValueError, clf.fit, X_sp, Y) Y2 = Y[:-1] # wrong dimensions for labels assert_raises(ValueError, clf.fit, X_sp, Y2) clf = svm.SVC() clf.fit(X_sp, Y) assert_array_equal(clf.predict(T), true_result) def test_linearsvc(): # Similar to test_SVC clf = svm.LinearSVC(random_state=0).fit(X, Y) sp_clf = svm.LinearSVC(random_state=0).fit(X_sp, Y) assert_true(sp_clf.fit_intercept) assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=4) assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=4) assert_array_almost_equal(clf.predict(X), sp_clf.predict(X_sp)) clf.fit(X2, Y2) sp_clf.fit(X2_sp, Y2) assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=4) assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=4) def test_linearsvc_iris(): # Test the sparse LinearSVC with the iris dataset sp_clf = svm.LinearSVC(random_state=0).fit(iris.data, iris.target) clf = svm.LinearSVC(random_state=0).fit(iris.data.toarray(), iris.target) assert_equal(clf.fit_intercept, sp_clf.fit_intercept) assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=1) assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=1) assert_array_almost_equal( clf.predict(iris.data.toarray()), sp_clf.predict(iris.data)) # check decision_function pred = np.argmax(sp_clf.decision_function(iris.data), 1) assert_array_almost_equal(pred, clf.predict(iris.data.toarray())) # sparsify the coefficients on both models and check that they still # produce the same results clf.sparsify() assert_array_equal(pred, clf.predict(iris.data)) sp_clf.sparsify() assert_array_equal(pred, sp_clf.predict(iris.data)) def test_weight(): # Test class weights X_, y_ = make_classification(n_samples=200, n_features=100, weights=[0.833, 0.167], random_state=0) X_ = sparse.csr_matrix(X_) for clf in (linear_model.LogisticRegression(), svm.LinearSVC(random_state=0), svm.SVC()): clf.set_params(class_weight={0: 5}) clf.fit(X_[:180], y_[:180]) y_pred = clf.predict(X_[180:]) assert_true(np.sum(y_pred == y_[180:]) >= 11) def test_sample_weights(): # Test weights on individual samples clf = svm.SVC() clf.fit(X_sp, Y) assert_array_equal(clf.predict([X[2]]), [1.]) sample_weight = [.1] * 3 + [10] * 3 clf.fit(X_sp, Y, sample_weight=sample_weight) assert_array_equal(clf.predict([X[2]]), [2.]) def test_sparse_liblinear_intercept_handling(): # Test that sparse liblinear honours intercept_scaling param test_svm.test_dense_liblinear_intercept_handling(svm.LinearSVC) def test_sparse_oneclasssvm(): """Check that sparse OneClassSVM gives the same result as dense OneClassSVM""" # many class dataset: X_blobs, _ = make_blobs(n_samples=100, centers=10, random_state=0) X_blobs = sparse.csr_matrix(X_blobs) datasets = [[X_sp, None, T], [X2_sp, None, T2], [X_blobs[:80], None, X_blobs[80:]], [iris.data, None, iris.data]] kernels = ["linear", "poly", "rbf", "sigmoid"] for dataset in datasets: for kernel in kernels: clf = svm.OneClassSVM(kernel=kernel, random_state=0) sp_clf = svm.OneClassSVM(kernel=kernel, random_state=0) check_svm_model_equal(clf, sp_clf, *dataset) def test_sparse_realdata(): # Test on a subset from the 20newsgroups dataset. # This catches some bugs if input is not correctly converted into # sparse format or weights are not correctly initialized. data = np.array([0.03771744, 0.1003567, 0.01174647, 0.027069]) indices = np.array([6, 5, 35, 31]) indptr = np.array( [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4]) X = sparse.csr_matrix((data, indices, indptr)) y = np.array( [1., 0., 2., 2., 1., 1., 1., 2., 2., 0., 1., 2., 2., 0., 2., 0., 3., 0., 3., 0., 1., 1., 3., 2., 3., 2., 0., 3., 1., 0., 2., 1., 2., 0., 1., 0., 2., 3., 1., 3., 0., 1., 0., 0., 2., 0., 1., 2., 2., 2., 3., 2., 0., 3., 2., 1., 2., 3., 2., 2., 0., 1., 0., 1., 2., 3., 0., 0., 2., 2., 1., 3., 1., 1., 0., 1., 2., 1., 1., 3.]) clf = svm.SVC(kernel='linear').fit(X.toarray(), y) sp_clf = svm.SVC(kernel='linear').fit(sparse.coo_matrix(X), y) assert_array_equal(clf.support_vectors_, sp_clf.support_vectors_.toarray()) assert_array_equal(clf.dual_coef_, sp_clf.dual_coef_.toarray()) def test_sparse_svc_clone_with_callable_kernel(): # Test that the "dense_fit" is called even though we use sparse input # meaning that everything works fine. a = svm.SVC(C=1, kernel=lambda x, y: x * y.T, probability=True, random_state=0) b = base.clone(a) b.fit(X_sp, Y) pred = b.predict(X_sp) b.predict_proba(X_sp) dense_svm = svm.SVC(C=1, kernel=lambda x, y: np.dot(x, y.T), probability=True, random_state=0) pred_dense = dense_svm.fit(X, Y).predict(X) assert_array_equal(pred_dense, pred) # b.decision_function(X_sp) # XXX : should be supported def test_timeout(): sp = svm.SVC(C=1, kernel=lambda x, y: x * y.T, probability=True, random_state=0, max_iter=1) assert_warns(ConvergenceWarning, sp.fit, X_sp, Y) def test_consistent_proba(): a = svm.SVC(probability=True, max_iter=1, random_state=0) proba_1 = a.fit(X, Y).predict_proba(X) a = svm.SVC(probability=True, max_iter=1, random_state=0) proba_2 = a.fit(X, Y).predict_proba(X) assert_array_almost_equal(proba_1, proba_2)
bsd-3-clause
Lab603/PicEncyclopedias
jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py
8
21806
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementations of different data feeders to provide data for TF trainer.""" # TODO(ipolosukhin): Replace this module with feed-dict queue runners & queues. from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import math import numpy as np import six from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.platform import tf_logging as logging # pylint: disable=g-multiple-import,g-bad-import-order from .pandas_io import HAS_PANDAS, extract_pandas_data, extract_pandas_matrix, extract_pandas_labels from .dask_io import HAS_DASK, extract_dask_data, extract_dask_labels # pylint: enable=g-multiple-import,g-bad-import-order def _get_in_out_shape(x_shape, y_shape, n_classes, batch_size=None): """Returns shape for input and output of the data feeder.""" if batch_size is None: batch_size = x_shape[0] elif batch_size <= 0: raise ValueError('Invalid batch_size %d.' % batch_size) x_shape = list(x_shape[1:]) if len(x_shape) > 1 else [1] input_shape = [batch_size] + x_shape if y_shape is None: return input_shape, None, batch_size y_shape = list(y_shape[1:]) if len(y_shape) > 1 else [] # Skip first dimension if it is 1. if y_shape and y_shape[0] == 1: y_shape = y_shape[1:] if n_classes is not None and n_classes > 1: output_shape = [batch_size] + y_shape + [n_classes] else: output_shape = [batch_size] + y_shape return input_shape, output_shape, batch_size def _data_type_filter(x, y): """Filter data types into acceptable format.""" if HAS_DASK: x = extract_dask_data(x) if y is not None: y = extract_dask_labels(y) if HAS_PANDAS: x = extract_pandas_data(x) if y is not None: y = extract_pandas_labels(y) return x, y def _is_iterable(x): return hasattr(x, 'next') or hasattr(x, '__next__') def setup_train_data_feeder( x, y, n_classes, batch_size=None, shuffle=True, epochs=None): """Create data feeder, to sample inputs from dataset. If `x` and `y` are iterators, use `StreamingDataFeeder`. Args: x: numpy, pandas or Dask matrix or iterable. y: numpy, pandas or Dask array or iterable. n_classes: number of classes. batch_size: size to split data into parts. Must be >= 1. shuffle: Whether to shuffle the inputs. epochs: Number of epochs to run. Returns: DataFeeder object that returns training data. Raises: ValueError: if one of `x` and `y` is iterable and the other is not. """ x, y = _data_type_filter(x, y) if HAS_DASK: # pylint: disable=g-import-not-at-top import dask.dataframe as dd if (isinstance(x, (dd.Series, dd.DataFrame)) and (y is None or isinstance(y, (dd.Series, dd.DataFrame)))): data_feeder_cls = DaskDataFeeder else: data_feeder_cls = DataFeeder else: data_feeder_cls = DataFeeder if _is_iterable(x): if y is not None and not _is_iterable(y): raise ValueError('Both x and y should be iterators for ' 'streaming learning to work.') return StreamingDataFeeder(x, y, n_classes, batch_size) return data_feeder_cls( x, y, n_classes, batch_size, shuffle=shuffle, epochs=epochs) def _batch_data(x, batch_size=None): if (batch_size is not None) and (batch_size <= 0): raise ValueError('Invalid batch_size %d.' % batch_size) chunk = [] for data in x: chunk.append(data) if (batch_size is not None) and (len(chunk) >= batch_size): yield np.matrix(chunk) chunk = [] yield np.matrix(chunk) def setup_predict_data_feeder(x, batch_size=None): """Returns an iterable for feeding into predict step. Args: x: numpy, pandas, Dask array or iterable. batch_size: Size of batches to split data into. If `None`, returns one batch of full size. Returns: List or iterator of parts of data to predict on. Raises: ValueError: if `batch_size` <= 0. """ if HAS_DASK: x = extract_dask_data(x) if HAS_PANDAS: x = extract_pandas_data(x) if _is_iterable(x): return _batch_data(x, batch_size) if len(x.shape) == 1: x = np.reshape(x, (-1, 1)) if batch_size is not None: if batch_size <= 0: raise ValueError('Invalid batch_size %d.' % batch_size) n_batches = int(math.ceil(float(len(x)) / batch_size)) return [x[i * batch_size:(i + 1) * batch_size] for i in xrange(n_batches)] return [x] def setup_processor_data_feeder(x): """Sets up processor iterable. Args: x: numpy, pandas or iterable. Returns: Iterable of data to process. """ if HAS_PANDAS: x = extract_pandas_matrix(x) return x def check_array(array, dtype): """Checks array on dtype and converts it if different. Args: array: Input array. dtype: Expected dtype. Returns: Original array or converted. """ # skip check if array is instance of other classes, e.g. h5py.Dataset # to avoid copying array and loading whole data into memory if isinstance(array, (np.ndarray, list)): array = np.array(array, dtype=dtype, order=None, copy=False) return array def _access(data, iloc): """Accesses an element from collection, using integer location based indexing. Args: data: array-like. The collection to access iloc: `int` or `list` of `int`s. Location(s) to access in `collection` Returns: The element of `a` found at location(s) `iloc`. """ if HAS_PANDAS: import pandas as pd # pylint: disable=g-import-not-at-top if isinstance(data, pd.Series) or isinstance(data, pd.DataFrame): return data.iloc[iloc] return data[iloc] def _check_dtype(dtype): if dtypes.as_dtype(dtype) == dtypes.float64: logging.warn( 'float64 is not supported by many models, consider casting to float32.') return dtype class DataFeeder(object): """Data feeder is an example class to sample data for TF trainer.""" def __init__( self, x, y, n_classes, batch_size=None, shuffle=True, random_state=None, epochs=None): """Initializes a DataFeeder instance. Args: x: Feature Nd numpy matrix of shape `[n_samples, n_features, ...]`. y: Target vector, either floats for regression or class id for classification. If matrix, will consider as a sequence of targets. Can be `None` for unsupervised setting. n_classes: Number of classes, 0 and 1 are considered regression, `None` will pass through the input labels without one-hot conversion. batch_size: Mini-batch size to accumulate. shuffle: Whether to shuffle `x`. random_state: Numpy `RandomState` object to reproduce sampling. epochs: Number of times to iterate over input data before raising `StopIteration` exception. Attributes: x: Input features. y: Input target. n_classes: Number of classes (if `None`, pass through indices without one-hot conversion). batch_size: Mini-batch size to accumulate. input_shape: Shape of the input. output_shape: Shape of the output. input_dtype: DType of input. output_dtype: DType of output. """ self._x = check_array(x, dtype=x.dtype) # self.n_classes is None means we're passing in raw target indices. y_dtype = ( np.int64 if n_classes is not None and n_classes > 1 else np.float32) if n_classes is not None: self._y = (None if y is None else check_array(y, dtype=y_dtype)) elif isinstance(y, list): self._y = np.array(y) else: self._y = y self.n_classes = n_classes self.max_epochs = epochs self.input_shape, self.output_shape, self._batch_size = _get_in_out_shape( self._x.shape, None if self._y is None else self._y.shape, n_classes, batch_size) # Input dtype matches dtype of x. self._input_dtype = _check_dtype(self._x.dtype) # self.n_classes is None means we're passing in raw target indices if n_classes is not None or self._y is None: self._output_dtype = np.float32 else: self._output_dtype = _check_dtype(self._y.dtype) self._shuffle = shuffle self.random_state = np.random.RandomState( 42) if random_state is None else random_state if self._shuffle: self.indices = self.random_state.permutation(self._x.shape[0]) else: self.indices = np.array(range(self._x.shape[0])) self.offset = 0 self.epoch = 0 self._epoch_placeholder = None @property def x(self): return self._x @property def y(self): return self._y @property def shuffle(self): return self._shuffle @property def input_dtype(self): return self._input_dtype @property def output_dtype(self): return self._output_dtype @property def batch_size(self): return self._batch_size def make_epoch_variable(self): """Adds a placeholder variable for the epoch to the graph. Returns: The epoch placeholder. """ self._epoch_placeholder = array_ops.placeholder(dtypes.int32, [1], name='epoch') return self._epoch_placeholder def input_builder(self): """Builds inputs in the graph. Returns: Two placeholders for inputs and outputs. """ input_shape = [None] + self.input_shape[1:] self._input_placeholder = array_ops.placeholder( dtypes.as_dtype(self._input_dtype), input_shape, name='input') if self.output_shape is None: self._output_placeholder = None else: output_shape = [None] + self.output_shape[1:] self._output_placeholder = array_ops.placeholder( dtypes.as_dtype(self._output_dtype), output_shape, name='output') return self._input_placeholder, self._output_placeholder def set_placeholders(self, input_placeholder, output_placeholder): """Sets placeholders for this data feeder. Args: input_placeholder: Placeholder for `x` variable. Should match shape of the examples in the x dataset. output_placeholder: Placeholder for `y` variable. Should match shape of the examples in the y dataset. Can be None. """ self._input_placeholder = input_placeholder self._output_placeholder = output_placeholder def get_feed_params(self): """Function returns a dict with data feed params while training. Returns: A dict with data feed params while training. """ return { 'epoch': self.epoch, 'offset': self.offset, 'batch_size': self._batch_size } def get_feed_dict_fn(self): """Returns a function that samples data into given placeholders. Returns: A function that when called samples a random subset of batch size from x and y. """ def _feed_dict_fn(): """Function that samples data into given placeholders.""" if self.max_epochs is not None and self.epoch + 1 > self.max_epochs: raise StopIteration assert self._input_placeholder is not None feed_dict = {} if self._epoch_placeholder is not None: feed_dict[self._epoch_placeholder.name] = [self.epoch] # Take next batch of indices. end = min(self._x.shape[0], self.offset + self._batch_size) batch_indices = self.indices[self.offset:end] # Assign input features from random indices. inp = ( np.array(_access(self._x, batch_indices)).reshape( (batch_indices.shape[0], 1)) if len(self._x.shape) == 1 else _access(self._x, batch_indices)) feed_dict[self._input_placeholder.name] = inp # move offset and reset it if necessary self.offset += self._batch_size if self.offset >= self._x.shape[0]: self.indices = self.random_state.permutation(self._x.shape[0]) self.offset = 0 self.epoch += 1 # return early if there are no labels if self._output_placeholder is None: return feed_dict # assign labels from random indices self.output_shape[0] = batch_indices.shape[0] out = np.zeros(self.output_shape, dtype=self._output_dtype) for i in xrange(out.shape[0]): sample = batch_indices[i] # self.n_classes is None means we're passing in raw target indices if self.n_classes is None: out[i] = _access(self._y, sample) else: if self.n_classes > 1: if len(self.output_shape) == 2: out.itemset((i, int(_access(self._y, sample))), 1.0) else: for idx, value in enumerate(_access(self._y, sample)): out.itemset(tuple([i, idx, value]), 1.0) else: out[i] = _access(self._y, sample) feed_dict[self._output_placeholder.name] = out return feed_dict return _feed_dict_fn class StreamingDataFeeder(DataFeeder): """Data feeder for TF trainer that reads data from iterator. Streaming data feeder allows to read data as it comes it from disk or somewhere else. It's custom to have this iterators rotate infinetly over the dataset, to allow control of how much to learn on the trainer side. """ def __init__(self, x, y, n_classes, batch_size): """Initializes a StreamingDataFeeder instance. Args: x: iterator that returns for each element, returns features. y: iterator that returns for each element, returns 1 or many classes / regression values. n_classes: indicator of how many classes the target has. batch_size: Mini batch size to accumulate. Attributes: x: input features. y: input target. n_classes: number of classes. batch_size: mini batch size to accumulate. input_shape: shape of the input. output_shape: shape of the output. input_dtype: dtype of input. output_dtype: dtype of output. """ # pylint: disable=invalid-name,super-init-not-called x_first_el = six.next(x) self._x = itertools.chain([x_first_el], x) if y is not None: y_first_el = six.next(y) self._y = itertools.chain([y_first_el], y) else: y_first_el = None self._y = None self.n_classes = n_classes self.input_shape, self.output_shape, self._batch_size = _get_in_out_shape( [1] + list(x_first_el.shape), [1] + list(y_first_el.shape) if y is not None else None, n_classes, batch_size) self._input_dtype = _check_dtype(x_first_el.dtype) # Output types are floats, due to both softmaxes and regression req. if n_classes is not None and n_classes > 0: self._output_dtype = np.float32 elif y is not None: if isinstance(y_first_el, list) or isinstance(y_first_el, np.ndarray): self._output_dtype = _check_dtype(np.dtype(type(y_first_el[0]))) else: self._output_dtype = _check_dtype(np.dtype(type(y_first_el))) def get_feed_params(self): """Function returns a dict with data feed params while training. Returns: A dict with data feed params while training. """ return {'batch_size': self._batch_size} def get_feed_dict_fn(self): """Returns a function, that will sample data and provide it to placeholders. Returns: A function that when called samples a random subset of batch size from x and y. """ self.stopped = False def _feed_dict_fn(): """Samples data and provides it to placeholders. Returns: Dict of input and output tensors. """ if self.stopped: raise StopIteration inp = np.zeros(self.input_shape, dtype=self._input_dtype) if self._y is not None: out = np.zeros(self.output_shape, dtype=self._output_dtype) for i in xrange(self._batch_size): # Add handling when queue ends. try: inp[i, :] = six.next(self._x) except StopIteration: self.stopped = True inp = inp[:i, :] if self._y is not None: out = out[:i] break if self._y is not None: y = six.next(self._y) if self.n_classes is not None and self.n_classes > 1: if len(self.output_shape) == 2: out.itemset((i, y), 1.0) else: for idx, value in enumerate(y): out.itemset(tuple([i, idx, value]), 1.0) else: out[i] = y if self._y is None: return {self._input_placeholder.name: inp} return {self._input_placeholder.name: inp, self._output_placeholder.name: out} return _feed_dict_fn class DaskDataFeeder(object): """Data feeder for that reads data from dask.Series and dask.DataFrame. Numpy arrays can be serialized to disk and it's possible to do random seeks into them. DaskDataFeeder will remove requirement to have full dataset in the memory and still do random seeks for sampling of batches. """ def __init__(self, x, y, n_classes, batch_size, shuffle=True, random_state=None, epochs=None): """Initializes a DaskDataFeeder instance. Args: x: iterator that returns for each element, returns features. y: iterator that returns for each element, returns 1 or many classes / regression values. n_classes: indicator of how many classes the target has. batch_size: Mini batch size to accumulate. shuffle: Whether to shuffle the inputs. random_state: random state for RNG. Note that it will mutate so use a int value for this if you want consistent sized batches. epochs: Number of epochs to run. Attributes: x: input features. y: input target. n_classes: number of classes. batch_size: mini batch size to accumulate. input_shape: shape of the input. output_shape: shape of the output. input_dtype: dtype of input. output_dtype: dtype of output. """ # pylint: disable=invalid-name,super-init-not-called import dask.dataframe as dd # pylint: disable=g-import-not-at-top # TODO(terrytangyuan): check x and y dtypes in dask_io like pandas self._x = x self._y = y # save column names self._x_columns = list(x.columns) if isinstance(y.columns[0], str): self._y_columns = list(y.columns) else: # deal with cases where two DFs have overlapped default numeric colnames self._y_columns = len(self._x_columns) + 1 self._y = self._y.rename(columns={y.columns[0]: self._y_columns}) # TODO(terrytangyuan): deal with unsupervised cases # combine into a data frame self.df = dd.multi.concat([self._x, self._y], axis=1) self.n_classes = n_classes x_count = x.count().compute()[0] x_shape = (x_count, len(self._x.columns)) y_shape = (x_count, len(self._y.columns)) # TODO(terrytangyuan): Add support for shuffle and epochs. self._shuffle = shuffle self.epochs = epochs self.input_shape, self.output_shape, self._batch_size = _get_in_out_shape( x_shape, y_shape, n_classes, batch_size) self.sample_fraction = self._batch_size / float(x_count) self._input_dtype = _check_dtype(self._x.dtypes[0]) self._output_dtype = _check_dtype(self._y.dtypes[self._y_columns]) if random_state is None: self.random_state = 66 else: self.random_state = random_state def get_feed_params(self): """Function returns a dict with data feed params while training. Returns: A dict with data feed params while training. """ return {'batch_size': self._batch_size} def get_feed_dict_fn(self, input_placeholder, output_placeholder): """Returns a function, that will sample data and provide it to placeholders. Args: input_placeholder: tf.Placeholder for input features mini batch. output_placeholder: tf.Placeholder for output targets. Returns: A function that when called samples a random subset of batch size from x and y. """ def _feed_dict_fn(): """Samples data and provides it to placeholders.""" # TODO(ipolosukhin): option for with/without replacement (dev version of # dask) sample = self.df.random_split( [self.sample_fraction, 1 - self.sample_fraction], random_state=self.random_state) inp = extract_pandas_matrix(sample[0][self._x_columns].compute()).tolist() out = extract_pandas_matrix(sample[0][self._y_columns].compute()) # convert to correct dtype inp = np.array(inp, dtype=self._input_dtype) # one-hot encode out for each class for cross entropy loss if HAS_PANDAS: import pandas as pd # pylint: disable=g-import-not-at-top if not isinstance(out, pd.Series): out = out.flatten() out_max = self._y.max().compute().values[0] encoded_out = np.zeros((out.size, out_max + 1), dtype=self._output_dtype) encoded_out[np.arange(out.size), out] = 1 return {input_placeholder.name: inp, output_placeholder.name: encoded_out} return _feed_dict_fn
mit
BigDataforYou/movie_recommendation_workshop_1
big_data_4_you_demo_1/venv/lib/python2.7/site-packages/pandas/tests/test_util.py
1
11190
# -*- coding: utf-8 -*- import nose from collections import OrderedDict from pandas.util._move import move_into_mutable_buffer, BadMove from pandas.util.decorators import deprecate_kwarg from pandas.util.validators import (validate_args, validate_kwargs, validate_args_and_kwargs) import pandas.util.testing as tm class TestDecorators(tm.TestCase): def setUp(self): @deprecate_kwarg('old', 'new') def _f1(new=False): return new @deprecate_kwarg('old', 'new', {'yes': True, 'no': False}) def _f2(new=False): return new @deprecate_kwarg('old', 'new', lambda x: x + 1) def _f3(new=0): return new self.f1 = _f1 self.f2 = _f2 self.f3 = _f3 def test_deprecate_kwarg(self): x = 78 with tm.assert_produces_warning(FutureWarning): result = self.f1(old=x) self.assertIs(result, x) with tm.assert_produces_warning(None): self.f1(new=x) def test_dict_deprecate_kwarg(self): x = 'yes' with tm.assert_produces_warning(FutureWarning): result = self.f2(old=x) self.assertEqual(result, True) def test_missing_deprecate_kwarg(self): x = 'bogus' with tm.assert_produces_warning(FutureWarning): result = self.f2(old=x) self.assertEqual(result, 'bogus') def test_callable_deprecate_kwarg(self): x = 5 with tm.assert_produces_warning(FutureWarning): result = self.f3(old=x) self.assertEqual(result, x + 1) with tm.assertRaises(TypeError): self.f3(old='hello') def test_bad_deprecate_kwarg(self): with tm.assertRaises(TypeError): @deprecate_kwarg('old', 'new', 0) def f4(new=None): pass def test_rands(): r = tm.rands(10) assert(len(r) == 10) def test_rands_array(): arr = tm.rands_array(5, size=10) assert(arr.shape == (10,)) assert(len(arr[0]) == 5) arr = tm.rands_array(7, size=(10, 10)) assert(arr.shape == (10, 10)) assert(len(arr[1, 1]) == 7) class TestValidateArgs(tm.TestCase): fname = 'func' def test_bad_min_fname_arg_count(self): msg = "'max_fname_arg_count' must be non-negative" with tm.assertRaisesRegexp(ValueError, msg): validate_args(self.fname, (None,), -1, 'foo') def test_bad_arg_length_max_value_single(self): args = (None, None) compat_args = ('foo',) min_fname_arg_count = 0 max_length = len(compat_args) + min_fname_arg_count actual_length = len(args) + min_fname_arg_count msg = ("{fname}\(\) takes at most {max_length} " "argument \({actual_length} given\)" .format(fname=self.fname, max_length=max_length, actual_length=actual_length)) with tm.assertRaisesRegexp(TypeError, msg): validate_args(self.fname, args, min_fname_arg_count, compat_args) def test_bad_arg_length_max_value_multiple(self): args = (None, None) compat_args = dict(foo=None) min_fname_arg_count = 2 max_length = len(compat_args) + min_fname_arg_count actual_length = len(args) + min_fname_arg_count msg = ("{fname}\(\) takes at most {max_length} " "arguments \({actual_length} given\)" .format(fname=self.fname, max_length=max_length, actual_length=actual_length)) with tm.assertRaisesRegexp(TypeError, msg): validate_args(self.fname, args, min_fname_arg_count, compat_args) def test_not_all_defaults(self): bad_arg = 'foo' msg = ("the '{arg}' parameter is not supported " "in the pandas implementation of {func}\(\)". format(arg=bad_arg, func=self.fname)) compat_args = OrderedDict() compat_args['foo'] = 2 compat_args['bar'] = -1 compat_args['baz'] = 3 arg_vals = (1, -1, 3) for i in range(1, 3): with tm.assertRaisesRegexp(ValueError, msg): validate_args(self.fname, arg_vals[:i], 2, compat_args) def test_validation(self): # No exceptions should be thrown validate_args(self.fname, (None,), 2, dict(out=None)) compat_args = OrderedDict() compat_args['axis'] = 1 compat_args['out'] = None validate_args(self.fname, (1, None), 2, compat_args) class TestValidateKwargs(tm.TestCase): fname = 'func' def test_bad_kwarg(self): goodarg = 'f' badarg = goodarg + 'o' compat_args = OrderedDict() compat_args[goodarg] = 'foo' compat_args[badarg + 'o'] = 'bar' kwargs = {goodarg: 'foo', badarg: 'bar'} msg = ("{fname}\(\) got an unexpected " "keyword argument '{arg}'".format( fname=self.fname, arg=badarg)) with tm.assertRaisesRegexp(TypeError, msg): validate_kwargs(self.fname, kwargs, compat_args) def test_not_all_none(self): bad_arg = 'foo' msg = ("the '{arg}' parameter is not supported " "in the pandas implementation of {func}\(\)". format(arg=bad_arg, func=self.fname)) compat_args = OrderedDict() compat_args['foo'] = 1 compat_args['bar'] = 's' compat_args['baz'] = None kwarg_keys = ('foo', 'bar', 'baz') kwarg_vals = (2, 's', None) for i in range(1, 3): kwargs = dict(zip(kwarg_keys[:i], kwarg_vals[:i])) with tm.assertRaisesRegexp(ValueError, msg): validate_kwargs(self.fname, kwargs, compat_args) def test_validation(self): # No exceptions should be thrown compat_args = OrderedDict() compat_args['f'] = None compat_args['b'] = 1 compat_args['ba'] = 's' kwargs = dict(f=None, b=1) validate_kwargs(self.fname, kwargs, compat_args) class TestValidateKwargsAndArgs(tm.TestCase): fname = 'func' def test_invalid_total_length_max_length_one(self): compat_args = ('foo',) kwargs = {'foo': 'FOO'} args = ('FoO', 'BaZ') min_fname_arg_count = 0 max_length = len(compat_args) + min_fname_arg_count actual_length = len(kwargs) + len(args) + min_fname_arg_count msg = ("{fname}\(\) takes at most {max_length} " "argument \({actual_length} given\)" .format(fname=self.fname, max_length=max_length, actual_length=actual_length)) with tm.assertRaisesRegexp(TypeError, msg): validate_args_and_kwargs(self.fname, args, kwargs, min_fname_arg_count, compat_args) def test_invalid_total_length_max_length_multiple(self): compat_args = ('foo', 'bar', 'baz') kwargs = {'foo': 'FOO', 'bar': 'BAR'} args = ('FoO', 'BaZ') min_fname_arg_count = 2 max_length = len(compat_args) + min_fname_arg_count actual_length = len(kwargs) + len(args) + min_fname_arg_count msg = ("{fname}\(\) takes at most {max_length} " "arguments \({actual_length} given\)" .format(fname=self.fname, max_length=max_length, actual_length=actual_length)) with tm.assertRaisesRegexp(TypeError, msg): validate_args_and_kwargs(self.fname, args, kwargs, min_fname_arg_count, compat_args) def test_no_args_with_kwargs(self): bad_arg = 'bar' min_fname_arg_count = 2 compat_args = OrderedDict() compat_args['foo'] = -5 compat_args[bad_arg] = 1 msg = ("the '{arg}' parameter is not supported " "in the pandas implementation of {func}\(\)". format(arg=bad_arg, func=self.fname)) args = () kwargs = {'foo': -5, bad_arg: 2} tm.assertRaisesRegexp(ValueError, msg, validate_args_and_kwargs, self.fname, args, kwargs, min_fname_arg_count, compat_args) args = (-5, 2) kwargs = {} tm.assertRaisesRegexp(ValueError, msg, validate_args_and_kwargs, self.fname, args, kwargs, min_fname_arg_count, compat_args) def test_duplicate_argument(self): min_fname_arg_count = 2 compat_args = OrderedDict() compat_args['foo'] = None compat_args['bar'] = None compat_args['baz'] = None kwargs = {'foo': None, 'bar': None} args = (None,) # duplicate value for 'foo' msg = ("{fname}\(\) got multiple values for keyword " "argument '{arg}'".format(fname=self.fname, arg='foo')) with tm.assertRaisesRegexp(TypeError, msg): validate_args_and_kwargs(self.fname, args, kwargs, min_fname_arg_count, compat_args) def test_validation(self): # No exceptions should be thrown compat_args = OrderedDict() compat_args['foo'] = 1 compat_args['bar'] = None compat_args['baz'] = -2 kwargs = {'baz': -2} args = (1, None) min_fname_arg_count = 2 validate_args_and_kwargs(self.fname, args, kwargs, min_fname_arg_count, compat_args) class TestMove(tm.TestCase): def test_more_than_one_ref(self): """Test case for when we try to use ``move_into_mutable_buffer`` when the object being moved has other references. """ b = b'testing' with tm.assertRaises(BadMove) as e: def handle_success(type_, value, tb): self.assertIs(value.args[0], b) return type(e).handle_success(e, type_, value, tb) # super e.handle_success = handle_success move_into_mutable_buffer(b) def test_exactly_one_ref(self): """Test case for when the object being moved has exactly one reference. """ b = b'testing' # We need to pass an expression on the stack to ensure that there are # not extra references hanging around. We cannot rewrite this test as # buf = b[:-3] # as_stolen_buf = move_into_mutable_buffer(buf) # because then we would have more than one reference to buf. as_stolen_buf = move_into_mutable_buffer(b[:-3]) # materialize as bytearray to show that it is mutable self.assertEqual(bytearray(as_stolen_buf), b'test') if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
mit
cswiercz/sympy
sympy/interactive/printing.py
31
15830
"""Tools for setting up printing in interactive sessions. """ from __future__ import print_function, division import sys from distutils.version import LooseVersion as V from io import BytesIO from sympy import latex as default_latex from sympy import preview from sympy.core.compatibility import integer_types from sympy.utilities.misc import debug def _init_python_printing(stringify_func): """Setup printing in Python interactive session. """ import sys from sympy.core.compatibility import builtins def _displayhook(arg): """Python's pretty-printer display hook. This function was adapted from: http://www.python.org/dev/peps/pep-0217/ """ if arg is not None: builtins._ = None print(stringify_func(arg)) builtins._ = arg sys.displayhook = _displayhook def _init_ipython_printing(ip, stringify_func, use_latex, euler, forecolor, backcolor, fontsize, latex_mode, print_builtin, latex_printer): """Setup printing in IPython interactive session. """ try: from IPython.lib.latextools import latex_to_png except ImportError: pass preamble = "\\documentclass[%s]{article}\n" \ "\\pagestyle{empty}\n" \ "\\usepackage{amsmath,amsfonts}%s\\begin{document}" if euler: addpackages = '\\usepackage{euler}' else: addpackages = '' preamble = preamble % (fontsize, addpackages) imagesize = 'tight' offset = "0cm,0cm" resolution = 150 dvi = r"-T %s -D %d -bg %s -fg %s -O %s" % ( imagesize, resolution, backcolor, forecolor, offset) dvioptions = dvi.split() debug("init_printing: DVIOPTIONS:", dvioptions) debug("init_printing: PREAMBLE:", preamble) latex = latex_printer or default_latex def _print_plain(arg, p, cycle): """caller for pretty, for use in IPython 0.11""" if _can_print_latex(arg): p.text(stringify_func(arg)) else: p.text(IPython.lib.pretty.pretty(arg)) def _preview_wrapper(o): exprbuffer = BytesIO() try: preview(o, output='png', viewer='BytesIO', outputbuffer=exprbuffer, preamble=preamble, dvioptions=dvioptions) except Exception as e: # IPython swallows exceptions debug("png printing:", "_preview_wrapper exception raised:", repr(e)) raise return exprbuffer.getvalue() def _matplotlib_wrapper(o): # mathtext does not understand certain latex flags, so we try to # replace them with suitable subs o = o.replace(r'\operatorname', '') o = o.replace(r'\overline', r'\bar') return latex_to_png(o) def _can_print_latex(o): """Return True if type o can be printed with LaTeX. If o is a container type, this is True if and only if every element of o can be printed with LaTeX. """ from sympy import Basic from sympy.matrices import MatrixBase from sympy.physics.vector import Vector, Dyadic if isinstance(o, (list, tuple, set, frozenset)): return all(_can_print_latex(i) for i in o) elif isinstance(o, dict): return all(_can_print_latex(i) and _can_print_latex(o[i]) for i in o) elif isinstance(o, bool): return False # TODO : Investigate if "elif hasattr(o, '_latex')" is more useful # to use here, than these explicit imports. elif isinstance(o, (Basic, MatrixBase, Vector, Dyadic)): return True elif isinstance(o, (float, integer_types)) and print_builtin: return True return False def _print_latex_png(o): """ A function that returns a png rendered by an external latex distribution, falling back to matplotlib rendering """ if _can_print_latex(o): s = latex(o, mode=latex_mode) try: return _preview_wrapper(s) except RuntimeError: if latex_mode != 'inline': s = latex(o, mode='inline') return _matplotlib_wrapper(s) def _print_latex_matplotlib(o): """ A function that returns a png rendered by mathtext """ if _can_print_latex(o): s = latex(o, mode='inline') try: return _matplotlib_wrapper(s) except Exception: # Matplotlib.mathtext cannot render some things (like # matrices) return None def _print_latex_text(o): """ A function to generate the latex representation of sympy expressions. """ if _can_print_latex(o): s = latex(o, mode='plain') s = s.replace(r'\dag', r'\dagger') s = s.strip('$') return '$$%s$$' % s def _result_display(self, arg): """IPython's pretty-printer display hook, for use in IPython 0.10 This function was adapted from: ipython/IPython/hooks.py:155 """ if self.rc.pprint: out = stringify_func(arg) if '\n' in out: print print(out) else: print(repr(arg)) import IPython if V(IPython.__version__) >= '0.11': from sympy.core.basic import Basic from sympy.matrices.matrices import MatrixBase from sympy.physics.vector import Vector, Dyadic printable_types = [Basic, MatrixBase, float, tuple, list, set, frozenset, dict, Vector, Dyadic] + list(integer_types) plaintext_formatter = ip.display_formatter.formatters['text/plain'] for cls in printable_types: plaintext_formatter.for_type(cls, _print_plain) png_formatter = ip.display_formatter.formatters['image/png'] if use_latex in (True, 'png'): debug("init_printing: using png formatter") for cls in printable_types: png_formatter.for_type(cls, _print_latex_png) elif use_latex == 'matplotlib': debug("init_printing: using matplotlib formatter") for cls in printable_types: png_formatter.for_type(cls, _print_latex_matplotlib) else: debug("init_printing: not using any png formatter") for cls in printable_types: # Better way to set this, but currently does not work in IPython #png_formatter.for_type(cls, None) if cls in png_formatter.type_printers: png_formatter.type_printers.pop(cls) latex_formatter = ip.display_formatter.formatters['text/latex'] if use_latex in (True, 'mathjax'): debug("init_printing: using mathjax formatter") for cls in printable_types: latex_formatter.for_type(cls, _print_latex_text) else: debug("init_printing: not using text/latex formatter") for cls in printable_types: # Better way to set this, but currently does not work in IPython #latex_formatter.for_type(cls, None) if cls in latex_formatter.type_printers: latex_formatter.type_printers.pop(cls) else: ip.set_hook('result_display', _result_display) def _is_ipython(shell): """Is a shell instance an IPython shell?""" # shortcut, so we don't import IPython if we don't have to if 'IPython' not in sys.modules: return False try: from IPython.core.interactiveshell import InteractiveShell except ImportError: # IPython < 0.11 try: from IPython.iplib import InteractiveShell except ImportError: # Reaching this points means IPython has changed in a backward-incompatible way # that we don't know about. Warn? return False return isinstance(shell, InteractiveShell) def init_printing(pretty_print=True, order=None, use_unicode=None, use_latex=None, wrap_line=None, num_columns=None, no_global=False, ip=None, euler=False, forecolor='Black', backcolor='Transparent', fontsize='10pt', latex_mode='equation*', print_builtin=True, str_printer=None, pretty_printer=None, latex_printer=None): """ Initializes pretty-printer depending on the environment. Parameters ========== pretty_print: boolean If True, use pretty_print to stringify or the provided pretty printer; if False, use sstrrepr to stringify or the provided string printer. order: string or None There are a few different settings for this parameter: lex (default), which is lexographic order; grlex, which is graded lexographic order; grevlex, which is reversed graded lexographic order; old, which is used for compatibility reasons and for long expressions; None, which sets it to lex. use_unicode: boolean or None If True, use unicode characters; if False, do not use unicode characters. use_latex: string, boolean, or None If True, use default latex rendering in GUI interfaces (png and mathjax); if False, do not use latex rendering; if 'png', enable latex rendering with an external latex compiler, falling back to matplotlib if external compilation fails; if 'matplotlib', enable latex rendering with matplotlib; if 'mathjax', enable latex text generation, for example MathJax rendering in IPython notebook or text rendering in LaTeX documents wrap_line: boolean If True, lines will wrap at the end; if False, they will not wrap but continue as one line. This is only relevant if `pretty_print` is True. num_columns: int or None If int, number of columns before wrapping is set to num_columns; if None, number of columns before wrapping is set to terminal width. This is only relevant if `pretty_print` is True. no_global: boolean If True, the settings become system wide; if False, use just for this console/session. ip: An interactive console This can either be an instance of IPython, or a class that derives from code.InteractiveConsole. euler: boolean, optional, default=False Loads the euler package in the LaTeX preamble for handwritten style fonts (http://www.ctan.org/pkg/euler). forecolor: string, optional, default='Black' DVI setting for foreground color. backcolor: string, optional, default='Transparent' DVI setting for background color. fontsize: string, optional, default='10pt' A font size to pass to the LaTeX documentclass function in the preamble. latex_mode: string, optional, default='equation*' The mode used in the LaTeX printer. Can be one of: {'inline'|'plain'|'equation'|'equation*'}. print_builtin: boolean, optional, default=True If true then floats and integers will be printed. If false the printer will only print SymPy types. str_printer: function, optional, default=None A custom string printer function. This should mimic sympy.printing.sstrrepr(). pretty_printer: function, optional, default=None A custom pretty printer. This should mimic sympy.printing.pretty(). latex_printer: function, optional, default=None A custom LaTeX printer. This should mimic sympy.printing.latex() This should mimic sympy.printing.latex(). Examples ======== >>> from sympy.interactive import init_printing >>> from sympy import Symbol, sqrt >>> from sympy.abc import x, y >>> sqrt(5) sqrt(5) >>> init_printing(pretty_print=True) # doctest: +SKIP >>> sqrt(5) # doctest: +SKIP ___ \/ 5 >>> theta = Symbol('theta') # doctest: +SKIP >>> init_printing(use_unicode=True) # doctest: +SKIP >>> theta # doctest: +SKIP \u03b8 >>> init_printing(use_unicode=False) # doctest: +SKIP >>> theta # doctest: +SKIP theta >>> init_printing(order='lex') # doctest: +SKIP >>> str(y + x + y**2 + x**2) # doctest: +SKIP x**2 + x + y**2 + y >>> init_printing(order='grlex') # doctest: +SKIP >>> str(y + x + y**2 + x**2) # doctest: +SKIP x**2 + x + y**2 + y >>> init_printing(order='grevlex') # doctest: +SKIP >>> str(y * x**2 + x * y**2) # doctest: +SKIP x**2*y + x*y**2 >>> init_printing(order='old') # doctest: +SKIP >>> str(x**2 + y**2 + x + y) # doctest: +SKIP x**2 + x + y**2 + y >>> init_printing(num_columns=10) # doctest: +SKIP >>> x**2 + x + y**2 + y # doctest: +SKIP x + y + x**2 + y**2 """ import sys from sympy.printing.printer import Printer if pretty_print: if pretty_printer is not None: stringify_func = pretty_printer else: from sympy.printing import pretty as stringify_func else: if str_printer is not None: stringify_func = str_printer else: from sympy.printing import sstrrepr as stringify_func # Even if ip is not passed, double check that not in IPython shell in_ipython = False if ip is None: try: ip = get_ipython() except NameError: pass else: in_ipython = (ip is not None) if ip and not in_ipython: in_ipython = _is_ipython(ip) if in_ipython and pretty_print: try: import IPython # IPython 1.0 deprecates the frontend module, so we import directly # from the terminal module to prevent a deprecation message from being # shown. if V(IPython.__version__) >= '1.0': from IPython.terminal.interactiveshell import TerminalInteractiveShell else: from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell from code import InteractiveConsole except ImportError: pass else: # This will be True if we are in the qtconsole or notebook if not isinstance(ip, (InteractiveConsole, TerminalInteractiveShell)) \ and 'ipython-console' not in ''.join(sys.argv): if use_unicode is None: debug("init_printing: Setting use_unicode to True") use_unicode = True if use_latex is None: debug("init_printing: Setting use_latex to True") use_latex = True if not no_global: Printer.set_global_settings(order=order, use_unicode=use_unicode, wrap_line=wrap_line, num_columns=num_columns) else: _stringify_func = stringify_func if pretty_print: stringify_func = lambda expr: \ _stringify_func(expr, order=order, use_unicode=use_unicode, wrap_line=wrap_line, num_columns=num_columns) else: stringify_func = lambda expr: _stringify_func(expr, order=order) if in_ipython: _init_ipython_printing(ip, stringify_func, use_latex, euler, forecolor, backcolor, fontsize, latex_mode, print_builtin, latex_printer) else: _init_python_printing(stringify_func)
bsd-3-clause
lvniqi/tianchi_power
code/preprocess.py
1
32964
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat May 13 17:36:18 2017 @author: boweiy """ from sklearn.model_selection import train_test_split import pandas as pd import numpy as np import os import xgboost as xgb from multiprocessing import Pool as m_Pool from sklearn import preprocessing from sklearn.cluster import MiniBatchKMeans, KMeans from sklearn.cluster import DBSCAN from sklearn.decomposition import PCA DATASET_PATH = './dataset/Tianchi_power.csv' DATASET_SEPT_PATH = './dataset/Tianchi_power_sept.csv' FEATURE_PATH = './features/' DAY_FEATURE_PATH = FEATURE_PATH+'day_model/' DAY_FEATURE_ALL_PATH = FEATURE_PATH+'day_model_all/' MONTH_FEATURE_PATH = FEATURE_PATH+'month_model/' HOLIDAY_MONTH_FEATURE_PATH = FEATURE_PATH+'holiday_month_model/' PROPHET_HOLIDAY_MONTH_FEATURE_PATH = FEATURE_PATH+'prophet_holiday_month_model/' HOLIDAY_PATH = FEATURE_PATH+'holiday/holi_feat_10.csv' FEST_PATH = FEATURE_PATH+'holiday/fest_feat_10.csv' WEATHER_PATH = FEATURE_PATH+'weather/weather.csv' PROPHET_PATH = FEATURE_PATH+'prophet/' USER_TYPE_PATH = FEATURE_PATH+'user_type/user_type.csv' HISTORY_PATH = FEATURE_PATH+'history/' WEATHER_COLUMNS = ['Temp','bad_weather','ssd'] #PROPHET_COLUMNS = ['trend','weekly','yearly','seasonal'] #PROPHET_COLUMNS = ['weekly','yearly'] PROPHET_COLUMNS = ['trend','yearly'] HISTORY_COLUMNS = ['weekly_median','weekly_max','weekly_min',\ 'weekly2_median','monthly_median'] MODELS_PATH = './models/' DAY_MODELS_PATH = MODELS_PATH +'day_model/' DAY_FILTERED_MODELS_PATH = MODELS_PATH +'day_filtered_model/' PROPHET_MODELS_PATH = MODELS_PATH +'prophet_model/' PROPHET_FILTERED_MODELS_PATH = MODELS_PATH +'prophet_filtered_model/' PROPHET_EXP_MODELS_PATH = MODELS_PATH +'prophet_exp_model/' PROPHET_EXP__FILTERED_MODELS_PATH = MODELS_PATH +'prophet_exp_filtered_model/' EXTERA_HOLI_PROPHET_MODELS_PATH = MODELS_PATH +'extera_holi_prophet_model/' EXTERA_HOLI_PROPHET_FILTERED_MODELS_PATH = MODELS_PATH +'extera_holi_prophet_filtered_model/' EXTERA_HOLI_PROPHET_F2_MODELS_PATH = MODELS_PATH +'extera_holi_prophet_f2_model/' EXTERA_HOLI_PROPHET_EXP_MODELS_PATH = MODELS_PATH +'extera_holi_prophet_exp_model/' EXTERA_HOLI_PROPHET_EXP_FILTERED_MODELS_PATH = MODELS_PATH +'extera_holi_prophet_exp_filtered_model/' EXTERA_HOLI_PROPHET_EXP_F2_MODELS_PATH = MODELS_PATH +'extera_holi_prophet_exp_f2_model/' PROPHET_14DAY_MODELS_PATH = MODELS_PATH +'prophet_14_model/' PROPHET_14DAY_FILTERED_MODELS_PATH = MODELS_PATH +'prophet_14_filtered_model/' PROPHET_14DAY_F2_MODELS_PATH = MODELS_PATH +'prophet_14_f2_model/' PROPHET_14DAY_EXP_MODELS_PATH = MODELS_PATH +'prophet_14_exp_model/' PROPHET_14DAY_EXP_FILTERED_MODELS_PATH = MODELS_PATH +'prophet_14_exp_filtered_model/' PROPHET_14DAY_EXP_F2_MODELS_PATH = MODELS_PATH +'prophet_14_exp_f2_model/' PROPHET_7DAY_MODELS_PATH = MODELS_PATH +'prophet_7_model/' PROPHET_7DAY_FILTERED_MODELS_PATH = MODELS_PATH +'prophet_7_filtered_model/' PROPHET_7DAY_F2_MODELS_PATH = MODELS_PATH +'prophet_7_f2_model/' PROPHET_7DAY_EXP_MODELS_PATH = MODELS_PATH +'prophet_7_exp_model/' PROPHET_7DAY_EXP_FILTERED_MODELS_PATH = MODELS_PATH +'prophet_7_exp_filtered_model/' PROPHET_7DAY_EXP_F2_MODELS_PATH = MODELS_PATH +'prophet_7_exp_f2_model/' TINY_7_MODELS_PATH = MODELS_PATH +'tiny_7_model/' TINY_7_FILTERED_MODELS_PATH = MODELS_PATH +'tiny_7_filtered_model/' TINY_7_F2_MODELS_PATH = MODELS_PATH +'tiny_7_f2_model/' TINY_7_EXP_MODELS_PATH = MODELS_PATH +'tiny_7_exp_model/' TINY_7_EXP_FILTERED_MODELS_PATH = MODELS_PATH +'tiny_7_exp_filtered_model/' TINY_7_EXP_F2_MODELS_PATH = MODELS_PATH +'tiny_7_exp_f2_model/' #%% np_tiny7 NP_TINY_7_MODELS_PATH = MODELS_PATH +'np_tiny_7_model/' NP_TINY_7_FILTERED_MODELS_PATH = MODELS_PATH +'np_tiny_7_filtered_model/' NP_TINY_7_F2_MODELS_PATH = MODELS_PATH +'np_tiny_7_f2_model/' NP_TINY_7_EXP_MODELS_PATH = MODELS_PATH +'np_tiny_7_exp_model/' NP_TINY_7_EXP_FILTERED_MODELS_PATH = MODELS_PATH +'np_tiny_7_exp_filtered_model/' NP_TINY_7_EXP_F2_MODELS_PATH = MODELS_PATH +'np_tiny_7_exp_f2_model/' #%% np_tiny7 PRE_PREDICT_MODELS_PATH = MODELS_PATH +'pre_predict_model/' PRE_PREDICT_FILTERED_MODELS_PATH = MODELS_PATH +'pre_predict_filtered_model/' PREDICT_MODELS_PATH = MODELS_PATH +'predict_model/' USER_MODELS_PATH = MODELS_PATH +'user_model/' USER_EXP_MODELS_PATH = MODELS_PATH +'user_exp_model/' _empty_user_df = pd.Series.from_csv('./dataset/empty_user.csv') _user_type_df = pd.Series.from_csv(USER_TYPE_PATH) _power_range_df = pd.Series.from_csv('./dataset/power_range.csv').apply(np.log) _exp_exp_ratio_df = pd.Series.from_csv('./dataset/exp_noexp_ratio.csv') #%% get method def get_dataset(): train_set = pd.DataFrame.from_csv(DATASET_PATH) eval_set = pd.DataFrame.from_csv(DATASET_SEPT_PATH) return pd.concat([train_set,eval_set]) def get_user_id_list(): return list(_empty_user_df.index) def get_empty_user_ids(): return list(_empty_user_df[_empty_user_df ==True].index) def get_full_user_ids(): return list(_empty_user_df[_empty_user_df ==False].index) def get_big_user_ids(th = 7): return list(_power_range_df[get_full_user_ids()][_power_range_df>th].index) def get_small_user_ids(th = 7): return list(_power_range_df[get_full_user_ids()][_power_range_df<=th].index) def get_exp_ratio_df(): return _exp_exp_ratio_df def get_user_id_by_path(df_path): return int(df_path[df_path.rindex('/')+1:df_path.rindex('.')]) def get_file_path(floder_path): return sorted(map(lambda dir_t:floder_path+dir_t,os.listdir(floder_path))) def get_day_df_path(day): floder_path = DAY_FEATURE_PATH+'%d/'%day return get_file_path(floder_path) def get_day_df(day): df_path = get_day_df_path(day) all_model = pd.concat(map(pd.DataFrame.from_csv,df_path)).dropna() #all_model.to_csv(DAY_FEATURE_ALL_PATH+'%d'%day) return all_model def get_month_df_path(): return get_file_path(MONTH_FEATURE_PATH) def get_holiday_month_df_path(): return get_file_path(HOLIDAY_MONTH_FEATURE_PATH) def get_prophet_holiday_month_df_path(): return get_file_path(PROPHET_HOLIDAY_MONTH_FEATURE_PATH) def get_history_path(): return get_file_path(HISTORY_PATH) def get_prophet_columns(): return PROPHET_COLUMNS def get_weather_columns(): return WEATHER_COLUMNS def get_scaled_user(): dataset = get_dataset() new_df = pd.DataFrame(index=set(dataset.index)) new_df = new_df.sort_index() for user_id in get_user_id_list(): #print user_id if not check_empty(user_id): new_df[user_id] = dataset[dataset.user_id == user_id].power_consumption new_df_log = new_df.apply(np.log) new_df_log_scaled = preprocessing.MinMaxScaler().fit_transform(new_df_log.ix[60:,:].dropna()) return pd.DataFrame(new_df_log_scaled,columns = new_df_log.columns) def classify_user(): new_df_log_scaled = get_scaled_user() c = DBSCAN(eps=90,min_samples=50,metric='manhattan').fit(new_df_log_scaled.T) pd.value_counts(c.labels_) d = c.labels_ types = pd.DataFrame(d,index=new_df_log_scaled.columns)[0] types[types == -1] = 2 return types def get_holiday_df(day): import datetime holiday_df = pd.DataFrame.from_csv(HOLIDAY_PATH) index_t = holiday_df.init_date.apply(lambda x: datetime.datetime.strptime(x[:10], '%Y/%m/%d')) holiday_df.pop('init_date') holiday_df = holiday_df.set_index(index_t) holiday_df.index += pd.Timedelta('%dD'%(30+(day-1))) #holiday_df = holiday_df.ix[:,day:30+day] holiday_df.columns = map(lambda x:'festday#%d'%x,range(-30-(day-1),31-(day-1)+5)) return holiday_df def get_festday_df(day): import datetime holiday_df = pd.DataFrame.from_csv(FEST_PATH) index_t = holiday_df.init_date.apply(lambda x: datetime.datetime.strptime(x[:10], '%Y/%m/%d')) holiday_df.pop('init_date') holiday_df = holiday_df.set_index(index_t) holiday_df.index += pd.Timedelta('%dD'%(30+(day-1))) #holiday_df = holiday_df.ix[:,day:30+day] holiday_df.columns = map(lambda x:'holiday#%d'%x,range(-30-(day-1),31-(day-1)+5)) return holiday_df def get_prophet_df(user_id): prophet_df = pd.DataFrame.from_csv(PROPHET_PATH+'%d.csv'%user_id) prophet_df.index = pd.to_datetime(prophet_df.ds) prophet_df = prophet_df[get_prophet_columns()] #predict 31 days new_df = pd.DataFrame(index = prophet_df.index[31:-3]) for col in prophet_df.columns: t_col = prophet_df[col].copy() t_col.index += pd.Timedelta('3D') #feature 3 days #predict 33 days for day in range(-3,31+3): new_df[col+'#%d'%day] = t_col t_col.index -= pd.Timedelta('1D') return new_df.dropna() def get_history_df(user_id): return pd.DataFrame.from_csv(HISTORY_PATH+'%d.csv'%user_id) def get_weather_df(): weather_df = pd.DataFrame.from_csv(WEATHER_PATH) weather_df = weather_df[get_weather_columns()] #predict 30 days new_df = pd.DataFrame(index = weather_df.index[30:-88-3]) for col in weather_df.columns: t_col = weather_df[col].copy() t_col.index += pd.Timedelta('3D') #feature 7 days #predict 30 days for day in range(-30,31+3): new_df[col+'#%d'%day] = t_col t_col.index -= pd.Timedelta('1D') return new_df.dropna() def get_day_all_df(day): df = pd.DataFrame.from_csv(DAY_FEATURE_ALL_PATH+'%d.csv'%day) return df def get_month_by_path(path): return pd.DataFrame.from_csv(path) def get_month_by_id(user_id): return pd.DataFrame.from_csv(PROPHET_HOLIDAY_MONTH_FEATURE_PATH+'%d.csv'%user_id) def get_month_all_df(): p = m_Pool(64) path_list = get_prophet_holiday_month_df_path() all_df_list = p.map(get_month_by_path,path_list) print 'Waiting for all subprocesses done...' p.close() p.join() return pd.concat(all_df_list) ''' df = pd.DataFrame.from_csv(FEATURE_PATH+'all.csv') return df ''' def get_month_big_all_df(th = 7): p = m_Pool(64) ids = get_big_user_ids(th) all_df_list = p.map(get_month_by_id,ids) print 'Waiting for all subprocesses done...' p.close() p.join() return pd.concat(all_df_list) def get_month_small_all_df(th = 7): p = m_Pool(64) ids = get_small_user_ids(th) all_df_list = p.map(get_month_by_id,ids) print 'Waiting for all subprocesses done...' p.close() p.join() return pd.concat(all_df_list) #%% drop na method def drop_na_df(old_df): old_df['y'] = old_df.y.fillna(-1) return old_df.dropna() def drop_na_month_df(old_df): new_df = old_df.copy() for col in new_df.columns: if 'y#' in col and len(col) <= 4: new_df[col] = new_df[col].fillna(-1) return new_df.dropna().replace(-1,np.nan) #%% mearge method def mearge_holiday_day_df(day): all_df_list = [] holiday_df = get_holiday_df(day) for df_path in get_day_df_path(day): print df_path old_df = pd.DataFrame.from_csv(df_path) old_df = drop_na_df(old_df) new_df = pd.merge(holiday_df,old_df,left_index=True,right_index=True) new_df.insert(0,'user_id',get_user_id_by_path(df_path)) all_df_list.append(new_df) all_df = pd.concat(all_df_list) all_df.to_csv(DAY_FEATURE_ALL_PATH+'%d.csv'%day) def mearge_holiday_month_df(holiday_df,festday_df,f_id,df_path): print "pos %d:file %s"%(f_id,df_path) user_id = get_user_id_by_path(df_path) old_df = pd.DataFrame.from_csv(df_path) old_df = drop_na_month_df(old_df) new_df = pd.merge(festday_df,old_df,left_index=True,right_index=True) new_df = pd.merge(holiday_df,new_df,left_index=True,right_index=True) new_df.insert(0,'user_id',user_id) new_df.to_csv(HOLIDAY_MONTH_FEATURE_PATH+'%d.csv'%user_id) def mearge_holiday_month_df_all(): holiday_df = get_holiday_df(1) festday_df = get_festday_df(1) p = m_Pool(64) for f_id,df_path in enumerate(get_month_df_path()): p.apply_async(mearge_holiday_month_df,(holiday_df,festday_df,f_id,df_path,)) print 'Waiting for all subprocesses done...' p.close() p.join() def mearge_prophet_holiday_month_df(df_path): print "file %s"%df_path user_id = get_user_id_by_path(df_path) old_df = pd.DataFrame.from_csv(df_path) old_df = drop_na_month_df(old_df) prophet_df = get_prophet_df(user_id) weather_df = get_weather_df() #history_df = get_history_df(user_id) #new_df = pd.merge(history_df,old_df,left_index=True,right_index=True) new_df = old_df new_df = pd.merge(prophet_df,new_df,left_index=True,right_index=True) new_df = pd.merge(weather_df,new_df,left_index=True,right_index=True) new_df.pop('user_id') #add his for his_day in [-28,-21,-14,-7]: power_column = ['power#%d'%(his_day+day_t) for day_t in range(0,7)] power_t = new_df[power_column] new_df.insert(0,'max7_power#%d'%(his_day),power_t.max(axis=1)) new_df.insert(0,'min7_power#%d'%(his_day),power_t.min(axis=1)) new_df.insert(0,'std7_power#%d'%(his_day),power_t.std(axis=1)) new_df.insert(0,'mean7_power#%d'%(his_day),power_t.mean(axis=1)) holi_t = new_df[['festday#%d'%(his_day+day_t) for day_t in range(0,7)]] new_df.insert(0,'mean7_holiday#%d'%(his_day),holi_t.mean(axis=1)) new_df.insert(0,'user_id',user_id) my_type = _user_type_df[user_id] for user_type in sorted(set(_user_type_df)): if my_type == user_type: new_df.insert(user_type+1,'user_type#%d'%user_type,1) else: new_df.insert(user_type+1,'user_type#%d'%user_type,0) new_df.to_csv(PROPHET_HOLIDAY_MONTH_FEATURE_PATH+'%d.csv'%user_id) return new_df def mearge_prophet_holiday_month_df_all(): all_df_list = [] p = m_Pool(64) path_list = get_holiday_month_df_path() all_df_list = p.map(mearge_prophet_holiday_month_df,path_list) print 'Waiting for all subprocesses done...' p.close() p.join() ''' all_df = pd.concat(all_df_list) all_df.to_csv(FEATURE_PATH+'all.csv') ''' def mearge_holiday_day_df_all(): p = m_Pool(64) for day in range(1,31): p.apply_async(mearge_holiday_day_df,args=(day,)) #p.apply_async(predict_using_prophet, args=(arg,)) print 'Waiting for all subprocesses done...' p.close() p.join() #%% save model method def save_model(xgb_regressor,day,folder_path): xgb_regressor._Booster.save_model(folder_path+'%d.xgbmodel'%day) save_day_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,DAY_MODELS_PATH) save_filtered_day_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,DAY_FILTERED_MODELS_PATH) save_prophet_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_MODELS_PATH) save_filtered_prophet_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_FILTERED_MODELS_PATH) save_prophet_exp_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_EXP_MODELS_PATH) save_filtered_prophet_exp_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_EXP__FILTERED_MODELS_PATH) save_extera_holi_prophet_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_MODELS_PATH) save_extera_holi_prophet_filtered_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_FILTERED_MODELS_PATH) save_extera_holi_prophet_f2_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_F2_MODELS_PATH) save_extera_holi_prophet_exp_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_EXP_MODELS_PATH) save_extera_holi_prophet_exp_filtered_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_EXP_FILTERED_MODELS_PATH) save_extera_holi_prophet_exp_f2_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_EXP_F2_MODELS_PATH) save_prophet_14day_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_14DAY_MODELS_PATH) save_prophet_14day_filtered_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_14DAY_FILTERED_MODELS_PATH) save_prophet_14day_f2_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_14DAY_F2_MODELS_PATH) save_prophet_14day_exp_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_14DAY_EXP_MODELS_PATH) save_prophet_14day_exp_filtered_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_14DAY_EXP_FILTERED_MODELS_PATH) save_prophet_14day_exp_f2_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_14DAY_EXP_F2_MODELS_PATH) save_prophet_7day_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_7DAY_MODELS_PATH) save_prophet_7day_filtered_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_7DAY_FILTERED_MODELS_PATH) save_prophet_7day_f2_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_7DAY_F2_MODELS_PATH) save_prophet_7day_exp_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_7DAY_EXP_MODELS_PATH) save_prophet_7day_exp_filtered_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_7DAY_EXP_FILTERED_MODELS_PATH) save_prophet_7day_exp_f2_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PROPHET_7DAY_EXP_F2_MODELS_PATH) save_tiny_7_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,TINY_7_MODELS_PATH) save_tiny_7_filtered_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,TINY_7_FILTERED_MODELS_PATH) save_tiny_7_f2_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,TINY_7_F2_MODELS_PATH) save_tiny_7_exp_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,TINY_7_EXP_MODELS_PATH) save_tiny_7_exp_filtered_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,TINY_7_EXP_FILTERED_MODELS_PATH) save_tiny_7_exp_f2_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,TINY_7_EXP_F2_MODELS_PATH) #%% np_tiny7 save_np_tiny_7_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,NP_TINY_7_MODELS_PATH) save_np_tiny_7_filtered_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,NP_TINY_7_FILTERED_MODELS_PATH) save_np_tiny_7_f2_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,NP_TINY_7_F2_MODELS_PATH) save_np_tiny_7_exp_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,NP_TINY_7_EXP_MODELS_PATH) save_np_tiny_7_exp_filtered_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,NP_TINY_7_EXP_FILTERED_MODELS_PATH) save_np_tiny_7_exp_f2_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,NP_TINY_7_EXP_F2_MODELS_PATH) #%% end np_tiny7 save_user_model = lambda xgb_regressor,day,user_id:save_model(xgb_regressor,day,USER_MODELS_PATH+'%d/'%user_id) save_user_exp_model = lambda xgb_regressor,day,user_id:save_model(xgb_regressor,day,USER_EXP_MODELS_PATH+'%d/'%user_id) save_pre_predict_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PRE_PREDICT_MODELS_PATH) save_filtered_pre_predict_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PRE_PREDICT_FILTERED_MODELS_PATH) save_predict_model = lambda xgb_regressor,day:save_model(xgb_regressor,day,PREDICT_MODELS_PATH) #%% load model method def load_model(xgb_regressor,day,folder_path): booster = xgb.Booster() booster.load_model(folder_path+'%d.xgbmodel'%day) xgb_regressor._Booster = booster load_day_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,DAY_MODELS_PATH) load_filtered_day_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,DAY_FILTERED_MODELS_PATH) load_prophet_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_MODELS_PATH) load_filtered_prophet_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_FILTERED_MODELS_PATH) load_prophet_exp_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_EXP_MODELS_PATH) load_filtered_prophet_exp_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_EXP__FILTERED_MODELS_PATH) load_extera_holi_prophet_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_MODELS_PATH) load_extera_holi_prophet_filtered_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_FILTERED_MODELS_PATH) load_extera_holi_prophet_f2_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_F2_MODELS_PATH) load_extera_holi_prophet_exp_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_EXP_MODELS_PATH) load_extera_holi_prophet_exp_filtered_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_EXP_FILTERED_MODELS_PATH) load_extera_holi_prophet_exp_f2_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,EXTERA_HOLI_PROPHET_EXP_F2_MODELS_PATH) load_prophet_14day_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_14DAY_MODELS_PATH) load_prophet_14day_filtered_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_14DAY_FILTERED_MODELS_PATH) load_prophet_14day_f2_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_14DAY_F2_MODELS_PATH) load_prophet_14day_exp_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_14DAY_EXP_MODELS_PATH) load_prophet_14day_exp_filtered_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_14DAY_EXP_FILTERED_MODELS_PATH) load_prophet_14day_exp_f2_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_14DAY_EXP_F2_MODELS_PATH) load_prophet_7day_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_7DAY_MODELS_PATH) load_prophet_7day_filtered_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_7DAY_FILTERED_MODELS_PATH) load_prophet_7day_f2_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_7DAY_F2_MODELS_PATH) load_prophet_7day_exp_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_7DAY_EXP_MODELS_PATH) load_prophet_7day_exp_filtered_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_7DAY_EXP_FILTERED_MODELS_PATH) load_prophet_7day_exp_f2_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PROPHET_7DAY_EXP_F2_MODELS_PATH) load_tiny_7_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,TINY_7_MODELS_PATH) load_tiny_7_filtered_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,TINY_7_FILTERED_MODELS_PATH) load_tiny_7_f2_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,TINY_7_F2_MODELS_PATH) load_tiny_7_exp_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,TINY_7_EXP_MODELS_PATH) load_tiny_7_exp_filtered_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,TINY_7_EXP_FILTERED_MODELS_PATH) load_tiny_7_exp_f2_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,TINY_7_EXP_F2_MODELS_PATH) #%% np_tiny7 load_np_tiny_7_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,NP_TINY_7_MODELS_PATH) load_np_tiny_7_filtered_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,NP_TINY_7_FILTERED_MODELS_PATH) load_np_tiny_7_f2_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,NP_TINY_7_F2_MODELS_PATH) load_np_tiny_7_exp_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,NP_TINY_7_EXP_MODELS_PATH) load_np_tiny_7_exp_filtered_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,NP_TINY_7_EXP_FILTERED_MODELS_PATH) load_np_tiny_7_exp_f2_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,NP_TINY_7_EXP_F2_MODELS_PATH) #%% end np_tiny7 load_user_model = lambda xgb_regressor,day,user_id:load_model(xgb_regressor,day,USER_MODELS_PATH+'%d/'%user_id) load_user_exp_model = lambda xgb_regressor,day,user_id:load_model(xgb_regressor,day,USER_EXP_MODELS_PATH+'%d/'%user_id) load_pre_predict_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PRE_PREDICT_MODELS_PATH) load_filtered_pre_predict_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PRE_PREDICT_FILTERED_MODELS_PATH) load_predict_model = lambda xgb_regressor,day:load_model(xgb_regressor,day,PREDICT_MODELS_PATH) #%% others def filter_empty_user(dataset): user_index = sorted(set(dataset.user_id)) empty_series = pd.Series(index=user_index,dtype='bool') for user_id in empty_series.index: filtered_power = filter_user_id(dataset,user_id).power_consumption power_end = filtered_power[-14:] if power_end.mean()<50: print 'warming ! user:%d,average:%f'%(user_id,power_end.mean()) empty_series[user_id] = True else: empty_series[user_id] = False return empty_series def filter_user_power_range(dataset): user_index = sorted(set(dataset.user_id)) power_series = pd.Series(index=user_index) for user_id in power_series.index: filtered_power = filter_user_id(dataset,user_id).power_consumption power_series[user_id] = filtered_power.median() return power_series def filter_user_id(dataset,user_id): return dataset[dataset.user_id == user_id] def filter_spring_festval(dataset): old_index = dataset.index pos_mask = ((old_index<'2015-1-1')|(old_index>'2015-3-25'))&\ ((old_index<'2016-1-1')|(old_index>'2016-3-25')) return dataset.ix[pos_mask] def filter_sept(dataset): old_index = dataset.index pos_mask = ((old_index>'2015-6-1')&(old_index<'2015-11-30'))|\ (old_index>'2016-6-1') return dataset.ix[pos_mask] def check_empty(user_id): """ return true if the power of user_id is 1 """ return _empty_user_df[user_id] def increase_index(last_year): """ 将2015年的index替换为2016年的 """ last_year.index += pd.Timedelta('365D') new_index = pd.Series(last_year.index) new_index[new_index >= '2016-2-29'] += pd.Timedelta('1D') last_year.index = new_index return last_year def exp_power(x_): new_x_ = pd.DataFrame() for col in x_: if 'power' in col: new_x_[col] = x_[col].apply(np.exp) else: new_x_[col] = x_[col] return new_x_ def save_month_df(df,user_id): df.to_csv(MONTH_FEATURE_PATH+'%d.csv'%user_id) def save_history_df(df,user_id): df.to_csv(HISTORY_PATH+'%d.csv'%user_id) def save_day_df(df,day,user_id): df.to_csv(DAY_FEATURE_PATH+'%d/%d.csv'%(day+1,user_id)) def get_feature_cloumn(columns,day, feature_range = 28, holiday_range = 5, has_extera_holiday = False, has_extera_weather = False, has_holiday = True, has_weather = True, has_prophet = True, has_power = True, has_user_type = True, has_history = False, has_user = False,): assert holiday_range%2 == 1 feature_column = [] if has_user_type: feature_column += ['user_type#%d'%user_t for user_t in sorted(set(_user_type_df))] if has_prophet: for prophet_column in get_prophet_columns(): feature_column += [prophet_column+'#%d'%day_t for day_t in range(day-1-2,day-1+3)] if has_extera_weather: end_pos = day-1-2 if day-1-2<0 else 0 for weather_column in get_weather_columns(): feature_column += [weather_column+'#%d'%day_t for day_t in range(-feature_range,end_pos)] if has_weather: for weather_column in get_weather_columns(): feature_column += [weather_column+'#%d'%day_t for day_t in range(day-1-2,day-1+3)] if has_extera_holiday: end_pos = day-1-holiday_range/2 if day-1-holiday_range/2<0 else 0 feature_column += ['holiday#%d'%day_t for day_t in range(-feature_range,end_pos)] feature_column += ['festday#%d'%day_t for day_t in range(-feature_range,end_pos)] if has_holiday: feature_column += ['holiday#%d'%day_t for day_t in range(day-1-holiday_range/2,day-1+holiday_range/2+1)] feature_column += ['festday#%d'%day_t for day_t in range(day-1-holiday_range/2,day-1+holiday_range/2+1)] if has_power: feature_column += ['power#%d'%day_t for day_t in range(-1,-feature_range-1,-1)] if has_user: full_user = get_full_user_ids() feature_column += ['user#%d'%user_t for user_t in full_user] if has_history: feature_column += [his_columns+'#%d'%(day-1) for his_columns in HISTORY_COLUMNS] return feature_column def get_feature_cloumn_tiny(columns,day, feature_range = 7, holiday_range = 9, has_extera_holiday = False, has_extera_weather = False, has_holiday = True, has_weather = True, has_prophet = True, has_power = True, has_user_type = False, has_history = True, has_user = False,): assert holiday_range%2 == 1 def get_day_his_list(): day_his_list = [] day_t = day - 1 while day_t > -30: if(day_t) < -feature_range: day_his_list.append(day_t) day_t -= 7 return day_his_list feature_column = [] day_his_list = get_day_his_list() if has_user_type: feature_column += ['user_type#%d'%user_t for user_t in sorted(set(_user_type_df))] if has_prophet: for prophet_column in get_prophet_columns(): feature_column += [prophet_column+'#%d'%day_t for day_t in range(day-1-2,day-1+3)] if has_extera_weather: end_pos = day-1-2 if day-1-2<0 else 0 feature_column += ['Temp'+'#%d'%day_t for day_t in range(-feature_range,end_pos)] if has_weather: feature_column += ['Temp'+'#%d'%day_t for day_t in range(day-1-2,day-1+3)] if has_extera_holiday: end_pos = day-1-holiday_range/2 if day-1-holiday_range/2<0 else 0 feature_column += ['holiday#%d'%day_t for day_t in range(-feature_range,end_pos)] feature_column += ['festday#%d'%day_t for day_t in range(-feature_range,end_pos)] if has_holiday: feature_column += ['holiday#%d'%day_t for day_t in range(day-1-holiday_range/2,day-1+holiday_range/2+1)] feature_column += ['festday#%d'%day_t for day_t in range(day-1-holiday_range/2,day-1+holiday_range/2+1)] if has_power: feature_column += ['power#%d'%day_t for day_t in range(-1,-feature_range-1,-1)] feature_column += ['power#%d'%day_t for day_t in day_his_list] if has_user: full_user = get_full_user_ids() feature_column += ['user#%d'%user_t for user_t in full_user] if has_history: for his_columns in ['mean7','max7','min7','std7']: feature_column += [his_columns+'_power#%d'%his_day for his_day in [-28,-21,-14,-7]] feature_column += ['mean7_holiday#%d'%his_day for his_day in[-28,-21,-14,-7]] return feature_column def logregobj(preds, dtrain): labels = dtrain.get_label() pred_exp = np.exp(preds) pred_2_exp = pred_exp*pred_exp labels_exp = np.exp(labels) grad = (pred_exp-labels_exp)*pred_exp hess = (2*pred_2_exp - pred_exp*labels_exp) ''' a = 2*labels b = (preds+labels)**2 grad = 122*np.where((preds - labels)>0,a,-a)/b grad = np.where(np.abs(preds - labels)<1e-10,0,grad) hess = grad*(-2)/(preds+labels) ''' return grad, hess def evalerror(preds, dtrain): labels = dtrain.get_label() ''' pred_exp = np.exp(preds) labels_exp = np.exp(labels) return 'error', np.sum(np.abs(pred_exp-labels_exp))/np.sum(labels_exp) ''' return 'error', np.sum(np.abs(preds-labels))/np.sum(labels) def crate_pre_train_model(x_,y_): (x_train,x_test) = train_test_split(x_,test_size=0.1,random_state=1) (y_train,y_test) = train_test_split(y_,test_size=0.1,random_state=1) dtrain = xgb.DMatrix( x_train, label=y_train) dtest = xgb.DMatrix( x_test, label=y_test) evallist = [(dtrain,'train'),(dtest,'eval')] param = {'objective':'reg:linear','max_depth':3 } param['nthread'] = 64 #param['min_child_weight'] = 15 #param['subsample'] = 1 #param['num_class'] = 7 plst = param.items() num_round = 5000 bst = xgb.train( plst, dtrain, num_round, evallist,early_stopping_rounds=100, #obj=logregobj, feval=evalerror ) return bst # %% main if __name__ == '__main__': mearge_holiday_month_df_all() mearge_prophet_holiday_month_df_all()
mit
yunfeilu/scikit-learn
doc/tutorial/text_analytics/skeletons/exercise_01_language_train_model.py
254
2005
"""Build a language detector model The goal of this exercise is to train a linear classifier on text features that represent sequences of up to 3 consecutive characters so as to be recognize natural languages by using the frequencies of short character sequences as 'fingerprints'. """ # Author: Olivier Grisel <olivier.grisel@ensta.org> # License: Simplified BSD import sys from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import Perceptron from sklearn.pipeline import Pipeline from sklearn.datasets import load_files from sklearn.cross_validation import train_test_split from sklearn import metrics # The training data folder must be passed as first argument languages_data_folder = sys.argv[1] dataset = load_files(languages_data_folder) # Split the dataset in training and test set: docs_train, docs_test, y_train, y_test = train_test_split( dataset.data, dataset.target, test_size=0.5) # TASK: Build a an vectorizer that splits strings into sequence of 1 to 3 # characters instead of word tokens # TASK: Build a vectorizer / classifier pipeline using the previous analyzer # the pipeline instance should stored in a variable named clf # TASK: Fit the pipeline on the training set # TASK: Predict the outcome on the testing set in a variable named y_predicted # Print the classification report print(metrics.classification_report(y_test, y_predicted, target_names=dataset.target_names)) # Plot the confusion matrix cm = metrics.confusion_matrix(y_test, y_predicted) print(cm) #import pylab as pl #pl.matshow(cm, cmap=pl.cm.jet) #pl.show() # Predict the result on some short new sentences: sentences = [ u'This is a language detection test.', u'Ceci est un test de d\xe9tection de la langue.', u'Dies ist ein Test, um die Sprache zu erkennen.', ] predicted = clf.predict(sentences) for s, p in zip(sentences, predicted): print(u'The language of "%s" is "%s"' % (s, dataset.target_names[p]))
bsd-3-clause
synergetics/spectrum
src/conventional/cumest.py
1
2697
#!/usr/bin/env python from __future__ import division import numpy as np from scipy.linalg import hankel import scipy.io as sio import matplotlib.pyplot as plt from ..tools import * from cum2est import * from cum3est import * from cum4est import * def cumest(y, norder=2, maxlag=0 ,nsamp=None, overlap=0, flag='biased' ,k1=0, k2=0): """ Second-, third- or fourth-order cumulants. Parameters: y - time-series - should be a vector norder - cumulant order: 2, 3 or 4 [default = 2] maxlag - maximum cumulant lag to compute [default = 0] samp_seg - samples per segment [default = data_length] overlap - percentage overlap of segments [default = 0] overlap is clipped to the allowed range of [0,99]. flag - 'biased' or 'unbiased' [default = 'biased'] k1,k2 - specify the slice of 3rd or 4th order cumulants Output: y_cum - C2(m) or C3(m,k1) or C4(m,k1,k2), -maxlag <= m <= maxlag depending upon the cumulant order selected """ (ksamp, nrecs) = y.shape if ksamp == 1: ksamp = nrecs nrecs = 1 if norder < 2 or norder > 4: raise ValueError('cumulant order must be 2, 3 or 4') if maxlag < 0: raise ValueError('"maxlag" must be non-negative') if nrecs > 1: nsamp = ksamp if nsamp <= 0 or nsamp > ksamp: nsamp = ksamp if nrecs > 1: overlap = 0 overlap = max(0,min(overlap,99)) # estimate the cumulants if norder == 2: y_cum = cum2est(y, maxlag, nsamp, overlap, flag) elif norder == 3: y_cum = cum3est(y, maxlag, nsamp, overlap, flag, k1) elif norder == 4: y_cum = cum3est(y, maxlag, nsamp, overlap, flag, k1, k2) return y_cum def test(): y = sio.loadmat(here(__file__) + '/demo/ma1.mat')['y'] # The right results are: # "biased": [-0.12250513 0.35963613 1.00586945 0.35963613 -0.12250513] # "unbiaed": [-0.12444965 0.36246791 1.00586945 0.36246791 -0.12444965] print cum2est(y, 2, 128, 0, 'unbiased') print cum2est(y, 2, 128, 0, 'biased') # For the 3rd cumulant: # "biased": [-0.18203039 0.07751503 0.67113035 0.729953 0.07751503] # "unbiased": [-0.18639911 0.07874543 0.67641484 0.74153955 0.07937539] print cum3est(y, 2, 128, 0, 'biased', 1) print cum3est(y, 2, 128, 0, 'unbiased', 1) # For testing the 4th-order cumulant # "biased": [-0.03642083 0.4755026 0.6352588 1.38975232 0.83791117 0.41641134 -0.97386322] # "unbiased": [-0.04011388 0.48736793 0.64948927 1.40734633 0.8445089 0.42303979 -0.99724968] print cum4est(y, 3, 128, 0, 'biased', 1, 1) print cum4est(y, 3, 128, 0, 'unbiased', 1, 1) if __name__ == '__main__': test()
mit
rvraghav93/scikit-learn
sklearn/linear_model/omp.py
3
31718
"""Orthogonal matching pursuit algorithms """ # Author: Vlad Niculae # # License: BSD 3 clause import warnings import numpy as np from scipy import linalg from scipy.linalg.lapack import get_lapack_funcs from .base import LinearModel, _pre_fit from ..base import RegressorMixin from ..utils import as_float_array, check_array, check_X_y from ..model_selection import check_cv from ..externals.joblib import Parallel, delayed solve_triangular_args = {'check_finite': False} premature = """ Orthogonal matching pursuit ended prematurely due to linear dependence in the dictionary. The requested precision might not have been met. """ def _cholesky_omp(X, y, n_nonzero_coefs, tol=None, copy_X=True, return_path=False): """Orthogonal Matching Pursuit step using the Cholesky decomposition. Parameters ---------- X : array, shape (n_samples, n_features) Input dictionary. Columns are assumed to have unit norm. y : array, shape (n_samples,) Input targets n_nonzero_coefs : int Targeted number of non-zero elements tol : float Targeted squared error, if not None overrides n_nonzero_coefs. copy_X : bool, optional Whether the design matrix X must be copied by the algorithm. A false value is only helpful if X is already Fortran-ordered, otherwise a copy is made anyway. return_path : bool, optional. Default: False Whether to return every value of the nonzero coefficients along the forward path. Useful for cross-validation. Returns ------- gamma : array, shape (n_nonzero_coefs,) Non-zero elements of the solution idx : array, shape (n_nonzero_coefs,) Indices of the positions of the elements in gamma within the solution vector coef : array, shape (n_features, n_nonzero_coefs) The first k values of column k correspond to the coefficient value for the active features at that step. The lower left triangle contains garbage. Only returned if ``return_path=True``. n_active : int Number of active features at convergence. """ if copy_X: X = X.copy('F') else: # even if we are allowed to overwrite, still copy it if bad order X = np.asfortranarray(X) min_float = np.finfo(X.dtype).eps nrm2, swap = linalg.get_blas_funcs(('nrm2', 'swap'), (X,)) potrs, = get_lapack_funcs(('potrs',), (X,)) alpha = np.dot(X.T, y) residual = y gamma = np.empty(0) n_active = 0 indices = np.arange(X.shape[1]) # keeping track of swapping max_features = X.shape[1] if tol is not None else n_nonzero_coefs if solve_triangular_args: # new scipy, don't need to initialize because check_finite=False L = np.empty((max_features, max_features), dtype=X.dtype) else: # old scipy, we need the garbage upper triangle to be non-Inf L = np.zeros((max_features, max_features), dtype=X.dtype) L[0, 0] = 1. if return_path: coefs = np.empty_like(L) while True: lam = np.argmax(np.abs(np.dot(X.T, residual))) if lam < n_active or alpha[lam] ** 2 < min_float: # atom already selected or inner product too small warnings.warn(premature, RuntimeWarning, stacklevel=2) break if n_active > 0: # Updates the Cholesky decomposition of X' X L[n_active, :n_active] = np.dot(X[:, :n_active].T, X[:, lam]) linalg.solve_triangular(L[:n_active, :n_active], L[n_active, :n_active], trans=0, lower=1, overwrite_b=True, **solve_triangular_args) v = nrm2(L[n_active, :n_active]) ** 2 if 1 - v <= min_float: # selected atoms are dependent warnings.warn(premature, RuntimeWarning, stacklevel=2) break L[n_active, n_active] = np.sqrt(1 - v) X.T[n_active], X.T[lam] = swap(X.T[n_active], X.T[lam]) alpha[n_active], alpha[lam] = alpha[lam], alpha[n_active] indices[n_active], indices[lam] = indices[lam], indices[n_active] n_active += 1 # solves LL'x = y as a composition of two triangular systems gamma, _ = potrs(L[:n_active, :n_active], alpha[:n_active], lower=True, overwrite_b=False) if return_path: coefs[:n_active, n_active - 1] = gamma residual = y - np.dot(X[:, :n_active], gamma) if tol is not None and nrm2(residual) ** 2 <= tol: break elif n_active == max_features: break if return_path: return gamma, indices[:n_active], coefs[:, :n_active], n_active else: return gamma, indices[:n_active], n_active def _gram_omp(Gram, Xy, n_nonzero_coefs, tol_0=None, tol=None, copy_Gram=True, copy_Xy=True, return_path=False): """Orthogonal Matching Pursuit step on a precomputed Gram matrix. This function uses the Cholesky decomposition method. Parameters ---------- Gram : array, shape (n_features, n_features) Gram matrix of the input data matrix Xy : array, shape (n_features,) Input targets n_nonzero_coefs : int Targeted number of non-zero elements tol_0 : float Squared norm of y, required if tol is not None. tol : float Targeted squared error, if not None overrides n_nonzero_coefs. copy_Gram : bool, optional Whether the gram matrix must be copied by the algorithm. A false value is only helpful if it is already Fortran-ordered, otherwise a copy is made anyway. copy_Xy : bool, optional Whether the covariance vector Xy must be copied by the algorithm. If False, it may be overwritten. return_path : bool, optional. Default: False Whether to return every value of the nonzero coefficients along the forward path. Useful for cross-validation. Returns ------- gamma : array, shape (n_nonzero_coefs,) Non-zero elements of the solution idx : array, shape (n_nonzero_coefs,) Indices of the positions of the elements in gamma within the solution vector coefs : array, shape (n_features, n_nonzero_coefs) The first k values of column k correspond to the coefficient value for the active features at that step. The lower left triangle contains garbage. Only returned if ``return_path=True``. n_active : int Number of active features at convergence. """ Gram = Gram.copy('F') if copy_Gram else np.asfortranarray(Gram) if copy_Xy: Xy = Xy.copy() min_float = np.finfo(Gram.dtype).eps nrm2, swap = linalg.get_blas_funcs(('nrm2', 'swap'), (Gram,)) potrs, = get_lapack_funcs(('potrs',), (Gram,)) indices = np.arange(len(Gram)) # keeping track of swapping alpha = Xy tol_curr = tol_0 delta = 0 gamma = np.empty(0) n_active = 0 max_features = len(Gram) if tol is not None else n_nonzero_coefs if solve_triangular_args: # new scipy, don't need to initialize because check_finite=False L = np.empty((max_features, max_features), dtype=Gram.dtype) else: # old scipy, we need the garbage upper triangle to be non-Inf L = np.zeros((max_features, max_features), dtype=Gram.dtype) L[0, 0] = 1. if return_path: coefs = np.empty_like(L) while True: lam = np.argmax(np.abs(alpha)) if lam < n_active or alpha[lam] ** 2 < min_float: # selected same atom twice, or inner product too small warnings.warn(premature, RuntimeWarning, stacklevel=3) break if n_active > 0: L[n_active, :n_active] = Gram[lam, :n_active] linalg.solve_triangular(L[:n_active, :n_active], L[n_active, :n_active], trans=0, lower=1, overwrite_b=True, **solve_triangular_args) v = nrm2(L[n_active, :n_active]) ** 2 if 1 - v <= min_float: # selected atoms are dependent warnings.warn(premature, RuntimeWarning, stacklevel=3) break L[n_active, n_active] = np.sqrt(1 - v) Gram[n_active], Gram[lam] = swap(Gram[n_active], Gram[lam]) Gram.T[n_active], Gram.T[lam] = swap(Gram.T[n_active], Gram.T[lam]) indices[n_active], indices[lam] = indices[lam], indices[n_active] Xy[n_active], Xy[lam] = Xy[lam], Xy[n_active] n_active += 1 # solves LL'x = y as a composition of two triangular systems gamma, _ = potrs(L[:n_active, :n_active], Xy[:n_active], lower=True, overwrite_b=False) if return_path: coefs[:n_active, n_active - 1] = gamma beta = np.dot(Gram[:, :n_active], gamma) alpha = Xy - beta if tol is not None: tol_curr += delta delta = np.inner(gamma, beta[:n_active]) tol_curr -= delta if abs(tol_curr) <= tol: break elif n_active == max_features: break if return_path: return gamma, indices[:n_active], coefs[:, :n_active], n_active else: return gamma, indices[:n_active], n_active def orthogonal_mp(X, y, n_nonzero_coefs=None, tol=None, precompute=False, copy_X=True, return_path=False, return_n_iter=False): """Orthogonal Matching Pursuit (OMP) Solves n_targets Orthogonal Matching Pursuit problems. An instance of the problem has the form: When parametrized by the number of non-zero coefficients using `n_nonzero_coefs`: argmin ||y - X\gamma||^2 subject to ||\gamma||_0 <= n_{nonzero coefs} When parametrized by error using the parameter `tol`: argmin ||\gamma||_0 subject to ||y - X\gamma||^2 <= tol Read more in the :ref:`User Guide <omp>`. Parameters ---------- X : array, shape (n_samples, n_features) Input data. Columns are assumed to have unit norm. y : array, shape (n_samples,) or (n_samples, n_targets) Input targets n_nonzero_coefs : int Desired number of non-zero entries in the solution. If None (by default) this value is set to 10% of n_features. tol : float Maximum norm of the residual. If not None, overrides n_nonzero_coefs. precompute : {True, False, 'auto'}, Whether to perform precomputations. Improves performance when n_targets or n_samples is very large. copy_X : bool, optional Whether the design matrix X must be copied by the algorithm. A false value is only helpful if X is already Fortran-ordered, otherwise a copy is made anyway. return_path : bool, optional. Default: False Whether to return every value of the nonzero coefficients along the forward path. Useful for cross-validation. return_n_iter : bool, optional default False Whether or not to return the number of iterations. Returns ------- coef : array, shape (n_features,) or (n_features, n_targets) Coefficients of the OMP solution. If `return_path=True`, this contains the whole coefficient path. In this case its shape is (n_features, n_features) or (n_features, n_targets, n_features) and iterating over the last axis yields coefficients in increasing order of active features. n_iters : array-like or int Number of active features across every target. Returned only if `return_n_iter` is set to True. See also -------- OrthogonalMatchingPursuit orthogonal_mp_gram lars_path decomposition.sparse_encode Notes ----- Orthogonal matching pursuit was introduced in S. Mallat, Z. Zhang, Matching pursuits with time-frequency dictionaries, IEEE Transactions on Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415. (http://blanche.polytechnique.fr/~mallat/papiers/MallatPursuit93.pdf) This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad, M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal Matching Pursuit Technical Report - CS Technion, April 2008. http://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf """ X = check_array(X, order='F', copy=copy_X) copy_X = False if y.ndim == 1: y = y.reshape(-1, 1) y = check_array(y) if y.shape[1] > 1: # subsequent targets will be affected copy_X = True if n_nonzero_coefs is None and tol is None: # default for n_nonzero_coefs is 0.1 * n_features # but at least one. n_nonzero_coefs = max(int(0.1 * X.shape[1]), 1) if tol is not None and tol < 0: raise ValueError("Epsilon cannot be negative") if tol is None and n_nonzero_coefs <= 0: raise ValueError("The number of atoms must be positive") if tol is None and n_nonzero_coefs > X.shape[1]: raise ValueError("The number of atoms cannot be more than the number " "of features") if precompute == 'auto': precompute = X.shape[0] > X.shape[1] if precompute: G = np.dot(X.T, X) G = np.asfortranarray(G) Xy = np.dot(X.T, y) if tol is not None: norms_squared = np.sum((y ** 2), axis=0) else: norms_squared = None return orthogonal_mp_gram(G, Xy, n_nonzero_coefs, tol, norms_squared, copy_Gram=copy_X, copy_Xy=False, return_path=return_path) if return_path: coef = np.zeros((X.shape[1], y.shape[1], X.shape[1])) else: coef = np.zeros((X.shape[1], y.shape[1])) n_iters = [] for k in range(y.shape[1]): out = _cholesky_omp( X, y[:, k], n_nonzero_coefs, tol, copy_X=copy_X, return_path=return_path) if return_path: _, idx, coefs, n_iter = out coef = coef[:, :, :len(idx)] for n_active, x in enumerate(coefs.T): coef[idx[:n_active + 1], k, n_active] = x[:n_active + 1] else: x, idx, n_iter = out coef[idx, k] = x n_iters.append(n_iter) if y.shape[1] == 1: n_iters = n_iters[0] if return_n_iter: return np.squeeze(coef), n_iters else: return np.squeeze(coef) def orthogonal_mp_gram(Gram, Xy, n_nonzero_coefs=None, tol=None, norms_squared=None, copy_Gram=True, copy_Xy=True, return_path=False, return_n_iter=False): """Gram Orthogonal Matching Pursuit (OMP) Solves n_targets Orthogonal Matching Pursuit problems using only the Gram matrix X.T * X and the product X.T * y. Read more in the :ref:`User Guide <omp>`. Parameters ---------- Gram : array, shape (n_features, n_features) Gram matrix of the input data: X.T * X Xy : array, shape (n_features,) or (n_features, n_targets) Input targets multiplied by X: X.T * y n_nonzero_coefs : int Desired number of non-zero entries in the solution. If None (by default) this value is set to 10% of n_features. tol : float Maximum norm of the residual. If not None, overrides n_nonzero_coefs. norms_squared : array-like, shape (n_targets,) Squared L2 norms of the lines of y. Required if tol is not None. copy_Gram : bool, optional Whether the gram matrix must be copied by the algorithm. A false value is only helpful if it is already Fortran-ordered, otherwise a copy is made anyway. copy_Xy : bool, optional Whether the covariance vector Xy must be copied by the algorithm. If False, it may be overwritten. return_path : bool, optional. Default: False Whether to return every value of the nonzero coefficients along the forward path. Useful for cross-validation. return_n_iter : bool, optional default False Whether or not to return the number of iterations. Returns ------- coef : array, shape (n_features,) or (n_features, n_targets) Coefficients of the OMP solution. If `return_path=True`, this contains the whole coefficient path. In this case its shape is (n_features, n_features) or (n_features, n_targets, n_features) and iterating over the last axis yields coefficients in increasing order of active features. n_iters : array-like or int Number of active features across every target. Returned only if `return_n_iter` is set to True. See also -------- OrthogonalMatchingPursuit orthogonal_mp lars_path decomposition.sparse_encode Notes ----- Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang, Matching pursuits with time-frequency dictionaries, IEEE Transactions on Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415. (http://blanche.polytechnique.fr/~mallat/papiers/MallatPursuit93.pdf) This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad, M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal Matching Pursuit Technical Report - CS Technion, April 2008. http://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf """ Gram = check_array(Gram, order='F', copy=copy_Gram) Xy = np.asarray(Xy) if Xy.ndim > 1 and Xy.shape[1] > 1: # or subsequent target will be affected copy_Gram = True if Xy.ndim == 1: Xy = Xy[:, np.newaxis] if tol is not None: norms_squared = [norms_squared] if n_nonzero_coefs is None and tol is None: n_nonzero_coefs = int(0.1 * len(Gram)) if tol is not None and norms_squared is None: raise ValueError('Gram OMP needs the precomputed norms in order ' 'to evaluate the error sum of squares.') if tol is not None and tol < 0: raise ValueError("Epsilon cannot be negative") if tol is None and n_nonzero_coefs <= 0: raise ValueError("The number of atoms must be positive") if tol is None and n_nonzero_coefs > len(Gram): raise ValueError("The number of atoms cannot be more than the number " "of features") if return_path: coef = np.zeros((len(Gram), Xy.shape[1], len(Gram))) else: coef = np.zeros((len(Gram), Xy.shape[1])) n_iters = [] for k in range(Xy.shape[1]): out = _gram_omp( Gram, Xy[:, k], n_nonzero_coefs, norms_squared[k] if tol is not None else None, tol, copy_Gram=copy_Gram, copy_Xy=copy_Xy, return_path=return_path) if return_path: _, idx, coefs, n_iter = out coef = coef[:, :, :len(idx)] for n_active, x in enumerate(coefs.T): coef[idx[:n_active + 1], k, n_active] = x[:n_active + 1] else: x, idx, n_iter = out coef[idx, k] = x n_iters.append(n_iter) if Xy.shape[1] == 1: n_iters = n_iters[0] if return_n_iter: return np.squeeze(coef), n_iters else: return np.squeeze(coef) class OrthogonalMatchingPursuit(LinearModel, RegressorMixin): """Orthogonal Matching Pursuit model (OMP) Parameters ---------- n_nonzero_coefs : int, optional Desired number of non-zero entries in the solution. If None (by default) this value is set to 10% of n_features. tol : float, optional Maximum norm of the residual. If not None, overrides n_nonzero_coefs. fit_intercept : boolean, optional whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). normalize : boolean, optional, default True This parameter is ignored when ``fit_intercept`` is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use :class:`sklearn.preprocessing.StandardScaler` before calling ``fit`` on an estimator with ``normalize=False``. precompute : {True, False, 'auto'}, default 'auto' Whether to use a precomputed Gram and Xy matrix to speed up calculations. Improves performance when `n_targets` or `n_samples` is very large. Note that if you already have such matrices, you can pass them directly to the fit method. Read more in the :ref:`User Guide <omp>`. Attributes ---------- coef_ : array, shape (n_features,) or (n_targets, n_features) parameter vector (w in the formula) intercept_ : float or array, shape (n_targets,) independent term in decision function. n_iter_ : int or array-like Number of active features across every target. Notes ----- Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang, Matching pursuits with time-frequency dictionaries, IEEE Transactions on Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415. (http://blanche.polytechnique.fr/~mallat/papiers/MallatPursuit93.pdf) This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad, M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal Matching Pursuit Technical Report - CS Technion, April 2008. http://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf See also -------- orthogonal_mp orthogonal_mp_gram lars_path Lars LassoLars decomposition.sparse_encode """ def __init__(self, n_nonzero_coefs=None, tol=None, fit_intercept=True, normalize=True, precompute='auto'): self.n_nonzero_coefs = n_nonzero_coefs self.tol = tol self.fit_intercept = fit_intercept self.normalize = normalize self.precompute = precompute def fit(self, X, y): """Fit the model using X, y as training data. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data. y : array-like, shape (n_samples,) or (n_samples, n_targets) Target values. Will be cast to X's dtype if necessary Returns ------- self : object returns an instance of self. """ X, y = check_X_y(X, y, multi_output=True, y_numeric=True) n_features = X.shape[1] X, y, X_offset, y_offset, X_scale, Gram, Xy = \ _pre_fit(X, y, None, self.precompute, self.normalize, self.fit_intercept, copy=True) if y.ndim == 1: y = y[:, np.newaxis] if self.n_nonzero_coefs is None and self.tol is None: # default for n_nonzero_coefs is 0.1 * n_features # but at least one. self.n_nonzero_coefs_ = max(int(0.1 * n_features), 1) else: self.n_nonzero_coefs_ = self.n_nonzero_coefs if Gram is False: coef_, self.n_iter_ = orthogonal_mp( X, y, self.n_nonzero_coefs_, self.tol, precompute=False, copy_X=True, return_n_iter=True) else: norms_sq = np.sum(y ** 2, axis=0) if self.tol is not None else None coef_, self.n_iter_ = orthogonal_mp_gram( Gram, Xy=Xy, n_nonzero_coefs=self.n_nonzero_coefs_, tol=self.tol, norms_squared=norms_sq, copy_Gram=True, copy_Xy=True, return_n_iter=True) self.coef_ = coef_.T self._set_intercept(X_offset, y_offset, X_scale) return self def _omp_path_residues(X_train, y_train, X_test, y_test, copy=True, fit_intercept=True, normalize=True, max_iter=100): """Compute the residues on left-out data for a full LARS path Parameters ----------- X_train : array, shape (n_samples, n_features) The data to fit the LARS on y_train : array, shape (n_samples) The target variable to fit LARS on X_test : array, shape (n_samples, n_features) The data to compute the residues on y_test : array, shape (n_samples) The target variable to compute the residues on copy : boolean, optional Whether X_train, X_test, y_train and y_test should be copied. If False, they may be overwritten. fit_intercept : boolean whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). normalize : boolean, optional, default True This parameter is ignored when ``fit_intercept`` is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use :class:`sklearn.preprocessing.StandardScaler` before calling ``fit`` on an estimator with ``normalize=False``. max_iter : integer, optional Maximum numbers of iterations to perform, therefore maximum features to include. 100 by default. Returns ------- residues : array, shape (n_samples, max_features) Residues of the prediction on the test data """ if copy: X_train = X_train.copy() y_train = y_train.copy() X_test = X_test.copy() y_test = y_test.copy() if fit_intercept: X_mean = X_train.mean(axis=0) X_train -= X_mean X_test -= X_mean y_mean = y_train.mean(axis=0) y_train = as_float_array(y_train, copy=False) y_train -= y_mean y_test = as_float_array(y_test, copy=False) y_test -= y_mean if normalize: norms = np.sqrt(np.sum(X_train ** 2, axis=0)) nonzeros = np.flatnonzero(norms) X_train[:, nonzeros] /= norms[nonzeros] coefs = orthogonal_mp(X_train, y_train, n_nonzero_coefs=max_iter, tol=None, precompute=False, copy_X=False, return_path=True) if coefs.ndim == 1: coefs = coefs[:, np.newaxis] if normalize: coefs[nonzeros] /= norms[nonzeros][:, np.newaxis] return np.dot(coefs.T, X_test.T) - y_test class OrthogonalMatchingPursuitCV(LinearModel, RegressorMixin): """Cross-validated Orthogonal Matching Pursuit model (OMP) Parameters ---------- copy : bool, optional Whether the design matrix X must be copied by the algorithm. A false value is only helpful if X is already Fortran-ordered, otherwise a copy is made anyway. fit_intercept : boolean, optional whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). normalize : boolean, optional, default True This parameter is ignored when ``fit_intercept`` is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use :class:`sklearn.preprocessing.StandardScaler` before calling ``fit`` on an estimator with ``normalize=False``. max_iter : integer, optional Maximum numbers of iterations to perform, therefore maximum features to include. 10% of ``n_features`` but at least 5 if available. cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 3-fold cross-validation, - integer, to specify the number of folds. - An object to be used as a cross-validation generator. - An iterable yielding train/test splits. For integer/None inputs, :class:`KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. n_jobs : integer, optional Number of CPUs to use during the cross validation. If ``-1``, use all the CPUs verbose : boolean or integer, optional Sets the verbosity amount Read more in the :ref:`User Guide <omp>`. Attributes ---------- intercept_ : float or array, shape (n_targets,) Independent term in decision function. coef_ : array, shape (n_features,) or (n_targets, n_features) Parameter vector (w in the problem formulation). n_nonzero_coefs_ : int Estimated number of non-zero coefficients giving the best mean squared error over the cross-validation folds. n_iter_ : int or array-like Number of active features across every target for the model refit with the best hyperparameters got by cross-validating across all folds. See also -------- orthogonal_mp orthogonal_mp_gram lars_path Lars LassoLars OrthogonalMatchingPursuit LarsCV LassoLarsCV decomposition.sparse_encode """ def __init__(self, copy=True, fit_intercept=True, normalize=True, max_iter=None, cv=None, n_jobs=1, verbose=False): self.copy = copy self.fit_intercept = fit_intercept self.normalize = normalize self.max_iter = max_iter self.cv = cv self.n_jobs = n_jobs self.verbose = verbose def fit(self, X, y): """Fit the model using X, y as training data. Parameters ---------- X : array-like, shape [n_samples, n_features] Training data. y : array-like, shape [n_samples] Target values. Will be cast to X's dtype if necessary Returns ------- self : object returns an instance of self. """ X, y = check_X_y(X, y, y_numeric=True, ensure_min_features=2, estimator=self) X = as_float_array(X, copy=False, force_all_finite=False) cv = check_cv(self.cv, classifier=False) max_iter = (min(max(int(0.1 * X.shape[1]), 5), X.shape[1]) if not self.max_iter else self.max_iter) cv_paths = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)( delayed(_omp_path_residues)( X[train], y[train], X[test], y[test], self.copy, self.fit_intercept, self.normalize, max_iter) for train, test in cv.split(X)) min_early_stop = min(fold.shape[0] for fold in cv_paths) mse_folds = np.array([(fold[:min_early_stop] ** 2).mean(axis=1) for fold in cv_paths]) best_n_nonzero_coefs = np.argmin(mse_folds.mean(axis=0)) + 1 self.n_nonzero_coefs_ = best_n_nonzero_coefs omp = OrthogonalMatchingPursuit(n_nonzero_coefs=best_n_nonzero_coefs, fit_intercept=self.fit_intercept, normalize=self.normalize) omp.fit(X, y) self.coef_ = omp.coef_ self.intercept_ = omp.intercept_ self.n_iter_ = omp.n_iter_ return self
bsd-3-clause
synthicity/urbansim
urbansim/urbanchoice/tests/test_interaction.py
3
1744
import numpy as np import numpy.testing as npt import pandas as pd import pytest from .. import interaction as inter @pytest.fixture def choosers(): return pd.DataFrame( {'var1': range(5, 10), 'thing_id': ['a', 'c', 'e', 'g', 'i']}) @pytest.fixture def alternatives(): return pd.DataFrame( {'var2': range(10, 20), 'var3': range(20, 30)}, index=pd.Index([x for x in 'abcdefghij'], name='thing_id')) def test_interaction_dataset_sim(choosers, alternatives): sample, merged, chosen = inter.mnl_interaction_dataset( choosers, alternatives, len(alternatives)) # chosen should be len(choosers) rows * len(alternatives) cols assert chosen.shape == (len(choosers), len(alternatives)) assert chosen[:, 0].sum() == len(choosers) assert chosen[:, 1:].sum() == 0 npt.assert_array_equal( sample, list(alternatives.index.values) * len(choosers)) assert len(merged) == len(choosers) * len(alternatives) npt.assert_array_equal(merged.index.values, sample) assert set(list(merged.columns)) == set([ 'var2', 'var3', 'join_index', 'thing_id', 'var1']) npt.assert_array_equal( merged['var1'].values, choosers['var1'].values.repeat(len(alternatives))) npt.assert_array_equal( merged['thing_id'].values, choosers['thing_id'].values.repeat(len(alternatives))) npt.assert_array_equal( merged['join_index'], choosers.index.values.repeat(len(alternatives))) npt.assert_array_equal( merged['var2'].values, np.tile(alternatives['var2'].values, len(choosers))) npt.assert_array_equal( merged['var3'].values, np.tile(alternatives['var3'].values, len(choosers)))
bsd-3-clause
Keleir/glances
glances/core/glances_main.py
11
15502
# -*- coding: utf-8 -*- # # This file is part of Glances. # # Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com> # # Glances is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Glances is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Glances main class.""" # Import system libs import argparse import os import sys import tempfile # Import Glances libs from glances.core.glances_config import Config from glances.core.glances_globals import appname, is_linux, is_windows, psutil_version, version from glances.core.glances_logging import logger class GlancesMain(object): """Main class to manage Glances instance.""" # Default stats' refresh time is 3 seconds refresh_time = 3 # Set the default cache lifetime to 1 second (only for server) # !!! Todo: configuration from the command line cached_time = 1 # By default, Glances is ran in standalone mode (no client/server) client_tag = False # Server TCP port number (default is 61209) server_port = 61209 # Web Server TCP port number (default is 61208) web_server_port = 61208 # Default username/password for client/server mode username = "glances" password = "" # Exemple of use example_of_use = "\ Examples of use:\n\ \n\ Monitor local machine (standalone mode):\n\ $ glances\n\ \n\ Monitor local machine with the Web interface (Web UI):\n\ $ glances -w\n\ Glances web server started on http://0.0.0.0:61208/\n\ \n\ Monitor local machine and export stats to a CSV file (standalone mode):\n\ $ glances --export-csv\n\ \n\ Monitor local machine and export stats to a InfluxDB server with 5s refresh time (standalone mode):\n\ $ glances -t 5 --export-influxdb\n\ \n\ Start a Glances server (server mode):\n\ $ glances -s\n\ \n\ Connect Glances to a Glances server (client mode):\n\ $ glances -c <ip_server>\n\ \n\ Connect Glances to a Glances server and export stats to a StatsD server (client mode):\n\ $ glances -c <ip_server> --export-statsd\n\ \n\ Start the client browser (browser mode):\n\ $ glances --browser\n\ " def __init__(self): """Manage the command line arguments.""" self.args = self.parse_args() def init_args(self): """Init all the command line arguments.""" _version = "Glances v" + version + " with psutil v" + psutil_version parser = argparse.ArgumentParser( prog=appname, conflict_handler='resolve', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=self.example_of_use) parser.add_argument( '-V', '--version', action='version', version=_version) parser.add_argument('-d', '--debug', action='store_true', default=False, dest='debug', help='enable debug mode') parser.add_argument('-C', '--config', dest='conf_file', help='path to the configuration file') # Enable or disable option on startup parser.add_argument('--disable-network', action='store_true', default=False, dest='disable_network', help='disable network module') parser.add_argument('--disable-ip', action='store_true', default=False, dest='disable_ip', help='disable IP module') parser.add_argument('--disable-diskio', action='store_true', default=False, dest='disable_diskio', help='disable disk I/O module') parser.add_argument('--disable-fs', action='store_true', default=False, dest='disable_fs', help='disable filesystem module') parser.add_argument('--disable-sensors', action='store_true', default=False, dest='disable_sensors', help='disable sensors module') parser.add_argument('--disable-hddtemp', action='store_true', default=False, dest='disable_hddtemp', help='disable HD temperature module') parser.add_argument('--disable-raid', action='store_true', default=False, dest='disable_raid', help='disable RAID module') parser.add_argument('--disable-docker', action='store_true', default=False, dest='disable_docker', help='disable Docker module') parser.add_argument('--disable-left-sidebar', action='store_true', default=False, dest='disable_left_sidebar', help='disable network, disk I/O, FS and sensors modules (py3sensors needed)') parser.add_argument('--disable-process', action='store_true', default=False, dest='disable_process', help='disable process module') parser.add_argument('--disable-log', action='store_true', default=False, dest='disable_log', help='disable log module') parser.add_argument('--disable-quicklook', action='store_true', default=False, dest='disable_quicklook', help='disable quick look module') parser.add_argument('--disable-bold', action='store_false', default=True, dest='disable_bold', help='disable bold mode in the terminal') parser.add_argument('--enable-process-extended', action='store_true', default=False, dest='enable_process_extended', help='enable extended stats on top process') parser.add_argument('--enable-history', action='store_true', default=False, dest='enable_history', help='enable the history mode (matplotlib needed)') parser.add_argument('--path-history', default=tempfile.gettempdir(), dest='path_history', help='set the export path for graph history') # Export modules feature parser.add_argument('--export-csv', default=None, dest='export_csv', help='export stats to a CSV file') parser.add_argument('--export-influxdb', action='store_true', default=False, dest='export_influxdb', help='export stats to an InfluxDB server (influxdb needed)') parser.add_argument('--export-statsd', action='store_true', default=False, dest='export_statsd', help='export stats to a StatsD server (statsd needed)') parser.add_argument('--export-rabbitmq', action='store_true', default=False, dest='export_rabbitmq', help='export stats to rabbitmq broker (pika needed)') # Client/Server option parser.add_argument('-c', '--client', dest='client', help='connect to a Glances server by IPv4/IPv6 address or hostname') parser.add_argument('-s', '--server', action='store_true', default=False, dest='server', help='run Glances in server mode') parser.add_argument('--browser', action='store_true', default=False, dest='browser', help='start the client browser (list of servers)') parser.add_argument('--disable-autodiscover', action='store_true', default=False, dest='disable_autodiscover', help='disable autodiscover feature') parser.add_argument('-p', '--port', default=None, type=int, dest='port', help='define the client/server TCP port [default: {0}]'.format(self.server_port)) parser.add_argument('-B', '--bind', default='0.0.0.0', dest='bind_address', help='bind server to the given IPv4/IPv6 address or hostname') parser.add_argument('--password', action='store_true', default=False, dest='password_prompt', help='define a client/server password') parser.add_argument('--snmp-community', default='public', dest='snmp_community', help='SNMP community') parser.add_argument('--snmp-port', default=161, type=int, dest='snmp_port', help='SNMP port') parser.add_argument('--snmp-version', default='2c', dest='snmp_version', help='SNMP version (1, 2c or 3)') parser.add_argument('--snmp-user', default='private', dest='snmp_user', help='SNMP username (only for SNMPv3)') parser.add_argument('--snmp-auth', default='password', dest='snmp_auth', help='SNMP authentication key (only for SNMPv3)') parser.add_argument('--snmp-force', action='store_true', default=False, dest='snmp_force', help='force SNMP mode') parser.add_argument('-t', '--time', default=self.refresh_time, type=float, dest='time', help='set refresh time in seconds [default: {0} sec]'.format(self.refresh_time)) parser.add_argument('-w', '--webserver', action='store_true', default=False, dest='webserver', help='run Glances in web server mode (bottle needed)') # Display options parser.add_argument('-q', '--quiet', default=False, action='store_true', dest='quiet', help='do not display the curses interface') parser.add_argument('-f', '--process-filter', default=None, type=str, dest='process_filter', help='set the process filter pattern (regular expression)') parser.add_argument('--process-short-name', action='store_true', default=False, dest='process_short_name', help='force short name for processes name') if not is_windows: parser.add_argument('--hide-kernel-threads', action='store_true', default=False, dest='no_kernel_threads', help='hide kernel threads in process list') if is_linux: parser.add_argument('--tree', action='store_true', default=False, dest='process_tree', help='display processes as a tree') parser.add_argument('-b', '--byte', action='store_true', default=False, dest='byte', help='display network rate in byte per second') parser.add_argument('-1', '--percpu', action='store_true', default=False, dest='percpu', help='start Glances in per CPU mode') parser.add_argument('--fs-free-space', action='store_false', default=False, dest='fs_free_space', help='display FS free space instead of used') parser.add_argument('--theme-white', action='store_true', default=False, dest='theme_white', help='optimize display colors for white background') return parser def parse_args(self): """Parse command line arguments.""" args = self.init_args().parse_args() # Load the configuration file, if it exists self.config = Config(args.conf_file) # Debug mode if args.debug: from logging import DEBUG logger.setLevel(DEBUG) # Client/server Port if args.port is None: if args.webserver: args.port = self.web_server_port else: args.port = self.server_port # Autodiscover if args.disable_autodiscover: logger.info("Auto discover mode is disabled") # In web server mode, defaul refresh time: 5 sec if args.webserver: args.time = 5 args.process_short_name = True # Server or client login/password args.username = self.username if args.password_prompt: # Interactive or file password if args.server: args.password = self.__get_password( description='Define the password for the Glances server', confirm=True) elif args.client: args.password = self.__get_password( description='Enter the Glances server password', clear=True) else: # Default is no password args.password = self.password # By default help is hidden args.help_tag = False # Display Rx and Tx, not the sum for the network args.network_sum = False args.network_cumul = False # Control parameter and exit if it is not OK self.args = args # Filter is only available in standalone mode if args.process_filter is not None and not self.is_standalone(): logger.critical("Process filter is only available in standalone mode") sys.exit(2) # Check graph output path if args.enable_history and args.path_history is not None: if not os.access(args.path_history, os.W_OK): logger.critical("History output path {0} do not exist or is not writable".format(args.path_history)) sys.exit(2) logger.debug("History output path is set to {0}".format(args.path_history)) # Disable HDDTemp if sensors are disabled if args.disable_sensors: args.disable_hddtemp = True logger.debug("Sensors and HDDTemp are disabled") return args def __hash_password(self, plain_password): """Hash a plain password and return the hashed one.""" from glances.core.glances_password import GlancesPassword password = GlancesPassword() return password.hash_password(plain_password) def __get_password(self, description='', confirm=False, clear=False): """Read a password from the command line. - if confirm = True, with confirmation - if clear = True, plain (clear password) """ from glances.core.glances_password import GlancesPassword password = GlancesPassword() return password.get_password(description, confirm, clear) def is_standalone(self): """Return True if Glances is running in standalone mode.""" return not self.args.client and not self.args.browser and not self.args.server and not self.args.webserver def is_client(self): """Return True if Glances is running in client mode.""" return (self.args.client or self.args.browser) and not self.args.server def is_client_browser(self): """Return True if Glances is running in client browser mode.""" return self.args.browser and not self.args.server def is_server(self): """Return True if Glances is running in server mode.""" return not self.args.client and self.args.server def is_webserver(self): """Return True if Glances is running in Web server mode.""" return not self.args.client and self.args.webserver def get_config(self): """Return configuration file object.""" return self.config def get_args(self): """Return the arguments.""" return self.args
lgpl-3.0
IBT-FMI/SAMRI
samri/pipelines/extra_functions.py
1
36883
# -*- coding: utf-8 -*- import csv import inspect import os import re import json import shutil from copy import deepcopy import pandas as pd # PyBIDS 0.6.5 and 0.10.2 compatibility try: from bids.grabbids import BIDSLayout except ModuleNotFoundError: from bids.layout import BIDSLayout BEST_GUESS_MODALITY_MATCH = { ('FLASH',):'T1w', ('TurboRARE','TRARE'):'T2w', } BIDS_METADATA_EXTRACTION_DICTS = [ {'field_name':'EchoTime', 'query_file':'method', 'regex':r'^##\$EchoTime=(?P<value>.*?)$', 'scale': 1./1000., 'type': float, }, {'field_name':'FlipAngle', 'query_file':'visu_pars', 'regex':r'^##\$VisuAcqFlipAngle=(?P<value>.*?)$', 'type': float, }, {'field_name':'Manufacturer', 'query_file':'configscan', 'regex':r'^##ORIGIN=(?P<value>.*?)$', }, {'field_name':'NumberOfVolumesDiscardedByScanner', 'query_file':'method', 'regex':r'^##\$PVM_DummyScans=(?P<value>.*?)$', 'type': int, }, {'field_name':'ReceiveCoilName', 'query_file':'configscan', 'regex':r'.*?,COILTABLE,1#\$Name,(?P<value>.*?)#\$Id.*?', }, {'field_name':'RepetitionTime', 'query_file':'method', 'regex':r'^##\$PVM_RepetitionTime=(?P<value>.*?)$', 'scale': 1./1000., 'type': float, }, {'field_name':'PulseSequenceType', 'query_file':'method', 'regex':r'^##\$Method=<Bruker:(?P<value>.*?)>$', }, ] MODALITY_MATCH = { ('BOLD','bold','Bold'):'bold', ('CBV','cbv','Cbv'):'cbv', ('T1','t1'):'T1w', ('T2','t2'):'T2w', ('MTon','MtOn'):'MTon', ('MToff','MtOff'):'MToff', } def extract_volumes(in_files, volume, axis=3, out_files_base='extracted_volume.nii.gz' ): """ Iterative wrapper for `samri.pipelines.extract.volume` """ from samri.pipelines.extra_functions import extract_volume from os import path out_files=[] for ix, in_file in enumerate(in_files): out_file = '{}_{}'.format(ix, out_files_base) out_file = path.abspath(path.expanduser(out_file)) extract_volume(in_file, volume, axis=axis, out_file=out_file) out_files.append(out_file) return out_files def extract_volume(in_file, volume, axis=3, out_file='extracted_volume.nii.gz' ): """ Extract one volume from a given axis of a NIfTI file. Parameters ---------- in_file : string Path to a NIfTI file with more than one volume on the selected axis. volume : int The volume on the selected axis which to extract. Volume numbering starts at zero. axis : int The axis which to select the volume on. Axis numbering starts at zero. """ import nibabel as nib import numpy as np img = nib.load(in_file) data = img.get_data() extracted_data = np.rollaxis(data,axis)[volume] img_ = nib.Nifti1Image(extracted_data, img.affine, img.header) nib.save(img_,out_file) def reset_background(in_file, bg_value=0, out_file='background_reset_complete.nii.gz', restriction_range='auto', ): """ Set the background voxel value of a 4D NIfTI time series to a given value. It is sometimes necessary to perform this function, as some workflows may populate the background with values which may confuse statistics further downstream. Background voxels are not specifically highlighted, we define the background as the mode of any image, assuming there is decisively more background than any other one level of the contrast. If your data for some reason does not satisfy this assumption, the function will not behave correctly. Parameters ---------- in_file : string File for which to reset background values. bg_value : float, optional What value to insert in voxels identified as background. out_file : str, optional Path where the background reset NIfTI image will be written. restriction_range : int or string, optional What restricted range (if any) to use as the bounding box for the image area on which the mode is actually determined. If auto, the mode is determined on a bounding box the size of the smallest spatial axis. If the variable evaluates as false, no restriction will be used and the mode will be calculated given all spatial data --- which can be extremely time-consuming. """ import nibabel as nib import numpy as np from scipy import stats img = nib.load(in_file) data = img.get_data() number_of_slices = np.shape(data)[3] if restriction_range == 'auto': restriction_range = min(np.shape(data)[:3]) for i in range(number_of_slices): if not restriction_range: old_bg_value = stats.mode(data[:,:,:,i]) else: old_bg_value = stats.mode(data[:restriction_range,:restriction_range,:restriction_range,i].flatten()) old_bg_value = old_bg_value.mode[0] data[:,:,:,i][data[:,:,:,i]==old_bg_value] = bg_value img_ = nib.Nifti1Image(data, img.affine, img.header) nib.save(img_,out_file) def force_dummy_scans(in_file, desired_dummy_scans=10, out_file="forced_dummy_scans_file.nii.gz", ): """Take a scan and crop initial timepoints depending upon the number of dummy scans (determined from a Bruker scan directory) and the desired number of dummy scans. in_file : string BIDS-compliant path to the 4D NIfTI file for which to force dummy scans. desired_dummy_scans : int , optional Desired timepoints dummy scans. """ import json import nibabel as nib from os import path out_file = path.abspath(path.expanduser(out_file)) in_file = path.abspath(path.expanduser(in_file)) in_file_dir = path.dirname(in_file) in_file_name = path.basename(in_file) in_file_noext = in_file_name.split('.', 1)[0] metadata_file = path.join(in_file_dir, in_file_noext+'.json') metadata = json.load(open(metadata_file)) dummy_scans = 0 try: dummy_scans = metadata['NumberOfVolumesDiscardedByScanner'] except: pass delete_scans = desired_dummy_scans - dummy_scans img = nib.load(in_file) if delete_scans <= 0: nib.save(img,out_file) else: img_ = nib.Nifti1Image(img.get_data()[...,delete_scans:], img.affine, img.header) nib.save(img_,out_file) deleted_scans = delete_scans return out_file, deleted_scans def get_tr(in_file, ndim=4, ): """Return the repetiton time of a NIfTI file. Parameters ---------- in_file : str Path to NIfTI file ndim : int Dimensionality of NIfTI file Returns ------- float : Repetition Time """ import nibabel as nib from os import path in_file = path.abspath(path.expanduser(in_file)) img = nib.load(in_file) header = img.header tr = header.get_zooms()[ndim-1] return tr def write_bids_metadata_file(scan_dir, extraction_dicts, out_file="bids_metadata.json", task='', ): """Create a sidecar JSON file according to the BIDS standard. Parameters ---------- scan_dir : str Path to the scan directory containing the acquisition protocol files. extraction_dicts : str A list of dictionaries which contain keys including `query_file` (which specifies the file, relative to `scan dir`, which to query), `regex` (which gives a regex expression which will be tested against each rowin the file until a match is found), and `field_name` (which specifies under what field name to record this value in the JSON file). Additionally, the following keys are also supported: `type` (a python class operator, e.g. `str` to which the value should be converted), and `scale` (a float with which the value is multiplied before recording in JSON). out_file : str, optional Path under which to save the resulting JSON. task_name : str, optional String value to assign to the "TaskName" field in the BIDS JSON. If this parameter evaluates to false, no "TaskName" will be recorded. """ import json import re from os import path from samri.pipelines.utils import parse_paravision_date out_file = path.abspath(path.expanduser(out_file)) scan_dir = path.abspath(path.expanduser(scan_dir)) metadata = {} # Extract parameters which are nicely accessible in the Bruker files: for extraction_dict in extraction_dicts: try: query_file = path.abspath(path.join(scan_dir,extraction_dict['query_file'])) with open(query_file) as search: for line in search: if re.match(extraction_dict['regex'], line): m = re.match(extraction_dict['regex'], line) value = m.groupdict()['value'] try: value = extraction_dict['type'](value) except KeyError: pass try: value = value * extraction_dict['scale'] except KeyError: pass metadata[extraction_dict['field_name']] = value break except FileNotFoundError: pass # Extract DelayAfterTrigger try: query_file = path.abspath(path.join(scan_dir,'AdjStatePerScan')) read_line = False with open(query_file) as search: for line in search: if '##$AdjScanStateTime=( 2 )' in line: read_line = True continue if read_line: m = re.match(r'^<(?P<value>.*?)> <.*?>$', line) adjustments_start = m.groupdict()['value'] adjustments_start = parse_paravision_date(adjustments_start) break except IOError: pass else: query_file = path.abspath(path.join(scan_dir,'acqp')) with open(query_file) as search: for line in search: if re.match(r'^##\$ACQ_time=<.*?>$', line): m = re.match(r'^##\$ACQ_time=<(?P<value>.*?)>$', line) adjustments_end = m.groupdict()['value'] adjustments_end = parse_paravision_date(adjustments_end) break try: adjustments_duration = adjustments_end - adjustments_start except UnboundLocalError: metadata['DelayAfterTrigger'] = 0 else: metadata['DelayAfterTrigger'] = adjustments_duration.total_seconds() if task: metadata['TaskName'] = task with open(out_file, 'w') as out_file_writeable: json.dump(metadata, out_file_writeable, indent=1) out_file_writeable.write("\n") # `json.dump` does not add a newline at the end; we do it here. return out_file def eventfile_add_habituation(in_file, amplitude_column='', discriminant_column='samri_l1_regressors', original_stimulation_value='stim', habituation_value='habituation', out_file="events.tsv", ): """Add habituation events to be used as regressors in BIDS file. Parameters ---------- in_file : str Path to TSV file with columns including 'onset' (formatted e.g. according to the BIDS specification). out_file : str, optional Path to which to write the adjusted events file Returns ------- str : Path to which the adjusted events file was saved. """ import pandas as pd from copy import deepcopy from os import path in_file = path.abspath(path.expanduser(in_file)) out_file = path.abspath(path.expanduser(out_file)) df = pd.read_csv(in_file, sep="\t") # We need to ascertain events are listed in progressive chronological order. df = df.sort_values(by=['onset'], ascending=True) df[discriminant_column] = "" df[discriminant_column] = original_stimulation_value df_ = deepcopy(df) df_[discriminant_column] = habituation_value total_events=len(df) habituation_amplitudes = [i for i in range(total_events)[::-1]] if not amplitude_column: amplitude_column='samri_l1_amplitude' df_[amplitude_column] = habituation_amplitudes df[amplitude_column] = [1]*total_events df = pd.concat([df,df_], sort=False) df.to_csv(out_file, sep=str('\t'), index=False) return out_file def write_bids_physio_file(scan_dir, out_file='physio.tsv', forced_dummy_scans=0., nii_name=False, ): """Create a BIDS physiology recording ("physio") file, based on available data files in the scan directory. Parameters ---------- scan_dir : str ParaVision scan directory path, containing one or more files prefixed with "physio_". out_file : str, optional Path to which to write the adjusted physiology file. Returns ------- out_file : str Path to which the collapsed physiology file was saved. out_file : str Path to which the collapsed physiology metadata file was saved. """ import csv import json import os if nii_name: nii_basename, ext = os.path.splitext(nii_name) if ext == '.gz': nii_basename, ext = os.path.splitext(nii_name) nii_basename_segments = nii_basename.split('_') nii_basename_segments = [i for i in nii_basename_segments if '-' in i] nii_basename = '_'.join(nii_basename_segments) out_file = '{}_physio.tsv'.format(nii_basename) out_file = os.path.abspath(os.path.expanduser(out_file)) scan_dir = os.path.abspath(os.path.expanduser(scan_dir)) physio_prefix = 'physio_' scan_dir_contents = os.listdir(scan_dir) physio_files = [i for i in scan_dir_contents if (physio_prefix in i)] if physio_files: physio_files = [os.path.join(scan_dir, i) for i in physio_files] else: return '/dev/null' physio_columns = [] column_names = [] start_times = [] sampling_frequencies = [] for physio_file in physio_files: if physio_file.endswith('.1D'): f = open(physio_file, 'r') physio_column = f.read() physio_column = physio_column.split(' ') physio_column = [float(i.split('*')[1]) for i in physio_column if i != ''] physio_columns.append(physio_column) column_name = os.path.basename(physio_file) column_name, _ = os.path.splitext(column_name) column_name = column_name[len(physio_prefix):] column_names.append(column_name) start_times.append(60) sampling_frequencies.append(1) column_lengths = [len(i) for i in physio_columns] # check if all regressors are of the same length, as this would otherwise break list transposition. if len(set(column_lengths)) != 1: max_len = max(column_lengths) for physio_column in physio_columns: physio_column += ['n/a'] * (max_len - len(physio_column)) physio_rows = [list(i) for i in zip(*physio_columns)] out_file = os.path.abspath(os.path.expanduser(out_file)) with open(out_file, 'w') as tsvfile: writer = csv.writer(tsvfile, delimiter='\t', lineterminator='\n') for physio_row in physio_rows: writer.writerow(physio_row) if len(set(start_times)) == 1: start_times = start_times[0] if len(set(sampling_frequencies)) == 1: sampling_frequencies = sampling_frequencies[0] physio_metadata = {} physio_metadata['SamplingFrequency'] = sampling_frequencies physio_metadata['Start_Time'] = start_times physio_metadata['Columns'] = column_names physio_metadata_name,_ = os.path.splitext(out_file) out_metadata_file = '{}.json'.format(physio_metadata_name) out_metadata_file = os.path.abspath(os.path.expanduser(out_metadata_file)) with open(out_metadata_file, 'w') as f: json.dump(physio_metadata, f, indent=1) f.write("\n") # `json.dump` does not add a newline at the end; we do it here. return out_file, out_metadata_file def write_bids_events_file(scan_dir, db_path="~/syncdata/meta.db", metadata_file='', out_file="events.tsv", prefer_labbookdb=False, timecourse_file='', task='', forced_dummy_scans=0., ): """Adjust a BIDS event file to reflect delays introduced after the trigger and before the scan onset. Parameters ---------- scan_dir : str ParaVision scan directory path. db_path : str, optional LabbookDB database file path from which to source the evets profile for the identifier assigned to the `task` parameter. metadata_file : str, optional Path to a BIDS metadata file. out_file : str, optional Path to which to write the adjusted events file prefer_labbookdb : bool, optional Whether to query the events file in the LabbookDB database file first (rather than look for the events file in the scan directory). timecourse_file : str, optional Path to a NIfTI file. task : str, optional Task identifier from a LabbookDB database. Returns ------- str : Path to which the adjusted events file was saved. """ import csv import sys import json import os import pandas as pd import nibabel as nib import numpy as np from datetime import datetime out_file = os.path.abspath(os.path.expanduser(out_file)) scan_dir = os.path.abspath(os.path.expanduser(scan_dir)) db_path = os.path.abspath(os.path.expanduser(db_path)) if not prefer_labbookdb: try: scan_dir_contents = os.listdir(scan_dir) sequence_files = [i for i in scan_dir_contents if ("sequence" in i and "tsv" in i)] if sequence_files: sequence_file = os.path.join(scan_dir, sequence_files[0]) else: timecourse_dir = os.path.dirname(timecourse_file) timecourse_name = os.path.basename(timecourse_file) stripped_name = timecourse_name.split('.', 1)[0].rsplit('_', 1)[0] sequence_file = os.path.join(timecourse_dir,stripped_name+'_events.tsv') mydf = pd.read_csv(sequence_file, sep="\s", engine='python') except: if os.path.isfile(db_path): from labbookdb.report.tracking import bids_eventsfile mydf = bids_eventsfile(db_path, task) else: return '/dev/null' else: try: if os.path.isfile(db_path): from labbookdb.report.tracking import bids_eventsfile mydf = bids_eventsfile(db_path, task) else: return '/dev/null' except ImportError: scan_dir_contents = os.listdir(scan_dir) sequence_files = [i for i in scan_dir_contents if ("sequence" in i and "tsv" in i)] if sequence_files: sequence_file = os.path.join(scan_dir, sequence_files[0]) else: timecourse_dir = os.path.dirname(timecourse_file) timecourse_name = os.path.basename(timecourse_file) stripped_name = timecourse_name.split('.', 1)[0].rsplit('_', 1)[0] sequence_file = os.path.join(timecourse_dir,stripped_name+'_events.tsv') mydf = pd.read_csv(sequence_file, sep="\s", engine='python') timecourse_file = os.path.abspath(os.path.expanduser(timecourse_file)) timecourse = nib.load(timecourse_file) zooms = timecourse.header.get_zooms() tr = float(zooms[-1]) delay = 0. if forced_dummy_scans: delay = forced_dummy_scans * tr elif metadata_file: metadata_file = os.path.abspath(os.path.expanduser(metadata_file)) with open(metadata_file) as metadata: metadata = json.load(metadata) try: delay += metadata['NumberOfVolumesDiscardedByScanner'] * tr except: pass try: delay += metadata['DelayAfterTrigger'] except: pass mydf['onset'] = mydf['onset'] - delay # 'n/a' specifically required by BIDS, as a consequence of its infinite wisdom mydf.to_csv(out_file, sep=str('\t'), na_rep='n/a', index=False) return out_file def physiofile_ts(in_file, column_name, save=True, ): """Based on a BIDS timecourse path and a physiological regressor name, get the corresponding timecourse.""" from os import path import json import nibabel as nib img = nib.load(in_file) nii_dir = path.dirname(in_file) nii_name = path.basename(in_file) stripped_name = nii_name.split('.', 1)[0].rsplit('_', 1)[0] physiofile = path.join(nii_dir,stripped_name+'_physio.tsv') physiofile_meta = path.join(nii_dir,stripped_name+'_physio.json') with open(physiofile_meta, 'r') as json_file: metadata = json.load(json_file) columns = metadata['Columns'] with open(physiofile, 'r') as f: physios = f.read().split('\n') physios = [i.split('\t') for i in physios if i != ''] physios = [list(map(float, sublist)) for sublist in physios] physios = [list(i) for i in zip(*physios)] ts_index = columns.index(column_name) ts = physios[ts_index] duration_img = img.header['dim'][4] duration_physios = len(ts) if duration_physios > duration_img: ts = ts[:duration_img] elif duration_img > duration_physios: data = img.get_data() data = data[:,:,:,:duration_physios] img = nib.Nifti1Image(data, img.affine, img.header) if save: nib.save(img, nii_name) nii_file = path.abspath(path.expanduser(nii_name)) elif isinstance(save, str): save = path.abspath(path.expanduser(save)) nib_save(img, save) nii_file = save else: nii_file = img return nii_file, ts def corresponding_physiofile(nii_path): """Based on a BIDS timecourse path, get the corresponding BIDS physiology file.""" from os import path nii_dir = path.dirname(nii_path) nii_name = path.basename(nii_path) stripped_name = nii_name.split('.', 1)[0].rsplit('_', 1)[0] physiofile = path.join(nii_dir,stripped_name+'_physio.tsv') meta_physiofile = path.join(nii_dir,stripped_name+'_physio.json') if not path.isfile(physiofile): physiofile = '' if not path.isfile(meta_physiofile): meta_physiofile = '' return physiofile, meta_physiofile def corresponding_eventfile(timecourse_file, as_list=False): """Based on a BIDS timecourse path, get the corresponding BIDS eventfile.""" from os import path timecourse_dir = path.dirname(timecourse_file) timecourse_name = path.basename(timecourse_file) stripped_name = timecourse_name.split('.', 1)[0].rsplit('_', 1)[0] eventfile = path.join(timecourse_dir,stripped_name+'_events.tsv') if as_list: return [eventfile,] else: return eventfile def get_bids_scan(data_selection, bids_base="", ind_type="", selector=None, subject=None, session=None, extra=['acq','run'], ): """Description... Parameters ---------- bids_base : str Path to the bids base path. data_selection : pandas.DataFrame A `pandas.DataFrame` object as produced by `samri.preprocessing.extra_functions.get_data_selection()`. selector : iterable, optional The first method of selecting the subject and scan, this value should be a length-2 list or tuple containing the subject and sthe session to be selected. subject : string, optional This has to be defined if `selector` is not defined. The subject for which to return a scan directory. session : string, optional This has to be defined if `selector` is not defined. The session for which to return a scan directory. """ import os #for some reason the import outside the function fails import pandas as pd from samri.pipelines.utils import bids_naming filtered_data = [] if selector: subject = selector[0] session = selector[1] filtered_data = data_selection[(data_selection["session"] == session)&(data_selection["subject"] == subject)] else: filtered_data = data_selection[data_selection.index==ind_type] if filtered_data.empty: raise Exception("SAMRIError: Does not exist: " + str(selector[0]) + str(selector[1]) + str(ind_type)) else: subject = filtered_data['subject'].item() session = filtered_data['session'].item() try: typ = filtered_data['type'].item() except: typ = "" try: task = filtered_data['task'].item() except: task = "" subject_session = [subject, session] #scan_path = os.path.join(bids_base, 'sub-' + subject + '/', 'ses-' + session + '/', typ ) try: nii_path = filtered_data['path'].item() except KeyError: nii_path = filtered_data['measurement'].item() nii_path += '/'+filtered_data['scan'].item() nii_name = bids_naming(subject_session, filtered_data, extra=extra, extension='', ) scan_path = nii_path else: scan_path = os.path.dirname(nii_path) nii_name = os.path.basename(nii_path) eventfile_name = bids_naming(subject_session, filtered_data, extra=extra, extension='.tsv', suffix='events' ) metadata_filename = bids_naming(subject_session, filtered_data, extra=extra, extension='.json', ) dict_slice = filtered_data.to_dict('records')[0] return scan_path, typ, task, nii_path, nii_name, eventfile_name, subject_session, metadata_filename, dict_slice, ind_type BIDS_KEY_DICTIONARY = { 'acquisition':['acquisition','ACQUISITION','acq','ACQ'], 'task':['task','TASK','stim','STIM','stimulation','STIMULATION'], } def assign_modality(scan_type, record): """ Add a modality column with a corresponding value to a `pandas.DataFrame` object. Parameters ---------- scan_type: str A string potentially containing a modality identifier. record: pandas.DataFrame A `pandas.Dataframe` object. Returns ------- An updated `pandas.DataFrame` object. Notes ----- The term "modality" is ambiguous in BIDS; here we use it to mean what is better though of as "contrast": https://github.com/bids-standard/bids-specification/pull/119 """ for modality_group in MODALITY_MATCH: for modality_string in modality_group: if modality_string in scan_type: record['modality'] = MODALITY_MATCH[modality_group] return scan_type, record for modality_group in BEST_GUESS_MODALITY_MATCH: for modality_string in modality_group: if modality_string in scan_type: record['modality'] = BEST_GUESS_MODALITY_MATCH[modality_group] return scan_type, record return scan_type, record def match_exclude_ss(entry, match, exclude, record, key): """Return true if an entry is to be accepted based on the match and exclude criteria.""" try: exclude_list = exclude[key] + [str(i) for i in exclude[key]] except KeyError: exclude_list = [] try: match_list = match[key] + [str(i) for i in match[key]] except KeyError: match_list = [] if entry not in exclude_list: if len(match_list) > 0 and (entry not in match_list or str(entry) not in match_list): return False record[key] = str(entry).strip(' ') return True else: return False def get_data_selection(workflow_base, match={}, exclude={}, measurements=[], exclude_measurements=[], count_runs=False, fail_suffix='_failed', ): """ Return a `pandas.DataFrame` object of the Bruker measurement directories located under a given base directory, and their respective scans, subjects, and tasks. Parameters ---------- workflow_base : str The path in which to query for Bruker measurement directories. match : dict A dictionary of matching criteria. The keys of this dictionary must be full BIDS key names (e.g. "task" or "acquisition"), and the values must be strings (e.g. "CogB") which, combined with the respective BIDS key, identify scans to be included (e.g. scans, the names of which containthe string "task-CogB" - delimited on either side by an underscore or the limit of the string). exclude : dict, optional A dictionary of exclusion criteria. The keys of this dictionary must be full BIDS key names (e.g. "task" or "acquisition"), and the values must be strings (e.g. "CogB") which, combined with the respective BIDS key, identify scans to be excluded(e.g. a scans, the names of which contain the string "task-CogB" - delimited on either side by an underscore or the limit of the string). measurements : list of str, optional A list of measurement directory names to be included exclusively (i.e. whitelist). If the list is empty, all directories (unless explicitly excluded via `exclude_measurements`) will be queried. exclude_measurements : list of str, optional A list of measurement directory names to be excluded from querying (i.e. a blacklist). Notes ----- This data selector function is robust to `ScanProgram.scanProgram` files which have been truncated before the first detected match, but not to files truncated after at least one match. """ workflow_base = os.path.abspath(os.path.expanduser(workflow_base)) if not measurements: measurements = os.listdir(workflow_base) measurement_path_list = [os.path.join(workflow_base,i) for i in measurements] selected_measurements=[] # Create a dummy path for bidsgrabber to parse file names from. # Ideally we could avoid this: https://github.com/bids-standard/pybids/issues/633 bids_temppath = '/var/tmp/samri_bids_temppaths/' try: os.mkdir(bids_temppath) except FileExistsError: pass data = {} data['Name'] = '' data['BIDSVersion'] = '' with open(os.path.join(bids_temppath,'dataset_description.json'), 'w') as outfile: json.dump(data, outfile) layout = BIDSLayout(bids_temppath) #populate a list of lists with acceptable subject names, sessions, and sub_dir's for sub_dir in measurement_path_list: if sub_dir not in exclude_measurements: run_counter = 0 selected_measurement = {} try: state_file = open(os.path.join(workflow_base,sub_dir,"subject"), "r") read_variables=0 #count variables so that breaking takes place after both have been read while True: current_line = state_file.readline() if "##$SUBJECT_id=" in current_line: entry=re.sub("[<>\n]", "", state_file.readline()) if not match_exclude_ss(entry, match, exclude, selected_measurement, 'subject'): break read_variables +=1 #count recorded variables if "##$SUBJECT_study_name=" in current_line: entry=re.sub("[<>\n]", "", state_file.readline()) if not match_exclude_ss(entry, match, exclude, selected_measurement, 'session'): break read_variables +=1 #count recorded variables if "##$SUBJECT_position=SUBJ_POS_" in current_line: m = re.match(r'^##\$SUBJECT_position=SUBJ_POS_(?P<position>.+?)$', current_line) position = m.groupdict()['position'] read_variables +=1 #count recorded variables selected_measurement['PV_position'] = position if read_variables == 3: selected_measurement['measurement'] = sub_dir scan_program_file = os.path.join(workflow_base,sub_dir,"ScanProgram.scanProgram") scan_dir_resolved = False try: with open(scan_program_file) as search: for line in search: line_considered = True measurement_copy = deepcopy(selected_measurement) if re.match(r'^[ \t]+<displayName>[a-zA-Z0-9-_]+? \(E\d+\)</displayName>[\r\n]+', line): if fail_suffix and re.match(r'^.+?{} \(E\d+\)</displayName>[\r\n]+'.format(fail_suffix), line): continue m = re.match(r'^[ \t]+<displayName>(?P<scan_type>.+?) \(E(?P<number>\d+)\)</displayName>[\r\n]+', line) number = m.groupdict()['number'] scan_type = m.groupdict()['scan_type'] bids_keys = layout.parse_file_entities('{}/{}'.format(bids_temppath,scan_type)) for key in match: # Session and subject fields are not recorded in scan_type and were already checked at this point. if key in ['session', 'subject']: continue try: if bids_keys[key] not in match[key]: line_considered = False break except KeyError: line_considered = False break if line_considered: measurement_copy['scan_type'] = str(scan_type).strip(' ') measurement_copy['scan'] = str(int(number)) measurement_copy['run'] = run_counter scan_type, measurement_copy = assign_modality(scan_type, measurement_copy) measurement_copy.update(bids_keys) run_counter += 1 selected_measurements.append(measurement_copy) scan_dir_resolved = True if not scan_dir_resolved: raise IOError() except IOError: for sub_sub_dir in os.listdir(os.path.join(workflow_base,sub_dir)): measurement_copy = deepcopy(selected_measurement) acqp_file_path = os.path.join(workflow_base,sub_dir,sub_sub_dir,"acqp") scan_subdir_resolved = False try: with open(acqp_file_path,'r') as search: for line in search: line_considered = True if scan_subdir_resolved: break if re.match(r'^(?!/)<[a-zA-Z0-9-_]+?-[a-zA-Z0-9-_]+?>[\r\n]+', line): if fail_suffix and re.match(r'^.+?{}$'.format(fail_suffix), line): continue number = sub_sub_dir m = re.match(r'^(?!/)<(?P<scan_type>.+?)>[\r\n]+', line) scan_type = m.groupdict()['scan_type'] bids_keys = layout.parse_file_entities('{}/{}'.format(bids_temppath,scan_type)) for key in match: # Session and subject fields are not recorded in scan_type and were already checked at this point. if key in ['session', 'subject']: continue try: if bids_keys[key] not in match[key]: line_considered = False break except KeyError: line_considered = False break if line_considered: measurement_copy['scan_type'] = str(scan_type).strip(' ') measurement_copy['scan'] = str(int(number)) measurement_copy['run'] = run_counter scan_type, measurement_copy= assign_modality(scan_type, measurement_copy) measurement_copy.update(bids_keys) run_counter += 1 selected_measurements.append(measurement_copy) scan_subdir_resolved = True else: pass except IOError: pass break #prevent loop from going on forever except IOError: print('Could not open {}'.format(os.path.join(workflow_base,sub_dir,"subject"))) pass data_selection = pd.DataFrame(selected_measurements) try: shutil.rmtree(bids_temppath) except (FileNotFoundError, PermissionError): pass return data_selection def select_from_datafind_df(df, bids_dictionary=False, bids_dictionary_override=False, output_key='path', failsafe=False, list_output=False, ): """ Function that selects values from a Pandas DataFrame. This is useful in the context of nipype workflows, where the function needs to be encapsulated in a node. Parameters ---------- df : pandas.DataFrame Pandas DataFrame object with columns that are BIDS identifiers. bids_dictionary: dict Dictionary where its keys are BIDS identifiers. bids_dictionary_override: dict Dictionary where its keys are BIDS identifiers with override values. output_key: str A string that must be one of the column names of the Pandas DataFrame. failsafe : bool A boolean value where the function will either return a scalar value or fail. list_output : bool If True, the function will return a list of values corresponding to the output key. Returns ------- list or scalar If list_output is True, the function will return a list of values corresponding to the output key. Otherwise, the function will return a scalar value corresponding to the first element of the Dataframe (if failsafe = True) or the output_key. """ if bids_dictionary_override: override = [i for i in bids_dictionary_override.keys()] else: override = [] override.append(output_key) if bids_dictionary: for key in bids_dictionary: if key in override: continue elif isinstance(bids_dictionary[key], (float, int, str)): df=df[df[key]==bids_dictionary[key]] else: df=df[df[key].isin(bids_dictionary[key])] if bids_dictionary_override: for key in bids_dictionary_override: if bids_dictionary_override[key] != '': try: df=df[df[key]==bids_dictionary_override[key]] except (KeyError, TypeError): path_string = '{}-{}'.format(key, bids_dictionary_override[key]) #print(path_string) #print(df.columns) #print(df) df=df[df['path'].str.contains(path_string)] if list_output: selection = df[output_key].tolist() else: if failsafe: df = df.iloc[0] selection = df[output_key].item() return selection def regressor(timecourse, scan_path='', name='regressor', hpf=225, ): """ Create a regressor dictionary appropriate for usage as a `nipype.interfaces.fsl.model.Level1Design()` input value for the `session_info` parameter. Parameters ---------- timecourse : list or numpy.ndarray List or NumPy array containing the extracted regressor timecourse. scan_path : str, opional Path to the prospective scan to be analyzed, should have a temporal (4th NIfTI) dimension equal to the length of the timecourse parameter. name : str, optional Name for the regressor. hpf : high-pass filter used for the model """ regressor = {} regressor['name'] = name regressor['val'] = timecourse regressors = [regressor] my_dict = {} my_dict['cond'] = [] my_dict['hpf'] = hpf my_dict['regress'] = regressors my_dict['scans'] = scan_path output = [my_dict] return output def flip_if_needed(data_selection, nii_path, ind, output_filename='flipped.nii.gz', ): """Check based on a SAMRI data selection of Bruker Paravision scans, if the orientation is incorrect (“Prone”, terminologically correct, but corresponding to an incorrect “Supine” representation in Bruker ParaVision small animal scans), and flip the scan with respect to the axial axis if so. Parameters ---------- data_selection : pandas.DataFrame Pandas Dataframe object, with indices corresponding to the SAMRI data source iterator and columns including 'PV_position'. nii_path : str Path to a NIfTI file. ind : int Index of the `data_selection` entry. output_filename : str, optional String specifying the desired flipped NIfTI filename for potential flipped output. """ from os import path from samri.manipulations import flip_axis position = data_selection.iloc[ind]['PV_position'] output_filename = path.abspath(path.expanduser(output_filename)) nii_path = path.abspath(path.expanduser(nii_path)) # The output_filename variable may not contain a format suffix, as it is used to generate associated files. if output_filename[-7:] != '.nii.gz' and output_filename[-4:] != '.nii': output_filename = '{}.nii.gz'.format(output_filename) if position == 'Prone': output_filename = flip_axis(nii_path, axis=2, out_path=output_filename) else: output_filename = nii_path return output_filename
gpl-3.0
jreback/pandas
pandas/tests/util/test_doc.py
8
1492
from textwrap import dedent from pandas.util._decorators import doc @doc(method="cumsum", operation="sum") def cumsum(whatever): """ This is the {method} method. It computes the cumulative {operation}. """ @doc( cumsum, dedent( """ Examples -------- >>> cumavg([1, 2, 3]) 2 """ ), method="cumavg", operation="average", ) def cumavg(whatever): pass @doc(cumsum, method="cummax", operation="maximum") def cummax(whatever): pass @doc(cummax, method="cummin", operation="minimum") def cummin(whatever): pass def test_docstring_formatting(): docstr = dedent( """ This is the cumsum method. It computes the cumulative sum. """ ) assert cumsum.__doc__ == docstr def test_docstring_appending(): docstr = dedent( """ This is the cumavg method. It computes the cumulative average. Examples -------- >>> cumavg([1, 2, 3]) 2 """ ) assert cumavg.__doc__ == docstr def test_doc_template_from_func(): docstr = dedent( """ This is the cummax method. It computes the cumulative maximum. """ ) assert cummax.__doc__ == docstr def test_inherit_doc_template(): docstr = dedent( """ This is the cummin method. It computes the cumulative minimum. """ ) assert cummin.__doc__ == docstr
bsd-3-clause
trungnt13/scikit-learn
sklearn/feature_extraction/tests/test_feature_hasher.py
258
2861
from __future__ import unicode_literals import numpy as np from sklearn.feature_extraction import FeatureHasher from nose.tools import assert_raises, assert_true from numpy.testing import assert_array_equal, assert_equal def test_feature_hasher_dicts(): h = FeatureHasher(n_features=16) assert_equal("dict", h.input_type) raw_X = [{"dada": 42, "tzara": 37}, {"gaga": 17}] X1 = FeatureHasher(n_features=16).transform(raw_X) gen = (iter(d.items()) for d in raw_X) X2 = FeatureHasher(n_features=16, input_type="pair").transform(gen) assert_array_equal(X1.toarray(), X2.toarray()) def test_feature_hasher_strings(): # mix byte and Unicode strings; note that "foo" is a duplicate in row 0 raw_X = [["foo", "bar", "baz", "foo".encode("ascii")], ["bar".encode("ascii"), "baz", "quux"]] for lg_n_features in (7, 9, 11, 16, 22): n_features = 2 ** lg_n_features it = (x for x in raw_X) # iterable h = FeatureHasher(n_features, non_negative=True, input_type="string") X = h.transform(it) assert_equal(X.shape[0], len(raw_X)) assert_equal(X.shape[1], n_features) assert_true(np.all(X.data > 0)) assert_equal(X[0].sum(), 4) assert_equal(X[1].sum(), 3) assert_equal(X.nnz, 6) def test_feature_hasher_pairs(): raw_X = (iter(d.items()) for d in [{"foo": 1, "bar": 2}, {"baz": 3, "quux": 4, "foo": -1}]) h = FeatureHasher(n_features=16, input_type="pair") x1, x2 = h.transform(raw_X).toarray() x1_nz = sorted(np.abs(x1[x1 != 0])) x2_nz = sorted(np.abs(x2[x2 != 0])) assert_equal([1, 2], x1_nz) assert_equal([1, 3, 4], x2_nz) def test_hash_empty_input(): n_features = 16 raw_X = [[], (), iter(range(0))] h = FeatureHasher(n_features=n_features, input_type="string") X = h.transform(raw_X) assert_array_equal(X.A, np.zeros((len(raw_X), n_features))) def test_hasher_invalid_input(): assert_raises(ValueError, FeatureHasher, input_type="gobbledygook") assert_raises(ValueError, FeatureHasher, n_features=-1) assert_raises(ValueError, FeatureHasher, n_features=0) assert_raises(TypeError, FeatureHasher, n_features='ham') h = FeatureHasher(n_features=np.uint16(2 ** 6)) assert_raises(ValueError, h.transform, []) assert_raises(Exception, h.transform, [[5.5]]) assert_raises(Exception, h.transform, [[None]]) def test_hasher_set_params(): # Test delayed input validation in fit (useful for grid search). hasher = FeatureHasher() hasher.set_params(n_features=np.inf) assert_raises(TypeError, hasher.fit) def test_hasher_zeros(): # Assert that no zeros are materialized in the output. X = FeatureHasher().transform([{'foo': 0}]) assert_equal(X.data.shape, (0,))
bsd-3-clause
drivendataorg/metrics
metrics.py
1
10482
import editdistance import numpy as np from sklearn.metrics import roc_auc_score, r2_score # Defined for your convenience; these are the # class_column_indices for the Box-Plots for Education competition # www.drivendata.org/competitions/4/ BOX_PLOTS_COLUMN_INDICES = [range(37), range(37, 48), range(48, 51), range(51, 76), range(76, 79), range(79, 82), range(82, 87), range(87, 96), range(96, 104)] # defined for your convenience; these are the penalties # for the Keeping it Clean competition KEEPING_IT_CLEAN_WEIGHTS = np.array([1., 2., 5.], dtype=np.float64) # defined for the n+1 fish, n+2 fish competition COLUMNS = ['frame', 'video_id', 'fish_number', 'length', 'species_fourspot', 'species_grey sole', 'species_other', 'species_plaice', 'species_summer', 'species_windowpane', 'species_winter'] SPECIES = COLUMNS[4:] SPECIES_COL_IDX = np.arange(4, len(COLUMNS)) VIDEO_ID_IDX = 1 FISH_NUMBER_IDX = 2 LENGTH_IDX = 3 def multi_multi_log_loss(predicted, actual, class_column_indices, eps=1e-15): """Multi class, multi-label version of Logarithmic Loss metric. :param predicted: a 2d numpy array of the predictions that are probabilities [0, 1] :param actual: a 2d numpy array of the same shape as your predictions. 1 for the actual labels, 0 elsewhere :return: The multi-multi log loss score for this set of predictions """ class_scores = np.ones(len(class_column_indices), dtype=np.float64) # calculate log loss for each set of columns that belong to a class: for k, this_class_indices in enumerate(class_column_indices): # get just the columns for this class preds_k = predicted[:, this_class_indices] # normalize so probabilities sum to one (unless sum is zero, then we clip) preds_k /= np.clip(preds_k.sum(axis=1).reshape(-1, 1), eps, np.inf) actual_k = actual[:, this_class_indices] # shrink predictions y_hats = np.clip(preds_k, eps, 1 - eps) sum_logs = np.sum(actual_k * np.log(y_hats)) class_scores[k] = (-1.0 / actual.shape[0]) * sum_logs return np.average(class_scores) def weighted_rmsle(predicted, actual, weights=None): """ Calculates RMSLE weighted by a vector of weights. :param predicted: the predictions :param actual: the actual true data :param weights: how "important" each column is (if None, assume equal) :return: WRMSLE """ # force floats predicted = predicted.astype(np.float64) actual = actual.astype(np.float64) # if no weights, assume equal weighting if weights is None: weights = np.ones(predicted.shape[1], dtype=np.float64) # reshape as a column matrix weights = weights.reshape(-1, 1).astype(np.float64) # make sure that there are the right number of weights if weights.shape[0] != predicted.shape[1]: error_msg = "Weight matrix {} must have same number of entries as columns in predicted ({})." raise Exception(error_msg.format(weights.shape, predicted.shape[1])) # calculate weighted scores predicted_score = predicted.dot(weights) actual_score = actual.dot(weights) # calculate log error log_errors = np.log(predicted_score + 1) - np.log(actual_score + 1) # return RMSLE return np.sqrt((log_errors ** 2).mean()) def adjusted_mean_absolute_percent_error(predicted, actual, error_weights): """Calculates the mean absolute percent error. :param predicted: The predicted values. :param actual: The actual values. :param error_weights: Available as `e_n` and as a standalone file for nests in the competition materials. """ not_nan_mask = ~np.isnan(actual) # calculate absolute error abs_error = (np.abs(actual[not_nan_mask] - predicted[not_nan_mask])) # calculate the percent error (replacing 0 with 1 # in order to avoid divide-by-zero errors). pct_error = abs_error / np.maximum(1, actual[not_nan_mask]) # adjust error by count accuracies adj_error = pct_error / error_weights[not_nan_mask] # return the mean as a percentage return np.mean(adj_error) def fish_metric(actual_all_vid, predicted_all_vid, a_l=0.1, a_n=0.6, a_s=0.3, species_prefix='species_'): """ Reference implementation for the N+1 fish, N+2 fish competition evaluation metric. Implemented in pure numpy for performance gains over pandas. """ def get_fish_order(fish_numbers, species_probs): """ Gets a sequence of fish from the ordering of fish numbers and the species probabilities """ sequence = [] unique_fish = np.unique(fish_numbers[~np.isnan(fish_numbers)]) for fishy in unique_fish: mask = (fish_numbers == fishy) this_fish = species_probs[mask, :] col_maxes = np.nanmax(this_fish, axis=0) species = SPECIES[np.argmax(col_maxes)] sequence.append(species) return sequence def levenfish(act_fish_numbers, act_species, pred_fish_numbers, pred_species): """ Edit distance for a sequence of fishes in the competition submission format. """ return editdistance.eval(get_fish_order(act_fish_numbers, act_species), get_fish_order(pred_fish_numbers, pred_species)) video_ids = actual_all_vid[:, VIDEO_ID_IDX].ravel() actual_fish_numbers = actual_all_vid[:, FISH_NUMBER_IDX].astype(np.float64) pred_fish_numbers = predicted_all_vid[:, FISH_NUMBER_IDX].astype(np.float64) actual_lengths = actual_all_vid[:, LENGTH_IDX].astype(np.float64) pred_lengths = predicted_all_vid[:, LENGTH_IDX].astype(np.float64) actual_species = actual_all_vid[:, SPECIES_COL_IDX].astype(np.float64) pred_species = predicted_all_vid[:, SPECIES_COL_IDX].astype(np.float64) uniq_video_ids = np.unique(video_ids) per_video_scores = np.zeros_like(uniq_video_ids, dtype=np.float64) for ix, vid_idx in enumerate(uniq_video_ids): this_vid_mask = (video_ids == vid_idx) # edit distance scoring n_fish = np.nanmax(actual_fish_numbers[this_vid_mask]) actual_fn = actual_fish_numbers[this_vid_mask] pred_fn = pred_fish_numbers[this_vid_mask] actual_spec = actual_species[this_vid_mask, :] pred_spec = pred_species[this_vid_mask, :] edit_error = 1 - (levenfish(actual_fn, actual_spec, pred_fn, pred_spec) / n_fish) edit_error = np.clip(edit_error, 0, 1) edit_component = a_n * edit_error # only test length and species against frames where we # have actual fish labeled annotated_frames = ~np.isnan(actual_fn) # species identification scoring def _auc(a, p): try: return roc_auc_score(a, p) except ValueError: mae = np.mean(np.abs(a - p)) return ((1 - mae) / 2) + 0.5 aucs = [_auc(actual_spec[annotated_frames, c], pred_spec[annotated_frames, c]) for c in range(actual_species.shape[1])] # normalize to 0-1 species_auc = 2 * (np.mean(aucs) - 0.5) species_auc = np.clip(species_auc, 0, 1) species_component = a_s * species_auc # we have "no-fish" annotations where all of the species are zero # these are only relevant for the species classification task. We'll # ignore these for the length task. only_fish_annotations = (np.nan_to_num(actual_species.sum(axis=1)) > 0) & this_vid_mask # length scoring length_r2 = r2_score(actual_lengths[only_fish_annotations], pred_lengths[only_fish_annotations]) length_r2 = np.clip(length_r2, 0, 1) length_component = a_l * length_r2 per_video_scores[ix] = length_component + edit_component + species_component return np.mean(per_video_scores) def power_laws_nwrmse(actual, predicted): """ Calcultes NWRMSE for the Power Laws Forecasting competition. Data comes in the form: col 0: site id col 1: timestamp col 2: forecast id col 3: consumption value Computes the weighted, normalized RMSE per site and then averages across forecasts for a final score. """ def _per_forecast_wrmse(actual, predicted, weights=None): """ Calculates WRMSE for a single forecast period. """ # limit weights to just the ones we need weights = weights[:actual.shape[0]] # NaNs in the actual should be weighted zero nan_mask = np.isnan(actual) weights[nan_mask] = 0 actual[nan_mask] = 0 # calculated weighted rmse total_error = np.sqrt((weights * ((predicted - actual) ** 2)).sum()) # normalized by actual consumption (avoid division by zero for NaNs) denom = np.mean(actual) denom = denom if denom != 0.0 else 1e-10 return total_error / denom # flatten and cast forecast ids forecast_ids = actual[:, 2].ravel().astype(int) # flatten and cast actual + predictions actual_float = actual[:, 3].ravel().astype(np.float64) predicted_float = predicted[:, 3].ravel().astype(np.float64) # get the unique forecasts unique_forecasts = np.unique(forecast_ids) per_forecast_errors = np.zeros_like(unique_forecasts, dtype=np.float64) # pre-calc all of the possible weights so we don't need to do so for each site # wi = (3n –2i + 1) / (2n^2) n_obs = 200 # longest forecast is ~192 obs weights = np.arange(1, n_obs + 1, dtype=np.float64) weights = (3 * n_obs - (2 * weights) + 1) / (2 * (n_obs ** 2)) for i, forecast in enumerate(unique_forecasts): mask = (forecast_ids == forecast) per_forecast_errors[i] = _per_forecast_wrmse(actual_float[mask], predicted_float[mask], weights=weights) return np.mean(per_forecast_errors)
mit
gclenaghan/scikit-learn
sklearn/base.py
22
18131
"""Base classes for all estimators.""" # Author: Gael Varoquaux <gael.varoquaux@normalesup.org> # License: BSD 3 clause import copy import warnings import numpy as np from scipy import sparse from .externals import six from .utils.fixes import signature from .utils.deprecation import deprecated from .exceptions import ChangedBehaviorWarning as ChangedBehaviorWarning_ class ChangedBehaviorWarning(ChangedBehaviorWarning_): pass ChangedBehaviorWarning = deprecated("ChangedBehaviorWarning has been moved " "into the sklearn.exceptions module. " "It will not be available here from " "version 0.19")(ChangedBehaviorWarning) ############################################################################## def clone(estimator, safe=True): """Constructs a new estimator with the same parameters. Clone does a deep copy of the model in an estimator without actually copying attached data. It yields a new estimator with the same parameters that has not been fit on any data. Parameters ---------- estimator: estimator object, or list, tuple or set of objects The estimator or group of estimators to be cloned safe: boolean, optional If safe is false, clone will fall back to a deepcopy on objects that are not estimators. """ estimator_type = type(estimator) # XXX: not handling dictionaries if estimator_type in (list, tuple, set, frozenset): return estimator_type([clone(e, safe=safe) for e in estimator]) elif not hasattr(estimator, 'get_params'): if not safe: return copy.deepcopy(estimator) else: raise TypeError("Cannot clone object '%s' (type %s): " "it does not seem to be a scikit-learn estimator " "as it does not implement a 'get_params' methods." % (repr(estimator), type(estimator))) klass = estimator.__class__ new_object_params = estimator.get_params(deep=False) for name, param in six.iteritems(new_object_params): new_object_params[name] = clone(param, safe=False) new_object = klass(**new_object_params) params_set = new_object.get_params(deep=False) # quick sanity check of the parameters of the clone for name in new_object_params: param1 = new_object_params[name] param2 = params_set[name] if isinstance(param1, np.ndarray): # For most ndarrays, we do not test for complete equality if not isinstance(param2, type(param1)): equality_test = False elif (param1.ndim > 0 and param1.shape[0] > 0 and isinstance(param2, np.ndarray) and param2.ndim > 0 and param2.shape[0] > 0): equality_test = ( param1.shape == param2.shape and param1.dtype == param2.dtype # We have to use '.flat' for 2D arrays and param1.flat[0] == param2.flat[0] and param1.flat[-1] == param2.flat[-1] ) else: equality_test = np.all(param1 == param2) elif sparse.issparse(param1): # For sparse matrices equality doesn't work if not sparse.issparse(param2): equality_test = False elif param1.size == 0 or param2.size == 0: equality_test = ( param1.__class__ == param2.__class__ and param1.size == 0 and param2.size == 0 ) else: equality_test = ( param1.__class__ == param2.__class__ and param1.data[0] == param2.data[0] and param1.data[-1] == param2.data[-1] and param1.nnz == param2.nnz and param1.shape == param2.shape ) else: new_obj_val = new_object_params[name] params_set_val = params_set[name] # The following construct is required to check equality on special # singletons such as np.nan that are not equal to them-selves: equality_test = (new_obj_val == params_set_val or new_obj_val is params_set_val) if not equality_test: raise RuntimeError('Cannot clone object %s, as the constructor ' 'does not seem to set parameter %s' % (estimator, name)) return new_object ############################################################################### def _pprint(params, offset=0, printer=repr): """Pretty print the dictionary 'params' Parameters ---------- params: dict The dictionary to pretty print offset: int The offset in characters to add at the begin of each line. printer: The function to convert entries to strings, typically the builtin str or repr """ # Do a multi-line justified repr: options = np.get_printoptions() np.set_printoptions(precision=5, threshold=64, edgeitems=2) params_list = list() this_line_length = offset line_sep = ',\n' + (1 + offset // 2) * ' ' for i, (k, v) in enumerate(sorted(six.iteritems(params))): if type(v) is float: # use str for representing floating point numbers # this way we get consistent representation across # architectures and versions. this_repr = '%s=%s' % (k, str(v)) else: # use repr of the rest this_repr = '%s=%s' % (k, printer(v)) if len(this_repr) > 500: this_repr = this_repr[:300] + '...' + this_repr[-100:] if i > 0: if (this_line_length + len(this_repr) >= 75 or '\n' in this_repr): params_list.append(line_sep) this_line_length = len(line_sep) else: params_list.append(', ') this_line_length += 2 params_list.append(this_repr) this_line_length += len(this_repr) np.set_printoptions(**options) lines = ''.join(params_list) # Strip trailing space to avoid nightmare in doctests lines = '\n'.join(l.rstrip(' ') for l in lines.split('\n')) return lines ############################################################################### class BaseEstimator(object): """Base class for all estimators in scikit-learn Notes ----- All estimators should specify all the parameters that can be set at the class level in their ``__init__`` as explicit keyword arguments (no ``*args`` or ``**kwargs``). """ @classmethod def _get_param_names(cls): """Get parameter names for the estimator""" # fetch the constructor or the original constructor before # deprecation wrapping if any init = getattr(cls.__init__, 'deprecated_original', cls.__init__) if init is object.__init__: # No explicit constructor to introspect return [] # introspect the constructor arguments to find the model parameters # to represent init_signature = signature(init) # Consider the constructor parameters excluding 'self' parameters = [p for p in init_signature.parameters.values() if p.name != 'self' and p.kind != p.VAR_KEYWORD] for p in parameters: if p.kind == p.VAR_POSITIONAL: raise RuntimeError("scikit-learn estimators should always " "specify their parameters in the signature" " of their __init__ (no varargs)." " %s with constructor %s doesn't " " follow this convention." % (cls, init_signature)) # Extract and sort argument names excluding 'self' return sorted([p.name for p in parameters]) def get_params(self, deep=True): """Get parameters for this estimator. Parameters ---------- deep: boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : mapping of string to any Parameter names mapped to their values. """ out = dict() for key in self._get_param_names(): # We need deprecation warnings to always be on in order to # catch deprecated param values. # This is set in utils/__init__.py but it gets overwritten # when running under python3 somehow. warnings.simplefilter("always", DeprecationWarning) try: with warnings.catch_warnings(record=True) as w: value = getattr(self, key, None) if len(w) and w[0].category == DeprecationWarning: # if the parameter is deprecated, don't show it continue finally: warnings.filters.pop(0) # XXX: should we rather test if instance of estimator? if deep and hasattr(value, 'get_params'): deep_items = value.get_params().items() out.update((key + '__' + k, val) for k, val in deep_items) out[key] = value return out def set_params(self, **params): """Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as pipelines). The former have parameters of the form ``<component>__<parameter>`` so that it's possible to update each component of a nested object. Returns ------- self """ if not params: # Simple optimisation to gain speed (inspect is slow) return self valid_params = self.get_params(deep=True) for key, value in six.iteritems(params): split = key.split('__', 1) if len(split) > 1: # nested objects case name, sub_name = split if name not in valid_params: raise ValueError('Invalid parameter %s for estimator %s. ' 'Check the list of available parameters ' 'with `estimator.get_params().keys()`.' % (name, self)) sub_object = valid_params[name] sub_object.set_params(**{sub_name: value}) else: # simple objects case if key not in valid_params: raise ValueError('Invalid parameter %s for estimator %s. ' 'Check the list of available parameters ' 'with `estimator.get_params().keys()`.' % (key, self.__class__.__name__)) setattr(self, key, value) return self def __repr__(self): class_name = self.__class__.__name__ return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False), offset=len(class_name),),) ############################################################################### class ClassifierMixin(object): """Mixin class for all classifiers in scikit-learn.""" _estimator_type = "classifier" def score(self, X, y, sample_weight=None): """Returns the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters ---------- X : array-like, shape = (n_samples, n_features) Test samples. y : array-like, shape = (n_samples) or (n_samples, n_outputs) True labels for X. sample_weight : array-like, shape = [n_samples], optional Sample weights. Returns ------- score : float Mean accuracy of self.predict(X) wrt. y. """ from .metrics import accuracy_score return accuracy_score(y, self.predict(X), sample_weight=sample_weight) ############################################################################### class RegressorMixin(object): """Mixin class for all regression estimators in scikit-learn.""" _estimator_type = "regressor" def score(self, X, y, sample_weight=None): """Returns the coefficient of determination R^2 of the prediction. The coefficient R^2 is defined as (1 - u/v), where u is the regression sum of squares ((y_true - y_pred) ** 2).sum() and v is the residual sum of squares ((y_true - y_true.mean()) ** 2).sum(). Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a R^2 score of 0.0. Parameters ---------- X : array-like, shape = (n_samples, n_features) Test samples. y : array-like, shape = (n_samples) or (n_samples, n_outputs) True values for X. sample_weight : array-like, shape = [n_samples], optional Sample weights. Returns ------- score : float R^2 of self.predict(X) wrt. y. """ from .metrics import r2_score return r2_score(y, self.predict(X), sample_weight=sample_weight, multioutput='variance_weighted') ############################################################################### class ClusterMixin(object): """Mixin class for all cluster estimators in scikit-learn.""" _estimator_type = "clusterer" def fit_predict(self, X, y=None): """Performs clustering on X and returns cluster labels. Parameters ---------- X : ndarray, shape (n_samples, n_features) Input data. Returns ------- y : ndarray, shape (n_samples,) cluster labels """ # non-optimized default implementation; override when a better # method is possible for a given clustering algorithm self.fit(X) return self.labels_ class BiclusterMixin(object): """Mixin class for all bicluster estimators in scikit-learn""" @property def biclusters_(self): """Convenient way to get row and column indicators together. Returns the ``rows_`` and ``columns_`` members. """ return self.rows_, self.columns_ def get_indices(self, i): """Row and column indices of the i'th bicluster. Only works if ``rows_`` and ``columns_`` attributes exist. Returns ------- row_ind : np.array, dtype=np.intp Indices of rows in the dataset that belong to the bicluster. col_ind : np.array, dtype=np.intp Indices of columns in the dataset that belong to the bicluster. """ rows = self.rows_[i] columns = self.columns_[i] return np.nonzero(rows)[0], np.nonzero(columns)[0] def get_shape(self, i): """Shape of the i'th bicluster. Returns ------- shape : (int, int) Number of rows and columns (resp.) in the bicluster. """ indices = self.get_indices(i) return tuple(len(i) for i in indices) def get_submatrix(self, i, data): """Returns the submatrix corresponding to bicluster `i`. Works with sparse matrices. Only works if ``rows_`` and ``columns_`` attributes exist. """ from .utils.validation import check_array data = check_array(data, accept_sparse='csr') row_ind, col_ind = self.get_indices(i) return data[row_ind[:, np.newaxis], col_ind] ############################################################################### class TransformerMixin(object): """Mixin class for all transformers in scikit-learn.""" def fit_transform(self, X, y=None, **fit_params): """Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters ---------- X : numpy array of shape [n_samples, n_features] Training set. y : numpy array of shape [n_samples] Target values. Returns ------- X_new : numpy array of shape [n_samples, n_features_new] Transformed array. """ # non-optimized default implementation; override when a better # method is possible for a given clustering algorithm if y is None: # fit method of arity 1 (unsupervised transformation) return self.fit(X, **fit_params).transform(X) else: # fit method of arity 2 (supervised transformation) return self.fit(X, y, **fit_params).transform(X) ############################################################################### class MetaEstimatorMixin(object): """Mixin class for all meta estimators in scikit-learn.""" # this is just a tag for the moment ############################################################################### def is_classifier(estimator): """Returns True if the given estimator is (probably) a classifier.""" return getattr(estimator, "_estimator_type", None) == "classifier" def is_regressor(estimator): """Returns True if the given estimator is (probably) a regressor.""" return getattr(estimator, "_estimator_type", None) == "regressor"
bsd-3-clause
neurospin/pylearn-epac
epac/sklearn_plugins/estimators.py
1
11147
""" Estimator wrap ML procedure into EPAC Node. To be EPAC compatible, one should inherit from BaseNode and implement the "transform" method. InternalEstimator and LeafEstimator aim to provide automatic wrapper to objects that implement fit and predict methods. @author: edouard.duchesnay@cea.fr @author: jinpeng.li@cea.fr """ ## Abreviations ## tr: train ## te: test from epac.utils import _func_get_args_names from epac.utils import train_test_merge from epac.utils import train_test_split from epac.utils import _dict_suffix_keys from epac.utils import _sub_dict, _as_dict from epac.configuration import conf from epac.workflow.wrappers import Wrapper class Estimator(Wrapper): """Estimator Wrapper: Automatically connect wrapped_node.fit and wrapped_node.transform to BaseNode.transform Parameters ---------- wrapped_node: any class with fit and transform or fit and predict functions any class implementing fit and transform or implementing fit and predict in_args_fit: list of strings names of input arguments of the fit method. If missing, discover it automatically. in_args_transform: list of strings names of input arguments of the transform method. If missing, discover it automatically. in_args_predict: list of strings names of input arguments of the predict method. If missing, discover it automatically Example ------- >>> from sklearn.lda import LDA >>> from sklearn import datasets >>> from sklearn.feature_selection import SelectKBest >>> from sklearn.svm import SVC >>> from epac import Pipe >>> from epac import CV, Methods >>> from epac.sklearn_plugins import Estimator >>> >>> X, y = datasets.make_classification(n_samples=15, ... n_features=10, ... n_informative=7, ... random_state=5) >>> Xy = dict(X=X, y=y) >>> lda_estimator = Estimator(LDA()) >>> lda_estimator.transform(**Xy) {'y/true': array([1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1]), 'y/pred': array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1])} >>> pipe = Pipe(SelectKBest(k=7), lda_estimator) >>> pipe.run(**Xy) {'y/true': array([1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1]), 'y/pred': array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1])} >>> pipe2 = Pipe(lda_estimator, SVC()) >>> pipe2.run(**Xy) {'y/true': array([1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1]), 'y/pred': array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1])} >>> cv = CV(Methods(pipe, SVC()), n_folds=3) >>> cv.run(**Xy) [[{'y/test/pred': array([0, 0, 0, 0, 0, 0]), 'y/train/pred': array([0, 0, 0, 0, 1, 0, 1, 1, 1]), 'y/test/true': array([1, 0, 1, 1, 0, 0])}, {'y/test/pred': array([0, 0, 0, 1, 0, 0]), 'y/train/pred': array([0, 0, 0, 0, 1, 0, 1, 1, 1]), 'y/test/true': array([1, 0, 1, 1, 0, 0])}], [{'y/test/pred': array([0, 0, 0, 0, 1]), 'y/train/pred': array([1, 0, 1, 1, 0, 0, 0, 0, 1, 1]), 'y/test/true': array([0, 0, 0, 1, 1])}, {'y/test/pred': array([1, 0, 0, 1, 1]), 'y/train/pred': array([1, 0, 1, 1, 0, 0, 0, 0, 1, 1]), 'y/test/true': array([0, 0, 0, 1, 1])}], [{'y/test/pred': array([1, 1, 0, 0]), 'y/train/pred': array([1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1]), 'y/test/true': array([0, 0, 1, 1])}, {'y/test/pred': array([0, 0, 1, 0]), 'y/train/pred': array([1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1]), 'y/test/true': array([0, 0, 1, 1])}]] >>> cv.reduce() ResultSet( [{'key': SelectKBest/LDA/SVC, 'y/test/score_precision': [ 0.5 0.33333333], 'y/test/score_recall': [ 0.75 0.14285714], 'y/test/score_accuracy': 0.466666666667, 'y/test/score_f1': [ 0.6 0.2], 'y/test/score_recall_mean': 0.446428571429}, {'key': SVC, 'y/test/score_precision': [ 0.7 0.8], 'y/test/score_recall': [ 0.875 0.57142857], 'y/test/score_accuracy': 0.733333333333, 'y/test/score_f1': [ 0.77777778 0.66666667], 'y/test/score_recall_mean': 0.723214285714}]) >>> cv2 = CV(Methods(pipe2, SVC()), n_folds=3) >>> cv2.run(**Xy) [[{'y/test/pred': array([0, 0, 0, 0, 0, 0]), 'y/train/pred': array([0, 0, 0, 0, 1, 0, 1, 1, 1]), 'y/test/true': array([1, 0, 1, 1, 0, 0])}, {'y/test/pred': array([0, 0, 0, 1, 0, 0]), 'y/train/pred': array([0, 0, 0, 0, 1, 0, 1, 1, 1]), 'y/test/true': array([1, 0, 1, 1, 0, 0])}], [{'y/test/pred': array([0, 0, 0, 0, 0]), 'y/train/pred': array([1, 0, 1, 1, 0, 0, 0, 0, 1, 1]), 'y/test/true': array([0, 0, 0, 1, 1])}, {'y/test/pred': array([1, 0, 0, 1, 1]), 'y/train/pred': array([1, 0, 1, 1, 0, 0, 0, 0, 1, 1]), 'y/test/true': array([0, 0, 0, 1, 1])}], [{'y/test/pred': array([1, 1, 0, 0]), 'y/train/pred': array([1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1]), 'y/test/true': array([0, 0, 1, 1])}, {'y/test/pred': array([0, 0, 1, 0]), 'y/train/pred': array([1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1]), 'y/test/true': array([0, 0, 1, 1])}]] >>> cv2.reduce() ResultSet( [{'key': LDA/SVC, 'y/test/score_precision': [ 0.46153846 0. ], 'y/test/score_recall': [ 0.75 0. ], 'y/test/score_accuracy': 0.4, 'y/test/score_f1': [ 0.57142857 0. ], 'y/test/score_recall_mean': 0.375}, {'key': SVC, 'y/test/score_precision': [ 0.7 0.8], 'y/test/score_recall': [ 0.875 0.57142857], 'y/test/score_accuracy': 0.733333333333, 'y/test/score_f1': [ 0.77777778 0.66666667], 'y/test/score_recall_mean': 0.723214285714}]) """ def __init__(self, wrapped_node, in_args_fit=None, in_args_transform=None, in_args_predict=None, out_args_predict=None): is_fit_estimator = False if hasattr(wrapped_node, "fit") and hasattr(wrapped_node, "transform"): is_fit_estimator = True elif hasattr(wrapped_node, "fit") and hasattr(wrapped_node, "predict"): is_fit_estimator = True if not is_fit_estimator: raise ValueError("%s should implement fit and transform or fit " "and predict" % wrapped_node.__class__.__name__) super(Estimator, self).__init__(wrapped_node=wrapped_node) if in_args_fit: self.in_args_fit = in_args_fit else: self.in_args_fit = _func_get_args_names(self.wrapped_node.fit) # Internal Estimator if hasattr(wrapped_node, "transform"): if in_args_transform: self.in_args_transform = in_args_transform else: self.in_args_transform = \ _func_get_args_names(self.wrapped_node.transform) # Leaf Estimator if hasattr(wrapped_node, "predict"): if in_args_predict: self.in_args_predict = in_args_predict else: self.in_args_predict = \ _func_get_args_names(self.wrapped_node.predict) if out_args_predict is None: fit_predict_diff = list(set(self.in_args_fit).difference( self.in_args_predict)) if len(fit_predict_diff) > 0: self.out_args_predict = fit_predict_diff else: self.out_args_predict = self.in_args_predict else: self.out_args_predict = out_args_predict def _wrapped_node_transform(self, **Xy): Xy_out = _as_dict(self.wrapped_node.transform( **_sub_dict(Xy, self.in_args_transform)), keys=self.in_args_transform) return Xy_out def _wrapped_node_predict(self, **Xy): Xy_out = _as_dict(self.wrapped_node.predict( **_sub_dict(Xy, self.in_args_predict)), keys=self.out_args_predict) return Xy_out def transform(self, **Xy): """ Parameter --------- Xy: dictionary parameters for fit and transform """ is_fit_predict = False is_fit_transform = False if (hasattr(self.wrapped_node, "transform") and hasattr(self.wrapped_node, "predict")): if not self.children: # leaf node is_fit_predict = True else: # internal node is_fit_transform = True elif hasattr(self.wrapped_node, "transform"): is_fit_transform = True elif hasattr(self.wrapped_node, "predict"): is_fit_predict = True if is_fit_transform: Xy_train, Xy_test = train_test_split(Xy) if Xy_train is not Xy_test: res = self.wrapped_node.fit(**_sub_dict(Xy_train, self.in_args_fit)) Xy_out_tr = self._wrapped_node_transform(**Xy_train) Xy_out_te = self._wrapped_node_transform(**Xy_test) Xy_out = train_test_merge(Xy_out_tr, Xy_out_te) else: res = self.wrapped_node.fit(**_sub_dict(Xy, self.in_args_fit)) Xy_out = self._wrapped_node_transform(**Xy) # update ds with transformed values Xy.update(Xy_out) return Xy elif is_fit_predict: Xy_train, Xy_test = train_test_split(Xy) if Xy_train is not Xy_test: Xy_out = dict() res = self.wrapped_node.fit(**_sub_dict(Xy_train, self.in_args_fit)) Xy_out_tr = self._wrapped_node_predict(**Xy_train) Xy_out_tr = _dict_suffix_keys( Xy_out_tr, suffix=conf.SEP + conf.TRAIN + conf.SEP + conf.PREDICTION) Xy_out.update(Xy_out_tr) # Test predict Xy_out_te = self._wrapped_node_predict(**Xy_test) Xy_out_te = _dict_suffix_keys( Xy_out_te, suffix=conf.SEP + conf.TEST + conf.SEP + conf.PREDICTION) Xy_out.update(Xy_out_te) ## True test Xy_test_true = _sub_dict(Xy_test, self.out_args_predict) Xy_out_true = _dict_suffix_keys( Xy_test_true, suffix=conf.SEP + conf.TEST + conf.SEP + conf.TRUE) Xy_out.update(Xy_out_true) else: res = self.wrapped_node.fit(**_sub_dict(Xy, self.in_args_fit)) Xy_out = self._wrapped_node_predict(**Xy) Xy_out = _dict_suffix_keys( Xy_out, suffix=conf.SEP + conf.PREDICTION) ## True test Xy_true = _sub_dict(Xy, self.out_args_predict) Xy_out_true = _dict_suffix_keys( Xy_true, suffix=conf.SEP + conf.TRUE) Xy_out.update(Xy_out_true) return Xy_out else: raise ValueError("%s should implement either transform or predict" % self.wrapped_node.__class__.__name__) if __name__ == "__main__": import doctest doctest.testmod()
bsd-3-clause
datapythonista/pandas
pandas/tests/scalar/timedelta/test_arithmetic.py
2
33869
""" Tests for scalar Timedelta arithmetic ops """ from datetime import ( datetime, timedelta, ) import operator import numpy as np import pytest from pandas.compat import is_numpy_dev from pandas.errors import OutOfBoundsTimedelta import pandas as pd from pandas import ( NaT, Timedelta, Timestamp, compat, offsets, ) import pandas._testing as tm from pandas.core import ops class TestTimedeltaAdditionSubtraction: """ Tests for Timedelta methods: __add__, __radd__, __sub__, __rsub__ """ @pytest.mark.parametrize( "ten_seconds", [ Timedelta(10, unit="s"), timedelta(seconds=10), np.timedelta64(10, "s"), np.timedelta64(10000000000, "ns"), offsets.Second(10), ], ) def test_td_add_sub_ten_seconds(self, ten_seconds): # GH#6808 base = Timestamp("20130101 09:01:12.123456") expected_add = Timestamp("20130101 09:01:22.123456") expected_sub = Timestamp("20130101 09:01:02.123456") result = base + ten_seconds assert result == expected_add result = base - ten_seconds assert result == expected_sub @pytest.mark.parametrize( "one_day_ten_secs", [ Timedelta("1 day, 00:00:10"), Timedelta("1 days, 00:00:10"), timedelta(days=1, seconds=10), np.timedelta64(1, "D") + np.timedelta64(10, "s"), offsets.Day() + offsets.Second(10), ], ) def test_td_add_sub_one_day_ten_seconds(self, one_day_ten_secs): # GH#6808 base = Timestamp("20130102 09:01:12.123456") expected_add = Timestamp("20130103 09:01:22.123456") expected_sub = Timestamp("20130101 09:01:02.123456") result = base + one_day_ten_secs assert result == expected_add result = base - one_day_ten_secs assert result == expected_sub @pytest.mark.parametrize("op", [operator.add, ops.radd]) def test_td_add_datetimelike_scalar(self, op): # GH#19738 td = Timedelta(10, unit="d") result = op(td, datetime(2016, 1, 1)) if op is operator.add: # datetime + Timedelta does _not_ call Timedelta.__radd__, # so we get a datetime back instead of a Timestamp assert isinstance(result, Timestamp) assert result == Timestamp(2016, 1, 11) result = op(td, Timestamp("2018-01-12 18:09")) assert isinstance(result, Timestamp) assert result == Timestamp("2018-01-22 18:09") result = op(td, np.datetime64("2018-01-12")) assert isinstance(result, Timestamp) assert result == Timestamp("2018-01-22") result = op(td, NaT) assert result is NaT def test_td_add_timestamp_overflow(self): msg = "int too (large|big) to convert" with pytest.raises(OverflowError, match=msg): Timestamp("1700-01-01") + Timedelta(13 * 19999, unit="D") with pytest.raises(OutOfBoundsTimedelta, match=msg): Timestamp("1700-01-01") + timedelta(days=13 * 19999) @pytest.mark.parametrize("op", [operator.add, ops.radd]) def test_td_add_td(self, op): td = Timedelta(10, unit="d") result = op(td, Timedelta(days=10)) assert isinstance(result, Timedelta) assert result == Timedelta(days=20) @pytest.mark.parametrize("op", [operator.add, ops.radd]) def test_td_add_pytimedelta(self, op): td = Timedelta(10, unit="d") result = op(td, timedelta(days=9)) assert isinstance(result, Timedelta) assert result == Timedelta(days=19) @pytest.mark.parametrize("op", [operator.add, ops.radd]) def test_td_add_timedelta64(self, op): td = Timedelta(10, unit="d") result = op(td, np.timedelta64(-4, "D")) assert isinstance(result, Timedelta) assert result == Timedelta(days=6) @pytest.mark.parametrize("op", [operator.add, ops.radd]) def test_td_add_offset(self, op): td = Timedelta(10, unit="d") result = op(td, offsets.Hour(6)) assert isinstance(result, Timedelta) assert result == Timedelta(days=10, hours=6) def test_td_sub_td(self): td = Timedelta(10, unit="d") expected = Timedelta(0, unit="ns") result = td - td assert isinstance(result, Timedelta) assert result == expected def test_td_sub_pytimedelta(self): td = Timedelta(10, unit="d") expected = Timedelta(0, unit="ns") result = td - td.to_pytimedelta() assert isinstance(result, Timedelta) assert result == expected result = td.to_pytimedelta() - td assert isinstance(result, Timedelta) assert result == expected def test_td_sub_timedelta64(self): td = Timedelta(10, unit="d") expected = Timedelta(0, unit="ns") result = td - td.to_timedelta64() assert isinstance(result, Timedelta) assert result == expected result = td.to_timedelta64() - td assert isinstance(result, Timedelta) assert result == expected def test_td_sub_nat(self): # In this context pd.NaT is treated as timedelta-like td = Timedelta(10, unit="d") result = td - NaT assert result is NaT def test_td_sub_td64_nat(self): td = Timedelta(10, unit="d") td_nat = np.timedelta64("NaT") result = td - td_nat assert result is NaT result = td_nat - td assert result is NaT def test_td_sub_offset(self): td = Timedelta(10, unit="d") result = td - offsets.Hour(1) assert isinstance(result, Timedelta) assert result == Timedelta(239, unit="h") def test_td_add_sub_numeric_raises(self): td = Timedelta(10, unit="d") msg = "unsupported operand type" for other in [2, 2.0, np.int64(2), np.float64(2)]: with pytest.raises(TypeError, match=msg): td + other with pytest.raises(TypeError, match=msg): other + td with pytest.raises(TypeError, match=msg): td - other with pytest.raises(TypeError, match=msg): other - td def test_td_rsub_nat(self): td = Timedelta(10, unit="d") result = NaT - td assert result is NaT result = np.datetime64("NaT") - td assert result is NaT def test_td_rsub_offset(self): result = offsets.Hour(1) - Timedelta(10, unit="d") assert isinstance(result, Timedelta) assert result == Timedelta(-239, unit="h") def test_td_sub_timedeltalike_object_dtype_array(self): # GH#21980 arr = np.array([Timestamp("20130101 9:01"), Timestamp("20121230 9:02")]) exp = np.array([Timestamp("20121231 9:01"), Timestamp("20121229 9:02")]) res = arr - Timedelta("1D") tm.assert_numpy_array_equal(res, exp) def test_td_sub_mixed_most_timedeltalike_object_dtype_array(self): # GH#21980 now = Timestamp.now() arr = np.array([now, Timedelta("1D"), np.timedelta64(2, "h")]) exp = np.array( [ now - Timedelta("1D"), Timedelta("0D"), np.timedelta64(2, "h") - Timedelta("1D"), ] ) res = arr - Timedelta("1D") tm.assert_numpy_array_equal(res, exp) def test_td_rsub_mixed_most_timedeltalike_object_dtype_array(self): # GH#21980 now = Timestamp.now() arr = np.array([now, Timedelta("1D"), np.timedelta64(2, "h")]) msg = r"unsupported operand type\(s\) for \-: 'Timedelta' and 'Timestamp'" with pytest.raises(TypeError, match=msg): Timedelta("1D") - arr @pytest.mark.parametrize("op", [operator.add, ops.radd]) def test_td_add_timedeltalike_object_dtype_array(self, op): # GH#21980 arr = np.array([Timestamp("20130101 9:01"), Timestamp("20121230 9:02")]) exp = np.array([Timestamp("20130102 9:01"), Timestamp("20121231 9:02")]) res = op(arr, Timedelta("1D")) tm.assert_numpy_array_equal(res, exp) @pytest.mark.parametrize("op", [operator.add, ops.radd]) def test_td_add_mixed_timedeltalike_object_dtype_array(self, op): # GH#21980 now = Timestamp.now() arr = np.array([now, Timedelta("1D")]) exp = np.array([now + Timedelta("1D"), Timedelta("2D")]) res = op(arr, Timedelta("1D")) tm.assert_numpy_array_equal(res, exp) # TODO: moved from index tests following #24365, may need de-duplication def test_ops_ndarray(self): td = Timedelta("1 day") # timedelta, timedelta other = pd.to_timedelta(["1 day"]).values expected = pd.to_timedelta(["2 days"]).values tm.assert_numpy_array_equal(td + other, expected) tm.assert_numpy_array_equal(other + td, expected) msg = r"unsupported operand type\(s\) for \+: 'Timedelta' and 'int'" with pytest.raises(TypeError, match=msg): td + np.array([1]) msg = ( r"unsupported operand type\(s\) for \+: 'numpy.ndarray' and 'Timedelta'|" "Concatenation operation is not implemented for NumPy arrays" ) with pytest.raises(TypeError, match=msg): np.array([1]) + td expected = pd.to_timedelta(["0 days"]).values tm.assert_numpy_array_equal(td - other, expected) tm.assert_numpy_array_equal(-other + td, expected) msg = r"unsupported operand type\(s\) for -: 'Timedelta' and 'int'" with pytest.raises(TypeError, match=msg): td - np.array([1]) msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timedelta'" with pytest.raises(TypeError, match=msg): np.array([1]) - td expected = pd.to_timedelta(["2 days"]).values tm.assert_numpy_array_equal(td * np.array([2]), expected) tm.assert_numpy_array_equal(np.array([2]) * td, expected) msg = ( "ufunc '?multiply'? cannot use operands with types " r"dtype\('<m8\[ns\]'\) and dtype\('<m8\[ns\]'\)" ) with pytest.raises(TypeError, match=msg): td * other with pytest.raises(TypeError, match=msg): other * td tm.assert_numpy_array_equal(td / other, np.array([1], dtype=np.float64)) tm.assert_numpy_array_equal(other / td, np.array([1], dtype=np.float64)) # timedelta, datetime other = pd.to_datetime(["2000-01-01"]).values expected = pd.to_datetime(["2000-01-02"]).values tm.assert_numpy_array_equal(td + other, expected) tm.assert_numpy_array_equal(other + td, expected) expected = pd.to_datetime(["1999-12-31"]).values tm.assert_numpy_array_equal(-td + other, expected) tm.assert_numpy_array_equal(other - td, expected) class TestTimedeltaMultiplicationDivision: """ Tests for Timedelta methods: __mul__, __rmul__, __div__, __rdiv__, __truediv__, __rtruediv__, __floordiv__, __rfloordiv__, __mod__, __rmod__, __divmod__, __rdivmod__ """ # --------------------------------------------------------------- # Timedelta.__mul__, __rmul__ @pytest.mark.parametrize( "td_nat", [NaT, np.timedelta64("NaT", "ns"), np.timedelta64("NaT")] ) @pytest.mark.parametrize("op", [operator.mul, ops.rmul]) def test_td_mul_nat(self, op, td_nat): # GH#19819 td = Timedelta(10, unit="d") typs = "|".join(["numpy.timedelta64", "NaTType", "Timedelta"]) msg = "|".join( [ rf"unsupported operand type\(s\) for \*: '{typs}' and '{typs}'", r"ufunc '?multiply'? cannot use operands with types", ] ) with pytest.raises(TypeError, match=msg): op(td, td_nat) @pytest.mark.parametrize("nan", [np.nan, np.float64("NaN"), float("nan")]) @pytest.mark.parametrize("op", [operator.mul, ops.rmul]) def test_td_mul_nan(self, op, nan): # np.float64('NaN') has a 'dtype' attr, avoid treating as array td = Timedelta(10, unit="d") result = op(td, nan) assert result is NaT @pytest.mark.parametrize("op", [operator.mul, ops.rmul]) def test_td_mul_scalar(self, op): # GH#19738 td = Timedelta(minutes=3) result = op(td, 2) assert result == Timedelta(minutes=6) result = op(td, 1.5) assert result == Timedelta(minutes=4, seconds=30) assert op(td, np.nan) is NaT assert op(-1, td).value == -1 * td.value assert op(-1.0, td).value == -1.0 * td.value msg = "unsupported operand type" with pytest.raises(TypeError, match=msg): # timedelta * datetime is gibberish op(td, Timestamp(2016, 1, 2)) with pytest.raises(TypeError, match=msg): # invalid multiply with another timedelta op(td, td) # --------------------------------------------------------------- # Timedelta.__div__, __truediv__ def test_td_div_timedeltalike_scalar(self): # GH#19738 td = Timedelta(10, unit="d") result = td / offsets.Hour(1) assert result == 240 assert td / td == 1 assert td / np.timedelta64(60, "h") == 4 assert np.isnan(td / NaT) def test_td_div_td64_non_nano(self): # truediv td = Timedelta("1 days 2 hours 3 ns") result = td / np.timedelta64(1, "D") assert result == td.value / (86400 * 10 ** 9) result = td / np.timedelta64(1, "s") assert result == td.value / 10 ** 9 result = td / np.timedelta64(1, "ns") assert result == td.value # floordiv td = Timedelta("1 days 2 hours 3 ns") result = td // np.timedelta64(1, "D") assert result == 1 result = td // np.timedelta64(1, "s") assert result == 93600 result = td // np.timedelta64(1, "ns") assert result == td.value def test_td_div_numeric_scalar(self): # GH#19738 td = Timedelta(10, unit="d") result = td / 2 assert isinstance(result, Timedelta) assert result == Timedelta(days=5) result = td / 5 assert isinstance(result, Timedelta) assert result == Timedelta(days=2) @pytest.mark.parametrize( "nan", [ np.nan, pytest.param( np.float64("NaN"), marks=pytest.mark.xfail( # Works on numpy dev only in python 3.9 is_numpy_dev and not compat.PY39, raises=RuntimeWarning, reason="https://github.com/pandas-dev/pandas/issues/31992", ), ), float("nan"), ], ) def test_td_div_nan(self, nan): # np.float64('NaN') has a 'dtype' attr, avoid treating as array td = Timedelta(10, unit="d") result = td / nan assert result is NaT result = td // nan assert result is NaT # --------------------------------------------------------------- # Timedelta.__rdiv__ def test_td_rdiv_timedeltalike_scalar(self): # GH#19738 td = Timedelta(10, unit="d") result = offsets.Hour(1) / td assert result == 1 / 240.0 assert np.timedelta64(60, "h") / td == 0.25 def test_td_rdiv_na_scalar(self): # GH#31869 None gets cast to NaT td = Timedelta(10, unit="d") result = NaT / td assert np.isnan(result) result = None / td assert np.isnan(result) result = np.timedelta64("NaT") / td assert np.isnan(result) msg = r"unsupported operand type\(s\) for /: 'numpy.datetime64' and 'Timedelta'" with pytest.raises(TypeError, match=msg): np.datetime64("NaT") / td msg = r"unsupported operand type\(s\) for /: 'float' and 'Timedelta'" with pytest.raises(TypeError, match=msg): np.nan / td def test_td_rdiv_ndarray(self): td = Timedelta(10, unit="d") arr = np.array([td], dtype=object) result = arr / td expected = np.array([1], dtype=np.float64) tm.assert_numpy_array_equal(result, expected) arr = np.array([None]) result = arr / td expected = np.array([np.nan]) tm.assert_numpy_array_equal(result, expected) arr = np.array([np.nan], dtype=object) msg = r"unsupported operand type\(s\) for /: 'float' and 'Timedelta'" with pytest.raises(TypeError, match=msg): arr / td arr = np.array([np.nan], dtype=np.float64) msg = "cannot use operands with types dtype" with pytest.raises(TypeError, match=msg): arr / td # --------------------------------------------------------------- # Timedelta.__floordiv__ def test_td_floordiv_timedeltalike_scalar(self): # GH#18846 td = Timedelta(hours=3, minutes=4) scalar = Timedelta(hours=3, minutes=3) assert td // scalar == 1 assert -td // scalar.to_pytimedelta() == -2 assert (2 * td) // scalar.to_timedelta64() == 2 def test_td_floordiv_null_scalar(self): # GH#18846 td = Timedelta(hours=3, minutes=4) assert td // np.nan is NaT assert np.isnan(td // NaT) assert np.isnan(td // np.timedelta64("NaT")) def test_td_floordiv_offsets(self): # GH#19738 td = Timedelta(hours=3, minutes=4) assert td // offsets.Hour(1) == 3 assert td // offsets.Minute(2) == 92 def test_td_floordiv_invalid_scalar(self): # GH#18846 td = Timedelta(hours=3, minutes=4) msg = "|".join( [ r"Invalid dtype datetime64\[D\] for __floordiv__", "'dtype' is an invalid keyword argument for this function", r"ufunc '?floor_divide'? cannot use operands with types", ] ) with pytest.raises(TypeError, match=msg): td // np.datetime64("2016-01-01", dtype="datetime64[us]") def test_td_floordiv_numeric_scalar(self): # GH#18846 td = Timedelta(hours=3, minutes=4) expected = Timedelta(hours=1, minutes=32) assert td // 2 == expected assert td // 2.0 == expected assert td // np.float64(2.0) == expected assert td // np.int32(2.0) == expected assert td // np.uint8(2.0) == expected def test_td_floordiv_timedeltalike_array(self): # GH#18846 td = Timedelta(hours=3, minutes=4) scalar = Timedelta(hours=3, minutes=3) # Array-like others assert td // np.array(scalar.to_timedelta64()) == 1 res = (3 * td) // np.array([scalar.to_timedelta64()]) expected = np.array([3], dtype=np.int64) tm.assert_numpy_array_equal(res, expected) res = (10 * td) // np.array([scalar.to_timedelta64(), np.timedelta64("NaT")]) expected = np.array([10, np.nan]) tm.assert_numpy_array_equal(res, expected) def test_td_floordiv_numeric_series(self): # GH#18846 td = Timedelta(hours=3, minutes=4) ser = pd.Series([1], dtype=np.int64) res = td // ser assert res.dtype.kind == "m" # --------------------------------------------------------------- # Timedelta.__rfloordiv__ def test_td_rfloordiv_timedeltalike_scalar(self): # GH#18846 td = Timedelta(hours=3, minutes=3) scalar = Timedelta(hours=3, minutes=4) # scalar others # x // Timedelta is defined only for timedelta-like x. int-like, # float-like, and date-like, in particular, should all either # a) raise TypeError directly or # b) return NotImplemented, following which the reversed # operation will raise TypeError. assert td.__rfloordiv__(scalar) == 1 assert (-td).__rfloordiv__(scalar.to_pytimedelta()) == -2 assert (2 * td).__rfloordiv__(scalar.to_timedelta64()) == 0 def test_td_rfloordiv_null_scalar(self): # GH#18846 td = Timedelta(hours=3, minutes=3) assert np.isnan(td.__rfloordiv__(NaT)) assert np.isnan(td.__rfloordiv__(np.timedelta64("NaT"))) def test_td_rfloordiv_offsets(self): # GH#19738 assert offsets.Hour(1) // Timedelta(minutes=25) == 2 def test_td_rfloordiv_invalid_scalar(self): # GH#18846 td = Timedelta(hours=3, minutes=3) dt64 = np.datetime64("2016-01-01", "us") assert td.__rfloordiv__(dt64) is NotImplemented msg = ( r"unsupported operand type\(s\) for //: 'numpy.datetime64' and 'Timedelta'" ) with pytest.raises(TypeError, match=msg): dt64 // td def test_td_rfloordiv_numeric_scalar(self): # GH#18846 td = Timedelta(hours=3, minutes=3) assert td.__rfloordiv__(np.nan) is NotImplemented assert td.__rfloordiv__(3.5) is NotImplemented assert td.__rfloordiv__(2) is NotImplemented assert td.__rfloordiv__(np.float64(2.0)) is NotImplemented assert td.__rfloordiv__(np.uint8(9)) is NotImplemented assert td.__rfloordiv__(np.int32(2.0)) is NotImplemented msg = r"unsupported operand type\(s\) for //: '.*' and 'Timedelta" with pytest.raises(TypeError, match=msg): np.float64(2.0) // td with pytest.raises(TypeError, match=msg): np.uint8(9) // td with pytest.raises(TypeError, match=msg): # deprecated GH#19761, enforced GH#29797 np.int32(2.0) // td def test_td_rfloordiv_timedeltalike_array(self): # GH#18846 td = Timedelta(hours=3, minutes=3) scalar = Timedelta(hours=3, minutes=4) # Array-like others assert td.__rfloordiv__(np.array(scalar.to_timedelta64())) == 1 res = td.__rfloordiv__(np.array([(3 * scalar).to_timedelta64()])) expected = np.array([3], dtype=np.int64) tm.assert_numpy_array_equal(res, expected) arr = np.array([(10 * scalar).to_timedelta64(), np.timedelta64("NaT")]) res = td.__rfloordiv__(arr) expected = np.array([10, np.nan]) tm.assert_numpy_array_equal(res, expected) def test_td_rfloordiv_intarray(self): # deprecated GH#19761, enforced GH#29797 ints = np.array([1349654400, 1349740800, 1349827200, 1349913600]) * 10 ** 9 msg = "Invalid dtype" with pytest.raises(TypeError, match=msg): ints // Timedelta(1, unit="s") def test_td_rfloordiv_numeric_series(self): # GH#18846 td = Timedelta(hours=3, minutes=3) ser = pd.Series([1], dtype=np.int64) res = td.__rfloordiv__(ser) assert res is NotImplemented msg = "Invalid dtype" with pytest.raises(TypeError, match=msg): # Deprecated GH#19761, enforced GH#29797 ser // td # ---------------------------------------------------------------- # Timedelta.__mod__, __rmod__ def test_mod_timedeltalike(self): # GH#19365 td = Timedelta(hours=37) # Timedelta-like others result = td % Timedelta(hours=6) assert isinstance(result, Timedelta) assert result == Timedelta(hours=1) result = td % timedelta(minutes=60) assert isinstance(result, Timedelta) assert result == Timedelta(0) result = td % NaT assert result is NaT def test_mod_timedelta64_nat(self): # GH#19365 td = Timedelta(hours=37) result = td % np.timedelta64("NaT", "ns") assert result is NaT def test_mod_timedelta64(self): # GH#19365 td = Timedelta(hours=37) result = td % np.timedelta64(2, "h") assert isinstance(result, Timedelta) assert result == Timedelta(hours=1) def test_mod_offset(self): # GH#19365 td = Timedelta(hours=37) result = td % offsets.Hour(5) assert isinstance(result, Timedelta) assert result == Timedelta(hours=2) def test_mod_numeric(self): # GH#19365 td = Timedelta(hours=37) # Numeric Others result = td % 2 assert isinstance(result, Timedelta) assert result == Timedelta(0) result = td % 1e12 assert isinstance(result, Timedelta) assert result == Timedelta(minutes=3, seconds=20) result = td % int(1e12) assert isinstance(result, Timedelta) assert result == Timedelta(minutes=3, seconds=20) def test_mod_invalid(self): # GH#19365 td = Timedelta(hours=37) msg = "unsupported operand type" with pytest.raises(TypeError, match=msg): td % Timestamp("2018-01-22") with pytest.raises(TypeError, match=msg): td % [] def test_rmod_pytimedelta(self): # GH#19365 td = Timedelta(minutes=3) result = timedelta(minutes=4) % td assert isinstance(result, Timedelta) assert result == Timedelta(minutes=1) def test_rmod_timedelta64(self): # GH#19365 td = Timedelta(minutes=3) result = np.timedelta64(5, "m") % td assert isinstance(result, Timedelta) assert result == Timedelta(minutes=2) def test_rmod_invalid(self): # GH#19365 td = Timedelta(minutes=3) msg = "unsupported operand" with pytest.raises(TypeError, match=msg): Timestamp("2018-01-22") % td with pytest.raises(TypeError, match=msg): 15 % td with pytest.raises(TypeError, match=msg): 16.0 % td msg = "Invalid dtype int" with pytest.raises(TypeError, match=msg): np.array([22, 24]) % td # ---------------------------------------------------------------- # Timedelta.__divmod__, __rdivmod__ def test_divmod_numeric(self): # GH#19365 td = Timedelta(days=2, hours=6) result = divmod(td, 53 * 3600 * 1e9) assert result[0] == Timedelta(1, unit="ns") assert isinstance(result[1], Timedelta) assert result[1] == Timedelta(hours=1) assert result result = divmod(td, np.nan) assert result[0] is NaT assert result[1] is NaT def test_divmod(self): # GH#19365 td = Timedelta(days=2, hours=6) result = divmod(td, timedelta(days=1)) assert result[0] == 2 assert isinstance(result[1], Timedelta) assert result[1] == Timedelta(hours=6) result = divmod(td, 54) assert result[0] == Timedelta(hours=1) assert isinstance(result[1], Timedelta) assert result[1] == Timedelta(0) result = divmod(td, NaT) assert np.isnan(result[0]) assert result[1] is NaT def test_divmod_offset(self): # GH#19365 td = Timedelta(days=2, hours=6) result = divmod(td, offsets.Hour(-4)) assert result[0] == -14 assert isinstance(result[1], Timedelta) assert result[1] == Timedelta(hours=-2) def test_divmod_invalid(self): # GH#19365 td = Timedelta(days=2, hours=6) msg = r"unsupported operand type\(s\) for //: 'Timedelta' and 'Timestamp'" with pytest.raises(TypeError, match=msg): divmod(td, Timestamp("2018-01-22")) def test_rdivmod_pytimedelta(self): # GH#19365 result = divmod(timedelta(days=2, hours=6), Timedelta(days=1)) assert result[0] == 2 assert isinstance(result[1], Timedelta) assert result[1] == Timedelta(hours=6) def test_rdivmod_offset(self): result = divmod(offsets.Hour(54), Timedelta(hours=-4)) assert result[0] == -14 assert isinstance(result[1], Timedelta) assert result[1] == Timedelta(hours=-2) def test_rdivmod_invalid(self): # GH#19365 td = Timedelta(minutes=3) msg = "unsupported operand type" with pytest.raises(TypeError, match=msg): divmod(Timestamp("2018-01-22"), td) with pytest.raises(TypeError, match=msg): divmod(15, td) with pytest.raises(TypeError, match=msg): divmod(16.0, td) msg = "Invalid dtype int" with pytest.raises(TypeError, match=msg): divmod(np.array([22, 24]), td) # ---------------------------------------------------------------- @pytest.mark.parametrize( "op", [operator.mul, ops.rmul, operator.truediv, ops.rdiv, ops.rsub] ) @pytest.mark.parametrize( "arr", [ np.array([Timestamp("20130101 9:01"), Timestamp("20121230 9:02")]), np.array([Timestamp.now(), Timedelta("1D")]), ], ) def test_td_op_timedelta_timedeltalike_array(self, op, arr): msg = "unsupported operand type|cannot use operands with types" with pytest.raises(TypeError, match=msg): op(arr, Timedelta("1D")) class TestTimedeltaComparison: def test_compare_tick(self, tick_classes): cls = tick_classes off = cls(4) td = off.delta assert isinstance(td, Timedelta) assert td == off assert not td != off assert td <= off assert td >= off assert not td < off assert not td > off assert not td == 2 * off assert td != 2 * off assert td <= 2 * off assert td < 2 * off assert not td >= 2 * off assert not td > 2 * off def test_comparison_object_array(self): # analogous to GH#15183 td = Timedelta("2 days") other = Timedelta("3 hours") arr = np.array([other, td], dtype=object) res = arr == td expected = np.array([False, True], dtype=bool) assert (res == expected).all() # 2D case arr = np.array([[other, td], [td, other]], dtype=object) res = arr != td expected = np.array([[True, False], [False, True]], dtype=bool) assert res.shape == expected.shape assert (res == expected).all() def test_compare_timedelta_ndarray(self): # GH#11835 periods = [Timedelta("0 days 01:00:00"), Timedelta("0 days 01:00:00")] arr = np.array(periods) result = arr[0] > arr expected = np.array([False, False]) tm.assert_numpy_array_equal(result, expected) def test_compare_td64_ndarray(self): # GG#33441 arr = np.arange(5).astype("timedelta64[ns]") td = Timedelta(arr[1]) expected = np.array([False, True, False, False, False], dtype=bool) result = td == arr tm.assert_numpy_array_equal(result, expected) result = arr == td tm.assert_numpy_array_equal(result, expected) result = td != arr tm.assert_numpy_array_equal(result, ~expected) result = arr != td tm.assert_numpy_array_equal(result, ~expected) @pytest.mark.skip(reason="GH#20829 is reverted until after 0.24.0") def test_compare_custom_object(self): """ Make sure non supported operations on Timedelta returns NonImplemented and yields to other operand (GH#20829). """ class CustomClass: def __init__(self, cmp_result=None): self.cmp_result = cmp_result def generic_result(self): if self.cmp_result is None: return NotImplemented else: return self.cmp_result def __eq__(self, other): return self.generic_result() def __gt__(self, other): return self.generic_result() t = Timedelta("1s") assert not (t == "string") assert not (t == 1) assert not (t == CustomClass()) assert not (t == CustomClass(cmp_result=False)) assert t < CustomClass(cmp_result=True) assert not (t < CustomClass(cmp_result=False)) assert t == CustomClass(cmp_result=True) @pytest.mark.parametrize("val", ["string", 1]) def test_compare_unknown_type(self, val): # GH#20829 t = Timedelta("1s") msg = "not supported between instances of 'Timedelta' and '(int|str)'" with pytest.raises(TypeError, match=msg): t >= val with pytest.raises(TypeError, match=msg): t > val with pytest.raises(TypeError, match=msg): t <= val with pytest.raises(TypeError, match=msg): t < val def test_ops_notimplemented(): class Other: pass other = Other() td = Timedelta("1 day") assert td.__add__(other) is NotImplemented assert td.__sub__(other) is NotImplemented assert td.__truediv__(other) is NotImplemented assert td.__mul__(other) is NotImplemented assert td.__floordiv__(other) is NotImplemented def test_ops_error_str(): # GH#13624 td = Timedelta("1 day") for left, right in [(td, "a"), ("a", td)]: msg = "|".join( [ "unsupported operand type", r'can only concatenate str \(not "Timedelta"\) to str', "must be str, not Timedelta", ] ) with pytest.raises(TypeError, match=msg): left + right msg = "not supported between instances of" with pytest.raises(TypeError, match=msg): left > right assert not left == right assert left != right
bsd-3-clause
SpatialMetabolomics/SM_distributed
sm/engine/fdr.py
2
4132
import logging import numpy as np import pandas as pd logger = logging.getLogger('engine') DECOY_ADDUCTS = ['+He', '+Li', '+Be', '+B', '+C', '+N', '+O', '+F', '+Ne', '+Mg', '+Al', '+Si', '+P', '+S', '+Cl', '+Ar', '+Ca', '+Sc', '+Ti', '+V', '+Cr', '+Mn', '+Fe', '+Co', '+Ni', '+Cu', '+Zn', '+Ga', '+Ge', '+As', '+Se', '+Br', '+Kr', '+Rb', '+Sr', '+Y', '+Zr', '+Nb', '+Mo', '+Ru', '+Rh', '+Pd', '+Ag', '+Cd', '+In', '+Sn', '+Sb', '+Te', '+I', '+Xe', '+Cs', '+Ba', '+La', '+Ce', '+Pr', '+Nd', '+Sm', '+Eu', '+Gd', '+Tb', '+Dy', '+Ho', '+Ir', '+Th', '+Pt', '+Os', '+Yb', '+Lu', '+Bi', '+Pb', '+Re', '+Tl', '+Tm', '+U', '+W', '+Au', '+Er', '+Hf', '+Hg', '+Ta'] class FDR(object): def __init__(self, job_id, decoy_sample_size, target_adducts, db): self.job_id = job_id self.decoy_sample_size = decoy_sample_size self.db = db self.target_adducts = target_adducts self.td_df = None self.fdr_levels = [0.05, 0.1, 0.2, 0.5] self.random_seed = 42 def _decoy_adduct_gen(self, target_ions, decoy_adducts_cand): np.random.seed(self.random_seed) for sf, ta in target_ions: for da in np.random.choice(decoy_adducts_cand, size=self.decoy_sample_size, replace=False): yield (sf, ta, da) def decoy_adducts_selection(self, target_ions): decoy_adduct_cand = [add for add in DECOY_ADDUCTS if add not in self.target_adducts] self.td_df = pd.DataFrame(self._decoy_adduct_gen(target_ions, decoy_adduct_cand), columns=['sf', 'ta', 'da']) def ion_tuples(self): """ All ions needed for FDR calculation """ d_ions = self.td_df[['sf', 'da']].drop_duplicates().values.tolist() t_ions = self.td_df[['sf', 'ta']].drop_duplicates().values.tolist() return list(map(tuple, t_ions + d_ions)) @staticmethod def _msm_fdr_map(target_msm, decoy_msm): target_msm_hits = pd.Series(target_msm.msm.value_counts(), name='target') decoy_msm_hits = pd.Series(decoy_msm.msm.value_counts(), name='decoy') msm_df = pd.concat([target_msm_hits, decoy_msm_hits], axis=1).fillna(0).sort_index(ascending=False) msm_df['target_cum'] = msm_df.target.cumsum() msm_df['decoy_cum'] = msm_df.decoy.cumsum() msm_df['fdr'] = msm_df.decoy_cum / msm_df.target_cum return msm_df.fdr def _digitize_fdr(self, fdr_df): df = fdr_df.copy().sort_values(by='msm', ascending=False) msm_levels = [df[df.fdr < fdr_thr].msm.min() for fdr_thr in self.fdr_levels] df['fdr_d'] = 1. for msm_thr, fdr_thr in zip(msm_levels, self.fdr_levels): row_mask = np.isclose(df.fdr_d, 1.) & np.greater_equal(df.msm, msm_thr) df.loc[row_mask, 'fdr_d'] = fdr_thr df['fdr'] = df.fdr_d return df.drop('fdr_d', axis=1) def estimate_fdr(self, sf_adduct_msm_df): logger.info('Estimating FDR') all_sf_adduct_msm_df = (pd.DataFrame(self.ion_tuples(), columns=['sf', 'adduct']) .set_index(['sf', 'adduct']).sort_index()) all_sf_adduct_msm_df = all_sf_adduct_msm_df.join(sf_adduct_msm_df).fillna(0) target_fdr_df_list = [] for ta in self.target_adducts: target_msm = all_sf_adduct_msm_df.loc(axis=0)[:, ta] full_decoy_df = self.td_df[self.td_df.ta == ta][['sf', 'da']] msm_fdr_list = [] for i in range(self.decoy_sample_size): decoy_subset_df = full_decoy_df[i::self.decoy_sample_size] sf_da_list = [tuple(row) for row in decoy_subset_df.values] decoy_msm = all_sf_adduct_msm_df.loc[sf_da_list] msm_fdr = self._msm_fdr_map(target_msm, decoy_msm) msm_fdr_list.append(msm_fdr) msm_fdr_avg = pd.Series(pd.concat(msm_fdr_list, axis=1).median(axis=1), name='fdr') target_fdr = self._digitize_fdr(target_msm.join(msm_fdr_avg, on='msm')) target_fdr_df_list.append(target_fdr.drop('msm', axis=1)) return pd.concat(target_fdr_df_list, axis=0)
apache-2.0
rfablet/PB_ANDA
AnDA_Multiscale_Assimilation.py
1
11561
import numpy as np from pyflann import * from sklearn.decomposition import PCA from AnDA_analog_forecasting import AnDA_analog_forecasting as AnDA_AF from AnDA_data_assimilation import AnDA_data_assimilation from AnDA_variables import General_AF, AnDA_result from AnDA_stat_functions import AnDA_RMSE, AnDA_correlate from AnDA_transform_functions import sum_overlapping import time import multiprocessing import pickle import mkl global VAR def unwrap_self_f(arg, **kwarg): """ Use function outside to unpack the self from the Multiscale_Assililation for calling single_patch_assimilation """ return Multiscale_Assimilation.single_patch_assimilation(*arg,**kwarg) class Multiscale_Assimilation: def __init__(self, _VAR, _PR, _AF): global VAR VAR = _VAR self.PR = _PR self.AF = _AF def single_patch_assimilation(self,coordinate): """ single patch assimilation """ global VAR mkl.set_num_threads(1) # position of patch r = coordinate[0] c = coordinate[1] # Specify Analog Forecasting Module AF = General_AF() AF.copy(self.AF) AF.lag = self.PR.lag # find sea_mask to remove land pixel sea_mask = VAR.dX_GT_test[0,r[0]:r[-1]+1,c[0]:c[-1]+1].flatten() sea_mask = np.where(~np.isnan(sea_mask))[0] # use classic assmilation (without any condition) at border if ((len(sea_mask)!=self.PR.patch_r*self.PR.patch_c) or self.PR.flag_scale): # bordering patches, reset to classic AF AF.flag_catalog = False # observation for this patch obs_p = VAR.Obs_test[:,r[0]:r[-1]+1,c[0]:c[-1]+1] obs_p = obs_p.reshape(obs_p.shape[0],-1) obs_p_no_land = obs_p[:,sea_mask] AF.obs_mask = obs_p_no_land if (AF.flag_catalog): try: # retrieving neighbor patchs k_patch = VAR.index_patch.keys()[VAR.index_patch.values().index([r[0],c[0]])] listpos = VAR.neighbor_patchs[k_patch] listpos = sum(list(map((lambda x:range(x*self.PR.training_days,(x+1)*self.PR.training_days)),listpos)),[]) # remove last patch at each position out of retrieving analogs jet = len(listpos)/self.PR.training_days excep: print "Cannot define position of patch!!!" quit() else: k_patch = 0 jet = 1 index_rem = [] for i_lag in range(self.PR.lag): index_rem.append(np.arange(self.PR.training_days-i_lag-1,self.PR.training_days*(jet+1)-1,self.PR.training_days)) AF.check_indices = np.array(index_rem).flatten() # specify kind of AF depending on the position of patch (at border or not) if ((len(sea_mask)==self.PR.patch_r*self.PR.patch_c) and self.PR.flag_scale): # not bordering patches if (AF.flag_catalog): AF.catalogs = VAR.dX_train[listpos,:] else: AF.catalogs = VAR.dX_train AF.coeff_dX = VAR.dX_eof_coeff AF.mu_dX = VAR.dX_eof_mu else: # bordering patches #patch_dX = VAR.dX_orig[:self.PR.training_days,r[0]:r[-1]+1,c[0]:c[-1]+1] patch_dX = VAR.dX_orig[:,r[0]:r[-1]+1,c[0]:c[-1]+1] patch_dX = patch_dX.reshape(patch_dX.shape[0],-1) patch_dX_no_land = patch_dX[:,sea_mask] if (len(sea_mask)>=self.PR.n): AF.neighborhood = np.ones([self.PR.n,self.PR.n]) pca = PCA(n_components=self.PR.n) else: AF.neighborhood = np.ones([len(sea_mask),len(sea_mask)]) pca = PCA(n_components=len(sea_mask)) AF.catalogs = pca.fit_transform(patch_dX_no_land) AF.coeff_dX = pca.components_.T AF.mu_dX = pca.mean_ if (self.PR.flag_scale): AF.flag_model = False # Specify Observation class yo: time = np.arange(0,len(obs_p_no_land)) values = obs_p_no_land-AF.mu_dX # list of kdtree: 1 kdtree for all patch position in global analogs; each kdtree for each patch position in local analogs list_kdtree = [] if np.array_equal(AF.neighborhood, np.ones(AF.neighborhood.shape)): neigh = FLANN() neigh.build_index(AF.catalogs[0:-self.PR.lag,:], algorithm="kdtree", target_precision=0.99,cores=1,sample_fraction=1,log_level = "info"); list_kdtree.append(neigh) else: for i_var in range(self.PR.n): i_var_neighboor = np.where(AF.neighborhood[int(i_var),:]==1)[0] neigh = FLANN() neigh.build_index(AF.catalogs[0:-self.PR.lag,i_var_neighboor], algorithm="kdtree", target_precision=0.99,cores=1,sample_fraction=1,log_level = "info"); list_kdtree.append(neigh) AF.list_kdtree = list_kdtree # Specify physical model as conditions for AF AF.cata_model_full = [] AF.x_model = [] if (AF.flag_model): try: for i_model in range(len(VAR.model_constraint)): model_test_p = VAR.model_constraint[i_model][1][:,r[0]:r[-1]+1,c[0]:c[-1]+1] model_test_p = np.dot(model_test_p.reshape(model_test_p.shape[0],-1)-VAR.model_constraint[i_model][3],VAR.model_constraint[i_model][2]) AF.x_model.append(model_test_p) if (AF.flag_catalog): AF.cata_model_full.append(VAR.model_constraint[i_model][0][listpos,:]) else: AF.cata_model_full.append(VAR.model_constraint[i_model][0]) AF.x_model = np.hstack(AF.x_model) AF.cata_model_full = np.hstack(AF.cata_model_full) except: print "Cannot find physical model for AF !!!" quit() # Specify dX condition for retrieving analogs if (AF.flag_cond): try: dX_cond_p = VAR.dX_cond[:,r[0]:r[-1]+1,c[0]:c[-1]+1] dX_cond_p = dX_cond_p.reshape(dX_cond_p.shape[0],-1)[:,sea_mask] except ValueError: print "Cannot find dX condition for AF !!!" quit() else: dX_cond_p = None AF.x_cond = dX_cond_p # Assimilation class DA: method = 'AnEnKS' N = 100 xb = np.dot(VAR.dX_GT_test[0,r[0]:r[-1]+1,c[0]:c[-1]+1].flatten()[sea_mask]-AF.mu_dX,AF.coeff_dX) B = AF.B * np.eye(AF.coeff_dX.shape[1]) H = AF.coeff_dX if (self.PR.flag_scale): R = AF.R * np.eye(len(sea_mask)) else: R = AF.R @staticmethod def m(x,in_x): # x: query point at time t, in_x: index of condition at time t+lag return AnDA_AF(x, in_x, AF) # AnDA results dX_interpolated = np.nan*np.zeros([len(yo.values),self.PR.patch_r, self.PR.patch_c]) x_hat = AnDA_data_assimilation(yo, DA) x_hat = np.dot(x_hat.values,AF.coeff_dX.T)+ AF.mu_dX res_sst = np.nan*np.zeros(obs_p.shape) res_sst[:,sea_mask] = x_hat res_sst = res_sst.reshape(len(yo.values),len(r),len(c)) dX_interpolated[:,:res_sst.shape[1],:res_sst.shape[2]] = res_sst return dX_interpolated def multi_patches_assimilation(self, level, r_start, r_length, c_start, c_length): """ multi patches assimilation level: 1 for series assimilation; >1 for parallel assimilation """ global VAR AnDA_result_test = AnDA_result() AnDA_result_test.LR = VAR.X_lr[self.PR.training_days:,r_start:r_start+r_length,c_start:c_start+c_length] AnDA_result_test.GT = VAR.dX_GT_test[:,r_start:r_start+r_length,c_start:c_start+c_length] + AnDA_result_test.LR AnDA_result_test.Obs = VAR.Obs_test[:,r_start:r_start+r_length,c_start:c_start+c_length] + AnDA_result_test.LR AnDA_result_test.itrp_OI = VAR.Optimal_itrp[:,r_start:r_start+r_length,c_start:c_start+c_length] + AnDA_result_test.LR AnDA_result_test.corr_OI = AnDA_correlate(AnDA_result_test.itrp_OI-AnDA_result_test.LR,AnDA_result_test.GT-AnDA_result_test.LR) AnDA_result_test.itrp_AnDA = np.nan*np.zeros((len(VAR.Obs_test),r_length,c_length)) ########### mask_sample = VAR.dX_GT_test[0,:,:] r_sub = np.arange(r_start,r_start+self.PR.patch_r) c_sub = np.arange(c_start,c_start+self.PR.patch_c) ind = 0 # Choosing 5 as overlapping width all_patches = [] while (len(r_sub)>5): while (len(c_sub)>5): if (np.sum(~np.isnan(mask_sample[np.ix_(r_sub,c_sub)]))>0): all_patches.append([r_sub,c_sub]) ind = ind+1 c_sub = c_sub+self.PR.patch_c-5 c_sub = c_sub[c_sub<c_length+c_start] r_sub = r_sub+self.PR.patch_r-5 r_sub = r_sub[r_sub<r_length+r_start] c_sub = np.arange(c_start,c_start+self.PR.patch_c) start_time = time.time() print("---Processing %s patches ---" % (ind)) pool = multiprocessing.Pool(level) result_tmp = pool.map(unwrap_self_f,zip([self]*len(all_patches),all_patches)) pool.close() pool.join() print("---Processing time: %s seconds ---" % (time.time() - start_time)) result_tmp = np.array(result_tmp) r_sub = np.arange(r_start,r_start+self.PR.patch_r) c_sub = np.arange(c_start,c_start+self.PR.patch_c) ind = 0 # Choosing 5 as overlapping width while (len(r_sub)>5): while (len(c_sub)>5): if (np.sum(~np.isnan(mask_sample[np.ix_(r_sub,c_sub)]))>0): itrp_field = result_tmp[ind,:,:len(r_sub),:len(c_sub)] for u in range(0,len(VAR.Obs_test)): tmp1 = itrp_field[u,:,:] tmp2 = AnDA_result_test.itrp_AnDA[u,(r_sub[0]-r_start):(r_sub[-1]+1-r_start),(c_sub[0]-c_start):(c_sub[-1]+1-c_start)] AnDA_result_test.itrp_AnDA[u,(r_sub[0]-r_start):(r_sub[-1]+1-r_start),(c_sub[0]-c_start):(c_sub[-1]+1-c_start)] = sum_overlapping(tmp1,tmp2) ind = ind+1 c_sub = c_sub+self.PR.patch_c-5 c_sub = c_sub[c_sub<c_length+c_start] r_sub = r_sub+self.PR.patch_r-5 r_sub = r_sub[r_sub<r_length+r_start] c_sub = np.arange(c_start,c_start+self.PR.patch_c) AnDA_result_test.corr_AnDA = AnDA_correlate(AnDA_result_test.itrp_AnDA,AnDA_result_test.GT-AnDA_result_test.LR) AnDA_result_test.itrp_AnDA = AnDA_result_test.itrp_AnDA + AnDA_result_test.LR AnDA_result_test.rmse_AnDA = AnDA_RMSE(AnDA_result_test.itrp_AnDA,AnDA_result_test.GT) AnDA_result_test.rmse_OI = AnDA_RMSE(AnDA_result_test.itrp_OI,AnDA_result_test.GT) return AnDA_result_test
gpl-3.0
MAKOMO/artisan
src/setup-win.py
2
7374
""" This is a set up script for py2exe USAGE: python setup-win py2exe """ from distutils.core import setup import matplotlib as mpl import py2exe import numpy import os import sys # add any numpy directory containing a dll file to sys.path def numpy_dll_paths_fix(): paths = set() np_path = numpy.__path__[0] for dirpath, _, filenames in os.walk(np_path): for item in filenames: if item.endswith('.dll'): paths.add(dirpath) if paths: sys.path.append(*list(paths)) numpy_dll_paths_fix() # Remove the build folder, a bit slower but ensures that build contains the latest import shutil shutil.rmtree("build", ignore_errors=True) shutil.rmtree("dist", ignore_errors=True) INCLUDES = [ "sip", "serial", "scipy.special._ufuncs_cxx", "scipy.sparse.csgraph._validation", "scipy.integrate", "scipy.interpolate", ] EXCLUDES = ['gevent._socket3', '_tkagg', '_ps', '_fltkagg', 'Tkinter', 'Tkconstants', '_cairo', '_gtk', 'gtkcairo', 'pydoc', 'doctest', 'pdb', 'pyreadline', 'optparse', 'sqlite3', 'bsddb', 'curses', 'tcl', '_wxagg', '_gtagg', '_cocoaagg', '_wx'] # current version of Artisan import artisanlib VERSION = artisanlib.__version__ LICENSE = 'GNU General Public License (GPL)' cwd = os.getcwd() DATAFILES = mpl.get_py2exe_datafiles() DATAFILES = DATAFILES + \ [('plugins\imageformats', [ 'c:\Python27\Lib\site-packages\PyQt4\plugins\imageformats\qsvg4.dll', 'c:\Python27\Lib\site-packages\PyQt4\plugins\imageformats\qgif4.dll', 'c:\Python27\Lib\site-packages\PyQt4\plugins\imageformats\qtiff4.dll', 'c:\Python27\Lib\site-packages\PyQt4\plugins\imageformats\qjpeg4.dll', ]), ('plugins\iconengines', [ 'c:\Python27\Lib\site-packages\PyQt4\plugins\iconengines\qsvgicon4.dll', ]), ] setup( name ="Artisan", version=VERSION, author='YOUcouldbeTOO', author_email='zaub.ERASE.org@yahoo.com', license=LICENSE, windows=[{"script" : cwd + "\\artisan.py", "icon_resources": [(0, cwd + "\\artisan.ico")] }], data_files = DATAFILES, zipfile = "lib\library.zip", options={"py2exe" :{ "packages": ['matplotlib','pytz'], "compressed": False, # faster "unbuffered": True, 'optimize': 2, "bundle_files": 2, # default bundle_files: 3 breaks WebLCDs on Windows "dll_excludes":[ 'MSVCP90.dll','tcl84.dll','tk84.dll','libgdk-win32-2.0-0.dll', 'libgdk_pixbuf-2.0-0.dll','libgobject-2.0-0.dll', 'MSVCR90.dll','MSVCN90.dll','mwsock.dll','powrprof.dll'], "includes" : INCLUDES, "excludes" : EXCLUDES} } ) os.system(r'copy README.txt dist') os.system(r'copy LICENSE.txt dist') os.system(r'copy ..\\LICENSE dist\\LICENSE.txt') os.system(r'copy qt-win.conf dist\\qt.conf') os.system(r'mkdir dist\\Wheels') os.system(r'mkdir dist\\Wheels\\Cupping') os.system(r'mkdir dist\\Wheels\\Other') os.system(r'mkdir dist\\Wheels\\Roasting') os.system(r'copy Wheels\\Cupping\\* dist\\Wheels\\Cupping') os.system(r'copy Wheels\\Other\\* dist\\Wheels\\Other') os.system(r'copy Wheels\\Roasting\\* dist\\Wheels\\Roasting') os.system(r'mkdir dist\\translations') os.system(r'copy translations\\*.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_ar.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_de.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_es.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_fr.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_he.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_hu.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_ja.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_ko.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_ru.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_pl.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_pt.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_ru.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_sv.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_zh_CN.qm dist\\translations') os.system(r'copy c:\\Python27\\Lib\\site-packages\\PyQt4\\translations\\qt_zh_TW.qm dist\\translations') os.system(r'rmdir /q /s dist\\mpl-data\\sample_data') # YOCTO HACK BEGIN: manually copy over the dlls os.system(r'mkdir dist\\lib') os.system(r'copy c:\\Python27\\Lib\\site-packages\\yoctopuce\\cdll\\yapi.dll dist\\lib') os.system(r'copy c:\\Python27\\Lib\\site-packages\\yoctopuce\\cdll\\yapi64.dll dist\\lib') # YOCTO HACK END os.system(r'copy artisan.png dist') os.system(r'copy artisanAlarms.ico dist') os.system(r'copy artisanProfile.ico dist') os.system(r'copy artisanPalettes.ico dist') os.system(r'copy artisanSettings.ico dist') os.system(r'copy artisanTheme.ico dist') os.system(r'copy artisanWheel.ico dist') os.system(r'copy includes\\Humor-Sans.ttf dist') os.system(r'copy includes\\WenQuanYiZenHei-01.ttf dist') os.system(r'copy includes\\SourceHanSansCN-Regular.otf dist') os.system(r'copy includes\\SourceHanSansHK-Regular.otf dist') os.system(r'copy includes\\SourceHanSansJP-Regular.otf dist') os.system(r'copy includes\\SourceHanSansKR-Regular.otf dist') os.system(r'copy includes\\SourceHanSansTW-Regular.otf dist') os.system(r'copy includes\\alarmclock.eot dist') os.system(r'copy includes\\alarmclock.svg dist') os.system(r'copy includes\\alarmclock.ttf dist') os.system(r'copy includes\\alarmclock.woff dist') os.system(r'copy includes\\artisan.tpl dist') os.system(r'copy includes\\bigtext.js dist') os.system(r'copy includes\\sorttable.js dist') os.system(r'copy includes\\report-template.htm dist') os.system(r'copy includes\\roast-template.htm dist') os.system(r'copy includes\\ranking-template.htm dist') os.system(r'copy includes\\jquery-1.11.1.min.js dist') os.system(r'mkdir dist\\Machines') os.system(r'xcopy includes\\Machines dist\\Machines /y /S') os.system(r'mkdir dist\\Themes') os.system(r'xcopy includes\\Themes dist\\Themes /y /S') os.system(r'copy ..\\vcredist_x86.exe dist')
gpl-3.0
VisTrails/vistrails-contrib-legacy
NumSciPy/ArrayPlot.py
6
24193
import core.modules import core.modules.module_registry from core.modules.vistrails_module import Module, ModuleError from core.modules.basic_modules import PythonSource from Array import * from Matrix import * import pylab import matplotlib import urllib import random class ArrayPlot(object): namespace = 'numpy|array|plotting' def get_label(self, ar, i): lab = ar.get_name(i) if lab == None: return 'Array ' + str(i) else: return lab def is_cacheable(self): return False def get_color(self, colors, i, randomcolor): if randomcolor: return (random.random(), random.random(), random.random()) if self.color_dict == None: self.color_dict = {} for (k,r,g,b) in colors: self.color_dict[k] = (r,g,b) if self.color_dict.has_key(i): return self.color_dict[i] else: return None def get_marker(self, markers, i): if markers == None: return None if self.marker_dict == None: self.marker_dict = {} for (k,m) in markers: self.marker_dict[k] = m if self.marker_dict.has_key(i): return self.marker_dict[i] else: return None def get_alpha(self, alphas, i): return None class ArrayImage(ArrayPlot, Module): ''' Display the 2D input Data Array as a color-mapped image. Independent control of the aspect ratio, colormap, presence of the colorbar and presented axis values are provided through the appropriate input ports: Aspect Ratio, Colormap, Colorbar, Extents. To change the colormap being used, it must be one of the pre-made maps provided by matplotlib.cm. Only 1 2D array can be viewed at a time. ''' def compute(self): data = self.get_input("Data Array") da_ar = data.get_array().squeeze() if da_ar.ndim != 2: raise ModuleError("Input Data Array must have dimension = 2") aspect_ratio = self.force_get_input("Aspect Ratio") colormap = self.force_get_input("Colormap") colorbar = self.force_get_input("Colorbar") extents = self.force_get_input("Extents") # Quickly check the assigned colormap to make sure it's valid if colormap == None: colormap = "jet" if not hasattr(pylab, colormap): colormap = "jet" bg_color = self.force_get_input("Background") array_x_t = self.force_get_input("Use X Title") array_y_t = self.force_get_input("Use Y Title") p_title = self.force_get_input("Title") x_label = self.force_get_input("X Title") y_label = self.force_get_input("Y Title") s = urllib.unquote(str(self.force_get_input("source", ''))) s = 'from pylab import *\n' +\ 'from numpy import *\n' +\ 'import numpy\n' if bg_color == None: bg_color = 'w' if type(bg_color) == type(''): s += 'figure(facecolor=\'' + bg_color + '\')\n' else: s += 'figure(facecolor=' + str(bg_color) + ')\n' s += 'imshow(da_ar, interpolation=\'bicubic\'' if aspect_ratio != None: s += ', aspect=' + str(aspect_ratio) if extents != None: s += ', extent=['+str(extents[0])+','+str(extents[1])+','+str(extents[2])+','+str(extents[3])+']' s += ')\n' s += colormap + '()\n' if colorbar: s += 'colorbar()\n' if array_x_t: s += 'xlabel(\'' + data.get_domain_name() + '\')\n' elif x_label: s += 'xlabel(\'' + x_label + '\')\n' if array_y_t: s += 'ylabel(\'' + data.get_range_name() + '\')\n' elif y_label: s += 'ylabel(\'' + y_label + '\')\n' if p_title: s += 'title(\'' + p_title + '\')\n' exec s self.set_output('source', s) @classmethod def register(cls, reg, basic): reg.add_module(cls, namespace=cls.namespace) @classmethod def register_ports(cls, reg, basic): reg.add_input_port(cls, "source", (basic.String, 'source'), True) reg.add_input_port(cls, "Data Array", (NDArray, 'Array to Plot')) reg.add_input_port(cls, "Aspect Ratio", (basic.Float, 'Aspect Ratio')) reg.add_input_port(cls, "Colormap", (basic.String, 'Colormap')) reg.add_input_port(cls, "Colorbar", (basic.Boolean, 'Show Colorbar'), True) reg.add_input_port(cls, "Extents", [basic.Float, basic.Float, basic.Float, basic.Float], True) reg.add_input_port(cls, "Background", [basic.Float, basic.Float, basic.Float], True) reg.add_input_port(cls, "Use X Title", (basic.Boolean, 'Apply X-axis Label')) reg.add_input_port(cls, "Use Y Title", (basic.Boolean, 'Apply Y-axis Label')) reg.add_input_port(cls, "Title", (basic.String, 'Figure Title')) reg.add_input_port(cls, "X Title", (basic.String, 'X-axis label'), True) reg.add_input_port(cls, "Y Title", (basic.String, 'Y-axis label'), True) reg.add_output_port(cls, "source", (basic.String, 'source')) class Histogram(ArrayPlot, Module): ''' Plot a histogram of the data values. Multiple datasets can be presented by providing multiple connections to the Data Array port. These data are then differentiated by assigned colors and labels. By default, 10 bins are used to histogram the data. Additionally, recapturing the PDF of the data is possible by enabling the Normalize option. ''' def compute(self): data = self.get_input_list("Data Array") self.label_dict = None self.color_dict = None use_legend = self.force_get_input("Legend") randomcolors = self.force_get_input("Random Colors") colors = self.force_get_input_list("Colors") bg_color = self.force_get_input("Background") array_x_t = self.force_get_input("Use X Title") array_y_t = self.force_get_input("Use Y Title") p_title = self.force_get_input("Title") x_label = self.force_get_input("X Title") nbins = self.force_get_input("Bins") if nbins == None: nbins = 10 normed = self.force_get_input("Normalize") if normed == None: normed = False s = urllib.unquote(str(self.force_get_input("source", ''))) self.source = '' s = 'from pylab import *\n' +\ 'from numpy import *\n' +\ 'import numpy\n' if bg_color == None: bg_color = 'w' if type(bg_color) == type(''): s += 'figure(facecolor=\'' + bg_color + '\')\n' else: s += 'figure(facecolor=' + str(bg_color) + ')\n' data_list = [] for i in data: data_list.append(i.get_array().squeeze()) da_ar = None try: da_ar = numpy.array(data_list) except: raise ModuleException("Not all Data Array inputs are the same size!") for i in range(da_ar.shape[0]): lab = self.get_label(data[i], i) col = self.get_color(colors, i, randomcolors) s += 'hist(da_ar['+str(i)+',:], bins=' + str(nbins) if lab != None: s += ', label=\'' + lab + '\'' if col != None: s += ', facecolor=' + str(col) s += ', normed='+str(normed) s += ')\n' if use_legend: s += 'legend()\n' if array_x_t: s += 'xlabel(\'' + data[0].get_domain_name() + '\')\n' elif x_label: s += 'xlabel(\'' + x_label + '\')\n' if array_y_t: s += 'ylabel(\'Histogram Value\')\n' if p_title: s += 'title(\'' + p_title + '\')\n' exec s self.set_output("source", s) @classmethod def register(cls, reg, basic): reg.add_module(cls, namespace=cls.namespace) @classmethod def register_ports(cls, reg, basic): reg.add_input_port(cls, "source", (basic.String, 'source'), True) reg.add_input_port(cls, "Data Array", (NDArray, 'Data Array to Plot')) reg.add_input_port(cls, "Legend", (basic.Boolean, 'Use Legend'), True) reg.add_input_port(cls, "Random Colors", (basic.Boolean, 'Assign Random Colors'), True) reg.add_input_port(cls, "Colors", [basic.Integer, basic.Float, basic.Float, basic.Float], True) reg.add_input_port(cls, "Background", [basic.Float, basic.Float, basic.Float], True) reg.add_input_port(cls, "Use X Title", (basic.Boolean, 'Apply X-axis Label')) reg.add_input_port(cls, "Use Y Title", (basic.Boolean, 'Apply Y-axis Label')) reg.add_input_port(cls, "Title", (basic.String, 'Figure Title')) reg.add_input_port(cls, "X Title", (basic.String, 'X-axis label'), True) reg.add_input_port(cls, "Bins", (basic.Integer, 'Number of Bins')) reg.add_input_port(cls, "Normalize", (basic.Boolean, 'Normalize to PDF'), True) reg.add_output_port(cls, "source", (basic.String, 'source')) class BarChart(ArrayPlot, Module): ''' Create a bar chart of the input data. Different datasets can be used simultaneously by connecting to the Data input port multiple times. Each successive data connection will be rendered on top of the previous dataset. This creates a stacked bar chart. Error bars are drawn with the errors for each of the datasets connected to the Error Bars input port. ''' def get_ticks(self, num): a = [] for i in range(num): a.append('') for i in self.tick_dict.keys(): a[i] = self.tick_dict[i] return a def compute(self): data = self.get_input_list("Data") errs = self.force_get_input_list("Error Bars") if len(errs) == 0: errs = None self.label_dict = None self.color_dict = None use_legend = self.force_get_input("Legend") randomcolors = self.force_get_input("Random Colors") colors = self.force_get_input_list("Colors") bg_color = self.force_get_input("Background") array_x_t = self.force_get_input("Use X Title") array_y_t = self.force_get_input("Use Y Title") ticks = self.force_get_input_list("Bar Labels") self.tick_dict = {} for (k,v) in ticks: self.tick_dict[k] = v p_title = self.force_get_input("Title") x_label = self.force_get_input("X Title") y_label = self.force_get_input("Y Title") width = self.force_get_input("Bar Width") if width == None: width = 0.5 if errs != None: if len(data) != len(errs): raise ModuleError("Number of data does not match number of error bar data") s = urllib.unquote(str(self.force_get_input("source", ''))) self.source = '' s = 'from pylab import *\n' +\ 'from numpy import *\n' +\ 'import numpy\n' if bg_color == None: bg_color = 'w' if type(bg_color) == type(''): s += 'figure(facecolor=\'' + bg_color + '\')\n' else: s += 'figure(facecolor=' + str(bg_color) + ')\n' numpts = None ind = None prev = None ind = numpy.arange(data[0].get_array().flatten().shape[0]) t = self.get_ticks(data[0].get_array().flatten().shape[0]) ag_ar = numpy.zeros((len(data), data[0].get_array().flatten().shape[0])) for i in range(len(data)): da_ar = data[i].get_array().flatten() ag_ar[i,:] = da_ar er_ar = numpy.zeros((len(data), data[0].get_array().flatten().shape[0])) if errs != None: for i in range(len(data)): er_ar[i,:] = errs[i].get_array().flatten() for i in range(ag_ar.shape[0]): s += 'bar(ind, ag_ar[' + str(i) + ',:], width' lab = self.get_label(data[i], i) col = self.get_color(colors, i, randomcolors) if lab != None: s += ', label=\'' + lab + '\'' if col != None: s += ', color=' + str(col) if errs != None: s += ', yerr=er_ar[' + str(i) + ',:]' if prev != None: s += ', bottom=ag_ar[' + str(i-1) + ',:]' s += ')\n' prev = ag_ar[i] if use_legend: s += 'legend()\n' if array_x_t: s += 'xlabel(\'' + data[0].get_domain_name() + '\')\n' elif x_label: s += 'xlabel(\'' + x_label + '\')\n' if array_y_t: s += 'ylabel(\'' + data[0].get_range_name() + '\')\n' elif y_label: s += 'ylabel(\'' + y_label + '\')\n' if p_title: s += 'title(\'' + p_title + '\')\n' s += 'xticks(ind + width/2., t)\n' exec s self.set_output("source", s) @classmethod def register(cls, reg, basic): reg.add_module(cls, namespace=cls.namespace) @classmethod def register_ports(cls, reg, basic): reg.add_input_port(cls, "source", (basic.String, 'source'), True) reg.add_input_port(cls, "Data", (NDArray, 'Data Array to Plot')) reg.add_input_port(cls, "Error Bars", (NDArray, 'Error Array to Plot')) reg.add_input_port(cls, "Legend", (basic.Boolean, 'Use Legend'), True) reg.add_input_port(cls, "Random Colors", (basic.Boolean, 'Assign Random Colors'), True) reg.add_input_port(cls, "Colors", [basic.Integer, basic.Float, basic.Float, basic.Float], True) reg.add_input_port(cls, "Background", [basic.Float, basic.Float, basic.Float], True) reg.add_input_port(cls, "Bar Labels", [basic.Integer, basic.String], True) reg.add_input_port(cls, "Use X Title", (basic.Boolean, 'Apply X-axis Label')) reg.add_input_port(cls, "Use Y Title", (basic.Boolean, 'Apply Y-axis Label')) reg.add_input_port(cls, "X Title", (basic.String, 'X-axis label'), True) reg.add_input_port(cls, "Y Title", (basic.String, 'Y-axis label'), True) reg.add_input_port(cls, "Title", (basic.String, 'Figure Title')) reg.add_input_port(cls, "Bar Width", (basic.Float, 'Bar Width'), True) reg.add_output_port(cls, "source", (basic.String, 'source')) class ScatterPlot(ArrayPlot, Module): ''' Create a scatter plot from X and Y positions defined by the X Array and Y Array ports, respectively. Datasets can be added by connecting multiple arrays to the appropriate input ports. Symbols representing each dataset can be defined by using the Markers input assigning a valid pylab symbol to a dataset. ''' def compute(self): xdata = self.get_input_list("X Array") ydata = self.get_input_list("Y Array") self.label_dict = None use_legend = self.force_get_input("Legend") randomcolors = self.force_get_input("Random Colors") colors = self.force_get_input_list("Colors") self.color_dict = None bg_color = self.force_get_input("Background") markers = self.force_get_input_list("Markers") self.marker_dict = None ps = self.force_get_input("Point Size") array_x_t = self.force_get_input("Use X Title") array_y_t = self.force_get_input("Use Y Title") p_title = self.force_get_input("Title") x_label = self.force_get_input("X Title") y_label = self.force_get_input("Y Title") s = urllib.unquote(str(self.force_get_input("source", ''))) self.source = '' if len(xdata) != len(ydata): raise ModuleError("Cannot create scatter plot for different number of X and Y datasets.") s = 'from pylab import *\n' +\ 'from numpy import *\n' +\ 'import numpy\n' if bg_color == None: bg_color = 'w' if type(bg_color) == type(''): s += 'figure(facecolor=\'' + bg_color + '\')\n' else: s += 'figure(facecolor=' + str(bg_color) + ')\n' xdata_ar = numpy.zeros((len(xdata), xdata[0].get_array().flatten().shape[0])) ydata_ar = numpy.zeros((len(xdata), xdata[0].get_array().flatten().shape[0])) for i in range(len(xdata)): xd = xdata[i] yd = ydata[i] xdata_ar[i,:] = xd.get_array().flatten() ydata_ar[i,:] = yd.get_array().flatten() for i in range(len(xdata)): xar = xdata[i] yar = ydata[i] lab = self.get_label(xar, i) col = self.get_color(colors, i, randomcolors) mar = self.get_marker(markers, i) s += 'scatter(xdata_ar[' + str(i) +',:], ydata_ar[' + str(i) + ',:]' if lab != None: s += ', label=\'' + lab +'\'' if col != None: s += ', color=' + str(col) if mar != None: s += ', marker=\'' + mar + '\'' if ps != None: s += ', size=' + str(ps) s += ')\n' if use_legend: s += 'legend()\n' if array_x_t: s += 'xlabel(\'' + xar.get_domain_name() + '\')\n' elif x_label: s += 'xlabel(\'' + x_label + '\')\n' if array_y_t: s += 'ylabel(\'' + yar.get_domain_name() + '\')\n' elif y_label: s += 'ylabel(\'' + y_label + '\')\n' if p_title: s += 'title(\'' + p_title + '\')\n' print s exec s self.set_output("source", s) @classmethod def register(cls, reg, basic): reg.add_module(cls, namespace=cls.namespace) @classmethod def register_ports(cls, reg, basic): reg.add_input_port(cls, "source", (basic.String, 'source'), True) reg.add_input_port(cls, "X Array", (NDArray, 'X Array to Plot')) reg.add_input_port(cls, "Y Array", (NDArray, 'Y Array to Plot')) reg.add_input_port(cls, "Legend", (basic.Boolean, 'Use Legend'), True) reg.add_input_port(cls, "Random Colors", (basic.Boolean, 'Assign Random Colors'), True) reg.add_input_port(cls, "Colors", [basic.Integer, basic.Float, basic.Float, basic.Float], True) reg.add_input_port(cls, "Background", [basic.Float, basic.Float, basic.Float], True) reg.add_input_port(cls, "Markers", [basic.Integer, basic.String], True) reg.add_input_port(cls, "Use X Title", (basic.Boolean, 'Apply X-axis Label')) reg.add_input_port(cls, "Use Y Title", (basic.Boolean, 'Apply Y-axis Label')) reg.add_input_port(cls, "X Title", (basic.String, 'X-axis label'), True) reg.add_input_port(cls, "Y Title", (basic.String, 'Y-axis label'), True) reg.add_input_port(cls, "Title", (basic.String, 'Figure Title')) reg.add_input_port(cls, "Point Size", (basic.Float, 'Point Size'), True) reg.add_output_port(cls, "source", (basic.String, 'source')) class LinePlot(ArrayPlot, Module): ''' Create a standard line plot from a 1 or 2-dimensional Input Array. If the Input Array is 2-dimensional, each row will be plotted as a new line. ''' def compute(self): data = self.get_input("Input Array") indexes = self.force_get_input("Indexes") self.label_dict = None use_legend = self.force_get_input("Legend") randomcolors = self.force_get_input("Random Colors") colors = self.force_get_input_list("Colors") self.color_dict = None markers = self.force_get_input_list("Markers") self.marker_dict = None x_label = self.force_get_input("X Title") y_label = self.force_get_input("Y Title") p_title = self.force_get_input("Title") bg_color = self.force_get_input("Background") array_x_t = self.force_get_input("Use X Title") array_y_t = self.force_get_input("Use Y Title") s = urllib.unquote(str(self.force_get_input("source", ''))) self.source = '' da_ar = data.get_array() if da_ar.ndim > 2: raise ModuleError("Cannot plot data with dimensions > 2") s = 'from pylab import *\n' +\ 'from numpy import *\n' +\ 'import numpy\n' if bg_color == None: bg_color = 'w' if type(bg_color) == type(''): s += 'figure(facecolor=\'' + bg_color + '\')\n' else: s += 'figure(facecolor=' + str(bg_color) + ')\n' if da_ar.ndim == 1: da_ar.shape = (1, da_ar.shape[0]) xar = self.force_get_input("X Values") sf = self.force_get_input("Scaling Factor") if sf == None: sf = 1. if xar == None: start_i = None end_i = None if indexes == None: start_i = 0 end_i = da_ar.shape[1] else: start_i = indexes[0] end_i = indexes[1] xar = numpy.arange(start_i, end_i) xar = xar * sf else: xar = xar.get_array() print da_ar.shape print xar.shape for i in range(da_ar.shape[0]): lab = self.get_label(data, i) col = self.get_color(colors, i, randomcolors) mar = self.get_marker(markers, i) if indexes == None: s += 'plot(xar, da_ar[' + str(i) + ',:]' else: s += 'plot(xar, da_ar[' + str(i) + ',' + str(indexes[0]) + ':' + str(indexes[1]) + ']' if lab != None: s += ', label=\'' + lab +'\'' if col != None: s += ', color=' + str(col) if mar != None: s += ', marker=\'' + mar + '\'' s += ')\n' if use_legend: s += 'legend()\n' if array_x_t: s += 'xlabel(\'' + data.get_domain_name() + '\')\n' elif x_label: s += 'xlabel(\'' + x_label + '\')\n' if array_y_t: s += 'ylabel(\'' + data.get_range_name() + '\')\n' elif y_label: s += 'ylabel(\'' + y_label + '\')\n' if p_title: s += 'title(\'' + p_title + '\')\n' exec s self.set_output("source", s) @classmethod def register(cls, reg, basic): reg.add_module(cls, namespace=cls.namespace) @classmethod def register_ports(cls, reg, basic): reg.add_input_port(cls, "source", (basic.String, 'source'), True) reg.add_input_port(cls, "Input Array", (NDArray, 'Array to Plot')) reg.add_input_port(cls, "X Values", (NDArray, 'Domain Values')) reg.add_input_port(cls, "Legend", (basic.Boolean, 'Use Legend'), True) reg.add_input_port(cls, "Random Colors", (basic.Boolean, 'Assign Random Colors'), True) reg.add_input_port(cls, "Colors", [basic.Integer, basic.Float, basic.Float, basic.Float], True) reg.add_input_port(cls, "Markers", [basic.Integer, basic.String], True) reg.add_input_port(cls, "Use X Title", (basic.Boolean, 'Apply X-axis Label')) reg.add_input_port(cls, "Use Y Title", (basic.Boolean, 'Apply Y-axis Label')) reg.add_input_port(cls, "X Title", (basic.String, 'X-axis label'), True) reg.add_input_port(cls, "Y Title", (basic.String, 'Y-axis label'), True) reg.add_input_port(cls, "Title", (basic.String, 'Figure Title')) reg.add_input_port(cls, "Background", [basic.Float, basic.Float, basic.Float], True) reg.add_input_port(cls, "Indexes", [basic.Integer, basic.Integer], True) reg.add_input_port(cls, "Scaling Factor", (basic.Float, 'Scaling Factor'), True) reg.add_output_port(cls, "source", (basic.String, 'source'))
bsd-3-clause
jmargeta/scikit-learn
sklearn/svm/classes.py
2
26517
from .base import BaseLibLinear, BaseSVC, BaseLibSVM from ..base import RegressorMixin from ..linear_model.base import LinearClassifierMixin, SparseCoefMixin from ..feature_selection.selector_mixin import SelectorMixin class LinearSVC(BaseLibLinear, LinearClassifierMixin, SelectorMixin, SparseCoefMixin): """Linear Support Vector Classification. Similar to SVC with parameter kernel='linear', but implemented in terms of liblinear rather than libsvm, so it has more flexibility in the choice of penalties and loss functions and should scale better (to large numbers of samples). This class supports both dense and sparse input and the multiclass support is handled according to a one-vs-the-rest scheme. Parameters ---------- C : float, optional (default=1.0) Penalty parameter C of the error term. loss : string, 'l1' or 'l2' (default='l2') Specifies the loss function. 'l1' is the hinge loss (standard SVM) while 'l2' is the squared hinge loss. penalty : string, 'l1' or 'l2' (default='l2') Specifies the norm used in the penalization. The 'l2' penalty is the standard used in SVC. The 'l1' leads to `coef_` vectors that are sparse. dual : bool, (default=True) Select the algorithm to either solve the dual or primal optimization problem. Prefer dual=False when n_samples > n_features. tol : float, optional (default=1e-4) Tolerance for stopping criteria multi_class: string, 'ovr' or 'crammer_singer' (default='ovr') Determines the multi-class strategy if `y` contains more than two classes. `ovr` trains n_classes one-vs-rest classifiers, while `crammer_singer` optimizes a joint objective over all classes. While `crammer_singer` is interesting from an theoretical perspective as it is consistent it is seldom used in practice and rarely leads to better accuracy and is more expensive to compute. If `crammer_singer` is choosen, the options loss, penalty and dual will be ignored. fit_intercept : boolean, optional (default=True) Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). intercept_scaling : float, optional (default=1) when self.fit_intercept is True, instance vector x becomes [x, self.intercept_scaling], i.e. a "synthetic" feature with constant value equals to intercept_scaling is appended to the instance vector. The intercept becomes intercept_scaling * synthetic feature weight Note! the synthetic feature weight is subject to l1/l2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight (and therefore on the intercept) intercept_scaling has to be increased class_weight : {dict, 'auto'}, optional Set the parameter C of class i to class_weight[i]*C for SVC. If not given, all classes are supposed to have weight one. The 'auto' mode uses the values of y to automatically adjust weights inversely proportional to class frequencies. verbose : int, default: 0 Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in liblinear that, if enabled, may not work properly in a multithreaded context. random_state: int seed, RandomState instance, or None (default) The seed of the pseudo random number generator to use when shuffling the data. Attributes ---------- `coef_` : array, shape = [n_features] if n_classes == 2 \ else [n_classes, n_features] Weights asigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `raw_coef_` that \ follows the internal memory layout of liblinear. `intercept_` : array, shape = [1] if n_classes == 2 else [n_classes] Constants in decision function. Notes ----- The underlying C implementation uses a random number generator to select features when fitting the model. It is thus not uncommon, to have slightly different results for the same input data. If that happens, try with a smaller tol parameter. The underlying implementation (liblinear) uses a sparse internal representation for the data that will incur a memory copy. **References:** `LIBLINEAR: A Library for Large Linear Classification <http://www.csie.ntu.edu.tw/~cjlin/liblinear/>`__ See also -------- SVC Implementation of Support Vector Machine classifier using libsvm: the kernel can be non-linear but its SMO algorithm does not scale to large number of samples as LinearSVC does. Furthermore SVC multi-class mode is implemented using one vs one scheme while LinearSVC uses one vs the rest. It is possible to implement one vs the rest with SVC by using the :class:`sklearn.multiclass.OneVsRestClassifier` wrapper. Finally SVC can fit dense data without memory copy if the input is C-contiguous. Sparse data will still incur memory copy though. sklearn.linear_model.SGDClassifier SGDClassifier can optimize the same cost function as LinearSVC by adjusting the penalty and loss parameters. Furthermore SGDClassifier is scalable to large number of samples as it uses a Stochastic Gradient Descent optimizer. Finally SGDClassifier can fit both dense and sparse data without memory copy if the input is C-contiguous or CSR. """ # all the implementation is provided by the mixins pass class SVC(BaseSVC): """C-Support Vector Classification. The implementations is a based on libsvm. The fit time complexity is more than quadratic with the number of samples which makes it hard to scale to dataset with more than a couple of 10000 samples. The multiclass support is handled according to a one-vs-one scheme. For details on the precise mathematical formulation of the provided kernel functions and how `gamma`, `coef0` and `degree` affect each, see the corresponding section in the narrative documentation: :ref:`svm_kernels`. .. The narrative documentation is available at http://scikit-learn.org/ Parameters ---------- C : float, optional (default=1.0) Penalty parameter C of the error term. kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable. If none is given, 'rbf' will be used. If a callable is given it is used to precompute the kernel matrix. degree : int, optional (default=3) Degree of kernel function. It is significant only in 'poly' and 'sigmoid'. gamma : float, optional (default=0.0) Kernel coefficient for 'rbf' and 'poly'. If gamma is 0.0 then 1/n_features will be used instead. coef0 : float, optional (default=0.0) Independent term in kernel function. It is only significant in 'poly' and 'sigmoid'. probability: boolean, optional (default=False) Whether to enable probability estimates. This must be enabled prior to calling predict_proba. shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. tol : float, optional (default=1e-3) Tolerance for stopping criterion. cache_size : float, optional Specify the size of the kernel cache (in MB) class_weight : {dict, 'auto'}, optional Set the parameter C of class i to class_weight[i]*C for SVC. If not given, all classes are supposed to have weight one. The 'auto' mode uses the values of y to automatically adjust weights inversely proportional to class frequencies. verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. max_iter : int, optional (default=-1) Hard limit on iterations within solver, or -1 for no limit. Attributes ---------- `support_` : array-like, shape = [n_SV] Index of support vectors. `support_vectors_` : array-like, shape = [n_SV, n_features] Support vectors. `n_support_` : array-like, dtype=int32, shape = [n_class] number of support vector for each class. `dual_coef_` : array, shape = [n_class-1, n_SV] Coefficients of the support vector in the decision function. \ For multiclass, coefficient for all 1-vs-1 classifiers. \ The layout of the coefficients in the multiclass case is somewhat \ non-trivial. See the section about multi-class classification in the \ SVM section of the User Guide for details. `coef_` : array, shape = [n_class-1, n_features] Weights asigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and `support_vectors_` `intercept_` : array, shape = [n_class * (n_class-1) / 2] Constants in decision function. Examples -------- >>> import numpy as np >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) >>> y = np.array([1, 1, 2, 2]) >>> from sklearn.svm import SVC >>> clf = SVC() >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=-1, probability=False, shrinking=True, tol=0.001, verbose=False) >>> print(clf.predict([[-0.8, -1]])) [1] See also -------- SVR Support Vector Machine for Regression implemented using libsvm. LinearSVC Scalable Linear Support Vector Machine for classififcation implemented using liblinear. Check the See also section of LinearSVC for more comparison element. """ def __init__(self, C=1.0, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, probability=False, tol=1e-3, cache_size=200, class_weight=None, verbose=False, max_iter=-1): super(SVC, self).__init__( 'c_svc', kernel, degree, gamma, coef0, tol, C, 0., 0., shrinking, probability, cache_size, class_weight, verbose, max_iter) class NuSVC(BaseSVC): """Nu-Support Vector Classification. Similar to SVC but uses a parameter to control the number of support vectors. The implementation is based on libsvm. Parameters ---------- nu : float, optional (default=0.5) An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. Should be in the interval (0, 1]. kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable. If none is given, 'rbf' will be used. If a callable is given it is used to precompute the kernel matrix. degree : int, optional (default=3) degree of kernel function is significant only in poly, rbf, sigmoid gamma : float, optional (default=0.0) kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features will be taken. coef0 : float, optional (default=0.0) independent term in kernel function. It is only significant in poly/sigmoid. probability: boolean, optional (default=False) Whether to enable probability estimates. This must be enabled prior to calling predict_proba. shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. tol : float, optional (default=1e-3) Tolerance for stopping criterion. cache_size : float, optional Specify the size of the kernel cache (in MB) verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. max_iter : int, optional (default=-1) Hard limit on iterations within solver, or -1 for no limit. Attributes ---------- `support_` : array-like, shape = [n_SV] Index of support vectors. `support_vectors_` : array-like, shape = [n_SV, n_features] Support vectors. `n_support_` : array-like, dtype=int32, shape = [n_class] number of support vector for each class. `dual_coef_` : array, shape = [n_class-1, n_SV] Coefficients of the support vector in the decision function. \ For multiclass, coefficient for all 1-vs-1 classifiers. \ The layout of the coefficients in the multiclass case is somewhat \ non-trivial. See the section about multi-class classification in \ the SVM section of the User Guide for details. `coef_` : array, shape = [n_class-1, n_features] Weights asigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and `support_vectors_` `intercept_` : array, shape = [n_class * (n_class-1) / 2] Constants in decision function. Examples -------- >>> import numpy as np >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) >>> y = np.array([1, 1, 2, 2]) >>> from sklearn.svm import NuSVC >>> clf = NuSVC() >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE NuSVC(cache_size=200, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=-1, nu=0.5, probability=False, shrinking=True, tol=0.001, verbose=False) >>> print(clf.predict([[-0.8, -1]])) [1] See also -------- SVC Support Vector Machine for classification using libsvm. LinearSVC Scalable linear Support Vector Machine for classification using liblinear. """ def __init__(self, nu=0.5, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, probability=False, tol=1e-3, cache_size=200, verbose=False, max_iter=-1): super(NuSVC, self).__init__( 'nu_svc', kernel, degree, gamma, coef0, tol, 0., nu, 0., shrinking, probability, cache_size, None, verbose, max_iter) class SVR(BaseLibSVM, RegressorMixin): """epsilon-Support Vector Regression. The free parameters in the model are C and epsilon. The implementations is a based on libsvm. Parameters ---------- C : float, optional (default=1.0) penalty parameter C of the error term. epsilon : float, optional (default=0.1) epsilon in the epsilon-SVR model. It specifies the epsilon-tube within which no penalty is associated in the training loss function with points predicted within a distance epsilon from the actual value. kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable. If none is given, 'rbf' will be used. If a callable is given it is used to precompute the kernel matrix. degree : int, optional (default=3) degree of kernel function is significant only in poly, rbf, sigmoid gamma : float, optional (default=0.0) kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features will be taken. coef0 : float, optional (default=0.0) independent term in kernel function. It is only significant in poly/sigmoid. probability: boolean, optional (default=False) Whether to enable probability estimates. This must be enabled prior to calling predict_proba. shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. tol : float, optional (default=1e-3) Tolerance for stopping criterion. cache_size : float, optional Specify the size of the kernel cache (in MB) verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. max_iter : int, optional (default=-1) Hard limit on iterations within solver, or -1 for no limit. Attributes ---------- `support_` : array-like, shape = [n_SV] Index of support vectors. `support_vectors_` : array-like, shape = [nSV, n_features] Support vectors. `dual_coef_` : array, shape = [n_classes-1, n_SV] Coefficients of the support vector in the decision function. `coef_` : array, shape = [n_classes-1, n_features] Weights asigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and `support_vectors_` `intercept_` : array, shape = [n_class * (n_class-1) / 2] Constants in decision function. Examples -------- >>> from sklearn.svm import SVR >>> import numpy as np >>> n_samples, n_features = 10, 5 >>> np.random.seed(0) >>> y = np.random.randn(n_samples) >>> X = np.random.randn(n_samples, n_features) >>> clf = SVR(C=1.0, epsilon=0.2) >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE SVR(C=1.0, cache_size=200, coef0=0.0, degree=3, epsilon=0.2, gamma=0.0, kernel='rbf', max_iter=-1, probability=False, shrinking=True, tol=0.001, verbose=False) See also -------- NuSVR Support Vector Machine for regression implemented using libsvm using a parameter to control the number of support vectors. """ def __init__(self, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, tol=1e-3, C=1.0, epsilon=0.1, shrinking=True, probability=False, cache_size=200, verbose=False, max_iter=-1): super(SVR, self).__init__( 'epsilon_svr', kernel, degree, gamma, coef0, tol, C, 0., epsilon, shrinking, probability, cache_size, None, verbose, max_iter) class NuSVR(BaseLibSVM, RegressorMixin): """Nu Support Vector Regression. Similar to NuSVC, for regression, uses a parameter nu to control the number of support vectors. However, unlike NuSVC, where nu replaces C, here nu replaces with the parameter epsilon of SVR. The implementations is a based on libsvm. Parameters ---------- C : float, optional (default=1.0) penalty parameter C of the error term. nu : float, optional An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. Should be in the interval (0, 1]. By default 0.5 will be taken. Only available if impl='nu_svc'. kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable. If none is given, 'rbf' will be used. If a callable is given it is used to precompute the kernel matrix. degree : int, optional (default=3) degree of kernel function is significant only in poly, rbf, sigmoid gamma : float, optional (default=0.0) kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features will be taken. coef0 : float, optional (default=0.0) independent term in kernel function. It is only significant in poly/sigmoid. probability: boolean, optional (default=False) Whether to enable probability estimates. This must be enabled prior to calling predict_proba. shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. tol : float, optional (default=1e-3) Tolerance for stopping criterion. cache_size : float, optional Specify the size of the kernel cache (in MB) verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. max_iter : int, optional (default=-1) Hard limit on iterations within solver, or -1 for no limit. Attributes ---------- `support_` : array-like, shape = [n_SV] Index of support vectors. `support_vectors_` : array-like, shape = [nSV, n_features] Support vectors. `dual_coef_` : array, shape = [n_classes-1, n_SV] Coefficients of the support vector in the decision function. `coef_` : array, shape = [n_classes-1, n_features] Weights asigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and `support_vectors_` `intercept_` : array, shape = [n_class * (n_class-1) / 2] Constants in decision function. Examples -------- >>> from sklearn.svm import NuSVR >>> import numpy as np >>> n_samples, n_features = 10, 5 >>> np.random.seed(0) >>> y = np.random.randn(n_samples) >>> X = np.random.randn(n_samples, n_features) >>> clf = NuSVR(C=1.0, nu=0.1) >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE NuSVR(C=1.0, cache_size=200, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=-1, nu=0.1, probability=False, shrinking=True, tol=0.001, verbose=False) See also -------- NuSVC Support Vector Machine for classification implemented with libsvm with a parameter to control the number of support vectors. SVR epsilon Support Vector Machine for regression implemented with libsvm. """ def __init__(self, nu=0.5, C=1.0, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, probability=False, tol=1e-3, cache_size=200, verbose=False, max_iter=-1): super(NuSVR, self).__init__( 'nu_svr', kernel, degree, gamma, coef0, tol, C, nu, 0., shrinking, probability, cache_size, None, verbose, max_iter) class OneClassSVM(BaseLibSVM): """Unsupervised Outliers Detection. Estimate the support of a high-dimensional distribution. The implementation is based on libsvm. Parameters ---------- kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable. If none is given, 'rbf' will be used. If a callable is given it is used to precompute the kernel matrix. nu : float, optional An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. Should be in the interval (0, 1]. By default 0.5 will be taken. degree : int, optional Degree of kernel function. Significant only in poly, rbf, sigmoid. gamma : float, optional (default=0.0) kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features will be taken. coef0 : float, optional Independent term in kernel function. It is only significant in poly/sigmoid. tol : float, optional Tolerance for stopping criterion. shrinking: boolean, optional Whether to use the shrinking heuristic. cache_size : float, optional Specify the size of the kernel cache (in MB) verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. max_iter : int, optional (default=-1) Hard limit on iterations within solver, or -1 for no limit. Attributes ---------- `support_` : array-like, shape = [n_SV] Index of support vectors. `support_vectors_` : array-like, shape = [nSV, n_features] Support vectors. `dual_coef_` : array, shape = [n_classes-1, n_SV] Coefficient of the support vector in the decision function. `coef_` : array, shape = [n_classes-1, n_features] Weights asigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and `support_vectors_` `intercept_` : array, shape = [n_classes-1] Constants in decision function. """ def __init__(self, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, tol=1e-3, nu=0.5, shrinking=True, cache_size=200, verbose=False, max_iter=-1): super(OneClassSVM, self).__init__( 'one_class', kernel, degree, gamma, coef0, tol, 0., nu, 0., shrinking, False, cache_size, None, verbose, max_iter) def fit(self, X, sample_weight=None, **params): """ Detects the soft boundary of the set of samples X. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Set of samples, where n_samples is the number of samples and n_features is the number of features. Returns ------- self : object Returns self. Notes ----- If X is not a C-ordered contiguous array it is copied. """ super(OneClassSVM, self).fit(X, [], sample_weight=sample_weight, **params) return self
bsd-3-clause
bthirion/scikit-learn
examples/ensemble/plot_ensemble_oob.py
58
3265
""" ============================= OOB Errors for Random Forests ============================= The ``RandomForestClassifier`` is trained using *bootstrap aggregation*, where each new tree is fit from a bootstrap sample of the training observations :math:`z_i = (x_i, y_i)`. The *out-of-bag* (OOB) error is the average error for each :math:`z_i` calculated using predictions from the trees that do not contain :math:`z_i` in their respective bootstrap sample. This allows the ``RandomForestClassifier`` to be fit and validated whilst being trained [1]. The example below demonstrates how the OOB error can be measured at the addition of each new tree during training. The resulting plot allows a practitioner to approximate a suitable value of ``n_estimators`` at which the error stabilizes. .. [1] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical Learning Ed. 2", p592-593, Springer, 2009. """ import matplotlib.pyplot as plt from collections import OrderedDict from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier # Author: Kian Ho <hui.kian.ho@gmail.com> # Gilles Louppe <g.louppe@gmail.com> # Andreas Mueller <amueller@ais.uni-bonn.de> # # License: BSD 3 Clause print(__doc__) RANDOM_STATE = 123 # Generate a binary classification dataset. X, y = make_classification(n_samples=500, n_features=25, n_clusters_per_class=1, n_informative=15, random_state=RANDOM_STATE) # NOTE: Setting the `warm_start` construction parameter to `True` disables # support for parallelized ensembles but is necessary for tracking the OOB # error trajectory during training. ensemble_clfs = [ ("RandomForestClassifier, max_features='sqrt'", RandomForestClassifier(warm_start=True, oob_score=True, max_features="sqrt", random_state=RANDOM_STATE)), ("RandomForestClassifier, max_features='log2'", RandomForestClassifier(warm_start=True, max_features='log2', oob_score=True, random_state=RANDOM_STATE)), ("RandomForestClassifier, max_features=None", RandomForestClassifier(warm_start=True, max_features=None, oob_score=True, random_state=RANDOM_STATE)) ] # Map a classifier name to a list of (<n_estimators>, <error rate>) pairs. error_rate = OrderedDict((label, []) for label, _ in ensemble_clfs) # Range of `n_estimators` values to explore. min_estimators = 15 max_estimators = 175 for label, clf in ensemble_clfs: for i in range(min_estimators, max_estimators + 1): clf.set_params(n_estimators=i) clf.fit(X, y) # Record the OOB error for each `n_estimators=i` setting. oob_error = 1 - clf.oob_score_ error_rate[label].append((i, oob_error)) # Generate the "OOB error rate" vs. "n_estimators" plot. for label, clf_err in error_rate.items(): xs, ys = zip(*clf_err) plt.plot(xs, ys, label=label) plt.xlim(min_estimators, max_estimators) plt.xlabel("n_estimators") plt.ylabel("OOB error rate") plt.legend(loc="upper right") plt.show()
bsd-3-clause
HyperloopTeam/FullOpenMDAO
lib/python2.7/site-packages/matplotlib/backends/backend_template.py
20
9358
""" This is a fully functional do nothing backend to provide a template to backend writers. It is fully functional in that you can select it as a backend with import matplotlib matplotlib.use('Template') and your matplotlib scripts will (should!) run without error, though no output is produced. This provides a nice starting point for backend writers because you can selectively implement methods (draw_rectangle, draw_lines, etc...) and slowly see your figure come to life w/o having to have a full blown implementation before getting any results. Copy this to backend_xxx.py and replace all instances of 'template' with 'xxx'. Then implement the class methods and functions below, and add 'xxx' to the switchyard in matplotlib/backends/__init__.py and 'xxx' to the backends list in the validate_backend methon in matplotlib/__init__.py and you're off. You can use your backend with:: import matplotlib matplotlib.use('xxx') from pylab import * plot([1,2,3]) show() matplotlib also supports external backends, so you can place you can use any module in your PYTHONPATH with the syntax:: import matplotlib matplotlib.use('module://my_backend') where my_backend.py is your module name. This syntax is also recognized in the rc file and in the -d argument in pylab, e.g.,:: python simple_plot.py -dmodule://my_backend If your backend implements support for saving figures (i.e. has a print_xyz() method) you can register it as the default handler for a given file type from matplotlib.backend_bases import register_backend register_backend('xyz', 'my_backend', 'XYZ File Format') ... plt.savefig("figure.xyz") The files that are most relevant to backend_writers are matplotlib/backends/backend_your_backend.py matplotlib/backend_bases.py matplotlib/backends/__init__.py matplotlib/__init__.py matplotlib/_pylab_helpers.py Naming Conventions * classes Upper or MixedUpperCase * varables lower or lowerUpper * functions lower or underscore_separated """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import matplotlib from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ FigureManagerBase, FigureCanvasBase from matplotlib.figure import Figure from matplotlib.transforms import Bbox class RendererTemplate(RendererBase): """ The renderer handles drawing/rendering operations. This is a minimal do-nothing class that can be used to get started when writing a new backend. Refer to backend_bases.RendererBase for documentation of the classes methods. """ def __init__(self, dpi): self.dpi = dpi def draw_path(self, gc, path, transform, rgbFace=None): pass # draw_markers is optional, and we get more correct relative # timings by leaving it out. backend implementers concerned with # performance will probably want to implement it # def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): # pass # draw_path_collection is optional, and we get more correct # relative timings by leaving it out. backend implementers concerned with # performance will probably want to implement it # def draw_path_collection(self, gc, master_transform, paths, # all_transforms, offsets, offsetTrans, facecolors, # edgecolors, linewidths, linestyles, # antialiaseds): # pass # draw_quad_mesh is optional, and we get more correct # relative timings by leaving it out. backend implementers concerned with # performance will probably want to implement it # def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight, # coordinates, offsets, offsetTrans, facecolors, # antialiased, edgecolors): # pass def draw_image(self, gc, x, y, im): pass def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): pass def flipy(self): return True def get_canvas_width_height(self): return 100, 100 def get_text_width_height_descent(self, s, prop, ismath): return 1, 1, 1 def new_gc(self): return GraphicsContextTemplate() def points_to_pixels(self, points): # if backend doesn't have dpi, e.g., postscript or svg return points # elif backend assumes a value for pixels_per_inch #return points/72.0 * self.dpi.get() * pixels_per_inch/72.0 # else #return points/72.0 * self.dpi.get() class GraphicsContextTemplate(GraphicsContextBase): """ The graphics context provides the color, line styles, etc... See the gtk and postscript backends for examples of mapping the graphics context attributes (cap styles, join styles, line widths, colors) to a particular backend. In GTK this is done by wrapping a gtk.gdk.GC object and forwarding the appropriate calls to it using a dictionary mapping styles to gdk constants. In Postscript, all the work is done by the renderer, mapping line styles to postscript calls. If it's more appropriate to do the mapping at the renderer level (as in the postscript backend), you don't need to override any of the GC methods. If it's more appropriate to wrap an instance (as in the GTK backend) and do the mapping here, you'll need to override several of the setter methods. The base GraphicsContext stores colors as a RGB tuple on the unit interval, e.g., (0.5, 0.0, 1.0). You may need to map this to colors appropriate for your backend. """ pass ######################################################################## # # The following functions and classes are for pylab and implement # window/figure managers, etc... # ######################################################################## def draw_if_interactive(): """ For image backends - is not required For GUI backends - this should be overriden if drawing should be done in interactive python mode """ pass def show(): """ For image backends - is not required For GUI backends - show() is usually the last line of a pylab script and tells the backend that it is time to draw. In interactive mode, this may be a do nothing func. See the GTK backend for an example of how to handle interactive versus batch mode """ for manager in Gcf.get_all_fig_managers(): # do something to display the GUI pass def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ # if a main-level app must be created, this (and # new_figure_manager_given_figure) is the usual place to # do it -- see backend_wx, backend_wxagg and backend_tkagg for # examples. Not all GUIs require explicit instantiation of a # main-level app (egg backend_gtk, backend_gtkagg) for pylab FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) return new_figure_manager_given_figure(num, thisFig) def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ canvas = FigureCanvasTemplate(figure) manager = FigureManagerTemplate(canvas, num) return manager class FigureCanvasTemplate(FigureCanvasBase): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Public attribute figure - A Figure instance Note GUI templates will want to connect events for button presses, mouse movements and key presses to functions that call the base class methods button_press_event, button_release_event, motion_notify_event, key_press_event, and key_release_event. See, e.g., backend_gtk.py, backend_wx.py and backend_tkagg.py """ def draw(self): """ Draw the figure using the renderer """ renderer = RendererTemplate(self.figure.dpi) self.figure.draw(renderer) # You should provide a print_xxx function for every file format # you can write. # If the file type is not in the base set of filetypes, # you should add it to the class-scope filetypes dictionary as follows: filetypes = FigureCanvasBase.filetypes.copy() filetypes['foo'] = 'My magic Foo format' def print_foo(self, filename, *args, **kwargs): """ Write out format foo. The dpi, facecolor and edgecolor are restored to their original values after this call, so you don't need to save and restore them. """ pass def get_default_filetype(self): return 'foo' class FigureManagerTemplate(FigureManagerBase): """ Wrap everything up into a window for the pylab interface For non interactive backends, the base class does all the work """ pass ######################################################################## # # Now just provide the standard names that backend.__init__ is expecting # ######################################################################## FigureCanvas = FigureCanvasTemplate FigureManager = FigureManagerTemplate
gpl-2.0
ndingwall/scikit-learn
examples/ensemble/plot_adaboost_twoclass.py
72
3333
""" ================== Two-class AdaBoost ================== This example fits an AdaBoosted decision stump on a non-linearly separable classification dataset composed of two "Gaussian quantiles" clusters (see :func:`sklearn.datasets.make_gaussian_quantiles`) and plots the decision boundary and decision scores. The distributions of decision scores are shown separately for samples of class A and B. The predicted class label for each sample is determined by the sign of the decision score. Samples with decision scores greater than zero are classified as B, and are otherwise classified as A. The magnitude of a decision score determines the degree of likeness with the predicted class label. Additionally, a new dataset could be constructed containing a desired purity of class B, for example, by only selecting samples with a decision score above some value. """ print(__doc__) # Author: Noel Dawe <noel.dawe@gmail.com> # # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import AdaBoostClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import make_gaussian_quantiles # Construct dataset X1, y1 = make_gaussian_quantiles(cov=2., n_samples=200, n_features=2, n_classes=2, random_state=1) X2, y2 = make_gaussian_quantiles(mean=(3, 3), cov=1.5, n_samples=300, n_features=2, n_classes=2, random_state=1) X = np.concatenate((X1, X2)) y = np.concatenate((y1, - y2 + 1)) # Create and fit an AdaBoosted decision tree bdt = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1), algorithm="SAMME", n_estimators=200) bdt.fit(X, y) plot_colors = "br" plot_step = 0.02 class_names = "AB" plt.figure(figsize=(10, 5)) # Plot the decision boundaries plt.subplot(121) x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step), np.arange(y_min, y_max, plot_step)) Z = bdt.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired) plt.axis("tight") # Plot the training points for i, n, c in zip(range(2), class_names, plot_colors): idx = np.where(y == i) plt.scatter(X[idx, 0], X[idx, 1], c=c, cmap=plt.cm.Paired, s=20, edgecolor='k', label="Class %s" % n) plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.legend(loc='upper right') plt.xlabel('x') plt.ylabel('y') plt.title('Decision Boundary') # Plot the two-class decision scores twoclass_output = bdt.decision_function(X) plot_range = (twoclass_output.min(), twoclass_output.max()) plt.subplot(122) for i, n, c in zip(range(2), class_names, plot_colors): plt.hist(twoclass_output[y == i], bins=10, range=plot_range, facecolor=c, label='Class %s' % n, alpha=.5, edgecolor='k') x1, x2, y1, y2 = plt.axis() plt.axis((x1, x2, y1, y2 * 1.2)) plt.legend(loc='upper right') plt.ylabel('Samples') plt.xlabel('Score') plt.title('Decision Scores') plt.tight_layout() plt.subplots_adjust(wspace=0.35) plt.show()
bsd-3-clause
sarahgrogan/scikit-learn
sklearn/linear_model/passive_aggressive.py
97
10879
# Authors: Rob Zinkov, Mathieu Blondel # License: BSD 3 clause from .stochastic_gradient import BaseSGDClassifier from .stochastic_gradient import BaseSGDRegressor from .stochastic_gradient import DEFAULT_EPSILON class PassiveAggressiveClassifier(BaseSGDClassifier): """Passive Aggressive Classifier Read more in the :ref:`User Guide <passive_aggressive>`. Parameters ---------- C : float Maximum step size (regularization). Defaults to 1.0. fit_intercept : bool, default=False Whether the intercept should be estimated or not. If False, the data is assumed to be already centered. n_iter : int, optional The number of passes over the training data (aka epochs). Defaults to 5. shuffle : bool, default=True Whether or not the training data should be shuffled after each epoch. random_state : int seed, RandomState instance, or None (default) The seed of the pseudo random number generator to use when shuffling the data. verbose : integer, optional The verbosity level n_jobs : integer, optional The number of CPUs to use to do the OVA (One Versus All, for multi-class problems) computation. -1 means 'all CPUs'. Defaults to 1. loss : string, optional The loss function to be used: hinge: equivalent to PA-I in the reference paper. squared_hinge: equivalent to PA-II in the reference paper. warm_start : bool, optional When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. class_weight : dict, {class_label: weight} or "balanced" or None, optional Preset for the class_weight fit parameter. Weights associated with classes. If not given, all classes are supposed to have weight one. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` Attributes ---------- coef_ : array, shape = [1, n_features] if n_classes == 2 else [n_classes,\ n_features] Weights assigned to the features. intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] Constants in decision function. See also -------- SGDClassifier Perceptron References ---------- Online Passive-Aggressive Algorithms <http://jmlr.csail.mit.edu/papers/volume7/crammer06a/crammer06a.pdf> K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006) """ def __init__(self, C=1.0, fit_intercept=True, n_iter=5, shuffle=True, verbose=0, loss="hinge", n_jobs=1, random_state=None, warm_start=False, class_weight=None): BaseSGDClassifier.__init__(self, penalty=None, fit_intercept=fit_intercept, n_iter=n_iter, shuffle=shuffle, verbose=verbose, random_state=random_state, eta0=1.0, warm_start=warm_start, class_weight=class_weight, n_jobs=n_jobs) self.C = C self.loss = loss def partial_fit(self, X, y, classes=None): """Fit linear model with Passive Aggressive algorithm. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Subset of the training data y : numpy array of shape [n_samples] Subset of the target values classes : array, shape = [n_classes] Classes across all calls to partial_fit. Can be obtained by via `np.unique(y_all)`, where y_all is the target vector of the entire dataset. This argument is required for the first call to partial_fit and can be omitted in the subsequent calls. Note that y doesn't need to contain all labels in `classes`. Returns ------- self : returns an instance of self. """ if self.class_weight == 'balanced': raise ValueError("class_weight 'balanced' is not supported for " "partial_fit. For 'balanced' weights, use " "`sklearn.utils.compute_class_weight` with " "`class_weight='balanced'`. In place of y you " "can use a large enough subset of the full " "training set target to properly estimate the " "class frequency distributions. Pass the " "resulting weights as the class_weight " "parameter.") lr = "pa1" if self.loss == "hinge" else "pa2" return self._partial_fit(X, y, alpha=1.0, C=self.C, loss="hinge", learning_rate=lr, n_iter=1, classes=classes, sample_weight=None, coef_init=None, intercept_init=None) def fit(self, X, y, coef_init=None, intercept_init=None): """Fit linear model with Passive Aggressive algorithm. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training data y : numpy array of shape [n_samples] Target values coef_init : array, shape = [n_classes,n_features] The initial coefficients to warm-start the optimization. intercept_init : array, shape = [n_classes] The initial intercept to warm-start the optimization. Returns ------- self : returns an instance of self. """ lr = "pa1" if self.loss == "hinge" else "pa2" return self._fit(X, y, alpha=1.0, C=self.C, loss="hinge", learning_rate=lr, coef_init=coef_init, intercept_init=intercept_init) class PassiveAggressiveRegressor(BaseSGDRegressor): """Passive Aggressive Regressor Read more in the :ref:`User Guide <passive_aggressive>`. Parameters ---------- C : float Maximum step size (regularization). Defaults to 1.0. epsilon : float If the difference between the current prediction and the correct label is below this threshold, the model is not updated. fit_intercept : bool Whether the intercept should be estimated or not. If False, the data is assumed to be already centered. Defaults to True. n_iter : int, optional The number of passes over the training data (aka epochs). Defaults to 5. shuffle : bool, default=True Whether or not the training data should be shuffled after each epoch. random_state : int seed, RandomState instance, or None (default) The seed of the pseudo random number generator to use when shuffling the data. verbose : integer, optional The verbosity level loss : string, optional The loss function to be used: epsilon_insensitive: equivalent to PA-I in the reference paper. squared_epsilon_insensitive: equivalent to PA-II in the reference paper. warm_start : bool, optional When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. Attributes ---------- coef_ : array, shape = [1, n_features] if n_classes == 2 else [n_classes,\ n_features] Weights assigned to the features. intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] Constants in decision function. See also -------- SGDRegressor References ---------- Online Passive-Aggressive Algorithms <http://jmlr.csail.mit.edu/papers/volume7/crammer06a/crammer06a.pdf> K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006) """ def __init__(self, C=1.0, fit_intercept=True, n_iter=5, shuffle=True, verbose=0, loss="epsilon_insensitive", epsilon=DEFAULT_EPSILON, random_state=None, warm_start=False): BaseSGDRegressor.__init__(self, penalty=None, l1_ratio=0, epsilon=epsilon, eta0=1.0, fit_intercept=fit_intercept, n_iter=n_iter, shuffle=shuffle, verbose=verbose, random_state=random_state, warm_start=warm_start) self.C = C self.loss = loss def partial_fit(self, X, y): """Fit linear model with Passive Aggressive algorithm. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Subset of training data y : numpy array of shape [n_samples] Subset of target values Returns ------- self : returns an instance of self. """ lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2" return self._partial_fit(X, y, alpha=1.0, C=self.C, loss="epsilon_insensitive", learning_rate=lr, n_iter=1, sample_weight=None, coef_init=None, intercept_init=None) def fit(self, X, y, coef_init=None, intercept_init=None): """Fit linear model with Passive Aggressive algorithm. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training data y : numpy array of shape [n_samples] Target values coef_init : array, shape = [n_features] The initial coefficients to warm-start the optimization. intercept_init : array, shape = [1] The initial intercept to warm-start the optimization. Returns ------- self : returns an instance of self. """ lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2" return self._fit(X, y, alpha=1.0, C=self.C, loss="epsilon_insensitive", learning_rate=lr, coef_init=coef_init, intercept_init=intercept_init)
bsd-3-clause
MattNolanLab/ei-attractor
grid_cell_model/plotting/connections.py
1
2559
'''Functions/methods to plot connectivity matrices. .. currentmodule:: grid_cell_model.plotting.connections Classes / Functions ------------------- .. autosummary:: plotConnHistogram plot2DWeightMatrix ''' import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ti from global_defs import globalAxesSettings def plotConnHistogram(val, **kw): ''' Plot a histogram of connection weights with some predetermined formatting. Parameters ---------- val : numpy array A 1D array of connetions. **kw Keyword arguments to the hist function. See code for some additional keyword arguments. ''' # keyword arguments kw['bins'] = kw.get('bins', 20) #kw['edgecolor'] = kw.get('edgecolor', 'none') ax = kw.pop('ax', plt.gca()) xlabel = kw.pop('xlabel', 'g (nS)') ylabel = kw.pop('ylabel', 'Count') title = kw.pop('title', '') locators = kw.pop('locators', {}) ylabelPos = kw.pop('ylabelPos', -0.2) globalAxesSettings(ax) n, _, _ = ax.hist(val, **kw) print(np.max(n)) ax.set_xlabel(xlabel) ax.text(ylabelPos, 0.5, ylabel, rotation=90, transform=ax.transAxes, va='center', ha='right') ax.set_title(title) # tick formatting x_major = locators.get('x_major', ti.MaxNLocator(3)) x_minor = locators.get('x_minor', ti.AutoMinorLocator(2)) y_major = locators.get('y_major', ti.LinearLocator(2)) y_minor = locators.get('y_minor', ti.AutoMinorLocator(4)) ax.xaxis.set_major_locator(x_major) ax.yaxis.set_major_locator(y_major) ax.xaxis.set_minor_locator(x_minor) ax.yaxis.set_minor_locator(y_minor) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) return ax def plot2DWeightMatrix(C, **kw): ax = kw.pop('ax', plt.gca()) xlabel = kw.pop('xlabel', 'Neuron #') ylabel = kw.pop('ylabel', 'Neuron #') labelpad = kw.pop('labelpad', None) title = kw.pop('title', '') kw['rasterized'] = kw.get('rasterized', True) X = np.arange(C.shape[1] + 1) Y = np.arange(C.shape[0] + 1) globalAxesSettings(ax) ax.pcolormesh(X, Y, C, **kw) ax.set_xticks([0.5, X[-1]-0.5]) ax.set_yticks([0.5, Y[-1]-0.5]) ax.set_xticklabels([1, X[-1]]) ax.set_yticklabels([1, Y[-1]]) plt.axis('scaled') ax.set_xlabel(xlabel, labelpad=labelpad) ax.set_ylabel(ylabel, labelpad=labelpad) ax.set_title(title, size='small') return ax
gpl-3.0
marcelovilaca/DIRAC
Core/Utilities/Graphs/PlotBase.py
10
9309
######################################################################## # $HeadURL$ ######################################################################## """ PlotBase is a base class for various Graphs plots The DIRAC Graphs package is derived from the GraphTool plotting package of the CMS/Phedex Project by ... <to be added> """ __RCSID__ = "$Id$" import types, random from DIRAC.Core.Utilities.Graphs.Palette import Palette from DIRAC.Core.Utilities.Graphs.GraphData import GraphData from matplotlib.patches import Rectangle from matplotlib.text import Text from DIRAC.Core.Utilities.Graphs.GraphUtilities import * from matplotlib.axes import Axes from matplotlib.pylab import setp class PlotBase( object ): def __init__( self, data = None, axes = None, *aw, **kw ): self.ax_contain = axes self.canvas = None self.figure = None if self.ax_contain: self.figure = self.ax_contain.get_figure() self.canvas = self.figure.canvas self.dpi = self.ax_contain.figure.get_dpi() self.ax_contain.set_axis_off() self.prefs = evalPrefs( *aw, **kw ) self.coords = {} self.palette = Palette() if type( data ) == types.DictType: self.gdata = GraphData( data ) elif type( data ) == types.InstanceType and data.__class__ == GraphData: self.gdata = data def dumpPrefs( self ): for key in self.prefs: print key.rjust( 20 ), ':', str( self.prefs[key] ).ljust( 40 ) def setAxes( self, axes ): self.ax_contain = axes self.ax_contain.set_axis_off() self.figure = self.ax_contain.get_figure() self.canvas = self.figure.canvas self.dpi = self.ax_contain.figure.get_dpi() def draw( self ): prefs = self.prefs dpi = self.ax_contain.figure.get_dpi() # Update palette palette = prefs.get( 'colors', {} ) if palette: self.palette.addPalette( palette ) xlabel = prefs.get( 'xlabel', '' ) ylabel = prefs.get( 'ylabel', '' ) xticks_flag = prefs.get( 'xticks', True ) yticks_flag = prefs.get( 'yticks', True ) text_size = prefs['text_size'] text_padding = prefs['text_padding'] label_text_size = prefs.get( 'label_text_size', text_size ) label_text_size_point = pixelToPoint( label_text_size, dpi ) tick_text_size = prefs.get( 'tick_text_size', text_size ) tick_text_size_point = pixelToPoint( tick_text_size, dpi ) ytick_length = prefs.get( 'ytick_length', 7 * tick_text_size ) plot_title = prefs.get( 'plot_title', '' ) if not plot_title or plot_title == 'NoTitle': plot_title_size = 0 plot_title_padding = 0 else: plot_title_size = prefs.get( 'plot_title_size', text_size ) plot_title_padding = prefs.get( 'plot_text_padding', text_padding ) plot_title_size_point = pixelToPoint( plot_title_size, dpi ) stats_flag = prefs.get( 'statistics_line', False ) stats_line = '' stats_line_space = 0. if stats_flag: stats_line = self.gdata.getStatString() stats_line_size = label_text_size stats_line_padding = label_text_size * 2. stats_line_space = stats_line_size + stats_line_padding plot_padding = prefs['plot_padding'] plot_left_padding = prefs.get( 'plot_left_padding', plot_padding ) plot_right_padding = prefs.get( 'plot_right_padding', 0 ) plot_bottom_padding = prefs.get( 'plot_bottom_padding', plot_padding ) plot_top_padding = prefs.get( 'plot_top_padding', 0 ) frame_flag = prefs['frame'] # Create plot axes, and set properties left, bottom, width, height = self.ax_contain.get_window_extent().bounds l, b, f_width, f_height = self.figure.get_window_extent().bounds # Space needed for labels and ticks x_label_space = 0 if xticks_flag: x_label_space += tick_text_size * 1.5 if xlabel: x_label_space += label_text_size * 1.5 y_label_space = 0 if yticks_flag: y_label_space += ytick_length if ylabel: y_label_space += label_text_size * 1.5 ax_plot_rect = ( float( plot_left_padding + left + y_label_space ) / f_width, float( plot_bottom_padding + bottom + x_label_space + stats_line_space ) / f_height, float( width - plot_left_padding - plot_right_padding - y_label_space ) / f_width, float( height - plot_bottom_padding - plot_top_padding - x_label_space - \ plot_title_size - 2 * plot_title_padding - stats_line_space ) / f_height ) ax = Axes( self.figure, ax_plot_rect ) if prefs['square_axis']: l, b, a_width, a_height = ax.get_window_extent().bounds delta = abs( a_height - a_width ) if a_height > a_width: a_height = a_width ax_plot_rect = ( float( plot_left_padding + left ) / f_width, float( plot_bottom_padding + bottom + delta / 2. ) / f_height, float( width - plot_left_padding - plot_right_padding ) / f_width, float( height - plot_bottom_padding - plot_title_size - 2 * plot_title_padding - delta ) / f_height ) else: a_width = a_height ax_plot_rect = ( float( plot_left_padding + left + delta / 2. ) / f_width, float( plot_bottom_padding + bottom ) / f_height, float( width - plot_left_padding - delta ) / f_width, float( height - plot_bottom_padding - plot_title_size - 2 * plot_title_padding ) / f_height ) ax.set_position( ax_plot_rect ) self.figure.add_axes( ax ) self.ax = ax frame = ax.patch frame.set_fill( False ) if frame_flag.lower() == 'off': self.ax.set_axis_off() self.log_xaxis = False self.log_yaxis = False else: # If requested, make x/y axis logarithmic if prefs.get( 'log_xaxis', 'False' ).find( 'r' ) >= 0: ax.semilogx() self.log_xaxis = True else: self.log_xaxis = False if prefs.get( 'log_yaxis', 'False' ).find( 'r' ) >= 0: ax.semilogy() self.log_yaxis = True else: self.log_yaxis = False if xticks_flag: setp( ax.get_xticklabels(), family = prefs['font_family'] ) setp( ax.get_xticklabels(), fontname = prefs['font'] ) setp( ax.get_xticklabels(), size = tick_text_size_point ) else: setp( ax.get_xticklabels(), size = 0 ) if yticks_flag: setp( ax.get_yticklabels(), family = prefs['font_family'] ) setp( ax.get_yticklabels(), fontname = prefs['font'] ) setp( ax.get_yticklabels(), size = tick_text_size_point ) else: setp( ax.get_yticklabels(), size = 0 ) setp( ax.get_xticklines(), markeredgewidth = pixelToPoint( 0.5, dpi ) ) setp( ax.get_xticklines(), markersize = pixelToPoint( text_size / 2., dpi ) ) setp( ax.get_yticklines(), markeredgewidth = pixelToPoint( 0.5, dpi ) ) setp( ax.get_yticklines(), markersize = pixelToPoint( text_size / 2., dpi ) ) setp( ax.get_xticklines(), zorder = 4.0 ) line_width = prefs.get( 'line_width', 1.0 ) frame_line_width = prefs.get( 'frame_line_width', line_width ) grid_line_width = prefs.get( 'grid_line_width', 0.1 ) plot_line_width = prefs.get( 'plot_line_width', 0.1 ) setp( ax.patch, linewidth = pixelToPoint( plot_line_width, dpi ) ) #setp( ax.spines, linewidth=pixelToPoint(frame_line_width,dpi) ) #setp( ax.axvline(), linewidth=pixelToPoint(1.0,dpi) ) axis_grid_flag = prefs.get( 'plot_axis_grid', True ) if axis_grid_flag: ax.grid( True, color = '#555555', linewidth = pixelToPoint( grid_line_width, dpi ) ) plot_axis_flag = prefs.get( 'plot_axis', True ) if plot_axis_flag: # Set labels if xlabel: t = ax.set_xlabel( xlabel ) t.set_family( prefs['font_family'] ) t.set_fontname( prefs['font'] ) t.set_size( label_text_size ) if ylabel: t = ax.set_ylabel( ylabel ) t.set_family( prefs['font_family'] ) t.set_fontname( prefs['font'] ) t.set_size( label_text_size ) else: self.ax.set_axis_off() # Create a plot title, if necessary if plot_title: self.ax.title = self.ax.text( 0.5, 1. + float( plot_title_padding ) / height, plot_title, verticalalignment = 'bottom', horizontalalignment = 'center', size = pixelToPoint( plot_title_size, dpi ), family = prefs['font_family'], fontname = prefs['font'] ) self.ax.title.set_transform( self.ax.transAxes ) self.ax.title.set_family( prefs['font_family'] ) self.ax.title.set_fontname( prefs['font'] ) if stats_line: self.ax.stats = self.ax.text( 0.5, ( -stats_line_space ) / height, stats_line, verticalalignment = 'top', horizontalalignment = 'center', size = pixelToPoint( stats_line_size, dpi ) ) self.ax.stats.set_transform( self.ax.transAxes )
gpl-3.0
jarrison/trEFM-learn
trEFMlearn/process_image.py
1
2175
import numpy as np import util from sklearn import preprocessing from pandas import read_csv def analyze_image(path, reg_object): """ This function analyzes data from a trEFM image that has been pre-processed and placed in a folder. The path must be given, as well as a previously fit SVR model to be used as the predictor of time constant. The function outputs a series of images calculated from the data. -Input- path: the file location of the preprocessed data. reg_object: An SVR class from scikit-learn that has already been fit. -Output- tau_image: Tau learned from the input image data. int_image: Sum of the total signal feature. fft_image: Sum of the power spectrum feature. amp_image: Difference in post trigger amplitude feature. """ nrows, ncols = 16, 64 tau_img = np.zeros((nrows, ncols)) int_image = np.zeros((nrows, ncols)) fft_image = np.zeros((nrows, ncols)) amp_image = np.zeros((nrows, ncols)) for i in range(nrows): print 'Line: '+str(i)+' of 16' for j in range(ncols): # The pixels have been pre-averaged, saving a significant amount of time and space pixel_signal = read_csv(path+'signalavg_y'+str(i)+ \ '_x'+str(j)+'.txt') # Calculate the features. fft_int = util.fft_integral(pixel_signal) real_int = util.find_integral(pixel_signal) amp_diff = util.amplitude_diff(pixel_signal, 4096) # Make a single sample and scale it. x = preprocessing.scale([fft_int, real_int, amp_diff]).reshape(1, -1) # Predict our tau at this pixel. tau = reg_object.predict(x) # Update the images. tau_img[i, ncols-j-1] = tau int_image[i, ncols-j-1] = real_int fft_image[i, ncols-j-1] = fft_int amp_image[i, ncols-j-1] = amp_diff return tau_img, int_image, fft_image, amp_image
mit
kashif/scikit-learn
examples/exercises/plot_iris_exercise.py
323
1602
""" ================================ SVM Exercise ================================ A tutorial exercise for using different SVM kernels. This exercise is used in the :ref:`using_kernels_tut` part of the :ref:`supervised_learning_tut` section of the :ref:`stat_learn_tut_index`. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, svm iris = datasets.load_iris() X = iris.data y = iris.target X = X[y != 0, :2] y = y[y != 0] n_sample = len(X) np.random.seed(0) order = np.random.permutation(n_sample) X = X[order] y = y[order].astype(np.float) X_train = X[:.9 * n_sample] y_train = y[:.9 * n_sample] X_test = X[.9 * n_sample:] y_test = y[.9 * n_sample:] # fit the model for fig_num, kernel in enumerate(('linear', 'rbf', 'poly')): clf = svm.SVC(kernel=kernel, gamma=10) clf.fit(X_train, y_train) plt.figure(fig_num) plt.clf() plt.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap=plt.cm.Paired) # Circle out the test data plt.scatter(X_test[:, 0], X_test[:, 1], s=80, facecolors='none', zorder=10) plt.axis('tight') x_min = X[:, 0].min() x_max = X[:, 0].max() y_min = X[:, 1].min() y_max = X[:, 1].max() XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j] Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()]) # Put the result into a color plot Z = Z.reshape(XX.shape) plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired) plt.contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'], levels=[-.5, 0, .5]) plt.title(kernel) plt.show()
bsd-3-clause
dsavoiu/kafe2
examples/007_cost_functions/01_poisson_cost_function.py
1
5063
#!/usr/bin/env python """ kafe2 example: Poisson cost function ==================================== In data analysis the uncertainty on measurement data is most often assumed to resemble a normal distribution. For many use cases this assumption works reasonably well but there is a problem: to get meaningful fit results you need to know about the uncertainties of your measurements. Now imagine for a moment that the quantity you're measuring is the number of radioactive decays coming from some substance in a given time period. What is your data error in this case? The precision with that you can correctly count the decays? The answer is that due to the inherently random nature of radioactive decay the variance, and therefore the uncertainty on your measurement data directly follows from the mean number of decays in a given time period - the number of decays are following a poisson distribution. In kafe2 this distribution can be modeled by initializing a fit object with a special cost function. In previous examples when no cost function was provided a normal distribution has been assumed by default. It is important to know that for large numbers of events a poisson distribution can be approximated by a normal distribution (y_error = sqrt(y_data)). Consult the other examples in this folder for more details. For our example on cost functions we imagine the following, admittedly a little contrived scenario: In some remote location on earth archeologists have found the ruins of an ancient civilization. They estimate the ruins to be about 7000 years old. The civilization in question seems to have known about mathematics and they even had their own calendar. Unfortunately we do not know the exact offset of this ancient calendar relative to our modern calendar. Luckily the ancient civilization seems to have mummified their rulers and written down their years of death though. Using a method called radiocarbon dating we can now try to estimate the offset between the ancient and the modern calendar by analyzing the relative amounts of carbon isotopes in the mummified remains of the ancient kings. More specifically, we take small samples from the mummies, extract the carbon from those samples and then measure the number of decaying carbon-14 atoms in our samples. Carbon-14 is a trace radioisotope with a half life of only 5730 years that is continuously being produced in earth's upper atmosphere. In a living organism there is a continuous exchange of carbon atoms with its environment which results in a stable concentration of carbon-14. Once an organism dies, however, the carbon atoms in its body are fixed and the concentration of carbon-14 starts to exponentially decrease over time. If we then measure the concentration of carbon-14 in our samples we can then calculate at which point in time they must have contained atmospheric amounts of carbon-14, i.e. the times of death of the ancient kings. """ import numpy as np import matplotlib.pyplot as plt from kafe2 import XYFit, Plot # Years of death are our x-data, measured c14 activity is our y-data. # Note that our data does NOT include any x or y errors. years_of_death, measured_c14_activity = np.loadtxt('measured_c14_activity.txt') days_per_year = 365.25 # assumed number of days per year current_year = 2019 # current year according to the modern calendar sample_mass = 1.0 # Mass of the carbon samples in g initial_c14_concentration = 1e-12 # Assumed initial concentration N_A = 6.02214076e23 # Avogadro constant in 1/mol molar_mass_c14 = 14.003241 # Molar mass of the Carbon-14 isotope in g/mol expected_initial_num_c14_atoms = initial_c14_concentration * N_A * sample_mass / molar_mass_c14 # x = years of death in the ancient calendar # Delta_t = difference between the ancient and the modern calendar in years # T_12_C14 = half life of carbon-14 in years, read as T 1/2 carbon-14 def expected_activity_per_day(x, Delta_t=5000, T_12_C14=5730): # activity = number of radioactive decays expected_initial_activity_per_day = expected_initial_num_c14_atoms * np.log(2) / (T_12_C14 * days_per_year) total_years_since_death = Delta_t + current_year - x return expected_initial_activity_per_day * np.exp(-np.log(2) * total_years_since_death / T_12_C14) # This is where we tell the fit to assume a poisson distribution for our data. xy_fit = XYFit( xy_data=[years_of_death, measured_c14_activity], model_function=expected_activity_per_day, cost_function="nll-poisson" ) # The half life of carbon-14 is only known with a precision of +-40 years xy_fit.add_parameter_constraint(name='T_12_C14', value=5730, uncertainty=40) # Perform the fit # Note that since for a Poisson distribution the data error is directly linked to the mean. # Because of this fits can be performed without explicitly adding data errors. xy_fit.do_fit() # Optional: print out a report on the fit results on the console xy_fit.report() # Optional: create a plot of the fit results using Plot xy_plot = Plot(xy_fit) xy_plot.plot(fit_info=True) plt.show()
gpl-3.0
ua-snap/downscale
snap_scripts/baseline_climatologies/calc_ra_monthly_L48.py
1
4827
# # # # # # # # # # # # # # # # # # # # # # # # # PORT S.McAffee's Ra SCRIPT TO Python # # # # # # # # # # # # # # # # # # # # # # # # def coordinates( fn=None, meta=None, numpy_array=None, input_crs=None, to_latlong=False ): ''' take a raster file as input and return the centroid coords for each of the grid cells as a pair of numpy 2d arrays (longitude, latitude) ''' import rasterio import numpy as np from affine import Affine from pyproj import Proj, transform if fn: # Read raster with rasterio.open( fn ) as r: T0 = r.transform # upper-left pixel corner affine transform p1 = Proj( r.crs ) A = r.read( 1 ) # pixel values elif (meta is not None) & (numpy_array is not None): A = numpy_array if input_crs != None: p1 = Proj( input_crs ) T0 = meta[ 'transform' ] else: p1 = None T0 = meta[ 'transform' ] else: BaseException( 'check inputs' ) # All rows and columns cols, rows = np.meshgrid(np.arange(A.shape[1]), np.arange(A.shape[0])) # Get affine transform for pixel centres T1 = T0 * Affine.translation( 0.5, 0.5 ) # Function to convert pixel row/column index (from 0) to easting/northing at centre rc2en = lambda r, c: ( c, r ) * T1 # All eastings and northings (there is probably a faster way to do this) eastings, northings = np.vectorize(rc2en, otypes=[np.float, np.float])(rows, cols) if to_latlong == False: return eastings, northings elif (to_latlong == True) & (input_crs != None): # Project all longitudes, latitudes longs, lats = transform(p1, p1.to_latlong(), eastings, northings) return longs, lats else: BaseException( 'cant reproject to latlong without an input_crs' ) def calc_ra( day, lat ): ''' calculate Ra (a direct port to Python from S.McAfee R script) based on Allen et.al 1998 ARGUMENTS: ---------- day = [int] Ordinal (1-365*) Day of the year to compute Ra lat = [np.ndarray] 2-D Numpy array with Latitude values converted to radians RETURNS: -------- numpy.ndarray containing Ra values over the AOI of `lat` ''' import numpy as np #Calculate the earth-sun distance, which is a function solely of Julian day. It is a single value for each day d = 1+(0.033*np.cos( (2*np.pi*day/365) ) ) #Calculate declination, a function of Julian day. It is a single value for each day. dc = 0.409*np.sin(((2*np.pi/365)*day)-1.39) w = np.nan_to_num(np.real( np.arccos( ( -1*np.tan( dc )*np.tan( lat ) ) ).astype(np.complex_))) return (24*60/np.pi) * d * 0.082 * (w*np.sin(lat)*np.sin(dc)+np.cos(lat)*np.cos(dc)*np.sin(w)) if __name__ == '__main__': import rasterio, datetime, os import numpy as np import pandas as pd import geopandas as gpd from functools import partial from pathos.mp_map import mp_map from shapely.geometry import Point from pyproj import Proj, transform fn = '/workspace/Shared/Tech_Projects/DeltaDownscaling/project_data/insolation_L48/prism_raw_template/PRISM_tmean_30yr_normal_800mM2_01_bil.tif' output_path = '/workspace/Shared/Tech_Projects/DeltaDownscaling/project_data/insolation_L48/climatologies' lons, lats = coordinates( fn, input_crs={'init':'epsg:4269'} ) if not os.path.exists( output_path ): os.makedirs( output_path ) rst = rasterio.open( fn ) # [ NOT IMPLEMENTED YET ] # mask those lats so we dont compute where we dont need to: data_ind = np.where( rst.read_masks( 1 ) != 0 ) # pts = zip( lons[ data_ind ].ravel().tolist(), lats[ data_ind ].ravel().tolist() ) lats_masked = lats[ data_ind ].ravel().tolist() lat_rad = (np.array(lats_masked)*np.pi)/180.0 # # radians from pts # p1 = Proj( init='epsg:4269' ) # p2 = Proj( init='epsg:4326' ) # transform_p = partial( transform, p1=p1, p2=p2 ) # pts_radians = [ transform_p( x=lon, y=lat, radians=True ) for lon,lat in pts ] # lat_rad = pd.DataFrame( pts_radians, columns=['lon','lat']).lat # calc ordinal days to compute ordinal_days = range( 1, 365+1, 1 ) # make a monthly grouper of ordinal days ordinal_to_months = [ str(datetime.date.fromordinal( i ).month) for i in ordinal_days ] # convert those months to strings ordinal_to_months = [ ('0'+month if len( month ) < 2 else month) for month in ordinal_to_months ] # calc girr f = partial( calc_ra, lat=lat_rad ) Ra = mp_map( f, ordinal_days, nproc=32 ) Ra_monthlies = pd.Series( Ra ).groupby( ordinal_to_months ).apply( lambda x: np.array(x.tolist()).mean( axis=0 ) ) # iteratively put them back in the indexed locations we took them from meta = rst.meta meta.update( compress='lzw', count=1, dtype='float32' ) for month in Ra_monthlies.index: arr = rst.read( 1 ) arr[ data_ind ] = Ra_monthlies.loc[ month ].tolist() output_filename = os.path.join( output_path, 'girr_w-m2_{}.tif'.format(str( month ) ) ) with rasterio.open( output_filename, 'w', **meta ) as out: out.write( arr.astype( np.float32 ), 1 )
mit
lgbouma/astrobase
astrobase/checkplot/pkl_utils.py
1
76493
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pkl_utils.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - Feb 2019 # License: MIT. ''' This contains utility functions that support checkplot.pkl public functions. ''' ############# ## LOGGING ## ############# import logging from astrobase import log_sub, log_fmt, log_date_fmt DEBUG = False if DEBUG: level = logging.DEBUG else: level = logging.INFO LOGGER = logging.getLogger(__name__) logging.basicConfig( level=level, style=log_sub, format=log_fmt, datefmt=log_date_fmt, ) LOGDEBUG = LOGGER.debug LOGINFO = LOGGER.info LOGWARNING = LOGGER.warning LOGERROR = LOGGER.error LOGEXCEPTION = LOGGER.exception ############# ## IMPORTS ## ############# import os import os.path import gzip import base64 import json import re import pickle from io import BytesIO as StrIO import numpy as np from numpy import min as npmin, max as npmax, abs as npabs # we're going to plot using Agg only import matplotlib mpl_regex = re.findall('rc[0-9]', matplotlib.__version__) if len(mpl_regex) == 1: # some matplotlib versions are e.g., "3.1.0rc1", which we resolve to # "(3,1,0)". MPLVERSION = tuple( int(x) for x in matplotlib.__version__.replace(mpl_regex[0],'').split('.') if x.isdigit() ) else: MPLVERSION = tuple(int(x) for x in matplotlib.__version__.split('.') if x.isdigit()) matplotlib.use('Agg') import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes # import this to get neighbors and their x,y coords from the Skyview FITS from astropy.wcs import WCS ################### ## LOCAL IMPORTS ## ################### from ..lcmath import phase_magseries, phase_bin_magseries from ..lcfit.nonphysical import spline_fit_magseries, savgol_fit_magseries from ..varclass.starfeatures import ( coord_features, color_features, color_classification, neighbor_gaia_features ) from ..plotbase import ( skyview_stamp, PLOTYLABELS, METHODLABELS, METHODSHORTLABELS ) from ..services.mast import tic_conesearch from .. import magnitudes ######################################## ## PICKLE CHECKPLOT UTILITY FUNCTIONS ## ######################################## def _xyzdist_to_distarcsec(xyzdist): '''This inverts the xyz unit vector distance -> angular distance relation. Parameters ---------- xyzdist : float or array-like This is the distance in xyz vector space generated from a transform of (RA,Dec) - > (x,y,z) Returns ------- dist_arcseconds : float or array-like The distance in arcseconds. ''' return np.degrees(2.0*np.arcsin(xyzdist/2.0))*3600.0 def _pkl_finder_objectinfo( objectinfo, varinfo, findercmap, finderconvolve, sigclip, normto, normmingap, deredden_object=True, custom_bandpasses=None, lclistpkl=None, nbrradiusarcsec=30.0, maxnumneighbors=5, plotdpi=100, findercachedir='~/.astrobase/stamp-cache', verbose=True, gaia_submit_timeout=10.0, gaia_submit_tries=3, gaia_max_timeout=180.0, gaia_mirror=None, fast_mode=False, complete_query_later=True ): '''This returns the finder chart and object information as a dict. Parameters ---------- objectinfo : dict or None If provided, this is a dict containing information on the object whose light curve is being processed. This function will then be able to look up and download a finder chart for this object and write that to the output checkplotdict. External services such as GAIA, SIMBAD, TIC@MAST, etc. will also be used to look up this object by its coordinates, and will add in information available from those services. The `objectinfo` dict must be of the form and contain at least the keys described below:: {'objectid': the name of the object, 'ra': the right ascension of the object in decimal degrees, 'decl': the declination of the object in decimal degrees, 'ndet': the number of observations of this object} You can also provide magnitudes and proper motions of the object using the following keys and the appropriate values in the `objectinfo` dict. These will be used to calculate colors, total and reduced proper motion, etc. and display these in the output checkplot PNG:: 'pmra' -> the proper motion in mas/yr in right ascension, 'pmdecl' -> the proper motion in mas/yr in declination, 'umag' -> U mag -> colors: U-B, U-V, U-g 'bmag' -> B mag -> colors: U-B, B-V 'vmag' -> V mag -> colors: U-V, B-V, V-R, V-I, V-K 'rmag' -> R mag -> colors: V-R, R-I 'imag' -> I mag -> colors: g-I, V-I, R-I, B-I 'jmag' -> 2MASS J mag -> colors: J-H, J-K, g-J, i-J 'hmag' -> 2MASS H mag -> colors: J-H, H-K 'kmag' -> 2MASS Ks mag -> colors: g-Ks, H-Ks, J-Ks, V-Ks 'sdssu' -> SDSS u mag -> colors: u-g, u-V 'sdssg' -> SDSS g mag -> colors: g-r, g-i, g-K, u-g, U-g, g-J 'sdssr' -> SDSS r mag -> colors: r-i, g-r 'sdssi' -> SDSS i mag -> colors: r-i, i-z, g-i, i-J, i-W1 'sdssz' -> SDSS z mag -> colors: i-z, z-W2, g-z 'ujmag' -> UKIRT J mag -> colors: J-H, H-K, J-K, g-J, i-J 'uhmag' -> UKIRT H mag -> colors: J-H, H-K 'ukmag' -> UKIRT K mag -> colors: g-K, H-K, J-K, V-K 'irac1' -> Spitzer IRAC1 mag -> colors: i-I1, I1-I2 'irac2' -> Spitzer IRAC2 mag -> colors: I1-I2, I2-I3 'irac3' -> Spitzer IRAC3 mag -> colors: I2-I3 'irac4' -> Spitzer IRAC4 mag -> colors: I3-I4 'wise1' -> WISE W1 mag -> colors: i-W1, W1-W2 'wise2' -> WISE W2 mag -> colors: W1-W2, W2-W3 'wise3' -> WISE W3 mag -> colors: W2-W3 'wise4' -> WISE W4 mag -> colors: W3-W4 If you have magnitude measurements in other bands, use the `custom_bandpasses` kwarg to pass these in. If this is None, no object information will be incorporated into the checkplot (kind of making it effectively useless for anything other than glancing at the phased light curves at various 'best' periods from the period-finder results). varinfo : dict or None If this is None, a blank dict of the form below will be added to the checkplotdict:: {'objectisvar': None -> variability flag (None indicates unset), 'vartags': CSV str containing variability type tags from review, 'varisperiodic': None -> periodic variability flag (None -> unset), 'varperiod': the period associated with the periodic variability, 'varepoch': the epoch associated with the periodic variability} If you provide a dict matching this format in this kwarg, this will be passed unchanged to the output checkplotdict produced. findercmap : str or matplotlib.cm.ColorMap object The Colormap object to use for the finder chart image. finderconvolve : astropy.convolution.Kernel object or None If not None, the Kernel object to use for convolving the finder image. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. normto : {'globalmedian', 'zero'} or a float This is specified as below:: 'globalmedian' -> norms each mag to global median of the LC column 'zero' -> norms each mag to zero a float -> norms each mag to this specified float value. normmingap : float This defines how much the difference between consecutive measurements is allowed to be to consider them as parts of different timegroups. By default it is set to 4.0 days. deredden_object : bool If this is True, will use the 2MASS DUST service to get extinction coefficients in various bands, and then try to deredden the magnitudes and colors of the object already present in the checkplot's objectinfo dict. custom_bandpasses : dict This is a dict used to provide custom bandpass definitions for any magnitude measurements in the objectinfo dict that are not automatically recognized by :py:func:`astrobase.varclass.starfeatures.color_features`. lclistpkl : dict or str If this is provided, must be a dict resulting from reading a catalog produced by the `lcproc.catalogs.make_lclist` function or a str path pointing to the pickle file produced by that function. This catalog is used to find neighbors of the current object in the current light curve collection. Looking at neighbors of the object within the radius specified by `nbrradiusarcsec` is useful for light curves produced by instruments that have a large pixel scale, so are susceptible to blending of variability and potential confusion of neighbor variability with that of the actual object being looked at. If this is None, no neighbor lookups will be performed. nbrradiusarcsec : float The radius in arcseconds to use for a search conducted around the coordinates of this object to look for any potential confusion and blending of variability amplitude caused by their proximity. maxnumneighbors : int The maximum number of neighbors that will have their light curves and magnitudes noted in this checkplot as potential blends with the target object. plotdpi : int The resolution in DPI of the plots to generate in this function (e.g. the finder chart, etc.) findercachedir : str The path to the astrobase cache directory for finder chart downloads from the NASA SkyView service. verbose : bool If True, will indicate progress and warn about potential problems. gaia_submit_timeout : float Sets the timeout in seconds to use when submitting a request to look up the object's information to the GAIA service. Note that if `fast_mode` is set, this is ignored. gaia_submit_tries : int Sets the maximum number of times the GAIA services will be contacted to obtain this object's information. If `fast_mode` is set, this is ignored, and the services will be contacted only once (meaning that a failure to respond will be silently ignored and no GAIA data will be added to the checkplot's objectinfo dict). gaia_max_timeout : float Sets the timeout in seconds to use when waiting for the GAIA service to respond to our request for the object's information. Note that if `fast_mode` is set, this is ignored. gaia_mirror : str This sets the GAIA mirror to use. This is a key in the `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each mirror. fast_mode : bool or float This runs the external catalog operations in a "fast" mode, with short timeouts and not trying to hit external catalogs that take a long time to respond. If this is set to True, the default settings for the external requests will then become:: skyview_lookup = False skyview_timeout = 10.0 skyview_retry_failed = False dust_timeout = 10.0 gaia_submit_timeout = 7.0 gaia_max_timeout = 10.0 gaia_submit_tries = 2 complete_query_later = False search_simbad = False If this is a float, will run in "fast" mode with the provided timeout value in seconds and the following settings:: skyview_lookup = True skyview_timeout = fast_mode skyview_retry_failed = False dust_timeout = fast_mode gaia_submit_timeout = 0.66*fast_mode gaia_max_timeout = fast_mode gaia_submit_tries = 2 complete_query_later = False search_simbad = False complete_query_later : bool If this is True, saves the state of GAIA queries that are not yet complete when `gaia_max_timeout` is reached while waiting for the GAIA service to respond to our request. A later call for GAIA info on the same object will attempt to pick up the results from the existing query if it's completed. If `fast_mode` is True, this is ignored. Returns ------- dict A checkplotdict is returned containing the objectinfo and varinfo dicts, ready to use with the functions below to add in light curve plots, phased LC plots, xmatch info, etc. ''' # optional mode to hit external services and fail fast if they timeout if fast_mode is True: skyview_lookup = False skyview_timeout = 10.0 skyview_retry_failed = False dust_timeout = 10.0 gaia_submit_timeout = 7.0 gaia_max_timeout = 10.0 gaia_submit_tries = 2 complete_query_later = False search_simbad = False elif isinstance(fast_mode, (int, float)) and fast_mode > 0.0: skyview_lookup = True skyview_timeout = fast_mode skyview_retry_failed = False dust_timeout = fast_mode gaia_submit_timeout = 0.66*fast_mode gaia_max_timeout = fast_mode gaia_submit_tries = 2 complete_query_later = False search_simbad = False else: skyview_lookup = True skyview_timeout = 10.0 skyview_retry_failed = True dust_timeout = 10.0 search_simbad = True if (isinstance(objectinfo, dict) and ('objectid' in objectinfo or 'hatid' in objectinfo) and 'ra' in objectinfo and 'decl' in objectinfo and objectinfo['ra'] and objectinfo['decl']): if 'objectid' not in objectinfo: objectid = objectinfo['hatid'] else: objectid = objectinfo['objectid'] if verbose and skyview_lookup: LOGINFO('adding in object information and ' 'finder chart for %s at RA: %.3f, DEC: %.3f' % (objectid, objectinfo['ra'], objectinfo['decl'])) elif verbose and not skyview_lookup: LOGINFO('adding in object information ' 'for %s at RA: %.3f, DEC: %.3f. ' 'skipping finder chart because skyview_lookup = False' % (objectid, objectinfo['ra'], objectinfo['decl'])) # get the finder chart try: if skyview_lookup: try: # generate the finder chart finder, finderheader = skyview_stamp( objectinfo['ra'], objectinfo['decl'], convolvewith=finderconvolve, verbose=verbose, flip=False, cachedir=findercachedir, timeout=skyview_timeout, retry_failed=skyview_retry_failed, ) except OSError: if not fast_mode: LOGERROR( 'finder image appears to be corrupt, retrying...' ) # generate the finder chart finder, finderheader = skyview_stamp( objectinfo['ra'], objectinfo['decl'], convolvewith=finderconvolve, verbose=verbose, flip=False, cachedir=findercachedir, forcefetch=True, timeout=skyview_timeout, retry_failed=False # do not start an infinite loop ) finderfig = plt.figure(figsize=(3,3),dpi=plotdpi) # initialize the finder WCS finderwcs = WCS(finderheader) # use the WCS transform for the plot ax = finderfig.add_subplot(111, frameon=False) ax.imshow(finder, cmap=findercmap, origin='lower') else: finder, finderheader, finderfig, finderwcs = ( None, None, None, None ) # skip down to after nbr stuff for the rest of the finderchart... # search around the target's location and get its neighbors if # lclistpkl is provided and it exists if (lclistpkl is not None and nbrradiusarcsec is not None and nbrradiusarcsec > 0.0): # if lclistpkl is a string, open it as a pickle if isinstance(lclistpkl, str) and os.path.exists(lclistpkl): if lclistpkl.endswith('.gz'): infd = gzip.open(lclistpkl,'rb') else: infd = open(lclistpkl,'rb') lclist = pickle.load(infd) infd.close() # otherwise, if it's a dict, we get it directly elif isinstance(lclistpkl, dict): lclist = lclistpkl # finally, if it's nothing we recognize, ignore it else: LOGERROR('could not understand lclistpkl kwarg, ' 'not getting neighbor info') lclist = dict() # check if we have a KDTree to use # if we don't, skip neighbor stuff if 'kdtree' not in lclist: LOGERROR('neighbors within %.1f arcsec for %s could ' 'not be found, no kdtree in lclistpkl: %s' % (objectid, lclistpkl)) neighbors = None kdt = None # otherwise, do neighbor processing else: kdt = lclist['kdtree'] obj_cosdecl = np.cos(np.radians(objectinfo['decl'])) obj_sindecl = np.sin(np.radians(objectinfo['decl'])) obj_cosra = np.cos(np.radians(objectinfo['ra'])) obj_sinra = np.sin(np.radians(objectinfo['ra'])) obj_xyz = np.column_stack((obj_cosra*obj_cosdecl, obj_sinra*obj_cosdecl, obj_sindecl)) match_xyzdist = ( 2.0 * np.sin(np.radians(nbrradiusarcsec/3600.0)/2.0) ) matchdists, matchinds = kdt.query( obj_xyz, k=maxnumneighbors+1, # get maxnumneighbors + tgt distance_upper_bound=match_xyzdist ) # sort by matchdist mdsorted = np.argsort(matchdists[0]) matchdists = matchdists[0][mdsorted] matchinds = matchinds[0][mdsorted] # luckily, the indices to the kdtree are the same as that # for the objects (I think) neighbors = [] nbrind = 0 for md, mi in zip(matchdists, matchinds): if np.isfinite(md) and md > 0.0: if skyview_lookup: # generate the xy for the finder we'll use a # HTML5 canvas and these pixcoords to highlight # each neighbor when we mouse over its row in # the neighbors tab # we use coord origin = 0 here and not the usual # 1 because we're annotating a numpy array pixcoords = finderwcs.all_world2pix( np.array([[lclist['objects']['ra'][mi], lclist['objects']['decl'][mi]]]), 0 ) # each elem is {'objectid', # 'ra','decl', # 'xpix','ypix', # 'dist','lcfpath'} thisnbr = { 'objectid':( lclist['objects']['objectid'][mi] ), 'ra':lclist['objects']['ra'][mi], 'decl':lclist['objects']['decl'][mi], 'xpix':pixcoords[0,0], 'ypix':300.0 - pixcoords[0,1], 'dist':_xyzdist_to_distarcsec(md), 'lcfpath': lclist['objects']['lcfname'][mi] } neighbors.append(thisnbr) nbrind = nbrind+1 # put in a nice marker for this neighbor into # the overall finder chart annotatex = pixcoords[0,0] annotatey = pixcoords[0,1] if ((300.0 - annotatex) > 50.0): offx = annotatex + 30.0 xha = 'center' else: offx = annotatex - 30.0 xha = 'center' if ((300.0 - annotatey) > 50.0): offy = annotatey - 30.0 yha = 'center' else: offy = annotatey + 30.0 yha = 'center' ax.annotate('N%s' % nbrind, (annotatex, annotatey), xytext=(offx, offy), arrowprops={'facecolor':'blue', 'edgecolor':'blue', 'width':1.0, 'headwidth':1.0, 'headlength':0.1, 'shrink':0.0}, color='blue', horizontalalignment=xha, verticalalignment=yha) else: thisnbr = { 'objectid':( lclist['objects']['objectid'][mi] ), 'ra':lclist['objects']['ra'][mi], 'decl':lclist['objects']['decl'][mi], 'xpix':0.0, 'ypix':0.0, 'dist':_xyzdist_to_distarcsec(md), 'lcfpath': lclist['objects']['lcfname'][mi] } neighbors.append(thisnbr) nbrind = nbrind+1 # if there are no neighbors, set the 'neighbors' key to None else: neighbors = None kdt = None if skyview_lookup: # # finish up the finder chart after neighbors are processed # ax.set_xticks([]) ax.set_yticks([]) # add a reticle pointing to the object's coordinates # we use coord origin = 0 here and not the usual # 1 because we're annotating a numpy array object_pixcoords = finderwcs.all_world2pix( [[objectinfo['ra'], objectinfo['decl']]], 0 ) ax.axvline( # x=150.0, x=object_pixcoords[0,0], ymin=0.375, ymax=0.45, linewidth=1, color='b' ) ax.axhline( # y=150.0, y=object_pixcoords[0,1], xmin=0.375, xmax=0.45, linewidth=1, color='b' ) ax.set_frame_on(False) # this is the output instance finderpng = StrIO() finderfig.savefig(finderpng, bbox_inches='tight', pad_inches=0.0, format='png') plt.close() # encode the finderpng instance to base64 finderpng.seek(0) finderb64 = base64.b64encode(finderpng.read()) # close the stringio buffer finderpng.close() else: finderb64 = None except Exception: LOGEXCEPTION('could not fetch a DSS stamp for this ' 'object %s using coords (%.3f,%.3f)' % (objectid, objectinfo['ra'], objectinfo['decl'])) finderb64 = None neighbors = None kdt = None # if we don't have ra, dec info, then everything is none up to this point else: finderb64 = None neighbors = None kdt = None # # end of finder chart operations # # now that we have the finder chart, get the rest of the object # information # get the rest of the features, these don't necessarily rely on ra, dec and # should degrade gracefully if these aren't provided if isinstance(objectinfo, dict): if 'objectid' not in objectinfo and 'hatid' in objectinfo: objectid = objectinfo['hatid'] objectinfo['objectid'] = objectid elif 'objectid' in objectinfo: objectid = objectinfo['objectid'] else: objectid = os.urandom(12).hex()[:7] objectinfo['objectid'] = objectid LOGWARNING('no objectid found in objectinfo dict, ' 'making up a random one: %s') # get the neighbor features and GAIA info nbrfeat = neighbor_gaia_features( objectinfo, kdt, nbrradiusarcsec, verbose=False, gaia_submit_timeout=gaia_submit_timeout, gaia_submit_tries=gaia_submit_tries, gaia_max_timeout=gaia_max_timeout, gaia_mirror=gaia_mirror, complete_query_later=complete_query_later, search_simbad=search_simbad ) objectinfo.update(nbrfeat) # see if the objectinfo dict has pmra/pmdecl entries. if it doesn't, # then we'll see if the nbrfeat dict has pmra/pmdecl from GAIA. we'll # set the appropriate provenance keys as well so we know where the PM # came from if ( ('pmra' not in objectinfo) or ( ('pmra' in objectinfo) and ( (objectinfo['pmra'] is None) or (not np.isfinite(objectinfo['pmra'])) ) ) ): if 'ok' in nbrfeat['gaia_status']: objectinfo['pmra'] = nbrfeat['gaia_pmras'][0] objectinfo['pmra_err'] = nbrfeat['gaia_pmra_errs'][0] objectinfo['pmra_source'] = 'gaia' if verbose: LOGWARNING('pmRA not found in provided objectinfo dict, ' 'using value from GAIA') else: objectinfo['pmra_source'] = 'light curve' if ( ('pmdecl' not in objectinfo) or ( ('pmdecl' in objectinfo) and ( (objectinfo['pmdecl'] is None) or (not np.isfinite(objectinfo['pmdecl'])) ) ) ): if 'ok' in nbrfeat['gaia_status']: objectinfo['pmdecl'] = nbrfeat['gaia_pmdecls'][0] objectinfo['pmdecl_err'] = nbrfeat['gaia_pmdecl_errs'][0] objectinfo['pmdecl_source'] = 'gaia' if verbose: LOGWARNING('pmDEC not found in provided objectinfo dict, ' 'using value from GAIA') else: objectinfo['pmdecl_source'] = 'light curve' # # update GAIA info so it's available at the first level # if 'ok' in objectinfo['gaia_status']: objectinfo['gaiaid'] = objectinfo['gaia_ids'][0] objectinfo['gaiamag'] = objectinfo['gaia_mags'][0] objectinfo['gaia_absmag'] = objectinfo['gaia_absolute_mags'][0] objectinfo['gaia_parallax'] = objectinfo['gaia_parallaxes'][0] objectinfo['gaia_parallax_err'] = ( objectinfo['gaia_parallax_errs'][0] ) objectinfo['gaia_pmra'] = objectinfo['gaia_pmras'][0] objectinfo['gaia_pmra_err'] = objectinfo['gaia_pmra_errs'][0] objectinfo['gaia_pmdecl'] = objectinfo['gaia_pmdecls'][0] objectinfo['gaia_pmdecl_err'] = objectinfo['gaia_pmdecl_errs'][0] else: objectinfo['gaiaid'] = None objectinfo['gaiamag'] = np.nan objectinfo['gaia_absmag'] = np.nan objectinfo['gaia_parallax'] = np.nan objectinfo['gaia_parallax_err'] = np.nan objectinfo['gaia_pmra'] = np.nan objectinfo['gaia_pmra_err'] = np.nan objectinfo['gaia_pmdecl'] = np.nan objectinfo['gaia_pmdecl_err'] = np.nan # # get the object's TIC information # if ('ra' in objectinfo and objectinfo['ra'] is not None and np.isfinite(objectinfo['ra']) and 'decl' in objectinfo and objectinfo['decl'] is not None and np.isfinite(objectinfo['decl'])): try: ticres = tic_conesearch(objectinfo['ra'], objectinfo['decl'], radius_arcmin=5.0/60.0, verbose=verbose, timeout=gaia_max_timeout, maxtries=gaia_submit_tries) if ticres is not None: with open(ticres['cachefname'],'r') as infd: ticinfo = json.load(infd) if ('data' in ticinfo and len(ticinfo['data']) > 0 and isinstance(ticinfo['data'][0], dict)): objectinfo['ticid'] = str(ticinfo['data'][0]['ID']) objectinfo['tessmag'] = ticinfo['data'][0]['Tmag'] objectinfo['tic_version'] = ( ticinfo['data'][0]['version'] ) objectinfo['tic_distarcsec'] = ( ticinfo['data'][0]['dstArcSec'] ) objectinfo['tessmag_origin'] = ( ticinfo['data'][0]['TESSflag'] ) objectinfo['tic_starprop_origin'] = ( ticinfo['data'][0]['SPFlag'] ) objectinfo['tic_lumclass'] = ( ticinfo['data'][0]['lumclass'] ) objectinfo['tic_teff'] = ( ticinfo['data'][0]['Teff'] ) objectinfo['tic_teff_err'] = ( ticinfo['data'][0]['e_Teff'] ) objectinfo['tic_logg'] = ( ticinfo['data'][0]['logg'] ) objectinfo['tic_logg_err'] = ( ticinfo['data'][0]['e_logg'] ) objectinfo['tic_mh'] = ( ticinfo['data'][0]['MH'] ) objectinfo['tic_mh_err'] = ( ticinfo['data'][0]['e_MH'] ) objectinfo['tic_radius'] = ( ticinfo['data'][0]['rad'] ) objectinfo['tic_radius_err'] = ( ticinfo['data'][0]['e_rad'] ) objectinfo['tic_mass'] = ( ticinfo['data'][0]['mass'] ) objectinfo['tic_mass_err'] = ( ticinfo['data'][0]['e_mass'] ) objectinfo['tic_density'] = ( ticinfo['data'][0]['rho'] ) objectinfo['tic_density_err'] = ( ticinfo['data'][0]['e_rho'] ) objectinfo['tic_luminosity'] = ( ticinfo['data'][0]['lum'] ) objectinfo['tic_luminosity_err'] = ( ticinfo['data'][0]['e_lum'] ) objectinfo['tic_distancepc'] = ( ticinfo['data'][0]['d'] ) objectinfo['tic_distancepc_err'] = ( ticinfo['data'][0]['e_d'] ) # # fill in any missing info using the TIC entry # if ('gaiaid' not in objectinfo or ('gaiaid' in objectinfo and (objectinfo['gaiaid'] is None))): objectinfo['gaiaid'] = ticinfo['data'][0]['GAIA'] if ('gaiamag' not in objectinfo or ('gaiamag' in objectinfo and (objectinfo['gaiamag'] is None or not np.isfinite(objectinfo['gaiamag'])))): objectinfo['gaiamag'] = ( ticinfo['data'][0]['GAIAmag'] ) objectinfo['gaiamag_err'] = ( ticinfo['data'][0]['e_GAIAmag'] ) if ('gaia_parallax' not in objectinfo or ('gaia_parallax' in objectinfo and (objectinfo['gaia_parallax'] is None or not np.isfinite(objectinfo['gaia_parallax'])))): objectinfo['gaia_parallax'] = ( ticinfo['data'][0]['plx'] ) objectinfo['gaia_parallax_err'] = ( ticinfo['data'][0]['e_plx'] ) if (objectinfo['gaiamag'] is not None and np.isfinite(objectinfo['gaiamag']) and objectinfo['gaia_parallax'] is not None and np.isfinite(objectinfo['gaia_parallax'])): objectinfo['gaia_absmag'] = ( magnitudes.absolute_gaia_magnitude( objectinfo['gaiamag'], objectinfo['gaia_parallax'] ) ) if ('pmra' not in objectinfo or ('pmra' in objectinfo and (objectinfo['pmra'] is None or not np.isfinite(objectinfo['pmra'])))): objectinfo['pmra'] = ticinfo['data'][0]['pmRA'] objectinfo['pmra_err'] = ( ticinfo['data'][0]['e_pmRA'] ) objectinfo['pmra_source'] = 'TIC' if ('pmdecl' not in objectinfo or ('pmdecl' in objectinfo and (objectinfo['pmdecl'] is None or not np.isfinite(objectinfo['pmdecl'])))): objectinfo['pmdecl'] = ticinfo['data'][0]['pmDEC'] objectinfo['pmdecl_err'] = ( ticinfo['data'][0]['e_pmDEC'] ) objectinfo['pmdecl_source'] = 'TIC' if ('bmag' not in objectinfo or ('bmag' in objectinfo and (objectinfo['bmag'] is None or not np.isfinite(objectinfo['bmag'])))): objectinfo['bmag'] = ticinfo['data'][0]['Bmag'] objectinfo['bmag_err'] = ( ticinfo['data'][0]['e_Bmag'] ) if ('vmag' not in objectinfo or ('vmag' in objectinfo and (objectinfo['vmag'] is None or not np.isfinite(objectinfo['vmag'])))): objectinfo['vmag'] = ticinfo['data'][0]['Vmag'] objectinfo['vmag_err'] = ( ticinfo['data'][0]['e_Vmag'] ) if ('sdssu' not in objectinfo or ('sdssu' in objectinfo and (objectinfo['sdssu'] is None or not np.isfinite(objectinfo['sdssu'])))): objectinfo['sdssu'] = ticinfo['data'][0]['umag'] objectinfo['sdssu_err'] = ( ticinfo['data'][0]['e_umag'] ) if ('sdssg' not in objectinfo or ('sdssg' in objectinfo and (objectinfo['sdssg'] is None or not np.isfinite(objectinfo['sdssg'])))): objectinfo['sdssg'] = ticinfo['data'][0]['gmag'] objectinfo['sdssg_err'] = ( ticinfo['data'][0]['e_gmag'] ) if ('sdssr' not in objectinfo or ('sdssr' in objectinfo and (objectinfo['sdssr'] is None or not np.isfinite(objectinfo['sdssr'])))): objectinfo['sdssr'] = ticinfo['data'][0]['rmag'] objectinfo['sdssr_err'] = ( ticinfo['data'][0]['e_rmag'] ) if ('sdssi' not in objectinfo or ('sdssi' in objectinfo and (objectinfo['sdssi'] is None or not np.isfinite(objectinfo['sdssi'])))): objectinfo['sdssi'] = ticinfo['data'][0]['imag'] objectinfo['sdssi_err'] = ( ticinfo['data'][0]['e_imag'] ) if ('sdssz' not in objectinfo or ('sdssz' in objectinfo and (objectinfo['sdssz'] is None or not np.isfinite(objectinfo['sdssz'])))): objectinfo['sdssz'] = ticinfo['data'][0]['zmag'] objectinfo['sdssz_err'] = ( ticinfo['data'][0]['e_zmag'] ) if ('jmag' not in objectinfo or ('jmag' in objectinfo and (objectinfo['jmag'] is None or not np.isfinite(objectinfo['jmag'])))): objectinfo['jmag'] = ticinfo['data'][0]['Jmag'] objectinfo['jmag_err'] = ( ticinfo['data'][0]['e_Jmag'] ) if ('hmag' not in objectinfo or ('hmag' in objectinfo and (objectinfo['hmag'] is None or not np.isfinite(objectinfo['hmag'])))): objectinfo['hmag'] = ticinfo['data'][0]['Hmag'] objectinfo['hmag_err'] = ( ticinfo['data'][0]['e_Hmag'] ) if ('kmag' not in objectinfo or ('kmag' in objectinfo and (objectinfo['kmag'] is None or not np.isfinite(objectinfo['kmag'])))): objectinfo['kmag'] = ticinfo['data'][0]['Kmag'] objectinfo['kmag_err'] = ( ticinfo['data'][0]['e_Kmag'] ) if ('wise1' not in objectinfo or ('wise1' in objectinfo and (objectinfo['wise1'] is None or not np.isfinite(objectinfo['wise1'])))): objectinfo['wise1'] = ticinfo['data'][0]['w1mag'] objectinfo['wise1_err'] = ( ticinfo['data'][0]['e_w1mag'] ) if ('wise2' not in objectinfo or ('wise2' in objectinfo and (objectinfo['wise2'] is None or not np.isfinite(objectinfo['wise2'])))): objectinfo['wise2'] = ticinfo['data'][0]['w2mag'] objectinfo['wise2_err'] = ( ticinfo['data'][0]['e_w2mag'] ) if ('wise3' not in objectinfo or ('wise3' in objectinfo and (objectinfo['wise3'] is None or not np.isfinite(objectinfo['wise3'])))): objectinfo['wise3'] = ticinfo['data'][0]['w3mag'] objectinfo['wise3_err'] = ( ticinfo['data'][0]['e_w3mag'] ) if ('wise4' not in objectinfo or ('wise4' in objectinfo and (objectinfo['wise4'] is None or not np.isfinite(objectinfo['wise4'])))): objectinfo['wise4'] = ticinfo['data'][0]['w4mag'] objectinfo['wise4_err'] = ( ticinfo['data'][0]['e_w4mag'] ) else: LOGERROR('could not look up TIC ' 'information for object: %s ' 'at (%.3f, %.3f)' % (objectinfo['objectid'], objectinfo['ra'], objectinfo['decl'])) except Exception: LOGEXCEPTION('could not look up TIC ' 'information for object: %s ' 'at (%.3f, %.3f)' % (objectinfo['objectid'], objectinfo['ra'], objectinfo['decl'])) # try to get the object's coord features coordfeat = coord_features(objectinfo) # get the color features colorfeat = color_features(objectinfo, deredden=deredden_object, custom_bandpasses=custom_bandpasses, dust_timeout=dust_timeout) # get the object's color classification colorclass = color_classification(colorfeat, coordfeat) # update the objectinfo dict with everything objectinfo.update(colorfeat) objectinfo.update(coordfeat) objectinfo.update(colorclass) # put together the initial checkplot pickle dictionary # this will be updated by the functions below as appropriate # and will written out as a gzipped pickle at the end of processing checkplotdict = {'objectid':objectid, 'neighbors':neighbors, 'objectinfo':objectinfo, 'finderchart':finderb64, 'sigclip':sigclip, 'normto':normto, 'normmingap':normmingap} # add the objecttags key to objectinfo checkplotdict['objectinfo']['objecttags'] = None # if there's no objectinfo, we can't do anything. else: # empty objectinfo dict checkplotdict = {'objectid':None, 'neighbors':None, 'objectinfo':{ 'available_bands':[], 'available_band_labels':[], 'available_dereddened_bands':[], 'available_dereddened_band_labels':[], 'available_colors':[], 'available_color_labels':[], 'bmag':None, 'bmag-vmag':None, 'decl':None, 'hatid':None, 'hmag':None, 'imag-jmag':None, 'jmag-kmag':None, 'jmag':None, 'kmag':None, 'ndet':None, 'network':None, 'objecttags':None, 'pmdecl':None, 'pmdecl_err':None, 'pmra':None, 'pmra_err':None, 'propermotion':None, 'ra':None, 'rpmj':None, 'sdssg':None, 'sdssi':None, 'sdssr':None, 'stations':None, 'twomassid':None, 'ucac4id':None, 'vmag':None }, 'finderchart':None, 'sigclip':sigclip, 'normto':normto, 'normmingap':normmingap} # end of objectinfo processing # add the varinfo dict if isinstance(varinfo, dict): checkplotdict['varinfo'] = varinfo else: checkplotdict['varinfo'] = { 'objectisvar':None, 'vartags':None, 'varisperiodic':None, 'varperiod':None, 'varepoch':None, } return checkplotdict def _pkl_periodogram(lspinfo, plotdpi=100, override_pfmethod=None): '''This returns the periodogram plot PNG as base64, plus info as a dict. Parameters ---------- lspinfo : dict This is an lspinfo dict containing results from a period-finding function. If it's from an astrobase period-finding function in periodbase, this will already be in the correct format. To use external period-finder results with this function, the `lspinfo` dict must be of the following form, with at least the keys listed below:: {'periods': np.array of all periods searched by the period-finder, 'lspvals': np.array of periodogram power value for each period, 'bestperiod': a float value that is the period with the highest peak in the periodogram, i.e. the most-likely actual period, 'method': a three-letter code naming the period-finder used; must be one of the keys in the `astrobase.periodbase.METHODLABELS` dict, 'nbestperiods': a list of the periods corresponding to periodogram peaks (`nbestlspvals` below) to annotate on the periodogram plot so they can be called out visually, 'nbestlspvals': a list of the power values associated with periodogram peaks to annotate on the periodogram plot so they can be called out visually; should be the same length as `nbestperiods` above} `nbestperiods` and `nbestlspvals` must have at least 5 elements each, e.g. describing the five 'best' (highest power) peaks in the periodogram. plotdpi : int The resolution in DPI of the output periodogram plot to make. override_pfmethod : str or None This is used to set a custom label for this periodogram method. Normally, this is taken from the 'method' key in the input `lspinfo` dict, but if you want to override the output method name, provide this as a string here. This can be useful if you have multiple results you want to incorporate into a checkplotdict from a single period-finder (e.g. if you ran BLS over several period ranges separately). Returns ------- dict Returns a dict that contains the following items:: {methodname: {'periods':the period array from lspinfo, 'lspval': the periodogram power array from lspinfo, 'bestperiod': the best period from lspinfo, 'nbestperiods': the 'nbestperiods' list from lspinfo, 'nbestlspvals': the 'nbestlspvals' list from lspinfo, 'periodogram': base64 encoded string representation of the periodogram plot}} The dict is returned in this format so it can be directly incorporated under the period-finder's label `methodname` in a checkplotdict, using Python's dict `update()` method. ''' # get the appropriate plot ylabel pgramylabel = PLOTYLABELS[lspinfo['method']] # get the periods and lspvals from lspinfo periods = lspinfo['periods'] lspvals = lspinfo['lspvals'] bestperiod = lspinfo['bestperiod'] nbestperiods = lspinfo['nbestperiods'] nbestlspvals = lspinfo['nbestlspvals'] # open the figure instance pgramfig = plt.figure(figsize=(7.5,4.8),dpi=plotdpi) # make the plot plt.plot(periods,lspvals) plt.xscale('log',basex=10) plt.xlabel('Period [days]') plt.ylabel(pgramylabel) plottitle = '%s - %.6f d' % (METHODLABELS[lspinfo['method']], bestperiod) plt.title(plottitle) # show the best five peaks on the plot for xbestperiod, xbestpeak in zip(nbestperiods, nbestlspvals): plt.annotate('%.6f' % xbestperiod, xy=(xbestperiod, xbestpeak), xycoords='data', xytext=(0.0,25.0), textcoords='offset points', arrowprops=dict(arrowstyle="->"),fontsize='14.0') # make a grid plt.grid(color='#a9a9a9', alpha=0.9, zorder=0, linewidth=1.0, linestyle=':') # this is the output instance pgrampng = StrIO() pgramfig.savefig(pgrampng, # bbox_inches='tight', pad_inches=0.0, format='png') plt.close() # encode the finderpng instance to base64 pgrampng.seek(0) pgramb64 = base64.b64encode(pgrampng.read()) # close the stringio buffer pgrampng.close() if not override_pfmethod: # this is the dict to return checkplotdict = { lspinfo['method']:{ 'periods':periods, 'lspvals':lspvals, 'bestperiod':bestperiod, 'nbestperiods':nbestperiods, 'nbestlspvals':nbestlspvals, 'periodogram':pgramb64, } } else: # this is the dict to return checkplotdict = { override_pfmethod:{ 'periods':periods, 'lspvals':lspvals, 'bestperiod':bestperiod, 'nbestperiods':nbestperiods, 'nbestlspvals':nbestlspvals, 'periodogram':pgramb64, } } return checkplotdict def _pkl_magseries_plot(stimes, smags, serrs, plotdpi=100, magsarefluxes=False): '''This returns the magseries plot PNG as base64, plus arrays as dict. Parameters ---------- stimes,smags,serrs : np.array The mag/flux time-series arrays along with associated errors. These should all have been run through nan-stripping and sigma-clipping beforehand. plotdpi : int The resolution of the plot to make in DPI. magsarefluxes : bool If True, indicates the input time-series is fluxes and not mags so the plot y-axis direction and range can be set appropriately. Returns ------- dict A dict of the following form is returned:: {'magseries': {'plot': base64 encoded str representation of the magnitude/flux time-series plot, 'times': the `stimes` array, 'mags': the `smags` array, 'errs': the 'serrs' array}} The dict is returned in this format so it can be directly incorporated in a checkplotdict, using Python's dict `update()` method. ''' scaledplottime = stimes - npmin(stimes) # open the figure instance magseriesfig = plt.figure(figsize=(7.5,4.8),dpi=plotdpi) plt.plot(scaledplottime, smags, marker='o', ms=2.0, ls='None',mew=0, color='green', rasterized=True) # flip y axis for mags if not magsarefluxes: plot_ylim = plt.ylim() plt.ylim((plot_ylim[1], plot_ylim[0])) # set the x axis limit plt.xlim((npmin(scaledplottime)-2.0, npmax(scaledplottime)+2.0)) # make a grid plt.grid(color='#a9a9a9', alpha=0.9, zorder=0, linewidth=1.0, linestyle=':') # make the x and y axis labels plot_xlabel = 'JD - %.3f' % npmin(stimes) if magsarefluxes: plot_ylabel = 'flux' else: plot_ylabel = 'magnitude' plt.xlabel(plot_xlabel) plt.ylabel(plot_ylabel) # fix the yaxis ticks (turns off offset and uses the full # value of the yaxis tick) plt.gca().get_yaxis().get_major_formatter().set_useOffset(False) plt.gca().get_xaxis().get_major_formatter().set_useOffset(False) # this is the output instance magseriespng = StrIO() magseriesfig.savefig(magseriespng, # bbox_inches='tight', pad_inches=0.05, format='png') plt.close() # encode the finderpng instance to base64 magseriespng.seek(0) magseriesb64 = base64.b64encode(magseriespng.read()) # close the stringio buffer magseriespng.close() checkplotdict = { 'magseries':{ 'plot':magseriesb64, 'times':stimes, 'mags':smags, 'errs':serrs } } return checkplotdict def _pkl_phased_magseries_plot( checkplotdict, lspmethod, periodind, stimes, smags, serrs, varperiod, varepoch, lspmethodind=0, phasewrap=True, phasesort=True, phasebin=0.002, minbinelems=7, plotxlim=(-0.8,0.8), plotdpi=100, bestperiodhighlight=None, xgridlines=None, xliminsetmode=False, magsarefluxes=False, directreturn=False, overplotfit=None, verbose=True, override_pfmethod=None ): '''This returns the phased magseries plot PNG as base64 plus info as a dict. Parameters ---------- checkplotdict : dict This is an existing checkplotdict to update. If it's None or `directreturn` = True, then the generated dict result for this magseries plot will be returned directly. lspmethod : str lspmethod is a string indicating the type of period-finding algorithm that produced the period. If this is not in `astrobase.plotbase.METHODSHORTLABELS`, it will be used verbatim. In most cases, this will come directly from the lspinfo dict produced by a period-finder function. periodind : int This is the index of the current periodogram period being operated on:: If == 0 -> best period and `bestperiodhighlight` is applied if not None If > 0 -> some other peak of the periodogram If == -1 -> special mode w/ no periodogram labels and enabled highlight stimes,smags,serrs : np.array The mag/flux time-series arrays along with associated errors. These should all have been run through nan-stripping and sigma-clipping beforehand. varperiod : float or None The period to use for this phased light curve plot tile. varepoch : 'min' or float or list of lists or None The epoch to use for this phased light curve plot tile. If this is a float, will use the provided value directly. If this is 'min', will automatically figure out the time-of-minimum of the phased light curve. If this is None, will use the mimimum value of `stimes` as the epoch of the phased light curve plot. If this is a list of lists, will use the provided value of `lspmethodind` to look up the current period-finder method and the provided value of `periodind` to look up the epoch associated with that method and the current period. This is mostly only useful when `twolspmode` is True. phasewrap : bool If this is True, the phased time-series will be wrapped around phase 0.0. phasesort : bool If True, will sort the phased light curve in order of increasing phase. phasebin: float The bin size to use to group together measurements closer than this amount in phase. This is in units of phase. If this is a float, a phase-binned version of the phased light curve will be overplotted on top of the regular phased light curve. minbinelems : int The minimum number of elements required per phase bin to include it in the phased LC plot. plotxlim : sequence of two floats or None The x-range (min, max) of the phased light curve plot. If None, will be determined automatically. plotdpi : int The resolution of the output plot PNGs in dots per inch. bestperiodhighlight : str or None If not None, this is a str with a matplotlib color specification to use as the background color to highlight the phased light curve plot of the 'best' period and epoch combination. If None, no highlight will be applied. xgridlines : list of floats or None If this is provided, must be a list of floats corresponding to the phase values where to draw vertical dashed lines as a means of highlighting these. xliminsetmode : bool If this is True, the generated phased light curve plot will use the values of `plotxlim` as the main plot x-axis limits (i.e. zoomed-in if `plotxlim` is a range smaller than the full phase range), and will show the full phased light curve plot as an smaller inset. Useful for planetary transit light curves. magsarefluxes : bool If True, indicates the input time-series is fluxes and not mags so the plot y-axis direction and range can be set appropriately. directreturn : bool If this set to True, will return only the dict corresponding to the phased LC plot for the input `periodind` and `lspmethod` and not return this result embedded in a checkplotdict. overplotfit : dict If this is provided, it must be a dict of the form returned by one of the astrobase.lcfit.fit_XXXXX_magseries functions. This can be used to overplot a light curve model fit on top of the phased light curve plot returned by this function. The `overplotfit` dict has the following form, including at least the keys listed here:: {'fittype':str: name of fit method, 'fitchisq':float: the chi-squared value of the fit, 'fitredchisq':float: the reduced chi-squared value of the fit, 'fitinfo':{'fitmags':array: model mags or fluxes from fit function}, 'magseries':{'times':array: times where the fitmags are evaluated}} `fitmags` and `times` should all be of the same size. The input `overplotfit` dict is copied over to the checkplotdict for each specific phased LC plot to save all of this information for use later. verbose : bool If True, will indicate progress and warn about problems. override_pfmethod : str or None This is used to set a custom label for the periodogram method. Normally, this is taken from the 'method' key in the input `lspinfo` dict, but if you want to override the output method name, provide this as a string here. This can be useful if you have multiple results you want to incorporate into a checkplotdict from a single period-finder (e.g. if you ran BLS over several period ranges separately). Returns ------- dict Returns a dict of the following form:: {lspmethod: {'plot': the phased LC plot as base64 str, 'period': the period used for this phased LC, 'epoch': the epoch used for this phased LC, 'phase': phase value array, 'phasedmags': mags/fluxes sorted in phase order, 'binphase': array of binned phase values, 'binphasedmags': mags/fluxes sorted in binphase order, 'phasewrap': value of the input `phasewrap` kwarg, 'phasesort': value of the input `phasesort` kwarg, 'phasebin': value of the input `phasebin` kwarg, 'minbinelems': value of the input `minbinelems` kwarg, 'plotxlim': value of the input `plotxlim` kwarg, 'lcfit': the provided `overplotfit` dict}} The dict is in this form because we can use Python dicts' `update()` method to update an existing checkplotdict. If `returndirect` is True, only the inner dict is returned. ''' # open the figure instance phasedseriesfig = plt.figure(figsize=(7.5,4.8),dpi=plotdpi) plotvarepoch = None # figure out the epoch, if it's None, use the min of the time if varepoch is None: plotvarepoch = npmin(stimes) # if the varepoch is 'min', then fit a spline to the light curve # phased using the min of the time, find the fit mag minimum and use # the time for that as the varepoch elif isinstance(varepoch,str) and varepoch == 'min': try: spfit = spline_fit_magseries(stimes, smags, serrs, varperiod, magsarefluxes=magsarefluxes, sigclip=None, verbose=verbose) plotvarepoch = spfit['fitinfo']['fitepoch'] if len(plotvarepoch) != 1: plotvarepoch = plotvarepoch[0] except Exception: LOGERROR('spline fit failed, trying SavGol fit') sgfit = savgol_fit_magseries(stimes, smags, serrs, varperiod, sigclip=None, magsarefluxes=magsarefluxes, verbose=verbose) plotvarepoch = sgfit['fitinfo']['fitepoch'] if len(plotvarepoch) != 1: plotvarepoch = plotvarepoch[0] finally: if plotvarepoch is None: LOGERROR('could not find a min epoch time, ' 'using min(times) as the epoch for ' 'the phase-folded LC') plotvarepoch = npmin(stimes) # special case with varepoch lists per each period-finder method elif isinstance(varepoch, list): try: thisvarepochlist = varepoch[lspmethodind] plotvarepoch = thisvarepochlist[periodind] except Exception: LOGEXCEPTION( "varepoch provided in list form either doesn't match " "the length of nbestperiods from the period-finder " "result, or something else went wrong. using min(times) " "as the epoch instead" ) plotvarepoch = npmin(stimes) # the final case is to use the provided varepoch directly else: plotvarepoch = varepoch if verbose: LOGINFO('plotting %s phased LC with period %s: %.6f, epoch: %.5f' % (lspmethod, periodind, varperiod, plotvarepoch)) # make the plot title based on the lspmethod if periodind == 0: plottitle = '%s best period: %.6f d - epoch: %.5f' % ( (METHODSHORTLABELS[lspmethod] if lspmethod in METHODSHORTLABELS else lspmethod), varperiod, plotvarepoch ) elif periodind > 0: plottitle = '%s peak %s: %.6f d - epoch: %.5f' % ( (METHODSHORTLABELS[lspmethod] if lspmethod in METHODSHORTLABELS else lspmethod), periodind+1, varperiod, plotvarepoch ) elif periodind == -1: plottitle = '%s period: %.6f d - epoch: %.5f' % ( lspmethod, varperiod, plotvarepoch ) # phase the magseries phasedlc = phase_magseries(stimes, smags, varperiod, plotvarepoch, wrap=phasewrap, sort=phasesort) plotphase = phasedlc['phase'] plotmags = phasedlc['mags'] # if we're supposed to bin the phases, do so if phasebin: binphasedlc = phase_bin_magseries(plotphase, plotmags, binsize=phasebin, minbinelems=minbinelems) binplotphase = binphasedlc['binnedphases'] binplotmags = binphasedlc['binnedmags'] else: binplotphase = None binplotmags = None # finally, make the phased LC plot plt.plot(plotphase, plotmags, marker='o', ms=2.0, ls='None',mew=0, color='gray', rasterized=True) # overlay the binned phased LC plot if we're making one if phasebin: plt.plot(binplotphase, binplotmags, marker='o', ms=4.0, ls='None',mew=0, color='#1c1e57', rasterized=True) # if we're making a overplotfit, then plot the fit over the other stuff if overplotfit and isinstance(overplotfit, dict): fitmethod = overplotfit['fittype'] fitredchisq = overplotfit['fitredchisq'] plotfitmags = overplotfit['fitinfo']['fitmags'] plotfittimes = overplotfit['magseries']['times'] # phase the fit magseries fitphasedlc = phase_magseries(plotfittimes, plotfitmags, varperiod, plotvarepoch, wrap=phasewrap, sort=phasesort) plotfitphase = fitphasedlc['phase'] plotfitmags = fitphasedlc['mags'] plotfitlabel = (r'%s fit ${\chi}^2/{\mathrm{dof}} = %.3f$' % (fitmethod, fitredchisq)) # plot the fit phase and mags plt.plot(plotfitphase, plotfitmags,'k-', linewidth=3, rasterized=True,label=plotfitlabel) plt.legend(loc='upper left', frameon=False) # flip y axis for mags if not magsarefluxes: plot_ylim = plt.ylim() plt.ylim((plot_ylim[1], plot_ylim[0])) # set the x axis limit if not plotxlim: plt.xlim((npmin(plotphase)-0.1, npmax(plotphase)+0.1)) else: plt.xlim((plotxlim[0],plotxlim[1])) # make a grid ax = plt.gca() if isinstance(xgridlines, (list, tuple)): ax.set_xticks(xgridlines, minor=False) plt.grid(color='#a9a9a9', alpha=0.9, zorder=0, linewidth=1.0, linestyle=':') # make the x and y axis labels plot_xlabel = 'phase' if magsarefluxes: plot_ylabel = 'flux' else: plot_ylabel = 'magnitude' plt.xlabel(plot_xlabel) plt.ylabel(plot_ylabel) # fix the yaxis ticks (turns off offset and uses the full # value of the yaxis tick) plt.gca().get_yaxis().get_major_formatter().set_useOffset(False) plt.gca().get_xaxis().get_major_formatter().set_useOffset(False) # set the plot title plt.title(plottitle) # make sure the best period phased LC plot stands out if (periodind == 0 or periodind == -1) and bestperiodhighlight: if MPLVERSION >= (2,0,0): plt.gca().set_facecolor(bestperiodhighlight) else: plt.gca().set_axis_bgcolor(bestperiodhighlight) # if we're making an inset plot showing the full range if (plotxlim and isinstance(plotxlim, (list, tuple)) and len(plotxlim) == 2 and xliminsetmode is True): # bump the ylim of the plot so that the inset can fit in this axes plot axesylim = plt.gca().get_ylim() if magsarefluxes: plt.gca().set_ylim( axesylim[0], axesylim[1] + 0.5*npabs(axesylim[1]-axesylim[0]) ) else: plt.gca().set_ylim( axesylim[0], axesylim[1] - 0.5*npabs(axesylim[1]-axesylim[0]) ) # put the inset axes in inset = inset_axes(plt.gca(), width="40%", height="40%", loc=1) # make the scatter plot for the phased LC plot inset.plot(plotphase, plotmags, marker='o', ms=2.0, ls='None',mew=0, color='gray', rasterized=True) if phasebin: # make the scatter plot for the phased LC plot inset.plot(binplotphase, binplotmags, marker='o', ms=4.0, ls='None',mew=0, color='#1c1e57', rasterized=True) # show the full phase coverage if phasewrap: inset.set_xlim(-0.2,0.8) else: inset.set_xlim(-0.1,1.1) # flip y axis for mags if not magsarefluxes: inset_ylim = inset.get_ylim() inset.set_ylim((inset_ylim[1], inset_ylim[0])) # set the plot title inset.text(0.5,0.9,'full phased light curve', ha='center',va='center',transform=inset.transAxes) # don't show axes labels or ticks inset.set_xticks([]) inset.set_yticks([]) # this is the output instance phasedseriespng = StrIO() phasedseriesfig.savefig(phasedseriespng, # bbox_inches='tight', pad_inches=0.0, format='png') plt.close() # encode the finderpng instance to base64 phasedseriespng.seek(0) phasedseriesb64 = base64.b64encode(phasedseriespng.read()) # close the stringio buffer phasedseriespng.close() # this includes a fitinfo dict if one is provided in overplotfit retdict = { 'plot':phasedseriesb64, 'period':varperiod, 'epoch':plotvarepoch, 'phase':plotphase, 'phasedmags':plotmags, 'binphase':binplotphase, 'binphasedmags':binplotmags, 'phasewrap':phasewrap, 'phasesort':phasesort, 'phasebin':phasebin, 'minbinelems':minbinelems, 'plotxlim':plotxlim, 'lcfit':overplotfit, } # if we're returning stuff directly, i.e. not being used embedded within # the checkplot_dict function if directreturn or checkplotdict is None: return retdict # this requires the checkplotdict to be present already, we'll just update # it at the appropriate lspmethod and periodind else: if override_pfmethod: checkplotdict[override_pfmethod][periodind] = retdict else: checkplotdict[lspmethod][periodind] = retdict return checkplotdict
mit
tomazberisa/custom_db
validate_bootstrap.py
1
3561
#!/usr/bin/env python3 import commanderline.commander_line as cl import pandas as pd import gzip ancestry_translation = { "ARABIAN" : "NEAREAST", "ASHKENAZI" : "ASHKENAZI-EMED", "BALOCHI-MAKRANI-BRAHUI" : "CASIA", "BANTUKENYA" : "EAFRICA", "BANTUNIGERIA" : "WAFRICA", "BIAKA" : "CAFRICA", "CAFRICA" : "CAFRICA", "CAMBODIA-THAI" : "SEASIA", "CSAMERICA" : "AMERICAS", "CYPRUS-MALTA-SICILY" : "ASHKENAZI-EMED", "EAFRICA" : "EAFRICA", "EASIA" : "EASIA", "EASTSIBERIA" : "NEASIA", "FINNISH" : "NEEUROPE", "GAMBIA" : "WAFRICA", "GUJARAT" : "SASIA", "HADZA" : "EAFRICA", "HAZARA-UYGUR-UZBEK" : "CASIA", "ITALY-BALKANS" : "ITALY-BALKANS", "JAPAN-KOREA" : "EASIA", "KALASH" : "CASIA", "MENDE" : "WAFRICA", "NAFRICA" : "NAFRICA", "NCASIA" : "NCASIA", "NEAREAST" : "NEAREAST", "NEASIA" : "NEASIA", "NEEUROPE" : "NEEUROPE", "NEUROPE" : "NEUROPE", "NGANASAN" : "NEASIA", "OCEANIA" : "OCEANIA", "PATHAN-SINDHI-BURUSHO" : "CASIA", "SAFRICA" : "SAFRICA", "SAMERICA" : "AMERICAS", "SARDINIA" : "SWEUROPE", "SEASIA" : "SEASIA", "SSASIA" : "SASIA", "SWEUROPE" : "SWEUROPE", "TAIWAN" : "SEASIA", "TUBALAR" : "NEASIA", "TURK-IRAN-CAUCASUS" : "TURK-IRAN-CAUCASUS" } def validate_bootstrap(file_list, negligible_threshold=0.01, bootstrap_confidence=0.8): ''' +--------------------+ | validate_bootstrap | +--------------------+ Script that takes into account bootstrap replicates and outputs estimated "super-ancestries". Main input is a text file, where the first line is the .Q output filename of a regular Ancestry run and remaining lines are the .Q files of bootstrap replicates. Details about Ancestry: https://bitbucket.org/joepickrell/ancestry Package dependencies: pandas commanderline ''' results=pd.DataFrame() with open(file_list, 'rt') as f_in: for i,f in enumerate(f_in): f=f.strip() d1=pd.read_csv(f, header=None, sep=' ') d1['super']=d1[0].apply(lambda el: ancestry_translation[el]) d2=d1.groupby('super').sum() d2.columns=[i] results=pd.concat([results, d2], axis=1) results=results.dropna(subset=[0]) bootstrap_replicate_count=results.iloc[:,1:].apply(lambda el: el>=negligible_threshold).T.sum()/(len(results.columns)-1) filt=bootstrap_replicate_count.apply(lambda el: el>=bootstrap_confidence) interm_results=results[filt][0] ambig=1-interm_results.sum() final_results=pd.concat([interm_results, pd.Series({'AMBIGUOUS':ambig})]) print(final_results) cl.commander_line(validate_bootstrap) if __name__ == '__main__' else None
mit
daler/Pharmacogenomics_Prediction_Pipeline_P3
tools/pipeline_helpers.py
4
7419
import os import yaml import numpy as np import pandas as pd import string def sanitize(s): """ Replace special characters with underscore """ valid = "-_.()" + string.ascii_letters + string.digits return ''.join(i if i in valid else "_" for i in s) def index_converter(df, label): """ Sanitizes and appends "_" + `label` to each index entry. Returns the dataframe with altered index """ def wrap(i): return sanitize('%s_%s' % (i, label)) df.index = pd.Series(df.index).apply(wrap) return df def pathway_scores_from_variants(variants_df, pathway_df, index_field): """ Similar to `pathway_scores_from_zscores`, but with different subsetting logic that makes sense with integer variants per gene. """ x = variants_df.join(pathway_df) dfs = [] dfs.append(index_converter(pd.pivot_table(x, index=index_field, aggfunc=np.sum), 'sum_var')) dfs.append(index_converter(pd.pivot_table(x, index=index_field, aggfunc=np.mean), 'mean_var')) return pd.concat(dfs) def pathway_scores_from_zscores(zscores_df, pathway_df, index_field): """ Calculates a variety of pathway scores for each cell line, given a gene x cell line dataframe of zscores and a gene x annotation_type data frame of annotation labels. The annotation values will be sanitized to remove any special characters. Parameters ---------- zscores_df : dataframe Index is Ensembl ID; columns are cell lines; values are zscores pathway_df : dataframe Index is Ensembl ID; columns are anything but must at least include `index_field`. index_field : str Column name to aggregate by, e.g., "GO" for gene ontology """ # join dataframes on index x = zscores_df.join(pathway_df) dfs = [] dfs.append(index_converter(pd.pivot_table(x[x>0], index=index_field, aggfunc=np.sum), 'sum_pos')) dfs.append(index_converter(pd.pivot_table(x[x<0], index=index_field, aggfunc=np.sum), 'sum_neg')) dfs.append(index_converter(pd.pivot_table(x, index=index_field, aggfunc=np.sum), 'sum_all')) dfs.append(index_converter(pd.pivot_table(x[x>0], index=index_field, aggfunc=np.mean), 'mean_pos')) dfs.append(index_converter(pd.pivot_table(x[x<0], index=index_field, aggfunc=np.mean), 'mean_neg')) dfs.append(index_converter(pd.pivot_table(x, index=index_field, aggfunc=np.mean), 'mean_all')) dfs.append(index_converter(pd.pivot_table(x[x>0], index=index_field, aggfunc='count') / pd.pivot_table(x[x>0], index=index_field, aggfunc=len), 'frac_pos')) dfs.append(index_converter(pd.pivot_table(x[x<0], index=index_field, aggfunc='count') / pd.pivot_table(x[x<0], index=index_field, aggfunc=len), 'frac_neg')) dfs.append(index_converter(pd.pivot_table(x[x!=0], index=index_field, aggfunc='count') / pd.pivot_table(x[x!=0], index=index_field, aggfunc=len), 'frac_changed')) return pd.concat(dfs) def stitch(filenames, sample_from_filename_func, index_col=0, data_col=0, **kwargs): """ Given a set of filenames each corresponding to one sample and at least one data column, create a matrix containing all samples. For example, given many htseq-count output files containing gene ID and count, create a matrix indexed by gene and with a column for each sample. Parameters ---------- filenames : list List of filenames to stitch together. sample_from_filename_func: Function that, when provided a filename, can figure out what the sample label should be. Easiest cases are those where the sample is contained in the filename, but this function could do things like access a lookup table or read the file itself to figure it out. index_col : int Which column of a single file should be considered the index data_col : int Which column of a single file should be considered the data. Additional keyword arguments are passed to pandas.read_table. """ read_table_kwargs = dict(index_col=index_col) read_table_kwargs.update(**kwargs) dfs = [] names = [] for fn in filenames: dfs.append(pd.read_table(fn, **read_table_kwargs).ix[:, data_col]) names.append(sample_from_filename_func(fn)) df = pd.concat(dfs, axis=1) df.columns = names return df def filtered_targets_from_config(config_file): """ Given a config.yaml file, convert the output from each feature set into an expected run-specific filtered output file. E.g., given the following config snippet:: features: go: snakefile: features/gene_ontology.snakefile output: zscores: "{prefix}/cleaned/go/go_zscores.csv" variants: "{prefix}/cleaned/go/go_variants.csv" run_info: run_1: filter_function: "filterfuncs.run1" This function will return: [ '{prefix}/runs/run_1/filtered/go/zscores_filtered.tab', '{prefix}/runs/run_1/filtered/go/variants_filtered.tab', ] """ config = yaml.load(open(config_file)) targets = [] for run in config['run_info'].keys(): for features_label, block in config['features'].items(): output = block['output'] for label, filename in output.items(): targets.append(os.path.join(config['prefix'], 'runs', run, 'filtered', features_label, label + '_filtered.tab')) return targets def resolve_name(name): """ Imports a specific object from a dotted path. From nose.utils.resolve_name (with the logging parts taken out) which in turn is from unittest.TestLoader.loadTestByName """ parts = name.split('.') parts_copy = parts[:] while parts_copy: try: module = __import__('.'.join(parts_copy)) break except ImportError: del parts_copy[-1] if not parts_copy: raise parts = parts[1:] obj = module for part in parts: obj = getattr(obj, part) return obj def remove_zero_variance(infile): """ Remove rows with zero variance """ d = pd.read_table(infile, index_col=0) return d[d.var(axis=1) > 0] def remove_nfrac_variants(infile, nfrac=0.1): """ Remove rows in which fewer than `nfrac` or greater than `1-nfrac` samples have a variant. """ d = pd.read_table(infile, index_col=0) n = d.shape[1] n_nonzero = (d == 0).sum(axis=1).astype(float) too_low = (n_nonzero / n) <= nfrac too_high = (n_nonzero / n) >= (1 - nfrac) return d[~(too_low | too_high)] def aggregate_filtered_features(inputs): def labels_from_filename(fn): toks = fn.split('/') feature_label = toks[-2] output_label = toks[-1].replace('_filtered.tab', '') return feature_label, output_label all_features = [] for fn in inputs: fn = str(fn) feature_label, output_label = labels_from_filename(fn) tag = feature_label + '_' + output_label + '_' d = pd.read_table(fn, index_col=0) d.index = tag + d.index all_features.append(d) return pd.concat(all_features)
cc0-1.0
elingg/tensorflow
tensorflow/contrib/factorization/python/ops/gmm.py
11
12252
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of Gaussian mixture model (GMM) clustering. This goes on top of skflow API. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import numpy as np from tensorflow.contrib import framework from tensorflow.contrib.factorization.python.ops import gmm_ops from tensorflow.contrib.framework.python.framework import checkpoint_utils from tensorflow.contrib.framework.python.ops import variables from tensorflow.contrib.learn.python.learn import graph_actions from tensorflow.contrib.learn.python.learn import monitors as monitor_lib from tensorflow.contrib.learn.python.learn.estimators import estimator as estimator_lib from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib from tensorflow.contrib.learn.python.learn.estimators._sklearn import TransformerMixin from tensorflow.contrib.learn.python.learn.learn_io import data_feeder from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed as random_seed_lib from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops.control_flow_ops import with_dependencies from tensorflow.python.platform import tf_logging as logging def _streaming_sum(scalar_tensor): """Create a sum metric and update op.""" sum_metric = framework.local_variable(constant_op.constant(0.0)) sum_update = sum_metric.assign_add(scalar_tensor) return sum_metric, sum_update class GMM(estimator_lib.Estimator, TransformerMixin): """GMM clustering.""" SCORES = 'scores' ASSIGNMENTS = 'assignments' ALL_SCORES = 'all_scores' def __init__(self, num_clusters, model_dir=None, random_seed=0, params='wmc', initial_clusters='random', covariance_type='full', batch_size=128, steps=10, continue_training=False, config=None, verbose=1): """Creates a model for running GMM training and inference. Args: num_clusters: number of clusters to train. model_dir: the directory to save the model results and log files. random_seed: Python integer. Seed for PRNG used to initialize centers. params: Controls which parameters are updated in the training process. Can contain any combination of "w" for weights, "m" for means, and "c" for covars. initial_clusters: specifies how to initialize the clusters for training. See gmm_ops.gmm for the possible values. covariance_type: one of "full", "diag". batch_size: See Estimator steps: See Estimator continue_training: See Estimator config: See Estimator verbose: See Estimator """ super(GMM, self).__init__(model_dir=model_dir, config=config) self.batch_size = batch_size self.steps = steps self.continue_training = continue_training self.verbose = verbose self._num_clusters = num_clusters self._params = params self._training_initial_clusters = initial_clusters self._covariance_type = covariance_type self._training_graph = None self._random_seed = random_seed def fit(self, x, y=None, monitors=None, logdir=None, steps=None): """Trains a GMM clustering on x. Note: See Estimator for logic for continuous training and graph construction across multiple calls to fit. Args: x: training input matrix of shape [n_samples, n_features]. y: labels. Should be None. monitors: List of `Monitor` objects to print training progress and invoke early stopping. logdir: the directory to save the log file that can be used for optional visualization. steps: number of training steps. If not None, overrides the value passed in constructor. Returns: Returns self. """ if logdir is not None: self._model_dir = logdir self._data_feeder = data_feeder.setup_train_data_feeder(x, None, self._num_clusters, self.batch_size) _legacy_train_model( # pylint: disable=protected-access self, input_fn=self._data_feeder.input_builder, feed_fn=self._data_feeder.get_feed_dict_fn(), steps=steps or self.steps, monitors=monitors, init_feed_fn=self._data_feeder.get_feed_dict_fn()) return self def predict(self, x, batch_size=None): """Predict cluster id for each element in x. Args: x: 2-D matrix or iterator. batch_size: size to use for batching up x for querying the model. Returns: Array with same number of rows as x, containing cluster ids. """ return np.array([ prediction[GMM.ASSIGNMENTS] for prediction in super(GMM, self).predict( x=x, batch_size=batch_size, as_iterable=True) ]) def score(self, x, batch_size=None): """Predict total sum of distances to nearest clusters. Args: x: 2-D matrix or iterator. batch_size: size to use for batching up x for querying the model. Returns: Total score. """ return np.sum(self.evaluate(x=x, batch_size=batch_size)[GMM.SCORES]) def transform(self, x, batch_size=None): """Transforms each element in x to distances to cluster centers. Args: x: 2-D matrix or iterator. batch_size: size to use for batching up x for querying the model. Returns: Array with same number of rows as x, and num_clusters columns, containing distances to the cluster centers. """ return np.array([ prediction[GMM.ALL_SCORES] for prediction in super(GMM, self).predict( x=x, batch_size=batch_size, as_iterable=True) ]) def clusters(self): """Returns cluster centers.""" clusters = checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_VARIABLE) return np.squeeze(clusters, 1) def covariances(self): """Returns the covariances.""" return checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_COVS_VARIABLE) def _parse_tensor_or_dict(self, features): if isinstance(features, dict): return array_ops.concat([features[k] for k in sorted(features.keys())], 1) return features def _get_train_ops(self, features, _): (_, _, losses, training_op) = gmm_ops.gmm( self._parse_tensor_or_dict(features), self._training_initial_clusters, self._num_clusters, self._random_seed, self._covariance_type, self._params) incr_step = state_ops.assign_add(variables.get_global_step(), 1) loss = math_ops.reduce_sum(losses) training_op = with_dependencies([training_op, incr_step], loss) return training_op, loss def _get_predict_ops(self, features): (all_scores, model_predictions, _, _) = gmm_ops.gmm( self._parse_tensor_or_dict(features), self._training_initial_clusters, self._num_clusters, self._random_seed, self._covariance_type, self._params) return { GMM.ALL_SCORES: all_scores[0], GMM.ASSIGNMENTS: model_predictions[0][0], } def _get_eval_ops(self, features, _, unused_metrics): (_, _, losses, _) = gmm_ops.gmm( self._parse_tensor_or_dict(features), self._training_initial_clusters, self._num_clusters, self._random_seed, self._covariance_type, self._params) return {GMM.SCORES: _streaming_sum(math_ops.reduce_sum(losses))} # TODO(xavigonzalvo): delete this after implementing model-fn based Estimator. def _legacy_train_model(estimator, input_fn, steps, feed_fn=None, init_op=None, init_feed_fn=None, init_fn=None, device_fn=None, monitors=None, log_every_steps=100, fail_on_nan_loss=True, max_steps=None): """Legacy train function of Estimator.""" if hasattr(estimator.config, 'execution_mode'): if estimator.config.execution_mode not in ('all', 'train'): return # Stagger startup of worker sessions based on task id. sleep_secs = min( estimator.config.training_worker_max_startup_secs, estimator.config.task_id * estimator.config.training_worker_session_startup_stagger_secs) if sleep_secs: logging.info('Waiting %d secs before starting task %d.', sleep_secs, estimator.config.task_id) time.sleep(sleep_secs) # Device allocation device_fn = device_fn or estimator._device_fn # pylint: disable=protected-access with ops.Graph().as_default() as g, g.device(device_fn): random_seed_lib.set_random_seed(estimator.config.tf_random_seed) global_step = framework.create_global_step(g) features, labels = input_fn() estimator._check_inputs(features, labels) # pylint: disable=protected-access # The default return type of _get_train_ops is ModelFnOps. But there are # some subclasses of tf.contrib.learn.Estimator which override this # method and use the legacy signature, namely _get_train_ops returns a # (train_op, loss) tuple. The following else-statement code covers these # cases, but will soon be deleted after the subclasses are updated. # TODO(b/32664904): Update subclasses and delete the else-statement. train_ops = estimator._get_train_ops(features, labels) # pylint: disable=protected-access if isinstance(train_ops, model_fn_lib.ModelFnOps): # Default signature train_op = train_ops.train_op loss_op = train_ops.loss if estimator.config.is_chief: hooks = train_ops.training_chief_hooks + train_ops.training_hooks else: hooks = train_ops.training_hooks else: # Legacy signature if len(train_ops) != 2: raise ValueError('Expected a tuple of train_op and loss, got {}'.format( train_ops)) train_op = train_ops[0] loss_op = train_ops[1] hooks = [] hooks += monitor_lib.replace_monitors_with_hooks(monitors, estimator) ops.add_to_collection(ops.GraphKeys.LOSSES, loss_op) return graph_actions._monitored_train( # pylint: disable=protected-access graph=g, output_dir=estimator.model_dir, train_op=train_op, loss_op=loss_op, global_step_tensor=global_step, init_op=init_op, init_feed_dict=init_feed_fn() if init_feed_fn is not None else None, init_fn=init_fn, log_every_steps=log_every_steps, supervisor_is_chief=estimator.config.is_chief, supervisor_master=estimator.config.master, supervisor_save_model_secs=estimator.config.save_checkpoints_secs, supervisor_save_model_steps=estimator.config.save_checkpoints_steps, supervisor_save_summaries_steps=estimator.config.save_summary_steps, keep_checkpoint_max=estimator.config.keep_checkpoint_max, keep_checkpoint_every_n_hours=( estimator.config.keep_checkpoint_every_n_hours), feed_fn=feed_fn, steps=steps, fail_on_nan_loss=fail_on_nan_loss, hooks=hooks, max_steps=max_steps)
apache-2.0
ningchi/scikit-learn
examples/feature_selection/plot_feature_selection.py
249
2827
""" =============================== Univariate Feature Selection =============================== An example showing univariate feature selection. Noisy (non informative) features are added to the iris data and univariate feature selection is applied. For each feature, we plot the p-values for the univariate feature selection and the corresponding weights of an SVM. We can see that univariate feature selection selects the informative features and that these have larger SVM weights. In the total set of features, only the 4 first ones are significant. We can see that they have the highest score with univariate feature selection. The SVM assigns a large weight to one of these features, but also Selects many of the non-informative features. Applying univariate feature selection before the SVM increases the SVM weight attributed to the significant features, and will thus improve classification. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, svm from sklearn.feature_selection import SelectPercentile, f_classif ############################################################################### # import some data to play with # The iris dataset iris = datasets.load_iris() # Some noisy data not correlated E = np.random.uniform(0, 0.1, size=(len(iris.data), 20)) # Add the noisy data to the informative features X = np.hstack((iris.data, E)) y = iris.target ############################################################################### plt.figure(1) plt.clf() X_indices = np.arange(X.shape[-1]) ############################################################################### # Univariate feature selection with F-test for feature scoring # We use the default selection function: the 10% most significant features selector = SelectPercentile(f_classif, percentile=10) selector.fit(X, y) scores = -np.log10(selector.pvalues_) scores /= scores.max() plt.bar(X_indices - .45, scores, width=.2, label=r'Univariate score ($-Log(p_{value})$)', color='g') ############################################################################### # Compare to the weights of an SVM clf = svm.SVC(kernel='linear') clf.fit(X, y) svm_weights = (clf.coef_ ** 2).sum(axis=0) svm_weights /= svm_weights.max() plt.bar(X_indices - .25, svm_weights, width=.2, label='SVM weight', color='r') clf_selected = svm.SVC(kernel='linear') clf_selected.fit(selector.transform(X), y) svm_weights_selected = (clf_selected.coef_ ** 2).sum(axis=0) svm_weights_selected /= svm_weights_selected.max() plt.bar(X_indices[selector.get_support()] - .05, svm_weights_selected, width=.2, label='SVM weights after selection', color='b') plt.title("Comparing feature selection") plt.xlabel('Feature number') plt.yticks(()) plt.axis('tight') plt.legend(loc='upper right') plt.show()
bsd-3-clause
altaetran/bayesianoracle
tests/quadraticBayesianAveraging/paper_examples/StatisticalQuadraticModels1D.py
1
9162
import numpy as np import bayesianoracle as bo import bayesianoracle.plot as boplotter import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib import colors as cl from matplotlib import gridspec, ticker # Import function information from function_data import * execfile("function_data.py") def plot_prior(bmao, model_ind, precision_alpha, precision_beta, bias_lambda): """ Auxillary plotting function Parameters ---------- bmao : Bayesian model averaging optimization process X : The values that have been previously traversed mode : mode = "predict" if the GaussianProcessEI prediction is disired or mode = "EI" if the expected improvement is desired k_fig : The suffix seed for saving the figure """ import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib import colors as cl from matplotlib import gridspec boplt = boplotter.Plotter1D(x_range=x_range, y_range=y_range, num_points=num_points) boplt.set_bma(bmao.bma) ### Plot the data and the models fig, ax = plt.subplots() # Plot the heatmap of probabilties, THEN the function THEN mean line boplt.plot_model(ax, model_ind=model_ind, bool_dataless=True, color='k', linestyle='-') func_line = boplt.plot_fun(ax, fun) mean_line = boplt.plot_model_mean(ax, model_ind=model_ind, color=boplt.colorcycle[model_ind], linestyle='-') # Create legend legend = plt.legend([mean_line, func_line], ['Quadratic Approximation', 'True Mean Function'], loc='upper center', bbox_to_anchor=(0.5, 1.075), ncol=1, fancybox=True, shadow=False, scatterpoints=1) plt.setp(legend.get_texts(), fontsize=12) plt.savefig("StatisticalQuadraticModels1D_figures/"+str(model_ind)+"_"+str(precision_alpha)+"_"+str(precision_beta)+"_"+str(bias_lambda)+"_prior.png", dpi=dpi) plt.close(fig) def plot_model(bmao, X, y_hist, model_ind, kernel_range, precision_alpha, precision_beta, bias_lambda): """ Auxillary plotting function Parameters ---------- bmao : Bayesian model averaging optimization process X : The values that have been previously traversed mode : mode = "predict" if the GaussianProcessEI prediction is disired or mode = "EI" if the expected improvement is desired k_fig : The suffix seed for saving the figure """ import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib import colors as cl from matplotlib import gridspec boplt = boplotter.Plotter1D(x_range=x_range, y_range=y_range, num_points=num_points) boplt.set_bma(bmao.bma) ### Plot the data and the models fig, ax = plt.subplots() # Plot the heatmap of probabilties, THEN the function THEN mean line THEN data boplt.plot_model(ax, model_ind=model_ind, kernel_range=kernel_range, bool_dataless=False, color='k', linestyle='-') func_line = boplt.plot_fun(ax, fun) mean_line = boplt.plot_biased_model_mean(ax, model_ind=model_ind, kernel_range=kernel_range, color=boplt.colorcycle[model_ind], linestyle='-') scat = boplt.plot_data(ax, X, y_hist, bool_color_cycled=True) # Create legend legend = plt.legend([mean_line, func_line, scat], ['Quadratic Approximation', 'True Mean Function', 'Data'], loc='upper center', bbox_to_anchor=(0.5, 1.075), ncol=2, fancybox=True, shadow=False, scatterpoints=1) legend.legendHandles[2]._sizes = [30] plt.setp(legend.get_texts(), fontsize=12) plt.savefig("StatisticalQuadraticModels1D_figures/"+str(model_ind)+"_predictive_"+str(kernel_range)+"_"+str(precision_alpha)+"_"+str(precision_beta)+"_"+str(bias_lambda)+".png", dpi=dpi) plt.close(fig) def plot_everything(bmao, X, y_hist, model_ind, sets, kernel_range): n_subplot = 10 fig = plt.figure(figsize=(8, 12), dpi=dpi) gs = gridspec.GridSpec(n_subplot/2, 2, height_ratios=[10, 10, 10, 10, 1]) # Make axes for plots ax = [] for i in range(n_subplot-2): ax.append(plt.subplot(gs[i])) # Make axis for colorbar ax_cb = plt.subplot(gs[-1,:]) row_i = 0 for (precision_alpha, precision_beta, bias_lambda) in sets: # Set parameter bmao.set_precision_prior_params(precision_alpha, precision_beta) bmao.set_bias_prior_params(bias_lambda) boplt = boplotter.Plotter1D(x_range=x_range, y_range=y_range, num_points=num_points) boplt.set_bma(bmao.bma) # Plot Prior heatmap = boplt.plot_model(ax[row_i], model_ind=model_ind, bool_dataless=True, color='k', linestyle='-', bool_colorbar=False, xlabel=None, upper=0.4) func_line = boplt.plot_fun(ax[row_i], fun, xlabel=None, color='black') mean_line = boplt.plot_model_mean(ax[row_i], model_ind=model_ind, color=boplt.colorcycle[model_ind], linestyle='-', xlabel=None) # Plot posterior heatmap = boplt.plot_model(ax[row_i+1], model_ind=model_ind, kernel_range=kernel_range, bool_dataless=False, color='k', linestyle='-', bool_colorbar=False, xlabel=None, upper=0.4) func_line = boplt.plot_fun(ax[row_i+1], fun, xlabel=None, color='black') mean_line = boplt.plot_biased_model_mean(ax[row_i+1], model_ind=model_ind, kernel_range=kernel_range, color=boplt.colorcycle[model_ind], linestyle='-', xlabel=None) scat = boplt.plot_data(ax[row_i+1], X, y_hist, bool_color_cycled=False, xlabel=None, edgecolor='white') # Add right legend #h = plt.ylabel(r'$\alpha='+str(precision_alpha)+r'$'+"\n"+ # r'$\beta='+str(precision_beta)+r'$'+"\n"+ # r'$\lambda='+str(bias_lambda)+r'$', # rotation=0, # multialignment='left', # horizontalalignment='left', # verticalalignment='center') #ax[row_i+1].yaxis.set_label_position("right") h = plt.ylabel(r'$\alpha='+str(precision_alpha)+r'$ '+ r'$\beta='+str(precision_beta)+r'$ '+ r'$\lambda='+str(bias_lambda)+r'$', rotation=270, multialignment='center', verticalalignment='center') #ax[row_i+1].yaxis.labelpad = 1.0 ax[row_i+1].yaxis.set_label_coords(1.05, 0.55) # Custom colorbar on axis 2 cbar = fig.colorbar(heatmap, cax=ax_cb, orientation='horizontal') cbar.set_label('probability') #tick_locator = ticker.MaxNLocator(nbins=11) #cbar.locator = tick_locator #cbar.update_ticks() row_i+=2 # Figure legend legend = fig.legend([mean_line, func_line, scat], ['Model Mean', 'True Mean', 'Data'], loc='upper center', bbox_to_anchor=(0.5, 0.97), ncol=2, fancybox=True, shadow=False, scatterpoints=1) legend.legendHandles[2]._sizes = [30] plt.setp(legend.get_texts(), fontsize=12) # Set titles ax[0].set_title(r'prior $y, p_{x}\left(y\mid \mathcal{M}, \gamma\right)$', y=1.09) ax[1].set_title(r'posterior $y, p_{x}\left(y\mid \mathcal{M},\mathcal{D}, \gamma\right)$', y=1.09) # Hide tick labels for k in range(len(ax)): ax[k].xaxis.set_ticklabels([]) if k % 2 == 1: ax[k].yaxis.set_ticklabels([]) # Set last x labels ax[6].set_xlabel(r'$x$') ax[7].set_xlabel(r'$x$') plt.tight_layout() plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05, wspace=0.075, hspace=0.2) plt.savefig("StatisticalQuadraticModels1D_figures/"+str(model_ind)+"_"+str(kernel_range)+"_predictive_all.png", dpi=dpi) bmao = bo.optimizer.QuadraticBMAOptimizer(ndim = 1, init_kernel_range=0.2, n_int=1, precision_beta = 1000.0, bias_lambda = 1.0, constraints = [constr1, constr2], bounding_box = bounding_box, bool_compact = True, kernel_type='Gaussian') # Simulated sampling of the function. X = None y_hist = np.array([]) # Populate bmao for k in xrange(X_complete.shape[1]): # Get next in sequence x_next = X_complete[:,k] x = x_next if k == 0: X = np.array([x_next]) else: X = np.hstack([X, np.array([x_next])]) # Get y, grad, hess from precomputed lists f = f_complete[k] grad = grad_complete[k] Hess = Hess_complete[k] y_hist = np.append(y_hist, f) # Add observations to the bmao bmao.add_observation(x, f, grad, Hess) sets = [(2, 1000, 1), (1.1, 100, 1), (2, 20, 0.01), (51.5, 1000, 0.01)] model_inds = [1] kernel_range = 0.25 # Try different betas for model_ind in model_inds: plot_everything(bmao, X, y_hist, model_ind, sets, kernel_range)
apache-2.0
JosmanPS/scikit-learn
sklearn/datasets/mldata.py
309
7838
"""Automatically download MLdata datasets.""" # Copyright (c) 2011 Pietro Berkes # License: BSD 3 clause import os from os.path import join, exists import re import numbers try: # Python 2 from urllib2 import HTTPError from urllib2 import quote from urllib2 import urlopen except ImportError: # Python 3+ from urllib.error import HTTPError from urllib.parse import quote from urllib.request import urlopen import numpy as np import scipy as sp from scipy import io from shutil import copyfileobj from .base import get_data_home, Bunch MLDATA_BASE_URL = "http://mldata.org/repository/data/download/matlab/%s" def mldata_filename(dataname): """Convert a raw name for a data set in a mldata.org filename.""" dataname = dataname.lower().replace(' ', '-') return re.sub(r'[().]', '', dataname) def fetch_mldata(dataname, target_name='label', data_name='data', transpose_data=True, data_home=None): """Fetch an mldata.org data set If the file does not exist yet, it is downloaded from mldata.org . mldata.org does not have an enforced convention for storing data or naming the columns in a data set. The default behavior of this function works well with the most common cases: 1) data values are stored in the column 'data', and target values in the column 'label' 2) alternatively, the first column stores target values, and the second data values 3) the data array is stored as `n_features x n_samples` , and thus needs to be transposed to match the `sklearn` standard Keyword arguments allow to adapt these defaults to specific data sets (see parameters `target_name`, `data_name`, `transpose_data`, and the examples below). mldata.org data sets may have multiple columns, which are stored in the Bunch object with their original name. Parameters ---------- dataname: Name of the data set on mldata.org, e.g.: "leukemia", "Whistler Daily Snowfall", etc. The raw name is automatically converted to a mldata.org URL . target_name: optional, default: 'label' Name or index of the column containing the target values. data_name: optional, default: 'data' Name or index of the column containing the data. transpose_data: optional, default: True If True, transpose the downloaded data array. data_home: optional, default: None Specify another download and cache folder for the data sets. By default all scikit learn data is stored in '~/scikit_learn_data' subfolders. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to learn, 'target', the classification labels, 'DESCR', the full description of the dataset, and 'COL_NAMES', the original names of the dataset columns. Examples -------- Load the 'iris' dataset from mldata.org: >>> from sklearn.datasets.mldata import fetch_mldata >>> import tempfile >>> test_data_home = tempfile.mkdtemp() >>> iris = fetch_mldata('iris', data_home=test_data_home) >>> iris.target.shape (150,) >>> iris.data.shape (150, 4) Load the 'leukemia' dataset from mldata.org, which needs to be transposed to respects the sklearn axes convention: >>> leuk = fetch_mldata('leukemia', transpose_data=True, ... data_home=test_data_home) >>> leuk.data.shape (72, 7129) Load an alternative 'iris' dataset, which has different names for the columns: >>> iris2 = fetch_mldata('datasets-UCI iris', target_name=1, ... data_name=0, data_home=test_data_home) >>> iris3 = fetch_mldata('datasets-UCI iris', ... target_name='class', data_name='double0', ... data_home=test_data_home) >>> import shutil >>> shutil.rmtree(test_data_home) """ # normalize dataset name dataname = mldata_filename(dataname) # check if this data set has been already downloaded data_home = get_data_home(data_home=data_home) data_home = join(data_home, 'mldata') if not exists(data_home): os.makedirs(data_home) matlab_name = dataname + '.mat' filename = join(data_home, matlab_name) # if the file does not exist, download it if not exists(filename): urlname = MLDATA_BASE_URL % quote(dataname) try: mldata_url = urlopen(urlname) except HTTPError as e: if e.code == 404: e.msg = "Dataset '%s' not found on mldata.org." % dataname raise # store Matlab file try: with open(filename, 'w+b') as matlab_file: copyfileobj(mldata_url, matlab_file) except: os.remove(filename) raise mldata_url.close() # load dataset matlab file with open(filename, 'rb') as matlab_file: matlab_dict = io.loadmat(matlab_file, struct_as_record=True) # -- extract data from matlab_dict # flatten column names col_names = [str(descr[0]) for descr in matlab_dict['mldata_descr_ordering'][0]] # if target or data names are indices, transform then into names if isinstance(target_name, numbers.Integral): target_name = col_names[target_name] if isinstance(data_name, numbers.Integral): data_name = col_names[data_name] # rules for making sense of the mldata.org data format # (earlier ones have priority): # 1) there is only one array => it is "data" # 2) there are multiple arrays # a) copy all columns in the bunch, using their column name # b) if there is a column called `target_name`, set "target" to it, # otherwise set "target" to first column # c) if there is a column called `data_name`, set "data" to it, # otherwise set "data" to second column dataset = {'DESCR': 'mldata.org dataset: %s' % dataname, 'COL_NAMES': col_names} # 1) there is only one array => it is considered data if len(col_names) == 1: data_name = col_names[0] dataset['data'] = matlab_dict[data_name] # 2) there are multiple arrays else: for name in col_names: dataset[name] = matlab_dict[name] if target_name in col_names: del dataset[target_name] dataset['target'] = matlab_dict[target_name] else: del dataset[col_names[0]] dataset['target'] = matlab_dict[col_names[0]] if data_name in col_names: del dataset[data_name] dataset['data'] = matlab_dict[data_name] else: del dataset[col_names[1]] dataset['data'] = matlab_dict[col_names[1]] # set axes to sklearn conventions if transpose_data: dataset['data'] = dataset['data'].T if 'target' in dataset: if not sp.sparse.issparse(dataset['target']): dataset['target'] = dataset['target'].squeeze() return Bunch(**dataset) # The following is used by nosetests to setup the docstring tests fixture def setup_module(module): # setup mock urllib2 module to avoid downloading from mldata.org from sklearn.utils.testing import install_mldata_mock install_mldata_mock({ 'iris': { 'data': np.empty((150, 4)), 'label': np.empty(150), }, 'datasets-uci-iris': { 'double0': np.empty((150, 4)), 'class': np.empty((150,)), }, 'leukemia': { 'data': np.empty((72, 7129)), }, }) def teardown_module(module): from sklearn.utils.testing import uninstall_mldata_mock uninstall_mldata_mock()
bsd-3-clause
kagayakidan/scikit-learn
sklearn/decomposition/tests/test_nmf.py
130
6059
import numpy as np from scipy import linalg from sklearn.decomposition import nmf from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import raises from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_less random_state = np.random.mtrand.RandomState(0) @raises(ValueError) def test_initialize_nn_input(): # Test NNDSVD behaviour on negative input nmf._initialize_nmf(-np.ones((2, 2)), 2) def test_initialize_nn_output(): # Test that NNDSVD does not return negative values data = np.abs(random_state.randn(10, 10)) for var in (None, 'a', 'ar'): W, H = nmf._initialize_nmf(data, 10, random_state=0) assert_false((W < 0).any() or (H < 0).any()) def test_initialize_close(): # Test NNDSVD error # Test that _initialize_nmf error is less than the standard deviation of # the entries in the matrix. A = np.abs(random_state.randn(10, 10)) W, H = nmf._initialize_nmf(A, 10) error = linalg.norm(np.dot(W, H) - A) sdev = linalg.norm(A - A.mean()) assert_true(error <= sdev) def test_initialize_variants(): # Test NNDSVD variants correctness # Test that the variants 'a' and 'ar' differ from basic NNDSVD only where # the basic version has zeros. data = np.abs(random_state.randn(10, 10)) W0, H0 = nmf._initialize_nmf(data, 10, variant=None) Wa, Ha = nmf._initialize_nmf(data, 10, variant='a') War, Har = nmf._initialize_nmf(data, 10, variant='ar', random_state=0) for ref, evl in ((W0, Wa), (W0, War), (H0, Ha), (H0, Har)): assert_true(np.allclose(evl[ref != 0], ref[ref != 0])) @raises(ValueError) def test_projgrad_nmf_fit_nn_input(): # Test model fit behaviour on negative input A = -np.ones((2, 2)) m = nmf.ProjectedGradientNMF(n_components=2, init=None, random_state=0) m.fit(A) def test_projgrad_nmf_fit_nn_output(): # Test that the decomposition does not contain negative values A = np.c_[5 * np.ones(5) - np.arange(1, 6), 5 * np.ones(5) + np.arange(1, 6)] for init in (None, 'nndsvd', 'nndsvda', 'nndsvdar'): model = nmf.ProjectedGradientNMF(n_components=2, init=init, random_state=0) transf = model.fit_transform(A) assert_false((model.components_ < 0).any() or (transf < 0).any()) def test_projgrad_nmf_fit_close(): # Test that the fit is not too far away pnmf = nmf.ProjectedGradientNMF(5, init='nndsvda', random_state=0) X = np.abs(random_state.randn(6, 5)) assert_less(pnmf.fit(X).reconstruction_err_, 0.05) def test_nls_nn_output(): # Test that NLS solver doesn't return negative values A = np.arange(1, 5).reshape(1, -1) Ap, _, _ = nmf._nls_subproblem(np.dot(A.T, -A), A.T, A, 0.001, 100) assert_false((Ap < 0).any()) def test_nls_close(): # Test that the NLS results should be close A = np.arange(1, 5).reshape(1, -1) Ap, _, _ = nmf._nls_subproblem(np.dot(A.T, A), A.T, np.zeros_like(A), 0.001, 100) assert_true((np.abs(Ap - A) < 0.01).all()) def test_projgrad_nmf_transform(): # Test that NMF.transform returns close values # (transform uses scipy.optimize.nnls for now) A = np.abs(random_state.randn(6, 5)) m = nmf.ProjectedGradientNMF(n_components=5, init='nndsvd', random_state=0) transf = m.fit_transform(A) assert_true(np.allclose(transf, m.transform(A), atol=1e-2, rtol=0)) def test_n_components_greater_n_features(): # Smoke test for the case of more components than features. A = np.abs(random_state.randn(30, 10)) nmf.ProjectedGradientNMF(n_components=15, sparseness='data', random_state=0).fit(A) def test_projgrad_nmf_sparseness(): # Test sparseness # Test that sparsity constraints actually increase sparseness in the # part where they are applied. A = np.abs(random_state.randn(10, 10)) m = nmf.ProjectedGradientNMF(n_components=5, random_state=0).fit(A) data_sp = nmf.ProjectedGradientNMF(n_components=5, sparseness='data', random_state=0).fit(A).data_sparseness_ comp_sp = nmf.ProjectedGradientNMF(n_components=5, sparseness='components', random_state=0).fit(A).comp_sparseness_ assert_greater(data_sp, m.data_sparseness_) assert_greater(comp_sp, m.comp_sparseness_) def test_sparse_input(): # Test that sparse matrices are accepted as input from scipy.sparse import csc_matrix A = np.abs(random_state.randn(10, 10)) A[:, 2 * np.arange(5)] = 0 T1 = nmf.ProjectedGradientNMF(n_components=5, init='random', random_state=999).fit_transform(A) A_sparse = csc_matrix(A) pg_nmf = nmf.ProjectedGradientNMF(n_components=5, init='random', random_state=999) T2 = pg_nmf.fit_transform(A_sparse) assert_array_almost_equal(pg_nmf.reconstruction_err_, linalg.norm(A - np.dot(T2, pg_nmf.components_), 'fro')) assert_array_almost_equal(T1, T2) # same with sparseness T2 = nmf.ProjectedGradientNMF( n_components=5, init='random', sparseness='data', random_state=999).fit_transform(A_sparse) T1 = nmf.ProjectedGradientNMF( n_components=5, init='random', sparseness='data', random_state=999).fit_transform(A) def test_sparse_transform(): # Test that transform works on sparse data. Issue #2124 from scipy.sparse import csc_matrix A = np.abs(random_state.randn(5, 4)) A[A > 1.0] = 0 A = csc_matrix(A) model = nmf.NMF(random_state=42) A_fit_tr = model.fit_transform(A) A_tr = model.transform(A) # This solver seems pretty inconsistent assert_array_almost_equal(A_fit_tr, A_tr, decimal=2)
bsd-3-clause
liyu1990/sklearn
sklearn/manifold/tests/test_mds.py
324
1862
import numpy as np from numpy.testing import assert_array_almost_equal from nose.tools import assert_raises from sklearn.manifold import mds def test_smacof(): # test metric smacof using the data of "Modern Multidimensional Scaling", # Borg & Groenen, p 154 sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) Z = np.array([[-.266, -.539], [.451, .252], [.016, -.238], [-.200, .524]]) X, _ = mds.smacof(sim, init=Z, n_components=2, max_iter=1, n_init=1) X_true = np.array([[-1.415, -2.471], [1.633, 1.107], [.249, -.067], [-.468, 1.431]]) assert_array_almost_equal(X, X_true, decimal=3) def test_smacof_error(): # Not symmetric similarity matrix: sim = np.array([[0, 5, 9, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) assert_raises(ValueError, mds.smacof, sim) # Not squared similarity matrix: sim = np.array([[0, 5, 9, 4], [5, 0, 2, 2], [4, 2, 1, 0]]) assert_raises(ValueError, mds.smacof, sim) # init not None and not correct format: sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) Z = np.array([[-.266, -.539], [.016, -.238], [-.200, .524]]) assert_raises(ValueError, mds.smacof, sim, init=Z, n_init=1) def test_MDS(): sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) mds_clf = mds.MDS(metric=False, n_jobs=3, dissimilarity="precomputed") mds_clf.fit(sim)
bsd-3-clause
boscotsang/BayesDigitClassify
classify_gf2.py
1
4586
import numpy from sklearn.metrics import confusion_matrix def load_data(): train_labels = [] with open('digitdata/traininglabels', 'rb') as f: for i, line in enumerate(f): train_labels.append(int(line)) train_labels = numpy.array(train_labels, dtype=int) train_x = numpy.zeros((train_labels.shape[0] * 28 * 28)) with open('digitdata/trainingimages', 'rb') as f: for i, line in enumerate(f): for j, char in enumerate(line.strip('\n')): if '+' == char or '#' == char: train_x[i * 28 + j] = 1 train_x = train_x.reshape((train_labels.shape[0], 28 * 28)) new_train_x = numpy.zeros((train_labels.shape[0], 14 * 14)) cnt = 0 for i in xrange(0, 28 * 28, 2): if (i+1) % 28 != 0 and i / 28 % 2 == 0: new_train_x[:, cnt] = train_x[:, i] + train_x[:, i+1]*2 + train_x[:, i+28]*4 + train_x[:, i+29]*8 cnt += 1 train_x = numpy.array(new_train_x, dtype=int) test_labels = [] with open('digitdata/testlabels', 'rb') as f: for i, line in enumerate(f): test_labels.append(int(line)) test_labels = numpy.array(test_labels, dtype=int) test_x = numpy.zeros((test_labels.shape[0] * 28 * 28)) with open('digitdata/testimages', 'rb') as f: for i, line in enumerate(f): for j, char in enumerate(line.strip('\n')): if '+' == char or '#' == char: test_x[i * 28 + j] = 1 test_x = test_x.reshape((test_labels.shape[0], 28 * 28)) new_test_x = numpy.zeros((test_labels.shape[0], 14 * 14)) cnt = 0 for i in xrange(0, 28 * 28, 2): if (i+1) % 28 != 0 and i / 28 % 2 == 0: new_test_x[:, cnt] = test_x[:, i] + test_x[:, i+1]*2 + test_x[:, i+28]*4 + test_x[:, i+29]*8 cnt += 1 test_x = numpy.array(new_test_x, dtype=int) return train_x, train_labels, test_x, test_labels class BayesClassifier(object): def __init__(self): self.bayesmatrix = None def fit(self, X, y): bayesmatrix = numpy.ones((10, 16, 14 * 14), dtype=numpy.float64) for k in xrange(10): for i in xrange(16): for j in xrange(X.shape[1]): bayesmatrix[k, i, j] = numpy.sum(X[y==k, j]==i) numclass = numpy.zeros(10) for i in xrange(10): numclass[i] = numpy.sum(y==i) + 1 bayesmatrix += 1. bayesmatrix /= numclass[:, numpy.newaxis, numpy.newaxis] self.bayesmatrix = bayesmatrix def predict(self, X): labels = [] for i in xrange(X.shape[0]): label = numpy.argmax(numpy.sum(numpy.log(self.bayesmatrix[:, 0, X[i, :]==0]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 1, X[i, :]==1]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 2, X[i, :]==2]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 3, X[i, :]==3]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 4, X[i, :]==4]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 5, X[i, :]==5]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 6, X[i, :]==6]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 7, X[i, :]==7]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 8, X[i, :]==8]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 9, X[i, :]==9]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 10, X[i, :]==10]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 11, X[i, :]==11]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 12, X[i, :]==12]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 13, X[i, :]==13]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 14, X[i, :]==14]), axis=1) + numpy.sum(numpy.log(self.bayesmatrix[:, 15, X[i, :]==15]), axis=1)) labels.append(label) return numpy.array(labels) if "__main__" == __name__: X, y, test_x, test_y = load_data() clf = BayesClassifier() clf.fit(X, y) pr = clf.predict(test_x) print "Confusion Matrix" print confusion_matrix(test_y, pr) print "Accuracy" print numpy.sum(pr == test_y) / float(test_y.shape[0])
mit
pllim/ginga
ginga/examples/matplotlib/example2_mpl.py
3
10002
#! /usr/bin/env python # # example2_mpl.py -- Simple, configurable FITS viewer using a matplotlib # QtAgg backend for Ginga and embedded in a Qt program. # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # """ Usage: example2_mpl.py [fits file] You need Qt4 with python bindings (or pyside) installed to run this example. """ import sys from matplotlib.figure import Figure from ginga.qtw.QtHelp import QtGui, QtCore from ginga.mplw.ImageViewCanvasMpl import ImageViewCanvas from ginga.mplw.FigureCanvasQt import FigureCanvas from ginga.misc import log from ginga import colors from ginga.canvas.CanvasObject import get_canvas_types from ginga.util.loader import load_data class FitsViewer(QtGui.QMainWindow): def __init__(self, logger): super(FitsViewer, self).__init__() self.logger = logger self.drawcolors = colors.get_colors() self.dc = get_canvas_types() fig = Figure() w = FigureCanvas(fig) fi = ImageViewCanvas(logger=logger) fi.enable_autocuts('on') fi.set_autocut_params('zscale') fi.enable_autozoom('on') fi.enable_draw(False) fi.set_callback('drag-drop', self.drop_file_cb) fi.set_callback('cursor-changed', self.cursor_cb) fi.set_bg(0.2, 0.2, 0.2) fi.ui_set_active(True) self.fitsimage = fi fi.set_figure(fig) bd = fi.get_bindings() bd.enable_all(True) # canvas that we will draw on canvas = self.dc.DrawingCanvas() canvas.enable_draw(True) canvas.enable_edit(True) canvas.set_drawtype('rectangle', color='lightblue') canvas.set_surface(fi) self.canvas = canvas # add canvas to view fi.get_canvas().add(canvas) canvas.ui_set_active(True) canvas.register_for_cursor_drawing(fi) canvas.add_callback('draw-event', self.draw_cb) w.resize(512, 512) vbox = QtGui.QVBoxLayout() vbox.setContentsMargins(QtCore.QMargins(2, 2, 2, 2)) vbox.setSpacing(1) vbox.addWidget(w, stretch=1) self.readout = QtGui.QLabel("") vbox.addWidget(self.readout, stretch=0, alignment=QtCore.Qt.AlignCenter) hbox = QtGui.QHBoxLayout() hbox.setContentsMargins(QtCore.QMargins(4, 2, 4, 2)) wdrawtype = QtGui.QComboBox() self.drawtypes = fi.get_drawtypes() for name in self.drawtypes: wdrawtype.addItem(name) index = self.drawtypes.index('rectangle') wdrawtype.setCurrentIndex(index) wdrawtype.activated.connect(self.set_drawparams) self.wdrawtype = wdrawtype wdrawcolor = QtGui.QComboBox() for name in self.drawcolors: wdrawcolor.addItem(name) index = self.drawcolors.index('lightblue') wdrawcolor.setCurrentIndex(index) wdrawcolor.activated.connect(self.set_drawparams) self.wdrawcolor = wdrawcolor wfill = QtGui.QCheckBox("Fill") wfill.stateChanged.connect(self.set_drawparams) self.wfill = wfill walpha = QtGui.QDoubleSpinBox() walpha.setRange(0.0, 1.0) walpha.setSingleStep(0.1) walpha.setValue(1.0) walpha.valueChanged.connect(self.set_drawparams) self.walpha = walpha wclear = QtGui.QPushButton("Clear Canvas") wclear.clicked.connect(self.clear_canvas) wopen = QtGui.QPushButton("Open File") wopen.clicked.connect(self.open_file) wquit = QtGui.QPushButton("Quit") wquit.clicked.connect(self.close) hbox.addStretch(1) for w in (wopen, wdrawtype, wdrawcolor, wfill, QtGui.QLabel('Alpha:'), walpha, wclear, wquit): hbox.addWidget(w, stretch=0) hw = QtGui.QWidget() hw.setLayout(hbox) vbox.addWidget(hw, stretch=0) mode = self.canvas.get_draw_mode() hbox = QtGui.QHBoxLayout() hbox.setContentsMargins(QtCore.QMargins(4, 2, 4, 2)) btn1 = QtGui.QRadioButton("Draw") btn1.setChecked(mode == 'draw') btn1.toggled.connect(lambda val: self.set_mode_cb('draw', val)) btn1.setToolTip("Choose this to draw on the canvas") hbox.addWidget(btn1) btn2 = QtGui.QRadioButton("Edit") btn2.setChecked(mode == 'edit') btn2.toggled.connect(lambda val: self.set_mode_cb('edit', val)) btn2.setToolTip("Choose this to edit things on the canvas") hbox.addWidget(btn2) btn3 = QtGui.QRadioButton("Pick") btn3.setChecked(mode == 'pick') btn3.toggled.connect(lambda val: self.set_mode_cb('pick', val)) btn3.setToolTip("Choose this to pick things on the canvas") hbox.addWidget(btn3) hbox.addWidget(QtGui.QLabel(''), stretch=1) hw = QtGui.QWidget() hw.setLayout(hbox) vbox.addWidget(hw, stretch=0) vw = QtGui.QWidget() self.setCentralWidget(vw) vw.setLayout(vbox) def set_drawparams(self, kind): index = self.wdrawtype.currentIndex() kind = self.drawtypes[index] index = self.wdrawcolor.currentIndex() fill = (self.wfill.checkState() != 0) alpha = self.walpha.value() params = {'color': self.drawcolors[index], 'alpha': alpha, } if kind in ('circle', 'rectangle', 'polygon', 'triangle', 'righttriangle', 'ellipse', 'square', 'box'): params['fill'] = fill params['fillalpha'] = alpha self.canvas.set_drawtype(kind, **params) def clear_canvas(self): self.canvas.delete_all_objects() def load_file(self, filepath): image = load_data(filepath, logger=self.logger) self.fitsimage.set_image(image) self.setWindowTitle(filepath) def open_file(self): res = QtGui.QFileDialog.getOpenFileName(self, "Open FITS file", ".", "FITS files (*.fits)") if isinstance(res, tuple): fileName = res[0] else: fileName = str(res) if len(fileName) != 0: self.load_file(fileName) def drop_file_cb(self, viewer, paths): fileName = paths[0] self.load_file(fileName) def cursor_cb(self, viewer, button, data_x, data_y): """This gets called when the data position relative to the cursor changes. """ # Get the value under the data coordinates try: # We report the value across the pixel, even though the coords # change halfway across the pixel value = viewer.get_data(int(data_x + viewer.data_off), int(data_y + viewer.data_off)) except Exception: value = None fits_x, fits_y = data_x + 1, data_y + 1 # Calculate WCS RA try: # NOTE: image function operates on DATA space coords image = viewer.get_image() if image is None: # No image loaded return ra_txt, dec_txt = image.pixtoradec(fits_x, fits_y, format='str', coords='fits') except Exception as e: self.logger.warning("Bad coordinate conversion: %s" % ( str(e))) ra_txt = 'BAD WCS' dec_txt = 'BAD WCS' text = "RA: %s DEC: %s X: %.2f Y: %.2f Value: %s" % ( ra_txt, dec_txt, fits_x, fits_y, value) self.readout.setText(text) def set_mode_cb(self, mode, tf): self.logger.info("canvas mode changed (%s) %s" % (mode, tf)) if not (tf is False): self.canvas.set_draw_mode(mode) return True def draw_cb(self, canvas, tag): obj = canvas.get_object_by_tag(tag) obj.add_callback('pick-down', self.pick_cb, 'down') obj.add_callback('pick-up', self.pick_cb, 'up') obj.add_callback('pick-move', self.pick_cb, 'move') obj.add_callback('pick-hover', self.pick_cb, 'hover') obj.add_callback('pick-enter', self.pick_cb, 'enter') obj.add_callback('pick-leave', self.pick_cb, 'leave') obj.add_callback('pick-key', self.pick_cb, 'key') obj.pickable = True obj.add_callback('edited', self.edit_cb) def pick_cb(self, obj, canvas, event, pt, ptype): self.logger.info("pick event '%s' with obj %s at (%.2f, %.2f)" % ( ptype, obj.kind, pt[0], pt[1])) return True def edit_cb(self, obj): self.logger.info("object %s has been edited" % (obj.kind)) return True def main(options, args): app = QtGui.QApplication(args) logger = log.get_logger(name="example2", options=options) w = FitsViewer(logger) w.resize(524, 540) w.show() app.setActiveWindow(w) w.raise_() w.activateWindow() if len(args) > 0: w.load_file(args[0]) app.exec_() if __name__ == "__main__": # Parse command line options from argparse import ArgumentParser argprs = ArgumentParser() argprs.add_argument("--debug", dest="debug", default=False, action="store_true", help="Enter the pdb debugger on main()") argprs.add_argument("--profile", dest="profile", action="store_true", default=False, help="Run the profiler on main()") log.addlogopts(argprs) (options, args) = argprs.parse_known_args(sys.argv[1:]) # Are we debugging this? if options.debug: import pdb pdb.run('main(options, args)') # Are we profiling this? elif options.profile: import profile print(("%s profile:" % sys.argv[0])) profile.run('main(options, args)') else: main(options, args) # END
bsd-3-clause
iamaris/anaMini
hist.py
7
1039
""" Demo of the histogram (hist) function with a few features. In addition to the basic histogram, this demo shows a few optional features: * Setting the number of data bins * The ``normed`` flag, which normalizes bin heights so that the integral of the histogram is 1. The resulting histogram is a probability density. * Setting the face color of the bars * Setting the opacity (alpha value). """ import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt # example data mu = 100 # mean of distribution sigma = 15 # standard deviation of distribution x = mu + sigma * np.random.randn(10000) num_bins = 50 # the histogram of the data n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5) # add a 'best fit' line y = mlab.normpdf(bins, mu, sigma) plt.plot(bins, y, 'r--') plt.xlabel('Smarts') plt.ylabel('Probability') plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$') # Tweak spacing to prevent clipping of ylabel plt.subplots_adjust(left=0.15) plt.show()
mit
madjelan/scikit-learn
examples/preprocessing/plot_function_transformer.py
161
1949
""" ========================================================= Using FunctionTransformer to select columns ========================================================= Shows how to use a function transformer in a pipeline. If you know your dataset's first principle component is irrelevant for a classification task, you can use the FunctionTransformer to select all but the first column of the PCA transformed data. """ import matplotlib.pyplot as plt import numpy as np from sklearn.cross_validation import train_test_split from sklearn.decomposition import PCA from sklearn.pipeline import make_pipeline from sklearn.preprocessing import FunctionTransformer def _generate_vector(shift=0.5, noise=15): return np.arange(1000) + (np.random.rand(1000) - shift) * noise def generate_dataset(): """ This dataset is two lines with a slope ~ 1, where one has a y offset of ~100 """ return np.vstack(( np.vstack(( _generate_vector(), _generate_vector() + 100, )).T, np.vstack(( _generate_vector(), _generate_vector(), )).T, )), np.hstack((np.zeros(1000), np.ones(1000))) def all_but_first_column(X): return X[:, 1:] def drop_first_component(X, y): """ Create a pipeline with PCA and the column selector and use it to transform the dataset. """ pipeline = make_pipeline( PCA(), FunctionTransformer(all_but_first_column), ) X_train, X_test, y_train, y_test = train_test_split(X, y) pipeline.fit(X_train, y_train) return pipeline.transform(X_test), y_test if __name__ == '__main__': X, y = generate_dataset() plt.scatter(X[:, 0], X[:, 1], c=y, s=50) plt.show() X_transformed, y_transformed = drop_first_component(*generate_dataset()) plt.scatter( X_transformed[:, 0], np.zeros(len(X_transformed)), c=y_transformed, s=50, ) plt.show()
bsd-3-clause
MTG/essentia
test/src/QA/clipping/test_clipping.py
1
10356
#!/usr/bin/env python # Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation (FSF), either version 3 of the License, or (at your # option) any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the Affero GNU General Public License # version 3 along with this program. If not, see http://www.gnu.org/licenses/ import sys import numpy as np from scipy.signal import medfilt import essentia.standard as es from essentia import array as esarr sys.path.insert(0, './') from qa_test import * from qa_testevents import QaTestEvents class DevWrap(QaWrapper): """ Development Solution. """ # parameters _sampleRate = 44100. _frameSize = 512 _hopSize = 256 _minimumDuration = 0 # ms _minimumDuration /= 1000. _energyThreshold = db2amp(-.001) _differentialThreshold = .1 # inner variables _idx = 0 _previousRegion = None def compute(self, *args): x = args[1] y = [] self._idx = 0 for frame in es.FrameGenerator(x, frameSize=self._frameSize, hopSize=self._hopSize, startFromZero=True): frame = np.abs(frame) starts = [] ends = [] s = int(self._frameSize / 2 - self._hopSize / 2) - 1 # consider non overlapping case e = int(self._frameSize / 2 + self._hopSize / 2) delta = np.diff(frame) delta = np.insert(delta, 0, 0) energyMask = np.array([x > self._energyThreshold for x in frame])[s:e].astype(int) deltaMask = np.array([np.abs(x) <= self._differentialThreshold for x in delta])[s:e].astype(int) combinedMask = energyMask * deltaMask flanks = np.diff(combinedMask) uFlanks = [idx for idx, x in enumerate(flanks) if x == 1] dFlanks = [idx for idx, x in enumerate(flanks) if x == -1] uFlanksValues = [] uFlanksPValues = [] for uFlank in uFlanks: uFlanksValues.append(frame[uFlank + s]) uFlanksPValues.append(frame[uFlank + s - 1]) dFlanksValues = [] dFlanksPValues = [] for dFlank in dFlanks: dFlanksValues.append(frame[dFlank + s]) dFlanksPValues.append(frame[dFlank + s + 1]) if self._previousRegion and dFlanks: start = self._previousRegion end = (self._idx * self._hopSize + dFlanks[0] + s) / self._sampleRate duration = start - end if duration > self._minimumDuration: starts.append(start) ends.append(end) self._previousRegion = None del dFlanks[0] del dFlanksValues[0] del dFlanksPValues[0] if len(dFlanks) is not len(uFlanks): self._previousRegion = (self._idx * self._hopSize + uFlanks[-1] + s) / self._sampleRate del uFlanks[-1] if len(dFlanks) is not len(uFlanks): raise EssentiaException( "Ath this point uFlanks ({}) and dFlanks ({}) are expected to have the same length!".format(len(dFlanks), len(uFlanks))) for idx in range(len(uFlanks)): start = float(self._idx * self._hopSize + uFlanks[idx] + s) / self._sampleRate end = float(self._idx * self._hopSize + dFlanks[idx] + s) / self._sampleRate duration = end - start if duration > self._minimumDuration: xs = [uFlanks[idx] - 1, uFlanks[idx], dFlanks[idx], dFlanks[idx] + 1] ys = [uFlanksPValues[idx], uFlanksValues[idx], dFlanksValues[idx], dFlanksPValues[idx]] coefs = np.polyfit(xs, ys, 2) starts.append(start) ends.append(end) estx, esty = self.maxParable(coefs) if esty > 1.0: starts.append(start) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.axvline(s, color='r') plt.axvline(e, color='r') plt.plot(frame, label='audio') xs = s + uFlanks[idx] plt.axvline(xs, color='g', alpha=.2) xs = s + dFlanks[idx] plt.axvline(xs, color='g', alpha=.2) xs = [uFlanks[idx] - 1, uFlanks[0], dFlanks[0], dFlanks[0] + 1] xs2 = np.array(xs) + s plt.plot(xs2, ys, 'ro', label='points used for the parable estimation') plt.plot(estx + s, esty, 'yo', label='estimated audio peak') x3 = np.linspace(xs[0], xs[-1], 10) y3 = [self.parEval(xx, coefs) for xx in x3] plt.plot(x3 + s, y3, label='estimated parable', alpha=.2) plt.axhline(1.0, color='g', ls='--', alpha=.2, label='maximun dynamic range') plt.title('Parabolic Regression for Clipping Detection') plt.xlim(xs2[0]-15, xs2[0] + 15) plt.legend() plot_name = 'clipping_plots/{}_{}'.format(self._idx, uFlanks[idx]) plt.savefig(plot_name) plt.clf() for start in starts: y.append(start) self._idx += 1 return esarr(y) def parEval(self, x, coefs): return coefs[0] * x ** 2 + coefs[1] * x + coefs[2] def maxParable(self, coefs): xm = -coefs[1] / (2 * coefs[0]) return xm, self.parEval(xm, coefs) class DevWrap2(QaWrapper): """ Development Solution. """ # parameters _sampleRate = 44100. _frameSize = 512 _hopSize = 256 _minimumDuration = 0 # ms _minimumDuration /= 1000. _energyThreshold = db2amp(-.001) _differentialThreshold = .001 # inner variables _idx = 0 _previousRegion = None def compute(self, *args): x = args[1] y = [] self._idx = 0 for frame in es.FrameGenerator(x, frameSize=self._frameSize, hopSize=self._hopSize, startFromZero=True): frame = np.abs(frame) starts = [] ends = [] s = int(self._frameSize / 2 - self._hopSize / 2) - 1 # consider non overlapping case e = int(self._frameSize / 2 + self._hopSize / 2) for idx in range(s, e): if frame[idx] >= self._energyThreshold: continue return esarr(y) class TruePeakDetector(QaWrapper): # Frame-wise implementation following ITU-R BS.1770-2 # parameters _sampleRate = 44100. _frameSize = 512 _hopSize = 256 _oversample = 4 _sampleRateOver = _oversample * _sampleRate _quality = 1 _BlockDC = False _emphatise = False # inner variables _idx = 0 _clippingThreshold = 0.9999695 def compute(self, *args): from math import pi x = args[1] for frame in es.FrameGenerator(x, frameSize=self._frameSize, hopSize=self._hopSize, startFromZero=True): y = [] s = int(self._frameSize / 2 - self._hopSize / 2) - 1 # consider non overlapping case e = int(self._frameSize / 2 + self._hopSize / 2) # Stage 1: Attenuation. Is not required because we are using float point. # Stage 2: Resample yResample = es.Resample(inputSampleRate=self._sampleRate, outputSampleRate=self._sampleRateOver, quality=self._quality)(frame) # Stage 3: Emphasis if self._emphatise: fPole = 20e3 # Hz fZero = 14.1e3 rPole = fPole / self._sampleRateOver rZero = fZero / self._sampleRateOver yEmphasis = es.IIR(denominator=esarr([1., rPole]), numerator=esarr([1., -rZero]))(yResample) else: yEmphasis = yResample # Stage 4 Absolute yMaxArray = np.abs(yEmphasis) # Stage 5 optional DC Block if self._BlockDC: yDCBlocked = es.DCRemoval(sampleRate=self._sampleRate, cutoffFrequency=1.)(yEmphasis) yAbsoluteDCBlocked = np.abs(yDCBlocked) yMaxArray = np.maximum(yMaxArray, yAbsoluteDCBlocked) y = [((i + self._idx * self._hopSize) / float(self._sampleRateOver), yMax) for i, yMax in enumerate(yMaxArray) if yMax > self._clippingThreshold] self._idx += 1 return esarr(y) if __name__ == '__main__': folder = 'clipping' # Instantiating wrappers wrappers = [ TruePeakDetector('events'), ] # Instantiating the test qa = QaTestEvents(verbose=True) # Add the wrappers to the test the wrappers qa.set_wrappers(wrappers) data_dir = '../../audio/recorded/distorted.wav' qa.load_audio(filename=data_dir) # Works for a single # qa.load_solution(data_dir, ground_true=True) # Compute all the estimations, get the scores and compare the computation times qa.compute_all(output_file='{}/compute.log'.format(folder)) # Optional plotting # qa.plot_all('clipping_plots/')
agpl-3.0
ueshin/apache-spark
python/pyspark/pandas/categorical.py
15
5290
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from typing import TYPE_CHECKING import pandas as pd from pandas.api.types import CategoricalDtype if TYPE_CHECKING: import pyspark.pandas as ps # noqa: F401 (SPARK-34943) class CategoricalAccessor(object): """ Accessor object for categorical properties of the Series values. Examples -------- >>> s = ps.Series(list("abbccc"), dtype="category") >>> s # doctest: +SKIP 0 a 1 b 2 b 3 c 4 c 5 c dtype: category Categories (3, object): ['a', 'b', 'c'] >>> s.cat.categories Index(['a', 'b', 'c'], dtype='object') >>> s.cat.codes 0 0 1 1 2 1 3 2 4 2 5 2 dtype: int8 """ def __init__(self, series: "ps.Series"): if not isinstance(series.dtype, CategoricalDtype): raise ValueError("Cannot call CategoricalAccessor on type {}".format(series.dtype)) self._data = series @property def categories(self) -> pd.Index: """ The categories of this categorical. Examples -------- >>> s = ps.Series(list("abbccc"), dtype="category") >>> s # doctest: +SKIP 0 a 1 b 2 b 3 c 4 c 5 c dtype: category Categories (3, object): ['a', 'b', 'c'] >>> s.cat.categories Index(['a', 'b', 'c'], dtype='object') """ return self._data.dtype.categories @categories.setter def categories(self, categories: pd.Index) -> None: raise NotImplementedError() @property def ordered(self) -> bool: """ Whether the categories have an ordered relationship. Examples -------- >>> s = ps.Series(list("abbccc"), dtype="category") >>> s # doctest: +SKIP 0 a 1 b 2 b 3 c 4 c 5 c dtype: category Categories (3, object): ['a', 'b', 'c'] >>> s.cat.ordered False """ return self._data.dtype.ordered @property def codes(self) -> "ps.Series": """ Return Series of codes as well as the index. Examples -------- >>> s = ps.Series(list("abbccc"), dtype="category") >>> s # doctest: +SKIP 0 a 1 b 2 b 3 c 4 c 5 c dtype: category Categories (3, object): ['a', 'b', 'c'] >>> s.cat.codes 0 0 1 1 2 1 3 2 4 2 5 2 dtype: int8 """ return self._data._with_new_scol(self._data.spark.column).rename() def add_categories(self, new_categories: pd.Index, inplace: bool = False) -> "ps.Series": raise NotImplementedError() def as_ordered(self, inplace: bool = False) -> "ps.Series": raise NotImplementedError() def as_unordered(self, inplace: bool = False) -> "ps.Series": raise NotImplementedError() def remove_categories(self, removals: pd.Index, inplace: bool = False) -> "ps.Series": raise NotImplementedError() def remove_unused_categories(self) -> "ps.Series": raise NotImplementedError() def rename_categories(self, new_categories: pd.Index, inplace: bool = False) -> "ps.Series": raise NotImplementedError() def reorder_categories( self, new_categories: pd.Index, ordered: bool = None, inplace: bool = False ) -> "ps.Series": raise NotImplementedError() def set_categories( self, new_categories: pd.Index, ordered: bool = None, rename: bool = False, inplace: bool = False, ) -> "ps.Series": raise NotImplementedError() def _test() -> None: import os import doctest import sys from pyspark.sql import SparkSession import pyspark.pandas.categorical os.chdir(os.environ["SPARK_HOME"]) globs = pyspark.pandas.categorical.__dict__.copy() globs["ps"] = pyspark.pandas spark = ( SparkSession.builder.master("local[4]") .appName("pyspark.pandas.categorical tests") .getOrCreate() ) (failure_count, test_count) = doctest.testmod( pyspark.pandas.categorical, globs=globs, optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE, ) spark.stop() if failure_count: sys.exit(-1) if __name__ == "__main__": _test()
apache-2.0
kaleoyster/ProjectNBI
nbi-utilities/data_gen/decisionFlowChart/validation.py
1
14013
""" description: Validation of the decision tree outputs """ import csv import os from sklearn.metrics import confusion_matrix, classification_report from collections import namedtuple from collections import defaultdict from collections import Counter __author__ = 'Akshay Kale' __copyright__ = 'GPL' # Year: 2019 ( output ) # Requires: 1992 - 2019 dataset to create the timeseries data format # Random Forest: # Decision Trees: # Fir the random forest: # For all the bridges in the nebraska: def read_main_dataset(csvFile): listOfRecords = list() with open(csvFile, 'r') as csvfile: csvReader = csv.reader(csvfile, delimiter=',') header = next(csvReader) header = [word.replace(" ", "_") for word in header] header = ["id" if word == '' else word for word in header] header[1] = 'unamed' Record = namedtuple('Record', header) for row in csvReader: record = Record(*row) structNum = record.structure_number deckInt = record.deck_intervention_in_next_3_years subInt = record.sub_intervention_in_next_3_years superInt = record.super_intervention_in_next_3_years listOfRecords.append([structNum, deckInt, superInt, subInt]) return listOfRecords def read_gt_results(csvRfFile): listOfRfIntervention = list() with open(csvRfFile, 'r') as csvfile: csvReader = csv.reader(csvfile, delimiter=',') header = next(csvReader) record = namedtuple('Record', header) for row in csvReader: rec = record(*row) structNum = rec.structureNumber intervention = rec.intervention rfIntervention = rec.rfIntervention listOfRfIntervention.append([structNum, intervention, rfIntervention]) return listOfRfIntervention def create_dict(listOfRecords): structDeck = defaultdict() structSub = defaultdict() structSup = defaultdict() for record in listOfRecords: struct = record[0] deck = record[1] sub = record[2] sup = record[3] structDeck[struct] = deck structSub[struct] = sub structSup[struct] = sup return structDeck, structSub, structSup def rf_true_negative(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] rfResult == 'Yes' if rfResult == 'No' and groundTruth == 'No': return True else: return False def rf_false_negative(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] rfResult == 'Yes' if rfResult == 'No' and groundTruth == 'Yes': return True else: return False def rf_false_positive(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if rfResult == 'Yes' and groundTruth == 'No': return True else: return False def rf_true_positive(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if rfResult == 'Yes' and groundTruth == 'Yes': return True else: return False def flow_true_positive(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'Yes' and groundTruth == 'Yes': return True else: return False def flow_false_positive(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'Yes' and groundTruth == 'No': return True else: return False def flow_false_negative(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'No' and groundTruth == 'Yes': return True else: return False def flow_true_negative(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'No' and groundTruth == 'No': return True else: return False def both_false_negative(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'No' and rfResult == 'No' and groundTruth == 'Yes': return True else: return False def both_true_negatives(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'No' and rfResult == 'No' and groundTruth == 'No': return True else: return False def both_true_positives(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'Yes' and rfResult == 'Yes' and groundTruth == 'Yes': return True else: return False def both_false_positives(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'Yes' and rfResult == 'Yes' and groundTruth == 'No': return True else: return False def both_rf_true_positive(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'No' and rfResult == 'Yes' and groundTruth == 'Yes': return True else: return False def both_rf_true_negative(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'Yes' and rfResult == 'No' and groundTruth == 'No': return True else: return False def both_flow_true_positive(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'Yes' and rfResult == 'No' and groundTruth == 'Yes': return True else: return False def both_flow_true_negative(record): intervention = record[1] rfResult = record[2] groundTruth = record[3] if intervention == 'No' and rfResult == 'Yes' and groundTruth == 'No': return True else: return False def count_ground_truth(lists): yesList = list() noList = list() for record in lists: yesRecord = record[3] if yesRecord == 'Yes': yesList.append(record) noList.append(record) return yesList, noList def integrate(listOfRfIntervention, structDeck): rfTruePositive = list() rfTrueNegative = list() rfFalsePositive = list() rfFalseNegative = list() flowTruePositive = list() flowTrueNegative = list() flowFalsePositive = list() flowFalseNegative = list() bothTruePositive = list() bothTrueNegative = list() bothFalseNegative = list() bothFalsePositive = list() bothRfTruePositive = list() bothRfTrueNegative = list() bothFlowTruePositive = list() bothFlowTrueNegative = list() counter = 0 yesList = list() noList = list() for record in listOfRfIntervention: structNum = record[0] record.append(structDeck.get(structNum)) # Recoding flow chart intervention if record[1][:4] == 'None': record[1] = 'No' else: record[1] = 'Yes' # Recoding random forest results if record[2] == '': record[2] = None elif record[2] == 'yes': record[2] = 'Yes' else: record[2] = 'No' # Record both positive if record[2] != None: counter = counter + 1 if record[3] == 'Yes': yesList.append(record) if record[3] == 'No': noList.append(record) if both_true_positives(record): bothTruePositive.append(record) if both_true_negatives(record): bothTrueNegative.append(record) if both_false_negative(record): bothFalseNegative.append(record) if both_false_positives(record): bothFalsePositive.append(record) if rf_true_positive(record): rfTruePositive.append(record) if rf_true_negative(record): rfTrueNegative.append(record) if rf_false_positive(record): rfFalsePositive.append(record) if rf_false_negative(record): rfFalseNegative.append(record) if flow_true_positive(record): flowTruePositive.append(record) if flow_true_negative(record): flowTrueNegative.append(record) if flow_false_positive(record): flowFalsePositive.append(record) if flow_false_negative(record): flowFalseNegative.append(record) if both_rf_true_positive(record): bothRfTruePositive.append(record) if both_rf_true_negative(record): bothRfTrueNegative.append(record) if both_flow_true_positive(record): bothFlowTruePositive.append(record) if both_flow_true_negative(record): bothFlowTrueNegative.append(record) else: continue returnSt = [ bothFalseNegative, bothFalsePositive, bothTrueNegative, bothTruePositive, rfTrueNegative, rfTruePositive, rfFalseNegative, rfFalsePositive, flowTrueNegative, flowTruePositive, flowFalseNegative, flowFalsePositive, counter, yesList, noList, bothFlowTruePositive, bothFlowTrueNegative, bothRfTruePositive, bothRfTrueNegative ] return returnSt def to_csv(listOfRecords, filename): with open(filename, 'w') as csvfile: csvWriter = csv.writer(csvfile) header = ['structureNumber'] for row in listOfRecords: csvWriter.writerow([row[0]]) def to_csv_all_bridges(listOfRecords, filename): with open(filename, 'w') as csvfile: csvWriter = csv.writer(csvfile) header = ['structureNumber', 'flowChartResult', 'randomForest', 'groundTruth'] csvWriter.writerow(header) for row in listOfRecords: csvWriter.writerow(row) def main(): path = '../../../../data/trees/decision-tree-dataset/' csvFile = 'decision_tree.csv' os.chdir(path) pathIntervention = '../../nbi/' csvGtFile = 'intervention_bds.csv' listOfRecords = read_main_dataset(csvFile) os.chdir(pathIntervention) listOfGtIntervention = read_gt_results(csvGtFile) # listOfRecords - deck, superstructure, substructure structDeck, structSub, structSup = create_dict(listOfRecords) ## RF intervention #Structure Number, Flow Chart, Random Forest, label bFN, bFP, bTN, bTP, rfTN, rfTP, rfFN, rfFP, flTN, flTP, flFN, flFP, count, yes, no, bfl, bfln, brf, brfn = integrate(listOfGtIntervention, structDeck) print("\n") print("--"*16+' Ground Truth '+"--"*16) print("\n") print('Number of records with ground truth Yes (Positive):', len(yes), ', Percent: ', (len(yes)/count)*100) print('Number of records with ground truth No (Negative):', len(no), ', Percent: ', (len(no)/count)*100) print("\n") print("--"*16+' Random Forest '+"--"*16) print("\n") # Randomforest print('Random Forest True Positive:', len(rfTP), ', Percent: ', (len(rfTP)/count)*100) print('Random Forest True Negative:', len(rfTN), ', Percent: ', (len(rfTN)/count)*100) print('Random Forest False Positive:', len(rfFP), ', Percent: ', (len(rfFP)/count)*100) print('Random Forest False Negative:', len(rfFN), ', Percent: ', (len(rfFN)/count)*100) print('Random Forest Accuracy:', (len(rfTP) + len(rfTN)) / count) print("\n") print("--"*16+' Flow Chart '+"--"*16) print("\n") # Flow chart print('Flow Chart True Positive:', len(flTP), ', Percent: ', (len(flTP)/len(count))*100) print('Flow Chart True Negative:', len(flTN), ', Percent: ', (len(flTN)/len(count))*100) print('Flow Chart False Positive:', len(flFP), ', Percent: ', (len(flFP)/len(count))*100) print('Flow Chart False Negative:', len(flFN), ', Percent: ', (len(flFN)/len(count))*100) print('Flow Chart Accuracy:', (len(flTP) + len(flTN)) / count) print("\n") print("--"*16+' Random Forest and Flow Chart '+"--"*16) print("\n") # Flow chart print('Both True Positive:', len(bTP), ', Percent: ', (len(bTP)/count)*100) print('Both True Negative:', len(bTN), ', Percent: ', (len(bTN)/count)*100) print('Both False Positive:', len(bFP), ', Percent: ', (len(bFP)/count)*100) print('Both False Negative:', len(bFN), ', Percent: ', (len(bFN)/count)*100) print('True Positive Rf - False Negative Flow:', len(brf), ', Percent: ', (len(brf)/count)*100) print('True Negative Rf - False Positive Flow:', len(brfn), ', Percent: ', (len(brfn)/count)*100) print('True Positive Flow - False Negative Rf:', len(bfl), ', Percent: ', (len(bfl)/count)*100) print('True Negative Flow - False Positive Rf:', len(bfln), ', Percent: ', (len(bfln)/count)*100) print("\n") print(len(bTP)+len(bTN)+len(bFP)+len(bFN)+len(brf)+len(brfn)+len(bfl)+len(bfln)) print(count) #export both true positive to_csv_all_bridges(bTP, 'bTP.csv') to_csv_all_bridges(bTN, 'bTN.csv') to_csv_all_bridges(bFP, 'bFP.csv') to_csv_all_bridges(bFN, 'bFN.csv') # flowchart to_csv_all_bridges(bfl, 'bridgesFl.csv') to_csv_all_bridges(bfln, 'bridgesFlNegative.csv') # randomforest to_csv_all_bridges(brf, 'bridgesRf.csv') to_csv_all_bridges(brfn, 'bridgesRfNegative.csv') # all bridges to_csv_all_bridges(listOfGtIntervention, 'allBridges.csv') if __name__ == '__main__': main()
gpl-2.0
oaelhara/numbbo
code-postprocessing/bbob_pproc/ppfigparam.py
1
9900
#! /usr/bin/env python # -*- coding: utf-8 -*- """Generate ERT vs param. figures. The figures will show the performance in terms of ERT on a log scale w.r.t. parameter. On the y-axis, data is represented as a number of function evaluations. Crosses (+) give the median number of function evaluations for the smallest reached target function value (also divided by dimension). Crosses (×) give the average number of overall conducted function evaluations in case the smallest target function value (1e-8) was not reached. """ from __future__ import absolute_import import os import sys import matplotlib.pyplot as plt import numpy as np from . import toolsstats, bestalg, genericsettings from .ppfig import saveFigure __all__ = ['beautify', 'plot', 'main'] avgstyle = dict(color='r', marker='x', markersize=20) medmarker = dict(linestyle='', marker='+', markersize=30, markeredgewidth=5, zorder=-1) colors = ('k', 'b', 'c', 'g', 'y', 'm', 'r', 'k', 'k', 'c', 'r', 'm') # sort of rainbow style styles = [{'color': 'k', 'marker': 'o', 'markeredgecolor': 'k'}, {'color': 'b'}, {'color': 'c', 'marker': 'v', 'markeredgecolor': 'c'}, {'color': 'g'}, {'color': 'y', 'marker': '^', 'markeredgecolor': 'y'}, {'color': 'm'}, {'color': 'r', 'marker': 's', 'markeredgecolor': 'r'}] # sort of rainbow style refcolor = 'wheat' # should correspond with the colors in pprldistr. dimsBBOB = (2, 3, 5, 10, 20, 40) #Get benchmark short infos. def read_fun_infos(isBiobjective): try: funInfos = {} filename = genericsettings.getBenchmarksShortInfos(isBiobjective) infofile = os.path.join(os.path.split(__file__)[0], filename) f = open(infofile, 'r') for line in f: if len(line) == 0 or line.startswith('%') or line.isspace() : continue funcId, funcInfo = line[0:-1].split(None, 1) funInfos[int(funcId)] = funcId + ' ' + funcInfo f.close() return funInfos except IOError, (errno, strerror): print "I/O error(%s): %s" % (errno, strerror) print 'Could not find file', infofile, \ 'Titles in figures will not be displayed.' def beautify(): """Customize figure presentation.""" # Input checking # Get axis handle and set scale for each axis axisHandle = plt.gca() axisHandle.set_xscale("log") axisHandle.set_yscale("log") # Grid options axisHandle.grid(True) ymin, ymax = plt.ylim() xmin, xmax = plt.xlim() # quadratic and cubic "grid" #plt.plot((2,200), (1, 1e2), 'k:') #plt.plot((2,200), (1, 1e4), 'k:') #plt.plot((2,200), (1e3, 1e5), 'k:') #plt.plot((2,200), (1e3, 1e7), 'k:') #plt.plot((2,200), (1e6, 1e8), 'k:') #plt.plot((2,200), (1e6, 1e10), 'k:') # axes limits plt.ylim(ymin=10**-0.2, ymax=ymax) # Set back the previous maximum. # ticks on axes # axisHandle.invert_xaxis() # plt.xlim(1.8, 45) # TODO should become input arg? # dimticklist = (2, 3, 4, 5, 10, 20, 40) # TODO: should become input arg at some point? # dimannlist = (2, 3, '', 5, 10, 20, 40) # TODO: should become input arg at some point? # TODO: All these should depend on one given input (xlim, ylim) # axisHandle.set_xticks(dimticklist) # axisHandle.set_xticklabels([str(n) for n in dimannlist]) tmp = axisHandle.get_yticks() tmp2 = [] for i in tmp: tmp2.append('%d' % round(np.log10(i))) axisHandle.set_yticklabels(tmp2) plt.ylabel('Run Lengths') def plot(dsList, param='dim', targets=(10., 1., 1e-1, 1e-2, 1e-3, 1e-5, 1e-8)): """Generate plot of ERT vs param.""" dictparam = dsList.dictByParam(param) params = sorted(dictparam) # sorted because we draw lines # generate plot from dsList res = [] # collect data rawdata = {} for p in params: assert len(dictparam[p]) == 1 rawdata[p] = dictparam[p][0].detEvals(targets) # expect dictparam[p] to have only one element # plot lines for ERT xpltdata = params for i, t in enumerate(targets): ypltdata = [] for p in params: data = rawdata[p][i] unsucc = np.isnan(data) assert len(dictparam[p]) == 1 data[unsucc] = dictparam[p][0].maxevals # compute ERT ert, srate, succ = toolsstats.sp(data, issuccessful=(unsucc == False)) ypltdata.append(ert) res.extend(plt.plot(xpltdata, ypltdata, markersize=20, zorder=len(targets) - i, **styles[i])) # for the legend plt.plot([], [], markersize=10, label=' %+d' % (np.log10(targets[i])), **styles[i]) # plot median of successful runs for hardest target with a success for p in params: for i, t in enumerate(reversed(targets)): # targets has to be from hardest to easiest data = rawdata[p][i] data = data[np.isnan(data) == False] if len(data) > 0: median = toolsstats.prctile(data, 50.)[0] res.extend(plt.plot(p, median, styles[i]['color'], **medmarker)) break # plot average number of function evaluations for the hardest target xpltdata = [] ypltdata = [] for p in params: data = rawdata[p][0] # first target xpltdata.append(p) if (np.isnan(data) == False).all(): tmpdata = data.copy() assert len(dictparam[p]) == 1 tmpdata[np.isnan(data)] = dictparam[p][0].maxevals[np.isnan(data)] tmp = np.mean(tmpdata) else: tmp = np.nan # Check what happens when plotting NaN ypltdata.append(tmp) res.extend(plt.plot(xpltdata, ypltdata, **avgstyle)) # display numbers of successes for hardest target where there is still one success for p in params: for i, t in enumerate(targets): # targets has to be from hardest to easiest data = rawdata[p][i] unsucc = np.isnan(data) assert len(dictparam[p]) == 1 data[unsucc] = dictparam[p][0].maxevals # compute ERT ert, srate, succ = toolsstats.sp(data, issuccessful=(unsucc == False)) if srate == 1.: break elif succ > 0: res.append(plt.text(p, ert * 1.85, "%d" % succ, axes=plt.gca(), horizontalalignment="center", verticalalignment="bottom")) break return res def main(dsList, _targets=(10., 1., 1e-1, 1e-2, 1e-3, 1e-5, 1e-8), param=('dim', 'Dimension'), is_normalized=True, outputdir='.', verbose=True): """Generates figure of ERT vs. param. This script will generate as many figures as there are functions. For a given function and a given parameter value there should be only **one** data set. Crosses (+) give the median number of function evaluations of successful trials for the smallest reached target function value. Crosses (x) give the average number of overall conducted function evaluations in case the smallest target function value (1e-8) was not reached. :keyword DataSetList dsList: data sets :keyword seq _targets: target precisions :keyword tuple param: parameter on x-axis. The first element has to be a string corresponding to the name of an attribute common to elements of dsList. The second element has to be a string which will be used as label for the figures. The values of attribute param have to be sortable. :keyword bool is_normalized: if True the y values are normalized by x values :keyword string outputdir: name of output directory for the image files :keyword bool verbose: controls verbosity """ funInfos = read_fun_infos(dsList.isBiobjective()) # TODO check input parameter param for func, dictfunc in dsList.dictByFunc().iteritems(): filename = os.path.join(outputdir,'ppfigparam_%s_f%03d' % (param[0], func)) try: targets = list(j[func] for j in _targets) except TypeError: targets = _targets targets = sorted(targets) # from hard to easy handles = plot(dictfunc, param[0], targets) # # display best 2009 # if not bestalg.bestalgentries2009: # bestalg.loadBBOB2009() # bestalgdata = [] # for d in dimsBBOB: # entry = bestalg.bestalgentries2009[(d, func)] # tmp = entry.detERT([1e-8])[0] # if not np.isinf(tmp): # bestalgdata.append(tmp/d) # else: # bestalgdata.append(None) # plt.plot(dimsBBOB, bestalgdata, color=refcolor, linewidth=10, zorder=-2) # plt.plot(dimsBBOB, bestalgdata, ls='', marker='d', markersize=25, # color=refcolor, markeredgecolor=refcolor, zorder=-2) a = plt.gca() if is_normalized: for i in handles: try: plt.setp(i, 'ydata', plt.getp(i, 'ydata') / plt.getp(i, 'xdata')) except TypeError: pass a.relim() a.autoscale_view() beautify() plt.xlabel(param[1]) if is_normalized: plt.setp(plt.gca(), 'ylabel', plt.getp(a, 'ylabel') + ' / ' + param[1]) if func in (1, 24, 101, 130): plt.legend(loc="best") if func in funInfos.keys(): a.set_title(funInfos[func]) saveFigure(filename, verbose=verbose) plt.close()
bsd-3-clause
cauchycui/scikit-learn
examples/mixture/plot_gmm_classifier.py
250
3918
""" ================== GMM classification ================== Demonstration of Gaussian mixture models for classification. See :ref:`gmm` for more information on the estimator. Plots predicted labels on both training and held out test data using a variety of GMM classifiers on the iris dataset. Compares GMMs with spherical, diagonal, full, and tied covariance matrices in increasing order of performance. Although one would expect full covariance to perform best in general, it is prone to overfitting on small datasets and does not generalize well to held out test data. On the plots, train data is shown as dots, while test data is shown as crosses. The iris dataset is four-dimensional. Only the first two dimensions are shown here, and thus some points are separated in other dimensions. """ print(__doc__) # Author: Ron Weiss <ronweiss@gmail.com>, Gael Varoquaux # License: BSD 3 clause # $Id$ import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np from sklearn import datasets from sklearn.cross_validation import StratifiedKFold from sklearn.externals.six.moves import xrange from sklearn.mixture import GMM def make_ellipses(gmm, ax): for n, color in enumerate('rgb'): v, w = np.linalg.eigh(gmm._get_covars()[n][:2, :2]) u = w[0] / np.linalg.norm(w[0]) angle = np.arctan2(u[1], u[0]) angle = 180 * angle / np.pi # convert to degrees v *= 9 ell = mpl.patches.Ellipse(gmm.means_[n, :2], v[0], v[1], 180 + angle, color=color) ell.set_clip_box(ax.bbox) ell.set_alpha(0.5) ax.add_artist(ell) iris = datasets.load_iris() # Break up the dataset into non-overlapping training (75%) and testing # (25%) sets. skf = StratifiedKFold(iris.target, n_folds=4) # Only take the first fold. train_index, test_index = next(iter(skf)) X_train = iris.data[train_index] y_train = iris.target[train_index] X_test = iris.data[test_index] y_test = iris.target[test_index] n_classes = len(np.unique(y_train)) # Try GMMs using different types of covariances. classifiers = dict((covar_type, GMM(n_components=n_classes, covariance_type=covar_type, init_params='wc', n_iter=20)) for covar_type in ['spherical', 'diag', 'tied', 'full']) n_classifiers = len(classifiers) plt.figure(figsize=(3 * n_classifiers / 2, 6)) plt.subplots_adjust(bottom=.01, top=0.95, hspace=.15, wspace=.05, left=.01, right=.99) for index, (name, classifier) in enumerate(classifiers.items()): # Since we have class labels for the training data, we can # initialize the GMM parameters in a supervised manner. classifier.means_ = np.array([X_train[y_train == i].mean(axis=0) for i in xrange(n_classes)]) # Train the other parameters using the EM algorithm. classifier.fit(X_train) h = plt.subplot(2, n_classifiers / 2, index + 1) make_ellipses(classifier, h) for n, color in enumerate('rgb'): data = iris.data[iris.target == n] plt.scatter(data[:, 0], data[:, 1], 0.8, color=color, label=iris.target_names[n]) # Plot the test data with crosses for n, color in enumerate('rgb'): data = X_test[y_test == n] plt.plot(data[:, 0], data[:, 1], 'x', color=color) y_train_pred = classifier.predict(X_train) train_accuracy = np.mean(y_train_pred.ravel() == y_train.ravel()) * 100 plt.text(0.05, 0.9, 'Train accuracy: %.1f' % train_accuracy, transform=h.transAxes) y_test_pred = classifier.predict(X_test) test_accuracy = np.mean(y_test_pred.ravel() == y_test.ravel()) * 100 plt.text(0.05, 0.8, 'Test accuracy: %.1f' % test_accuracy, transform=h.transAxes) plt.xticks(()) plt.yticks(()) plt.title(name) plt.legend(loc='lower right', prop=dict(size=12)) plt.show()
bsd-3-clause
madjelan/scikit-learn
sklearn/neighbors/regression.py
106
10572
"""Nearest Neighbor Regression""" # Authors: Jake Vanderplas <vanderplas@astro.washington.edu> # Fabian Pedregosa <fabian.pedregosa@inria.fr> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # Sparseness support by Lars Buitinck <L.J.Buitinck@uva.nl> # Multi-output support by Arnaud Joly <a.joly@ulg.ac.be> # # License: BSD 3 clause (C) INRIA, University of Amsterdam import numpy as np from .base import _get_weights, _check_weights, NeighborsBase, KNeighborsMixin from .base import RadiusNeighborsMixin, SupervisedFloatMixin from ..base import RegressorMixin from ..utils import check_array class KNeighborsRegressor(NeighborsBase, KNeighborsMixin, SupervisedFloatMixin, RegressorMixin): """Regression based on k-nearest neighbors. The target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set. Read more in the :ref:`User Guide <regression>`. Parameters ---------- n_neighbors : int, optional (default = 5) Number of neighbors to use by default for :meth:`k_neighbors` queries. weights : str or callable weight function used in prediction. Possible values: - 'uniform' : uniform weights. All points in each neighborhood are weighted equally. - 'distance' : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. - [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Uniform weights are used by default. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDtree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_size : int, optional (default = 30) Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. metric : string or DistanceMetric object (default='minkowski') the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of the DistanceMetric class for a list of available metrics. p : integer, optional (default = 2) Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_params: dict, optional (default = None) additional keyword arguments for the metric function. Examples -------- >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import KNeighborsRegressor >>> neigh = KNeighborsRegressor(n_neighbors=2) >>> neigh.fit(X, y) # doctest: +ELLIPSIS KNeighborsRegressor(...) >>> print(neigh.predict([[1.5]])) [ 0.5] See also -------- NearestNeighbors RadiusNeighborsRegressor KNeighborsClassifier RadiusNeighborsClassifier Notes ----- See :ref:`Nearest Neighbors <neighbors>` in the online documentation for a discussion of the choice of ``algorithm`` and ``leaf_size``. .. warning:: Regarding the Nearest Neighbors algorithms, if it is found that two neighbors, neighbor `k+1` and `k`, have identical distances but but different labels, the results will depend on the ordering of the training data. http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm """ def __init__(self, n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, **kwargs): self._init_params(n_neighbors=n_neighbors, algorithm=algorithm, leaf_size=leaf_size, metric=metric, p=p, metric_params=metric_params, **kwargs) self.weights = _check_weights(weights) def predict(self, X): """Predict the target for the provided data Parameters ---------- X : array or matrix, shape = [n_samples, n_features] Returns ------- y : array of int, shape = [n_samples] or [n_samples, n_outputs] Target values """ X = check_array(X, accept_sparse='csr') neigh_dist, neigh_ind = self.kneighbors(X) weights = _get_weights(neigh_dist, self.weights) _y = self._y if _y.ndim == 1: _y = _y.reshape((-1, 1)) if weights is None: y_pred = np.mean(_y[neigh_ind], axis=1) else: y_pred = np.empty((X.shape[0], _y.shape[1]), dtype=np.float) denom = np.sum(weights, axis=1) for j in range(_y.shape[1]): num = np.sum(_y[neigh_ind, j] * weights, axis=1) y_pred[:, j] = num / denom if self._y.ndim == 1: y_pred = y_pred.ravel() return y_pred class RadiusNeighborsRegressor(NeighborsBase, RadiusNeighborsMixin, SupervisedFloatMixin, RegressorMixin): """Regression based on neighbors within a fixed radius. The target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set. Read more in the :ref:`User Guide <regression>`. Parameters ---------- radius : float, optional (default = 1.0) Range of parameter space to use by default for :meth`radius_neighbors` queries. weights : str or callable weight function used in prediction. Possible values: - 'uniform' : uniform weights. All points in each neighborhood are weighted equally. - 'distance' : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. - [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Uniform weights are used by default. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDtree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_size : int, optional (default = 30) Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. metric : string or DistanceMetric object (default='minkowski') the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of the DistanceMetric class for a list of available metrics. p : integer, optional (default = 2) Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_params: dict, optional (default = None) additional keyword arguments for the metric function. Examples -------- >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import RadiusNeighborsRegressor >>> neigh = RadiusNeighborsRegressor(radius=1.0) >>> neigh.fit(X, y) # doctest: +ELLIPSIS RadiusNeighborsRegressor(...) >>> print(neigh.predict([[1.5]])) [ 0.5] See also -------- NearestNeighbors KNeighborsRegressor KNeighborsClassifier RadiusNeighborsClassifier Notes ----- See :ref:`Nearest Neighbors <neighbors>` in the online documentation for a discussion of the choice of ``algorithm`` and ``leaf_size``. http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm """ def __init__(self, radius=1.0, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, **kwargs): self._init_params(radius=radius, algorithm=algorithm, leaf_size=leaf_size, p=p, metric=metric, metric_params=metric_params, **kwargs) self.weights = _check_weights(weights) def predict(self, X): """Predict the target for the provided data Parameters ---------- X : array or matrix, shape = [n_samples, n_features] Returns ------- y : array of int, shape = [n_samples] or [n_samples, n_outputs] Target values """ X = check_array(X, accept_sparse='csr') neigh_dist, neigh_ind = self.radius_neighbors(X) weights = _get_weights(neigh_dist, self.weights) _y = self._y if _y.ndim == 1: _y = _y.reshape((-1, 1)) if weights is None: y_pred = np.array([np.mean(_y[ind, :], axis=0) for ind in neigh_ind]) else: y_pred = np.array([(np.average(_y[ind, :], axis=0, weights=weights[i])) for (i, ind) in enumerate(neigh_ind)]) if self._y.ndim == 1: y_pred = y_pred.ravel() return y_pred
bsd-3-clause
ericpre/hyperspy
hyperspy/tests/drawing/test_plot_signal1d.py
1
11462
# Copyright 2007-2021 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # HyperSpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with HyperSpy. If not, see <http://www.gnu.org/licenses/>. import os from shutil import copyfile from pathlib import Path import matplotlib.pyplot as plt import numpy as np import pytest import scipy.misc import hyperspy.api as hs from hyperspy.misc.test_utils import update_close_figure from hyperspy.signals import Signal1D from hyperspy.drawing.signal1d import Signal1DLine from hyperspy.tests.drawing.test_plot_signal import _TestPlot scalebar_color = 'blue' default_tol = 2.0 baseline_dir = 'plot_signal1d' style_pytest_mpl = 'default' style = ['default', 'overlap', 'cascade', 'mosaic', 'heatmap'] def _generate_filename_list(style): path = Path(__file__).resolve().parent baseline_path = path.joinpath(baseline_dir) filename_list = [f'test_plot_spectra_{s}' for s in style] + \ [f'test_plot_spectra_rev_{s}' for s in style] filename_list2 = [] for filename in filename_list: for i in range(0, 4): filename_list2.append( baseline_path.joinpath(f'{filename}{i}.png') ) return filename_list2 @pytest.fixture def setup_teardown(request, scope="class"): try: import pytest_mpl # This option is available only when pytest-mpl is installed mpl_generate_path_cmdopt = request.config.getoption("--mpl-generate-path") except ImportError: mpl_generate_path_cmdopt = None # SETUP # duplicate baseline images to match the test_name when the # parametrized 'test_plot_spectra' are run. For a same 'style', the # expected images are the same. if mpl_generate_path_cmdopt is None: for filename in _generate_filename_list(style): copyfile(f"{str(filename)[:-5]}.png", filename) yield # TEARDOWN # Create the baseline images: copy one baseline image for each test # and remove the other ones. if mpl_generate_path_cmdopt: for filename in _generate_filename_list(style): copyfile(filename, f"{str(filename)[:-5]}.png") # Delete the images that have been created in 'setup_class' for filename in _generate_filename_list(style): os.remove(filename) @pytest.mark.usefixtures("setup_teardown") class TestPlotSpectra(): s = hs.signals.Signal1D(scipy.misc.ascent()[100:160:10]) # Add a test signal with decreasing axis s_reverse = s.deepcopy() s_reverse.axes_manager[1].offset = 512 s_reverse.axes_manager[1].scale = -1 def _generate_parameters(style): parameters = [] for s in style: for fig in [True, None]: for ax in [True, None]: parameters.append([s, fig, ax]) return parameters def _generate_ids(style, duplicate=4): ids = [] for s in style: ids.extend([s] * duplicate) return ids @pytest.mark.parametrize(("style", "fig", "ax"), _generate_parameters(style), ids=_generate_ids(style)) @pytest.mark.mpl_image_compare(baseline_dir=baseline_dir, tolerance=default_tol, style=style_pytest_mpl) def test_plot_spectra(self, style, fig, ax): if fig: fig = plt.figure() if ax: fig = plt.figure() ax = fig.add_subplot(111) ax = hs.plot.plot_spectra(self.s, style=style, legend='auto', fig=fig, ax=ax) if style == 'mosaic': ax = ax[0] return ax.figure @pytest.mark.parametrize(("style", "fig", "ax"), _generate_parameters(style), ids=_generate_ids(style)) @pytest.mark.mpl_image_compare(baseline_dir=baseline_dir, tolerance=default_tol, style=style_pytest_mpl) def test_plot_spectra_rev(self, style, fig, ax): if fig: fig = plt.figure() if ax: fig = plt.figure() ax = fig.add_subplot(111) ax = hs.plot.plot_spectra(self.s_reverse, style=style, legend='auto', fig=fig, ax=ax) if style == 'mosaic': ax = ax[0] return ax.figure @pytest.mark.parametrize("figure", ['1nav', '1sig', '2nav', '2sig']) @pytest.mark.mpl_image_compare(baseline_dir=baseline_dir, tolerance=default_tol, style=style_pytest_mpl) def test_plot_spectra_sync(self, figure): s1 = hs.signals.Signal1D(scipy.misc.face()).as_signal1D(0).inav[:, :3] s2 = s1.deepcopy() * -1 hs.plot.plot_signals([s1, s2]) if figure == '1nav': return s1._plot.signal_plot.figure if figure == '1sig': return s1._plot.navigator_plot.figure if figure == '2nav': return s2._plot.navigator_plot.figure if figure == '2sig': return s2._plot.navigator_plot.figure def test_plot_spectra_legend_pick(self): x = np.linspace(0., 2., 512) n = np.arange(1, 5) x_pow_n = x[None, :]**n[:, None] s = hs.signals.Signal1D(x_pow_n) my_legend = [r'x^' + str(io) for io in n] f = plt.figure() ax = hs.plot.plot_spectra(s, legend=my_legend, fig=f) leg = ax.get_legend() leg_artists = leg.get_lines() click = plt.matplotlib.backend_bases.MouseEvent( 'button_press_event', f.canvas, 0, 0, 'left') for artist, li in zip(leg_artists, ax.lines[::-1]): plt.matplotlib.backends.backend_agg.FigureCanvasBase.pick_event( f.canvas, click, artist) assert not li.get_visible() plt.matplotlib.backends.backend_agg.FigureCanvasBase.pick_event( f.canvas, click, artist) @pytest.mark.mpl_image_compare(baseline_dir=baseline_dir, tolerance=default_tol, style=style_pytest_mpl) def test_plot_spectra_auto_update(self): s = hs.signals.Signal1D(np.arange(100)) s2 = s / 2 ax = hs.plot.plot_spectra([s, s2]) s.data = -s.data s.events.data_changed.trigger(s) s2.data = -s2.data * 4 + 50 s2.events.data_changed.trigger(s2) return ax.get_figure() @update_close_figure() def test_plot_nav0_close(): test_plot = _TestPlot(ndim=0, sdim=1) test_plot.signal.plot() return test_plot.signal @update_close_figure() def test_plot_nav1_close(): test_plot = _TestPlot(ndim=1, sdim=1) test_plot.signal.plot() return test_plot.signal @update_close_figure(check_data_changed_close=False) def test_plot_nav2_close(): test_plot = _TestPlot(ndim=2, sdim=1) test_plot.signal.plot() return test_plot.signal def _test_plot_two_cursors(ndim): test_plot = _TestPlot(ndim=ndim, sdim=1) # sdim=2 not supported s = test_plot.signal s.metadata.General.title = 'Nav %i, Sig 1, two cursor' % ndim s.axes_manager[0].index = 4 s.plot() s._plot.add_right_pointer() s._plot.navigator_plot.figure.canvas.draw() s._plot.signal_plot.figure.canvas.draw() s._plot.right_pointer.axes_manager[0].index = 2 if ndim == 2: s.axes_manager[1].index = 2 s._plot.right_pointer.axes_manager[1].index = 3 return s @pytest.mark.parametrize('autoscale', ['', 'x', 'xv', 'v']) @pytest.mark.parametrize('norm', ['log', 'auto']) def test_plot_two_cursos_parameters(autoscale, norm): kwargs = {'autoscale':autoscale, 'norm':norm} test_plot = _TestPlot(ndim=2, sdim=1) # sdim=2 not supported s = test_plot.signal s.plot(**kwargs) s._plot.add_right_pointer(**kwargs) for line in s._plot.signal_plot.ax_lines: assert line.autoscale == autoscale def _generate_parameter(): parameters = [] for ndim in [1, 2]: for plot_type in ['nav', 'sig']: parameters.append([ndim, plot_type]) return parameters @pytest.mark.mpl_image_compare(baseline_dir=baseline_dir, tolerance=default_tol, style=style_pytest_mpl) def test_plot_log_scale(): s = Signal1D(np.exp(-np.arange(100) / 5.0)) s.plot(norm='log') return s._plot.signal_plot.figure @pytest.mark.parametrize(("ndim", "plot_type"), _generate_parameter()) @pytest.mark.mpl_image_compare(baseline_dir=baseline_dir, tolerance=default_tol, style=style_pytest_mpl) def test_plot_two_cursors(ndim, plot_type): s = _test_plot_two_cursors(ndim=ndim) if plot_type == "sig": f = s._plot.signal_plot.figure else: f= s._plot.navigator_plot.figure return f @update_close_figure(check_data_changed_close=False) def test_plot_nav2_sig1_two_cursors_close(): return _test_plot_two_cursors(ndim=2) def test_plot_with_non_finite_value(): s = hs.signals.Signal1D(np.array([np.nan, 2.0])) s.plot() s.axes_manager.events.indices_changed.trigger(s.axes_manager) s = hs.signals.Signal1D(np.array([np.nan, np.nan])) s.plot() s.axes_manager.events.indices_changed.trigger(s.axes_manager) s = hs.signals.Signal1D(np.array([-np.inf, 2.0])) s.plot() s.axes_manager.events.indices_changed.trigger(s.axes_manager) s = hs.signals.Signal1D(np.array([np.inf, 2.0])) s.plot() s.axes_manager.events.indices_changed.trigger(s.axes_manager) def test_plot_add_line_events(): s = hs.signals.Signal1D(np.arange(100)) s.plot() assert len(s.axes_manager.events.indices_changed.connected) == 1 figure = s._plot.signal_plot def line_function(axes_manager=None): return 100 - np.arange(100) line = Signal1DLine() line.data_function = line_function line.set_line_properties(color='blue', type='line', scaley=False) figure.add_line(line, connect_navigation=True) line.plot() assert len(line.events.closed.connected) == 1 assert len(s.axes_manager.events.indices_changed.connected) == 2 line.close() figure.close_right_axis() assert len(line.events.closed.connected) == 0 assert len(s.axes_manager.events.indices_changed.connected) == 1 figure.close() assert len(s.axes_manager.events.indices_changed.connected) == 0 @pytest.mark.parametrize("autoscale", ['', 'x', 'xv', 'v']) @pytest.mark.mpl_image_compare(baseline_dir=baseline_dir, tolerance=default_tol, style=style_pytest_mpl) def test_plot_autoscale(autoscale): s = hs.datasets.artificial_data.get_core_loss_eels_line_scan_signal( add_powerlaw=True, add_noise=False) s.plot(autoscale=autoscale) ax = s._plot.signal_plot.ax ax.set_xlim(500.0, 700.0) ax.set_ylim(-10.0, 20.0) s.axes_manager.events.indices_changed.trigger(s.axes_manager) return s._plot.signal_plot.figure
gpl-3.0
nuclear-wizard/moose
modules/tensor_mechanics/test/tests/tensile/small_deform_hard3.py
12
1286
#!/usr/bin/env python3 #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html import os import sys import numpy as np import matplotlib.pyplot as plt def expected(): ini = 1.0 res = 0.5 lim = 1E-5 lo2 = 0.5 * lim alpha = (ini - res) / 4.0 / lo2**3 beta = -3.0 * alpha * lo2**2 data = [i*1E-5/100 for i in range(100)] data = [(x, alpha * (x - lo2)**3 + beta * (x - lo2) + (ini + res) / 2.0) for x in data] return zip(*data) def moose(): f = open("gold/small_deform_hard3_update_version.csv") data = [line.strip().split(",") for line in f.readlines()[2:-1]] data = [(d[2], d[4]) for d in data] f.close() return zip(*data) plt.figure() expect = expected() m = moose() plt.plot(expect[0], expect[1], 'k-', linewidth = 3.0, label = 'expected') plt.plot(m[0], m[1], 'k^', label = 'MOOSE') plt.legend(loc = 'upper right') plt.xlabel("internal parameter") plt.ylabel("Tensile strength") plt.title("Tensile yield with softening") plt.savefig("small_deform_hard3.pdf") sys.exit(0)
lgpl-2.1
UBC-Astrophysics/ObsPlan
ObsPlan.py
1
9933
#!/usr/bin/env python # # ObsPlan.py # # Elisa Antolini # Jeremy Heyl # UBC Southern Observatory # # This script takes the LIGO-Virgo Skymap (P(d|m)) and optionally a # galaxy-density map (P(m)) and finds the most likely fields to # observe (P(m|d)). The fields are assumed to be healpix regions from a # tesselation with a given value of nside (the value of nside # depends of the field of view of the telescope). # # P(position|data) = P(position) P(data|position) / P(data) # # P(position) is the galaxy density map ( P(m) ) # P(data|position) is the skymap from LIGO-Virgo ( P(d|m) ) # P(data) is constant with position so we neglect it. # # # # usage: ObsPlan.py [-h] [--gal-map GAL_MAP] [--nvalues NVALUES] # [--cumprob CUMPROB] [--savefigures] [--no-savefigures] # [--textoutput] [--no-textoutput] # sky-map nside # # # nside = ceil ( sqrt (3/Pi) 60 / s ) # # where s is the length of one side of the square field of view in degrees. # # # Questions: heyl@phas.ubc.ca # # Copyright 2015, Elisa Antolini and Jeremy Heyl # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from argparse import ArgumentParser import math as mt import numpy as np import healpy as hp import matplotlib.pyplot as plt import sys def IndexToDeclRa(NSIDE,index): theta,phi=hp.pixelfunc.pix2ang(NSIDE,index) return np.degrees(mt.pi/2.-theta),np.degrees(phi) def DeclRaToIndex(decl,RA,NSIDE): return hp.pixelfunc.ang2pix(NSIDE,np.radians(90.-decl),np.radians(RA)) def PlotMap(Map,NsideMap,MapName): hp.mollview(Map,coord='C',rot = [0,0.3], title='Histogram-Equalized Probability Density Map', unit='prob', xsize=NsideMap) hp.graticule() plt.savefig(MapName) def isPower(num, base): if base == 1 and num != 1: return False if base == 1 and num == 1: return True if base == 0 and num != 1: return False power = int (mt.log (num, base) + 0.5) return base ** power == num def MakeObsPlan(SkyMap_name,nside,SaveFigures,nvalues=None, cumprob=None,DensityMap_name=None, TextOutput=False): #Check if the nside is a power of two val = isPower(nside,2) if val == False: print(" **************** WARNING **************** ") print("The inserted NSIDE is not a power of two") y = np.log2(nside) exp = int(y) if (exp + 0.5) < y : exp = exp +1 nside = int(np.power(2,exp)) print("The nearest NSIDE applicable is "+str(nside)) print(" ****************************************** ") nside_DensityMap = 0 if DensityMap_name != None : #Load the Glaxy Density Map P(m) Densitymap_Ring = hp.read_map(DensityMap_name,0) nside_DensityMap = hp.pixelfunc.get_nside(Densitymap_Ring) galpixels_DensityMap = np.asarray(Densitymap_Ring) if SaveFigures : PlotMap(galpixels_DensityMap,nside_DensityMap,'./GalaxyDensityMap.png') #Load the Sky Map from LIGO-Virgo ( P(d|m) ) Skymap_Ring = hp.read_map(SkyMap_name,0) nside_SkyMap = hp.pixelfunc.get_nside(Skymap_Ring) galpixels_SkyMap = np.asarray(Skymap_Ring) if SaveFigures: PlotMap(galpixels_SkyMap,nside_SkyMap,'./LIGOSkyMap.png') #Resize the Sky Map if necessary if nside_SkyMap != nside: galpixels_SkyMap = hp.pixelfunc.ud_grade(galpixels_SkyMap,nside_out = nside, order_in = 'RING', order_out = 'RING') if SaveFigures: PlotMap(galpixels_SkyMap,nside,'./LIGOSkyMapResized.png') #Resize Galaxy Density Map if necessary if DensityMap_name != None : if nside_DensityMap != nside: galpixels_DensityMap = hp.pixelfunc.ud_grade(galpixels_DensityMap,nside_out = nside, order_in = 'RING', order_out = 'RING') galpixels_DensityMap = np.where(galpixels_DensityMap>0,galpixels_DensityMap,0) if SaveFigures: PlotMap(galpixels_DensityMap,nside,'./GalaxyDensityMapResized.png') Map_Position_Data = np.zeros(hp.nside2npix(nside)) # Multiply the resulting maps together -> # P(position|data) = P(position) P(data|position) if DensityMap_name != None : Map_Position_Data = galpixels_SkyMap * galpixels_DensityMap else : Map_Position_Data = galpixels_SkyMap # Normalize to 1 the sum of the pixels Map_Position_Data/=np.sum(Map_Position_Data) if SaveFigures: PlotMap(Map_Position_Data,nside,'./MapPositionData.png') # Sort the array by the probability # Sort from the largest to the smallest healpixno=np.argsort(-Map_Position_Data) Map_Position_Data=Map_Position_Data[healpixno] # accumulate the probability probsum=np.cumsum(Map_Position_Data) dec, ra = IndexToDeclRa(nside,healpixno) if TextOutput: np.savetxt("SkyMap_OutFile.txt.gz", np.transpose([healpixno,ra,dec, Map_Position_Data,probsum, np.arange(1,len(probsum)+1)]), fmt="%16d %10.5f %10.5f %10.5f %10.5f %16d", header="Healpix Number| RA| Dec|Probability|Cumulative Prob | Number of Fields") else: np.savez("SkyMap_OutFile", healpixno=healpixno,ra=ra,dec=dec, prob=Map_Position_Data,probsum=probsum) if nvalues != None: print("# %d most probable values :" % nvalues) ii=np.arange(nvalues) np.savetxt(sys.stdout, np.transpose([healpixno[ii],ra[ii],dec[ii], Map_Position_Data[ii],probsum[ii],ii+1]), fmt="%16d %10.5f %10.5f %10.5f %10.5f %16d", header="Healpix Number| RA| Dec|Probability|Cumulative Prob | Number of Fields") if cumprob != None: print("# Most probable values with cumprob < %g" % cumprob) ii=(probsum<cumprob) hpn=healpixno[ii] np.savetxt(sys.stdout, np.transpose([hpn,ra[ii],dec[ii], Map_Position_Data[ii],probsum[ii], np.arange(1,len(hpn)+1)]), fmt="%16d %10.5f %10.5f %10.5f %10.5f %16d", header="Healpix Number| RA| Dec|Probability|Cumulative Prob | Number of Fields") def _parse_command_line_arguments(): """ Parse and return command line arguments """ parser = ArgumentParser( description=( 'Command-line tool to generate an observing plan from a LIGO/Virgo probability map (with an optional galaxy map too)' ), ) parser.add_argument( 'sky-map', type=str, help=( 'A FITS file containing the LIGO/Virgo probability map in HEALPIX format' ), ) parser.add_argument( 'nside', type=int, help=( 'nside for the output map' 'nside = ceil(sqrt(3/Pi) 60 / s)' 'where s is the length of one side of the square field of view in degrees.' 'It will be rounded to the nearest power of two.' ), ) parser.add_argument( '--gal-map', required=False, type=str, help='A FITS file containing the galaxy density map in HEALPIX format' ) parser.add_argument( '--nvalues', required=False, type=int, help='Number of Maximum Probability pixels to be shown' ) parser.add_argument( '--cumprob', required=False, type=float, help='Output up to the given cumulative probability' ) parser.add_argument('--savefigures',dest='savefigures',action='store_true') parser.add_argument('--no-savefigures',dest='savefigures',action='store_false') parser.set_defaults(savefigures=False) parser.add_argument('--textoutput',dest='textoutput',action='store_true') parser.add_argument('--no-textoutput',dest='textoutput',action='store_false') parser.set_defaults(textoutput=False) arguments = vars(parser.parse_args()) return arguments #------------------------------------------------------------------------------ # main # def _main(): """ This is the main routine. """ args=_parse_command_line_arguments() MakeObsPlan(args['sky-map'],args['nside'],args['savefigures'], nvalues=args['nvalues'],cumprob=args['cumprob'], DensityMap_name=args['gal_map'],TextOutput=args['textoutput']) ''' #### Input Parameters ##### DensityMap_name = argv[1] # Density Map Name or none SkyMap_name = argv[2] # Sky Map Name nside = int(argv[3]) # NSIDE of probability Map SaveFigures = argv[4] # Yes or No nvalues = int(argv[5]) # Number of Maximum Probability pixels to be shown MakeObsPlan(SkyMap_name,nside,SaveFigures,nvalues,DensityMap_name) ''' #------------------------------------------------------------------------------ # Start program execution. # if __name__ == '__main__': _main()
gpl-3.0
Barmaley-exe/scikit-learn
sklearn/metrics/tests/test_score_objects.py
2
13929
import pickle import numpy as np from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regexp from sklearn.utils.testing import assert_true from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_not_equal from sklearn.base import BaseEstimator from sklearn.metrics import (f1_score, r2_score, roc_auc_score, fbeta_score, log_loss, precision_score, recall_score) from sklearn.metrics.cluster import adjusted_rand_score from sklearn.metrics.scorer import (check_scoring, _PredictScorer, _passthrough_scorer) from sklearn.metrics import make_scorer, get_scorer, SCORERS from sklearn.svm import LinearSVC from sklearn.pipeline import make_pipeline from sklearn.cluster import KMeans from sklearn.dummy import DummyRegressor from sklearn.linear_model import Ridge, LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import make_blobs from sklearn.datasets import make_classification from sklearn.datasets import make_multilabel_classification from sklearn.datasets import load_diabetes from sklearn.cross_validation import train_test_split, cross_val_score from sklearn.grid_search import GridSearchCV from sklearn.multiclass import OneVsRestClassifier REGRESSION_SCORERS = ['r2', 'mean_absolute_error', 'mean_squared_error', 'median_absolute_error'] CLF_SCORERS = ['accuracy', 'f1', 'f1_weighted', 'f1_macro', 'f1_micro', 'roc_auc', 'average_precision', 'precision', 'precision_weighted', 'precision_macro', 'precision_micro', 'recall', 'recall_weighted', 'recall_macro', 'recall_micro', 'log_loss', 'adjusted_rand_score' # not really, but works ] MULTILABEL_ONLY_SCORERS = ['precision_samples', 'recall_samples', 'f1_samples'] class EstimatorWithoutFit(object): """Dummy estimator to test check_scoring""" pass class EstimatorWithFit(BaseEstimator): """Dummy estimator to test check_scoring""" def fit(self, X, y): return self class EstimatorWithFitAndScore(object): """Dummy estimator to test check_scoring""" def fit(self, X, y): return self def score(self, X, y): return 1.0 class EstimatorWithFitAndPredict(object): """Dummy estimator to test check_scoring""" def fit(self, X, y): self.y = y return self def predict(self, X): return self.y class DummyScorer(object): """Dummy scorer that always returns 1.""" def __call__(self, est, X, y): return 1 def test_check_scoring(): """Test all branches of check_scoring""" estimator = EstimatorWithoutFit() pattern = (r"estimator should a be an estimator implementing 'fit' method," r" .* was passed") assert_raises_regexp(TypeError, pattern, check_scoring, estimator) estimator = EstimatorWithFitAndScore() estimator.fit([[1]], [1]) scorer = check_scoring(estimator) assert_true(scorer is _passthrough_scorer) assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFitAndPredict() estimator.fit([[1]], [1]) pattern = (r"If no scoring is specified, the estimator passed should have" r" a 'score' method\. The estimator .* does not\.") assert_raises_regexp(TypeError, pattern, check_scoring, estimator) scorer = check_scoring(estimator, "accuracy") assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFit() scorer = check_scoring(estimator, "accuracy") assert_true(isinstance(scorer, _PredictScorer)) estimator = EstimatorWithFit() scorer = check_scoring(estimator, allow_none=True) assert_true(scorer is None) def test_check_scoring_gridsearchcv(): # test that check_scoring works on GridSearchCV and pipeline. # slightly redundant non-regression test. grid = GridSearchCV(LinearSVC(), param_grid={'C': [.1, 1]}) scorer = check_scoring(grid, "f1") assert_true(isinstance(scorer, _PredictScorer)) pipe = make_pipeline(LinearSVC()) scorer = check_scoring(pipe, "f1") assert_true(isinstance(scorer, _PredictScorer)) # check that cross_val_score definitely calls the scorer # and doesn't make any assumptions about the estimator apart from having a # fit. scores = cross_val_score(EstimatorWithFit(), [[1], [2], [3]], [1, 0, 1], scoring=DummyScorer()) assert_array_equal(scores, 1) def test_make_scorer(): """Sanity check on the make_scorer factory function.""" f = lambda *args: 0 assert_raises(ValueError, make_scorer, f, needs_threshold=True, needs_proba=True) def test_classification_scores(): """Test classification scorers.""" X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LinearSVC(random_state=0) clf.fit(X_train, y_train) for prefix, metric in [('f1', f1_score), ('precision', precision_score), ('recall', recall_score)]: score1 = get_scorer('%s_weighted' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='weighted') assert_almost_equal(score1, score2) score1 = get_scorer('%s_macro' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='macro') assert_almost_equal(score1, score2) score1 = get_scorer('%s_micro' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='micro') assert_almost_equal(score1, score2) score1 = get_scorer('%s' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=1) assert_almost_equal(score1, score2) # test fbeta score that takes an argument scorer = make_scorer(fbeta_score, beta=2) score1 = scorer(clf, X_test, y_test) score2 = fbeta_score(y_test, clf.predict(X_test), beta=2) assert_almost_equal(score1, score2) # test that custom scorer can be pickled unpickled_scorer = pickle.loads(pickle.dumps(scorer)) score3 = unpickled_scorer(clf, X_test, y_test) assert_almost_equal(score1, score3) # smoke test the repr: repr(fbeta_score) def test_regression_scorers(): """Test regression scorers.""" diabetes = load_diabetes() X, y = diabetes.data, diabetes.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = Ridge() clf.fit(X_train, y_train) score1 = get_scorer('r2')(clf, X_test, y_test) score2 = r2_score(y_test, clf.predict(X_test)) assert_almost_equal(score1, score2) def test_thresholded_scorers(): """Test scorers that take thresholds.""" X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LogisticRegression(random_state=0) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) score3 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2) assert_almost_equal(score1, score3) logscore = get_scorer('log_loss')(clf, X_test, y_test) logloss = log_loss(y_test, clf.predict_proba(X_test)) assert_almost_equal(-logscore, logloss) # same for an estimator without decision_function clf = DecisionTreeClassifier() clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2) # Test that an exception is raised on more than two classes X, y = make_blobs(random_state=0, centers=3) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf.fit(X_train, y_train) assert_raises(ValueError, get_scorer('roc_auc'), clf, X_test, y_test) def test_thresholded_scorers_multilabel_indicator_data(): """Test that the scorer work with multilabel-indicator format for multilabel and multi-output multi-class classifier """ X, y = make_multilabel_classification(return_indicator=True, allow_unlabeled=False, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) # Multi-output multi-class predict_proba clf = DecisionTreeClassifier() clf.fit(X_train, y_train) y_proba = clf.predict_proba(X_test) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack(p[:, -1] for p in y_proba).T) assert_almost_equal(score1, score2) # Multi-output multi-class decision_function # TODO Is there any yet? clf = DecisionTreeClassifier() clf.fit(X_train, y_train) clf._predict_proba = clf.predict_proba clf.predict_proba = None clf.decision_function = lambda X: [p[:, 1] for p in clf._predict_proba(X)] y_proba = clf.decision_function(X_test) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack(p for p in y_proba).T) assert_almost_equal(score1, score2) # Multilabel predict_proba clf = OneVsRestClassifier(DecisionTreeClassifier()) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)) assert_almost_equal(score1, score2) # Multilabel decision function clf = OneVsRestClassifier(LinearSVC(random_state=0)) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) assert_almost_equal(score1, score2) def test_unsupervised_scorers(): """Test clustering scorers against gold standard labeling.""" # We don't have any real unsupervised Scorers yet. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) km = KMeans(n_clusters=3) km.fit(X_train) score1 = get_scorer('adjusted_rand_score')(km, X_test, y_test) score2 = adjusted_rand_score(y_test, km.predict(X_test)) assert_almost_equal(score1, score2) @ignore_warnings def test_raises_on_score_list(): """Test that when a list of scores is returned, we raise proper errors.""" X, y = make_blobs(random_state=0) f1_scorer_no_average = make_scorer(f1_score, average=None) clf = DecisionTreeClassifier() assert_raises(ValueError, cross_val_score, clf, X, y, scoring=f1_scorer_no_average) grid_search = GridSearchCV(clf, scoring=f1_scorer_no_average, param_grid={'max_depth': [1, 2]}) assert_raises(ValueError, grid_search.fit, X, y) @ignore_warnings def test_scorer_sample_weight(): """Test that scorers support sample_weight or raise sensible errors""" # Unlike the metrics invariance test, in the scorer case it's harder # to ensure that, on the classifier output, weighted and unweighted # scores really should be unequal. X, y = make_classification(random_state=0) _, y_ml = make_multilabel_classification(n_samples=X.shape[0], return_indicator=True, random_state=0) split = train_test_split(X, y, y_ml, random_state=0) X_train, X_test, y_train, y_test, y_ml_train, y_ml_test = split sample_weight = np.ones_like(y_test) sample_weight[:10] = 0 # get sensible estimators for each metric sensible_regr = DummyRegressor(strategy='median') sensible_regr.fit(X_train, y_train) sensible_clf = DecisionTreeClassifier(random_state=0) sensible_clf.fit(X_train, y_train) sensible_ml_clf = DecisionTreeClassifier(random_state=0) sensible_ml_clf.fit(X_train, y_ml_train) estimator = dict([(name, sensible_regr) for name in REGRESSION_SCORERS] + [(name, sensible_clf) for name in CLF_SCORERS] + [(name, sensible_ml_clf) for name in MULTILABEL_ONLY_SCORERS]) for name, scorer in SCORERS.items(): if name in MULTILABEL_ONLY_SCORERS: target = y_ml_test else: target = y_test try: weighted = scorer(estimator[name], X_test, target, sample_weight=sample_weight) ignored = scorer(estimator[name], X_test[10:], target[10:]) unweighted = scorer(estimator[name], X_test, target) assert_not_equal(weighted, unweighted, msg="scorer {0} behaves identically when " "called with sample weights: {1} vs " "{2}".format(name, weighted, unweighted)) assert_almost_equal(weighted, ignored, err_msg="scorer {0} behaves differently when " "ignoring samples and setting sample_weight to" " 0: {1} vs {2}".format(name, weighted, ignored)) except TypeError as e: assert_true("sample_weight" in str(e), "scorer {0} raises unhelpful exception when called " "with sample weights: {1}".format(name, str(e)))
bsd-3-clause
laszlocsomor/tensorflow
tensorflow/examples/tutorials/input_fn/boston.py
76
2920
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """DNNRegressor with custom input_fn for Housing dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import pandas as pd import tensorflow as tf tf.logging.set_verbosity(tf.logging.INFO) COLUMNS = ["crim", "zn", "indus", "nox", "rm", "age", "dis", "tax", "ptratio", "medv"] FEATURES = ["crim", "zn", "indus", "nox", "rm", "age", "dis", "tax", "ptratio"] LABEL = "medv" def get_input_fn(data_set, num_epochs=None, shuffle=True): return tf.estimator.inputs.pandas_input_fn( x=pd.DataFrame({k: data_set[k].values for k in FEATURES}), y=pd.Series(data_set[LABEL].values), num_epochs=num_epochs, shuffle=shuffle) def main(unused_argv): # Load datasets training_set = pd.read_csv("boston_train.csv", skipinitialspace=True, skiprows=1, names=COLUMNS) test_set = pd.read_csv("boston_test.csv", skipinitialspace=True, skiprows=1, names=COLUMNS) # Set of 6 examples for which to predict median house values prediction_set = pd.read_csv("boston_predict.csv", skipinitialspace=True, skiprows=1, names=COLUMNS) # Feature cols feature_cols = [tf.feature_column.numeric_column(k) for k in FEATURES] # Build 2 layer fully connected DNN with 10, 10 units respectively. regressor = tf.estimator.DNNRegressor(feature_columns=feature_cols, hidden_units=[10, 10], model_dir="/tmp/boston_model") # Train regressor.train(input_fn=get_input_fn(training_set), steps=5000) # Evaluate loss over one epoch of test_set. ev = regressor.evaluate( input_fn=get_input_fn(test_set, num_epochs=1, shuffle=False)) loss_score = ev["loss"] print("Loss: {0:f}".format(loss_score)) # Print out predictions over a slice of prediction_set. y = regressor.predict( input_fn=get_input_fn(prediction_set, num_epochs=1, shuffle=False)) # .predict() returns an iterator of dicts; convert to a list and print # predictions predictions = list(p["predictions"] for p in itertools.islice(y, 6)) print("Predictions: {}".format(str(predictions))) if __name__ == "__main__": tf.app.run()
apache-2.0
empirical-org/WikipediaSentences
notebooks/BERT-4 Experiments Multilabel.py
1
19268
#!/usr/bin/env python # coding: utf-8 # # Multilabel BERT Experiments # # In this notebook we do some first experiments with BERT: we finetune a BERT model+classifier on each of our datasets separately and compute the accuracy of the resulting classifier on the test data. # For these experiments we use the `pytorch_transformers` package. It contains a variety of neural network architectures for transfer learning and pretrained models, including BERT and XLNET. # # Two different BERT models are relevant for our experiments: # # - BERT-base-uncased: a relatively small BERT model that should already give reasonable results, # - BERT-large-uncased: a larger model for real state-of-the-art results. # In[1]: from multilabel import EATINGMEAT_BECAUSE_MAP, EATINGMEAT_BUT_MAP, JUNKFOOD_BECAUSE_MAP, JUNKFOOD_BUT_MAP label_map = EATINGMEAT_BECAUSE_MAP # In[2]: import torch from pytorch_transformers.tokenization_bert import BertTokenizer from pytorch_transformers.modeling_bert import BertForSequenceClassification BERT_MODEL = 'bert-large-uncased' BATCH_SIZE = 16 if "base" in BERT_MODEL else 2 GRADIENT_ACCUMULATION_STEPS = 1 if "base" in BERT_MODEL else 8 tokenizer = BertTokenizer.from_pretrained(BERT_MODEL) # ## Data # # We use the same data as for all our previous experiments. Here we load the training, development and test data for a particular prompt. # In[3]: import ndjson import glob from collections import Counter prefix = "eatingmeat_because_xl" train_file = f"../data/interim/{prefix}_train_withprompt.ndjson" synth_files = glob.glob(f"../data/interim/{prefix}_train_withprompt_*.ndjson") dev_file = f"../data/interim/{prefix}_dev_withprompt.ndjson" test_file = f"../data/interim/{prefix}_test_withprompt.ndjson" with open(train_file) as i: train_data = ndjson.load(i) synth_data = [] for f in synth_files: if "allsynth" in f: continue with open(f) as i: synth_data += ndjson.load(i) with open(dev_file) as i: dev_data = ndjson.load(i) with open(test_file) as i: test_data = ndjson.load(i) labels = Counter([item["label"] for item in train_data]) print(labels) # Next, we build the label vocabulary, which maps every label in the training data to an index. # In[4]: label2idx = {} idx2label = {} target_names = [] for item in label_map: for label in label_map[item]: if label not in target_names: idx = len(target_names) target_names.append(label) label2idx[label] = idx idx2label[idx] = label print(label2idx) print(idx2label) # In[5]: def map_to_multilabel(items): return [{"text": item["text"], "label": label_map[item["label"]]} for item in items] train_data = map_to_multilabel(train_data) dev_data = map_to_multilabel(dev_data) test_data = map_to_multilabel(test_data) # In[6]: import random def sample(train_data, synth_data, label2idx, number): """Sample a fixed number of items from every label from the training data and test data. """ new_train_data = [] for label in label2idx: data_for_label = [i for i in train_data if i["label"] == label] # If there is more training data than the required number, # take a random sample of n examples from the training data. if len(data_for_label) >= number: random.shuffle(data_for_label) new_train_data += data_for_label[:number] # If there is less training data than the required number, # combine training data with synthetic data. elif len(data_for_label) < number: # Automatically add all training data new_train_data += data_for_label # Compute the required number of additional data rest = number-len(data_for_label) # Collect the synthetic data for the label synth_data_for_label = [i for i in synth_data if i["label"] == label] # If there is more synthetic data than required, # take a random sample from the synthetic data. if len(synth_data_for_label) > rest: random.shuffle(synth_data_for_label) new_train_data += synth_data_for_label[:rest] # If there is less synthetic data than required, # sample with replacement from this data until we have # the required number. else: new_train_data += random.choices(synth_data_for_label, k=rest) return new_train_data def random_sample(train_data, train_size): random.shuffle(train_data) train_data = train_data[:TRAIN_SIZE] #train_data = sample(train_data, synth_data, label2idx, 200) print("Train data size:", len(train_data)) # ## Model # # We load the pretrained model and put it on a GPU if one is available. We also put the model in "training" mode, so that we can correctly update its internal parameters on the basis of our data sets. # In[7]: from torch import nn from pytorch_transformers.modeling_bert import BertPreTrainedModel, BertModel class BertForMultiLabelSequenceClassification(BertPreTrainedModel): r""" **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``: Labels for computing the sequence classification/regression loss. Indices should be in ``[0, ..., config.num_labels - 1]``. If ``config.num_labels == 1`` a regression loss is computed (Mean-Square loss), If ``config.num_labels > 1`` a classification loss is computed (Cross-Entropy). Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: Classification (or regression if config.num_labels==1) loss. **logits**: ``torch.FloatTensor`` of shape ``(batch_size, config.num_labels)`` Classification (or regression if config.num_labels==1) scores (before SoftMax). **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``) list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings) of shape ``(batch_size, sequence_length, hidden_size)``: Hidden-states of the model at the output of each layer plus the initial embedding outputs. **attentions**: (`optional`, returned when ``config.output_attentions=True``) list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``: Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Examples:: tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertForSequenceClassification.from_pretrained('bert-base-uncased') input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 outputs = model(input_ids, labels=labels) loss, logits = outputs[:2] """ def __init__(self, config): super(BertForMultiLabelSequenceClassification, self).__init__(config) self.num_labels = config.num_labels self.bert = BertModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, self.config.num_labels) self.apply(self.init_weights) def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None, position_ids=None, head_mask=None): outputs = self.bert(input_ids, position_ids=position_ids, token_type_ids=token_type_ids, attention_mask=attention_mask, head_mask=head_mask) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here if labels is not None: loss_fct = nn.BCEWithLogitsLoss() loss = loss_fct(logits, labels) outputs = (loss,) + outputs return outputs # (loss), logits, (hidden_states), (attentions) # In[8]: model = BertForMultiLabelSequenceClassification.from_pretrained(BERT_MODEL, num_labels=len(label2idx)) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) model.train() # ## Preprocessing # # We preprocess the data by turning every example to an `InputFeatures` item. This item has all the attributes we need for finetuning BERT: # # - input ids: the ids of the tokens in the text # - input mask: tells BERT what part of the input it should not look at (such as padding tokens) # - segment ids: tells BERT what segment every token belongs to. BERT can take two different segments as input # - label id: the id of this item's label # In[ ]: import logging import numpy as np logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt = '%m/%d/%Y %H:%M:%S', level = logging.INFO) logger = logging.getLogger(__name__) MAX_SEQ_LENGTH=100 class InputFeatures(object): """A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids, label_ids): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.label_ids = label_ids def convert_examples_to_features(examples, label2idx, max_seq_length, tokenizer, verbose=0): """Loads a data file into a list of `InputBatch`s.""" features = [] for (ex_index, ex) in enumerate(examples): # TODO: should deal better with sentences > max tok length input_ids = tokenizer.encode("[CLS] " + ex["text"] + " [SEP]") segment_ids = [0] * len(input_ids) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. input_mask = [1] * len(input_ids) # Zero-pad up to the sequence length. padding = [0] * (max_seq_length - len(input_ids)) input_ids += padding input_mask += padding segment_ids += padding assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length label_ids = np.zeros(len(label2idx)) for label in ex["label"]: label_ids[label2idx[label]] = 1 if verbose and ex_index == 0: logger.info("*** Example ***") logger.info("text: %s" % ex["text"]) logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids])) logger.info("input_mask: %s" % " ".join([str(x) for x in input_mask])) logger.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids])) logger.info("label:" + str(ex["label"]) + " id: " + str(label_ids)) features.append( InputFeatures(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_ids=label_ids)) return features train_features = convert_examples_to_features(train_data, label2idx, MAX_SEQ_LENGTH, tokenizer, verbose=0) dev_features = convert_examples_to_features(dev_data, label2idx, MAX_SEQ_LENGTH, tokenizer) test_features = convert_examples_to_features(test_data, label2idx, MAX_SEQ_LENGTH, tokenizer, verbose=1) # Next, we initialize data loaders for each of our data sets. These data loaders present the data for training (for example, by grouping them into batches). # In[ ]: import torch from torch.utils.data import TensorDataset, DataLoader, RandomSampler def get_data_loader(features, max_seq_length, batch_size, shuffle=True): all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) all_segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long) all_label_ids = torch.tensor([f.label_ids for f in features], dtype=torch.float) data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids) dataloader = DataLoader(data, shuffle=shuffle, batch_size=batch_size) return dataloader train_dataloader = get_data_loader(train_features, MAX_SEQ_LENGTH, BATCH_SIZE) dev_dataloader = get_data_loader(dev_features, MAX_SEQ_LENGTH, BATCH_SIZE) test_dataloader = get_data_loader(test_features, MAX_SEQ_LENGTH, BATCH_SIZE, shuffle=False) # ## Evaluation # # Our evaluation method takes a pretrained model and a dataloader. It has the model predict the labels for the items in the data loader, and returns the loss, the correct labels, and the predicted labels. # In[ ]: from torch.nn import Sigmoid def evaluate(model, dataloader, verbose=False): eval_loss = 0 nb_eval_steps = 0 predicted_labels, correct_labels = [], [] for step, batch in enumerate(tqdm(dataloader, desc="Evaluation iteration")): batch = tuple(t.to(device) for t in batch) input_ids, input_mask, segment_ids, label_ids = batch with torch.no_grad(): tmp_eval_loss, logits = model(input_ids, segment_ids, input_mask, label_ids) sig = Sigmoid() outputs = sig(logits).to('cpu').numpy() label_ids = label_ids.to('cpu').numpy() predicted_labels += list(outputs >= 0.5) correct_labels += list(label_ids) eval_loss += tmp_eval_loss.mean().item() nb_eval_steps += 1 eval_loss = eval_loss / nb_eval_steps correct_labels = np.array(correct_labels) predicted_labels = np.array(predicted_labels) return eval_loss, correct_labels, predicted_labels # ## Training # # Let's prepare the training. We set the training parameters and choose an optimizer and learning rate scheduler. # In[ ]: from pytorch_transformers.optimization import AdamW, WarmupLinearSchedule NUM_TRAIN_EPOCHS = 20 LEARNING_RATE = 1e-5 WARMUP_PROPORTION = 0.1 def warmup_linear(x, warmup=0.002): if x < warmup: return x/warmup return 1.0 - x num_train_steps = int(len(train_data) / BATCH_SIZE / GRADIENT_ACCUMULATION_STEPS * NUM_TRAIN_EPOCHS) param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01}, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] optimizer = AdamW(optimizer_grouped_parameters, lr=LEARNING_RATE, correct_bias=False) scheduler = WarmupLinearSchedule(optimizer, warmup_steps=100, t_total=num_train_steps) # Now we do the actual training. In each epoch, we present the model with all training data and compute the loss on the training set and the development set. We save the model whenever the development loss improves. We end training when we haven't seen an improvement of the development loss for a specific number of epochs (the patience). # # Optionally, we use gradient accumulation to accumulate the gradient for several training steps. This is useful when we want to use a larger batch size than our current GPU allows us to do. # In[ ]: import os from tqdm import trange from tqdm import tqdm from sklearn.metrics import classification_report, precision_recall_fscore_support OUTPUT_DIR = "/tmp/" MODEL_FILE_NAME = "pytorch_model.bin" PATIENCE = 5 global_step = 0 model.train() loss_history = [] best_epoch = 0 for epoch in trange(int(NUM_TRAIN_EPOCHS), desc="Epoch"): tr_loss = 0 nb_tr_examples, nb_tr_steps = 0, 0 for step, batch in enumerate(tqdm(train_dataloader, desc="Training iteration")): batch = tuple(t.to(device) for t in batch) input_ids, input_mask, segment_ids, label_ids = batch outputs = model(input_ids, segment_ids, input_mask, label_ids) loss = outputs[0] if GRADIENT_ACCUMULATION_STEPS > 1: loss = loss / GRADIENT_ACCUMULATION_STEPS loss.backward() tr_loss += loss.item() nb_tr_examples += input_ids.size(0) nb_tr_steps += 1 if (step + 1) % GRADIENT_ACCUMULATION_STEPS == 0: lr_this_step = LEARNING_RATE * warmup_linear(global_step/num_train_steps, WARMUP_PROPORTION) for param_group in optimizer.param_groups: param_group['lr'] = lr_this_step optimizer.step() optimizer.zero_grad() global_step += 1 dev_loss, _, _ = evaluate(model, dev_dataloader) print("Loss history:", loss_history) print("Dev loss:", dev_loss) if len(loss_history) == 0 or dev_loss < min(loss_history): model_to_save = model.module if hasattr(model, 'module') else model output_model_file = os.path.join(OUTPUT_DIR, MODEL_FILE_NAME) torch.save(model_to_save.state_dict(), output_model_file) best_epoch = epoch if epoch-best_epoch >= PATIENCE: print("No improvement on development set. Finish training.") break loss_history.append(dev_loss) # ## Results # # We load the pretrained model, set it to evaluation mode and compute its performance on the training, development and test set. We print out an evaluation report for the test set. # # Note that different runs will give slightly different results. # In[ ]: from tqdm import tqdm_notebook as tqdm output_model_file = "/tmp/pytorch_model.bin" print("Loading model from", output_model_file) device="cpu" model_state_dict = torch.load(output_model_file, map_location=lambda storage, loc: storage) model = BertForMultiLabelSequenceClassification.from_pretrained(BERT_MODEL, state_dict=model_state_dict, num_labels=len(label2idx)) model.to(device) model.eval() _, test_correct, test_predicted = evaluate(model, test_dataloader, verbose=True) # In[ ]: all_correct = 0 fp, fn, tp, tn = 0, 0, 0, 0 for c, p in zip(test_correct, test_predicted): if sum(c == p) == len(c): all_correct +=1 for ci, pi in zip(c, p): if pi == 1 and ci == 1: tp += 1 same = 1 elif pi == 1 and ci == 0: fp += 1 elif pi == 0 and ci == 1: fn += 1 else: tn += 1 same =1 precision = tp/(tp+fp) recall = tp/(tp+fn) print("P:", precision) print("R:", recall) print("A:", all_correct/len(test_correct)) # In[ ]: for item, predicted, correct in zip(test_data, test_predicted, test_correct): correct_labels = [idx2label[i] for i, l in enumerate(correct) if l == 1] predicted_labels = [idx2label[i] for i, l in enumerate(predicted) if l == 1] print("{}#{}#{}".format(item["text"], ";".join(correct_labels), ";".join(predicted_labels))) # In[ ]:
agpl-3.0
antlr/codebuff
python/src/tsql_noisy_one_file_capture.py
1
3111
# # AUTO-GENERATED FILE. DO NOT EDIT # CodeBuff 1.4.19 'Sat Jun 18 16:50:22 PDT 2016' # import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = plt.subplot(111) labels = ["backupset_queries.sql", "buffer_pool_usage_by_db.sql", "compare_db_powershell.sql", "compare_tables.sql", "create_columnlist.sql", "database_execute_permissions.sql", "daysCTE.sql", "dmart_bits.sql", "dmart_bits_IAPPBO510.sql", "dmart_bits_PSQLRPT24.sql", "DriveSpace.sql", "enum_permissions.sql", "ex_CTEExample.sql", "ex_GROUPBY.sql", "ex_SUMbyColumn.sql", "filegroup_location_per_object.sql", "Generate_Weekly_Perfmon.sql", "index_bits.sql", "ipmonitor_notes.sql", "IPMonVerificationMaster.sql", "OrphanedUserCleanup_bits.sql", "ProgressQueries.sql", "project_status.sql", "RealECOrdersBy30days.sql", "role_details.sql", "sel_DeadLinkedServers.sql", "server_correlate.sql", "sprocswithservernames_bits.sql", "SQLErrorLogs_queries.sql", "SQLFilesAudit.sql", "SQLQuery23.sql", "SQLSpaceStats_bits.sql", "SQLStatsQueries.sql", "t_component_bits.sql", "table_info.sql", "vwTableInfo.sql"] N = len(labels) featureIndexes = range(0,N) tsql_noisy_self = [0.076227985, 0.050177395, 0.11878453, 0.02, 0.011173184, 0.17552336, 0.010526316, 0.028654816, 0.050495468, 0.09415402, 0.05640423, 0.045490824, 0.00790798, 0.03748126, 0.13157895, 0.1565762, 0.032279316, 0.07828173, 0.059966013, 0.026165765, 0.07442748, 0.10529519, 0.12922297, 0.089143865, 0.05014245, 0.01509434, 0.022739017, 0.03258427, 0.112651646, 0.09617138, 0.07216722, 0.09363118, 0.03537234, 0.012289658, 0.28449047, 0.04287046] tsql_noisy_corpus = [0.08400097, 0.105207786, 0.12039595, 0.016949153, 0.06703911, 0.18035427, 0.31681034, 0.06707472, 0.05935062, 0.1066142, 0.055229142, 0.10428016, 0.023005033, 0.13868067, 0.257329, 0.2526096, 0.09486166, 0.1001306, 0.06457878, 0.058658116, 0.114503816, 0.057212416, 0.1714527, 0.18038237, 0.09441341, 0.035849057, 0.08885616, 0.030998852, 0.28156027, 0.18732908, 0.09658966, 0.25, 0.14528553, 0.078667864, 0.3151883, 0.08043956] tsql_noisy_diff = np.abs(np.subtract(tsql_noisy_self, tsql_noisy_corpus)) all = zip(tsql_noisy_self, tsql_noisy_corpus, tsql_noisy_diff, labels) all = sorted(all, key=lambda x : x[2], reverse=True) tsql_noisy_self, tsql_noisy_corpus, tsql_noisy_diff, labels = zip(*all) ax.plot(featureIndexes, tsql_noisy_self, label="tsql_noisy_self") #ax.plot(featureIndexes, tsql_noisy_corpus, label="tsql_noisy_corpus") ax.plot(featureIndexes, tsql_noisy_diff, label="tsql_noisy_diff") ax.set_xticklabels(labels, rotation=60, fontsize=8) plt.xticks(featureIndexes, labels, rotation=60) ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5) ax.text(1, .25, 'median $f$ self distance = %5.3f, corpus+$f$ distance = %5.3f' % (np.median(tsql_noisy_self),np.median(tsql_noisy_corpus))) ax.set_xlabel("File Name") ax.set_ylabel("Edit Distance") ax.set_title("Difference between Formatting File tsql_noisy $f$\nwith Training=$f$ and Training=$f$+Corpus") plt.legend() plt.tight_layout() fig.savefig("images/tsql_noisy_one_file_capture.pdf", format='pdf') plt.show()
bsd-2-clause
Jozhogg/iris
docs/iris/example_code/General/SOI_filtering.py
6
3050
""" Applying a filter to a time-series ================================== This example demonstrates low pass filtering a time-series by applying a weighted running mean over the time dimension. The time-series used is the Darwin-only Southern Oscillation index (SOI), which is filtered using two different Lanczos filters, one to filter out time-scales of less than two years and one to filter out time-scales of less than 7 years. References ---------- Duchon C. E. (1979) Lanczos Filtering in One and Two Dimensions. Journal of Applied Meteorology, Vol 18, pp 1016-1022. Trenberth K. E. (1984) Signal Versus Noise in the Southern Oscillation. Monthly Weather Review, Vol 112, pp 326-332 """ import numpy as np import matplotlib.pyplot as plt import iris import iris.plot as iplt def low_pass_weights(window, cutoff): """Calculate weights for a low pass Lanczos filter. Args: window: int The length of the filter window. cutoff: float The cutoff frequency in inverse time steps. """ order = ((window - 1) // 2 ) + 1 nwts = 2 * order + 1 w = np.zeros([nwts]) n = nwts // 2 w[n] = 2 * cutoff k = np.arange(1., n) sigma = np.sin(np.pi * k / n) * n / (np.pi * k) firstfactor = np.sin(2. * np.pi * cutoff * k) / (np.pi * k) w[n-1:0:-1] = firstfactor * sigma w[n+1:-1] = firstfactor * sigma return w[1:-1] def main(): # Load the monthly-valued Southern Oscillation Index (SOI) time-series. fname = iris.sample_data_path('SOI_Darwin.nc') soi = iris.load_cube(fname) # Window length for filters. window = 121 # Construct 2-year (24-month) and 7-year (84-month) low pass filters # for the SOI data which is monthly. wgts24 = low_pass_weights(window, 1. / 24.) wgts84 = low_pass_weights(window, 1. / 84.) # Apply each filter using the rolling_window method used with the weights # keyword argument. A weighted sum is required because the magnitude of # the weights are just as important as their relative sizes. soi24 = soi.rolling_window('time', iris.analysis.SUM, len(wgts24), weights=wgts24) soi84 = soi.rolling_window('time', iris.analysis.SUM, len(wgts84), weights=wgts84) # Plot the SOI time series and both filtered versions. plt.figure(figsize=(9, 4)) iplt.plot(soi, color='0.7', linewidth=1., linestyle='-', alpha=1., label='no filter') iplt.plot(soi24, color='b', linewidth=2., linestyle='-', alpha=.7, label='2-year filter') iplt.plot(soi84, color='r', linewidth=2., linestyle='-', alpha=.7, label='7-year filter') plt.ylim([-4, 4]) plt.title('Southern Oscillation Index (Darwin Only)') plt.xlabel('Time') plt.ylabel('SOI') plt.legend(fontsize=10) iplt.show() if __name__ == '__main__': main()
lgpl-3.0
victorfsf/eva
setup.py
1
1454
# -*- coding: utf-8 -*- from setuptools import setup from setuptools import find_packages version = '0.0.1' setup( name='eva', packages=find_packages(exclude=['tests']), package_data={ 'eva': [], }, install_requires=[ 'nltk==3.2.4', 'numpy==1.12.1', 'pandas==0.20.1', 'python-crfsuite==0.9.2', 'regex==2017.5.26', 'scikit-learn==0.18.1', 'scipy==0.19.0', 'boltons==17.1.0', 'requests==2.18.1' ], zip_safe=False, version=version, description='Chatbot EVA', author='Victor Ferraz', author_email='vfsf@cin.ufpe.br', url='https://github.com/victorfsf/eva', keywords=[ 'eva', 'nlp', 'ml', 'ai', 'natural language processing', 'machine learning', 'artificial intelligence', 'chatbot', 'chat', 'chatter', 'chatterbot', 'virtual assistant', 'python3', ], classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Natural Language :: Portuguese (Brazilian)', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
gpl-3.0
lenovor/scikit-learn
sklearn/ensemble/tests/test_voting_classifier.py
40
6991
"""Testing for the boost module (sklearn.ensemble.boost).""" import numpy as np from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_equal from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import VotingClassifier from sklearn.grid_search import GridSearchCV from sklearn import datasets from sklearn import cross_validation from sklearn.datasets import make_multilabel_classification from sklearn.svm import SVC from sklearn.multiclass import OneVsRestClassifier # Load the iris dataset and randomly permute it iris = datasets.load_iris() X, y = iris.data[:, 1:3], iris.target def test_majority_label_iris(): """Check classification by majority label on dataset iris.""" clf1 = LogisticRegression(random_state=123) clf2 = RandomForestClassifier(random_state=123) clf3 = GaussianNB() eclf = VotingClassifier(estimators=[ ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard') scores = cross_validation.cross_val_score(eclf, X, y, cv=5, scoring='accuracy') assert_almost_equal(scores.mean(), 0.95, decimal=2) def test_tie_situation(): """Check voting classifier selects smaller class label in tie situation.""" clf1 = LogisticRegression(random_state=123) clf2 = RandomForestClassifier(random_state=123) eclf = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2)], voting='hard') assert_equal(clf1.fit(X, y).predict(X)[73], 2) assert_equal(clf2.fit(X, y).predict(X)[73], 1) assert_equal(eclf.fit(X, y).predict(X)[73], 1) def test_weights_iris(): """Check classification by average probabilities on dataset iris.""" clf1 = LogisticRegression(random_state=123) clf2 = RandomForestClassifier(random_state=123) clf3 = GaussianNB() eclf = VotingClassifier(estimators=[ ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='soft', weights=[1, 2, 10]) scores = cross_validation.cross_val_score(eclf, X, y, cv=5, scoring='accuracy') assert_almost_equal(scores.mean(), 0.93, decimal=2) def test_predict_on_toy_problem(): """Manually check predicted class labels for toy dataset.""" clf1 = LogisticRegression(random_state=123) clf2 = RandomForestClassifier(random_state=123) clf3 = GaussianNB() X = np.array([[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2], [2.1, 1.4], [3.1, 2.3]]) y = np.array([1, 1, 1, 2, 2, 2]) assert_equal(all(clf1.fit(X, y).predict(X)), all([1, 1, 1, 2, 2, 2])) assert_equal(all(clf2.fit(X, y).predict(X)), all([1, 1, 1, 2, 2, 2])) assert_equal(all(clf3.fit(X, y).predict(X)), all([1, 1, 1, 2, 2, 2])) eclf = VotingClassifier(estimators=[ ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard', weights=[1, 1, 1]) assert_equal(all(eclf.fit(X, y).predict(X)), all([1, 1, 1, 2, 2, 2])) eclf = VotingClassifier(estimators=[ ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='soft', weights=[1, 1, 1]) assert_equal(all(eclf.fit(X, y).predict(X)), all([1, 1, 1, 2, 2, 2])) def test_predict_proba_on_toy_problem(): """Calculate predicted probabilities on toy dataset.""" clf1 = LogisticRegression(random_state=123) clf2 = RandomForestClassifier(random_state=123) clf3 = GaussianNB() X = np.array([[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2]]) y = np.array([1, 1, 2, 2]) clf1_res = np.array([[0.59790391, 0.40209609], [0.57622162, 0.42377838], [0.50728456, 0.49271544], [0.40241774, 0.59758226]]) clf2_res = np.array([[0.8, 0.2], [0.8, 0.2], [0.2, 0.8], [0.3, 0.7]]) clf3_res = np.array([[0.9985082, 0.0014918], [0.99845843, 0.00154157], [0., 1.], [0., 1.]]) t00 = (2*clf1_res[0][0] + clf2_res[0][0] + clf3_res[0][0]) / 4 t11 = (2*clf1_res[1][1] + clf2_res[1][1] + clf3_res[1][1]) / 4 t21 = (2*clf1_res[2][1] + clf2_res[2][1] + clf3_res[2][1]) / 4 t31 = (2*clf1_res[3][1] + clf2_res[3][1] + clf3_res[3][1]) / 4 eclf = VotingClassifier(estimators=[ ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='soft', weights=[2, 1, 1]) eclf_res = eclf.fit(X, y).predict_proba(X) assert_almost_equal(t00, eclf_res[0][0], decimal=1) assert_almost_equal(t11, eclf_res[1][1], decimal=1) assert_almost_equal(t21, eclf_res[2][1], decimal=1) assert_almost_equal(t31, eclf_res[3][1], decimal=1) try: eclf = VotingClassifier(estimators=[ ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard') eclf.fit(X, y).predict_proba(X) except AttributeError: pass else: raise AssertionError('AttributeError for voting == "hard"' ' and with predict_proba not raised') def test_multilabel(): """Check if error is raised for multilabel classification.""" X, y = make_multilabel_classification(n_classes=2, n_labels=1, allow_unlabeled=False, return_indicator=True, random_state=123) clf = OneVsRestClassifier(SVC(kernel='linear')) eclf = VotingClassifier(estimators=[('ovr', clf)], voting='hard') try: eclf.fit(X, y) except NotImplementedError: return def test_gridsearch(): """Check GridSearch support.""" clf1 = LogisticRegression(random_state=1) clf2 = RandomForestClassifier(random_state=1) clf3 = GaussianNB() eclf = VotingClassifier(estimators=[ ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='soft') params = {'lr__C': [1.0, 100.0], 'voting': ['soft', 'hard'], 'weights': [[0.5, 0.5, 0.5], [1.0, 0.5, 0.5]]} grid = GridSearchCV(estimator=eclf, param_grid=params, cv=5) grid.fit(iris.data, iris.target)
bsd-3-clause
jjx02230808/project0223
examples/ensemble/plot_random_forest_embedding.py
286
3531
""" ========================================================= Hashing feature transformation using Totally Random Trees ========================================================= RandomTreesEmbedding provides a way to map data to a very high-dimensional, sparse representation, which might be beneficial for classification. The mapping is completely unsupervised and very efficient. This example visualizes the partitions given by several trees and shows how the transformation can also be used for non-linear dimensionality reduction or non-linear classification. Points that are neighboring often share the same leaf of a tree and therefore share large parts of their hashed representation. This allows to separate two concentric circles simply based on the principal components of the transformed data. In high-dimensional spaces, linear classifiers often achieve excellent accuracy. For sparse binary data, BernoulliNB is particularly well-suited. The bottom row compares the decision boundary obtained by BernoulliNB in the transformed space with an ExtraTreesClassifier forests learned on the original data. """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_circles from sklearn.ensemble import RandomTreesEmbedding, ExtraTreesClassifier from sklearn.decomposition import TruncatedSVD from sklearn.naive_bayes import BernoulliNB # make a synthetic dataset X, y = make_circles(factor=0.5, random_state=0, noise=0.05) # use RandomTreesEmbedding to transform data hasher = RandomTreesEmbedding(n_estimators=10, random_state=0, max_depth=3) X_transformed = hasher.fit_transform(X) # Visualize result using PCA pca = TruncatedSVD(n_components=2) X_reduced = pca.fit_transform(X_transformed) # Learn a Naive Bayes classifier on the transformed data nb = BernoulliNB() nb.fit(X_transformed, y) # Learn an ExtraTreesClassifier for comparison trees = ExtraTreesClassifier(max_depth=3, n_estimators=10, random_state=0) trees.fit(X, y) # scatter plot of original and reduced data fig = plt.figure(figsize=(9, 8)) ax = plt.subplot(221) ax.scatter(X[:, 0], X[:, 1], c=y, s=50) ax.set_title("Original Data (2d)") ax.set_xticks(()) ax.set_yticks(()) ax = plt.subplot(222) ax.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, s=50) ax.set_title("PCA reduction (2d) of transformed data (%dd)" % X_transformed.shape[1]) ax.set_xticks(()) ax.set_yticks(()) # Plot the decision in original space. For that, we will assign a color to each # point in the mesh [x_min, m_max] x [y_min, y_max]. h = .01 x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # transform grid using RandomTreesEmbedding transformed_grid = hasher.transform(np.c_[xx.ravel(), yy.ravel()]) y_grid_pred = nb.predict_proba(transformed_grid)[:, 1] ax = plt.subplot(223) ax.set_title("Naive Bayes on Transformed data") ax.pcolormesh(xx, yy, y_grid_pred.reshape(xx.shape)) ax.scatter(X[:, 0], X[:, 1], c=y, s=50) ax.set_ylim(-1.4, 1.4) ax.set_xlim(-1.4, 1.4) ax.set_xticks(()) ax.set_yticks(()) # transform grid using ExtraTreesClassifier y_grid_pred = trees.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1] ax = plt.subplot(224) ax.set_title("ExtraTrees predictions") ax.pcolormesh(xx, yy, y_grid_pred.reshape(xx.shape)) ax.scatter(X[:, 0], X[:, 1], c=y, s=50) ax.set_ylim(-1.4, 1.4) ax.set_xlim(-1.4, 1.4) ax.set_xticks(()) ax.set_yticks(()) plt.tight_layout() plt.show()
bsd-3-clause
costypetrisor/scikit-learn
sklearn/tree/tests/test_tree.py
72
47440
""" Testing for the tree module (sklearn.tree). """ import pickle from functools import partial from itertools import product import platform import numpy as np from scipy.sparse import csc_matrix from scipy.sparse import csr_matrix from scipy.sparse import coo_matrix from sklearn.random_projection import sparse_random_matrix from sklearn.metrics import accuracy_score from sklearn.metrics import mean_squared_error from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_in from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_greater_equal from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_true from sklearn.utils.testing import raises from sklearn.utils.validation import check_random_state from sklearn.utils.validation import NotFittedError from sklearn.tree import DecisionTreeClassifier from sklearn.tree import DecisionTreeRegressor from sklearn.tree import ExtraTreeClassifier from sklearn.tree import ExtraTreeRegressor from sklearn import tree from sklearn.tree.tree import SPARSE_SPLITTERS from sklearn.tree._tree import TREE_LEAF from sklearn import datasets from sklearn.preprocessing._weights import _balance_weights CLF_CRITERIONS = ("gini", "entropy") REG_CRITERIONS = ("mse", ) CLF_TREES = { "DecisionTreeClassifier": DecisionTreeClassifier, "Presort-DecisionTreeClassifier": partial(DecisionTreeClassifier, splitter="presort-best"), "ExtraTreeClassifier": ExtraTreeClassifier, } REG_TREES = { "DecisionTreeRegressor": DecisionTreeRegressor, "Presort-DecisionTreeRegressor": partial(DecisionTreeRegressor, splitter="presort-best"), "ExtraTreeRegressor": ExtraTreeRegressor, } ALL_TREES = dict() ALL_TREES.update(CLF_TREES) ALL_TREES.update(REG_TREES) SPARSE_TREES = [name for name, Tree in ALL_TREES.items() if Tree().splitter in SPARSE_SPLITTERS] X_small = np.array([ [0, 0, 4, 0, 0, 0, 1, -14, 0, -4, 0, 0, 0, 0, ], [0, 0, 5, 3, 0, -4, 0, 0, 1, -5, 0.2, 0, 4, 1, ], [-1, -1, 0, 0, -4.5, 0, 0, 2.1, 1, 0, 0, -4.5, 0, 1, ], [-1, -1, 0, -1.2, 0, 0, 0, 0, 0, 0, 0.2, 0, 0, 1, ], [-1, -1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, ], [-1, -2, 0, 4, -3, 10, 4, 0, -3.2, 0, 4, 3, -4, 1, ], [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -3, 1, ], [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1, ], [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1, ], [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -1, 0, ], [2, 8, 5, 1, 0.5, -4, 10, 0, 1, -5, 3, 0, 2, 0, ], [2, 0, 1, 1, 1, -1, 1, 0, 0, -2, 3, 0, 1, 0, ], [2, 0, 1, 2, 3, -1, 10, 2, 0, -1, 1, 2, 2, 0, ], [1, 1, 0, 2, 2, -1, 1, 2, 0, -5, 1, 2, 3, 0, ], [3, 1, 0, 3, 0, -4, 10, 0, 1, -5, 3, 0, 3, 1, ], [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 0.5, 0, -3, 1, ], [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 1.5, 1, -1, -1, ], [2.11, 8, -6, -0.5, 0, 10, 0, 0, -3.2, 6, 0.5, 0, -1, -1, ], [2, 0, 5, 1, 0.5, -2, 10, 0, 1, -5, 3, 1, 0, -1, ], [2, 0, 1, 1, 1, -2, 1, 0, 0, -2, 0, 0, 0, 1, ], [2, 1, 1, 1, 2, -1, 10, 2, 0, -1, 0, 2, 1, 1, ], [1, 1, 0, 0, 1, -3, 1, 2, 0, -5, 1, 2, 1, 1, ], [3, 1, 0, 1, 0, -4, 1, 0, 1, -2, 0, 0, 1, 0, ]]) y_small = [1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0] y_small_reg = [1.0, 2.1, 1.2, 0.05, 10, 2.4, 3.1, 1.01, 0.01, 2.98, 3.1, 1.1, 0.0, 1.2, 2, 11, 0, 0, 4.5, 0.201, 1.06, 0.9, 0] # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y = [-1, -1, -1, 1, 1, 1] T = [[-1, -1], [2, 2], [3, 2]] true_result = [-1, 1, 1] # also load the iris dataset # and randomly permute it iris = datasets.load_iris() rng = np.random.RandomState(1) perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] # also load the boston dataset # and randomly permute it boston = datasets.load_boston() perm = rng.permutation(boston.target.size) boston.data = boston.data[perm] boston.target = boston.target[perm] digits = datasets.load_digits() perm = rng.permutation(digits.target.size) digits.data = digits.data[perm] digits.target = digits.target[perm] random_state = check_random_state(0) X_multilabel, y_multilabel = datasets.make_multilabel_classification( random_state=0, return_indicator=True, n_samples=30, n_features=10) X_sparse_pos = random_state.uniform(size=(20, 5)) X_sparse_pos[X_sparse_pos <= 0.8] = 0. y_random = random_state.randint(0, 4, size=(20, )) X_sparse_mix = sparse_random_matrix(20, 10, density=0.25, random_state=0) DATASETS = { "iris": {"X": iris.data, "y": iris.target}, "boston": {"X": boston.data, "y": boston.target}, "digits": {"X": digits.data, "y": digits.target}, "toy": {"X": X, "y": y}, "clf_small": {"X": X_small, "y": y_small}, "reg_small": {"X": X_small, "y": y_small_reg}, "multilabel": {"X": X_multilabel, "y": y_multilabel}, "sparse-pos": {"X": X_sparse_pos, "y": y_random}, "sparse-neg": {"X": - X_sparse_pos, "y": y_random}, "sparse-mix": {"X": X_sparse_mix, "y": y_random}, "zeros": {"X": np.zeros((20, 3)), "y": y_random} } for name in DATASETS: DATASETS[name]["X_sparse"] = csc_matrix(DATASETS[name]["X"]) def assert_tree_equal(d, s, message): assert_equal(s.node_count, d.node_count, "{0}: inequal number of node ({1} != {2})" "".format(message, s.node_count, d.node_count)) assert_array_equal(d.children_right, s.children_right, message + ": inequal children_right") assert_array_equal(d.children_left, s.children_left, message + ": inequal children_left") external = d.children_right == TREE_LEAF internal = np.logical_not(external) assert_array_equal(d.feature[internal], s.feature[internal], message + ": inequal features") assert_array_equal(d.threshold[internal], s.threshold[internal], message + ": inequal threshold") assert_array_equal(d.n_node_samples.sum(), s.n_node_samples.sum(), message + ": inequal sum(n_node_samples)") assert_array_equal(d.n_node_samples, s.n_node_samples, message + ": inequal n_node_samples") assert_almost_equal(d.impurity, s.impurity, err_msg=message + ": inequal impurity") assert_array_almost_equal(d.value[external], s.value[external], err_msg=message + ": inequal value") def test_classification_toy(): # Check classification on a toy dataset. for name, Tree in CLF_TREES.items(): clf = Tree(random_state=0) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) clf = Tree(max_features=1, random_state=1) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) def test_weighted_classification_toy(): # Check classification on a weighted toy dataset. for name, Tree in CLF_TREES.items(): clf = Tree(random_state=0) clf.fit(X, y, sample_weight=np.ones(len(X))) assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) clf.fit(X, y, sample_weight=np.ones(len(X)) * 0.5) assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) def test_regression_toy(): # Check regression on a toy dataset. for name, Tree in REG_TREES.items(): reg = Tree(random_state=1) reg.fit(X, y) assert_almost_equal(reg.predict(T), true_result, err_msg="Failed with {0}".format(name)) clf = Tree(max_features=1, random_state=1) clf.fit(X, y) assert_almost_equal(reg.predict(T), true_result, err_msg="Failed with {0}".format(name)) def test_xor(): # Check on a XOR problem y = np.zeros((10, 10)) y[:5, :5] = 1 y[5:, 5:] = 1 gridx, gridy = np.indices(y.shape) X = np.vstack([gridx.ravel(), gridy.ravel()]).T y = y.ravel() for name, Tree in CLF_TREES.items(): clf = Tree(random_state=0) clf.fit(X, y) assert_equal(clf.score(X, y), 1.0, "Failed with {0}".format(name)) clf = Tree(random_state=0, max_features=1) clf.fit(X, y) assert_equal(clf.score(X, y), 1.0, "Failed with {0}".format(name)) def test_iris(): # Check consistency on dataset iris. for (name, Tree), criterion in product(CLF_TREES.items(), CLF_CRITERIONS): clf = Tree(criterion=criterion, random_state=0) clf.fit(iris.data, iris.target) score = accuracy_score(clf.predict(iris.data), iris.target) assert_greater(score, 0.9, "Failed with {0}, criterion = {1} and score = {2}" "".format(name, criterion, score)) clf = Tree(criterion=criterion, max_features=2, random_state=0) clf.fit(iris.data, iris.target) score = accuracy_score(clf.predict(iris.data), iris.target) assert_greater(score, 0.5, "Failed with {0}, criterion = {1} and score = {2}" "".format(name, criterion, score)) def test_boston(): # Check consistency on dataset boston house prices. for (name, Tree), criterion in product(REG_TREES.items(), REG_CRITERIONS): reg = Tree(criterion=criterion, random_state=0) reg.fit(boston.data, boston.target) score = mean_squared_error(boston.target, reg.predict(boston.data)) assert_less(score, 1, "Failed with {0}, criterion = {1} and score = {2}" "".format(name, criterion, score)) # using fewer features reduces the learning ability of this tree, # but reduces training time. reg = Tree(criterion=criterion, max_features=6, random_state=0) reg.fit(boston.data, boston.target) score = mean_squared_error(boston.target, reg.predict(boston.data)) assert_less(score, 2, "Failed with {0}, criterion = {1} and score = {2}" "".format(name, criterion, score)) def test_probability(): # Predict probabilities using DecisionTreeClassifier. for name, Tree in CLF_TREES.items(): clf = Tree(max_depth=1, max_features=1, random_state=42) clf.fit(iris.data, iris.target) prob_predict = clf.predict_proba(iris.data) assert_array_almost_equal(np.sum(prob_predict, 1), np.ones(iris.data.shape[0]), err_msg="Failed with {0}".format(name)) assert_array_equal(np.argmax(prob_predict, 1), clf.predict(iris.data), err_msg="Failed with {0}".format(name)) assert_almost_equal(clf.predict_proba(iris.data), np.exp(clf.predict_log_proba(iris.data)), 8, err_msg="Failed with {0}".format(name)) def test_arrayrepr(): # Check the array representation. # Check resize X = np.arange(10000)[:, np.newaxis] y = np.arange(10000) for name, Tree in REG_TREES.items(): reg = Tree(max_depth=None, random_state=0) reg.fit(X, y) def test_pure_set(): # Check when y is pure. X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y = [1, 1, 1, 1, 1, 1] for name, TreeClassifier in CLF_TREES.items(): clf = TreeClassifier(random_state=0) clf.fit(X, y) assert_array_equal(clf.predict(X), y, err_msg="Failed with {0}".format(name)) for name, TreeRegressor in REG_TREES.items(): reg = TreeRegressor(random_state=0) reg.fit(X, y) assert_almost_equal(clf.predict(X), y, err_msg="Failed with {0}".format(name)) def test_numerical_stability(): # Check numerical stability. X = np.array([ [152.08097839, 140.40744019, 129.75102234, 159.90493774], [142.50700378, 135.81935120, 117.82884979, 162.75781250], [127.28772736, 140.40744019, 129.75102234, 159.90493774], [132.37025452, 143.71923828, 138.35694885, 157.84558105], [103.10237122, 143.71928406, 138.35696411, 157.84559631], [127.71276855, 143.71923828, 138.35694885, 157.84558105], [120.91514587, 140.40744019, 129.75102234, 159.90493774]]) y = np.array( [1., 0.70209277, 0.53896582, 0., 0.90914464, 0.48026916, 0.49622521]) with np.errstate(all="raise"): for name, Tree in REG_TREES.items(): reg = Tree(random_state=0) reg.fit(X, y) reg.fit(X, -y) reg.fit(-X, y) reg.fit(-X, -y) def test_importances(): # Check variable importances. X, y = datasets.make_classification(n_samples=2000, n_features=10, n_informative=3, n_redundant=0, n_repeated=0, shuffle=False, random_state=0) for name, Tree in CLF_TREES.items(): clf = Tree(random_state=0) clf.fit(X, y) importances = clf.feature_importances_ n_important = np.sum(importances > 0.1) assert_equal(importances.shape[0], 10, "Failed with {0}".format(name)) assert_equal(n_important, 3, "Failed with {0}".format(name)) X_new = clf.transform(X, threshold="mean") assert_less(0, X_new.shape[1], "Failed with {0}".format(name)) assert_less(X_new.shape[1], X.shape[1], "Failed with {0}".format(name)) # Check on iris that importances are the same for all builders clf = DecisionTreeClassifier(random_state=0) clf.fit(iris.data, iris.target) clf2 = DecisionTreeClassifier(random_state=0, max_leaf_nodes=len(iris.data)) clf2.fit(iris.data, iris.target) assert_array_equal(clf.feature_importances_, clf2.feature_importances_) @raises(ValueError) def test_importances_raises(): # Check if variable importance before fit raises ValueError. clf = DecisionTreeClassifier() clf.feature_importances_ def test_importances_gini_equal_mse(): # Check that gini is equivalent to mse for binary output variable X, y = datasets.make_classification(n_samples=2000, n_features=10, n_informative=3, n_redundant=0, n_repeated=0, shuffle=False, random_state=0) # The gini index and the mean square error (variance) might differ due # to numerical instability. Since those instabilities mainly occurs at # high tree depth, we restrict this maximal depth. clf = DecisionTreeClassifier(criterion="gini", max_depth=5, random_state=0).fit(X, y) reg = DecisionTreeRegressor(criterion="mse", max_depth=5, random_state=0).fit(X, y) assert_almost_equal(clf.feature_importances_, reg.feature_importances_) assert_array_equal(clf.tree_.feature, reg.tree_.feature) assert_array_equal(clf.tree_.children_left, reg.tree_.children_left) assert_array_equal(clf.tree_.children_right, reg.tree_.children_right) assert_array_equal(clf.tree_.n_node_samples, reg.tree_.n_node_samples) def test_max_features(): # Check max_features. for name, TreeRegressor in REG_TREES.items(): reg = TreeRegressor(max_features="auto") reg.fit(boston.data, boston.target) assert_equal(reg.max_features_, boston.data.shape[1]) for name, TreeClassifier in CLF_TREES.items(): clf = TreeClassifier(max_features="auto") clf.fit(iris.data, iris.target) assert_equal(clf.max_features_, 2) for name, TreeEstimator in ALL_TREES.items(): est = TreeEstimator(max_features="sqrt") est.fit(iris.data, iris.target) assert_equal(est.max_features_, int(np.sqrt(iris.data.shape[1]))) est = TreeEstimator(max_features="log2") est.fit(iris.data, iris.target) assert_equal(est.max_features_, int(np.log2(iris.data.shape[1]))) est = TreeEstimator(max_features=1) est.fit(iris.data, iris.target) assert_equal(est.max_features_, 1) est = TreeEstimator(max_features=3) est.fit(iris.data, iris.target) assert_equal(est.max_features_, 3) est = TreeEstimator(max_features=0.01) est.fit(iris.data, iris.target) assert_equal(est.max_features_, 1) est = TreeEstimator(max_features=0.5) est.fit(iris.data, iris.target) assert_equal(est.max_features_, int(0.5 * iris.data.shape[1])) est = TreeEstimator(max_features=1.0) est.fit(iris.data, iris.target) assert_equal(est.max_features_, iris.data.shape[1]) est = TreeEstimator(max_features=None) est.fit(iris.data, iris.target) assert_equal(est.max_features_, iris.data.shape[1]) # use values of max_features that are invalid est = TreeEstimator(max_features=10) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_features=-1) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_features=0.0) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_features=1.5) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_features="foobar") assert_raises(ValueError, est.fit, X, y) def test_error(): # Test that it gives proper exception on deficient input. for name, TreeEstimator in CLF_TREES.items(): # predict before fit est = TreeEstimator() assert_raises(NotFittedError, est.predict_proba, X) est.fit(X, y) X2 = [-2, -1, 1] # wrong feature shape for sample assert_raises(ValueError, est.predict_proba, X2) for name, TreeEstimator in ALL_TREES.items(): # Invalid values for parameters assert_raises(ValueError, TreeEstimator(min_samples_leaf=-1).fit, X, y) assert_raises(ValueError, TreeEstimator(min_weight_fraction_leaf=-1).fit, X, y) assert_raises(ValueError, TreeEstimator(min_weight_fraction_leaf=0.51).fit, X, y) assert_raises(ValueError, TreeEstimator(min_samples_split=-1).fit, X, y) assert_raises(ValueError, TreeEstimator(max_depth=-1).fit, X, y) assert_raises(ValueError, TreeEstimator(max_features=42).fit, X, y) # Wrong dimensions est = TreeEstimator() y2 = y[:-1] assert_raises(ValueError, est.fit, X, y2) # Test with arrays that are non-contiguous. Xf = np.asfortranarray(X) est = TreeEstimator() est.fit(Xf, y) assert_almost_equal(est.predict(T), true_result) # predict before fitting est = TreeEstimator() assert_raises(NotFittedError, est.predict, T) # predict on vector with different dims est.fit(X, y) t = np.asarray(T) assert_raises(ValueError, est.predict, t[:, 1:]) # wrong sample shape Xt = np.array(X).T est = TreeEstimator() est.fit(np.dot(X, Xt), y) assert_raises(ValueError, est.predict, X) assert_raises(ValueError, est.apply, X) clf = TreeEstimator() clf.fit(X, y) assert_raises(ValueError, clf.predict, Xt) assert_raises(ValueError, clf.apply, Xt) # apply before fitting est = TreeEstimator() assert_raises(NotFittedError, est.apply, T) def test_min_samples_leaf(): # Test if leaves contain more than leaf_count training examples X = np.asfortranarray(iris.data.astype(tree._tree.DTYPE)) y = iris.target # test both DepthFirstTreeBuilder and BestFirstTreeBuilder # by setting max_leaf_nodes for max_leaf_nodes in (None, 1000): for name, TreeEstimator in ALL_TREES.items(): est = TreeEstimator(min_samples_leaf=5, max_leaf_nodes=max_leaf_nodes, random_state=0) est.fit(X, y) out = est.tree_.apply(X) node_counts = np.bincount(out) # drop inner nodes leaf_count = node_counts[node_counts != 0] assert_greater(np.min(leaf_count), 4, "Failed with {0}".format(name)) def check_min_weight_fraction_leaf(name, datasets, sparse=False): """Test if leaves contain at least min_weight_fraction_leaf of the training set""" if sparse: X = DATASETS[datasets]["X_sparse"].astype(np.float32) else: X = DATASETS[datasets]["X"].astype(np.float32) y = DATASETS[datasets]["y"] weights = rng.rand(X.shape[0]) total_weight = np.sum(weights) TreeEstimator = ALL_TREES[name] # test both DepthFirstTreeBuilder and BestFirstTreeBuilder # by setting max_leaf_nodes for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 6)): est = TreeEstimator(min_weight_fraction_leaf=frac, max_leaf_nodes=max_leaf_nodes, random_state=0) est.fit(X, y, sample_weight=weights) if sparse: out = est.tree_.apply(X.tocsr()) else: out = est.tree_.apply(X) node_weights = np.bincount(out, weights=weights) # drop inner nodes leaf_weights = node_weights[node_weights != 0] assert_greater_equal( np.min(leaf_weights), total_weight * est.min_weight_fraction_leaf, "Failed with {0} " "min_weight_fraction_leaf={1}".format( name, est.min_weight_fraction_leaf)) def test_min_weight_fraction_leaf(): # Check on dense input for name in ALL_TREES: yield check_min_weight_fraction_leaf, name, "iris" # Check on sparse input for name in SPARSE_TREES: yield check_min_weight_fraction_leaf, name, "multilabel", True def test_pickle(): # Check that tree estimator are pickable for name, TreeClassifier in CLF_TREES.items(): clf = TreeClassifier(random_state=0) clf.fit(iris.data, iris.target) score = clf.score(iris.data, iris.target) serialized_object = pickle.dumps(clf) clf2 = pickle.loads(serialized_object) assert_equal(type(clf2), clf.__class__) score2 = clf2.score(iris.data, iris.target) assert_equal(score, score2, "Failed to generate same score " "after pickling (classification) " "with {0}".format(name)) for name, TreeRegressor in REG_TREES.items(): reg = TreeRegressor(random_state=0) reg.fit(boston.data, boston.target) score = reg.score(boston.data, boston.target) serialized_object = pickle.dumps(reg) reg2 = pickle.loads(serialized_object) assert_equal(type(reg2), reg.__class__) score2 = reg2.score(boston.data, boston.target) assert_equal(score, score2, "Failed to generate same score " "after pickling (regression) " "with {0}".format(name)) def test_multioutput(): # Check estimators on multi-output problems. X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1], [-2, 1], [-1, 1], [-1, 2], [2, -1], [1, -1], [1, -2]] y = [[-1, 0], [-1, 0], [-1, 0], [1, 1], [1, 1], [1, 1], [-1, 2], [-1, 2], [-1, 2], [1, 3], [1, 3], [1, 3]] T = [[-1, -1], [1, 1], [-1, 1], [1, -1]] y_true = [[-1, 0], [1, 1], [-1, 2], [1, 3]] # toy classification problem for name, TreeClassifier in CLF_TREES.items(): clf = TreeClassifier(random_state=0) y_hat = clf.fit(X, y).predict(T) assert_array_equal(y_hat, y_true) assert_equal(y_hat.shape, (4, 2)) proba = clf.predict_proba(T) assert_equal(len(proba), 2) assert_equal(proba[0].shape, (4, 2)) assert_equal(proba[1].shape, (4, 4)) log_proba = clf.predict_log_proba(T) assert_equal(len(log_proba), 2) assert_equal(log_proba[0].shape, (4, 2)) assert_equal(log_proba[1].shape, (4, 4)) # toy regression problem for name, TreeRegressor in REG_TREES.items(): reg = TreeRegressor(random_state=0) y_hat = reg.fit(X, y).predict(T) assert_almost_equal(y_hat, y_true) assert_equal(y_hat.shape, (4, 2)) def test_classes_shape(): # Test that n_classes_ and classes_ have proper shape. for name, TreeClassifier in CLF_TREES.items(): # Classification, single output clf = TreeClassifier(random_state=0) clf.fit(X, y) assert_equal(clf.n_classes_, 2) assert_array_equal(clf.classes_, [-1, 1]) # Classification, multi-output _y = np.vstack((y, np.array(y) * 2)).T clf = TreeClassifier(random_state=0) clf.fit(X, _y) assert_equal(len(clf.n_classes_), 2) assert_equal(len(clf.classes_), 2) assert_array_equal(clf.n_classes_, [2, 2]) assert_array_equal(clf.classes_, [[-1, 1], [-2, 2]]) def test_unbalanced_iris(): # Check class rebalancing. unbalanced_X = iris.data[:125] unbalanced_y = iris.target[:125] sample_weight = _balance_weights(unbalanced_y) for name, TreeClassifier in CLF_TREES.items(): clf = TreeClassifier(random_state=0) clf.fit(unbalanced_X, unbalanced_y, sample_weight=sample_weight) assert_almost_equal(clf.predict(unbalanced_X), unbalanced_y) def test_memory_layout(): # Check that it works no matter the memory layout for (name, TreeEstimator), dtype in product(ALL_TREES.items(), [np.float64, np.float32]): est = TreeEstimator(random_state=0) # Nothing X = np.asarray(iris.data, dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) # C-order X = np.asarray(iris.data, order="C", dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) # F-order X = np.asarray(iris.data, order="F", dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) # Contiguous X = np.ascontiguousarray(iris.data, dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) if est.splitter in SPARSE_SPLITTERS: # csr matrix X = csr_matrix(iris.data, dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) # csc_matrix X = csc_matrix(iris.data, dtype=dtype) y = iris.target assert_array_equal(est.fit(X, y).predict(X), y) # Strided X = np.asarray(iris.data[::3], dtype=dtype) y = iris.target[::3] assert_array_equal(est.fit(X, y).predict(X), y) def test_sample_weight(): # Check sample weighting. # Test that zero-weighted samples are not taken into account X = np.arange(100)[:, np.newaxis] y = np.ones(100) y[:50] = 0.0 sample_weight = np.ones(100) sample_weight[y == 0] = 0.0 clf = DecisionTreeClassifier(random_state=0) clf.fit(X, y, sample_weight=sample_weight) assert_array_equal(clf.predict(X), np.ones(100)) # Test that low weighted samples are not taken into account at low depth X = np.arange(200)[:, np.newaxis] y = np.zeros(200) y[50:100] = 1 y[100:200] = 2 X[100:200, 0] = 200 sample_weight = np.ones(200) sample_weight[y == 2] = .51 # Samples of class '2' are still weightier clf = DecisionTreeClassifier(max_depth=1, random_state=0) clf.fit(X, y, sample_weight=sample_weight) assert_equal(clf.tree_.threshold[0], 149.5) sample_weight[y == 2] = .5 # Samples of class '2' are no longer weightier clf = DecisionTreeClassifier(max_depth=1, random_state=0) clf.fit(X, y, sample_weight=sample_weight) assert_equal(clf.tree_.threshold[0], 49.5) # Threshold should have moved # Test that sample weighting is the same as having duplicates X = iris.data y = iris.target duplicates = rng.randint(0, X.shape[0], 200) clf = DecisionTreeClassifier(random_state=1) clf.fit(X[duplicates], y[duplicates]) sample_weight = np.bincount(duplicates, minlength=X.shape[0]) clf2 = DecisionTreeClassifier(random_state=1) clf2.fit(X, y, sample_weight=sample_weight) internal = clf.tree_.children_left != tree._tree.TREE_LEAF assert_array_almost_equal(clf.tree_.threshold[internal], clf2.tree_.threshold[internal]) def test_sample_weight_invalid(): # Check sample weighting raises errors. X = np.arange(100)[:, np.newaxis] y = np.ones(100) y[:50] = 0.0 clf = DecisionTreeClassifier(random_state=0) sample_weight = np.random.rand(100, 1) assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) sample_weight = np.array(0) assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) sample_weight = np.ones(101) assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) sample_weight = np.ones(99) assert_raises(ValueError, clf.fit, X, y, sample_weight=sample_weight) def check_class_weights(name): """Check class_weights resemble sample_weights behavior.""" TreeClassifier = CLF_TREES[name] # Iris is balanced, so no effect expected for using 'balanced' weights clf1 = TreeClassifier(random_state=0) clf1.fit(iris.data, iris.target) clf2 = TreeClassifier(class_weight='balanced', random_state=0) clf2.fit(iris.data, iris.target) assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) # Make a multi-output problem with three copies of Iris iris_multi = np.vstack((iris.target, iris.target, iris.target)).T # Create user-defined weights that should balance over the outputs clf3 = TreeClassifier(class_weight=[{0: 2., 1: 2., 2: 1.}, {0: 2., 1: 1., 2: 2.}, {0: 1., 1: 2., 2: 2.}], random_state=0) clf3.fit(iris.data, iris_multi) assert_almost_equal(clf2.feature_importances_, clf3.feature_importances_) # Check against multi-output "auto" which should also have no effect clf4 = TreeClassifier(class_weight='balanced', random_state=0) clf4.fit(iris.data, iris_multi) assert_almost_equal(clf3.feature_importances_, clf4.feature_importances_) # Inflate importance of class 1, check against user-defined weights sample_weight = np.ones(iris.target.shape) sample_weight[iris.target == 1] *= 100 class_weight = {0: 1., 1: 100., 2: 1.} clf1 = TreeClassifier(random_state=0) clf1.fit(iris.data, iris.target, sample_weight) clf2 = TreeClassifier(class_weight=class_weight, random_state=0) clf2.fit(iris.data, iris.target) assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) # Check that sample_weight and class_weight are multiplicative clf1 = TreeClassifier(random_state=0) clf1.fit(iris.data, iris.target, sample_weight ** 2) clf2 = TreeClassifier(class_weight=class_weight, random_state=0) clf2.fit(iris.data, iris.target, sample_weight) assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) def test_class_weights(): for name in CLF_TREES: yield check_class_weights, name def check_class_weight_errors(name): # Test if class_weight raises errors and warnings when expected. TreeClassifier = CLF_TREES[name] _y = np.vstack((y, np.array(y) * 2)).T # Invalid preset string clf = TreeClassifier(class_weight='the larch', random_state=0) assert_raises(ValueError, clf.fit, X, y) assert_raises(ValueError, clf.fit, X, _y) # Not a list or preset for multi-output clf = TreeClassifier(class_weight=1, random_state=0) assert_raises(ValueError, clf.fit, X, _y) # Incorrect length list for multi-output clf = TreeClassifier(class_weight=[{-1: 0.5, 1: 1.}], random_state=0) assert_raises(ValueError, clf.fit, X, _y) def test_class_weight_errors(): for name in CLF_TREES: yield check_class_weight_errors, name def test_max_leaf_nodes(): # Test greedy trees with max_depth + 1 leafs. from sklearn.tree._tree import TREE_LEAF X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) k = 4 for name, TreeEstimator in ALL_TREES.items(): est = TreeEstimator(max_depth=None, max_leaf_nodes=k + 1).fit(X, y) tree = est.tree_ assert_equal((tree.children_left == TREE_LEAF).sum(), k + 1) # max_leaf_nodes in (0, 1) should raise ValueError est = TreeEstimator(max_depth=None, max_leaf_nodes=0) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_depth=None, max_leaf_nodes=1) assert_raises(ValueError, est.fit, X, y) est = TreeEstimator(max_depth=None, max_leaf_nodes=0.1) assert_raises(ValueError, est.fit, X, y) def test_max_leaf_nodes_max_depth(): # Test preceedence of max_leaf_nodes over max_depth. X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) k = 4 for name, TreeEstimator in ALL_TREES.items(): est = TreeEstimator(max_depth=1, max_leaf_nodes=k).fit(X, y) tree = est.tree_ assert_greater(tree.max_depth, 1) def test_arrays_persist(): # Ensure property arrays' memory stays alive when tree disappears # non-regression for #2726 for attr in ['n_classes', 'value', 'children_left', 'children_right', 'threshold', 'impurity', 'feature', 'n_node_samples']: value = getattr(DecisionTreeClassifier().fit([[0]], [0]).tree_, attr) # if pointing to freed memory, contents may be arbitrary assert_true(-2 <= value.flat[0] < 2, 'Array points to arbitrary memory') def test_only_constant_features(): random_state = check_random_state(0) X = np.zeros((10, 20)) y = random_state.randint(0, 2, (10, )) for name, TreeEstimator in ALL_TREES.items(): est = TreeEstimator(random_state=0) est.fit(X, y) assert_equal(est.tree_.max_depth, 0) def test_with_only_one_non_constant_features(): X = np.hstack([np.array([[1.], [1.], [0.], [0.]]), np.zeros((4, 1000))]) y = np.array([0., 1., 0., 1.0]) for name, TreeEstimator in CLF_TREES.items(): est = TreeEstimator(random_state=0, max_features=1) est.fit(X, y) assert_equal(est.tree_.max_depth, 1) assert_array_equal(est.predict_proba(X), 0.5 * np.ones((4, 2))) for name, TreeEstimator in REG_TREES.items(): est = TreeEstimator(random_state=0, max_features=1) est.fit(X, y) assert_equal(est.tree_.max_depth, 1) assert_array_equal(est.predict(X), 0.5 * np.ones((4, ))) def test_big_input(): # Test if the warning for too large inputs is appropriate. X = np.repeat(10 ** 40., 4).astype(np.float64).reshape(-1, 1) clf = DecisionTreeClassifier() try: clf.fit(X, [0, 1, 0, 1]) except ValueError as e: assert_in("float32", str(e)) def test_realloc(): from sklearn.tree._tree import _realloc_test assert_raises(MemoryError, _realloc_test) def test_huge_allocations(): n_bits = int(platform.architecture()[0].rstrip('bit')) X = np.random.randn(10, 2) y = np.random.randint(0, 2, 10) # Sanity check: we cannot request more memory than the size of the address # space. Currently raises OverflowError. huge = 2 ** (n_bits + 1) clf = DecisionTreeClassifier(splitter='best', max_leaf_nodes=huge) assert_raises(Exception, clf.fit, X, y) # Non-regression test: MemoryError used to be dropped by Cython # because of missing "except *". huge = 2 ** (n_bits - 1) - 1 clf = DecisionTreeClassifier(splitter='best', max_leaf_nodes=huge) assert_raises(MemoryError, clf.fit, X, y) def check_sparse_input(tree, dataset, max_depth=None): TreeEstimator = ALL_TREES[tree] X = DATASETS[dataset]["X"] X_sparse = DATASETS[dataset]["X_sparse"] y = DATASETS[dataset]["y"] # Gain testing time if dataset in ["digits", "boston"]: n_samples = X.shape[0] // 5 X = X[:n_samples] X_sparse = X_sparse[:n_samples] y = y[:n_samples] for sparse_format in (csr_matrix, csc_matrix, coo_matrix): X_sparse = sparse_format(X_sparse) # Check the default (depth first search) d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) y_pred = d.predict(X) if tree in CLF_TREES: y_proba = d.predict_proba(X) y_log_proba = d.predict_log_proba(X) for sparse_matrix in (csr_matrix, csc_matrix, coo_matrix): X_sparse_test = sparse_matrix(X_sparse, dtype=np.float32) assert_array_almost_equal(s.predict(X_sparse_test), y_pred) if tree in CLF_TREES: assert_array_almost_equal(s.predict_proba(X_sparse_test), y_proba) assert_array_almost_equal(s.predict_log_proba(X_sparse_test), y_log_proba) def test_sparse_input(): for tree, dataset in product(SPARSE_TREES, ("clf_small", "toy", "digits", "multilabel", "sparse-pos", "sparse-neg", "sparse-mix", "zeros")): max_depth = 3 if dataset == "digits" else None yield (check_sparse_input, tree, dataset, max_depth) # Due to numerical instability of MSE and too strict test, we limit the # maximal depth for tree, dataset in product(REG_TREES, ["boston", "reg_small"]): if tree in SPARSE_TREES: yield (check_sparse_input, tree, dataset, 2) def check_sparse_parameters(tree, dataset): TreeEstimator = ALL_TREES[tree] X = DATASETS[dataset]["X"] X_sparse = DATASETS[dataset]["X_sparse"] y = DATASETS[dataset]["y"] # Check max_features d = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X, y) s = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) assert_array_almost_equal(s.predict(X), d.predict(X)) # Check min_samples_split d = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit(X, y) s = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) assert_array_almost_equal(s.predict(X), d.predict(X)) # Check min_samples_leaf d = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit(X, y) s = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) assert_array_almost_equal(s.predict(X), d.predict(X)) # Check best-first search d = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X, y) s = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) assert_array_almost_equal(s.predict(X), d.predict(X)) def test_sparse_parameters(): for tree, dataset in product(SPARSE_TREES, ["sparse-pos", "sparse-neg", "sparse-mix", "zeros"]): yield (check_sparse_parameters, tree, dataset) def check_sparse_criterion(tree, dataset): TreeEstimator = ALL_TREES[tree] X = DATASETS[dataset]["X"] X_sparse = DATASETS[dataset]["X_sparse"] y = DATASETS[dataset]["y"] # Check various criterion CRITERIONS = REG_CRITERIONS if tree in REG_TREES else CLF_CRITERIONS for criterion in CRITERIONS: d = TreeEstimator(random_state=0, max_depth=3, criterion=criterion).fit(X, y) s = TreeEstimator(random_state=0, max_depth=3, criterion=criterion).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) assert_array_almost_equal(s.predict(X), d.predict(X)) def test_sparse_criterion(): for tree, dataset in product(SPARSE_TREES, ["sparse-pos", "sparse-neg", "sparse-mix", "zeros"]): yield (check_sparse_criterion, tree, dataset) def check_explicit_sparse_zeros(tree, max_depth=3, n_features=10): TreeEstimator = ALL_TREES[tree] # n_samples set n_feature to ease construction of a simultaneous # construction of a csr and csc matrix n_samples = n_features samples = np.arange(n_samples) # Generate X, y random_state = check_random_state(0) indices = [] data = [] offset = 0 indptr = [offset] for i in range(n_features): n_nonzero_i = random_state.binomial(n_samples, 0.5) indices_i = random_state.permutation(samples)[:n_nonzero_i] indices.append(indices_i) data_i = random_state.binomial(3, 0.5, size=(n_nonzero_i, )) - 1 data.append(data_i) offset += n_nonzero_i indptr.append(offset) indices = np.concatenate(indices) data = np.array(np.concatenate(data), dtype=np.float32) X_sparse = csc_matrix((data, indices, indptr), shape=(n_samples, n_features)) X = X_sparse.toarray() X_sparse_test = csr_matrix((data, indices, indptr), shape=(n_samples, n_features)) X_test = X_sparse_test.toarray() y = random_state.randint(0, 3, size=(n_samples, )) # Ensure that X_sparse_test owns its data, indices and indptr array X_sparse_test = X_sparse_test.copy() # Ensure that we have explicit zeros assert_greater((X_sparse.data == 0.).sum(), 0) assert_greater((X_sparse_test.data == 0.).sum(), 0) # Perform the comparison d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) assert_tree_equal(d.tree_, s.tree_, "{0} with dense and sparse format gave different " "trees".format(tree)) Xs = (X_test, X_sparse_test) for X1, X2 in product(Xs, Xs): assert_array_almost_equal(s.tree_.apply(X1), d.tree_.apply(X2)) assert_array_almost_equal(s.apply(X1), d.apply(X2)) assert_array_almost_equal(s.apply(X1), s.tree_.apply(X1)) assert_array_almost_equal(s.predict(X1), d.predict(X2)) if tree in CLF_TREES: assert_array_almost_equal(s.predict_proba(X1), d.predict_proba(X2)) def test_explicit_sparse_zeros(): for tree in SPARSE_TREES: yield (check_explicit_sparse_zeros, tree) def check_raise_error_on_1d_input(name): TreeEstimator = ALL_TREES[name] X = iris.data[:, 0].ravel() X_2d = iris.data[:, 0].reshape((-1, 1)) y = iris.target assert_raises(ValueError, TreeEstimator(random_state=0).fit, X, y) est = TreeEstimator(random_state=0) est.fit(X_2d, y) assert_raises(ValueError, est.predict, X) def test_1d_input(): for name in ALL_TREES: yield check_raise_error_on_1d_input, name def _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight): # Private function to keep pretty printing in nose yielded tests est = TreeEstimator(random_state=0) est.fit(X, y, sample_weight=sample_weight) assert_equal(est.tree_.max_depth, 1) est = TreeEstimator(random_state=0, min_weight_fraction_leaf=0.4) est.fit(X, y, sample_weight=sample_weight) assert_equal(est.tree_.max_depth, 0) def check_min_weight_leaf_split_level(name): TreeEstimator = ALL_TREES[name] X = np.array([[0], [0], [0], [0], [1]]) y = [0, 0, 0, 0, 1] sample_weight = [0.2, 0.2, 0.2, 0.2, 0.2] _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight) if TreeEstimator().splitter in SPARSE_SPLITTERS: _check_min_weight_leaf_split_level(TreeEstimator, csc_matrix(X), y, sample_weight) def test_min_weight_leaf_split_level(): for name in ALL_TREES: yield check_min_weight_leaf_split_level, name def check_public_apply(name): X_small32 = X_small.astype(tree._tree.DTYPE) est = ALL_TREES[name]() est.fit(X_small, y_small) assert_array_equal(est.apply(X_small), est.tree_.apply(X_small32)) def check_public_apply_sparse(name): X_small32 = csr_matrix(X_small.astype(tree._tree.DTYPE)) est = ALL_TREES[name]() est.fit(X_small, y_small) assert_array_equal(est.apply(X_small), est.tree_.apply(X_small32)) def test_public_apply(): for name in ALL_TREES: yield (check_public_apply, name) for name in SPARSE_TREES: yield (check_public_apply_sparse, name)
bsd-3-clause
dimroc/tensorflow-mnist-tutorial
lib/python3.6/site-packages/matplotlib/textpath.py
10
16668
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from collections import OrderedDict import six from six.moves import zip import warnings import numpy as np from matplotlib.path import Path from matplotlib import rcParams import matplotlib.font_manager as font_manager from matplotlib.ft2font import KERNING_DEFAULT, LOAD_NO_HINTING from matplotlib.ft2font import LOAD_TARGET_LIGHT from matplotlib.mathtext import MathTextParser import matplotlib.dviread as dviread from matplotlib.font_manager import FontProperties, get_font from matplotlib.transforms import Affine2D from six.moves.urllib.parse import quote as urllib_quote class TextToPath(object): """ A class that convert a given text to a path using ttf fonts. """ FONT_SCALE = 100. DPI = 72 def __init__(self): """ Initialization """ self.mathtext_parser = MathTextParser('path') self.tex_font_map = None from matplotlib.cbook import maxdict self._ps_fontd = maxdict(50) self._texmanager = None self._adobe_standard_encoding = None def _get_adobe_standard_encoding(self): enc_name = dviread.find_tex_file('8a.enc') enc = dviread.Encoding(enc_name) return dict([(c, i) for i, c in enumerate(enc.encoding)]) def _get_font(self, prop): """ find a ttf font. """ fname = font_manager.findfont(prop) font = get_font(fname) font.set_size(self.FONT_SCALE, self.DPI) return font def _get_hinting_flag(self): return LOAD_NO_HINTING def _get_char_id(self, font, ccode): """ Return a unique id for the given font and character-code set. """ sfnt = font.get_sfnt() try: ps_name = sfnt[(1, 0, 0, 6)].decode('macroman') except KeyError: ps_name = sfnt[(3, 1, 0x0409, 6)].decode('utf-16be') char_id = urllib_quote('%s-%x' % (ps_name, ccode)) return char_id def _get_char_id_ps(self, font, ccode): """ Return a unique id for the given font and character-code set (for tex). """ ps_name = font.get_ps_font_info()[2] char_id = urllib_quote('%s-%d' % (ps_name, ccode)) return char_id def glyph_to_path(self, font, currx=0.): """ convert the ft2font glyph to vertices and codes. """ verts, codes = font.get_path() if currx != 0.0: verts[:, 0] += currx return verts, codes def get_text_width_height_descent(self, s, prop, ismath): if rcParams['text.usetex']: texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() w, h, d = texmanager.get_text_width_height_descent(s, fontsize, renderer=None) return w, h, d fontsize = prop.get_size_in_points() scale = float(fontsize) / self.FONT_SCALE if ismath: prop = prop.copy() prop.set_size(self.FONT_SCALE) width, height, descent, trash, used_characters = \ self.mathtext_parser.parse(s, 72, prop) return width * scale, height * scale, descent * scale font = self._get_font(prop) font.set_text(s, 0.0, flags=LOAD_NO_HINTING) w, h = font.get_width_height() w /= 64.0 # convert from subpixels h /= 64.0 d = font.get_descent() d /= 64.0 return w * scale, h * scale, d * scale def get_text_path(self, prop, s, ismath=False, usetex=False): """ convert text *s* to path (a tuple of vertices and codes for matplotlib.path.Path). *prop* font property *s* text to be converted *usetex* If True, use matplotlib usetex mode. *ismath* If True, use mathtext parser. Effective only if usetex == False. """ if not usetex: if not ismath: font = self._get_font(prop) glyph_info, glyph_map, rects = self.get_glyphs_with_font( font, s) else: glyph_info, glyph_map, rects = self.get_glyphs_mathtext( prop, s) else: glyph_info, glyph_map, rects = self.get_glyphs_tex(prop, s) verts, codes = [], [] for glyph_id, xposition, yposition, scale in glyph_info: verts1, codes1 = glyph_map[glyph_id] if len(verts1): verts1 = np.array(verts1) * scale + [xposition, yposition] verts.extend(verts1) codes.extend(codes1) for verts1, codes1 in rects: verts.extend(verts1) codes.extend(codes1) return verts, codes def get_glyphs_with_font(self, font, s, glyph_map=None, return_new_glyphs_only=False): """ convert the string *s* to vertices and codes using the provided ttf font. """ # Mostly copied from backend_svg.py. lastgind = None currx = 0 xpositions = [] glyph_ids = [] if glyph_map is None: glyph_map = OrderedDict() if return_new_glyphs_only: glyph_map_new = OrderedDict() else: glyph_map_new = glyph_map # I'm not sure if I get kernings right. Needs to be verified. -JJL for c in s: ccode = ord(c) gind = font.get_char_index(ccode) if gind is None: ccode = ord('?') gind = 0 if lastgind is not None: kern = font.get_kerning(lastgind, gind, KERNING_DEFAULT) else: kern = 0 glyph = font.load_char(ccode, flags=LOAD_NO_HINTING) horiz_advance = (glyph.linearHoriAdvance / 65536.0) char_id = self._get_char_id(font, ccode) if char_id not in glyph_map: glyph_map_new[char_id] = self.glyph_to_path(font) currx += (kern / 64.0) xpositions.append(currx) glyph_ids.append(char_id) currx += horiz_advance lastgind = gind ypositions = [0] * len(xpositions) sizes = [1.] * len(xpositions) rects = [] return (list(zip(glyph_ids, xpositions, ypositions, sizes)), glyph_map_new, rects) def get_glyphs_mathtext(self, prop, s, glyph_map=None, return_new_glyphs_only=False): """ convert the string *s* to vertices and codes by parsing it with mathtext. """ prop = prop.copy() prop.set_size(self.FONT_SCALE) width, height, descent, glyphs, rects = self.mathtext_parser.parse( s, self.DPI, prop) if not glyph_map: glyph_map = OrderedDict() if return_new_glyphs_only: glyph_map_new = OrderedDict() else: glyph_map_new = glyph_map xpositions = [] ypositions = [] glyph_ids = [] sizes = [] currx, curry = 0, 0 for font, fontsize, ccode, ox, oy in glyphs: char_id = self._get_char_id(font, ccode) if char_id not in glyph_map: font.clear() font.set_size(self.FONT_SCALE, self.DPI) glyph = font.load_char(ccode, flags=LOAD_NO_HINTING) glyph_map_new[char_id] = self.glyph_to_path(font) xpositions.append(ox) ypositions.append(oy) glyph_ids.append(char_id) size = fontsize / self.FONT_SCALE sizes.append(size) myrects = [] for ox, oy, w, h in rects: vert1 = [(ox, oy), (ox, oy + h), (ox + w, oy + h), (ox + w, oy), (ox, oy), (0, 0)] code1 = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] myrects.append((vert1, code1)) return (list(zip(glyph_ids, xpositions, ypositions, sizes)), glyph_map_new, myrects) def get_texmanager(self): """ return the :class:`matplotlib.texmanager.TexManager` instance """ if self._texmanager is None: from matplotlib.texmanager import TexManager self._texmanager = TexManager() return self._texmanager def get_glyphs_tex(self, prop, s, glyph_map=None, return_new_glyphs_only=False): """ convert the string *s* to vertices and codes using matplotlib's usetex mode. """ # codes are modstly borrowed from pdf backend. texmanager = self.get_texmanager() if self.tex_font_map is None: self.tex_font_map = dviread.PsfontsMap( dviread.find_tex_file('pdftex.map')) if self._adobe_standard_encoding is None: self._adobe_standard_encoding = self._get_adobe_standard_encoding() fontsize = prop.get_size_in_points() if hasattr(texmanager, "get_dvi"): dvifilelike = texmanager.get_dvi(s, self.FONT_SCALE) dvi = dviread.DviFromFileLike(dvifilelike, self.DPI) else: dvifile = texmanager.make_dvi(s, self.FONT_SCALE) dvi = dviread.Dvi(dvifile, self.DPI) try: page = next(iter(dvi)) finally: dvi.close() if glyph_map is None: glyph_map = OrderedDict() if return_new_glyphs_only: glyph_map_new = OrderedDict() else: glyph_map_new = glyph_map glyph_ids, xpositions, ypositions, sizes = [], [], [], [] # Gather font information and do some setup for combining # characters into strings. # oldfont, seq = None, [] for x1, y1, dvifont, glyph, width in page.text: font_and_encoding = self._ps_fontd.get(dvifont.texname) font_bunch = self.tex_font_map[dvifont.texname] if font_and_encoding is None: font = get_font(font_bunch.filename) for charmap_name, charmap_code in [("ADOBE_CUSTOM", 1094992451), ("ADOBE_STANDARD", 1094995778)]: try: font.select_charmap(charmap_code) except (ValueError, RuntimeError): pass else: break else: charmap_name = "" warnings.warn("No supported encoding in font (%s)." % font_bunch.filename) if charmap_name == "ADOBE_STANDARD" and font_bunch.encoding: enc0 = dviread.Encoding(font_bunch.encoding) enc = dict([(i, self._adobe_standard_encoding.get(c, None)) for i, c in enumerate(enc0.encoding)]) else: enc = dict() self._ps_fontd[dvifont.texname] = font, enc else: font, enc = font_and_encoding ft2font_flag = LOAD_TARGET_LIGHT char_id = self._get_char_id_ps(font, glyph) if char_id not in glyph_map: font.clear() font.set_size(self.FONT_SCALE, self.DPI) if enc: charcode = enc.get(glyph, None) else: charcode = glyph if charcode is not None: glyph0 = font.load_char(charcode, flags=ft2font_flag) else: warnings.warn("The glyph (%d) of font (%s) cannot be " "converted with the encoding. Glyph may " "be wrong" % (glyph, font_bunch.filename)) glyph0 = font.load_char(glyph, flags=ft2font_flag) glyph_map_new[char_id] = self.glyph_to_path(font) glyph_ids.append(char_id) xpositions.append(x1) ypositions.append(y1) sizes.append(dvifont.size / self.FONT_SCALE) myrects = [] for ox, oy, h, w in page.boxes: vert1 = [(ox, oy), (ox + w, oy), (ox + w, oy + h), (ox, oy + h), (ox, oy), (0, 0)] code1 = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] myrects.append((vert1, code1)) return (list(zip(glyph_ids, xpositions, ypositions, sizes)), glyph_map_new, myrects) text_to_path = TextToPath() class TextPath(Path): """ Create a path from the text. """ def __init__(self, xy, s, size=None, prop=None, _interpolation_steps=1, usetex=False, *kl, **kwargs): """ Create a path from the text. No support for TeX yet. Note that it simply is a path, not an artist. You need to use the PathPatch (or other artists) to draw this path onto the canvas. xy : position of the text. s : text size : font size prop : font property """ if prop is None: prop = FontProperties() if size is None: size = prop.get_size_in_points() self._xy = xy self.set_size(size) self._cached_vertices = None self._vertices, self._codes = self.text_get_vertices_codes( prop, s, usetex=usetex) self._should_simplify = False self._simplify_threshold = rcParams['path.simplify_threshold'] self._has_nonfinite = False self._interpolation_steps = _interpolation_steps def set_size(self, size): """ set the size of the text """ self._size = size self._invalid = True def get_size(self): """ get the size of the text """ return self._size def _get_vertices(self): """ Return the cached path after updating it if necessary. """ self._revalidate_path() return self._cached_vertices def _get_codes(self): """ Return the codes """ return self._codes vertices = property(_get_vertices) codes = property(_get_codes) def _revalidate_path(self): """ update the path if necessary. The path for the text is initially create with the font size of FONT_SCALE, and this path is rescaled to other size when necessary. """ if (self._invalid or (self._cached_vertices is None)): tr = Affine2D().scale( self._size / text_to_path.FONT_SCALE, self._size / text_to_path.FONT_SCALE).translate(*self._xy) self._cached_vertices = tr.transform(self._vertices) self._invalid = False def is_math_text(self, s): """ Returns True if the given string *s* contains any mathtext. """ # copied from Text.is_math_text -JJL # Did we find an even number of non-escaped dollar signs? # If so, treat is as math text. dollar_count = s.count(r'$') - s.count(r'\$') even_dollars = (dollar_count > 0 and dollar_count % 2 == 0) if rcParams['text.usetex']: return s, 'TeX' if even_dollars: return s, True else: return s.replace(r'\$', '$'), False def text_get_vertices_codes(self, prop, s, usetex): """ convert the string *s* to vertices and codes using the provided font property *prop*. Mostly copied from backend_svg.py. """ if usetex: verts, codes = text_to_path.get_text_path(prop, s, usetex=True) else: clean_line, ismath = self.is_math_text(s) verts, codes = text_to_path.get_text_path(prop, clean_line, ismath=ismath) return verts, codes
apache-2.0
droundy/deft
papers/fuzzy-fmt/nm_hist2_work_in_progress.py
1
1064
#!/usr/bin/python2 #NOTE: Run this script from deft/papers/fuzzy-fmt with the #command ./nm_hist.py #MODIFYING this program to take command line arguments... import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt import os seeds=50 mcprefactor=40000 for gw in [.05]: #for gw in [0.01, 0.05, 0.1, 0.5, 0.7]: print "gw=%g" % (gw) #for mcconstant in [300, 800]: for mcconstant in [5, 20, 50, 100]: #for mcconstant in [5, 20, 50, 100, 200, 500, 1000]: print "mcconstant=%g" % (mcconstant) for seed in range(1, seeds+1): print "seed=%g" % (seed) os.system('figs/new-melting.mkdat --kT 2 --n 1.3 --gw %g --fv 0 --dx .5 --mc-error .001 --mc-constant %g --mc-prefactor %g --seed %g | tail -n 2 >> Hist_%g_%g_gw%g_mcerror0.001.dat' % (gw, mcconstant, mcprefactor, seed, mcconstant, mcprefactor, gw)) os.system('./Histogram.py Hist_%g_%g_gw%g_mcerror0.001.dat --gw %g --mcconstant %g --seeds %g >> Hist_%g_mcerror0.001.dat' % (mcconstant, mcprefactor, gw, gw, mcconstant, seeds, mcprefactor))
gpl-2.0
sahana/Turkey
controllers/msg.py
5
80604
# -*- coding: utf-8 -*- """ Messaging Module - Controllers """ module = request.controller resourcename = request.function if not settings.has_module(module): raise HTTP(404, body="Module disabled: %s" % module) # ----------------------------------------------------------------------------- def index(): """ Module's Home Page """ module_name = settings.modules[module].name_nice response.title = module_name return dict(module_name=module_name) # ----------------------------------------------------------------------------- def basestation(): """ RESTful CRUD controller for Base Stations """ return s3_rest_controller() # ============================================================================= def compose(): """ Compose a Message which can be sent to a pentity via a number of different communications channels """ return msg.compose() # ============================================================================= def message(): """ RESTful CRUD controller for the master message log """ tablename = "msg_message" table = s3db.msg_message table.instance_type.readable = True table.instance_type.label = T("Channel") # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Message Details"), title_list = T("Message Log"), label_list_button = T("View Message Log"), msg_list_empty = T("No Messages currently in the Message Log") ) def postp(r, output): if r.interactive: # Normal Action Buttons s3_action_buttons(r) # Custom Action Buttons s3.actions += [dict(label=str(T("Mark Sender")), _class="action-btn", url=URL(f="mark_sender", args="[id]")), ] return output s3.postp = postp s3db.configure(tablename, deletable = False, editable = False, insertable = False, ) return s3_rest_controller() # ============================================================================= def mark_sender(): """ Assign priority to the given sender """ try: mid = request.args[0] except: raise SyntaxError mtable = s3db.msg_message stable = s3db.msg_sender # @ToDo: Replace 2 queries with Join srecord = db(mtable.id == mid).select(mtable.from_address, limitby=(0, 1) ).first() sender = srecord.from_address record = db(stable.sender == sender).select(stable.id, limitby=(0, 1) ).first() if record: args = "update" else: args = "create" url = URL(f="sender", args=args, vars=dict(sender=sender)) redirect(url) # ============================================================================= def outbox(): """ View the contents of the Outbox """ if not auth.s3_logged_in(): session.error = T("Requires Login!") redirect(URL(c="default", f="user", args="login")) tablename = "msg_outbox" table = s3db[tablename] table.message_id.label = T("Message") table.message_id.writable = False table.message_id.readable = True table.pe_id.readable = True table.pe_id.label = T("Recipient") table.message_id.represent = s3db.msg_message_represent table.pe_id.represent = s3db.pr_PersonEntityRepresent(default_label="") # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Message Details"), title_list = T("Outbox"), label_list_button = T("View Outbox"), label_delete_button = T("Delete Message"), msg_record_deleted = T("Message deleted"), msg_list_empty = T("No Messages currently in Outbox") ) def postp(r, output): if isinstance(output, dict): add_btn = A(T("Compose"), _class="action-btn", _href=URL(f="compose") ) output["rheader"] = add_btn return output s3.postp = postp s3db.configure(tablename, # Permissions-based #deletable = False, editable = False, insertable = False, ) return s3_rest_controller() # ----------------------------------------------------------------------------- def email_outbox(): """ RESTful CRUD controller for the Email Outbox - all Outbound Email Messages are visible here """ if not auth.s3_logged_in(): session.error = T("Requires Login!") redirect(URL(c="default", f="user", args="login")) tablename = "msg_email" table = s3db.msg_email s3.filter = (table.inbound == False) table.inbound.readable = False # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Email Details"), title_list = T("Sent Emails"), label_list_button = T("View Sent Emails"), label_delete_button = T("Delete Email"), msg_record_deleted = T("Email deleted"), msg_list_empty = T("No Emails currently in Outbox") ) def postp(r, output): if isinstance(output, dict): add_btn = A(T("Compose"), _class="action-btn", _href=URL(f="compose") ) output["rheader"] = add_btn return output s3.postp = postp s3db.configure(tablename, # Permissions-based #deletable = False, editable = False, insertable = False, listadd = False, list_fields = ["id", "date", "to_address", "subject", "body", ], ) return s3_rest_controller(module, "email") # ----------------------------------------------------------------------------- def facebook_outbox(): """ RESTful CRUD controller for the Facebook Outbox - all Outbound Facebook Messages are visible here """ if not auth.s3_logged_in(): session.error = T("Requires Login!") redirect(URL(c="default", f="user", args="login")) tablename = "msg_facebook" table = s3db.msg_facebook s3.filter = (table.inbound == False) table.inbound.readable = False # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Post Details"), title_list = T("Sent Posts"), label_list_button = T("View Sent Posts"), label_delete_button = T("Delete Post"), msg_record_deleted = T("Post deleted"), msg_list_empty = T("No Posts currently in Outbox") ) #def postp(r, output): # if isinstance(output, dict): # add_btn = A(T("Compose"), # _class="action-btn", # _href=URL(f="compose") # ) # output["rheader"] = add_btn # return output #s3.postp = postp s3db.configure(tablename, # Permissions-based #deletable = False, editable = False, insertable = False, listadd = False, list_fields = ["id", "date", #"to_address", "body", ], ) return s3_rest_controller(module, "facebook") # ----------------------------------------------------------------------------- def sms_outbox(): """ RESTful CRUD controller for the SMS Outbox - all sent SMS are visible here """ if not auth.s3_logged_in(): session.error = T("Requires Login!") redirect(URL(c="default", f="user", args="login")) tablename = "msg_sms" table = s3db.msg_sms s3.filter = (table.inbound == False) table.inbound.readable = False # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("SMS Details"), title_list = T("Sent SMS"), label_list_button = T("View Sent SMS"), label_delete_button = T("Delete SMS"), msg_record_deleted = T("SMS deleted"), msg_list_empty = T("No SMS currently in Outbox") ) def postp(r, output): if isinstance(output, dict): add_btn = A(T("Compose"), _class="action-btn", _href=URL(f="compose") ) output["rheader"] = add_btn return output s3.postp = postp s3db.configure(tablename, # Permissions-based #deletable = False, editable = False, insertable = False, listadd = False, list_fields = ["id", "date", "to_address", "body", ], ) return s3_rest_controller(module, "sms") # ----------------------------------------------------------------------------- def twitter_outbox(): """ RESTful CRUD controller for the Twitter Outbox - all sent Tweets are visible here """ if not auth.s3_logged_in(): session.error = T("Requires Login!") redirect(URL(c="default", f="user", args="login")) tablename = "msg_twitter" table = s3db.msg_twitter s3.filter = (table.inbound == False) table.inbound.readable = False # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Tweet Details"), title_list = T("Sent Tweets"), label_list_button = T("View Sent Tweets"), label_delete_button = T("Delete Tweet"), msg_record_deleted = T("Tweet deleted"), msg_list_empty = T("No Tweets currently in Outbox") ) def postp(r, output): if isinstance(output, dict): add_btn = A(T("Compose"), _class="action-btn", _href=URL(f="compose") ) output["rheader"] = add_btn return output s3.postp = postp s3db.configure(tablename, # Permissions-based #deletable = False, editable = False, insertable = False, listadd = False, list_fields = ["id", "date", "to_address", "body", ], ) return s3_rest_controller(module, "twitter") # ============================================================================= def inbox(): """ RESTful CRUD controller for the Inbox - all Inbound Messages are visible here """ if not auth.s3_logged_in(): session.error = T("Requires Login!") redirect(URL(c="default", f="user", args="login")) table = s3db.msg_message s3.filter = (table.inbound == True) table.inbound.readable = False tablename = "msg_message" # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Message Details"), title_list = T("InBox"), label_list_button = T("View InBox"), label_delete_button = T("Delete Message"), msg_record_deleted = T("Message deleted"), msg_list_empty = T("No Messages currently in InBox") ) s3db.configure(tablename, # Permissions-based #deletable = False, editable = False, insertable = False, list_fields = ["id", "date", "channel_id", "from_address", "body", ], ) return s3_rest_controller(module, "message") # ----------------------------------------------------------------------------- def email_inbox(): """ RESTful CRUD controller for the Email Inbox - all Inbound Email Messages are visible here """ if not auth.s3_logged_in(): session.error = T("Requires Login!") redirect(URL(c="default", f="user", args="login")) s3.filter = (FS("inbound") == True) from s3 import S3SQLCustomForm, S3SQLInlineComponent crud_form = S3SQLCustomForm("date", "subject", "from_address", "body", S3SQLInlineComponent( "attachment", name = "document_id", label = T("Attachments"), fields = ["document_id", ], ), ) tablename = "msg_email" # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Email Details"), title_list = T("Email InBox"), label_list_button = T("View Email InBox"), label_delete_button = T("Delete Email"), msg_record_deleted = T("Email deleted"), msg_list_empty = T("No Emails currently in InBox") ) s3db.configure(tablename, crud_form = crud_form, # Permissions-based #deletable = False, editable = False, insertable = False, list_fields = ["id", "date", "from_address", "subject", "body", (T("Attachments"), "attachment.document_id"), ], ) def prep(r): s3db.msg_email.inbound.readable = False if r.id: s3db.msg_attachment.document_id.label = "" return True s3.prep = prep return s3_rest_controller(module, "email") # ============================================================================= def rss(): """ RESTful CRUD controller for RSS feed posts """ if not auth.s3_has_role(ADMIN): session.error = ERROR.UNAUTHORISED redirect(URL(f="index")) tablename = "msg_rss" table = s3db.msg_rss # To represent the description suitably # If it is an image display an image #table.description.represent = lambda description: HTML(description) # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("RSS Post Details"), title_list = T("RSS Posts"), label_list_button = T("View RSS Posts"), label_delete_button = T("Delete Post"), msg_record_deleted = T("RSS Post deleted"), msg_list_empty = T("No Posts available") ) s3db.configure(tablename, # Permissions-based #deletable = False, editable = False, insertable = False, list_fields = ["id", "date", "body", ], ) return s3_rest_controller() # ----------------------------------------------------------------------------- def sms_inbox(): """ RESTful CRUD controller for the SMS Inbox - all Inbound SMS Messages go here """ if not auth.s3_logged_in(): session.error = T("Requires Login!") redirect(URL(c="default", f="user", args="login")) tablename = "msg_sms" table = s3db[tablename] s3.filter = (table.inbound == True) table.inbound.readable = False # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("SMS Details"), title_list = T("SMS InBox"), label_list_button = T("View SMS InBox"), label_delete_button = T("Delete SMS"), msg_record_deleted = T("SMS deleted"), msg_list_empty = T("No SMS currently in InBox") ) s3db.configure(tablename, # Permissions-based #deletable = False, editable = False, insertable = False, list_fields = ["id", "date", "from_address", "body", ], ) return s3_rest_controller(module, "sms") # ----------------------------------------------------------------------------- def twitter(): """ Twitter RESTful Controller @ToDo: Action Button to update async """ s3db.configure("msg_twitter", editable = False, insertable = False, list_fields = ["id", "date", "from_address", "to_address", "body", ], ) return s3_rest_controller() # ----------------------------------------------------------------------------- def twitter_inbox(): """ RESTful CRUD controller for the Twitter Inbox - all Inbound Tweets (Directed Messages) are visible here """ if not auth.s3_logged_in(): session.error = T("Requires Login!") redirect(URL(c="default", f="user", args="login")) tablename = "msg_twitter" table = s3db.msg_twitter s3.filter = (table.inbound == True) table.inbound.readable = False # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Tweet Details"), title_list = T("Twitter InBox"), label_list_button = T("View Twitter InBox"), label_delete_button = T("Delete Tweet"), msg_record_deleted = T("Tweet deleted"), msg_list_empty = T("No Tweets currently in InBox") ) s3db.configure(tablename, editable = False, insertable = False, list_fields = ["id", "date", "from_address", "body", ], ) return s3_rest_controller(module, "twitter") # ============================================================================= def tropo(): """ Receive a JSON POST from the Tropo WebAPI @see: https://www.tropo.com/docs/webapi/newhowitworks.htm """ # Stored in modules/tropo.py from tropo import Tropo, Session try: s = Session(request.body.read()) t = Tropo() # This is their service contacting us, so parse their request try: row_id = s.parameters["row_id"] # This is an Outbound message which we've requested Tropo to send for us table = s3db.msg_tropo_scratch query = (table.row_id == row_id) row = db(query).select().first() # Send the message #t.message(say_obj={"say":{"value":row.message}},to=row.recipient,network=row.network) t.call(to=row.recipient, network=row.network) t.say(row.message) # Update status to sent in Outbox outbox = s3db.msg_outbox db(outbox.id == row.row_id).update(status=2) # @ToDo: Set message log to actioned #log = s3db.msg_log #db(log.id == row.message_id).update(actioned=True) # Clear the Scratchpad db(query).delete() return t.RenderJson() except: # This is an Inbound message try: message = s.initialText # This is an SMS/IM # Place it in the InBox uuid = s.id recipient = s.to["id"] try: fromaddress = s.fromaddress["id"] except: # SyntaxError: s.from => invalid syntax (why!?) fromaddress = "" # @ToDo: Update to new model #s3db.msg_log.insert(uuid=uuid, fromaddress=fromaddress, # recipient=recipient, message=message, # inbound=True) # Send the message to the parser reply = msg.parse_message(message) t.say([reply]) return t.RenderJson() except: # This is a Voice call # - we can't handle these yet raise HTTP(501) except: # GET request or some random POST pass # ============================================================================= @auth.s3_requires_membership(1) def sms_outbound_gateway(): """ SMS Outbound Gateway selection for the messaging framework """ # CRUD Strings s3.crud_strings["msg_sms_outbound_gateway"] = Storage( label_create=T("Create SMS Outbound Gateway"), title_display=T("SMS Outbound Gateway Details"), title_list=T("SMS Outbound Gateways"), title_update=T("Edit SMS Outbound Gateway"), label_list_button=T("List SMS Outbound Gateways"), label_delete_button=T("Delete SMS Outbound Gateway"), msg_record_created=T("SMS Outbound Gateway added"), msg_record_modified=T("SMS Outbound Gateway updated"), msg_record_deleted=T("SMS Outbound Gateway deleted"), msg_list_empty=T("No SMS Outbound Gateways currently registered")) return s3_rest_controller() # ----------------------------------------------------------------------------- def channel(): """ RESTful CRUD controller for Channels - unused """ return s3_rest_controller() # ----------------------------------------------------------------------------- def email_channel(): """ RESTful CRUD controller for Inbound Email channels - appears in the administration menu """ if not auth.s3_has_role(ADMIN): session.error = ERROR.UNAUTHORISED redirect(URL(f="index")) tablename = "msg_email_channel" table = s3db[tablename] table.server.label = T("Server") table.protocol.label = T("Protocol") table.use_ssl.label = "SSL" table.port.label = T("Port") table.username.label = T("Username") table.password.label = T("Password") table.delete_from_server.label = T("Delete from Server?") table.port.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Port"), T("For POP-3 this is usually 110 (995 for SSL), for IMAP this is usually 143 (993 for IMAP)."))) table.delete_from_server.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Delete"), T("If this is set to True then mails will be deleted from the server after downloading."))) # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Email Settings"), title_list = T("Email Accounts"), label_create = T("Add Email Account"), title_update = T("Edit Email Settings"), label_list_button = T("View Email Accounts"), msg_record_created = T("Account added"), msg_record_deleted = T("Email Account deleted"), msg_list_empty = T("No Accounts currently defined"), msg_record_modified = T("Email Settings updated") ) def postp(r, output): if r.interactive: # Normal Action Buttons s3_action_buttons(r) # Custom Action Buttons for Enable/Disable table = r.table query = (table.deleted == False) rows = db(query).select(table.id, table.enabled, ) restrict_e = [str(row.id) for row in rows if not row.enabled] restrict_d = [str(row.id) for row in rows if row.enabled] s3.actions += [dict(label=str(T("Enable")), _class="action-btn", url=URL(args=["[id]", "enable"]), restrict = restrict_e), dict(label=str(T("Disable")), _class="action-btn", url = URL(args = ["[id]", "disable"]), restrict = restrict_d), ] if not s3task._is_alive(): # No Scheduler Running s3.actions += [dict(label=str(T("Poll")), _class="action-btn", url = URL(args = ["[id]", "poll"]), restrict = restrict_d) ] return output s3.postp = postp return s3_rest_controller() # ----------------------------------------------------------------------------- def facebook_channel(): """ RESTful CRUD controller for Facebook channels - appears in the administration menu """ if not auth.s3_has_role(ADMIN): session.error = ERROR.UNAUTHORISED redirect(URL(f="index")) tablename = "msg_facebook_channel" table = s3db[tablename] # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Facebook Settings"), title_list = T("Facebook Accounts"), label_create = T("Add Facebook Account"), title_update = T("Edit Facebook Settings"), label_list_button = T("View Facebook Accounts"), msg_record_created = T("Account added"), msg_record_deleted = T("Facebook Account deleted"), msg_list_empty = T("No Accounts currently defined"), msg_record_modified = T("Facebook Settings updated") ) def postp(r, output): if r.interactive: # Normal Action Buttons s3_action_buttons(r) # Custom Action Buttons for Enable/Disable table = r.table query = (table.deleted == False) rows = db(query).select(table.id, table.enabled, ) restrict_e = [str(row.id) for row in rows if not row.enabled] restrict_d = [str(row.id) for row in rows if row.enabled] s3.actions += [dict(label=str(T("Enable")), _class="action-btn", url=URL(args=["[id]", "enable"]), restrict = restrict_e), dict(label=str(T("Disable")), _class="action-btn", url = URL(args = ["[id]", "disable"]), restrict = restrict_d), ] #if not s3task._is_alive(): # # No Scheduler Running # s3.actions += [dict(label=str(T("Poll")), # _class="action-btn", # url = URL(args = ["[id]", "poll"]), # restrict = restrict_d) # ] return output s3.postp = postp return s3_rest_controller() # ----------------------------------------------------------------------------- def mcommons_channel(): """ RESTful CRUD controller for Mobile Commons SMS Channels - appears in the administration menu """ if not auth.s3_has_role(ADMIN): session.error = ERROR.UNAUTHORISED redirect(URL(f="index")) tablename = "msg_mcommons_channel" table = s3db[tablename] table.name.label = T("Account Name") table.name.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Account Name"), T("Name for your Mobile Commons Account"))) table.campaign_id.label = T("Campaign ID") table.url.label = T("URL") table.url.comment = DIV(_class="tooltip", _title="%s|%s" % (T("URL"), T("URL for the Mobile Commons API"))) table.username.label = T("Username") table.password.label = T("Password") table.timestmp.label = T("Last Downloaded") table.timestmp.writable = False # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Mobile Commons Setting Details"), title_list = T("Mobile Commons Settings"), label_create = T("Add Mobile Commons Settings"), title_update = T("Edit Mobile Commons Settings"), label_list_button = T("View Mobile Commons Settings"), msg_record_created = T("Mobile Commons Setting added"), msg_record_deleted = T("Mobile Commons Setting deleted"), msg_list_empty = T("No Mobile Commons Settings currently defined"), msg_record_modified = T("Mobile Commons settings updated") ) def postp(r, output): if r.interactive: # Normal Action Buttons s3_action_buttons(r) # Custom Action Buttons for Enable/Disable table = r.table query = (table.deleted == False) rows = db(query).select(table.id, table.enabled, ) restrict_e = [str(row.id) for row in rows if not row.enabled] restrict_d = [str(row.id) for row in rows if row.enabled] s3.actions += [dict(label=str(T("Enable")), _class="action-btn", url=URL(args=["[id]", "enable"]), restrict = restrict_e), dict(label=str(T("Disable")), _class="action-btn", url = URL(args = ["[id]", "disable"]), restrict = restrict_d), ] if not s3task._is_alive(): # No Scheduler Running s3.actions += [dict(label=str(T("Poll")), _class="action-btn", url = URL(args = ["[id]", "poll"]), restrict = restrict_d) ] return output s3.postp = postp return s3_rest_controller() # ----------------------------------------------------------------------------- def rss_channel(): """ RESTful CRUD controller for RSS channels - appears in the administration menu """ if not auth.s3_has_role(ADMIN): session.error = ERROR.UNAUTHORISED redirect(URL(f="index")) tablename = "msg_rss_channel" table = s3db[tablename] table.name.label = T("Name") table.description.label = T("Description") table.url.label = T("URL/Link") table.url.comment = DIV(_class="tooltip", _title="%s|%s" % (T("URL"), T("Link for the RSS Feed."))) table.enabled.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Subscriptions Status"), T("Are you susbscribed?"))) # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("RSS Channel Details"), title_list = T("RSS Channels"), label_create = T("Add RSS Channel"), title_update = T("Edit RSS Channel"), label_list_button = T("View RSS Channels"), msg_record_created = T("Channel added"), msg_record_deleted = T("RSS Channel deleted"), msg_list_empty = T("No RSS Channels currently defined"), msg_record_modified = T("RSS Channel updated")) def status_represent(v): try: v = int(v) except: # Text return v return "There have been no new entries for %s requests" % v s3db.msg_channel_status.status.represent = status_represent def postp(r, output): if r.interactive: # Normal Action Buttons s3_action_buttons(r) # Custom Action Buttons for Enable/Disable table = r.table query = (table.deleted == False) rows = db(query).select(table.id, table.enabled, ) restrict_e = [str(row.id) for row in rows if not row.enabled] restrict_d = [str(row.id) for row in rows if row.enabled] s3.actions += [dict(label=str(T("Subscribe")), _class="action-btn", url=URL(args=["[id]", "enable"]), restrict = restrict_e), dict(label=str(T("Unsubscribe")), _class="action-btn", url = URL(args = ["[id]", "disable"]), restrict = restrict_d), ] if not s3task._is_alive(): # No Scheduler Running s3.actions += [dict(label=str(T("Poll")), _class="action-btn", url = URL(args = ["[id]", "poll"]), restrict = restrict_d) ] return output s3.postp = postp return s3_rest_controller() # ----------------------------------------------------------------------------- def twilio_channel(): """ RESTful CRUD controller for Twilio SMS channels - appears in the administration menu """ if not auth.s3_has_role(ADMIN): session.error = ERROR.UNAUTHORISED redirect(URL(f="index")) tablename = "msg_twilio_channel" table = s3db[tablename] table.account_name.label = T("Account Name") table.account_name.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Account Name"), T("Identifier Name for your Twilio Account."))) table.url.label = T("URL") table.url.comment = DIV(_class="tooltip", _title="%s|%s" % (T("URL"), T("URL for the twilio API."))) table.account_sid.label = "Account SID" table.auth_token.label = T("AUTH TOKEN") # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Twilio Channel Details"), title_list = T("Twilio Channels"), label_create = T("Add Twilio Channel"), title_update = T("Edit Twilio Channel"), label_list_button = T("View Twilio Channels"), msg_record_created = T("Twilio Channel added"), msg_record_deleted = T("Twilio Channel deleted"), msg_record_modified = T("Twilio Channel updated"), msg_list_empty = T("No Twilio Channels currently defined")) def postp(r, output): if r.interactive: # Normal Action Buttons s3_action_buttons(r) # Custom Action Buttons for Enable/Disable table = r.table query = (table.deleted == False) rows = db(query).select(table.id, table.enabled, ) restrict_e = [str(row.id) for row in rows if not row.enabled] restrict_d = [str(row.id) for row in rows if row.enabled] s3.actions += [dict(label=str(T("Enable")), _class="action-btn", url=URL(args=["[id]", "enable"]), restrict = restrict_e), dict(label=str(T("Disable")), _class="action-btn", url = URL(args = ["[id]", "disable"]), restrict = restrict_d), ] if not s3task._is_alive(): # No Scheduler Running s3.actions += [dict(label=str(T("Poll")), _class="action-btn", url = URL(args = ["[id]", "poll"]), restrict = restrict_d) ] return output s3.postp = postp return s3_rest_controller() # ----------------------------------------------------------------------------- @auth.s3_requires_membership(1) def sms_modem_channel(): """ RESTful CRUD controller for modem channels - appears in the administration menu Multiple Modems can be configured to receive Inbound Messages """ try: import serial except ImportError: session.error = T("Python Serial module not available within the running Python - this needs installing to activate the Modem") redirect(URL(c="admin", f="index")) tablename = "%s_%s" % (module, resourcename) table = s3db[tablename] table.modem_port.label = T("Port") table.modem_baud.label = T("Baud") table.enabled.label = T("Enabled") table.modem_port.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Port"), T("The serial port at which the modem is connected - /dev/ttyUSB0, etc on linux and com1, com2, etc on Windows"))) table.modem_baud.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Baud"), T("Baud rate to use for your modem - The default is safe for most cases"))) table.enabled.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Enabled"), T("Unselect to disable the modem"))) # CRUD Strings s3.crud_strings[tablename] = Storage( label_create = T("Add Modem Channel"), title_display = T("Modem Channel Details"), title_list = T("Modem Channels"), title_update = T("Edit Modem Channel"), label_list_button = T("View Modem Channels"), msg_record_created = T("Modem Channel added"), msg_record_modified = T("Modem Channel updated"), msg_record_deleted = T("Modem Channel deleted"), msg_list_empty = T("No Modem Channels currently defined")) return s3_rest_controller() #------------------------------------------------------------------------------ @auth.s3_requires_membership(1) def sms_smtp_channel(): """ RESTful CRUD controller for SMTP to SMS Outbound channels - appears in the administration menu """ tablename = "%s_%s" % (module, resourcename) table = s3db[tablename] table.address.label = T("Address") table.subject.label = T("Subject") table.enabled.label = T("Enabled") table.address.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Address"), T("Email Address to which to send SMS messages. Assumes sending to phonenumber@address"))) table.subject.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Subject"), T("Optional Subject to put into Email - can be used as a Security Password by the service provider"))) table.enabled.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Enabled"), T("Unselect to disable this SMTP service"))) # CRUD Strings s3.crud_strings["msg_sms_outbound_gateway"] = Storage( label_create=T("Create SMTP to SMS Channel"), title_display=T("SMTP to SMS Channel Details"), title_list=T("SMTP to SMS Channels"), title_update=T("Edit SMTP to SMS Channel"), label_list_button=T("List SMTP to SMS Channels"), label_delete_button=T("Delete SMTP to SMS Channel"), msg_record_created=T("SMTP to SMS Channel added"), msg_record_modified=T("SMTP to SMS Channel updated"), msg_record_deleted=T("SMTP to SMS Channel deleted"), msg_list_empty=T("No SMTP to SMS Channels currently registered")) s3db.configure(tablename, update_next = URL(args=[1, "update"])) return s3_rest_controller() #------------------------------------------------------------------------------ @auth.s3_requires_membership(1) def sms_webapi_channel(): """ RESTful CRUD controller for Web API channels - appears in the administration menu """ tablename = "%s_%s" % (module, resourcename) table = s3db[tablename] table.url.label = T("URL") table.message_variable.label = T("Message variable") table.to_variable.label = T("To variable") table.username.label = T("Username") table.password.label = T("Password") table.enabled.label = T("Enabled") table.url.comment = DIV(_class="tooltip", _title="%s|%s" % (T("URL"), T("The URL of your web gateway without the POST parameters"))) table.parameters.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Parameters"), T("The POST variables other than the ones containing the message and the phone number"))) table.message_variable.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Message Variable"), T("The POST variable on the URL used for sending messages"))) table.to_variable.comment = DIV(_class="tooltip", _title="%s|%s" % (T("To variable"), T("The POST variable containing the phone number"))) table.username.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Username"), T("If the service requries HTTP BASIC Auth (e.g. Mobile Commons)"))) table.password.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Password"), T("If the service requries HTTP BASIC Auth (e.g. Mobile Commons)"))) table.enabled.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Enabled"), T("Unselect to disable this API service"))) # CRUD Strings s3.crud_strings[tablename] = Storage( label_create=T("Create Web API Channel"), title_display=T("Web API Channel Details"), title_list=T("Web API Channels"), title_update=T("Edit Web API Channel"), label_list_button=T("List Web API Channels"), label_delete_button=T("Delete Web API Channel"), msg_record_created=T("Web API Channel added"), msg_record_modified=T("Web API Channel updated"), msg_record_deleted=T("Web API Channel deleted"), msg_list_empty=T("No Web API Channels currently registered")) return s3_rest_controller() # ----------------------------------------------------------------------------- @auth.s3_requires_membership(1) def tropo_channel(): """ RESTful CRUD controller for Tropo channels - appears in the administration menu """ tablename = "msg_tropo_channel" table = s3db[tablename] table.token_messaging.label = T("Tropo Messaging Token") table.token_messaging.comment = DIV(DIV(_class="stickytip", _title="%s|%s" % (T("Tropo Messaging Token"), T("The token associated with this application on") + " <a href='https://www.tropo.com/docs/scripting/troposessionapi.htm' target=_blank>Tropo.com</a>"))) #table.token_voice.label = T("Tropo Voice Token") #table.token_voice.comment = DIV(DIV(_class="stickytip",_title=T("Tropo Voice Token") + "|" + T("The token associated with this application on") + " <a href='https://www.tropo.com/docs/scripting/troposessionapi.htm' target=_blank>Tropo.com</a>")) # CRUD Strings s3.crud_strings[tablename] = Storage( label_create=T("Create Tropo Channel"), title_display=T("Tropo Channel Details"), title_list=T("Tropo Channels"), title_update=T("Edit Tropo Channel"), label_list_button=T("List Tropo Channels"), label_delete_button=T("Delete Tropo Channel"), msg_record_created=T("Tropo Channel added"), msg_record_modified=T("Tropo Channel updated"), msg_record_deleted=T("Tropo Channel deleted"), msg_list_empty=T("No Tropo Channels currently registered")) return s3_rest_controller() # ----------------------------------------------------------------------------- @auth.s3_requires_membership(1) def twitter_channel(): """ RESTful CRUD controller for Twitter channels - appears in the administration menu Only 1 of these normally in existence @ToDo: Don't enforce """ #try: # import tweepy #except: # session.error = T("tweepy module not available within the running Python - this needs installing for non-Tropo Twitter support!") # redirect(URL(c="admin", f="index")) tablename = "%s_%s" % (module, resourcename) table = s3db[tablename] # CRUD Strings s3.crud_strings[tablename] = Storage( title_update = T("Edit Twitter account"), msg_record_modified = T("Twitter account updated"), ) def prep(r): oauth_consumer_key = settings.msg.twitter_oauth_consumer_key oauth_consumer_secret = settings.msg.twitter_oauth_consumer_secret if not (oauth_consumer_key and oauth_consumer_secret): session.error = T("You should edit Twitter settings in models/000_config.py") return True oauth = tweepy.OAuthHandler(oauth_consumer_key, oauth_consumer_secret) if r.http == "GET" and r.method in ("create", "update"): # We're showing the form _s3 = session.s3 try: _s3.twitter_oauth_url = oauth.get_authorization_url() _s3.twitter_request_key = oauth.request_token.key _s3.twitter_request_secret = oauth.request_token.secret except tweepy.TweepError: session.error = T("Problem connecting to twitter.com - please refresh") return True #table.pin.readable = True #table.pin.label = T("PIN number from Twitter (leave empty to detach account)") #table.pin.value = "" table.twitter_account.label = T("Current Twitter account") return True else: # Not showing form, no need for pin #table.pin.readable = False #table.pin.label = T("PIN") # won't be seen #table.pin.value = "" # but let's be on the safe side pass return True #s3.prep = prep # Post-process def postp(r, output): if r.interactive: # Normal Action Buttons s3_action_buttons(r) # Custom Action Buttons for Enable/Disable table = r.table query = (table.deleted == False) rows = db(query).select(table.id, table.enabled, ) restrict_e = [str(row.id) for row in rows if not row.enabled] restrict_d = [str(row.id) for row in rows if row.enabled] s3.actions += [dict(label=str(T("Enable")), _class="action-btn", url=URL(args=["[id]", "enable"]), restrict = restrict_e), dict(label=str(T("Disable")), _class="action-btn", url = URL(args = ["[id]", "disable"]), restrict = restrict_d), ] if not s3task._is_alive(): # No Scheduler Running s3.actions += [dict(label=str(T("Poll")), _class="action-btn", url = URL(args = ["[id]", "poll"]), restrict = restrict_d) ] #if isinstance(output, dict): # if r.http == "GET" and r.method in ("create", "update"): # rheader = A(T("Collect PIN from Twitter"), # _href=session.s3.twitter_oauth_url, # _target="_blank") # output["rheader"] = rheader return output s3.postp = postp s3db.configure(tablename, listadd = False, deletable = False, ) return s3_rest_controller(deduplicate="", list_btn="") # ----------------------------------------------------------------------------- def inject_search_after_save(output): """ Inject a Search After Save checkbox in the Twitter Search Query Form """ if "form" in output: id = "search_after_save" label = LABEL("%s:" % T("Search After Save?"), _for="msg_twitter_search") widget = INPUT(_name="search_after_save", _type="checkbox", value="on", _id=id, _class="boolean") comment = "" if s3_formstyle == "bootstrap": _controls = DIV(widget, comment, _class="controls") row = DIV(label, _controls, _class="control-group", _id="%s__row" % id ) elif callable(s3_formstyle): row = s3_formstyle(id, label, widget, comment) else: # Unsupported raise output["form"][0][-2].append(row) # ----------------------------------------------------------------------------- def action_after_save(form): """ Schedules Twitter query search immediately after save depending on flag """ if request.post_vars.get("search_after_save"): s3task.async("msg_twitter_search", args=[form.vars.id]) session.information = T("The search results should appear shortly - refresh to see them") # ----------------------------------------------------------------------------- def twitter_search(): """ RESTful CRUD controller to add keywords for Twitter Search """ tablename = "msg_twitter_search" table = s3db[tablename] table.is_processed.writable = False table.is_searched.writable = False table.is_processed.readable = False table.is_searched.readable = False langs = settings.get_L10n_languages().keys() # Tweak languages to those supported by Twitter S3Msg = s3base.S3Msg() try: import tweepy except: session.error = T("tweepy module not available within the running Python - this needs installing for non-Tropo Twitter support!") redirect(URL(c="msg", f="index")) twitter_settings = S3Msg.get_twitter_api() supported_languages = ['fr', 'en', 'ar', 'ja', 'es', 'de', 'it', 'id', 'pt', 'ko', 'tr', 'ru', 'nl', 'fil', 'msa', 'zh-tw', 'zh-cn', 'hi', 'no', 'sv', 'fi', 'da', 'pl', 'hu', 'fa', 'he', 'ur', 'th'] if twitter_settings: twitter_api = twitter_settings[0] try: supported_languages = map(lambda x: str(x["code"]), twitter_api.supported_languages()) except (tweepy.TweepError, AttributeError): # List according to Twitter 1.1 API https://dev.twitter.com/docs/api/1.1/get/help/languages pass substitute_list = {"en-gb": "en", "pt-br": "pt"} new_langs = [] lang_default = current.response.s3.language for l in langs: if l in supported_languages: new_langs.append(l) else: supported_substitute = substitute_list.get(l) if supported_substitute: if lang_default == l: lang_default = supported_substitute if supported_substitute not in langs: new_langs.append(supported_substitute) else: if lang_default == l: lang_default = 'en' langs = new_langs table.lang.requires = IS_IN_SET(langs) table.lang.default = lang_default comment = "Add the keywords separated by single spaces." table.keywords.comment = DIV(_class="tooltip", _title="%s|%s" % (T("Keywords"), T(comment))) # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Twitter Search Queries"), title_list = T("Twitter Search Queries"), label_create = T("Add Twitter Search Query"), title_update = T("Edit Twitter Search Query"), label_list_button = T("View Queries"), msg_record_created = T("Query added"), msg_record_deleted = T("Query deleted"), msg_list_empty = T("No Query currently defined"), msg_record_modified = T("Query updated") ) if request.post_vars.get("search_after_save"): url_after_save = URL(f="twitter_result") else: url_after_save = None s3db.configure(tablename, listadd=True, deletable=True, create_onaccept=action_after_save, create_next=url_after_save ) def prep(r): if r.interactive: table = s3db.msg_twitter_channel if not db(table.id > 0).select(table.id, limitby=(0, 1)).first(): session.error = T("Need to configure Twitter Authentication") redirect(URL(f="twitter_channel")) return True s3.prep = prep def postp(r, output): if r.interactive: # Normal Action Buttons s3_action_buttons(r) # Custom Action Buttons rtable = r.table query = (rtable.deleted == False) & \ (rtable.is_searched == False) records = db(query).select(rtable.id) restrict_s = [str(record.id) for record in records] query = (rtable.deleted == False) & \ (rtable.is_processed == False) records = db(query).select(rtable.id) restrict_k = [str(record.id) for record in records] # @ToDo: Make these S3Methods rather than additional controllers s3.actions += [dict(label=str(T("Search")), _class="action-btn", url=URL(args=["[id]", "poll"]), restrict = restrict_s), dict(label=str(T("Analyze with KeyGraph")), _class="action-btn", url = URL(args=["[id]", "keygraph"]), restrict = restrict_k), ] inject_search_after_save(output) return output s3.postp = postp return s3_rest_controller() # ----------------------------------------------------------------------------- def twitter_result(): """ RESTful CRUD controller for Twitter Search Results. """ tablename = "msg_twitter_result" # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Twitter Search Results"), title_list = T("Twitter Search Results"), label_list_button = T("View Tweets"), msg_record_deleted = T("Tweet deleted"), msg_list_empty = T("No Tweets Available."), ) from s3.s3filter import S3DateFilter, S3TextFilter filter_widgets = [ S3DateFilter("date", label=T("Tweeted on"), hide_time=True, _class="date-filter-class", comment=T("Filter Tweets by the date they were tweeted on"), ), S3TextFilter("from_address", label=T("Tweeted by"), _class="tweeter-filter-class", comment=T("Filter Tweets by who tweeted them"), ) ] report_fields = ["search_id", "date", "lang", ] report_options = Storage( rows=report_fields, cols=report_fields, fact=report_fields, defaults=Storage( rows="search_id", cols="lang", totals=True, ) ) s3db.configure(tablename, deletable=False, editable=False, insertable=False, filter_widgets=filter_widgets, report_options=report_options, ) def postp(r, output): if r.id or r.method in ("read", "display"): # Display the Tweet as an Embedded tweet record = output["item"].record # Tweet link twitter_url = "https://twitter.com/%s/statuses/%s" % (record.from_address, record.tweet_id) script_url = "https://platform.twitter.com/widgets.js" # Themeable Throbber throbber = DIV(_class = "s3-twitter-throbber", ) # Display throbber while Tweet loads tweet_container = DIV(throbber, _class = "s3-twitter-container", ) tweet_user = TAG[""](A(_href = twitter_url, _style = "display: none"), ) # Configure Tweet display attributes = {"_width": "350px", "_data-conversation": "none", "_class": "twitter-tweet", "lang": record.lang, } tweet = TAG["blockquote"](tweet_container, tweet_user, SCRIPT(_src = script_url, _charset = "utf-8"), **attributes ) # Insert tweet output["item"] = tweet return output s3.postp = postp return s3_rest_controller() # ----------------------------------------------------------------------------- def sender(): """ RESTful CRUD controller for whitelisting senders. User can assign priority to senders. """ tablename = "msg_sender" # CRUD Strings s3.crud_strings[tablename] = Storage( title_display = T("Whitelisted Senders"), title_list = T("Whitelisted Senders"), label_create = T("Whitelist a Sender"), title_update = T("Edit Sender Priority"), label_list_button = T("View Sender Priority"), msg_record_created = T("Sender Whitelisted"), msg_record_deleted = T("Sender deleted"), msg_list_empty = T("No Senders Whitelisted"), msg_record_modified = T("Sender Priority updated") ) s3db.configure(tablename, listadd=True) def prep(r): if r.method == "create": dsender = request.vars['sender'] dpriority = request.vars['priority'] r.table.sender.default = dsender r.table.priority.default = dpriority return True s3.prep = prep return s3_rest_controller() # ----------------------------------------------------------------------------- def keyword(): """ REST Controller """ return s3_rest_controller() # ----------------------------------------------------------------------------- def parser(): """ RESTful CRUD controller for Parsers - appears in the administration menu """ if not auth.s3_has_role(ADMIN): session.error = ERROR.UNAUTHORISED redirect(URL(f="index")) def prep(r): if r.interactive: # CRUD Strings s3.crud_strings["msg_parser"] = Storage( title_display = T("Parser Connection Details"), title_list = T("Parser Connections"), label_create = T("Connect Parser"), title_update = T("Edit Parser Connection"), label_list_button = T("View Parser Connections"), msg_record_created = T("Parser connected"), msg_record_deleted = T("Parser connection removed"), msg_record_modified = T("Parser connection updated"), msg_list_empty = T("No Parsers currently connected"), ) import inspect import sys template = settings.get_msg_parser() module_name = "applications.%s.modules.templates.%s.parser" % \ (appname, template) __import__(module_name) mymodule = sys.modules[module_name] S3Parser = mymodule.S3Parser() # Dynamic lookup of the parsing functions in S3Parser class. parsers = inspect.getmembers(S3Parser, \ predicate=inspect.isfunction) parse_opts = [] pappend = parse_opts.append for p in parsers: p = p[0] # Filter out helper functions if not p.startswith("_"): pappend(p) table = r.table table.channel_id.requires = IS_ONE_OF(db, "msg_channel.channel_id", s3base.S3Represent(lookup="msg_channel"), sort = True, ) table.function_name.requires = IS_IN_SET(parse_opts, zero = None) return True s3.prep = prep def postp(r, output): if r.interactive: # Normal Action Buttons s3_action_buttons(r) # Custom Action Buttons for Enable/Disable table = r.table query = (table.deleted == False) rows = db(query).select(table.id, table.enabled, ) restrict_e = [str(row.id) for row in rows if not row.enabled] restrict_d = [str(row.id) for row in rows if row.enabled] s3.actions += [dict(label=str(T("Enable")), _class="action-btn", url=URL(args=["[id]", "enable"]), restrict = restrict_e), dict(label=str(T("Disable")), _class="action-btn", url = URL(args = ["[id]", "disable"]), restrict = restrict_d), ] if not s3task._is_alive(): # No Scheduler Running s3.actions += [dict(label=str(T("Parse")), _class="action-btn", url = URL(args = ["[id]", "parse"]), restrict = restrict_d) ] return output s3.postp = postp return s3_rest_controller() # ============================================================================= # The following functions hook into the pr functions: # def group(): """ RESTful CRUD controller """ if auth.is_logged_in() or auth.basic(): pass else: redirect(URL(c="default", f="user", args="login", vars={"_next":URL(c="msg", f="group")})) module = "pr" tablename = "%s_%s" % (module, resourcename) table = s3db[tablename] # Hide unnecessary fields table.description.readable = table.description.writable = False # Do not show system groups s3.filter = (table.system == False) return s3_rest_controller(module, resourcename, rheader=s3db.pr_rheader) # ----------------------------------------------------------------------------- def group_membership(): """ RESTful CRUD controller """ if auth.is_logged_in() or auth.basic(): pass else: redirect(URL(c="default", f="user", args="login", vars={"_next":URL(c="msg", f="group_membership")})) table = s3db.pr_group_membership # Hide unnecessary fields table.comments.readable = table.comments.writable = False table.group_head.readable = table.group_head.writable = False return s3_rest_controller("pr", resourcename) # ----------------------------------------------------------------------------- def contact(): """ Allow the user to add, update and delete their contacts """ table = s3db.pr.contact ptable = s3db.pr_person if auth.is_logged_in() or auth.basic(): s3.filter = (table.pe_id == auth.user.pe_id) else: redirect(URL(c="default", f="user", args="login", vars={"_next":URL(c="msg", f="contact")})) # These fields will be populated automatically table.name.writable = table.name.readable = False table.pe_id.writable = table.pe_id.readable = False table.person_name.writable = table.person_name.readable = False table.id.writable = False #table.id.readable = False def msg_contact_onvalidation(form): # Add the person id to the record if auth.user: form.vars.pe_id = auth.user.pe_id s3db.configure(table._tablename, onvalidation=msg_contact_onvalidation) def prep(r): # Restrict update and delete access to contacts not owned by the user if r.id : pe_id = r.record.pe_id if auth.user and auth.user.pe_id == pe_id: return True else: session.error = T("Access denied") return dict(bypass = True, output = redirect(URL(r=request))) else: return True s3.prep = prep response.menu_options = [] return s3_rest_controller("pr", resourcename) # ----------------------------------------------------------------------------- def search(): """ Do a search of groups which match a type - used for auto-completion """ if not (auth.is_logged_in() or auth.basic()): # Not allowed return # JQuery UI Autocomplete uses 'term' instead of 'value' # (old JQuery Autocomplete uses 'q' instead of 'value') value = request.vars.term or request.vars.q type = get_vars.get("type", None) if value: # Call the search function if type: items = person_search(value, type) else: items = person_search(value) # Encode in JSON item = json.dumps(items) response.headers["Content-Type"] = "application/json" return item return # ----------------------------------------------------------------------------- def recipient_represent(id, default_label=""): """ Simplified output as-compared to pr_pentity_represent """ output = "" table = s3db.pr_pentity pe = db(table.pe_id == id).select(table.instance_type, limitby=(0, 1)).first() if not pe: return output instance_type = pe.instance_type table = db.get(instance_type, None) if not table: return output if instance_type == "pr_person": person = db(table.pe_id == id).select(table.first_name, table.middle_name, table.last_name, limitby=(0, 1)).first() if person: output = s3_fullname(person) elif instance_type == "pr_group": group = db(table.pe_id == id).select(table.name, limitby=(0, 1)).first() if group: output = group.name return output # ----------------------------------------------------------------------------- def person_search(value, type=None): """ Search for People & Groups which match a search term """ # Shortcuts groups = s3db.pr_group persons = s3db.pr_person items = [] # We want to do case-insensitive searches # (default anyway on MySQL/SQLite, but not PostgreSQL) value = value.lower() if type: represent = recipient_represent else: represent = s3db.pr_pentity_represent if type == "pr_group" or not type: # Check Groups query = (groups["name"].lower().like("%" + value + "%")) & (groups.deleted == False) rows = db(query).select(groups.pe_id) for row in rows: items.append({"id":row.pe_id, "name":represent(row.pe_id, default_label = "")}) if type == "pr_person" or not type: # Check Persons deleted = (persons.deleted == False) # First name query = (persons["first_name"].lower().like("%" + value + "%")) & deleted rows = db(query).select(persons.pe_id, cache=s3db.cache) for row in rows: items.append({"id":row.pe_id, "name":represent(row.pe_id, default_label = "")}) # Middle name query = (persons["middle_name"].lower().like("%" + value + "%")) & deleted rows = db(query).select(persons.pe_id, cache=s3db.cache) for row in rows: items.append({"id":row.pe_id, "name":represent(row.pe_id, default_label = "")}) # Last name query = (persons["last_name"].lower().like("%" + value + "%")) & deleted rows = db(query).select(persons.pe_id, cache=s3db.cache) for row in rows: items.append({"id":row.pe_id, "name":represent(row.pe_id, default_label = "")}) return items # ----------------------------------------------------------------------------- def subscription(): """ RESTful CRUD controller """ return s3_rest_controller() # ----------------------------------------------------------------------------- # Send Outbound Messages (was for being called via cron, now useful for debugging) # ----------------------------------------------------------------------------- def process_email_outbox(): """ Send Pending Email Messages """ msg.process_outbox(contact_method = "EMAIL") # ----------------------------------------------------------------------------- def process_sms_outbox(): """ Send Pending SMS Messages """ msg.process_outbox(contact_method = "SMS") # ----------------------------------------------------------------------------- def process_twitter_outbox(): """ Send Pending Twitter Messages """ msg.process_outbox(contact_method = "TWITTER") # ============================================================================= # Enabled only for testing: # @auth.s3_requires_membership(1) def facebook_post(): """ Post to Facebook """ title = T("Post to Facebook") # Test the formstyle formstyle = s3.crud.formstyle row = formstyle("test", "test", "test", "test") if isinstance(row, tuple): # Formstyle with separate row for label (e.g. default Eden formstyle) tuple_rows = True else: # Formstyle with just a single row (e.g. Bootstrap, Foundation or DRRPP) tuple_rows = False form_rows = [] comment = "" _id = "channel_id" label = LABEL("%s:" % T("Channel")) table = s3db.msg_facebook_channel query = (table.deleted == False) & \ (table.enabled == True) rows = db(query).select(table.channel_id, table.name) options = [OPTION(row.name, _value=row.channel_id) for row in rows] channel_select = SELECT(_name = "channel_id", _id = _id, *options ) widget = channel_select row = formstyle("%s__row" % _id, label, widget, comment) if tuple_rows: form_rows.append(row[0]) form_rows.append(row[1]) else: form_rows.append(row) _id = "post" label = LABEL("%s:" % T("Contents")) widget = TEXTAREA(_name = "post", ) row = formstyle("%s__row" % _id, label, widget, comment) if tuple_rows: form_rows.append(row[0]) form_rows.append(row[1]) else: form_rows.append(row) _id = "submit" label = "" widget = INPUT(_type="submit", _value=T("Post")) row = formstyle("%s__row" % _id, label, widget, comment) if tuple_rows: form_rows.append(row[0]) form_rows.append(row[1]) else: form_rows.append(row) if tuple_rows: # Assume TRs form = FORM(TABLE(*form_rows)) else: form = FORM(*form_rows) if form.accepts(request.vars, session): form_vars = form.vars channel_id = form_vars.get("channel_id") post = form_vars.get("post") if channel_id and post: msg.post_to_facebook(post, channel_id) output = dict(form = form, title = title, ) return output # ============================================================================= # Enabled only for testing: # @auth.s3_requires_membership(1) def twitter_post(): """ Post to Twitter """ title = T("Post to Twitter") # Test the formstyle formstyle = s3.crud.formstyle row = formstyle("test", "test", "test", "test") if isinstance(row, tuple): # Formstyle with separate row for label (e.g. default Eden formstyle) tuple_rows = True else: # Formstyle with just a single row (e.g. Bootstrap, Foundation or DRRPP) tuple_rows = False form_rows = [] comment = "" _id = "channel_id" label = LABEL("%s:" % T("Channel")) table = s3db.msg_twitter_channel query = (table.deleted == False) & \ (table.enabled == True) rows = db(query).select(table.channel_id, table.name) options = [OPTION(row.name, _value=row.channel_id) for row in rows] channel_select = SELECT(_name = "channel_id", _id = _id, *options ) widget = channel_select row = formstyle("%s__row" % _id, label, widget, comment) if tuple_rows: form_rows.append(row[0]) form_rows.append(row[1]) else: form_rows.append(row) _id = "post" label = LABEL("%s:" % T("Contents")) widget = TEXTAREA(_name = "post", ) row = formstyle("%s__row" % _id, label, widget, comment) if tuple_rows: form_rows.append(row[0]) form_rows.append(row[1]) else: form_rows.append(row) _id = "submit" label = "" widget = INPUT(_type="submit", _value=T("Post")) row = formstyle("%s__row" % _id, label, widget, comment) if tuple_rows: form_rows.append(row[0]) form_rows.append(row[1]) else: form_rows.append(row) if tuple_rows: # Assume TRs form = FORM(TABLE(*form_rows)) else: form = FORM(*form_rows) if form.accepts(request.vars, session): form_vars = form.vars channel_id = form_vars.get("channel_id") post = form_vars.get("post") if channel_id and post: msg.send_tweet(post) output = dict(form = form, title = title, ) return output # ============================================================================= # Enabled only for testing: # @auth.s3_requires_membership(1) def tag(): """ RESTful CRUD controller """ tablename = "%s_%s" % (module, resourcename) table = s3db[tablename] # Load all models s3db.load_all_models() table.resource.requires = IS_IN_SET(db.tables) s3db.configure(tablename, listadd=False) return s3_rest_controller() # ============================================================================= # Enabled only for testing: # def readKeyGraph(queryID): """ """ import os curpath = os.getcwd() f = open("%s.txt" % queryID, "r") topics = int(f.next()) nodelabel = {} E = [] nodetopic = {} for x in range(0, topics): thisnodes = [] nodes = int(f.next().split("KEYGRAPH_NODES:")[1]) for y in range(0, nodes): s = f.next() nodeid = s.split(":")[0] nodetopic[str(nodeid)] = x l1 = s.split(":")[1] l2 = s.split(":")[2] try: nodelabel[str(nodeid)] = unicode(l2.strip()) except: pass edges = int(f.next().split("KEYGRAPH_EDGES:")[1]) edges = edges / 2 for y in range(0,edges): s = f.next() n1 = s.split(" ")[0].strip() n2 = s.split(" ")[1].strip() if (n1 in nodelabel.keys()) and (n2 in nodelabel.keys()): E.append((str(n1), str(n2))) f.next() f.next() """ for x in range(0,len(E)): lx = list(E[x]) lx.append((nodetopic[E[x][0]] - nodetopic[E[x][1]] + 3)*100) E[x] = tuple(lx) """ #import networkx as nx from igraph import Graph, write_svg #g = nx.Graph() g = Graph() g.add_vertices([ str(s) for s in nodelabel.keys()]) #g.add_nodes_from(nodelabel) g.add_edges(E) g.vs["name"] = nodelabel.values() g.vs["label"] = g.vs["name"] g.vs["doc_id"] = nodelabel.keys() layout = g.layout_lgl() #layout = g.layout_kamada_kawai() visual_style = {} visual_style["vertex_size"] = 20 #visual_style["vertex_color"] = [color_dict[gender] for gender in g.vs["gender"]] visual_style["vertex_label"] = g.vs["name"] #visual_style["edge_width"] = [1 + 2 * int(len(is_formal)) for is_formal in g.vs["label"]] visual_style["layout"] = layout visual_style["bbox"] = (2000, 2000) visual_style["margin"] = 20 #plot(g, **visual_style) #c = g.clusters().subgraphs() #print g.ecount() filename = "%s.svg" % queryID write_svg(g.community_fastgreedy().as_clustering().graph, layout=layout, **visual_style) #plot(g.community_fastgreedy().as_clustering(), layout=layout) #plot(g) #g.add_weighted_edges_from(E) #nx.relabel_nodes(g, nodelabel, copy=False) #nx.draw(g, node_size=100, font_size=8, edge_size=10000) #labels = nx.draw_networkx_labels(g,pos=nx.spring_layout(g),labels=nodelabel) #import matplotlib.pyplot as plt #plt.savefig('kg3.png', facecolor='w', edgecolor='w',orientation='portrait', papertype=None, format=None,transparent=False, bbox_inches=None, pad_inches=0.1) #plt.show() # END ================================================================================
mit
akionakamura/scikit-learn
examples/svm/plot_svm_scale_c.py
223
5375
""" ============================================== Scaling the regularization parameter for SVCs ============================================== The following example illustrates the effect of scaling the regularization parameter when using :ref:`svm` for :ref:`classification <svm_classification>`. For SVC classification, we are interested in a risk minimization for the equation: .. math:: C \sum_{i=1, n} \mathcal{L} (f(x_i), y_i) + \Omega (w) where - :math:`C` is used to set the amount of regularization - :math:`\mathcal{L}` is a `loss` function of our samples and our model parameters. - :math:`\Omega` is a `penalty` function of our model parameters If we consider the loss function to be the individual error per sample, then the data-fit term, or the sum of the error for each sample, will increase as we add more samples. The penalization term, however, will not increase. When using, for example, :ref:`cross validation <cross_validation>`, to set the amount of regularization with `C`, there will be a different amount of samples between the main problem and the smaller problems within the folds of the cross validation. Since our loss function is dependent on the amount of samples, the latter will influence the selected value of `C`. The question that arises is `How do we optimally adjust C to account for the different amount of training samples?` The figures below are used to illustrate the effect of scaling our `C` to compensate for the change in the number of samples, in the case of using an `l1` penalty, as well as the `l2` penalty. l1-penalty case ----------------- In the `l1` case, theory says that prediction consistency (i.e. that under given hypothesis, the estimator learned predicts as well as a model knowing the true distribution) is not possible because of the bias of the `l1`. It does say, however, that model consistency, in terms of finding the right set of non-zero parameters as well as their signs, can be achieved by scaling `C1`. l2-penalty case ----------------- The theory says that in order to achieve prediction consistency, the penalty parameter should be kept constant as the number of samples grow. Simulations ------------ The two figures below plot the values of `C` on the `x-axis` and the corresponding cross-validation scores on the `y-axis`, for several different fractions of a generated data-set. In the `l1` penalty case, the cross-validation-error correlates best with the test-error, when scaling our `C` with the number of samples, `n`, which can be seen in the first figure. For the `l2` penalty case, the best result comes from the case where `C` is not scaled. .. topic:: Note: Two separate datasets are used for the two different plots. The reason behind this is the `l1` case works better on sparse data, while `l2` is better suited to the non-sparse case. """ print(__doc__) # Author: Andreas Mueller <amueller@ais.uni-bonn.de> # Jaques Grobler <jaques.grobler@inria.fr> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.svm import LinearSVC from sklearn.cross_validation import ShuffleSplit from sklearn.grid_search import GridSearchCV from sklearn.utils import check_random_state from sklearn import datasets rnd = check_random_state(1) # set up dataset n_samples = 100 n_features = 300 # l1 data (only 5 informative features) X_1, y_1 = datasets.make_classification(n_samples=n_samples, n_features=n_features, n_informative=5, random_state=1) # l2 data: non sparse, but less features y_2 = np.sign(.5 - rnd.rand(n_samples)) X_2 = rnd.randn(n_samples, n_features / 5) + y_2[:, np.newaxis] X_2 += 5 * rnd.randn(n_samples, n_features / 5) clf_sets = [(LinearSVC(penalty='l1', loss='squared_hinge', dual=False, tol=1e-3), np.logspace(-2.3, -1.3, 10), X_1, y_1), (LinearSVC(penalty='l2', loss='squared_hinge', dual=True, tol=1e-4), np.logspace(-4.5, -2, 10), X_2, y_2)] colors = ['b', 'g', 'r', 'c'] for fignum, (clf, cs, X, y) in enumerate(clf_sets): # set up the plot for each regressor plt.figure(fignum, figsize=(9, 10)) for k, train_size in enumerate(np.linspace(0.3, 0.7, 3)[::-1]): param_grid = dict(C=cs) # To get nice curve, we need a large number of iterations to # reduce the variance grid = GridSearchCV(clf, refit=False, param_grid=param_grid, cv=ShuffleSplit(n=n_samples, train_size=train_size, n_iter=250, random_state=1)) grid.fit(X, y) scores = [x[1] for x in grid.grid_scores_] scales = [(1, 'No scaling'), ((n_samples * train_size), '1/n_samples'), ] for subplotnum, (scaler, name) in enumerate(scales): plt.subplot(2, 1, subplotnum + 1) plt.xlabel('C') plt.ylabel('CV Score') grid_cs = cs * float(scaler) # scale the C's plt.semilogx(grid_cs, scores, label="fraction %.2f" % train_size) plt.title('scaling=%s, penalty=%s, loss=%s' % (name, clf.penalty, clf.loss)) plt.legend(loc="best") plt.show()
bsd-3-clause
weidel-p/nest-simulator
extras/ConnPlotter/examples/connplotter_tutorial.py
12
27772
# -*- coding: utf-8 -*- # # connplotter_tutorial.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # NEST is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <http://www.gnu.org/licenses/>. # !======================== # ! ConnPlotter: A Tutorial # !======================== # ! # ! :Author: Hans Ekkehard Plesser # ! :Institution: Norwegian University of Life Sciences, Simula # ! Research Laboratory, RIKEN Brain Sciences Institute # ! :Version: 0.7 # ! :Date: 1 December 2009 # ! :Copyright: Hans Ekkehard Plesser # ! :License: Creative Commons Attribution-Noncommercial-Share Alike License # ! v 3.0 # ! # ! :Note: For best results, you should run this script with PyReport by # ! Gael Varoquaux, available from # ! http://gael-varoquaux.info/computers/pyreport/ # ! # ! Please set using_pyreport to True if you want to run the # ! script through pyreport. Otherwise, figures will not be captured # ! correctly. using_pyreport = False # ! Introduction # !============= # ! This tutorial gives a brief introduction to the ConnPlotter # ! toolbox. It is by no means complete. # ! Avoid interactive backend when using pyreport if using_pyreport: import matplotlib matplotlib.use("Agg") # ! Import pyplot to call plt.show() so that pyreport # ! can capture figures created. Must come before import # ! ConnPlotter so we get the correct show(). import matplotlib.pyplot as plt # ! If not using pyreport, disable plt.show() until we reach end of script if not using_pyreport: plt_show = plt.show def nop(s=None): pass plt.show = nop # ! Import numpy import numpy as np # ! Import NEST import nest # ! Import ConnPlotter and its examples import ConnPlotter as cpl import ConnPlotter.examples as ex # ! Turn of warnings about resized figure windows import warnings warnings.simplefilter("ignore") # ! Define a helper function to show LaTeX tables on the fly def showTextTable(connPattern, fileTrunk): """ Shows a Table of Connectivity as textual table. Arguments: connPattern ConnectionPattern instance fileTrunk Eventual PNG image will be fileTrunk.png """ import subprocess as subp # to call LaTeX etc import os # to remove files # Write to LaTeX file so we get a nice textual representation # We want a complete LaTeX document, so we set ``standalone`` # to ``True``. connPattern.toLaTeX(file=fileTrunk + '.tex', standalone=True, enumerate=True) # Create PDF, crop, and convert to PNG try: devnull = open('/dev/null', 'w') subp.call(['pdflatex', fileTrunk], stdout=devnull, stderr=subp.STDOUT) # need wrapper, since pdfcrop does not begin with #! subp.call(['pdfcrop ' + fileTrunk + '.pdf ' + fileTrunk + '-crop.pdf'], shell=True, stdout=devnull, stderr=subp.STDOUT) devnull.close() os.rename(fileTrunk + '-crop.pdf', fileTrunk + '.pdf') for suffix in ('.tex', '-crop.pdf', '.png', '.aux', '.log'): if os.path.exists(fileTrunk + suffix): os.remove(fileTrunk + suffix) except: raise Exception('Could not create PDF Table.') # ! Simple network # ! ============== # ! This is a simple network with two layers A and B; layer B has two # ! populations, E and I. On the NEST side, we use only synapse type # ! ``static_synapse``. ConnPlotter then infers that synapses with positive # ! weights should have type ``exc``, those with negative weight type ``inh``. # ! Those two types are know to ConnPlotter. # ! Obtain layer, connection and model list from the example set s_layer, s_conn, s_model = ex.simple() # ! Create Connection Pattern representation # p is evaluated, in case it is a Parameter for i in range(len(s_conn)): s_conn[i][2]['p'] = eval(str(s_conn[i][2]['p'])) s_cp = cpl.ConnectionPattern(s_layer, s_conn) # ! Show pattern as textual table (we cheat a little and include PDF directly) showTextTable(s_cp, 'simple_tt') # $ \centerline{\includegraphics{simple_tt.pdf}} # ! Show pattern in full detail # ! --------------------------- # ! A separate patch is shown for each pair of populations. # ! # ! - Rows represent senders, columns targets. # ! - Layer names are given to the left/above, population names to the right # ! and below. # ! - Excitatory synapses shown in blue, inhibitory in red. # ! - Each patch has its own color scale. s_cp.plot() plt.show() # ! Let us take a look at what this connection pattern table shows: # ! # ! - The left column, with header "A", is empty: The "A" layer receives # ! no input. # ! - The right column shows input to layer "B" # ! # ! * The top row, labeled "A", has two patches in the "B" column: # ! # ! + The left patch shows relatively focused input to the "E" population # ! in layer "B" (first row of "Connectivity" table). # ! + The right patch shows wider input to the "I" population in layer # ! "B" (second row of "Connectivity" table). # ! + Patches are red, indicating excitatory connections. # ! + In both cases, mask are circular, and the product of connection # ! weight and probability is independent of the distance between sender # ! and target neuron. # ! # ! * The grey rectangle to the bottom right shows all connections from # ! layer "B" populations to layer "B" populations. It is subdivided into # ! two rows and two columns: # ! # ! + Left column: inputs to the "E" population. # ! + Right column: inputs to the "I" population. # ! + Top row: projections from the "E" population. # ! + Bottom row: projections from the "I" population. # ! + There is only one type of synapse for each sender-target pair, # ! so there is only a single patch per pair. # ! + Patches in the top row, from population "E" show excitatory # ! connections, thus they are red. # ! + Patches in the bottom row, from population "I" show inhibitory # ! connections, thus they are blue. # ! + The patches in detail are: # ! # ! - **E to E** (top-left, row 3+4 in table): two rectangular # ! projections at 90 degrees. # ! - **E to I** (top-right, row 5 in table): narrow gaussian projection. # ! - **I to E** (bottom-left, row 6 in table): wider gaussian projection # ! - **I to I** (bottom-right, row 7 in table): circular projection # ! covering entire layer. # ! # ! - **NB:** Color scales are different, so one **cannot** compare connection # ! strengths between patches. # ! Full detail, common color scale # ! ------------------------------- s_cp.plot(globalColors=True) plt.show() # ! This figure shows the same data as the one above, but now all patches use # ! a common color scale, so full intensity color (either red or blue) # ! indicates the strongest connectivity. From this we see that # ! # ! - A to B/E is stronger than A to B/I # ! - B/E to B/I is the strongest of all connections at the center # ! - B/I to B/E is stronger than B/I to B/I # ! Aggregate by groups # ! ------------------- # ! For each pair of population groups, sum connections of the same type # ! across populations. s_cp.plot(aggrGroups=True) plt.show() # ! In the figure above, all excitatory connections from B to B layer have been # ! combined into one patch, as have all inhibitory connections from B to B. # ! In the upper-right corner, all connections from layer A to layer B have # ! been combined; the patch for inhibitory connections is missing, as there # ! are none. # ! Aggregate by groups and synapse models # ! -------------------------------------- s_cp.plot(aggrGroups=True, aggrSyns=True) plt.show() # ! When aggregating across synapse models, excitatory and inhibitory # ! connections are combined. By default, excitatory connections are weights # ! with +1, inhibitory connections with -1 in the sum. This may yield kernels # ! with positive and negative values. They are shown on a red-white-blue scale # ! as follows: # ! # ! - White always represents 0. # ! - Positive values are represented by increasingly saturated red. # ! - Negative values are represented by increasingly saturated blue. # ! - Colorscales are separate for red and blue: # ! # ! * largest positive value: fully saturated red # ! * largest negative value: fully saturated blue # ! # ! - Each patch has its own colorscales. # ! - When ``aggrSyns=True`` is combined with ``globalColors=True``, # ! all patches use the same minimum and maximum in their red and blue # ! color scales. The the minimum is the negative of the maximum, so that # ! blue and red intesities can be compared. s_cp.plot(aggrGroups=True, aggrSyns=True, globalColors=True) plt.show() # ! - We can explicitly set the limits of the color scale; if values exceeding # ! the limits are present, this is indicated by an arrowhead at the end of # ! the colorbar. User-defined color limits need not be symmetric about 0. s_cp.plot(aggrGroups=True, aggrSyns=True, globalColors=True, colorLimits=[-2, 3]) plt.show() # ! Save pattern to file # ! -------------------- # s_cp.plot(file='simple_example.png') # ! This saves the detailed diagram to the given file. If you want to save # ! the pattern in several file formats, you can pass a tuple of file names, # ! e.g., ``s_cp.plot(file=('a.eps', 'a.png'))``. # ! # ! **NB:** Saving directly to PDF may lead to files with artifacts. We # ! recommend to save to EPS and the convert to PDF. # ! Build network in NEST # ! --------------------- # ! Create models for model in s_model: nest.CopyModel(model[0], model[1], model[2]) # ! Create layers, store layer info in Python variable for layer in s_layer: exec('{} = nest.Create(layer[1], positions=nest.spatial.grid(layer[2], extent=layer[3]))'.format(layer[0])) # ! Create connections, need to insert variable names for conn in s_conn: eval('nest.Connect({}, {}, conn[2], conn[3])'.format(conn[0], conn[1])) nest.Simulate(10) # ! **Ooops:*** Nothing happened? Well, it did, but pyreport cannot capture the # ! output directly generated by NEST. The absence of an error message in this # ! place shows that network construction and simulation went through. # ! Inspecting the connections actually created # ! ::::::::::::::::::::::::::::::::::::::::::: # ! The following block of messy and makeshift code plots the targets of the # ! center neuron of the B/E population in the B/E and the B/I populations. E_ctr = nest.FindCenterElement(RG_E) # get all targets, split into excitatory and inhibitory Econns = nest.GetConnections(E_ctr, RG_E, synapse_model='static_synapse') Etgts = Econns.get('target') Iconns = nest.GetConnections(E_ctr, RG_I, synapse_model='static_synapse') Itgts = Iconns.get('target') # obtain positions of targets Etpos = np.array([nest.GetPosition(RG_E[RG_E.index(tnode_id)]) for tnode_id in Etgts]) Itpos = np.array([nest.GetPosition(RG_I[RG_I.index(tnode_id)]) for tnode_id in Itgts]) # plot excitatory plt.clf() plt.subplot(121) plt.scatter(Etpos[:, 0], Etpos[:, 1]) ctrpos = nest.GetPosition(E_ctr) ax = plt.gca() ax.add_patch(plt.Circle(ctrpos, radius=0.02, zorder=99, fc='r', alpha=0.4, ec='none')) ax.add_patch( plt.Rectangle(ctrpos + np.array((-0.4, -0.2)), 0.8, 0.4, zorder=1, fc='none', ec='r', lw=3)) ax.add_patch( plt.Rectangle(ctrpos + np.array((-0.2, -0.4)), 0.4, 0.8, zorder=1, fc='none', ec='r', lw=3)) ax.add_patch( plt.Rectangle(ctrpos + np.array((-0.5, -0.5)), 1.0, 1.0, zorder=1, fc='none', ec='k', lw=3)) ax.set(aspect='equal', xlim=[-0.5, 0.5], ylim=[-0.5, 0.5], xticks=[], yticks=[]) # plot inhibitory plt.subplot(122) plt.scatter(Itpos[:, 0], Itpos[:, 1]) ctrpos = nest.GetPosition(E_ctr) ax = plt.gca() ax.add_patch(plt.Circle(ctrpos, radius=0.02, zorder=99, fc='r', alpha=0.4, ec='none')) ax.add_patch(plt.Circle(ctrpos, radius=0.1, zorder=2, fc='none', ec='r', lw=2, ls='dashed')) ax.add_patch(plt.Circle(ctrpos, radius=0.2, zorder=2, fc='none', ec='r', lw=2, ls='dashed')) ax.add_patch(plt.Circle(ctrpos, radius=0.3, zorder=2, fc='none', ec='r', lw=2, ls='dashed')) ax.add_patch(plt.Circle(ctrpos, radius=0.5, zorder=2, fc='none', ec='r', lw=3)) ax.add_patch(plt.Rectangle((-0.5, -0.5), 1.0, 1.0, zorder=1, fc='none', ec='k', lw=3)) ax.set(aspect='equal', xlim=[-0.5, 0.5], ylim=[-0.5, 0.5], xticks=[], yticks=[]) plt.show() # ! Thick red lines mark the mask, dashed red lines to the right one, two and # ! three standard deviations. The sender location is marked by the red spot # ! in the center. Layers are 40x40 in size. # ! A more complex network # ! ====================== # ! # ! This network has layers A and B, with E and I populations in B. The added # ! complexity comes from the fact that we now have four synapse types: AMPA, # ! NMDA, GABA_A and GABA_B. These synapse types are known to ConnPlotter. # ! Setup and tabular display c_layer, c_conn, c_model = ex.complex() # p is evaluated, in case it is a Parameter for i in range(len(c_conn)): c_conn[i][2]['p'] = eval(str(c_conn[i][2]['p'])) c_cp = cpl.ConnectionPattern(c_layer, c_conn) showTextTable(c_cp, 'complex_tt') # $ \centerline{\includegraphics{complex_tt.pdf}} # ! Pattern in full detail # ! ---------------------- c_cp.plot() plt.show() # ! Note the following differences to the simple pattern case: # ! # ! - For each pair of populations, e.g., B/E as sender and B/E as target, # ! we now have two patches representing AMPA and NMDA synapse for the E # ! population, GABA_A and _B for the I population. # ! - Colors are as follows: # ! # ! :AMPA: red # ! :NMDA: orange # ! :GABA_A: blue # ! :GABA_B: purple # ! - Note that the horizontal rectangular pattern (table line 3) describes # ! AMPA synapses, while the vertical rectangular pattern (table line 4) # ! describes NMDA synapses. # ! Full detail, common color scale # ! ------------------------------- c_cp.plot(globalColors=True) plt.show() # ! As above, but now with a common color scale. # ! **NB:** The patch for the B/I to B/I connection may look empty, but it # ! actually shows a very light shade of red. Rules are as follows: # ! # ! - If there is no connection between two populations, show the grey layer # ! background. # ! - All parts of the target layer that are outside the mask or strictly zero # ! are off-white. # ! - If it looks bright white, it is a very diluted shade of the color for the # ! pertaining synpase type. # ! Full detail, explicit color limits # ! ---------------------------------- c_cp.plot(colorLimits=[0, 1]) plt.show() # ! As above, but the common color scale is now given explicitly. # ! The arrow at the right end of the color scale indicates that the values # ! in the kernels extend beyond +1. # ! Aggregate by synapse models # ! ----------------------------- # ! For each population pair, connections are summed across # ! synapse models. # ! # ! - Excitatory kernels are weighted with +1, inhibitory kernels with -1. # ! - The resulting kernels are shown on a color scale ranging from red # ! (inhibitory) via white (zero) to blue (excitatory). # ! - Each patch has its own color scale c_cp.plot(aggrSyns=True) plt.show() # ! # ! - AMPA and NMDA connections from B/E to B/E are now combined to form a # ! cross. # ! - GABA_A and GABA_B connections from B/I to B/E are two concentric spots. # ! Aggregate by population group # ! ------------------------------ c_cp.plot(aggrGroups=True) plt.show() # ! This is in many ways orthogonal to aggregation by synapse model: # ! We keep synapse types separat, while we combine across populations. Thus, # ! we have added the horizonal bar (B/E to B/E, row 3) with the spot # ! (B/E to B/I, row 5). # ! Aggregate by population group and synapse model # ! ----------------------------------------------------------------- c_cp.plot(aggrGroups=True, aggrSyns=True) plt.show() # ! All connection are combined for each pair of sender/target layer. # ! CPTs using the total charge deposited (TCD) as intensity # ! ----------------------------------------------------------- # ! TCD-based CPTs are currently only available for the ht_neuron, since # ! ConnPlotter does not know how to obtain \int g(t) dt from NEST for other # ! conductance-based model neurons. # ! We need to create a separate ConnectionPattern instance for each membrane # ! potential we want to use in the TCD computation c_cp_75 = cpl.ConnectionPattern(c_layer, c_conn, intensity='tcd', mList=c_model, Vmem=-75.0) c_cp_45 = cpl.ConnectionPattern(c_layer, c_conn, intensity='tcd', mList=c_model, Vmem=-45.0) # ! In order to obtain a meaningful comparison between both membrane # ! potentials, we use the same global color scale. # ! V_m = -75 mV # ! :::::::::::::: c_cp_75.plot(colorLimits=[0, 150]) plt.show() # ! V_m = -45 mV # ! :::::::::::::: c_cp_45.plot(colorLimits=[0, 150]) plt.show() # ! Note that the NMDA projection virtually vanishes for V_m=-75mV, but is very # ! strong for V_m=-45mV. GABA_A and GABA_B projections are also stronger, # ! while AMPA is weaker for V_m=-45mV. # ! Non-Dale network model # ! ====================== # ! By default, ConnPlotter assumes that networks follow Dale's law, i.e., # ! either make excitatory or inhibitory connections. If this assumption # ! is violated, we need to inform ConnPlotter how synapse types are grouped. # ! We look at a simple example here. # ! Load model nd_layer, nd_conn, nd_model = ex.non_dale() # ! We specify the synapse configuration using the synTypes argument: # ! # ! - synTypes is a tuple. # ! - Each element in the tuple represents a group of synapse models # ! - Any sender can make connections with synapses from **one group only**. # ! - Each synapse model is specified by a ``SynType``. # ! - The SynType constructor takes three arguments: # ! # ! * The synapse model name # ! * The weight to apply then aggregating across synapse models # ! * The color to use for the synapse type # ! # ! - Synapse names must be unique, and must form a superset of all synapse # ! models in the network. nd_cp = cpl.ConnectionPattern(nd_layer, nd_conn, synTypes=( (cpl.SynType('exc', 1.0, 'b'), cpl.SynType('inh', -1.0, 'r')),)) showTextTable(nd_cp, 'non_dale_tt') # $ \centerline{\includegraphics{non_dale_tt.pdf}} nd_cp.plot() plt.show() # ! Note that we now have red and blue patches side by side, as the same # ! population can make excitatory and inhibitory connections. # ! Configuring the ConnectionPattern display # ! ========================================= # ! I will now show you a few ways in which you can configure how ConnPlotter # ! shows connection patterns. # ! User defined synapse types # ! -------------------------- # ! # ! By default, ConnPlotter knows two following sets of synapse types. # ! # ! exc/inh # ! - Used automatically when all connections have the same synapse_model. # ! - Connections with positive weight are assigned model exc, those with # ! negative weight model inh. # ! - When computing totals, exc has weight +1, inh weight -1 # ! - Exc is colored blue, inh red. # ! # ! AMPA/NMDA/GABA_A/GABA_B # ! - Used if the set of ``synapse_model`` s in the network is a subset of # ! those four types. # ! - AMPA/NMDA carry weight +1, GABA_A/GABA_B weight -1. # ! - Colors are as follows: # ! # ! :AMPA: blue # ! :NMDA: green # ! :GABA_A: red # ! :GABA_B: magenta # ! # ! # ! We saw a first example of user-defined synapse types in the non-Dale # ! example above. In that case, we only changed the grouping. Here, I will # ! demonstrate the effect of different ordering, weighting, and color # ! specifications. We use the complex model from above as example. # ! # ! *NOTE*: It is most likey a *bad idea* to change the colors or placement of # ! synapse types. If everyone uses the same design rules, we will all be able # ! to read each others figures much more easily. # ! Placement of synapse types # ! :::::::::::::::::::::::::: # ! # ! The ``synTypes`` nested tuple defines the placement of patches for # ! different synapse models. Default layout is # ! # ! ====== ====== # ! AMPA NMDA # ! GABA_A GABA_B # ! ====== ====== # ! # ! All four matrix elements are shown in this layout only when using # ! ``mode='layer'`` display. Otherwise, one or the other row is shown. # ! Note that synapses that can arise from a layer simultaneously, must # ! always be placed on one matrix row, i.e., in one group. As an example, # ! we now invert placement, without any other changes: cinv_syns = ((cpl.SynType('GABA_B', -1, 'm'), cpl.SynType('GABA_A', -1, 'r')), (cpl.SynType('NMDA', 1, 'g'), cpl.SynType('AMPA', 1, 'b'))) cinv_cp = cpl.ConnectionPattern(c_layer, c_conn, synTypes=cinv_syns) cinv_cp.plot() plt.show() # ! Notice that on each row the synapses are exchanged compared to the original # ! figure above. When displaying by layer, also the rows have traded place: cinv_cp.plot(aggrGroups=True) plt.show() # ! Totals are not affected: cinv_cp.plot(aggrGroups=True, aggrSyns=True) plt.show() # ! Weighting of synapse types in ``totals`` mode # ! ::::::::::::::::::::::::::::::::::::::::::::: # ! # ! Different synapses may have quite different efficacies, so weighting them # ! all with +-1 when computing totals may give a wrong impression. Different # ! weights can be supplied as second argument to SynTypes(). We return to the # ! normal placement of synapses and # ! create two examples with very different weights: cw1_syns = ((cpl.SynType('AMPA', 10, 'b'), cpl.SynType('NMDA', 1, 'g')), (cpl.SynType('GABA_A', -2, 'g'), cpl.SynType('GABA_B', -10, 'b'))) cw1_cp = cpl.ConnectionPattern(c_layer, c_conn, synTypes=cw1_syns) cw2_syns = ((cpl.SynType('AMPA', 1, 'b'), cpl.SynType('NMDA', 10, 'g')), (cpl.SynType('GABA_A', -20, 'g'), cpl.SynType('GABA_B', -1, 'b'))) cw2_cp = cpl.ConnectionPattern(c_layer, c_conn, synTypes=cw2_syns) # ! We first plot them both in population mode cw1_cp.plot(aggrSyns=True) plt.show() cw2_cp.plot(aggrSyns=True) plt.show() # ! Finally, we plot them aggregating across groups and synapse models cw1_cp.plot(aggrGroups=True, aggrSyns=True) plt.show() cw2_cp.plot(aggrGroups=True, aggrSyns=True) plt.show() # ! Alternative colors for synapse patches # ! :::::::::::::::::::::::::::::::::::::: # ! Different colors can be specified using any legal color specification. # ! Colors should be saturated, as they will be mixed with white. You may # ! also provide a colormap explicitly. For this example, we use once more # ! normal placement and weights. As all synapse types are shown in layer # ! mode, we use that mode for display here. cc_syns = ( (cpl.SynType('AMPA', 1, 'maroon'), cpl.SynType('NMDA', 1, (0.9, 0.5, 0))), (cpl.SynType('GABA_A', -1, '0.7'), cpl.SynType('GABA_B', 1, plt.cm.hsv))) cc_cp = cpl.ConnectionPattern(c_layer, c_conn, synTypes=cc_syns) cc_cp.plot(aggrGroups=True) plt.show() # ! We get the following colors: # ! # ! AMPA brownish # ! NMDA golden orange # ! GABA_A jet colormap from red (max) to blue (0) # ! GABA_B grey # ! # ! **NB:** When passing an explicit colormap, parts outside the mask will be # ! shown to the "bad" color of the colormap, usually the "bottom" color in the # ! map. To let points outside the mask appear in white, set the bad color of # ! the colormap; unfortunately, this modifies the colormap. plt.cm.hsv.set_bad(cpl.colormaps.bad_color) ccb_syns = ( (cpl.SynType('AMPA', 1, 'maroon'), cpl.SynType('NMDA', 1, (0.9, 0.5, 0.1))), (cpl.SynType('GABA_A', -1, '0.7'), cpl.SynType('GABA_B', 1, plt.cm.hsv))) ccb_cp = cpl.ConnectionPattern(c_layer, c_conn, synTypes=ccb_syns) ccb_cp.plot(aggrGroups=True) plt.show() # ! Other configuration options # ! --------------------------- # ! # ! Some more adjustments are possible by setting certain module properties. # ! Some of these need to be set before ConnectionPattern() is constructed. # ! # ! Background color for masked parts of each patch cpl.colormaps.bad_color = 'cyan' # ! Background for layers cpl.plotParams.layer_bg = (0.8, 0.8, 0.0) # ! Resolution for patch computation cpl.plotParams.n_kern = 5 # ! Physical size of patches: longest egde of largest patch, in mm cpl.plotParams.patch_size = 40 # ! Margins around the figure (excluding labels) cpl.plotParams.margins.left = 40 cpl.plotParams.margins.top = 30 cpl.plotParams.margins.bottom = 15 cpl.plotParams.margins.right = 30 # ! Fonts for layer and population labels import matplotlib.font_manager as fmgr cpl.plotParams.layer_font = fmgr.FontProperties(family='serif', weight='bold', size='xx-large') cpl.plotParams.pop_font = fmgr.FontProperties('small') # ! Orientation for layer and population label cpl.plotParams.layer_orientation = {'sender': 'vertical', 'target': 60} cpl.plotParams.pop_orientation = {'sender': 'horizontal', 'target': -45} # ! Font for legend titles and ticks, tick placement, and tick format cpl.plotParams.legend_title_font = fmgr.FontProperties(family='serif', weight='bold', size='large') cpl.plotParams.legend_tick_font = fmgr.FontProperties(family='sans-serif', weight='light', size='xx-small') cpl.plotParams.legend_ticks = [0, 1, 2] cpl.plotParams.legend_tick_format = '%.1f pA' cx_cp = cpl.ConnectionPattern(c_layer, c_conn) cx_cp.plot(colorLimits=[0, 2]) plt.show() # ! Several more options are available to control the format of the color bars # ! (they all are members of plotParams): # ! * legend_location : if 'top', place synapse name atop color bar # ! * cbwidth : width of single color bar relative to figure # ! * margins.colbar : height of lower margin set aside for color bar, in mm # ! * cbheight : height of single color bar relative to margins.colbar # ! * cbwidth : width of single color bar relative to figure width # ! * cbspace : spacing between color bars, relative to figure width # ! * cboffset : offset of first color bar from left margin, relative to # ! figure width # ! You can also specify the width of the final figure, but this may not work # ! well with on-screen display or here in pyreport. Width is in mm. # ! Note that left and right margin combined are 70mm wide, so only 50mm are # ! left for the actual CPT. cx_cp.plot(fixedWidth=120) plt.show() # ! If not using pyreport, we finally show and block if not using_pyreport: print("") print("The connplotter_tutorial script is done. " + "Call plt.show() and enjoy the figures!") print( "You may need to close all figures manually " + "to get the Python prompt back.") print("") plt.show = plt_show
gpl-2.0
jkleve/Optimization-Algorithms
tests/ga_analysis.py
1
6534
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import numpy as np import sys sys.path.append("../utils") sys.path.append("../functions") sys.path.append("../genetic_algorithm") import genetic_algorithm import ackley_function import easom_function import rosenbrock_function import griewank_function import ga_settings from oa_utils import read_xy_data, optimize_settings from test_helpers import gen_filename from regression_utils import get_regression_coef # def cmp_selection_cutoff_vs_mutation_rate(): # X, y = read_xy_data('../data/ga/griewank/max_mutation_amount,mutation_rate.dat') # # b = get_regression_coef(X, y) # # x1_start = 0.1 # x1_step = 0.1 # x1_end = 1.0 # x2_start = 0.1 # x2_step = 0.1 # x2_end = 1.0 # # fig = plt.figure() # ax1 = fig.add_subplot(111, projection='3d') # ax1.set_zlim(3, 9) # # for i, row in enumerate(X): # ax1.scatter(row[1],row[2],y[i]) # # pltx = np.arange(x1_start, x1_end+x1_step, x1_step) # plty = np.arange(x2_start, x2_end+x2_step, x2_step) # pltX, pltY = np.meshgrid(pltx, plty) # F = b[0] + b[1]*pltX + b[2]*pltY + b[3]*pltX*pltX + b[4]*pltX*pltY + b[5]*pltY*pltY # ax1.plot_wireframe(pltX, pltY, F) # ax1.contour(pltX, pltY, F, zdir='z', offset=3, cmap=cm.jet) # # ax1.set_title('Response Surface of Mutation Rate vs Selection Cutoff of GA on Griewank Function') # ax1.set_xlabel('Selection Cutoff') # ax1.set_ylabel('Mutation Rate') # ax1.set_zlabel('Mean Euclidean Distance from Global Minimum') # plt.show() def cmp_max_mutation_vs_mutation_rate(): X, y = read_xy_data('../data/ga/griewank/max_mutation_amount,mutation_rate.dat') b = get_regression_coef(X, y) x1_start = 0.1 x1_step = 0.1 x1_end = 1.0 x2_start = 0.1 x2_step = 0.1 x2_end = 1.0 fig = plt.figure() ax1 = fig.add_subplot(111, projection='3d') ax1.set_zlim(3, 9) for i, row in enumerate(X): ax1.scatter(row[1],row[2],y[i]) pltx = np.arange(x1_start, x1_end+x1_step, x1_step) plty = np.arange(x2_start, x2_end+x2_step, x2_step) pltX, pltY = np.meshgrid(pltx, plty) F = b[0] + b[1]*pltX + b[2]*pltY + b[3]*pltX*pltX + b[4]*pltX*pltY + b[5]*pltY*pltY ax1.plot_wireframe(pltX, pltY, F) ax1.contour(pltX, pltY, F, zdir='z', offset=3, cmap=cm.jet) ax1.set_title('Response Surface of Mutation Rate vs Maximum Mutation Allowed of GA on Griewank Function') ax1.set_xlabel('Mutation Amount') ax1.set_ylabel('Mutation Rate') ax1.set_zlabel('Mean Euclidean Distance from Global Minimum') plt.show() def cmp_func_val_over_iterations(o_algorithm, settings, o_function): x1_start = 0.3 x1_step = 0.1 x1_end = 0.6 x2_start = 0.25 x2_step = 0.25 x2_end = 0.75 x1_name = "selection_cutoff" x2_name = "mutation_rate" population_size = [50] optimize_settings(settings) fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True) tests1 = [] tests2 = [] tests3 = [] for test in population_size: for i, x1 in enumerate(np.arange(x1_start, x1_end+x1_step, x1_step)): for j, x2 in enumerate(np.arange(x2_start, x2_end+x2_step, x2_step)): settings[x1_name] = x1 settings[x2_name] = x2 f = [] settings['population_size'] = test algorithm = o_algorithm(settings, o_function) while settings['num_iterations'] > algorithm.num_generations: f.append(algorithm.get_best_f()) algorithm.do_loop() if j == 0: tests1.append("Selection Cutoff %4.2f Mutation Rate %4.2f" % (x1, x2)) ax1.plot(range(1,len(f)+1), f) elif j == 1: tests2.append("Selection Cutoff %4.2f Mutation Rate %4.2f" % (x1, x2)) ax2.plot(range(1,len(f)+1), f) elif j == 2: tests3.append("Selection Cutoff %4.2f Mutation Rate %4.2f" % (x1, x2)) ax3.plot(range(1,len(f)+1), f) ax1.legend(tests1) ax2.legend(tests2) ax3.legend(tests3) ax1.set_title('GA Comparison of Selection Cutoff & Mutation Rate on Ackley Function (50 particles)') ax1.set_xlabel('Number of Iterations') ax2.set_xlabel('Number of Iterations') ax3.set_xlabel('Number of Iterations') ax1.set_ylabel('Objective Function Value') ax2.set_ylabel('Objective Function Value') ax3.set_ylabel('Objective Function Value') #ax2.ylabel('Objective Function Value') #ax3.ylabel('Objective Function Value') #plt.legend(tests) plt.show() def create_bulk_var_cmp_graphs(): import ga_tests input_loc = '../tmp/' output_loc = '../tmp/' x1_start = 0.1 x1_step = 0.1 x1_end = 1.0 x2_start = 0.1 x2_step = 0.1 x2_end = 1.0 tests = ga_tests.tests functions = ga_tests.functions for f in functions: for t in tests.items(): names = t[1] x1_name = names['x1'] x2_name = names['x2'] filename = input_loc + gen_filename(x1_name, x2_name, f) (X, y) = read_xy_data(filename) b = get_regression_coef(X, y) fig = plt.figure() ax1 = fig.add_subplot(111, projection='3d') #ax1.set_zlim(3, 9) for i, row in enumerate(X): ax1.scatter(row[1],row[2],y[i]) pltx = np.arange(x1_start, x1_end+x1_step, x1_step) plty = np.arange(x2_start, x2_end+x2_step, x2_step) pltX, pltY = np.meshgrid(pltx, plty) F = b[0] + b[1]*pltX + b[2]*pltY + b[3]*pltX*pltX + b[4]*pltX*pltY + b[5]*pltY*pltY #ax1.plot_wireframe(pltX, pltY, F) ax1.contour(pltX, pltY, F, zdir='z', offset=0, cmap=cm.jet) ax1.set_title('Response Surface of Mutation Rate vs Selection Cutoff of GA on Griewank Function') ax1.set_xlabel('Selection Cutoff') ax1.set_ylabel('Mutation Rate') ax1.set_zlabel('Mean Euclidean Distance from Global Minimum') plt.show() if __name__ == "__main__": create_bulk_var_cmp_graphs() #cmp_selection_cutoff_vs_mutation_rate() #cmp_func_val_over_iterations(genetic_algorithm.GA, \ # ga_settings.settings, \ # ackley_function.objective_function)
mit
has2k1/plydata
plydata/one_table_verbs.py
1
33733
""" One table verb initializations """ import itertools from .operators import DataOperator from .expressions import Expression __all__ = ['define', 'create', 'sample_n', 'sample_frac', 'select', 'rename', 'distinct', 'unique', 'arrange', 'group_by', 'ungroup', 'group_indices', 'summarize', 'query', 'do', 'head', 'tail', 'pull', 'slice_rows', # Aliases 'summarise', 'mutate', 'transmute', ] class define(DataOperator): """ Add column to DataFrame Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. args : strs, tuples, optional Expressions or ``(name, expression)`` pairs. This should be used when the *name* is not a valid python variable name. The expression should be of type :class:`str` or an *interable* with the same number of elements as the dataframe. kwargs : dict, optional ``{name: expression}`` pairs. Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({'x': [1, 2, 3]}) >>> df >> define(x_sq='x**2') x x_sq 0 1 1 1 2 4 2 3 9 >>> df >> define(('x*2', 'x*2'), ('x*3', 'x*3'), x_cubed='x**3') x x*2 x*3 x_cubed 0 1 2 3 1 1 2 4 6 8 2 3 6 9 27 >>> df >> define('x*4') x x*4 0 1 4 1 2 8 2 3 12 Notes ----- If :obj:`plydata.options.modify_input_data` is ``True``, :class:`define` will modify the original dataframe. """ def __init__(self, *args, **kwargs): self.set_env_from_verb_init() cols = [] exprs = [] for arg in args: if isinstance(arg, str): col = expr = arg else: col, expr = arg cols.append(col) exprs.append(expr) _cols = itertools.chain(cols, kwargs.keys()) _exprs = itertools.chain(exprs, kwargs.values()) self.expressions = [Expression(stmt, col) for stmt, col in zip(_exprs, _cols)] class create(define): """ Create DataFrame with columns Similar to :class:`define`, but it drops the existing columns. Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. args : strs, tuples, optional Expressions or ``(name, expression)`` pairs. This should be used when the *name* is not a valid python variable name. The expression should be of type :class:`str` or an *interable* with the same number of elements as the dataframe. kwargs : dict, optional ``{name: expression}`` pairs. kwargs : dict, optional ``{name: expression}`` pairs. Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({'x': [1, 2, 3]}) >>> df >> create(x_sq='x**2') x_sq 0 1 1 4 2 9 >>> df >> create(('x*2', 'x*2'), ('x*3', 'x*3'), x_cubed='x**3') x*2 x*3 x_cubed 0 2 3 1 1 4 6 8 2 6 9 27 >>> df >> create('x*4') x*4 0 4 1 8 2 12 """ class sample_n(DataOperator): """ Sample n rows from dataframe Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. n : int, optional Number of items from axis to return. replace : boolean, optional Sample with or without replacement. Default = False. weights : str or ndarray-like, optional Default 'None' results in equal probability weighting. If passed a Series, will align with target object on index. Index values in weights not found in sampled object will be ignored and index values in sampled object not in weights will be assigned weights of zero. If called on a DataFrame, will accept the name of a column when axis = 0. Unless weights are a Series, weights must be same length as axis being sampled. If weights do not sum to 1, they will be normalized to sum to 1. Missing values in the weights column will be treated as zero. inf and -inf values not allowed. random_state : int or numpy.random.RandomState, optional Seed for the random number generator (if int), or numpy RandomState object. axis : int or string, optional Axis to sample. Accepts axis number or name. Default is stat axis for given data type (0 for Series and DataFrames, 1 for Panels). Examples -------- >>> import pandas as pd >>> import numpy as np >>> rs = np.random.RandomState(1234567890) >>> df = pd.DataFrame({'x': range(20)}) >>> df >> sample_n(5, random_state=rs) x 5 5 19 19 14 14 8 8 17 17 """ def __init__(self, n=1, replace=False, weights=None, random_state=None, axis=None): self.kwargs = dict(n=n, replace=replace, weights=weights, random_state=random_state, axis=axis) class sample_frac(DataOperator): """ Sample a fraction of rows from dataframe Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. frac : float, optional Fraction of axis items to return. Cannot be used with `n`. replace : boolean, optional Sample with or without replacement. Default = False. weights : str or ndarray-like, optional Default 'None' results in equal probability weighting. If passed a Series, will align with target object on index. Index values in weights not found in sampled object will be ignored and index values in sampled object not in weights will be assigned weights of zero. If called on a DataFrame, will accept the name of a column when axis = 0. Unless weights are a Series, weights must be same length as axis being sampled. If weights do not sum to 1, they will be normalized to sum to 1. Missing values in the weights column will be treated as zero. inf and -inf values not allowed. random_state : int or numpy.random.RandomState, optional Seed for the random number generator (if int), or numpy RandomState object. axis : int or string, optional Axis to sample. Accepts axis number or name. Default is stat axis for given data type (0 for Series and DataFrames, 1 for Panels). Examples -------- >>> import pandas as pd >>> import numpy as np >>> rs = np.random.RandomState(1234567890) >>> df = pd.DataFrame({'x': range(20)}) >>> df >> sample_frac(0.25, random_state=rs) x 5 5 19 19 14 14 8 8 17 17 """ def __init__(self, frac=None, replace=False, weights=None, random_state=None, axis=None): self.kwargs = dict( frac=frac, replace=replace, weights=weights, random_state=random_state, axis=axis) class select(DataOperator): """ Select columns by name Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. names : tuple, optional Names of columns in dataframe. Normally, they are strings can include slice e.g :py:`slice('col2', 'col5')`. You can also exclude columns by prepending a ``-`` e.g py:`select('-col1')`, will include all columns minus than *col1*. startswith : str or tuple, optional All column names that start with this string will be included. endswith : str or tuple, optional All column names that end with this string will be included. contains : str or tuple, optional All column names that contain with this string will be included. matches : str or regex or tuple, optional All column names that match the string or a compiled regex pattern will be included. A tuple can be used to match multiple regexs. drop : bool, optional If ``True``, the selection is inverted. The unspecified/unmatched columns are returned instead. Default is ``False``. Examples -------- >>> import pandas as pd >>> x = [1, 2, 3] >>> df = pd.DataFrame({'bell': x, 'whistle': x, 'nail': x, 'tail': x}) >>> df >> select('bell', 'nail') bell nail 0 1 1 1 2 2 2 3 3 >>> df >> select('bell', 'nail', drop=True) whistle tail 0 1 1 1 2 2 2 3 3 >>> df >> select('whistle', endswith='ail') whistle nail tail 0 1 1 1 1 2 2 2 2 3 3 3 >>> df >> select('bell', matches=r'\\w+tle$') bell whistle 0 1 1 1 2 2 2 3 3 You can select column slices too. Like :meth:`~pandas.DataFrame.loc`, the stop column is included. >>> df = pd.DataFrame({'a': x, 'b': x, 'c': x, 'd': x, ... 'e': x, 'f': x, 'g': x, 'h': x}) >>> df a b c d e f g h 0 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 >>> df >> select('a', slice('c', 'e'), 'g') a c d e g 0 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 You can exclude columns by prepending ``-`` >>> df >> select('-a', '-c', '-e') b d f g h 0 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 Remove and place column at the end >>> df >> select('-a', '-c', '-e', 'a') b d f g h a 0 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 Notes ----- To exclude columns by prepending a minus, the first column passed to :class:`select` must be prepended with minus. :py:`select('-a', 'c')` will exclude column ``a``, while :py:`select('c', '-a')` will not exclude column ``a``. """ def __init__(self, *names, startswith=None, endswith=None, contains=None, matches=None, drop=False): def as_tuple(obj): if obj is None: return tuple() elif isinstance(obj, tuple): return obj elif isinstance(obj, list): return tuple(obj) else: return (obj,) self.names = names self.startswith = as_tuple(startswith) self.endswith = as_tuple(endswith) self.contains = as_tuple(contains) self.matches = as_tuple(matches) self.drop = drop @staticmethod def from_columns(*columns): """ Create a select verb from the columns specification Parameters ---------- *columns : list-like | select | str | slice Column names to be gathered and whose contents will make values. Return ------ out : select Select verb representation of the columns. """ from .helper_verbs import select_all, select_at, select_if n = len(columns) if n == 0: return select_all() elif n == 1: obj = columns[0] if isinstance(obj, (select, select_all, select_at, select_if)): return obj elif isinstance(obj, slice): return select(obj) elif isinstance(obj, (list, tuple)): return select(*obj) elif isinstance(obj, str): return select(obj) else: raise TypeError( "Unrecognised type {}".format(type(obj)) ) else: return select(*columns) class rename(DataOperator): """ Rename columns Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. args : tuple, optional A single positional argument that holds ``{'new_name': 'old_name'}`` pairs. This is useful if the *old_name* is not a valid python variable name. kwargs : dict, optional ``{new_name: 'old_name'}`` pairs. If all the columns to be renamed are valid python variable names, then they can be specified as keyword arguments. Examples -------- >>> import pandas as pd >>> import numpy as np >>> x = np.array([1, 2, 3]) >>> df = pd.DataFrame({'bell': x, 'whistle': x, ... 'nail': x, 'tail': x}) >>> df >> rename(gong='bell', pin='nail') gong whistle pin tail 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 >>> df >> rename({'flap': 'tail'}, pin='nail') bell whistle pin flap 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 Notes ----- If :obj:`plydata.options.modify_input_data` is ``True``, :class:`rename` will modify the original dataframe. """ lookup = None def __init__(self, *args, **kwargs): lookup = args[0] if len(args) else {} self.lookup = {v: k for k, v in lookup.items()} self.lookup.update({v: k for k, v in kwargs.items()}) class distinct(DataOperator): """ Select distinct/unique rows Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. columns : list-like, optional Column names to use when determining uniqueness. keep : {'first', 'last', False}, optional - ``first`` : Keep the first occurence. - ``last`` : Keep the last occurence. - False : Do not keep any of the duplicates. Default is False. kwargs : dict, optional ``{name: expression}`` computed columns. If specified, these are taken together with the columns when determining unique rows. Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({'x': [1, 1, 2, 3, 4, 4, 5], ... 'y': [1, 2, 3, 4, 5, 5, 6]}) >>> df >> distinct() x y 0 1 1 1 1 2 2 2 3 3 3 4 4 4 5 6 5 6 >>> df >> distinct(['x']) x y 0 1 1 2 2 3 3 3 4 4 4 5 6 5 6 >>> df >> distinct(['x'], 'last') x y 1 1 2 2 2 3 3 3 4 5 4 5 6 5 6 >>> df >> distinct(z='x%2') x y z 0 1 1 1 2 2 3 0 >>> df >> distinct(['x'], z='x%2') x y z 0 1 1 1 2 2 3 0 3 3 4 1 4 4 5 0 6 5 6 1 >>> df >> define(z='x%2') >> distinct(['x', 'z']) x y z 0 1 1 1 2 2 3 0 3 3 4 1 4 4 5 0 6 5 6 1 """ columns = None keep = 'first' def __init__(self, *args, **kwargs): self.set_env_from_verb_init() if len(args) == 1: if isinstance(args[0], (str, bool)): self.keep = args[0] else: self.columns = args[0] elif len(args) == 2: self.columns, self.keep = args elif len(args) > 2: raise Exception("Too many positional arguments.") # define if kwargs: if self.columns is None: self.columns = [] elif not isinstance(self.columns, list): self.columns = list(self.columns) _cols = list(kwargs.keys()) _exprs = list(kwargs.values()) self.columns.extend(_cols) else: _cols = [] _exprs = [] self.expressions = [Expression(stmt, col) for stmt, col in zip(_exprs, _cols)] class arrange(DataOperator): """ Sort rows by column variables Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. args : tuple Columns/expressions to sort by. reset_index : bool, optional (default: True) If ``True``, the index is reset to a sequential range index. If ``False``, the original index is maintained. Examples -------- >>> import pandas as pd >>> import numpy as np >>> df = pd.DataFrame({'x': [1, 5, 2, 2, 4, 0], ... 'y': [1, 2, 3, 4, 5, 6]}) >>> df >> arrange('x') x y 0 0 6 1 1 1 2 2 3 3 2 4 4 4 5 5 5 2 >>> df >> arrange('x', '-y') x y 0 0 6 1 1 1 2 2 4 3 2 3 4 4 5 5 5 2 >>> df >> arrange('np.sin(y)') x y 0 4 5 1 2 4 2 0 6 3 2 3 4 1 1 5 5 2 """ expressions = None def __init__(self, *args, reset_index=True): self.set_env_from_verb_init() self.reset_index = reset_index name_gen = ('col_{}'.format(x) for x in range(100)) self.expressions = [ Expression(stmt, col) for stmt, col in zip(args, name_gen) ] class group_by(define): """ Group dataframe by one or more columns/variables Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. args : strs, tuples, optional Expressions or ``(name, expression)`` pairs. This should be used when the *name* is not a valid python variable name. The expression should be of type :class:`str` or an *interable* with the same number of elements as the dataframe. add_ : bool, optional If True, add to existing groups. Default is to create new groups. kwargs : dict, optional ``{name: expression}`` pairs. Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({'x': [1, 5, 2, 2, 4, 0, 4], ... 'y': [1, 2, 3, 4, 5, 6, 5]}) >>> df >> group_by('x') groups: ['x'] x y 0 1 1 1 5 2 2 2 3 3 2 4 4 4 5 5 0 6 6 4 5 Like :meth:`define`, :meth:`group_by` creates any missing columns. >>> df >> group_by('y-1', xplus1='x+1') groups: ['y-1', 'xplus1'] x y y-1 xplus1 0 1 1 0 2 1 5 2 1 6 2 2 3 2 3 3 2 4 3 3 4 4 5 4 5 5 0 6 5 1 6 4 5 4 5 Columns that are grouped on remain in the dataframe after any verb operations that do not use the group information. For example: >>> df >> group_by('y-1', xplus1='x+1') >> select('y') groups: ['y-1', 'xplus1'] y-1 xplus1 y 0 0 2 1 1 1 6 2 2 2 3 3 3 3 3 4 4 4 5 5 5 5 1 6 6 4 5 5 Notes ----- If :obj:`plydata.options.modify_input_data` is ``True``, :class:`group_by` will modify the original dataframe. """ groups = None def __init__(self, *args, add_=False, **kwargs): self.set_env_from_verb_init() super().__init__(*args, **kwargs) self.add_ = add_ self.groups = [expr.column for expr in self.expressions] class ungroup(DataOperator): """ Remove the grouping variables for dataframe Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({'x': [1, 2, 3], ... 'y': [1, 2, 3]}) >>> df >> group_by('x') groups: ['x'] x y 0 1 1 1 2 2 2 3 3 >>> df >> group_by('x') >> ungroup() x y 0 1 1 1 2 2 2 3 3 """ class group_indices(group_by): """ Generate a unique id for each group Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. args : strs, tuples, optional Expressions or ``(name, expression)`` pairs. This should be used when the *name* is not a valid python variable name. The expression should be of type :class:`str` or an *interable* with the same number of elements as the dataframe. As this verb returns an array, the tuples have no added benefit over strings. kwargs : dict, optional ``{name: expression}`` pairs. As this verb returns an array, keyword arguments have no added benefit over :class:`str` positional arguments. Returns ------- out : numpy.array Ids for each group Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({'x': [1, 5, 2, 2, 4, 0, 4], ... 'y': [1, 2, 3, 4, 5, 6, 5]}) >>> df >> group_by('x') groups: ['x'] x y 0 1 1 1 5 2 2 2 3 3 2 4 4 4 5 5 0 6 6 4 5 >>> df >> group_by('x') >> group_indices() array([1, 4, 2, 2, 3, 0, 3]) You can pass the group column(s) as parameters to :class:`group_indices` >>> df >> group_indices('x*2') array([1, 4, 2, 2, 3, 0, 3]) """ class summarize(define): """ Summarise multiple values to a single value Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. args : strs, tuples, optional Expressions or ``(name, expression)`` pairs. This should be used when the *name* is not a valid python variable name. The expression should be of type :class:`str` or an *interable* with the same number of elements as the dataframe. kwargs : dict, optional ``{name: expression}`` pairs. Examples -------- >>> import pandas as pd >>> import numpy as np >>> df = pd.DataFrame({'x': [1, 5, 2, 2, 4, 0, 4], ... 'y': [1, 2, 3, 4, 5, 6, 5], ... 'z': [1, 3, 3, 4, 5, 5, 5]}) Can take only positional, only keyword arguments or both. >>> df >> summarize('np.sum(x)', max='np.max(x)') np.sum(x) max 0 18 5 When summarizing after a :class:`group_by` operation the group columns are retained. >>> df >> group_by('y', 'z') >> summarize(mean_x='np.mean(x)') y z mean_x 0 1 1 1.0 1 2 3 5.0 2 3 3 2.0 3 4 4 2.0 4 5 5 4.0 5 6 5 0.0 .. rubric:: Aggregate Functions When summarizing the following functions can be used, they take an array and return a *single* number. - ``min(x)`` - Alias of :func:`numpy.amin` (a.k.a ``numpy.min``). - ``max(x)`` - Alias of :func:`numpy.amax` (a.k.a ``numpy.max``). - ``sum(x)`` - Alias of :func:`numpy.sum`. - ``cumsum(x)`` - Alias of :func:`numpy.cumsum`. - ``mean(x)`` - Alias of :func:`numpy.mean`. - ``median(x)`` - Alias of :func:`numpy.median`. - ``std(x)`` - Alias of :func:`numpy.std`. - ``first(x)`` - First element of ``x``. - ``last(x)`` - Last element of ``x``. - ``nth(x, n)`` - *nth* value of ``x`` or ``numpy.nan``. - ``n_distinct(x)`` - Number of distint elements in ``x``. - ``n_unique(x)`` - Alias of ``n_distinct``. - ``n()`` - Number of elements in current group. The aliases of the Numpy functions save you from typing 3 or 5 key strokes and you get better column names. i.e ``min(x)`` instead of ``np.min(x)`` or ``numpy.min(x)`` if you have Numpy imported. >>> df = pd.DataFrame({'x': [0, 1, 2, 3, 4, 5], ... 'y': [0, 0, 1, 1, 2, 3]}) >>> df >> summarize('min(x)', 'max(x)', 'mean(x)', 'sum(x)', ... 'first(x)', 'last(x)', 'nth(x, 3)') min(x) max(x) mean(x) sum(x) first(x) last(x) nth(x, 3) 0 0 5 2.5 15 0 5 3 Summarizing groups with aggregate functions >>> df >> group_by('y') >> summarize('mean(x)') y mean(x) 0 0 0.5 1 1 2.5 2 2 4.0 3 3 5.0 >>> df >> group_by('y') >> summarize(y_count='n()') y y_count 0 0 2 1 1 2 2 2 1 3 3 1 You can use ``n()`` even when there are no groups. >>> df >> summarize('n()') n() 0 6 """ class query(DataOperator): """ Return rows with matching conditions Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. expr : str The query string to evaluate. You can refer to variables in the environment by prefixing them with an '@' character like ``@a + b``. Allowed functions are `sin`, `cos`, `exp`, `log`, `expm1`, `log1p`, `sqrt`, `sinh`, `cosh`, `tanh`, `arcsin`, `arccos`, `arctan`, `arccosh`, `arcsinh`, `arctanh`, `abs` and `arctan2`. reset_index : bool, optional (default: True) If ``True``, the index is reset to a sequential range index. If ``False``, the original index is maintained. kwargs : dict See the documentation for :func:`pandas.eval` for complete details on the keyword arguments accepted by :meth:`pandas.DataFrame.query`. Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({'x': [0, 1, 2, 3, 4, 5], ... 'y': [0, 0, 1, 1, 2, 3]}) >>> df >> query('x % 2 == 0') x y 0 0 0 1 2 1 2 4 2 >>> df >> query('x % 2 == 0 & y > 0') x y 0 2 1 1 4 2 By default, Bitwise operators ``&`` and ``|`` have the same precedence as the booleans ``and`` and ``or``. >>> df >> query('x % 2 == 0 and y > 0') x y 0 2 1 1 4 2 ``query`` works within groups >>> df >> query('x == x.min()') x y 0 0 0 >>> df >> group_by('y') >> query('x == x.min()') groups: ['y'] x y 0 0 0 1 2 1 2 4 2 3 5 3 For more information see :meth:`pandas.DataFrame.query`. To query rows and columns with ``NaN`` values, use :class:`dropna` Notes ----- :class:`~plydata.one_table_verbs.query` is the equivalent of dplyr's `filter` verb but with slightly different python syntax the expressions. """ expression = None def __init__(self, expr, reset_index=True, **kwargs): self.set_env_from_verb_init() self.reset_index = reset_index self.expression = expr self.kwargs = kwargs class do(DataOperator): """ Do arbitrary operations on a dataframe Considering the *split-apply-combine* data manipulation strategy, :class:`do` gives a window into which to place the complex *apply* actions, and also control over the form of results when they are combined. This allows Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. func : function, optional A single function to apply to each group. *The function should accept a dataframe and return a dataframe*. kwargs : dict, optional ``{name: function}`` pairs. *The function should accept a dataframe and return an array*. The function computes a column called ``name``. Examples -------- >>> import pandas as pd >>> import numpy as np >>> df = pd.DataFrame({'x': [1, 2, 2, 3], ... 'y': [2, 3, 4, 3], ... 'z': list('aabb')}) Define a function that uses numpy to do a least squares fit. It takes input from a dataframe and output is a dataframe. ``gdf`` is a dataframe that contains only rows from the current group. >>> def least_squares(gdf): ... X = np.vstack([gdf.x, np.ones(len(gdf))]).T ... (m, c), _, _, _ = np.linalg.lstsq(X, gdf.y, None) ... return pd.DataFrame({'intercept': c, 'slope': [m]}) Define functions that take x and y values and compute the intercept and slope. >>> def slope(x, y): ... return np.diff(y)[0] / np.diff(x)[0] ... >>> def intercept(x, y): ... return y.values[0] - slope(x, y) * x.values[0] Demonstrating do >>> df >> group_by('z') >> do(least_squares) groups: ['z'] z intercept slope 0 a 1.0 1.0 1 b 6.0 -1.0 We can get the same result, by passing separate functions that calculate the columns independently. >>> df >> group_by('z') >> do( ... intercept=lambda gdf: intercept(gdf.x, gdf.y), ... slope=lambda gdf: slope(gdf.x, gdf.y)) groups: ['z'] z intercept slope 0 a 1.0 1.0 1 b 6.0 -1.0 The functions need not return numerical values. Pandas columns can hold any type of object. You could store result objects from more complicated models. Each model would be linked to a group. Notice that the group columns (``z`` in the above cases) are included in the result. Notes ----- You cannot have both a position argument and keyword arguments. """ single_function = False def __init__(self, func=None, **kwargs): if func is not None: if kwargs: raise ValueError( "Unexpected positional and keyword arguments.") if not callable(func): raise TypeError( "func should be a callable object") if func: self.single_function = True self.expressions = [Expression(func, None)] else: stmts_cols = zip(kwargs.values(), kwargs.keys()) self.expressions = [ Expression(stmt, col) for stmt, col in stmts_cols ] class head(DataOperator): """ Select the top n rows Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. n : int, optional Number of rows to return. If the ``data`` is grouped, then number of rows per group. Default is 5. Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({ ... 'x': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ... 'y': list('aaaabbcddd') }) >>> df >> head(2) x y 0 1 a 1 2 a Grouped dataframe >>> df >> group_by('y') >> head(2) groups: ['y'] x y 0 1 a 1 2 a 2 5 b 3 6 b 4 7 c 5 8 d 6 9 d """ def __init__(self, n=5): self.n = n class tail(DataOperator): """ Select the bottom n rows Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. n : int, optional Number of rows to return. If the ``data`` is grouped, then number of rows per group. Default is 5. Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({ ... 'x': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ... 'y': list('aaaabbcddd') }) >>> df >> tail(2) x y 8 9 d 9 10 d Grouped dataframe >>> df >> group_by('y') >> tail(2) groups: ['y'] x y 0 3 a 1 4 a 2 5 b 3 6 b 4 7 c 5 9 d 6 10 d """ def __init__(self, n=5): self.n = n class pull(DataOperator): """ Pull a single column from the dataframe Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. column : name Column name or index id. use_index : bool Whether to pull column by name or by its integer index. Default is False. Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({ ... 'x': [1, 2, 3], ... 'y': [4, 5, 6], ... 'z': [7, 8, 9] ... }) >>> df x y z 0 1 4 7 1 2 5 8 2 3 6 9 >>> df >> pull('y') array([4, 5, 6]) >>> df >> pull(0, True) array([1, 2, 3]) >>> df >> pull(-1, True) array([7, 8, 9]) Notes ----- Always returns a numpy array. If :obj:`plydata.options.modify_input_data` is ``True``, :class:`pull` will not make a copy the original column. """ def __init__(self, column, use_index=False): self.column = column self.use_index = use_index class slice_rows(DataOperator): """ Select rows A wrapper around :class:`slice` to use when piping. Parameters ---------- data : dataframe, optional Useful when not using the ``>>`` operator. *args : tuple (start, stop, step) as expected by the builtin :class:`slice` type. Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({'x': range(10), 'y': range(100, 110)}) >>> df >> slice_rows(5) x y 0 0 100 1 1 101 2 2 102 3 3 103 4 4 104 >>> df >> slice_rows(3, 7) x y 3 3 103 4 4 104 5 5 105 6 6 106 >>> df >> slice_rows(None, None, 3) x y 0 0 100 3 3 103 6 6 106 9 9 109 The above examples are equivalent to:: df[slice(5)] df[slice(3, 7)] df[slice(None, None, 3)] respectively. Notes ----- If :obj:`plydata.options.modify_input_data` is ``True``, :class:`slice_rows` will not make a copy the original dataframe. """ def __init__(self, *args): self.slice = slice(*args) # Aliases mutate = define transmute = create unique = distinct summarise = summarize
bsd-3-clause
bond-/udacity-ml
src/numpy-pandas-tutorials/quiz-create-dataframe.py
1
1819
from pandas import DataFrame, Series ################# # Syntax Reminder: # # The following code would create a two-column pandas DataFrame # named df with columns labeled 'name' and 'age': # # people = ['Sarah', 'Mike', 'Chrisna'] # ages = [28, 32, 25] # df = DataFrame({'name' : Series(people), # 'age' : Series(ages)}) def create_dataframe(): ''' Create a pandas dataframe called 'olympic_medal_counts_df' containing the data from the table of 2014 Sochi winter olympics medal counts. The columns for this dataframe should be called 'country_name', 'gold', 'silver', and 'bronze'. There is no need to specify row indexes for this dataframe (in this case, the rows will automatically be assigned numbered indexes). You do not need to call the function in your code when running it in the browser - the grader will do that automatically when you submit or test it. ''' countries = ['Russian Fed.', 'Norway', 'Canada', 'United States', 'Netherlands', 'Germany', 'Switzerland', 'Belarus', 'Austria', 'France', 'Poland', 'China', 'Korea', 'Sweden', 'Czech Republic', 'Slovenia', 'Japan', 'Finland', 'Great Britain', 'Ukraine', 'Slovakia', 'Italy', 'Latvia', 'Australia', 'Croatia', 'Kazakhstan'] gold = [13, 11, 10, 9, 8, 8, 6, 5, 4, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0] silver = [11, 5, 10, 7, 7, 6, 3, 0, 8, 4, 1, 4, 3, 7, 4, 2, 4, 3, 1, 0, 0, 2, 2, 2, 1, 0] bronze = [9, 10, 5, 12, 9, 5, 2, 1, 5, 7, 1, 2, 2, 6, 2, 4, 3, 1, 2, 1, 0, 6, 2, 1, 0, 1] # your code here olympic_medal_counts_df = DataFrame({'country_name': countries, 'gold': gold, 'silver': silver, 'bronze': bronze}) return olympic_medal_counts_df
apache-2.0
harisbal/pandas
pandas/tests/io/test_common.py
2
10380
""" Tests for the pandas.io.common functionalities """ import mmap import os import pytest import pandas as pd import pandas.io.common as icom import pandas.util._test_decorators as td import pandas.util.testing as tm from pandas.compat import ( is_platform_windows, StringIO, FileNotFoundError, ) class CustomFSPath(object): """For testing fspath on unknown objects""" def __init__(self, path): self.path = path def __fspath__(self): return self.path # Functions that consume a string path and return a string or path-like object path_types = [str, CustomFSPath] try: from pathlib import Path path_types.append(Path) except ImportError: pass try: from py.path import local as LocalPath path_types.append(LocalPath) except ImportError: pass HERE = os.path.abspath(os.path.dirname(__file__)) # https://github.com/cython/cython/issues/1720 @pytest.mark.filterwarnings("ignore:can't resolve package:ImportWarning") class TestCommonIOCapabilities(object): data1 = """index,A,B,C,D foo,2,3,4,5 bar,7,8,9,10 baz,12,13,14,15 qux,12,13,14,15 foo2,12,13,14,15 bar2,12,13,14,15 """ def test_expand_user(self): filename = '~/sometest' expanded_name = icom._expand_user(filename) assert expanded_name != filename assert os.path.isabs(expanded_name) assert os.path.expanduser(filename) == expanded_name def test_expand_user_normal_path(self): filename = '/somefolder/sometest' expanded_name = icom._expand_user(filename) assert expanded_name == filename assert os.path.expanduser(filename) == expanded_name @td.skip_if_no('pathlib') def test_stringify_path_pathlib(self): rel_path = icom._stringify_path(Path('.')) assert rel_path == '.' redundant_path = icom._stringify_path(Path('foo//bar')) assert redundant_path == os.path.join('foo', 'bar') @td.skip_if_no('py.path') def test_stringify_path_localpath(self): path = os.path.join('foo', 'bar') abs_path = os.path.abspath(path) lpath = LocalPath(path) assert icom._stringify_path(lpath) == abs_path def test_stringify_path_fspath(self): p = CustomFSPath('foo/bar.csv') result = icom._stringify_path(p) assert result == 'foo/bar.csv' @pytest.mark.parametrize('extension,expected', [ ('', None), ('.gz', 'gzip'), ('.bz2', 'bz2'), ('.zip', 'zip'), ('.xz', 'xz'), ]) @pytest.mark.parametrize('path_type', path_types) def test_infer_compression_from_path(self, extension, expected, path_type): path = path_type('foo/bar.csv' + extension) compression = icom._infer_compression(path, compression='infer') assert compression == expected def test_get_filepath_or_buffer_with_path(self): filename = '~/sometest' filepath_or_buffer, _, _, should_close = icom.get_filepath_or_buffer( filename) assert filepath_or_buffer != filename assert os.path.isabs(filepath_or_buffer) assert os.path.expanduser(filename) == filepath_or_buffer assert not should_close def test_get_filepath_or_buffer_with_buffer(self): input_buffer = StringIO() filepath_or_buffer, _, _, should_close = icom.get_filepath_or_buffer( input_buffer) assert filepath_or_buffer == input_buffer assert not should_close def test_iterator(self): reader = pd.read_csv(StringIO(self.data1), chunksize=1) result = pd.concat(reader, ignore_index=True) expected = pd.read_csv(StringIO(self.data1)) tm.assert_frame_equal(result, expected) # GH12153 it = pd.read_csv(StringIO(self.data1), chunksize=1) first = next(it) tm.assert_frame_equal(first, expected.iloc[[0]]) tm.assert_frame_equal(pd.concat(it), expected.iloc[1:]) @pytest.mark.parametrize('reader, module, error_class, fn_ext', [ (pd.read_csv, 'os', FileNotFoundError, 'csv'), (pd.read_fwf, 'os', FileNotFoundError, 'txt'), (pd.read_excel, 'xlrd', FileNotFoundError, 'xlsx'), (pd.read_feather, 'feather', Exception, 'feather'), (pd.read_hdf, 'tables', FileNotFoundError, 'h5'), (pd.read_stata, 'os', FileNotFoundError, 'dta'), (pd.read_sas, 'os', FileNotFoundError, 'sas7bdat'), (pd.read_json, 'os', ValueError, 'json'), (pd.read_msgpack, 'os', ValueError, 'mp'), (pd.read_pickle, 'os', FileNotFoundError, 'pickle'), ]) def test_read_non_existant(self, reader, module, error_class, fn_ext): pytest.importorskip(module) path = os.path.join(HERE, 'data', 'does_not_exist.' + fn_ext) with pytest.raises(error_class): reader(path) def test_read_non_existant_read_table(self): path = os.path.join(HERE, 'data', 'does_not_exist.' + 'csv') with pytest.raises(FileNotFoundError): with tm.assert_produces_warning(FutureWarning): pd.read_table(path) @pytest.mark.parametrize('reader, module, path', [ (pd.read_csv, 'os', ('io', 'data', 'iris.csv')), (pd.read_fwf, 'os', ('io', 'data', 'fixed_width_format.txt')), (pd.read_excel, 'xlrd', ('io', 'data', 'test1.xlsx')), (pd.read_feather, 'feather', ('io', 'data', 'feather-0_3_1.feather')), (pd.read_hdf, 'tables', ('io', 'data', 'legacy_hdf', 'datetimetz_object.h5')), (pd.read_stata, 'os', ('io', 'data', 'stata10_115.dta')), (pd.read_sas, 'os', ('io', 'sas', 'data', 'test1.sas7bdat')), (pd.read_json, 'os', ('io', 'json', 'data', 'tsframe_v012.json')), (pd.read_msgpack, 'os', ('io', 'msgpack', 'data', 'frame.mp')), (pd.read_pickle, 'os', ('io', 'data', 'categorical_0_14_1.pickle')), ]) def test_read_fspath_all(self, reader, module, path, datapath): pytest.importorskip(module) path = datapath(*path) mypath = CustomFSPath(path) result = reader(mypath) expected = reader(path) if path.endswith('.pickle'): # categorical tm.assert_categorical_equal(result, expected) else: tm.assert_frame_equal(result, expected) def test_read_fspath_all_read_table(self, datapath): path = datapath('io', 'data', 'iris.csv') mypath = CustomFSPath(path) with tm.assert_produces_warning(FutureWarning): result = pd.read_table(mypath) with tm.assert_produces_warning(FutureWarning): expected = pd.read_table(path) if path.endswith('.pickle'): # categorical tm.assert_categorical_equal(result, expected) else: tm.assert_frame_equal(result, expected) @pytest.mark.parametrize('writer_name, writer_kwargs, module', [ ('to_csv', {}, 'os'), ('to_excel', {'engine': 'xlwt'}, 'xlwt'), ('to_feather', {}, 'feather'), ('to_html', {}, 'os'), ('to_json', {}, 'os'), ('to_latex', {}, 'os'), ('to_msgpack', {}, 'os'), ('to_pickle', {}, 'os'), ('to_stata', {}, 'os'), ]) def test_write_fspath_all(self, writer_name, writer_kwargs, module): p1 = tm.ensure_clean('string') p2 = tm.ensure_clean('fspath') df = pd.DataFrame({"A": [1, 2]}) with p1 as string, p2 as fspath: pytest.importorskip(module) mypath = CustomFSPath(fspath) writer = getattr(df, writer_name) writer(string, **writer_kwargs) with open(string, 'rb') as f: expected = f.read() writer(mypath, **writer_kwargs) with open(fspath, 'rb') as f: result = f.read() assert result == expected def test_write_fspath_hdf5(self): # Same test as write_fspath_all, except HDF5 files aren't # necessarily byte-for-byte identical for a given dataframe, so we'll # have to read and compare equality pytest.importorskip('tables') df = pd.DataFrame({"A": [1, 2]}) p1 = tm.ensure_clean('string') p2 = tm.ensure_clean('fspath') with p1 as string, p2 as fspath: mypath = CustomFSPath(fspath) df.to_hdf(mypath, key='bar') df.to_hdf(string, key='bar') result = pd.read_hdf(fspath, key='bar') expected = pd.read_hdf(string, key='bar') tm.assert_frame_equal(result, expected) @pytest.fixture def mmap_file(datapath): return datapath('io', 'data', 'test_mmap.csv') class TestMMapWrapper(object): def test_constructor_bad_file(self, mmap_file): non_file = StringIO('I am not a file') non_file.fileno = lambda: -1 # the error raised is different on Windows if is_platform_windows(): msg = "The parameter is incorrect" err = OSError else: msg = "[Errno 22]" err = mmap.error tm.assert_raises_regex(err, msg, icom.MMapWrapper, non_file) target = open(mmap_file, 'r') target.close() msg = "I/O operation on closed file" tm.assert_raises_regex( ValueError, msg, icom.MMapWrapper, target) def test_get_attr(self, mmap_file): with open(mmap_file, 'r') as target: wrapper = icom.MMapWrapper(target) attrs = dir(wrapper.mmap) attrs = [attr for attr in attrs if not attr.startswith('__')] attrs.append('__next__') for attr in attrs: assert hasattr(wrapper, attr) assert not hasattr(wrapper, 'foo') def test_next(self, mmap_file): with open(mmap_file, 'r') as target: wrapper = icom.MMapWrapper(target) lines = target.readlines() for line in lines: next_line = next(wrapper) assert next_line.strip() == line.strip() pytest.raises(StopIteration, next, wrapper) def test_unknown_engine(self): with tm.ensure_clean() as path: df = tm.makeDataFrame() df.to_csv(path) with tm.assert_raises_regex(ValueError, 'Unknown engine'): pd.read_csv(path, engine='pyt')
bsd-3-clause
draperjames/bokeh
bokeh/core/compat/mpl_helpers.py
14
5432
"Helpers function for mpl module." #----------------------------------------------------------------------------- # Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import absolute_import import numpy as np from itertools import cycle, islice from ...models import GlyphRenderer #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- def convert_color(mplcolor): "Converts mpl color formats to Bokeh color formats." charmap = dict(b="blue", g="green", r="red", c="cyan", m="magenta", y="yellow", k="black", w="white") if mplcolor in charmap: return charmap[mplcolor] try: colorfloat = float(mplcolor) if 0 <= colorfloat <= 1.0: # This is a grayscale value return tuple([int(255 * colorfloat)] * 3) except: pass if isinstance(mplcolor, tuple): # These will be floats in the range 0..1 return int(255 * mplcolor[0]), int(255 * mplcolor[1]), int(255 * mplcolor[2]) return mplcolor def convert_dashes(dash): """ Converts a Matplotlib dash specification bokeh.core.properties.DashPattern supports the matplotlib named dash styles, but not the little shorthand characters. This function takes care of mapping those. """ mpl_dash_map = { "-": "solid", "--": "dashed", ":": "dotted", "-.": "dashdot", } # If the value doesn't exist in the map, then just return the value back. return mpl_dash_map.get(dash, dash) def get_props_cycled(col, prop, fx=lambda x: x): """ We need to cycle the `get.property` list (where property can be colors, line_width, etc) as matplotlib does. We use itertools tools for do this cycling ans slice manipulation. Parameters: col: matplotlib collection object prop: property we want to get from matplotlib collection fx: function (optional) to transform the elements from list obtained after the property call. Defaults to identity function. """ n = len(col.get_paths()) t_prop = [fx(x) for x in prop] sliced = islice(cycle(t_prop), None, n) return list(sliced) def is_ax_end(r): "Check if the 'name' (if it exists) in the Glyph's datasource is 'ax_end'" if isinstance(r, GlyphRenderer): try: if r.data_source.data["name"] == "ax_end": return True except KeyError: return False else: return False def xkcd_line(x, y, xlim=None, ylim=None, mag=1.0, f1=30, f2=0.001, f3=5): """ Mimic a hand-drawn line from (x, y) data Source: http://jakevdp.github.io/blog/2012/10/07/xkcd-style-plots-in-matplotlib/ Parameters ---------- x, y : array_like arrays to be modified xlim, ylim : data range the assumed plot range for the modification. If not specified, they will be guessed from the data mag : float magnitude of distortions f1, f2, f3 : int, float, int filtering parameters. f1 gives the size of the window, f2 gives the high-frequency cutoff, f3 gives the size of the filter Returns ------- x, y : ndarrays The modified lines """ try: from scipy import interpolate, signal except ImportError: print("\nThe SciPy package is required to use the xkcd_line function.\n") raise x = np.asarray(x) y = np.asarray(y) # get limits for rescaling if xlim is None: xlim = (x.min(), x.max()) if ylim is None: ylim = (y.min(), y.max()) if xlim[1] == xlim[0]: xlim = ylim if ylim[1] == ylim[0]: ylim = xlim # scale the data x_scaled = (x - xlim[0]) * 1. / (xlim[1] - xlim[0]) y_scaled = (y - ylim[0]) * 1. / (ylim[1] - ylim[0]) # compute the total distance along the path dx = x_scaled[1:] - x_scaled[:-1] dy = y_scaled[1:] - y_scaled[:-1] dist_tot = np.sum(np.sqrt(dx * dx + dy * dy)) # number of interpolated points is proportional to the distance Nu = int(200 * dist_tot) u = np.arange(-1, Nu + 1) * 1. / (Nu - 1) # interpolate curve at sampled points k = min(3, len(x) - 1) res = interpolate.splprep([x_scaled, y_scaled], s=0, k=k) x_int, y_int = interpolate.splev(u, res[0]) # we'll perturb perpendicular to the drawn line dx = x_int[2:] - x_int[:-2] dy = y_int[2:] - y_int[:-2] dist = np.sqrt(dx * dx + dy * dy) # create a filtered perturbation coeffs = mag * np.random.normal(0, 0.01, len(x_int) - 2) b = signal.firwin(f1, f2 * dist_tot, window=('kaiser', f3)) response = signal.lfilter(b, 1, coeffs) x_int[1:-1] += response * dy / dist y_int[1:-1] += response * dx / dist # un-scale data x_int = x_int[1:-1] * (xlim[1] - xlim[0]) + xlim[0] y_int = y_int[1:-1] * (ylim[1] - ylim[0]) + ylim[0] return x_int, y_int
bsd-3-clause
xzh86/scikit-learn
benchmarks/bench_plot_nmf.py
206
5890
""" Benchmarks of Non-Negative Matrix Factorization """ from __future__ import print_function from collections import defaultdict import gc from time import time import numpy as np from scipy.linalg import norm from sklearn.decomposition.nmf import NMF, _initialize_nmf from sklearn.datasets.samples_generator import make_low_rank_matrix from sklearn.externals.six.moves import xrange def alt_nnmf(V, r, max_iter=1000, tol=1e-3, R=None): ''' A, S = nnmf(X, r, tol=1e-3, R=None) Implement Lee & Seung's algorithm Parameters ---------- V : 2-ndarray, [n_samples, n_features] input matrix r : integer number of latent features max_iter : integer, optional maximum number of iterations (default: 1000) tol : double tolerance threshold for early exit (when the update factor is within tol of 1., the function exits) R : integer, optional random seed Returns ------- A : 2-ndarray, [n_samples, r] Component part of the factorization S : 2-ndarray, [r, n_features] Data part of the factorization Reference --------- "Algorithms for Non-negative Matrix Factorization" by Daniel D Lee, Sebastian H Seung (available at http://citeseer.ist.psu.edu/lee01algorithms.html) ''' # Nomenclature in the function follows Lee & Seung eps = 1e-5 n, m = V.shape if R == "svd": W, H = _initialize_nmf(V, r) elif R is None: R = np.random.mtrand._rand W = np.abs(R.standard_normal((n, r))) H = np.abs(R.standard_normal((r, m))) for i in xrange(max_iter): updateH = np.dot(W.T, V) / (np.dot(np.dot(W.T, W), H) + eps) H *= updateH updateW = np.dot(V, H.T) / (np.dot(W, np.dot(H, H.T)) + eps) W *= updateW if i % 10 == 0: max_update = max(updateW.max(), updateH.max()) if abs(1. - max_update) < tol: break return W, H def report(error, time): print("Frobenius loss: %.5f" % error) print("Took: %.2fs" % time) print() def benchmark(samples_range, features_range, rank=50, tolerance=1e-5): it = 0 timeset = defaultdict(lambda: []) err = defaultdict(lambda: []) max_it = len(samples_range) * len(features_range) for n_samples in samples_range: for n_features in features_range: print("%2d samples, %2d features" % (n_samples, n_features)) print('=======================') X = np.abs(make_low_rank_matrix(n_samples, n_features, effective_rank=rank, tail_strength=0.2)) gc.collect() print("benchmarking nndsvd-nmf: ") tstart = time() m = NMF(n_components=30, tol=tolerance, init='nndsvd').fit(X) tend = time() - tstart timeset['nndsvd-nmf'].append(tend) err['nndsvd-nmf'].append(m.reconstruction_err_) report(m.reconstruction_err_, tend) gc.collect() print("benchmarking nndsvda-nmf: ") tstart = time() m = NMF(n_components=30, init='nndsvda', tol=tolerance).fit(X) tend = time() - tstart timeset['nndsvda-nmf'].append(tend) err['nndsvda-nmf'].append(m.reconstruction_err_) report(m.reconstruction_err_, tend) gc.collect() print("benchmarking nndsvdar-nmf: ") tstart = time() m = NMF(n_components=30, init='nndsvdar', tol=tolerance).fit(X) tend = time() - tstart timeset['nndsvdar-nmf'].append(tend) err['nndsvdar-nmf'].append(m.reconstruction_err_) report(m.reconstruction_err_, tend) gc.collect() print("benchmarking random-nmf") tstart = time() m = NMF(n_components=30, init=None, max_iter=1000, tol=tolerance).fit(X) tend = time() - tstart timeset['random-nmf'].append(tend) err['random-nmf'].append(m.reconstruction_err_) report(m.reconstruction_err_, tend) gc.collect() print("benchmarking alt-random-nmf") tstart = time() W, H = alt_nnmf(X, r=30, R=None, tol=tolerance) tend = time() - tstart timeset['alt-random-nmf'].append(tend) err['alt-random-nmf'].append(np.linalg.norm(X - np.dot(W, H))) report(norm(X - np.dot(W, H)), tend) return timeset, err if __name__ == '__main__': from mpl_toolkits.mplot3d import axes3d # register the 3d projection axes3d import matplotlib.pyplot as plt samples_range = np.linspace(50, 500, 3).astype(np.int) features_range = np.linspace(50, 500, 3).astype(np.int) timeset, err = benchmark(samples_range, features_range) for i, results in enumerate((timeset, err)): fig = plt.figure('scikit-learn Non-Negative Matrix Factorization benchmark results') ax = fig.gca(projection='3d') for c, (label, timings) in zip('rbgcm', sorted(results.iteritems())): X, Y = np.meshgrid(samples_range, features_range) Z = np.asarray(timings).reshape(samples_range.shape[0], features_range.shape[0]) # plot the actual surface ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3, color=c) # dummy point plot to stick the legend to since surface plot do not # support legends (yet?) ax.plot([1], [1], [1], color=c, label=label) ax.set_xlabel('n_samples') ax.set_ylabel('n_features') zlabel = 'Time (s)' if i == 0 else 'reconstruction error' ax.set_zlabel(zlabel) ax.legend() plt.show()
bsd-3-clause
boada/HETDEXCluster
legacy/stats/rejectOutliers.py
4
5284
import glob import pandas as pd import pylab as pyl from astLib import astCoords as aco from astLib import astStats as ast from astLib import astCalc as aca def parseResults(files): ''' Reads all of the results files and puts them into a list with the results. Returns field, dither, fiber, and redshift. ''' r = [] for f in files: print f cluster, field, dither = f.split('_') data = pyl.genfromtxt(f, delimiter='\t', names=True, dtype=None) try: for fiber, z, Q in zip(data['Fiber'], data['Redshift'], data['Quality']): if Q == 0: r.append((field, 'D'+str(dither.rstrip('.results')), fiber, z)) except TypeError: fiber = int(data['Fiber']) z = float(data['Redshift']) Q = int(data['Quality']) if Q == 0: r.append((field, 'D'+str(dither.rstrip('.results')), fiber, z)) print len(r), 'objects read' return r def matchToCatalog(results, catalog): ''' Matches the list pumped out from parseResults to the full dataframe. Returns another pandas dataframe to work with. ''' cat = pd.read_csv(catalog)[['tile', 'dither', 'fiber', 'ra', 'dec']] data = pd.DataFrame(results, columns=['tile', 'dither', 'fiber', 'redshift']) # This does the actual matching matched = pd.merge(cat, data, left_on=['tile', 'dither', 'fiber'], right_on=['tile', 'dither', 'fiber'], how='inner') return matched def findClusterCenterRedshift(data): ''' Finds the center of the cluster in redshift space using the biweightlocation estimator. ''' x = pyl.copy(data['redshift'].values) return ast.biweightLocation(x, tuningConstant=6.0) def findSeperationSpatial(data, center): ''' Finds the distance to all of the galaxies from the center of the cluster in the spatial plane. Returns values in Mpc. ''' # Add a new column to the dataframe data['seperation'] = 0.0 for row in data.iterrows(): sepDeg = aco.calcAngSepDeg(center[0], center[1], row[1]['ra'], row[1]['dec']) sepMpc = sepDeg * aca.da(row[1]['redshift'])/57.2957795131 data['seperation'][row[0]] = sepMpc return data def findLOSV(data): ''' Finds the line of sight velocity for each of the galaxies. ''' c = 2.99E5 # speed of light in km/s avgz = findClusterCenterRedshift(data) # Add a new column to the dataframe data['LOSV'] = 0.0 for row in data.iterrows(): data['LOSV'][row[0]] = c *(row[1]['redshift'] - avgz)/(1 + avgz) return data def split_list(alist, wanted_parts=1): ''' Breaks a list into a number of parts. If it does not divide evenly then the last list will have an extra element. ''' length = len(alist) return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] for i in range(wanted_parts) ] def rejectInterlopers(data): ''' Does all of the work to figure out which galaxies don't belong. Makes several sorted copies of the dataframe and then applies the fixed gapper method. ''' # make some copies so we can sort them around sepSorted = data.sort('seperation', ascending=True) # How many parts to break into parts = len(data)//15 splitData = split_list(data, parts) # Now we sort the parts by LOSV and find the rejects interlopers = [] for part in splitData: # sort by LOSV LOSVsorted = part.sort('LOSV', ascending=True) rejected = True while rejected: # Find the difference between all of the neighboring elements difference = pyl.diff(LOSVsorted['LOSV']) # If diff > 1000 reject rejects = abs(difference) > 1000 # Now remove those items indices = pyl.where(rejects == True) #print LOSVsorted['LOSV'] #print difference #print indices[0] if rejects.any() == True: # Always take the more extreme index for index, i in enumerate(indices[0]): if (abs(LOSVsorted['LOSV'][LOSVsorted.index[i]]) - abs(LOSVsorted['LOSV'][LOSVsorted.index[i+1]])) > 0: pass elif (abs(LOSVsorted['LOSV'][LOSVsorted.index[i]]) - abs(LOSVsorted['LOSV'][LOSVsorted.index[i+1]])) < 0: indices[0][index] = i+1 #print LOSVsorted.index[list(indices[0])] dataframeIndex = list(LOSVsorted.index[list(indices[0])]) LOSVsorted = LOSVsorted.drop(dataframeIndex) interlopers += dataframeIndex else: rejected = False print 'interlopers',interlopers return data.drop(interlopers) catalog = '/Users/steven/Projects/cluster/data/boada/may_2012/catalogs/c260p61+32p13_complete.csv' files = glob.glob('*.results') center = 260.61326, 32.132568 results = parseResults(files) matched = matchToCatalog(results, catalog) seperated = findSeperationSpatial(matched, center) losv = findLOSV(seperated) cleaned = rejectInterlopers(losv)
mit
ephes/scikit-learn
examples/covariance/plot_mahalanobis_distances.py
348
6232
r""" ================================================================ Robust covariance estimation and Mahalanobis distances relevance ================================================================ An example to show covariance estimation with the Mahalanobis distances on Gaussian distributed data. For Gaussian distributed data, the distance of an observation :math:`x_i` to the mode of the distribution can be computed using its Mahalanobis distance: :math:`d_{(\mu,\Sigma)}(x_i)^2 = (x_i - \mu)'\Sigma^{-1}(x_i - \mu)` where :math:`\mu` and :math:`\Sigma` are the location and the covariance of the underlying Gaussian distribution. In practice, :math:`\mu` and :math:`\Sigma` are replaced by some estimates. The usual covariance maximum likelihood estimate is very sensitive to the presence of outliers in the data set and therefor, the corresponding Mahalanobis distances are. One would better have to use a robust estimator of covariance to guarantee that the estimation is resistant to "erroneous" observations in the data set and that the associated Mahalanobis distances accurately reflect the true organisation of the observations. The Minimum Covariance Determinant estimator is a robust, high-breakdown point (i.e. it can be used to estimate the covariance matrix of highly contaminated datasets, up to :math:`\frac{n_\text{samples}-n_\text{features}-1}{2}` outliers) estimator of covariance. The idea is to find :math:`\frac{n_\text{samples}+n_\text{features}+1}{2}` observations whose empirical covariance has the smallest determinant, yielding a "pure" subset of observations from which to compute standards estimates of location and covariance. The Minimum Covariance Determinant estimator (MCD) has been introduced by P.J.Rousseuw in [1]. This example illustrates how the Mahalanobis distances are affected by outlying data: observations drawn from a contaminating distribution are not distinguishable from the observations coming from the real, Gaussian distribution that one may want to work with. Using MCD-based Mahalanobis distances, the two populations become distinguishable. Associated applications are outliers detection, observations ranking, clustering, ... For visualization purpose, the cubic root of the Mahalanobis distances are represented in the boxplot, as Wilson and Hilferty suggest [2] [1] P. J. Rousseeuw. Least median of squares regression. J. Am Stat Ass, 79:871, 1984. [2] Wilson, E. B., & Hilferty, M. M. (1931). The distribution of chi-square. Proceedings of the National Academy of Sciences of the United States of America, 17, 684-688. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.covariance import EmpiricalCovariance, MinCovDet n_samples = 125 n_outliers = 25 n_features = 2 # generate data gen_cov = np.eye(n_features) gen_cov[0, 0] = 2. X = np.dot(np.random.randn(n_samples, n_features), gen_cov) # add some outliers outliers_cov = np.eye(n_features) outliers_cov[np.arange(1, n_features), np.arange(1, n_features)] = 7. X[-n_outliers:] = np.dot(np.random.randn(n_outliers, n_features), outliers_cov) # fit a Minimum Covariance Determinant (MCD) robust estimator to data robust_cov = MinCovDet().fit(X) # compare estimators learnt from the full data set with true parameters emp_cov = EmpiricalCovariance().fit(X) ############################################################################### # Display results fig = plt.figure() plt.subplots_adjust(hspace=-.1, wspace=.4, top=.95, bottom=.05) # Show data set subfig1 = plt.subplot(3, 1, 1) inlier_plot = subfig1.scatter(X[:, 0], X[:, 1], color='black', label='inliers') outlier_plot = subfig1.scatter(X[:, 0][-n_outliers:], X[:, 1][-n_outliers:], color='red', label='outliers') subfig1.set_xlim(subfig1.get_xlim()[0], 11.) subfig1.set_title("Mahalanobis distances of a contaminated data set:") # Show contours of the distance functions xx, yy = np.meshgrid(np.linspace(plt.xlim()[0], plt.xlim()[1], 100), np.linspace(plt.ylim()[0], plt.ylim()[1], 100)) zz = np.c_[xx.ravel(), yy.ravel()] mahal_emp_cov = emp_cov.mahalanobis(zz) mahal_emp_cov = mahal_emp_cov.reshape(xx.shape) emp_cov_contour = subfig1.contour(xx, yy, np.sqrt(mahal_emp_cov), cmap=plt.cm.PuBu_r, linestyles='dashed') mahal_robust_cov = robust_cov.mahalanobis(zz) mahal_robust_cov = mahal_robust_cov.reshape(xx.shape) robust_contour = subfig1.contour(xx, yy, np.sqrt(mahal_robust_cov), cmap=plt.cm.YlOrBr_r, linestyles='dotted') subfig1.legend([emp_cov_contour.collections[1], robust_contour.collections[1], inlier_plot, outlier_plot], ['MLE dist', 'robust dist', 'inliers', 'outliers'], loc="upper right", borderaxespad=0) plt.xticks(()) plt.yticks(()) # Plot the scores for each point emp_mahal = emp_cov.mahalanobis(X - np.mean(X, 0)) ** (0.33) subfig2 = plt.subplot(2, 2, 3) subfig2.boxplot([emp_mahal[:-n_outliers], emp_mahal[-n_outliers:]], widths=.25) subfig2.plot(1.26 * np.ones(n_samples - n_outliers), emp_mahal[:-n_outliers], '+k', markeredgewidth=1) subfig2.plot(2.26 * np.ones(n_outliers), emp_mahal[-n_outliers:], '+k', markeredgewidth=1) subfig2.axes.set_xticklabels(('inliers', 'outliers'), size=15) subfig2.set_ylabel(r"$\sqrt[3]{\rm{(Mahal. dist.)}}$", size=16) subfig2.set_title("1. from non-robust estimates\n(Maximum Likelihood)") plt.yticks(()) robust_mahal = robust_cov.mahalanobis(X - robust_cov.location_) ** (0.33) subfig3 = plt.subplot(2, 2, 4) subfig3.boxplot([robust_mahal[:-n_outliers], robust_mahal[-n_outliers:]], widths=.25) subfig3.plot(1.26 * np.ones(n_samples - n_outliers), robust_mahal[:-n_outliers], '+k', markeredgewidth=1) subfig3.plot(2.26 * np.ones(n_outliers), robust_mahal[-n_outliers:], '+k', markeredgewidth=1) subfig3.axes.set_xticklabels(('inliers', 'outliers'), size=15) subfig3.set_ylabel(r"$\sqrt[3]{\rm{(Mahal. dist.)}}$", size=16) subfig3.set_title("2. from robust estimates\n(Minimum Covariance Determinant)") plt.yticks(()) plt.show()
bsd-3-clause
george-montanez/LICORScabinet
TruncatedKDE.py
1
1467
from __future__ import division import numpy as np from sklearn.neighbors import NearestNeighbors from DensityEstimator import DensityEstimator from VectorGaussianKernel import VectorGaussianKernel from multi_flatten import multi_flatten class TruncatedKDE(DensityEstimator): def __init__(self, d_points, num_subsamples=-1, num_pts_used=-1, d=None, **kwargs): super(TruncatedKDE, self).__init__(d_points, num_subsamples, num_pts_used) if num_pts_used == -1: num_pts_used = self.points.shape[0] self.num_of_neighbors = num_pts_used if not d: if len(self.points.shape) < 2: d = 1 else: d = self.points.shape[1] self.dim = d num_pts = min(self.num_of_neighbors, self.points.shape[0]) self.VGK = VectorGaussianKernel() self.bw = self.VGK.rule_of_thumb_bandwidth(self.points, num_pts) self.nbrs = NearestNeighbors(n_neighbors=num_pts, algorithm='ball_tree').fit(self.points) def __call__(self, query_points, **kwargs): return self.kde(query_points) def kde(self, query_points): pts = multi_flatten(query_points) bandwidths = np.ones(pts.shape[0]) * self.bw distances, indices = self.nbrs.kneighbors(pts) num_pts = min(self.num_of_neighbors, self.points.shape[0]) return self.VGK.KDE_evaluation(distances, bandwidths, self.dim, num_pts)
gpl-2.0
rerpy/rerpy
doc/sphinxext/ipython_directive.py
1
27232
# -*- coding: utf-8 -*- """Sphinx directive to support embedded IPython code. This directive allows pasting of entire interactive IPython sessions, prompts and all, and their code will actually get re-executed at doc build time, with all prompts renumbered sequentially. It also allows you to input code as a pure python input by giving the argument python to the directive. The output looks like an interactive ipython section. To enable this directive, simply list it in your Sphinx ``conf.py`` file (making sure the directory where you placed it is visible to sphinx, as is needed for all Sphinx directives). By default this directive assumes that your prompts are unchanged IPython ones, but this can be customized. The configurable options that can be placed in conf.py are ipython_savefig_dir: The directory in which to save the figures. This is relative to the Sphinx source directory. The default is `html_static_path`. ipython_rgxin: The compiled regular expression to denote the start of IPython input lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You shouldn't need to change this. ipython_rgxout: The compiled regular expression to denote the start of IPython output lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You shouldn't need to change this. ipython_promptin: The string to represent the IPython input prompt in the generated ReST. The default is 'In [%d]:'. This expects that the line numbers are used in the prompt. ipython_promptout: The string to represent the IPython prompt in the generated ReST. The default is 'Out [%d]:'. This expects that the line numbers are used in the prompt. ToDo ---- - Turn the ad-hoc test() function into a real test suite. - Break up ipython-specific functionality from matplotlib stuff into better separated code. Authors ------- - John D Hunter: orignal author. - Fernando Perez: refactoring, documentation, cleanups, port to 0.11. - VáclavŠmilauer <eudoxos-AT-arcig.cz>: Prompt generalizations. - Skipper Seabold, refactoring, cleanups, pure python addition """ #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Stdlib import cStringIO import os import re import sys import tempfile import ast # To keep compatibility with various python versions try: from hashlib import md5 except ImportError: from md5 import md5 # Third-party try: import matplotlib matplotlib.use('Agg') except ImportError: pass import sphinx from docutils.parsers.rst import directives from docutils import nodes from sphinx.util.compat import Directive # Our own from IPython import Config, InteractiveShell from IPython.core.profiledir import ProfileDir from IPython.utils import io #----------------------------------------------------------------------------- # Globals #----------------------------------------------------------------------------- # for tokenizing blocks COMMENT, INPUT, OUTPUT = range(3) #----------------------------------------------------------------------------- # Functions and class declarations #----------------------------------------------------------------------------- def block_parser(part, rgxin, rgxout, fmtin, fmtout): """ part is a string of ipython text, comprised of at most one input, one ouput, comments, and blank lines. The block parser parses the text into a list of:: blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...] where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and data is, depending on the type of token:: COMMENT : the comment string INPUT: the (DECORATOR, INPUT_LINE, REST) where DECORATOR: the input decorator (or None) INPUT_LINE: the input as string (possibly multi-line) REST : any stdout generated by the input line (not OUTPUT) OUTPUT: the output string, possibly multi-line """ block = [] lines = part.split('\n') N = len(lines) i = 0 decorator = None while 1: if i==N: # nothing left to parse -- the last line break line = lines[i] i += 1 line_stripped = line.strip() if line_stripped.startswith('#'): block.append((COMMENT, line)) continue if line_stripped.startswith('@'): # we're assuming at most one decorator -- may need to # rethink decorator = line_stripped continue # does this look like an input line? matchin = rgxin.match(line) if matchin: lineno, inputline = int(matchin.group(1)), matchin.group(2) # the ....: continuation string continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2)) Nc = len(continuation) # input lines can continue on for more than one line, if # we have a '\' line continuation char or a function call # echo line 'print'. The input line can only be # terminated by the end of the block or an output line, so # we parse out the rest of the input line if it is # multiline as well as any echo text rest = [] while i<N: # look ahead; if the next line is blank, or a comment, or # an output line, we're done nextline = lines[i] matchout = rgxout.match(nextline) #print "nextline=%s, continuation=%s, starts=%s"%(nextline, continuation, nextline.startswith(continuation)) if matchout or nextline.startswith('#'): break elif nextline.startswith(continuation): inputline += '\n' + nextline[Nc:] else: rest.append(nextline) i+= 1 block.append((INPUT, (decorator, inputline, '\n'.join(rest)))) continue # if it looks like an output line grab all the text to the end # of the block matchout = rgxout.match(line) if matchout: lineno, output = int(matchout.group(1)), matchout.group(2) if i<N-1: output = '\n'.join([output] + lines[i:]) block.append((OUTPUT, output)) break return block class EmbeddedSphinxShell(object): """An embedded IPython instance to run inside Sphinx""" def __init__(self): self.cout = cStringIO.StringIO() # Create config object for IPython config = Config() config.Global.display_banner = False config.Global.exec_lines = ['import numpy as np', 'from pylab import *' ] config.InteractiveShell.autocall = False config.InteractiveShell.autoindent = False config.InteractiveShell.colors = 'NoColor' # create a profile so instance history isn't saved tmp_profile_dir = tempfile.mkdtemp(prefix='profile_') profname = 'auto_profile_sphinx_build' pdir = os.path.join(tmp_profile_dir,profname) profile = ProfileDir.create_profile_dir(pdir) # Create and initialize ipython, but don't start its mainloop IP = InteractiveShell.instance(config=config, profile_dir=profile) # io.stdout redirect must be done *after* instantiating InteractiveShell io.stdout = self.cout io.stderr = self.cout # For debugging, so we can see normal output, use this: #from IPython.utils.io import Tee #io.stdout = Tee(self.cout, channel='stdout') # dbg #io.stderr = Tee(self.cout, channel='stderr') # dbg # Store a few parts of IPython we'll need. self.IP = IP self.user_ns = self.IP.user_ns self.user_global_ns = self.IP.user_global_ns self.input = '' self.output = '' self.is_verbatim = False self.is_doctest = False self.is_suppress = False # on the first call to the savefig decorator, we'll import # pyplot as plt so we can make a call to the plt.gcf().savefig self._pyplot_imported = False def clear_cout(self): self.cout.seek(0) self.cout.truncate(0) def process_input_line(self, line, store_history=True): """process the input, capturing stdout""" #print "input='%s'"%self.input stdout = sys.stdout splitter = self.IP.input_splitter try: sys.stdout = self.cout splitter.push(line) more = splitter.push_accepts_more() if not more: source_raw = splitter.source_raw_reset()[1] self.IP.run_cell(source_raw, store_history=store_history) finally: sys.stdout = stdout def process_image(self, decorator): """ # build out an image directive like # .. image:: somefile.png # :width 4in # # from an input like # savefig somefile.png width=4in """ savefig_dir = self.savefig_dir source_dir = self.source_dir saveargs = decorator.split(' ') filename = saveargs[1] # insert relative path to image file in source outfile = os.path.relpath(os.path.join(savefig_dir,filename), source_dir) imagerows = ['.. image:: %s'%outfile] for kwarg in saveargs[2:]: arg, val = kwarg.split('=') arg = arg.strip() val = val.strip() imagerows.append(' :%s: %s'%(arg, val)) image_file = os.path.basename(outfile) # only return file name image_directive = '\n'.join(imagerows) return image_file, image_directive # Callbacks for each type of token def process_input(self, data, input_prompt, lineno): """Process data block for INPUT token.""" decorator, input, rest = data image_file = None image_directive = None #print 'INPUT:', data # dbg is_verbatim = decorator=='@verbatim' or self.is_verbatim is_doctest = decorator=='@doctest' or self.is_doctest is_suppress = decorator=='@suppress' or self.is_suppress is_savefig = decorator is not None and \ decorator.startswith('@savefig') input_lines = input.split('\n') if len(input_lines) > 1: if input_lines[-1] != "": input_lines.append('') # make sure there's a blank line # so splitter buffer gets reset continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2)) Nc = len(continuation) if is_savefig: image_file, image_directive = self.process_image(decorator) ret = [] is_semicolon = False for i, line in enumerate(input_lines): if line.endswith(';'): is_semicolon = True if i==0: # process the first input line if is_verbatim: self.process_input_line('') self.IP.execution_count += 1 # increment it anyway else: # only submit the line in non-verbatim mode self.process_input_line(line, store_history=True) formatted_line = '%s %s'%(input_prompt, line) else: # process a continuation line if not is_verbatim: self.process_input_line(line, store_history=True) formatted_line = '%s %s'%(continuation, line) if not is_suppress: ret.append(formatted_line) if not is_suppress and len(rest.strip()) and is_verbatim: # the "rest" is the standard output of the # input, which needs to be added in # verbatim mode ret.append(rest) self.cout.seek(0) output = self.cout.read() if not is_suppress and not is_semicolon: ret.append(output) elif is_semicolon: # get spacing right ret.append('') self.cout.truncate(0) return (ret, input_lines, output, is_doctest, image_file, image_directive) #print 'OUTPUT', output # dbg def process_output(self, data, output_prompt, input_lines, output, is_doctest, image_file): """Process data block for OUTPUT token.""" if is_doctest: submitted = data.strip() found = output if found is not None: found = found.strip() # XXX - fperez: in 0.11, 'output' never comes with the prompt # in it, just the actual output text. So I think all this code # can be nuked... # the above comment does not appear to be accurate... (minrk) ind = found.find(output_prompt) if ind<0: e='output prompt="%s" does not match out line=%s' % \ (output_prompt, found) raise RuntimeError(e) found = found[len(output_prompt):].strip() if found!=submitted: e = ('doctest failure for input_lines="%s" with ' 'found_output="%s" and submitted output="%s"' % (input_lines, found, submitted) ) raise RuntimeError(e) #print 'doctest PASSED for input_lines="%s" with found_output="%s" and submitted output="%s"'%(input_lines, found, submitted) def process_comment(self, data): """Process data fPblock for COMMENT token.""" if not self.is_suppress: return [data] def save_image(self, image_file): """ Saves the image file to disk. """ self.ensure_pyplot() command = 'plt.gcf().savefig("%s")'%image_file #print 'SAVEFIG', command # dbg self.process_input_line('bookmark ipy_thisdir', store_history=False) self.process_input_line('cd -b ipy_savedir', store_history=False) self.process_input_line(command, store_history=False) self.process_input_line('cd -b ipy_thisdir', store_history=False) self.process_input_line('bookmark -d ipy_thisdir', store_history=False) self.clear_cout() def process_block(self, block): """ process block from the block_parser and return a list of processed lines """ ret = [] output = None input_lines = None lineno = self.IP.execution_count input_prompt = self.promptin%lineno output_prompt = self.promptout%lineno image_file = None image_directive = None for token, data in block: if token==COMMENT: out_data = self.process_comment(data) elif token==INPUT: (out_data, input_lines, output, is_doctest, image_file, image_directive) = \ self.process_input(data, input_prompt, lineno) elif token==OUTPUT: out_data = \ self.process_output(data, output_prompt, input_lines, output, is_doctest, image_file) if out_data: ret.extend(out_data) # save the image files if image_file is not None: self.save_image(image_file) return ret, image_directive def ensure_pyplot(self): if self._pyplot_imported: return self.process_input_line('import matplotlib.pyplot as plt', store_history=False) def process_pure_python(self, content): """ content is a list of strings. it is unedited directive conent This runs it line by line in the InteractiveShell, prepends prompts as needed capturing stderr and stdout, then returns the content as a list as if it were ipython code """ output = [] savefig = False # keep up with this to clear figure multiline = False # to handle line continuation multiline_start = None fmtin = self.promptin ct = 0 for lineno, line in enumerate(content): line_stripped = line.strip() if not len(line): output.append(line) continue # handle decorators if line_stripped.startswith('@'): output.extend([line]) if 'savefig' in line: savefig = True # and need to clear figure continue # handle comments if line_stripped.startswith('#'): output.extend([line]) continue # deal with lines checking for multiline continuation = u' %s:'% ''.join(['.']*(len(str(ct))+2)) if not multiline: modified = u"%s %s" % (fmtin % ct, line_stripped) output.append(modified) ct += 1 try: ast.parse(line_stripped) output.append(u'') except Exception: # on a multiline multiline = True multiline_start = lineno else: # still on a multiline modified = u'%s %s' % (continuation, line) output.append(modified) try: mod = ast.parse( '\n'.join(content[multiline_start:lineno+1])) if isinstance(mod.body[0], ast.FunctionDef): # check to see if we have the whole function for element in mod.body[0].body: if isinstance(element, ast.Return): multiline = False else: output.append(u'') multiline = False except Exception: pass if savefig: # clear figure if plotted self.ensure_pyplot() self.process_input_line('plt.clf()', store_history=False) self.clear_cout() savefig = False return output class IpythonDirective(Directive): has_content = True required_arguments = 0 optional_arguments = 4 # python, suppress, verbatim, doctest final_argumuent_whitespace = True option_spec = { 'python': directives.unchanged, 'suppress' : directives.flag, 'verbatim' : directives.flag, 'doctest' : directives.flag, } shell = EmbeddedSphinxShell() def get_config_options(self): # contains sphinx configuration variables config = self.state.document.settings.env.config # get config variables to set figure output directory confdir = self.state.document.settings.env.app.confdir savefig_dir = config.ipython_savefig_dir source_dir = os.path.dirname(self.state.document.current_source) if savefig_dir is None: savefig_dir = config.html_static_path if isinstance(savefig_dir, list): savefig_dir = savefig_dir[0] # safe to assume only one path? savefig_dir = os.path.join(confdir, savefig_dir) # get regex and prompt stuff rgxin = config.ipython_rgxin rgxout = config.ipython_rgxout promptin = config.ipython_promptin promptout = config.ipython_promptout return savefig_dir, source_dir, rgxin, rgxout, promptin, promptout def setup(self): # reset the execution count if we haven't processed this doc #NOTE: this may be borked if there are multiple seen_doc tmp files #check time stamp? seen_docs = [i for i in os.listdir(tempfile.tempdir) if i.startswith('seen_doc')] if seen_docs: fname = os.path.join(tempfile.tempdir, seen_docs[0]) docs = open(fname).read().split('\n') if not self.state.document.current_source in docs: self.shell.IP.history_manager.reset() self.shell.IP.execution_count = 1 else: # haven't processed any docs yet docs = [] # get config values (savefig_dir, source_dir, rgxin, rgxout, promptin, promptout) = self.get_config_options() # and attach to shell so we don't have to pass them around self.shell.rgxin = rgxin self.shell.rgxout = rgxout self.shell.promptin = promptin self.shell.promptout = promptout self.shell.savefig_dir = savefig_dir self.shell.source_dir = source_dir # setup bookmark for saving figures directory self.shell.process_input_line('bookmark ipy_savedir %s'%savefig_dir, store_history=False) self.shell.clear_cout() # write the filename to a tempfile because it's been "seen" now if not self.state.document.current_source in docs: fd, fname = tempfile.mkstemp(prefix="seen_doc", text=True) fout = open(fname, 'a') fout.write(self.state.document.current_source+'\n') fout.close() return rgxin, rgxout, promptin, promptout def teardown(self): # delete last bookmark self.shell.process_input_line('bookmark -d ipy_savedir', store_history=False) self.shell.clear_cout() def run(self): debug = False #TODO, any reason block_parser can't be a method of embeddable shell # then we wouldn't have to carry these around rgxin, rgxout, promptin, promptout = self.setup() options = self.options self.shell.is_suppress = 'suppress' in options self.shell.is_doctest = 'doctest' in options self.shell.is_verbatim = 'verbatim' in options # handle pure python code if 'python' in self.arguments: content = self.content self.content = self.shell.process_pure_python(content) parts = '\n'.join(self.content).split('\n\n') lines = ['.. code-block:: ipython',''] figures = [] for part in parts: block = block_parser(part, rgxin, rgxout, promptin, promptout) if len(block): rows, figure = self.shell.process_block(block) for row in rows: lines.extend([' %s'%line for line in row.split('\n')]) if figure is not None: figures.append(figure) #text = '\n'.join(lines) #figs = '\n'.join(figures) for figure in figures: lines.append('') lines.extend(figure.split('\n')) lines.append('') #print lines if len(lines)>2: if debug: print '\n'.join(lines) else: #NOTE: this raises some errors, what's it for? #print 'INSERTING %d lines'%len(lines) self.state_machine.insert_input( lines, self.state_machine.input_lines.source(0)) text = '\n'.join(lines) txtnode = nodes.literal_block(text, text) txtnode['language'] = 'ipython' #imgnode = nodes.image(figs) # cleanup self.teardown() return []#, imgnode] # Enable as a proper Sphinx directive def setup(app): setup.app = app app.add_directive('ipython', IpythonDirective) app.add_config_value('ipython_savefig_dir', None, True) app.add_config_value('ipython_rgxin', re.compile('In \[(\d+)\]:\s?(.*)\s*'), True) app.add_config_value('ipython_rgxout', re.compile('Out\[(\d+)\]:\s?(.*)\s*'), True) app.add_config_value('ipython_promptin', 'In [%d]:', True) app.add_config_value('ipython_promptout', 'Out[%d]:', True) # Simple smoke test, needs to be converted to a proper automatic test. def test(): examples = [ r""" In [9]: pwd Out[9]: '/home/jdhunter/py4science/book' In [10]: cd bookdata/ /home/jdhunter/py4science/book/bookdata In [2]: from pylab import * In [2]: ion() In [3]: im = imread('stinkbug.png') @savefig mystinkbug.png width=4in In [4]: imshow(im) Out[4]: <matplotlib.image.AxesImage object at 0x39ea850> """, r""" In [1]: x = 'hello world' # string methods can be # used to alter the string @doctest In [2]: x.upper() Out[2]: 'HELLO WORLD' @verbatim In [3]: x.st<TAB> x.startswith x.strip """, r""" In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\ .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv' In [131]: print url.split('&') ['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv'] In [60]: import urllib """, r"""\ In [133]: import numpy.random @suppress In [134]: numpy.random.seed(2358) @doctest In [135]: numpy.random.rand(10,2) Out[135]: array([[ 0.64524308, 0.59943846], [ 0.47102322, 0.8715456 ], [ 0.29370834, 0.74776844], [ 0.99539577, 0.1313423 ], [ 0.16250302, 0.21103583], [ 0.81626524, 0.1312433 ], [ 0.67338089, 0.72302393], [ 0.7566368 , 0.07033696], [ 0.22591016, 0.77731835], [ 0.0072729 , 0.34273127]]) """, r""" In [106]: print x jdh In [109]: for i in range(10): .....: print i .....: .....: 0 1 2 3 4 5 6 7 8 9 """, r""" In [144]: from pylab import * In [145]: ion() # use a semicolon to suppress the output @savefig test_hist.png width=4in In [151]: hist(np.random.randn(10000), 100); @savefig test_plot.png width=4in In [151]: plot(np.random.randn(10000), 'o'); """, r""" # use a semicolon to suppress the output In [151]: plt.clf() @savefig plot_simple.png width=4in In [151]: plot([1,2,3]) @savefig hist_simple.png width=4in In [151]: hist(np.random.randn(10000), 100); """, r""" # update the current fig In [151]: ylabel('number') In [152]: title('normal distribution') @savefig hist_with_text.png In [153]: grid(True) """, ] # skip local-file depending first example: examples = examples[1:] #ipython_directive.DEBUG = True # dbg #options = dict(suppress=True) # dbg options = dict() for example in examples: content = example.split('\n') ipython_directive('debug', arguments=None, options=options, content=content, lineno=0, content_offset=None, block_text=None, state=None, state_machine=None, ) # Run test suite as a script if __name__=='__main__': if not os.path.isdir('_static'): os.mkdir('_static') test() print 'All OK? Check figures in _static/'
gpl-2.0
louisLouL/pair_trading
capstone_env/lib/python3.6/site-packages/pandas/tests/series/test_analytics.py
4
63970
# coding=utf-8 # pylint: disable-msg=E1101,W0612 from itertools import product from distutils.version import LooseVersion import pytest from numpy import nan import numpy as np import pandas as pd from pandas import (Series, Categorical, DataFrame, isnull, notnull, bdate_range, date_range, _np_version_under1p10) from pandas.core.index import MultiIndex from pandas.core.indexes.datetimes import Timestamp from pandas.core.indexes.timedeltas import Timedelta import pandas.core.config as cf import pandas.core.nanops as nanops from pandas.compat import lrange, range, is_platform_windows from pandas import compat from pandas.util.testing import (assert_series_equal, assert_almost_equal, assert_frame_equal, assert_index_equal) import pandas.util.testing as tm from .common import TestData skip_if_bottleneck_on_windows = (is_platform_windows() and nanops._USE_BOTTLENECK) class TestSeriesAnalytics(TestData): def test_sum_zero(self): arr = np.array([]) assert nanops.nansum(arr) == 0 arr = np.empty((10, 0)) assert (nanops.nansum(arr, axis=1) == 0).all() # GH #844 s = Series([], index=[]) assert s.sum() == 0 df = DataFrame(np.empty((10, 0))) assert (df.sum(1) == 0).all() def test_nansum_buglet(self): s = Series([1.0, np.nan], index=[0, 1]) result = np.nansum(s) assert_almost_equal(result, 1) def test_overflow(self): # GH 6915 # overflowing on the smaller int dtypes for dtype in ['int32', 'int64']: v = np.arange(5000000, dtype=dtype) s = Series(v) # no bottleneck result = s.sum(skipna=False) assert int(result) == v.sum(dtype='int64') result = s.min(skipna=False) assert int(result) == 0 result = s.max(skipna=False) assert int(result) == v[-1] for dtype in ['float32', 'float64']: v = np.arange(5000000, dtype=dtype) s = Series(v) # no bottleneck result = s.sum(skipna=False) assert result == v.sum(dtype=dtype) result = s.min(skipna=False) assert np.allclose(float(result), 0.0) result = s.max(skipna=False) assert np.allclose(float(result), v[-1]) @pytest.mark.xfail( skip_if_bottleneck_on_windows, reason="buggy bottleneck with sum overflow on windows") def test_overflow_with_bottleneck(self): # GH 6915 # overflowing on the smaller int dtypes for dtype in ['int32', 'int64']: v = np.arange(5000000, dtype=dtype) s = Series(v) # use bottleneck if available result = s.sum() assert int(result) == v.sum(dtype='int64') result = s.min() assert int(result) == 0 result = s.max() assert int(result) == v[-1] for dtype in ['float32', 'float64']: v = np.arange(5000000, dtype=dtype) s = Series(v) # use bottleneck if available result = s.sum() assert result == v.sum(dtype=dtype) result = s.min() assert np.allclose(float(result), 0.0) result = s.max() assert np.allclose(float(result), v[-1]) @pytest.mark.xfail( skip_if_bottleneck_on_windows, reason="buggy bottleneck with sum overflow on windows") def test_sum(self): self._check_stat_op('sum', np.sum, check_allna=True) def test_sum_inf(self): import pandas.core.nanops as nanops s = Series(np.random.randn(10)) s2 = s.copy() s[5:8] = np.inf s2[5:8] = np.nan assert np.isinf(s.sum()) arr = np.random.randn(100, 100).astype('f4') arr[:, 2] = np.inf with cf.option_context("mode.use_inf_as_null", True): assert_almost_equal(s.sum(), s2.sum()) res = nanops.nansum(arr, axis=1) assert np.isinf(res).all() def test_mean(self): self._check_stat_op('mean', np.mean) def test_median(self): self._check_stat_op('median', np.median) # test with integers, test failure int_ts = Series(np.ones(10, dtype=int), index=lrange(10)) tm.assert_almost_equal(np.median(int_ts), int_ts.median()) def test_mode(self): # No mode should be found. exp = Series([], dtype=np.float64) tm.assert_series_equal(Series([]).mode(), exp) exp = Series([1], dtype=np.int64) tm.assert_series_equal(Series([1]).mode(), exp) exp = Series(['a', 'b', 'c'], dtype=np.object) tm.assert_series_equal(Series(['a', 'b', 'c']).mode(), exp) # Test numerical data types. exp_single = [1] data_single = [1] * 5 + [2] * 3 exp_multi = [1, 3] data_multi = [1] * 5 + [2] * 3 + [3] * 5 for dt in np.typecodes['AllInteger'] + np.typecodes['Float']: s = Series(data_single, dtype=dt) exp = Series(exp_single, dtype=dt) tm.assert_series_equal(s.mode(), exp) s = Series(data_multi, dtype=dt) exp = Series(exp_multi, dtype=dt) tm.assert_series_equal(s.mode(), exp) # Test string and object types. exp = ['b'] data = ['a'] * 2 + ['b'] * 3 s = Series(data, dtype='c') exp = Series(exp, dtype='c') tm.assert_series_equal(s.mode(), exp) exp = ['bar'] data = ['foo'] * 2 + ['bar'] * 3 for dt in [str, object]: s = Series(data, dtype=dt) exp = Series(exp, dtype=dt) tm.assert_series_equal(s.mode(), exp) # Test datetime types. exp = Series(['1900-05-03', '2011-01-03', '2013-01-02'], dtype='M8[ns]') s = Series(['2011-01-03', '2013-01-02', '1900-05-03'], dtype='M8[ns]') tm.assert_series_equal(s.mode(), exp) exp = Series(['2011-01-03', '2013-01-02'], dtype='M8[ns]') s = Series(['2011-01-03', '2013-01-02', '1900-05-03', '2011-01-03', '2013-01-02'], dtype='M8[ns]') tm.assert_series_equal(s.mode(), exp) # gh-5986: Test timedelta types. exp = Series(['-1 days', '0 days', '1 days'], dtype='timedelta64[ns]') s = Series(['1 days', '-1 days', '0 days'], dtype='timedelta64[ns]') tm.assert_series_equal(s.mode(), exp) exp = Series(['2 min', '1 day'], dtype='timedelta64[ns]') s = Series(['1 day', '1 day', '-1 day', '-1 day 2 min', '2 min', '2 min'], dtype='timedelta64[ns]') tm.assert_series_equal(s.mode(), exp) # Test mixed dtype. exp = Series(['foo']) s = Series([1, 'foo', 'foo']) tm.assert_series_equal(s.mode(), exp) # Test for uint64 overflow. exp = Series([2**63], dtype=np.uint64) s = Series([1, 2**63, 2**63], dtype=np.uint64) tm.assert_series_equal(s.mode(), exp) exp = Series([1, 2**63], dtype=np.uint64) s = Series([1, 2**63], dtype=np.uint64) tm.assert_series_equal(s.mode(), exp) # Test category dtype. c = Categorical([1, 2]) exp = Categorical([1, 2], categories=[1, 2]) exp = Series(exp, dtype='category') tm.assert_series_equal(Series(c).mode(), exp) c = Categorical([1, 'a', 'a']) exp = Categorical(['a'], categories=[1, 'a']) exp = Series(exp, dtype='category') tm.assert_series_equal(Series(c).mode(), exp) c = Categorical([1, 1, 2, 3, 3]) exp = Categorical([1, 3], categories=[1, 2, 3]) exp = Series(exp, dtype='category') tm.assert_series_equal(Series(c).mode(), exp) def test_prod(self): self._check_stat_op('prod', np.prod) def test_min(self): self._check_stat_op('min', np.min, check_objects=True) def test_max(self): self._check_stat_op('max', np.max, check_objects=True) def test_var_std(self): alt = lambda x: np.std(x, ddof=1) self._check_stat_op('std', alt) alt = lambda x: np.var(x, ddof=1) self._check_stat_op('var', alt) result = self.ts.std(ddof=4) expected = np.std(self.ts.values, ddof=4) assert_almost_equal(result, expected) result = self.ts.var(ddof=4) expected = np.var(self.ts.values, ddof=4) assert_almost_equal(result, expected) # 1 - element series with ddof=1 s = self.ts.iloc[[0]] result = s.var(ddof=1) assert isnull(result) result = s.std(ddof=1) assert isnull(result) def test_sem(self): alt = lambda x: np.std(x, ddof=1) / np.sqrt(len(x)) self._check_stat_op('sem', alt) result = self.ts.sem(ddof=4) expected = np.std(self.ts.values, ddof=4) / np.sqrt(len(self.ts.values)) assert_almost_equal(result, expected) # 1 - element series with ddof=1 s = self.ts.iloc[[0]] result = s.sem(ddof=1) assert isnull(result) def test_skew(self): tm._skip_if_no_scipy() from scipy.stats import skew alt = lambda x: skew(x, bias=False) self._check_stat_op('skew', alt) # test corner cases, skew() returns NaN unless there's at least 3 # values min_N = 3 for i in range(1, min_N + 1): s = Series(np.ones(i)) df = DataFrame(np.ones((i, i))) if i < min_N: assert np.isnan(s.skew()) assert np.isnan(df.skew()).all() else: assert 0 == s.skew() assert (df.skew() == 0).all() def test_kurt(self): tm._skip_if_no_scipy() from scipy.stats import kurtosis alt = lambda x: kurtosis(x, bias=False) self._check_stat_op('kurt', alt) index = MultiIndex(levels=[['bar'], ['one', 'two', 'three'], [0, 1]], labels=[[0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]]) s = Series(np.random.randn(6), index=index) tm.assert_almost_equal(s.kurt(), s.kurt(level=0)['bar']) # test corner cases, kurt() returns NaN unless there's at least 4 # values min_N = 4 for i in range(1, min_N + 1): s = Series(np.ones(i)) df = DataFrame(np.ones((i, i))) if i < min_N: assert np.isnan(s.kurt()) assert np.isnan(df.kurt()).all() else: assert 0 == s.kurt() assert (df.kurt() == 0).all() def test_describe(self): s = Series([0, 1, 2, 3, 4], name='int_data') result = s.describe() expected = Series([5, 2, s.std(), 0, 1, 2, 3, 4], name='int_data', index=['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max']) tm.assert_series_equal(result, expected) s = Series([True, True, False, False, False], name='bool_data') result = s.describe() expected = Series([5, 2, False, 3], name='bool_data', index=['count', 'unique', 'top', 'freq']) tm.assert_series_equal(result, expected) s = Series(['a', 'a', 'b', 'c', 'd'], name='str_data') result = s.describe() expected = Series([5, 4, 'a', 2], name='str_data', index=['count', 'unique', 'top', 'freq']) tm.assert_series_equal(result, expected) def test_argsort(self): self._check_accum_op('argsort', check_dtype=False) argsorted = self.ts.argsort() assert issubclass(argsorted.dtype.type, np.integer) # GH 2967 (introduced bug in 0.11-dev I think) s = Series([Timestamp('201301%02d' % (i + 1)) for i in range(5)]) assert s.dtype == 'datetime64[ns]' shifted = s.shift(-1) assert shifted.dtype == 'datetime64[ns]' assert isnull(shifted[4]) result = s.argsort() expected = Series(lrange(5), dtype='int64') assert_series_equal(result, expected) result = shifted.argsort() expected = Series(lrange(4) + [-1], dtype='int64') assert_series_equal(result, expected) def test_argsort_stable(self): s = Series(np.random.randint(0, 100, size=10000)) mindexer = s.argsort(kind='mergesort') qindexer = s.argsort() mexpected = np.argsort(s.values, kind='mergesort') qexpected = np.argsort(s.values, kind='quicksort') tm.assert_series_equal(mindexer, Series(mexpected), check_dtype=False) tm.assert_series_equal(qindexer, Series(qexpected), check_dtype=False) pytest.raises(AssertionError, tm.assert_numpy_array_equal, qindexer, mindexer) def test_cumsum(self): self._check_accum_op('cumsum') def test_cumprod(self): self._check_accum_op('cumprod') def test_cummin(self): tm.assert_numpy_array_equal(self.ts.cummin().values, np.minimum.accumulate(np.array(self.ts))) ts = self.ts.copy() ts[::2] = np.NaN result = ts.cummin()[1::2] expected = np.minimum.accumulate(ts.valid()) tm.assert_series_equal(result, expected) def test_cummax(self): tm.assert_numpy_array_equal(self.ts.cummax().values, np.maximum.accumulate(np.array(self.ts))) ts = self.ts.copy() ts[::2] = np.NaN result = ts.cummax()[1::2] expected = np.maximum.accumulate(ts.valid()) tm.assert_series_equal(result, expected) def test_cummin_datetime64(self): s = pd.Series(pd.to_datetime(['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-3'])) expected = pd.Series(pd.to_datetime(['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-1'])) result = s.cummin(skipna=True) tm.assert_series_equal(expected, result) expected = pd.Series(pd.to_datetime( ['NaT', '2000-1-2', '2000-1-2', '2000-1-1', '2000-1-1', '2000-1-1' ])) result = s.cummin(skipna=False) tm.assert_series_equal(expected, result) def test_cummax_datetime64(self): s = pd.Series(pd.to_datetime(['NaT', '2000-1-2', 'NaT', '2000-1-1', 'NaT', '2000-1-3'])) expected = pd.Series(pd.to_datetime(['NaT', '2000-1-2', 'NaT', '2000-1-2', 'NaT', '2000-1-3'])) result = s.cummax(skipna=True) tm.assert_series_equal(expected, result) expected = pd.Series(pd.to_datetime( ['NaT', '2000-1-2', '2000-1-2', '2000-1-2', '2000-1-2', '2000-1-3' ])) result = s.cummax(skipna=False) tm.assert_series_equal(expected, result) def test_cummin_timedelta64(self): s = pd.Series(pd.to_timedelta(['NaT', '2 min', 'NaT', '1 min', 'NaT', '3 min', ])) expected = pd.Series(pd.to_timedelta(['NaT', '2 min', 'NaT', '1 min', 'NaT', '1 min', ])) result = s.cummin(skipna=True) tm.assert_series_equal(expected, result) expected = pd.Series(pd.to_timedelta(['NaT', '2 min', '2 min', '1 min', '1 min', '1 min', ])) result = s.cummin(skipna=False) tm.assert_series_equal(expected, result) def test_cummax_timedelta64(self): s = pd.Series(pd.to_timedelta(['NaT', '2 min', 'NaT', '1 min', 'NaT', '3 min', ])) expected = pd.Series(pd.to_timedelta(['NaT', '2 min', 'NaT', '2 min', 'NaT', '3 min', ])) result = s.cummax(skipna=True) tm.assert_series_equal(expected, result) expected = pd.Series(pd.to_timedelta(['NaT', '2 min', '2 min', '2 min', '2 min', '3 min', ])) result = s.cummax(skipna=False) tm.assert_series_equal(expected, result) def test_npdiff(self): pytest.skip("skipping due to Series no longer being an " "ndarray") # no longer works as the return type of np.diff is now nd.array s = Series(np.arange(5)) r = np.diff(s) assert_series_equal(Series([nan, 0, 0, 0, nan]), r) def _check_stat_op(self, name, alternate, check_objects=False, check_allna=False): import pandas.core.nanops as nanops def testit(): f = getattr(Series, name) # add some NaNs self.series[5:15] = np.NaN # idxmax, idxmin, min, and max are valid for dates if name not in ['max', 'min']: ds = Series(date_range('1/1/2001', periods=10)) pytest.raises(TypeError, f, ds) # skipna or no assert notnull(f(self.series)) assert isnull(f(self.series, skipna=False)) # check the result is correct nona = self.series.dropna() assert_almost_equal(f(nona), alternate(nona.values)) assert_almost_equal(f(self.series), alternate(nona.values)) allna = self.series * nan if check_allna: # xref 9422 # bottleneck >= 1.0 give 0.0 for an allna Series sum try: assert nanops._USE_BOTTLENECK import bottleneck as bn # noqa assert bn.__version__ >= LooseVersion('1.0') assert f(allna) == 0.0 except: assert np.isnan(f(allna)) # dtype=object with None, it works! s = Series([1, 2, 3, None, 5]) f(s) # 2888 l = [0] l.extend(lrange(2 ** 40, 2 ** 40 + 1000)) s = Series(l, dtype='int64') assert_almost_equal(float(f(s)), float(alternate(s.values))) # check date range if check_objects: s = Series(bdate_range('1/1/2000', periods=10)) res = f(s) exp = alternate(s) assert res == exp # check on string data if name not in ['sum', 'min', 'max']: pytest.raises(TypeError, f, Series(list('abc'))) # Invalid axis. pytest.raises(ValueError, f, self.series, axis=1) # Unimplemented numeric_only parameter. if 'numeric_only' in compat.signature(f).args: tm.assert_raises_regex(NotImplementedError, name, f, self.series, numeric_only=True) testit() try: import bottleneck as bn # noqa nanops._USE_BOTTLENECK = False testit() nanops._USE_BOTTLENECK = True except ImportError: pass def _check_accum_op(self, name, check_dtype=True): func = getattr(np, name) tm.assert_numpy_array_equal(func(self.ts).values, func(np.array(self.ts)), check_dtype=check_dtype) # with missing values ts = self.ts.copy() ts[::2] = np.NaN result = func(ts)[1::2] expected = func(np.array(ts.valid())) tm.assert_numpy_array_equal(result.values, expected, check_dtype=False) def test_compress(self): cond = [True, False, True, False, False] s = Series([1, -1, 5, 8, 7], index=list('abcde'), name='foo') expected = Series(s.values.compress(cond), index=list('ac'), name='foo') tm.assert_series_equal(s.compress(cond), expected) def test_numpy_compress(self): cond = [True, False, True, False, False] s = Series([1, -1, 5, 8, 7], index=list('abcde'), name='foo') expected = Series(s.values.compress(cond), index=list('ac'), name='foo') tm.assert_series_equal(np.compress(cond, s), expected) msg = "the 'axis' parameter is not supported" tm.assert_raises_regex(ValueError, msg, np.compress, cond, s, axis=1) msg = "the 'out' parameter is not supported" tm.assert_raises_regex(ValueError, msg, np.compress, cond, s, out=s) def test_round(self): self.ts.index.name = "index_name" result = self.ts.round(2) expected = Series(np.round(self.ts.values, 2), index=self.ts.index, name='ts') assert_series_equal(result, expected) assert result.name == self.ts.name def test_numpy_round(self): # See gh-12600 s = Series([1.53, 1.36, 0.06]) out = np.round(s, decimals=0) expected = Series([2., 1., 0.]) assert_series_equal(out, expected) msg = "the 'out' parameter is not supported" with tm.assert_raises_regex(ValueError, msg): np.round(s, decimals=0, out=s) def test_built_in_round(self): if not compat.PY3: pytest.skip( 'build in round cannot be overriden prior to Python 3') s = Series([1.123, 2.123, 3.123], index=lrange(3)) result = round(s) expected_rounded0 = Series([1., 2., 3.], index=lrange(3)) tm.assert_series_equal(result, expected_rounded0) decimals = 2 expected_rounded = Series([1.12, 2.12, 3.12], index=lrange(3)) result = round(s, decimals) tm.assert_series_equal(result, expected_rounded) def test_prod_numpy16_bug(self): s = Series([1., 1., 1.], index=lrange(3)) result = s.prod() assert not isinstance(result, Series) def test_all_any(self): ts = tm.makeTimeSeries() bool_series = ts > 0 assert not bool_series.all() assert bool_series.any() # Alternative types, with implicit 'object' dtype. s = Series(['abc', True]) assert 'abc' == s.any() # 'abc' || True => 'abc' def test_all_any_params(self): # Check skipna, with implicit 'object' dtype. s1 = Series([np.nan, True]) s2 = Series([np.nan, False]) assert s1.all(skipna=False) # nan && True => True assert s1.all(skipna=True) assert np.isnan(s2.any(skipna=False)) # nan || False => nan assert not s2.any(skipna=True) # Check level. s = pd.Series([False, False, True, True, False, True], index=[0, 0, 1, 1, 2, 2]) assert_series_equal(s.all(level=0), Series([False, True, False])) assert_series_equal(s.any(level=0), Series([False, True, True])) # bool_only is not implemented with level option. pytest.raises(NotImplementedError, s.any, bool_only=True, level=0) pytest.raises(NotImplementedError, s.all, bool_only=True, level=0) # bool_only is not implemented alone. pytest.raises(NotImplementedError, s.any, bool_only=True) pytest.raises(NotImplementedError, s.all, bool_only=True) def test_modulo(self): with np.errstate(all='ignore'): # GH3590, modulo as ints p = DataFrame({'first': [3, 4, 5, 8], 'second': [0, 0, 0, 3]}) result = p['first'] % p['second'] expected = Series(p['first'].values % p['second'].values, dtype='float64') expected.iloc[0:3] = np.nan assert_series_equal(result, expected) result = p['first'] % 0 expected = Series(np.nan, index=p.index, name='first') assert_series_equal(result, expected) p = p.astype('float64') result = p['first'] % p['second'] expected = Series(p['first'].values % p['second'].values) assert_series_equal(result, expected) p = p.astype('float64') result = p['first'] % p['second'] result2 = p['second'] % p['first'] assert not np.array_equal(result, result2) # GH 9144 s = Series([0, 1]) result = s % 0 expected = Series([nan, nan]) assert_series_equal(result, expected) result = 0 % s expected = Series([nan, 0.0]) assert_series_equal(result, expected) def test_ops_consistency_on_empty(self): # GH 7869 # consistency on empty # float result = Series(dtype=float).sum() assert result == 0 result = Series(dtype=float).mean() assert isnull(result) result = Series(dtype=float).median() assert isnull(result) # timedelta64[ns] result = Series(dtype='m8[ns]').sum() assert result == Timedelta(0) result = Series(dtype='m8[ns]').mean() assert result is pd.NaT result = Series(dtype='m8[ns]').median() assert result is pd.NaT def test_corr(self): tm._skip_if_no_scipy() import scipy.stats as stats # full overlap tm.assert_almost_equal(self.ts.corr(self.ts), 1) # partial overlap tm.assert_almost_equal(self.ts[:15].corr(self.ts[5:]), 1) assert isnull(self.ts[:15].corr(self.ts[5:], min_periods=12)) ts1 = self.ts[:15].reindex(self.ts.index) ts2 = self.ts[5:].reindex(self.ts.index) assert isnull(ts1.corr(ts2, min_periods=12)) # No overlap assert np.isnan(self.ts[::2].corr(self.ts[1::2])) # all NA cp = self.ts[:10].copy() cp[:] = np.nan assert isnull(cp.corr(cp)) A = tm.makeTimeSeries() B = tm.makeTimeSeries() result = A.corr(B) expected, _ = stats.pearsonr(A, B) tm.assert_almost_equal(result, expected) def test_corr_rank(self): tm._skip_if_no_scipy() import scipy import scipy.stats as stats # kendall and spearman A = tm.makeTimeSeries() B = tm.makeTimeSeries() A[-5:] = A[:5] result = A.corr(B, method='kendall') expected = stats.kendalltau(A, B)[0] tm.assert_almost_equal(result, expected) result = A.corr(B, method='spearman') expected = stats.spearmanr(A, B)[0] tm.assert_almost_equal(result, expected) # these methods got rewritten in 0.8 if scipy.__version__ < LooseVersion('0.9'): pytest.skip("skipping corr rank because of scipy version " "{0}".format(scipy.__version__)) # results from R A = Series( [-0.89926396, 0.94209606, -1.03289164, -0.95445587, 0.76910310, - 0.06430576, -2.09704447, 0.40660407, -0.89926396, 0.94209606]) B = Series( [-1.01270225, -0.62210117, -1.56895827, 0.59592943, -0.01680292, 1.17258718, -1.06009347, -0.10222060, -0.89076239, 0.89372375]) kexp = 0.4319297 sexp = 0.5853767 tm.assert_almost_equal(A.corr(B, method='kendall'), kexp) tm.assert_almost_equal(A.corr(B, method='spearman'), sexp) def test_cov(self): # full overlap tm.assert_almost_equal(self.ts.cov(self.ts), self.ts.std() ** 2) # partial overlap tm.assert_almost_equal(self.ts[:15].cov(self.ts[5:]), self.ts[5:15].std() ** 2) # No overlap assert np.isnan(self.ts[::2].cov(self.ts[1::2])) # all NA cp = self.ts[:10].copy() cp[:] = np.nan assert isnull(cp.cov(cp)) # min_periods assert isnull(self.ts[:15].cov(self.ts[5:], min_periods=12)) ts1 = self.ts[:15].reindex(self.ts.index) ts2 = self.ts[5:].reindex(self.ts.index) assert isnull(ts1.cov(ts2, min_periods=12)) def test_count(self): assert self.ts.count() == len(self.ts) self.ts[::2] = np.NaN assert self.ts.count() == np.isfinite(self.ts).sum() mi = MultiIndex.from_arrays([list('aabbcc'), [1, 2, 2, nan, 1, 2]]) ts = Series(np.arange(len(mi)), index=mi) left = ts.count(level=1) right = Series([2, 3, 1], index=[1, 2, nan]) assert_series_equal(left, right) ts.iloc[[0, 3, 5]] = nan assert_series_equal(ts.count(level=1), right - 1) def test_dot(self): a = Series(np.random.randn(4), index=['p', 'q', 'r', 's']) b = DataFrame(np.random.randn(3, 4), index=['1', '2', '3'], columns=['p', 'q', 'r', 's']).T result = a.dot(b) expected = Series(np.dot(a.values, b.values), index=['1', '2', '3']) assert_series_equal(result, expected) # Check index alignment b2 = b.reindex(index=reversed(b.index)) result = a.dot(b) assert_series_equal(result, expected) # Check ndarray argument result = a.dot(b.values) assert np.all(result == expected.values) assert_almost_equal(a.dot(b['2'].values), expected['2']) # Check series argument assert_almost_equal(a.dot(b['1']), expected['1']) assert_almost_equal(a.dot(b2['1']), expected['1']) pytest.raises(Exception, a.dot, a.values[:3]) pytest.raises(ValueError, a.dot, b.T) def test_value_counts_nunique(self): # basics.rst doc example series = Series(np.random.randn(500)) series[20:500] = np.nan series[10:20] = 5000 result = series.nunique() assert result == 11 def test_unique(self): # 714 also, dtype=float s = Series([1.2345] * 100) s[::2] = np.nan result = s.unique() assert len(result) == 2 s = Series([1.2345] * 100, dtype='f4') s[::2] = np.nan result = s.unique() assert len(result) == 2 # NAs in object arrays #714 s = Series(['foo'] * 100, dtype='O') s[::2] = np.nan result = s.unique() assert len(result) == 2 # decision about None s = Series([1, 2, 3, None, None, None], dtype=object) result = s.unique() expected = np.array([1, 2, 3, None], dtype=object) tm.assert_numpy_array_equal(result, expected) def test_drop_duplicates(self): # check both int and object for s in [Series([1, 2, 3, 3]), Series(['1', '2', '3', '3'])]: expected = Series([False, False, False, True]) assert_series_equal(s.duplicated(), expected) assert_series_equal(s.drop_duplicates(), s[~expected]) sc = s.copy() sc.drop_duplicates(inplace=True) assert_series_equal(sc, s[~expected]) expected = Series([False, False, True, False]) assert_series_equal(s.duplicated(keep='last'), expected) assert_series_equal(s.drop_duplicates(keep='last'), s[~expected]) sc = s.copy() sc.drop_duplicates(keep='last', inplace=True) assert_series_equal(sc, s[~expected]) expected = Series([False, False, True, True]) assert_series_equal(s.duplicated(keep=False), expected) assert_series_equal(s.drop_duplicates(keep=False), s[~expected]) sc = s.copy() sc.drop_duplicates(keep=False, inplace=True) assert_series_equal(sc, s[~expected]) for s in [Series([1, 2, 3, 5, 3, 2, 4]), Series(['1', '2', '3', '5', '3', '2', '4'])]: expected = Series([False, False, False, False, True, True, False]) assert_series_equal(s.duplicated(), expected) assert_series_equal(s.drop_duplicates(), s[~expected]) sc = s.copy() sc.drop_duplicates(inplace=True) assert_series_equal(sc, s[~expected]) expected = Series([False, True, True, False, False, False, False]) assert_series_equal(s.duplicated(keep='last'), expected) assert_series_equal(s.drop_duplicates(keep='last'), s[~expected]) sc = s.copy() sc.drop_duplicates(keep='last', inplace=True) assert_series_equal(sc, s[~expected]) expected = Series([False, True, True, False, True, True, False]) assert_series_equal(s.duplicated(keep=False), expected) assert_series_equal(s.drop_duplicates(keep=False), s[~expected]) sc = s.copy() sc.drop_duplicates(keep=False, inplace=True) assert_series_equal(sc, s[~expected]) def test_clip(self): val = self.ts.median() assert self.ts.clip_lower(val).min() == val assert self.ts.clip_upper(val).max() == val assert self.ts.clip(lower=val).min() == val assert self.ts.clip(upper=val).max() == val result = self.ts.clip(-0.5, 0.5) expected = np.clip(self.ts, -0.5, 0.5) assert_series_equal(result, expected) assert isinstance(expected, Series) def test_clip_types_and_nulls(self): sers = [Series([np.nan, 1.0, 2.0, 3.0]), Series([None, 'a', 'b', 'c']), Series(pd.to_datetime( [np.nan, 1, 2, 3], unit='D'))] for s in sers: thresh = s[2] l = s.clip_lower(thresh) u = s.clip_upper(thresh) assert l[notnull(l)].min() == thresh assert u[notnull(u)].max() == thresh assert list(isnull(s)) == list(isnull(l)) assert list(isnull(s)) == list(isnull(u)) def test_clip_against_series(self): # GH #6966 s = Series([1.0, 1.0, 4.0]) threshold = Series([1.0, 2.0, 3.0]) assert_series_equal(s.clip_lower(threshold), Series([1.0, 2.0, 4.0])) assert_series_equal(s.clip_upper(threshold), Series([1.0, 1.0, 3.0])) lower = Series([1.0, 2.0, 3.0]) upper = Series([1.5, 2.5, 3.5]) assert_series_equal(s.clip(lower, upper), Series([1.0, 2.0, 3.5])) assert_series_equal(s.clip(1.5, upper), Series([1.5, 1.5, 3.5])) def test_clip_with_datetimes(self): # GH 11838 # naive and tz-aware datetimes t = Timestamp('2015-12-01 09:30:30') s = Series([Timestamp('2015-12-01 09:30:00'), Timestamp( '2015-12-01 09:31:00')]) result = s.clip(upper=t) expected = Series([Timestamp('2015-12-01 09:30:00'), Timestamp( '2015-12-01 09:30:30')]) assert_series_equal(result, expected) t = Timestamp('2015-12-01 09:30:30', tz='US/Eastern') s = Series([Timestamp('2015-12-01 09:30:00', tz='US/Eastern'), Timestamp('2015-12-01 09:31:00', tz='US/Eastern')]) result = s.clip(upper=t) expected = Series([Timestamp('2015-12-01 09:30:00', tz='US/Eastern'), Timestamp('2015-12-01 09:30:30', tz='US/Eastern')]) assert_series_equal(result, expected) def test_cummethods_bool(self): # GH 6270 # looks like a buggy np.maximum.accumulate for numpy 1.6.1, py 3.2 def cummin(x): return np.minimum.accumulate(x) def cummax(x): return np.maximum.accumulate(x) a = pd.Series([False, False, False, True, True, False, False]) b = ~a c = pd.Series([False] * len(b)) d = ~c methods = {'cumsum': np.cumsum, 'cumprod': np.cumprod, 'cummin': cummin, 'cummax': cummax} args = product((a, b, c, d), methods) for s, method in args: expected = Series(methods[method](s.values)) result = getattr(s, method)() assert_series_equal(result, expected) e = pd.Series([False, True, nan, False]) cse = pd.Series([0, 1, nan, 1], dtype=object) cpe = pd.Series([False, 0, nan, 0]) cmin = pd.Series([False, False, nan, False]) cmax = pd.Series([False, True, nan, True]) expecteds = {'cumsum': cse, 'cumprod': cpe, 'cummin': cmin, 'cummax': cmax} for method in methods: res = getattr(e, method)() assert_series_equal(res, expecteds[method]) def test_isin(self): s = Series(['A', 'B', 'C', 'a', 'B', 'B', 'A', 'C']) result = s.isin(['A', 'C']) expected = Series([True, False, True, False, False, False, True, True]) assert_series_equal(result, expected) def test_isin_with_string_scalar(self): # GH4763 s = Series(['A', 'B', 'C', 'a', 'B', 'B', 'A', 'C']) with pytest.raises(TypeError): s.isin('a') with pytest.raises(TypeError): s = Series(['aaa', 'b', 'c']) s.isin('aaa') def test_isin_with_i8(self): # GH 5021 expected = Series([True, True, False, False, False]) expected2 = Series([False, True, False, False, False]) # datetime64[ns] s = Series(date_range('jan-01-2013', 'jan-05-2013')) result = s.isin(s[0:2]) assert_series_equal(result, expected) result = s.isin(s[0:2].values) assert_series_equal(result, expected) # fails on dtype conversion in the first place result = s.isin(s[0:2].values.astype('datetime64[D]')) assert_series_equal(result, expected) result = s.isin([s[1]]) assert_series_equal(result, expected2) result = s.isin([np.datetime64(s[1])]) assert_series_equal(result, expected2) result = s.isin(set(s[0:2])) assert_series_equal(result, expected) # timedelta64[ns] s = Series(pd.to_timedelta(lrange(5), unit='d')) result = s.isin(s[0:2]) assert_series_equal(result, expected) def test_timedelta64_analytics(self): from pandas import date_range # index min/max td = Series(date_range('2012-1-1', periods=3, freq='D')) - \ Timestamp('20120101') result = td.idxmin() assert result == 0 result = td.idxmax() assert result == 2 # GH 2982 # with NaT td[0] = np.nan result = td.idxmin() assert result == 1 result = td.idxmax() assert result == 2 # abs s1 = Series(date_range('20120101', periods=3)) s2 = Series(date_range('20120102', periods=3)) expected = Series(s2 - s1) # this fails as numpy returns timedelta64[us] # result = np.abs(s1-s2) # assert_frame_equal(result,expected) result = (s1 - s2).abs() assert_series_equal(result, expected) # max/min result = td.max() expected = Timedelta('2 days') assert result == expected result = td.min() expected = Timedelta('1 days') assert result == expected def test_idxmin(self): # test idxmin # _check_stat_op approach can not be used here because of isnull check. # add some NaNs self.series[5:15] = np.NaN # skipna or no assert self.series[self.series.idxmin()] == self.series.min() assert isnull(self.series.idxmin(skipna=False)) # no NaNs nona = self.series.dropna() assert nona[nona.idxmin()] == nona.min() assert (nona.index.values.tolist().index(nona.idxmin()) == nona.values.argmin()) # all NaNs allna = self.series * nan assert isnull(allna.idxmin()) # datetime64[ns] from pandas import date_range s = Series(date_range('20130102', periods=6)) result = s.idxmin() assert result == 0 s[0] = np.nan result = s.idxmin() assert result == 1 def test_numpy_argmin(self): # argmin is aliased to idxmin data = np.random.randint(0, 11, size=10) result = np.argmin(Series(data)) assert result == np.argmin(data) if not _np_version_under1p10: msg = "the 'out' parameter is not supported" tm.assert_raises_regex(ValueError, msg, np.argmin, Series(data), out=data) def test_idxmax(self): # test idxmax # _check_stat_op approach can not be used here because of isnull check. # add some NaNs self.series[5:15] = np.NaN # skipna or no assert self.series[self.series.idxmax()] == self.series.max() assert isnull(self.series.idxmax(skipna=False)) # no NaNs nona = self.series.dropna() assert nona[nona.idxmax()] == nona.max() assert (nona.index.values.tolist().index(nona.idxmax()) == nona.values.argmax()) # all NaNs allna = self.series * nan assert isnull(allna.idxmax()) from pandas import date_range s = Series(date_range('20130102', periods=6)) result = s.idxmax() assert result == 5 s[5] = np.nan result = s.idxmax() assert result == 4 # Float64Index # GH 5914 s = pd.Series([1, 2, 3], [1.1, 2.1, 3.1]) result = s.idxmax() assert result == 3.1 result = s.idxmin() assert result == 1.1 s = pd.Series(s.index, s.index) result = s.idxmax() assert result == 3.1 result = s.idxmin() assert result == 1.1 def test_numpy_argmax(self): # argmax is aliased to idxmax data = np.random.randint(0, 11, size=10) result = np.argmax(Series(data)) assert result == np.argmax(data) if not _np_version_under1p10: msg = "the 'out' parameter is not supported" tm.assert_raises_regex(ValueError, msg, np.argmax, Series(data), out=data) def test_ptp(self): N = 1000 arr = np.random.randn(N) ser = Series(arr) assert np.ptp(ser) == np.ptp(arr) # GH11163 s = Series([3, 5, np.nan, -3, 10]) assert s.ptp() == 13 assert pd.isnull(s.ptp(skipna=False)) mi = pd.MultiIndex.from_product([['a', 'b'], [1, 2, 3]]) s = pd.Series([1, np.nan, 7, 3, 5, np.nan], index=mi) expected = pd.Series([6, 2], index=['a', 'b'], dtype=np.float64) tm.assert_series_equal(s.ptp(level=0), expected) expected = pd.Series([np.nan, np.nan], index=['a', 'b']) tm.assert_series_equal(s.ptp(level=0, skipna=False), expected) with pytest.raises(ValueError): s.ptp(axis=1) s = pd.Series(['a', 'b', 'c', 'd', 'e']) with pytest.raises(TypeError): s.ptp() with pytest.raises(NotImplementedError): s.ptp(numeric_only=True) def test_empty_timeseries_redections_return_nat(self): # covers #11245 for dtype in ('m8[ns]', 'm8[ns]', 'M8[ns]', 'M8[ns, UTC]'): assert Series([], dtype=dtype).min() is pd.NaT assert Series([], dtype=dtype).max() is pd.NaT def test_unique_data_ownership(self): # it works! #1807 Series(Series(["a", "c", "b"]).unique()).sort_values() def test_repeat(self): s = Series(np.random.randn(3), index=['a', 'b', 'c']) reps = s.repeat(5) exp = Series(s.values.repeat(5), index=s.index.values.repeat(5)) assert_series_equal(reps, exp) with tm.assert_produces_warning(FutureWarning): result = s.repeat(reps=5) assert_series_equal(result, exp) to_rep = [2, 3, 4] reps = s.repeat(to_rep) exp = Series(s.values.repeat(to_rep), index=s.index.values.repeat(to_rep)) assert_series_equal(reps, exp) def test_numpy_repeat(self): s = Series(np.arange(3), name='x') expected = Series(s.values.repeat(2), name='x', index=s.index.values.repeat(2)) assert_series_equal(np.repeat(s, 2), expected) msg = "the 'axis' parameter is not supported" tm.assert_raises_regex(ValueError, msg, np.repeat, s, 2, axis=0) def test_searchsorted(self): s = Series([1, 2, 3]) idx = s.searchsorted(1, side='left') tm.assert_numpy_array_equal(idx, np.array([0], dtype=np.intp)) idx = s.searchsorted(1, side='right') tm.assert_numpy_array_equal(idx, np.array([1], dtype=np.intp)) with tm.assert_produces_warning(FutureWarning): idx = s.searchsorted(v=1, side='left') tm.assert_numpy_array_equal(idx, np.array([0], dtype=np.intp)) def test_searchsorted_numeric_dtypes_scalar(self): s = Series([1, 2, 90, 1000, 3e9]) r = s.searchsorted(30) e = 2 assert r == e r = s.searchsorted([30]) e = np.array([2], dtype=np.intp) tm.assert_numpy_array_equal(r, e) def test_searchsorted_numeric_dtypes_vector(self): s = Series([1, 2, 90, 1000, 3e9]) r = s.searchsorted([91, 2e6]) e = np.array([3, 4], dtype=np.intp) tm.assert_numpy_array_equal(r, e) def test_search_sorted_datetime64_scalar(self): s = Series(pd.date_range('20120101', periods=10, freq='2D')) v = pd.Timestamp('20120102') r = s.searchsorted(v) e = 1 assert r == e def test_search_sorted_datetime64_list(self): s = Series(pd.date_range('20120101', periods=10, freq='2D')) v = [pd.Timestamp('20120102'), pd.Timestamp('20120104')] r = s.searchsorted(v) e = np.array([1, 2], dtype=np.intp) tm.assert_numpy_array_equal(r, e) def test_searchsorted_sorter(self): # GH8490 s = Series([3, 1, 2]) r = s.searchsorted([0, 3], sorter=np.argsort(s)) e = np.array([0, 2], dtype=np.intp) tm.assert_numpy_array_equal(r, e) def test_is_unique(self): # GH11946 s = Series(np.random.randint(0, 10, size=1000)) assert not s.is_unique s = Series(np.arange(1000)) assert s.is_unique def test_is_monotonic(self): s = Series(np.random.randint(0, 10, size=1000)) assert not s.is_monotonic s = Series(np.arange(1000)) assert s.is_monotonic assert s.is_monotonic_increasing s = Series(np.arange(1000, 0, -1)) assert s.is_monotonic_decreasing s = Series(pd.date_range('20130101', periods=10)) assert s.is_monotonic assert s.is_monotonic_increasing s = Series(list(reversed(s.tolist()))) assert not s.is_monotonic assert s.is_monotonic_decreasing def test_sort_index_level(self): mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC')) s = Series([1, 2], mi) backwards = s.iloc[[1, 0]] res = s.sort_index(level='A') assert_series_equal(backwards, res) res = s.sort_index(level=['A', 'B']) assert_series_equal(backwards, res) res = s.sort_index(level='A', sort_remaining=False) assert_series_equal(s, res) res = s.sort_index(level=['A', 'B'], sort_remaining=False) assert_series_equal(s, res) def test_apply_categorical(self): values = pd.Categorical(list('ABBABCD'), categories=list('DCBA'), ordered=True) s = pd.Series(values, name='XX', index=list('abcdefg')) result = s.apply(lambda x: x.lower()) # should be categorical dtype when the number of categories are # the same values = pd.Categorical(list('abbabcd'), categories=list('dcba'), ordered=True) exp = pd.Series(values, name='XX', index=list('abcdefg')) tm.assert_series_equal(result, exp) tm.assert_categorical_equal(result.values, exp.values) result = s.apply(lambda x: 'A') exp = pd.Series(['A'] * 7, name='XX', index=list('abcdefg')) tm.assert_series_equal(result, exp) assert result.dtype == np.object def test_shift_int(self): ts = self.ts.astype(int) shifted = ts.shift(1) expected = ts.astype(float).shift(1) assert_series_equal(shifted, expected) def test_shift_categorical(self): # GH 9416 s = pd.Series(['a', 'b', 'c', 'd'], dtype='category') assert_series_equal(s.iloc[:-1], s.shift(1).shift(-1).valid()) sp1 = s.shift(1) assert_index_equal(s.index, sp1.index) assert np.all(sp1.values.codes[:1] == -1) assert np.all(s.values.codes[:-1] == sp1.values.codes[1:]) sn2 = s.shift(-2) assert_index_equal(s.index, sn2.index) assert np.all(sn2.values.codes[-2:] == -1) assert np.all(s.values.codes[2:] == sn2.values.codes[:-2]) assert_index_equal(s.values.categories, sp1.values.categories) assert_index_equal(s.values.categories, sn2.values.categories) def test_reshape_deprecate(self): x = Series(np.random.random(10), name='x') tm.assert_produces_warning(FutureWarning, x.reshape, x.shape) def test_reshape_non_2d(self): # see gh-4554 with tm.assert_produces_warning(FutureWarning): x = Series(np.random.random(201), name='x') assert x.reshape(x.shape, ) is x # see gh-2719 with tm.assert_produces_warning(FutureWarning): a = Series([1, 2, 3, 4]) result = a.reshape(2, 2) expected = a.values.reshape(2, 2) tm.assert_numpy_array_equal(result, expected) assert isinstance(result, type(expected)) def test_reshape_2d_return_array(self): x = Series(np.random.random(201), name='x') with tm.assert_produces_warning(FutureWarning): result = x.reshape((-1, 1)) assert not isinstance(result, Series) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result2 = np.reshape(x, (-1, 1)) assert not isinstance(result2, Series) with tm.assert_produces_warning(FutureWarning): result = x[:, None] expected = x.reshape((-1, 1)) tm.assert_almost_equal(result, expected) def test_reshape_bad_kwarg(self): a = Series([1, 2, 3, 4]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): msg = "'foo' is an invalid keyword argument for this function" tm.assert_raises_regex( TypeError, msg, a.reshape, (2, 2), foo=2) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): msg = r"reshape\(\) got an unexpected keyword argument 'foo'" tm.assert_raises_regex( TypeError, msg, a.reshape, a.shape, foo=2) def test_numpy_reshape(self): a = Series([1, 2, 3, 4]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = np.reshape(a, (2, 2)) expected = a.values.reshape(2, 2) tm.assert_numpy_array_equal(result, expected) assert isinstance(result, type(expected)) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = np.reshape(a, a.shape) tm.assert_series_equal(result, a) def test_unstack(self): from numpy import nan index = MultiIndex(levels=[['bar', 'foo'], ['one', 'three', 'two']], labels=[[1, 1, 0, 0], [0, 1, 0, 2]]) s = Series(np.arange(4.), index=index) unstacked = s.unstack() expected = DataFrame([[2., nan, 3.], [0., 1., nan]], index=['bar', 'foo'], columns=['one', 'three', 'two']) assert_frame_equal(unstacked, expected) unstacked = s.unstack(level=0) assert_frame_equal(unstacked, expected.T) index = MultiIndex(levels=[['bar'], ['one', 'two', 'three'], [0, 1]], labels=[[0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]]) s = Series(np.random.randn(6), index=index) exp_index = MultiIndex(levels=[['one', 'two', 'three'], [0, 1]], labels=[[0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1]]) expected = DataFrame({'bar': s.values}, index=exp_index).sort_index(level=0) unstacked = s.unstack(0).sort_index() assert_frame_equal(unstacked, expected) # GH5873 idx = pd.MultiIndex.from_arrays([[101, 102], [3.5, np.nan]]) ts = pd.Series([1, 2], index=idx) left = ts.unstack() right = DataFrame([[nan, 1], [2, nan]], index=[101, 102], columns=[nan, 3.5]) assert_frame_equal(left, right) idx = pd.MultiIndex.from_arrays([['cat', 'cat', 'cat', 'dog', 'dog' ], ['a', 'a', 'b', 'a', 'b'], [1, 2, 1, 1, np.nan]]) ts = pd.Series([1.0, 1.1, 1.2, 1.3, 1.4], index=idx) right = DataFrame([[1.0, 1.3], [1.1, nan], [nan, 1.4], [1.2, nan]], columns=['cat', 'dog']) tpls = [('a', 1), ('a', 2), ('b', nan), ('b', 1)] right.index = pd.MultiIndex.from_tuples(tpls) assert_frame_equal(ts.unstack(level=0), right) def test_value_counts_datetime(self): # most dtypes are tested in test_base.py values = [pd.Timestamp('2011-01-01 09:00'), pd.Timestamp('2011-01-01 10:00'), pd.Timestamp('2011-01-01 11:00'), pd.Timestamp('2011-01-01 09:00'), pd.Timestamp('2011-01-01 09:00'), pd.Timestamp('2011-01-01 11:00')] exp_idx = pd.DatetimeIndex(['2011-01-01 09:00', '2011-01-01 11:00', '2011-01-01 10:00']) exp = pd.Series([3, 2, 1], index=exp_idx, name='xxx') s = pd.Series(values, name='xxx') tm.assert_series_equal(s.value_counts(), exp) # check DatetimeIndex outputs the same result idx = pd.DatetimeIndex(values, name='xxx') tm.assert_series_equal(idx.value_counts(), exp) # normalize exp = pd.Series(np.array([3., 2., 1]) / 6., index=exp_idx, name='xxx') tm.assert_series_equal(s.value_counts(normalize=True), exp) tm.assert_series_equal(idx.value_counts(normalize=True), exp) def test_value_counts_datetime_tz(self): values = [pd.Timestamp('2011-01-01 09:00', tz='US/Eastern'), pd.Timestamp('2011-01-01 10:00', tz='US/Eastern'), pd.Timestamp('2011-01-01 11:00', tz='US/Eastern'), pd.Timestamp('2011-01-01 09:00', tz='US/Eastern'), pd.Timestamp('2011-01-01 09:00', tz='US/Eastern'), pd.Timestamp('2011-01-01 11:00', tz='US/Eastern')] exp_idx = pd.DatetimeIndex(['2011-01-01 09:00', '2011-01-01 11:00', '2011-01-01 10:00'], tz='US/Eastern') exp = pd.Series([3, 2, 1], index=exp_idx, name='xxx') s = pd.Series(values, name='xxx') tm.assert_series_equal(s.value_counts(), exp) idx = pd.DatetimeIndex(values, name='xxx') tm.assert_series_equal(idx.value_counts(), exp) exp = pd.Series(np.array([3., 2., 1]) / 6., index=exp_idx, name='xxx') tm.assert_series_equal(s.value_counts(normalize=True), exp) tm.assert_series_equal(idx.value_counts(normalize=True), exp) def test_value_counts_period(self): values = [pd.Period('2011-01', freq='M'), pd.Period('2011-02', freq='M'), pd.Period('2011-03', freq='M'), pd.Period('2011-01', freq='M'), pd.Period('2011-01', freq='M'), pd.Period('2011-03', freq='M')] exp_idx = pd.PeriodIndex(['2011-01', '2011-03', '2011-02'], freq='M') exp = pd.Series([3, 2, 1], index=exp_idx, name='xxx') s = pd.Series(values, name='xxx') tm.assert_series_equal(s.value_counts(), exp) # check DatetimeIndex outputs the same result idx = pd.PeriodIndex(values, name='xxx') tm.assert_series_equal(idx.value_counts(), exp) # normalize exp = pd.Series(np.array([3., 2., 1]) / 6., index=exp_idx, name='xxx') tm.assert_series_equal(s.value_counts(normalize=True), exp) tm.assert_series_equal(idx.value_counts(normalize=True), exp) def test_value_counts_categorical_ordered(self): # most dtypes are tested in test_base.py values = pd.Categorical([1, 2, 3, 1, 1, 3], ordered=True) exp_idx = pd.CategoricalIndex([1, 3, 2], categories=[1, 2, 3], ordered=True) exp = pd.Series([3, 2, 1], index=exp_idx, name='xxx') s = pd.Series(values, name='xxx') tm.assert_series_equal(s.value_counts(), exp) # check CategoricalIndex outputs the same result idx = pd.CategoricalIndex(values, name='xxx') tm.assert_series_equal(idx.value_counts(), exp) # normalize exp = pd.Series(np.array([3., 2., 1]) / 6., index=exp_idx, name='xxx') tm.assert_series_equal(s.value_counts(normalize=True), exp) tm.assert_series_equal(idx.value_counts(normalize=True), exp) def test_value_counts_categorical_not_ordered(self): values = pd.Categorical([1, 2, 3, 1, 1, 3], ordered=False) exp_idx = pd.CategoricalIndex([1, 3, 2], categories=[1, 2, 3], ordered=False) exp = pd.Series([3, 2, 1], index=exp_idx, name='xxx') s = pd.Series(values, name='xxx') tm.assert_series_equal(s.value_counts(), exp) # check CategoricalIndex outputs the same result idx = pd.CategoricalIndex(values, name='xxx') tm.assert_series_equal(idx.value_counts(), exp) # normalize exp = pd.Series(np.array([3., 2., 1]) / 6., index=exp_idx, name='xxx') tm.assert_series_equal(s.value_counts(normalize=True), exp) tm.assert_series_equal(idx.value_counts(normalize=True), exp) @pytest.fixture def s_main_dtypes(): df = pd.DataFrame( {'datetime': pd.to_datetime(['2003', '2002', '2001', '2002', '2005']), 'datetimetz': pd.to_datetime( ['2003', '2002', '2001', '2002', '2005']).tz_localize('US/Eastern'), 'timedelta': pd.to_timedelta(['3d', '2d', '1d', '2d', '5d'])}) for dtype in ['int8', 'int16', 'int32', 'int64', 'float32', 'float64', 'uint8', 'uint16', 'uint32', 'uint64']: df[dtype] = Series([3, 2, 1, 2, 5], dtype=dtype) return df class TestNLargestNSmallest(object): @pytest.mark.parametrize( "r", [Series([3., 2, 1, 2, '5'], dtype='object'), Series([3., 2, 1, 2, 5], dtype='object'), # not supported on some archs # Series([3., 2, 1, 2, 5], dtype='complex256'), Series([3., 2, 1, 2, 5], dtype='complex128'), Series(list('abcde'), dtype='category'), Series(list('abcde'))]) def test_error(self, r): dt = r.dtype msg = ("Cannot use method 'n(larg|small)est' with " "dtype {dt}".format(dt=dt)) args = 2, len(r), 0, -1 methods = r.nlargest, r.nsmallest for method, arg in product(methods, args): with tm.assert_raises_regex(TypeError, msg): method(arg) @pytest.mark.parametrize( "s", [v for k, v in s_main_dtypes().iteritems()]) def test_nsmallest_nlargest(self, s): # float, int, datetime64 (use i8), timedelts64 (same), # object that are numbers, object that are strings assert_series_equal(s.nsmallest(2), s.iloc[[2, 1]]) assert_series_equal(s.nsmallest(2, keep='last'), s.iloc[[2, 3]]) empty = s.iloc[0:0] assert_series_equal(s.nsmallest(0), empty) assert_series_equal(s.nsmallest(-1), empty) assert_series_equal(s.nlargest(0), empty) assert_series_equal(s.nlargest(-1), empty) assert_series_equal(s.nsmallest(len(s)), s.sort_values()) assert_series_equal(s.nsmallest(len(s) + 1), s.sort_values()) assert_series_equal(s.nlargest(len(s)), s.iloc[[4, 0, 1, 3, 2]]) assert_series_equal(s.nlargest(len(s) + 1), s.iloc[[4, 0, 1, 3, 2]]) def test_misc(self): s = Series([3., np.nan, 1, 2, 5]) assert_series_equal(s.nlargest(), s.iloc[[4, 0, 3, 2]]) assert_series_equal(s.nsmallest(), s.iloc[[2, 3, 0, 4]]) msg = 'keep must be either "first", "last"' with tm.assert_raises_regex(ValueError, msg): s.nsmallest(keep='invalid') with tm.assert_raises_regex(ValueError, msg): s.nlargest(keep='invalid') # GH 15297 s = Series([1] * 5, index=[1, 2, 3, 4, 5]) expected_first = Series([1] * 3, index=[1, 2, 3]) expected_last = Series([1] * 3, index=[5, 4, 3]) result = s.nsmallest(3) assert_series_equal(result, expected_first) result = s.nsmallest(3, keep='last') assert_series_equal(result, expected_last) result = s.nlargest(3) assert_series_equal(result, expected_first) result = s.nlargest(3, keep='last') assert_series_equal(result, expected_last) @pytest.mark.parametrize('n', range(1, 5)) def test_n(self, n): # GH 13412 s = Series([1, 4, 3, 2], index=[0, 0, 1, 1]) result = s.nlargest(n) expected = s.sort_values(ascending=False).head(n) assert_series_equal(result, expected) result = s.nsmallest(n) expected = s.sort_values().head(n) assert_series_equal(result, expected)
mit
DeercoderResearch/deepnet
deepnet/ais.py
10
7589
"""Computes partition function for RBM-like models using Annealed Importance Sampling.""" import numpy as np from deepnet import dbm from deepnet import util from deepnet import trainer as tr from choose_matrix_library import * import sys import numpy as np import pdb import time import itertools import matplotlib.pyplot as plt from deepnet import visualize import lightspeed def SampleEnergySoftmax(layer, numsamples, use_lightspeed=False): sample = layer.sample energy = layer.state temp = layer.expanded_batch if use_lightspeed: layer.ApplyActivation() layer.state.sum(axis=0, target=layer.temp) layer.state.div_by_row(layer.temp, target=temp) probs_cpu = temp.asarray().astype(np.float64) samples_cpu = lightspeed.SampleSoftmax(probs_cpu, numsamples) sample.overwrite(samples_cpu.astype(np.float32)) else: sample.assign(0) for i in range(numsamples): energy.perturb_energy_for_softmax_sampling(target=temp) temp.choose_max_and_accumulate(sample) def LogMeanExp(x): offset = x.max() return offset + np.log(np.exp(x-offset).mean()) def LogSumExp(x): offset = x.max() return offset + np.log(np.exp(x-offset).sum()) def Display(w, hid_state, input_state, w_var, x_axis): w = w.asarray().flatten() #plt.figure(1) #plt.clf() #plt.hist(w, 100) #visualize.display_hidden(hid_state.asarray(), 2, 'activations', prob=True) #plt.figure(3) #plt.clf() #plt.imshow(hid_state.asarray().T, cmap=plt.cm.gray, interpolation='nearest') #plt.figure(4) #plt.clf() #plt.imshow(input_state.asarray().T, cmap=plt.cm.gray, interpolation='nearest') #, state.shape[0], state.shape[1], state.shape[0], 3, title='Markov chains') #plt.tight_layout(pad=0, w_pad=0, h_pad=0) plt.figure(5) plt.clf() plt.suptitle('Variance') plt.plot(np.array(x_axis), np.array(w_var)) plt.draw() def AISReplicatedSoftmax(model, D, num_chains, display=False): schedule = np.concatenate(( #np.arange(0.0, 1.0, 0.01), #np.arange(0.0, 1.0, 0.001), np.arange(0.0, 0.7, 0.001), # 700 np.arange(0.7, 0.9, 0.0001), # 2000 np.arange(0.9, 1.0, 0.00002) # 5000 )) #schedule = np.array([0.]) cm.CUDAMatrix.init_random(seed=0) assert len(model.layer) == 2, 'Only implemented for RBMs.' steps = len(schedule) input_layer = model.layer[0] hidden_layer = model.layer[1] edge = model.edge[0] batchsize = num_chains w = edge.params['weight'] a = hidden_layer.params['bias'] b = input_layer.params['bias'] numvis, numhid = w.shape f = 0.1 input_layer.AllocateBatchsizeDependentMemory(num_chains) hidden_layer.AllocateBatchsizeDependentMemory(num_chains) # INITIALIZE TO SAMPLES FROM BASE MODEL. input_layer.state.assign(0) input_layer.NN.assign(D) input_layer.state.add_col_mult(b, f) SampleEnergySoftmax(input_layer, D) w_ais = cm.CUDAMatrix(np.zeros((1, batchsize))) #pdb.set_trace() w_variance = [] x_axis = [] if display: Display(w_ais, hidden_layer.state, input_layer.state, w_variance, x_axis) #raw_input('Press Enter.') #pdb.set_trace() # RUN AIS. for i in range(steps-1): sys.stdout.write('\r%d' % (i+1)) sys.stdout.flush() cm.dot(w.T, input_layer.sample, target=hidden_layer.state) hidden_layer.state.add_col_mult(a, D) hidden_layer.state.mult(schedule[i], target=hidden_layer.temp) hidden_layer.state.mult(schedule[i+1]) cm.log_1_plus_exp(hidden_layer.state, target=hidden_layer.deriv) cm.log_1_plus_exp(hidden_layer.temp) hidden_layer.deriv.subtract(hidden_layer.temp) w_ais.add_sums(hidden_layer.deriv, axis=0) w_ais.add_dot(b.T, input_layer.sample, mult=(1-f)*(schedule[i+1]-schedule[i])) hidden_layer.ApplyActivation() hidden_layer.Sample() cm.dot(w, hidden_layer.sample, target=input_layer.state) input_layer.state.add_col_vec(b) input_layer.state.mult(schedule[i+1]) input_layer.state.add_col_mult(b, f*(1-schedule[i+1])) SampleEnergySoftmax(input_layer, D) if display and (i % 100 == 0 or i == steps - 2): w_variance.append(w_ais.asarray().var()) x_axis.append(i) Display(w_ais, hidden_layer.state, input_layer.sample, w_variance, x_axis) sys.stdout.write('\n') z = LogMeanExp(w_ais.asarray()) + D * LogSumExp(f * b.asarray()) + numhid * np.log(2) return z def AISBinaryRbm(model, schedule): cm.CUDAMatrix.init_random(seed=int(time.time())) assert len(model.layer) == 2, 'Only implemented for RBMs.' steps = len(schedule) input_layer = model.layer[0] hidden_layer = model.layer[1] edge = model.edge[0] batchsize = model.t_op.batchsize w = edge.params['weight'] a = hidden_layer.params['bias'] b = input_layer.params['bias'] numvis, numhid = w.shape # INITIALIZE TO UNIFORM RANDOM. input_layer.state.assign(0) input_layer.ApplyActivation() input_layer.Sample() w_ais = cm.CUDAMatrix(np.zeros((1, batchsize))) unitcell = cm.empty((1, 1)) # RUN AIS. for i in range(1, steps): cm.dot(w.T, input_layer.sample, target=hidden_layer.state) hidden_layer.state.add_col_vec(a) hidden_layer.state.mult(schedule[i-1], target=hidden_layer.temp) hidden_layer.state.mult(schedule[i]) cm.log_1_plus_exp(hidden_layer.state, target=hidden_layer.deriv) cm.log_1_plus_exp(hidden_layer.temp) hidden_layer.deriv.subtract(hidden_layer.temp) w_ais.add_sums(hidden_layer.deriv, axis=0) w_ais.add_dot(b.T, input_layer.state, mult=schedule[i]-schedule[i-1]) hidden_layer.ApplyActivation() hidden_layer.Sample() cm.dot(w, hidden_layer.sample, target=input_layer.state) input_layer.state.add_col_vec(b) input_layer.state.mult(schedule[i]) input_layer.ApplyActivation() input_layer.Sample() z = LogMeanExp(w_ais.asarray()) + numvis * np.log(2) + numhid * np.log(2) return z def GetAll(n): x = np.zeros((n, 2**n)) a = [] for i in range(n): a.append([0, 1]) for i, r in enumerate(itertools.product(*tuple(a))): x[:, i] = np.array(r) return x def ExactZ_binary_binary(model): assert len(model.layer) == 2, 'Only implemented for RBMs.' steps = len(schedule) input_layer = model.layer[0] hidden_layer = model.layer[1] edge = model.edge[0] w = edge.params['weight'] a = hidden_layer.params['bias'] b = input_layer.params['bias'] numvis, numhid = w.shape batchsize = 2**numvis input_layer.AllocateBatchsizeDependentMemory(batchsize) hidden_layer.AllocateBatchsizeDependentMemory(batchsize) all_inputs = GetAll(numvis) w_ais = cm.CUDAMatrix(np.zeros((1, batchsize))) input_layer.sample.overwrite(all_inputs) cm.dot(w.T, input_layer.sample, target=hidden_layer.state) hidden_layer.state.add_col_vec(a) cm.log_1_plus_exp(hidden_layer.state) w_ais.add_sums(hidden_layer.state, axis=0) w_ais.add_dot(b.T, input_layer.state) offset = float(w_ais.asarray().max()) w_ais.subtract(offset) cm.exp(w_ais) z = offset + np.log(w_ais.asarray().sum()) return z def Usage(): print '%s <model file> <number of Markov chains to run> [number of words (for Replicated Softmax models)]' if __name__ == '__main__': board = tr.LockGPU() model_file = sys.argv[1] numchains = int(sys.argv[2]) if len(sys.argv) > 3: D = int(sys.argv[3]) #10 # number of words. m = dbm.DBM(model_file) m.LoadModelOnGPU(batchsize=numchains) plt.ion() log_z = AISReplicatedSoftmax(m, D, numchains, display=True) print 'Log Z %.5f' % log_z #log_z = AIS(m, schedule) #print 'Log Z %.5f' % log_z #log_z = ExactZ_binary_binary(m) #print 'Exact %.5f' % log_z tr.FreeGPU(board) raw_input('Press Enter.')
bsd-3-clause
kevinyu98/spark
python/pyspark/testing/sqlutils.py
9
7813
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import datetime import os import shutil import tempfile from contextlib import contextmanager from pyspark.sql import SparkSession from pyspark.sql.types import ArrayType, DoubleType, UserDefinedType, Row from pyspark.testing.utils import ReusedPySparkTestCase from pyspark.util import _exception_message pandas_requirement_message = None try: from pyspark.sql.pandas.utils import require_minimum_pandas_version require_minimum_pandas_version() except ImportError as e: # If Pandas version requirement is not satisfied, skip related tests. pandas_requirement_message = _exception_message(e) pyarrow_requirement_message = None try: from pyspark.sql.pandas.utils import require_minimum_pyarrow_version require_minimum_pyarrow_version() except ImportError as e: # If Arrow version requirement is not satisfied, skip related tests. pyarrow_requirement_message = _exception_message(e) test_not_compiled_message = None try: from pyspark.sql.utils import require_test_compiled require_test_compiled() except Exception as e: test_not_compiled_message = _exception_message(e) have_pandas = pandas_requirement_message is None have_pyarrow = pyarrow_requirement_message is None test_compiled = test_not_compiled_message is None class UTCOffsetTimezone(datetime.tzinfo): """ Specifies timezone in UTC offset """ def __init__(self, offset=0): self.ZERO = datetime.timedelta(hours=offset) def utcoffset(self, dt): return self.ZERO def dst(self, dt): return self.ZERO class ExamplePointUDT(UserDefinedType): """ User-defined type (UDT) for ExamplePoint. """ @classmethod def sqlType(self): return ArrayType(DoubleType(), False) @classmethod def module(cls): return 'pyspark.sql.tests' @classmethod def scalaUDT(cls): return 'org.apache.spark.sql.test.ExamplePointUDT' def serialize(self, obj): return [obj.x, obj.y] def deserialize(self, datum): return ExamplePoint(datum[0], datum[1]) class ExamplePoint: """ An example class to demonstrate UDT in Scala, Java, and Python. """ __UDT__ = ExamplePointUDT() def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "ExamplePoint(%s,%s)" % (self.x, self.y) def __str__(self): return "(%s,%s)" % (self.x, self.y) def __eq__(self, other): return isinstance(other, self.__class__) and \ other.x == self.x and other.y == self.y class PythonOnlyUDT(UserDefinedType): """ User-defined type (UDT) for ExamplePoint. """ @classmethod def sqlType(self): return ArrayType(DoubleType(), False) @classmethod def module(cls): return '__main__' def serialize(self, obj): return [obj.x, obj.y] def deserialize(self, datum): return PythonOnlyPoint(datum[0], datum[1]) @staticmethod def foo(): pass @property def props(self): return {} class PythonOnlyPoint(ExamplePoint): """ An example class to demonstrate UDT in only Python """ __UDT__ = PythonOnlyUDT() class MyObject(object): def __init__(self, key, value): self.key = key self.value = value class SQLTestUtils(object): """ This util assumes the instance of this to have 'spark' attribute, having a spark session. It is usually used with 'ReusedSQLTestCase' class but can be used if you feel sure the the implementation of this class has 'spark' attribute. """ @contextmanager def sql_conf(self, pairs): """ A convenient context manager to test some configuration specific logic. This sets `value` to the configuration `key` and then restores it back when it exits. """ assert isinstance(pairs, dict), "pairs should be a dictionary." assert hasattr(self, "spark"), "it should have 'spark' attribute, having a spark session." keys = pairs.keys() new_values = pairs.values() old_values = [self.spark.conf.get(key, None) for key in keys] for key, new_value in zip(keys, new_values): self.spark.conf.set(key, new_value) try: yield finally: for key, old_value in zip(keys, old_values): if old_value is None: self.spark.conf.unset(key) else: self.spark.conf.set(key, old_value) @contextmanager def database(self, *databases): """ A convenient context manager to test with some specific databases. This drops the given databases if it exists and sets current database to "default" when it exits. """ assert hasattr(self, "spark"), "it should have 'spark' attribute, having a spark session." try: yield finally: for db in databases: self.spark.sql("DROP DATABASE IF EXISTS %s CASCADE" % db) self.spark.catalog.setCurrentDatabase("default") @contextmanager def table(self, *tables): """ A convenient context manager to test with some specific tables. This drops the given tables if it exists. """ assert hasattr(self, "spark"), "it should have 'spark' attribute, having a spark session." try: yield finally: for t in tables: self.spark.sql("DROP TABLE IF EXISTS %s" % t) @contextmanager def tempView(self, *views): """ A convenient context manager to test with some specific views. This drops the given views if it exists. """ assert hasattr(self, "spark"), "it should have 'spark' attribute, having a spark session." try: yield finally: for v in views: self.spark.catalog.dropTempView(v) @contextmanager def function(self, *functions): """ A convenient context manager to test with some specific functions. This drops the given functions if it exists. """ assert hasattr(self, "spark"), "it should have 'spark' attribute, having a spark session." try: yield finally: for f in functions: self.spark.sql("DROP FUNCTION IF EXISTS %s" % f) class ReusedSQLTestCase(ReusedPySparkTestCase, SQLTestUtils): @classmethod def setUpClass(cls): super(ReusedSQLTestCase, cls).setUpClass() cls.spark = SparkSession(cls.sc) cls.tempdir = tempfile.NamedTemporaryFile(delete=False) os.unlink(cls.tempdir.name) cls.testData = [Row(key=i, value=str(i)) for i in range(100)] cls.df = cls.spark.createDataFrame(cls.testData) @classmethod def tearDownClass(cls): super(ReusedSQLTestCase, cls).tearDownClass() cls.spark.stop() shutil.rmtree(cls.tempdir.name, ignore_errors=True)
apache-2.0
drewokane/seaborn
seaborn/timeseries.py
4
15212
"""Timeseries plotting functions.""" from __future__ import division import numpy as np import pandas as pd from scipy import stats, interpolate import matplotlib as mpl import matplotlib.pyplot as plt from .external.six import string_types from . import utils from . import algorithms as algo from .palettes import color_palette def tsplot(data, time=None, unit=None, condition=None, value=None, err_style="ci_band", ci=68, interpolate=True, color=None, estimator=np.mean, n_boot=5000, err_palette=None, err_kws=None, legend=True, ax=None, **kwargs): """Plot one or more timeseries with flexible representation of uncertainty. This function is intended to be used with data where observations are nested within sampling units that were measured at multiple timepoints. It can take data specified either as a long-form (tidy) DataFrame or as an ndarray with dimensions (unit, time) The interpretation of some of the other parameters changes depending on the type of object passed as data. Parameters ---------- data : DataFrame or ndarray Data for the plot. Should either be a "long form" dataframe or an array with dimensions (unit, time, condition). In both cases, the condition field/dimension is optional. The type of this argument determines the interpretation of the next few parameters. When using a DataFrame, the index has to be sequential. time : string or series-like Either the name of the field corresponding to time in the data DataFrame or x values for a plot when data is an array. If a Series, the name will be used to label the x axis. unit : string Field in the data DataFrame identifying the sampling unit (e.g. subject, neuron, etc.). The error representation will collapse over units at each time/condition observation. This has no role when data is an array. value : string Either the name of the field corresponding to the data values in the data DataFrame (i.e. the y coordinate) or a string that forms the y axis label when data is an array. condition : string or Series-like Either the name of the field identifying the condition an observation falls under in the data DataFrame, or a sequence of names with a length equal to the size of the third dimension of data. There will be a separate trace plotted for each condition. If condition is a Series with a name attribute, the name will form the title for the plot legend (unless legend is set to False). err_style : string or list of strings or None Names of ways to plot uncertainty across units from set of {ci_band, ci_bars, boot_traces, boot_kde, unit_traces, unit_points}. Can use one or more than one method. ci : float or list of floats in [0, 100] Confidence interval size(s). If a list, it will stack the error plots for each confidence interval. Only relevant for error styles with "ci" in the name. interpolate : boolean Whether to do a linear interpolation between each timepoint when plotting. The value of this parameter also determines the marker used for the main plot traces, unless marker is specified as a keyword argument. color : seaborn palette or matplotlib color name or dictionary Palette or color for the main plots and error representation (unless plotting by unit, which can be separately controlled with err_palette). If a dictionary, should map condition name to color spec. estimator : callable Function to determine central tendency and to pass to bootstrap must take an ``axis`` argument. n_boot : int Number of bootstrap iterations. err_palette : seaborn palette Palette name or list of colors used when plotting data for each unit. err_kws : dict, optional Keyword argument dictionary passed through to matplotlib function generating the error plot, legend : bool, optional If ``True`` and there is a ``condition`` variable, add a legend to the plot. ax : axis object, optional Plot in given axis; if None creates a new figure kwargs : Other keyword arguments are passed to main plot() call Returns ------- ax : matplotlib axis axis with plot data Examples -------- Plot a trace with translucent confidence bands: .. plot:: :context: close-figs >>> import numpy as np; np.random.seed(22) >>> import seaborn as sns; sns.set(color_codes=True) >>> x = np.linspace(0, 15, 31) >>> data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1) >>> ax = sns.tsplot(data=data) Plot a long-form dataframe with several conditions: .. plot:: :context: close-figs >>> gammas = sns.load_dataset("gammas") >>> ax = sns.tsplot(time="timepoint", value="BOLD signal", ... unit="subject", condition="ROI", ... data=gammas) Use error bars at the positions of the observations: .. plot:: :context: close-figs >>> ax = sns.tsplot(data=data, err_style="ci_bars", color="g") Don't interpolate between the observations: .. plot:: :context: close-figs >>> import matplotlib.pyplot as plt >>> ax = sns.tsplot(data=data, err_style="ci_bars", interpolate=False) Show multiple confidence bands: .. plot:: :context: close-figs >>> ax = sns.tsplot(data=data, ci=[68, 95], color="m") Use a different estimator: .. plot:: :context: close-figs >>> ax = sns.tsplot(data=data, estimator=np.median) Show each bootstrap resample: .. plot:: :context: close-figs >>> ax = sns.tsplot(data=data, err_style="boot_traces", n_boot=500) Show the trace from each sampling unit: .. plot:: :context: close-figs >>> ax = sns.tsplot(data=data, err_style="unit_traces") """ # Sort out default values for the parameters if ax is None: ax = plt.gca() if err_kws is None: err_kws = {} # Handle different types of input data if isinstance(data, pd.DataFrame): xlabel = time ylabel = value # Condition is optional if condition is None: condition = pd.Series(np.ones(len(data))) legend = False legend_name = None n_cond = 1 else: legend = True and legend legend_name = condition n_cond = len(data[condition].unique()) else: data = np.asarray(data) # Data can be a timecourse from a single unit or # several observations in one condition if data.ndim == 1: data = data[np.newaxis, :, np.newaxis] elif data.ndim == 2: data = data[:, :, np.newaxis] n_unit, n_time, n_cond = data.shape # Units are experimental observations. Maybe subjects, or neurons if unit is None: units = np.arange(n_unit) unit = "unit" units = np.repeat(units, n_time * n_cond) ylabel = None # Time forms the xaxis of the plot if time is None: times = np.arange(n_time) else: times = np.asarray(time) xlabel = None if hasattr(time, "name"): xlabel = time.name time = "time" times = np.tile(np.repeat(times, n_cond), n_unit) # Conditions split the timeseries plots if condition is None: conds = range(n_cond) legend = False if isinstance(color, dict): err = "Must have condition names if using color dict." raise ValueError(err) else: conds = np.asarray(condition) legend = True and legend if hasattr(condition, "name"): legend_name = condition.name else: legend_name = None condition = "cond" conds = np.tile(conds, n_unit * n_time) # Value forms the y value in the plot if value is None: ylabel = None else: ylabel = value value = "value" # Convert to long-form DataFrame data = pd.DataFrame(dict(value=data.ravel(), time=times, unit=units, cond=conds)) # Set up the err_style and ci arguments for the loop below if isinstance(err_style, string_types): err_style = [err_style] elif err_style is None: err_style = [] if not hasattr(ci, "__iter__"): ci = [ci] # Set up the color palette if color is None: current_palette = utils.get_color_cycle() if len(current_palette) < n_cond: colors = color_palette("husl", n_cond) else: colors = color_palette(n_colors=n_cond) elif isinstance(color, dict): colors = [color[c] for c in data[condition].unique()] else: try: colors = color_palette(color, n_cond) except ValueError: color = mpl.colors.colorConverter.to_rgb(color) colors = [color] * n_cond # Do a groupby with condition and plot each trace for c, (cond, df_c) in enumerate(data.groupby(condition, sort=False)): df_c = df_c.pivot(unit, time, value) x = df_c.columns.values.astype(np.float) # Bootstrap the data for confidence intervals boot_data = algo.bootstrap(df_c.values, n_boot=n_boot, axis=0, func=estimator) cis = [utils.ci(boot_data, v, axis=0) for v in ci] central_data = estimator(df_c.values, axis=0) # Get the color for this condition color = colors[c] # Use subroutines to plot the uncertainty for style in err_style: # Allow for null style (only plot central tendency) if style is None: continue # Grab the function from the global environment try: plot_func = globals()["_plot_%s" % style] except KeyError: raise ValueError("%s is not a valid err_style" % style) # Possibly set up to plot each observation in a different color if err_palette is not None and "unit" in style: orig_color = color color = color_palette(err_palette, len(df_c.values)) # Pass all parameters to the error plotter as keyword args plot_kwargs = dict(ax=ax, x=x, data=df_c.values, boot_data=boot_data, central_data=central_data, color=color, err_kws=err_kws) # Plot the error representation, possibly for multiple cis for ci_i in cis: plot_kwargs["ci"] = ci_i plot_func(**plot_kwargs) if err_palette is not None and "unit" in style: color = orig_color # Plot the central trace kwargs.setdefault("marker", "" if interpolate else "o") ls = kwargs.pop("ls", "-" if interpolate else "") kwargs.setdefault("linestyle", ls) label = cond if legend else "_nolegend_" ax.plot(x, central_data, color=color, label=label, **kwargs) # Pad the sides of the plot only when not interpolating ax.set_xlim(x.min(), x.max()) x_diff = x[1] - x[0] if not interpolate: ax.set_xlim(x.min() - x_diff, x.max() + x_diff) # Add the plot labels if xlabel is not None: ax.set_xlabel(xlabel) if ylabel is not None: ax.set_ylabel(ylabel) if legend: ax.legend(loc=0, title=legend_name) return ax # Subroutines for tsplot errorbar plotting # ---------------------------------------- def _plot_ci_band(ax, x, ci, color, err_kws, **kwargs): """Plot translucent error bands around the central tendancy.""" low, high = ci if "alpha" not in err_kws: err_kws["alpha"] = 0.2 ax.fill_between(x, low, high, facecolor=color, **err_kws) def _plot_ci_bars(ax, x, central_data, ci, color, err_kws, **kwargs): """Plot error bars at each data point.""" for x_i, y_i, (low, high) in zip(x, central_data, ci.T): ax.plot([x_i, x_i], [low, high], color=color, solid_capstyle="round", **err_kws) def _plot_boot_traces(ax, x, boot_data, color, err_kws, **kwargs): """Plot 250 traces from bootstrap.""" err_kws.setdefault("alpha", 0.25) err_kws.setdefault("linewidth", 0.25) if "lw" in err_kws: err_kws["linewidth"] = err_kws.pop("lw") ax.plot(x, boot_data.T, color=color, label="_nolegend_", **err_kws) def _plot_unit_traces(ax, x, data, ci, color, err_kws, **kwargs): """Plot a trace for each observation in the original data.""" if isinstance(color, list): if "alpha" not in err_kws: err_kws["alpha"] = .5 for i, obs in enumerate(data): ax.plot(x, obs, color=color[i], label="_nolegend_", **err_kws) else: if "alpha" not in err_kws: err_kws["alpha"] = .2 ax.plot(x, data.T, color=color, label="_nolegend_", **err_kws) def _plot_unit_points(ax, x, data, color, err_kws, **kwargs): """Plot each original data point discretely.""" if isinstance(color, list): for i, obs in enumerate(data): ax.plot(x, obs, "o", color=color[i], alpha=0.8, markersize=4, label="_nolegend_", **err_kws) else: ax.plot(x, data.T, "o", color=color, alpha=0.5, markersize=4, label="_nolegend_", **err_kws) def _plot_boot_kde(ax, x, boot_data, color, **kwargs): """Plot the kernal density estimate of the bootstrap distribution.""" kwargs.pop("data") _ts_kde(ax, x, boot_data, color, **kwargs) def _plot_unit_kde(ax, x, data, color, **kwargs): """Plot the kernal density estimate over the sample.""" _ts_kde(ax, x, data, color, **kwargs) def _ts_kde(ax, x, data, color, **kwargs): """Upsample over time and plot a KDE of the bootstrap distribution.""" kde_data = [] y_min, y_max = data.min(), data.max() y_vals = np.linspace(y_min, y_max, 100) upsampler = interpolate.interp1d(x, data) data_upsample = upsampler(np.linspace(x.min(), x.max(), 100)) for pt_data in data_upsample.T: pt_kde = stats.kde.gaussian_kde(pt_data) kde_data.append(pt_kde(y_vals)) kde_data = np.transpose(kde_data) rgb = mpl.colors.ColorConverter().to_rgb(color) img = np.zeros((kde_data.shape[0], kde_data.shape[1], 4)) img[:, :, :3] = rgb kde_data /= kde_data.max(axis=0) kde_data[kde_data > 1] = 1 img[:, :, 3] = kde_data ax.imshow(img, interpolation="spline16", zorder=2, extent=(x.min(), x.max(), y_min, y_max), aspect="auto", origin="lower")
bsd-3-clause
PrieureDeSion/intelligent-agents
sin(x) Neural Network/Neural Network.py
1
2675
''' Function Approximator This neural network uses Universal Approximator technique to predict the value of function in a closed domain. This works on the theorem that any function in a closed domain which is continuous or discontinuous at finitely many points can be approximated using piece-wise constant functions. It comprises of one hidden layer with variable number of neurons (default 50) ''' #from sys import argv import tensorflow as tf import numpy as np import tflearn import matplotlib.pyplot as plt #script , hid_dim = argv def univAprox(x, hidden_dim=50): input_dim = 1 output_dim = 1 with tf.variable_scope('UniversalApproximator'): ua_w = tf.get_variable( name='ua_w' , shape=[input_dim, hidden_dim] , initializer=tf.random_normal_initializer(stddev=.1) ) ua_b = tf.get_variable( name='ua_b' , shape=[hidden_dim] , initializer=tf.constant_initializer(0.) ) z = tf.matmul(x, ua_w) + ua_b a = tf.nn.relu(z) ua_v = tf.get_variable( name='ua_v' , shape=[hidden_dim, output_dim] , initializer=tf.random_normal_initializer(stddev=.1) ) z = tf.matmul(a, ua_v) return z def func_to_approx(x): return tf.sin(x) def main(): with tf.variable_scope('Graph') as scope: x = tf.placeholder(tf.float32, shape=[None, 1], name="x") y_true = func_to_approx(x) y = univAprox(x,500) with tf.variable_scope('Loss'): loss = tf.reduce_mean(tf.square(y - y_true)) loss_summary_t = tf.summary.scalar('loss', loss) adam = tf.train.AdamOptimizer(learning_rate=1e-2) train_op = adam.minimize(loss) #saver = tf.train.Saver() with tf.Session() as sess: print "Training our universal approximator" sess.run(tf.global_variables_initializer()) for i in range(1000): x_in = np.random.uniform(-10, 10, [100000, 1]) current_loss, loss_summary, _ = sess.run([loss, loss_summary_t, train_op], feed_dict={ x: x_in }) if (i+1) % 100 == 0 : print ('batch: %d, loss %f' % (i+1,current_loss)) saver_path = saver.save(sess , 'model.ckpt') print '\n' , "Plotting Graph" with tf.Session() as sess: saver.restore(sess, 'model.ckpt') print "Model Restored" x_p = np.array([[(i - 1000)/100] for i in range(2000)]) y_p = sess.run(y , feed_dict= {x:x_p}) plt.plot(x_p , y_p , 'k' ) plt.axis([-12 , 12 , -2 , 2]) plt.show() return if __name__ == '__main__': main()
gpl-3.0
saiwing-yeung/scikit-learn
examples/manifold/plot_mds.py
88
2731
""" ========================= Multi-dimensional scaling ========================= An illustration of the metric and non-metric MDS on generated noisy data. The reconstructed points using the metric MDS and non metric MDS are slightly shifted to avoid overlapping. """ # Author: Nelle Varoquaux <nelle.varoquaux@gmail.com> # License: BSD print(__doc__) import numpy as np from matplotlib import pyplot as plt from matplotlib.collections import LineCollection from sklearn import manifold from sklearn.metrics import euclidean_distances from sklearn.decomposition import PCA n_samples = 20 seed = np.random.RandomState(seed=3) X_true = seed.randint(0, 20, 2 * n_samples).astype(np.float) X_true = X_true.reshape((n_samples, 2)) # Center the data X_true -= X_true.mean() similarities = euclidean_distances(X_true) # Add noise to the similarities noise = np.random.rand(n_samples, n_samples) noise = noise + noise.T noise[np.arange(noise.shape[0]), np.arange(noise.shape[0])] = 0 similarities += noise mds = manifold.MDS(n_components=2, max_iter=3000, eps=1e-9, random_state=seed, dissimilarity="precomputed", n_jobs=1) pos = mds.fit(similarities).embedding_ nmds = manifold.MDS(n_components=2, metric=False, max_iter=3000, eps=1e-12, dissimilarity="precomputed", random_state=seed, n_jobs=1, n_init=1) npos = nmds.fit_transform(similarities, init=pos) # Rescale the data pos *= np.sqrt((X_true ** 2).sum()) / np.sqrt((pos ** 2).sum()) npos *= np.sqrt((X_true ** 2).sum()) / np.sqrt((npos ** 2).sum()) # Rotate the data clf = PCA(n_components=2) X_true = clf.fit_transform(X_true) pos = clf.fit_transform(pos) npos = clf.fit_transform(npos) fig = plt.figure(1) ax = plt.axes([0., 0., 1., 1.]) s = 100 plt.scatter(X_true[:, 0], X_true[:, 1], color='navy', s=s, lw=0, label='True Position') plt.scatter(pos[:, 0], pos[:, 1], color='turquoise', s=s, lw=0, label='MDS') plt.scatter(npos[:, 0], npos[:, 1], color='darkorange', s=s, lw=0, label='NMDS') plt.legend(scatterpoints=1, loc='best', shadow=False) similarities = similarities.max() / similarities * 100 similarities[np.isinf(similarities)] = 0 # Plot the edges start_idx, end_idx = np.where(pos) # a sequence of (*line0*, *line1*, *line2*), where:: # linen = (x0, y0), (x1, y1), ... (xm, ym) segments = [[X_true[i, :], X_true[j, :]] for i in range(len(pos)) for j in range(len(pos))] values = np.abs(similarities) lc = LineCollection(segments, zorder=0, cmap=plt.cm.Blues, norm=plt.Normalize(0, values.max())) lc.set_array(similarities.flatten()) lc.set_linewidths(0.5 * np.ones(len(segments))) ax.add_collection(lc) plt.show()
bsd-3-clause
QBI-Microscopy/omero-user-scripts
Image_Processing/ExtractROIs.py
1
31955
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Title: Extract ROIs from images Description: Extracts multiple polygon or rectangle ROIs from an image or set of images and creates individual images from them with associated links to parent image. __author__ Liz Cooper-Williams, QBI This script is based on components/tools/OmeroPy/scripts/omero/util_scripts/Images_From_ROIs.py Written by Will Moore &nbsp;&nbsp;&nbsp;&nbsp; <a href="mailto:will@lifesci.dundee.ac.uk">will@lifesci.dundee.ac.uk</a> ----------------------------------------------------------------------------- Copyright (C) 2006-2014 University of Dundee. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ------------------------------------------------------------------------------ This script gets all the Rectangles from a particular image, then creates new images with the regions within the ROIs, and saves them back to the server. """ import omero.model import omero.scripts as scripts from omero.gateway import BlitzGateway from omero.rtypes import rstring, rlong, robject import omero.util.script_utils as script_utils import omero.util.tiles from os import path import numpy as np #from scipy import misc #import matplotlib.pyplot as plt from matplotlib.path import Path import re import time startTime = 0 def printDuration(output=True): global startTime if startTime == 0: startTime = time.time() if output: print "Script timer = %s secs" % (time.time() - startTime) """ Get x and y coordinates of outline of shape Input: omero.model.shape Output: array of x coords and corresponding array of y coords """ def getPolygonPoints(shape): bbox = shape.getPoints() pattern = re.compile('\D*(\d+,\d+)*') m = pattern.findall(bbox.getValue()) xc = [] yc = [] for i in m: if i != '': mx = re.match('(\d+),(\d+)',i) xc.append(int(mx.group(1))) yc.append(int(mx.group(2))) else: break return xc,yc """ Get top left coords and dimensions of bounding box of shape Input : omero.model.shape Output: X,Y (top left coords), width (px) and height (px) """ def getBoundDimensions(shape): X = 0 Y = 0 width = 0 height = 0 # calculate bounding box dimensions from any shape if (type(shape) == omero.model.EllipseI): cx = int(shape.getCx().getValue()) #centre x cy = int(shape.getCy().getValue()) #centre y rx = int(shape.getRx().getValue()) #radius x ry = int(shape.getRy().getValue()) #radius y X = cx - rx Y = cy - ry width = 2 * rx height = 2 * ry elif type(shape) == omero.model.PolygonI: #SmartPolygonI sp = omero.model.SmartPolygonI(shape) #sp.asPoints() - bounding box #sp.areaPoints() - all xy points #regex: http://pythex.org/ xc,yc = getPolygonPoints(shape) X = min(xc) Y = min(yc) width = max(xc) - min(xc) height = max(yc) - min(yc) return X, Y, width, height """ Get a mask for the shape (ellipse or polygon) Input: omero.model.shape, omero.image Output: mask of same dimensions as original image - crop as required """ def getPolygonMask(shape, img): x = [] y = [] if (type(shape) == omero.model.EllipseI): cx = int(shape.getCx().getValue()) #centre x cy = int(shape.getCy().getValue()) #centre y rx = int(shape.getRx().getValue()) #radius x ry = int(shape.getRy().getValue()) #radius y # vertices of the ellipse #x = [cx-rx, cx, cx+rx, cx, cx-rx] #y = [cy, cy-ry, cy, cy+ry, cy] t = np.linspace(-np.pi,np.pi,100) x = cx + rx * np.cos(t) y = cy + ry * np.sin(t) elif type(shape) == omero.model.PolygonI: # vertices of the polygon x,y = getPolygonPoints(shape) xc = np.array(x) yc = np.array(y) xycrop = np.vstack((xc, yc)).T # xy coordinates for each pixel in the image #nr = img.getPrimaryPixels().getSizeY() #nc = img.getPrimaryPixels().getSizeX() nr = img.getSizeY() nc = img.getSizeX() #nr = img.getPrimaryPixels().getPhysicalSizeY().getValue() #nc = img.getPrimaryPixels().getPhysicalSizeX().getValue() print "Mask nr=", nr, " nc=", nc if (int(nr) + int(nc) >= 100000): print "Cannot create mask of this size: %d x %d " % (nr,nc) mask = None else: #plane = img.getPrimaryPixels().getPlane(0,0,0) #nr, nc = plane.shape ygrid, xgrid = np.mgrid[:nr, :nc] xypix = np.vstack((xgrid.ravel(), ygrid.ravel())).T # construct a Path from the vertices pth = Path(xycrop, closed=False) # test which pixels fall within the path mask = pth.contains_points(xypix) # reshape to the same size as the image #mask = mask.reshape(plane.shape) mask = mask.reshape((img.getPrimaryPixels().getSizeY(),img.getPrimaryPixels().getSizeX())) mask = ~mask return mask """ Create a mask from ROI shape to match current tile """ def getOffsetPolyMaskTile(shape, pos_x, pos_y, tW, tH): x = [] y = [] if (type(shape) == omero.model.EllipseI): cx = int(shape.getCx().getValue()) #centre x cy = int(shape.getCy().getValue()) #centre y rx = int(shape.getRx().getValue()) #radius x ry = int(shape.getRy().getValue()) #radius y # vertices of the ellipse #x = [cx-rx, cx, cx+rx, cx, cx-rx] #y = [cy, cy-ry, cy, cy+ry, cy] t = np.linspace(-np.pi,np.pi,100) x = cx + rx * np.cos(t) y = cy + ry * np.sin(t) elif type(shape) == omero.model.PolygonI: # vertices of the polygon x,y = getPolygonPoints(shape) xv = np.array(x) yv = np.array(y) #List of poly coords xycrop = np.vstack((xv, yv)).T # Get region of image xt = range(pos_x, pos_x + tW) yt = range(pos_y, pos_y + tH) xtile, ytile = np.meshgrid(xt, yt, sparse=False, indexing='xy') xypix = np.vstack((xtile.ravel(), ytile.ravel())).T pth = Path(xycrop, closed=False) mask = pth.contains_points(xypix) mask = mask.reshape(tH, tW) return ~mask def hasPoints(shape): rtn = False if (type(shape) == omero.model.EllipseI): if shape.getRx().getValue() > 0: rtn = True elif type(shape) == omero.model.RectangleI: if shape.getWidth().getValue() > 0: rtn = True elif type(shape) == omero.model.PolygonI: pts = getPolygonPoints(shape) #print "Shape getPoints:", pts[0] if len(pts[0]) > 2: rtn = True if (not rtn): print "Skipping ROI as it is empty:" , shape.getId().getValue() return rtn """ getShapes Input: active connection, image id Output: Returns a structure containing flexible shape variables eg shape['width'] including a list of bounding box dimensions (x, y, width, height, zStart, zStop, tStart, tStop) as shape['bbox'] for each ROI shape in the imag """ def getShapes(conn, imageId, image): rois = [] #image = conn.getObject("Image", imageId) roiService = conn.getRoiService() result = roiService.findByImage(imageId, None) for roi in result.rois: print "ROI: ID:", roi.getId().getValue() zStart = None zEnd = 0 tStart = None tEnd = 0 x = None for i,s in enumerate(roi.copyShapes()): #omero.model #ignore empty ROIs if (not hasPoints(s)): continue shape = {} shape['id'] = int(s.getId().getValue()) shape['theT'] = int(s.getTheT().getValue()) shape['theZ'] = int(s.getTheZ().getValue()) # Determine 4D data for tiling if tStart is None: tStart = shape['theT'] if zStart is None: zStart = shape['theZ'] tStart = min(shape['theT'], tStart) tEnd = max(shape['theT'], tEnd) zStart = min(shape['theZ'], zStart) zEnd = max(shape['theZ'], zEnd) # Use label for new image filename if s.getTextValue(): shape['ROIlabel'] = s.getTextValue().getValue() else: shape['ROIlabel'] = 'ROI_' + str(shape['id']) # Masks used to clear pixels outside shape shape['shape'] = s shape['maskroi'] = None if type(s) == omero.model.RectangleI: print "Found Rectangle: " + shape['ROIlabel'] # check t range and z range for every rectangle shape['type'] = 'Rectangle' # Get region bbox x = int(s.getX().getValue()) y = int(s.getY().getValue()) width = int(s.getWidth().getValue()) height = int(s.getHeight().getValue()) shape['bbox'] = (x, y, width, height, zStart, zEnd, tStart, tEnd) shape['x'] = x shape['y'] = y shape['width'] = width shape['height'] = height elif type(s) == omero.model.EllipseI: print "Found Ellipse: " + shape['ROIlabel'] #Get bounding box dimensions x, y, width, height = getBoundDimensions(s) shape['bbox'] = (x, y, width, height, zStart, zEnd, tStart, tEnd) shape['type'] = 'Ellipse' shape['cx'] = s.getCx().getValue() shape['cy'] = s.getCy().getValue() shape['rx'] = s.getRx().getValue() shape['ry'] = s.getRy().getValue() #Create mask - reverse axes for numpy #mask = getPolygonMask(s, image) #maskroi= mask[y:height+y,x:width+x] shape['maskroi'] = 1 elif type(s) == omero.model.PolygonI: x, y, width, height = getBoundDimensions(s) shape['bbox'] = (x, y, width, height, zStart, zEnd, tStart, tEnd) shape['maskroi'] = 1 shape['type'] = 'Polygon' else: print type(s), " Not supported by this script" shape={} if (shape): rois.append(shape) print "ROIS loaded:", len(rois) return rois """ Process an image. Creates a 5D image representing the ROI "cropping" the original image via a Mask Image is put in a dataset if specified. """ def processImage(conn, image, parameterMap, datasetid=None): bgcolor = parameterMap['Background_Color'] tagname = parameterMap['Use_ROI_label'] imageId = image.getId() # Extract ROI shapes from image rois = getShapes(conn, imageId, image) iIds = [] firstimage = None datasetdescription = "" roilimit = conn.getRoiLimitSetting() print "ROI limit = ", roilimit if len(rois) > 0: #Constants maxw = conn.getMaxPlaneSize()[0] - 100 print "Max plane size = ", maxw omeroToNumpy = {'int8': 'int8', 'uint8': 'uint8', 'int16': 'int16', 'uint16': 'uint16', 'int32': 'int32', 'uint32': 'uint32', 'float': 'float32', 'double': 'double'} #Check size of parent image - LIMIT:? imgW = image.getSizeX() imgH = image.getSizeY() print "ID: %s \nImage size: %d x %d " % (imageId, imgW, imgH) imageName = image.getName() updateService = conn.getUpdateService() pixelsService = conn.getPixelsService() queryService = conn.getQueryService() renderService = conn.getRenderingSettingsService() # rawPixelsStore = conn.c.sf.createRawPixelsStore() # containerService = conn.getContainerService() print "Connection: Got services..." pixels = image.getPrimaryPixels() # Check image data type imgPtype = pixels.getPixelsType().getValue() # omero::model::PixelsType pixelsType = queryService.findByQuery( "from PixelsType as p where p.value='%s'" % imgPtype, None) if pixelsType is None: raise Exception( "Cannot create an image in OMERO from numpy array " "with dtype: %s" % imgPtype) # uint8 = [0,255], uint16 = [0,65535], [-32767,32768] for int16 whites = {'uint8':255, 'int8':255, 'uint16': 65535, 'int16': 32768} # tile_max = whites[imgPtype] # tile_min = 0.0 if (bgcolor == 'White'): if (imgPtype in whites): bgcolor = whites[imgPtype] else: bgcolor = 255 #default # elif(bgcolor == 'MaxColor'): # bgcolor = tile_max # elif(bgcolor == 'MinColor'): # bgcolor = tile_min else: bgcolor = 0.0 # Process ROIs for r in rois: x, y, w, h, z1, z2, t1, t2 = r['bbox'] print " ROI x: %s y: %s w: %s h: %s z1: %s z2: %s t1: %s t2: %s"\ % (x, y, w, h, z1, z2, t1, t2) # need a tile generator to get all the planes within the ROI sizeZ = z2-z1 + 1 sizeT = t2-t1 + 1 sizeC = image.getSizeC() zctTileList = [] tile = (x, y, w, h) # Generate mask for ROI maskroi = r['maskroi'] mask = None shape = r['shape'] #else: # polycoords = getPolygonPoints(shape) # LARGE FILES create tiles within max px limits - even tiles tilefactor = int(w/maxw) tileWidth = w / (tilefactor + 1) tilefactor = int(h/maxw) tileHeight = h / (tilefactor + 1) tileTotal = w/tileWidth * h/tileHeight print "Tilewidth=", tileWidth, " Tileheight=", tileHeight , " Tilecount=", tileTotal tiles = [] maskList = [] if (tileTotal > 1): print "Generating %d subtiles ..." % tileTotal for i, pos_y in enumerate(range(y, y + h, tileHeight)): tH = min(h - (tileHeight * i), tileHeight) for j, pos_x in enumerate(range(x, x + w, tileWidth)): tW = min(w - (tileWidth * j), tileWidth) area = (pos_x, pos_y, tW, tH) tiles.append(area) if(maskroi is not None): masktile = getOffsetPolyMaskTile(shape, pos_x, pos_y, tW, tH) maskList.append(masktile) # m1 = mask # masktile = m1[pos_y:tH + pos_y, pos_x:tW + pos_x] # maskList.append(masktile) else: tiles.append(tile) if (maskroi is not None): mask = getPolygonMask(shape, image) #whole image if (mask is not None): maskroi= mask[y:h+y,x:w+x] #cropped to ROI print "generating zctTileList..." for z in range(z1, z2 + 1): for c in range(sizeC): for t in range(t1, t2 + 1): for tile in tiles: zctTileList.append((z, c, t, tile)) #Generators def tileGen(mask=None): for i, t in enumerate(pixels.getTiles(zctTileList)): if(mask is not None): #print(t.shape) t[mask]=bgcolor #plt.imshow(t) #plt.show() yield t def getImageTile(tileCount): print "tileCount=", tileCount p1 = tileList[tileCount] p = np.zeros(p1.shape, dtype=convertToType) p += p1 if(len(maskList) > 0 and tileCount <= len(maskList) * len(channelList)): maski = tileCount % len(maskList) print "mask idx:", maski m1 = maskList[maski] print "mask:", m1.shape p[m1] = bgcolor # return p.tobytes() # numpy 1.9 + return p.min(),p.max(),p.tostring() # numpy 1.8- # Set image name for new image (imageName,ext) = path.splitext(image.getName()) if (tagname and len(r['ROIlabel']) > 0): imageName = imageName + '_'+ r['ROIlabel'] # + ext else: roid = r['id'] imageName = imageName + '_'+ str(roid) # + ext #DONT CREATE TAGS tagname = None # Add a description for the image description = "Created from image:\n Name: %s\n ROIimage: %s\n Image ID: %d"\ " \n x: %d y: %d" % (image.getName(), imageName, imageId, x, y) print description # Due to string limit with BlitzGateway - subtile image # Currently this is VERY slow - needs to improve if (tileTotal > 1): channelList = range(sizeC) #Create empty image then populate pixels iId = pixelsService.createImage( w, h, sizeZ, sizeT, channelList, pixelsType, imageName, description, conn.SERVICE_OPTS) print "Empty Image created with %d x %d" % (w,h) newImg = conn.getObject("Image", iId) pid = newImg.getPixelsId() print "New Image pid: ", pid # rawPixelsStore.setPixelsId(pid, True, conn.SERVICE_OPTS) #print "New Image Id = %s" % newImg.getId() convertToType = getattr(np, omeroToNumpy[imgPtype]) print "type=", convertToType #Run once - list of generators tileList = list(pixels.getTiles(zctTileList)) print "Size of tilelist=", len(tileList) print "Size of masklist=", len(maskList) channelsMinMax = [] class Iteration(omero.util.tiles.TileLoopIteration): def run(self, data, z, c, t, x, y, tileWidth, tileHeight, tileCount): # dimensions re new empty image same as ROI print "Iteration:z=", z, " c=", c, " t=", t, " x=", x,\ " y=", y, " w=", tileWidth, " h=", tileHeight, \ " tcnt=", tileCount #Get pixel data from image to load into these coords minValue,maxValue,tile2d = getImageTile(tileCount) # first plane of each channel if len(channelsMinMax) < (c + 1): channelsMinMax.append([minValue, maxValue]) else: channelsMinMax[c][0] = min( channelsMinMax[c][0], minValue) channelsMinMax[c][1] = max( channelsMinMax[c][1], maxValue) print "generated tile2d ...setting data" data.setTile(tile2d, z, c, t, x, y, tileWidth, tileHeight) #Replace pixels in empty image which is same size as ROI print "Generating new image from RPSTileLoop" loop = omero.util.tiles.RPSTileLoop(conn.c.sf, omero.model.PixelsI(pid, False)) times = loop.forEachTile(tileWidth, tileHeight, Iteration()) print times, " loops" for theC, mm in enumerate(channelsMinMax): pixelsService.setChannelGlobalMinMax( pid, theC, float(mm[0]), float(mm[1]), conn.SERVICE_OPTS) else: # Use this method for smaller images/tiles print "Generating new image from NumpySeq" newImg = conn.createImageFromNumpySeq( tileGen(maskroi), imageName, sizeZ=sizeZ, sizeC=sizeC, sizeT=sizeT, sourceImageId=imageId, description=rstring(description), dataset=None) if newImg is not None: print "New Image Id = %s" % newImg.getId() if (tagname): tagAnn = omero.gateway.TagAnnotationWrapper(conn) tagAnn.setValue(str(r['ROIlabel'])) tagAnn.save() newImg.linkAnnotation(tagAnn) # Link to dataset if (datasetid is None): print "Dataset id is not set - getting parent" datasetid = image.getParent().getId() link = omero.model.DatasetImageLinkI() link.parent = omero.model.DatasetI(datasetid, False) link.child = omero.model.ImageI(newImg.getId(), False) link = updateService.saveAndReturnObject(link) if (link is not None): print "New image linked to dataset" else: print "ERROR: New image dataset link failed: now its an orphan" # for return - just one if firstimage is None: firstimage = newImg._obj print "Setting first image" #BUG IN createImageFromNumpy doesn't save description - try again here - OK if (len(newImg.getDescription()) <=0): newImg = conn.getObject("Image", newImg.getId()) newImg.setDescription(description) updateService.saveObject(newImg._obj,conn.SERVICE_OPTS) #NB don't use return function iIds.append(newImg.getId()) # Apply rnd settings of the source image to new images. #Class parameter for changing settings must be in {Project, Dataset, Image, Plate, Screen, PlateAcquisition, Pixels}, not class ome.model.display.Thumbnail print "Applying rendering settings" renderService.applySettingsToSet(image.getId(), 'Image', iIds) else: print "ERROR: No new images created from Image ID %d." % image.getId() return firstimage, datasetdescription, iIds def makeImagesFromRois(conn, parameterMap): """ Processes the list of Image_IDs, either making a new dataset for new images or adding to the parent dataset, with new images extracted from (optionally labelled) ROIs on the parent images. """ dataType = parameterMap["Data_Type"] message = "" # Get the images to process objects, logMessage = script_utils.getObjects(conn, parameterMap) message += logMessage if not objects: return None, message # Either images or datasets if dataType == 'Image': images = objects else: images = [] for ds in objects: images += ds.listChildren() imageIds = [i.getId() for i in images] #imageIds = [i.getId() for i in images if (i.getROICount() > 0)] print "Selected %d images for processing" % len(imageIds) #Generate dataset to add images to updateService = conn.getUpdateService() roiService = conn.getRoiService() datasetName = parameterMap['Container_Name'] datasetid = None link = None dataset = None datasetdescription = "Images in this Dataset are generated by script: ExtractROIs\n" if (len(datasetName) > 0): #Assume all new images to be linked here dataset = omero.model.DatasetI() dataset.name = rstring(datasetName) # TODO update description after adding images in case no ROIS found for img in images: result = roiService.findByImage(img.getId(), None) if (len(result.rois) > 0): datasetdescription += "\nImages in this Dataset are from ROIs of parent Image:\n"\ " Name: %s\n Image ID: %d" % (img.getName(), img.getId()) dataset.description = rstring(datasetdescription) dataset = updateService.saveAndReturnObject(dataset) datasetid = dataset.getId() #Link this to parent project parentDataset = images[0].getParent() if parentDataset and parentDataset.canLink(): print "Linking to parent project" project = parentDataset.getParent() link = omero.model.ProjectDatasetLinkI() link.setParent(omero.model.ProjectI(project.getId(), False)) link.setChild(dataset) updateService.saveObject(link) print "Dataset created: %s Id: %s" % (datasetName, int(datasetid.getValue())) newImages = [] #ids of new images #newDatasets = [] notfound = [] for iId in imageIds: image = conn.getObject("Image", iId) if image is None: notfound.append(str(iId)) next firstimg, desc, imageIds = processImage(conn, image, parameterMap, datasetid) if firstimg is not None: newImages.extend(imageIds) datasetdescription += "\nDataset:\n" datasetdescription += desc print desc #newDatasets.append(datasetname) message += "Created %d new images" % len(newImages) if (datasetid is None): message += " in parent dataset" elif len(newImages) == 0: #remove empty dataset h = conn.deleteObjects("Dataset", [datasetid], deleteAnns=True, deleteChildren=False) message += " no images so removing dataset" else: message += " in new dataset %s" % datasetName if link is None: message += " - unable to link to parent project: look in orphaned" if (len(notfound) > 0): message += " - ids not found: %s" % notfound message += "." robj = (len(newImages) > 0) and firstimg or None return robj,message def runAsScript(): """ The main entry point of the script, as called by the client via the scripting service, passing the required parameters. """ printDuration(False) # start timer dataTypes = [rstring('Dataset'), rstring('Image')] #bgTypes = [rstring("Black"),rstring("White"),rstring("MaxColor"),rstring("MinColor")] bgTypes = [rstring("Black"),rstring("White")] client = scripts.client( 'Extract ROIs for all Images', """Extract Images from the regions defined by ROIs. \ Updated script: 29 Feb 2016 Accepts: Rectangle, Ellipse, Polygon Shapes Supports: All image sizes including large images \ >12000 x 12000 px Outputs: Multiple ROIs produced as separate images with option to use \ ROI labels in filenames and tags Replaces: Images from ROIs scripts (also Advanced) Note: Resulting Large Images can be exported via QBI->Utils->ExportImage """, scripts.String( "Data_Type", optional=False, grouping="1", description="Select a 'Dataset' of images or specific images with these IDs", values=dataTypes, default="Image"), scripts.List( "IDs", optional=False, grouping="2", description="List of Dataset IDs or Image IDs to " " process.").ofType(rlong(0)), scripts.String( "Container_Name", grouping="3", description="Put Images in new Dataset with this name", default="ExtractedROIs"), scripts.Bool( "Use_ROI_label", grouping="4", default=False, description="Use ROI labels in filename and as tag"), scripts.Bool( "Clear_Outside_Polygon", grouping="5", default=False, description="Clear area outside of polygon ROI (default is black)"), scripts.String( "Background_Color", grouping="5.1", default="Black", description="Background fill colour", values=bgTypes), version="1.0", authors=["Liz Cooper-Williams", "QBI Software"], institutions=["Queensland Brain Institute", "The University of Queensland"], contact="e.cooperwilliams@uq.edu.au", ) try: # Params from client parameterMap = client.getInputs(unwrap=True) print parameterMap # create a wrapper so we can use the Blitz Gateway. conn = BlitzGateway(client_obj=client) robj, message = makeImagesFromRois(conn, parameterMap) client.setOutput("Message", rstring(message)) if robj is not None: client.setOutput("Result", robject(robj)) finally: client.closeSession() printDuration() def runAsTest(): """ Test script locally with preset id. """ #connect to OMERO server user = 'root' pw = 'omero' host = 'localhost' conn = BlitzGateway(user, pw, host=host, port=4064) connected = conn.connect() # Check if you are connected. # ============================================================= if not connected: import sys print "Error: Connection not available, check VM is running.\n" sys.exit(1) else: print "Succesfully Connected to ", host printDuration(False) # start timer parameterMap ={'Data_Type' :'Image', 'IDs': [632], 'Container_Name': 'ROIs', 'Clear_Outside_Polygon': True, 'Background_Color': 'White' , 'Use_ROI_label': True, } try: # Params from client #parameterMap = client.getInputs(unwrap=True) print parameterMap # create a wrapper so we can use the Blitz Gateway. #conn = BlitzGateway(client_obj=client) robj, message = makeImagesFromRois(conn, parameterMap) print message if robj is not None: #print robject(robj) print "Robj is OK" finally: conn._closeSession() printDuration() if __name__ == "__main__": runAsScript() #runAsTest()
gpl-2.0
JoostHuizinga/ea-plotting-scripts
createPlots.py
1
77159
#!/usr/bin/env python3 import matplotlib import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib.patches import Polygon import os import sys import io import copy import argparse as ap from createPlotUtils import * __author__ = "Joost Huizinga" __version__ = "1.7 (Dec. 19 2019)" initOptions("Script for creating line-plots.", "[input_directories [input_directories ...]] [OPTIONS]", __version__) # Constants MAX_GEN_NOT_PROVIDED = -1 NO_LINE = 0 LINE_WIDTH = 2 FILL_ALPHA = 0.5 # Global variables # At some point we may want to create an object to hold all global plot settings # (or a local object that is passed to all relevant functions) # but for now this dictionary is all we need. extra_artists = {} # Derived defaults def def_output_dir(): if getExists("config_file"): return base(getStr("config_file")) + "_out" else: number = 1 name = "my_plot_" + str(number) while os.path.exists(name): number += 1 name = "my_plot_" + str(number) return name def def_comp_cache(): return base(getStr("config_file")) + ".cache" def def_box_height(): return max((len(getList("input_directories"))-1)*0.35, 0.5) def def_marker_step(): if getInt("max_generation") > 5: return getInt("max_generation")/5 else: return None def def_marker_offset(): marker_step = get("marker_step") if hasattr(marker_step, '__call__'): marker_step = marker_step() if isinstance(marker_step, list): marker_step = int(marker_step[0]) if marker_step == 0 or marker_step is None: marker_step = 1 num_treatments = len(getList("input_directories")) + len(getList("file")) if num_treatments < 1: num_treatments = 1 step = marker_step/num_treatments if step < 1: step = 1 return list(range(0, marker_step, int(step))) def def_legend_font_size(): return getInt("font_size")-4 def def_title_font_size(): return getInt("font_size")+4 def def_tick_font_size(): return getInt("font_size")-6 def def_sig_marker(): return getList("marker") def def_treatment_names(): if len(getList("input_directories")) > 0: return [os.path.basename(x) for x in getList("input_directories")] else: return [os.path.basename(x) for x in getList("file")] def def_treatment_names_short(): return getList("treatment_names") def def_bg_color(color): byte = "" new_color = "#" for char in color: if char == '#': continue byte += char if len(byte) == 2: byte_as_int = int(byte, 16) new_value = min(byte_as_int+128, 255) new_value_as_string = "%x" % new_value new_color += new_value_as_string byte = "" return new_color def def_background_colors(): return [def_bg_color(color) for color in getList("colors")] #Directory settings addOption("templates", ".*", help="Directories to traverse to find files to plot. " "Accepts regular expressions.") addOption("pool", help="Pool the results in this directory together by taking the " "maximum. Accepts regular expressions.") addOption("output_directory", def_output_dir, nargs=1, help="Resulting plots will be put into this directory.") #General plot settings addOption("max_generation", MAX_GEN_NOT_PROVIDED, nargs=1, help="The maximum number of generations to plot." "If not provided, the maximum will be determined from the data.") addOption("step", 1, nargs=1, help="Step-size with which to plot the data.") addOption("stat_test_step", 1, nargs=1, help="Step-size at which to perform statistical comparisons between " "treatments.") addOption("marker_step", def_marker_step, nargs=1, help="Step-size at which to place treatment markers.") addOption("bootstrap", False, nargs=1, help="If true, the shaded area will be based on bootstrapped " "confidence intervals. Otherwise the shaded area represents the " "inter-quartile range.") addOption("stats", "median_and_interquartile_range", nargs=1, help="The type of statistics to plot in format [central]_and_[ci]." "Central options: mean, median. CI options: interquartile_range, " "std_error, bootstrap_percentile, bootstrap_pivotal, bootstrap_bca, " "bootstrap_pi, bootstrap_abc. Percentile and takes the " "percentile of the sampled data (biased). Pivotal also subtracts " "difference between the sampled and the original distribution " "(unbiased, but may be wrong for certain distributions). Pi is " "the scikits implementation of the percentile method. Bca is a " "faster, bias-correct bootstrap method. Abc is a parametric method " "meaning its faster, but it requires a smooth function to be " "available.") addOption("smoothing", 1, nargs=1, help="Applies a median window of the provided size to smooth the " "line plot.") addOption("box_margin_before", 0, nargs=1, aliases=["box_sep"], help="Space before the significance indicator boxes, " "separating them from the main plot..") addOption("box_margin_between", 0, nargs=1, help="Space between the significance indicator boxes.") addOption("fig_size", [8, 6], nargs=2, help="The size of the resulting figure.") addOption("separator", " ", nargs=1, help="The separator used for the input data.") addOption("marker_size", 18, nargs=1, help="The size of the treatment markers.") addOption("x_from_file", False, nargs=1, help="If true, x-values will be read from file, rather than assumed " "to be from 0 to the number of data-points.") addOption("x_column", 0, nargs=1, help="If x_from_file is true, this parameter determines which colomn " "contains the x data.") addOption("x_values", help="Use the provided values for the x-axis.") addOption("x_ticks", help="Use the provided strings as labels for the x-ticks.") addOption("one_value_per_dir", False, nargs=1, help="If true, assumes that every file found holds a single value, " "to be plotted sequentially.") addOption("type", "pdf", nargs=1, help="The file type in which the plot will be written.") addOption("bb", "tight", nargs=1, help="How the bounding box of the image is determined. Options are " "default (keep aspect ratio and white space), " "tight (sacrifice aspect ratio to prune white space), " "manual (specify the bounding box yourself)," "and custom (keep aspect ratio but prune some white space).") addOption("bb_width", nargs=1, help="The width of the bounding box, in inches.") addOption("bb_height", nargs=1, help="The height of the bounding box, in inches.") addOption("bb_x_offset", 0, nargs=1, help="The x offset of the bounding box, in inches.") addOption("bb_y_offset", 0, nargs=1, help="The y offset of the bounding box, in inches.") addOption("bb_x_center_includes_labels", True, nargs=1, help="If True, take the figure labels into account when horizontally " "centering the bounding box. If false, ignore the labels when " "horizontally centering.") addOption("bb_y_center_includes_labels", True, nargs=1, help="If True, take the figure labels into account when vertically " "centering the bounding box. If false, ignore the labels when " "vertically centering.") # General inset settings addOption('inset_stats', '', nargs=1, help="Which statistic to plot in the inset. " "See the stats option for legal arguments.") addOption('inset_x', 0.5, nargs=1, help="The x-coordinate of the left side of the inset in figure " "coordinates.") addOption('inset_y', 0.5, nargs=1, help="The y-coordinate of the bottom side of the inset in figure " "coordinates.") addOption('inset_w', 0.47, nargs=1, help="The width of the inset.") addOption('inset_h', 0.47, nargs=1, help="The height of the inset.") addOption('inset_area_x1', 0, nargs=1, help="The smallest x-value for the data covered in the inset " "(in data coordinates).") addOption('inset_area_x2', 1, nargs=1, help="The largest x-value for the data covered in the inset " "(in data coordinates).") addOption('inset_area_y1', 0, nargs=1, help="The smallest y-value for the data covered in the inset " "(in data coordinates).") addOption('inset_area_y2', 1, nargs=1, help="The largest y-value for the data covered in the inset " "(in data coordinates).") addOption('inset_labels', 'none', nargs=1, help="Which tick-labels to show. Current options are 'all' and " "'none'.") addOption('inset_ticks', 'none', nargs=1, help="Which ticks to show. Current options are 'all' and 'none'.") addOption('inset_lines_visible', 'all', nargs=1, help="Which lines to show for indicating the inset area. " "Current options are 'all' and 'none'.") # General significance bar settings addOption("comparison_offset_x", 0, nargs=1, aliases=["sig_lbl_x_offset"], help="Allows moving the label next the significance indicator box.") addOption("comparison_offset_y", 0, nargs=1, aliases=["sig_lbl_y_offset"], help="Allows moving the label next the significance indicator box.") addOption("sig_header_show", False, nargs=1, help="Whether there should be a header for the significance indicator box.") addOption("sig_header_x_offset", 0, nargs=1, help="Allows moving the header next the significance indicator box.") addOption("sig_header_y_offset", 0, nargs=1, help="Allows moving the header next the significance indicator box.") addOption("sig_label", "p<0.05 vs ", nargs=1, aliases=["sig_lbl", "sig_header"], help="Label next to the significance indicator box.") addOption("sig_lbl_add_treat_name", True, nargs=1, help="Whether to add the short name of the main treatment as part " "of the label next to the significance indicator box.") addOption("sig_treat_lbls_x_offset", 0.005, nargs=1, help="Allows moving the treatment labels next to the " "significance indicator box horizontally.") addOption("sig_treat_lbls_y_offset", 0, nargs=1, help="Allows moving the treatment labels next to the " "significance indicator box vertically.") addOption("sig_treat_lbls_rotate", 0, nargs=1, help="Allows rotating the treatment labels next to the " "significance indicator box.") addOption("sig_treat_lbls_symbols", False, nargs=1, help="Plot symbols instead of names for the treatment labels next to " "the significance indicator box.") addOption("sig_treat_lbls_align", "bottom", nargs=1, help="Alignment for the treatment labels next to the significance " "indicator box. Possible values are: 'top', 'bottom', and 'center'.") addOption("sig_treat_lbls_show", True, nargs=1, help="Whether to show the treatment labels next to the significance " "indicator box.") addOption("p_threshold", 0.05, nargs=1, help="P threshold for the significance indicators.") # Per comparison settings addOption("comparison_main", 0, aliases=["main_treatment"], help="Statistical comparisons are performed against this treatment.") addOption("comparison_others", "", help="Statistical comparisons are performed against this treatment.") addOption("comparison_height", def_box_height, aliases=["box_height"], help="The height of the box showing significance indicators.") # Font settings addOption("font_size", 18, nargs=1, help="The base font-size for the plot " "(other font-sizes are relative to this one).") addOption("title_size", def_title_font_size, nargs=1, aliases=["title_font_size"], help="Font size for the titel.") addOption("legend_font_size", def_legend_font_size, nargs=1, help="Font size for the legend.") addOption("tick_font_size", def_tick_font_size, nargs=1, help="Font size for the tick-labels.") addOption("sig_treat_lbls_font_size", def_tick_font_size, nargs=1, help="Font size for the treatment labels next to " "the significance indicator box.") addOption("sig_header_font_size", def_tick_font_size, nargs=1, help="Font size for the header next to the " "the significance indicator box.") # Misc settings addOption("sig", True, nargs=1, help="Show the significance bar underneath the plot.") addOption("title", True, nargs=1, help="Show the title of the plot.") addOption("legend_columns", 1, nargs=1, help="Number of columns for the legend.") addOption("legend_x_offset", 0, nargs=1, help="Allows for fine movement of the legend.") addOption("legend_y_offset", 0, nargs=1, help="Allows for fine movement of the legend.") addOption("plot_confidence_interval_border", False, nargs=1, help="Whether or not the show borders at the edges of the shaded " "confidence region.") addOption("confidence_interval_border_style", ":", nargs=1, help="Line style of the confidence interval border.") addOption("confidence_interval_border_width", 1, nargs=1, help="Line width of the confidence interval border.") addOption("confidence_interval_alpha", FILL_ALPHA, nargs=1, help="Alpha value for the shaded region.") # Per plot settings addOption("to_plot", 1, aliases=["plot_column"], help="The columns from the input files that should be plotted.") addOption("file_names", "my_plot", aliases=["plot_output"], help="The names of the output files for each plotted column.") addOption("titles", "Unnamed plot", aliases=["plot_title"], help="The titles for each plot.") addOption("x_labels", "Number of Generations", aliases=["plot_x_label"], help="The x labels for each plot.") addOption("y_labels", "Value", aliases=["plot_y_label"], help="The x labels for each plot.") addOption("legend_loc", "best", aliases=["plot_legend_loc"], help="Legend location for each plot.") addOption("y_axis_min", aliases=["plot_y_min"], help="The minimum value for the y axis.") addOption("y_axis_max", aliases=["plot_y_max"], help="The maximum value for the y axis.") addOption("x_axis_max", aliases=["plot_x_max"], help="The minimum value for the x axis.") addOption("x_axis_min", aliases=["plot_x_min"], help="The maximum value for the x axis.") # Cache settings addOption("read_cache", True, nargs=1, help="If false, script will not attempt to read data from cache.") addOption("write_cache", True, nargs=1, help="If false, script will not write cache files.") addOption("read_median_ci_cache", True, nargs=1, help="If false, script will not read median values from cache.") addOption("write_median_ci_cache", True, nargs=1, help="If false, script will not write median values to cache.") addOption("read_comparison_cache", True, nargs=1, help="If false, script will not read statistical results from cache.") addOption("write_comparison_cache", True, nargs=1, help="If false, script will not write statistical results to cache.") addOption("comparison_cache", def_comp_cache, nargs=1, help="Name of the cache file that holds statistical results.") # Per treatment settings addOption("input_directories", aliases=["treatment_dir"], help="Directories containing the files for each specific treatment.") addOption("treatment_names", def_treatment_names, aliases=["treatment_name"], help="The names of each treatment, used for the legend.") addOption("treatment_names_short", def_treatment_names_short, aliases=["treatment_name_short"], help="A short name for each treatment, used when the regular name " "does not fit.") addOption("colors", ["#000082", "#008200", "#820000", "#008282", "#828200", "#820082"], aliases=["treatment_color"], help="The color for each treatment.") addOption("background_colors", def_background_colors, aliases=["treatment_bgcolor"], help="The color of the shaded region, for each treatment.") addOption("marker", ["o", "^", "v", "<", ">", "*"], aliases=["treatment_marker"], help="The marker used for each treatment.") addOption("linestyle", ["-"], aliases=["treatment_linestyle"], help="The marker used for each treatment.") addOption("sig_marker", def_sig_marker, help="The marker used in the signficance indicator box.") addOption("marker_offset", def_marker_offset, help="Offset between the markers of different treatments, so they " "are not plotted on top of each other.") addPositionalOption("file", nargs="*", help="Files or directories from which to read the data.") ################### ##### CLASSES ##### ################### class Treatment: def __init__(self, treatment_id, directory, treatment_name, short_name): #Get Global data self.templates = getList("templates") self.pool = getList("pool") if len(self.pool) > 0: debug_print("files", "Pooling:", self.pool) self.root_directory = directory self.dirs = getDirs(self.pool, directory) self.files = [] self.files_per_pool = [] for pool_dir in self.dirs: files = get_files(self.templates, pool_dir) self.files += files self.files_per_pool.append(files) self.cache_file_name_prefix = (self.root_directory + "/ch_" + self.templates[-1] + "_") if os.path.isdir(directory): debug_print("files", "Retrieving files from directory:", directory, "with template:", self.templates) self.root_directory = directory self.files = get_files(self.templates, directory) self.cache_file_name_prefix = (self.root_directory + "/ch_" + self.templates[-1] + "_") elif os.path.isfile(directory): debug_print("files", "Retrieving file:", directory) self.root_directory = os.path.dirname(os.path.realpath(directory)) self.files = [directory] self.cache_file_name_prefix = (self.root_directory + "/ch_" + os.path.basename(directory) + "_") else: debug_print("files", "File not found.") self.root_directory = None self.files = [] self.cache_file_name_prefix = "unknown_" self.name = treatment_name self.short_name = short_name self.id = treatment_id self.parts = [self.files] def __str__(self): return (str(self.root_directory) + " " + str(self.name) + " " + str(self.short_name) + " " + str(self.id)) def add_dir(self, directory): self.parts.append(get_files(self.templates, directory)) def get_id(self): return self.id def get_name(self): return self.name def get_name_short(self): return self.short_name def get_cache_file_name(self, plot_id, stats=''): if stats == '': return self.cache_file_name_prefix + str(plot_id) + ".cache" return self.cache_file_name_prefix + stats + '_' + str(plot_id) + ".cache" class TreatmentList: def __init__(self): self.treatments = [] self.unnamed_treatment_count = 0 def __len__(self): return len(self.treatments) def __iter__(self): return iter(self.treatments) def __getitem__(self, index): return self.treatments[index] def __str__(self): return str(self.treatments) def add_treatment(self, treat_dir, suggest_name=None, short_name=None): treat_id = len(self.treatments) if suggest_name and short_name: self.treatments.append(Treatment(treat_id, treat_dir, suggest_name, short_name)) elif suggest_name: self.treatments.append(Treatment(treat_id, treat_dir, suggest_name, suggest_name)) else: self.unnamed_treatment_count += 1 name = "Unnamed " + str(self.unnamed_treatment_count) self.treatments.append(Treatment(treat_id, treat_dir, name, name)) def get_treatment_directories(self): treatment_directories = [] for treatment in self.treatments: treatment_directories.append(treatment.root_directory) return treatment_directories def get_treatment_names(self): treatment_names = [] for treatment in self.treatments: treatment_names.append(treatment.name) return treatment_names def get_treatment_short_names(self): treatment_names = [] for treatment in self.treatments: treatment_names.append(treatment.short_name) return treatment_names class MedianAndCI: def __init__(self): self.median = dict() self.ci_min = dict() self.ci_max = dict() def __len__(self): return len(self.median) def add(self, generation, median, ci_min, ci_max): self.median[generation] = median self.ci_min[generation] = ci_min self.ci_max[generation] = ci_max def to_cache(self, cache_file_name): sorted_keys = sorted(self.median) median_array = self.get_median_array() ci_min_array = self.get_ci_min_array() ci_max_array = self.get_ci_max_array() with open(cache_file_name, 'w') as cache_file: print("Writing " + cache_file_name + "...") for i in range(len(median_array)): cache_file.write(str(median_array[i]) + " ") cache_file.write(str(ci_min_array[i]) + " ") cache_file.write(str(ci_max_array[i]) + " ") cache_file.write(str(sorted_keys[i]) + "\n") def get_median_array(self): return dict_to_np_array(self.median) def get_ci_min_array(self): return dict_to_np_array(self.ci_min) def get_ci_max_array(self): return dict_to_np_array(self.ci_max) class RawData: def __init__(self): self.raw_data = dict() self.max_generation = None def __getitem__(self, plot_id): return self.raw_data[plot_id] def __contains__(self, plot_id): return plot_id in self.raw_data def get_max_generation(self, plot_id=None): if plot_id is None: if not self.max_generation: self.init_max_generation() return self.max_generation else: return max(self.raw_data[plot_id].keys()) def add(self, plot_id, generation, value): #print "Adding", plot_id, generation, value debug_print("raw_data", "For plot", plot_id, "added:", generation, value) if plot_id not in self.raw_data: self.raw_data[plot_id] = dict() if generation not in self.raw_data[plot_id]: self.raw_data[plot_id][generation] = list() self.raw_data[plot_id][generation].append(value) def get(self, plot_id, generation): return self.raw_data[plot_id][generation] def init_max_generation(self): #Read global data self.max_generation = getInt("max_generation") if self.max_generation == MAX_GEN_NOT_PROVIDED: for data in self.raw_data.values(): generations = max(data.keys()) debug_print("plot", "generations: " + str(generations)) if generations > self.max_generation: self.max_generation = generations class DataSingleTreatment: def __init__(self, treatment): self.treatment = treatment self.raw_data = None self.median_and_ci = dict() self.stats = dict() self.max_generation = None def get_raw_data(self): if not self.raw_data: self.init_raw_data() return self.raw_data def get_stats(self, plot_id, stats): if plot_id not in self.stats: self.init_stats(plot_id, stats) if stats not in self.stats[plot_id]: self.init_stats(plot_id, stats) return self.stats[plot_id][stats] def get_median_and_ci(self, plot_id): print('WARNING: Method get_median_and_ci is deprecated') if plot_id not in self.median_and_ci: self.init_median_and_ci(plot_id) return self.median_and_ci[plot_id] def get_max_generation(self): if not self.max_generation: self.init_max_generation() return self.max_generation def stats_to_cache(self, stats): #Read global data to_plot = getIntList("to_plot") for plot_id in to_plot: median_and_ci = self.get_stats(plot_id, stats) filename = self.treatment.get_cache_file_name(plot_id, stats) median_and_ci.to_cache(filename) def to_cache(self): print('WARNING: to_cache is deprecated') #Read global data to_plot = getIntList("to_plot") for plot_id in to_plot: median_and_ci = self.get_median_and_ci(plot_id) median_and_ci.to_cache(self.treatment.get_cache_file_name(plot_id)) def init_max_generation(self): #Read global data self.max_generation = getInt("max_generation") if self.max_generation == MAX_GEN_NOT_PROVIDED: raw_data = self.get_raw_data() self.max_generation = raw_data.get_max_generation() def init_raw_data(self): #Read global data separator = getStr("separator") to_plot = getIntList("to_plot") y_column = getInt("x_column") one_value_per_dir = getBool("one_value_per_dir") pool = len(getList("pool")) > 0 #Init raw data self.raw_data = RawData() if len(self.treatment.files) == 0: print("Warning: treatment " + self.treatment.get_name() + " has no files associated with it.") if one_value_per_dir: generation = 0 for file_names in self.treatment.parts: debug_print("files", "Parts: ", file_names) for file_name in file_names: with open(file_name, 'r') as separated_file: print("Reading raw data for value " + str(generation) + " from " + file_name + "...") skip_header(separated_file) for line in separated_file: split_line = get_split_line(line, separator) self._add(split_line, generation) generation += 1 elif pool: for dir_name, file_names in zip(self.treatment.dirs, self.treatment.files_per_pool): print("Pooling for directory: ", dir_name) results = [] for file_name in file_names: with open(file_name, 'r') as separated_file: print("Reading raw data from " + file_name + "...") skip_header(separated_file) generation = 0 for line in separated_file: split_line = get_split_line(line, separator) result = self._parse_pool(split_line, generation) #print "Value read: ", result if len(results) < (generation+1): results.append(result) else: for i in range(len(result)): old_value = results[generation][i] new_value = result[i] if new_value > old_value: results[generation][i] = new_value generation += 1 generation = 0 for result in results: for plot_id, value in zip(to_plot, result): #print "Value used:", value self.raw_data.add(plot_id, generation, value) generation += 1 else: for file_name in self.treatment.files: with open(file_name, 'r') as separated_file: print("Reading raw data from " + file_name + "...") skip_header(separated_file) generation = 0 for line in separated_file: #split_line_temp = line.split(separator) split_line = get_split_line(line, separator) self._add(split_line, generation) generation += 1 def init_stats(self, plot_id, stats): #Get global data read_cache = getBool("read_cache") and getBool("read_median_ci_cache") if read_cache: try: self.init_stats_from_cache(plot_id, stats) assert plot_id in self.stats assert stats in self.stats[plot_id] return except IOError: pass except CacheException: pass self.init_stats_from_data(plot_id, stats) assert plot_id in self.stats assert stats in self.stats[plot_id] def init_median_and_ci(self, plot_id): print('WARNING: init_median_and_ci is deprecated') #Get global data read_cache = getBool("read_cache") and getBool("read_median_ci_cache") if read_cache: try: self.init_median_and_ci_from_cache(plot_id) return except IOError: pass except CacheException: pass self.init_median_and_ci_from_data(plot_id) def init_stats_from_cache(self, plot_id, stats): # Read global data step = getInt("step") x_from_file = getBool("x_from_file") # Get the max generation for which we have data max_generation = self.get_max_generation() generations_to_plot = range(0, max_generation, step) data_points = len(generations_to_plot) cache_file_name = self.treatment.get_cache_file_name(plot_id, stats) # Count the number of data points we have in count = get_nr_of_lines(cache_file_name) #Read the cache file with open(cache_file_name, 'r') as cache_file: print("Reading from cache file " + cache_file_name + "...") if plot_id not in self.stats: self.stats[plot_id] = dict() self.stats[plot_id][stats] = MedianAndCI() data_point_number = 0 for line in cache_file: try: generation = generations_to_plot[data_point_number] split_line = line.split() debug_print("data", "Expected generation:", generation) debug_print("data", split_line) if generation != int(split_line[3]) and not x_from_file: raise CacheError("Step mismatch") self.stats[plot_id][stats].add(int(split_line[3]), split_line[0], split_line[1], split_line[2]) data_point_number += 1 except IndexError: break def init_median_and_ci_from_cache(self, plot_id): print('WARNING: init_median_and_ci_from_cache is deprecated') # Read global data step = getInt("step") x_from_file = getBool("x_from_file") # Get the max generation for which we have data max_generation = self.get_max_generation() generations_to_plot = range(0, max_generation, step) data_points = len(generations_to_plot) cache_file_name = self.treatment.get_cache_file_name(plot_id) # Count the number of data points we have in count = get_nr_of_lines(cache_file_name) #Read the cache file with open(cache_file_name, 'r') as cache_file: print("Reading from cache file " + cache_file_name + "...") self.median_and_ci[plot_id] = MedianAndCI() data_point_number = 0 for line in cache_file: try: generation = generations_to_plot[data_point_number] split_line = line.split() debug_print("data", "Expected generation:", generation) debug_print("data", split_line) if generation != int(split_line[3]) and not x_from_file: raise CacheError("Step mismatch") self.median_and_ci[plot_id].add(int(split_line[3]), split_line[0], split_line[1], split_line[2]) data_point_number += 1 except IndexError: break def init_stats_from_data(self, plot_id, stats): #Read global data step = getInt("step") #stats = getStr('stats') write_cache = (getBool("write_cache") and getBool("write_median_ci_cache")) x_from_file = getBool("x_from_file") #Initialize empty median and ci if plot_id not in self.stats: self.stats[plot_id] = dict() self.stats[plot_id][stats] = MedianAndCI() #self.median_and_ci[plot_id] = MedianAndCI() max_generation = self.get_max_generation() if plot_id not in self.get_raw_data(): print("Warning: no data available for plot", plot_id, "skipping.") return if x_from_file: max_generation_available = self.get_raw_data().get_max_generation(plot_id) else: max_generation_available = len(self.get_raw_data()[plot_id]) if max_generation_available < max_generation: print("Warning: data does not extent until max generation: " + str(max_generation)) print("Maximum generation available is: " + str(max_generation_available)) max_generation = max_generation_available #Calculate median and confidence intervals print("Calculating confidence intervals...") y_values = sorted(self.get_raw_data()[plot_id].keys()) generations_to_plot = y_values[0:len(y_values):step] debug_print("plot", "generations_to_plot: " + str(generations_to_plot) + " max generation: " + str(max_generation)) for generation in generations_to_plot: raw_data = self.get_raw_data()[plot_id][generation] # if bootstrap: print("Generation: " + str(generation)) # print("raw_data:", raw_data) median, ci_min, ci_max = calc_stats(raw_data, stats) # print("median:", median, ci_min, ci_max) debug_print("ci", str(median) + " " + str(ci_min) + " " + str(ci_max)) # else: # median, ci_min, ci_max = calc_median_and_interquartile_range(raw_data) self.stats[plot_id][stats].add(generation, median, ci_min, ci_max) if write_cache: self.stats_to_cache(stats) def init_median_and_ci_from_data(self, plot_id): print('WARNING: init_median_and_ci_from_data is deprecated') #Read global data step = getInt("step") stats = getStr('stats') # Backwards compatibility with outdated bootstrap option bootstrap = getBool("bootstrap") if bootstrap: stats = 'median_and_bootstrap_percentile' write_cache = (getBool("write_cache") and getBool("write_median_ci_cache")) x_from_file = getBool("x_from_file") #Initialize empty median and ci self.median_and_ci[plot_id] = MedianAndCI() max_generation = self.get_max_generation() if plot_id not in self.get_raw_data(): print("Warning: no data available for plot", plot_id, "skipping.") return if x_from_file: max_generation_available = self.get_raw_data().get_max_generation(plot_id) else: max_generation_available = len(self.get_raw_data()[plot_id]) if max_generation_available < max_generation: print("Warning: data does not extent until max generation: " + str(max_generation)) print("Maximum generation available is: " + str(max_generation_available)) max_generation = max_generation_available #Calculate median and confidence intervals print("Calculating confidence intervals...") y_values = sorted(self.get_raw_data()[plot_id].keys()) generations_to_plot = y_values[0:len(y_values):step] debug_print("plot", "generations_to_plot: " + str(generations_to_plot) + " max generation: " + str(max_generation)) for generation in generations_to_plot: raw_data = self.get_raw_data()[plot_id][generation] # if bootstrap: print("Generation: " + str(generation)) # print("raw_data:", raw_data) median, ci_min, ci_max = calc_stats(raw_data, stats) # print("median:", median, ci_min, ci_max) debug_print("ci", str(median) + " " + str(ci_min) + " " + str(ci_max)) # else: # median, ci_min, ci_max = calc_median_and_interquartile_range(raw_data) self.median_and_ci[plot_id].add(generation, median, ci_min, ci_max) if write_cache: self.to_cache() def _parse_pool(self, split_line, generation): to_plot = getIntList("to_plot") x_values_passed = getExists("x_values") x_values = getIntList("x_values") result = [] debug_print("read_values", "Split line:", split_line, "plot requested:", to_plot) for plot_id in to_plot: if len(split_line) <= plot_id: print("Error: no data for requested column" + str(plot_id) + "in line (length" + str(len(split_line)) + ")" + split_line) else: result.append(float(split_line[plot_id])) return result def _add(self, split_line, generation): to_plot = getIntList("to_plot") x_from_file = getBool("x_from_file") x_column = getInt("x_column") x_values_passed = getExists("x_values") x_values = getIntList("x_values") debug_print("read_values", "Split line:", split_line, "plot requested:", to_plot) for plot_id in to_plot: if len(split_line) <= plot_id: print ("Error: no data for requested column", plot_id, "in line (length", len(split_line), ")", split_line) elif x_from_file and len(split_line) > 1: self.raw_data.add(plot_id, int(split_line[x_column]), float(split_line[plot_id])) elif x_values_passed and generation < len(x_values): self.raw_data.add(plot_id, x_values[generation], float(split_line[plot_id])) else: self.raw_data.add(plot_id, generation, float(split_line[plot_id])) class DataOfInterest: def __init__(self, treatment_list): self.treatment_list = treatment_list self.treatment_data = dict() self.treatment_name_cache = dict() self.comparison_cache = None self.max_generation = None def get_treatment_index(self, treatment_name): if treatment_name in self.treatment_name_cache: return self.treatment_name_cache[treatment_name] else: for tr in self.treatment_list: self.treatment_name_cache[tr.get_name()] = tr.get_id() self.treatment_name_cache[tr.get_name_short()] = tr.get_id() return self.treatment_name_cache[treatment_name] def get_treatment_list(self): return self.treatment_list def get_treatment(self, treatment_id): return self.treatment_list[treatment_id] def get_treatment_data(self, treatment): treatment_id = treatment.get_id() if treatment_id not in self.treatment_data: self.treatment_data[treatment_id] = DataSingleTreatment(self.treatment_list[treatment_id]) return self.treatment_data[treatment_id] def get_max_generation(self): if not self.max_generation: self.init_max_generation() return self.max_generation def get_min_generation(self): return 0 def get_x_values(self, treatment, plot_id): #Read global data max_generation = getInt("max_generation") first_plot = getInt("to_plot") x_from_file = getBool("x_from_file") treatment_data = self.get_treatment_data(treatment) med_ci = treatment_data.get_median_and_ci(first_plot) if max_generation == MAX_GEN_NOT_PROVIDED or x_from_file: keys = sorted(med_ci.median.keys()) return keys[0:len(med_ci.median.keys()):getInt("step")] else: return range(0, len(med_ci.median)*getInt("step"), getInt("step")) def get_x_values_stats(self, treatment, plot_id, stats): #Read global data max_generation = getInt("max_generation") first_plot = getInt("to_plot") x_from_file = getBool("x_from_file") treatment_data = self.get_treatment_data(treatment) med_ci = treatment_data.get_stats(first_plot, stats) if max_generation == MAX_GEN_NOT_PROVIDED or x_from_file: keys = sorted(med_ci.median.keys()) return keys[0:len(med_ci.median.keys()):getInt("step")] else: return range(0, len(med_ci.median)*getInt("step"), getInt("step")) def get_comparison(self, treatment_id_1, treatment_id_2, plot_id): if not self.comparison_cache: self.init_compare() key = (treatment_id_1, treatment_id_2, plot_id) if key not in self.comparison_cache: print("Error: no comparison entry for values" + str(key)) print("Cache:", self.comparison_cache) return [] return self.comparison_cache[key] def to_cache(self): # Read global data cache_file_name = getStr("comparison_cache") stat_test_step = getInt("stat_test_step") with open(cache_file_name, 'w') as cache_file: print ("Writing " + cache_file_name + "...") for entry in self.comparison_cache.items(): key, generations = entry main_treatment_id, other_treatment_id, plot_id = key cache_file.write(str(plot_id) + " ") cache_file.write(str(main_treatment_id) + " ") cache_file.write(str(other_treatment_id) + " ") cache_file.write(str(stat_test_step) + " ") for generation in generations: cache_file.write(str(generation) + " ") cache_file.write("\n") def init_max_generation(self): #Read global data self.max_generation = getInt("max_generation") #Calculate max generation if necessary if self.max_generation == MAX_GEN_NOT_PROVIDED: for treatment in self.treatment_list: treatment_data = self.get_treatment_data(treatment) if treatment_data.get_max_generation() > self.max_generation: self.max_generation = treatment_data.get_max_generation() def init_compare(self): #Read global data read_cache = getBool("read_cache") and getBool("read_comparison_cache") self.comparison_cache = DictOfLists() if read_cache: try: self.init_compare_from_cache() return except IOError: pass except CacheException: pass self.init_compare_from_data() def init_compare_from_cache(self): # Read global data comp_cache_name = getStr("comparison_cache") stat_test_step = getInt("stat_test_step") # Actually read the cache file with open(comp_cache_name, 'r') as cache_file: print("Reading from comparison cache "+comp_cache_name+"...") for line in cache_file: numbers = line.split() if len(numbers) < 4: raise CacheException("Entry is to short.") plot_id_cache = int(numbers[0]) main_treat_id_cache = int(numbers[1]) other_treat_id_cache = int(numbers[2]) stat_test_step_cache = int(numbers[3]) if stat_test_step != stat_test_step_cache: raise CacheException("Cache created with different step") key = (main_treat_id_cache, other_treat_id_cache, plot_id_cache) self.comparison_cache.init_key(key) for i in range(4, len(numbers)): self.comparison_cache.add(key, int(numbers[i])) self.verify_cache() def verify_cache(self): # Verify that all data is there plot_ids = getIntList("to_plot") for plot_id in plot_ids: for compare_i in range(len(getList("comparison_main"))): main_treat_id = getStr("comparison_main", compare_i) main_treat_i = get_treatment_index(main_treat_id, self) for other_treat_i in get_other_treatments(compare_i, self): key = (main_treat_i, other_treat_i, plot_id) if key not in self.comparison_cache: raise CacheException("Cache is missing an entry.") def init_compare_from_data(self): # Get global data plot_ids = getIntList("to_plot") write_cache = (getBool("write_cache") and getBool("write_comparison_cache")) # Compare data for all plots and all treatments for plot_id in plot_ids: for compare_i in range(len(getList("comparison_main"))): main_treat_id = getStr("comparison_main", compare_i) main_treat_i = get_treatment_index(main_treat_id, self) for other_treat_i in get_other_treatments(compare_i, self): self.compare_treat(main_treat_i, other_treat_i, plot_id) if write_cache: self.to_cache() def compare_treat(self, main_treat_i, other_treat_i, plot_id): debug_print("cache", "Comparing: ", other_treat_i, " : ", main_treat_i) # Retrieve data stat_test_step = getInt("stat_test_step") p_threshold = getFloat("p_threshold") main_treat = self.treatment_list[main_treat_i] main_data = self.get_treatment_data(main_treat).get_raw_data() other_treat = self.treatment_list[other_treat_i] other_data = self.get_treatment_data(other_treat).get_raw_data() # Assert that data is available if plot_id not in main_data: warn_data_avail(plot_id, main_treat) return if plot_id not in other_data: warn_data_avail(plot_id, other_treat) return warn_max_gen(self, main_data, other_data, plot_id) # Construct a key and add it to the cache key = (main_treat_i, other_treat_i, plot_id) self.comparison_cache.init_key(key) # Gather all generations for which we have data for both treatments main_gen = set(main_data[plot_id].keys()) other_gen = set(other_data[plot_id].keys()) generations = list(main_gen.intersection(other_gen)) generations.sort() # Perform the actual statistical test for generation in generations[::stat_test_step]: data1 = main_data[plot_id][generation] data2 = other_data[plot_id][generation] p_value = mann_whitney_u(data1, data2) print("Generation:", generation, "p-value:", p_value, "mean 1:", np.mean(data1), "mean 2:", np.mean(data2)) if p_value < p_threshold: self.comparison_cache.add(key, generation) ###################### ## HELPER FUNCTIONS ## ###################### def warn_data_avail(plot_id, treatment): print("Warning: no data available for plot", plot_id, "treatment", treatment.get_name(), ", skipping...") def warn_max_gen(data_intr, main_data, other_data, plot_id): # Determine max generation for this comparison max_gen = data_intr.get_max_generation() max_gen_main = main_data.get_max_generation(plot_id) max_gen_other = other_data.get_max_generation(plot_id) max_gen_avail = min(max_gen_main, max_gen_other) if max_gen_avail < max_gen: print("Warning: data does extent until max generation: " + str(max_gen)) print("Maximum generation available is: " + str(max_gen_avail)) max_gen = max_gen_avail return max_gen def getSigMarker(compare_to_symbol): sig_marker = getStrDefaultFirst("sig_marker", compare_to_symbol) try: matplotlib.markers.MarkerStyle(sig_marker) except ValueError: print("Warning: invalid significance marker, marker replaced with *.") sig_marker = "*" return sig_marker def getMarker(compare_to_symbol): sig_marker = getStr("marker", compare_to_symbol) try: matplotlib.markers.MarkerStyle(sig_marker) except ValueError: print("Warning: invalid plot marker, marker replaced with *.") sig_marker = "*" return sig_marker def getLinestyle(compare_to_symbol): linestyle = getStrDefaultFirst("linestyle", compare_to_symbol) if linestyle not in ['-', '--', '-.', ':']: print("Warning: invalid linestyle, linestyle replaced with -.") linestyle = "-" return linestyle def getFgColor(compare_to_symbol): color = getStr("colors", compare_to_symbol) try: matplotlib.colors.colorConverter.to_rgb(color) except ValueError: print("Warning: invalid treatment color, color replaced with grey.") color = "#505050" return color def getBgColor(compare_to_symbol): back_color = getStr("background_colors", compare_to_symbol) if back_color == "default": fore_color = getStr("colors", compare_to_symbol) back_color = def_bg_color(fore_color) try: matplotlib.colors.colorConverter.to_rgb(back_color) except ValueError: print("Warning: invalid background color", back_color, ", color replaced with grey.") back_color = "#505050" return back_color def get_other_treatments(compare_i, data_intr): main_treat_id = getStr("comparison_main", compare_i) main_treat_i = get_treatment_index(main_treat_id, data_intr) nr_of_treatments = len(data_intr.get_treatment_list()) other_treatment_ids = getStrDefaultEmpty("comparison_others", compare_i) other_treatments = parse_treatment_ids(other_treatment_ids, data_intr) if len(other_treatments) == 0: other_treatments = range(nr_of_treatments-1, -1, -1) other_treatments.remove(main_treat_i) else: other_treatments.reverse() return other_treatments ###################### # PLOTTING FUNCTIONS # ###################### def create_plots(data_of_interest): for plot_id in getIntList("to_plot"): create_plot(plot_id, data_of_interest) def draw_plot(plot_id, data_of_interest, ax, stats): for treatment in data_of_interest.get_treatment_list(): plot_treatment(plot_id, treatment, data_of_interest, ax, stats) def draw_inset(plot_id, data_of_interest, ax): inset_stats = getStr('inset_stats') inset_x = getFloat('inset_x') inset_y = getFloat('inset_y') inset_w = getFloat('inset_w') inset_h = getFloat('inset_h') inset_area_x1 = getFloat('inset_area_x1') inset_area_x2 = getFloat('inset_area_x2') inset_area_y1 = getFloat('inset_area_y1') inset_area_y2 = getFloat('inset_area_y2') inset_labels = getStr('inset_labels') inset_ticks = getStr('inset_ticks') inset_lines_visible = getStr('inset_lines_visible') axins = ax.inset_axes([inset_x, inset_y, inset_w, inset_h]) axins.set_xlim(inset_area_x1, inset_area_x2) axins.set_ylim(inset_area_y1, inset_area_y2) if inset_labels == 'none': axins.set_xticklabels('') axins.set_yticklabels('') if inset_ticks == 'none': axins.xaxis.set_ticks_position('none') axins.yaxis.set_ticks_position('none') rec_patch, conn_lines = ax.indicate_inset_zoom(axins) if inset_lines_visible == 'all': for conn_line in conn_lines: conn_line._visible = True elif inset_lines_visible == 'none': for conn_line in conn_lines: conn_line._visible = False draw_plot(plot_id, data_of_interest, axins, inset_stats) def create_plot(plot_id, data_of_interest): stats = getStr('stats') inset_stats = getStr('inset_stats') # Backwards compatibility with outdated bootstrap option bootstrap = getBool("bootstrap") if bootstrap: stats = 'median_and_bootstrap_percentile' extra_artists[plot_id] = [] plt.figure(int(plot_id)) ax = plt.gca() draw_plot(plot_id, data_of_interest, ax, stats) if inset_stats != '': draw_inset(plot_id, data_of_interest, ax) def plot_treatment(plot_id, treatment, data_of_interest, ax, stats): #Get data max_generation = data_of_interest.get_max_generation() treatment_name = treatment.get_name() treatment_index = treatment.get_id() treatment_data = data_of_interest.get_treatment_data(treatment) mean_and_ci = treatment_data.get_stats(plot_id, stats) marker = getMarker(treatment_index) linestyle = getLinestyle(treatment_index) marker_size = getFloat("marker_size") marker_offset = getInt("marker_offset", treatment_index) color = getFgColor(treatment_index) bg_color = getBgColor(treatment_index) debug_print("plot", "Max generation: " + str(max_generation)) debug_print("plot", "Step: " + str(getInt("step"))) print("For plot " + str(plot_id) + " plotting treatment: " + treatment.get_name()) if len(mean_and_ci) == 0: print("Warning: no data available for plot", plot_id, "of treatment", treatment.get_name(), ", skipping.") return plot_mean = mean_and_ci.get_median_array() var_min = mean_and_ci.get_ci_min_array() var_max = mean_and_ci.get_ci_max_array() #Apply median filter plot_mean = median_filter(plot_mean, getInt("smoothing")) var_min = median_filter(var_min, getInt("smoothing")) var_max = median_filter(var_max, getInt("smoothing")) #Calculate plot markers data_step_x = data_of_interest.get_x_values_stats(treatment, plot_id, stats) debug_print("plot", "X len", len(data_step_x), "X data: ", data_step_x) debug_print("plot", "Y len", len(plot_mean), "Y data: ", plot_mean) assert(len(data_step_x) == len(plot_mean)) if get("marker_step")[0] is not None: marker_step = getInt("marker_step") else: marker_step = max_generation / 10 if marker_step < 1: marker_step = 1 adj_marker_step = int(marker_step/getInt("step")) adjusted_marker_offset = int(marker_offset/getInt("step")) #Debug statements debug_print("plot", "Marker step: " + str(marker_step) + " adjusted: " + str(adj_marker_step)) debug_print("plot", "Marker offset: " + str(marker_offset) + " adjusted: " + str(adjusted_marker_offset)) #Calculate markers print('adjusted_marker_offset', adjusted_marker_offset) print('adj_marker_step', adj_marker_step) plot_marker_y = plot_mean[adjusted_marker_offset:len(plot_mean):adj_marker_step] plot_marker_x = data_step_x[adjusted_marker_offset:len(plot_mean):adj_marker_step] #Debug statements debug_print("plot", "Plot marker X len", len(plot_marker_x), "X data: ", plot_marker_x) debug_print("plot", "Plot marker Y len", len(plot_marker_y), "Y data: ", plot_marker_y) assert(len(plot_marker_x) == len(plot_marker_y)) #Calculate data step #if getBool("y_from_file"): # data_step_x = sorted(data_of_interest.get_raw_data()[plot_id].keys()) #else: # data_step_x = range(0, len(plot_mean)*getInt("step"), getInt("step")) #Plot mean #The actual median ax.plot(data_step_x, plot_mean, color=color, linewidth=LINE_WIDTH, linestyle=linestyle) #Fill confidence interval alpha=getFloat("confidence_interval_alpha") ax.fill_between(data_step_x, var_min, var_max, edgecolor=bg_color, facecolor=bg_color, alpha=alpha, linewidth=NO_LINE) if getBool("plot_confidence_interval_border"): style=getStr("confidence_interval_border_style") width=getFloat("confidence_interval_border_width") ax.plot(data_step_x, var_min, color=color, linewidth=width, linestyle=style) ax.plot(data_step_x, var_max, color=color, linewidth=width, linestyle=style) #Markers used on top of the line in the plot ax.plot(plot_marker_x, plot_marker_y, color=color, linewidth=NO_LINE, marker=marker, markersize=marker_size) #Markers used in the legend #To plot the legend markers, plot a point completely outside of the plot. ax.plot([data_step_x[0] - max_generation], [0], color=color, linewidth=LINE_WIDTH, linestyle=linestyle, marker=marker, label=treatment_name, markersize=marker_size) def add_significance_bar(i, gs, data_intr, bar_nr): ROW_HEIGHT = 1.0 HALF_ROW_HEIGHT = ROW_HEIGHT/2.0 max_generation = data_intr.get_max_generation() min_generation = data_intr.get_min_generation() main_treat_id = getStr("comparison_main", bar_nr) main_treat_i = get_treatment_index(main_treat_id, data_intr) main_treat = data_intr.get_treatment_list()[main_treat_i] other_treats = get_other_treatments(bar_nr, data_intr) plot_id = getInt("to_plot", i) box_top = len(other_treats)*ROW_HEIGHT box_bot = 0 print(" Calculating significance for plot: " + str(i)) sig_label = getStr("sig_label") sig_label = sig_label.replace('\\n', '\n') if getBool("sig_lbl_add_treat_name") and not getBool("sig_header_show"): lbl = sig_label + main_treat.get_name_short() elif not getBool("sig_header_show"): lbl = sig_label elif getBool("sig_lbl_add_treat_name"): lbl = main_treat.get_name_short() else: lbl = "" ax = plt.subplot(gs[bar_nr]) ax.set_xlim(0, max_generation) ax.get_yaxis().set_ticks([]) ax.set_ylim(box_bot, box_top) if getBool("sig_header_show") and bar_nr == 0: # Add text on the side dx = -(getFloat("sig_header_x_offset")*float(max_generation)) dy = box_top - (getFloat("sig_header_y_offset")*float(box_top)) an = ax.annotate(sig_label, xy=(dx, dy), xytext=(dx, dy), annotation_clip=False, verticalalignment='top', horizontalalignment='right', size=getInt("sig_header_font_size") ) extra_artists[plot_id].append(an) ax.set_ylabel(lbl, rotation='horizontal', fontsize=getInt("tick_font_size"), horizontalalignment='right', verticalalignment='center') # Sets the position of the p<0.05 label # While the y coordinate can be set directly with set_position, the x # coordinate passed to this method is ignored by default. So instead, # the labelpad is used to modify the x coordinate (and, as you may # expect, there is no labelpad for the y coordinate, hence the two # different methods for applying the offset). x, y = ax.get_yaxis().label.get_position() ax.get_yaxis().labelpad += getFloat("comparison_offset_x") ax.get_yaxis().label.set_position((0, y - getFloat("comparison_offset_y"))) ax.tick_params(bottom=True, top=False) if bar_nr == (len(getList("comparison_main")) -1): ax.set_xlabel(getStrDefaultFirst("x_labels", i)) else: ax.set_xlabel("") ax.set_xticks([]) odd = True row_center = HALF_ROW_HEIGHT for other_treat_i in other_treats: sig_marker = getSigMarker(other_treat_i) color = getFgColor(other_treat_i) back_color = getBgColor(other_treat_i) other_treat = data_intr.get_treatment_list()[other_treat_i] #Add the background box row_top = row_center + HALF_ROW_HEIGHT row_bot = row_center - HALF_ROW_HEIGHT box = Polygon([(min_generation, row_bot), (min_generation, row_top), (max_generation, row_top), (max_generation, row_bot)], facecolor=back_color, zorder=-100) ax.add_patch(box) #Add the line separating the treatments ax.plot([min_generation, max_generation], [row_bot, row_bot], color='black', linestyle='-', linewidth=1.0, solid_capstyle="projecting") comp = data_intr.get_comparison(main_treat_i, other_treat_i, plot_id) for index in comp: ax.scatter(index, row_center, marker=sig_marker, c=color, s=50) # Determmine position for treatment labels lbls_x = max_generation*(1.0 + getFloat("sig_treat_lbls_x_offset")) if getStr("sig_treat_lbls_align") == "top": lbls_y = row_top + getFloat("sig_treat_lbls_y_offset") lbls_v_align = "top" elif getStr("sig_treat_lbls_align") == "bottom": lbls_y = row_bot + getFloat("sig_treat_lbls_y_offset") lbls_v_align = "bottom" elif getStr("sig_treat_lbls_align") == "center": lbls_y = row_center + getFloat("sig_treat_lbls_y_offset") lbls_v_align = "center" else: raise Exception("Invalid option for 'sig_treat_lbls_align': " + getStr("sig_treat_lbls_align")) if getBool("sig_treat_lbls_show"): if getBool("sig_treat_lbls_symbols"): # Add symbol markers on the side if odd: lbls_x = max_generation*(1.010 + getFloat("sig_treat_lbls_x_offset")) else: lbls_x = max_generation*(1.035 + getFloat("sig_treat_lbls_x_offset")) ax.plot([max_generation, lbls_x], [lbls_y, lbls_y], color='black', linestyle='-', linewidth=1.0, solid_capstyle="projecting", clip_on=False, zorder=90) p = ax.scatter(lbls_x, lbls_y, marker=sig_marker, c=color, s=100, clip_on=False, zorder=100) extra_artists[plot_id].append(p) else: # Add text on the side an = ax.annotate(other_treat.get_name_short(), xy=(max_generation, lbls_y), xytext=(lbls_x, lbls_y), annotation_clip=False, verticalalignment=lbls_v_align, horizontalalignment='left', rotation=getFloat("sig_treat_lbls_rotate"), size=getInt("sig_treat_lbls_font_size") ) extra_artists[plot_id].append(an) # End of loop operations odd = not odd row_center += ROW_HEIGHT def plot_significance(gs, data_intr): print("Calculating significance...") for i in range(len(getList("to_plot"))): for j in range(len(getList("comparison_main"))): add_significance_bar(i, gs, data_intr, j) print("Calculating significance done.") ###################### ### CONFIGURE PLOTS ## ###################### def setup_plots(nr_of_generations): """ A setup for the different plots (both the main plot and the small bar at the bottom). """ # Setup the matplotlib params preamble=[r'\usepackage[T1]{fontenc}', r'\usepackage{amsmath}', r'\usepackage{txfonts}', r'\usepackage{textcomp}'] matplotlib.rc('font', **{'family':'sans-serif', 'sans-serif':['Helvetica']}) matplotlib.rc('text.latex', preamble=preamble) params = {'backend': 'pdf', 'axes.labelsize': getInt("font_size"), 'font.size': getInt("font_size"), 'legend.fontsize': getInt("legend_font_size"), 'xtick.labelsize': getInt("tick_font_size"), 'ytick.labelsize': getInt("tick_font_size"), 'text.usetex': latex_available()} matplotlib.rcParams.update(params) # If we want to plot significance indicators we have to make an additional # box below the plot if getBool("sig"): ratios = [10] nr_of_comparisons = len(getList("comparison_main")) for i in range(nr_of_comparisons): ratios.append(getFloat("comparison_height", i)) high_level_ratios = [ratios[0], sum(ratios[1:])] #gs = gridspec.GridSpec(1 + nr_of_comparisons, 1, height_ratios=ratios) main_plot_gridspec = gridspec.GridSpec( 2, 1, height_ratios=high_level_ratios, hspace=getFloat("box_margin_before")) sig_indicator_gridspec = gridspec.GridSpecFromSubplotSpec( nr_of_comparisons, 1, subplot_spec=main_plot_gridspec[1], height_ratios=ratios[1:], hspace=getFloat("box_margin_between")) #gs.update(hspace=getFloat("box_margin_before")) #gs1.update(hspace=getFloat("box_margin_between")) else: main_plot_gridspec = gridspec.GridSpec(1, 1) sig_indicator_gridspec = None # Set all labels and limits for the main window (gs[0]) for i in range(len(getList("to_plot"))): plot_id = getInt("to_plot", i) fig = plt.figure(plot_id, figsize=getFloatPair("fig_size")) ax = fig.add_subplot(main_plot_gridspec[0]) ax.set_ylabel(getStr("y_labels", i)) if getExists("y_axis_min", i) and getExists("y_axis_max", i): ax.set_ylim(getFloat("y_axis_min", i), getFloat("y_axis_max", i)) x_max = nr_of_generations x_min = 0 if getExists("x_axis_max"): x_max = getFloat("x_axis_max") if getExists("x_axis_min"): x_min = getFloat("x_axis_min") ax.set_xlim(x_min, x_max) ax.set_xlabel(getStrDefaultFirst("x_labels", i)) if getBool("sig"): ax.tick_params(labelbottom=False) ax.set_xlabel("") ax.tick_params(axis='x', bottom='off') else: ax.set_xlabel(getStrDefaultFirst("x_labels", i)) if getBool("title"): plt.title(getStr("titles", i), fontsize=getInt("title_size")) if getExists("x_ticks"): ax.set_xticks(getIntList("x_ticks")) return sig_indicator_gridspec def write_plots(): print("Writing plots...") output_dir = getStr("output_directory") ext = "." + getStr("type") if not os.path.exists(output_dir): os.makedirs(output_dir) for i in range(len(getList("to_plot"))): print("Writing plot " + str(i) + " ...") plot_id = getInt("to_plot", i) fig = plt.figure(plot_id) ax = fig.get_axes()[0] #if getFloat("box_sep") == 0: # plt.tight_layout() if getStr("legend_loc", i) != "none": loc = getStr("legend_loc", i) columns = getInt("legend_columns") anchor_x = getFloat("legend_x_offset") anchor_y = getFloat("legend_y_offset") debug_print("legend", "location:", loc, "columns:", columns , "anchor x:", anchor_x, "anchor y:", anchor_y) lgd = ax.legend(loc=loc, ncol=columns, bbox_to_anchor=(anchor_x, anchor_y, 1, 1), labelspacing=0.1) extra_artists[plot_id].append(lgd) # Determine custom bounding box if getStr("bb") == "custom": fig_size = getFloatPair("fig_size") renderer = get_renderer(fig) bb = fig.get_window_extent(renderer) bb = fig.get_tightbbox(renderer) target_bb = matplotlib.transforms.Bbox.from_bounds(0,0, fig_size[0], fig_size[1]) trans2 = matplotlib.transforms.BboxTransformTo(target_bb) trans = fig.transFigure.inverted() print("Figure size:", fig_size) print("Original bb box:", bb.get_points()) for artist in extra_artists[plot_id]: other_bb = artist.get_window_extent(renderer) other_bb = other_bb.transformed(trans) other_bb = other_bb.transformed(trans2) print(other_bb.get_points()) bb = matplotlib.transforms.BboxBase.union([bb, other_bb]) target_aspect = fig_size[0] / fig_size[1] bb_aspect = bb.width / bb.height print(target_aspect, bb_aspect) if target_aspect < bb_aspect: bb = bb.expanded(1, bb_aspect / target_aspect) else: bb = bb.expanded(target_aspect / bb_aspect, 1) bb = bb.padded(0.2) print("Extended bb box:", bb.get_points()) plt.savefig(output_dir + "/" + getStr("file_names", i) + ext, bbox_extra_artists=extra_artists[plot_id], bbox_inches=bb) elif getStr("bb") == "manual": fig_size = getFloatPair("fig_size") renderer = get_renderer(fig) ext_width = getFloat("bb_width") ext_heigth = getFloat("bb_height") x_offset = getFloat("bb_x_offset") y_offset = getFloat("bb_y_offset") x_tight_center = getFloat("bb_x_center_includes_labels") y_tight_center = getFloat("bb_y_center_includes_labels") # Get the transformations that we need inches_to_pixels = fig.dpi_scale_trans pixels_to_inches = inches_to_pixels.inverted() # Get the bounding box of the window win_bb_in_pixels = fig.get_window_extent(renderer) # Get the bounding box of the actual figure, including labels fig_bb_in_inches = fig.get_tightbbox(renderer) fig_bb_in_pixels = fig_bb_in_inches.transformed(inches_to_pixels) # Get a new bounding box just as wide as the window, but with the # center of the figure bounding box new_bb_in_pixels = win_bb_in_pixels.frozen() if x_tight_center: width_ratio = win_bb_in_pixels.width / fig_bb_in_pixels.width new_bb_in_pixels.x0 = fig_bb_in_pixels.x0 new_bb_in_pixels.x1 = fig_bb_in_pixels.x1 new_bb_in_pixels = new_bb_in_pixels.expanded(width_ratio, 1) if y_tight_center: height_ratio = win_bb_in_pixels.height / fig_bb_in_pixels.height new_bb_in_pixels.y0 = fig_bb_in_pixels.y0 new_bb_in_pixels.y1 = fig_bb_in_pixels.y1 new_bb_in_pixels = new_bb_in_pixels.expanded(1, height_ratio) # Transform to inch space bb_in_inches = new_bb_in_pixels.transformed(pixels_to_inches) # Apply custom transformations bb_in_inches = bb_in_inches.expanded( float(ext_width)/float(fig_size[0]), float(ext_heigth)/float(fig_size[1])) bb_in_inches.y0 += y_offset bb_in_inches.y1 += y_offset bb_in_inches.x0 += x_offset bb_in_inches.x1 += x_offset plt.savefig(output_dir + "/" + getStr("file_names", i) + ext, bbox_extra_artists=extra_artists[plot_id], bbox_inches=bb_in_inches) elif getStr("bb") == "default": plt.savefig(output_dir + "/" + getStr("file_names", i) + ext, bbox_extra_artists=extra_artists[plot_id]) elif getStr("bb") == "tight": plt.savefig(output_dir + "/" + getStr("file_names", i) + ext, bbox_extra_artists=extra_artists[plot_id], bbox_inches='tight') else: raise Exception("Invalid bounding box option.") print("Writing plot " + str(i) + " done.") ###################### #### PARSE OPTIONS ### ###################### def parse_options(): parse_global_options() treatment_list = TreatmentList() for i in range(len(getList("input_directories"))): if getBool("one_value_per_dir"): if len(treatment_list) < 1: treatment_list.add_treatment(getStr("input_directories", i), getStr("treatment_names", i), getStr("treatment_names_short", i)) else: treatment_list[0].add_dir(getStr("input_directories", i)) else: treatment_list.add_treatment(getStr("input_directories", i), getStr("treatment_names", i), getStr("treatment_names_short", i)) for i in range(len(getList("file"))): treatment_list.add_treatment(getStr("file", i), getStr("treatment_names", i), getStr("treatment_names_short", i)) if len(treatment_list) < 1: print("No treatments provided") sys.exit(1) if len(treatment_list) == 1: setGlb("sig", [False]) if not getExists("comparison_cache"): setGlb("comparison_cache", [getStr("output_directory") + "/comparison.cache"]) data_intr = DataOfInterest(treatment_list) if not getExists("marker_step"): setGlb("marker_step", [int(data_intr.get_max_generation()/10)]) return treatment_list, data_intr ###################### ######## MAIN ######## ###################### def main(): treatment_list, data_of_interest = parse_options() sig_indicator_gridspec = setup_plots(data_of_interest.get_max_generation()) #Plot all treatments create_plots(data_of_interest) #Plots the dots indicating significance if getBool("sig"): plot_significance(sig_indicator_gridspec, data_of_interest) #Writes the plots to disk write_plots() if __name__ == '__main__': main()
mit
exowanderer/SpitzerDeepLearningNetwork
Python Scripts/spitzer_cal_NALU_train.py
1
15910
from multiprocessing import set_start_method, cpu_count #set_start_method('forkserver') import os os.environ["OMP_NUM_THREADS"] = str(cpu_count()) # or to whatever you want from argparse import ArgumentParser from datetime import datetime from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score from sklearn.utils import shuffle from tqdm import tqdm import pandas as pd import numpy as np import tensorflow as tf import nalu time_now = datetime.utcnow().strftime("%Y%m%d%H%M%S") def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') def chisq(y_true, y_pred, y_error): return np.sum(((y_true-y_pred)/y_error)**2.) ap = ArgumentParser() ap.add_argument('-d', '--directory', type=str, required=False, default='nalu_tf_save_dir/saves_{}'.format(time_now), help='The tensorflow ckpt save file.') ap.add_argument('-nnl', '--n_nalu_layers', type=int, required=False, default=1, help='Whether to use 1 (default), 2, or ... N NALU layers.') ap.add_argument('-nnn', '--n_nalu_neurons', type=int, required=False, default=0, help='How many features on the second NALU layer.') ap.add_argument('-ne', '--n_epochs', type=int, required=False, default=200, help='Number of N_EPOCHS to train the network with.') ap.add_argument('-nc', '--n_classes', type=int, required=False, default=1, help='n_classes == 1 for Regression (default); > 1 for Classification.') ap.add_argument('-bs', '--batch_size', type=int, required=False, default=32, help='Batch size: number of samples per batch.') ap.add_argument('-lr', '--learning_rate', type=float, required=False, default=1e-3, help='Learning rate: how fast the optimizer moves up/down the gradient.') ap.add_argument('-ts', '--test_size', type=float, required=False, default=0.75, help='How much to split the train / test ratio.') ap.add_argument('-rs', '--random_state', type=int, required=False, default=42, help='Integer value to initialize train/test splitting randomization.') ap.add_argument('-pp', '--pre_process', type=str2bool, nargs='?', required=False, default=True, help='Toggle whether to MinMax-preprocess the features.') ap.add_argument('-pca', '--pca_transform', type=str2bool, nargs='?', required=False, default=True, help='Toggle whether to PCA-pretransform the features.') ap.add_argument('-v', '--verbose', type=str2bool, nargs='?', required=False, default=False, help='Whether to set verbosity = True or False (default).') ap.add_argument('-ds', '--data_set', type=str, required=False, default='', help='The csv file containing the data with which to train.') try: args = vars(ap.parse_args()) except Exception as e: print('Error: {}'.format(e)) args = {} args['directory'] = ap.get_default('directory') args['n_nalu_layers'] = ap.get_default('n_nalu_layers') args['n_nalu_neurons'] = ap.get_default('n_nalu_neurons') args['n_epochs'] = ap.get_default('n_epochs') args['n_classes'] = ap.get_default('n_classes') args['batch_size'] = ap.get_default('batch_size') args['learning_rate'] = ap.get_default('learning_rate') args['test_size'] = ap.get_default('test_size') args['random_state'] = ap.get_default('random_state') args['pre_process'] = ap.get_default('pre_process') args['pca_transform'] = ap.get_default('pca_transform') args['verbose'] = ap.get_default('verbose') args['data_set'] = ap.get_default('data_set') DO_PP = args['pre_process'] DO_PCA = args['pca_transform'] verbose = args['verbose'] data_set_fname = args['data_set'] ''' print("loading pipelines on disk vis joblib.") full_pipe = joblib.load('pmap_full_pipe_transformer_16features.joblib.save') std_scaler_from_raw = joblib.load('pmap_standard_scaler_transformer_16features.joblib.save') pca_transformer_from_std_scaled = joblib.load('pmap_pca_transformer_from_stdscaler_16features.joblib.save') minmax_scaler_transformer_raw = joblib.load('pmap_minmax_scaler_transformer_from_raw_16features.joblib.save') minmax_scaler_transformer_pca = joblib.load('pmap_minmax_scaler_transformer_from_pca_16features.joblib.save') ''' label_n_error_filename = 'pmap_raw_labels_and_errors.csv' print("Loading in raw labels and errors from {}".format(label_n_error_filename)) labels_df = pd.read_csv(label_n_error_filename) labels = labels_df['Flux'].values[:,None] labels_err = labels_df['Flux_err'].values # Feature File Switch if DO_PP and DO_PCA: features_input_filename = 'pmap_full_pipe_transformed_16features.csv' elif DO_PP: features_input_filename = 'pmap_minmax_transformed_from_raw_16features.csv' elif DO_PCA: features_input_filename = 'pmap_pca_transformed_from_stdscaler_16features.csv' else: features_input_filename = 'pmap_raw_16features.csv' print("Loading in pre-processed features from {}".format(features_input_filename)) features_input = pd.read_csv(feature_input_filename).drop(['idx'], axis=1).values def nalu(input_layer, num_outputs): """ Neural Arithmetic Logic Unit tesnorflow layer Arguments: input_layer - A Tensor representing previous layer num_outputs - number of ouput units Returns: A tensor representing the output of NALU """ shape = (int(input_layer.shape[-1]), num_outputs) # define variables W_hat = tf.Variable(tf.truncated_normal(shape, stddev=0.02)) M_hat = tf.Variable(tf.truncated_normal(shape, stddev=0.02)) G = tf.Variable(tf.truncated_normal(shape, stddev=0.02)) # operations according to paper W = tf.tanh(W_hat) * tf.sigmoid(M_hat) m = tf.exp(tf.matmul(tf.log(tf.abs(input_layer) + 1e-7), W)) g = tf.sigmoid(tf.matmul(input_layer, G)) a = tf.matmul(input_layer, W) out = g * a + (1 - g) * m return out if __name__ == "__main__": N_FEATURES = features_input.shape[-1] EXPORT_DIR = args['directory'] N_NALU_LAYERS = args['n_nalu_layers'] N_NALU_NEURONS = args['n_nalu_neurons'] if args['n_nalu_neurons'] > 0 else N_FEATURES N_CLASSES = args['n_classes'] # = 1 for regression TEST_SIZE = args['test_size'] RANDOM_STATE = args['random_state'] N_EPOCHS = args['n_epochs'] LEARNING_RATE = args['learning_rate'] BATCH_SIZE = args['batch_size'] EXPORT_DIR = EXPORT_DIR + '_nnl{}_nnn{}_nc{}_bs{}_lr{}_ne{}_ts{}_rs{}_PP{}_PCA{}/'.format(N_NALU_LAYERS, N_NALU_NEURONS, N_CLASSES, BATCH_SIZE, LEARNING_RATE, N_EPOCHS, TEST_SIZE, RANDOM_STATE, {True:1, False:0}[DO_PP], {True:1, False:0}[DO_PCA]) print("Saving models to path: {}".format(EXPORT_DIR)) idx_train, idx_test = train_test_split(np.arange(labels.size), test_size=TEST_SIZE, random_state=RANDOM_STATE) X_data, Y_data = features_input[idx_train], labels[idx_train]#[:,None] LAST_BIT = X_data.shape[0]-BATCH_SIZE*(X_data.shape[0]//BATCH_SIZE) # Force integer number of batches total by dropping last "<BATCH_SIEZ" number of samples X_data_use = X_data[:-LAST_BIT].copy() Y_data_use = Y_data[:-LAST_BIT].copy() output_dict = {} output_dict['loss'] = np.zeros(N_EPOCHS) output_dict['accuracy'] = np.zeros(N_EPOCHS) output_dict['R2_train'] = np.zeros(N_EPOCHS) output_dict['R2_test'] = np.zeros(N_EPOCHS) output_dict['chisq_train'] = np.zeros(N_EPOCHS) output_dict['chisq_test'] = np.zeros(N_EPOCHS) with tf.device("/cpu:0"): # tf.reset_default_graph() # define placeholders and network X = tf.placeholder(tf.float32, shape=[None, N_FEATURES]) Y_true = tf.placeholder(tf.float32, shape=[None, 1]) # Setup NALU Layers nalu_layers = {'nalu0':nalu(X,N_NALU_NEURONS)} for kn in range(1, N_NALU_LAYERS): #with tf.name_scope('nalu{}'.format(kn)): nalu_layers['nalu{}'.format(kn)] = nalu(nalu_layers['nalu{}'.format(kn-1)], N_NALU_NEURONS) # with tf.name_scope("output"): Y_pred = nalu(nalu_layers['nalu{}'.format(N_NALU_LAYERS-1)], N_CLASSES) # N_CLASSES = 1 for regression #with tf.name_scope('loss'): # loss and train operations loss = tf.nn.l2_loss(Y_pred - Y_true) # NALU uses mse optimizer = tf.train.AdamOptimizer(LEARNING_RATE) train_op = optimizer.minimize(loss) # Add an op to initialize the variables. init_op = tf.global_variables_initializer() # Add ops to save and restore all the variables. saver = tf.train.Saver()#max_to_keep=N_EPOCHS) sess_config = tf.ConfigProto( device_count={"CPU": cpu_count()}, inter_op_parallelism_threads=cpu_count(), intra_op_parallelism_threads=cpu_count()) """ with tf.name_scope("eval"): ''' Tensorboard Redouts''' ''' Training R-Squared Score''' total_error = tf.reduce_sum(tf.square(tf.subtract(Y_true, tf.reduce_mean(Y_true)))) unexplained_error = tf.reduce_sum(tf.square(tf.subtract(Y_true, Y_pred))) R_squared = tf.subtract(1.0, tf.div(unexplained_error, total_error)) # ''' Testing R-Squared Score''' # Y_pred_test = Y_pred.eval(feed_dict={X: features[idx_test]}) # total_error_test = tf.reduce_sum(tf.square(tf.subtract(Y_data_use, tf.reduce_mean(Y_data_use)))) # unexplained_error_test = tf.reduce_sum(tf.square(tf.subtract(Y_data_use, Y_pred_test))) # R_squared_test = tf.subtract(1, tf.div(unexplained_error, total_error)) ''' Loss and RMSE ''' squared_error = tf.square(tf.subtract(Y_true, Y_pred)) loss = tf.reduce_sum(tf.sqrt(tf.cast(squared_error, tf.float32))) rmse = tf.sqrt(tf.reduce_mean(tf.cast(squared_error, tf.float32))) with tf.name_scope("summary"): ''' Declare Scalar Tensorboard Terms''' tf.summary.scalar('loss', loss) tf.summary.scalar('RMSE', rmse) tf.summary.scalar('R_sqrd', R_squared) ''' Declare Histogram Tensorboard Terms''' # Squared Error Histogram tf.summary.histogram('SqErr Hist', squared_error) # NALU Layers Histogram for kn in range(N_NALU_LAYERS): tf.summary.histogram('NALU{}'.format(kn), nalu_layers['nalu{}'.format(kn)]) ''' Merge all the summaries and write them out to `export_dir` + `/logs_train_`time_now`` ''' merged = tf.summary.merge_all() """ with tf.Session(config=sess_config) as sess: ''' Output all summaries to `export_dir` + `/logs_train_`time_now`` ''' train_writer = tf.summary.FileWriter(EXPORT_DIR + '/logs_train_{}'.format(time_now),sess.graph) ''' END Tensorboard Readout Step''' sess.run(init_op) best_test_r2 = 0 for ep in tqdm(range(N_EPOCHS)): i = 0 gts = 0 # Reshuffle features and labels together X_data_use, Y_data_use = shuffle(X_data_use, Y_data_use) for k in tqdm(range(len(X_data_use)//BATCH_SIZE)): batch_now = range(k*BATCH_SIZE, (k+1)*BATCH_SIZE) # xs, ys = X_data_use[i:i+BATCH_SIZE], Y_data_use[i:i+BATCH_SIZE] xs, ys = X_data_use[batch_now], Y_data_use[batch_now] _, ys_pred, l = sess.run([train_op, Y_pred, loss], feed_dict={X: xs, Y_true: ys}) # calculate number of correct predictions from batch gts += np.sum(np.isclose(ys, ys_pred, atol=1e-4, rtol=1e-4)) ytest_pred = Y_pred.eval(feed_dict={X: features_input[idx_test]}) if np.isnan(ytest_pred).any(): ytest_pred = median_sub_nan(ytest_pred) test_r2 = r2_score(labels[idx_test], ytest_pred)#[:,None] # print("Test R2 Score: {}".format(test_r2_score)) acc = gts/len(Y_data_use) train_r2 = r2_score(ys, ys_pred) print('\nepoch {}, loss: {:.5}, accuracy: {:.5}, Batch R2: {:.5}, Test R2: {:.5}'.format(ep, l, acc, train_r2, test_r2)) """ output_dict['loss'][ep] = l output_dict['accuracy'][ep] = acc output_dict['R2_train'][ep] = train_r2 output_dict['R2_test'][ep] = test_r2 output_dict['chisq_train'][ep] = chisq(ys.flatten(), ys_pred.flatten(), labels_err[i:i+BATCH_SIZE]) output_dict['chisq_test'][ep] = chisq(labels[idx_test], ytest_pred.flatten(), labels_err[idx_test]) """ if verbose: print('Saving Default to Disk') now_save_name = EXPORT_DIR + "model_epoch{}_l{:.5}_a{:.5}_BatchR2-{:.5}_TestR2-{:.5}.ckpt".format( ep, l, acc, train_r2, test_r2) save_path = saver.save(sess, now_save_name) if test_r2 >= best_test_r2: if verbose: print('Saving Best to Disk') best_test_r2 = test_r2 ''' Store the Best Scored Test-R2 ''' best_save_name = EXPORT_DIR + "best_test_r2/model_epoch{}_l{:.5}_a{:.5}_BatchR2-{:.5}_TestR2-{:.5}.ckpt".format( ep, l, acc, train_r2, test_r2) save_path = saver.save(sess, best_save_name) ep = '_FINAL' final_save_name = EXPORT_DIR+ "model_epoch{}_l{:.5}_a{:.5}_BatchR2-{:.5}_TestR2-{:.5}.ckpt".format( ep, l, acc, train_r2, test_r2) save_path = saver.save(sess, final_save_name) print("Model saved in path: {}".format(save_path)) """ try: pd.DataFrame(output_dict, index=range(N_EPOCHS)).to_csv(EXPORT_DIR+ "model_loss_acc_BatchR2_TestR2_DataFrame.csv") except Exception as e: print('DataFrame to CSV broke because', str(e)) """ ''' with tf.name_scope("loss"): def tf_nll(labels, output, uncs, coeff=1): error = output - labels return tf.reduce_sum(tf.divide(tf.squared_difference(output, labels) , tf.square(uncs)))# + tf.log(tf.square(uncs)) #return tf.reduce_sum(1 * (coeff * np.log(2*np.pi) + coeff * tf.log(uncs) + (0.5/uncs) * tf.pow(error, 2))) negloglike = tf_nll(labels=y, output=output, uncs=unc) reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) loss = tf.add_n([negloglike] + reg_losses, name="chisq") with tf.name_scope("eval"): accuracy = tf.reduce_mean(tf.squared_difference(output, y, name="accuracy")) SqErrRatio= tf.divide(accuracy, tf.reduce_mean(tf.squared_difference(y, tf.reduce_mean(y)))) r2_acc = 1.0 - SqErrRatio chsiqMean = tf_nll(labels=y, output=tf.reduce_mean(y), uncs=unc) chisqModel= tf_nll(labels=y, output=output, uncs=unc) rho2_acc = 1.0 - chisqModel / chsiqMean" mse_summary = tf.summary.scalar('train_acc' , accuracy ) loss_summary = tf.summary.scalar('loss' , loss ) nll_summary = tf.summary.scalar('negloglike', negloglike) r2s_summary = tf.summary.scalar('r2_acc' , r2_acc ) p2s_summary = tf.summary.scalar('rho2_acc' , rho2_acc ) val_summary = tf.summary.scalar('val_acc' , accuracy ) # hid1_hist = tf.summary.histogram('hidden1', hidden1) # hid2_hist = tf.summary.histogram('hidden1', hidden1) # hid3_hist = tf.summary.histogram('hidden1', hidden1) file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph()) '''
mit
Unidata/MetPy
v1.0/_downloads/6405360ec40d7796ed64eb783f2ffe55/NEXRAD_Level_2_File.py
7
2016
# Copyright (c) 2015,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """ NEXRAD Level 2 File =================== Use MetPy to read information from a NEXRAD Level 2 (volume) file and plot """ import matplotlib.pyplot as plt import numpy as np from metpy.cbook import get_test_data from metpy.io import Level2File from metpy.plots import add_metpy_logo, add_timestamp ########################################### # Open the file name = get_test_data('KTLX20130520_201643_V06.gz', as_file_obj=False) f = Level2File(name) print(f.sweeps[0][0]) ########################################### # Pull data out of the file sweep = 0 # First item in ray is header, which has azimuth angle az = np.array([ray[0].az_angle for ray in f.sweeps[sweep]]) # 5th item is a dict mapping a var name (byte string) to a tuple # of (header, data array) ref_hdr = f.sweeps[sweep][0][4][b'REF'][0] ref_range = np.arange(ref_hdr.num_gates) * ref_hdr.gate_width + ref_hdr.first_gate ref = np.array([ray[4][b'REF'][1] for ray in f.sweeps[sweep]]) rho_hdr = f.sweeps[sweep][0][4][b'RHO'][0] rho_range = (np.arange(rho_hdr.num_gates + 1) - 0.5) * rho_hdr.gate_width + rho_hdr.first_gate rho = np.array([ray[4][b'RHO'][1] for ray in f.sweeps[sweep]]) ########################################### fig, axes = plt.subplots(1, 2, figsize=(15, 8)) add_metpy_logo(fig, 190, 85, size='large') for var_data, var_range, ax in zip((ref, rho), (ref_range, rho_range), axes): # Turn into an array, then mask data = np.ma.array(var_data) data[np.isnan(data)] = np.ma.masked # Convert az,range to x,y xlocs = var_range * np.sin(np.deg2rad(az[:, np.newaxis])) ylocs = var_range * np.cos(np.deg2rad(az[:, np.newaxis])) # Plot the data ax.pcolormesh(xlocs, ylocs, data, cmap='viridis') ax.set_aspect('equal', 'datalim') ax.set_xlim(-40, 20) ax.set_ylim(-30, 30) add_timestamp(ax, f.dt, y=0.02, high_contrast=True) plt.show()
bsd-3-clause
evidation-health/bokeh
bokeh/tests/test_protocol.py
42
3959
from __future__ import absolute_import import unittest from unittest import skipIf import numpy as np try: import pandas as pd is_pandas = True except ImportError as e: is_pandas = False class TestBokehJSONEncoder(unittest.TestCase): def setUp(self): from bokeh.protocol import BokehJSONEncoder self.encoder = BokehJSONEncoder() def test_fail(self): self.assertRaises(TypeError, self.encoder.default, {'testing': 1}) @skipIf(not is_pandas, "pandas does not work in PyPy.") def test_panda_series(self): s = pd.Series([1, 3, 5, 6, 8]) self.assertEqual(self.encoder.default(s), [1, 3, 5, 6, 8]) def test_numpyarray(self): a = np.arange(5) self.assertEqual(self.encoder.default(a), [0, 1, 2, 3, 4]) def test_numpyint(self): npint = np.asscalar(np.int64(1)) self.assertEqual(self.encoder.default(npint), 1) self.assertIsInstance(self.encoder.default(npint), int) def test_numpyfloat(self): npfloat = np.float64(1.33) self.assertEqual(self.encoder.default(npfloat), 1.33) self.assertIsInstance(self.encoder.default(npfloat), float) def test_numpybool_(self): nptrue = np.bool_(True) self.assertEqual(self.encoder.default(nptrue), True) self.assertIsInstance(self.encoder.default(nptrue), bool) @skipIf(not is_pandas, "pandas does not work in PyPy.") def test_pd_timestamp(self): ts = pd.tslib.Timestamp('April 28, 1948') self.assertEqual(self.encoder.default(ts), -684115200000) class TestSerializeJson(unittest.TestCase): def setUp(self): from bokeh.protocol import serialize_json, deserialize_json self.serialize = serialize_json self.deserialize = deserialize_json def test_with_basic(self): self.assertEqual(self.serialize({'test': [1, 2, 3]}), '{"test": [1, 2, 3]}') def test_with_np_array(self): a = np.arange(5) self.assertEqual(self.serialize(a), '[0, 1, 2, 3, 4]') @skipIf(not is_pandas, "pandas does not work in PyPy.") def test_with_pd_series(self): s = pd.Series([0, 1, 2, 3, 4]) self.assertEqual(self.serialize(s), '[0, 1, 2, 3, 4]') def test_nans_and_infs(self): arr = np.array([np.nan, np.inf, -np.inf, 0]) serialized = self.serialize(arr) deserialized = self.deserialize(serialized) assert deserialized[0] == 'NaN' assert deserialized[1] == 'Infinity' assert deserialized[2] == '-Infinity' assert deserialized[3] == 0 @skipIf(not is_pandas, "pandas does not work in PyPy.") def test_nans_and_infs_pandas(self): arr = pd.Series(np.array([np.nan, np.inf, -np.inf, 0])) serialized = self.serialize(arr) deserialized = self.deserialize(serialized) assert deserialized[0] == 'NaN' assert deserialized[1] == 'Infinity' assert deserialized[2] == '-Infinity' assert deserialized[3] == 0 @skipIf(not is_pandas, "pandas does not work in PyPy.") def test_datetime_types(self): """should convert to millis """ idx = pd.date_range('2001-1-1', '2001-1-5') df = pd.DataFrame({'vals' :idx}, index=idx) serialized = self.serialize({'vals' : df.vals, 'idx' : df.index}) deserialized = self.deserialize(serialized) baseline = {u'vals': [978307200000, 978393600000, 978480000000, 978566400000, 978652800000], u'idx': [978307200000, 978393600000, 978480000000, 978566400000, 978652800000] } assert deserialized == baseline if __name__ == "__main__": unittest.main()
bsd-3-clause
chilang/zeppelin
python/src/main/resources/python/bootstrap_sql.py
60
1189
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Setup SQL over Pandas DataFrames # It requires next dependencies to be installed: # - pandas # - pandasql from __future__ import print_function try: from pandasql import sqldf pysqldf = lambda q: sqldf(q, globals()) except ImportError: pysqldf = lambda q: print("Can not run SQL over Pandas DataFrame" + "Make sure 'pandas' and 'pandasql' libraries are installed")
apache-2.0
tangyouze/tushare
tushare/stock/shibor.py
38
5010
# -*- coding:utf-8 -*- """ 上海银行间同业拆放利率(Shibor)数据接口 Created on 2014/07/31 @author: Jimmy Liu @group : waditu @contact: jimmysoa@sina.cn """ import pandas as pd import numpy as np from tushare.stock import cons as ct from tushare.util import dateu as du def shibor_data(year=None): """ 获取上海银行间同业拆放利率(Shibor) Parameters ------ year:年份(int) Return ------ date:日期 ON:隔夜拆放利率 1W:1周拆放利率 2W:2周拆放利率 1M:1个月拆放利率 3M:3个月拆放利率 6M:6个月拆放利率 9M:9个月拆放利率 1Y:1年拆放利率 """ year = du.get_year() if year is None else year lab = ct.SHIBOR_TYPE['Shibor'] lab = lab.encode('utf-8') if ct.PY3 else lab try: df = pd.read_excel(ct.SHIBOR_DATA_URL%(ct.P_TYPE['http'], ct.DOMAINS['shibor'], ct.PAGES['dw'], 'Shibor', year, lab, year)) df.columns = ct.SHIBOR_COLS df['date'] = df['date'].map(lambda x: x.date()) df['date'] = df['date'].astype(np.datetime64) return df except: return None def shibor_quote_data(year=None): """ 获取Shibor银行报价数据 Parameters ------ year:年份(int) Return ------ date:日期 bank:报价银行名称 ON:隔夜拆放利率 ON_B:隔夜拆放买入价 ON_A:隔夜拆放卖出价 1W_B:1周买入 1W_A:1周卖出 2W_B:买入 2W_A:卖出 1M_B:买入 1M_A:卖出 3M_B:买入 3M_A:卖出 6M_B:买入 6M_A:卖出 9M_B:买入 9M_A:卖出 1Y_B:买入 1Y_A:卖出 """ year = du.get_year() if year is None else year lab = ct.SHIBOR_TYPE['Quote'] lab = lab.encode('utf-8') if ct.PY3 else lab try: df = pd.read_excel(ct.SHIBOR_DATA_URL%(ct.P_TYPE['http'], ct.DOMAINS['shibor'], ct.PAGES['dw'], 'Quote', year, lab, year), skiprows=[0]) df.columns = ct.QUOTE_COLS df['date'] = df['date'].map(lambda x: x.date()) df['date'] = df['date'].astype(np.datetime64) return df except: return None def shibor_ma_data(year=None): """ 获取Shibor均值数据 Parameters ------ year:年份(int) Return ------ date:日期 其它分别为各周期5、10、20均价 """ year = du.get_year() if year is None else year lab = ct.SHIBOR_TYPE['Tendency'] lab = lab.encode('utf-8') if ct.PY3 else lab try: df = pd.read_excel(ct.SHIBOR_DATA_URL%(ct.P_TYPE['http'], ct.DOMAINS['shibor'], ct.PAGES['dw'], 'Shibor_Tendency', year, lab, year), skiprows=[0]) df.columns = ct.SHIBOR_MA_COLS df['date'] = df['date'].map(lambda x: x.date()) df['date'] = df['date'].astype(np.datetime64) return df except: return None def lpr_data(year=None): """ 获取贷款基础利率(LPR) Parameters ------ year:年份(int) Return ------ date:日期 1Y:1年贷款基础利率 """ year = du.get_year() if year is None else year lab = ct.SHIBOR_TYPE['LPR'] lab = lab.encode('utf-8') if ct.PY3 else lab try: df = pd.read_excel(ct.SHIBOR_DATA_URL%(ct.P_TYPE['http'], ct.DOMAINS['shibor'], ct.PAGES['dw'], 'LPR', year, lab, year)) df.columns = ct.LPR_COLS df['date'] = df['date'].map(lambda x: x.date()) df['date'] = df['date'].astype(np.datetime64) return df except: return None def lpr_ma_data(year=None): """ 获取贷款基础利率均值数据 Parameters ------ year:年份(int) Return ------ date:日期 1Y_5:5日均值 1Y_10:10日均值 1Y_20:20日均值 """ year = du.get_year() if year is None else year lab = ct.SHIBOR_TYPE['LPR_Tendency'] lab = lab.encode('utf-8') if ct.PY3 else lab try: df = pd.read_excel(ct.SHIBOR_DATA_URL%(ct.P_TYPE['http'], ct.DOMAINS['shibor'], ct.PAGES['dw'], 'LPR_Tendency', year, lab, year), skiprows=[0]) df.columns = ct.LPR_MA_COLS df['date'] = df['date'].map(lambda x: x.date()) df['date'] = df['date'].astype(np.datetime64) return df except: return None
bsd-3-clause
vibhorag/scikit-learn
sklearn/utils/tests/test_multiclass.py
128
12853
from __future__ import division import numpy as np import scipy.sparse as sp from itertools import product from sklearn.externals.six.moves import xrange from sklearn.externals.six import iteritems from scipy.sparse import issparse from scipy.sparse import csc_matrix from scipy.sparse import csr_matrix from scipy.sparse import coo_matrix from scipy.sparse import dok_matrix from scipy.sparse import lil_matrix from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regex from sklearn.utils.multiclass import unique_labels from sklearn.utils.multiclass import is_multilabel from sklearn.utils.multiclass import type_of_target from sklearn.utils.multiclass import class_distribution class NotAnArray(object): """An object that is convertable to an array. This is useful to simulate a Pandas timeseries.""" def __init__(self, data): self.data = data def __array__(self): return self.data EXAMPLES = { 'multilabel-indicator': [ # valid when the data is formated as sparse or dense, identified # by CSR format when the testing takes place csr_matrix(np.random.RandomState(42).randint(2, size=(10, 10))), csr_matrix(np.array([[0, 1], [1, 0]])), csr_matrix(np.array([[0, 1], [1, 0]], dtype=np.bool)), csr_matrix(np.array([[0, 1], [1, 0]], dtype=np.int8)), csr_matrix(np.array([[0, 1], [1, 0]], dtype=np.uint8)), csr_matrix(np.array([[0, 1], [1, 0]], dtype=np.float)), csr_matrix(np.array([[0, 1], [1, 0]], dtype=np.float32)), csr_matrix(np.array([[0, 0], [0, 0]])), csr_matrix(np.array([[0, 1]])), # Only valid when data is dense np.array([[-1, 1], [1, -1]]), np.array([[-3, 3], [3, -3]]), NotAnArray(np.array([[-3, 3], [3, -3]])), ], 'multiclass': [ [1, 0, 2, 2, 1, 4, 2, 4, 4, 4], np.array([1, 0, 2]), np.array([1, 0, 2], dtype=np.int8), np.array([1, 0, 2], dtype=np.uint8), np.array([1, 0, 2], dtype=np.float), np.array([1, 0, 2], dtype=np.float32), np.array([[1], [0], [2]]), NotAnArray(np.array([1, 0, 2])), [0, 1, 2], ['a', 'b', 'c'], np.array([u'a', u'b', u'c']), np.array([u'a', u'b', u'c'], dtype=object), np.array(['a', 'b', 'c'], dtype=object), ], 'multiclass-multioutput': [ np.array([[1, 0, 2, 2], [1, 4, 2, 4]]), np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.int8), np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.uint8), np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.float), np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.float32), np.array([['a', 'b'], ['c', 'd']]), np.array([[u'a', u'b'], [u'c', u'd']]), np.array([[u'a', u'b'], [u'c', u'd']], dtype=object), np.array([[1, 0, 2]]), NotAnArray(np.array([[1, 0, 2]])), ], 'binary': [ [0, 1], [1, 1], [], [0], np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1]), np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.bool), np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.int8), np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.uint8), np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.float), np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.float32), np.array([[0], [1]]), NotAnArray(np.array([[0], [1]])), [1, -1], [3, 5], ['a'], ['a', 'b'], ['abc', 'def'], np.array(['abc', 'def']), [u'a', u'b'], np.array(['abc', 'def'], dtype=object), ], 'continuous': [ [1e-5], [0, .5], np.array([[0], [.5]]), np.array([[0], [.5]], dtype=np.float32), ], 'continuous-multioutput': [ np.array([[0, .5], [.5, 0]]), np.array([[0, .5], [.5, 0]], dtype=np.float32), np.array([[0, .5]]), ], 'unknown': [ [[]], [()], # sequence of sequences that were'nt supported even before deprecation np.array([np.array([]), np.array([1, 2, 3])], dtype=object), [np.array([]), np.array([1, 2, 3])], [set([1, 2, 3]), set([1, 2])], [frozenset([1, 2, 3]), frozenset([1, 2])], # and also confusable as sequences of sequences [{0: 'a', 1: 'b'}, {0: 'a'}], # empty second dimension np.array([[], []]), # 3d np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]), ] } NON_ARRAY_LIKE_EXAMPLES = [ set([1, 2, 3]), {0: 'a', 1: 'b'}, {0: [5], 1: [5]}, 'abc', frozenset([1, 2, 3]), None, ] MULTILABEL_SEQUENCES = [ [[1], [2], [0, 1]], [(), (2), (0, 1)], np.array([[], [1, 2]], dtype='object'), NotAnArray(np.array([[], [1, 2]], dtype='object')) ] def test_unique_labels(): # Empty iterable assert_raises(ValueError, unique_labels) # Multiclass problem assert_array_equal(unique_labels(xrange(10)), np.arange(10)) assert_array_equal(unique_labels(np.arange(10)), np.arange(10)) assert_array_equal(unique_labels([4, 0, 2]), np.array([0, 2, 4])) # Multilabel indicator assert_array_equal(unique_labels(np.array([[0, 0, 1], [1, 0, 1], [0, 0, 0]])), np.arange(3)) assert_array_equal(unique_labels(np.array([[0, 0, 1], [0, 0, 0]])), np.arange(3)) # Several arrays passed assert_array_equal(unique_labels([4, 0, 2], xrange(5)), np.arange(5)) assert_array_equal(unique_labels((0, 1, 2), (0,), (2, 1)), np.arange(3)) # Border line case with binary indicator matrix assert_raises(ValueError, unique_labels, [4, 0, 2], np.ones((5, 5))) assert_raises(ValueError, unique_labels, np.ones((5, 4)), np.ones((5, 5))) assert_array_equal(unique_labels(np.ones((4, 5)), np.ones((5, 5))), np.arange(5)) def test_unique_labels_non_specific(): # Test unique_labels with a variety of collected examples # Smoke test for all supported format for format in ["binary", "multiclass", "multilabel-indicator"]: for y in EXAMPLES[format]: unique_labels(y) # We don't support those format at the moment for example in NON_ARRAY_LIKE_EXAMPLES: assert_raises(ValueError, unique_labels, example) for y_type in ["unknown", "continuous", 'continuous-multioutput', 'multiclass-multioutput']: for example in EXAMPLES[y_type]: assert_raises(ValueError, unique_labels, example) def test_unique_labels_mixed_types(): # Mix with binary or multiclass and multilabel mix_clf_format = product(EXAMPLES["multilabel-indicator"], EXAMPLES["multiclass"] + EXAMPLES["binary"]) for y_multilabel, y_multiclass in mix_clf_format: assert_raises(ValueError, unique_labels, y_multiclass, y_multilabel) assert_raises(ValueError, unique_labels, y_multilabel, y_multiclass) assert_raises(ValueError, unique_labels, [[1, 2]], [["a", "d"]]) assert_raises(ValueError, unique_labels, ["1", 2]) assert_raises(ValueError, unique_labels, [["1", 2], [1, 3]]) assert_raises(ValueError, unique_labels, [["1", "2"], [2, 3]]) def test_is_multilabel(): for group, group_examples in iteritems(EXAMPLES): if group in ['multilabel-indicator']: dense_assert_, dense_exp = assert_true, 'True' else: dense_assert_, dense_exp = assert_false, 'False' for example in group_examples: # Only mark explicitly defined sparse examples as valid sparse # multilabel-indicators if group == 'multilabel-indicator' and issparse(example): sparse_assert_, sparse_exp = assert_true, 'True' else: sparse_assert_, sparse_exp = assert_false, 'False' if (issparse(example) or (hasattr(example, '__array__') and np.asarray(example).ndim == 2 and np.asarray(example).dtype.kind in 'biuf' and np.asarray(example).shape[1] > 0)): examples_sparse = [sparse_matrix(example) for sparse_matrix in [coo_matrix, csc_matrix, csr_matrix, dok_matrix, lil_matrix]] for exmpl_sparse in examples_sparse: sparse_assert_(is_multilabel(exmpl_sparse), msg=('is_multilabel(%r)' ' should be %s') % (exmpl_sparse, sparse_exp)) # Densify sparse examples before testing if issparse(example): example = example.toarray() dense_assert_(is_multilabel(example), msg='is_multilabel(%r) should be %s' % (example, dense_exp)) def test_type_of_target(): for group, group_examples in iteritems(EXAMPLES): for example in group_examples: assert_equal(type_of_target(example), group, msg=('type_of_target(%r) should be %r, got %r' % (example, group, type_of_target(example)))) for example in NON_ARRAY_LIKE_EXAMPLES: msg_regex = 'Expected array-like \(array or non-string sequence\).*' assert_raises_regex(ValueError, msg_regex, type_of_target, example) for example in MULTILABEL_SEQUENCES: msg = ('You appear to be using a legacy multi-label data ' 'representation. Sequence of sequences are no longer supported;' ' use a binary array or sparse matrix instead.') assert_raises_regex(ValueError, msg, type_of_target, example) def test_class_distribution(): y = np.array([[1, 0, 0, 1], [2, 2, 0, 1], [1, 3, 0, 1], [4, 2, 0, 1], [2, 0, 0, 1], [1, 3, 0, 1]]) # Define the sparse matrix with a mix of implicit and explicit zeros data = np.array([1, 2, 1, 4, 2, 1, 0, 2, 3, 2, 3, 1, 1, 1, 1, 1, 1]) indices = np.array([0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 5, 0, 1, 2, 3, 4, 5]) indptr = np.array([0, 6, 11, 11, 17]) y_sp = sp.csc_matrix((data, indices, indptr), shape=(6, 4)) classes, n_classes, class_prior = class_distribution(y) classes_sp, n_classes_sp, class_prior_sp = class_distribution(y_sp) classes_expected = [[1, 2, 4], [0, 2, 3], [0], [1]] n_classes_expected = [3, 3, 1, 1] class_prior_expected = [[3/6, 2/6, 1/6], [1/3, 1/3, 1/3], [1.0], [1.0]] for k in range(y.shape[1]): assert_array_almost_equal(classes[k], classes_expected[k]) assert_array_almost_equal(n_classes[k], n_classes_expected[k]) assert_array_almost_equal(class_prior[k], class_prior_expected[k]) assert_array_almost_equal(classes_sp[k], classes_expected[k]) assert_array_almost_equal(n_classes_sp[k], n_classes_expected[k]) assert_array_almost_equal(class_prior_sp[k], class_prior_expected[k]) # Test again with explicit sample weights (classes, n_classes, class_prior) = class_distribution(y, [1.0, 2.0, 1.0, 2.0, 1.0, 2.0]) (classes_sp, n_classes_sp, class_prior_sp) = class_distribution(y, [1.0, 2.0, 1.0, 2.0, 1.0, 2.0]) class_prior_expected = [[4/9, 3/9, 2/9], [2/9, 4/9, 3/9], [1.0], [1.0]] for k in range(y.shape[1]): assert_array_almost_equal(classes[k], classes_expected[k]) assert_array_almost_equal(n_classes[k], n_classes_expected[k]) assert_array_almost_equal(class_prior[k], class_prior_expected[k]) assert_array_almost_equal(classes_sp[k], classes_expected[k]) assert_array_almost_equal(n_classes_sp[k], n_classes_expected[k]) assert_array_almost_equal(class_prior_sp[k], class_prior_expected[k])
bsd-3-clause