repo_name
stringlengths
6
112
path
stringlengths
4
204
copies
stringlengths
1
3
size
stringlengths
4
6
content
stringlengths
714
810k
license
stringclasses
15 values
nesterione/scikit-learn
sklearn/tests/test_base.py
216
7045
# Author: Gael Varoquaux # License: BSD 3 clause import numpy as np import scipy.sparse as sp from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_not_equal from sklearn.utils.testing import assert_raises from sklearn.base import BaseEstimator, clone, is_classifier from sklearn.svm import SVC from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.utils import deprecated ############################################################################# # A few test classes class MyEstimator(BaseEstimator): def __init__(self, l1=0, empty=None): self.l1 = l1 self.empty = empty class K(BaseEstimator): def __init__(self, c=None, d=None): self.c = c self.d = d class T(BaseEstimator): def __init__(self, a=None, b=None): self.a = a self.b = b class DeprecatedAttributeEstimator(BaseEstimator): def __init__(self, a=None, b=None): self.a = a if b is not None: DeprecationWarning("b is deprecated and renamed 'a'") self.a = b @property @deprecated("Parameter 'b' is deprecated and renamed to 'a'") def b(self): return self._b class Buggy(BaseEstimator): " A buggy estimator that does not set its parameters right. " def __init__(self, a=None): self.a = 1 class NoEstimator(object): def __init__(self): pass def fit(self, X=None, y=None): return self def predict(self, X=None): return None class VargEstimator(BaseEstimator): """Sklearn estimators shouldn't have vargs.""" def __init__(self, *vargs): pass ############################################################################# # The tests def test_clone(): # Tests that clone creates a correct deep copy. # We create an estimator, make a copy of its original state # (which, in this case, is the current state of the estimator), # and check that the obtained copy is a correct deep copy. from sklearn.feature_selection import SelectFpr, f_classif selector = SelectFpr(f_classif, alpha=0.1) new_selector = clone(selector) assert_true(selector is not new_selector) assert_equal(selector.get_params(), new_selector.get_params()) selector = SelectFpr(f_classif, alpha=np.zeros((10, 2))) new_selector = clone(selector) assert_true(selector is not new_selector) def test_clone_2(): # Tests that clone doesn't copy everything. # We first create an estimator, give it an own attribute, and # make a copy of its original state. Then we check that the copy doesn't # have the specific attribute we manually added to the initial estimator. from sklearn.feature_selection import SelectFpr, f_classif selector = SelectFpr(f_classif, alpha=0.1) selector.own_attribute = "test" new_selector = clone(selector) assert_false(hasattr(new_selector, "own_attribute")) def test_clone_buggy(): # Check that clone raises an error on buggy estimators. buggy = Buggy() buggy.a = 2 assert_raises(RuntimeError, clone, buggy) no_estimator = NoEstimator() assert_raises(TypeError, clone, no_estimator) varg_est = VargEstimator() assert_raises(RuntimeError, clone, varg_est) def test_clone_empty_array(): # Regression test for cloning estimators with empty arrays clf = MyEstimator(empty=np.array([])) clf2 = clone(clf) assert_array_equal(clf.empty, clf2.empty) clf = MyEstimator(empty=sp.csr_matrix(np.array([[0]]))) clf2 = clone(clf) assert_array_equal(clf.empty.data, clf2.empty.data) def test_clone_nan(): # Regression test for cloning estimators with default parameter as np.nan clf = MyEstimator(empty=np.nan) clf2 = clone(clf) assert_true(clf.empty is clf2.empty) def test_repr(): # Smoke test the repr of the base estimator. my_estimator = MyEstimator() repr(my_estimator) test = T(K(), K()) assert_equal( repr(test), "T(a=K(c=None, d=None), b=K(c=None, d=None))" ) some_est = T(a=["long_params"] * 1000) assert_equal(len(repr(some_est)), 415) def test_str(): # Smoke test the str of the base estimator my_estimator = MyEstimator() str(my_estimator) def test_get_params(): test = T(K(), K()) assert_true('a__d' in test.get_params(deep=True)) assert_true('a__d' not in test.get_params(deep=False)) test.set_params(a__d=2) assert_true(test.a.d == 2) assert_raises(ValueError, test.set_params, a__a=2) def test_get_params_deprecated(): # deprecated attribute should not show up as params est = DeprecatedAttributeEstimator(a=1) assert_true('a' in est.get_params()) assert_true('a' in est.get_params(deep=True)) assert_true('a' in est.get_params(deep=False)) assert_true('b' not in est.get_params()) assert_true('b' not in est.get_params(deep=True)) assert_true('b' not in est.get_params(deep=False)) def test_is_classifier(): svc = SVC() assert_true(is_classifier(svc)) assert_true(is_classifier(GridSearchCV(svc, {'C': [0.1, 1]}))) assert_true(is_classifier(Pipeline([('svc', svc)]))) assert_true(is_classifier(Pipeline([('svc_cv', GridSearchCV(svc, {'C': [0.1, 1]}))]))) def test_set_params(): # test nested estimator parameter setting clf = Pipeline([("svc", SVC())]) # non-existing parameter in svc assert_raises(ValueError, clf.set_params, svc__stupid_param=True) # non-existing parameter of pipeline assert_raises(ValueError, clf.set_params, svm__stupid_param=True) # we don't currently catch if the things in pipeline are estimators # bad_pipeline = Pipeline([("bad", NoEstimator())]) # assert_raises(AttributeError, bad_pipeline.set_params, # bad__stupid_param=True) def test_score_sample_weight(): from sklearn.tree import DecisionTreeClassifier from sklearn.tree import DecisionTreeRegressor from sklearn import datasets rng = np.random.RandomState(0) # test both ClassifierMixin and RegressorMixin estimators = [DecisionTreeClassifier(max_depth=2), DecisionTreeRegressor(max_depth=2)] sets = [datasets.load_iris(), datasets.load_boston()] for est, ds in zip(estimators, sets): est.fit(ds.data, ds.target) # generate random sample weights sample_weight = rng.randint(1, 10, size=len(ds.target)) # check that the score with and without sample weights are different assert_not_equal(est.score(ds.data, ds.target), est.score(ds.data, ds.target, sample_weight=sample_weight), msg="Unweighted and weighted scores " "are unexpectedly equal")
bsd-3-clause
xubenben/scikit-learn
benchmarks/bench_lasso.py
297
3305
""" Benchmarks of Lasso vs LassoLars First, we fix a training set and increase the number of samples. Then we plot the computation time as function of the number of samples. In the second benchmark, we increase the number of dimensions of the training set. Then we plot the computation time as function of the number of dimensions. In both cases, only 10% of the features are informative. """ import gc from time import time import numpy as np from sklearn.datasets.samples_generator import make_regression def compute_bench(alpha, n_samples, n_features, precompute): lasso_results = [] lars_lasso_results = [] it = 0 for ns in n_samples: for nf in n_features: it += 1 print('==================') print('Iteration %s of %s' % (it, max(len(n_samples), len(n_features)))) print('==================') n_informative = nf // 10 X, Y, coef_ = make_regression(n_samples=ns, n_features=nf, n_informative=n_informative, noise=0.1, coef=True) X /= np.sqrt(np.sum(X ** 2, axis=0)) # Normalize data gc.collect() print("- benchmarking Lasso") clf = Lasso(alpha=alpha, fit_intercept=False, precompute=precompute) tstart = time() clf.fit(X, Y) lasso_results.append(time() - tstart) gc.collect() print("- benchmarking LassoLars") clf = LassoLars(alpha=alpha, fit_intercept=False, normalize=False, precompute=precompute) tstart = time() clf.fit(X, Y) lars_lasso_results.append(time() - tstart) return lasso_results, lars_lasso_results if __name__ == '__main__': from sklearn.linear_model import Lasso, LassoLars import pylab as pl alpha = 0.01 # regularization parameter n_features = 10 list_n_samples = np.linspace(100, 1000000, 5).astype(np.int) lasso_results, lars_lasso_results = compute_bench(alpha, list_n_samples, [n_features], precompute=True) pl.figure('scikit-learn LASSO benchmark results') pl.subplot(211) pl.plot(list_n_samples, lasso_results, 'b-', label='Lasso') pl.plot(list_n_samples, lars_lasso_results, 'r-', label='LassoLars') pl.title('precomputed Gram matrix, %d features, alpha=%s' % (n_features, alpha)) pl.legend(loc='upper left') pl.xlabel('number of samples') pl.ylabel('Time (s)') pl.axis('tight') n_samples = 2000 list_n_features = np.linspace(500, 3000, 5).astype(np.int) lasso_results, lars_lasso_results = compute_bench(alpha, [n_samples], list_n_features, precompute=False) pl.subplot(212) pl.plot(list_n_features, lasso_results, 'b-', label='Lasso') pl.plot(list_n_features, lars_lasso_results, 'r-', label='LassoLars') pl.title('%d samples, alpha=%s' % (n_samples, alpha)) pl.legend(loc='upper left') pl.xlabel('number of features') pl.ylabel('Time (s)') pl.axis('tight') pl.show()
bsd-3-clause
kunalghosh/BECS-114.1100-Computational-Science
exercise10/2d_example.py
1
13693
from __future__ import division from itertools import combinations import cPickle as pickle import sys import pylab import numpy as np class PLattice: def __init__(self, dimension, initial_value, temperature, seed=None): # create an array storing the values on the lattice and set them # to initial_value if seed is not None: np.random.seed(seed) rand_vals = np.random.random(dimension)*2-1 # scale the rand numbers between -1,1 self.lattice = np.floor(rand_vals) + np.ceil(rand_vals) else: np.random.seed(5555) self.lattice = initial_value * pylab.ones(dimension) self.dimension = dimension # dimension = (row,col) self.length = np.prod(self.dimension) self.row_max = self.dimension[0] self.col_max = self.dimension[1] self.J = 1 self.temp = temperature self.indices = np.asarray([zip(np.ones(self.col_max).astype(int)*r,np.arange(self.col_max)) for r in xrange(self.row_max)]) l,b,h = self.indices.shape self.indices = self.indices.reshape(l*b,h) # compute the energy and magnetization of the initial configuration self.energy = self.compute_energy() self.magnetization = self.compute_magnetization() def __get_indices__(self, idx): # the modulus operator implements the periodic boundary # (may not be the most efficient way but it's ok for this...) # one should check that negative values of idx behave also as expected # idx in this case is a Tuple OR a List of Tuples # List of Tuples would allow us to vectorize operations. retVal = None if isinstance(idx,np.ndarray) or isinstance(idx,list): new_rows,new_cols = np.asarray(zip(*idx)) new_rows = new_rows % self.row_max new_cols = new_cols % self.col_max retVal = np.asarray(zip(new_rows, new_cols)) elif isinstance(idx,tuple): new_row = idx[0] % self.row_max new_col = idx[1] % self.col_max retVal = (new_row, new_col) else: raise ValueError("Only list of Tuples or Tuples accepted") return retVal # see below the flip method and the flip example in the main-part on how # __getitem__ and __setitem__ work def __get_left_idx(self,idx): retVal = None if isinstance(idx,np.ndarray) or isinstance(idx,list): rows,cols = np.asarray(zip(*idx)) cols = (cols - 1) % self.col_max retVal = np.asarray(zip(rows,cols)) elif isinstance(idx,tuple): retVal = (idx[0],(idx[1]-1) % self.col_max) else: raise ValueError("Only list of Tuples or Tuples accepted") return retVal def __get_right_idx(self,idx): retVal = None if isinstance(idx,np.ndarray) or isinstance(idx,list): rows,cols = np.asarray(zip(*idx)) cols = (cols + 1) % self.col_max retVal = np.asarray(zip(rows,cols)) elif isinstance(idx,tuple): retVal = (idx[0],(idx[1]+1) % self.col_max) else: raise ValueError("Only list of Tuples or Tuples accepted") return retVal def __get_top_idx(self,idx): retVal = None if isinstance(idx,np.ndarray) or isinstance(idx,list): rows,cols = np.asarray(zip(*idx)) rows = (rows - 1) % self.row_max retVal = np.asarray(zip(rows,cols)) elif isinstance(idx,tuple): retVal = ((idx[0]-1) % self.row_max,idx[1]) else: raise ValueError("Only list of Tuples or Tuples accepted") return retVal def __get_bottom_idx(self,idx): retVal = None if isinstance(idx,np.ndarray) or isinstance(idx,list): rows,cols = np.asarray(zip(*idx)) rows = (rows + 1) % self.row_max retVal = np.asarray(zip(rows,cols)) elif isinstance(idx,tuple): retVal = ((idx[0]+1) % self.row_max,idx[1]) else: raise ValueError("Only list of Tuples or Tuples accepted") return retVal def __getitem__(self, idx): idxes = self.__get_indices__(idx) retVal = None if isinstance(idx,np.ndarray) or isinstance(idx,list): retVal = self.lattice[zip(*idxes)] elif isinstance(idx,tuple): retVal = self.lattice[idxes] else: raise ValueError("Only list of Tuples or Tuples accepted") return retVal def __setitem__(self, idx, val): # same here self.lattice[self.__get_indices__(idx)] = val def flip(self, idx, compute_energy=True): # this is equal to self[idx] = -1 * self[idx] # self[idx] causes call to either __getitem__ or __setitem__ (see below) self[idx] *= -1 if compute_energy: self.energy = self.compute_energy() def compute_magnetization(self): return np.sum(self.lattice) def get_energy(self): return self.energy def get_energy_per_site(self): return np.true_divide(self.get_energy(),self.length) def get_magnetization(self): return self.magnetization def get_magnetization_per_site(self): return np.true_divide(self.get_magnetization(),self.length) def compute_energy(self): # compute the energy here and return it # get values of the right cell and the bottom cell and do this for each cell. # this ensure that an i,j is not indexed twice right_indices = self.__get_right_idx(self.indices) bottom_indices = self.__get_bottom_idx(self.indices) right_vals = self[right_indices] bottom_vals = self[bottom_indices] cell_vals = self[self.indices] np.add(right_vals, bottom_vals, out=bottom_vals) np.multiply(bottom_vals,cell_vals,out=cell_vals) return np.sum(cell_vals) * -1 def __is_flip_accepted(self, idx): retVal = None deltaE = 2 * self[idx] * ( self[self.__get_bottom_idx(idx)] + self[self.__get_top_idx(idx)] + self[self.__get_left_idx(idx)] + self[self.__get_right_idx(idx)] ) if deltaE <= 0: retVal = True else: w = np.exp((-1 * deltaE)/self.temp) # kB = 1 if np.random.random() < w: retVal = True else: retVal = False return retVal,deltaE def do_montecarlo(self): # we need max_row * max_col random indices rand_row_indices = np.random.randint(low=0,high=self.row_max,size=self.length) rand_col_indices = np.random.randint(low=0,high=self.col_max,size=self.length) idxes = zip(rand_row_indices,rand_col_indices) for idx in idxes: result, deltaE = self.__is_flip_accepted(idx) if result: # Flip Accepted self.flip(idx,compute_energy=False) self.energy += deltaE self.magnetization += 2 * self[idx] def print_lattice(self): import pprint pprint.pprint(self.lattice) def get_lattice(self): return self.lattice def plot_lattice(lattice,fileName): from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm fig = plt.figure() x,y = lattice.shape X = np.arange(0, x, 1) Y = np.arange(0, y, 1) X, Y = np.meshgrid(X, Y) R = lattice[X,Y] surf = plt.imshow(R,origin='lower', aspect='auto', extent=(1,x,1,y)) plt.savefig(fileName+".png") plt.close() if __name__ == "__main__": # create the lattice object l = PLattice((32,32), -1,temperature = 2.265, seed=None) # print the energy print l.energy # print the values of the lattice at the left neighbor, current index and # right neighbor to check that periodic boundary works... # Code to check periodic boundary # for i in xrange(l.col_max): # print "Col = {} -- ".format(i), # print l[0,i-1], l[0,i], l[0,i+1] # for i in xrange(l.row_max): # print "Row = {} -- ".format(i), # print l[i-1,0], l[i,0], l[i+1,0] # here's how the monte carlo simulation could be implemented # you need to use e.g. lists to keep track of the energy etc. # at each iteration... runlength = 1000 lattice_shape = (32,32) energies_per_temp = [] magnetizations_per_temp = [] lattices_per_temp = [] xvals = range(1,runlength+1) seeds = [None,6000,7000,8000,9000,10000,11000] colours = ["k","r","g","b","c","m","y"] # For checking equlibriation m_old,m_new = -200,200 # Mean magnetization m_abs_old, m_abs_new = -200,200 # Mean abs magnetization for temp in [2.1,3.5]: energies = [] magnetizations = [] lattices = [] pylab.figure() for idx,val in enumerate(zip(seeds,colours)): run_seed,color = val energy = [] magnetization = [] l = PLattice(lattice_shape, -1, temperature = temp, seed=run_seed) for i in xrange(1, runlength+1): # ... keep track of the interesting quantities # print the progress in long runs l.do_montecarlo() energy.append(l.get_energy_per_site()) magnetization.append(l.get_magnetization_per_site()) if i % 100 == 0: # print "Temp = %f , Seed = %d , %d MCS completed." % (temp, run_seed if run_seed is not None else -1, i) m_old, m_new = m_new, np.mean(magnetization[-100:]) m_abs_old, m_abs_new = m_abs_new, np.mean(np.abs(magnetization[-100:])) err_m, err_abs = np.abs(m_old-m_new) , np.abs(m_abs_old - m_abs_new) if err_m < 0.01: print "Temp = {} Run {} Convergence after {} MCS at M = {}, M_err = {}".format(temp, idx,i,m_new,err_m) if err_abs < 0.01: print "Temp = {} Run {} Convergence after {} MCS at abs(M) = {}, abs(M)err = {}".format(temp,idx,i,m_abs_new,err_abs) print "Temp = {} Run {} Final Data after {} MCS at abs(M) = {}, abs(M)err = {}, abs(M) = {}, abs(M)err = {}".format(temp,idx,i,m_abs_new,err_abs,m_abs_new,err_abs) energies.append(energy) magnetizations.append(magnetization) lattices.append(l.get_lattice()) plot_lattice(lattices[-1],"%d_run_%d"%(int(temp),idx)) pylab.plot(xvals,energy,marker=".",c=color,label="Run %d" % idx) pylab.plot(xvals,magnetization,marker=".",c=color) pylab.legend(framealpha=0.5,loc=10) pylab.xlabel("Run Length") pylab.title("2D Ising model Temp = %f L = %d \n (Magnetization on Top, Energy below)" % (temp,lattice_shape[0])) pylab.savefig("energyVsmagnetization_%d.png"%int(temp)) pylab.show() for idx,val in enumerate(zip(magnetizations,colours)): m,c = val pylab.plot(xvals, m, marker=".",c=c,label="Run %d" % idx) pylab.legend(framealpha=0.5,loc=10) pylab.xlabel("Run Length") pylab.ylabel("Magnetization") pylab.title("2D Ising model Temp = %f L = %d" % (temp,lattice_shape[0])) pylab.savefig("magnetization_%d.png"%int(temp)) pylab.show() energies_per_temp.append(energies) magnetizations_per_temp.append(magnetizations) lattices_per_temp.append(lattices) with open('data.pkl', 'wb') as dat_dmp_file: pickle.dump([energies_per_temp, magnetizations_per_temp, lattices_per_temp], dat_dmp_file) temp = 2.265 runlength = 50000 xvals = range(1,runlength+1) pylab.figure() energies = [] magnetizations = [] lattices = [] for idx,val in enumerate(zip([seeds[1]],[colours[1]])): run_seed,color = val energy = [] magnetization = [] l = PLattice(lattice_shape, -1, temperature=temp, seed=run_seed) for i in xrange(1, runlength+1): l.do_montecarlo() energy.append(l.get_energy_per_site()) magnetization.append(l.get_magnetization_per_site()) if i % 1000 == 0: print "Temp = %f , Seed = %d , %d MCS completed." % (temp, run_seed if run_seed is not None else -1, i) energies.append(energy) magnetizations.append(magnetization) lattices.append(l.get_lattice()) plot_lattice(lattices[-1],"50000_lattice") # pylab.plot(xvals,energy,marker=".",c=color,label="Run %d" % idx) try: pylab.plot(xvals,magnetization,marker=".",c=color) except: pass with open('data50000.pkl', 'wb') as dat_dmp_file: pickle.dump([energies, magnetizations], dat_dmp_file) #pickle.dump(magnetizations, dat_dmp_file) pylab.legend(framealpha=0.5,loc=10) pylab.xlabel("Run Length") pylab.ylabel("Magnetization") pylab.title("2D Ising model Temp = %f L = %d" % (temp,lattice_shape[0])) pylab.savefig("magnetization5000_%d.png"%int(temp)) pylab.show()
bsd-2-clause
LuizArmesto/gastos_abertos
utils/import_contrato_urls.py
1
1650
# -*- coding: utf-8 -*- ''' Read a xls with Contracts and insert them in the DB. Usage: ./import_contrato [FILE] [LINES_PER_INSERT] ./import_contrato (-h | --help) Options: -h --help Show this message. ''' import pandas as pd import numpy as np from datetime import datetime, timedelta import calendar from sqlalchemy.sql.expression import insert from sqlalchemy import update from docopt import docopt from gastosabertos import create_app from gastosabertos.contratos.models import Contrato def get_db(): from gastosabertos.extensions import db app = create_app() db.app = app return db def parse_money(money_string): return str(money_string).replace('.', '').replace(',', '.') def parse_date(date_string): new_date = datetime.strptime(date_string, '%d/%m/%Y') return new_date def insert_rows(db, rows_data): ins = insert(Contrato.__table__, rows_data) db.session.execute(ins) db.session.commit() def insert_all(db, csv_file='../data/urls.csv', lines_per_insert=100): data = pd.read_csv(csv_file) for di, d in data[:10].iterrows(): stmt = update(Contrato).values({'file_url':d['file_url'], 'txt_file_url':d['file_txt']}).where(Contrato.numero == d['numero']) db.session.execute(stmt) db.session.commit() if __name__ == '__main__': arguments = docopt(__doc__) args = {} csv_file = arguments['FILE'] if csv_file: args['csv_file'] = csv_file lines_per_insert = arguments['LINES_PER_INSERT'] if lines_per_insert: args['lines_per_insert'] = int(lines_per_insert) db = get_db() insert_all(db, **args)
agpl-3.0
andyraib/data-storage
python_scripts/env/lib/python3.6/site-packages/matplotlib/tests/test_backend_bases.py
5
3227
from matplotlib.backend_bases import FigureCanvasBase from matplotlib.backend_bases import RendererBase from matplotlib.testing.decorators import image_comparison, cleanup import matplotlib.pyplot as plt import matplotlib.transforms as transforms import matplotlib.path as path from nose.tools import assert_equal import numpy as np import os import shutil import tempfile def test_uses_per_path(): id = transforms.Affine2D() paths = [path.Path.unit_regular_polygon(i) for i in range(3, 7)] tforms = [id.rotate(i) for i in range(1, 5)] offsets = np.arange(20).reshape((10, 2)) facecolors = ['red', 'green'] edgecolors = ['red', 'green'] def check(master_transform, paths, all_transforms, offsets, facecolors, edgecolors): rb = RendererBase() raw_paths = list(rb._iter_collection_raw_paths( master_transform, paths, all_transforms)) gc = rb.new_gc() ids = [path_id for xo, yo, path_id, gc0, rgbFace in rb._iter_collection(gc, master_transform, all_transforms, range(len(raw_paths)), offsets, transforms.IdentityTransform(), facecolors, edgecolors, [], [], [False], [], 'data')] uses = rb._iter_collection_uses_per_path( paths, all_transforms, offsets, facecolors, edgecolors) seen = [0] * len(raw_paths) for i in ids: seen[i] += 1 for n in seen: assert n in (uses-1, uses) check(id, paths, tforms, offsets, facecolors, edgecolors) check(id, paths[0:1], tforms, offsets, facecolors, edgecolors) check(id, [], tforms, offsets, facecolors, edgecolors) check(id, paths, tforms[0:1], offsets, facecolors, edgecolors) check(id, paths, [], offsets, facecolors, edgecolors) for n in range(0, offsets.shape[0]): check(id, paths, tforms, offsets[0:n, :], facecolors, edgecolors) check(id, paths, tforms, offsets, [], edgecolors) check(id, paths, tforms, offsets, facecolors, []) check(id, paths, tforms, offsets, [], []) check(id, paths, tforms, offsets, facecolors[0:1], edgecolors) @cleanup def test_get_default_filename(): try: test_dir = tempfile.mkdtemp() plt.rcParams['savefig.directory'] = test_dir fig = plt.figure() canvas = FigureCanvasBase(fig) filename = canvas.get_default_filename() assert_equal(filename, 'image.png') finally: shutil.rmtree(test_dir) @cleanup def test_get_default_filename_already_exists(): # From #3068: Suggest non-existing default filename try: test_dir = tempfile.mkdtemp() plt.rcParams['savefig.directory'] = test_dir fig = plt.figure() canvas = FigureCanvasBase(fig) # create 'image.png' in figure's save dir open(os.path.join(test_dir, 'image.png'), 'w').close() filename = canvas.get_default_filename() assert_equal(filename, 'image-1.png') finally: shutil.rmtree(test_dir) if __name__ == "__main__": import nose nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
apache-2.0
sandeepkrjha/pgmpy
pgmpy/models/BayesianModel.py
1
36803
#!/usr/bin/env python3 import itertools from collections import defaultdict import logging from operator import mul import networkx as nx import numpy as np import pandas as pd from pgmpy.base import DirectedGraph from pgmpy.factors.discrete import TabularCPD, JointProbabilityDistribution, DiscreteFactor from pgmpy.independencies import Independencies from pgmpy.extern import six from pgmpy.extern.six.moves import range, reduce from pgmpy.models.MarkovModel import MarkovModel class BayesianModel(DirectedGraph): """ Base class for bayesian model. A models stores nodes and edges with conditional probability distribution (cpd) and other attributes. models hold directed edges. Self loops are not allowed neither multiple (parallel) edges. Nodes should be strings. Edges are represented as links between nodes. Parameters ---------- data : input graph Data to initialize graph. If data=None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. Examples -------- Create an empty bayesian model with no nodes and no edges. >>> from pgmpy.models import BayesianModel >>> G = BayesianModel() G can be grown in several ways. **Nodes:** Add one node at a time: >>> G.add_node('a') Add the nodes from any container (a list, set or tuple or the nodes from another graph). >>> G.add_nodes_from(['a', 'b']) **Edges:** G can also be grown by adding edges. Add one edge, >>> G.add_edge('a', 'b') a list of edges, >>> G.add_edges_from([('a', 'b'), ('b', 'c')]) If some edges connect nodes not yet in the model, the nodes are added automatically. There are no errors when adding nodes or edges that already exist. **Shortcuts:** Many common graph features allow python syntax for speed reporting. >>> 'a' in G # check if node in graph True >>> len(G) # number of nodes in graph 3 """ def __init__(self, ebunch=None): super(BayesianModel, self).__init__() if ebunch: self.add_edges_from(ebunch) self.cpds = [] self.cardinalities = defaultdict(int) def add_edge(self, u, v, **kwargs): """ Add an edge between u and v. The nodes u and v will be automatically added if they are not already in the graph Parameters ---------- u,v : nodes Nodes can be any hashable python object. Examples -------- >>> from pgmpy.models import BayesianModel/home/abinash/software_packages/numpy-1.7.1 >>> G = BayesianModel() >>> G.add_nodes_from(['grade', 'intel']) >>> G.add_edge('grade', 'intel') """ if u == v: raise ValueError('Self loops are not allowed.') if u in self.nodes() and v in self.nodes() and nx.has_path(self, v, u): raise ValueError( 'Loops are not allowed. Adding the edge from (%s->%s) forms a loop.' % (u, v)) else: super(BayesianModel, self).add_edge(u, v, **kwargs) def remove_node(self, node): """ Remove node from the model. Removing a node also removes all the associated edges, removes the CPD of the node and marginalizes the CPDs of it's children. Parameters ---------- node : node Node which is to be removed from the model. Returns ------- None Examples -------- >>> import pandas as pd >>> import numpy as np >>> from pgmpy.models import BayesianModel >>> model = BayesianModel([('A', 'B'), ('B', 'C'), ... ('A', 'D'), ('D', 'C')]) >>> values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 4)), ... columns=['A', 'B', 'C', 'D']) >>> model.fit(values) >>> model.get_cpds() [<TabularCPD representing P(A:2) at 0x7f28248e2438>, <TabularCPD representing P(B:2 | A:2) at 0x7f28248e23c8>, <TabularCPD representing P(C:2 | B:2, D:2) at 0x7f28248e2748>, <TabularCPD representing P(D:2 | A:2) at 0x7f28248e26a0>] >>> model.remove_node('A') >>> model.get_cpds() [<TabularCPD representing P(B:2) at 0x7f28248e23c8>, <TabularCPD representing P(C:2 | B:2, D:2) at 0x7f28248e2748>, <TabularCPD representing P(D:2) at 0x7f28248e26a0>] """ affected_nodes = [v for u, v in self.edges() if u == node] for affected_node in affected_nodes: node_cpd = self.get_cpds(node=affected_node) if node_cpd: node_cpd.marginalize([node], inplace=True) if self.get_cpds(node=node): self.remove_cpds(node) super(BayesianModel, self).remove_node(node) def remove_nodes_from(self, nodes): """ Remove multiple nodes from the model. Removing a node also removes all the associated edges, removes the CPD of the node and marginalizes the CPDs of it's children. Parameters ---------- nodes : list, set (iterable) Nodes which are to be removed from the model. Returns ------- None Examples -------- >>> import pandas as pd >>> import numpy as np >>> from pgmpy.models import BayesianModel >>> model = BayesianModel([('A', 'B'), ('B', 'C'), ... ('A', 'D'), ('D', 'C')]) >>> values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 4)), ... columns=['A', 'B', 'C', 'D']) >>> model.fit(values) >>> model.get_cpds() [<TabularCPD representing P(A:2) at 0x7f28248e2438>, <TabularCPD representing P(B:2 | A:2) at 0x7f28248e23c8>, <TabularCPD representing P(C:2 | B:2, D:2) at 0x7f28248e2748>, <TabularCPD representing P(D:2 | A:2) at 0x7f28248e26a0>] >>> model.remove_nodes_from(['A', 'B']) >>> model.get_cpds() [<TabularCPD representing P(C:2 | D:2) at 0x7f28248e2a58>, <TabularCPD representing P(D:2) at 0x7f28248e26d8>] """ for node in nodes: self.remove_node(node) def add_cpds(self, *cpds): """ Add CPD (Conditional Probability Distribution) to the Bayesian Model. Parameters ---------- cpds : list, set, tuple (array-like) List of CPDs which will be associated with the model EXAMPLE ------- >>> from pgmpy.models import BayesianModel >>> from pgmpy.factors.discrete.CPD import TabularCPD >>> student = BayesianModel([('diff', 'grades'), ('intel', 'grades')]) >>> grades_cpd = TabularCPD('grades', 3, [[0.1,0.1,0.1,0.1,0.1,0.1], ... [0.1,0.1,0.1,0.1,0.1,0.1], ... [0.8,0.8,0.8,0.8,0.8,0.8]], ... evidence=['diff', 'intel'], evidence_card=[2, 3]) >>> student.add_cpds(grades_cpd) +------+-----------------------+---------------------+ |diff: | easy | hard | +------+------+------+---------+------+------+-------+ |intel:| dumb | avg | smart | dumb | avg | smart | +------+------+------+---------+------+------+-------+ |gradeA| 0.1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 | +------+------+------+---------+------+------+-------+ |gradeB| 0.1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 | +------+------+------+---------+------+------+-------+ |gradeC| 0.8 | 0.8 | 0.8 | 0.8 | 0.8 | 0.8 | +------+------+------+---------+------+------+-------+ """ for cpd in cpds: if not isinstance(cpd, TabularCPD): raise ValueError('Only TabularCPD can be added.') if set(cpd.variables) - set(cpd.variables).intersection( set(self.nodes())): raise ValueError('CPD defined on variable not in the model', cpd) for prev_cpd_index in range(len(self.cpds)): if self.cpds[prev_cpd_index].variable == cpd.variable: logging.warning("Replacing existing CPD for {var}".format(var=cpd.variable)) self.cpds[prev_cpd_index] = cpd break else: self.cpds.append(cpd) def get_cpds(self, node=None): """ Returns the cpd of the node. If node is not specified returns all the CPDs that have been added till now to the graph Parameter --------- node: any hashable python object (optional) The node whose CPD we want. If node not specified returns all the CPDs added to the model. Returns ------- A list of TabularCPDs. Examples -------- >>> from pgmpy.models import BayesianModel >>> from pgmpy.factors.discrete import TabularCPD >>> student = BayesianModel([('diff', 'grade'), ('intel', 'grade')]) >>> cpd = TabularCPD('grade', 2, [[0.1, 0.9, 0.2, 0.7], ... [0.9, 0.1, 0.8, 0.3]], ... ['intel', 'diff'], [2, 2]) >>> student.add_cpds(cpd) >>> student.get_cpds() """ if node: if node not in self.nodes(): raise ValueError('Node not present in the Directed Graph') for cpd in self.cpds: if cpd.variable == node: return cpd raise ValueError("CPD not added for the node: {node}".format(node=node)) else: return self.cpds def remove_cpds(self, *cpds): """ Removes the cpds that are provided in the argument. Parameters ---------- *cpds: TabularCPD object A CPD object on any subset of the variables of the model which is to be associated with the model. Examples -------- >>> from pgmpy.models import BayesianModel >>> from pgmpy.factors.discrete import TabularCPD >>> student = BayesianModel([('diff', 'grade'), ('intel', 'grade')]) >>> cpd = TabularCPD('grade', 2, [[0.1, 0.9, 0.2, 0.7], ... [0.9, 0.1, 0.8, 0.3]], ... ['intel', 'diff'], [2, 2]) >>> student.add_cpds(cpd) >>> student.remove_cpds(cpd) """ for cpd in cpds: if isinstance(cpd, six.string_types): cpd = self.get_cpds(cpd) self.cpds.remove(cpd) def get_cardinality(self, node): """ Returns the cardinality of the node. Throws an error if the CPD for the queried node hasn't been added to the network. Parameters ---------- node: Any hashable python object. Returns ------- int: The cardinality of the node. """ return self.get_cpds(node).cardinality[0] def check_model(self): """ Check the model for various errors. This method checks for the following errors. * Checks if the sum of the probabilities for each state is equal to 1 (tol=0.01). * Checks if the CPDs associated with nodes are consistent with their parents. Returns ------- check: boolean True if all the checks are passed """ for node in self.nodes(): cpd = self.get_cpds(node=node) if isinstance(cpd, TabularCPD): evidence = cpd.variables[:0:-1] parents = self.get_parents(node) if set(evidence if evidence else []) != set(parents if parents else []): raise ValueError("CPD associated with %s doesn't have " "proper parents associated with it." % node) if not np.allclose(cpd.to_factor().marginalize([node], inplace=False).values.flatten('C'), np.ones(np.product(cpd.cardinality[:0:-1])), atol=0.01): raise ValueError('Sum of probabilites of states for node %s' ' is not equal to 1.' % node) return True def _get_ancestors_of(self, obs_nodes_list): """ Returns a dictionary of all ancestors of all the observed nodes including the node itself. Parameters ---------- obs_nodes_list: string, list-type name of all the observed nodes Examples -------- >>> from pgmpy.models import BayesianModel >>> model = BayesianModel([('D', 'G'), ('I', 'G'), ('G', 'L'), ... ('I', 'L')]) >>> model._get_ancestors_of('G') {'D', 'G', 'I'} >>> model._get_ancestors_of(['G', 'I']) {'D', 'G', 'I'} """ if not isinstance(obs_nodes_list, (list, tuple)): obs_nodes_list = [obs_nodes_list] for node in obs_nodes_list: if node not in self.nodes(): raise ValueError('Node {s} not in not in graph'.format(s=node)) ancestors_list = set() nodes_list = set(obs_nodes_list) while nodes_list: node = nodes_list.pop() if node not in ancestors_list: nodes_list.update(self.predecessors(node)) ancestors_list.add(node) return ancestors_list def active_trail_nodes(self, variables, observed=None): """ Returns a dictionary with the given variables as keys and all the nodes reachable from that respective variable as values. Parameters ---------- variables: str or array like variables whose active trails are to be found. observed : List of nodes (optional) If given the active trails would be computed assuming these nodes to be observed. Examples -------- >>> from pgmpy.models import BayesianModel >>> student = BayesianModel() >>> student.add_nodes_from(['diff', 'intel', 'grades']) >>> student.add_edges_from([('diff', 'grades'), ('intel', 'grades')]) >>> student.active_trail_nodes('diff') {'diff': {'diff', 'grades'}} >>> student.active_trail_nodes(['diff', 'intel'], observed='grades') {'diff': {'diff', 'intel'}, 'intel': {'diff', 'intel'}} References ---------- Details of the algorithm can be found in 'Probabilistic Graphical Model Principles and Techniques' - Koller and Friedman Page 75 Algorithm 3.1 """ if observed: observed_list = observed if isinstance(observed, (list, tuple)) else [observed] else: observed_list = [] ancestors_list = self._get_ancestors_of(observed_list) # Direction of flow of information # up -> from parent to child # down -> from child to parent active_trails = {} for start in variables if isinstance(variables, (list, tuple)) else [variables]: visit_list = set() visit_list.add((start, 'up')) traversed_list = set() active_nodes = set() while visit_list: node, direction = visit_list.pop() if (node, direction) not in traversed_list: if node not in observed_list: active_nodes.add(node) traversed_list.add((node, direction)) if direction == 'up' and node not in observed_list: for parent in self.predecessors(node): visit_list.add((parent, 'up')) for child in self.successors(node): visit_list.add((child, 'down')) elif direction == 'down': if node not in observed_list: for child in self.successors(node): visit_list.add((child, 'down')) if node in ancestors_list: for parent in self.predecessors(node): visit_list.add((parent, 'up')) active_trails[start] = active_nodes return active_trails def local_independencies(self, variables): """ Returns an instance of Independencies containing the local independencies of each of the variables. Parameters ---------- variables: str or array like variables whose local independencies are to be found. Examples -------- >>> from pgmpy.models import BayesianModel >>> student = BayesianModel() >>> student.add_edges_from([('diff', 'grade'), ('intel', 'grade'), >>> ('grade', 'letter'), ('intel', 'SAT')]) >>> ind = student.local_independencies('grade') >>> ind (grade _|_ SAT | diff, intel) """ def dfs(node): """ Returns the descendents of node. Since Bayesian Networks are acyclic, this is a very simple dfs which does not remember which nodes it has visited. """ descendents = [] visit = [node] while visit: n = visit.pop() neighbors = self.neighbors(n) visit.extend(neighbors) descendents.extend(neighbors) return descendents independencies = Independencies() for variable in variables if isinstance(variables, (list, tuple)) else [variables]: non_descendents = set(self.nodes()) - {variable} - set(dfs(variable)) parents = set(self.get_parents(variable)) if non_descendents - parents: independencies.add_assertions([variable, non_descendents - parents, parents]) return independencies def is_active_trail(self, start, end, observed=None): """ Returns True if there is any active trail between start and end node Parameters ---------- start : Graph Node end : Graph Node observed : List of nodes (optional) If given the active trail would be computed assuming these nodes to be observed. additional_observed : List of nodes (optional) If given the active trail would be computed assuming these nodes to be observed along with the nodes marked as observed in the model. Examples -------- >>> from pgmpy.models import BayesianModel >>> student = BayesianModel() >>> student.add_nodes_from(['diff', 'intel', 'grades', 'letter', 'sat']) >>> student.add_edges_from([('diff', 'grades'), ('intel', 'grades'), ('grades', 'letter'), ... ('intel', 'sat')]) >>> student.is_active_trail('diff', 'intel') False >>> student.is_active_trail('grades', 'sat') True """ if end in self.active_trail_nodes(start, observed)[start]: return True else: return False def get_independencies(self, latex=False): """ Computes independencies in the Bayesian Network, by checking d-seperation. Parameters ---------- latex: boolean If latex=True then latex string of the independence assertion would be created. Examples -------- >>> from pgmpy.models import BayesianModel >>> chain = BayesianModel([('X', 'Y'), ('Y', 'Z')]) >>> chain.get_independencies() (X _|_ Z | Y) (Z _|_ X | Y) """ independencies = Independencies() for start in (self.nodes()): rest = set(self.nodes()) - {start} for r in range(len(rest)): for observed in itertools.combinations(rest, r): d_seperated_variables = rest - set(observed) - set( self.active_trail_nodes(start, observed=observed)[start]) if d_seperated_variables: independencies.add_assertions([start, d_seperated_variables, observed]) independencies.reduce() if not latex: return independencies else: return independencies.latex_string() def to_markov_model(self): """ Converts bayesian model to markov model. The markov model created would be the moral graph of the bayesian model. Examples -------- >>> from pgmpy.models import BayesianModel >>> G = BayesianModel([('diff', 'grade'), ('intel', 'grade'), ... ('intel', 'SAT'), ('grade', 'letter')]) >>> mm = G.to_markov_model() >>> mm.nodes() ['diff', 'grade', 'intel', 'SAT', 'letter'] >>> mm.edges() [('diff', 'intel'), ('diff', 'grade'), ('intel', 'grade'), ('intel', 'SAT'), ('grade', 'letter')] """ moral_graph = self.moralize() mm = MarkovModel(moral_graph.edges()) mm.add_factors(*[cpd.to_factor() for cpd in self.cpds]) return mm def to_junction_tree(self): """ Creates a junction tree (or clique tree) for a given bayesian model. For converting a Bayesian Model into a Clique tree, first it is converted into a Markov one. For a given markov model (H) a junction tree (G) is a graph 1. where each node in G corresponds to a maximal clique in H 2. each sepset in G separates the variables strictly on one side of the edge to other. Examples -------- >>> from pgmpy.models import BayesianModel >>> from pgmpy.factors.discrete import TabularCPD >>> G = BayesianModel([('diff', 'grade'), ('intel', 'grade'), ... ('intel', 'SAT'), ('grade', 'letter')]) >>> diff_cpd = TabularCPD('diff', 2, [[0.2], [0.8]]) >>> intel_cpd = TabularCPD('intel', 3, [[0.5], [0.3], [0.2]]) >>> grade_cpd = TabularCPD('grade', 3, ... [[0.1,0.1,0.1,0.1,0.1,0.1], ... [0.1,0.1,0.1,0.1,0.1,0.1], ... [0.8,0.8,0.8,0.8,0.8,0.8]], ... evidence=['diff', 'intel'], ... evidence_card=[2, 3]) >>> sat_cpd = TabularCPD('SAT', 2, ... [[0.1, 0.2, 0.7], ... [0.9, 0.8, 0.3]], ... evidence=['intel'], evidence_card=[3]) >>> letter_cpd = TabularCPD('letter', 2, ... [[0.1, 0.4, 0.8], ... [0.9, 0.6, 0.2]], ... evidence=['grade'], evidence_card=[3]) >>> G.add_cpds(diff_cpd, intel_cpd, grade_cpd, sat_cpd, letter_cpd) >>> jt = G.to_junction_tree() """ mm = self.to_markov_model() return mm.to_junction_tree() def fit(self, data, estimator_type=None, state_names=[], complete_samples_only=True, **kwargs): """ Estimates the CPD for each variable based on a given data set. Parameters ---------- data: pandas DataFrame object DataFrame object with column names identical to the variable names of the network. (If some values in the data are missing the data cells should be set to `numpy.NaN`. Note that pandas converts each column containing `numpy.NaN`s to dtype `float`.) estimator: Estimator class One of: - MaximumLikelihoodEstimator (default) - BayesianEstimator: In this case, pass 'prior_type' and either 'pseudo_counts' or 'equivalent_sample_size' as additional keyword arguments. See `BayesianEstimator.get_parameters()` for usage. state_names: dict (optional) A dict indicating, for each variable, the discrete set of states that the variable can take. If unspecified, the observed values in the data set are taken to be the only possible states. complete_samples_only: bool (default `True`) Specifies how to deal with missing data, if present. If set to `True` all rows that contain `np.Nan` somewhere are ignored. If `False` then, for each variable, every row where neither the variable nor its parents are `np.NaN` is used. Examples -------- >>> import pandas as pd >>> from pgmpy.models import BayesianModel >>> from pgmpy.estimators import MaximumLikelihoodEstimator >>> data = pd.DataFrame(data={'A': [0, 0, 1], 'B': [0, 1, 0], 'C': [1, 1, 0]}) >>> model = BayesianModel([('A', 'C'), ('B', 'C')]) >>> model.fit(data) >>> model.get_cpds() [<TabularCPD representing P(A:2) at 0x7fb98a7d50f0>, <TabularCPD representing P(B:2) at 0x7fb98a7d5588>, <TabularCPD representing P(C:2 | A:2, B:2) at 0x7fb98a7b1f98>] """ from pgmpy.estimators import MaximumLikelihoodEstimator, BayesianEstimator, BaseEstimator if estimator_type is None: estimator_type = MaximumLikelihoodEstimator else: if not issubclass(estimator_type, BaseEstimator): raise TypeError("Estimator object should be a valid pgmpy estimator.") estimator = estimator_type(self, data, state_names=state_names, complete_samples_only=complete_samples_only) cpds_list = estimator.get_parameters(**kwargs) self.add_cpds(*cpds_list) def predict(self, data): """ Predicts states of all the missing variables. Parameters ---------- data : pandas DataFrame object A DataFrame object with column names same as the variables in the model. Examples -------- >>> import numpy as np >>> import pandas as pd >>> from pgmpy.models import BayesianModel >>> values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 5)), ... columns=['A', 'B', 'C', 'D', 'E']) >>> train_data = values[:800] >>> predict_data = values[800:] >>> model = BayesianModel([('A', 'B'), ('C', 'B'), ('C', 'D'), ('B', 'E')]) >>> model.fit(values) >>> predict_data = predict_data.copy() >>> predict_data.drop('E', axis=1, inplace=True) >>> y_pred = model.predict(predict_data) >>> y_pred E 800 0 801 1 802 1 803 1 804 0 ... ... 993 0 994 0 995 1 996 1 997 0 998 0 999 0 """ from pgmpy.inference import VariableElimination if set(data.columns) == set(self.nodes()): raise ValueError("No variable missing in data. Nothing to predict") elif set(data.columns) - set(self.nodes()): raise ValueError("Data has variables which are not in the model") missing_variables = set(self.nodes()) - set(data.columns) pred_values = defaultdict(list) # Send state_names dict from one of the estimated CPDs to the inference class. model_inference = VariableElimination(self, state_names=self.get_cpds()[0].state_names) for index, data_point in data.iterrows(): states_dict = model_inference.map_query(variables=missing_variables, evidence=data_point.to_dict()) for k, v in states_dict.items(): pred_values[k].append(v) return pd.DataFrame(pred_values, index=data.index) def predict_probability(self, data): """ Predicts probabilities of all states of the missing variables. Parameters ---------- data : pandas DataFrame object A DataFrame object with column names same as the variables in the model. Examples -------- >>> import numpy as np >>> import pandas as pd >>> from pgmpy.models import BayesianModel >>> values = pd.DataFrame(np.random.randint(low=0, high=2, size=(100, 5)), ... columns=['A', 'B', 'C', 'D', 'E']) >>> train_data = values[:80] >>> predict_data = values[80:] >>> model = BayesianModel([('A', 'B'), ('C', 'B'), ('C', 'D'), ('B', 'E')]) >>> model.fit(values) >>> predict_data = predict_data.copy() >>> predict_data.drop('B', axis=1, inplace=True) >>> y_prob = model.predict_probability(predict_data) >>> y_prob B_0 B_1 80 0.439178 0.560822 81 0.581970 0.418030 82 0.488275 0.511725 83 0.581970 0.418030 84 0.510794 0.489206 85 0.439178 0.560822 86 0.439178 0.560822 87 0.417124 0.582876 88 0.407978 0.592022 89 0.429905 0.570095 90 0.581970 0.418030 91 0.407978 0.592022 92 0.429905 0.570095 93 0.429905 0.570095 94 0.439178 0.560822 95 0.407978 0.592022 96 0.559904 0.440096 97 0.417124 0.582876 98 0.488275 0.511725 99 0.407978 0.592022 """ from pgmpy.inference import VariableElimination if set(data.columns) == set(self.nodes()): raise ValueError("No variable missing in data. Nothing to predict") elif set(data.columns) - set(self.nodes()): raise ValueError("Data has variables which are not in the model") missing_variables = set(self.nodes()) - set(data.columns) pred_values = defaultdict(list) model_inference = VariableElimination(self) for index, data_point in data.iterrows(): states_dict = model_inference.query(variables=missing_variables, evidence=data_point.to_dict()) for k, v in states_dict.items(): for l in range(len(v.values)): state = self.get_cpds(k).state_names[k][l] pred_values[k + '_' + str(state)].append(v.values[l]) return pd.DataFrame(pred_values, index=data.index) def get_factorized_product(self, latex=False): # TODO: refer to IMap class for explanation why this is not implemented. pass def get_immoralities(self): """ Finds all the immoralities in the model A v-structure X -> Z <- Y is an immorality if there is no direct edge between X and Y . Returns ------- set: A set of all the immoralities in the model Examples --------- >>> from pgmpy.models import BayesianModel >>> student = BayesianModel() >>> student.add_edges_from([('diff', 'grade'), ('intel', 'grade'), ... ('intel', 'SAT'), ('grade', 'letter')]) >>> student.get_immoralities() {('diff','intel')} """ immoralities = set() for node in self.nodes(): for parents in itertools.combinations(self.predecessors(node), 2): if not self.has_edge(parents[0], parents[1]) and not self.has_edge(parents[1], parents[0]): immoralities.add(tuple(sorted(parents))) return immoralities def is_iequivalent(self, model): """ Checks whether the given model is I-equivalent Two graphs G1 and G2 are said to be I-equivalent if they have same skeleton and have same set of immoralities. Note: For same skeleton different names of nodes can work but for immoralities names of nodes must be same Parameters ---------- model : A Bayesian model object, for which you want to check I-equivalence Returns -------- boolean : True if both are I-equivalent, False otherwise Examples -------- >>> from pgmpy.models import BayesianModel >>> G = BayesianModel() >>> G.add_edges_from([('V', 'W'), ('W', 'X'), ... ('X', 'Y'), ('Z', 'Y')]) >>> G1 = BayesianModel() >>> G1.add_edges_from([('W', 'V'), ('X', 'W'), ... ('X', 'Y'), ('Z', 'Y')]) >>> G.is_iequivalent(G1) True """ if not isinstance(model, BayesianModel): raise TypeError('model must be an instance of Bayesian Model') skeleton = nx.algorithms.isomorphism.GraphMatcher(self.to_undirected(), model.to_undirected()) if skeleton.is_isomorphic() and self.get_immoralities() == model.get_immoralities(): return True return False def is_imap(self, JPD): """ Checks whether the bayesian model is Imap of given JointProbabilityDistribution Parameters ----------- JPD : An instance of JointProbabilityDistribution Class, for which you want to check the Imap Returns -------- boolean : True if bayesian model is Imap for given Joint Probability Distribution False otherwise Examples -------- >>> from pgmpy.models import BayesianModel >>> from pgmpy.factors.discrete import TabularCPD >>> from pgmpy.factors.discrete import JointProbabilityDistribution >>> G = BayesianModel([('diff', 'grade'), ('intel', 'grade')]) >>> diff_cpd = TabularCPD('diff', 2, [[0.2], [0.8]]) >>> intel_cpd = TabularCPD('intel', 3, [[0.5], [0.3], [0.2]]) >>> grade_cpd = TabularCPD('grade', 3, ... [[0.1,0.1,0.1,0.1,0.1,0.1], ... [0.1,0.1,0.1,0.1,0.1,0.1], ... [0.8,0.8,0.8,0.8,0.8,0.8]], ... evidence=['diff', 'intel'], ... evidence_card=[2, 3]) >>> G.add_cpds(diff_cpd, intel_cpd, grade_cpd) >>> val = [0.01, 0.01, 0.08, 0.006, 0.006, 0.048, 0.004, 0.004, 0.032, 0.04, 0.04, 0.32, 0.024, 0.024, 0.192, 0.016, 0.016, 0.128] >>> JPD = JointProbabilityDistribution(['diff', 'intel', 'grade'], [2, 3, 3], val) >>> G.is_imap(JPD) True """ if not isinstance(JPD, JointProbabilityDistribution): raise TypeError("JPD must be an instance of JointProbabilityDistribution") factors = [cpd.to_factor() for cpd in self.get_cpds()] factor_prod = reduce(mul, factors) JPD_fact = DiscreteFactor(JPD.variables, JPD.cardinality, JPD.values) if JPD_fact == factor_prod: return True else: return False def copy(self): """ Returns a copy of the model. Returns ------- BayesianModel: Copy of the model on which the method was called. Examples -------- >>> from pgmpy.models import BayesianModel >>> from pgmpy.factors.discrete import TabularCPD >>> model = BayesianModel([('A', 'B'), ('B', 'C')]) >>> cpd_a = TabularCPD('A', 2, [[0.2], [0.8]]) >>> cpd_b = TabularCPD('B', 2, [[0.3, 0.7], [0.7, 0.3]], evidence=['A'], evidence_card=[2]) >>> cpd_c = TabularCPD('C', 2, [[0.1, 0.9], [0.9, 0.1]], evidence=['B'], evidence_card=[2]) >>> model.add_cpds(cpd_a, cpd_b, cpd_c) >>> copy_model = model.copy() >>> copy_model.nodes() ['C', 'A', 'B'] >>> copy_model.edges() [('A', 'B'), ('B', 'C')] >>> copy_model.get_cpds() [<TabularCPD representing P(A:2) at 0x7f2824930a58>, <TabularCPD representing P(B:2 | A:2) at 0x7f2824930a90>, <TabularCPD representing P(C:2 | B:2) at 0x7f2824944240>] """ model_copy = BayesianModel() model_copy.add_nodes_from(self.nodes()) model_copy.add_edges_from(self.edges()) if self.cpds: model_copy.add_cpds(*[cpd.copy() for cpd in self.cpds]) return model_copy
mit
jepio/pers_engine
persanalysis/fitengine.py
1
1436
""" Module for fitting graphs to file """ import matplotlib.pyplot as plt from plotengine import PlotEngine # pylint: disable=E1101 import numpy as np from scipy.optimize import curve_fit class FitEngine(PlotEngine): """ Class that performs fitting and saving of plots. """ functions = {"lin": (lambda x, a, b: a * x + b, "A*x+B", ["A", "B"]), "exp": (lambda x, a, b, c: a * np.exp(b * x) + c, "A*exp(B*x)+C", ["A", "B", "C"])} def __init__(self, data_tuple, name, func_name): super(FitEngine, self).__init__(data_tuple, name) self.func = FitEngine.functions[func_name] self.fit() def fit(self): """ Fit function to data and plot. """ func_to_fit = self.func[0] popt, pcov = curve_fit(func_to_fit, self.xval, self.yval, sigma=self.yerr) print "Function definition:" print self.func[1] if type(pcov) is float: pcov = np.zeros((len(popt), len(popt))) pcov = np.sqrt(np.abs(pcov)) for i, par_val in enumerate(popt): string = "{0}: {1:.3g} +/- {2:.3g}".format( self.func[2][i], par_val, pcov[i][i]) print string xmin, xmax = plt.xlim() ymin, ymax = plt.ylim() xvals = np.linspace(xmin, xmax, num=100) plt.plot(xvals, func_to_fit(xvals, *popt)) plt.ylim(ymin, ymax)
gpl-2.0
robcarver17/pysystemtrade
systems/positionsizing.py
1
18802
import pandas as pd from syscore.dateutils import ROOT_BDAYS_INYEAR from syscore.objects import missing_data from sysdata.config.configdata import Config from sysdata.sim.sim_data import simData from sysquant.estimators.vol import robust_vol_calc from systems.stage import SystemStage from systems.system_cache import input, diagnostic, output from systems.forecast_combine import ForecastCombine from systems.rawdata import RawData class PositionSizing(SystemStage): """ Stage for position sizing (take combined forecast; turn into subsystem positions) KEY INPUTS: a) system.combForecast.get_combined_forecast(instrument_code) found in self.get_combined_forecast b) system.rawdata.get_daily_percentage_volatility(instrument_code) found in self.get_price_volatility(instrument_code) If not found, uses system.data.daily_prices to calculate c) system.rawdata.daily_denominator_price((instrument_code) found in self.get_instrument_sizing_data(instrument_code) If not found, uses system.data.daily_prices d) system.data.get_value_of_block_price_move(instrument_code) found in self.get_instrument_sizing_data(instrument_code) e) system.data.get_fx_for_instrument(instrument_code, base_currency) found in self.get_fx_rate(instrument_code) KEY OUTPUT: system.positionSize.get_subsystem_position(instrument_code) Name: positionSize """ @property def name(self): return "positionSize" @output() def get_subsystem_position(self, instrument_code: str) -> pd.Series: """ Get scaled position (assuming for now we trade our entire capital for one instrument) KEY OUTPUT :param instrument_code: instrument to get values for :type instrument_code: str :returns: Tx1 pd.DataFrame >>> from systems.tests.testdata import get_test_object_futures_with_comb_forecasts >>> from systems.basesystem import System >>> (comb, fcs, rules, rawdata, data, config)=get_test_object_futures_with_comb_forecasts() >>> system=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> >>> system.positionSize.get_subsystem_position("EDOLLAR").tail(2) ss_position 2015-12-10 1.811465 2015-12-11 2.544598 >>> >>> system2=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> system2.positionSize.get_subsystem_position("EDOLLAR").tail(2) ss_position 2015-12-10 1.811465 2015-12-11 2.544598 """ self.log.msg( "Calculating subsystem position for %s" % instrument_code, instrument_code=instrument_code, ) """ We don't allow this to be changed in config """ avg_abs_forecast = self.avg_abs_forecast() vol_scalar = self.get_volatility_scalar(instrument_code) forecast = self.get_combined_forecast(instrument_code) vol_scalar = vol_scalar.reindex(forecast.index).ffill() subsystem_position = vol_scalar * forecast / avg_abs_forecast return subsystem_position def avg_abs_forecast(self) -> float: return self.config.average_absolute_forecast @property def config(self) -> Config: return self.parent.config @diagnostic() def get_volatility_scalar(self, instrument_code: str) -> pd.Series: """ Get ratio of required volatility vs volatility of instrument in instrument's own currency :param instrument_code: instrument to get values for :type instrument_code: str :returns: Tx1 pd.DataFrame >>> from systems.tests.testdata import get_test_object_futures_with_comb_forecasts >>> from systems.basesystem import System >>> (comb, fcs, rules, rawdata, data, config)=get_test_object_futures_with_comb_forecasts() >>> system=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> >>> system.positionSize.get_volatility_scalar("EDOLLAR").tail(2) vol_scalar 2015-12-10 11.187869 2015-12-11 10.332930 >>> >>> ## without raw data >>> system2=System([ rules, fcs, comb, PositionSizing()], data, config) >>> system2.positionSize.get_volatility_scalar("EDOLLAR").tail(2) vol_scalar 2015-12-10 11.180444 2015-12-11 10.344278 """ self.log.msg( "Calculating volatility scalar for %s" % instrument_code, instrument_code=instrument_code, ) instr_value_vol = self.get_instrument_value_vol(instrument_code) cash_vol_target = self.get_daily_cash_vol_target() vol_scalar = cash_vol_target / instr_value_vol return vol_scalar @diagnostic() def get_instrument_value_vol(self, instrument_code: str) -> pd.Series: """ Get value of volatility of instrument in base currency (used for account value) :param instrument_code: instrument to get values for :type instrument_code: str :returns: Tx1 pd.DataFrame >>> from systems.tests.testdata import get_test_object_futures_with_comb_forecasts >>> from systems.basesystem import System >>> (comb, fcs, rules, rawdata, data, config)=get_test_object_futures_with_comb_forecasts() >>> system=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> >>> system.positionSize.get_instrument_value_vol("EDOLLAR").tail(2) ivv 2015-12-10 89.382530 2015-12-11 96.777975 >>> >>> system2=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> system2.positionSize.get_instrument_value_vol("EDOLLAR").tail(2) ivv 2015-12-10 89.382530 2015-12-11 96.777975 """ self.log.msg( "Calculating instrument value vol for %s" % instrument_code, instrument_code=instrument_code, ) instr_ccy_vol = self.get_instrument_currency_vol(instrument_code) fx_rate = self.get_fx_rate(instrument_code) fx_rate = fx_rate.reindex(instr_ccy_vol.index, method="ffill") instr_value_vol = instr_ccy_vol.ffill() * fx_rate return instr_value_vol @diagnostic() def get_instrument_currency_vol(self, instrument_code: str) -> pd.Series: """ Get value of volatility of instrument in instrument's own currency :param instrument_code: instrument to get values for :type instrument_code: str :returns: Tx1 pd.DataFrame >>> from systems.tests.testdata import get_test_object_futures_with_comb_forecasts >>> from systems.basesystem import System >>> (comb, fcs, rules, rawdata, data, config)=get_test_object_futures_with_comb_forecasts() >>> system=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> >>> system.positionSize.get_instrument_currency_vol("EDOLLAR").tail(2) icv 2015-12-10 135.272415 2015-12-11 146.464756 >>> >>> system2=System([ rules, fcs, comb, PositionSizing()], data, config) >>> system2.positionSize.get_instrument_currency_vol("EDOLLAR").tail(2) icv 2015-12-10 135.362246 2015-12-11 146.304072 """ self.log.msg( "Calculating instrument currency vol for %s" % instrument_code, instrument_code=instrument_code, ) block_value = self.get_block_value(instrument_code) daily_perc_vol = self.get_price_volatility(instrument_code) ## FIXME WHY NOT RESAMPLE? (block_value, daily_perc_vol) = block_value.align( daily_perc_vol, join="inner") instr_ccy_vol = block_value.ffill() * daily_perc_vol return instr_ccy_vol @diagnostic() def get_block_value(self, instrument_code: str) -> pd.Series: """ Calculate block value for instrument_code :param instrument_code: instrument to get values for :type instrument_code: str :returns: Tx1 pd.DataFrame >>> from systems.tests.testdata import get_test_object_futures_with_comb_forecasts >>> from systems.basesystem import System >>> (comb, fcs, rules, rawdata, data, config)=get_test_object_futures_with_comb_forecasts() >>> system=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> >>> system.positionSize.get_block_value("EDOLLAR").tail(2) bvalue 2015-12-10 2447.0000 2015-12-11 2449.6875 >>> >>> system=System([rules, fcs, comb, PositionSizing()], data, config) >>> system.positionSize.get_block_value("EDOLLAR").tail(2) bvalue 2015-12-10 2447.0000 2015-12-11 2449.6875 """ underlying_price = self.get_underlying_price( instrument_code) value_of_price_move = self.parent.data.get_value_of_block_price_move( instrument_code ) block_value = underlying_price.ffill() * value_of_price_move * 0.01 return block_value @diagnostic() def get_underlying_price(self, instrument_code: str) -> pd.Series: """ Get various things from data and rawdata to calculate position sizes KEY INPUT :param instrument_code: instrument to get values for :type instrument_code: str :returns: Tx1 pd.DataFrame: underlying price [as used to work out % volatility], >>> from systems.tests.testdata import get_test_object_futures_with_comb_forecasts >>> from systems.basesystem import System >>> (comb, fcs, rules, rawdata, data, config)=get_test_object_futures_with_comb_forecasts() >>> system=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> >>> ans=system.positionSize.get_underlying_price("EDOLLAR") >>> ans[0].tail(2) price 2015-12-10 97.8800 2015-12-11 97.9875 >>> >>> ans[1] 2500 >>> >>> system=System([rules, fcs, comb, PositionSizing()], data, config) >>> >>> ans=system.positionSize.get_underlying_price("EDOLLAR") >>> ans[0].tail(2) price 2015-12-10 97.8800 2015-12-11 97.9875 >>> >>> ans[1] 2500 """ rawdata = self.rawdata_stage if rawdata is missing_data: underlying_price = self.data.daily_prices(instrument_code) else: underlying_price = self.rawdata_stage.daily_denominator_price( instrument_code ) return underlying_price @property def rawdata_stage(self) -> RawData: rawdata_stage = getattr(self.parent, "rawdata", missing_data) return rawdata_stage @property def data(self) -> simData: return self.parent.data @diagnostic() def get_price_volatility(self, instrument_code: str) -> pd.Series: """ Get the daily % volatility; If a rawdata stage exists from there; otherwise work it out :param instrument_code: instrument to get values for :type instrument_code: str :returns: Tx1 pd.DataFrame KEY INPUT Note as an exception to the normal rule we cache this, as it sometimes comes from data >>> from systems.tests.testdata import get_test_object_futures_with_comb_forecasts >>> from systems.basesystem import System >>> (comb, fcs, rules, rawdata, data, config)=get_test_object_futures_with_comb_forecasts() >>> system=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> >>> system.positionSize.get_price_volatility("EDOLLAR").tail(2) vol 2015-12-10 0.055281 2015-12-11 0.059789 >>> >>> system2=System([ rules, fcs, comb, PositionSizing()], data, config) >>> >>> system2.positionSize.get_price_volatility("EDOLLAR").tail(2) vol 2015-12-10 0.055318 2015-12-11 0.059724 """ rawdata = self.rawdata_stage if rawdata is missing_data: daily_perc_vol = self.calculate_daily_percentage_vol(instrument_code) else: daily_perc_vol = rawdata.get_daily_percentage_volatility( instrument_code ) return daily_perc_vol @diagnostic() def calculate_daily_percentage_vol(self, instrument_code: str) -> pd.Series: # backadjusted prices can be negative underlying_price = self.get_underlying_price(instrument_code) return_vol = self.calculate_daily_returns_vol(instrument_code) daily_vol_as_ratio = return_vol / underlying_price daily_perc_vol = 100.0 * daily_vol_as_ratio return daily_perc_vol @diagnostic() def calculate_daily_returns_vol(self, instrument_code: str) -> pd.Series: price = self._daily_prices_direct_from_data(instrument_code) returns_vol = robust_vol_calc(price.diff()) return returns_vol @input def _daily_prices_direct_from_data(self, instrument_code: str) -> pd.Series: price = self.data.daily_prices(instrument_code) return price @diagnostic() def get_vol_target_dict(self) -> dict: # FIXME UGLY REPLACE WITH COMPONENTS """ Get the daily cash vol target Requires: percentage_vol_target, notional_trading_capital, base_currency To find these, look in (a) in system.config.parameters... (b).... if not found, in systems.get_defaults.py :Returns: tuple (str, float): str is base_currency, float is value >>> from systems.tests.testdata import get_test_object_futures_with_comb_forecasts >>> from systems.basesystem import System >>> (comb, fcs, rules, rawdata, data, config)=get_test_object_futures_with_comb_forecasts() >>> system=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> >>> ## from config >>> system.positionSize.get_vol_target_dict()['base_currency'] 'GBP' >>> >>> ## from defaults >>> del(config.base_currency) >>> system=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> system.positionSize.get_vol_target_dict()['base_currency'] 'USD' >>> """ self.log.msg("Getting vol target") percentage_vol_target = self.get_percentage_vol_target() notional_trading_capital = self.get_notional_trading_capital() base_currency = self.get_base_currency() annual_cash_vol_target = self.annual_cash_vol_target() daily_cash_vol_target = self.get_daily_cash_vol_target() vol_target_dict = dict( base_currency=base_currency, percentage_vol_target=percentage_vol_target, notional_trading_capital=notional_trading_capital, annual_cash_vol_target=annual_cash_vol_target, daily_cash_vol_target=daily_cash_vol_target, ) return vol_target_dict @diagnostic() def get_daily_cash_vol_target(self) -> float: annual_cash_vol_target = self.annual_cash_vol_target() daily_cash_vol_target = annual_cash_vol_target / ROOT_BDAYS_INYEAR return daily_cash_vol_target @diagnostic() def annual_cash_vol_target(self) -> float: notional_trading_capital = self.get_notional_trading_capital() percentage_vol_target = self.get_percentage_vol_target() annual_cash_vol_target = ( notional_trading_capital * percentage_vol_target / 100.0 ) return annual_cash_vol_target @input def get_notional_trading_capital(self) -> float: notional_trading_capital = float( self.config.notional_trading_capital) return notional_trading_capital @input def get_percentage_vol_target(self): return float(self.config.percentage_vol_target) @diagnostic() def get_base_currency(self) -> str: base_currency = self.config.base_currency return base_currency @input def get_fx_rate(self, instrument_code: str) -> pd.Series: """ Get FX rate to translate instrument volatility into same currency as account value. KEY INPUT :param instrument_code: instrument to get values for :type instrument_code: str :returns: Tx1 pd.DataFrame: fx rate >>> from systems.tests.testdata import get_test_object_futures_with_comb_forecasts >>> from systems.basesystem import System >>> (comb, fcs, rules, rawdata, data, config)=get_test_object_futures_with_comb_forecasts() >>> system=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> >>> system.positionSize.get_fx_rate("EDOLLAR").tail(2) fx 2015-12-09 0.664311 2015-12-10 0.660759 """ base_currency = self.get_base_currency() fx_rate = self.data.get_fx_for_instrument( instrument_code, base_currency) return fx_rate @input def get_combined_forecast(self, instrument_code: str) -> pd.Series: """ Get the combined forecast from previous module :param instrument_code: instrument to get values for :type instrument_code: str :returns: Tx1 pd.DataFrame KEY INPUT >>> from systems.tests.testdata import get_test_object_futures_with_comb_forecasts >>> from systems.basesystem import System >>> (comb, fcs, rules, rawdata, data, config)=get_test_object_futures_with_comb_forecasts() >>> system=System([rawdata, rules, fcs, comb, PositionSizing()], data, config) >>> >>> system.positionSize.get_combined_forecast("EDOLLAR").tail(2) comb_forecast 2015-12-10 1.619134 2015-12-11 2.462610 """ return self.comb_forecast_stage.get_combined_forecast(instrument_code) @property def comb_forecast_stage(self) -> ForecastCombine: return self.parent.combForecast if __name__ == "__main__": import doctest doctest.testmod()
gpl-3.0
kernc/scikit-learn
doc/datasets/mldata_fixture.py
367
1183
"""Fixture module to skip the datasets loading when offline Mock urllib2 access to mldata.org and create a temporary data folder. """ from os import makedirs from os.path import join import numpy as np import tempfile import shutil from sklearn import datasets from sklearn.utils.testing import install_mldata_mock from sklearn.utils.testing import uninstall_mldata_mock def globs(globs): # Create a temporary folder for the data fetcher global custom_data_home custom_data_home = tempfile.mkdtemp() makedirs(join(custom_data_home, 'mldata')) globs['custom_data_home'] = custom_data_home return globs def setup_module(): # setup mock urllib2 module to avoid downloading from mldata.org install_mldata_mock({ 'mnist-original': { 'data': np.empty((70000, 784)), 'label': np.repeat(np.arange(10, dtype='d'), 7000), }, 'iris': { 'data': np.empty((150, 4)), }, 'datasets-uci-iris': { 'double0': np.empty((150, 4)), 'class': np.empty((150,)), }, }) def teardown_module(): uninstall_mldata_mock() shutil.rmtree(custom_data_home)
bsd-3-clause
e-koch/TurbuStat
turbustat/statistics/dendrograms/dendro_stats.py
2
34290
# Licensed under an MIT open source license - see LICENSE from __future__ import print_function, absolute_import, division ''' Dendrogram statistics as described in Burkhart et al. (2013) Two statistics are contained: * number of leaves + branches vs. $\delta$ parameter * statistical moments of the intensity histogram Requires the astrodendro package (http://github.com/astrodendro/dendro-core) ''' import numpy as np from warnings import warn import statsmodels.api as sm from astropy.utils.console import ProgressBar import warnings try: from astrodendro import Dendrogram, periodic_neighbours astrodendro_flag = True except ImportError: Warning("Need to install astrodendro to use dendrogram statistics.") astrodendro_flag = False from ..stats_utils import hellinger, common_histogram_bins, standardize from ..base_statistic import BaseStatisticMixIn from ...io import common_types, threed_types, twod_types from .mecdf import mecdf class Dendrogram_Stats(BaseStatisticMixIn): """ Dendrogram statistics as described in Burkhart et al. (2013) Two statistics are contained: * number of leaves & branches vs. :math:`\delta` parameter * statistical moments of the intensity histogram Parameters ---------- data : %(dtypes)s Data to create the dendrogram from. min_deltas : {`~numpy.ndarray`, 'auto', None}, optional Minimum deltas of leaves in the dendrogram. Multiple values must be given in increasing order to correctly prune the dendrogram. The default estimates delta levels from percentiles in the data. dendro_params : dict Further parameters for the dendrogram algorithm (see www.dendrograms.org for more info). num_deltas : int, optional Number of min_delta values to use when `min_delta='auto'`. """ __doc__ %= {"dtypes": " or ".join(common_types + twod_types + threed_types)} def __init__(self, data, header=None, min_deltas='auto', dendro_params=None, num_deltas=10): super(Dendrogram_Stats, self).__init__() if not astrodendro_flag: raise ImportError("astrodendro must be installed to use " "Dendrogram_Stats.") self.input_data_header(data, header) if dendro_params is None: self.dendro_params = {"min_npix": 10, "min_value": 0.001, "min_delta": 0.1} else: self.dendro_params = dendro_params if min_deltas == 'auto': self.autoset_min_deltas(num=num_deltas) else: self.min_deltas = min_deltas @property def min_deltas(self): ''' Array of min_delta values to compute the dendrogram. ''' return self._min_deltas @min_deltas.setter def min_deltas(self, value): # In the case where only one min_delta is given if "min_delta" in self.dendro_params and value is None: self._min_deltas = np.array([self.dendro_params["min_delta"]]) else: # Multiple values given. Ensure they are in increasing order if not (np.diff(value) > 0).all(): raise ValueError("Multiple values of min_delta must be given " "in increasing order.") if not isinstance(value, np.ndarray): self._min_deltas = np.array([value]) else: self._min_deltas = value def autoset_min_deltas(self, num=10): ''' Create an array delta values that the dendrogram will be pruned to. Creates equally-spaced delta values between the minimum value set in `~Dendrogram_Stats.dendro_params` and the maximum in the data. The last delta (which would only occur at the peak in the data) is removed. Parameters ---------- num : int, optional Number of delta values to create. ''' min_val = self.dendro_params.get('min_value', -np.inf) min_delta = self.dendro_params.get('min_delta', 1e-5) # Calculate the ptp above the min_val ptp = np.nanmax(self.data[self.data > min_val]) - min_val self.min_deltas = np.linspace(min_delta, ptp, num + 1)[:-1] def compute_dendro(self, show_progress=False, save_dendro=False, dendro_name=None, dendro_obj=None, periodic_bounds=False): ''' Compute the dendrogram and prune to the minimum deltas. ** min_deltas must be in ascending order! ** Parameters ---------- show_progress : optional, bool Enables the progress bar in astrodendro. save_dendro : optional, bool Saves the dendrogram in HDF5 format. **Requires pyHDF5** dendro_name : str, optional Save name when save_dendro is enabled. ".hdf5" appended automatically. dendro_obj : Dendrogram, optional Input a pre-computed dendrogram object. It is assumed that the dendrogram has already been computed! periodic_bounds : bool, optional Enable when the data is periodic in the spatial dimensions. ''' self._numfeatures = np.empty(self.min_deltas.shape, dtype=int) self._values = [] if dendro_obj is None: if periodic_bounds: # Find the spatial dimensions num_axes = self.data.ndim spat_axes = [] for i, axis_type in enumerate(self._wcs.get_axis_types()): if axis_type["coordinate_type"] == u"celestial": spat_axes.append(num_axes - i - 1) neighbours = periodic_neighbours(spat_axes) else: neighbours = None d = Dendrogram.compute(self.data, verbose=show_progress, min_delta=self.min_deltas[0], min_value=self.dendro_params["min_value"], min_npix=self.dendro_params["min_npix"], neighbours=neighbours) else: d = dendro_obj self._numfeatures[0] = len(d) self._values.append(np.array([struct.vmax for struct in d.all_structures])) if len(self.min_deltas) > 1: # Another progress bar for pruning steps if show_progress: print("Pruning steps.") bar = ProgressBar(len(self.min_deltas[1:])) for i, delta in enumerate(self.min_deltas[1:]): d.prune(min_delta=delta) self._numfeatures[i + 1] = len(d) self._values.append(np.array([struct.vmax for struct in d.all_structures])) if show_progress: bar.update(i + 1) @property def numfeatures(self): ''' Number of branches and leaves at each value of min_delta ''' return self._numfeatures @property def values(self): ''' Array of peak intensity values of leaves and branches at all values of min_delta. ''' return self._values def make_hists(self, min_number=10, **kwargs): ''' Creates histograms based on values from the tree. *Note:* These histograms are remade when calculating the distance to ensure the proper form for the Hellinger distance. Parameters ---------- min_number : int, optional Minimum number of structures needed to create a histogram. ''' hists = [] for value in self.values: if len(value) < min_number: hists.append([np.zeros((0, ))] * 2) continue if 'bins' not in kwargs: bins = int(np.sqrt(len(value))) else: bins = kwargs['bins'] kwargs.pop('bins') hist, bins = np.histogram(value, bins=bins, **kwargs) bin_cents = (bins[:-1] + bins[1:]) / 2 hists.append([bin_cents, hist]) self._hists = hists @property def hists(self): ''' Histogram values and bins computed from the peak intensity in all structures. One set of values and bins are returned for each value of `~Dendro_Statistics.min_deltas` ''' return self._hists def fit_numfeat(self, size=5, verbose=False): ''' Fit a line to the power-law tail. The break is approximated using a moving window, computing the standard deviation. A spike occurs at the break point. Parameters ---------- size : int. optional Size of std. window. Passed to std_window. verbose : bool, optional Shows the model summary. ''' if len(self.numfeatures) == 1: raise ValueError("Multiple min_delta values must be provided to " "perform fitting. Only one value was given.") nums = self.numfeatures[self.numfeatures > 1] deltas = self.min_deltas[self.numfeatures > 1] # Find the position of the break break_pos = std_window(nums, size=size) self.break_pos = deltas[break_pos] # Still enough point to fit to? if len(deltas[break_pos:]) < 2: raise ValueError("Too few points to fit. Try running with more " "min_deltas or lowering the std. window size.") # Remove points where there is only 1 feature or less. self._fitvals = [np.log10(deltas[break_pos:]), np.log10(nums[break_pos:])] x = sm.add_constant(self.fitvals[0]) self._model = sm.OLS(self.fitvals[1], x).fit(cov_type='HC3') if verbose: print(self.model.summary()) errors = self.model.bse self._tail_slope = self.model.params[-1] self._tail_slope_err = errors[-1] @property def model(self): ''' Power-law tail fit model. ''' return self._model @property def fitvals(self): ''' Log values of delta and number of structures used for the power-law tail fit. ''' return self._fitvals @property def tail_slope(self): ''' Slope of power-law tail. ''' return self._tail_slope @property def tail_slope_err(self): ''' 1-sigma error on slope of power-law tail. ''' return self._tail_slope_err @staticmethod def load_dendrogram(hdf5_file, min_deltas=None): ''' Load in a previously saved dendrogram. **Requires pyHDF5** Parameters ---------- hdf5_file : str Name of saved file. min_deltas : numpy.ndarray or list Minimum deltas of leaves in the dendrogram. ''' dendro = Dendrogram.load_from(hdf5_file) self = Dendrogram_Stats(dendro.data, min_deltas=min_deltas, dendro_params=dendro.params) return self def plot_fit(self, save_name=None, show_hists=True, color='r', fit_color='k', symbol='o'): ''' Parameters ---------- save_name : str,optional Save the figure when a file name is given. xunit : u.Unit, optional The unit to show the x-axis in. show_hists : bool, optional Plot the histograms of intensity. Requires `~Dendrogram_Stats.make_hists` to be run first. color : {str, RGB tuple}, optional Color to show the delta-variance curve in. fit_color : {str, RGB tuple}, optional Color of the fitted line. Defaults to `color` when no input is given. ''' import matplotlib.pyplot as plt if not show_hists: ax1 = plt.subplot(111) else: ax1 = plt.subplot(121) if fit_color is None: fit_color = color ax1.plot(self.fitvals[0], self.fitvals[1], symbol, color=color) ax1.plot(self.fitvals[0], self.model.fittedvalues, color=fit_color) plt.xlabel(r"log $\delta$") plt.ylabel(r"log Number of Features") if show_hists: ax2 = plt.subplot(122) if not hasattr(self, "_hists"): raise ValueError("Histograms were not computed with " "Dendrogram_Stats.make_hists. Cannot plot.") for bins, vals in self.hists: if bins.size < 1: continue bin_width = np.abs(bins[1] - bins[0]) ax2.bar(bins, vals, align="center", width=bin_width, alpha=0.25, color=color) plt.xlabel("Data Value") plt.tight_layout() if save_name is not None: plt.savefig(save_name) plt.close() else: plt.show() def run(self, periodic_bounds=False, verbose=False, save_name=None, show_progress=True, dendro_obj=None, save_results=False, output_name=None, fit_kwargs={}, make_hists=True, hist_kwargs={}): ''' Compute dendrograms. Necessary to maintain the package format. Parameters ---------- periodic_bounds : bool or list, optional Enable when the data is periodic in the spatial dimensions. Passing a two-element list can be used to individually set how the boundaries are treated for the datasets. verbose : optional, bool Enable plotting of results. save_name : str,optional Save the figure when a file name is given. show_progress : optional, bool Enables progress bars while making the dendrogram. dendro_obj : Dendrogram, optional Pass a pre-computed dendrogram object. **MUST have min_delta set at or below the smallest value in`~Dendro_Statistics.min_deltas`.** save_results : bool, optional Save the statistic results as a pickle file. See `~Dendro_Statistics.save_results`. output_name : str, optional Filename used when `save_results` is enabled. Must be given when saving. fit_kwargs : dict, optional Passed to `~Dendro_Statistics.fit_numfeat`. make_hists : bool, optional Enable computing histograms. hist_kwargs : dict, optional Passed to `~Dendro_Statistics.make_hists`. ''' self.compute_dendro(show_progress=show_progress, dendro_obj=dendro_obj, periodic_bounds=periodic_bounds) self.fit_numfeat(verbose=verbose, **fit_kwargs) if make_hists: self.make_hists(**hist_kwargs) if verbose: self.plot_fit(save_name=save_name, show_hists=make_hists) if save_results: self.save_results(output_name=output_name) class Dendrogram_Distance(object): """ Calculate the distance between 2 cubes using dendrograms. The number of features vs. minimum delta is fit to a linear model, with an interaction term to gauge the difference. The distance is the t-statistic of that parameter. The Hellinger distance is computed for the histograms at each minimum delta value. The distance is the average of the Hellinger distances. .. note:: When passing a computed `~DeltaVariance` class for `dataset1` or `dataset2`, it may be necessary to recompute the dendrogram if `~Dendrogram_Stats.min_deltas` does not equal `min_deltas` generated here (or passed as kwarg). Parameters ---------- dataset1 : %(dtypes)s or `~Dendrogram_Stats` Data cube or 2D image. Or pass a `~Dendrogram_Stats` class that may be pre-computed. where the dendrogram statistics are saved. dataset2 : %(dtypes)s or `~Dendrogram_Stats` See `dataset1` above. min_deltas : numpy.ndarray or list Minimum deltas (branch heights) of leaves in the dendrogram. The set of dendrograms must be computed with the same minimum branch heights. nbins : str or float, optional Number of bins for the histograms. 'best' sets that number using the square root of the average number of features between the histograms to be compared. min_features : int, optional The minimum number of features (branches and leaves) for the histogram be used in the histogram distance. dendro_params : dict or list of dicts, optional Further parameters for the dendrogram algorithm (see the `astrodendro documentation <dendrograms.readthedocs.io>`_ for more info). If a list of dictionaries is given, the first list entry should be the dictionary for `dataset1`, and the second for `dataset2`. dendro_kwargs : dict, optional Passed to `~turbustat.statistics.Dendrogram_Stats.run`. dendro2_kwargs : None, dict, optional Passed to `~turbustat.statistics.Dendrogram_Stats.run` for `dataset2`. When `None` is given, parameters given in `dendro_kwargs` will be used for both datasets. """ __doc__ %= {"dtypes": " or ".join(common_types + twod_types + threed_types)} def __init__(self, dataset1, dataset2, min_deltas=None, nbins="best", min_features=100, dendro_params=None, dendro_kwargs={}, dendro2_kwargs=None): if not astrodendro_flag: raise ImportError("astrodendro must be installed to use " "Dendrogram_Stats.") self.nbins = nbins if min_deltas is None: # min_deltas = np.append(np.logspace(-1.5, -0.7, 8), # np.logspace(-0.6, -0.35, 10)) warnings.warn("Using default min_deltas ranging from 10^-2.5 to" "10^0.5. Check whether this range is appropriate" " for your data.") min_deltas = np.logspace(-2.5, 0.5, 100) if dendro_params is not None: if isinstance(dendro_params, list): dendro_params1 = dendro_params[0] dendro_params2 = dendro_params[1] elif isinstance(dendro_params, dict): dendro_params1 = dendro_params dendro_params2 = dendro_params else: raise TypeError("dendro_params is a {}. It must be a dictionary" ", or a list containing a dictionary entries." .format(type(dendro_params))) else: dendro_params1 = None dendro_params2 = None if dendro2_kwargs is None: dendro2_kwargs = dendro_kwargs # if fiducial_model is not None: # self.dendro1 = fiducial_model # elif isinstance(dataset1, str): # self.dendro1 = Dendrogram_Stats.load_results(dataset1) if isinstance(dataset1, Dendrogram_Stats): self.dendro1 = dataset1 # Check if we need to re-run the stat has_slope = hasattr(self.dendro1, "_tail_slope") match_deltas = (self.dendro1.min_deltas == min_deltas).all() if not has_slope or not match_deltas: warn("Dendrogram_Stats needs to be re-run for dataset1 " "to compute the slope or have the same set of " "`min_deltas`.") dendro_kwargs.pop('make_hists', None) dendro_kwargs.pop('verbose', None) self.dendro1.run(verbose=False, make_hists=False, **dendro_kwargs) else: self.dendro1 = Dendrogram_Stats(dataset1, min_deltas=min_deltas, dendro_params=dendro_params1) dendro_kwargs.pop('make_hists', None) dendro_kwargs.pop('verbose', None) self.dendro1.run(verbose=False, make_hists=False, **dendro_kwargs) # if isinstance(dataset2, str): # self.dendro2 = Dendrogram_Stats.load_results(dataset2) if isinstance(dataset2, Dendrogram_Stats): self.dendro2 = dataset2 # Check if we need to re-run the stat has_slope = hasattr(self.dendro2, "_tail_slope") match_deltas = (self.dendro2.min_deltas == min_deltas).all() if not has_slope or not match_deltas: warn("Dendrogram_Stats needs to be re-run for dataset2 " "to compute the slope or have the same set of " "`min_deltas`.") dendro_kwargs.pop('make_hists', None) dendro_kwargs.pop('verbose', None) self.dendro2.run(verbose=False, make_hists=False, **dendro2_kwargs) else: self.dendro2 = \ Dendrogram_Stats(dataset2, min_deltas=min_deltas, dendro_params=dendro_params2) dendro_kwargs.pop('make_hists', None) dendro_kwargs.pop('verbose', None) self.dendro2.run(verbose=False, make_hists=False, **dendro2_kwargs) # Set the minimum number of components to create a histogram cutoff1 = np.argwhere(self.dendro1.numfeatures > min_features) cutoff2 = np.argwhere(self.dendro2.numfeatures > min_features) if cutoff1.any(): cutoff1 = cutoff1[-1] else: raise ValueError("The dendrogram from dataset1 does not contain the" " necessary number of features, %s. Lower" " min_features or alter min_deltas." % (min_features)) if cutoff2.any(): cutoff2 = cutoff2[-1] else: raise ValueError("The dendrogram from dataset2 does not contain the" " necessary number of features, %s. Lower" " min_features or alter min_deltas." % (min_features)) self.cutoff = np.min([cutoff1, cutoff2]) @property def num_distance(self): ''' Distance between slopes from the for to the log Number of features vs. branch height. ''' return self._num_distance def numfeature_stat(self, verbose=False, save_name=None, plot_kwargs1={}, plot_kwargs2={}): ''' Calculate the distance based on the number of features statistic. Parameters ---------- verbose : bool, optional Enables plotting. save_name : str, optional Saves the plot when a filename is given. plot_kwargs1 : dict, optional Set the color, symbol, and label for dataset1 (e.g., plot_kwargs1={'color': 'b', 'symbol': 'D', 'label': '1'}). plot_kwargs2 : dict, optional Set the color, symbol, and label for dataset2. ''' self._num_distance = \ np.abs(self.dendro1.tail_slope - self.dendro2.tail_slope) / \ np.sqrt(self.dendro1.tail_slope_err**2 + self.dendro2.tail_slope_err**2) if verbose: import matplotlib.pyplot as plt defaults1 = {'color': 'b', 'symbol': 'D', 'label': '1'} defaults2 = {'color': 'g', 'symbol': 'o', 'label': '2'} for key in defaults1: if key not in plot_kwargs1: plot_kwargs1[key] = defaults1[key] for key in defaults2: if key not in plot_kwargs2: plot_kwargs2[key] = defaults2[key] if 'xunit' in plot_kwargs1: del plot_kwargs1['xunit'] if 'xunit' in plot_kwargs2: del plot_kwargs2['xunit'] plt.figure() # Dendrogram 1 plt.plot(self.dendro1.fitvals[0], self.dendro1.fitvals[1], plot_kwargs1['symbol'], label=plot_kwargs1['label'], color=plot_kwargs1['color']) plt.plot(self.dendro1.fitvals[0], self.dendro1.model.fittedvalues, plot_kwargs1['color']) # Dendrogram 2 plt.plot(self.dendro2.fitvals[0], self.dendro2.fitvals[1], plot_kwargs2['symbol'], label=plot_kwargs2['label'], color=plot_kwargs2['color']) plt.plot(self.dendro2.fitvals[0], self.dendro2.model.fittedvalues, plot_kwargs2['color']) plt.grid(True) plt.xlabel(r"log $\delta$") plt.ylabel("log Number of Features") plt.legend(loc='best') plt.tight_layout() if save_name is not None: plt.savefig(save_name) plt.close() else: plt.show() return self @property def histogram_distance(self): return self._histogram_distance def histogram_stat(self, verbose=False, save_name=None, plot_kwargs1={}, plot_kwargs2={}): ''' Computes the distance using histograms. Parameters ---------- verbose : bool, optional Enables plotting. save_name : str, optional Saves the plot when a filename is given. plot_kwargs1 : dict, optional Set the color, symbol, and label for dataset1 (e.g., plot_kwargs1={'color': 'b', 'symbol': 'D', 'label': '1'}). plot_kwargs2 : dict, optional Set the color, symbol, and label for dataset2. ''' if self.nbins == "best": self.nbins = [np.floor(np.sqrt((n1 + n2) / 2.)) for n1, n2 in zip(self.dendro1.numfeatures[:self.cutoff], self.dendro2.numfeatures[:self.cutoff])] else: self.nbins = [self.nbins] * \ len(self.dendro1.numfeatures[:self.cutoff]) self.nbins = np.array(self.nbins, dtype=int) self.histograms1 = \ np.empty((len(self.dendro1.numfeatures[:self.cutoff]), np.max(self.nbins))) self.histograms2 = \ np.empty((len(self.dendro2.numfeatures[:self.cutoff]), np.max(self.nbins))) self.bins = [] for n, (data1, data2, nbin) in enumerate( zip(self.dendro1.values[:self.cutoff], self.dendro2.values[:self.cutoff], self.nbins)): stand_data1 = standardize(data1) stand_data2 = standardize(data2) bins = common_histogram_bins(stand_data1, stand_data2, nbins=nbin + 1) self.bins.append(bins) hist1 = np.histogram(stand_data1, bins=bins, density=True)[0] self.histograms1[n, :] = \ np.append(hist1, (np.max(self.nbins) - bins.size + 1) * [np.NaN]) hist2 = np.histogram(stand_data2, bins=bins, density=True)[0] self.histograms2[n, :] = \ np.append(hist2, (np.max(self.nbins) - bins.size + 1) * [np.NaN]) # Normalize self.histograms1[n, :] /= np.nansum(self.histograms1[n, :]) self.histograms2[n, :] /= np.nansum(self.histograms2[n, :]) self.mecdf1 = mecdf(self.histograms1) self.mecdf2 = mecdf(self.histograms2) self._histogram_distance = hellinger_stat(self.histograms1, self.histograms2) if verbose: import matplotlib.pyplot as plt defaults1 = {'color': 'b', 'symbol': 'D', 'label': '1'} defaults2 = {'color': 'g', 'symbol': 'o', 'label': '2'} for key in defaults1: if key not in plot_kwargs1: plot_kwargs1[key] = defaults1[key] for key in defaults2: if key not in plot_kwargs2: plot_kwargs2[key] = defaults2[key] if 'xunit' in plot_kwargs1: del plot_kwargs1['xunit'] if 'xunit' in plot_kwargs2: del plot_kwargs2['xunit'] plt.figure() ax1 = plt.subplot(2, 2, 1) ax1.set_title(plot_kwargs1['label']) ax1.set_ylabel("ECDF") for n in range(len(self.dendro1.min_deltas[:self.cutoff])): ax1.plot((self.bins[n][:-1] + self.bins[n][1:]) / 2, self.mecdf1[n, :][:self.nbins[n]], plot_kwargs1['symbol'], color=plot_kwargs1['color']) ax1.axes.xaxis.set_ticklabels([]) ax2 = plt.subplot(2, 2, 2) ax2.set_title(plot_kwargs2['label']) ax2.axes.xaxis.set_ticklabels([]) ax2.axes.yaxis.set_ticklabels([]) for n in range(len(self.dendro2.min_deltas[:self.cutoff])): ax2.plot((self.bins[n][:-1] + self.bins[n][1:]) / 2, self.mecdf2[n, :][:self.nbins[n]], plot_kwargs2['symbol'], color=plot_kwargs2['color']) ax3 = plt.subplot(2, 2, 3) ax3.set_ylabel("PDF") for n in range(len(self.dendro1.min_deltas[:self.cutoff])): bin_width = self.bins[n][1] - self.bins[n][0] ax3.bar((self.bins[n][:-1] + self.bins[n][1:]) / 2, self.histograms1[n, :][:self.nbins[n]], align="center", width=bin_width, alpha=0.25, color=plot_kwargs1['color']) ax3.set_xlabel("z-score") ax4 = plt.subplot(2, 2, 4) for n in range(len(self.dendro2.min_deltas[:self.cutoff])): bin_width = self.bins[n][1] - self.bins[n][0] ax4.bar((self.bins[n][:-1] + self.bins[n][1:]) / 2, self.histograms2[n, :][:self.nbins[n]], align="center", width=bin_width, alpha=0.25, color=plot_kwargs2['color']) ax4.set_xlabel("z-score") ax4.axes.yaxis.set_ticklabels([]) plt.tight_layout() if save_name is not None: plt.savefig(save_name) plt.close() else: plt.show() return self def distance_metric(self, verbose=False, save_name=None, plot_kwargs1={}, plot_kwargs2={}): ''' Calculate both distance metrics. Parameters ---------- verbose : bool, optional Enables plotting. save_name : str, optional Save plots by passing a file name. `hist_distance` and `num_distance` will be appended to the file name to distinguish the plots made with the two metrics. plot_kwargs1 : dict, optional Set the color, symbol, and label for dataset1 (e.g., plot_kwargs1={'color': 'b', 'symbol': 'D', 'label': '1'}). plot_kwargs2 : dict, optional Set the color, symbol, and label for dataset2. ''' if save_name is not None: import os # Distinguish name for the two plots base_name, extens = os.path.splitext(save_name) save_name_hist = "{0}.hist_distance{1}".format(base_name, extens) save_name_num = "{0}.num_distance{1}".format(base_name, extens) else: save_name_hist = None save_name_num = None self.histogram_stat(verbose=verbose, plot_kwargs1=plot_kwargs1, plot_kwargs2=plot_kwargs2, save_name=save_name_hist) self.numfeature_stat(verbose=verbose, plot_kwargs1=plot_kwargs1, plot_kwargs2=plot_kwargs2, save_name=save_name_num) return self def DendroDistance(*args, **kwargs): ''' Old name for the Dendrogram_Distance class. ''' warn("Use the new 'Dendrogram_Distance' class. 'DendroDistance' is deprecated and will" " be removed in a future release.", Warning) return Dendrogram_Distance(*args, **kwargs) def hellinger_stat(x, y): ''' Compute the Hellinger statistic of multiple samples. ''' assert x.shape == y.shape if len(x.shape) == 1: return hellinger(x, y) else: dists = np.empty((x.shape[0], 1)) for n in range(x.shape[0]): dists[n, 0] = hellinger(x[n, :], y[n, :]) return np.mean(dists) def std_window(y, size=5, return_results=False): ''' Uses a moving standard deviation window to find where the powerlaw break is. Parameters ---------- y : np.ndarray Data. size : int, optional Odd integer which sets the window size. return_results : bool, optional If enabled, returns the results of the window. Otherwise, only the position of the break is returned. ''' half_size = (size - 1) // 2 shape = max(y.shape) stds = np.empty((shape - size + 1)) for i in range(half_size, shape - half_size): stds[i - half_size] = np.std(y[i - half_size: i + half_size]) # Now find the max break_pos = np.argmax(stds) + half_size if return_results: return break_pos, stds return break_pos
mit
chanceraine/nupic.research
projects/sequence_prediction/discrete_sequences/lstm_old/predict_LSTM_2.py
2
7108
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import operator import random import time from matplotlib import pyplot as plt import numpy as np from pybrain.datasets import SequentialDataSet from pybrain.tools.shortcuts import buildNetwork from pybrain.structure.modules import LSTMLayer from pybrain.supervised import RPropMinusTrainer from predict import generateSequences from plot import plotAccuracy NUM_PREDICTIONS = 1 vectors = {} def num2vec(num, nDim): if num in vectors: return vectors[num] sample = np.random.random((1,nDim)) # if num < 100: # vectors[num] = sample vectors[num] = sample return sample def seq2vec(sequence, nDim): nSample = len(sequence) seq_vec = np.zeros((nSample, nDim)) for i in xrange(nSample): seq_vec[i] = num2vec(sequence[i], nDim) return seq_vec def closest_node(node, nodes): nodes = np.array(nodes) dist_2 = np.sum((nodes - node)**2, axis=2) return np.argmin(dist_2) def classify(netActivation): idx = closest_node(netActivation, vectors.values()) return vectors.keys()[idx] def initializeLSTMnet(nDim, nLSTMcells=10): # Build LSTM network with nDim input units, nLSTMcells hidden units (LSTM cells) and nDim output cells net = buildNetwork(nDim, nLSTMcells, nDim, hiddenclass=LSTMLayer, bias=True, outputbias=False, recurrent=True) return net if __name__ == "__main__": sequences = generateSequences(NUM_PREDICTIONS) # nDim = max([len(sequence) for sequence in sequences]) + 2 # TODO: Why 2? nDim = 100 from pylab import rcParams rcParams.update({'figure.autolayout': True}) rcParams.update({'figure.facecolor': 'white'}) rcParams.update({'ytick.labelsize': 8}) # for i in xrange(len(sequences)): # sequence = sequences[i] # print sequence # seq_vec = seq2vec(sequence, nDim) # for j in xrange(len(sequence)-1): # ds.addSample(seq_vec[j], seq_vec[j+1]) # ds.newSequence() rptPerSeqList = [1, 2, 5, 10, 20, 50, 100, 250, 500, 1000] accuracyList = [] for rptNum in rptPerSeqList: # train LSTM # net = initializeLSTMnet(nDim, nLSTMcells=30) # net.reset() # trainer = RPropMinusTrainer(net) # for _ in xrange(rptNum): # # Batch training mode # # print "generate a dataset of sequences" # ds = SequentialDataSet(nDim, nDim) # trainer.setData(ds) # import random # random.shuffle(sequences) # concat_sequences = [] # for sequence in sequences: # concat_sequences += sequence # concat_sequences.append(random.randrange(100, 1000000)) # # concat_sequences = sum(sequences, []) # for j in xrange(len(concat_sequences) - 1): # ds.addSample(num2vec(concat_sequences[j], nDim), num2vec(concat_sequences[j+1], nDim)) # trainer.train() net = initializeLSTMnet(nDim, nLSTMcells=50) net.reset() ds = SequentialDataSet(nDim, nDim) trainer = RPropMinusTrainer(net) trainer.setData(ds) for _ in xrange(1000): # Batch training mode # print "generate a dataset of sequences" import random random.shuffle(sequences) concat_sequences = [] for sequence in sequences: concat_sequences += sequence concat_sequences.append(random.randrange(100, 1000000)) for j in xrange(len(concat_sequences) - 1): ds.addSample(num2vec(concat_sequences[j], nDim), num2vec(concat_sequences[j+1], nDim)) trainer.trainEpochs(rptNum) print print "test LSTM, repeats =", rptNum # test LSTM correct = [] for i in xrange(len(sequences)): net.reset() sequence = sequences[i] sequence = sequence + [random.randrange(100, 1000000)] print sequence predictedInput = [] for j in xrange(len(sequence)): sample = num2vec(sequence[j], nDim) netActivation = net.activate(sample) if j+1 < len(sequence) - 1: predictedInput.append(classify(netActivation)) print " actual input: ", sequence[j+1], " predicted Input: ", predictedInput[j] correct.append(predictedInput[j] == sequence[j+1]) # correct.append(predictedInput[-1] == sequence[-1]) accuracyList.append(sum(correct)/float(len(correct))) print "Accuracy: ", accuracyList[-1] plt.semilogx(np.array(rptPerSeqList), np.array(accuracyList), '-*') plt.xlabel(' Repeat of entire batch') plt.ylabel(' Accuracy ') plt.show() # online mode (does not work well) # net = initializeLSTMnet(nDim, nLSTMcells=20) # accuracyList = [] # for seq in xrange(5000): # sequence = random.choice(sequences) # print sequence # seq_vec = seq2vec(sequence, nDim) # ds = SequentialDataSet(nDim, nDim) # for j in xrange(len(sequence)-1): # ds.addSample(seq_vec[j], seq_vec[j+1]) # # # test LSTM # net.reset() # predictedInput = [] # for i in xrange(len(sequence)-1): # sample = num2vec(sequence[i], nDim) # netActivation = net.activate(sample) # predictedInput.append(np.argmax(netActivation)) # print " predicted Input: ", predictedInput[i], " actual input: ", sequence[i+1] # # accuracyList.append(predictedInput[-1] == sequence[-1]) # # # train LSTM # net.reset() # trainer = RPropMinusTrainer(net, dataset=ds) # trainer.trainEpochs(1) # # # test LSTM on the whole dataset # # correct = [] # # for i in xrange(len(sequences)): # # sequence = sequences[i] # # print sequence # # net.reset() # # predictedInput = [] # # for j in xrange(len(sequence)-1): # # sample = num2vec(sequence[j], nDim) # # netActivation = net.activate(sample) # # predictedInput.append(np.argmax(netActivation)) # # print " actual input: ", sequence[j+1], " predicted Input: ", predictedInput[j] # # # # correct.append(predictedInput[-1] == sequence[-1]) # # accuracyList.append(sum(correct)/float(len(correct))) # # if seq % 100 == 0: # rcParams.update({'figure.figsize': (12, 6)}) # plt.figure(1) # plt.clf() # plotAccuracy(accuracyList) # plt.draw()
agpl-3.0
OspreyX/trading-with-python
historicDataDownloader/historicDataDownloader.py
77
4526
''' Created on 4 aug. 2012 Copyright: Jev Kuznetsov License: BSD a module for downloading historic data from IB ''' import ib import pandas from ib.ext.Contract import Contract from ib.opt import ibConnection, message from time import sleep import tradingWithPython.lib.logger as logger from pandas import DataFrame, Index import datetime as dt from timeKeeper import TimeKeeper import time timeFormat = "%Y%m%d %H:%M:%S" class DataHandler(object): ''' handles incoming messages ''' def __init__(self,tws): self._log = logger.getLogger('DH') tws.register(self.msgHandler,message.HistoricalData) self.reset() def reset(self): self._log.debug('Resetting data') self.dataReady = False self._timestamp = [] self._data = {'open':[],'high':[],'low':[],'close':[],'volume':[],'count':[],'WAP':[]} def msgHandler(self,msg): #print '[msg]', msg if msg.date[:8] == 'finished': self._log.debug('Data recieved') self.dataReady = True return self._timestamp.append(dt.datetime.strptime(msg.date,timeFormat)) for k in self._data.keys(): self._data[k].append(getattr(msg, k)) @property def data(self): ''' return downloaded data as a DataFrame ''' df = DataFrame(data=self._data,index=Index(self._timestamp)) return df class Downloader(object): def __init__(self,debug=False): self._log = logger.getLogger('DLD') self._log.debug('Initializing data dwonloader. Pandas version={0}, ibpy version:{1}'.format(pandas.__version__,ib.version)) self.tws = ibConnection() self._dataHandler = DataHandler(self.tws) if debug: self.tws.registerAll(self._debugHandler) self.tws.unregister(self._debugHandler,message.HistoricalData) self._log.debug('Connecting to tws') self.tws.connect() self._timeKeeper = TimeKeeper() # keep track of past requests self._reqId = 1 # current request id def _debugHandler(self,msg): print '[debug]', msg def requestData(self,contract,endDateTime,durationStr='1800 S',barSizeSetting='1 secs',whatToShow='TRADES',useRTH=1,formatDate=1): self._log.debug('Requesting data for %s end time %s.' % (contract.m_symbol,endDateTime)) while self._timeKeeper.nrRequests(timeSpan=600) > 59: print 'Too many requests done. Waiting... ' time.sleep(1) self._timeKeeper.addRequest() self._dataHandler.reset() self.tws.reqHistoricalData(self._reqId,contract,endDateTime,durationStr,barSizeSetting,whatToShow,useRTH,formatDate) self._reqId+=1 #wait for data startTime = time.time() timeout = 3 while not self._dataHandler.dataReady and (time.time()-startTime < timeout): sleep(2) if not self._dataHandler.dataReady: self._log.error('Data timeout') print self._dataHandler.data return self._dataHandler.data def getIntradayData(self,contract, dateTuple ): ''' get full day data on 1-s interval date: a tuple of (yyyy,mm,dd) ''' openTime = dt.datetime(*dateTuple)+dt.timedelta(hours=16) closeTime = dt.datetime(*dateTuple)+dt.timedelta(hours=22) timeRange = pandas.date_range(openTime,closeTime,freq='30min') datasets = [] for t in timeRange: datasets.append(self.requestData(contract,t.strftime(timeFormat))) return pandas.concat(datasets) def disconnect(self): self.tws.disconnect() if __name__=='__main__': dl = Downloader(debug=True) c = Contract() c.m_symbol = 'SPY' c.m_secType = 'STK' c.m_exchange = 'SMART' c.m_currency = 'USD' df = dl.getIntradayData(c, (2012,8,6)) df.to_csv('test.csv') # df = dl.requestData(c, '20120803 22:00:00') # df.to_csv('test1.csv') # df = dl.requestData(c, '20120803 21:30:00') # df.to_csv('test2.csv') dl.disconnect() print 'Done.'
bsd-3-clause
MohMehrnia/TextBaseEmotionDetectionWithEnsembleMethod
TextEmotionDetection.py
1
22843
import numpy as np import pandas as pd import csv import os.path import warnings from sklearn.preprocessing import LabelEncoder from nltk.corpus import stopwords from nltk.stem.porter import * from nltk.tokenize import RegexpTokenizer from collections import namedtuple from hpsklearn import HyperoptEstimator, svc, knn, random_forest, decision_tree, gaussian_nb, pca from sklearn import svm from hyperopt import tpe from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.naive_bayes import GaussianNB from sklearn.metrics import f1_score from sklearn.metrics import accuracy_score from sklearn.ensemble import VotingClassifier from dbn.tensorflow import SupervisedDBNClassification from nltk.stem import WordNetLemmatizer warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim') from gensim.models.doc2vec import Doc2Vec def readdata(train_set_path): x = [] y = [] stop_words = set(stopwords.words('english')) with open(train_set_path, encoding="utf8") as infile: for line in infile: data = [] data = line.split(",") stemmer = PorterStemmer() lemmatizer = WordNetLemmatizer() if data[1] != "tweet_id": content = re.sub(r"(?:\@|https?\://)\S+", "", data[3].lower()) toker = RegexpTokenizer(r'((?<=[^\w\s])\w(?=[^\w\s])|(\W))+', gaps=True) word_tokens = toker.tokenize(content) # filtered_sentence = [stemmer.stem(w) for w in word_tokens if not w in stop_words and w.isalpha()] filtered_sentence = [lemmatizer.lemmatize(w) for w in word_tokens if not w in stop_words and w.isalpha()] x.append(' '.join(filtered_sentence)) y.append(data[1]) x, y = np.array(x), np.array(y) return x, y def encode_label(label): le = LabelEncoder() label_encoded = le.fit(label).transform(label) print(le.classes_) return label_encoded def loaddata(filename,instancecol): file_reader = csv.reader(open(filename,'r'),delimiter=',') x = [] y = [] for row in file_reader: x.append(row[0:instancecol]) y.append(row[-1]) return np.array(x[1:]).astype(np.float32), np.array(y[1:]).astype(np.int) def create_model(x, y, feature_count): docs = [] dfs = [] features_vectors = pd.DataFrame() analyzedDocument = namedtuple('AnalyzedDocument', 'words tags') for i, text in enumerate(x): words = text.lower().split() tags = [i] docs.append(analyzedDocument(words, tags)) model = Doc2Vec(docs, size=feature_count, window=300, min_count=1, workers=4) for i in range(model.docvecs.__len__()): dfs.append(model.docvecs[i].transpose()) features_vectors = pd.DataFrame(dfs) features_vectors['label'] = y return features_vectors, model def extract_features(dataset_csv, feature_csv, instancecol): if not os.path.exists(feature_csv): print('Beginning Extract Features.......') x, y = readdata(dataset_csv) y = encode_label(y) features_vactors, model = create_model(x, y, instancecol) features_vactors.to_csv(feature_csv, mode='a', header=False, index=False) print('Ending Extract Features.......') else: print('Loading Last Features.......') x, y = loaddata(feature_csv, instancecol) print('End Loading Last Features.......') return x, y def svm_model(): estim = svm.SVC() estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def svm_model_tpe(): estim = HyperoptEstimator(classifier=svc('my_clf', kernels=['linear', 'sigmoid']), preprocessing=[pca('my_pca')], algo=tpe.suggest, max_evals=150, trial_timeout=60, verbose=0) estim.fit(x_train, y_train) print("score", estim.score(x_test, y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) print(estim.best_model()) def knn_model(): estim = KNeighborsClassifier(n_neighbors=3) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def knn_model_tpe(): estim = HyperoptEstimator(classifier=knn('my_clf'), preprocessing=[pca('my_pca')], algo=tpe.suggest, max_evals=150, trial_timeout=60, verbose=0) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) print(estim.best_model()) def randomforest_model(): estim = RandomForestClassifier(max_depth=2, random_state=0) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def randomforst_model_tpe(): estim = HyperoptEstimator(classifier=random_forest('my_clf'), preprocessing=[pca('my_pca')], algo=tpe.suggest, max_evals=150, trial_timeout=60, verbose=0) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) print(estim.best_model()) def decisiontree_model(): estim = DecisionTreeClassifier(random_state=0) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def decisiontree_model_tpe(): estim = HyperoptEstimator(classifier=decision_tree('my_clf', min_samples_leaf=0.2, min_samples_split=0.5), preprocessing=[pca('my_pca')], algo=tpe.suggest, max_evals=150, trial_timeout=60, verbose=0) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) print(estim.best_model()) def gaussian_nb_model(): estim = GaussianNB() estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def gaussian_nb_model_tpe(): estim = HyperoptEstimator(classifier=gaussian_nb('my_clf'), preprocessing=[pca('my_pca')], algo=tpe.suggest, max_evals=150, trial_timeout=60, verbose=0) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) print(estim.best_model()) def gaussian_nb_model(): estim = GaussianNB() estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def gaussian_nb_model_tpe(): estim = HyperoptEstimator(classifier=gaussian_nb('my_clf'), preprocessing=[pca('my_pca')], algo=tpe.suggest, max_evals=150, trial_timeout=60, verbose=0) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) print(estim.best_model()) def dbn(): estim = SupervisedDBNClassification(hidden_layers_structure=[256, 256, 256, 256, 256, 256 ], learning_rate_rbm=0.05, learning_rate=0.1, n_epochs_rbm=10, n_iter_backprop=100, batch_size=32, activation_function='relu', dropout_p=0.2, verbose=0) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) return 0 def ensemble_group1_without_tpe(): clf1 = DecisionTreeClassifier(random_state=0) clf2 = GaussianNB() clf3 = KNeighborsClassifier(n_neighbors=3) clf4 = RandomForestClassifier(max_depth=2, random_state=0) clf5 = svm.SVC(probability=True) estim = VotingClassifier(estimators=[('dt', clf1), ('GNB', clf2), ('KNN', clf3), ('RF', clf4), ('svm', clf5)], voting='soft', weights=[97.98, 93.11, 99.05, 99.09, 99.09]) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test, average='micro')) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def ensemble_group1(): clf1 = DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=None, max_features='log2', max_leaf_nodes=None, min_samples_leaf=0.2, min_samples_split=0.5, min_weight_fraction_leaf=0.0, presort=False, random_state=2, splitter='random') clf2 = GaussianNB(priors=None) clf3 = KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='euclidean', metric_params=None, n_jobs=1, n_neighbors=5, p=2, weights='distance') clf4 = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='entropy', max_depth=None, max_features=0.6933792121972574, max_leaf_nodes=None, min_samples_leaf=18, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=2078, n_jobs=1, oob_score=False, random_state=1, verbose=False, warm_start=False) clf5 = svm.SVC(C=1045.8970220658168, cache_size=512, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=1, gamma='auto', kernel='linear', max_iter=14263117.0, random_state=3, shrinking=False, probability=True, tol=5.3658140645203695e-05, verbose=False) estim = VotingClassifier(estimators=[('dt', clf1), ('GNB', clf2), ('KNN', clf3), ('RF', clf4), ('svm', clf5)], voting='soft', weights=[99.09, 99.05, 99.05, 99.09, 99.09]) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test, average='micro')) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def ensemble_group2_without_tpe(): clf1 = DecisionTreeClassifier(random_state=0) clf2 = GaussianNB() clf3 = KNeighborsClassifier(n_neighbors=3) clf4 = RandomForestClassifier(max_depth=2, random_state=0) clf5 = svm.SVC(probability=True) estim = VotingClassifier(estimators=[('dt', clf1), ('GNB', clf2), ('KNN', clf3)], voting='soft', weights=[97.98, 93.11, 99.05]) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def ensemble_group2(): clf1 = DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=None, max_features='log2', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=0.2, min_samples_split=0.5, min_weight_fraction_leaf=0.0, presort=False, random_state=2, splitter='random') clf2 = GaussianNB(priors=None) clf3 = KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='euclidean', metric_params=None, n_jobs=1, n_neighbors=5, p=2, weights='distance') clf4 = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='entropy', max_depth=None, max_features=0.6933792121972574, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=18, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=2078, n_jobs=1, oob_score=False, random_state=1, verbose=False, warm_start=False) clf5 = svm.SVC(C=1045.8970220658168, cache_size=512, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=1, gamma='auto', kernel='linear', max_iter=14263117.0, random_state=3, shrinking=False, probability=True, tol=5.3658140645203695e-05, verbose=False) estim = VotingClassifier(estimators=[('dt', clf1), ('GNB', clf2), ('KNN', clf3)], voting='soft', weights=[99.09, 99.05, 99.05]) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def ensemble_group3_without_tpe(): clf1 = DecisionTreeClassifier(random_state=0) clf2 = GaussianNB() clf3 = KNeighborsClassifier(n_neighbors=3) clf4 = RandomForestClassifier(max_depth=2, random_state=0) clf5 = svm.SVC(probability=True) estim = VotingClassifier(estimators=[('KNN', clf3), ('RF', clf4), ('svm', clf5)], voting='soft', weights=[99.05, 99.09, 99.09]) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def ensemble_group3(): clf1 = DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=None, max_features='log2', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=0.2, min_samples_split=0.5, min_weight_fraction_leaf=0.0, presort=False, random_state=2, splitter='random') clf2 = GaussianNB(priors=None) clf3 = KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='euclidean', metric_params=None, n_jobs=1, n_neighbors=5, p=2, weights='distance') clf4 = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='entropy', max_depth=None, max_features=0.6933792121972574, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=18, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=2078, n_jobs=1, oob_score=False, random_state=1, verbose=False, warm_start=False) clf5 = svm.SVC(C=1045.8970220658168, cache_size=512, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=1, gamma='auto', kernel='linear', max_iter=14263117.0, random_state=3, shrinking=False, probability=True, tol=5.3658140645203695e-05, verbose=False) estim = VotingClassifier(estimators=[('KNN', clf3), ('RF', clf4), ('svm', clf5)], voting='soft', weights=[99.05, 99.09, 99.09]) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def ensemble_group4_without_tpe(): clf1 = DecisionTreeClassifier(random_state=0) clf2 = GaussianNB() clf3 = KNeighborsClassifier(n_neighbors=3) clf4 = RandomForestClassifier(max_depth=2, random_state=0) clf5 = svm.SVC(probability=True) estim = VotingClassifier(estimators=[('GNB', clf2), ('RF', clf4), ('svm', clf5)], voting='soft', weights=[93.11, 99.09, 99.09]) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def ensemble_group4(): clf1 = DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=None, max_features='log2', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=0.2, min_samples_split=0.5, min_weight_fraction_leaf=0.0, presort=False, random_state=2, splitter='random') clf2 = GaussianNB(priors=None) clf3 = KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='euclidean', metric_params=None, n_jobs=1, n_neighbors=5, p=2, weights='distance') clf4 = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='entropy', max_depth=None, max_features=0.6933792121972574, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=18, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=2078, n_jobs=1, oob_score=False, random_state=1, verbose=False, warm_start=False) clf5 = svm.SVC(C=1045.8970220658168, cache_size=512, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=1, gamma='auto', kernel='linear', max_iter=14263117.0, random_state=3, shrinking=False, probability=True, tol=5.3658140645203695e-05, verbose=False) estim = VotingClassifier(estimators=[('GNB', clf2), ('RF', clf4), ('svm', clf5)], voting='soft', weights=[99.05, 99.09, 99.09]) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def ensemble_group5_without_tpe(): clf1 = DecisionTreeClassifier(random_state=0) clf2 = GaussianNB() clf3 = KNeighborsClassifier(n_neighbors=3) clf4 = RandomForestClassifier(max_depth=2, random_state=0) clf5 = svm.SVC(probability=True) estim = VotingClassifier(estimators=[('GNB', clf2), ('KNN', clf3), ('svm', clf5)], voting='soft', weights=[93.11, 99.05, 99.09]) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) def ensemble_group5(): clf1 = DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=None, max_features='log2', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=0.2, min_samples_split=0.5, min_weight_fraction_leaf=0.0, presort=False, random_state=2, splitter='random') clf2 = GaussianNB(priors=None) clf3 = KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='euclidean', metric_params=None, n_jobs=1, n_neighbors=5, p=2, weights='distance') clf4 = RandomForestClassifier(bootstrap=True, class_weight=None, criterion='entropy', max_depth=None, max_features=0.6933792121972574, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=18, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=2078, n_jobs=1, oob_score=False, random_state=1, verbose=False, warm_start=False) clf5 = svm.SVC(C=1045.8970220658168, cache_size=512, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=1, gamma='auto', kernel='linear', max_iter=14263117.0, random_state=3, shrinking=False, probability=True, tol=5.3658140645203695e-05, verbose=False) estim = VotingClassifier(estimators=[('GNB', clf2), ('KNN', clf3), ('svm', clf5)], voting='soft', weights=[99.05, 99.05, 99.09]) estim.fit(x_train, y_train) print("f1score", f1_score(estim.predict(x_test), y_test)) print("accuracy score", accuracy_score(estim.predict(x_test), y_test)) if __name__ == '__main__': x_vectors, y_vectors = extract_features('D:\\My Source Codes\\Projects-Python' '\\TextBaseEmotionDetectionWithEnsembleMethod\\Dataset\\' 'text_emotion_6class.csv', 'D:\\My Source Codes\\Projects-Python' '\\TextBaseEmotionDetectionWithEnsembleMethod\\Dataset\\features6cl300le.csv', 100)
apache-2.0
jakobworldpeace/scikit-learn
examples/linear_model/plot_sgd_iris.py
58
2202
""" ======================================== Plot multi-class SGD on the iris dataset ======================================== Plot decision surface of multi-class SGD on iris dataset. The hyperplanes corresponding to the three one-versus-all (OVA) classifiers are represented by the dashed lines. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.linear_model import SGDClassifier # import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. We could # avoid this ugly slicing by using a two-dim dataset y = iris.target colors = "bry" # shuffle idx = np.arange(X.shape[0]) np.random.seed(13) np.random.shuffle(idx) X = X[idx] y = y[idx] # standardize mean = X.mean(axis=0) std = X.std(axis=0) X = (X - mean) / std h = .02 # step size in the mesh clf = SGDClassifier(alpha=0.001, n_iter=100).fit(X, y) # create a mesh to plot in 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, h), np.arange(y_min, y_max, h)) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, x_max]x[y_min, y_max]. Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired) plt.axis('tight') # Plot also the training points for i, color in zip(clf.classes_, colors): idx = np.where(y == i) plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i], cmap=plt.cm.Paired) plt.title("Decision surface of multi-class SGD") plt.axis('tight') # Plot the three one-against-all classifiers xmin, xmax = plt.xlim() ymin, ymax = plt.ylim() coef = clf.coef_ intercept = clf.intercept_ def plot_hyperplane(c, color): def line(x0): return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1] plt.plot([xmin, xmax], [line(xmin), line(xmax)], ls="--", color=color) for i, color in zip(clf.classes_, colors): plot_hyperplane(i, color) plt.legend() plt.show()
bsd-3-clause
kingtaurus/cs224d
assignment3/codebase_release/rnn_pytorch.py
1
6742
import sys import os import random import numpy as np import matplotlib.pyplot as plt import math import time import itertools import shutil import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from torch.nn.utils import clip_grad_norm import tree as tr from utils import Vocab from collections import OrderedDict import seaborn as sns from random import shuffle sns.set_style('whitegrid') embed_size = 100 label_size = 2 early_stopping = 2 anneal_threshold = 0.99 anneal_by = 1.5 max_epochs = 30 lr = 0.01 l2 = 0.02 average_over = 700 train_size = 800 class RNN_Model(nn.Module): def __init__(self, vocab, embed_size=100, label_size=2): super(RNN_Model, self).__init__() self.embed_size = embed_size self.label_size = label_size self.vocab = vocab self.embedding = nn.Embedding(int(self.vocab.total_words), self.embed_size) self.fcl = nn.Linear(self.embed_size, self.embed_size, bias=True) self.fcr = nn.Linear(self.embed_size, self.embed_size, bias=True) self.projection = nn.Linear(self.embed_size, self.label_size , bias=True) self.activation = F.relu self.node_list = [] def init_variables(self): print("total_words = ", self.vocab.total_words) def walk_tree(self, in_node): if in_node.isLeaf: word_id = torch.LongTensor((self.vocab.encode(in_node.word), )) current_node = self.embedding(Variable(word_id)) self.node_list.append(self.projection(current_node).unsqueeze(0)) else: left = self.walk_tree(in_node.left) right = self.walk_tree(in_node.right) current_node = self.activation(self.fcl(left) + self.fcl(right)) self.node_list.append(self.projection(current_node).unsqueeze(0)) return current_node def forward(self, x): """ Forward function accepts input data and returns a Variable of output data """ self.node_list = [] root_node = self.walk_tree(x.root) all_nodes = torch.cat(self.node_list) #now I need to project out return all_nodes def main(): print("do nothing") if __name__ == '__main__': train_data, dev_data, test_data = tr.simplified_data(train_size, 100, 200) vocab = Vocab() train_sents = [t.get_words() for t in train_data] vocab.construct(list(itertools.chain.from_iterable(train_sents))) model = RNN_Model(vocab, embed_size=50) main() lr = 0.01 loss_history = [] optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9, dampening=0.0) # params (iterable): iterable of parameters to optimize or dicts defining # parameter groups # lr (float): learning rate # momentum (float, optional): momentum factor (default: 0) # weight_decay (float, optional): weight decay (L2 penalty) (default: 0) #torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9, dampening=0, weight_decay=0) # print(model.fcl._parameters['weight']) for epoch in range(max_epochs): print("epoch = ", epoch) shuffle(train_data) total_root_prediction = 0. total_summed_accuracy = 0. if (epoch % 10 == 0) and epoch > 0: for param_group in optimizer.param_groups: #update learning rate print("Droping learning from %f to %f"%(param_group['lr'], 0.5 * param_group['lr'])) param_group['lr'] = 0.5 * param_group['lr'] for step, tree in enumerate(train_data): # if step == 0: # optimizer.zero_grad() # objective_loss.backward() # if step == len(train_data) - 1: # optimizer.step() all_nodes = model(tree) labels = [] indices = [] for x,y in enumerate(tree.labels): if y != 2: labels.append(y) indices.append(x) torch_labels = torch.LongTensor([l for l in labels if l != 2]) logits = all_nodes.index_select(dim=0, index=Variable(torch.LongTensor(indices))) logits_squeezed = logits.squeeze() predictions = logits.max(dim=2)[1].squeeze() correct = predictions.data == torch_labels #so correctly predicted (root); total_root_prediction += float(correct[-1]) total_summed_accuracy += float(correct.sum()) / len(labels) objective_loss = F.cross_entropy(input=logits_squeezed, target=Variable(torch_labels)) if objective_loss.data[0] > 5 and epoch > 10: #interested in phrase that have large loss (i.e. incorrectly classified) print(' '.join(tree.get_words())) loss_history.append(objective_loss.data[0]) if step % 20 == 0 and step > 0: print("step %3d, last loss %0.3f, mean loss (%d steps) %0.3f" % (step, objective_loss.data[0], average_over, np.mean(loss_history[-average_over:]))) optimizer.zero_grad() if np.isnan(objective_loss.data[0]): print("object_loss was not a number") sys.exit(1) else: objective_loss.backward() clip_grad_norm(model.parameters(), 5, norm_type=2.) #temp_grad += model.fcl._parameters['weight'].grad.data # # Update weights using gradient descent; w1.data and w2.data are Tensors, # # w1.grad and w2.grad are Variables and w1.grad.data and w2.grad.data are # # Tensors. # loss.backward() # w1.data -= learning_rate * w1.grad.data # w2.data -= learning_rate * w2.grad.data optimizer.step() print("total root predicted correctly = ", total_root_prediction/ float(train_size)) print("total node (including root) predicted correctly = ", total_summed_accuracy / float(train_size)) total_dev_loss = 0. dev_correct_at_root = 0. dev_correct_all = 0. for step, dev_example in enumerate(dev_data): all_nodes = model(dev_example) labels = [] indices = [] for x,y in enumerate(dev_example.labels): if y != 2: labels.append(y) indices.append(x) torch_labels = torch.LongTensor([l for l in labels if l != 2]) logits = all_nodes.index_select(dim=0, index=Variable(torch.LongTensor(indices))) logits_squeezed = logits.squeeze() predictions = logits.max(dim=2)[1].squeeze() correct = predictions.data == torch_labels #so correctly predicted (root); dev_correct_at_root += float(correct[-1]) dev_correct_all += float(correct.sum()) / len(labels) objective_loss = F.cross_entropy(input=logits_squeezed, target=Variable(torch_labels)) total_dev_loss += objective_loss.data[0] print("total_dev_loss = ", total_dev_loss) print("correct (root) = ", dev_correct_at_root) print("correct (all)= ", dev_correct_all) # logits = logits.index_select(dim=0, index=Variable(torch.LongTensor(indices))) plt.figure() plt.plot(loss_history) plt.show() print("DONE!")
mit
jl2922/hci
extrapolate_o3.py
1
3771
""" Obtain results from csv and extrapolate to CBS & FCI limit.""" import sys import numpy as np import pandas as pd import statsmodels.api as sm np.set_printoptions(precision=12) def printCorrelationEnergy(statsResult): coefs = statsResult.params.values stdevs = statsResult.bse print('Correlation Energy: ' + str(coefs[0]) + ' +- ' + str(stdevs[0])) def BEWRegression(X, y, e, title): augX = sm.add_constant(X) # Backward elimination. print('\n' + '#' * 80) print('REG: ' + title) print('-' * 80) print('Backward elimination:') results = sm.WLS(y, augX, weights=1.0 / np.square(e)).fit() intercept = results.params.values[0] variance = np.square( np.dot(augX, np.abs(results.params.values)) + intercept) + np.square(e) iteration = 0 while True: results = sm.WLS(y, augX, weights=1.0 / variance).fit() printCorrelationEnergy(results) intercept = results.params.values[0] variance = np.square( np.dot(augX, np.abs(results.params.values)) + intercept) + np.square(e) iteration = iteration + 1 if iteration < 5: continue maxPIndex = np.argmax(results.pvalues) maxP = results.pvalues[maxPIndex] if maxP < 0.5: break print('Eliminate: ' + maxPIndex) print('P > |t|: ' + str(maxP)) augX.drop(maxPIndex, axis=1, inplace=True) # Weighted OLS print('\n[FINAL Weighted OLS]') variance = np.square( np.dot(augX, np.abs(results.params.values)) + intercept) + np.square(e) results = sm.WLS(y, augX, weights=1.0 / variance).fit() # print(results.summary()) printCorrelationEnergy(results) def main(): """main function""" # Check and read res file. res_file = 'pt_result.csv' if len(sys.argv) == 2: res_file = sys.argv[1] parameters = ['n_orbs_var_inv', 'eps_var', 'n_orbs_pt_inv', 'eps_pt'] # Read raw data. data = pd.read_csv(res_file) # Add inverse terms. data['n_orbs_var_inv'] = 1.0 / data['n_orbs_var'] data['n_orbs_pt_inv'] = 1.0 / data['n_orbs_pt'] # Remove parameters not enough for extrapolation. for parameter in parameters: if data[parameter].value_counts().size < 3: parameters.remove(parameter) # Add cross terms. selectedParameters = parameters[:] for i in range(len(parameters)): for j in range(i, len(parameters)): for k in range(j, len(parameters)): column = parameters[i] + ' * ' + \ parameters[j] + ' * ' + parameters[k] selectedParameters.append(column) data[column] = data[parameters[i]] * \ data[parameters[j]] * data[parameters[k]] # Estimate intercept. X = data[selectedParameters] y = data['energy_corr'] e = data['uncert'] BEWRegression(X, y, e, 'all data') for i, parameter in enumerate(parameters): maxValue = X.max()[i] keep = X[parameter] != maxValue X_rmax = X[keep] y_rmax = y[keep] e_rmax = e[keep] BEWRegression(X_rmax, y_rmax, e_rmax, 'accu data') for i, parameter in enumerate(parameters): minValue = X.min()[i] keep = X[parameter] != minValue X_rmin = X[keep] y_rmin = y[keep] e_rmin = e[keep] BEWRegression(X_rmin, y_rmin, e_rmin, 'verify data') for i, parameter in enumerate(parameters): maxValue = X_rmin.max()[i] keep = X_rmin[parameter] != maxValue X_rminmax = X_rmin[keep] y_rminmax = y_rmin[keep] e_rminmax = e_rmin[keep] BEWRegression(X_rminmax, y_rminmax, e_rminmax, 'verify accu data') if __name__ == '__main__': main()
mit
linebp/pandas
pandas/tests/frame/test_subclass.py
15
9524
# -*- coding: utf-8 -*- from __future__ import print_function from warnings import catch_warnings import numpy as np from pandas import DataFrame, Series, MultiIndex, Panel import pandas as pd import pandas.util.testing as tm from pandas.tests.frame.common import TestData class TestDataFrameSubclassing(TestData): def test_frame_subclassing_and_slicing(self): # Subclass frame and ensure it returns the right class on slicing it # In reference to PR 9632 class CustomSeries(Series): @property def _constructor(self): return CustomSeries def custom_series_function(self): return 'OK' class CustomDataFrame(DataFrame): """ Subclasses pandas DF, fills DF with simulation results, adds some custom plotting functions. """ def __init__(self, *args, **kw): super(CustomDataFrame, self).__init__(*args, **kw) @property def _constructor(self): return CustomDataFrame _constructor_sliced = CustomSeries def custom_frame_function(self): return 'OK' data = {'col1': range(10), 'col2': range(10)} cdf = CustomDataFrame(data) # Did we get back our own DF class? assert isinstance(cdf, CustomDataFrame) # Do we get back our own Series class after selecting a column? cdf_series = cdf.col1 assert isinstance(cdf_series, CustomSeries) assert cdf_series.custom_series_function() == 'OK' # Do we get back our own DF class after slicing row-wise? cdf_rows = cdf[1:5] assert isinstance(cdf_rows, CustomDataFrame) assert cdf_rows.custom_frame_function() == 'OK' # Make sure sliced part of multi-index frame is custom class mcol = pd.MultiIndex.from_tuples([('A', 'A'), ('A', 'B')]) cdf_multi = CustomDataFrame([[0, 1], [2, 3]], columns=mcol) assert isinstance(cdf_multi['A'], CustomDataFrame) mcol = pd.MultiIndex.from_tuples([('A', ''), ('B', '')]) cdf_multi2 = CustomDataFrame([[0, 1], [2, 3]], columns=mcol) assert isinstance(cdf_multi2['A'], CustomSeries) def test_dataframe_metadata(self): df = tm.SubclassedDataFrame({'X': [1, 2, 3], 'Y': [1, 2, 3]}, index=['a', 'b', 'c']) df.testattr = 'XXX' assert df.testattr == 'XXX' assert df[['X']].testattr == 'XXX' assert df.loc[['a', 'b'], :].testattr == 'XXX' assert df.iloc[[0, 1], :].testattr == 'XXX' # see gh-9776 assert df.iloc[0:1, :].testattr == 'XXX' # see gh-10553 unpickled = tm.round_trip_pickle(df) tm.assert_frame_equal(df, unpickled) assert df._metadata == unpickled._metadata assert df.testattr == unpickled.testattr def test_indexing_sliced(self): # GH 11559 df = tm.SubclassedDataFrame({'X': [1, 2, 3], 'Y': [4, 5, 6], 'Z': [7, 8, 9]}, index=['a', 'b', 'c']) res = df.loc[:, 'X'] exp = tm.SubclassedSeries([1, 2, 3], index=list('abc'), name='X') tm.assert_series_equal(res, exp) assert isinstance(res, tm.SubclassedSeries) res = df.iloc[:, 1] exp = tm.SubclassedSeries([4, 5, 6], index=list('abc'), name='Y') tm.assert_series_equal(res, exp) assert isinstance(res, tm.SubclassedSeries) res = df.loc[:, 'Z'] exp = tm.SubclassedSeries([7, 8, 9], index=list('abc'), name='Z') tm.assert_series_equal(res, exp) assert isinstance(res, tm.SubclassedSeries) res = df.loc['a', :] exp = tm.SubclassedSeries([1, 4, 7], index=list('XYZ'), name='a') tm.assert_series_equal(res, exp) assert isinstance(res, tm.SubclassedSeries) res = df.iloc[1, :] exp = tm.SubclassedSeries([2, 5, 8], index=list('XYZ'), name='b') tm.assert_series_equal(res, exp) assert isinstance(res, tm.SubclassedSeries) res = df.loc['c', :] exp = tm.SubclassedSeries([3, 6, 9], index=list('XYZ'), name='c') tm.assert_series_equal(res, exp) assert isinstance(res, tm.SubclassedSeries) def test_to_panel_expanddim(self): # GH 9762 with catch_warnings(record=True): class SubclassedFrame(DataFrame): @property def _constructor_expanddim(self): return SubclassedPanel class SubclassedPanel(Panel): pass index = MultiIndex.from_tuples([(0, 0), (0, 1), (0, 2)]) df = SubclassedFrame({'X': [1, 2, 3], 'Y': [4, 5, 6]}, index=index) result = df.to_panel() assert isinstance(result, SubclassedPanel) expected = SubclassedPanel([[[1, 2, 3]], [[4, 5, 6]]], items=['X', 'Y'], major_axis=[0], minor_axis=[0, 1, 2], dtype='int64') tm.assert_panel_equal(result, expected) def test_subclass_attr_err_propagation(self): # GH 11808 class A(DataFrame): @property def bar(self): return self.i_dont_exist with tm.assert_raises_regex(AttributeError, '.*i_dont_exist.*'): A().bar def test_subclass_align(self): # GH 12983 df1 = tm.SubclassedDataFrame({'a': [1, 3, 5], 'b': [1, 3, 5]}, index=list('ACE')) df2 = tm.SubclassedDataFrame({'c': [1, 2, 4], 'd': [1, 2, 4]}, index=list('ABD')) res1, res2 = df1.align(df2, axis=0) exp1 = tm.SubclassedDataFrame({'a': [1, np.nan, 3, np.nan, 5], 'b': [1, np.nan, 3, np.nan, 5]}, index=list('ABCDE')) exp2 = tm.SubclassedDataFrame({'c': [1, 2, np.nan, 4, np.nan], 'd': [1, 2, np.nan, 4, np.nan]}, index=list('ABCDE')) assert isinstance(res1, tm.SubclassedDataFrame) tm.assert_frame_equal(res1, exp1) assert isinstance(res2, tm.SubclassedDataFrame) tm.assert_frame_equal(res2, exp2) res1, res2 = df1.a.align(df2.c) assert isinstance(res1, tm.SubclassedSeries) tm.assert_series_equal(res1, exp1.a) assert isinstance(res2, tm.SubclassedSeries) tm.assert_series_equal(res2, exp2.c) def test_subclass_align_combinations(self): # GH 12983 df = tm.SubclassedDataFrame({'a': [1, 3, 5], 'b': [1, 3, 5]}, index=list('ACE')) s = tm.SubclassedSeries([1, 2, 4], index=list('ABD'), name='x') # frame + series res1, res2 = df.align(s, axis=0) exp1 = pd.DataFrame({'a': [1, np.nan, 3, np.nan, 5], 'b': [1, np.nan, 3, np.nan, 5]}, index=list('ABCDE')) # name is lost when exp2 = pd.Series([1, 2, np.nan, 4, np.nan], index=list('ABCDE'), name='x') assert isinstance(res1, tm.SubclassedDataFrame) tm.assert_frame_equal(res1, exp1) assert isinstance(res2, tm.SubclassedSeries) tm.assert_series_equal(res2, exp2) # series + frame res1, res2 = s.align(df) assert isinstance(res1, tm.SubclassedSeries) tm.assert_series_equal(res1, exp2) assert isinstance(res2, tm.SubclassedDataFrame) tm.assert_frame_equal(res2, exp1) def test_subclass_iterrows(self): # GH 13977 df = tm.SubclassedDataFrame({'a': [1]}) for i, row in df.iterrows(): assert isinstance(row, tm.SubclassedSeries) tm.assert_series_equal(row, df.loc[i]) def test_subclass_sparse_slice(self): rows = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]] ssdf = tm.SubclassedSparseDataFrame(rows) ssdf.testattr = "testattr" tm.assert_sp_frame_equal(ssdf.loc[:2], tm.SubclassedSparseDataFrame(rows[:3])) tm.assert_sp_frame_equal(ssdf.iloc[:2], tm.SubclassedSparseDataFrame(rows[:2])) tm.assert_sp_frame_equal(ssdf[:2], tm.SubclassedSparseDataFrame(rows[:2])) assert ssdf.loc[:2].testattr == "testattr" assert ssdf.iloc[:2].testattr == "testattr" assert ssdf[:2].testattr == "testattr" tm.assert_sp_series_equal(ssdf.loc[1], tm.SubclassedSparseSeries(rows[1]), check_names=False) tm.assert_sp_series_equal(ssdf.iloc[1], tm.SubclassedSparseSeries(rows[1]), check_names=False) def test_subclass_sparse_transpose(self): ossdf = tm.SubclassedSparseDataFrame([[1, 2, 3], [4, 5, 6]]) essdf = tm.SubclassedSparseDataFrame([[1, 4], [2, 5], [3, 6]]) tm.assert_sp_frame_equal(ossdf.T, essdf)
bsd-3-clause
hhj0325/pystock
com/hhj/pystock/matplotlib_demo/pie_bar_demo.py
1
1939
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['axes.titlesize'] = 20 mpl.rcParams['xtick.labelsize'] = 16 mpl.rcParams['ytick.labelsize'] = 16 mpl.rcParams['axes.labelsize'] = 16 mpl.rcParams['xtick.major.size'] = 0 mpl.rcParams['ytick.major.size'] = 0 # 包含了狗,猫和猎豹的最高奔跑速度,还有对应的可视化颜色 speed_map = { 'dog': (48, '#7199cf'), 'cat': (45, '#4fc4aa'), 'cheetah': (120, '#e1a7a2') } # 整体图的标题 fig = plt.figure('Bar chart & Pie chart') # 在整张图上加入一个子图,121的意思是在一个1行2列的子图中的第一张 ax = fig.add_subplot(121) ax.set_title('Running speed - bar chart') # 生成x轴每个元素的位置 xticks = np.arange(3) # 定义柱状图每个柱的宽度 bar_width = 0.5 # 动物名称 animals = speed_map.keys() # 奔跑速度 speeds = [x[0] for x in speed_map.values()] # 对应颜色 colors = [x[1] for x in speed_map.values()] # 画柱状图,横轴是动物标签的位置,纵轴是速度,定义柱的宽度,同时设置柱的边缘为透明 bars = ax.bar(xticks, speeds, width=bar_width, edgecolor='none') # 设置y轴的标题 ax.set_ylabel('Speed(km/h)') # x轴每个标签的具体位置,设置为每个柱的中央 ax.set_xticks(xticks+bar_width/2) # 设置每个标签的名字 ax.set_xticklabels(animals) # 设置x轴的范围 ax.set_xlim([bar_width/2-0.5, 3-bar_width/2]) # 设置y轴的范围 ax.set_ylim([0, 125]) # 给每个bar分配指定的颜色 for bar, color in zip(bars, colors): bar.set_color(color) # 在122位置加入新的图 ax = fig.add_subplot(122) ax.set_title('Running speed - pie chart') # 生成同时包含名称和速度的标签 labels = ['{}\n{} km/h'.format(animal, speed) for animal, speed in zip(animals, speeds)] # 画饼状图,并指定标签和对应颜色 ax.pie(speeds, labels=labels, colors=colors) plt.show()
apache-2.0
AlexanderFabisch/scikit-learn
examples/linear_model/plot_sgd_loss_functions.py
73
1232
""" ========================== SGD: convex loss functions ========================== A plot that compares the various convex loss functions supported by :class:`sklearn.linear_model.SGDClassifier` . """ print(__doc__) import numpy as np import matplotlib.pyplot as plt def modified_huber_loss(y_true, y_pred): z = y_pred * y_true loss = -4 * z loss[z >= -1] = (1 - z[z >= -1]) ** 2 loss[z >= 1.] = 0 return loss xmin, xmax = -4, 4 xx = np.linspace(xmin, xmax, 100) lw = 2 plt.plot([xmin, 0, 0, xmax], [1, 1, 0, 0], color='gold', lw=lw, label="Zero-one loss") plt.plot(xx, np.where(xx < 1, 1 - xx, 0), color='teal', lw=lw, label="Hinge loss") plt.plot(xx, -np.minimum(xx, 0), color='yellowgreen', lw=lw, label="Perceptron loss") plt.plot(xx, np.log2(1 + np.exp(-xx)), color='cornflowerblue', lw=lw, label="Log loss") plt.plot(xx, np.where(xx < 1, 1 - xx, 0) ** 2, color='orange', lw=lw, label="Squared hinge loss") plt.plot(xx, modified_huber_loss(xx, 1), color='darkorchid', lw=lw, linestyle='--', label="Modified Huber loss") plt.ylim((0, 8)) plt.legend(loc="upper right") plt.xlabel(r"Decision function $f(x)$") plt.ylabel("$L(y, f(x))$") plt.show()
bsd-3-clause
RobertArbon/YAMLP
SciFlow/FFtraversal.py
1
2387
import ImportData import numpy as np import CoulombMatrix import cProfile, pstats, StringIO import time from datetime import datetime import matplotlib.pyplot as plt def fft_idx(X, k): """ This function does something. :param X: parameter X :param k: parameter k :return: returns training indexes """ # Creating the matrix of the distances dist_mat_glob = np.zeros(shape=(X.shape[0], X.shape[0])) for i in range(X.shape[0] - 1): for j in range(i + 1, X.shape[0]): distvec = X[j, :] - X[i, :] dist_mat_glob[i, j] = np.dot(distvec, distvec) dist_mat_glob[j, i] = np.dot(distvec, distvec) # print "Generated " + str(X.shape[0]) + " by " + str(X.shape[0]) + " distance matrix." n_samples = X.shape[0] train_set = [] idx = np.int32(np.random.uniform(n_samples)) train_set.append(idx) for i in range(1, k): dist_list = [] for index in train_set: dist_list.append(dist_mat_glob[index, :]) dist_set = np.amin(dist_list, axis=0) dist_idx = np.argmax(dist_set) train_set.append(dist_idx) # np.save("train_idx.npy",train_set) return train_set if __name__ == "__main__": X, y, Q = ImportData.loadPd_q("/Users/walfits/Repositories/trainingNN/dataSets/PBE_B3LYP/pbe_b3lyp_partQ_rel.csv") descript = CoulombMatrix.CoulombMatrix(X) # X_coul, y_coul = descript.generatePRCM(y_data=y, numRep=2) X_coul = descript.generateTrimmedCM() print X_coul.shape pr = cProfile.Profile() pr.enable() train_idx = fft_idx(X_coul[:5000, :], 4000) pr.disable() s = StringIO.StringIO() sortby = 'cumulative' ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats() print s.getvalue() # x = range(100, 1100, 100) # y = [] # # for i in range(100, 1100, 100): # X_set = X_coul[:i, :] # # Starting the timer # startTime = time.time() # fft_idx(X_coul[:i,:], int(i*0.8)) # # Ending the timer # endTime = time.time() # finalTime = endTime - startTime # y.append(finalTime) # # fig2, ax2 = plt.subplots(figsize=(6, 6)) # ax2.scatter(x, y) # ax2.set_xlabel('Data set size') # ax2.set_ylabel('Time to split (s)') # ax2.legend() # plt.show() # # print x # print y
mit
fengzhyuan/scikit-learn
sklearn/covariance/robust_covariance.py
198
29735
""" Robust location and covariance estimators. Here are implemented estimators that are resistant to outliers. """ # Author: Virgile Fritsch <[email protected]> # # License: BSD 3 clause import warnings import numbers import numpy as np from scipy import linalg from scipy.stats import chi2 from . import empirical_covariance, EmpiricalCovariance from ..utils.extmath import fast_logdet, pinvh from ..utils import check_random_state, check_array # Minimum Covariance Determinant # Implementing of an algorithm by Rousseeuw & Van Driessen described in # (A Fast Algorithm for the Minimum Covariance Determinant Estimator, # 1999, American Statistical Association and the American Society # for Quality, TECHNOMETRICS) # XXX Is this really a public function? It's not listed in the docs or # exported by sklearn.covariance. Deprecate? def c_step(X, n_support, remaining_iterations=30, initial_estimates=None, verbose=False, cov_computation_method=empirical_covariance, random_state=None): """C_step procedure described in [Rouseeuw1984]_ aiming at computing MCD. Parameters ---------- X : array-like, shape (n_samples, n_features) Data set in which we look for the n_support observations whose scatter matrix has minimum determinant. n_support : int, > n_samples / 2 Number of observations to compute the robust estimates of location and covariance from. remaining_iterations : int, optional Number of iterations to perform. According to [Rouseeuw1999]_, two iterations are sufficient to get close to the minimum, and we never need more than 30 to reach convergence. initial_estimates : 2-tuple, optional Initial estimates of location and shape from which to run the c_step procedure: - initial_estimates[0]: an initial location estimate - initial_estimates[1]: an initial covariance estimate verbose : boolean, optional Verbose mode. random_state : integer or numpy.RandomState, optional The random generator used. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. cov_computation_method : callable, default empirical_covariance The function which will be used to compute the covariance. Must return shape (n_features, n_features) Returns ------- location : array-like, shape (n_features,) Robust location estimates. covariance : array-like, shape (n_features, n_features) Robust covariance estimates. support : array-like, shape (n_samples,) A mask for the `n_support` observations whose scatter matrix has minimum determinant. References ---------- .. [Rouseeuw1999] A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS """ X = np.asarray(X) random_state = check_random_state(random_state) return _c_step(X, n_support, remaining_iterations=remaining_iterations, initial_estimates=initial_estimates, verbose=verbose, cov_computation_method=cov_computation_method, random_state=random_state) def _c_step(X, n_support, random_state, remaining_iterations=30, initial_estimates=None, verbose=False, cov_computation_method=empirical_covariance): n_samples, n_features = X.shape # Initialisation support = np.zeros(n_samples, dtype=bool) if initial_estimates is None: # compute initial robust estimates from a random subset support[random_state.permutation(n_samples)[:n_support]] = True else: # get initial robust estimates from the function parameters location = initial_estimates[0] covariance = initial_estimates[1] # run a special iteration for that case (to get an initial support) precision = pinvh(covariance) X_centered = X - location dist = (np.dot(X_centered, precision) * X_centered).sum(1) # compute new estimates support[np.argsort(dist)[:n_support]] = True X_support = X[support] location = X_support.mean(0) covariance = cov_computation_method(X_support) # Iterative procedure for Minimum Covariance Determinant computation det = fast_logdet(covariance) previous_det = np.inf while (det < previous_det) and (remaining_iterations > 0): # save old estimates values previous_location = location previous_covariance = covariance previous_det = det previous_support = support # compute a new support from the full data set mahalanobis distances precision = pinvh(covariance) X_centered = X - location dist = (np.dot(X_centered, precision) * X_centered).sum(axis=1) # compute new estimates support = np.zeros(n_samples, dtype=bool) support[np.argsort(dist)[:n_support]] = True X_support = X[support] location = X_support.mean(axis=0) covariance = cov_computation_method(X_support) det = fast_logdet(covariance) # update remaining iterations for early stopping remaining_iterations -= 1 previous_dist = dist dist = (np.dot(X - location, precision) * (X - location)).sum(axis=1) # Catch computation errors if np.isinf(det): raise ValueError( "Singular covariance matrix. " "Please check that the covariance matrix corresponding " "to the dataset is full rank and that MinCovDet is used with " "Gaussian-distributed data (or at least data drawn from a " "unimodal, symmetric distribution.") # Check convergence if np.allclose(det, previous_det): # c_step procedure converged if verbose: print("Optimal couple (location, covariance) found before" " ending iterations (%d left)" % (remaining_iterations)) results = location, covariance, det, support, dist elif det > previous_det: # determinant has increased (should not happen) warnings.warn("Warning! det > previous_det (%.15f > %.15f)" % (det, previous_det), RuntimeWarning) results = previous_location, previous_covariance, \ previous_det, previous_support, previous_dist # Check early stopping if remaining_iterations == 0: if verbose: print('Maximum number of iterations reached') results = location, covariance, det, support, dist return results def select_candidates(X, n_support, n_trials, select=1, n_iter=30, verbose=False, cov_computation_method=empirical_covariance, random_state=None): """Finds the best pure subset of observations to compute MCD from it. The purpose of this function is to find the best sets of n_support observations with respect to a minimization of their covariance matrix determinant. Equivalently, it removes n_samples-n_support observations to construct what we call a pure data set (i.e. not containing outliers). The list of the observations of the pure data set is referred to as the `support`. Starting from a random support, the pure data set is found by the c_step procedure introduced by Rousseeuw and Van Driessen in [Rouseeuw1999]_. Parameters ---------- X : array-like, shape (n_samples, n_features) Data (sub)set in which we look for the n_support purest observations. n_support : int, [(n + p + 1)/2] < n_support < n The number of samples the pure data set must contain. select : int, int > 0 Number of best candidates results to return. n_trials : int, nb_trials > 0 or 2-tuple Number of different initial sets of observations from which to run the algorithm. Instead of giving a number of trials to perform, one can provide a list of initial estimates that will be used to iteratively run c_step procedures. In this case: - n_trials[0]: array-like, shape (n_trials, n_features) is the list of `n_trials` initial location estimates - n_trials[1]: array-like, shape (n_trials, n_features, n_features) is the list of `n_trials` initial covariances estimates n_iter : int, nb_iter > 0 Maximum number of iterations for the c_step procedure. (2 is enough to be close to the final solution. "Never" exceeds 20). random_state : integer or numpy.RandomState, default None The random generator used. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. cov_computation_method : callable, default empirical_covariance The function which will be used to compute the covariance. Must return shape (n_features, n_features) verbose : boolean, default False Control the output verbosity. See Also --------- c_step Returns ------- best_locations : array-like, shape (select, n_features) The `select` location estimates computed from the `select` best supports found in the data set (`X`). best_covariances : array-like, shape (select, n_features, n_features) The `select` covariance estimates computed from the `select` best supports found in the data set (`X`). best_supports : array-like, shape (select, n_samples) The `select` best supports found in the data set (`X`). References ---------- .. [Rouseeuw1999] A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS """ random_state = check_random_state(random_state) n_samples, n_features = X.shape if isinstance(n_trials, numbers.Integral): run_from_estimates = False elif isinstance(n_trials, tuple): run_from_estimates = True estimates_list = n_trials n_trials = estimates_list[0].shape[0] else: raise TypeError("Invalid 'n_trials' parameter, expected tuple or " " integer, got %s (%s)" % (n_trials, type(n_trials))) # compute `n_trials` location and shape estimates candidates in the subset all_estimates = [] if not run_from_estimates: # perform `n_trials` computations from random initial supports for j in range(n_trials): all_estimates.append( _c_step( X, n_support, remaining_iterations=n_iter, verbose=verbose, cov_computation_method=cov_computation_method, random_state=random_state)) else: # perform computations from every given initial estimates for j in range(n_trials): initial_estimates = (estimates_list[0][j], estimates_list[1][j]) all_estimates.append(_c_step( X, n_support, remaining_iterations=n_iter, initial_estimates=initial_estimates, verbose=verbose, cov_computation_method=cov_computation_method, random_state=random_state)) all_locs_sub, all_covs_sub, all_dets_sub, all_supports_sub, all_ds_sub = \ zip(*all_estimates) # find the `n_best` best results among the `n_trials` ones index_best = np.argsort(all_dets_sub)[:select] best_locations = np.asarray(all_locs_sub)[index_best] best_covariances = np.asarray(all_covs_sub)[index_best] best_supports = np.asarray(all_supports_sub)[index_best] best_ds = np.asarray(all_ds_sub)[index_best] return best_locations, best_covariances, best_supports, best_ds def fast_mcd(X, support_fraction=None, cov_computation_method=empirical_covariance, random_state=None): """Estimates the Minimum Covariance Determinant matrix. Read more in the :ref:`User Guide <robust_covariance>`. Parameters ---------- X : array-like, shape (n_samples, n_features) The data matrix, with p features and n samples. support_fraction : float, 0 < support_fraction < 1 The proportion of points to be included in the support of the raw MCD estimate. Default is None, which implies that the minimum value of support_fraction will be used within the algorithm: `[n_sample + n_features + 1] / 2`. random_state : integer or numpy.RandomState, optional The generator used to randomly subsample. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. cov_computation_method : callable, default empirical_covariance The function which will be used to compute the covariance. Must return shape (n_features, n_features) Notes ----- The FastMCD algorithm has been introduced by Rousseuw and Van Driessen in "A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS". The principle is to compute robust estimates and random subsets before pooling them into a larger subsets, and finally into the full data set. Depending on the size of the initial sample, we have one, two or three such computation levels. Note that only raw estimates are returned. If one is interested in the correction and reweighting steps described in [Rouseeuw1999]_, see the MinCovDet object. References ---------- .. [Rouseeuw1999] A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS .. [Butler1993] R. W. Butler, P. L. Davies and M. Jhun, Asymptotics For The Minimum Covariance Determinant Estimator, The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400 Returns ------- location : array-like, shape (n_features,) Robust location of the data. covariance : array-like, shape (n_features, n_features) Robust covariance of the features. support : array-like, type boolean, shape (n_samples,) A mask of the observations that have been used to compute the robust location and covariance estimates of the data set. """ random_state = check_random_state(random_state) X = np.asarray(X) if X.ndim == 1: X = np.reshape(X, (1, -1)) warnings.warn("Only one sample available. " "You may want to reshape your data array") n_samples, n_features = X.shape # minimum breakdown value if support_fraction is None: n_support = int(np.ceil(0.5 * (n_samples + n_features + 1))) else: n_support = int(support_fraction * n_samples) # 1-dimensional case quick computation # (Rousseeuw, P. J. and Leroy, A. M. (2005) References, in Robust # Regression and Outlier Detection, John Wiley & Sons, chapter 4) if n_features == 1: if n_support < n_samples: # find the sample shortest halves X_sorted = np.sort(np.ravel(X)) diff = X_sorted[n_support:] - X_sorted[:(n_samples - n_support)] halves_start = np.where(diff == np.min(diff))[0] # take the middle points' mean to get the robust location estimate location = 0.5 * (X_sorted[n_support + halves_start] + X_sorted[halves_start]).mean() support = np.zeros(n_samples, dtype=bool) X_centered = X - location support[np.argsort(np.abs(X_centered), 0)[:n_support]] = True covariance = np.asarray([[np.var(X[support])]]) location = np.array([location]) # get precision matrix in an optimized way precision = pinvh(covariance) dist = (np.dot(X_centered, precision) * (X_centered)).sum(axis=1) else: support = np.ones(n_samples, dtype=bool) covariance = np.asarray([[np.var(X)]]) location = np.asarray([np.mean(X)]) X_centered = X - location # get precision matrix in an optimized way precision = pinvh(covariance) dist = (np.dot(X_centered, precision) * (X_centered)).sum(axis=1) # Starting FastMCD algorithm for p-dimensional case if (n_samples > 500) and (n_features > 1): # 1. Find candidate supports on subsets # a. split the set in subsets of size ~ 300 n_subsets = n_samples // 300 n_samples_subsets = n_samples // n_subsets samples_shuffle = random_state.permutation(n_samples) h_subset = int(np.ceil(n_samples_subsets * (n_support / float(n_samples)))) # b. perform a total of 500 trials n_trials_tot = 500 # c. select 10 best (location, covariance) for each subset n_best_sub = 10 n_trials = max(10, n_trials_tot // n_subsets) n_best_tot = n_subsets * n_best_sub all_best_locations = np.zeros((n_best_tot, n_features)) try: all_best_covariances = np.zeros((n_best_tot, n_features, n_features)) except MemoryError: # The above is too big. Let's try with something much small # (and less optimal) all_best_covariances = np.zeros((n_best_tot, n_features, n_features)) n_best_tot = 10 n_best_sub = 2 for i in range(n_subsets): low_bound = i * n_samples_subsets high_bound = low_bound + n_samples_subsets current_subset = X[samples_shuffle[low_bound:high_bound]] best_locations_sub, best_covariances_sub, _, _ = select_candidates( current_subset, h_subset, n_trials, select=n_best_sub, n_iter=2, cov_computation_method=cov_computation_method, random_state=random_state) subset_slice = np.arange(i * n_best_sub, (i + 1) * n_best_sub) all_best_locations[subset_slice] = best_locations_sub all_best_covariances[subset_slice] = best_covariances_sub # 2. Pool the candidate supports into a merged set # (possibly the full dataset) n_samples_merged = min(1500, n_samples) h_merged = int(np.ceil(n_samples_merged * (n_support / float(n_samples)))) if n_samples > 1500: n_best_merged = 10 else: n_best_merged = 1 # find the best couples (location, covariance) on the merged set selection = random_state.permutation(n_samples)[:n_samples_merged] locations_merged, covariances_merged, supports_merged, d = \ select_candidates( X[selection], h_merged, n_trials=(all_best_locations, all_best_covariances), select=n_best_merged, cov_computation_method=cov_computation_method, random_state=random_state) # 3. Finally get the overall best (locations, covariance) couple if n_samples < 1500: # directly get the best couple (location, covariance) location = locations_merged[0] covariance = covariances_merged[0] support = np.zeros(n_samples, dtype=bool) dist = np.zeros(n_samples) support[selection] = supports_merged[0] dist[selection] = d[0] else: # select the best couple on the full dataset locations_full, covariances_full, supports_full, d = \ select_candidates( X, n_support, n_trials=(locations_merged, covariances_merged), select=1, cov_computation_method=cov_computation_method, random_state=random_state) location = locations_full[0] covariance = covariances_full[0] support = supports_full[0] dist = d[0] elif n_features > 1: # 1. Find the 10 best couples (location, covariance) # considering two iterations n_trials = 30 n_best = 10 locations_best, covariances_best, _, _ = select_candidates( X, n_support, n_trials=n_trials, select=n_best, n_iter=2, cov_computation_method=cov_computation_method, random_state=random_state) # 2. Select the best couple on the full dataset amongst the 10 locations_full, covariances_full, supports_full, d = select_candidates( X, n_support, n_trials=(locations_best, covariances_best), select=1, cov_computation_method=cov_computation_method, random_state=random_state) location = locations_full[0] covariance = covariances_full[0] support = supports_full[0] dist = d[0] return location, covariance, support, dist class MinCovDet(EmpiricalCovariance): """Minimum Covariance Determinant (MCD): robust estimator of covariance. The Minimum Covariance Determinant covariance estimator is to be applied on Gaussian-distributed data, but could still be relevant on data drawn from a unimodal, symmetric distribution. It is not meant to be used with multi-modal data (the algorithm used to fit a MinCovDet object is likely to fail in such a case). One should consider projection pursuit methods to deal with multi-modal datasets. Read more in the :ref:`User Guide <robust_covariance>`. Parameters ---------- store_precision : bool Specify if the estimated precision is stored. assume_centered : Boolean If True, the support of the robust location and the covariance estimates is computed, and a covariance estimate is recomputed from it, without centering the data. Useful to work with data whose mean is significantly equal to zero but is not exactly zero. If False, the robust location and covariance are directly computed with the FastMCD algorithm without additional treatment. support_fraction : float, 0 < support_fraction < 1 The proportion of points to be included in the support of the raw MCD estimate. Default is None, which implies that the minimum value of support_fraction will be used within the algorithm: [n_sample + n_features + 1] / 2 random_state : integer or numpy.RandomState, optional The random generator used. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. Attributes ---------- raw_location_ : array-like, shape (n_features,) The raw robust estimated location before correction and re-weighting. raw_covariance_ : array-like, shape (n_features, n_features) The raw robust estimated covariance before correction and re-weighting. raw_support_ : array-like, shape (n_samples,) A mask of the observations that have been used to compute the raw robust estimates of location and shape, before correction and re-weighting. location_ : array-like, shape (n_features,) Estimated robust location covariance_ : array-like, shape (n_features, n_features) Estimated robust covariance matrix precision_ : array-like, shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) support_ : array-like, shape (n_samples,) A mask of the observations that have been used to compute the robust estimates of location and shape. dist_ : array-like, shape (n_samples,) Mahalanobis distances of the training set (on which `fit` is called) observations. References ---------- .. [Rouseeuw1984] `P. J. Rousseeuw. Least median of squares regression. J. Am Stat Ass, 79:871, 1984.` .. [Rouseeuw1999] `A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS` .. [Butler1993] `R. W. Butler, P. L. Davies and M. Jhun, Asymptotics For The Minimum Covariance Determinant Estimator, The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400` """ _nonrobust_covariance = staticmethod(empirical_covariance) def __init__(self, store_precision=True, assume_centered=False, support_fraction=None, random_state=None): self.store_precision = store_precision self.assume_centered = assume_centered self.support_fraction = support_fraction self.random_state = random_state def fit(self, X, y=None): """Fits a Minimum Covariance Determinant with the FastMCD algorithm. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training data, where n_samples is the number of samples and n_features is the number of features. y : not used, present for API consistence purpose. Returns ------- self : object Returns self. """ X = check_array(X) random_state = check_random_state(self.random_state) n_samples, n_features = X.shape # check that the empirical covariance is full rank if (linalg.svdvals(np.dot(X.T, X)) > 1e-8).sum() != n_features: warnings.warn("The covariance matrix associated to your dataset " "is not full rank") # compute and store raw estimates raw_location, raw_covariance, raw_support, raw_dist = fast_mcd( X, support_fraction=self.support_fraction, cov_computation_method=self._nonrobust_covariance, random_state=random_state) if self.assume_centered: raw_location = np.zeros(n_features) raw_covariance = self._nonrobust_covariance(X[raw_support], assume_centered=True) # get precision matrix in an optimized way precision = pinvh(raw_covariance) raw_dist = np.sum(np.dot(X, precision) * X, 1) self.raw_location_ = raw_location self.raw_covariance_ = raw_covariance self.raw_support_ = raw_support self.location_ = raw_location self.support_ = raw_support self.dist_ = raw_dist # obtain consistency at normal models self.correct_covariance(X) # re-weight estimator self.reweight_covariance(X) return self def correct_covariance(self, data): """Apply a correction to raw Minimum Covariance Determinant estimates. Correction using the empirical correction factor suggested by Rousseeuw and Van Driessen in [Rouseeuw1984]_. Parameters ---------- data : array-like, shape (n_samples, n_features) The data matrix, with p features and n samples. The data set must be the one which was used to compute the raw estimates. Returns ------- covariance_corrected : array-like, shape (n_features, n_features) Corrected robust covariance estimate. """ correction = np.median(self.dist_) / chi2(data.shape[1]).isf(0.5) covariance_corrected = self.raw_covariance_ * correction self.dist_ /= correction return covariance_corrected def reweight_covariance(self, data): """Re-weight raw Minimum Covariance Determinant estimates. Re-weight observations using Rousseeuw's method (equivalent to deleting outlying observations from the data set before computing location and covariance estimates). [Rouseeuw1984]_ Parameters ---------- data : array-like, shape (n_samples, n_features) The data matrix, with p features and n samples. The data set must be the one which was used to compute the raw estimates. Returns ------- location_reweighted : array-like, shape (n_features, ) Re-weighted robust location estimate. covariance_reweighted : array-like, shape (n_features, n_features) Re-weighted robust covariance estimate. support_reweighted : array-like, type boolean, shape (n_samples,) A mask of the observations that have been used to compute the re-weighted robust location and covariance estimates. """ n_samples, n_features = data.shape mask = self.dist_ < chi2(n_features).isf(0.025) if self.assume_centered: location_reweighted = np.zeros(n_features) else: location_reweighted = data[mask].mean(0) covariance_reweighted = self._nonrobust_covariance( data[mask], assume_centered=self.assume_centered) support_reweighted = np.zeros(n_samples, dtype=bool) support_reweighted[mask] = True self._set_covariance(covariance_reweighted) self.location_ = location_reweighted self.support_ = support_reweighted X_centered = data - self.location_ self.dist_ = np.sum( np.dot(X_centered, self.get_precision()) * X_centered, 1) return location_reweighted, covariance_reweighted, support_reweighted
bsd-3-clause
Aggieyixin/cjc2016
code/tba/tutorials-scikit-learn-master/robustness.py
5
2733
import numpy as np from matplotlib import pyplot as plt from scipy import stats from sklearn.tree import DecisionTreeClassifier def plot_surface(model, X, y): n_classes = 3 plot_colors = "ryb" cmap = plt.cm.RdYlBu plot_step = 0.02 plot_step_coarser = 0.5 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)) if isinstance(model, DecisionTreeClassifier): Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z, cmap=cmap) else: estimator_alpha = 1.0 / len(model.estimators_) for tree in model.estimators_: Z = tree.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z, alpha=estimator_alpha, cmap=cmap) xx_coarser, yy_coarser = np.meshgrid(np.arange(x_min, x_max, plot_step_coarser), np.arange(y_min, y_max, plot_step_coarser)) Z_points_coarser = model.predict(np.c_[xx_coarser.ravel(), yy_coarser.ravel()]).reshape(xx_coarser.shape) cs_points = plt.scatter(xx_coarser, yy_coarser, s=15, c=Z_points_coarser, cmap=cmap, edgecolors="none") for i, c in zip(range(n_classes), plot_colors): idx = np.where(y == i) plt.scatter(X[idx, 0], X[idx, 1], c=c, cmap=cmap) plt.show() def plot_outlier_detector(clf, X, ground_truth): n_outliers = (ground_truth == 0).sum() outliers_fraction = 1. * n_outliers / len(ground_truth) 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.linspace(x_min, x_max, 500), np.linspace(y_min, y_max, 500)) y_pred = clf.decision_function(X).ravel() threshold = stats.scoreatpercentile(y_pred, 100 * outliers_fraction) y_pred = y_pred > threshold Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7), cmap=plt.cm.Blues_r) a = plt.contour(xx, yy, Z, levels=[threshold], linewidths=2, colors='red') plt.contourf(xx, yy, Z, levels=[threshold, Z.max()], colors='orange') b = plt.scatter(X[:-n_outliers, 0], X[:-n_outliers, 1], c='white') c = plt.scatter(X[-n_outliers:, 0], X[-n_outliers:, 1], c='black') plt.legend( [a.collections[0], b, c], ['Learned decision function', 'True inliers', 'True outliers']) plt.show()
mit
goyalankit/po-compiler
object_files/networkx-1.8.1/examples/drawing/sampson.py
40
1379
#!/usr/bin/env python """ Sampson's monastery data. Shows how to read data from a zip file and plot multiple frames. """ __author__ = """Aric Hagberg ([email protected])""" # Copyright (C) 2010 by # Aric Hagberg <[email protected]> # Dan Schult <[email protected]> # Pieter Swart <[email protected]> # All rights reserved. # BSD license. import zipfile, cStringIO import networkx as nx import matplotlib.pyplot as plt zf = zipfile.ZipFile('sampson_data.zip') # zipfile object e1=cStringIO.StringIO(zf.read('samplike1.txt')) # read info file e2=cStringIO.StringIO(zf.read('samplike2.txt')) # read info file e3=cStringIO.StringIO(zf.read('samplike3.txt')) # read info file G1=nx.read_edgelist(e1,delimiter='\t') G2=nx.read_edgelist(e2,delimiter='\t') G3=nx.read_edgelist(e3,delimiter='\t') pos=nx.spring_layout(G3,iterations=100) plt.clf() plt.subplot(221) plt.title('samplike1') nx.draw(G1,pos,node_size=50,with_labels=False) plt.subplot(222) plt.title('samplike2') nx.draw(G2,pos,node_size=50,with_labels=False) plt.subplot(223) plt.title('samplike3') nx.draw(G3,pos,node_size=50,with_labels=False) plt.subplot(224) plt.title('samplike1,2,3') nx.draw(G3,pos,edgelist=G3.edges(),node_size=50,with_labels=False) nx.draw_networkx_edges(G1,pos,alpha=0.25) nx.draw_networkx_edges(G2,pos,alpha=0.25) plt.savefig("sampson.png") # save as png plt.show() # display
apache-2.0
google-research/google-research
persistent_es/plot_toy_regression.py
1
5719
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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. """Plot loss curves from saved CSV files for the toy regression experiment. Example: -------- python plot_toy_regression.py """ import os import csv import ipdb import pickle as pkl from collections import defaultdict import numpy as np import scipy.ndimage import matplotlib.pyplot as plt import matplotlib.colors as colors import seaborn as sns sns.set_style('white') sns.set_palette('bright') # Darker colors flatui = ["#E00072", "#00830B", "#2B1A7F", "#E06111", "#02D4F9", "#4F4C4B",] sns.set_palette(flatui) sns.palplot(sns.color_palette()) # Plotting from saved CSV files def load_log(exp_dir, log_filename='train_log.csv'): result_dict = defaultdict(list) with open(os.path.join(exp_dir, log_filename), newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: for key in row: try: if key in ['global_iteration', 'iteration', 'epoch']: result_dict[key].append(int(row[key])) else: result_dict[key].append(float(row[key])) except: pass return result_dict def plot_heatmap(pkl_path, xlabel, ylabel, smoothed=False, sigma=5.0, cmap=plt.cm.viridis, colorbar=True, figsize=(10,8)): with open(pkl_path, 'rb') as f: heatmap_data = pkl.load(f) if smoothed: smoothed_F_grid = scipy.ndimage.gaussian_filter(heatmap_data['L_grid'], sigma=sigma) best_smoothed_theta = np.unravel_index(smoothed_F_grid.argmin(), smoothed_F_grid.shape) best_smoothed_x = heatmap_data['xv'][best_smoothed_theta] best_smoothed_y = heatmap_data['yv'][best_smoothed_theta] plt.figure(figsize=figsize) plt.pcolormesh(heatmap_data['xv'], heatmap_data['yv'], smoothed_F_grid, norm=colors.LogNorm(), cmap=cmap) if colorbar: plt.colorbar() plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.xlabel(xlabel, fontsize=22) plt.ylabel(ylabel, fontsize=22) else: plt.figure(figsize=figsize) plt.pcolormesh(heatmap_data['xv'], heatmap_data['yv'], heatmap_data['L_grid'], norm=colors.LogNorm(), cmap=cmap) if colorbar: plt.colorbar() plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.xlabel(xlabel, fontsize=22) plt.ylabel(ylabel, fontsize=22) if not os.path.exists('figures'): os.makedirs('figures') tbptt_k10 = load_log('saves/toy_regression/tbptt-s:linear-optim:adam-lr:0.01-T:100-K:10-N:100-sigma:1.0-seed:1', 'iteration.csv') rtrl_k10 = load_log('saves/toy_regression/rtrl-s:linear-optim:adam-lr:0.01-T:100-K:10-N:100-sigma:1.0-seed:1', 'iteration.csv') uoro_k10 = load_log('saves/toy_regression/uoro-s:linear-optim:adam-lr:0.01-T:100-K:10-N:100-sigma:1.0-seed:1', 'iteration.csv') es_k10 = load_log('saves/toy_regression/es-s:linear-optim:adam-lr:0.01-T:100-K:10-N:100-sigma:1.0-seed:1', 'iteration.csv') pes_k10 = load_log('saves/toy_regression/pes-s:linear-optim:adam-lr:0.01-T:100-K:10-N:100-sigma:1.0-seed:1', 'iteration.csv') plot_heatmap('saves/toy_regression/sgd_lr:linear_sum_T_100_N_400_grid.pkl', xlabel='Initial LR', ylabel='Final LR', smoothed=False, cmap=plt.cm.Purples_r, colorbar=False, figsize=(7,5)) plt.plot(np.array(tbptt_k10['theta0']), np.array(tbptt_k10['theta1']), linewidth=3, label='TBPTT') plt.plot(np.array(uoro_k10['theta0']), np.array(uoro_k10['theta1']), linewidth=3, label='UORO') plt.plot(np.array(rtrl_k10['theta0']), np.array(rtrl_k10['theta1']), linewidth=3, label='RTRL') plt.plot(np.array(es_k10['theta0']), np.array(es_k10['theta1']), linewidth=3, label='ES') plt.plot(np.array(pes_k10['theta0']), np.array(pes_k10['theta1']), linewidth=3, label='PES') plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.xlabel('Initial LR', fontsize=24) plt.ylabel('Final LR', fontsize=24) plt.legend(fontsize=20, fancybox=True, framealpha=0.7) plt.savefig('figures/toy_regression_heatmap.png', bbox_inches='tight', pad_inches=0, dpi=300) # ================================================================================================ plt.figure(figsize=(6,4)) plt.plot(tbptt_k10['inner_problem_steps'], tbptt_k10['L'], linewidth=3, label='TBPTT') plt.plot(uoro_k10['inner_problem_steps'], uoro_k10['L'], linewidth=3, label='UORO') plt.plot(rtrl_k10['inner_problem_steps'], rtrl_k10['L'], linewidth=3, label='RTRL') plt.plot(es_k10['inner_problem_steps'], es_k10['L'], linewidth=3, label='ES') plt.plot(pes_k10['inner_problem_steps'], pes_k10['L'], linewidth=3, label='PES') plt.xscale('log') plt.xticks(fontsize=18) plt.yticks([500, 1000, 1500, 2000, 2500], fontsize=18) plt.xlabel('Inner Iterations', fontsize=20) plt.ylabel('Meta Objective', fontsize=20) plt.legend(fontsize=18, fancybox=True, framealpha=0.3) sns.despine() plt.savefig('figures/toy_regression_meta_obj.pdf', bbox_inches='tight', pad_inches=0)
apache-2.0
timothydmorton/bokeh
examples/interactions/interactive_bubble/data.py
49
1265
import numpy as np from bokeh.palettes import Spectral6 def process_data(): from bokeh.sampledata.gapminder import fertility, life_expectancy, population, regions # Make the column names ints not strings for handling columns = list(fertility.columns) years = list(range(int(columns[0]), int(columns[-1]))) rename_dict = dict(zip(columns, years)) fertility = fertility.rename(columns=rename_dict) life_expectancy = life_expectancy.rename(columns=rename_dict) population = population.rename(columns=rename_dict) regions = regions.rename(columns=rename_dict) # Turn population into bubble sizes. Use min_size and factor to tweak. scale_factor = 200 population_size = np.sqrt(population / np.pi) / scale_factor min_size = 3 population_size = population_size.where(population_size >= min_size).fillna(min_size) # Use pandas categories and categorize & color the regions regions.Group = regions.Group.astype('category') regions_list = list(regions.Group.cat.categories) def get_color(r): return Spectral6[regions_list.index(r.Group)] regions['region_color'] = regions.apply(get_color, axis=1) return fertility, life_expectancy, population_size, regions, years, regions_list
bsd-3-clause
RachitKansal/scikit-learn
examples/plot_johnson_lindenstrauss_bound.py
127
7477
r""" ===================================================================== The Johnson-Lindenstrauss bound for embedding with random projections ===================================================================== The `Johnson-Lindenstrauss lemma`_ states that any high dimensional dataset can be randomly projected into a lower dimensional Euclidean space while controlling the distortion in the pairwise distances. .. _`Johnson-Lindenstrauss lemma`: http://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma Theoretical bounds ================== The distortion introduced by a random projection `p` is asserted by the fact that `p` is defining an eps-embedding with good probability as defined by: .. math:: (1 - eps) \|u - v\|^2 < \|p(u) - p(v)\|^2 < (1 + eps) \|u - v\|^2 Where u and v are any rows taken from a dataset of shape [n_samples, n_features] and p is a projection by a random Gaussian N(0, 1) matrix with shape [n_components, n_features] (or a sparse Achlioptas matrix). The minimum number of components to guarantees the eps-embedding is given by: .. math:: n\_components >= 4 log(n\_samples) / (eps^2 / 2 - eps^3 / 3) The first plot shows that with an increasing number of samples ``n_samples``, the minimal number of dimensions ``n_components`` increased logarithmically in order to guarantee an ``eps``-embedding. The second plot shows that an increase of the admissible distortion ``eps`` allows to reduce drastically the minimal number of dimensions ``n_components`` for a given number of samples ``n_samples`` Empirical validation ==================== We validate the above bounds on the the digits dataset or on the 20 newsgroups text document (TF-IDF word frequencies) dataset: - for the digits dataset, some 8x8 gray level pixels data for 500 handwritten digits pictures are randomly projected to spaces for various larger number of dimensions ``n_components``. - for the 20 newsgroups dataset some 500 documents with 100k features in total are projected using a sparse random matrix to smaller euclidean spaces with various values for the target number of dimensions ``n_components``. The default dataset is the digits dataset. To run the example on the twenty newsgroups dataset, pass the --twenty-newsgroups command line argument to this script. For each value of ``n_components``, we plot: - 2D distribution of sample pairs with pairwise distances in original and projected spaces as x and y axis respectively. - 1D histogram of the ratio of those distances (projected / original). We can see that for low values of ``n_components`` the distribution is wide with many distorted pairs and a skewed distribution (due to the hard limit of zero ratio on the left as distances are always positives) while for larger values of n_components the distortion is controlled and the distances are well preserved by the random projection. Remarks ======= According to the JL lemma, projecting 500 samples without too much distortion will require at least several thousands dimensions, irrespective of the number of features of the original dataset. Hence using random projections on the digits dataset which only has 64 features in the input space does not make sense: it does not allow for dimensionality reduction in this case. On the twenty newsgroups on the other hand the dimensionality can be decreased from 56436 down to 10000 while reasonably preserving pairwise distances. """ print(__doc__) import sys from time import time import numpy as np import matplotlib.pyplot as plt from sklearn.random_projection import johnson_lindenstrauss_min_dim from sklearn.random_projection import SparseRandomProjection from sklearn.datasets import fetch_20newsgroups_vectorized from sklearn.datasets import load_digits from sklearn.metrics.pairwise import euclidean_distances # Part 1: plot the theoretical dependency between n_components_min and # n_samples # range of admissible distortions eps_range = np.linspace(0.1, 0.99, 5) colors = plt.cm.Blues(np.linspace(0.3, 1.0, len(eps_range))) # range of number of samples (observation) to embed n_samples_range = np.logspace(1, 9, 9) plt.figure() for eps, color in zip(eps_range, colors): min_n_components = johnson_lindenstrauss_min_dim(n_samples_range, eps=eps) plt.loglog(n_samples_range, min_n_components, color=color) plt.legend(["eps = %0.1f" % eps for eps in eps_range], loc="lower right") plt.xlabel("Number of observations to eps-embed") plt.ylabel("Minimum number of dimensions") plt.title("Johnson-Lindenstrauss bounds:\nn_samples vs n_components") # range of admissible distortions eps_range = np.linspace(0.01, 0.99, 100) # range of number of samples (observation) to embed n_samples_range = np.logspace(2, 6, 5) colors = plt.cm.Blues(np.linspace(0.3, 1.0, len(n_samples_range))) plt.figure() for n_samples, color in zip(n_samples_range, colors): min_n_components = johnson_lindenstrauss_min_dim(n_samples, eps=eps_range) plt.semilogy(eps_range, min_n_components, color=color) plt.legend(["n_samples = %d" % n for n in n_samples_range], loc="upper right") plt.xlabel("Distortion eps") plt.ylabel("Minimum number of dimensions") plt.title("Johnson-Lindenstrauss bounds:\nn_components vs eps") # Part 2: perform sparse random projection of some digits images which are # quite low dimensional and dense or documents of the 20 newsgroups dataset # which is both high dimensional and sparse if '--twenty-newsgroups' in sys.argv: # Need an internet connection hence not enabled by default data = fetch_20newsgroups_vectorized().data[:500] else: data = load_digits().data[:500] n_samples, n_features = data.shape print("Embedding %d samples with dim %d using various random projections" % (n_samples, n_features)) n_components_range = np.array([300, 1000, 10000]) dists = euclidean_distances(data, squared=True).ravel() # select only non-identical samples pairs nonzero = dists != 0 dists = dists[nonzero] for n_components in n_components_range: t0 = time() rp = SparseRandomProjection(n_components=n_components) projected_data = rp.fit_transform(data) print("Projected %d samples from %d to %d in %0.3fs" % (n_samples, n_features, n_components, time() - t0)) if hasattr(rp, 'components_'): n_bytes = rp.components_.data.nbytes n_bytes += rp.components_.indices.nbytes print("Random matrix with size: %0.3fMB" % (n_bytes / 1e6)) projected_dists = euclidean_distances( projected_data, squared=True).ravel()[nonzero] plt.figure() plt.hexbin(dists, projected_dists, gridsize=100, cmap=plt.cm.PuBu) plt.xlabel("Pairwise squared distances in original space") plt.ylabel("Pairwise squared distances in projected space") plt.title("Pairwise distances distribution for n_components=%d" % n_components) cb = plt.colorbar() cb.set_label('Sample pairs counts') rates = projected_dists / dists print("Mean distances rate: %0.2f (%0.2f)" % (np.mean(rates), np.std(rates))) plt.figure() plt.hist(rates, bins=50, normed=True, range=(0., 2.)) plt.xlabel("Squared distances rate: projected / original") plt.ylabel("Distribution of samples pairs") plt.title("Histogram of pairwise distance rates for n_components=%d" % n_components) # TODO: compute the expected value of eps and add them to the previous plot # as vertical lines / region plt.show()
bsd-3-clause
aetilley/scikit-learn
sklearn/datasets/lfw.py
50
19048
"""Loader for the Labeled Faces in the Wild (LFW) dataset This dataset is a collection of JPEG pictures of famous people collected over the internet, all details are available on the official website: http://vis-www.cs.umass.edu/lfw/ Each picture is centered on a single face. The typical task is called Face Verification: given a pair of two pictures, a binary classifier must predict whether the two images are from the same person. An alternative task, Face Recognition or Face Identification is: given the picture of the face of an unknown person, identify the name of the person by referring to a gallery of previously seen pictures of identified persons. Both Face Verification and Face Recognition are tasks that are typically performed on the output of a model trained to perform Face Detection. The most popular model for Face Detection is called Viola-Johns and is implemented in the OpenCV library. The LFW faces were extracted by this face detector from various online websites. """ # Copyright (c) 2011 Olivier Grisel <[email protected]> # License: BSD 3 clause from os import listdir, makedirs, remove from os.path import join, exists, isdir from sklearn.utils import deprecated import logging import numpy as np try: import urllib.request as urllib # for backwards compatibility except ImportError: import urllib from .base import get_data_home, Bunch from ..externals.joblib import Memory from ..externals.six import b logger = logging.getLogger(__name__) BASE_URL = "http://vis-www.cs.umass.edu/lfw/" ARCHIVE_NAME = "lfw.tgz" FUNNELED_ARCHIVE_NAME = "lfw-funneled.tgz" TARGET_FILENAMES = [ 'pairsDevTrain.txt', 'pairsDevTest.txt', 'pairs.txt', ] def scale_face(face): """Scale back to 0-1 range in case of normalization for plotting""" scaled = face - face.min() scaled /= scaled.max() return scaled # # Common private utilities for data fetching from the original LFW website # local disk caching, and image decoding. # def check_fetch_lfw(data_home=None, funneled=True, download_if_missing=True): """Helper function to download any missing LFW data""" data_home = get_data_home(data_home=data_home) lfw_home = join(data_home, "lfw_home") if funneled: archive_path = join(lfw_home, FUNNELED_ARCHIVE_NAME) data_folder_path = join(lfw_home, "lfw_funneled") archive_url = BASE_URL + FUNNELED_ARCHIVE_NAME else: archive_path = join(lfw_home, ARCHIVE_NAME) data_folder_path = join(lfw_home, "lfw") archive_url = BASE_URL + ARCHIVE_NAME if not exists(lfw_home): makedirs(lfw_home) for target_filename in TARGET_FILENAMES: target_filepath = join(lfw_home, target_filename) if not exists(target_filepath): if download_if_missing: url = BASE_URL + target_filename logger.warning("Downloading LFW metadata: %s", url) urllib.urlretrieve(url, target_filepath) else: raise IOError("%s is missing" % target_filepath) if not exists(data_folder_path): if not exists(archive_path): if download_if_missing: logger.warning("Downloading LFW data (~200MB): %s", archive_url) urllib.urlretrieve(archive_url, archive_path) else: raise IOError("%s is missing" % target_filepath) import tarfile logger.info("Decompressing the data archive to %s", data_folder_path) tarfile.open(archive_path, "r:gz").extractall(path=lfw_home) remove(archive_path) return lfw_home, data_folder_path def _load_imgs(file_paths, slice_, color, resize): """Internally used to load images""" # Try to import imread and imresize from PIL. We do this here to prevent # the whole sklearn.datasets module from depending on PIL. try: try: from scipy.misc import imread except ImportError: from scipy.misc.pilutil import imread from scipy.misc import imresize except ImportError: raise ImportError("The Python Imaging Library (PIL)" " is required to load data from jpeg files") # compute the portion of the images to load to respect the slice_ parameter # given by the caller default_slice = (slice(0, 250), slice(0, 250)) if slice_ is None: slice_ = default_slice else: slice_ = tuple(s or ds for s, ds in zip(slice_, default_slice)) h_slice, w_slice = slice_ h = (h_slice.stop - h_slice.start) // (h_slice.step or 1) w = (w_slice.stop - w_slice.start) // (w_slice.step or 1) if resize is not None: resize = float(resize) h = int(resize * h) w = int(resize * w) # allocate some contiguous memory to host the decoded image slices n_faces = len(file_paths) if not color: faces = np.zeros((n_faces, h, w), dtype=np.float32) else: faces = np.zeros((n_faces, h, w, 3), dtype=np.float32) # iterate over the collected file path to load the jpeg files as numpy # arrays for i, file_path in enumerate(file_paths): if i % 1000 == 0: logger.info("Loading face #%05d / %05d", i + 1, n_faces) face = np.asarray(imread(file_path)[slice_], dtype=np.float32) face /= 255.0 # scale uint8 coded colors to the [0.0, 1.0] floats if resize is not None: face = imresize(face, resize) if not color: # average the color channels to compute a gray levels # representaion face = face.mean(axis=2) faces[i, ...] = face return faces # # Task #1: Face Identification on picture with names # def _fetch_lfw_people(data_folder_path, slice_=None, color=False, resize=None, min_faces_per_person=0): """Perform the actual data loading for the lfw people dataset This operation is meant to be cached by a joblib wrapper. """ # scan the data folder content to retain people with more that # `min_faces_per_person` face pictures person_names, file_paths = [], [] for person_name in sorted(listdir(data_folder_path)): folder_path = join(data_folder_path, person_name) if not isdir(folder_path): continue paths = [join(folder_path, f) for f in listdir(folder_path)] n_pictures = len(paths) if n_pictures >= min_faces_per_person: person_name = person_name.replace('_', ' ') person_names.extend([person_name] * n_pictures) file_paths.extend(paths) n_faces = len(file_paths) if n_faces == 0: raise ValueError("min_faces_per_person=%d is too restrictive" % min_faces_per_person) target_names = np.unique(person_names) target = np.searchsorted(target_names, person_names) faces = _load_imgs(file_paths, slice_, color, resize) # shuffle the faces with a deterministic RNG scheme to avoid having # all faces of the same person in a row, as it would break some # cross validation and learning algorithms such as SGD and online # k-means that make an IID assumption indices = np.arange(n_faces) np.random.RandomState(42).shuffle(indices) faces, target = faces[indices], target[indices] return faces, target, target_names def fetch_lfw_people(data_home=None, funneled=True, resize=0.5, min_faces_per_person=0, color=False, slice_=(slice(70, 195), slice(78, 172)), download_if_missing=True): """Loader for the Labeled Faces in the Wild (LFW) people dataset This dataset is a collection of JPEG pictures of famous people collected on the internet, all details are available on the official website: http://vis-www.cs.umass.edu/lfw/ Each picture is centered on a single face. Each pixel of each channel (color in RGB) is encoded by a float in range 0.0 - 1.0. The task is called Face Recognition (or Identification): given the picture of a face, find the name of the person given a training set (gallery). The original images are 250 x 250 pixels, but the default slice and resize arguments reduce them to 62 x 74. Parameters ---------- data_home : optional, default: None Specify another download and cache folder for the datasets. By default all scikit learn data is stored in '~/scikit_learn_data' subfolders. funneled : boolean, optional, default: True Download and use the funneled variant of the dataset. resize : float, optional, default 0.5 Ratio used to resize the each face picture. min_faces_per_person : int, optional, default None The extracted dataset will only retain pictures of people that have at least `min_faces_per_person` different pictures. color : boolean, optional, default False Keep the 3 RGB channels instead of averaging them to a single gray level channel. If color is True the shape of the data has one more dimension than than the shape with color = False. slice_ : optional Provide a custom 2D slice (height, width) to extract the 'interesting' part of the jpeg files and avoid use statistical correlation from the background download_if_missing : optional, True by default If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. Returns ------- dataset : dict-like object with the following attributes: dataset.data : numpy array of shape (13233, 2914) Each row corresponds to a ravelled face image of original size 62 x 47 pixels. Changing the ``slice_`` or resize parameters will change the shape of the output. dataset.images : numpy array of shape (13233, 62, 47) Each row is a face image corresponding to one of the 5749 people in the dataset. Changing the ``slice_`` or resize parameters will change the shape of the output. dataset.target : numpy array of shape (13233,) Labels associated to each face image. Those labels range from 0-5748 and correspond to the person IDs. dataset.DESCR : string Description of the Labeled Faces in the Wild (LFW) dataset. """ lfw_home, data_folder_path = check_fetch_lfw( data_home=data_home, funneled=funneled, download_if_missing=download_if_missing) logger.info('Loading LFW people faces from %s', lfw_home) # wrap the loader in a memoizing function that will return memmaped data # arrays for optimal memory usage m = Memory(cachedir=lfw_home, compress=6, verbose=0) load_func = m.cache(_fetch_lfw_people) # load and memoize the pairs as np arrays faces, target, target_names = load_func( data_folder_path, resize=resize, min_faces_per_person=min_faces_per_person, color=color, slice_=slice_) # pack the results as a Bunch instance return Bunch(data=faces.reshape(len(faces), -1), images=faces, target=target, target_names=target_names, DESCR="LFW faces dataset") # # Task #2: Face Verification on pairs of face pictures # def _fetch_lfw_pairs(index_file_path, data_folder_path, slice_=None, color=False, resize=None): """Perform the actual data loading for the LFW pairs dataset This operation is meant to be cached by a joblib wrapper. """ # parse the index file to find the number of pairs to be able to allocate # the right amount of memory before starting to decode the jpeg files with open(index_file_path, 'rb') as index_file: split_lines = [ln.strip().split(b('\t')) for ln in index_file] pair_specs = [sl for sl in split_lines if len(sl) > 2] n_pairs = len(pair_specs) # interating over the metadata lines for each pair to find the filename to # decode and load in memory target = np.zeros(n_pairs, dtype=np.int) file_paths = list() for i, components in enumerate(pair_specs): if len(components) == 3: target[i] = 1 pair = ( (components[0], int(components[1]) - 1), (components[0], int(components[2]) - 1), ) elif len(components) == 4: target[i] = 0 pair = ( (components[0], int(components[1]) - 1), (components[2], int(components[3]) - 1), ) else: raise ValueError("invalid line %d: %r" % (i + 1, components)) for j, (name, idx) in enumerate(pair): try: person_folder = join(data_folder_path, name) except TypeError: person_folder = join(data_folder_path, str(name, 'UTF-8')) filenames = list(sorted(listdir(person_folder))) file_path = join(person_folder, filenames[idx]) file_paths.append(file_path) pairs = _load_imgs(file_paths, slice_, color, resize) shape = list(pairs.shape) n_faces = shape.pop(0) shape.insert(0, 2) shape.insert(0, n_faces // 2) pairs.shape = shape return pairs, target, np.array(['Different persons', 'Same person']) @deprecated("Function 'load_lfw_people' has been deprecated in 0.17 and will be " "removed in 0.19." "Use fetch_lfw_people(download_if_missing=False) instead.") def load_lfw_people(download_if_missing=False, **kwargs): """Alias for fetch_lfw_people(download_if_missing=False) Check fetch_lfw_people.__doc__ for the documentation and parameter list. """ return fetch_lfw_people(download_if_missing=download_if_missing, **kwargs) def fetch_lfw_pairs(subset='train', data_home=None, funneled=True, resize=0.5, color=False, slice_=(slice(70, 195), slice(78, 172)), download_if_missing=True): """Loader for the Labeled Faces in the Wild (LFW) pairs dataset This dataset is a collection of JPEG pictures of famous people collected on the internet, all details are available on the official website: http://vis-www.cs.umass.edu/lfw/ Each picture is centered on a single face. Each pixel of each channel (color in RGB) is encoded by a float in range 0.0 - 1.0. The task is called Face Verification: given a pair of two pictures, a binary classifier must predict whether the two images are from the same person. In the official `README.txt`_ this task is described as the "Restricted" task. As I am not sure as to implement the "Unrestricted" variant correctly, I left it as unsupported for now. .. _`README.txt`: http://vis-www.cs.umass.edu/lfw/README.txt The original images are 250 x 250 pixels, but the default slice and resize arguments reduce them to 62 x 74. Read more in the :ref:`User Guide <labeled_faces_in_the_wild>`. Parameters ---------- subset : optional, default: 'train' Select the dataset to load: 'train' for the development training set, 'test' for the development test set, and '10_folds' for the official evaluation set that is meant to be used with a 10-folds cross validation. data_home : optional, default: None Specify another download and cache folder for the datasets. By default all scikit learn data is stored in '~/scikit_learn_data' subfolders. funneled : boolean, optional, default: True Download and use the funneled variant of the dataset. resize : float, optional, default 0.5 Ratio used to resize the each face picture. color : boolean, optional, default False Keep the 3 RGB channels instead of averaging them to a single gray level channel. If color is True the shape of the data has one more dimension than than the shape with color = False. slice_ : optional Provide a custom 2D slice (height, width) to extract the 'interesting' part of the jpeg files and avoid use statistical correlation from the background download_if_missing : optional, True by default If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. Returns ------- The data is returned as a Bunch object with the following attributes: data : numpy array of shape (2200, 5828) Each row corresponds to 2 ravel'd face images of original size 62 x 47 pixels. Changing the ``slice_`` or resize parameters will change the shape of the output. pairs : numpy array of shape (2200, 2, 62, 47) Each row has 2 face images corresponding to same or different person from the dataset containing 5749 people. Changing the ``slice_`` or resize parameters will change the shape of the output. target : numpy array of shape (13233,) Labels associated to each pair of images. The two label values being different persons or the same person. DESCR : string Description of the Labeled Faces in the Wild (LFW) dataset. """ lfw_home, data_folder_path = check_fetch_lfw( data_home=data_home, funneled=funneled, download_if_missing=download_if_missing) logger.info('Loading %s LFW pairs from %s', subset, lfw_home) # wrap the loader in a memoizing function that will return memmaped data # arrays for optimal memory usage m = Memory(cachedir=lfw_home, compress=6, verbose=0) load_func = m.cache(_fetch_lfw_pairs) # select the right metadata file according to the requested subset label_filenames = { 'train': 'pairsDevTrain.txt', 'test': 'pairsDevTest.txt', '10_folds': 'pairs.txt', } if subset not in label_filenames: raise ValueError("subset='%s' is invalid: should be one of %r" % ( subset, list(sorted(label_filenames.keys())))) index_file_path = join(lfw_home, label_filenames[subset]) # load and memoize the pairs as np arrays pairs, target, target_names = load_func( index_file_path, data_folder_path, resize=resize, color=color, slice_=slice_) # pack the results as a Bunch instance return Bunch(data=pairs.reshape(len(pairs), -1), pairs=pairs, target=target, target_names=target_names, DESCR="'%s' segment of the LFW pairs dataset" % subset) @deprecated("Function 'load_lfw_pairs' has been deprecated in 0.17 and will be " "removed in 0.19." "Use fetch_lfw_pairs(download_if_missing=False) instead.") def load_lfw_pairs(download_if_missing=False, **kwargs): """Alias for fetch_lfw_pairs(download_if_missing=False) Check fetch_lfw_pairs.__doc__ for the documentation and parameter list. """ return fetch_lfw_pairs(download_if_missing=download_if_missing, **kwargs)
bsd-3-clause
songjs1993/DeepLearning
3CNN/CNN_LeNet_5_cifar_dev.py
1
15045
# Auther: Alan """ 实现AlexNet网络结构:但是实际上AlexNet网络结构的餐率领有60M,其实际的参数量比后来的几个网络结构都要多,这里不选择 但是尝试实现更深层的卷积网络来查看性能 这里一共整理了4层 """ # Auther: Alan """ 将LeNet5应用在Cifar数据集上 """ import tensorflow as tf import random import os import scipy.io as sio import matplotlib.pyplot as plt # plt 用于显示图片 import matplotlib.image as mpimg # mpimg 用于读取图片 import numpy as np # import Image from PIL import Image global max_row, max_col def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): # 这里完全可以用一个数组代替 tf.zeros(units[1]) initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): # strides表示每一维度的步长 return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding="SAME") def max_pool_2x2(x): # ksize表示池化窗口的大小, 其中最前面的1和最后的1分别表示batch和channel(这里不考虑对不同batch做池化,所以设置为1) # 另外一个任务:判断两张图片是否为同一个人,觉得可以将其当做不同channel,一起进行池化的操作 return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME") def max_pool_3x3(x): return tf.nn.max_pool(x, ksize=[1,3,3,1], strides=[1,3,3,1], padding="SAME") def max_pool_5x5(x): return tf.nn.max_pool(x, ksize=[1,5,5,1], strides=[1,5,5,1], padding="SAME") def CNN_LeNet_5_Mnist(logs_path): """ LeNet对Mnist数据集进行测试 :return: """ from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # print(mnist) x = tf.placeholder(tf.float32, [None, 784]) y_ = tf.placeholder(tf.float32, [None, 10]) x_image = tf.reshape(x, [-1,28,28,1]) # 把向量重新整理成矩阵,最后一个表示通道个数 # 第一二参数值得卷积核尺寸大小,即patch,第三个参数是图像通道数,第四个参数是卷积核的数目,代表会出现多少个卷积特征 W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 32, 64]) # 多通道卷积,卷积出64个特征 b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) W_fc1 = weight_variable([7*7*64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) tf.summary.scalar("cross_entropy", cross_entropy) correct_prediction = tf.equal(tf.arg_max(y_conv, 1), tf.arg_max(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) merged_summary_op = tf.summary.merge_all() # 初始化变量 init_op = tf.global_variables_initializer() # 开始训练 sess = tf.Session() sess.run(init_op) # iterate # Xtrain, ytrain = get_batch(self.args, self.simrank, self.walks, minibatch * 100, self.tem_simrank) # 找一个大点的数据集测试效果 summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph()) # for i in range((int)(20000)): num_examples = 12800*2 #这里暂时手动设置吧 minibatch = 128 for epoch in range(20): print("iter:", epoch) avg_cost = 0. total_batch = int(num_examples / minibatch) # Loop over all batches for i in range(total_batch): batchs = mnist.train.next_batch(minibatch) batch_xs, batch_ys = batchs[0], batchs[1] # batch_xs, batch_ys = next_batch(self.args, self.simrank, self.walks, minibatch, self.tem_simrank, # num_examples) # and summary nodes _, c, summary = sess.run([train_step, cross_entropy, merged_summary_op], feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5}) # Write logs at every iteration summary_writer.add_summary(summary, epoch * total_batch + i) # Compute average loss avg_cost += c / total_batch if (i % 10 == 0): print("i:", i, " current c:", c, " ave_cost:", avg_cost) # Display logs per epoch step # if (epoch + 1) % display_step == 0: print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(avg_cost)) # 到达一定程度进行测试test输出 if epoch%1==0: batchs = mnist.train.next_batch(minibatch) print("test accuracy %g" % sess.run(accuracy, feed_dict={ x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) # x: batchs[0], y_: batchs[1], keep_prob: 1.0})) def get_one_hot(label, num): y = [] for i in range(num): # 一共17个类别 if i == label: y.append(1.0) else: y.append(0.0) return y from scipy.io import loadmat def read_data_cifar(train_file, test_file): """ 获取train/val/test数据集 :param input_path: :param split_path: :return: """ f1 = loadmat(train_file) f2 = loadmat(test_file) train_x = f1["data"] train_y_ = f1["fine_labels"] test_x = f2["data"] test_y_ = f2["fine_labels"] # 需要处理labels train_y = [] for train in train_y_: y = [] for i in range(100): if i == int(train)-1: y.append(1.0) else: y.append(0.0) train_y.append(y) test_y = [] for test in test_y_: y = [] for i in range(100): if i == int(test) - 1: y.append(1.0) else: y.append(0.0) test_y.append(y) train_y = np.array(train_y) test_y = np.array(test_y) print(train_x.shape, train_y.shape, test_x.shape, test_y.shape) train_X = [] test_X = [] for i in range(train_x.shape[0]): batch = train_x[i] if i%500==0: print("get image i:", i) # lena = Image.fromarray(np.reshape(np.reshape(batch, [3, 1024]).T, [32, 32, 3])) # lena.save("temp_cifar.png") train_X.append(np.reshape((np.reshape(np.reshape(batch, [3, 1024]).T, [32, 32, 3])), [-1])) for i in range(test_x.shape[0]): batch = test_x[i] if i % 500 == 0: print("get image i:", i) # lena = Image.fromarray(np.reshape(np.reshape(batch, [3, 1024]).T, [32, 32, 3])) test_X.append(np.reshape((np.reshape(np.reshape(batch, [3, 1024]).T, [32, 32, 3])), [-1])) return np.array(train_X) / 255.0, train_y, np.array(test_X) / 255.0, test_y def CNN_LeNet_5_dev(train_file, test_file, log_path): trainX, trainY, testX, testY = read_data_cifar(train_file, test_file) print("trainX.shape: ", trainX.shape, trainY.shape, testX.shape, testY.shape) # 构建网络 x = tf.placeholder(tf.float32, [None, 1024*3]) y_ = tf.placeholder(tf.float32, [None, 100]) x_image = tf.reshape(x, [-1,32,32,3]) # 把向量重新整理成矩阵,最后一个表示通道个数 # 第一二参数值得卷积核尺寸大小,即patch,第三个参数是图像通道数,第四个参数是卷积核的数目,代表会出现多少个卷积特征 W_conv1 = weight_variable([3, 3, 3, 64]) b_conv1 = bias_variable([64]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) # 16*16 W_conv2 = weight_variable([3, 3, 64, 64]) # 多通道卷积,卷积出64个特征 b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) # 8*8 W_conv3 = weight_variable([3, 3, 64, 128]) # 多通道卷积,卷积出64个特征 b_conv3 = bias_variable([128]) h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3) h_pool3 = max_pool_2x2(h_conv3) # 4*4 W_conv4 = weight_variable([3, 3, 128, 128]) # 多通道卷积,卷积出64个特征 b_conv4 = bias_variable([128]) h_conv4 = tf.nn.relu(conv2d(h_pool3, W_conv4) + b_conv4) h_pool4 = max_pool_2x2(h_conv4) # 2*2 W_fc1 = weight_variable([2*2*128, 2*128]) b_fc1 = bias_variable([2*128]) h_pool2_flat = tf.reshape(h_pool4, [-1, 2*2*128]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([2*128, 100]) b_fc2 = bias_variable([100]) y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y_)) #2/3/4/5 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv+1e-10), reduction_indices=[1])) #1 # learning_rate = 0.1 # global_step = 1000 # decay_steps = 0.95 # learning_rate = tf.train.exponential_decay(learning_rate, global_step, decay_steps, decay_rate, staircase=True) # tf.summary.scalar('learning_rate', learning_rate) # # Optimizer. # grads = optimizer.compute_gradients(loss) # op_gradients = optimizer.apply_gradients(grads, global_step=global_step) global_step = 500 learning_rate = 1e-1 # train_step = tf.train.AdamOptimizer(1e-3).minimize(cross_entropy) train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy) #1/2 train_step = tf.train.GradientDescentOptimizer(1e-5).minimize(cross_entropy) # 3/4 train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) # 5 # train_step = tf.train.AdamOptimizer(1e-3).minimize(cross_entropy) momentum = 0.9 # train_step = tf.train.MomentumOptimizer(learning_rate, momentum).minimize(cross_entropy) train_step_3 = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy) # tf.summary.scalar("cross_entropy", cross_entropy) correct_prediction = tf.equal(tf.arg_max(y_conv, 1), tf.arg_max(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) merged_summary_op = tf.summary.merge_all() # 初始化变量 init_op = tf.global_variables_initializer() # summary_writer = tf.summary.FileWriter(log_path, graph=tf.get_default_graph()) # 开始训练 drops = [1.0, 0.8, 0.6, 0.4, 0.2] drops = [0.5] drops = [0.4] for i in range(len(drops)): drop = drops[i] log_path = log_path + str(i) print("log_path: ", log_path, " drop:", drop) sess = tf.Session() sess.run(init_op) # iterate # Xtrain, ytrain = get_batch(self.args, self.simrank, self.walks, minibatch * 100, self.tem_simrank) # 找一个大点的数据集测试效果 # for i in range((int)(20000)): num_examples = trainX.shape[0] minibatch = 128 maxc = -1.0 for epoch in range(global_step): print("iter:", epoch) # if epoch > 400: # train_step = train_step_3 avg_cost = 0. total_batch = int(num_examples / minibatch) # Loop over all batches for i in range(total_batch): batch_xs, batch_ys = next_batch(trainX, trainY, minibatch, num_examples) # print(type(batch_xs),type(batch_ys)) # print(batch_xs.shape, batch_ys.shape) # print(batch_xs[0]) # and summary nodes # print(sess.run(h_pool4, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.8})) # print(sess.run(y_conv, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.8})) # print(sess.run(cross_entropy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.8})) # return # _, c, summary = sess.run([train_step, cross_entropy, merged_summary_op],feed_dict={x: batch_xs, y_: batch_ys, keep_prob: drop}) _, c = sess.run([train_step, cross_entropy], feed_dict={x: batch_xs, y_: batch_ys, keep_prob: drop}) # Write logs at every iteration # summary_writer.add_summary(summary, epoch * total_batch + i) # Compute average loss avg_cost += c / total_batch if (i % 1 == 0): print("i:", i, " current c:", c, " ave_cost:", avg_cost) # if i % 500 == 0: # # batchs = mnist.train.next_batch(minibatch) # print("test accuracy %g" % sess.run(accuracy, feed_dict={ # x: testX, y_: testY, keep_prob: 1.0})) # Display logs per epoch step print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(avg_cost)) # 到达一定程度进行测试test输出 if epoch % 1 == 0: # batchs = mnist.train.next_batch(minibatch) acc = sess.run(accuracy, feed_dict={x: testX, y_: testY, keep_prob: 1.0}) if acc > maxc: maxc = acc print("test accuracy %g" % acc) # x: batchs[0], y_: batchs[1], keep_prob: 1.0})) print("====================================================================") sess.close() print("max acc: ", maxc) print("finish!") print("finish all!") def next_batch(trainX, trainY, minibatch, num_examples): locations = random.sample([i for i in range(num_examples)], minibatch) batch_xs = trainX[locations] batch_ys = trainY[locations] return batch_xs, batch_ys # locations = random.sample([i for i in range(num_examples)], minibatch) # batch_xs_ = trainX[locations] # batch_ys = trainY[locations] # # batch_xs = [] # for batch in batch_xs_: # # lena = Image.fromarray(np.reshape(np.reshape(batch, [3, 1024]).T, [32, 32, 3])) # batch_xs.append(np.reshape((np.reshape(np.reshape(batch, [3, 1024]).T, [32, 32, 3])),[-1])) # return np.array(batch_xs), batch_ys if __name__ =="__main__": # 尝试对LeNet网络加深结构,到5层卷积,尝试效果,这里使用默认的dropout比例0.4 CNN_LeNet_5_dev("./cifar_data/train.mat", "./cifar_data/test.mat", "./CNN/cifar")
apache-2.0
siutanwong/scikit-learn
sklearn/preprocessing/__init__.py
268
1319
""" The :mod:`sklearn.preprocessing` module includes scaling, centering, normalization, binarization and imputation methods. """ from ._function_transformer import FunctionTransformer from .data import Binarizer from .data import KernelCenterer from .data import MinMaxScaler from .data import MaxAbsScaler from .data import Normalizer from .data import RobustScaler from .data import StandardScaler from .data import add_dummy_feature from .data import binarize from .data import normalize from .data import scale from .data import robust_scale from .data import maxabs_scale from .data import minmax_scale from .data import OneHotEncoder from .data import PolynomialFeatures from .label import label_binarize from .label import LabelBinarizer from .label import LabelEncoder from .label import MultiLabelBinarizer from .imputation import Imputer __all__ = [ 'Binarizer', 'FunctionTransformer', 'Imputer', 'KernelCenterer', 'LabelBinarizer', 'LabelEncoder', 'MultiLabelBinarizer', 'MinMaxScaler', 'MaxAbsScaler', 'Normalizer', 'OneHotEncoder', 'RobustScaler', 'StandardScaler', 'add_dummy_feature', 'PolynomialFeatures', 'binarize', 'normalize', 'scale', 'robust_scale', 'maxabs_scale', 'minmax_scale', 'label_binarize', ]
bsd-3-clause
architecture-building-systems/CityEnergyAnalyst
cea/technologies/network_layout/minimum_spanning_tree.py
2
4015
""" This script calculates the minimum spanning tree of a shapefile network """ import networkx as nx import cea.inputlocator from geopandas import GeoDataFrame as gdf import cea.config import os __author__ = "Jimeno A. Fonseca" __copyright__ = "Copyright 2017, Architecture and Building Systems - ETH Zurich" __credits__ = ["Jimeno A. Fonseca"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "[email protected]" __status__ = "Production" def calc_minimum_spanning_tree(input_network_shp, output_network_folder, building_nodes_shp, output_edges, output_nodes, weight_field, type_mat_default, pipe_diameter_default): # read shapefile into networkx format into a directed graph graph = nx.read_shp(input_network_shp) # transform to an undirected graph iterator_edges = graph.edges(data=True) G = nx.Graph() # plant = (11660.95859999981, 37003.7689999986) for (x, y, data) in iterator_edges: G.add_edge(x, y, weight=data[weight_field]) # calculate minimum spanning tree of undirected graph mst_non_directed = nx.minimum_spanning_edges(G, data=False) # transform back directed graph and save: mst_directed = nx.DiGraph() mst_directed.add_edges_from(mst_non_directed) nx.write_shp(mst_directed, output_network_folder) # populate fields Type_mat, Name, Pipe_Dn mst_edges = gdf.from_file(output_edges) mst_edges['Type_mat'] = type_mat_default mst_edges['Pipe_DN'] = pipe_diameter_default mst_edges['Name'] = ["PIPE" + str(x) for x in mst_edges['FID']] mst_edges.drop("FID", axis=1, inplace=True) mst_edges.crs = gdf.from_file(input_network_shp).crs # to add coordinate system mst_edges.to_file(output_edges, driver='ESRI Shapefile') # populate fields Building, Type, Name mst_nodes = gdf.from_file(output_nodes) buiding_nodes_df = gdf.from_file(building_nodes_shp) mst_nodes.crs = buiding_nodes_df.crs # to add same coordinate system buiding_nodes_df['coordinates'] = buiding_nodes_df['geometry'].apply( lambda x: (round(x.coords[0][0], 4), round(x.coords[0][1], 4))) mst_nodes['coordinates'] = mst_nodes['geometry'].apply( lambda x: (round(x.coords[0][0], 4), round(x.coords[0][1], 4))) names_temporary = ["NODE" + str(x) for x in mst_nodes['FID']] new_mst_nodes = mst_nodes.merge(buiding_nodes_df, suffixes=['', '_y'], on="coordinates", how='outer') new_mst_nodes.fillna(value="NONE", inplace=True) new_mst_nodes['Building'] = new_mst_nodes['Name'] new_mst_nodes['Name'] = names_temporary new_mst_nodes['Type'] = new_mst_nodes['Building'].apply(lambda x: 'CONSUMER' if x != "NONE" else x) new_mst_nodes.drop(["FID", "coordinates", 'floors_bg', 'floors_ag', 'height_bg', 'height_ag', 'geometry_y'], axis=1, inplace=True) new_mst_nodes.to_file(output_nodes, driver='ESRI Shapefile') def main(config): assert os.path.exists(config.scenario), 'Scenario not found: %s' % config.scenario locator = cea.inputlocator.InputLocator(scenario=config.scenario) weight_field = 'Shape_Leng' type_mat_default = config.network_layout.type_mat pipe_diameter_default = config.network_layout.pipe_diameter type_network = config.network_layout.network_type building_nodes = locator.get_temporary_file("nodes_buildings.shp") input_network_shp = locator.get_temporary_file("potential_network.shp") # shapefile, location of output. output_edges = locator.get_network_layout_edges_shapefile(type_network,'') output_nodes = locator.get_network_layout_nodes_shapefile(type_network,'') output_network_folder = locator.get_input_network_folder(type_network,'') calc_minimum_spanning_tree(input_network_shp, output_network_folder, building_nodes, output_edges, output_nodes, weight_field, type_mat_default, pipe_diameter_default) if __name__ == '__main__': main(cea.config.Configuration())
mit
weixuanfu2016/tpot
tpot/config/regressor_mdr.py
4
1737
# -*- coding: utf-8 -*- """This file is part of the TPOT library. TPOT was primarily developed at the University of Pennsylvania by: - Randal S. Olson ([email protected]) - Weixuan Fu ([email protected]) - Daniel Angell ([email protected]) - and many more generous open source contributors TPOT 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. TPOT 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 TPOT. If not, see <http://www.gnu.org/licenses/>. """ import numpy as np # Check the TPOT documentation for information on the structure of config dicts tpot_mdr_regressor_config_dict = { # Regressors 'sklearn.linear_model.ElasticNetCV': { 'l1_ratio': np.arange(0.0, 1.01, 0.05), 'tol': [1e-5, 1e-4, 1e-3, 1e-2, 1e-1] }, # Feature Constructors 'mdr.ContinuousMDR': { 'tie_break': [0, 1], 'default_label': [0, 1] }, # Feature Selectors 'skrebate.ReliefF': { 'n_features_to_select': range(1, 6), 'n_neighbors': [2, 10, 50, 100, 250, 500] }, 'skrebate.SURF': { 'n_features_to_select': range(1, 6) }, 'skrebate.SURFstar': { 'n_features_to_select': range(1, 6) }, 'skrebate.MultiSURF': { 'n_features_to_select': range(1, 6) } }
lgpl-3.0
kernc/scikit-learn
sklearn/preprocessing/__init__.py
268
1319
""" The :mod:`sklearn.preprocessing` module includes scaling, centering, normalization, binarization and imputation methods. """ from ._function_transformer import FunctionTransformer from .data import Binarizer from .data import KernelCenterer from .data import MinMaxScaler from .data import MaxAbsScaler from .data import Normalizer from .data import RobustScaler from .data import StandardScaler from .data import add_dummy_feature from .data import binarize from .data import normalize from .data import scale from .data import robust_scale from .data import maxabs_scale from .data import minmax_scale from .data import OneHotEncoder from .data import PolynomialFeatures from .label import label_binarize from .label import LabelBinarizer from .label import LabelEncoder from .label import MultiLabelBinarizer from .imputation import Imputer __all__ = [ 'Binarizer', 'FunctionTransformer', 'Imputer', 'KernelCenterer', 'LabelBinarizer', 'LabelEncoder', 'MultiLabelBinarizer', 'MinMaxScaler', 'MaxAbsScaler', 'Normalizer', 'OneHotEncoder', 'RobustScaler', 'StandardScaler', 'add_dummy_feature', 'PolynomialFeatures', 'binarize', 'normalize', 'scale', 'robust_scale', 'maxabs_scale', 'minmax_scale', 'label_binarize', ]
bsd-3-clause
samuel1208/scikit-learn
examples/neighbors/plot_approximate_nearest_neighbors_hyperparameters.py
227
5170
""" ================================================= Hyper-parameters of Approximate Nearest Neighbors ================================================= This example demonstrates the behaviour of the accuracy of the nearest neighbor queries of Locality Sensitive Hashing Forest as the number of candidates and the number of estimators (trees) vary. In the first plot, accuracy is measured with the number of candidates. Here, the term "number of candidates" refers to maximum bound for the number of distinct points retrieved from each tree to calculate the distances. Nearest neighbors are selected from this pool of candidates. Number of estimators is maintained at three fixed levels (1, 5, 10). In the second plot, the number of candidates is fixed at 50. Number of trees is varied and the accuracy is plotted against those values. To measure the accuracy, the true nearest neighbors are required, therefore :class:`sklearn.neighbors.NearestNeighbors` is used to compute the exact neighbors. """ from __future__ import division print(__doc__) # Author: Maheshakya Wijewardena <[email protected]> # # License: BSD 3 clause ############################################################################### import numpy as np from sklearn.datasets.samples_generator import make_blobs from sklearn.neighbors import LSHForest from sklearn.neighbors import NearestNeighbors import matplotlib.pyplot as plt # Initialize size of the database, iterations and required neighbors. n_samples = 10000 n_features = 100 n_queries = 30 rng = np.random.RandomState(42) # Generate sample data X, _ = make_blobs(n_samples=n_samples + n_queries, n_features=n_features, centers=10, random_state=0) X_index = X[:n_samples] X_query = X[n_samples:] # Get exact neighbors nbrs = NearestNeighbors(n_neighbors=1, algorithm='brute', metric='cosine').fit(X_index) neighbors_exact = nbrs.kneighbors(X_query, return_distance=False) # Set `n_candidate` values n_candidates_values = np.linspace(10, 500, 5).astype(np.int) n_estimators_for_candidate_value = [1, 5, 10] n_iter = 10 stds_accuracies = np.zeros((len(n_estimators_for_candidate_value), n_candidates_values.shape[0]), dtype=float) accuracies_c = np.zeros((len(n_estimators_for_candidate_value), n_candidates_values.shape[0]), dtype=float) # LSH Forest is a stochastic index: perform several iteration to estimate # expected accuracy and standard deviation displayed as error bars in # the plots for j, value in enumerate(n_estimators_for_candidate_value): for i, n_candidates in enumerate(n_candidates_values): accuracy_c = [] for seed in range(n_iter): lshf = LSHForest(n_estimators=value, n_candidates=n_candidates, n_neighbors=1, random_state=seed) # Build the LSH Forest index lshf.fit(X_index) # Get neighbors neighbors_approx = lshf.kneighbors(X_query, return_distance=False) accuracy_c.append(np.sum(np.equal(neighbors_approx, neighbors_exact)) / n_queries) stds_accuracies[j, i] = np.std(accuracy_c) accuracies_c[j, i] = np.mean(accuracy_c) # Set `n_estimators` values n_estimators_values = [1, 5, 10, 20, 30, 40, 50] accuracies_trees = np.zeros(len(n_estimators_values), dtype=float) # Calculate average accuracy for each value of `n_estimators` for i, n_estimators in enumerate(n_estimators_values): lshf = LSHForest(n_estimators=n_estimators, n_neighbors=1) # Build the LSH Forest index lshf.fit(X_index) # Get neighbors neighbors_approx = lshf.kneighbors(X_query, return_distance=False) accuracies_trees[i] = np.sum(np.equal(neighbors_approx, neighbors_exact))/n_queries ############################################################################### # Plot the accuracy variation with `n_candidates` plt.figure() colors = ['c', 'm', 'y'] for i, n_estimators in enumerate(n_estimators_for_candidate_value): label = 'n_estimators = %d ' % n_estimators plt.plot(n_candidates_values, accuracies_c[i, :], 'o-', c=colors[i], label=label) plt.errorbar(n_candidates_values, accuracies_c[i, :], stds_accuracies[i, :], c=colors[i]) plt.legend(loc='upper left', fontsize='small') plt.ylim([0, 1.2]) plt.xlim(min(n_candidates_values), max(n_candidates_values)) plt.ylabel("Accuracy") plt.xlabel("n_candidates") plt.grid(which='both') plt.title("Accuracy variation with n_candidates") # Plot the accuracy variation with `n_estimators` plt.figure() plt.scatter(n_estimators_values, accuracies_trees, c='k') plt.plot(n_estimators_values, accuracies_trees, c='g') plt.ylim([0, 1.2]) plt.xlim(min(n_estimators_values), max(n_estimators_values)) plt.ylabel("Accuracy") plt.xlabel("n_estimators") plt.grid(which='both') plt.title("Accuracy variation with n_estimators") plt.show()
bsd-3-clause
INM-6/Python-Module-of-the-Week
session20_NEST/snakemake/scripts/plotPhaseDiagram.py
1
1399
import os import argparse import numpy as np import matplotlib.pyplot as plt # parse command line parameters parser = argparse.ArgumentParser(description='Plot phase diagram.') parser.add_argument('spikefiles', type=str, nargs='+', help='input files') parser.add_argument('plotfile', type=str, help='output file') args = parser.parse_args() # calculate CV for all simulation g_list = [] nu_ex_list = [] CV_list = [] for sf in args.spikefiles: # extract name of the file fn = os.path.splitext(os.path.basename(sf))[0] # extract parameters from filename g_list.append(float(fn.split('_')[1])) nu_ex_list.append(float(fn.split('_')[2])) # load the spike file ids, times = np.load(sf) ids = ids.astype(np.int) # calculate CV for current neuron CV = 0. unique_ids = set(ids) if len(unique_ids) > 0: for id in unique_ids: ISIs = np.diff(times[ids == id]) if len(ISIs) > 1: CV += np.std(ISIs) / np.mean(ISIs) CV /= len(unique_ids) CV_list.append(CV) # make scatter plot, CV indicated by color plt.scatter(g_list, nu_ex_list, c=CV_list, marker='s', s=500, vmin=0, vmax=1) # set axis range and label plt.xlim(0, 8) plt.xlabel('$g$') plt.ylim(0, 4) plt.ylabel('$\\nu_{ext}/\\nu_{thr}$') # add colorbar and title plt.colorbar() plt.title('Coefficient of Variation') plt.savefig(args.plotfile)
mit
marcsans/cnn-physics-perception
phy/lib/python2.7/site-packages/numpy/lib/function_base.py
15
150516
from __future__ import division, absolute_import, print_function import warnings import sys import collections import operator import numpy as np import numpy.core.numeric as _nx from numpy.core import linspace, atleast_1d, atleast_2d from numpy.core.numeric import ( ones, zeros, arange, concatenate, array, asarray, asanyarray, empty, empty_like, ndarray, around, floor, ceil, take, dot, where, intp, integer, isscalar ) from numpy.core.umath import ( pi, multiply, add, arctan2, frompyfunc, cos, less_equal, sqrt, sin, mod, exp, log10 ) from numpy.core.fromnumeric import ( ravel, nonzero, sort, partition, mean, any, sum ) from numpy.core.numerictypes import typecodes, number from numpy.lib.twodim_base import diag from .utils import deprecate from numpy.core.multiarray import _insert, add_docstring from numpy.core.multiarray import digitize, bincount, interp as compiled_interp from numpy.core.umath import _add_newdoc_ufunc as add_newdoc_ufunc from numpy.compat import long from numpy.compat.py3k import basestring # Force range to be a generator, for np.delete's usage. if sys.version_info[0] < 3: range = xrange __all__ = [ 'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', 'percentile', 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', 'extract', 'place', 'vectorize', 'asarray_chkfinite', 'average', 'histogram', 'histogramdd', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid', 'delete', 'insert', 'append', 'interp', 'add_newdoc_ufunc' ] def iterable(y): """ Check whether or not an object can be iterated over. Parameters ---------- y : object Input object. Returns ------- b : {0, 1} Return 1 if the object has an iterator method or is a sequence, and 0 otherwise. Examples -------- >>> np.iterable([1, 2, 3]) 1 >>> np.iterable(2) 0 """ try: iter(y) except: return 0 return 1 def _hist_bin_sqrt(x): """ Square root histogram bin estimator. Bin width is inversely proportional to the data size. Used by many programs for its simplicity. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ return x.ptp() / np.sqrt(x.size) def _hist_bin_sturges(x): """ Sturges histogram bin estimator. A very simplistic estimator based on the assumption of normality of the data. This estimator has poor performance for non-normal data, which becomes especially obvious for large data sets. The estimate depends only on size of the data. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ return x.ptp() / (np.log2(x.size) + 1.0) def _hist_bin_rice(x): """ Rice histogram bin estimator. Another simple estimator with no normality assumption. It has better performance for large data than Sturges, but tends to overestimate the number of bins. The number of bins is proportional to the cube root of data size (asymptotically optimal). The estimate depends only on size of the data. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ return x.ptp() / (2.0 * x.size ** (1.0 / 3)) def _hist_bin_scott(x): """ Scott histogram bin estimator. The binwidth is proportional to the standard deviation of the data and inversely proportional to the cube root of data size (asymptotically optimal). Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ return (24.0 * np.pi**0.5 / x.size)**(1.0 / 3.0) * np.std(x) def _hist_bin_doane(x): """ Doane's histogram bin estimator. Improved version of Sturges' formula which works better for non-normal data. See http://stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ if x.size > 2: sg1 = np.sqrt(6.0 * (x.size - 2) / ((x.size + 1.0) * (x.size + 3))) sigma = np.std(x) if sigma > 0.0: # These three operations add up to # g1 = np.mean(((x - np.mean(x)) / sigma)**3) # but use only one temp array instead of three temp = x - np.mean(x) np.true_divide(temp, sigma, temp) np.power(temp, 3, temp) g1 = np.mean(temp) return x.ptp() / (1.0 + np.log2(x.size) + np.log2(1.0 + np.absolute(g1) / sg1)) return 0.0 def _hist_bin_fd(x): """ The Freedman-Diaconis histogram bin estimator. The Freedman-Diaconis rule uses interquartile range (IQR) to estimate binwidth. It is considered a variation of the Scott rule with more robustness as the IQR is less affected by outliers than the standard deviation. However, the IQR depends on fewer points than the standard deviation, so it is less accurate, especially for long tailed distributions. If the IQR is 0, this function returns 1 for the number of bins. Binwidth is inversely proportional to the cube root of data size (asymptotically optimal). Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ iqr = np.subtract(*np.percentile(x, [75, 25])) return 2.0 * iqr * x.size ** (-1.0 / 3.0) def _hist_bin_auto(x): """ Histogram bin estimator that uses the minimum width of the Freedman-Diaconis and Sturges estimators. The FD estimator is usually the most robust method, but its width estimate tends to be too large for small `x`. The Sturges estimator is quite good for small (<1000) datasets and is the default in the R language. This method gives good off the shelf behaviour. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. See Also -------- _hist_bin_fd, _hist_bin_sturges """ # There is no need to check for zero here. If ptp is, so is IQR and # vice versa. Either both are zero or neither one is. return min(_hist_bin_fd(x), _hist_bin_sturges(x)) # Private dict initialized at module load time _hist_bin_selectors = {'auto': _hist_bin_auto, 'doane': _hist_bin_doane, 'fd': _hist_bin_fd, 'rice': _hist_bin_rice, 'scott': _hist_bin_scott, 'sqrt': _hist_bin_sqrt, 'sturges': _hist_bin_sturges} def histogram(a, bins=10, range=None, normed=False, weights=None, density=None): r""" Compute the histogram of a set of data. Parameters ---------- a : array_like Input data. The histogram is computed over the flattened array. bins : int or sequence of scalars or str, optional If `bins` is an int, it defines the number of equal-width bins in the given range (10, by default). If `bins` is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths. .. versionadded:: 1.11.0 If `bins` is a string from the list below, `histogram` will use the method chosen to calculate the optimal bin width and consequently the number of bins (see `Notes` for more detail on the estimators) from the data that falls within the requested range. While the bin width will be optimal for the actual data in the range, the number of bins will be computed to fill the entire range, including the empty portions. For visualisation, using the 'auto' option is suggested. Weighted data is not supported for automated bin size selection. 'auto' Maximum of the 'sturges' and 'fd' estimators. Provides good all round performance 'fd' (Freedman Diaconis Estimator) Robust (resilient to outliers) estimator that takes into account data variability and data size . 'doane' An improved version of Sturges' estimator that works better with non-normal datasets. 'scott' Less robust estimator that that takes into account data variability and data size. 'rice' Estimator does not take variability into account, only data size. Commonly overestimates number of bins required. 'sturges' R's default method, only accounts for data size. Only optimal for gaussian data and underestimates number of bins for large non-gaussian datasets. 'sqrt' Square root (of data size) estimator, used by Excel and other programs for its speed and simplicity. range : (float, float), optional The lower and upper range of the bins. If not provided, range is simply ``(a.min(), a.max())``. Values outside the range are ignored. The first element of the range must be less than or equal to the second. `range` affects the automatic bin computation as well. While bin width is computed to be optimal based on the actual data within `range`, the bin count will fill the entire range including portions containing no data. normed : bool, optional This keyword is deprecated in Numpy 1.6 due to confusing/buggy behavior. It will be removed in Numpy 2.0. Use the ``density`` keyword instead. If ``False``, the result will contain the number of samples in each bin. If ``True``, the result is the value of the probability *density* function at the bin, normalized such that the *integral* over the range is 1. Note that this latter behavior is known to be buggy with unequal bin widths; use ``density`` instead. weights : array_like, optional An array of weights, of the same shape as `a`. Each value in `a` only contributes its associated weight towards the bin count (instead of 1). If `density` is True, the weights are normalized, so that the integral of the density over the range remains 1. density : bool, optional If ``False``, the result will contain the number of samples in each bin. If ``True``, the result is the value of the probability *density* function at the bin, normalized such that the *integral* over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability *mass* function. Overrides the ``normed`` keyword if given. Returns ------- hist : array The values of the histogram. See `density` and `weights` for a description of the possible semantics. bin_edges : array of dtype float Return the bin edges ``(length(hist)+1)``. See Also -------- histogramdd, bincount, searchsorted, digitize Notes ----- All but the last (righthand-most) bin is half-open. In other words, if `bins` is:: [1, 2, 3, 4] then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which *includes* 4. .. versionadded:: 1.11.0 The methods to estimate the optimal number of bins are well founded in literature, and are inspired by the choices R provides for histogram visualisation. Note that having the number of bins proportional to :math:`n^{1/3}` is asymptotically optimal, which is why it appears in most estimators. These are simply plug-in methods that give good starting points for number of bins. In the equations below, :math:`h` is the binwidth and :math:`n_h` is the number of bins. All estimators that compute bin counts are recast to bin width using the `ptp` of the data. The final bin count is obtained from ``np.round(np.ceil(range / h))`. 'Auto' (maximum of the 'Sturges' and 'FD' estimators) A compromise to get a good value. For small datasets the Sturges value will usually be chosen, while larger datasets will usually default to FD. Avoids the overly conservative behaviour of FD and Sturges for small and large datasets respectively. Switchover point is usually :math:`a.size \approx 1000`. 'FD' (Freedman Diaconis Estimator) .. math:: h = 2 \frac{IQR}{n^{1/3}} The binwidth is proportional to the interquartile range (IQR) and inversely proportional to cube root of a.size. Can be too conservative for small datasets, but is quite good for large datasets. The IQR is very robust to outliers. 'Scott' .. math:: h = \sigma \sqrt[3]{\frac{24 * \sqrt{\pi}}{n}} The binwidth is proportional to the standard deviation of the data and inversely proportional to cube root of ``x.size``. Can be too conservative for small datasets, but is quite good for large datasets. The standard deviation is not very robust to outliers. Values are very similar to the Freedman-Diaconis estimator in the absence of outliers. 'Rice' .. math:: n_h = 2n^{1/3} The number of bins is only proportional to cube root of ``a.size``. It tends to overestimate the number of bins and it does not take into account data variability. 'Sturges' .. math:: n_h = \log _{2}n+1 The number of bins is the base 2 log of ``a.size``. This estimator assumes normality of data and is too conservative for larger, non-normal datasets. This is the default method in R's ``hist`` method. 'Doane' .. math:: n_h = 1 + \log_{2}(n) + \log_{2}(1 + \frac{|g_1|}{\sigma_{g_1})} g_1 = mean[(\frac{x - \mu}{\sigma})^3] \sigma_{g_1} = \sqrt{\frac{6(n - 2)}{(n + 1)(n + 3)}} An improved version of Sturges' formula that produces better estimates for non-normal datasets. This estimator attempts to account for the skew of the data. 'Sqrt' .. math:: n_h = \sqrt n The simplest and fastest estimator. Only takes into account the data size. Examples -------- >>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3]) (array([0, 2, 1]), array([0, 1, 2, 3])) >>> np.histogram(np.arange(4), bins=np.arange(5), density=True) (array([ 0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4])) >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3]) (array([1, 4, 1]), array([0, 1, 2, 3])) >>> a = np.arange(5) >>> hist, bin_edges = np.histogram(a, density=True) >>> hist array([ 0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5]) >>> hist.sum() 2.4999999999999996 >>> np.sum(hist*np.diff(bin_edges)) 1.0 .. versionadded:: 1.11.0 Automated Bin Selection Methods example, using 2 peak random data with 2000 points: >>> import matplotlib.pyplot as plt >>> rng = np.random.RandomState(10) # deterministic random data >>> a = np.hstack((rng.normal(size=1000), ... rng.normal(loc=5, scale=2, size=1000))) >>> plt.hist(a, bins='auto') # plt.hist passes it's arguments to np.histogram >>> plt.title("Histogram with 'auto' bins") >>> plt.show() """ a = asarray(a) if weights is not None: weights = asarray(weights) if np.any(weights.shape != a.shape): raise ValueError( 'weights should have the same shape as a.') weights = weights.ravel() a = a.ravel() # Do not modify the original value of range so we can check for `None` if range is None: if a.size == 0: # handle empty arrays. Can't determine range, so use 0-1. mn, mx = 0.0, 1.0 else: mn, mx = a.min() + 0.0, a.max() + 0.0 else: mn, mx = [mi + 0.0 for mi in range] if mn > mx: raise ValueError( 'max must be larger than min in range parameter.') if not np.all(np.isfinite([mn, mx])): raise ValueError( 'range parameter must be finite.') if mn == mx: mn -= 0.5 mx += 0.5 if isinstance(bins, basestring): # if `bins` is a string for an automatic method, # this will replace it with the number of bins calculated if bins not in _hist_bin_selectors: raise ValueError("{0} not a valid estimator for bins".format(bins)) if weights is not None: raise TypeError("Automated estimation of the number of " "bins is not supported for weighted data") # Make a reference to `a` b = a # Update the reference if the range needs truncation if range is not None: keep = (a >= mn) keep &= (a <= mx) if not np.logical_and.reduce(keep): b = a[keep] if b.size == 0: bins = 1 else: # Do not call selectors on empty arrays width = _hist_bin_selectors[bins](b) if width: bins = int(np.ceil((mx - mn) / width)) else: # Width can be zero for some estimators, e.g. FD when # the IQR of the data is zero. bins = 1 # Histogram is an integer or a float array depending on the weights. if weights is None: ntype = np.dtype(np.intp) else: ntype = weights.dtype # We set a block size, as this allows us to iterate over chunks when # computing histograms, to minimize memory usage. BLOCK = 65536 if not iterable(bins): if np.isscalar(bins) and bins < 1: raise ValueError( '`bins` should be a positive integer.') # At this point, if the weights are not integer, floating point, or # complex, we have to use the slow algorithm. if weights is not None and not (np.can_cast(weights.dtype, np.double) or np.can_cast(weights.dtype, np.complex)): bins = linspace(mn, mx, bins + 1, endpoint=True) if not iterable(bins): # We now convert values of a to bin indices, under the assumption of # equal bin widths (which is valid here). # Initialize empty histogram n = np.zeros(bins, ntype) # Pre-compute histogram scaling factor norm = bins / (mx - mn) # Compute the bin edges for potential correction. bin_edges = linspace(mn, mx, bins + 1, endpoint=True) # We iterate over blocks here for two reasons: the first is that for # large arrays, it is actually faster (for example for a 10^8 array it # is 2x as fast) and it results in a memory footprint 3x lower in the # limit of large arrays. for i in arange(0, len(a), BLOCK): tmp_a = a[i:i+BLOCK] if weights is None: tmp_w = None else: tmp_w = weights[i:i + BLOCK] # Only include values in the right range keep = (tmp_a >= mn) keep &= (tmp_a <= mx) if not np.logical_and.reduce(keep): tmp_a = tmp_a[keep] if tmp_w is not None: tmp_w = tmp_w[keep] tmp_a_data = tmp_a.astype(float) tmp_a = tmp_a_data - mn tmp_a *= norm # Compute the bin indices, and for values that lie exactly on mx we # need to subtract one indices = tmp_a.astype(np.intp) indices[indices == bins] -= 1 # The index computation is not guaranteed to give exactly # consistent results within ~1 ULP of the bin edges. decrement = tmp_a_data < bin_edges[indices] indices[decrement] -= 1 # The last bin includes the right edge. The other bins do not. increment = (tmp_a_data >= bin_edges[indices + 1]) & (indices != bins - 1) indices[increment] += 1 # We now compute the histogram using bincount if ntype.kind == 'c': n.real += np.bincount(indices, weights=tmp_w.real, minlength=bins) n.imag += np.bincount(indices, weights=tmp_w.imag, minlength=bins) else: n += np.bincount(indices, weights=tmp_w, minlength=bins).astype(ntype) # Rename the bin edges for return. bins = bin_edges else: bins = asarray(bins) if (np.diff(bins) < 0).any(): raise ValueError( 'bins must increase monotonically.') # Initialize empty histogram n = np.zeros(bins.shape, ntype) if weights is None: for i in arange(0, len(a), BLOCK): sa = sort(a[i:i+BLOCK]) n += np.r_[sa.searchsorted(bins[:-1], 'left'), sa.searchsorted(bins[-1], 'right')] else: zero = array(0, dtype=ntype) for i in arange(0, len(a), BLOCK): tmp_a = a[i:i+BLOCK] tmp_w = weights[i:i+BLOCK] sorting_index = np.argsort(tmp_a) sa = tmp_a[sorting_index] sw = tmp_w[sorting_index] cw = np.concatenate(([zero, ], sw.cumsum())) bin_index = np.r_[sa.searchsorted(bins[:-1], 'left'), sa.searchsorted(bins[-1], 'right')] n += cw[bin_index] n = np.diff(n) if density is not None: if density: db = array(np.diff(bins), float) return n/db/n.sum(), bins else: return n, bins else: # deprecated, buggy behavior. Remove for Numpy 2.0 if normed: db = array(np.diff(bins), float) return n/(n*db).sum(), bins else: return n, bins def histogramdd(sample, bins=10, range=None, normed=False, weights=None): """ Compute the multidimensional histogram of some data. Parameters ---------- sample : array_like The data to be histogrammed. It must be an (N,D) array or data that can be converted to such. The rows of the resulting array are the coordinates of points in a D dimensional polytope. bins : sequence or int, optional The bin specification: * A sequence of arrays describing the bin edges along each dimension. * The number of bins for each dimension (nx, ny, ... =bins) * The number of bins for all dimensions (nx=ny=...=bins). range : sequence, optional A sequence of lower and upper bin edges to be used if the edges are not given explicitly in `bins`. Defaults to the minimum and maximum values along each dimension. normed : bool, optional If False, returns the number of samples in each bin. If True, returns the bin density ``bin_count / sample_count / bin_volume``. weights : (N,) array_like, optional An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`. Weights are normalized to 1 if normed is True. If normed is False, the values of the returned histogram are equal to the sum of the weights belonging to the samples falling into each bin. Returns ------- H : ndarray The multidimensional histogram of sample x. See normed and weights for the different possible semantics. edges : list A list of D arrays describing the bin edges for each dimension. See Also -------- histogram: 1-D histogram histogram2d: 2-D histogram Examples -------- >>> r = np.random.randn(100,3) >>> H, edges = np.histogramdd(r, bins = (5, 8, 4)) >>> H.shape, edges[0].size, edges[1].size, edges[2].size ((5, 8, 4), 6, 9, 5) """ try: # Sample is an ND-array. N, D = sample.shape except (AttributeError, ValueError): # Sample is a sequence of 1D arrays. sample = atleast_2d(sample).T N, D = sample.shape nbin = empty(D, int) edges = D*[None] dedges = D*[None] if weights is not None: weights = asarray(weights) try: M = len(bins) if M != D: raise ValueError( 'The dimension of bins must be equal to the dimension of the ' ' sample x.') except TypeError: # bins is an integer bins = D*[bins] # Select range for each dimension # Used only if number of bins is given. if range is None: # Handle empty input. Range can't be determined in that case, use 0-1. if N == 0: smin = zeros(D) smax = ones(D) else: smin = atleast_1d(array(sample.min(0), float)) smax = atleast_1d(array(sample.max(0), float)) else: if not np.all(np.isfinite(range)): raise ValueError( 'range parameter must be finite.') smin = zeros(D) smax = zeros(D) for i in arange(D): smin[i], smax[i] = range[i] # Make sure the bins have a finite width. for i in arange(len(smin)): if smin[i] == smax[i]: smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 # avoid rounding issues for comparisons when dealing with inexact types if np.issubdtype(sample.dtype, np.inexact): edge_dt = sample.dtype else: edge_dt = float # Create edge arrays for i in arange(D): if isscalar(bins[i]): if bins[i] < 1: raise ValueError( "Element at index %s in `bins` should be a positive " "integer." % i) nbin[i] = bins[i] + 2 # +2 for outlier bins edges[i] = linspace(smin[i], smax[i], nbin[i]-1, dtype=edge_dt) else: edges[i] = asarray(bins[i], edge_dt) nbin[i] = len(edges[i]) + 1 # +1 for outlier bins dedges[i] = diff(edges[i]) if np.any(np.asarray(dedges[i]) <= 0): raise ValueError( "Found bin edge of size <= 0. Did you specify `bins` with" "non-monotonic sequence?") nbin = asarray(nbin) # Handle empty input. if N == 0: return np.zeros(nbin-2), edges # Compute the bin number each sample falls into. Ncount = {} for i in arange(D): Ncount[i] = digitize(sample[:, i], edges[i]) # Using digitize, values that fall on an edge are put in the right bin. # For the rightmost bin, we want values equal to the right edge to be # counted in the last bin, and not as an outlier. for i in arange(D): # Rounding precision mindiff = dedges[i].min() if not np.isinf(mindiff): decimal = int(-log10(mindiff)) + 6 # Find which points are on the rightmost edge. not_smaller_than_edge = (sample[:, i] >= edges[i][-1]) on_edge = (around(sample[:, i], decimal) == around(edges[i][-1], decimal)) # Shift these points one bin to the left. Ncount[i][where(on_edge & not_smaller_than_edge)[0]] -= 1 # Flattened histogram matrix (1D) # Reshape is used so that overlarge arrays # will raise an error. hist = zeros(nbin, float).reshape(-1) # Compute the sample indices in the flattened histogram matrix. ni = nbin.argsort() xy = zeros(N, int) for i in arange(0, D-1): xy += Ncount[ni[i]] * nbin[ni[i+1:]].prod() xy += Ncount[ni[-1]] # Compute the number of repetitions in xy and assign it to the # flattened histmat. if len(xy) == 0: return zeros(nbin-2, int), edges flatcount = bincount(xy, weights) a = arange(len(flatcount)) hist[a] = flatcount # Shape into a proper matrix hist = hist.reshape(sort(nbin)) for i in arange(nbin.size): j = ni.argsort()[i] hist = hist.swapaxes(i, j) ni[i], ni[j] = ni[j], ni[i] # Remove outliers (indices 0 and -1 for each dimension). core = D*[slice(1, -1)] hist = hist[core] # Normalize if normed is True if normed: s = hist.sum() for i in arange(D): shape = ones(D, int) shape[i] = nbin[i] - 2 hist = hist / dedges[i].reshape(shape) hist /= s if (hist.shape != nbin - 2).any(): raise RuntimeError( "Internal Shape Error") return hist, edges def average(a, axis=None, weights=None, returned=False): """ Compute the weighted average along the specified axis. Parameters ---------- a : array_like Array containing data to be averaged. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which to average `a`. If `None`, averaging is done over the flattened array. weights : array_like, optional An array of weights associated with the values in `a`. Each value in `a` contributes to the average according to its associated weight. The weights array can either be 1-D (in which case its length must be the size of `a` along the given axis) or of the same shape as `a`. If `weights=None`, then all data in `a` are assumed to have a weight equal to one. returned : bool, optional Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`) is returned, otherwise only the average is returned. If `weights=None`, `sum_of_weights` is equivalent to the number of elements over which the average is taken. Returns ------- average, [sum_of_weights] : array_type or double Return the average along the specified axis. When returned is `True`, return a tuple with the average as the first element and the sum of the weights as the second element. The return type is `Float` if `a` is of integer type, otherwise it is of the same type as `a`. `sum_of_weights` is of the same type as `average`. Raises ------ ZeroDivisionError When all weights along axis are zero. See `numpy.ma.average` for a version robust to this type of error. TypeError When the length of 1D `weights` is not the same as the shape of `a` along axis. See Also -------- mean ma.average : average for masked arrays -- useful if your data contains "missing" values Examples -------- >>> data = range(1,5) >>> data [1, 2, 3, 4] >>> np.average(data) 2.5 >>> np.average(range(1,11), weights=range(10,0,-1)) 4.0 >>> data = np.arange(6).reshape((3,2)) >>> data array([[0, 1], [2, 3], [4, 5]]) >>> np.average(data, axis=1, weights=[1./4, 3./4]) array([ 0.75, 2.75, 4.75]) >>> np.average(data, weights=[1./4, 3./4]) Traceback (most recent call last): ... TypeError: Axis must be specified when shapes of a and weights differ. """ if not isinstance(a, np.matrix): a = np.asarray(a) if weights is None: avg = a.mean(axis) scl = avg.dtype.type(a.size/avg.size) else: a = a + 0.0 wgt = np.asarray(weights) # Sanity checks if a.shape != wgt.shape: if axis is None: raise TypeError( "Axis must be specified when shapes of a and weights " "differ.") if wgt.ndim != 1: raise TypeError( "1D weights expected when shapes of a and weights differ.") if wgt.shape[0] != a.shape[axis]: raise ValueError( "Length of weights not compatible with specified axis.") # setup wgt to broadcast along axis wgt = np.array(wgt, copy=0, ndmin=a.ndim).swapaxes(-1, axis) scl = wgt.sum(axis=axis, dtype=np.result_type(a.dtype, wgt.dtype)) if (scl == 0.0).any(): raise ZeroDivisionError( "Weights sum to zero, can't be normalized") avg = np.multiply(a, wgt).sum(axis)/scl if returned: scl = np.multiply(avg, 0) + scl return avg, scl else: return avg def asarray_chkfinite(a, dtype=None, order=None): """Convert the input to an array, checking for NaNs or Infs. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Success requires no NaNs or Infs. dtype : data-type, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to 'C'. Returns ------- out : ndarray Array interpretation of `a`. No copy is performed if the input is already an ndarray. If `a` is a subclass of ndarray, a base class ndarray is returned. Raises ------ ValueError Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity). See Also -------- asarray : Create and array. asanyarray : Similar function which passes through subclasses. ascontiguousarray : Convert input to a contiguous array. asfarray : Convert input to a floating point ndarray. asfortranarray : Convert input to an ndarray with column-major memory order. fromiter : Create an array from an iterator. fromfunction : Construct an array by executing a function on grid positions. Examples -------- Convert a list into an array. If all elements are finite ``asarray_chkfinite`` is identical to ``asarray``. >>> a = [1, 2] >>> np.asarray_chkfinite(a, dtype=float) array([1., 2.]) Raises ValueError if array_like contains Nans or Infs. >>> a = [1, 2, np.inf] >>> try: ... np.asarray_chkfinite(a) ... except ValueError: ... print('ValueError') ... ValueError """ a = asarray(a, dtype=dtype, order=order) if a.dtype.char in typecodes['AllFloat'] and not np.isfinite(a).all(): raise ValueError( "array must not contain infs or NaNs") return a def piecewise(x, condlist, funclist, *args, **kw): """ Evaluate a piecewise-defined function. Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true. Parameters ---------- x : ndarray The input domain. condlist : list of bool arrays Each boolean array corresponds to a function in `funclist`. Wherever `condlist[i]` is True, `funclist[i](x)` is used as the output value. Each boolean array in `condlist` selects a piece of `x`, and should therefore be of the same shape as `x`. The length of `condlist` must correspond to that of `funclist`. If one extra function is given, i.e. if ``len(funclist) - len(condlist) == 1``, then that extra function is the default value, used wherever all conditions are false. funclist : list of callables, f(x,*args,**kw), or scalars Each function is evaluated over `x` wherever its corresponding condition is True. It should take an array as input and give an array or a scalar value as output. If, instead of a callable, a scalar is provided then a constant function (``lambda x: scalar``) is assumed. args : tuple, optional Any further arguments given to `piecewise` are passed to the functions upon execution, i.e., if called ``piecewise(..., ..., 1, 'a')``, then each function is called as ``f(x, 1, 'a')``. kw : dict, optional Keyword arguments used in calling `piecewise` are passed to the functions upon execution, i.e., if called ``piecewise(..., ..., lambda=1)``, then each function is called as ``f(x, lambda=1)``. Returns ------- out : ndarray The output is the same shape and type as x and is found by calling the functions in `funclist` on the appropriate portions of `x`, as defined by the boolean arrays in `condlist`. Portions not covered by any condition have a default value of 0. See Also -------- choose, select, where Notes ----- This is similar to choose or select, except that functions are evaluated on elements of `x` that satisfy the corresponding condition from `condlist`. The result is:: |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- Examples -------- Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.]) Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for ``x >= 0``. >>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x]) array([ 2.5, 1.5, 0.5, 0.5, 1.5, 2.5]) """ x = asanyarray(x) n2 = len(funclist) if (isscalar(condlist) or not (isinstance(condlist[0], list) or isinstance(condlist[0], ndarray))): condlist = [condlist] condlist = array(condlist, dtype=bool) n = len(condlist) # This is a hack to work around problems with NumPy's # handling of 0-d arrays and boolean indexing with # numpy.bool_ scalars zerod = False if x.ndim == 0: x = x[None] zerod = True if condlist.shape[-1] != 1: condlist = condlist.T if n == n2 - 1: # compute the "otherwise" condition. totlist = np.logical_or.reduce(condlist, axis=0) # Only able to stack vertically if the array is 1d or less if x.ndim <= 1: condlist = np.vstack([condlist, ~totlist]) else: condlist = [asarray(c, dtype=bool) for c in condlist] totlist = condlist[0] for k in range(1, n): totlist |= condlist[k] condlist.append(~totlist) n += 1 y = zeros(x.shape, x.dtype) for k in range(n): item = funclist[k] if not isinstance(item, collections.Callable): y[condlist[k]] = item else: vals = x[condlist[k]] if vals.size > 0: y[condlist[k]] = item(vals, *args, **kw) if zerod: y = y.squeeze() return y def select(condlist, choicelist, default=0): """ Return an array drawn from elements in choicelist, depending on conditions. Parameters ---------- condlist : list of bool ndarrays The list of conditions which determine from which array in `choicelist` the output elements are taken. When multiple conditions are satisfied, the first one encountered in `condlist` is used. choicelist : list of ndarrays The list of arrays from which the output elements are taken. It has to be of the same length as `condlist`. default : scalar, optional The element inserted in `output` when all conditions evaluate to False. Returns ------- output : ndarray The output at position m is the m-th element of the array in `choicelist` where the m-th element of the corresponding array in `condlist` is True. See Also -------- where : Return elements from one of two arrays depending on condition. take, choose, compress, diag, diagonal Examples -------- >>> x = np.arange(10) >>> condlist = [x<3, x>5] >>> choicelist = [x, x**2] >>> np.select(condlist, choicelist) array([ 0, 1, 2, 0, 0, 0, 36, 49, 64, 81]) """ # Check the size of condlist and choicelist are the same, or abort. if len(condlist) != len(choicelist): raise ValueError( 'list of cases must be same length as list of conditions') # Now that the dtype is known, handle the deprecated select([], []) case if len(condlist) == 0: # 2014-02-24, 1.9 warnings.warn("select with an empty condition list is not possible" "and will be deprecated", DeprecationWarning) return np.asarray(default)[()] choicelist = [np.asarray(choice) for choice in choicelist] choicelist.append(np.asarray(default)) # need to get the result type before broadcasting for correct scalar # behaviour dtype = np.result_type(*choicelist) # Convert conditions to arrays and broadcast conditions and choices # as the shape is needed for the result. Doing it separately optimizes # for example when all choices are scalars. condlist = np.broadcast_arrays(*condlist) choicelist = np.broadcast_arrays(*choicelist) # If cond array is not an ndarray in boolean format or scalar bool, abort. deprecated_ints = False for i in range(len(condlist)): cond = condlist[i] if cond.dtype.type is not np.bool_: if np.issubdtype(cond.dtype, np.integer): # A previous implementation accepted int ndarrays accidentally. # Supported here deliberately, but deprecated. condlist[i] = condlist[i].astype(bool) deprecated_ints = True else: raise ValueError( 'invalid entry in choicelist: should be boolean ndarray') if deprecated_ints: # 2014-02-24, 1.9 msg = "select condlists containing integer ndarrays is deprecated " \ "and will be removed in the future. Use `.astype(bool)` to " \ "convert to bools." warnings.warn(msg, DeprecationWarning) if choicelist[0].ndim == 0: # This may be common, so avoid the call. result_shape = condlist[0].shape else: result_shape = np.broadcast_arrays(condlist[0], choicelist[0])[0].shape result = np.full(result_shape, choicelist[-1], dtype) # Use np.copyto to burn each choicelist array onto result, using the # corresponding condlist as a boolean mask. This is done in reverse # order since the first choice should take precedence. choicelist = choicelist[-2::-1] condlist = condlist[::-1] for choice, cond in zip(choicelist, condlist): np.copyto(result, choice, where=cond) return result def copy(a, order='K'): """ Return an array copy of the given object. Parameters ---------- a : array_like Input data. order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :meth:ndarray.copy are very similar, but have different default values for their order= arguments.) Returns ------- arr : ndarray Array interpretation of `a`. Notes ----- This is equivalent to >>> np.array(a, copy=True) #doctest: +SKIP Examples -------- Create an array x, with a reference y and a copy z: >>> x = np.array([1, 2, 3]) >>> y = x >>> z = np.copy(x) Note that, when we modify x, y changes, but not z: >>> x[0] = 10 >>> x[0] == y[0] True >>> x[0] == z[0] False """ return array(a, order=order, copy=True) # Basic operations def gradient(f, *varargs, **kwargs): """ Return the gradient of an N-dimensional array. The gradient is computed using second order accurate central differences in the interior and either first differences or second order accurate one-sides (forward or backwards) differences at the boundaries. The returned gradient hence has the same shape as the input array. Parameters ---------- f : array_like An N-dimensional array containing samples of a scalar function. varargs : scalar or list of scalar, optional N scalars specifying the sample distances for each dimension, i.e. `dx`, `dy`, `dz`, ... Default distance: 1. single scalar specifies sample distance for all dimensions. if `axis` is given, the number of varargs must equal the number of axes. edge_order : {1, 2}, optional Gradient is calculated using N\ :sup:`th` order accurate differences at the boundaries. Default: 1. .. versionadded:: 1.9.1 axis : None or int or tuple of ints, optional Gradient is calculated only along the given axis or axes The default (axis = None) is to calculate the gradient for all the axes of the input array. axis may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.11.0 Returns ------- gradient : list of ndarray Each element of `list` has the same shape as `f` giving the derivative of `f` with respect to each dimension. Examples -------- >>> x = np.array([1, 2, 4, 7, 11, 16], dtype=np.float) >>> np.gradient(x) array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ]) >>> np.gradient(x, 2) array([ 0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ]) For two dimensional arrays, the return will be two arrays ordered by axis. In this example the first array stands for the gradient in rows and the second one in columns direction: >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=np.float)) [array([[ 2., 2., -1.], [ 2., 2., -1.]]), array([[ 1. , 2.5, 4. ], [ 1. , 1. , 1. ]])] >>> x = np.array([0, 1, 2, 3, 4]) >>> dx = np.gradient(x) >>> y = x**2 >>> np.gradient(y, dx, edge_order=2) array([-0., 2., 4., 6., 8.]) The axis keyword can be used to specify a subset of axes of which the gradient is calculated >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=np.float), axis=0) array([[ 2., 2., -1.], [ 2., 2., -1.]]) """ f = np.asanyarray(f) N = len(f.shape) # number of dimensions axes = kwargs.pop('axis', None) if axes is None: axes = tuple(range(N)) # check axes to have correct type and no duplicate entries if isinstance(axes, int): axes = (axes,) if not isinstance(axes, tuple): raise TypeError("A tuple of integers or a single integer is required") # normalize axis values: axes = tuple(x + N if x < 0 else x for x in axes) if max(axes) >= N or min(axes) < 0: raise ValueError("'axis' entry is out of bounds") if len(set(axes)) != len(axes): raise ValueError("duplicate value in 'axis'") n = len(varargs) if n == 0: dx = [1.0]*N elif n == 1: dx = [varargs[0]]*N elif n == len(axes): dx = list(varargs) else: raise SyntaxError( "invalid number of arguments") edge_order = kwargs.pop('edge_order', 1) if kwargs: raise TypeError('"{}" are not valid keyword arguments.'.format( '", "'.join(kwargs.keys()))) if edge_order > 2: raise ValueError("'edge_order' greater than 2 not supported") # use central differences on interior and one-sided differences on the # endpoints. This preserves second order-accuracy over the full domain. outvals = [] # create slice objects --- initially all are [:, :, ..., :] slice1 = [slice(None)]*N slice2 = [slice(None)]*N slice3 = [slice(None)]*N slice4 = [slice(None)]*N otype = f.dtype.char if otype not in ['f', 'd', 'F', 'D', 'm', 'M']: otype = 'd' # Difference of datetime64 elements results in timedelta64 if otype == 'M': # Need to use the full dtype name because it contains unit information otype = f.dtype.name.replace('datetime', 'timedelta') elif otype == 'm': # Needs to keep the specific units, can't be a general unit otype = f.dtype # Convert datetime64 data into ints. Make dummy variable `y` # that is a view of ints if the data is datetime64, otherwise # just set y equal to the array `f`. if f.dtype.char in ["M", "m"]: y = f.view('int64') else: y = f for i, axis in enumerate(axes): if y.shape[axis] < 2: raise ValueError( "Shape of array too small to calculate a numerical gradient, " "at least two elements are required.") # Numerical differentiation: 1st order edges, 2nd order interior if y.shape[axis] == 2 or edge_order == 1: # Use first order differences for time data out = np.empty_like(y, dtype=otype) slice1[axis] = slice(1, -1) slice2[axis] = slice(2, None) slice3[axis] = slice(None, -2) # 1D equivalent -- out[1:-1] = (y[2:] - y[:-2])/2.0 out[slice1] = (y[slice2] - y[slice3])/2.0 slice1[axis] = 0 slice2[axis] = 1 slice3[axis] = 0 # 1D equivalent -- out[0] = (y[1] - y[0]) out[slice1] = (y[slice2] - y[slice3]) slice1[axis] = -1 slice2[axis] = -1 slice3[axis] = -2 # 1D equivalent -- out[-1] = (y[-1] - y[-2]) out[slice1] = (y[slice2] - y[slice3]) # Numerical differentiation: 2st order edges, 2nd order interior else: # Use second order differences where possible out = np.empty_like(y, dtype=otype) slice1[axis] = slice(1, -1) slice2[axis] = slice(2, None) slice3[axis] = slice(None, -2) # 1D equivalent -- out[1:-1] = (y[2:] - y[:-2])/2.0 out[slice1] = (y[slice2] - y[slice3])/2.0 slice1[axis] = 0 slice2[axis] = 0 slice3[axis] = 1 slice4[axis] = 2 # 1D equivalent -- out[0] = -(3*y[0] - 4*y[1] + y[2]) / 2.0 out[slice1] = -(3.0*y[slice2] - 4.0*y[slice3] + y[slice4])/2.0 slice1[axis] = -1 slice2[axis] = -1 slice3[axis] = -2 slice4[axis] = -3 # 1D equivalent -- out[-1] = (3*y[-1] - 4*y[-2] + y[-3]) out[slice1] = (3.0*y[slice2] - 4.0*y[slice3] + y[slice4])/2.0 # divide by step size out /= dx[i] outvals.append(out) # reset the slice object in this dimension to ":" slice1[axis] = slice(None) slice2[axis] = slice(None) slice3[axis] = slice(None) slice4[axis] = slice(None) if len(axes) == 1: return outvals[0] else: return outvals def diff(a, n=1, axis=-1): """ Calculate the n-th discrete difference along given axis. The first difference is given by ``out[n] = a[n+1] - a[n]`` along the given axis, higher differences are calculated by using `diff` recursively. Parameters ---------- a : array_like Input array n : int, optional The number of times values are differenced. axis : int, optional The axis along which the difference is taken, default is the last axis. Returns ------- diff : ndarray The n-th differences. The shape of the output is the same as `a` except along `axis` where the dimension is smaller by `n`. . See Also -------- gradient, ediff1d, cumsum Examples -------- >>> x = np.array([1, 2, 4, 7, 0]) >>> np.diff(x) array([ 1, 2, 3, -7]) >>> np.diff(x, n=2) array([ 1, 1, -10]) >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]]) >>> np.diff(x) array([[2, 3, 4], [5, 1, 2]]) >>> np.diff(x, axis=0) array([[-1, 2, 0, -2]]) """ if n == 0: return a if n < 0: raise ValueError( "order must be non-negative but got " + repr(n)) a = asanyarray(a) nd = len(a.shape) slice1 = [slice(None)]*nd slice2 = [slice(None)]*nd slice1[axis] = slice(1, None) slice2[axis] = slice(None, -1) slice1 = tuple(slice1) slice2 = tuple(slice2) if n > 1: return diff(a[slice1]-a[slice2], n-1, axis=axis) else: return a[slice1]-a[slice2] def interp(x, xp, fp, left=None, right=None, period=None): """ One-dimensional linear interpolation. Returns the one-dimensional piecewise linear interpolant to a function with given values at discrete data-points. Parameters ---------- x : array_like The x-coordinates of the interpolated values. xp : 1-D sequence of floats The x-coordinates of the data points, must be increasing if argument `period` is not specified. Otherwise, `xp` is internally sorted after normalizing the periodic boundaries with ``xp = xp % period``. fp : 1-D sequence of floats The y-coordinates of the data points, same length as `xp`. left : float, optional Value to return for `x < xp[0]`, default is `fp[0]`. right : float, optional Value to return for `x > xp[-1]`, default is `fp[-1]`. period : None or float, optional A period for the x-coordinates. This parameter allows the proper interpolation of angular x-coordinates. Parameters `left` and `right` are ignored if `period` is specified. .. versionadded:: 1.10.0 Returns ------- y : float or ndarray The interpolated values, same shape as `x`. Raises ------ ValueError If `xp` and `fp` have different length If `xp` or `fp` are not 1-D sequences If `period == 0` Notes ----- Does not check that the x-coordinate sequence `xp` is increasing. If `xp` is not increasing, the results are nonsense. A simple check for increasing is:: np.all(np.diff(xp) > 0) Examples -------- >>> xp = [1, 2, 3] >>> fp = [3, 2, 0] >>> np.interp(2.5, xp, fp) 1.0 >>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp) array([ 3. , 3. , 2.5 , 0.56, 0. ]) >>> UNDEF = -99.0 >>> np.interp(3.14, xp, fp, right=UNDEF) -99.0 Plot an interpolant to the sine function: >>> x = np.linspace(0, 2*np.pi, 10) >>> y = np.sin(x) >>> xvals = np.linspace(0, 2*np.pi, 50) >>> yinterp = np.interp(xvals, x, y) >>> import matplotlib.pyplot as plt >>> plt.plot(x, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(xvals, yinterp, '-x') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.show() Interpolation with periodic x-coordinates: >>> x = [-180, -170, -185, 185, -10, -5, 0, 365] >>> xp = [190, -190, 350, -350] >>> fp = [5, 10, 3, 4] >>> np.interp(x, xp, fp, period=360) array([7.5, 5., 8.75, 6.25, 3., 3.25, 3.5, 3.75]) """ if period is None: if isinstance(x, (float, int, number)): return compiled_interp([x], xp, fp, left, right).item() elif isinstance(x, np.ndarray) and x.ndim == 0: return compiled_interp([x], xp, fp, left, right).item() else: return compiled_interp(x, xp, fp, left, right) else: if period == 0: raise ValueError("period must be a non-zero value") period = abs(period) left = None right = None return_array = True if isinstance(x, (float, int, number)): return_array = False x = [x] x = np.asarray(x, dtype=np.float64) xp = np.asarray(xp, dtype=np.float64) fp = np.asarray(fp, dtype=np.float64) if xp.ndim != 1 or fp.ndim != 1: raise ValueError("Data points must be 1-D sequences") if xp.shape[0] != fp.shape[0]: raise ValueError("fp and xp are not of the same length") # normalizing periodic boundaries x = x % period xp = xp % period asort_xp = np.argsort(xp) xp = xp[asort_xp] fp = fp[asort_xp] xp = np.concatenate((xp[-1:]-period, xp, xp[0:1]+period)) fp = np.concatenate((fp[-1:], fp, fp[0:1])) if return_array: return compiled_interp(x, xp, fp, left, right) else: return compiled_interp(x, xp, fp, left, right).item() def angle(z, deg=0): """ Return the angle of the complex argument. Parameters ---------- z : array_like A complex number or sequence of complex numbers. deg : bool, optional Return angle in degrees if True, radians if False (default). Returns ------- angle : ndarray or scalar The counterclockwise angle from the positive real axis on the complex plane, with dtype as numpy.float64. See Also -------- arctan2 absolute Examples -------- >>> np.angle([1.0, 1.0j, 1+1j]) # in radians array([ 0. , 1.57079633, 0.78539816]) >>> np.angle(1+1j, deg=True) # in degrees 45.0 """ if deg: fact = 180/pi else: fact = 1.0 z = asarray(z) if (issubclass(z.dtype.type, _nx.complexfloating)): zimag = z.imag zreal = z.real else: zimag = 0 zreal = z return arctan2(zimag, zreal) * fact def unwrap(p, discont=pi, axis=-1): """ Unwrap by changing deltas between values to 2*pi complement. Unwrap radian phase `p` by changing absolute jumps greater than `discont` to their 2*pi complement along the given axis. Parameters ---------- p : array_like Input array. discont : float, optional Maximum discontinuity between values, default is ``pi``. axis : int, optional Axis along which unwrap will operate, default is the last axis. Returns ------- out : ndarray Output array. See Also -------- rad2deg, deg2rad Notes ----- If the discontinuity in `p` is smaller than ``pi``, but larger than `discont`, no unwrapping is done because taking the 2*pi complement would only make the discontinuity larger. Examples -------- >>> phase = np.linspace(0, np.pi, num=5) >>> phase[3:] += np.pi >>> phase array([ 0. , 0.78539816, 1.57079633, 5.49778714, 6.28318531]) >>> np.unwrap(phase) array([ 0. , 0.78539816, 1.57079633, -0.78539816, 0. ]) """ p = asarray(p) nd = len(p.shape) dd = diff(p, axis=axis) slice1 = [slice(None, None)]*nd # full slices slice1[axis] = slice(1, None) ddmod = mod(dd + pi, 2*pi) - pi _nx.copyto(ddmod, pi, where=(ddmod == -pi) & (dd > 0)) ph_correct = ddmod - dd _nx.copyto(ph_correct, 0, where=abs(dd) < discont) up = array(p, copy=True, dtype='d') up[slice1] = p[slice1] + ph_correct.cumsum(axis) return up def sort_complex(a): """ Sort a complex array using the real part first, then the imaginary part. Parameters ---------- a : array_like Input array Returns ------- out : complex ndarray Always returns a sorted complex array. Examples -------- >>> np.sort_complex([5, 3, 6, 2, 1]) array([ 1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j]) >>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j]) array([ 1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j]) """ b = array(a, copy=True) b.sort() if not issubclass(b.dtype.type, _nx.complexfloating): if b.dtype.char in 'bhBH': return b.astype('F') elif b.dtype.char == 'g': return b.astype('G') else: return b.astype('D') else: return b def trim_zeros(filt, trim='fb'): """ Trim the leading and/or trailing zeros from a 1-D array or sequence. Parameters ---------- filt : 1-D array or sequence Input array. trim : str, optional A string with 'f' representing trim from front and 'b' to trim from back. Default is 'fb', trim zeros from both front and back of the array. Returns ------- trimmed : 1-D array or sequence The result of trimming the input. The input data type is preserved. Examples -------- >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0)) >>> np.trim_zeros(a) array([1, 2, 3, 0, 2, 1]) >>> np.trim_zeros(a, 'b') array([0, 0, 0, 1, 2, 3, 0, 2, 1]) The input data type is preserved, list/tuple in means list/tuple out. >>> np.trim_zeros([0, 1, 2, 0]) [1, 2] """ first = 0 trim = trim.upper() if 'F' in trim: for i in filt: if i != 0.: break else: first = first + 1 last = len(filt) if 'B' in trim: for i in filt[::-1]: if i != 0.: break else: last = last - 1 return filt[first:last] @deprecate def unique(x): """ This function is deprecated. Use numpy.lib.arraysetops.unique() instead. """ try: tmp = x.flatten() if tmp.size == 0: return tmp tmp.sort() idx = concatenate(([True], tmp[1:] != tmp[:-1])) return tmp[idx] except AttributeError: items = sorted(set(x)) return asarray(items) def extract(condition, arr): """ Return the elements of an array that satisfy some condition. This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If `condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``. Note that `place` does the exact opposite of `extract`. Parameters ---------- condition : array_like An array whose nonzero or True entries indicate the elements of `arr` to extract. arr : array_like Input array of the same size as `condition`. Returns ------- extract : ndarray Rank 1 array of values from `arr` where `condition` is True. See Also -------- take, put, copyto, compress, place Examples -------- >>> arr = np.arange(12).reshape((3, 4)) >>> arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> condition = np.mod(arr, 3)==0 >>> condition array([[ True, False, False, True], [False, False, True, False], [False, True, False, False]], dtype=bool) >>> np.extract(condition, arr) array([0, 3, 6, 9]) If `condition` is boolean: >>> arr[condition] array([0, 3, 6, 9]) """ return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) def place(arr, mask, vals): """ Change elements of an array based on conditional and input values. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `copyto` uses the elements where `mask` is True. Note that `extract` does the exact opposite of `place`. Parameters ---------- arr : ndarray Array to put data into. mask : array_like Boolean mask array. Must have the same size as `a`. vals : 1-D sequence Values to put into `a`. Only the first N elements are used, where N is the number of True values in `mask`. If `vals` is smaller than N it will be repeated. See Also -------- copyto, put, take, extract Examples -------- >>> arr = np.arange(6).reshape(2, 3) >>> np.place(arr, arr>2, [44, 55]) >>> arr array([[ 0, 1, 2], [44, 55, 44]]) """ if not isinstance(arr, np.ndarray): raise TypeError("argument 1 must be numpy.ndarray, " "not {name}".format(name=type(arr).__name__)) return _insert(arr, mask, vals) def disp(mesg, device=None, linefeed=True): """ Display a message on a device. Parameters ---------- mesg : str Message to display. device : object Device to write message. If None, defaults to ``sys.stdout`` which is very similar to ``print``. `device` needs to have ``write()`` and ``flush()`` methods. linefeed : bool, optional Option whether to print a line feed or not. Defaults to True. Raises ------ AttributeError If `device` does not have a ``write()`` or ``flush()`` method. Examples -------- Besides ``sys.stdout``, a file-like object can also be used as it has both required methods: >>> from StringIO import StringIO >>> buf = StringIO() >>> np.disp('"Display" in a file', device=buf) >>> buf.getvalue() '"Display" in a file\\n' """ if device is None: device = sys.stdout if linefeed: device.write('%s\n' % mesg) else: device.write('%s' % mesg) device.flush() return class vectorize(object): """ vectorize(pyfunc, otypes='', doc=None, excluded=None, cache=False) Generalized function class. Define a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns a numpy array as output. The vectorized function evaluates `pyfunc` over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy. The data type of the output of `vectorized` is determined by calling the function with the first element of the input. This can be avoided by specifying the `otypes` argument. Parameters ---------- pyfunc : callable A python function or method. otypes : str or list of dtypes, optional The output data type. It must be specified as either a string of typecode characters or a list of data type specifiers. There should be one data type specifier for each output. doc : str, optional The docstring for the function. If `None`, the docstring will be the ``pyfunc.__doc__``. excluded : set, optional Set of strings or integers representing the positional or keyword arguments for which the function will not be vectorized. These will be passed directly to `pyfunc` unmodified. .. versionadded:: 1.7.0 cache : bool, optional If `True`, then cache the first function call that determines the number of outputs if `otypes` is not provided. .. versionadded:: 1.7.0 Returns ------- vectorized : callable Vectorized function. Examples -------- >>> def myfunc(a, b): ... "Return a-b if a>b, otherwise return a+b" ... if a > b: ... return a - b ... else: ... return a + b >>> vfunc = np.vectorize(myfunc) >>> vfunc([1, 2, 3, 4], 2) array([3, 4, 1, 2]) The docstring is taken from the input function to `vectorize` unless it is specified >>> vfunc.__doc__ 'Return a-b if a>b, otherwise return a+b' >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`') >>> vfunc.__doc__ 'Vectorized `myfunc`' The output type is determined by evaluating the first element of the input, unless it is specified >>> out = vfunc([1, 2, 3, 4], 2) >>> type(out[0]) <type 'numpy.int32'> >>> vfunc = np.vectorize(myfunc, otypes=[np.float]) >>> out = vfunc([1, 2, 3, 4], 2) >>> type(out[0]) <type 'numpy.float64'> The `excluded` argument can be used to prevent vectorizing over certain arguments. This can be useful for array-like arguments of a fixed length such as the coefficients for a polynomial as in `polyval`: >>> def mypolyval(p, x): ... _p = list(p) ... res = _p.pop(0) ... while _p: ... res = res*x + _p.pop(0) ... return res >>> vpolyval = np.vectorize(mypolyval, excluded=['p']) >>> vpolyval(p=[1, 2, 3], x=[0, 1]) array([3, 6]) Positional arguments may also be excluded by specifying their position: >>> vpolyval.excluded.add(0) >>> vpolyval([1, 2, 3], x=[0, 1]) array([3, 6]) Notes ----- The `vectorize` function is provided primarily for convenience, not for performance. The implementation is essentially a for loop. If `otypes` is not specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if `cache` is `True` to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive. The new keyword argument interface and `excluded` argument support further degrades performance. """ def __init__(self, pyfunc, otypes='', doc=None, excluded=None, cache=False): self.pyfunc = pyfunc self.cache = cache self._ufunc = None # Caching to improve default performance if doc is None: self.__doc__ = pyfunc.__doc__ else: self.__doc__ = doc if isinstance(otypes, str): self.otypes = otypes for char in self.otypes: if char not in typecodes['All']: raise ValueError( "Invalid otype specified: %s" % (char,)) elif iterable(otypes): self.otypes = ''.join([_nx.dtype(x).char for x in otypes]) else: raise ValueError( "Invalid otype specification") # Excluded variable support if excluded is None: excluded = set() self.excluded = set(excluded) def __call__(self, *args, **kwargs): """ Return arrays with the results of `pyfunc` broadcast (vectorized) over `args` and `kwargs` not in `excluded`. """ excluded = self.excluded if not kwargs and not excluded: func = self.pyfunc vargs = args else: # The wrapper accepts only positional arguments: we use `names` and # `inds` to mutate `the_args` and `kwargs` to pass to the original # function. nargs = len(args) names = [_n for _n in kwargs if _n not in excluded] inds = [_i for _i in range(nargs) if _i not in excluded] the_args = list(args) def func(*vargs): for _n, _i in enumerate(inds): the_args[_i] = vargs[_n] kwargs.update(zip(names, vargs[len(inds):])) return self.pyfunc(*the_args, **kwargs) vargs = [args[_i] for _i in inds] vargs.extend([kwargs[_n] for _n in names]) return self._vectorize_call(func=func, args=vargs) def _get_ufunc_and_otypes(self, func, args): """Return (ufunc, otypes).""" # frompyfunc will fail if args is empty if not args: raise ValueError('args can not be empty') if self.otypes: otypes = self.otypes nout = len(otypes) # Note logic here: We only *use* self._ufunc if func is self.pyfunc # even though we set self._ufunc regardless. if func is self.pyfunc and self._ufunc is not None: ufunc = self._ufunc else: ufunc = self._ufunc = frompyfunc(func, len(args), nout) else: # Get number of outputs and output types by calling the function on # the first entries of args. We also cache the result to prevent # the subsequent call when the ufunc is evaluated. # Assumes that ufunc first evaluates the 0th elements in the input # arrays (the input values are not checked to ensure this) inputs = [asarray(_a).flat[0] for _a in args] outputs = func(*inputs) # Performance note: profiling indicates that -- for simple # functions at least -- this wrapping can almost double the # execution time. # Hence we make it optional. if self.cache: _cache = [outputs] def _func(*vargs): if _cache: return _cache.pop() else: return func(*vargs) else: _func = func if isinstance(outputs, tuple): nout = len(outputs) else: nout = 1 outputs = (outputs,) otypes = ''.join([asarray(outputs[_k]).dtype.char for _k in range(nout)]) # Performance note: profiling indicates that creating the ufunc is # not a significant cost compared with wrapping so it seems not # worth trying to cache this. ufunc = frompyfunc(_func, len(args), nout) return ufunc, otypes def _vectorize_call(self, func, args): """Vectorized call to `func` over positional `args`.""" if not args: _res = func() else: ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args) # Convert args to object arrays first inputs = [array(_a, copy=False, subok=True, dtype=object) for _a in args] outputs = ufunc(*inputs) if ufunc.nout == 1: _res = array(outputs, copy=False, subok=True, dtype=otypes[0]) else: _res = tuple([array(_x, copy=False, subok=True, dtype=_t) for _x, _t in zip(outputs, otypes)]) return _res def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None): """ Estimate a covariance matrix, given data and weights. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, then the covariance matrix element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance of :math:`x_i`. See the notes for an outline of the algorithm. Parameters ---------- m : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `m` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. y : array_like, optional An additional set of variables and observations. `y` has the same form as that of `m`. rowvar : bool, optional If `rowvar` is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias : bool, optional Default normalization (False) is by ``(N - 1)``, where ``N`` is the number of observations given (unbiased estimate). If `bias` is True, then normalization is by ``N``. These values can be overridden by using the keyword ``ddof`` in numpy versions >= 1.5. ddof : int, optional If not ``None`` the default value implied by `bias` is overridden. Note that ``ddof=1`` will return the unbiased estimate, even if both `fweights` and `aweights` are specified, and ``ddof=0`` will return the simple average. See the notes for the details. The default value is ``None``. .. versionadded:: 1.5 fweights : array_like, int, optional 1-D array of integer freguency weights; the number of times each observation vector should be repeated. .. versionadded:: 1.10 aweights : array_like, optional 1-D array of observation vector weights. These relative weights are typically large for observations considered "important" and smaller for observations considered less "important". If ``ddof=0`` the array of weights can be used to assign probabilities to observation vectors. .. versionadded:: 1.10 Returns ------- out : ndarray The covariance matrix of the variables. See Also -------- corrcoef : Normalized covariance matrix Notes ----- Assume that the observations are in the columns of the observation array `m` and let ``f = fweights`` and ``a = aweights`` for brevity. The steps to compute the weighted covariance are as follows:: >>> w = f * a >>> v1 = np.sum(w) >>> v2 = np.sum(w * a) >>> m -= np.sum(m * w, axis=1, keepdims=True) / v1 >>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2) Note that when ``a == 1``, the normalization factor ``v1 / (v1**2 - ddof * v2)`` goes over to ``1 / (np.sum(f) - ddof)`` as it should. Examples -------- Consider two variables, :math:`x_0` and :math:`x_1`, which correlate perfectly, but in opposite directions: >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T >>> x array([[0, 1, 2], [2, 1, 0]]) Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance matrix shows this clearly: >>> np.cov(x) array([[ 1., -1.], [-1., 1.]]) Note that element :math:`C_{0,1}`, which shows the correlation between :math:`x_0` and :math:`x_1`, is negative. Further, note how `x` and `y` are combined: >>> x = [-2.1, -1, 4.3] >>> y = [3, 1.1, 0.12] >>> X = np.vstack((x,y)) >>> print(np.cov(X)) [[ 11.71 -4.286 ] [ -4.286 2.14413333]] >>> print(np.cov(x, y)) [[ 11.71 -4.286 ] [ -4.286 2.14413333]] >>> print(np.cov(x)) 11.71 """ # Check inputs if ddof is not None and ddof != int(ddof): raise ValueError( "ddof must be integer") # Handles complex arrays too m = np.asarray(m) if y is None: dtype = np.result_type(m, np.float64) else: y = np.asarray(y) dtype = np.result_type(m, y, np.float64) X = array(m, ndmin=2, dtype=dtype) if rowvar == 0 and X.shape[0] != 1: X = X.T if X.shape[0] == 0: return np.array([]).reshape(0, 0) if y is not None: y = array(y, copy=False, ndmin=2, dtype=dtype) if rowvar == 0 and y.shape[0] != 1: y = y.T X = np.vstack((X, y)) if ddof is None: if bias == 0: ddof = 1 else: ddof = 0 # Get the product of frequencies and weights w = None if fweights is not None: fweights = np.asarray(fweights, dtype=np.float) if not np.all(fweights == np.around(fweights)): raise TypeError( "fweights must be integer") if fweights.ndim > 1: raise RuntimeError( "cannot handle multidimensional fweights") if fweights.shape[0] != X.shape[1]: raise RuntimeError( "incompatible numbers of samples and fweights") if any(fweights < 0): raise ValueError( "fweights cannot be negative") w = fweights if aweights is not None: aweights = np.asarray(aweights, dtype=np.float) if aweights.ndim > 1: raise RuntimeError( "cannot handle multidimensional aweights") if aweights.shape[0] != X.shape[1]: raise RuntimeError( "incompatible numbers of samples and aweights") if any(aweights < 0): raise ValueError( "aweights cannot be negative") if w is None: w = aweights else: w *= aweights avg, w_sum = average(X, axis=1, weights=w, returned=True) w_sum = w_sum[0] # Determine the normalization if w is None: fact = X.shape[1] - ddof elif ddof == 0: fact = w_sum elif aweights is None: fact = w_sum - ddof else: fact = w_sum - ddof*sum(w*aweights)/w_sum if fact <= 0: warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning) fact = 0.0 X -= avg[:, None] if w is None: X_T = X.T else: X_T = (X*w).T c = dot(X, X_T.conj()) c *= 1. / np.float64(fact) return c.squeeze() def corrcoef(x, y=None, rowvar=1, bias=np._NoValue, ddof=np._NoValue): """ Return Pearson product-moment correlation coefficients. Please refer to the documentation for `cov` for more detail. The relationship between the correlation coefficient matrix, `R`, and the covariance matrix, `C`, is .. math:: R_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} * C_{jj} } } The values of `R` are between -1 and 1, inclusive. Parameters ---------- x : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `x` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. y : array_like, optional An additional set of variables and observations. `y` has the same shape as `x`. rowvar : int, optional If `rowvar` is non-zero (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias : _NoValue, optional Has no effect, do not use. .. deprecated:: 1.10.0 ddof : _NoValue, optional Has no effect, do not use. .. deprecated:: 1.10.0 Returns ------- R : ndarray The correlation coefficient matrix of the variables. See Also -------- cov : Covariance matrix Notes ----- Due to floating point rounding the resulting array may not be Hermitian, the diagonal elements may not be 1, and the elements may not satisfy the inequality abs(a) <= 1. The real and imaginary parts are clipped to the interval [-1, 1] in an attempt to improve on that situation but is not much help in the complex case. This function accepts but discards arguments `bias` and `ddof`. This is for backwards compatibility with previous versions of this function. These arguments had no effect on the return values of the function and can be safely ignored in this and previous versions of numpy. """ if bias is not np._NoValue or ddof is not np._NoValue: # 2015-03-15, 1.10 warnings.warn('bias and ddof have no effect and are deprecated', DeprecationWarning) c = cov(x, y, rowvar) try: d = diag(c) except ValueError: # scalar covariance # nan if incorrect value (nan, inf, 0), 1 otherwise return c / c stddev = sqrt(d.real) c /= stddev[:, None] c /= stddev[None, :] # Clip real and imaginary parts to [-1, 1]. This does not guarantee # abs(a[i,j]) <= 1 for complex arrays, but is the best we can do without # excessive work. np.clip(c.real, -1, 1, out=c.real) if np.iscomplexobj(c): np.clip(c.imag, -1, 1, out=c.imag) return c def blackman(M): """ Return the Blackman window. The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : ndarray The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See Also -------- bartlett, hamming, hanning, kaiser Notes ----- The Blackman window is defined as .. math:: w(n) = 0.42 - 0.5 \\cos(2\\pi n/M) + 0.08 \\cos(4\\pi n/M) Most references to the Blackman window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. It is known as a "near optimal" tapering function, almost as good (by some measures) as the kaiser window. References ---------- Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471. Examples -------- >>> np.blackman(12) array([ -1.38777878e-17, 3.26064346e-02, 1.59903635e-01, 4.14397981e-01, 7.36045180e-01, 9.67046769e-01, 9.67046769e-01, 7.36045180e-01, 4.14397981e-01, 1.59903635e-01, 3.26064346e-02, -1.38777878e-17]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.blackman(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Blackman window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Blackman window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return 0.42 - 0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1)) def bartlett(M): """ Return the Bartlett window. The Bartlett window is very similar to a triangular window, except that the end points are at zero. It is often used in signal processing for tapering a signal, without generating too much ripple in the frequency domain. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : array The triangular window, with the maximum value normalized to one (the value one appears only if the number of samples is odd), with the first and last samples equal to zero. See Also -------- blackman, hamming, hanning, kaiser Notes ----- The Bartlett window is defined as .. math:: w(n) = \\frac{2}{M-1} \\left( \\frac{M-1}{2} - \\left|n - \\frac{M-1}{2}\\right| \\right) Most references to the Bartlett window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. Note that convolution with this window produces linear interpolation. It is also known as an apodization (which means"removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. The fourier transform of the Bartlett is the product of two sinc functions. Note the excellent discussion in Kanasewich. References ---------- .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra", Biometrika 37, 1-16, 1950. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 109-110. .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal Processing", Prentice-Hall, 1999, pp. 468-471. .. [4] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 429. Examples -------- >>> np.bartlett(12) array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273, 0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636, 0.18181818, 0. ]) Plot the window and its frequency response (requires SciPy and matplotlib): >>> from numpy.fft import fft, fftshift >>> window = np.bartlett(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Bartlett window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Bartlett window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return where(less_equal(n, (M-1)/2.0), 2.0*n/(M-1), 2.0 - 2.0*n/(M-1)) def hanning(M): """ Return the Hanning window. The Hanning window is a taper formed by using a weighted cosine. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : ndarray, shape(M,) The window, with the maximum value normalized to one (the value one appears only if `M` is odd). See Also -------- bartlett, blackman, hamming, kaiser Notes ----- The Hanning window is defined as .. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right) \\qquad 0 \\leq n \\leq M-1 The Hanning was named for Julius von Hann, an Austrian meteorologist. It is also known as the Cosine Bell. Some authors prefer that it be called a Hann window, to help avoid confusion with the very similar Hamming window. Most references to the Hanning window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 106-108. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 425. Examples -------- >>> np.hanning(12) array([ 0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037, 0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249, 0.07937323, 0. ]) Plot the window and its frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.hanning(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Hann window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of the Hann window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return 0.5 - 0.5*cos(2.0*pi*n/(M-1)) def hamming(M): """ Return the Hamming window. The Hamming window is a taper formed by using a weighted cosine. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : ndarray The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See Also -------- bartlett, blackman, hanning, kaiser Notes ----- The Hamming window is defined as .. math:: w(n) = 0.54 - 0.46cos\\left(\\frac{2\\pi{n}}{M-1}\\right) \\qquad 0 \\leq n \\leq M-1 The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and is described in Blackman and Tukey. It was recommended for smoothing the truncated autocovariance function in the time domain. Most references to the Hamming window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 109-110. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 425. Examples -------- >>> np.hamming(12) array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594, 0.98136677, 0.98136677, 0.84123594, 0.60546483, 0.34890909, 0.15302337, 0.08 ]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.hamming(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Hamming window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Hamming window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return 0.54 - 0.46*cos(2.0*pi*n/(M-1)) ## Code from cephes for i0 _i0A = [ -4.41534164647933937950E-18, 3.33079451882223809783E-17, -2.43127984654795469359E-16, 1.71539128555513303061E-15, -1.16853328779934516808E-14, 7.67618549860493561688E-14, -4.85644678311192946090E-13, 2.95505266312963983461E-12, -1.72682629144155570723E-11, 9.67580903537323691224E-11, -5.18979560163526290666E-10, 2.65982372468238665035E-9, -1.30002500998624804212E-8, 6.04699502254191894932E-8, -2.67079385394061173391E-7, 1.11738753912010371815E-6, -4.41673835845875056359E-6, 1.64484480707288970893E-5, -5.75419501008210370398E-5, 1.88502885095841655729E-4, -5.76375574538582365885E-4, 1.63947561694133579842E-3, -4.32430999505057594430E-3, 1.05464603945949983183E-2, -2.37374148058994688156E-2, 4.93052842396707084878E-2, -9.49010970480476444210E-2, 1.71620901522208775349E-1, -3.04682672343198398683E-1, 6.76795274409476084995E-1 ] _i0B = [ -7.23318048787475395456E-18, -4.83050448594418207126E-18, 4.46562142029675999901E-17, 3.46122286769746109310E-17, -2.82762398051658348494E-16, -3.42548561967721913462E-16, 1.77256013305652638360E-15, 3.81168066935262242075E-15, -9.55484669882830764870E-15, -4.15056934728722208663E-14, 1.54008621752140982691E-14, 3.85277838274214270114E-13, 7.18012445138366623367E-13, -1.79417853150680611778E-12, -1.32158118404477131188E-11, -3.14991652796324136454E-11, 1.18891471078464383424E-11, 4.94060238822496958910E-10, 3.39623202570838634515E-9, 2.26666899049817806459E-8, 2.04891858946906374183E-7, 2.89137052083475648297E-6, 6.88975834691682398426E-5, 3.36911647825569408990E-3, 8.04490411014108831608E-1 ] def _chbevl(x, vals): b0 = vals[0] b1 = 0.0 for i in range(1, len(vals)): b2 = b1 b1 = b0 b0 = x*b1 - b2 + vals[i] return 0.5*(b0 - b2) def _i0_1(x): return exp(x) * _chbevl(x/2.0-2, _i0A) def _i0_2(x): return exp(x) * _chbevl(32.0/x - 2.0, _i0B) / sqrt(x) def i0(x): """ Modified Bessel function of the first kind, order 0. Usually denoted :math:`I_0`. This function does broadcast, but will *not* "up-cast" int dtype arguments unless accompanied by at least one float or complex dtype argument (see Raises below). Parameters ---------- x : array_like, dtype float or complex Argument of the Bessel function. Returns ------- out : ndarray, shape = x.shape, dtype = x.dtype The modified Bessel function evaluated at each of the elements of `x`. Raises ------ TypeError: array cannot be safely cast to required type If argument consists exclusively of int dtypes. See Also -------- scipy.special.iv, scipy.special.ive Notes ----- We use the algorithm published by Clenshaw [1]_ and referenced by Abramowitz and Stegun [2]_, for which the function domain is partitioned into the two intervals [0,8] and (8,inf), and Chebyshev polynomial expansions are employed in each interval. Relative error on the domain [0,30] using IEEE arithmetic is documented [3]_ as having a peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000). References ---------- .. [1] C. W. Clenshaw, "Chebyshev series for mathematical functions", in *National Physical Laboratory Mathematical Tables*, vol. 5, London: Her Majesty's Stationery Office, 1962. .. [2] M. Abramowitz and I. A. Stegun, *Handbook of Mathematical Functions*, 10th printing, New York: Dover, 1964, pp. 379. http://www.math.sfu.ca/~cbm/aands/page_379.htm .. [3] http://kobesearch.cpan.org/htdocs/Math-Cephes/Math/Cephes.html Examples -------- >>> np.i0([0.]) array(1.0) >>> np.i0([0., 1. + 2j]) array([ 1.00000000+0.j , 0.18785373+0.64616944j]) """ x = atleast_1d(x).copy() y = empty_like(x) ind = (x < 0) x[ind] = -x[ind] ind = (x <= 8.0) y[ind] = _i0_1(x[ind]) ind2 = ~ind y[ind2] = _i0_2(x[ind2]) return y.squeeze() ## End of cephes code for i0 def kaiser(M, beta): """ Return the Kaiser window. The Kaiser window is a taper formed by using a Bessel function. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. beta : float Shape parameter for window. Returns ------- out : array The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See Also -------- bartlett, blackman, hamming, hanning Notes ----- The Kaiser window is defined as .. math:: w(n) = I_0\\left( \\beta \\sqrt{1-\\frac{4n^2}{(M-1)^2}} \\right)/I_0(\\beta) with .. math:: \\quad -\\frac{M-1}{2} \\leq n \\leq \\frac{M-1}{2}, where :math:`I_0` is the modified zeroth-order Bessel function. The Kaiser was named for Jim Kaiser, who discovered a simple approximation to the DPSS window based on Bessel functions. The Kaiser window is a very good approximation to the Digital Prolate Spheroidal Sequence, or Slepian window, which is the transform which maximizes the energy in the main lobe of the window relative to total energy. The Kaiser can approximate many other windows by varying the beta parameter. ==== ======================= beta Window shape ==== ======================= 0 Rectangular 5 Similar to a Hamming 6 Similar to a Hanning 8.6 Similar to a Blackman ==== ======================= A beta value of 14 is probably a good starting point. Note that as beta gets large, the window narrows, and so the number of samples needs to be large enough to sample the increasingly narrow spike, otherwise NaNs will get returned. Most references to the Kaiser window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. John Wiley and Sons, New York, (1966). .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 177-178. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function Examples -------- >>> np.kaiser(12, 14) array([ 7.72686684e-06, 3.46009194e-03, 4.65200189e-02, 2.29737120e-01, 5.99885316e-01, 9.45674898e-01, 9.45674898e-01, 5.99885316e-01, 2.29737120e-01, 4.65200189e-02, 3.46009194e-03, 7.72686684e-06]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.kaiser(51, 14) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Kaiser window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Sample") <matplotlib.text.Text object at 0x...> >>> plt.show() >>> plt.figure() <matplotlib.figure.Figure object at 0x...> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Kaiser window") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Magnitude [dB]") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("Normalized frequency [cycles per sample]") <matplotlib.text.Text object at 0x...> >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ from numpy.dual import i0 if M == 1: return np.array([1.]) n = arange(0, M) alpha = (M-1)/2.0 return i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/i0(float(beta)) def sinc(x): """ Return the sinc function. The sinc function is :math:`\\sin(\\pi x)/(\\pi x)`. Parameters ---------- x : ndarray Array (possibly multi-dimensional) of values for which to to calculate ``sinc(x)``. Returns ------- out : ndarray ``sinc(x)``, which has the same shape as the input. Notes ----- ``sinc(0)`` is the limit value 1. The name sinc is short for "sine cardinal" or "sinus cardinalis". The sinc function is used in various signal processing applications, including in anti-aliasing, in the construction of a Lanczos resampling filter, and in interpolation. For bandlimited interpolation of discrete-time signals, the ideal interpolation kernel is proportional to the sinc function. References ---------- .. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/SincFunction.html .. [2] Wikipedia, "Sinc function", http://en.wikipedia.org/wiki/Sinc_function Examples -------- >>> x = np.linspace(-4, 4, 41) >>> np.sinc(x) array([ -3.89804309e-17, -4.92362781e-02, -8.40918587e-02, -8.90384387e-02, -5.84680802e-02, 3.89804309e-17, 6.68206631e-02, 1.16434881e-01, 1.26137788e-01, 8.50444803e-02, -3.89804309e-17, -1.03943254e-01, -1.89206682e-01, -2.16236208e-01, -1.55914881e-01, 3.89804309e-17, 2.33872321e-01, 5.04551152e-01, 7.56826729e-01, 9.35489284e-01, 1.00000000e+00, 9.35489284e-01, 7.56826729e-01, 5.04551152e-01, 2.33872321e-01, 3.89804309e-17, -1.55914881e-01, -2.16236208e-01, -1.89206682e-01, -1.03943254e-01, -3.89804309e-17, 8.50444803e-02, 1.26137788e-01, 1.16434881e-01, 6.68206631e-02, 3.89804309e-17, -5.84680802e-02, -8.90384387e-02, -8.40918587e-02, -4.92362781e-02, -3.89804309e-17]) >>> plt.plot(x, np.sinc(x)) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Sinc Function") <matplotlib.text.Text object at 0x...> >>> plt.ylabel("Amplitude") <matplotlib.text.Text object at 0x...> >>> plt.xlabel("X") <matplotlib.text.Text object at 0x...> >>> plt.show() It works in 2-D as well: >>> x = np.linspace(-4, 4, 401) >>> xx = np.outer(x, x) >>> plt.imshow(np.sinc(xx)) <matplotlib.image.AxesImage object at 0x...> """ x = np.asanyarray(x) y = pi * where(x == 0, 1.0e-20, x) return sin(y)/y def msort(a): """ Return a copy of an array sorted along the first axis. Parameters ---------- a : array_like Array to be sorted. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- sort Notes ----- ``np.msort(a)`` is equivalent to ``np.sort(a, axis=0)``. """ b = array(a, subok=True, copy=True) b.sort(0) return b def _ureduce(a, func, **kwargs): """ Internal Function. Call `func` with `a` as first argument swapping the axes to use extended axis on functions that don't support it natively. Returns result and a.shape with axis dims set to 1. Parameters ---------- a : array_like Input array or object that can be converted to an array. func : callable Reduction function Kapable of receiving an axis argument. It is is called with `a` as first argument followed by `kwargs`. kwargs : keyword arguments additional keyword arguments to pass to `func`. Returns ------- result : tuple Result of func(a, **kwargs) and a.shape with axis dims set to 1 which can be used to reshape the result to the same shape a ufunc with keepdims=True would produce. """ a = np.asanyarray(a) axis = kwargs.get('axis', None) if axis is not None: keepdim = list(a.shape) nd = a.ndim try: axis = operator.index(axis) if axis >= nd or axis < -nd: raise IndexError("axis %d out of bounds (%d)" % (axis, a.ndim)) keepdim[axis] = 1 except TypeError: sax = set() for x in axis: if x >= nd or x < -nd: raise IndexError("axis %d out of bounds (%d)" % (x, nd)) if x in sax: raise ValueError("duplicate value in axis") sax.add(x % nd) keepdim[x] = 1 keep = sax.symmetric_difference(frozenset(range(nd))) nkeep = len(keep) # swap axis that should not be reduced to front for i, s in enumerate(sorted(keep)): a = a.swapaxes(i, s) # merge reduced axis a = a.reshape(a.shape[:nkeep] + (-1,)) kwargs['axis'] = -1 else: keepdim = [1] * a.ndim r = func(a, **kwargs) return r, keepdim def median(a, axis=None, out=None, overwrite_input=False, keepdims=False): """ Compute the median along the specified axis. Returns the median of the array elements. Parameters ---------- a : array_like Input array or object that can be converted to an array. axis : {int, sequence of int, None}, optional Axis or axes along which the medians are computed. The default is to compute the median along a flattened version of the array. A sequence of axes is supported since version 1.9.0. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary. overwrite_input : bool, optional If True, then allow use of memory of input array `a` for calculations. The input array will be modified by the call to `median`. This will save memory when you do not need to preserve the contents of the input array. Treat the input as undefined, but it will probably be fully or partially sorted. Default is False. If `overwrite_input` is ``True`` and `a` is not already an `ndarray`, an error will be raised. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. .. versionadded:: 1.9.0 Returns ------- median : ndarray A new array holding the result. If the input contains integers or floats smaller than ``float64``, then the output data-type is ``np.float64``. Otherwise, the data-type of the output is the same as that of the input. If `out` is specified, that array is returned instead. See Also -------- mean, percentile Notes ----- Given a vector ``V`` of length ``N``, the median of ``V`` is the middle value of a sorted copy of ``V``, ``V_sorted`` - i e., ``V_sorted[(N-1)/2]``, when ``N`` is odd, and the average of the two middle values of ``V_sorted`` when ``N`` is even. Examples -------- >>> a = np.array([[10, 7, 4], [3, 2, 1]]) >>> a array([[10, 7, 4], [ 3, 2, 1]]) >>> np.median(a) 3.5 >>> np.median(a, axis=0) array([ 6.5, 4.5, 2.5]) >>> np.median(a, axis=1) array([ 7., 2.]) >>> m = np.median(a, axis=0) >>> out = np.zeros_like(m) >>> np.median(a, axis=0, out=m) array([ 6.5, 4.5, 2.5]) >>> m array([ 6.5, 4.5, 2.5]) >>> b = a.copy() >>> np.median(b, axis=1, overwrite_input=True) array([ 7., 2.]) >>> assert not np.all(a==b) >>> b = a.copy() >>> np.median(b, axis=None, overwrite_input=True) 3.5 >>> assert not np.all(a==b) """ r, k = _ureduce(a, func=_median, axis=axis, out=out, overwrite_input=overwrite_input) if keepdims: return r.reshape(k) else: return r def _median(a, axis=None, out=None, overwrite_input=False): # can't be reasonably be implemented in terms of percentile as we have to # call mean to not break astropy a = np.asanyarray(a) # Set the partition indexes if axis is None: sz = a.size else: sz = a.shape[axis] if sz % 2 == 0: szh = sz // 2 kth = [szh - 1, szh] else: kth = [(sz - 1) // 2] # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact): kth.append(-1) if overwrite_input: if axis is None: part = a.ravel() part.partition(kth) else: a.partition(kth, axis=axis) part = a else: part = partition(a, kth, axis=axis) if part.shape == (): # make 0-D arrays work return part.item() if axis is None: axis = 0 indexer = [slice(None)] * part.ndim index = part.shape[axis] // 2 if part.shape[axis] % 2 == 1: # index with slice to allow mean (below) to work indexer[axis] = slice(index, index+1) else: indexer[axis] = slice(index-1, index+1) # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact) and sz > 0: # warn and return nans like mean would rout = mean(part[indexer], axis=axis, out=out) part = np.rollaxis(part, axis, part.ndim) n = np.isnan(part[..., -1]) if rout.ndim == 0: if n == True: warnings.warn("Invalid value encountered in median", RuntimeWarning) if out is not None: out[...] = a.dtype.type(np.nan) rout = out else: rout = a.dtype.type(np.nan) elif np.count_nonzero(n.ravel()) > 0: warnings.warn("Invalid value encountered in median for" + " %d results" % np.count_nonzero(n.ravel()), RuntimeWarning) rout[n] = np.nan return rout else: # if there are no nans # Use mean in odd and even case to coerce data type # and check, use out array. return mean(part[indexer], axis=axis, out=out) def percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False): """ Compute the qth percentile of the data along the specified axis. Returns the qth percentile(s) of the array elements. Parameters ---------- a : array_like Input array or object that can be converted to an array. q : float in range of [0,100] (or sequence of floats) Percentile to compute, which must be between 0 and 100 inclusive. axis : {int, sequence of int, None}, optional Axis or axes along which the percentiles are computed. The default is to compute the percentile(s) along a flattened version of the array. A sequence of axes is supported since version 1.9.0. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary. overwrite_input : bool, optional If True, then allow use of memory of input array `a` calculations. The input array will be modified by the call to `percentile`. This will save memory when you do not need to preserve the contents of the input array. In this case you should not make any assumptions about the contents of the input `a` after this function completes -- treat it as undefined. Default is False. If `a` is not already an array, this parameter will have no effect as `a` will be converted to an array internally regardless of the value of this parameter. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} This optional parameter specifies the interpolation method to use when the desired quantile lies between two data points ``i < j``: * linear: ``i + (j - i) * fraction``, where ``fraction`` is the fractional part of the index surrounded by ``i`` and ``j``. * lower: ``i``. * higher: ``j``. * nearest: ``i`` or ``j``, whichever is nearest. * midpoint: ``(i + j) / 2``. .. versionadded:: 1.9.0 keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array `a`. .. versionadded:: 1.9.0 Returns ------- percentile : scalar or ndarray If `q` is a single percentile and `axis=None`, then the result is a scalar. If multiple percentiles are given, first axis of the result corresponds to the percentiles. The other axes are the axes that remain after the reduction of `a`. If the input contains integers or floats smaller than ``float64``, the output data-type is ``float64``. Otherwise, the output data-type is the same as that of the input. If `out` is specified, that array is returned instead. See Also -------- mean, median, nanpercentile Notes ----- Given a vector ``V`` of length ``N``, the ``q``-th percentile of ``V`` is the value ``q/100`` of the way from the mimumum to the maximum in in a sorted copy of ``V``. The values and distances of the two nearest neighbors as well as the `interpolation` parameter will determine the percentile if the normalized ranking does not match the location of ``q`` exactly. This function is the same as the median if ``q=50``, the same as the minimum if ``q=0`` and the same as the maximum if ``q=100``. Examples -------- >>> a = np.array([[10, 7, 4], [3, 2, 1]]) >>> a array([[10, 7, 4], [ 3, 2, 1]]) >>> np.percentile(a, 50) 3.5 >>> np.percentile(a, 50, axis=0) array([[ 6.5, 4.5, 2.5]]) >>> np.percentile(a, 50, axis=1) array([ 7., 2.]) >>> np.percentile(a, 50, axis=1, keepdims=True) array([[ 7.], [ 2.]]) >>> m = np.percentile(a, 50, axis=0) >>> out = np.zeros_like(m) >>> np.percentile(a, 50, axis=0, out=out) array([[ 6.5, 4.5, 2.5]]) >>> m array([[ 6.5, 4.5, 2.5]]) >>> b = a.copy() >>> np.percentile(b, 50, axis=1, overwrite_input=True) array([ 7., 2.]) >>> assert not np.all(a == b) """ q = array(q, dtype=np.float64, copy=True) r, k = _ureduce(a, func=_percentile, q=q, axis=axis, out=out, overwrite_input=overwrite_input, interpolation=interpolation) if keepdims: if q.ndim == 0: return r.reshape(k) else: return r.reshape([len(q)] + k) else: return r def _percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False): a = asarray(a) if q.ndim == 0: # Do not allow 0-d arrays because following code fails for scalar zerod = True q = q[None] else: zerod = False # avoid expensive reductions, relevant for arrays with < O(1000) elements if q.size < 10: for i in range(q.size): if q[i] < 0. or q[i] > 100.: raise ValueError("Percentiles must be in the range [0,100]") q[i] /= 100. else: # faster than any() if np.count_nonzero(q < 0.) or np.count_nonzero(q > 100.): raise ValueError("Percentiles must be in the range [0,100]") q /= 100. # prepare a for partioning if overwrite_input: if axis is None: ap = a.ravel() else: ap = a else: if axis is None: ap = a.flatten() else: ap = a.copy() if axis is None: axis = 0 Nx = ap.shape[axis] indices = q * (Nx - 1) # round fractional indices according to interpolation method if interpolation == 'lower': indices = floor(indices).astype(intp) elif interpolation == 'higher': indices = ceil(indices).astype(intp) elif interpolation == 'midpoint': indices = 0.5 * (floor(indices) + ceil(indices)) elif interpolation == 'nearest': indices = around(indices).astype(intp) elif interpolation == 'linear': pass # keep index as fraction and interpolate else: raise ValueError( "interpolation can only be 'linear', 'lower' 'higher', " "'midpoint', or 'nearest'") n = np.array(False, dtype=bool) # check for nan's flag if indices.dtype == intp: # take the points along axis # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact): indices = concatenate((indices, [-1])) ap.partition(indices, axis=axis) # ensure axis with qth is first ap = np.rollaxis(ap, axis, 0) axis = 0 # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact): indices = indices[:-1] n = np.isnan(ap[-1:, ...]) if zerod: indices = indices[0] r = take(ap, indices, axis=axis, out=out) else: # weight the points above and below the indices indices_below = floor(indices).astype(intp) indices_above = indices_below + 1 indices_above[indices_above > Nx - 1] = Nx - 1 # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact): indices_above = concatenate((indices_above, [-1])) weights_above = indices - indices_below weights_below = 1.0 - weights_above weights_shape = [1, ] * ap.ndim weights_shape[axis] = len(indices) weights_below.shape = weights_shape weights_above.shape = weights_shape ap.partition(concatenate((indices_below, indices_above)), axis=axis) # ensure axis with qth is first ap = np.rollaxis(ap, axis, 0) weights_below = np.rollaxis(weights_below, axis, 0) weights_above = np.rollaxis(weights_above, axis, 0) axis = 0 # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact): indices_above = indices_above[:-1] n = np.isnan(ap[-1:, ...]) x1 = take(ap, indices_below, axis=axis) * weights_below x2 = take(ap, indices_above, axis=axis) * weights_above # ensure axis with qth is first x1 = np.rollaxis(x1, axis, 0) x2 = np.rollaxis(x2, axis, 0) if zerod: x1 = x1.squeeze(0) x2 = x2.squeeze(0) if out is not None: r = add(x1, x2, out=out) else: r = add(x1, x2) if np.any(n): warnings.warn("Invalid value encountered in percentile", RuntimeWarning) if zerod: if ap.ndim == 1: if out is not None: out[...] = a.dtype.type(np.nan) r = out else: r = a.dtype.type(np.nan) else: r[..., n.squeeze(0)] = a.dtype.type(np.nan) else: if r.ndim == 1: r[:] = a.dtype.type(np.nan) else: r[..., n.repeat(q.size, 0)] = a.dtype.type(np.nan) return r def trapz(y, x=None, dx=1.0, axis=-1): """ Integrate along the given axis using the composite trapezoidal rule. Integrate `y` (`x`) along given axis. Parameters ---------- y : array_like Input array to integrate. x : array_like, optional The sample points corresponding to the `y` values. If `x` is None, the sample points are assumed to be evenly spaced `dx` apart. The default is None. dx : scalar, optional The spacing between sample points when `x` is None. The default is 1. axis : int, optional The axis along which to integrate. Returns ------- trapz : float Definite integral as approximated by trapezoidal rule. See Also -------- sum, cumsum Notes ----- Image [2]_ illustrates trapezoidal rule -- y-axis locations of points will be taken from `y` array, by default x-axis distances between points will be 1.0, alternatively they can be provided with `x` array or with `dx` scalar. Return value will be equal to combined area under the red lines. References ---------- .. [1] Wikipedia page: http://en.wikipedia.org/wiki/Trapezoidal_rule .. [2] Illustration image: http://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png Examples -------- >>> np.trapz([1,2,3]) 4.0 >>> np.trapz([1,2,3], x=[4,6,8]) 8.0 >>> np.trapz([1,2,3], dx=2) 8.0 >>> a = np.arange(6).reshape(2, 3) >>> a array([[0, 1, 2], [3, 4, 5]]) >>> np.trapz(a, axis=0) array([ 1.5, 2.5, 3.5]) >>> np.trapz(a, axis=1) array([ 2., 8.]) """ y = asanyarray(y) if x is None: d = dx else: x = asanyarray(x) if x.ndim == 1: d = diff(x) # reshape to correct shape shape = [1]*y.ndim shape[axis] = d.shape[0] d = d.reshape(shape) else: d = diff(x, axis=axis) nd = len(y.shape) slice1 = [slice(None)]*nd slice2 = [slice(None)]*nd slice1[axis] = slice(1, None) slice2[axis] = slice(None, -1) try: ret = (d * (y[slice1] + y[slice2]) / 2.0).sum(axis) except ValueError: # Operations didn't work, cast to ndarray d = np.asarray(d) y = np.asarray(y) ret = add.reduce(d * (y[slice1]+y[slice2])/2.0, axis) return ret #always succeed def add_newdoc(place, obj, doc): """ Adds documentation to obj which is in module place. If doc is a string add it to obj as a docstring If doc is a tuple, then the first element is interpreted as an attribute of obj and the second as the docstring (method, docstring) If doc is a list, then each element of the list should be a sequence of length two --> [(method1, docstring1), (method2, docstring2), ...] This routine never raises an error. This routine cannot modify read-only docstrings, as appear in new-style classes or built-in functions. Because this routine never raises an error the caller must check manually that the docstrings were changed. """ try: new = getattr(__import__(place, globals(), {}, [obj]), obj) if isinstance(doc, str): add_docstring(new, doc.strip()) elif isinstance(doc, tuple): add_docstring(getattr(new, doc[0]), doc[1].strip()) elif isinstance(doc, list): for val in doc: add_docstring(getattr(new, val[0]), val[1].strip()) except: pass # Based on scitools meshgrid def meshgrid(*xi, **kwargs): """ Return coordinate matrices from coordinate vectors. Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn. .. versionchanged:: 1.9 1-D and 0-D cases are allowed. Parameters ---------- x1, x2,..., xn : array_like 1-D arrays representing the coordinates of a grid. indexing : {'xy', 'ij'}, optional Cartesian ('xy', default) or matrix ('ij') indexing of output. See Notes for more details. .. versionadded:: 1.7.0 sparse : bool, optional If True a sparse grid is returned in order to conserve memory. Default is False. .. versionadded:: 1.7.0 copy : bool, optional If False, a view into the original arrays are returned in order to conserve memory. Default is True. Please note that ``sparse=False, copy=False`` will likely return non-contiguous arrays. Furthermore, more than one element of a broadcast array may refer to a single memory location. If you need to write to the arrays, make copies first. .. versionadded:: 1.7.0 Returns ------- X1, X2,..., XN : ndarray For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` , return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij' or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy' with the elements of `xi` repeated to fill the matrix along the first dimension for `x1`, the second for `x2` and so on. Notes ----- This function supports both indexing conventions through the indexing keyword argument. Giving the string 'ij' returns a meshgrid with matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing. In the 2-D case with inputs of length M and N, the outputs are of shape (N, M) for 'xy' indexing and (M, N) for 'ij' indexing. In the 3-D case with inputs of length M, N and P, outputs are of shape (N, M, P) for 'xy' indexing and (M, N, P) for 'ij' indexing. The difference is illustrated by the following code snippet:: xv, yv = meshgrid(x, y, sparse=False, indexing='ij') for i in range(nx): for j in range(ny): # treat xv[i,j], yv[i,j] xv, yv = meshgrid(x, y, sparse=False, indexing='xy') for i in range(nx): for j in range(ny): # treat xv[j,i], yv[j,i] In the 1-D and 0-D case, the indexing and sparse keywords have no effect. See Also -------- index_tricks.mgrid : Construct a multi-dimensional "meshgrid" using indexing notation. index_tricks.ogrid : Construct an open multi-dimensional "meshgrid" using indexing notation. Examples -------- >>> nx, ny = (3, 2) >>> x = np.linspace(0, 1, nx) >>> y = np.linspace(0, 1, ny) >>> xv, yv = meshgrid(x, y) >>> xv array([[ 0. , 0.5, 1. ], [ 0. , 0.5, 1. ]]) >>> yv array([[ 0., 0., 0.], [ 1., 1., 1.]]) >>> xv, yv = meshgrid(x, y, sparse=True) # make sparse output arrays >>> xv array([[ 0. , 0.5, 1. ]]) >>> yv array([[ 0.], [ 1.]]) `meshgrid` is very useful to evaluate functions on a grid. >>> x = np.arange(-5, 5, 0.1) >>> y = np.arange(-5, 5, 0.1) >>> xx, yy = meshgrid(x, y, sparse=True) >>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2) >>> h = plt.contourf(x,y,z) """ ndim = len(xi) copy_ = kwargs.pop('copy', True) sparse = kwargs.pop('sparse', False) indexing = kwargs.pop('indexing', 'xy') if kwargs: raise TypeError("meshgrid() got an unexpected keyword argument '%s'" % (list(kwargs)[0],)) if indexing not in ['xy', 'ij']: raise ValueError( "Valid values for `indexing` are 'xy' and 'ij'.") s0 = (1,) * ndim output = [np.asanyarray(x).reshape(s0[:i] + (-1,) + s0[i + 1::]) for i, x in enumerate(xi)] shape = [x.size for x in output] if indexing == 'xy' and ndim > 1: # switch first and second axis output[0].shape = (1, -1) + (1,)*(ndim - 2) output[1].shape = (-1, 1) + (1,)*(ndim - 2) shape[0], shape[1] = shape[1], shape[0] if sparse: if copy_: return [x.copy() for x in output] else: return output else: # Return the full N-D matrix (not only the 1-D vector) if copy_: mult_fact = np.ones(shape, dtype=int) return [x * mult_fact for x in output] else: return np.broadcast_arrays(*output) def delete(arr, obj, axis=None): """ Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by `arr[obj]`. Parameters ---------- arr : array_like Input array. obj : slice, int or array of ints Indicate which sub-arrays to remove. axis : int, optional The axis along which to delete the subarray defined by `obj`. If `axis` is None, `obj` is applied to the flattened array. Returns ------- out : ndarray A copy of `arr` with the elements specified by `obj` removed. Note that `delete` does not occur in-place. If `axis` is None, `out` is a flattened array. See Also -------- insert : Insert elements into an array. append : Append elements at the end of an array. Notes ----- Often it is preferable to use a boolean mask. For example: >>> mask = np.ones(len(arr), dtype=bool) >>> mask[[0,2,4]] = False >>> result = arr[mask,...] Is equivalent to `np.delete(arr, [0,2,4], axis=0)`, but allows further use of `mask`. Examples -------- >>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) >>> arr array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) >>> np.delete(arr, 1, 0) array([[ 1, 2, 3, 4], [ 9, 10, 11, 12]]) >>> np.delete(arr, np.s_[::2], 1) array([[ 2, 4], [ 6, 8], [10, 12]]) >>> np.delete(arr, [1,3,5], None) array([ 1, 3, 5, 7, 8, 9, 10, 11, 12]) """ wrap = None if type(arr) is not ndarray: try: wrap = arr.__array_wrap__ except AttributeError: pass arr = asarray(arr) ndim = arr.ndim arrorder = 'F' if arr.flags.fnc else 'C' if axis is None: if ndim != 1: arr = arr.ravel() ndim = arr.ndim axis = ndim - 1 if ndim == 0: # 2013-09-24, 1.9 warnings.warn( "in the future the special handling of scalars will be removed " "from delete and raise an error", DeprecationWarning) if wrap: return wrap(arr) else: return arr.copy() slobj = [slice(None)]*ndim N = arr.shape[axis] newshape = list(arr.shape) if isinstance(obj, slice): start, stop, step = obj.indices(N) xr = range(start, stop, step) numtodel = len(xr) if numtodel <= 0: if wrap: return wrap(arr.copy()) else: return arr.copy() # Invert if step is negative: if step < 0: step = -step start = xr[-1] stop = xr[0] + 1 newshape[axis] -= numtodel new = empty(newshape, arr.dtype, arrorder) # copy initial chunk if start == 0: pass else: slobj[axis] = slice(None, start) new[slobj] = arr[slobj] # copy end chunck if stop == N: pass else: slobj[axis] = slice(stop-numtodel, None) slobj2 = [slice(None)]*ndim slobj2[axis] = slice(stop, None) new[slobj] = arr[slobj2] # copy middle pieces if step == 1: pass else: # use array indexing. keep = ones(stop-start, dtype=bool) keep[:stop-start:step] = False slobj[axis] = slice(start, stop-numtodel) slobj2 = [slice(None)]*ndim slobj2[axis] = slice(start, stop) arr = arr[slobj2] slobj2[axis] = keep new[slobj] = arr[slobj2] if wrap: return wrap(new) else: return new _obj = obj obj = np.asarray(obj) # After removing the special handling of booleans and out of # bounds values, the conversion to the array can be removed. if obj.dtype == bool: warnings.warn( "in the future insert will treat boolean arrays and array-likes " "as boolean index instead of casting it to integer", FutureWarning) obj = obj.astype(intp) if isinstance(_obj, (int, long, integer)): # optimization for a single value obj = obj.item() if (obj < -N or obj >= N): raise IndexError( "index %i is out of bounds for axis %i with " "size %i" % (obj, axis, N)) if (obj < 0): obj += N newshape[axis] -= 1 new = empty(newshape, arr.dtype, arrorder) slobj[axis] = slice(None, obj) new[slobj] = arr[slobj] slobj[axis] = slice(obj, None) slobj2 = [slice(None)]*ndim slobj2[axis] = slice(obj+1, None) new[slobj] = arr[slobj2] else: if obj.size == 0 and not isinstance(_obj, np.ndarray): obj = obj.astype(intp) if not np.can_cast(obj, intp, 'same_kind'): # obj.size = 1 special case always failed and would just # give superfluous warnings. # 2013-09-24, 1.9 warnings.warn( "using a non-integer array as obj in delete will result in an " "error in the future", DeprecationWarning) obj = obj.astype(intp) keep = ones(N, dtype=bool) # Test if there are out of bound indices, this is deprecated inside_bounds = (obj < N) & (obj >= -N) if not inside_bounds.all(): # 2013-09-24, 1.9 warnings.warn( "in the future out of bounds indices will raise an error " "instead of being ignored by `numpy.delete`.", DeprecationWarning) obj = obj[inside_bounds] positive_indices = obj >= 0 if not positive_indices.all(): warnings.warn( "in the future negative indices will not be ignored by " "`numpy.delete`.", FutureWarning) obj = obj[positive_indices] keep[obj, ] = False slobj[axis] = keep new = arr[slobj] if wrap: return wrap(new) else: return new def insert(arr, obj, values, axis=None): """ Insert values along the given axis before the given indices. Parameters ---------- arr : array_like Input array. obj : int, slice or sequence of ints Object that defines the index or indices before which `values` is inserted. .. versionadded:: 1.8.0 Support for multiple insertions when `obj` is a single scalar or a sequence with one element (similar to calling insert multiple times). values : array_like Values to insert into `arr`. If the type of `values` is different from that of `arr`, `values` is converted to the type of `arr`. `values` should be shaped so that ``arr[...,obj,...] = values`` is legal. axis : int, optional Axis along which to insert `values`. If `axis` is None then `arr` is flattened first. Returns ------- out : ndarray A copy of `arr` with `values` inserted. Note that `insert` does not occur in-place: a new array is returned. If `axis` is None, `out` is a flattened array. See Also -------- append : Append elements at the end of an array. concatenate : Join a sequence of arrays along an existing axis. delete : Delete elements from an array. Notes ----- Note that for higher dimensional inserts `obj=0` behaves very different from `obj=[0]` just like `arr[:,0,:] = values` is different from `arr[:,[0],:] = values`. Examples -------- >>> a = np.array([[1, 1], [2, 2], [3, 3]]) >>> a array([[1, 1], [2, 2], [3, 3]]) >>> np.insert(a, 1, 5) array([1, 5, 1, 2, 2, 3, 3]) >>> np.insert(a, 1, 5, axis=1) array([[1, 5, 1], [2, 5, 2], [3, 5, 3]]) Difference between sequence and scalars: >>> np.insert(a, [1], [[1],[2],[3]], axis=1) array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) >>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1), ... np.insert(a, [1], [[1],[2],[3]], axis=1)) True >>> b = a.flatten() >>> b array([1, 1, 2, 2, 3, 3]) >>> np.insert(b, [2, 2], [5, 6]) array([1, 1, 5, 6, 2, 2, 3, 3]) >>> np.insert(b, slice(2, 4), [5, 6]) array([1, 1, 5, 2, 6, 2, 3, 3]) >>> np.insert(b, [2, 2], [7.13, False]) # type casting array([1, 1, 7, 0, 2, 2, 3, 3]) >>> x = np.arange(8).reshape(2, 4) >>> idx = (1, 3) >>> np.insert(x, idx, 999, axis=1) array([[ 0, 999, 1, 2, 999, 3], [ 4, 999, 5, 6, 999, 7]]) """ wrap = None if type(arr) is not ndarray: try: wrap = arr.__array_wrap__ except AttributeError: pass arr = asarray(arr) ndim = arr.ndim arrorder = 'F' if arr.flags.fnc else 'C' if axis is None: if ndim != 1: arr = arr.ravel() ndim = arr.ndim axis = ndim - 1 else: if ndim > 0 and (axis < -ndim or axis >= ndim): raise IndexError( "axis %i is out of bounds for an array of " "dimension %i" % (axis, ndim)) if (axis < 0): axis += ndim if (ndim == 0): # 2013-09-24, 1.9 warnings.warn( "in the future the special handling of scalars will be removed " "from insert and raise an error", DeprecationWarning) arr = arr.copy() arr[...] = values if wrap: return wrap(arr) else: return arr slobj = [slice(None)]*ndim N = arr.shape[axis] newshape = list(arr.shape) if isinstance(obj, slice): # turn it into a range object indices = arange(*obj.indices(N), **{'dtype': intp}) else: # need to copy obj, because indices will be changed in-place indices = np.array(obj) if indices.dtype == bool: # See also delete warnings.warn( "in the future insert will treat boolean arrays and " "array-likes as a boolean index instead of casting it to " "integer", FutureWarning) indices = indices.astype(intp) # Code after warning period: #if obj.ndim != 1: # raise ValueError('boolean array argument obj to insert ' # 'must be one dimensional') #indices = np.flatnonzero(obj) elif indices.ndim > 1: raise ValueError( "index array argument obj to insert must be one dimensional " "or scalar") if indices.size == 1: index = indices.item() if index < -N or index > N: raise IndexError( "index %i is out of bounds for axis %i with " "size %i" % (obj, axis, N)) if (index < 0): index += N # There are some object array corner cases here, but we cannot avoid # that: values = array(values, copy=False, ndmin=arr.ndim, dtype=arr.dtype) if indices.ndim == 0: # broadcasting is very different here, since a[:,0,:] = ... behaves # very different from a[:,[0],:] = ...! This changes values so that # it works likes the second case. (here a[:,0:1,:]) values = np.rollaxis(values, 0, (axis % values.ndim) + 1) numnew = values.shape[axis] newshape[axis] += numnew new = empty(newshape, arr.dtype, arrorder) slobj[axis] = slice(None, index) new[slobj] = arr[slobj] slobj[axis] = slice(index, index+numnew) new[slobj] = values slobj[axis] = slice(index+numnew, None) slobj2 = [slice(None)] * ndim slobj2[axis] = slice(index, None) new[slobj] = arr[slobj2] if wrap: return wrap(new) return new elif indices.size == 0 and not isinstance(obj, np.ndarray): # Can safely cast the empty list to intp indices = indices.astype(intp) if not np.can_cast(indices, intp, 'same_kind'): # 2013-09-24, 1.9 warnings.warn( "using a non-integer array as obj in insert will result in an " "error in the future", DeprecationWarning) indices = indices.astype(intp) indices[indices < 0] += N numnew = len(indices) order = indices.argsort(kind='mergesort') # stable sort indices[order] += np.arange(numnew) newshape[axis] += numnew old_mask = ones(newshape[axis], dtype=bool) old_mask[indices] = False new = empty(newshape, arr.dtype, arrorder) slobj2 = [slice(None)]*ndim slobj[axis] = indices slobj2[axis] = old_mask new[slobj] = values new[slobj2] = arr if wrap: return wrap(new) return new def append(arr, values, axis=None): """ Append values to the end of an array. Parameters ---------- arr : array_like Values are appended to a copy of this array. values : array_like These values are appended to a copy of `arr`. It must be of the correct shape (the same shape as `arr`, excluding `axis`). If `axis` is not specified, `values` can be any shape and will be flattened before use. axis : int, optional The axis along which `values` are appended. If `axis` is not given, both `arr` and `values` are flattened before use. Returns ------- append : ndarray A copy of `arr` with `values` appended to `axis`. Note that `append` does not occur in-place: a new array is allocated and filled. If `axis` is None, `out` is a flattened array. See Also -------- insert : Insert elements into an array. delete : Delete elements from an array. Examples -------- >>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]]) array([1, 2, 3, 4, 5, 6, 7, 8, 9]) When `axis` is specified, `values` must have the correct shape. >>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0) Traceback (most recent call last): ... ValueError: arrays must have same number of dimensions """ arr = asanyarray(arr) if axis is None: if arr.ndim != 1: arr = arr.ravel() values = ravel(values) axis = arr.ndim-1 return concatenate((arr, values), axis=axis)
mit
louispotok/pandas
pandas/tests/scalar/test_nat.py
3
10360
import pytest from datetime import datetime, timedelta import pytz import numpy as np from pandas import (NaT, Index, Timestamp, Timedelta, Period, DatetimeIndex, PeriodIndex, TimedeltaIndex, Series, isna) from pandas.util import testing as tm from pandas._libs.tslib import iNaT from pandas.compat import callable @pytest.mark.parametrize('nat, idx', [(Timestamp('NaT'), DatetimeIndex), (Timedelta('NaT'), TimedeltaIndex), (Period('NaT', freq='M'), PeriodIndex)]) def test_nat_fields(nat, idx): for field in idx._field_ops: # weekday is a property of DTI, but a method # on NaT/Timestamp for compat with datetime if field == 'weekday': continue result = getattr(NaT, field) assert np.isnan(result) result = getattr(nat, field) assert np.isnan(result) for field in idx._bool_ops: result = getattr(NaT, field) assert result is False result = getattr(nat, field) assert result is False def test_nat_vector_field_access(): idx = DatetimeIndex(['1/1/2000', None, None, '1/4/2000']) for field in DatetimeIndex._field_ops: # weekday is a property of DTI, but a method # on NaT/Timestamp for compat with datetime if field == 'weekday': continue result = getattr(idx, field) expected = Index([getattr(x, field) for x in idx]) tm.assert_index_equal(result, expected) s = Series(idx) for field in DatetimeIndex._field_ops: # weekday is a property of DTI, but a method # on NaT/Timestamp for compat with datetime if field == 'weekday': continue result = getattr(s.dt, field) expected = [getattr(x, field) for x in idx] tm.assert_series_equal(result, Series(expected)) for field in DatetimeIndex._bool_ops: result = getattr(s.dt, field) expected = [getattr(x, field) for x in idx] tm.assert_series_equal(result, Series(expected)) @pytest.mark.parametrize('klass', [Timestamp, Timedelta, Period]) def test_identity(klass): assert klass(None) is NaT result = klass(np.nan) assert result is NaT result = klass(None) assert result is NaT result = klass(iNaT) assert result is NaT result = klass(np.nan) assert result is NaT result = klass(float('nan')) assert result is NaT result = klass(NaT) assert result is NaT result = klass('NaT') assert result is NaT assert isna(klass('nat')) @pytest.mark.parametrize('klass', [Timestamp, Timedelta, Period]) def test_equality(klass): # nat if klass is not Period: klass('').value == iNaT klass('nat').value == iNaT klass('NAT').value == iNaT klass(None).value == iNaT klass(np.nan).value == iNaT assert isna(klass('nat')) @pytest.mark.parametrize('klass', [Timestamp, Timedelta]) def test_round_nat(klass): # GH14940 ts = klass('nat') for method in ["round", "floor", "ceil"]: round_method = getattr(ts, method) for freq in ["s", "5s", "min", "5min", "h", "5h"]: assert round_method(freq) is ts def test_NaT_methods(): # GH 9513 # GH 17329 for `timestamp` raise_methods = ['astimezone', 'combine', 'ctime', 'dst', 'fromordinal', 'fromtimestamp', 'isocalendar', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'toordinal', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'timestamp'] nat_methods = ['date', 'now', 'replace', 'to_datetime', 'today', 'tz_convert', 'tz_localize'] nan_methods = ['weekday', 'isoweekday'] for method in raise_methods: if hasattr(NaT, method): with pytest.raises(ValueError): getattr(NaT, method)() for method in nan_methods: if hasattr(NaT, method): assert np.isnan(getattr(NaT, method)()) for method in nat_methods: if hasattr(NaT, method): # see gh-8254 exp_warning = None if method == 'to_datetime': exp_warning = FutureWarning with tm.assert_produces_warning( exp_warning, check_stacklevel=False): assert getattr(NaT, method)() is NaT # GH 12300 assert NaT.isoformat() == 'NaT' def test_NaT_docstrings(): # GH#17327 nat_names = dir(NaT) # NaT should have *most* of the Timestamp methods, with matching # docstrings. The attributes that are not expected to be present in NaT # are private methods plus `ts_expected` below. ts_names = dir(Timestamp) ts_missing = [x for x in ts_names if x not in nat_names and not x.startswith('_')] ts_missing.sort() ts_expected = ['freqstr', 'normalize', 'to_julian_date', 'to_period', 'tz'] assert ts_missing == ts_expected ts_overlap = [x for x in nat_names if x in ts_names and not x.startswith('_') and callable(getattr(Timestamp, x))] for name in ts_overlap: tsdoc = getattr(Timestamp, name).__doc__ natdoc = getattr(NaT, name).__doc__ assert tsdoc == natdoc # NaT should have *most* of the Timedelta methods, with matching # docstrings. The attributes that are not expected to be present in NaT # are private methods plus `td_expected` below. # For methods that are both Timestamp and Timedelta methods, the # Timestamp docstring takes priority. td_names = dir(Timedelta) td_missing = [x for x in td_names if x not in nat_names and not x.startswith('_')] td_missing.sort() td_expected = ['components', 'delta', 'is_populated', 'to_pytimedelta', 'to_timedelta64', 'view'] assert td_missing == td_expected td_overlap = [x for x in nat_names if x in td_names and x not in ts_names and # Timestamp __doc__ takes priority not x.startswith('_') and callable(getattr(Timedelta, x))] assert td_overlap == ['total_seconds'] for name in td_overlap: tddoc = getattr(Timedelta, name).__doc__ natdoc = getattr(NaT, name).__doc__ assert tddoc == natdoc @pytest.mark.parametrize('klass', [Timestamp, Timedelta]) def test_isoformat(klass): result = klass('NaT').isoformat() expected = 'NaT' assert result == expected def test_nat_arithmetic(): # GH 6873 i = 2 f = 1.5 for (left, right) in [(NaT, i), (NaT, f), (NaT, np.nan)]: assert left / right is NaT assert left * right is NaT assert right * left is NaT with pytest.raises(TypeError): right / left # Timestamp / datetime t = Timestamp('2014-01-01') dt = datetime(2014, 1, 1) for (left, right) in [(NaT, NaT), (NaT, t), (NaT, dt)]: # NaT __add__ or __sub__ Timestamp-like (or inverse) returns NaT assert right + left is NaT assert left + right is NaT assert left - right is NaT assert right - left is NaT # timedelta-like # offsets are tested in test_offsets.py delta = timedelta(3600) td = Timedelta('5s') for (left, right) in [(NaT, delta), (NaT, td)]: # NaT + timedelta-like returns NaT assert right + left is NaT assert left + right is NaT assert right - left is NaT assert left - right is NaT assert np.isnan(left / right) assert np.isnan(right / left) # GH 11718 t_utc = Timestamp('2014-01-01', tz='UTC') t_tz = Timestamp('2014-01-01', tz='US/Eastern') dt_tz = pytz.timezone('Asia/Tokyo').localize(dt) for (left, right) in [(NaT, t_utc), (NaT, t_tz), (NaT, dt_tz)]: # NaT __add__ or __sub__ Timestamp-like (or inverse) returns NaT assert right + left is NaT assert left + right is NaT assert left - right is NaT assert right - left is NaT # int addition / subtraction for (left, right) in [(NaT, 2), (NaT, 0), (NaT, -3)]: assert right + left is NaT assert left + right is NaT assert left - right is NaT assert right - left is NaT def test_nat_rfloordiv_timedelta(): # GH#18846 # See also test_timedelta.TestTimedeltaArithmetic.test_floordiv 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_nat_arithmetic_index(): # GH 11718 dti = DatetimeIndex(['2011-01-01', '2011-01-02'], name='x') exp = DatetimeIndex([NaT, NaT], name='x') tm.assert_index_equal(dti + NaT, exp) tm.assert_index_equal(NaT + dti, exp) dti_tz = DatetimeIndex(['2011-01-01', '2011-01-02'], tz='US/Eastern', name='x') exp = DatetimeIndex([NaT, NaT], name='x', tz='US/Eastern') tm.assert_index_equal(dti_tz + NaT, exp) tm.assert_index_equal(NaT + dti_tz, exp) exp = TimedeltaIndex([NaT, NaT], name='x') for (left, right) in [(NaT, dti), (NaT, dti_tz)]: tm.assert_index_equal(left - right, exp) tm.assert_index_equal(right - left, exp) # timedelta # GH#19124 tdi = TimedeltaIndex(['1 day', '2 day'], name='x') tdi_nat = TimedeltaIndex([NaT, NaT], name='x') tm.assert_index_equal(tdi + NaT, tdi_nat) tm.assert_index_equal(NaT + tdi, tdi_nat) tm.assert_index_equal(tdi - NaT, tdi_nat) tm.assert_index_equal(NaT - tdi, tdi_nat) @pytest.mark.parametrize('box, assert_func', [ (TimedeltaIndex, tm.assert_index_equal), (Series, tm.assert_series_equal) ]) def test_nat_arithmetic_td64_vector(box, assert_func): # GH#19124 vec = box(['1 day', '2 day'], dtype='timedelta64[ns]') box_nat = box([NaT, NaT], dtype='timedelta64[ns]') assert_func(vec + NaT, box_nat) assert_func(NaT + vec, box_nat) assert_func(vec - NaT, box_nat) assert_func(NaT - vec, box_nat) def test_nat_pinned_docstrings(): # GH17327 assert NaT.ctime.__doc__ == datetime.ctime.__doc__
bsd-3-clause
fredRos/pypmc
doc/conf.py
1
8272
# -*- coding: utf-8 -*- # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.mathjax', 'matplotlib.sphinxext.plot_directive'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'pypmc' copyright = u'2019, Frederik Beaujean and Stephan Jahn' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # from pypmc import __version__ as pypmc_version # The short X.Y version. version = str(pypmc_version) # The full version, including alpha/beta/rc tags. release = str(pypmc_version) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = False # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # turn off flags by hand using :no-members: autodoc_default_flags = ['members', 'show-inheritance', 'inherited-members'] # Show the code used to generate a plot with matplotlib plot_include_source = True # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinxdoc' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pypmcdoc' # mathjax doesn't support preambles pngmath_latex_preamble = r""" \newcommand{\vecgamma}{\vec{\gamma}} \newcommand{\vecth}{\vec{\theta}} """ # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). 'papersize': 'a4paper', # The font size ('10pt', '11pt' or '12pt'). 'pointsize': '12pt', # reuse LaTeX preamble from html for pdf 'preamble': r'\usepackage{mathpazo}' + '\n' + pngmath_latex_preamble, } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'pypmc.tex', u'pypmc Documentation', u'Frederik Beaujean, Stephan Jahn', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pypmc', u'pypmc Documentation', [u'Frederik Beaujean, Stephan Jahn'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'pypmc', u'pypmc Documentation', u'Frederik Beaujean, Stephan Jahn', 'pypmc', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
gpl-2.0
jreback/pandas
pandas/tests/indexes/period/test_period.py
2
19866
import numpy as np import pytest from pandas._libs.tslibs.period import IncompatibleFrequency import pandas.util._test_decorators as td import pandas as pd from pandas import ( DataFrame, DatetimeIndex, Index, NaT, Period, PeriodIndex, Series, date_range, offsets, period_range, ) import pandas._testing as tm from ..datetimelike import DatetimeLike class TestPeriodIndex(DatetimeLike): _holder = PeriodIndex @pytest.fixture( params=[ tm.makePeriodIndex(10), period_range("20130101", periods=10, freq="D")[::-1], ], ids=["index_inc", "index_dec"], ) def index(self, request): return request.param def create_index(self) -> PeriodIndex: return period_range("20130101", periods=5, freq="D") def test_pickle_compat_construction(self): pass @pytest.mark.parametrize("freq", ["D", "M", "A"]) def test_pickle_round_trip(self, freq): idx = PeriodIndex(["2016-05-16", "NaT", NaT, np.NaN], freq=freq) result = tm.round_trip_pickle(idx) tm.assert_index_equal(result, idx) def test_where(self): # This is handled in test_indexing pass @pytest.mark.parametrize("use_numpy", [True, False]) @pytest.mark.parametrize( "index", [ period_range("2000-01-01", periods=3, freq="D"), period_range("2001-01-01", periods=3, freq="2D"), PeriodIndex(["2001-01", "NaT", "2003-01"], freq="M"), ], ) def test_repeat_freqstr(self, index, use_numpy): # GH10183 expected = PeriodIndex([p for p in index for _ in range(3)]) result = np.repeat(index, 3) if use_numpy else index.repeat(3) tm.assert_index_equal(result, expected) assert result.freqstr == index.freqstr def test_no_millisecond_field(self): msg = "type object 'DatetimeIndex' has no attribute 'millisecond'" with pytest.raises(AttributeError, match=msg): DatetimeIndex.millisecond msg = "'DatetimeIndex' object has no attribute 'millisecond'" with pytest.raises(AttributeError, match=msg): DatetimeIndex([]).millisecond def test_make_time_series(self): index = period_range(freq="A", start="1/1/2001", end="12/1/2009") series = Series(1, index=index) assert isinstance(series, Series) def test_shallow_copy_empty(self): # GH13067 idx = PeriodIndex([], freq="M") result = idx._shallow_copy() expected = idx tm.assert_index_equal(result, expected) def test_shallow_copy_disallow_i8(self): # GH-24391 pi = period_range("2018-01-01", periods=3, freq="2D") with pytest.raises(AssertionError, match="ndarray"): pi._shallow_copy(pi.asi8) def test_shallow_copy_requires_disallow_period_index(self): pi = period_range("2018-01-01", periods=3, freq="2D") with pytest.raises(AssertionError, match="PeriodIndex"): pi._shallow_copy(pi) def test_view_asi8(self): idx = PeriodIndex([], freq="M") exp = np.array([], dtype=np.int64) tm.assert_numpy_array_equal(idx.view("i8"), exp) tm.assert_numpy_array_equal(idx.asi8, exp) idx = PeriodIndex(["2011-01", NaT], freq="M") exp = np.array([492, -9223372036854775808], dtype=np.int64) tm.assert_numpy_array_equal(idx.view("i8"), exp) tm.assert_numpy_array_equal(idx.asi8, exp) exp = np.array([14975, -9223372036854775808], dtype=np.int64) idx = PeriodIndex(["2011-01-01", NaT], freq="D") tm.assert_numpy_array_equal(idx.view("i8"), exp) tm.assert_numpy_array_equal(idx.asi8, exp) def test_values(self): idx = PeriodIndex([], freq="M") exp = np.array([], dtype=object) tm.assert_numpy_array_equal(idx.values, exp) tm.assert_numpy_array_equal(idx.to_numpy(), exp) exp = np.array([], dtype=np.int64) tm.assert_numpy_array_equal(idx.asi8, exp) idx = PeriodIndex(["2011-01", NaT], freq="M") exp = np.array([Period("2011-01", freq="M"), NaT], dtype=object) tm.assert_numpy_array_equal(idx.values, exp) tm.assert_numpy_array_equal(idx.to_numpy(), exp) exp = np.array([492, -9223372036854775808], dtype=np.int64) tm.assert_numpy_array_equal(idx.asi8, exp) idx = PeriodIndex(["2011-01-01", NaT], freq="D") exp = np.array([Period("2011-01-01", freq="D"), NaT], dtype=object) tm.assert_numpy_array_equal(idx.values, exp) tm.assert_numpy_array_equal(idx.to_numpy(), exp) exp = np.array([14975, -9223372036854775808], dtype=np.int64) tm.assert_numpy_array_equal(idx.asi8, exp) def test_period_index_length(self): pi = period_range(freq="A", start="1/1/2001", end="12/1/2009") assert len(pi) == 9 pi = period_range(freq="Q", start="1/1/2001", end="12/1/2009") assert len(pi) == 4 * 9 pi = period_range(freq="M", start="1/1/2001", end="12/1/2009") assert len(pi) == 12 * 9 start = Period("02-Apr-2005", "B") i1 = period_range(start=start, periods=20) assert len(i1) == 20 assert i1.freq == start.freq assert i1[0] == start end_intv = Period("2006-12-31", "W") i1 = period_range(end=end_intv, periods=10) assert len(i1) == 10 assert i1.freq == end_intv.freq assert i1[-1] == end_intv end_intv = Period("2006-12-31", "1w") i2 = period_range(end=end_intv, periods=10) assert len(i1) == len(i2) assert (i1 == i2).all() assert i1.freq == i2.freq msg = "start and end must have same freq" with pytest.raises(ValueError, match=msg): period_range(start=start, end=end_intv) end_intv = Period("2005-05-01", "B") i1 = period_range(start=start, end=end_intv) msg = ( "Of the three parameters: start, end, and periods, exactly two " "must be specified" ) with pytest.raises(ValueError, match=msg): period_range(start=start) # infer freq from first element i2 = PeriodIndex([end_intv, Period("2005-05-05", "B")]) assert len(i2) == 2 assert i2[0] == end_intv i2 = PeriodIndex(np.array([end_intv, Period("2005-05-05", "B")])) assert len(i2) == 2 assert i2[0] == end_intv # Mixed freq should fail vals = [end_intv, Period("2006-12-31", "w")] msg = r"Input has different freq=W-SUN from PeriodIndex\(freq=B\)" with pytest.raises(IncompatibleFrequency, match=msg): PeriodIndex(vals) vals = np.array(vals) with pytest.raises(ValueError, match=msg): PeriodIndex(vals) def test_fields(self): # year, month, day, hour, minute # second, weekofyear, week, dayofweek, weekday, dayofyear, quarter # qyear pi = period_range(freq="A", start="1/1/2001", end="12/1/2005") self._check_all_fields(pi) pi = period_range(freq="Q", start="1/1/2001", end="12/1/2002") self._check_all_fields(pi) pi = period_range(freq="M", start="1/1/2001", end="1/1/2002") self._check_all_fields(pi) pi = period_range(freq="D", start="12/1/2001", end="6/1/2001") self._check_all_fields(pi) pi = period_range(freq="B", start="12/1/2001", end="6/1/2001") self._check_all_fields(pi) pi = period_range(freq="H", start="12/31/2001", end="1/1/2002 23:00") self._check_all_fields(pi) pi = period_range(freq="Min", start="12/31/2001", end="1/1/2002 00:20") self._check_all_fields(pi) pi = period_range( freq="S", start="12/31/2001 00:00:00", end="12/31/2001 00:05:00" ) self._check_all_fields(pi) end_intv = Period("2006-12-31", "W") i1 = period_range(end=end_intv, periods=10) self._check_all_fields(i1) def _check_all_fields(self, periodindex): fields = [ "year", "month", "day", "hour", "minute", "second", "weekofyear", "week", "dayofweek", "day_of_week", "dayofyear", "day_of_year", "quarter", "qyear", "days_in_month", ] periods = list(periodindex) s = Series(periodindex) for field in fields: field_idx = getattr(periodindex, field) assert len(periodindex) == len(field_idx) for x, val in zip(periods, field_idx): assert getattr(x, field) == val if len(s) == 0: continue field_s = getattr(s.dt, field) assert len(periodindex) == len(field_s) for x, val in zip(periods, field_s): assert getattr(x, field) == val def test_is_(self): create_index = lambda: period_range(freq="A", start="1/1/2001", end="12/1/2009") index = create_index() assert index.is_(index) assert not index.is_(create_index()) assert index.is_(index.view()) assert index.is_(index.view().view().view().view().view()) assert index.view().is_(index) ind2 = index.view() index.name = "Apple" assert ind2.is_(index) assert not index.is_(index[:]) assert not index.is_(index.asfreq("M")) assert not index.is_(index.asfreq("A")) assert not index.is_(index - 2) assert not index.is_(index - 0) def test_periods_number_check(self): msg = ( "Of the three parameters: start, end, and periods, exactly two " "must be specified" ) with pytest.raises(ValueError, match=msg): period_range("2011-1-1", "2012-1-1", "B") def test_index_duplicate_periods(self): # monotonic idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq="A-JUN") ts = Series(np.random.randn(len(idx)), index=idx) result = ts["2007"] expected = ts[1:3] tm.assert_series_equal(result, expected) result[:] = 1 assert (ts[1:3] == 1).all() # not monotonic idx = PeriodIndex([2000, 2007, 2007, 2009, 2007], freq="A-JUN") ts = Series(np.random.randn(len(idx)), index=idx) result = ts["2007"] expected = ts[idx == "2007"] tm.assert_series_equal(result, expected) def test_index_unique(self): idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq="A-JUN") expected = PeriodIndex([2000, 2007, 2009], freq="A-JUN") tm.assert_index_equal(idx.unique(), expected) assert idx.nunique() == 3 def test_shift(self): # This is tested in test_arithmetic pass @td.skip_if_32bit def test_ndarray_compat_properties(self): super().test_ndarray_compat_properties() def test_negative_ordinals(self): Period(ordinal=-1000, freq="A") Period(ordinal=0, freq="A") idx1 = PeriodIndex(ordinal=[-1, 0, 1], freq="A") idx2 = PeriodIndex(ordinal=np.array([-1, 0, 1]), freq="A") tm.assert_index_equal(idx1, idx2) def test_pindex_fieldaccessor_nat(self): idx = PeriodIndex( ["2011-01", "2011-02", "NaT", "2012-03", "2012-04"], freq="D", name="name" ) exp = Index([2011, 2011, -1, 2012, 2012], dtype=np.int64, name="name") tm.assert_index_equal(idx.year, exp) exp = Index([1, 2, -1, 3, 4], dtype=np.int64, name="name") tm.assert_index_equal(idx.month, exp) def test_pindex_qaccess(self): pi = PeriodIndex(["2Q05", "3Q05", "4Q05", "1Q06", "2Q06"], freq="Q") s = Series(np.random.rand(len(pi)), index=pi).cumsum() # Todo: fix these accessors! assert s["05Q4"] == s[2] def test_pindex_multiples(self): expected = PeriodIndex( ["2011-01", "2011-03", "2011-05", "2011-07", "2011-09", "2011-11"], freq="2M", ) pi = period_range(start="1/1/11", end="12/31/11", freq="2M") tm.assert_index_equal(pi, expected) assert pi.freq == offsets.MonthEnd(2) assert pi.freqstr == "2M" pi = period_range(start="1/1/11", periods=6, freq="2M") tm.assert_index_equal(pi, expected) assert pi.freq == offsets.MonthEnd(2) assert pi.freqstr == "2M" def test_iteration(self): index = period_range(start="1/1/10", periods=4, freq="B") result = list(index) assert isinstance(result[0], Period) assert result[0].freq == index.freq def test_is_full(self): index = PeriodIndex([2005, 2007, 2009], freq="A") assert not index.is_full index = PeriodIndex([2005, 2006, 2007], freq="A") assert index.is_full index = PeriodIndex([2005, 2005, 2007], freq="A") assert not index.is_full index = PeriodIndex([2005, 2005, 2006], freq="A") assert index.is_full index = PeriodIndex([2006, 2005, 2005], freq="A") with pytest.raises(ValueError, match="Index is not monotonic"): index.is_full assert index[:0].is_full def test_with_multi_index(self): # #1705 index = date_range("1/1/2012", periods=4, freq="12H") index_as_arrays = [index.to_period(freq="D"), index.hour] s = Series([0, 1, 2, 3], index_as_arrays) assert isinstance(s.index.levels[0], PeriodIndex) assert isinstance(s.index.values[0][0], Period) def test_convert_array_of_periods(self): rng = period_range("1/1/2000", periods=20, freq="D") periods = list(rng) result = Index(periods) assert isinstance(result, PeriodIndex) def test_append_concat(self): # #1815 d1 = date_range("12/31/1990", "12/31/1999", freq="A-DEC") d2 = date_range("12/31/2000", "12/31/2009", freq="A-DEC") s1 = Series(np.random.randn(10), d1) s2 = Series(np.random.randn(10), d2) s1 = s1.to_period() s2 = s2.to_period() # drops index result = pd.concat([s1, s2]) assert isinstance(result.index, PeriodIndex) assert result.index[0] == s1.index[0] def test_pickle_freq(self): # GH2891 prng = period_range("1/1/2011", "1/1/2012", freq="M") new_prng = tm.round_trip_pickle(prng) assert new_prng.freq == offsets.MonthEnd() assert new_prng.freqstr == "M" def test_map(self): # test_map_dictlike generally tests index = PeriodIndex([2005, 2007, 2009], freq="A") result = index.map(lambda x: x.ordinal) exp = Index([x.ordinal for x in index]) tm.assert_index_equal(result, exp) def test_insert(self): # GH 18295 (test missing) expected = PeriodIndex(["2017Q1", NaT, "2017Q2", "2017Q3", "2017Q4"], freq="Q") for na in (np.nan, NaT, None): result = period_range("2017Q1", periods=4, freq="Q").insert(1, na) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "msg, key", [ (r"Period\('2019', 'A-DEC'\), 'foo', 'bar'", (Period(2019), "foo", "bar")), (r"Period\('2019', 'A-DEC'\), 'y1', 'bar'", (Period(2019), "y1", "bar")), (r"Period\('2019', 'A-DEC'\), 'foo', 'z1'", (Period(2019), "foo", "z1")), ( r"Period\('2018', 'A-DEC'\), Period\('2016', 'A-DEC'\), 'bar'", (Period(2018), Period(2016), "bar"), ), (r"Period\('2018', 'A-DEC'\), 'foo', 'y1'", (Period(2018), "foo", "y1")), ( r"Period\('2017', 'A-DEC'\), 'foo', Period\('2015', 'A-DEC'\)", (Period(2017), "foo", Period(2015)), ), (r"Period\('2017', 'A-DEC'\), 'z1', 'bar'", (Period(2017), "z1", "bar")), ], ) def test_contains_raise_error_if_period_index_is_in_multi_index(self, msg, key): # issue 20684 """ parse_time_string return parameter if type not matched. PeriodIndex.get_loc takes returned value from parse_time_string as a tuple. If first argument is Period and a tuple has 3 items, process go on not raise exception """ df = DataFrame( { "A": [Period(2019), "x1", "x2"], "B": [Period(2018), Period(2016), "y1"], "C": [Period(2017), "z1", Period(2015)], "V1": [1, 2, 3], "V2": [10, 20, 30], } ).set_index(["A", "B", "C"]) with pytest.raises(KeyError, match=msg): df.loc[key] def test_format_empty(self): # GH35712 empty_idx = self._holder([], freq="A") assert empty_idx.format() == [] assert empty_idx.format(name=True) == [""] def test_maybe_convert_timedelta(): pi = PeriodIndex(["2000", "2001"], freq="D") offset = offsets.Day(2) assert pi._maybe_convert_timedelta(offset) == 2 assert pi._maybe_convert_timedelta(2) == 2 offset = offsets.BusinessDay() msg = r"Input has different freq=B from PeriodIndex\(freq=D\)" with pytest.raises(ValueError, match=msg): pi._maybe_convert_timedelta(offset) def test_is_monotonic_with_nat(): # GH#31437 # PeriodIndex.is_monotonic should behave analogously to DatetimeIndex, # in particular never be monotonic when we have NaT dti = date_range("2016-01-01", periods=3) pi = dti.to_period("D") tdi = Index(dti.view("timedelta64[ns]")) for obj in [pi, pi._engine, dti, dti._engine, tdi, tdi._engine]: if isinstance(obj, Index): # i.e. not Engines assert obj.is_monotonic assert obj.is_monotonic_increasing assert not obj.is_monotonic_decreasing assert obj.is_unique dti1 = dti.insert(0, NaT) pi1 = dti1.to_period("D") tdi1 = Index(dti1.view("timedelta64[ns]")) for obj in [pi1, pi1._engine, dti1, dti1._engine, tdi1, tdi1._engine]: if isinstance(obj, Index): # i.e. not Engines assert not obj.is_monotonic assert not obj.is_monotonic_increasing assert not obj.is_monotonic_decreasing assert obj.is_unique dti2 = dti.insert(3, NaT) pi2 = dti2.to_period("H") tdi2 = Index(dti2.view("timedelta64[ns]")) for obj in [pi2, pi2._engine, dti2, dti2._engine, tdi2, tdi2._engine]: if isinstance(obj, Index): # i.e. not Engines assert not obj.is_monotonic assert not obj.is_monotonic_increasing assert not obj.is_monotonic_decreasing assert obj.is_unique @pytest.mark.parametrize("array", [True, False]) def test_dunder_array(array): obj = PeriodIndex(["2000-01-01", "2001-01-01"], freq="D") if array: obj = obj._data expected = np.array([obj[0], obj[1]], dtype=object) result = np.array(obj) tm.assert_numpy_array_equal(result, expected) result = np.asarray(obj) tm.assert_numpy_array_equal(result, expected) expected = obj.asi8 for dtype in ["i8", "int64", np.int64]: result = np.array(obj, dtype=dtype) tm.assert_numpy_array_equal(result, expected) result = np.asarray(obj, dtype=dtype) tm.assert_numpy_array_equal(result, expected) for dtype in ["float64", "int32", "uint64"]: msg = "argument must be" with pytest.raises(TypeError, match=msg): np.array(obj, dtype=dtype) with pytest.raises(TypeError, match=msg): np.array(obj, dtype=getattr(np, dtype))
bsd-3-clause
skymanaditya1/numpy
doc/example.py
81
3581
"""This is the docstring for the example.py module. Modules names should have short, all-lowercase names. The module name may have underscores if this improves readability. Every module should have a docstring at the very top of the file. The module's docstring may extend over multiple lines. If your docstring does extend over multiple lines, the closing three quotation marks must be on a line by itself, preferably preceeded by a blank line. """ from __future__ import division, absolute_import, print_function import os # standard library imports first # Do NOT import using *, e.g. from numpy import * # # Import the module using # # import numpy # # instead or import individual functions as needed, e.g # # from numpy import array, zeros # # If you prefer the use of abbreviated module names, we suggest the # convention used by NumPy itself:: import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # These abbreviated names are not to be used in docstrings; users must # be able to paste and execute docstrings after importing only the # numpy module itself, unabbreviated. from my_module import my_func, other_func def foo(var1, var2, long_var_name='hi') : r"""A one-line summary that does not use variable names or the function name. Several sentences providing an extended description. Refer to variables using back-ticks, e.g. `var`. Parameters ---------- var1 : array_like Array_like means all those objects -- lists, nested lists, etc. -- that can be converted to an array. We can also refer to variables like `var1`. var2 : int The type above can either refer to an actual Python type (e.g. ``int``), or describe the type of the variable in more detail, e.g. ``(N,) ndarray`` or ``array_like``. Long_variable_name : {'hi', 'ho'}, optional Choices in brackets, default first when optional. Returns ------- type Explanation of anonymous return value of type ``type``. describe : type Explanation of return value named `describe`. out : type Explanation of `out`. Other Parameters ---------------- only_seldom_used_keywords : type Explanation common_parameters_listed_above : type Explanation Raises ------ BadException Because you shouldn't have done that. See Also -------- otherfunc : relationship (optional) newfunc : Relationship (optional), which could be fairly long, in which case the line wraps here. thirdfunc, fourthfunc, fifthfunc Notes ----- Notes about the implementation algorithm (if needed). This can have multiple paragraphs. You may include some math: .. math:: X(e^{j\omega } ) = x(n)e^{ - j\omega n} And even use a greek symbol like :math:`omega` inline. References ---------- Cite the relevant literature, e.g. [1]_. You may also cite these references in the notes section above. .. [1] O. McNoleg, "The integration of GIS, remote sensing, expert systems and adaptive co-kriging for environmental habitat modelling of the Highland Haggis using object-oriented, fuzzy-logic and neural-network techniques," Computers & Geosciences, vol. 22, pp. 585-588, 1996. Examples -------- These are written in doctest format, and should illustrate how to use the function. >>> a=[1,2,3] >>> print [x + 3 for x in a] [4, 5, 6] >>> print "a\n\nb" a b """ pass
bsd-3-clause
zooniverse/aggregation
experimental/paper/errorCheck.py
2
1134
#!/usr/bin/env python __author__ = 'greg' import pymongo from aggregation import base_directory from penguinAggregation import PenguinAggregation import os import sys import numpy as np import matplotlib.pyplot as plt import urllib import matplotlib.cbook as cbook # add the paths necessary for clustering algorithm and ibcc - currently only works on Greg's computer if os.path.exists("/home/ggdhines"): sys.path.append("/home/ggdhines/PycharmProjects/reduction/experimental/clusteringAlg") elif os.path.exists("/Users/greg"): sys.path.append("/Users/greg/Code/reduction/experimental/clusteringAlg") else: sys.path.append("/home/greg/github/reduction/experimental/clusteringAlg") from divisiveKmeans import DivisiveKmeans from zeroFix import ZeroFix clusterAlg = DivisiveKmeans().__fit__ fixAlg = ZeroFix().__fix__ penguin = PenguinAggregation() client = pymongo.MongoClient() db = client['penguin_2015-01-18'] collection = db["penguin_classifications"] subject_collection = db["penguin_subjects"] accuracy = [] numGold = [] penguin.__readin_subject__("APZ00035nr") penguin.__display_raw_markings__("APZ00035nr")
apache-2.0
krafczyk/spack
var/spack/repos/builtin/packages/py-sncosmo/package.py
5
2131
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # 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 terms and # conditions of 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, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class PySncosmo(PythonPackage): """SNCosmo is a Python library for high-level supernova cosmology analysis.""" homepage = "http://sncosmo.readthedocs.io/" url = "https://pypi.io/packages/source/s/sncosmo/sncosmo-1.2.0.tar.gz" version('1.2.0', '028e6d1dc84ab1c17d2f3b6378b2cb1e') # Required dependencies # py-sncosmo binaries are duplicates of those from py-astropy extends('python', ignore=r'bin/.*') depends_on('py-setuptools', type='build') depends_on('py-numpy', type=('build', 'run')) depends_on('py-scipy', type=('build', 'run')) depends_on('py-astropy', type=('build', 'run')) # Recommended dependencies depends_on('py-matplotlib', type=('build', 'run')) depends_on('py-iminuit', type=('build', 'run')) depends_on('py-emcee', type=('build', 'run')) depends_on('py-nestle', type=('build', 'run'))
lgpl-2.1
vdods/heisenberg
heisenberg/self_similar/plot.py
2
1058
import matplotlib.pyplot as plt import pathlib import typing class Plot: def __init__ (self, *, row_count:int, col_count:int, size:float) -> None: self.fig, self.axis_vv = plt.subplots( row_count, col_count, squeeze=False, figsize=(size*col_count,size*row_count), ) def axis (self, row:int, col:int) -> typing.Any: # TODO: Real type return self.axis_vv[row][col] def savefig (self, plot_p:pathlib.Path, *, tight_layout_kwargs:typing.Dict[str,typing.Any]=dict()) -> None: self.fig.tight_layout(**tight_layout_kwargs) plot_p.parent.mkdir(parents=True, exist_ok=True) plt.savefig(str(plot_p), bbox_inches='tight') print(f'wrote to file "{plot_p}"') # VERY important to do this -- otherwise your memory will slowly fill up! # Not sure which one is actually sufficient -- apparently none of them are, YAY! plt.clf() plt.cla() plt.close() plt.close(self.fig) #del fig #del axis_vv
mit
kagayakidan/scikit-learn
sklearn/tests/test_isotonic.py
230
11087
import numpy as np import pickle from sklearn.isotonic import (check_increasing, isotonic_regression, IsotonicRegression) from sklearn.utils.testing import (assert_raises, assert_array_equal, assert_true, assert_false, assert_equal, assert_array_almost_equal, assert_warns_message, assert_no_warnings) from sklearn.utils import shuffle def test_permutation_invariance(): # check that fit is permuation invariant. # regression test of missing sorting of sample-weights ir = IsotonicRegression() x = [1, 2, 3, 4, 5, 6, 7] y = [1, 41, 51, 1, 2, 5, 24] sample_weight = [1, 2, 3, 4, 5, 6, 7] x_s, y_s, sample_weight_s = shuffle(x, y, sample_weight, random_state=0) y_transformed = ir.fit_transform(x, y, sample_weight=sample_weight) y_transformed_s = ir.fit(x_s, y_s, sample_weight=sample_weight_s).transform(x) assert_array_equal(y_transformed, y_transformed_s) def test_check_increasing_up(): x = [0, 1, 2, 3, 4, 5] y = [0, 1.5, 2.77, 8.99, 8.99, 50] # Check that we got increasing=True and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_true(is_increasing) def test_check_increasing_up_extreme(): x = [0, 1, 2, 3, 4, 5] y = [0, 1, 2, 3, 4, 5] # Check that we got increasing=True and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_true(is_increasing) def test_check_increasing_down(): x = [0, 1, 2, 3, 4, 5] y = [0, -1.5, -2.77, -8.99, -8.99, -50] # Check that we got increasing=False and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_false(is_increasing) def test_check_increasing_down_extreme(): x = [0, 1, 2, 3, 4, 5] y = [0, -1, -2, -3, -4, -5] # Check that we got increasing=False and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_false(is_increasing) def test_check_ci_warn(): x = [0, 1, 2, 3, 4, 5] y = [0, -1, 2, -3, 4, -5] # Check that we got increasing=False and CI interval warning is_increasing = assert_warns_message(UserWarning, "interval", check_increasing, x, y) assert_false(is_increasing) def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(y_min=0., y_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) # check that it is immune to permutation perm = np.random.permutation(len(y)) ir = IsotonicRegression(y_min=0., y_max=1.) assert_array_equal(ir.fit_transform(x[perm], y[perm]), ir.fit_transform(x, y)[perm]) assert_array_equal(ir.transform(x[perm]), ir.transform(x)[perm]) # check we don't crash when all x are equal: ir = IsotonicRegression() assert_array_equal(ir.fit_transform(np.ones(len(x)), y), np.mean(y)) def test_isotonic_regression_ties_min(): # Setup examples with ties on minimum x = [0, 1, 1, 2, 3, 4, 5] y = [0, 1, 2, 3, 4, 5, 6] y_true = [0, 1.5, 1.5, 3, 4, 5, 6] # Check that we get identical results for fit/transform and fit_transform ir = IsotonicRegression() ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(y_true, ir.fit_transform(x, y)) def test_isotonic_regression_ties_max(): # Setup examples with ties on maximum x = [1, 2, 3, 4, 5, 5] y = [1, 2, 3, 4, 5, 6] y_true = [1, 2, 3, 4, 5.5, 5.5] # Check that we get identical results for fit/transform and fit_transform ir = IsotonicRegression() ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(y_true, ir.fit_transform(x, y)) def test_isotonic_regression_ties_secondary_(): """ Test isotonic regression fit, transform and fit_transform against the "secondary" ties method and "pituitary" data from R "isotone" package, as detailed in: J. d. Leeuw, K. Hornik, P. Mair, Isotone Optimization in R: Pool-Adjacent-Violators Algorithm (PAVA) and Active Set Methods Set values based on pituitary example and the following R command detailed in the paper above: > library("isotone") > data("pituitary") > res1 <- gpava(pituitary$age, pituitary$size, ties="secondary") > res1$x `isotone` version: 1.0-2, 2014-09-07 R version: R version 3.1.1 (2014-07-10) """ x = [8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14] y = [21, 23.5, 23, 24, 21, 25, 21.5, 22, 19, 23.5, 25] y_true = [22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 24.25, 24.25] # Check fit, transform and fit_transform ir = IsotonicRegression() ir.fit(x, y) assert_array_almost_equal(ir.transform(x), y_true, 4) assert_array_almost_equal(ir.fit_transform(x, y), y_true, 4) def test_isotonic_regression_reversed(): y = np.array([10, 9, 10, 7, 6, 6.1, 5]) y_ = IsotonicRegression(increasing=False).fit_transform( np.arange(len(y)), y) assert_array_equal(np.ones(y_[:-1].shape), ((y_[:-1] - y_[1:]) >= 0)) def test_isotonic_regression_auto_decreasing(): # Set y and x for decreasing y = np.array([10, 9, 10, 7, 6, 6.1, 5]) x = np.arange(len(y)) # Create model and fit_transform ir = IsotonicRegression(increasing='auto') y_ = assert_no_warnings(ir.fit_transform, x, y) # Check that relationship decreases is_increasing = y_[0] < y_[-1] assert_false(is_increasing) def test_isotonic_regression_auto_increasing(): # Set y and x for decreasing y = np.array([5, 6.1, 6, 7, 10, 9, 10]) x = np.arange(len(y)) # Create model and fit_transform ir = IsotonicRegression(increasing='auto') y_ = assert_no_warnings(ir.fit_transform, x, y) # Check that relationship increases is_increasing = y_[0] < y_[-1] assert_true(is_increasing) def test_assert_raises_exceptions(): ir = IsotonicRegression() rng = np.random.RandomState(42) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, rng.randn(3, 10)) def test_isotonic_sample_weight_parameter_default_value(): # check if default value of sample_weight parameter is one ir = IsotonicRegression() # random test data rng = np.random.RandomState(42) n = 100 x = np.arange(n) y = rng.randint(-50, 50, size=(n,)) + 50. * np.log(1 + np.arange(n)) # check if value is correctly used weights = np.ones(n) y_set_value = ir.fit_transform(x, y, sample_weight=weights) y_default_value = ir.fit_transform(x, y) assert_array_equal(y_set_value, y_default_value) def test_isotonic_min_max_boundaries(): # check if min value is used correctly ir = IsotonicRegression(y_min=2, y_max=4) n = 6 x = np.arange(n) y = np.arange(n) y_test = [2, 2, 2, 3, 4, 4] y_result = np.round(ir.fit_transform(x, y)) assert_array_equal(y_result, y_test) def test_isotonic_sample_weight(): ir = IsotonicRegression() x = [1, 2, 3, 4, 5, 6, 7] y = [1, 41, 51, 1, 2, 5, 24] sample_weight = [1, 2, 3, 4, 5, 6, 7] expected_y = [1, 13.95, 13.95, 13.95, 13.95, 13.95, 24] received_y = ir.fit_transform(x, y, sample_weight=sample_weight) assert_array_equal(expected_y, received_y) def test_isotonic_regression_oob_raise(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="raise") ir.fit(x, y) # Check that an exception is thrown assert_raises(ValueError, ir.predict, [min(x) - 10, max(x) + 10]) def test_isotonic_regression_oob_clip(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="clip") ir.fit(x, y) # Predict from training and test x and check that min/max match. y1 = ir.predict([min(x) - 10, max(x) + 10]) y2 = ir.predict(x) assert_equal(max(y1), max(y2)) assert_equal(min(y1), min(y2)) def test_isotonic_regression_oob_nan(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="nan") ir.fit(x, y) # Predict from training and test x and check that we have two NaNs. y1 = ir.predict([min(x) - 10, max(x) + 10]) assert_equal(sum(np.isnan(y1)), 2) def test_isotonic_regression_oob_bad(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="xyz") # Make sure that we throw an error for bad out_of_bounds value assert_raises(ValueError, ir.fit, x, y) def test_isotonic_regression_oob_bad_after(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="raise") # Make sure that we throw an error for bad out_of_bounds value in transform ir.fit(x, y) ir.out_of_bounds = "xyz" assert_raises(ValueError, ir.transform, x) def test_isotonic_regression_pickle(): y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="clip") ir.fit(x, y) ir_ser = pickle.dumps(ir, pickle.HIGHEST_PROTOCOL) ir2 = pickle.loads(ir_ser) np.testing.assert_array_equal(ir.predict(x), ir2.predict(x)) def test_isotonic_duplicate_min_entry(): x = [0, 0, 1] y = [0, 0, 1] ir = IsotonicRegression(increasing=True, out_of_bounds="clip") ir.fit(x, y) all_predictions_finite = np.all(np.isfinite(ir.predict(x))) assert_true(all_predictions_finite) def test_isotonic_zero_weight_loop(): # Test from @ogrisel's issue: # https://github.com/scikit-learn/scikit-learn/issues/4297 # Get deterministic RNG with seed rng = np.random.RandomState(42) # Create regression and samples regression = IsotonicRegression() n_samples = 50 x = np.linspace(-3, 3, n_samples) y = x + rng.uniform(size=n_samples) # Get some random weights and zero out w = rng.uniform(size=n_samples) w[5:8] = 0 regression.fit(x, y, sample_weight=w) # This will hang in failure case. regression.fit(x, y, sample_weight=w)
bsd-3-clause
enigmampc/catalyst
catalyst/data/treasuries_can.py
15
5257
# # Copyright 2013 Quantopian, Inc. # # 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. import pandas as pd import six from toolz import curry from toolz.curried.operator import add as prepend COLUMN_NAMES = { "V39063": '1month', "V39065": '3month', "V39066": '6month', "V39067": '1year', "V39051": '2year', "V39052": '3year', "V39053": '5year', "V39054": '7year', "V39055": '10year', # Bank of Canada refers to this as 'Long' Rate, approximately 30 years. "V39056": '30year', } BILL_IDS = ['V39063', 'V39065', 'V39066', 'V39067'] BOND_IDS = ['V39051', 'V39052', 'V39053', 'V39054', 'V39055', 'V39056'] @curry def _format_url(instrument_type, instrument_ids, start_date, end_date, earliest_allowed_date): """ Format a URL for loading data from Bank of Canada. """ return ( "http://www.bankofcanada.ca/stats/results/csv" "?lP=lookup_{instrument_type}_yields.php" "&sR={restrict}" "&se={instrument_ids}" "&dF={start}" "&dT={end}".format( instrument_type=instrument_type, instrument_ids='-'.join(map(prepend("L_"), instrument_ids)), restrict=earliest_allowed_date.strftime("%Y-%m-%d"), start=start_date.strftime("%Y-%m-%d"), end=end_date.strftime("%Y-%m-%d"), ) ) format_bill_url = _format_url('tbill', BILL_IDS) format_bond_url = _format_url('bond', BOND_IDS) def load_frame(url, skiprows): """ Load a DataFrame of data from a Bank of Canada site. """ return pd.read_csv( url, skiprows=skiprows, skipinitialspace=True, na_values=["Bank holiday", "Not available"], parse_dates=["Date"], index_col="Date", ).dropna(how='all') \ .tz_localize('UTC') \ .rename(columns=COLUMN_NAMES) def check_known_inconsistencies(bill_data, bond_data): """ There are a couple quirks in the data provided by Bank of Canada. Check that no new quirks have been introduced in the latest download. """ inconsistent_dates = bill_data.index.sym_diff(bond_data.index) known_inconsistencies = [ # bill_data has an entry for 2010-02-15, which bond_data doesn't. # bond_data has an entry for 2006-09-04, which bill_data doesn't. # Both of these dates are bank holidays (Flag Day and Labor Day, # respectively). pd.Timestamp('2006-09-04', tz='UTC'), pd.Timestamp('2010-02-15', tz='UTC'), # 2013-07-25 comes back as "Not available" from the bills endpoint. # This date doesn't seem to be a bank holiday, but the previous # calendar implementation dropped this entry, so we drop it as well. # If someone cares deeply about the integrity of the Canadian trading # calendar, they may want to consider forward-filling here rather than # dropping the row. pd.Timestamp('2013-07-25', tz='UTC'), ] unexpected_inconsistences = inconsistent_dates.drop(known_inconsistencies) if len(unexpected_inconsistences): in_bills = bill_data.index.difference(bond_data.index).difference( known_inconsistencies ) in_bonds = bond_data.index.difference(bill_data.index).difference( known_inconsistencies ) raise ValueError( "Inconsistent dates for Canadian treasury bills vs bonds. \n" "Dates with bills but not bonds: {in_bills}.\n" "Dates with bonds but not bills: {in_bonds}.".format( in_bills=in_bills, in_bonds=in_bonds, ) ) def earliest_possible_date(): """ The earliest date for which we can load data from this module. """ today = pd.Timestamp('now', tz='UTC').normalize() # Bank of Canada only has the last 10 years of data at any given time. return today.replace(year=today.year - 10) def get_treasury_data(start_date, end_date): bill_data = load_frame( format_bill_url(start_date, end_date, start_date), # We skip fewer rows here because we query for fewer bill fields, # which makes the header smaller. skiprows=18, ) bond_data = load_frame( format_bond_url(start_date, end_date, start_date), skiprows=22, ) check_known_inconsistencies(bill_data, bond_data) # dropna('any') removes the rows for which we only had data for one of # bills/bonds. out = pd.concat([bond_data, bill_data], axis=1).dropna(how='any') assert set(out.columns) == set(six.itervalues(COLUMN_NAMES)) # Multiply by 0.01 to convert from percentages to expected output format. return out * 0.01
apache-2.0
sandeep-n/incubator-systemml
src/main/python/tests/test_mllearn_df.py
4
5381
#!/usr/bin/python #------------------------------------------------------------- # # 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. # #------------------------------------------------------------- # To run: # - Python 2: `PYSPARK_PYTHON=python2 spark-submit --master local[*] --driver-class-path SystemML.jar test_mllearn_df.py` # - Python 3: `PYSPARK_PYTHON=python3 spark-submit --master local[*] --driver-class-path SystemML.jar test_mllearn_df.py` # Make the `systemml` package importable import os import sys path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../") sys.path.insert(0, path) import unittest import numpy as np from pyspark.context import SparkContext from pyspark.ml import Pipeline from pyspark.ml.feature import HashingTF, Tokenizer from pyspark.sql import SparkSession from sklearn import datasets, metrics, neighbors from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn import linear_model from sklearn.metrics import accuracy_score, r2_score from systemml.mllearn import LinearRegression, LogisticRegression, NaiveBayes, SVM sc = SparkContext() sparkSession = SparkSession.builder.getOrCreate() # Currently not integrated with JUnit test # ~/spark-1.6.1-scala-2.11/bin/spark-submit --master local[*] --driver-class-path SystemML.jar test.py class TestMLLearn(unittest.TestCase): def test_logistic_sk2(self): digits = datasets.load_digits() X_digits = digits.data y_digits = digits.target n_samples = len(X_digits) X_train = X_digits[:int(.9 * n_samples)] y_train = y_digits[:int(.9 * n_samples)] X_test = X_digits[int(.9 * n_samples):] y_test = y_digits[int(.9 * n_samples):] # Convert to DataFrame for i/o: current way to transfer data logistic = LogisticRegression(sparkSession, transferUsingDF=True) logistic.fit(X_train, y_train) mllearn_predicted = logistic.predict(X_test) sklearn_logistic = linear_model.LogisticRegression() sklearn_logistic.fit(X_train, y_train) self.failUnless(accuracy_score(sklearn_logistic.predict(X_test), mllearn_predicted) > 0.95) # We are comparable to a similar algorithm in scikit learn def test_linear_regression(self): diabetes = datasets.load_diabetes() diabetes_X = diabetes.data[:, np.newaxis, 2] diabetes_X_train = diabetes_X[:-20] diabetes_X_test = diabetes_X[-20:] diabetes_y_train = diabetes.target[:-20] diabetes_y_test = diabetes.target[-20:] regr = LinearRegression(sparkSession, solver='direct-solve', transferUsingDF=True) regr.fit(diabetes_X_train, diabetes_y_train) mllearn_predicted = regr.predict(diabetes_X_test) sklearn_regr = linear_model.LinearRegression() sklearn_regr.fit(diabetes_X_train, diabetes_y_train) self.failUnless(r2_score(sklearn_regr.predict(diabetes_X_test), mllearn_predicted) > 0.95) # We are comparable to a similar algorithm in scikit learn def test_linear_regression_cg(self): diabetes = datasets.load_diabetes() diabetes_X = diabetes.data[:, np.newaxis, 2] diabetes_X_train = diabetes_X[:-20] diabetes_X_test = diabetes_X[-20:] diabetes_y_train = diabetes.target[:-20] diabetes_y_test = diabetes.target[-20:] regr = LinearRegression(sparkSession, solver='newton-cg', transferUsingDF=True) regr.fit(diabetes_X_train, diabetes_y_train) mllearn_predicted = regr.predict(diabetes_X_test) sklearn_regr = linear_model.LinearRegression() sklearn_regr.fit(diabetes_X_train, diabetes_y_train) self.failUnless(r2_score(sklearn_regr.predict(diabetes_X_test), mllearn_predicted) > 0.95) # We are comparable to a similar algorithm in scikit learn def test_svm_sk2(self): digits = datasets.load_digits() X_digits = digits.data y_digits = digits.target n_samples = len(X_digits) X_train = X_digits[:int(.9 * n_samples)] y_train = y_digits[:int(.9 * n_samples)] X_test = X_digits[int(.9 * n_samples):] y_test = y_digits[int(.9 * n_samples):] svm = SVM(sparkSession, is_multi_class=True, transferUsingDF=True) mllearn_predicted = svm.fit(X_train, y_train).predict(X_test) from sklearn import linear_model, svm clf = svm.LinearSVC() sklearn_predicted = clf.fit(X_train, y_train).predict(X_test) self.failUnless(accuracy_score(sklearn_predicted, mllearn_predicted) > 0.95 ) if __name__ == '__main__': unittest.main()
apache-2.0
bendudson/BOUT
tools/pylib/post_bout/pb_nonlinear.py
2
3020
#some function to plot nonlinear stuff from pb_corral import LinRes from ListDict import ListDictKey, ListDictFilt import numpy as np import matplotlib.pyplot as plt from matplotlib import cm import matplotlib.artist as artist import matplotlib.ticker as ticker import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.backends.backend_pdf import PdfPages from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch from reportlab.graphics.charts.linecharts import HorizontalLineChart from reportlab.graphics.shapes import Drawing from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker from reportlab.lib import colors from replab_x_vs_y import RL_Plot from matplotlib.ticker import ScalarFormatter, FormatStrFormatter, MultipleLocator class NLinResDraw(LinRes): def __init__(self,alldb): LinRes.__init__(self,alldb) def plotnlrhs(self,pp,field='Ni',yscale='linear',clip=0, xaxis='t',xscale='linear',xrange=1): colors = ['b','g','r','c','m','y','k','b','g','r','c','m','y','k'] Modes = subset(self.db,'field',[field]) #pick field comp ='ave' fig1 = plt.figure() adj = fig1.subplots_adjust(hspace=0.4,wspace=0.4) fig1.suptitle('Nonlinear contribution for ' + field) props = dict( alpha=0.8, edgecolors='none') Nplots = self.nrun k=0 for j in list(set(Modes.path).union()): s = subset(Modes.db,'path',[j]) #pick a run folder - many modes dz = s.dz[0] data = s.ave[0]['nl'] x = np.array(range(data.size)) ax =fig1.add_subplot(round(Nplots/2.0 + 1.0),2,k+1) ax.set_ylabel(r'$\frac{ddt_N}{ddt}$',fontsize=12,rotation='horizontal') k+=1 ax.grid(True,linestyle='-',color='.75') try: ax.set_yscale(yscale,linthreshy=1e-13) except: ax.set_yscale('linear') i=1 ax.plot(x,data.flatten(), c=cm.jet(.2*i),linestyle='-') #data = np.array(ListDictKey(s.db,comp)) #pick component should be ok for a fixed dz key # we are not interested in looping over all modes fig1.savefig(pp,format='pdf') plt.close(fig1) #return 0 class subset(NLinResDraw): def __init__(self,alldb,key,valuelist,model=False): selection = ListDictFilt(alldb,key,valuelist) if len(selection) !=0: LinRes.__init__(self,selection) self.skey = key if model==True: self.model() else: LinRes.__init__(self,alldb) if model==True: self.model()
gpl-3.0
fabianp/scikit-learn
sklearn/utils/arpack.py
265
64837
""" This contains a copy of the future version of scipy.sparse.linalg.eigen.arpack.eigsh It's an upgraded wrapper of the ARPACK library which allows the use of shift-invert mode for symmetric matrices. Find a few eigenvectors and eigenvalues of a matrix. Uses ARPACK: http://www.caam.rice.edu/software/ARPACK/ """ # Wrapper implementation notes # # ARPACK Entry Points # ------------------- # The entry points to ARPACK are # - (s,d)seupd : single and double precision symmetric matrix # - (s,d,c,z)neupd: single,double,complex,double complex general matrix # This wrapper puts the *neupd (general matrix) interfaces in eigs() # and the *seupd (symmetric matrix) in eigsh(). # There is no Hermetian complex/double complex interface. # To find eigenvalues of a Hermetian matrix you # must use eigs() and not eigsh() # It might be desirable to handle the Hermetian case differently # and, for example, return real eigenvalues. # Number of eigenvalues returned and complex eigenvalues # ------------------------------------------------------ # The ARPACK nonsymmetric real and double interface (s,d)naupd return # eigenvalues and eigenvectors in real (float,double) arrays. # Since the eigenvalues and eigenvectors are, in general, complex # ARPACK puts the real and imaginary parts in consecutive entries # in real-valued arrays. This wrapper puts the real entries # into complex data types and attempts to return the requested eigenvalues # and eigenvectors. # Solver modes # ------------ # ARPACK and handle shifted and shift-inverse computations # for eigenvalues by providing a shift (sigma) and a solver. __docformat__ = "restructuredtext en" __all__ = ['eigs', 'eigsh', 'svds', 'ArpackError', 'ArpackNoConvergence'] import warnings from scipy.sparse.linalg.eigen.arpack import _arpack import numpy as np from scipy.sparse.linalg.interface import aslinearoperator, LinearOperator from scipy.sparse import identity, isspmatrix, isspmatrix_csr from scipy.linalg import lu_factor, lu_solve from scipy.sparse.sputils import isdense from scipy.sparse.linalg import gmres, splu import scipy from distutils.version import LooseVersion _type_conv = {'f': 's', 'd': 'd', 'F': 'c', 'D': 'z'} _ndigits = {'f': 5, 'd': 12, 'F': 5, 'D': 12} DNAUPD_ERRORS = { 0: "Normal exit.", 1: "Maximum number of iterations taken. " "All possible eigenvalues of OP has been found. IPARAM(5) " "returns the number of wanted converged Ritz values.", 2: "No longer an informational error. Deprecated starting " "with release 2 of ARPACK.", 3: "No shifts could be applied during a cycle of the " "Implicitly restarted Arnoldi iteration. One possibility " "is to increase the size of NCV relative to NEV. ", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 2 and less than or equal to N.", -4: "The maximum number of Arnoldi update iterations allowed " "must be greater than zero.", -5: " WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work array WORKL is not sufficient.", -8: "Error return from LAPACK eigenvalue calculation;", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", -13: "NEV and WHICH = 'BE' are incompatible.", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " "enough workspace and array storage has been allocated." } SNAUPD_ERRORS = DNAUPD_ERRORS ZNAUPD_ERRORS = DNAUPD_ERRORS.copy() ZNAUPD_ERRORS[-10] = "IPARAM(7) must be 1,2,3." CNAUPD_ERRORS = ZNAUPD_ERRORS DSAUPD_ERRORS = { 0: "Normal exit.", 1: "Maximum number of iterations taken. " "All possible eigenvalues of OP has been found.", 2: "No longer an informational error. Deprecated starting with " "release 2 of ARPACK.", 3: "No shifts could be applied during a cycle of the Implicitly " "restarted Arnoldi iteration. One possibility is to increase " "the size of NCV relative to NEV. ", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV must be greater than NEV and less than or equal to N.", -4: "The maximum number of Arnoldi update iterations allowed " "must be greater than zero.", -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work array WORKL is not sufficient.", -8: "Error return from trid. eigenvalue calculation; " "Informational error from LAPACK routine dsteqr .", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4,5.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", -13: "NEV and WHICH = 'BE' are incompatible. ", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " "enough workspace and array storage has been allocated.", } SSAUPD_ERRORS = DSAUPD_ERRORS DNEUPD_ERRORS = { 0: "Normal exit.", 1: "The Schur form computed by LAPACK routine dlahqr " "could not be reordered by LAPACK routine dtrsen. " "Re-enter subroutine dneupd with IPARAM(5)NCV and " "increase the size of the arrays DR and DI to have " "dimension at least dimension NCV and allocate at least NCV " "columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 2 and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: "Error return from calculation of a real Schur form. " "Informational error from LAPACK routine dlahqr .", -9: "Error return from calculation of eigenvectors. " "Informational error from LAPACK routine dtrevc.", -10: "IPARAM(7) must be 1,2,3,4.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "HOWMNY = 'S' not yet implemented", -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.", -14: "DNAUPD did not find any eigenvalues to sufficient " "accuracy.", -15: "DNEUPD got a different count of the number of converged " "Ritz values than DNAUPD got. This indicates the user " "probably made an error in passing data from DNAUPD to " "DNEUPD or that the data was modified before entering " "DNEUPD", } SNEUPD_ERRORS = DNEUPD_ERRORS.copy() SNEUPD_ERRORS[1] = ("The Schur form computed by LAPACK routine slahqr " "could not be reordered by LAPACK routine strsen . " "Re-enter subroutine dneupd with IPARAM(5)=NCV and " "increase the size of the arrays DR and DI to have " "dimension at least dimension NCV and allocate at least " "NCV columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.") SNEUPD_ERRORS[-14] = ("SNAUPD did not find any eigenvalues to sufficient " "accuracy.") SNEUPD_ERRORS[-15] = ("SNEUPD got a different count of the number of " "converged Ritz values than SNAUPD got. This indicates " "the user probably made an error in passing data from " "SNAUPD to SNEUPD or that the data was modified before " "entering SNEUPD") ZNEUPD_ERRORS = {0: "Normal exit.", 1: "The Schur form computed by LAPACK routine csheqr " "could not be reordered by LAPACK routine ztrsen. " "Re-enter subroutine zneupd with IPARAM(5)=NCV and " "increase the size of the array D to have " "dimension at least dimension NCV and allocate at least " "NCV columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 1 and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: "Error return from LAPACK eigenvalue calculation. " "This should never happened.", -9: "Error return from calculation of eigenvectors. " "Informational error from LAPACK routine ztrevc.", -10: "IPARAM(7) must be 1,2,3", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "HOWMNY = 'S' not yet implemented", -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.", -14: "ZNAUPD did not find any eigenvalues to sufficient " "accuracy.", -15: "ZNEUPD got a different count of the number of " "converged Ritz values than ZNAUPD got. This " "indicates the user probably made an error in passing " "data from ZNAUPD to ZNEUPD or that the data was " "modified before entering ZNEUPD"} CNEUPD_ERRORS = ZNEUPD_ERRORS.copy() CNEUPD_ERRORS[-14] = ("CNAUPD did not find any eigenvalues to sufficient " "accuracy.") CNEUPD_ERRORS[-15] = ("CNEUPD got a different count of the number of " "converged Ritz values than CNAUPD got. This indicates " "the user probably made an error in passing data from " "CNAUPD to CNEUPD or that the data was modified before " "entering CNEUPD") DSEUPD_ERRORS = { 0: "Normal exit.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV must be greater than NEV and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: ("Error return from trid. eigenvalue calculation; " "Information error from LAPACK routine dsteqr."), -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4,5.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "NEV and WHICH = 'BE' are incompatible.", -14: "DSAUPD did not find any eigenvalues to sufficient accuracy.", -15: "HOWMNY must be one of 'A' or 'S' if RVEC = .true.", -16: "HOWMNY = 'S' not yet implemented", -17: ("DSEUPD got a different count of the number of converged " "Ritz values than DSAUPD got. This indicates the user " "probably made an error in passing data from DSAUPD to " "DSEUPD or that the data was modified before entering " "DSEUPD.") } SSEUPD_ERRORS = DSEUPD_ERRORS.copy() SSEUPD_ERRORS[-14] = ("SSAUPD did not find any eigenvalues " "to sufficient accuracy.") SSEUPD_ERRORS[-17] = ("SSEUPD got a different count of the number of " "converged " "Ritz values than SSAUPD got. This indicates the user " "probably made an error in passing data from SSAUPD to " "SSEUPD or that the data was modified before entering " "SSEUPD.") _SAUPD_ERRORS = {'d': DSAUPD_ERRORS, 's': SSAUPD_ERRORS} _NAUPD_ERRORS = {'d': DNAUPD_ERRORS, 's': SNAUPD_ERRORS, 'z': ZNAUPD_ERRORS, 'c': CNAUPD_ERRORS} _SEUPD_ERRORS = {'d': DSEUPD_ERRORS, 's': SSEUPD_ERRORS} _NEUPD_ERRORS = {'d': DNEUPD_ERRORS, 's': SNEUPD_ERRORS, 'z': ZNEUPD_ERRORS, 'c': CNEUPD_ERRORS} # accepted values of parameter WHICH in _SEUPD _SEUPD_WHICH = ['LM', 'SM', 'LA', 'SA', 'BE'] # accepted values of parameter WHICH in _NAUPD _NEUPD_WHICH = ['LM', 'SM', 'LR', 'SR', 'LI', 'SI'] class ArpackError(RuntimeError): """ ARPACK error """ def __init__(self, info, infodict=_NAUPD_ERRORS): msg = infodict.get(info, "Unknown error") RuntimeError.__init__(self, "ARPACK error %d: %s" % (info, msg)) class ArpackNoConvergence(ArpackError): """ ARPACK iteration did not converge Attributes ---------- eigenvalues : ndarray Partial result. Converged eigenvalues. eigenvectors : ndarray Partial result. Converged eigenvectors. """ def __init__(self, msg, eigenvalues, eigenvectors): ArpackError.__init__(self, -1, {-1: msg}) self.eigenvalues = eigenvalues self.eigenvectors = eigenvectors class _ArpackParams(object): def __init__(self, n, k, tp, mode=1, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): if k <= 0: raise ValueError("k must be positive, k=%d" % k) if maxiter is None: maxiter = n * 10 if maxiter <= 0: raise ValueError("maxiter must be positive, maxiter=%d" % maxiter) if tp not in 'fdFD': raise ValueError("matrix type must be 'f', 'd', 'F', or 'D'") if v0 is not None: # ARPACK overwrites its initial resid, make a copy self.resid = np.array(v0, copy=True) info = 1 else: self.resid = np.zeros(n, tp) info = 0 if sigma is None: #sigma not used self.sigma = 0 else: self.sigma = sigma if ncv is None: ncv = 2 * k + 1 ncv = min(ncv, n) self.v = np.zeros((n, ncv), tp) # holds Ritz vectors self.iparam = np.zeros(11, "int") # set solver mode and parameters ishfts = 1 self.mode = mode self.iparam[0] = ishfts self.iparam[2] = maxiter self.iparam[3] = 1 self.iparam[6] = mode self.n = n self.tol = tol self.k = k self.maxiter = maxiter self.ncv = ncv self.which = which self.tp = tp self.info = info self.converged = False self.ido = 0 def _raise_no_convergence(self): msg = "No convergence (%d iterations, %d/%d eigenvectors converged)" k_ok = self.iparam[4] num_iter = self.iparam[2] try: ev, vec = self.extract(True) except ArpackError as err: msg = "%s [%s]" % (msg, err) ev = np.zeros((0,)) vec = np.zeros((self.n, 0)) k_ok = 0 raise ArpackNoConvergence(msg % (num_iter, k_ok, self.k), ev, vec) class _SymmetricArpackParams(_ArpackParams): def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None, Minv_matvec=None, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): # The following modes are supported: # mode = 1: # Solve the standard eigenvalue problem: # A*x = lambda*x : # A - symmetric # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = None [not used] # # mode = 2: # Solve the general eigenvalue problem: # A*x = lambda*M*x # A - symmetric # M - symmetric positive definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # Minv_matvec = left multiplication by M^-1 # # mode = 3: # Solve the general eigenvalue problem in shift-invert mode: # A*x = lambda*M*x # A - symmetric # M - symmetric positive semi-definite # Arguments should be # matvec = None [not used] # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 # # mode = 4: # Solve the general eigenvalue problem in Buckling mode: # A*x = lambda*AG*x # A - symmetric positive semi-definite # AG - symmetric indefinite # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = left multiplication by [A-sigma*AG]^-1 # # mode = 5: # Solve the general eigenvalue problem in Cayley-transformed mode: # A*x = lambda*M*x # A - symmetric # M - symmetric positive semi-definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 if mode == 1: if matvec is None: raise ValueError("matvec must be specified for mode=1") if M_matvec is not None: raise ValueError("M_matvec cannot be specified for mode=1") if Minv_matvec is not None: raise ValueError("Minv_matvec cannot be specified for mode=1") self.OP = matvec self.B = lambda x: x self.bmat = 'I' elif mode == 2: if matvec is None: raise ValueError("matvec must be specified for mode=2") if M_matvec is None: raise ValueError("M_matvec must be specified for mode=2") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=2") self.OP = lambda x: Minv_matvec(matvec(x)) self.OPa = Minv_matvec self.OPb = matvec self.B = M_matvec self.bmat = 'G' elif mode == 3: if matvec is not None: raise ValueError("matvec must not be specified for mode=3") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=3") if M_matvec is None: self.OP = Minv_matvec self.OPa = Minv_matvec self.B = lambda x: x self.bmat = 'I' else: self.OP = lambda x: Minv_matvec(M_matvec(x)) self.OPa = Minv_matvec self.B = M_matvec self.bmat = 'G' elif mode == 4: if matvec is None: raise ValueError("matvec must be specified for mode=4") if M_matvec is not None: raise ValueError("M_matvec must not be specified for mode=4") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=4") self.OPa = Minv_matvec self.OP = lambda x: self.OPa(matvec(x)) self.B = matvec self.bmat = 'G' elif mode == 5: if matvec is None: raise ValueError("matvec must be specified for mode=5") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=5") self.OPa = Minv_matvec self.A_matvec = matvec if M_matvec is None: self.OP = lambda x: Minv_matvec(matvec(x) + sigma * x) self.B = lambda x: x self.bmat = 'I' else: self.OP = lambda x: Minv_matvec(matvec(x) + sigma * M_matvec(x)) self.B = M_matvec self.bmat = 'G' else: raise ValueError("mode=%i not implemented" % mode) if which not in _SEUPD_WHICH: raise ValueError("which must be one of %s" % ' '.join(_SEUPD_WHICH)) if k >= n: raise ValueError("k must be less than rank(A), k=%d" % k) _ArpackParams.__init__(self, n, k, tp, mode, sigma, ncv, v0, maxiter, which, tol) if self.ncv > n or self.ncv <= k: raise ValueError("ncv must be k<ncv<=n, ncv=%s" % self.ncv) self.workd = np.zeros(3 * n, self.tp) self.workl = np.zeros(self.ncv * (self.ncv + 8), self.tp) ltr = _type_conv[self.tp] if ltr not in ["s", "d"]: raise ValueError("Input matrix is not real-valued.") self._arpack_solver = _arpack.__dict__[ltr + 'saupd'] self._arpack_extract = _arpack.__dict__[ltr + 'seupd'] self.iterate_infodict = _SAUPD_ERRORS[ltr] self.extract_infodict = _SEUPD_ERRORS[ltr] self.ipntr = np.zeros(11, "int") def iterate(self): self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info = \ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n) yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n) if self.ido == -1: # initialization self.workd[yslice] = self.OP(self.workd[xslice]) elif self.ido == 1: # compute y = Op*x if self.mode == 1: self.workd[yslice] = self.OP(self.workd[xslice]) elif self.mode == 2: self.workd[xslice] = self.OPb(self.workd[xslice]) self.workd[yslice] = self.OPa(self.workd[xslice]) elif self.mode == 5: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) Ax = self.A_matvec(self.workd[xslice]) self.workd[yslice] = self.OPa(Ax + (self.sigma * self.workd[Bxslice])) else: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) self.workd[yslice] = self.OPa(self.workd[Bxslice]) elif self.ido == 2: self.workd[yslice] = self.B(self.workd[xslice]) elif self.ido == 3: raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0") else: self.converged = True if self.info == 0: pass elif self.info == 1: self._raise_no_convergence() else: raise ArpackError(self.info, infodict=self.iterate_infodict) def extract(self, return_eigenvectors): rvec = return_eigenvectors ierr = 0 howmny = 'A' # return all eigenvectors sselect = np.zeros(self.ncv, 'int') # unused d, z, ierr = self._arpack_extract(rvec, howmny, sselect, self.sigma, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam[0:7], self.ipntr, self.workd[0:2 * self.n], self.workl, ierr) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) k_ok = self.iparam[4] d = d[:k_ok] z = z[:, :k_ok] if return_eigenvectors: return d, z else: return d class _UnsymmetricArpackParams(_ArpackParams): def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None, Minv_matvec=None, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): # The following modes are supported: # mode = 1: # Solve the standard eigenvalue problem: # A*x = lambda*x # A - square matrix # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = None [not used] # # mode = 2: # Solve the generalized eigenvalue problem: # A*x = lambda*M*x # A - square matrix # M - symmetric, positive semi-definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # Minv_matvec = left multiplication by M^-1 # # mode = 3,4: # Solve the general eigenvalue problem in shift-invert mode: # A*x = lambda*M*x # A - square matrix # M - symmetric, positive semi-definite # Arguments should be # matvec = None [not used] # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 # if A is real and mode==3, use the real part of Minv_matvec # if A is real and mode==4, use the imag part of Minv_matvec # if A is complex and mode==3, # use real and imag parts of Minv_matvec if mode == 1: if matvec is None: raise ValueError("matvec must be specified for mode=1") if M_matvec is not None: raise ValueError("M_matvec cannot be specified for mode=1") if Minv_matvec is not None: raise ValueError("Minv_matvec cannot be specified for mode=1") self.OP = matvec self.B = lambda x: x self.bmat = 'I' elif mode == 2: if matvec is None: raise ValueError("matvec must be specified for mode=2") if M_matvec is None: raise ValueError("M_matvec must be specified for mode=2") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=2") self.OP = lambda x: Minv_matvec(matvec(x)) self.OPa = Minv_matvec self.OPb = matvec self.B = M_matvec self.bmat = 'G' elif mode in (3, 4): if matvec is None: raise ValueError("matvec must be specified " "for mode in (3,4)") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified " "for mode in (3,4)") self.matvec = matvec if tp in 'DF': # complex type if mode == 3: self.OPa = Minv_matvec else: raise ValueError("mode=4 invalid for complex A") else: # real type if mode == 3: self.OPa = lambda x: np.real(Minv_matvec(x)) else: self.OPa = lambda x: np.imag(Minv_matvec(x)) if M_matvec is None: self.B = lambda x: x self.bmat = 'I' self.OP = self.OPa else: self.B = M_matvec self.bmat = 'G' self.OP = lambda x: self.OPa(M_matvec(x)) else: raise ValueError("mode=%i not implemented" % mode) if which not in _NEUPD_WHICH: raise ValueError("Parameter which must be one of %s" % ' '.join(_NEUPD_WHICH)) if k >= n - 1: raise ValueError("k must be less than rank(A)-1, k=%d" % k) _ArpackParams.__init__(self, n, k, tp, mode, sigma, ncv, v0, maxiter, which, tol) if self.ncv > n or self.ncv <= k + 1: raise ValueError("ncv must be k+1<ncv<=n, ncv=%s" % self.ncv) self.workd = np.zeros(3 * n, self.tp) self.workl = np.zeros(3 * self.ncv * (self.ncv + 2), self.tp) ltr = _type_conv[self.tp] self._arpack_solver = _arpack.__dict__[ltr + 'naupd'] self._arpack_extract = _arpack.__dict__[ltr + 'neupd'] self.iterate_infodict = _NAUPD_ERRORS[ltr] self.extract_infodict = _NEUPD_ERRORS[ltr] self.ipntr = np.zeros(14, "int") if self.tp in 'FD': self.rwork = np.zeros(self.ncv, self.tp.lower()) else: self.rwork = None def iterate(self): if self.tp in 'fd': self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info =\ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) else: self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info =\ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.rwork, self.info) xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n) yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n) if self.ido == -1: # initialization self.workd[yslice] = self.OP(self.workd[xslice]) elif self.ido == 1: # compute y = Op*x if self.mode in (1, 2): self.workd[yslice] = self.OP(self.workd[xslice]) else: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) self.workd[yslice] = self.OPa(self.workd[Bxslice]) elif self.ido == 2: self.workd[yslice] = self.B(self.workd[xslice]) elif self.ido == 3: raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0") else: self.converged = True if self.info == 0: pass elif self.info == 1: self._raise_no_convergence() else: raise ArpackError(self.info, infodict=self.iterate_infodict) def extract(self, return_eigenvectors): k, n = self.k, self.n ierr = 0 howmny = 'A' # return all eigenvectors sselect = np.zeros(self.ncv, 'int') # unused sigmar = np.real(self.sigma) sigmai = np.imag(self.sigma) workev = np.zeros(3 * self.ncv, self.tp) if self.tp in 'fd': dr = np.zeros(k + 1, self.tp) di = np.zeros(k + 1, self.tp) zr = np.zeros((n, k + 1), self.tp) dr, di, zr, ierr = \ self._arpack_extract( return_eigenvectors, howmny, sselect, sigmar, sigmai, workev, self.bmat, self.which, k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) nreturned = self.iparam[4] # number of good eigenvalues returned # Build complex eigenvalues from real and imaginary parts d = dr + 1.0j * di # Arrange the eigenvectors: complex eigenvectors are stored as # real,imaginary in consecutive columns z = zr.astype(self.tp.upper()) # The ARPACK nonsymmetric real and double interface (s,d)naupd # return eigenvalues and eigenvectors in real (float,double) # arrays. # Efficiency: this should check that return_eigenvectors == True # before going through this construction. if sigmai == 0: i = 0 while i <= k: # check if complex if abs(d[i].imag) != 0: # this is a complex conjugate pair with eigenvalues # in consecutive columns if i < k: z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1] z[:, i + 1] = z[:, i].conjugate() i += 1 else: #last eigenvalue is complex: the imaginary part of # the eigenvector has not been returned #this can only happen if nreturned > k, so we'll # throw out this case. nreturned -= 1 i += 1 else: # real matrix, mode 3 or 4, imag(sigma) is nonzero: # see remark 3 in <s,d>neupd.f # Build complex eigenvalues from real and imaginary parts i = 0 while i <= k: if abs(d[i].imag) == 0: d[i] = np.dot(zr[:, i], self.matvec(zr[:, i])) else: if i < k: z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1] z[:, i + 1] = z[:, i].conjugate() d[i] = ((np.dot(zr[:, i], self.matvec(zr[:, i])) + np.dot(zr[:, i + 1], self.matvec(zr[:, i + 1]))) + 1j * (np.dot(zr[:, i], self.matvec(zr[:, i + 1])) - np.dot(zr[:, i + 1], self.matvec(zr[:, i])))) d[i + 1] = d[i].conj() i += 1 else: #last eigenvalue is complex: the imaginary part of # the eigenvector has not been returned #this can only happen if nreturned > k, so we'll # throw out this case. nreturned -= 1 i += 1 # Now we have k+1 possible eigenvalues and eigenvectors # Return the ones specified by the keyword "which" if nreturned <= k: # we got less or equal as many eigenvalues we wanted d = d[:nreturned] z = z[:, :nreturned] else: # we got one extra eigenvalue (likely a cc pair, but which?) # cut at approx precision for sorting rd = np.round(d, decimals=_ndigits[self.tp]) if self.which in ['LR', 'SR']: ind = np.argsort(rd.real) elif self.which in ['LI', 'SI']: # for LI,SI ARPACK returns largest,smallest # abs(imaginary) why? ind = np.argsort(abs(rd.imag)) else: ind = np.argsort(abs(rd)) if self.which in ['LR', 'LM', 'LI']: d = d[ind[-k:]] z = z[:, ind[-k:]] if self.which in ['SR', 'SM', 'SI']: d = d[ind[:k]] z = z[:, ind[:k]] else: # complex is so much simpler... d, z, ierr =\ self._arpack_extract( return_eigenvectors, howmny, sselect, self.sigma, workev, self.bmat, self.which, k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.rwork, ierr) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) k_ok = self.iparam[4] d = d[:k_ok] z = z[:, :k_ok] if return_eigenvectors: return d, z else: return d def _aslinearoperator_with_dtype(m): m = aslinearoperator(m) if not hasattr(m, 'dtype'): x = np.zeros(m.shape[1]) m.dtype = (m * x).dtype return m class SpLuInv(LinearOperator): """ SpLuInv: helper class to repeatedly solve M*x=b using a sparse LU-decopposition of M """ def __init__(self, M): self.M_lu = splu(M) LinearOperator.__init__(self, M.shape, self._matvec, dtype=M.dtype) self.isreal = not np.issubdtype(self.dtype, np.complexfloating) def _matvec(self, x): # careful here: splu.solve will throw away imaginary # part of x if M is real if self.isreal and np.issubdtype(x.dtype, np.complexfloating): return (self.M_lu.solve(np.real(x)) + 1j * self.M_lu.solve(np.imag(x))) else: return self.M_lu.solve(x) class LuInv(LinearOperator): """ LuInv: helper class to repeatedly solve M*x=b using an LU-decomposition of M """ def __init__(self, M): self.M_lu = lu_factor(M) LinearOperator.__init__(self, M.shape, self._matvec, dtype=M.dtype) def _matvec(self, x): return lu_solve(self.M_lu, x) class IterInv(LinearOperator): """ IterInv: helper class to repeatedly solve M*x=b using an iterative method. """ def __init__(self, M, ifunc=gmres, tol=0): if tol <= 0: # when tol=0, ARPACK uses machine tolerance as calculated # by LAPACK's _LAMCH function. We should match this tol = np.finfo(M.dtype).eps self.M = M self.ifunc = ifunc self.tol = tol if hasattr(M, 'dtype'): dtype = M.dtype else: x = np.zeros(M.shape[1]) dtype = (M * x).dtype LinearOperator.__init__(self, M.shape, self._matvec, dtype=dtype) def _matvec(self, x): b, info = self.ifunc(self.M, x, tol=self.tol) if info != 0: raise ValueError("Error in inverting M: function " "%s did not converge (info = %i)." % (self.ifunc.__name__, info)) return b class IterOpInv(LinearOperator): """ IterOpInv: helper class to repeatedly solve [A-sigma*M]*x = b using an iterative method """ def __init__(self, A, M, sigma, ifunc=gmres, tol=0): if tol <= 0: # when tol=0, ARPACK uses machine tolerance as calculated # by LAPACK's _LAMCH function. We should match this tol = np.finfo(A.dtype).eps self.A = A self.M = M self.sigma = sigma self.ifunc = ifunc self.tol = tol x = np.zeros(A.shape[1]) if M is None: dtype = self.mult_func_M_None(x).dtype self.OP = LinearOperator(self.A.shape, self.mult_func_M_None, dtype=dtype) else: dtype = self.mult_func(x).dtype self.OP = LinearOperator(self.A.shape, self.mult_func, dtype=dtype) LinearOperator.__init__(self, A.shape, self._matvec, dtype=dtype) def mult_func(self, x): return self.A.matvec(x) - self.sigma * self.M.matvec(x) def mult_func_M_None(self, x): return self.A.matvec(x) - self.sigma * x def _matvec(self, x): b, info = self.ifunc(self.OP, x, tol=self.tol) if info != 0: raise ValueError("Error in inverting [A-sigma*M]: function " "%s did not converge (info = %i)." % (self.ifunc.__name__, info)) return b def get_inv_matvec(M, symmetric=False, tol=0): if isdense(M): return LuInv(M).matvec elif isspmatrix(M): if isspmatrix_csr(M) and symmetric: M = M.T return SpLuInv(M).matvec else: return IterInv(M, tol=tol).matvec def get_OPinv_matvec(A, M, sigma, symmetric=False, tol=0): if sigma == 0: return get_inv_matvec(A, symmetric=symmetric, tol=tol) if M is None: #M is the identity matrix if isdense(A): if (np.issubdtype(A.dtype, np.complexfloating) or np.imag(sigma) == 0): A = np.copy(A) else: A = A + 0j A.flat[::A.shape[1] + 1] -= sigma return LuInv(A).matvec elif isspmatrix(A): A = A - sigma * identity(A.shape[0]) if symmetric and isspmatrix_csr(A): A = A.T return SpLuInv(A.tocsc()).matvec else: return IterOpInv(_aslinearoperator_with_dtype(A), M, sigma, tol=tol).matvec else: if ((not isdense(A) and not isspmatrix(A)) or (not isdense(M) and not isspmatrix(M))): return IterOpInv(_aslinearoperator_with_dtype(A), _aslinearoperator_with_dtype(M), sigma, tol=tol).matvec elif isdense(A) or isdense(M): return LuInv(A - sigma * M).matvec else: OP = A - sigma * M if symmetric and isspmatrix_csr(OP): OP = OP.T return SpLuInv(OP.tocsc()).matvec def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, maxiter=None, tol=0, return_eigenvectors=True, Minv=None, OPinv=None, OPpart=None): """ Find k eigenvalues and eigenvectors of the square matrix A. Solves ``A * x[i] = w[i] * x[i]``, the standard eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i]. If M is specified, solves ``A * x[i] = w[i] * M * x[i]``, the generalized eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i] Parameters ---------- A : An N x N matrix, array, sparse matrix, or LinearOperator representing \ the operation A * x, where A is a real or complex square matrix. k : int, default 6 The number of eigenvalues and eigenvectors desired. `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. return_eigenvectors : boolean, default True Whether to return the eigenvectors along with the eigenvalues. M : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation M*x for the generalized eigenvalue problem ``A * x = w * M * x`` M must represent a real symmetric matrix. For best results, M should be of the same type as A. Additionally: * If sigma==None, M is positive definite * If sigma is specified, M is positive semi-definite If sigma==None, eigs requires an operator to compute the solution of the linear equation `M * x = b`. This is done internally via a (sparse) LU decomposition for an explicit matrix M, or via an iterative solver for a general linear operator. Alternatively, the user can supply the matrix or operator Minv, which gives x = Minv * b = M^-1 * b sigma : real or complex Find eigenvalues near sigma using shift-invert mode. This requires an operator to compute the solution of the linear system `[A - sigma * M] * x = b`, where M is the identity matrix if unspecified. This is computed internally via a (sparse) LU decomposition for explicit matrices A & M, or via an iterative solver if either A or M is a general linear operator. Alternatively, the user can supply the matrix or operator OPinv, which gives x = OPinv * b = [A - sigma * M]^-1 * b. For a real matrix A, shift-invert can either be done in imaginary mode or real mode, specified by the parameter OPpart ('r' or 'i'). Note that when sigma is specified, the keyword 'which' (below) refers to the shifted eigenvalues w'[i] where: * If A is real and OPpart == 'r' (default), w'[i] = 1/2 * [ 1/(w[i]-sigma) + 1/(w[i]-conj(sigma)) ] * If A is real and OPpart == 'i', w'[i] = 1/2i * [ 1/(w[i]-sigma) - 1/(w[i]-conj(sigma)) ] * If A is complex, w'[i] = 1/(w[i]-sigma) v0 : array Starting vector for iteration. ncv : integer The number of Lanczos vectors generated `ncv` must be greater than `k`; it is recommended that ``ncv > 2*k``. which : string ['LM' | 'SM' | 'LR' | 'SR' | 'LI' | 'SI'] Which `k` eigenvectors and eigenvalues to find: - 'LM' : largest magnitude - 'SM' : smallest magnitude - 'LR' : largest real part - 'SR' : smallest real part - 'LI' : largest imaginary part - 'SI' : smallest imaginary part When sigma != None, 'which' refers to the shifted eigenvalues w'[i] (see discussion in 'sigma', above). ARPACK is generally better at finding large values than small values. If small eigenvalues are desired, consider using shift-invert mode for better performance. maxiter : integer Maximum number of Arnoldi update iterations allowed tol : float Relative accuracy for eigenvalues (stopping criterion) The default value of 0 implies machine precision. return_eigenvectors : boolean Return eigenvectors (True) in addition to eigenvalues Minv : N x N matrix, array, sparse matrix, or linear operator See notes in M, above. OPinv : N x N matrix, array, sparse matrix, or linear operator See notes in sigma, above. OPpart : 'r' or 'i'. See notes in sigma, above Returns ------- w : array Array of k eigenvalues. v : array An array of `k` eigenvectors. ``v[:, i]`` is the eigenvector corresponding to the eigenvalue w[i]. Raises ------ ArpackNoConvergence When the requested convergence is not obtained. The currently converged eigenvalues and eigenvectors can be found as ``eigenvalues`` and ``eigenvectors`` attributes of the exception object. See Also -------- eigsh : eigenvalues and eigenvectors for symmetric matrix A svds : singular value decomposition for a matrix A Examples -------- Find 6 eigenvectors of the identity matrix: >>> from sklearn.utils.arpack import eigs >>> id = np.identity(13) >>> vals, vecs = eigs(id, k=6) >>> vals array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]) >>> vecs.shape (13, 6) Notes ----- This function is a wrapper to the ARPACK [1]_ SNEUPD, DNEUPD, CNEUPD, ZNEUPD, functions which use the Implicitly Restarted Arnoldi Method to find the eigenvalues and eigenvectors [2]_. References ---------- .. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE: Solution of Large Scale Eigenvalue Problems by Implicitly Restarted Arnoldi Methods. SIAM, Philadelphia, PA, 1998. """ if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix (shape=%s)' % (A.shape,)) if M is not None: if M.shape != A.shape: raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] if k <= 0 or k >= n: raise ValueError("k must be between 1 and rank(A)-1") if sigma is None: matvec = _aslinearoperator_with_dtype(A).matvec if OPinv is not None: raise ValueError("OPinv should not be specified " "with sigma = None.") if OPpart is not None: raise ValueError("OPpart should not be specified with " "sigma = None or complex A") if M is None: #standard eigenvalue problem mode = 1 M_matvec = None Minv_matvec = None if Minv is not None: raise ValueError("Minv should not be " "specified with M = None.") else: #general eigenvalue problem mode = 2 if Minv is None: Minv_matvec = get_inv_matvec(M, symmetric=True, tol=tol) else: Minv = _aslinearoperator_with_dtype(Minv) Minv_matvec = Minv.matvec M_matvec = _aslinearoperator_with_dtype(M).matvec else: #sigma is not None: shift-invert mode if np.issubdtype(A.dtype, np.complexfloating): if OPpart is not None: raise ValueError("OPpart should not be specified " "with sigma=None or complex A") mode = 3 elif OPpart is None or OPpart.lower() == 'r': mode = 3 elif OPpart.lower() == 'i': if np.imag(sigma) == 0: raise ValueError("OPpart cannot be 'i' if sigma is real") mode = 4 else: raise ValueError("OPpart must be one of ('r','i')") matvec = _aslinearoperator_with_dtype(A).matvec if Minv is not None: raise ValueError("Minv should not be specified when sigma is") if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=False, tol=tol) else: OPinv = _aslinearoperator_with_dtype(OPinv) Minv_matvec = OPinv.matvec if M is None: M_matvec = None else: M_matvec = _aslinearoperator_with_dtype(M).matvec params = _UnsymmetricArpackParams(n, k, A.dtype.char, matvec, mode, M_matvec, Minv_matvec, sigma, ncv, v0, maxiter, which, tol) while not params.converged: params.iterate() return params.extract(return_eigenvectors) def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, maxiter=None, tol=0, return_eigenvectors=True, Minv=None, OPinv=None, mode='normal'): """ Find k eigenvalues and eigenvectors of the real symmetric square matrix or complex hermitian matrix A. Solves ``A * x[i] = w[i] * x[i]``, the standard eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i]. If M is specified, solves ``A * x[i] = w[i] * M * x[i]``, the generalized eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i] Parameters ---------- A : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation A * x, where A is a real symmetric matrix For buckling mode (see below) A must additionally be positive-definite k : integer The number of eigenvalues and eigenvectors desired. `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. M : An N x N matrix, array, sparse matrix, or linear operator representing the operation M * x for the generalized eigenvalue problem ``A * x = w * M * x``. M must represent a real, symmetric matrix. For best results, M should be of the same type as A. Additionally: * If sigma == None, M is symmetric positive definite * If sigma is specified, M is symmetric positive semi-definite * In buckling mode, M is symmetric indefinite. If sigma == None, eigsh requires an operator to compute the solution of the linear equation `M * x = b`. This is done internally via a (sparse) LU decomposition for an explicit matrix M, or via an iterative solver for a general linear operator. Alternatively, the user can supply the matrix or operator Minv, which gives x = Minv * b = M^-1 * b sigma : real Find eigenvalues near sigma using shift-invert mode. This requires an operator to compute the solution of the linear system `[A - sigma * M] x = b`, where M is the identity matrix if unspecified. This is computed internally via a (sparse) LU decomposition for explicit matrices A & M, or via an iterative solver if either A or M is a general linear operator. Alternatively, the user can supply the matrix or operator OPinv, which gives x = OPinv * b = [A - sigma * M]^-1 * b. Note that when sigma is specified, the keyword 'which' refers to the shifted eigenvalues w'[i] where: - if mode == 'normal', w'[i] = 1 / (w[i] - sigma) - if mode == 'cayley', w'[i] = (w[i] + sigma) / (w[i] - sigma) - if mode == 'buckling', w'[i] = w[i] / (w[i] - sigma) (see further discussion in 'mode' below) v0 : array Starting vector for iteration. ncv : integer The number of Lanczos vectors generated ncv must be greater than k and smaller than n; it is recommended that ncv > 2*k which : string ['LM' | 'SM' | 'LA' | 'SA' | 'BE'] If A is a complex hermitian matrix, 'BE' is invalid. Which `k` eigenvectors and eigenvalues to find - 'LM' : Largest (in magnitude) eigenvalues - 'SM' : Smallest (in magnitude) eigenvalues - 'LA' : Largest (algebraic) eigenvalues - 'SA' : Smallest (algebraic) eigenvalues - 'BE' : Half (k/2) from each end of the spectrum When k is odd, return one more (k/2+1) from the high end When sigma != None, 'which' refers to the shifted eigenvalues w'[i] (see discussion in 'sigma', above). ARPACK is generally better at finding large values than small values. If small eigenvalues are desired, consider using shift-invert mode for better performance. maxiter : integer Maximum number of Arnoldi update iterations allowed tol : float Relative accuracy for eigenvalues (stopping criterion). The default value of 0 implies machine precision. Minv : N x N matrix, array, sparse matrix, or LinearOperator See notes in M, above OPinv : N x N matrix, array, sparse matrix, or LinearOperator See notes in sigma, above. return_eigenvectors : boolean Return eigenvectors (True) in addition to eigenvalues mode : string ['normal' | 'buckling' | 'cayley'] Specify strategy to use for shift-invert mode. This argument applies only for real-valued A and sigma != None. For shift-invert mode, ARPACK internally solves the eigenvalue problem ``OP * x'[i] = w'[i] * B * x'[i]`` and transforms the resulting Ritz vectors x'[i] and Ritz values w'[i] into the desired eigenvectors and eigenvalues of the problem ``A * x[i] = w[i] * M * x[i]``. The modes are as follows: - 'normal' : OP = [A - sigma * M]^-1 * M B = M w'[i] = 1 / (w[i] - sigma) - 'buckling' : OP = [A - sigma * M]^-1 * A B = A w'[i] = w[i] / (w[i] - sigma) - 'cayley' : OP = [A - sigma * M]^-1 * [A + sigma * M] B = M w'[i] = (w[i] + sigma) / (w[i] - sigma) The choice of mode will affect which eigenvalues are selected by the keyword 'which', and can also impact the stability of convergence (see [2] for a discussion) Returns ------- w : array Array of k eigenvalues v : array An array of k eigenvectors The v[i] is the eigenvector corresponding to the eigenvector w[i] Raises ------ ArpackNoConvergence When the requested convergence is not obtained. The currently converged eigenvalues and eigenvectors can be found as ``eigenvalues`` and ``eigenvectors`` attributes of the exception object. See Also -------- eigs : eigenvalues and eigenvectors for a general (nonsymmetric) matrix A svds : singular value decomposition for a matrix A Notes ----- This function is a wrapper to the ARPACK [1]_ SSEUPD and DSEUPD functions which use the Implicitly Restarted Lanczos Method to find the eigenvalues and eigenvectors [2]_. Examples -------- >>> from sklearn.utils.arpack import eigsh >>> id = np.identity(13) >>> vals, vecs = eigsh(id, k=6) >>> vals # doctest: +SKIP array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]) >>> print(vecs.shape) (13, 6) References ---------- .. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE: Solution of Large Scale Eigenvalue Problems by Implicitly Restarted Arnoldi Methods. SIAM, Philadelphia, PA, 1998. """ # complex hermitian matrices should be solved with eigs if np.issubdtype(A.dtype, np.complexfloating): if mode != 'normal': raise ValueError("mode=%s cannot be used with " "complex matrix A" % mode) if which == 'BE': raise ValueError("which='BE' cannot be used with complex matrix A") elif which == 'LA': which = 'LR' elif which == 'SA': which = 'SR' ret = eigs(A, k, M=M, sigma=sigma, which=which, v0=v0, ncv=ncv, maxiter=maxiter, tol=tol, return_eigenvectors=return_eigenvectors, Minv=Minv, OPinv=OPinv) if return_eigenvectors: return ret[0].real, ret[1] else: return ret.real if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix (shape=%s)' % (A.shape,)) if M is not None: if M.shape != A.shape: raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] if k <= 0 or k >= n: raise ValueError("k must be between 1 and rank(A)-1") if sigma is None: A = _aslinearoperator_with_dtype(A) matvec = A.matvec if OPinv is not None: raise ValueError("OPinv should not be specified " "with sigma = None.") if M is None: #standard eigenvalue problem mode = 1 M_matvec = None Minv_matvec = None if Minv is not None: raise ValueError("Minv should not be " "specified with M = None.") else: #general eigenvalue problem mode = 2 if Minv is None: Minv_matvec = get_inv_matvec(M, symmetric=True, tol=tol) else: Minv = _aslinearoperator_with_dtype(Minv) Minv_matvec = Minv.matvec M_matvec = _aslinearoperator_with_dtype(M).matvec else: # sigma is not None: shift-invert mode if Minv is not None: raise ValueError("Minv should not be specified when sigma is") # normal mode if mode == 'normal': mode = 3 matvec = None if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: OPinv = _aslinearoperator_with_dtype(OPinv) Minv_matvec = OPinv.matvec if M is None: M_matvec = None else: M = _aslinearoperator_with_dtype(M) M_matvec = M.matvec # buckling mode elif mode == 'buckling': mode = 4 if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: Minv_matvec = _aslinearoperator_with_dtype(OPinv).matvec matvec = _aslinearoperator_with_dtype(A).matvec M_matvec = None # cayley-transform mode elif mode == 'cayley': mode = 5 matvec = _aslinearoperator_with_dtype(A).matvec if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: Minv_matvec = _aslinearoperator_with_dtype(OPinv).matvec if M is None: M_matvec = None else: M_matvec = _aslinearoperator_with_dtype(M).matvec # unrecognized mode else: raise ValueError("unrecognized mode '%s'" % mode) params = _SymmetricArpackParams(n, k, A.dtype.char, matvec, mode, M_matvec, Minv_matvec, sigma, ncv, v0, maxiter, which, tol) while not params.converged: params.iterate() return params.extract(return_eigenvectors) def _svds(A, k=6, ncv=None, tol=0): """Compute k singular values/vectors for a sparse matrix using ARPACK. Parameters ---------- A : sparse matrix Array to compute the SVD on k : int, optional Number of singular values and vectors to compute. ncv : integer The number of Lanczos vectors generated ncv must be greater than k+1 and smaller than n; it is recommended that ncv > 2*k tol : float, optional Tolerance for singular values. Zero (default) means machine precision. Notes ----- This is a naive implementation using an eigensolver on A.H * A or A * A.H, depending on which one is more efficient. """ if not (isinstance(A, np.ndarray) or isspmatrix(A)): A = np.asarray(A) n, m = A.shape if np.issubdtype(A.dtype, np.complexfloating): herm = lambda x: x.T.conjugate() eigensolver = eigs else: herm = lambda x: x.T eigensolver = eigsh if n > m: X = A XH = herm(A) else: XH = A X = herm(A) if hasattr(XH, 'dot'): def matvec_XH_X(x): return XH.dot(X.dot(x)) else: def matvec_XH_X(x): return np.dot(XH, np.dot(X, x)) XH_X = LinearOperator(matvec=matvec_XH_X, dtype=X.dtype, shape=(X.shape[1], X.shape[1])) # Ignore deprecation warnings here: dot on matrices is deprecated, # but this code is a backport anyhow with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) eigvals, eigvec = eigensolver(XH_X, k=k, tol=tol ** 2) s = np.sqrt(eigvals) if n > m: v = eigvec if hasattr(X, 'dot'): u = X.dot(v) / s else: u = np.dot(X, v) / s vh = herm(v) else: u = eigvec if hasattr(X, 'dot'): vh = herm(X.dot(u) / s) else: vh = herm(np.dot(X, u) / s) return u, s, vh # check if backport is actually needed: if scipy.version.version >= LooseVersion('0.10'): from scipy.sparse.linalg import eigs, eigsh, svds else: eigs, eigsh, svds = _eigs, _eigsh, _svds
bsd-3-clause
HolgerPeters/scikit-learn
examples/ensemble/plot_gradient_boosting_oob.py
82
4768
""" ====================================== Gradient Boosting Out-of-Bag estimates ====================================== Out-of-bag (OOB) estimates can be a useful heuristic to estimate the "optimal" number of boosting iterations. OOB estimates are almost identical to cross-validation estimates but they can be computed on-the-fly without the need for repeated model fitting. OOB estimates are only available for Stochastic Gradient Boosting (i.e. ``subsample < 1.0``), the estimates are derived from the improvement in loss based on the examples not included in the bootstrap sample (the so-called out-of-bag examples). The OOB estimator is a pessimistic estimator of the true test loss, but remains a fairly good approximation for a small number of trees. The figure shows the cumulative sum of the negative OOB improvements as a function of the boosting iteration. As you can see, it tracks the test loss for the first hundred iterations but then diverges in a pessimistic way. The figure also shows the performance of 3-fold cross validation which usually gives a better estimate of the test loss but is computationally more demanding. """ print(__doc__) # Author: Peter Prettenhofer <[email protected]> # # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn import ensemble from sklearn.model_selection import KFold from sklearn.model_selection import train_test_split # Generate data (adapted from G. Ridgeway's gbm example) n_samples = 1000 random_state = np.random.RandomState(13) x1 = random_state.uniform(size=n_samples) x2 = random_state.uniform(size=n_samples) x3 = random_state.randint(0, 4, size=n_samples) p = 1 / (1.0 + np.exp(-(np.sin(3 * x1) - 4 * x2 + x3))) y = random_state.binomial(1, p, size=n_samples) X = np.c_[x1, x2, x3] X = X.astype(np.float32) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=9) # Fit classifier with out-of-bag estimates params = {'n_estimators': 1200, 'max_depth': 3, 'subsample': 0.5, 'learning_rate': 0.01, 'min_samples_leaf': 1, 'random_state': 3} clf = ensemble.GradientBoostingClassifier(**params) clf.fit(X_train, y_train) acc = clf.score(X_test, y_test) print("Accuracy: {:.4f}".format(acc)) n_estimators = params['n_estimators'] x = np.arange(n_estimators) + 1 def heldout_score(clf, X_test, y_test): """compute deviance scores on ``X_test`` and ``y_test``. """ score = np.zeros((n_estimators,), dtype=np.float64) for i, y_pred in enumerate(clf.staged_decision_function(X_test)): score[i] = clf.loss_(y_test, y_pred) return score def cv_estimate(n_splits=3): cv = KFold(n_splits=n_splits) cv_clf = ensemble.GradientBoostingClassifier(**params) val_scores = np.zeros((n_estimators,), dtype=np.float64) for train, test in cv.split(X_train, y_train): cv_clf.fit(X_train[train], y_train[train]) val_scores += heldout_score(cv_clf, X_train[test], y_train[test]) val_scores /= n_splits return val_scores # Estimate best n_estimator using cross-validation cv_score = cv_estimate(3) # Compute best n_estimator for test data test_score = heldout_score(clf, X_test, y_test) # negative cumulative sum of oob improvements cumsum = -np.cumsum(clf.oob_improvement_) # min loss according to OOB oob_best_iter = x[np.argmin(cumsum)] # min loss according to test (normalize such that first loss is 0) test_score -= test_score[0] test_best_iter = x[np.argmin(test_score)] # min loss according to cv (normalize such that first loss is 0) cv_score -= cv_score[0] cv_best_iter = x[np.argmin(cv_score)] # color brew for the three curves oob_color = list(map(lambda x: x / 256.0, (190, 174, 212))) test_color = list(map(lambda x: x / 256.0, (127, 201, 127))) cv_color = list(map(lambda x: x / 256.0, (253, 192, 134))) # plot curves and vertical lines for best iterations plt.plot(x, cumsum, label='OOB loss', color=oob_color) plt.plot(x, test_score, label='Test loss', color=test_color) plt.plot(x, cv_score, label='CV loss', color=cv_color) plt.axvline(x=oob_best_iter, color=oob_color) plt.axvline(x=test_best_iter, color=test_color) plt.axvline(x=cv_best_iter, color=cv_color) # add three vertical lines to xticks xticks = plt.xticks() xticks_pos = np.array(xticks[0].tolist() + [oob_best_iter, cv_best_iter, test_best_iter]) xticks_label = np.array(list(map(lambda t: int(t), xticks[0])) + ['OOB', 'CV', 'Test']) ind = np.argsort(xticks_pos) xticks_pos = xticks_pos[ind] xticks_label = xticks_label[ind] plt.xticks(xticks_pos, xticks_label) plt.legend(loc='upper right') plt.ylabel('normalized loss') plt.xlabel('number of iterations') plt.show()
bsd-3-clause
JarnoRFB/GENNN
builder/network_builder.py
1
14253
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import json from builder.helper import get_tensor_size from tensorflow.examples.tutorials.mnist import input_data import os import datetime import math VALIDATION_SIZE = 5000 mnist = input_data.read_data_sets('MNIST_data', one_hot=False, reshape=False, validation_size=VALIDATION_SIZE) class Network: """A nerual network build from a JSON specification.""" def __init__(self, json_network_spec, test=False): self.network_spec = json.loads(json_network_spec) if self.network_spec['max_number_of_iterations'] % self.network_spec['validate_each_n_steps'] != 0: raise(ValueError('max_number_of_iterations is no multiple of validate_each_n_steps.')) self.x = None self.y_ = None self.loss = None self.accuracy = None self.train_op = None self._build_network() self._test = test def evaluate(self, get_weights=False): """Evaluate performance of network. Returns: The accuracy on the validation data. """ merged_summary = tf.summary.merge_all() # Time when starting the training. start_time = datetime.datetime.now() # Arrays for storing intermediate results. losses = np.zeros(self.network_spec['max_number_of_iterations'] // self.network_spec['validate_each_n_steps']) accuracies = np.zeros(self.network_spec['max_number_of_iterations'] // self.network_spec['validate_each_n_steps']) with tf.Session() as sess: if(get_weights): saver = tf.train.Saver() writer = tf.summary.FileWriter(self.network_spec['logdir'], graph=sess.graph) sess.run(tf.global_variables_initializer()) for i in range(self.network_spec['max_number_of_iterations']): batch = mnist.train.next_batch(self.network_spec['hyperparameters']['batchsize']) self.train_op.run(feed_dict={self.x: batch[0], self.y_: batch[1]}) if i % self.network_spec['validate_each_n_steps'] == 0: # Write summary and save data for plots. summary, accuracy_val, loss_val = sess.run([merged_summary, self.accuracy, self.loss], feed_dict={self.x: batch[0], self.y_: batch[1]}) writer.add_summary(summary, global_step=i) losses[int(i / self.network_spec['validate_each_n_steps'])] = loss_val accuracies[int(i / self.network_spec['validate_each_n_steps'])] = accuracy_val # Check whether training has taken too long. if (datetime.datetime.now() - start_time).seconds // 60 > self.network_spec['max_runtime']: break writer.close() # Since data is to big to fit in GPU, split data into chunks of 1000 and calculate the mean. chunk_size = 1000 steps = int(VALIDATION_SIZE / chunk_size) validation_accuracies = np.zeros(steps) if not self._test: for i in range(steps): validation_accuracies[i] = sess.run( self.accuracy, feed_dict={self.x: mnist.validation.images[i * chunk_size:(i+1) * chunk_size], self.y_: mnist.validation.labels[i * chunk_size:(i+1) * chunk_size]} ) else: for i in range(steps): validation_accuracies = sess.run( self.accuracy, feed_dict={self.x: mnist.test.images, self.y_: mnist.test.labels} ) # Save plots for losses and accuracies. self._plot(loss=losses, accuracy=accuracies) # Get total number of weights. n_weights = 0 for var in tf.trainable_variables(): n_weights += get_tensor_size(var) extended_spec = self._extend_network_spec(accuracy=float(validation_accuracies.mean()), n_weights=n_weights) # Write extended to logdir. self._write_to_logdir(extended_spec, 'network.json') if(get_weights): save_path = saver.save(sess, self.network_spec['logdir'] + "model.ckpt") return extended_spec def feedforward_layer(self, input_tensor, layer_number): """Build a feedforward layer ended with an activation function. Args: input_tensor: The output from the layer before. layer_number (int): The number of the layer in the network. Returns: tensor: The activated output. """ layer_spec = self.network_spec['layers'][layer_number] with tf.name_scope('feedforward' + str(layer_number)): weighted = self._feedforward_step(input_tensor, layer_spec['size']) activation = getattr(tf.nn, layer_spec['activation_function'])(weighted) return activation def conv_layer(self, input_tensor, layer_number): """Build a convolution layer ended with an activation function. Args: input_tensor: The output from the layer before. layer_number (int): The number of the layer in the network. Returns: tensor: The activated output. """ inchannels, input_tensor = self._ensure_2d(input_tensor) layer_spec = self.network_spec['layers'][layer_number] filter_shape = (layer_spec['filter']['height'], layer_spec['filter']['width'], inchannels, layer_spec['filter']['outchannels']) filter_strides = (layer_spec['strides']['inchannels'], layer_spec['strides']['x'], layer_spec['strides']['y'], layer_spec['strides']['batch']) with tf.name_scope('conv' + str(layer_number)): w = self._weight_variable(filter_shape, name='W') b = self._bias_variable([layer_spec['filter']['outchannels']], name='b') conv = tf.nn.conv2d(input_tensor, w, strides=filter_strides, padding='SAME') activation = getattr(tf.nn, layer_spec['activation_function'])(conv + b, name='activation') return activation def maxpool_layer(self, input_tensor, layer_number): """Build a maxpooling layer. Args: input_tensor: The output from the layer before. layer_number (int): The number of the layer in the network. Returns: tensor: The max pooled output. """ _, input_tensor = self._ensure_2d(input_tensor) layer_spec = self.network_spec['layers'][layer_number] kernel_shape = (1, # First number has to be one for ksize of maxpool layer. layer_spec['kernel']['height'], layer_spec['kernel']['width'], layer_spec['kernel']['outchannels']) kernel_strides = (layer_spec['strides']['inchannels'], layer_spec['strides']['x'], layer_spec['strides']['y'], layer_spec['strides']['batch']) with tf.name_scope('maxpool' + str(layer_number)): pool = tf.nn.max_pool(input_tensor, ksize=kernel_shape, strides=kernel_strides, padding='SAME', name='maxpool') return pool def _build_network(self): """Build network based on JSON specification. Construct all layers according to the JSON specification. Then project everything on a readout layer. Then build loss and the training op. """ # Write extended to logdir. os.makedirs(self.network_spec['logdir'], exist_ok=True) self._write_to_logdir(json.dumps(self.network_spec), 'network.json') # Reset the old graphs from previous candidates. tf.reset_default_graph() self.x = tf.placeholder(tf.float32, shape=[None, 28, 28, 1], name='input') self.y_ = tf.placeholder(tf.int32, shape=[None], name='labels') current_tensor = self._build_layers(self.x) readout = self._build_readout_layer(current_tensor, n_classes=10) loss = self._build_loss(readout, self.y_) self.train_op = self._build_train_op(loss) def _build_layers(self, current_tensor): """Build layers based on the JSON specification. Returns: tensor: The output from the last layer. """ for i, layer_spec in enumerate(self.network_spec['layers']): current_tensor = getattr(self, layer_spec['type'])(current_tensor, layer_number=i) return current_tensor def _build_readout_layer(self, input_tensor, n_classes): """Project into tensor onto readout layer with n classes.""" with tf.name_scope('readout'): readout = self._feedforward_step(input_tensor, n_classes) return readout def _build_loss(self, readout, labels): """Build the layer including the loss and the accuracy. Args: readout (tensor): The readout layer. A probability distribution over the classes. labels (tensor): Labels as integers. Returns: tensor: The loss tensor (cross entropy). """ with tf.name_scope('loss'): self.loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=readout, labels=labels)) tf.summary.scalar('cross_entropy', self.loss) correct_prediction = tf.nn.in_top_k(readout, labels, 1) self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar('accuracy', self.accuracy) return self.loss def _build_train_op(self, loss): """Build the training op. Args: loss (tensor): The loss function to be optimized. Returns: The training op. """ with tf.name_scope('train'): learning_rate = self.network_spec['hyperparameters']['learningrate'] optimizer = getattr(tf.train, self.network_spec['hyperparameters']['optimizer'])(learning_rate) train_op = optimizer.minimize(loss) return train_op def _feedforward_step(self, input_tensor, size): """Project tensor on column of `size` many neurons. Args: input_tensor: The tensor to be projected. size: The size of the feedforward layer. Returns: tensor: The forwarded tensor. """ # Flatten the input tensor. flat_dim = get_tensor_size(input_tensor) input_tensor_flat = tf.reshape(input_tensor, [-1, flat_dim], name='reshape') w = self._weight_variable([flat_dim, size], name='W') b = self._bias_variable([size], name='b') weighted = tf.matmul(input_tensor_flat, w) + b return weighted def _ensure_2d(self, input_tensor): """Make sure that `input_tensor` can be used for convolution and maxpooling ops. Args: input_tensor (tensor): The tensor that potentially has to be converted to 2D. Returns: Number of inchannels for the next layer. The `input_tensor` for the next layer. """ if len(input_tensor.get_shape()) > 2: inchannels = int(input_tensor.get_shape()[-1]) # inchannels else: inchannels = 1 input_tensor = self._reshape_to_2d(input_tensor) return inchannels, input_tensor @staticmethod def _reshape_to_2d(input_tensor): # The length of the flat tensor. flat_size = int(input_tensor.get_shape()[1]) side_length = math.ceil(math.sqrt(flat_size)) padding_size = (side_length ** 2) - flat_size if padding_size != 0: padding = tf.zeros(shape=[tf.shape(input_tensor)[0], (side_length ** 2) - flat_size], name='padding') input_tensor = tf.concat([input_tensor, padding], axis=1) input_tensor_2d = tf.reshape(input_tensor, [-1, side_length, side_length, 1], name='reshape') return input_tensor_2d @staticmethod def _weight_variable(shape, name): """Initialize weights randomly with normal distribution.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial, name=name) @staticmethod def _bias_variable(shape, name): """Set all biases to 0.1""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=name) def _write_to_logdir(self, file_str, fname): """Write a string to a file in the logdir. Args: file_str: The string to be written to the file. fname: The name of the file. """ file_loc = os.path.join(self.network_spec['logdir'], fname) with open(file_loc, 'w') as fp: fp.write(file_str) def _extend_network_spec(self, **kwargs): """Write results into JSON.""" extended_spec = self.network_spec extended_spec['results'] = kwargs extended_json_spec = json.dumps(extended_spec) return extended_json_spec def _plot(self, **kwargs): """Save plots in logdir. Keyword Args: A mapping between a label and a numpy array to be plotted. """ steps = np.arange( self.network_spec['max_number_of_iterations'] // self.network_spec['validate_each_n_steps'] ) * self.network_spec['validate_each_n_steps'] for y_label, y_vals in kwargs.items(): fig = plt.figure() ax = fig.add_subplot(111) ax.plot(steps, y_vals) ax.set_xlabel('batch') ax.set_ylabel(y_label) fig.savefig(self.network_spec['logdir'] + y_label + '.png', format='png') plt.clf() plt.close(fig)
mit
simon-anders/htseq
python3/doc/tss3.py
7
1263
import HTSeq import numpy from matplotlib import pyplot bamfile = HTSeq.BAM_Reader( "SRR001432_head.bam" ) gtffile = HTSeq.GFF_Reader( "Homo_sapiens.GRCh37.56_chrom1.gtf" ) halfwinwidth = 3000 fragmentsize = 200 tsspos = HTSeq.GenomicArrayOfSets( "auto", stranded=False ) for feature in gtffile: if feature.type == "exon" and feature.attr["exon_number"] == "1": p = feature.iv.start_d_as_pos window = HTSeq.GenomicInterval( p.chrom, p.pos - halfwinwidth, p.pos + halfwinwidth, "." ) tsspos[ window ] += p profile = numpy.zeros( 2*halfwinwidth, dtype="i" ) for almnt in bamfile: if almnt.aligned: almnt.iv.length = fragmentsize s = set() for step_iv, step_set in tsspos[ almnt.iv ].steps(): s |= step_set for p in s: if p.strand == "+": start_in_window = almnt.iv.start - p.pos + halfwinwidth end_in_window = almnt.iv.end - p.pos + halfwinwidth else: start_in_window = p.pos + halfwinwidth - almnt.iv.end end_in_window = p.pos + halfwinwidth - almnt.iv.start start_in_window = max( start_in_window, 0 ) end_in_window = min( end_in_window, 2*halfwinwidth ) profile[ start_in_window : end_in_window ] += 1
gpl-3.0
michaelaye/scikit-image
doc/ext/plot2rst.py
13
20439
""" Example generation from python files. Generate the rst files for the examples by iterating over the python example files. Files that generate images should start with 'plot'. To generate your own examples, add this extension to the list of ``extensions``in your Sphinx configuration file. In addition, make sure the example directory(ies) in `plot2rst_paths` (see below) points to a directory with examples named `plot_*.py` and include an `index.rst` file. This code was adapted from scikit-image, which took it from scikit-learn. Options ------- The ``plot2rst`` extension accepts the following options: plot2rst_paths : length-2 tuple, or list of tuples Tuple or list of tuples of paths to (python plot, generated rst) files, i.e. (source, destination). Note that both paths are relative to Sphinx 'source' directory. Defaults to ('../examples', 'auto_examples') plot2rst_rcparams : dict Matplotlib configuration parameters. See http://matplotlib.sourceforge.net/users/customizing.html for details. plot2rst_default_thumb : str Path (relative to doc root) of default thumbnail image. plot2rst_thumb_shape : float Shape of thumbnail in pixels. The image is resized to fit within this shape and the excess is filled with white pixels. This fixed size ensures that that gallery images are displayed in a grid. plot2rst_plot_tag : str When this tag is found in the example file, the current plot is saved and tag is replaced with plot path. Defaults to 'PLOT2RST.current_figure'. Suggested CSS definitions ------------------------- div.body h2 { border-bottom: 1px solid #BBB; clear: left; } /*---- example gallery ----*/ .gallery.figure { float: left; margin: 1em; } .gallery.figure img{ display: block; margin-left: auto; margin-right: auto; width: 200px; } .gallery.figure .caption { width: 200px; text-align: center !important; } """ import os import re import shutil import token import tokenize import traceback import itertools import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from skimage import io from skimage import transform from skimage.util.dtype import dtype_range from notebook import Notebook from docutils.core import publish_parts from sphinx.domains.python import PythonDomain LITERALINCLUDE = """ .. literalinclude:: {src_name} :lines: {code_start}- """ CODE_LINK = """ **Python source code:** :download:`download <{0}>` (generated using ``skimage`` |version|) """ NOTEBOOK_LINK = """ **IPython Notebook:** :download:`download <{0}>` (generated using ``skimage`` |version|) """ TOCTREE_TEMPLATE = """ .. toctree:: :hidden: %s """ IMAGE_TEMPLATE = """ .. image:: images/%s :align: center """ GALLERY_IMAGE_TEMPLATE = """ .. figure:: %(thumb)s :figclass: gallery :target: ./%(source)s.html :ref:`example_%(link_name)s` """ class Path(str): """Path object for manipulating directory and file paths.""" def __new__(self, path): return str.__new__(self, path) @property def isdir(self): return os.path.isdir(self) @property def exists(self): """Return True if path exists""" return os.path.exists(self) def pjoin(self, *args): """Join paths. `p` prefix prevents confusion with string method.""" return self.__class__(os.path.join(self, *args)) def psplit(self): """Split paths. `p` prefix prevents confusion with string method.""" return [self.__class__(p) for p in os.path.split(self)] def makedirs(self): if not self.exists: os.makedirs(self) def listdir(self): return os.listdir(self) def format(self, *args, **kwargs): return self.__class__(super(Path, self).format(*args, **kwargs)) def __add__(self, other): return self.__class__(super(Path, self).__add__(other)) def __iadd__(self, other): return self.__add__(other) def setup(app): app.connect('builder-inited', generate_example_galleries) app.add_config_value('plot2rst_paths', ('../examples', 'auto_examples'), True) app.add_config_value('plot2rst_rcparams', {}, True) app.add_config_value('plot2rst_default_thumb', None, True) app.add_config_value('plot2rst_thumb_shape', (250, 300), True) app.add_config_value('plot2rst_plot_tag', 'PLOT2RST.current_figure', True) app.add_config_value('plot2rst_index_name', 'index', True) def generate_example_galleries(app): cfg = app.builder.config if isinstance(cfg.source_suffix, list): cfg.source_suffix_str = cfg.source_suffix[0] else: cfg.source_suffix_str = cfg.source_suffix doc_src = Path(os.path.abspath(app.builder.srcdir)) # path/to/doc/source if isinstance(cfg.plot2rst_paths, tuple): cfg.plot2rst_paths = [cfg.plot2rst_paths] for src_dest in cfg.plot2rst_paths: plot_path, rst_path = [Path(p) for p in src_dest] example_dir = doc_src.pjoin(plot_path) rst_dir = doc_src.pjoin(rst_path) generate_examples_and_gallery(example_dir, rst_dir, cfg) def generate_examples_and_gallery(example_dir, rst_dir, cfg): """Generate rst from examples and create gallery to showcase examples.""" if not example_dir.exists: print("No example directory found at", example_dir) return rst_dir.makedirs() # we create an index.rst with all examples gallery_index = open(rst_dir.pjoin('index'+cfg.source_suffix_str), 'w') # Here we don't use an os.walk, but we recurse only twice: flat is # better than nested. write_gallery(gallery_index, example_dir, rst_dir, cfg) for d in sorted(example_dir.listdir()): example_sub = example_dir.pjoin(d) if example_sub.isdir: rst_sub = rst_dir.pjoin(d) rst_sub.makedirs() write_gallery(gallery_index, example_sub, rst_sub, cfg, depth=1) gallery_index.flush() def write_gallery(gallery_index, src_dir, rst_dir, cfg, depth=0): """Generate the rst files for an example directory, i.e. gallery. Write rst files from python examples and add example links to gallery. Parameters ---------- gallery_index : file Index file for plot gallery. src_dir : 'str' Source directory for python examples. rst_dir : 'str' Destination directory for rst files generated from python examples. cfg : config object Sphinx config object created by Sphinx. """ index_name = cfg.plot2rst_index_name + cfg.source_suffix_str gallery_template = src_dir.pjoin(index_name) if not os.path.exists(gallery_template): print(src_dir) print(80*'_') print('Example directory %s does not have a %s file' % (src_dir, index_name)) print('Skipping this directory') print(80*'_') return gallery_description = open(gallery_template).read() gallery_index.write('\n\n%s\n\n' % gallery_description) rst_dir.makedirs() examples = [fname for fname in sorted(src_dir.listdir(), key=_plots_first) if fname.endswith('py')] ex_names = [ex[:-3] for ex in examples] # strip '.py' extension if depth == 0: sub_dir = Path('') else: sub_dir_list = src_dir.psplit()[-depth:] sub_dir = Path('/'.join(sub_dir_list) + '/') joiner = '\n %s' % sub_dir gallery_index.write(TOCTREE_TEMPLATE % (sub_dir + joiner.join(ex_names))) for src_name in examples: try: write_example(src_name, src_dir, rst_dir, cfg) except Exception: print("Exception raised while running:") print("%s in %s" % (src_name, src_dir)) print('~' * 60) traceback.print_exc() print('~' * 60) continue link_name = sub_dir.pjoin(src_name) link_name = link_name.replace(os.path.sep, '_') if link_name.startswith('._'): link_name = link_name[2:] info = {} info['thumb'] = sub_dir.pjoin('images/thumb', src_name[:-3] + '.png') info['source'] = sub_dir + src_name[:-3] info['link_name'] = link_name gallery_index.write(GALLERY_IMAGE_TEMPLATE % info) def _plots_first(fname): """Decorate filename so that examples with plots are displayed first.""" if not (fname.startswith('plot') and fname.endswith('.py')): return 'zz' + fname return fname def write_example(src_name, src_dir, rst_dir, cfg): """Write rst file from a given python example. Parameters ---------- src_name : str Name of example file. src_dir : 'str' Source directory for python examples. rst_dir : 'str' Destination directory for rst files generated from python examples. cfg : config object Sphinx config object created by Sphinx. """ last_dir = src_dir.psplit()[-1] # to avoid leading . in file names, and wrong names in links if last_dir == '.' or last_dir == 'examples': last_dir = Path('') else: last_dir += '_' src_path = src_dir.pjoin(src_name) example_file = rst_dir.pjoin(src_name) shutil.copyfile(src_path, example_file) image_dir = rst_dir.pjoin('images') thumb_dir = image_dir.pjoin('thumb') notebook_dir = rst_dir.pjoin('notebook') image_dir.makedirs() thumb_dir.makedirs() notebook_dir.makedirs() base_image_name = os.path.splitext(src_name)[0] image_path = image_dir.pjoin(base_image_name + '_{0}.png') basename, py_ext = os.path.splitext(src_name) rst_path = rst_dir.pjoin(basename + cfg.source_suffix_str) notebook_path = notebook_dir.pjoin(basename + '.ipynb') if _plots_are_current(src_path, image_path) and rst_path.exists and \ notebook_path.exists: return print('plot2rst: %s' % basename) blocks = split_code_and_text_blocks(example_file) if blocks[0][2].startswith('#!'): blocks.pop(0) # don't add shebang line to rst file. rst_link = '.. _example_%s:\n\n' % (last_dir + src_name) figure_list, rst = process_blocks(blocks, src_path, image_path, cfg) has_inline_plots = any(cfg.plot2rst_plot_tag in b[2] for b in blocks) if has_inline_plots: example_rst = ''.join([rst_link, rst]) else: # print first block of text, display all plots, then display code. first_text_block = [b for b in blocks if b[0] == 'text'][0] label, (start, end), content = first_text_block figure_list = save_all_figures(image_path) rst_blocks = [IMAGE_TEMPLATE % f.lstrip('/') for f in figure_list] example_rst = rst_link example_rst += eval(content) example_rst += ''.join(rst_blocks) code_info = dict(src_name=src_name, code_start=end) example_rst += LITERALINCLUDE.format(**code_info) example_rst += CODE_LINK.format(src_name) ipnotebook_name = src_name.replace('.py', '.ipynb') ipnotebook_name = './notebook/' + ipnotebook_name example_rst += NOTEBOOK_LINK.format(ipnotebook_name) f = open(rst_path, 'w') f.write(example_rst) f.flush() thumb_path = thumb_dir.pjoin(src_name[:-3] + '.png') first_image_file = image_dir.pjoin(figure_list[0].lstrip('/')) if first_image_file.exists: first_image = io.imread(first_image_file) save_thumbnail(first_image, thumb_path, cfg.plot2rst_thumb_shape) if not thumb_path.exists: if cfg.plot2rst_default_thumb is None: print("WARNING: No plots found and default thumbnail not defined.") print("Specify 'plot2rst_default_thumb' in Sphinx config file.") else: shutil.copy(cfg.plot2rst_default_thumb, thumb_path) # Export example to IPython notebook nb = Notebook() # Add sphinx roles to the examples, otherwise docutils # cannot compile the ReST for the notebook sphinx_roles = PythonDomain.roles.keys() preamble = '\n'.join('.. role:: py:{0}(literal)\n'.format(role) for role in sphinx_roles) # Grab all references to inject them in cells where needed ref_regexp = re.compile('\n(\.\. \[(\d+)\].*(?:\n[ ]{7,8}.*)+)') math_role_regexp = re.compile(':math:`(.*?)`') text = '\n'.join((content for (cell_type, _, content) in blocks if cell_type != 'code')) references = re.findall(ref_regexp, text) for (cell_type, _, content) in blocks: if cell_type == 'code': nb.add_cell(content, cell_type='code') else: if content.startswith('r'): content = content.replace('r"""', '') escaped = False else: content = content.replace('"""', '') escaped = True if not escaped: content = content.replace("\\", "\\\\") content = content.replace('.. seealso::', '**See also:**') content = re.sub(math_role_regexp, r'$\1$', content) # Remove math directive when rendering notebooks # until we implement a smarter way of capturing and replacing # its content content = content.replace('.. math::', '') if not content.strip(): continue content = (preamble + content).rstrip('\n') content = '\n'.join([line for line in content.split('\n') if not line.startswith('.. image')]) # Remove reference links until we can figure out a better way to # preserve them for (reference, ref_id) in references: ref_tag = '[{0}]_'.format(ref_id) if ref_tag in content: content = content.replace(ref_tag, ref_tag[:-1]) html = publish_parts(content, writer_name='html')['html_body'] nb.add_cell(html, cell_type='markdown') with open(notebook_path, 'w') as f: f.write(nb.json()) def save_thumbnail(image, thumb_path, shape): """Save image as a thumbnail with the specified shape. The image is first resized to fit within the specified shape and then centered in an array of the specified shape before saving. """ rescale = min(float(w_1) / w_2 for w_1, w_2 in zip(shape, image.shape)) small_shape = (rescale * np.asarray(image.shape[:2])).astype(int) small_image = transform.resize(image, small_shape) if len(image.shape) == 3: shape = shape + (image.shape[2],) background_value = dtype_range[small_image.dtype.type][1] thumb = background_value * np.ones(shape, dtype=small_image.dtype) i = (shape[0] - small_shape[0]) // 2 j = (shape[1] - small_shape[1]) // 2 thumb[i:i+small_shape[0], j:j+small_shape[1]] = small_image io.imsave(thumb_path, thumb) def _plots_are_current(src_path, image_path): first_image_file = Path(image_path.format(1)) needs_replot = (not first_image_file.exists or _mod_time(first_image_file) <= _mod_time(src_path)) return not needs_replot def _mod_time(file_path): return os.stat(file_path).st_mtime def split_code_and_text_blocks(source_file): """Return list with source file separated into code and text blocks. Returns ------- blocks : list of (label, (start, end+1), content) List where each element is a tuple with the label ('text' or 'code'), the (start, end+1) line numbers, and content string of block. """ block_edges, idx_first_text_block = get_block_edges(source_file) with open(source_file) as f: source_lines = f.readlines() # Every other block should be a text block idx_text_block = np.arange(idx_first_text_block, len(block_edges), 2) blocks = [] slice_ranges = zip(block_edges[:-1], block_edges[1:]) for i, (start, end) in enumerate(slice_ranges): block_label = 'text' if i in idx_text_block else 'code' # subtract 1 from indices b/c line numbers start at 1, not 0 content = ''.join(source_lines[start-1:end-1]) blocks.append((block_label, (start, end), content)) return blocks def get_block_edges(source_file): """Return starting line numbers of code and text blocks Returns ------- block_edges : list of int Line number for the start of each block. Note the idx_first_text_block : {0 | 1} 0 if first block is text then, else 1 (second block better be text). """ block_edges = [] with open(source_file) as f: token_iter = tokenize.generate_tokens(f.readline) for token_tuple in token_iter: t_id, t_str, (srow, scol), (erow, ecol), src_line = token_tuple if (token.tok_name[t_id] == 'STRING' and scol == 0): # Add one point to line after text (for later slicing) block_edges.extend((srow, erow+1)) idx_first_text_block = 0 # when example doesn't start with text block. if not block_edges[0] == 1: block_edges.insert(0, 1) idx_first_text_block = 1 # when example doesn't end with text block. if not block_edges[-1] == erow: # iffy: I'm using end state of loop block_edges.append(erow) return block_edges, idx_first_text_block def process_blocks(blocks, src_path, image_path, cfg): """Run source, save plots as images, and convert blocks to rst. Parameters ---------- blocks : list of block tuples Code and text blocks from example. See `split_code_and_text_blocks`. src_path : str Path to example file. image_path : str Path where plots are saved (format string which accepts figure number). cfg : config object Sphinx config object created by Sphinx. Returns ------- figure_list : list List of figure names saved by the example. rst_text : str Text with code wrapped code-block directives. """ src_dir, src_name = src_path.psplit() if not src_name.startswith('plot'): return [], '' # index of blocks which have inline plots inline_tag = cfg.plot2rst_plot_tag idx_inline_plot = [i for i, b in enumerate(blocks) if inline_tag in b[2]] image_dir, image_fmt_str = image_path.psplit() figure_list = [] plt.rcdefaults() plt.rcParams.update(cfg.plot2rst_rcparams) plt.close('all') example_globals = {} rst_blocks = [] fig_num = 1 for i, (blabel, brange, bcontent) in enumerate(blocks): if blabel == 'code': exec(bcontent, example_globals) rst_blocks.append(codestr2rst(bcontent)) else: if i in idx_inline_plot: plt.savefig(image_path.format(fig_num)) figure_name = image_fmt_str.format(fig_num) fig_num += 1 figure_list.append(figure_name) figure_link = os.path.join('images', figure_name) bcontent = bcontent.replace(inline_tag, figure_link) rst_blocks.append(docstr2rst(bcontent)) return figure_list, '\n'.join(rst_blocks) def codestr2rst(codestr): """Return reStructuredText code block from code string""" code_directive = ".. code-block:: python\n\n" indented_block = '\t' + codestr.replace('\n', '\n\t') return code_directive + indented_block def docstr2rst(docstr): """Return reStructuredText from docstring""" idx_whitespace = len(docstr.rstrip()) - len(docstr) whitespace = docstr[idx_whitespace:] return eval(docstr) + whitespace def save_all_figures(image_path): """Save all matplotlib figures. Parameters ---------- image_path : str Path where plots are saved (format string which accepts figure number). """ figure_list = [] image_dir, image_fmt_str = image_path.psplit() fig_mngr = matplotlib._pylab_helpers.Gcf.get_all_fig_managers() for fig_num in (m.num for m in fig_mngr): # Set the fig_num figure as the current figure as we can't # save a figure that's not the current figure. plt.figure(fig_num) plt.savefig(image_path.format(fig_num)) figure_list.append(image_fmt_str.format(fig_num)) return figure_list
bsd-3-clause
rvraghav93/scikit-learn
sklearn/learning_curve.py
8
15418
"""Utilities to evaluate models with respect to a variable """ # Author: Alexander Fabisch <[email protected]> # # License: BSD 3 clause import warnings import numpy as np from .base import is_classifier, clone from .cross_validation import check_cv from .externals.joblib import Parallel, delayed from .cross_validation import _safe_split, _score, _fit_and_score from .metrics.scorer import check_scoring from .utils import indexable warnings.warn("This module was deprecated in version 0.18 in favor of the " "model_selection module into which all the functions are moved." " This module will be removed in 0.20", DeprecationWarning) __all__ = ['learning_curve', 'validation_curve'] def learning_curve(estimator, X, y, train_sizes=np.linspace(0.1, 1.0, 5), cv=None, scoring=None, exploit_incremental_learning=False, n_jobs=1, pre_dispatch="all", verbose=0, error_score='raise'): """Learning curve. .. deprecated:: 0.18 This module will be removed in 0.20. Use :func:`sklearn.model_selection.learning_curve` instead. Determines cross-validated training and test scores for different training set sizes. A cross-validation generator splits the whole dataset k times in training and test data. Subsets of the training set with varying sizes will be used to train the estimator and a score for each training subset size and the test set will be computed. Afterwards, the scores will be averaged over all k runs for each training subset size. Read more in the :ref:`User Guide <learning_curves>`. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. train_sizes : array-like, shape (n_ticks,), dtype float or int Relative or absolute numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of the maximum size of the training set (that is determined by the selected validation method), i.e. it has to be within (0, 1]. Otherwise it is interpreted as absolute sizes of the training sets. Note that for classification the number of samples usually have to be big enough to contain at least one sample from each class. (default: np.linspace(0.1, 1.0, 5)) 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, if the estimator is a classifier and ``y`` is either binary or multiclass, :class:`sklearn.model_selection.StratifiedKFold` is used. In all other cases, :class:`sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. scoring : string, callable or None, optional, default: None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. exploit_incremental_learning : boolean, optional, default: False If the estimator supports incremental learning, this will be used to speed up fitting for different training set sizes. n_jobs : integer, optional Number of jobs to run in parallel (default 1). pre_dispatch : integer or string, optional Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The string can be an expression like '2*n_jobs'. verbose : integer, optional Controls the verbosity: the higher, the more messages. error_score : 'raise' (default) or numeric Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error. Returns ------- train_sizes_abs : array, shape = (n_unique_ticks,), dtype int Numbers of training examples that has been used to generate the learning curve. Note that the number of ticks might be less than n_ticks because duplicate entries will be removed. train_scores : array, shape (n_ticks, n_cv_folds) Scores on training sets. test_scores : array, shape (n_ticks, n_cv_folds) Scores on test set. Notes ----- See :ref:`examples/model_selection/plot_learning_curve.py <sphx_glr_auto_examples_model_selection_plot_learning_curve.py>` """ if exploit_incremental_learning and not hasattr(estimator, "partial_fit"): raise ValueError("An estimator must support the partial_fit interface " "to exploit incremental learning") X, y = indexable(X, y) # Make a list since we will be iterating multiple times over the folds cv = list(check_cv(cv, X, y, classifier=is_classifier(estimator))) scorer = check_scoring(estimator, scoring=scoring) # HACK as long as boolean indices are allowed in cv generators if cv[0][0].dtype == bool: new_cv = [] for i in range(len(cv)): new_cv.append((np.nonzero(cv[i][0])[0], np.nonzero(cv[i][1])[0])) cv = new_cv n_max_training_samples = len(cv[0][0]) # Because the lengths of folds can be significantly different, it is # not guaranteed that we use all of the available training data when we # use the first 'n_max_training_samples' samples. train_sizes_abs = _translate_train_sizes(train_sizes, n_max_training_samples) n_unique_ticks = train_sizes_abs.shape[0] if verbose > 0: print("[learning_curve] Training set sizes: " + str(train_sizes_abs)) parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, verbose=verbose) if exploit_incremental_learning: classes = np.unique(y) if is_classifier(estimator) else None out = parallel(delayed(_incremental_fit_estimator)( clone(estimator), X, y, classes, train, test, train_sizes_abs, scorer, verbose) for train, test in cv) else: out = parallel(delayed(_fit_and_score)( clone(estimator), X, y, scorer, train[:n_train_samples], test, verbose, parameters=None, fit_params=None, return_train_score=True, error_score=error_score) for train, test in cv for n_train_samples in train_sizes_abs) out = np.array(out)[:, :2] n_cv_folds = out.shape[0] // n_unique_ticks out = out.reshape(n_cv_folds, n_unique_ticks, 2) out = np.asarray(out).transpose((2, 1, 0)) return train_sizes_abs, out[0], out[1] def _translate_train_sizes(train_sizes, n_max_training_samples): """Determine absolute sizes of training subsets and validate 'train_sizes'. Examples: _translate_train_sizes([0.5, 1.0], 10) -> [5, 10] _translate_train_sizes([5, 10], 10) -> [5, 10] Parameters ---------- train_sizes : array-like, shape (n_ticks,), dtype float or int Numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of 'n_max_training_samples', i.e. it has to be within (0, 1]. n_max_training_samples : int Maximum number of training samples (upper bound of 'train_sizes'). Returns ------- train_sizes_abs : array, shape (n_unique_ticks,), dtype int Numbers of training examples that will be used to generate the learning curve. Note that the number of ticks might be less than n_ticks because duplicate entries will be removed. """ train_sizes_abs = np.asarray(train_sizes) n_ticks = train_sizes_abs.shape[0] n_min_required_samples = np.min(train_sizes_abs) n_max_required_samples = np.max(train_sizes_abs) if np.issubdtype(train_sizes_abs.dtype, np.float): if n_min_required_samples <= 0.0 or n_max_required_samples > 1.0: raise ValueError("train_sizes has been interpreted as fractions " "of the maximum number of training samples and " "must be within (0, 1], but is within [%f, %f]." % (n_min_required_samples, n_max_required_samples)) train_sizes_abs = (train_sizes_abs * n_max_training_samples).astype( dtype=np.int, copy=False) train_sizes_abs = np.clip(train_sizes_abs, 1, n_max_training_samples) else: if (n_min_required_samples <= 0 or n_max_required_samples > n_max_training_samples): raise ValueError("train_sizes has been interpreted as absolute " "numbers of training samples and must be within " "(0, %d], but is within [%d, %d]." % (n_max_training_samples, n_min_required_samples, n_max_required_samples)) train_sizes_abs = np.unique(train_sizes_abs) if n_ticks > train_sizes_abs.shape[0]: warnings.warn("Removed duplicate entries from 'train_sizes'. Number " "of ticks will be less than the size of " "'train_sizes' %d instead of %d)." % (train_sizes_abs.shape[0], n_ticks), RuntimeWarning) return train_sizes_abs def _incremental_fit_estimator(estimator, X, y, classes, train, test, train_sizes, scorer, verbose): """Train estimator on training subsets incrementally and compute scores.""" train_scores, test_scores = [], [] partitions = zip(train_sizes, np.split(train, train_sizes)[:-1]) for n_train_samples, partial_train in partitions: train_subset = train[:n_train_samples] X_train, y_train = _safe_split(estimator, X, y, train_subset) X_partial_train, y_partial_train = _safe_split(estimator, X, y, partial_train) X_test, y_test = _safe_split(estimator, X, y, test, train_subset) if y_partial_train is None: estimator.partial_fit(X_partial_train, classes=classes) else: estimator.partial_fit(X_partial_train, y_partial_train, classes=classes) train_scores.append(_score(estimator, X_train, y_train, scorer)) test_scores.append(_score(estimator, X_test, y_test, scorer)) return np.array((train_scores, test_scores)).T def validation_curve(estimator, X, y, param_name, param_range, cv=None, scoring=None, n_jobs=1, pre_dispatch="all", verbose=0): """Validation curve. .. deprecated:: 0.18 This module will be removed in 0.20. Use :func:`sklearn.model_selection.validation_curve` instead. Determine training and test scores for varying parameter values. Compute scores for an estimator with different values of a specified parameter. This is similar to grid search with one parameter. However, this will also compute training scores and is merely a utility for plotting the results. Read more in the :ref:`User Guide <validation_curve>`. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. param_name : string Name of the parameter that will be varied. param_range : array-like, shape (n_values,) The values of the parameter that will be evaluated. 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, if the estimator is a classifier and ``y`` is either binary or multiclass, :class:`sklearn.model_selection.StratifiedKFold` is used. In all other cases, :class:`sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. scoring : string, callable or None, optional, default: None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. n_jobs : integer, optional Number of jobs to run in parallel (default 1). pre_dispatch : integer or string, optional Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The string can be an expression like '2*n_jobs'. verbose : integer, optional Controls the verbosity: the higher, the more messages. Returns ------- train_scores : array, shape (n_ticks, n_cv_folds) Scores on training sets. test_scores : array, shape (n_ticks, n_cv_folds) Scores on test set. Notes ----- See :ref:`examples/model_selection/plot_validation_curve.py <sphx_glr_auto_examples_model_selection_plot_validation_curve.py>` """ X, y = indexable(X, y) cv = check_cv(cv, X, y, classifier=is_classifier(estimator)) scorer = check_scoring(estimator, scoring=scoring) parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, verbose=verbose) out = parallel(delayed(_fit_and_score)( clone(estimator), X, y, scorer, train, test, verbose, parameters={param_name: v}, fit_params=None, return_train_score=True) for train, test in cv for v in param_range) out = np.asarray(out)[:, :2] n_params = len(param_range) n_cv_folds = out.shape[0] // n_params out = out.reshape(n_cv_folds, n_params, 2).transpose((2, 1, 0)) return out[0], out[1]
bsd-3-clause
drix00/microanalysis_file_format
pySpectrumFileFormat/OxfordInstruments/MapRaw/MapRawFormat.py
1
7049
#!/usr/bin/env python # -*- coding: utf-8 -*- """ .. py:currentmodule:: OxfordInstruments.MapRaw.MapRawFormat :synopsis: Read Oxford Instruments map in the raw format. .. moduleauthor:: Hendrix Demers <[email protected]> Read Oxford Instruments map in the raw format. """ ############################################################################### # Copyright 2012 Hendrix Demers # # 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. ############################################################################### # Standard library modules. import os.path import struct import logging # Third party modules. import matplotlib.pyplot as plt import numpy as np # Local modules. # Project modules. import pySpectrumFileFormat.OxfordInstruments.MapRaw.ParametersFile as ParametersFile # Globals and constants variables. class MapRawFormat(object): def __init__(self, rawFilepath): logging.info("Raw file: %s", rawFilepath) self._rawFilepath = rawFilepath parametersFilepath = self._rawFilepath.replace('.raw', '.rpl') self._parameters = ParametersFile.ParametersFile() self._parameters.read(parametersFilepath) self._format = self._generateFormat(self._parameters) def _generateFormat(self, parameters): spectrumFormat = "" if parameters.byteOrder == ParametersFile.BYTE_ORDER_LITTLE_ENDIAN: spectrumFormat += '<' if parameters.dataLength_B == 1: if parameters.dataType == ParametersFile.DATA_TYPE_SIGNED: spectrumFormat += "b" elif parameters.dataType == ParametersFile.DATA_TYPE_UNSIGNED: spectrumFormat += "B" elif parameters.dataLength_B == 2: if parameters.dataType == ParametersFile.DATA_TYPE_SIGNED: spectrumFormat += "h" elif parameters.dataType == ParametersFile.DATA_TYPE_UNSIGNED: spectrumFormat += "H" elif parameters.dataLength_B == 4: if parameters.dataType == ParametersFile.DATA_TYPE_SIGNED: spectrumFormat += "i" elif parameters.dataType == ParametersFile.DATA_TYPE_UNSIGNED: spectrumFormat += "I" logging.info("Format: %s", spectrumFormat) return spectrumFormat def _generateSumSpectraFormat(self, parameters): spectrumFormat = "" if parameters.byteOrder == ParametersFile.BYTE_ORDER_LITTLE_ENDIAN: spectrumFormat += '<' spectrumFormat += '%i' % (parameters.width*parameters.height) if parameters.dataLength_B == 1: if parameters.dataType == ParametersFile.DATA_TYPE_SIGNED: spectrumFormat += "b" elif parameters.dataType == ParametersFile.DATA_TYPE_UNSIGNED: spectrumFormat += "B" elif parameters.dataLength_B == 2: if parameters.dataType == ParametersFile.DATA_TYPE_SIGNED: spectrumFormat += "h" elif parameters.dataType == ParametersFile.DATA_TYPE_UNSIGNED: spectrumFormat += "H" elif parameters.dataLength_B == 4: if parameters.dataType == ParametersFile.DATA_TYPE_SIGNED: spectrumFormat += "i" elif parameters.dataType == ParametersFile.DATA_TYPE_UNSIGNED: spectrumFormat += "I" logging.info("Format: %s", spectrumFormat) return spectrumFormat def getSpectrum(self, pixelId): logging.debug("Pixel ID: %i", pixelId) imageOffset = self._parameters.width*self._parameters.height logging.debug("File offset: %i", imageOffset) logging.debug("Size: %i", struct.calcsize(self._format)) x = np.arange(0, self._parameters.depth) y = np.zeros_like(x) rawFile = open(self._rawFilepath, 'rb') for channel in range(self._parameters.depth): fileOffset = self._parameters.offset + (pixelId + channel*imageOffset)*self._parameters.dataLength_B rawFile.seek(fileOffset) fileBuffer = rawFile.read(struct.calcsize(self._format)) items = struct.unpack(self._format, fileBuffer) y[channel] = float(items[0]) rawFile.close() return x, y def getSumSpectrum(self): imageOffset = self._parameters.width*self._parameters.height x = np.arange(0, self._parameters.depth) y = np.zeros_like(x) rawFile = open(self._rawFilepath, 'rb') fileOffset = self._parameters.offset rawFile.seek(fileOffset) sumSpectrumformat = self._generateSumSpectraFormat(self._parameters) for channel in range(self._parameters.depth): logging.info("Channel: %i", channel) fileBuffer = rawFile.read(struct.calcsize(sumSpectrumformat)) items = struct.unpack(sumSpectrumformat, fileBuffer) y[channel] = np.sum(items) rawFile.close() return x, y def getSumSpectrumOld(self): numberPixels = self._parameters.width*self._parameters.height logging.info("Numbe rof pixels: %i", numberPixels) x = np.arange(0, self._parameters.depth) ySum = np.zeros_like(x) for pixelId in range(numberPixels): _x, y = self.getSpectrum(pixelId) ySum += y return x, ySum def run(): path = r"J:\hdemers\work\mcgill2012\results\experimental\McGill\su8000\others\exampleEDS" #filename = "Map30kV.raw" filename = "Project 1.raw" filepath = os.path.join(path, filename) mapRaw = MapRawFormat(filepath) line = 150 column = 150 pixelId = line + column*512 xData, yData = mapRaw.getSpectrum(pixelId=pixelId) plt.figure() plt.plot(xData, yData) xData, yData = mapRaw.getSumSpectrum() plt.figure() plt.plot(xData, yData) plt.show() def run20120307(): path = r"J:\hdemers\work\mcgill2012\results\experimental\McGill\su8000\hdemers\20120307\rareearthSample" filename = "mapSOI_15.raw" filepath = os.path.join(path, filename) mapRaw = MapRawFormat(filepath) line = 150 column = 150 pixelId = line + column*512 xData, yData = mapRaw.getSpectrum(pixelId=pixelId) plt.figure() plt.plot(xData, yData) plt.show() if __name__ == '__main__': # pragma: no cover run()
apache-2.0
dssg/wikienergy
disaggregator/build/pandas/pandas/tseries/resample.py
1
16718
from datetime import timedelta import numpy as np from pandas.core.groupby import BinGrouper, Grouper from pandas.tseries.frequencies import to_offset, is_subperiod, is_superperiod from pandas.tseries.index import DatetimeIndex, date_range from pandas.tseries.tdi import TimedeltaIndex from pandas.tseries.offsets import DateOffset, Tick, Day, _delta_to_nanoseconds from pandas.tseries.period import PeriodIndex, period_range import pandas.tseries.tools as tools import pandas.core.common as com import pandas.compat as compat from pandas.lib import Timestamp import pandas.lib as lib import pandas.tslib as tslib _DEFAULT_METHOD = 'mean' class TimeGrouper(Grouper): """ Custom groupby class for time-interval grouping Parameters ---------- freq : pandas date offset or offset alias for identifying bin edges closed : closed end of interval; left or right label : interval boundary to use for labeling; left or right nperiods : optional, integer convention : {'start', 'end', 'e', 's'} If axis is PeriodIndex Notes ----- Use begin, end, nperiods to generate intervals that cannot be derived directly from the associated object """ def __init__(self, freq='Min', closed=None, label=None, how='mean', nperiods=None, axis=0, fill_method=None, limit=None, loffset=None, kind=None, convention=None, base=0, **kwargs): freq = to_offset(freq) end_types = set(['M', 'A', 'Q', 'BM', 'BA', 'BQ', 'W']) rule = freq.rule_code if (rule in end_types or ('-' in rule and rule[:rule.find('-')] in end_types)): if closed is None: closed = 'right' if label is None: label = 'right' else: if closed is None: closed = 'left' if label is None: label = 'left' self.closed = closed self.label = label self.nperiods = nperiods self.kind = kind self.convention = convention or 'E' self.convention = self.convention.lower() self.loffset = loffset self.how = how self.fill_method = fill_method self.limit = limit self.base = base # always sort time groupers kwargs['sort'] = True super(TimeGrouper, self).__init__(freq=freq, axis=axis, **kwargs) def resample(self, obj): self._set_grouper(obj, sort=True) ax = self.grouper if isinstance(ax, DatetimeIndex): rs = self._resample_timestamps() elif isinstance(ax, PeriodIndex): offset = to_offset(self.freq) if offset.n > 1: if self.kind == 'period': # pragma: no cover print('Warning: multiple of frequency -> timestamps') # Cannot have multiple of periods, convert to timestamp self.kind = 'timestamp' if self.kind is None or self.kind == 'period': rs = self._resample_periods() else: obj = self.obj.to_timestamp(how=self.convention) self._set_grouper(obj) rs = self._resample_timestamps() elif isinstance(ax, TimedeltaIndex): rs = self._resample_timestamps(kind='timedelta') elif len(ax) == 0: return self.obj else: # pragma: no cover raise TypeError('Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex') rs_axis = rs._get_axis(self.axis) rs_axis.name = ax.name return rs def _get_grouper(self, obj): self._set_grouper(obj) return self._get_binner_for_resample() def _get_binner_for_resample(self, kind=None): # create the BinGrouper # assume that self.set_grouper(obj) has already been called ax = self.ax if kind is None: kind = self.kind if kind is None or kind == 'timestamp': self.binner, bins, binlabels = self._get_time_bins(ax) elif kind == 'timedelta': self.binner, bins, binlabels = self._get_time_delta_bins(ax) else: self.binner, bins, binlabels = self._get_time_period_bins(ax) self.grouper = BinGrouper(bins, binlabels) return self.binner, self.grouper, self.obj def _get_binner_for_grouping(self, obj): # return an ordering of the transformed group labels, # suitable for multi-grouping, e.g the labels for # the resampled intervals ax = self._set_grouper(obj) self._get_binner_for_resample() # create the grouper binner = self.binner l = [] for key, group in self.grouper.get_iterator(ax): l.extend([key]*len(group)) grouper = binner.__class__(l,freq=binner.freq,name=binner.name) # since we may have had to sort # may need to reorder groups here if self.indexer is not None: indexer = self.indexer.argsort(kind='quicksort') grouper = grouper.take(indexer) return grouper def _get_time_bins(self, ax): if not isinstance(ax, DatetimeIndex): raise TypeError('axis must be a DatetimeIndex, but got ' 'an instance of %r' % type(ax).__name__) if len(ax) == 0: binner = labels = DatetimeIndex(data=[], freq=self.freq, name=ax.name) return binner, [], labels first, last = ax.min(), ax.max() first, last = _get_range_edges(first, last, self.freq, closed=self.closed, base=self.base) tz = ax.tz binner = labels = DatetimeIndex(freq=self.freq, start=first.replace(tzinfo=None), end=last.replace(tzinfo=None), tz=tz, name=ax.name) # a little hack trimmed = False if (len(binner) > 2 and binner[-2] == last and self.closed == 'right'): binner = binner[:-1] trimmed = True ax_values = ax.asi8 binner, bin_edges = self._adjust_bin_edges(binner, ax_values) # general version, knowing nothing about relative frequencies bins = lib.generate_bins_dt64(ax_values, bin_edges, self.closed, hasnans=ax.hasnans) if self.closed == 'right': labels = binner if self.label == 'right': labels = labels[1:] elif not trimmed: labels = labels[:-1] else: if self.label == 'right': labels = labels[1:] elif not trimmed: labels = labels[:-1] if ax.hasnans: binner = binner.insert(0, tslib.NaT) labels = labels.insert(0, tslib.NaT) # if we end up with more labels than bins # adjust the labels # GH4076 if len(bins) < len(labels): labels = labels[:len(bins)] return binner, bins, labels def _adjust_bin_edges(self, binner, ax_values): # Some hacks for > daily data, see #1471, #1458, #1483 bin_edges = binner.asi8 if self.freq != 'D' and is_superperiod(self.freq, 'D'): day_nanos = _delta_to_nanoseconds(timedelta(1)) if self.closed == 'right': bin_edges = bin_edges + day_nanos - 1 # intraday values on last day if bin_edges[-2] > ax_values.max(): bin_edges = bin_edges[:-1] binner = binner[:-1] return binner, bin_edges def _get_time_delta_bins(self, ax): if not isinstance(ax, TimedeltaIndex): raise TypeError('axis must be a TimedeltaIndex, but got ' 'an instance of %r' % type(ax).__name__) if not len(ax): binner = labels = TimedeltaIndex(data=[], freq=self.freq, name=ax.name) return binner, [], labels labels = binner = TimedeltaIndex(start=ax[0], end=ax[-1], freq=self.freq, name=ax.name) end_stamps = labels + 1 bins = ax.searchsorted(end_stamps, side='left') return binner, bins, labels def _get_time_period_bins(self, ax): if not isinstance(ax, DatetimeIndex): raise TypeError('axis must be a DatetimeIndex, but got ' 'an instance of %r' % type(ax).__name__) if not len(ax): binner = labels = PeriodIndex(data=[], freq=self.freq, name=ax.name) return binner, [], labels labels = binner = PeriodIndex(start=ax[0], end=ax[-1], freq=self.freq, name=ax.name) end_stamps = (labels + 1).asfreq(self.freq, 's').to_timestamp() if ax.tzinfo: end_stamps = end_stamps.tz_localize(ax.tzinfo) bins = ax.searchsorted(end_stamps, side='left') return binner, bins, labels @property def _agg_method(self): return self.how if self.how else _DEFAULT_METHOD def _resample_timestamps(self, kind=None): # assumes set_grouper(obj) already called axlabels = self.ax self._get_binner_for_resample(kind=kind) grouper = self.grouper binner = self.binner obj = self.obj # Determine if we're downsampling if axlabels.freq is not None or axlabels.inferred_freq is not None: if len(grouper.binlabels) < len(axlabels) or self.how is not None: # downsample grouped = obj.groupby(grouper, axis=self.axis) result = grouped.aggregate(self._agg_method) # GH2073 if self.fill_method is not None: result = result.fillna(method=self.fill_method, limit=self.limit) else: # upsampling shortcut if self.axis: raise AssertionError('axis must be 0') if self.closed == 'right': res_index = binner[1:] else: res_index = binner[:-1] # if we have the same frequency as our axis, then we are equal sampling # even if how is None if self.fill_method is None and self.limit is None and to_offset( axlabels.inferred_freq) == self.freq: result = obj.copy() result.index = res_index else: result = obj.reindex(res_index, method=self.fill_method, limit=self.limit) else: # Irregular data, have to use groupby grouped = obj.groupby(grouper, axis=self.axis) result = grouped.aggregate(self._agg_method) if self.fill_method is not None: result = result.fillna(method=self.fill_method, limit=self.limit) loffset = self.loffset if isinstance(loffset, compat.string_types): loffset = to_offset(self.loffset) if isinstance(loffset, (DateOffset, timedelta)): if (isinstance(result.index, DatetimeIndex) and len(result.index) > 0): result.index = result.index + loffset return result def _resample_periods(self): # assumes set_grouper(obj) already called axlabels = self.ax obj = self.obj if len(axlabels) == 0: new_index = PeriodIndex(data=[], freq=self.freq) return obj.reindex(new_index) else: start = axlabels[0].asfreq(self.freq, how=self.convention) end = axlabels[-1].asfreq(self.freq, how='end') new_index = period_range(start, end, freq=self.freq) # Start vs. end of period memb = axlabels.asfreq(self.freq, how=self.convention) if is_subperiod(axlabels.freq, self.freq) or self.how is not None: # Downsampling rng = np.arange(memb.values[0], memb.values[-1] + 1) bins = memb.searchsorted(rng, side='right') grouper = BinGrouper(bins, new_index) grouped = obj.groupby(grouper, axis=self.axis) return grouped.aggregate(self._agg_method) elif is_superperiod(axlabels.freq, self.freq): # Get the fill indexer indexer = memb.get_indexer(new_index, method=self.fill_method, limit=self.limit) return _take_new_index(obj, indexer, new_index, axis=self.axis) else: raise ValueError('Frequency %s cannot be resampled to %s' % (axlabels.freq, self.freq)) def _take_new_index(obj, indexer, new_index, axis=0): from pandas.core.api import Series, DataFrame if isinstance(obj, Series): new_values = com.take_1d(obj.values, indexer) return Series(new_values, index=new_index, name=obj.name) elif isinstance(obj, DataFrame): if axis == 1: raise NotImplementedError return DataFrame(obj._data.reindex_indexer( new_axis=new_index, indexer=indexer, axis=1)) else: raise NotImplementedError def _get_range_edges(first, last, offset, closed='left', base=0): if isinstance(offset, compat.string_types): offset = to_offset(offset) if isinstance(offset, Tick): is_day = isinstance(offset, Day) day_nanos = _delta_to_nanoseconds(timedelta(1)) # #1165 if (is_day and day_nanos % offset.nanos == 0) or not is_day: return _adjust_dates_anchored(first, last, offset, closed=closed, base=base) if not isinstance(offset, Tick): # and first.time() != last.time(): # hack! first = tools.normalize_date(first) last = tools.normalize_date(last) if closed == 'left': first = Timestamp(offset.rollback(first)) else: first = Timestamp(first - offset) last = Timestamp(last + offset) return first, last def _adjust_dates_anchored(first, last, offset, closed='right', base=0): from pandas.tseries.tools import normalize_date # First and last offsets should be calculated from the start day to fix an # error cause by resampling across multiple days when a one day period is # not a multiple of the frequency. # # See https://github.com/pydata/pandas/issues/8683 start_day_nanos = Timestamp(normalize_date(first)).value base_nanos = (base % offset.n) * offset.nanos // offset.n start_day_nanos += base_nanos foffset = (first.value - start_day_nanos) % offset.nanos loffset = (last.value - start_day_nanos) % offset.nanos if closed == 'right': if foffset > 0: # roll back fresult = first.value - foffset else: fresult = first.value - offset.nanos if loffset > 0: # roll forward lresult = last.value + (offset.nanos - loffset) else: # already the end of the road lresult = last.value else: # closed == 'left' if foffset > 0: fresult = first.value - foffset else: # start of the road fresult = first.value if loffset > 0: # roll forward lresult = last.value + (offset.nanos - loffset) else: lresult = last.value + offset.nanos return (Timestamp(fresult, tz=first.tz), Timestamp(lresult, tz=last.tz)) def asfreq(obj, freq, method=None, how=None, normalize=False): """ Utility frequency conversion method for Series/DataFrame """ if isinstance(obj.index, PeriodIndex): if method is not None: raise NotImplementedError if how is None: how = 'E' new_index = obj.index.asfreq(freq, how=how) new_obj = obj.copy() new_obj.index = new_index return new_obj else: if len(obj.index) == 0: return obj.copy() dti = date_range(obj.index[0], obj.index[-1], freq=freq) rs = obj.reindex(dti, method=method) if normalize: rs.index = rs.index.normalize() return rs
mit
imaculate/scikit-learn
examples/applications/plot_out_of_core_classification.py
32
13829
""" ====================================================== Out-of-core classification of text documents ====================================================== This is an example showing how scikit-learn can be used for classification using an out-of-core approach: learning from data that doesn't fit into main memory. We make use of an online classifier, i.e., one that supports the partial_fit method, that will be fed with batches of examples. To guarantee that the features space remains the same over time we leverage a HashingVectorizer that will project each example into the same feature space. This is especially useful in the case of text classification where new features (words) may appear in each batch. The dataset used in this example is Reuters-21578 as provided by the UCI ML repository. It will be automatically downloaded and uncompressed on first run. The plot represents the learning curve of the classifier: the evolution of classification accuracy over the course of the mini-batches. Accuracy is measured on the first 1000 samples, held out as a validation set. To limit the memory consumption, we queue examples up to a fixed amount before feeding them to the learner. """ # Authors: Eustache Diemert <[email protected]> # @FedericoV <https://github.com/FedericoV/> # License: BSD 3 clause from __future__ import print_function from glob import glob import itertools import os.path import re import tarfile import time import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams from sklearn.externals.six.moves import html_parser from sklearn.externals.six.moves import urllib from sklearn.datasets import get_data_home from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.linear_model import PassiveAggressiveClassifier from sklearn.linear_model import Perceptron from sklearn.naive_bayes import MultinomialNB def _not_in_sphinx(): # Hack to detect whether we are running by the sphinx builder return '__file__' in globals() ############################################################################### # Reuters Dataset related routines ############################################################################### class ReutersParser(html_parser.HTMLParser): """Utility class to parse a SGML file and yield documents one at a time.""" def __init__(self, encoding='latin-1'): html_parser.HTMLParser.__init__(self) self._reset() self.encoding = encoding def handle_starttag(self, tag, attrs): method = 'start_' + tag getattr(self, method, lambda x: None)(attrs) def handle_endtag(self, tag): method = 'end_' + tag getattr(self, method, lambda: None)() def _reset(self): self.in_title = 0 self.in_body = 0 self.in_topics = 0 self.in_topic_d = 0 self.title = "" self.body = "" self.topics = [] self.topic_d = "" def parse(self, fd): self.docs = [] for chunk in fd: self.feed(chunk.decode(self.encoding)) for doc in self.docs: yield doc self.docs = [] self.close() def handle_data(self, data): if self.in_body: self.body += data elif self.in_title: self.title += data elif self.in_topic_d: self.topic_d += data def start_reuters(self, attributes): pass def end_reuters(self): self.body = re.sub(r'\s+', r' ', self.body) self.docs.append({'title': self.title, 'body': self.body, 'topics': self.topics}) self._reset() def start_title(self, attributes): self.in_title = 1 def end_title(self): self.in_title = 0 def start_body(self, attributes): self.in_body = 1 def end_body(self): self.in_body = 0 def start_topics(self, attributes): self.in_topics = 1 def end_topics(self): self.in_topics = 0 def start_d(self, attributes): self.in_topic_d = 1 def end_d(self): self.in_topic_d = 0 self.topics.append(self.topic_d) self.topic_d = "" def stream_reuters_documents(data_path=None): """Iterate over documents of the Reuters dataset. The Reuters archive will automatically be downloaded and uncompressed if the `data_path` directory does not exist. Documents are represented as dictionaries with 'body' (str), 'title' (str), 'topics' (list(str)) keys. """ DOWNLOAD_URL = ('http://archive.ics.uci.edu/ml/machine-learning-databases/' 'reuters21578-mld/reuters21578.tar.gz') ARCHIVE_FILENAME = 'reuters21578.tar.gz' if data_path is None: data_path = os.path.join(get_data_home(), "reuters") if not os.path.exists(data_path): """Download the dataset.""" print("downloading dataset (once and for all) into %s" % data_path) os.mkdir(data_path) def progress(blocknum, bs, size): total_sz_mb = '%.2f MB' % (size / 1e6) current_sz_mb = '%.2f MB' % ((blocknum * bs) / 1e6) if _not_in_sphinx(): print('\rdownloaded %s / %s' % (current_sz_mb, total_sz_mb), end='') archive_path = os.path.join(data_path, ARCHIVE_FILENAME) urllib.request.urlretrieve(DOWNLOAD_URL, filename=archive_path, reporthook=progress) if _not_in_sphinx(): print('\r', end='') print("untarring Reuters dataset...") tarfile.open(archive_path, 'r:gz').extractall(data_path) print("done.") parser = ReutersParser() for filename in glob(os.path.join(data_path, "*.sgm")): for doc in parser.parse(open(filename, 'rb')): yield doc ############################################################################### # Main ############################################################################### # Create the vectorizer and limit the number of features to a reasonable # maximum vectorizer = HashingVectorizer(decode_error='ignore', n_features=2 ** 18, non_negative=True) # Iterator over parsed Reuters SGML files. data_stream = stream_reuters_documents() # We learn a binary classification between the "acq" class and all the others. # "acq" was chosen as it is more or less evenly distributed in the Reuters # files. For other datasets, one should take care of creating a test set with # a realistic portion of positive instances. all_classes = np.array([0, 1]) positive_class = 'acq' # Here are some classifiers that support the `partial_fit` method partial_fit_classifiers = { 'SGD': SGDClassifier(), 'Perceptron': Perceptron(), 'NB Multinomial': MultinomialNB(alpha=0.01), 'Passive-Aggressive': PassiveAggressiveClassifier(), } def get_minibatch(doc_iter, size, pos_class=positive_class): """Extract a minibatch of examples, return a tuple X_text, y. Note: size is before excluding invalid docs with no topics assigned. """ data = [(u'{title}\n\n{body}'.format(**doc), pos_class in doc['topics']) for doc in itertools.islice(doc_iter, size) if doc['topics']] if not len(data): return np.asarray([], dtype=int), np.asarray([], dtype=int) X_text, y = zip(*data) return X_text, np.asarray(y, dtype=int) def iter_minibatches(doc_iter, minibatch_size): """Generator of minibatches.""" X_text, y = get_minibatch(doc_iter, minibatch_size) while len(X_text): yield X_text, y X_text, y = get_minibatch(doc_iter, minibatch_size) # test data statistics test_stats = {'n_test': 0, 'n_test_pos': 0} # First we hold out a number of examples to estimate accuracy n_test_documents = 1000 tick = time.time() X_test_text, y_test = get_minibatch(data_stream, 1000) parsing_time = time.time() - tick tick = time.time() X_test = vectorizer.transform(X_test_text) vectorizing_time = time.time() - tick test_stats['n_test'] += len(y_test) test_stats['n_test_pos'] += sum(y_test) print("Test set is %d documents (%d positive)" % (len(y_test), sum(y_test))) def progress(cls_name, stats): """Report progress information, return a string.""" duration = time.time() - stats['t0'] s = "%20s classifier : \t" % cls_name s += "%(n_train)6d train docs (%(n_train_pos)6d positive) " % stats s += "%(n_test)6d test docs (%(n_test_pos)6d positive) " % test_stats s += "accuracy: %(accuracy).3f " % stats s += "in %.2fs (%5d docs/s)" % (duration, stats['n_train'] / duration) return s cls_stats = {} for cls_name in partial_fit_classifiers: stats = {'n_train': 0, 'n_train_pos': 0, 'accuracy': 0.0, 'accuracy_history': [(0, 0)], 't0': time.time(), 'runtime_history': [(0, 0)], 'total_fit_time': 0.0} cls_stats[cls_name] = stats get_minibatch(data_stream, n_test_documents) # Discard test set # We will feed the classifier with mini-batches of 1000 documents; this means # we have at most 1000 docs in memory at any time. The smaller the document # batch, the bigger the relative overhead of the partial fit methods. minibatch_size = 1000 # Create the data_stream that parses Reuters SGML files and iterates on # documents as a stream. minibatch_iterators = iter_minibatches(data_stream, minibatch_size) total_vect_time = 0.0 # Main loop : iterate on mini-batches of examples for i, (X_train_text, y_train) in enumerate(minibatch_iterators): tick = time.time() X_train = vectorizer.transform(X_train_text) total_vect_time += time.time() - tick for cls_name, cls in partial_fit_classifiers.items(): tick = time.time() # update estimator with examples in the current mini-batch cls.partial_fit(X_train, y_train, classes=all_classes) # accumulate test accuracy stats cls_stats[cls_name]['total_fit_time'] += time.time() - tick cls_stats[cls_name]['n_train'] += X_train.shape[0] cls_stats[cls_name]['n_train_pos'] += sum(y_train) tick = time.time() cls_stats[cls_name]['accuracy'] = cls.score(X_test, y_test) cls_stats[cls_name]['prediction_time'] = time.time() - tick acc_history = (cls_stats[cls_name]['accuracy'], cls_stats[cls_name]['n_train']) cls_stats[cls_name]['accuracy_history'].append(acc_history) run_history = (cls_stats[cls_name]['accuracy'], total_vect_time + cls_stats[cls_name]['total_fit_time']) cls_stats[cls_name]['runtime_history'].append(run_history) if i % 3 == 0: print(progress(cls_name, cls_stats[cls_name])) if i % 3 == 0: print('\n') ############################################################################### # Plot results ############################################################################### def plot_accuracy(x, y, x_legend): """Plot accuracy as a function of x.""" x = np.array(x) y = np.array(y) plt.title('Classification accuracy as a function of %s' % x_legend) plt.xlabel('%s' % x_legend) plt.ylabel('Accuracy') plt.grid(True) plt.plot(x, y) rcParams['legend.fontsize'] = 10 cls_names = list(sorted(cls_stats.keys())) # Plot accuracy evolution plt.figure() for _, stats in sorted(cls_stats.items()): # Plot accuracy evolution with #examples accuracy, n_examples = zip(*stats['accuracy_history']) plot_accuracy(n_examples, accuracy, "training examples (#)") ax = plt.gca() ax.set_ylim((0.8, 1)) plt.legend(cls_names, loc='best') plt.figure() for _, stats in sorted(cls_stats.items()): # Plot accuracy evolution with runtime accuracy, runtime = zip(*stats['runtime_history']) plot_accuracy(runtime, accuracy, 'runtime (s)') ax = plt.gca() ax.set_ylim((0.8, 1)) plt.legend(cls_names, loc='best') # Plot fitting times plt.figure() fig = plt.gcf() cls_runtime = [] for cls_name, stats in sorted(cls_stats.items()): cls_runtime.append(stats['total_fit_time']) cls_runtime.append(total_vect_time) cls_names.append('Vectorization') bar_colors = ['b', 'g', 'r', 'c', 'm', 'y'] ax = plt.subplot(111) rectangles = plt.bar(range(len(cls_names)), cls_runtime, width=0.5, color=bar_colors) ax.set_xticks(np.linspace(0.25, len(cls_names) - 0.75, len(cls_names))) ax.set_xticklabels(cls_names, fontsize=10) ymax = max(cls_runtime) * 1.2 ax.set_ylim((0, ymax)) ax.set_ylabel('runtime (s)') ax.set_title('Training Times') def autolabel(rectangles): """attach some text vi autolabel on rectangles.""" for rect in rectangles: height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height, '%.4f' % height, ha='center', va='bottom') autolabel(rectangles) plt.show() # Plot prediction times plt.figure() cls_runtime = [] cls_names = list(sorted(cls_stats.keys())) for cls_name, stats in sorted(cls_stats.items()): cls_runtime.append(stats['prediction_time']) cls_runtime.append(parsing_time) cls_names.append('Read/Parse\n+Feat.Extr.') cls_runtime.append(vectorizing_time) cls_names.append('Hashing\n+Vect.') ax = plt.subplot(111) rectangles = plt.bar(range(len(cls_names)), cls_runtime, width=0.5, color=bar_colors) ax.set_xticks(np.linspace(0.25, len(cls_names) - 0.75, len(cls_names))) ax.set_xticklabels(cls_names, fontsize=8) plt.setp(plt.xticks()[1], rotation=30) ymax = max(cls_runtime) * 1.2 ax.set_ylim((0, ymax)) ax.set_ylabel('runtime (s)') ax.set_title('Prediction Times (%d instances)' % n_test_documents) autolabel(rectangles) plt.show()
bsd-3-clause
toomanycats/IndeedScraper
compare.py
1
4116
from sklearn.feature_extraction.text import CountVectorizer import indeed_scrape import GrammarParser import subprocess import numpy as np import logging import os from os import path import numpy as np data_dir = os.getenv('OPENSHIFT_DATA_DIR') if data_dir is None: data_dir = os.getenv('PWD') logging = logging.getLogger(__name__) grammar = GrammarParser.GrammarParser() ind = indeed_scrape.Indeed('kw') class MissingKeywords(object): def __init__(self): self.stop_words = 'resume affirmative cover letter equal religion sex disibility veteran status sexual orientation and work ability http https www gender com org the' def pdf_to_text(self, infile): logging.debug("pdf_to_text, infile:%s" % infile) jar_file = os.path.join(data_dir, 'pdfbox-app-2.0.0-RC2.jar') cmd = "java -jar %(jar)s ExtractText -console %(infile)s" cmd = cmd % {'jar':jar_file, 'infile':infile } process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() errcode = process.returncode if errcode > 0: logging.error(err) logging.error(out) logging.error(errcode) raise Exception return out def make_row(self, kw, ind_cnt, res_cnt): row = '<tr><td>%s</td><td>%s</td><td>%s</td></tr>' row = row %(kw, ind_cnt, res_cnt) return row def vectorizer(self, corpus, max_fea, n_min, n_max): ind = indeed_scrape.Indeed(None) ind.stop_words = self.stop_words ind.add_stop_words() stop_words = ind.stop_words vectorizer = CountVectorizer(max_features=max_fea, max_df=0.80, min_df=5, lowercase=True, stop_words=stop_words, ngram_range=(n_min, n_max), analyzer='word', decode_error='ignore', strip_accents='unicode' ) matrix = vectorizer.fit_transform(corpus) features = vectorizer.get_feature_names() return matrix, features, vectorizer def _trans_ind_agg_to_perc(self, mat): ind_mat = mat.toarray() # recall: mat is docs x features # we want count of features overall docs ind_cnt = ind_mat.T.sum(axis=1) # and really we want the percentage ind_perc = ind_cnt / float(ind_mat.shape[0]) ind_perc = np.round(ind_perc, decimals=2) return ind_perc def main(self, resume_path, indeed_summaries): res_text = self.pdf_to_text(resume_path) bi_rows = self.bi_gram_analysis(res_text, indeed_summaries) uni_rows = self.unigram_analysis(res_text, indeed_summaries) return bi_rows, uni_rows def unigram_analysis(self, res_text, indeed_summaries): ind_mat, keywords, vec_obj = self.vectorizer(indeed_summaries, 10, 1, 1) ind_perc = self._trans_ind_agg_to_perc(ind_mat) res_mat = vec_obj.transform([res_text]) # resume matrix is a 1 dim so no need to sum # or transpose res_mat = res_mat.toarray().squeeze() rows = self.make_rows(keywords, ind_perc, res_mat) return rows def bi_gram_analysis(self, res_text, indeed_summaries): ind_mat, keywords, vec_obj = self.vectorizer(indeed_summaries, 20, 2, 2) ind_perc = self._trans_ind_agg_to_perc(ind_mat) res_mat = vec_obj.transform([res_text]) res_mat = res_mat.toarray().squeeze() rows = self.make_rows(keywords, ind_perc, res_mat) return rows def make_rows(self, keywords, ind_perc, res_mat): rows = '' for i in range(len(ind_perc)): rows += self.make_row(keywords[i], ind_perc[i], res_mat[i]) return rows
mit
guorendong/iridium-browser-ubuntu
native_client/site_scons/site_tools/naclsdk.py
2
28784
#!/usr/bin/python # Copyright (c) 2012 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """NaCl SDK tool SCons.""" import __builtin__ import re import os import shutil import sys import SCons.Scanner import SCons.Script import subprocess import tempfile NACL_TOOL_MAP = { 'arm': { '32': { 'tooldir': 'arm-nacl', 'as_flag': '', 'cc_flag': '', 'ld_flag': '', }, }, 'x86': { '32': { 'tooldir': 'i686-nacl', 'other_libdir': 'lib32', 'as_flag': '--32', 'cc_flag': '-m32', 'ld_flag': ' -melf_i386_nacl', }, '64': { 'tooldir': 'x86_64-nacl', 'other_libdir': 'lib64', 'as_flag': '--64', 'cc_flag': '-m64', 'ld_flag': ' -melf_x86_64_nacl', }, }, } def _StubOutEnvToolsForBuiltElsewhere(env): """Stub out all tools so that they point to 'true'. Some machines have their code built by another machine, they'll therefore run 'true' instead of running the usual build tools. Args: env: The SCons environment in question. """ assert(env.Bit('built_elsewhere')) env.Replace(CC='true', CXX='true', LINK='true', AR='true', RANLIB='true', AS='true', ASPP='true', LD='true', STRIP='true', OBJDUMP='true', OBJCOPY='true', PNACLOPT='true', PNACLFINALIZE='true') def _SetEnvForNativeSdk(env, sdk_path): """Initialize environment according to target architecture.""" bin_path = os.path.join(sdk_path, 'bin') # NOTE: attempts to eliminate this PATH setting and use # absolute path have been futile env.PrependENVPath('PATH', bin_path) tool_prefix = None tool_map = NACL_TOOL_MAP[env['TARGET_ARCHITECTURE']] subarch_spec = tool_map[env['TARGET_SUBARCH']] tooldir = subarch_spec['tooldir'] # We need to pass it extra options for the subarch we are building. as_mode_flag = subarch_spec['as_flag'] cc_mode_flag = subarch_spec['cc_flag'] ld_mode_flag = subarch_spec['ld_flag'] if os.path.exists(os.path.join(sdk_path, tooldir)): # The tooldir for the build target exists. # The tools there do the right thing without special options. tool_prefix = tooldir libdir = os.path.join(tooldir, 'lib') else: # We're building for a target for which there is no matching tooldir. # For example, for x86-32 when only <sdk_path>/x86_64-nacl/ exists. # Find a tooldir for a different subarch that does exist. others_map = tool_map.copy() del others_map[env['TARGET_SUBARCH']] for subarch, tool_spec in others_map.iteritems(): tooldir = tool_spec['tooldir'] if os.path.exists(os.path.join(sdk_path, tooldir)): # OK, this is the other subarch to use as tooldir. tool_prefix = tooldir # The lib directory may have an alternate name, i.e. # 'lib32' in the x86_64-nacl tooldir. libdir = os.path.join(tooldir, subarch_spec.get('other_libdir', 'lib')) break if tool_prefix is None: raise Exception("Cannot find a toolchain for %s in %s" % (env['TARGET_FULLARCH'], sdk_path)) cc = 'clang' if env.Bit('nacl_clang') else 'gcc' cxx = 'clang++' if env.Bit('nacl_clang') else 'g++' env.Replace(# Replace header and lib paths. # where to put nacl extra sdk headers # TODO(robertm): switch to using the mechanism that # passes arguments to scons NACL_SDK_INCLUDE='%s/%s/include' % (sdk_path, tool_prefix), # where to find/put nacl generic extra sdk libraries NACL_SDK_LIB='%s/%s' % (sdk_path, libdir), # Replace the normal unix tools with the NaCl ones. CC=os.path.join(bin_path, '%s-%s' % (tool_prefix, cc)), CXX=os.path.join(bin_path, '%s-%s' % (tool_prefix, cxx)), AR=os.path.join(bin_path, '%s-ar' % tool_prefix), AS=os.path.join(bin_path, '%s-as' % tool_prefix), ASPP=os.path.join(bin_path, '%s-%s' % (tool_prefix, cc)), FILECHECK=os.path.join(bin_path, 'FileCheck'), GDB=os.path.join(bin_path, '%s-gdb' % tool_prefix), # NOTE: use g++ for linking so we can handle C AND C++. LINK=os.path.join(bin_path, '%s-%s' % (tool_prefix, cxx)), # Grrr... and sometimes we really need ld. LD=os.path.join(bin_path, '%s-ld' % tool_prefix) + ld_mode_flag, RANLIB=os.path.join(bin_path, '%s-ranlib' % tool_prefix), NM=os.path.join(bin_path, '%s-nm' % tool_prefix), OBJDUMP=os.path.join(bin_path, '%s-objdump' % tool_prefix), OBJCOPY=os.path.join(bin_path, '%s-objcopy' % tool_prefix), STRIP=os.path.join(bin_path, '%s-strip' % tool_prefix), ADDR2LINE=os.path.join(bin_path, '%s-addr2line' % tool_prefix), BASE_LINKFLAGS=[cc_mode_flag], BASE_CFLAGS=[cc_mode_flag], BASE_CXXFLAGS=[cc_mode_flag], BASE_ASFLAGS=[as_mode_flag], BASE_ASPPFLAGS=[cc_mode_flag], CFLAGS=['-std=gnu99'], CCFLAGS=['-O3', '-Werror', '-Wall', '-Wno-variadic-macros', '-Wswitch-enum', '-g', '-fno-stack-protector', '-fdiagnostics-show-option', '-pedantic', '-D__linux__', ], ASFLAGS=[], ) # NaClSdk environment seems to be inherited from the host environment. # On Linux host, this probably makes sense. On Windows and Mac, this # introduces nothing except problems. # For now, simply override the environment settings as in # <scons>/engine/SCons/Platform/posix.py env.Replace(LIBPREFIX='lib', LIBSUFFIX='.a', SHLIBPREFIX='$LIBPREFIX', SHLIBSUFFIX='.so', LIBPREFIXES=['$LIBPREFIX'], LIBSUFFIXES=['$LIBSUFFIX', '$SHLIBSUFFIX'], ) # Force -fPIC when compiling for shared libraries. env.AppendUnique(SHCCFLAGS=['-fPIC'], ) def _SetEnvForPnacl(env, root): # All the PNaCl tools require Python to be in the PATH. arch = env['TARGET_FULLARCH'] assert arch in ['arm', 'mips32', 'x86-32', 'x86-64'] if env.Bit('pnacl_unsandboxed'): if env.Bit('host_linux'): arch = '%s-linux' % arch elif env.Bit('host_mac'): arch = '%s-mac' % arch if env.Bit('nonsfi_nacl'): arch += '-nonsfi' arch_flag = ' -arch %s' % arch ld_arch_flag = '' if env.Bit('pnacl_generate_pexe') else arch_flag llc_mtriple_flag = '' if env.Bit('minsfi'): llc_cpu = '' if env.Bit('build_x86_32'): llc_cpu = 'i686' elif env.Bit('build_x86_64'): llc_cpu = 'x86_64' if env.Bit('host_linux'): llc_mtriple_flag = ' -mtriple=%s-linux-gnu' % llc_cpu elif env.Bit('host_mac'): llc_mtriple_flag = ' -mtriple=%s-apple-darwin' % llc_cpu translator_root = os.path.join(os.path.dirname(root), 'pnacl_translator') binroot = os.path.join(root, 'bin') binprefix = os.path.join(binroot, 'pnacl-') binext = '' if env.Bit('host_windows'): binext = '.bat' pnacl_ar = binprefix + 'ar' + binext pnacl_as = binprefix + 'as' + binext pnacl_nm = binprefix + 'nm' + binext pnacl_ranlib = binprefix + 'ranlib' + binext # Use the standalone sandboxed translator in sbtc mode if env.Bit('use_sandboxed_translator'): pnacl_translate = os.path.join(translator_root, 'bin', 'pnacl-translate' + binext) else: pnacl_translate = binprefix + 'translate' + binext pnacl_cc = binprefix + 'clang' + binext pnacl_cxx = binprefix + 'clang++' + binext pnacl_ld = binprefix + 'ld' + binext pnacl_disass = binprefix + 'dis' + binext pnacl_filecheck = os.path.join(binroot, 'FileCheck') pnacl_finalize = binprefix + 'finalize' + binext pnacl_opt = binprefix + 'opt' + binext pnacl_strip = binprefix + 'strip' + binext pnacl_llc = binprefix + 'llc' + binext # NOTE: XXX_flags start with space for easy concatenation # The flags generated here get baked into the commands (CC, CXX, LINK) # instead of CFLAGS etc to keep them from getting blown away by some # tests. Don't add flags here unless they always need to be preserved. pnacl_cxx_flags = '' pnacl_cc_flags = ' -std=gnu99' pnacl_ld_flags = ' ' + ' '.join(env['PNACL_BCLDFLAGS']) pnacl_translate_flags = '' pnacl_llc_flags = '' sdk_base = os.path.join(root, 'le32-nacl') bias_flags = '' # The supported use cases for nonpexe mode (IRT building, nonsfi) use biased # bitcode and native calling conventions, so inject the --target= flags to # get that by default. The one exception to that rule is PNaCl zerocost EH, # so put the flags in BASE_{C,CXX,LINK}FLAGS rather than in the commands # directly, so that the test can override them. In addition to using the # flags, we have to point NACL_SDK_{LIB,INCLUDE} to the toolchain directories # containing the biased bitcode libraries. if not env.Bit('pnacl_generate_pexe') and env['TARGET_FULLARCH'] != 'mips32': bias_flags = ' '.join(env.BiasedBitcodeFlags()) archdir = {'x86-32': 'i686', 'x86-64': 'x86_64', 'arm': 'arm'} sdk_base = os.path.join(root, archdir[env['TARGET_FULLARCH']] + '_bc-nacl') if env.Bit('nacl_pic'): pnacl_cc_flags += ' -fPIC' pnacl_cxx_flags += ' -fPIC' # NOTE: this is a special hack for the pnacl backend which # does more than linking pnacl_ld_flags += ' -fPIC' pnacl_translate_flags += ' -fPIC' if env.Bit('minsfi'): pnacl_llc_flags += ' -relocation-model=pic -filetype=obj' pnacl_ld_flags += ' -nostdlib -Wl,-r -L' + os.path.join(root, 'usr', 'lib') if env.Bit('use_sandboxed_translator'): sb_flags = ' --pnacl-sb' pnacl_ld_flags += sb_flags pnacl_translate_flags += sb_flags if env.Bit('x86_64_zero_based_sandbox'): pnacl_translate_flags += ' -sfi-zero-based-sandbox' env.Replace(# Replace header and lib paths. NACL_SDK_INCLUDE=os.path.join(root, sdk_base, 'include'), NACL_SDK_LIB=os.path.join(root, sdk_base, 'lib'), # Remove arch-specific flags (if any) BASE_LINKFLAGS=bias_flags, BASE_CFLAGS=bias_flags, BASE_CXXFLAGS=bias_flags, BASE_ASFLAGS='', BASE_ASPPFLAGS='', # Replace the normal unix tools with the PNaCl ones. CC=pnacl_cc + pnacl_cc_flags, CXX=pnacl_cxx + pnacl_cxx_flags, ASPP=pnacl_cc + pnacl_cc_flags, LIBPREFIX="lib", SHLIBPREFIX="lib", SHLIBSUFFIX=".so", OBJSUFFIX=".bc", LINK=pnacl_cxx + ld_arch_flag + pnacl_ld_flags, # Although we are currently forced to produce native output # for LINK, we are free to produce bitcode for SHLINK # (SharedLibrary linking) because scons doesn't do anything # with shared libraries except use them with the toolchain. SHLINK=pnacl_cxx + ld_arch_flag + pnacl_ld_flags, LD=pnacl_ld, AR=pnacl_ar, AS=pnacl_as + ld_arch_flag, RANLIB=pnacl_ranlib, FILECHECK=pnacl_filecheck, DISASS=pnacl_disass, OBJDUMP=pnacl_disass, STRIP=pnacl_strip, TRANSLATE=pnacl_translate + arch_flag + pnacl_translate_flags, PNACLFINALIZE=pnacl_finalize, PNACLOPT=pnacl_opt, LLC=pnacl_llc + llc_mtriple_flag + pnacl_llc_flags, ) if env.Bit('built_elsewhere'): def FakeInstall(dest, source, env): print 'Not installing', dest _StubOutEnvToolsForBuiltElsewhere(env) env.Replace(INSTALL=FakeInstall) if env.Bit('translate_in_build_step'): env.Replace(TRANSLATE='true') env.Replace(PNACLFINALIZE='true') def PNaClForceNative(env): assert(env.Bit('bitcode')) if env.Bit('pnacl_generate_pexe'): env.Replace(CC='NO-NATIVE-CC-INVOCATION-ALLOWED', CXX='NO-NATIVE-CXX-INVOCATION-ALLOWED') return env.Replace(OBJSUFFIX='.o', SHLIBSUFFIX='.so') arch_flag = ' -arch ${TARGET_FULLARCH}' if env.Bit('nonsfi_nacl'): arch_flag += '-nonsfi' cc_flags = ' --pnacl-allow-native --pnacl-allow-translate' env.Append(CC=arch_flag + cc_flags, CXX=arch_flag + cc_flags, ASPP=arch_flag + cc_flags, LINK=cc_flags) # Already has -arch env['LD'] = 'NO-NATIVE-LD-INVOCATION-ALLOWED' env['SHLINK'] = '${LINK}' if env.Bit('built_elsewhere'): _StubOutEnvToolsForBuiltElsewhere(env) # Get an environment for nacl-gcc when in PNaCl mode. def PNaClGetNNaClEnv(env): assert(env.Bit('bitcode')) assert(not env.Bit('build_mips32')) # This is kind of a hack. We clone the environment, # clear the bitcode bit, and then reload naclsdk.py native_env = env.Clone() native_env.ClearBits('bitcode') if env.Bit('built_elsewhere'): _StubOutEnvToolsForBuiltElsewhere(env) else: native_env = native_env.Clone(tools=['naclsdk']) if native_env.Bit('pnacl_generate_pexe'): native_env.Replace(CC='NO-NATIVE-CC-INVOCATION-ALLOWED', CXX='NO-NATIVE-CXX-INVOCATION-ALLOWED') else: # These are unfortunately clobbered by running Tool. native_env.Replace(EXTRA_CFLAGS=env['EXTRA_CFLAGS'], EXTRA_CXXFLAGS=env['EXTRA_CXXFLAGS'], CCFLAGS=env['CCFLAGS'], CFLAGS=env['CFLAGS'], CXXFLAGS=env['CXXFLAGS']) return native_env # This adds architecture specific defines for the target architecture. # These are normally omitted by PNaCl. # For example: __i686__, __arm__, __mips__, __x86_64__ def AddBiasForPNaCl(env, temporarily_allow=True): assert(env.Bit('bitcode')) # re: the temporarily_allow flag -- that is for: # BUG= http://code.google.com/p/nativeclient/issues/detail?id=1248 if env.Bit('pnacl_generate_pexe') and not temporarily_allow: env.Replace(CC='NO-NATIVE-CC-INVOCATION-ALLOWED', CXX='NO-NATIVE-CXX-INVOCATION-ALLOWED') return if env.Bit('build_arm'): bias_flag = '--pnacl-bias=arm' elif env.Bit('build_x86_32'): bias_flag = '--pnacl-bias=x86-32' elif env.Bit('build_x86_64'): bias_flag = '--pnacl-bias=x86-64' elif env.Bit('build_mips32'): bias_flag = '--pnacl-bias=mips32' else: raise Exception("Unknown architecture!") if env.Bit('nonsfi_nacl'): bias_flag += '-nonsfi' env.AppendUnique(CCFLAGS=[bias_flag], ASPPFLAGS=[bias_flag]) def ValidateSdk(env): checkables = ['${NACL_SDK_INCLUDE}/stdio.h'] for c in checkables: if os.path.exists(env.subst(c)): continue # Windows build does not use cygwin and so can not see nacl subdirectory # if it's cygwin's symlink - check for /include instead... if os.path.exists(re.sub(r'(nacl64|nacl)/include/([^/]*)$', r'include/\2', env.subst(c))): continue # TODO(pasko): remove the legacy header presence test below. if os.path.exists(re.sub(r'nacl/include/([^/]*)$', r'nacl64/include/\1', env.subst(c))): continue message = env.subst(''' ERROR: NativeClient toolchain does not seem present!, Missing: %s Configuration is: NACL_SDK_INCLUDE=${NACL_SDK_INCLUDE} NACL_SDK_LIB=${NACL_SDK_LIB} CC=${CC} CXX=${CXX} AR=${AR} AS=${AS} ASPP=${ASPP} LINK=${LINK} RANLIB=${RANLIB} Run: gclient runhooks --force or build the SDK yourself. ''' % c) sys.stderr.write(message + "\n\n") sys.exit(-1) def ScanLinkerScript(node, env, libpath): """SCons scanner for linker script files. This handles trivial linker scripts like those used for libc.so and libppapi.a. These scripts just indicate more input files to be linked in, so we want to produce dependencies on them. A typical such linker script looks like: /* Some comments. */ INPUT ( foo.a libbar.a libbaz.a ) or: /* GNU ld script Use the shared library, but some functions are only in the static library, so try that secondarily. */ OUTPUT_FORMAT(elf64-x86-64) GROUP ( /lib/libc.so.6 /usr/lib/libc_nonshared.a AS_NEEDED ( /lib/ld-linux-x86-64.so.2 ) ) """ contents = node.get_text_contents() if contents.startswith('!<arch>\n') or contents.startswith('\177ELF'): # An archive or ELF file is not a linker script. return [] comment_pattern = re.compile(r'/\*.*?\*/', re.DOTALL | re.MULTILINE) def remove_comments(text): return re.sub(comment_pattern, '', text) tokens = remove_comments(contents).split() libs = [] while tokens: token = tokens.pop() if token.startswith('OUTPUT_FORMAT('): pass elif token == 'OUTPUT_FORMAT': # Swallow the next three tokens: '(', 'xyz', ')' del tokens[0:2] elif token in ['(', ')', 'INPUT', 'GROUP', 'AS_NEEDED']: pass else: libs.append(token) # Find those items in the library path, ignoring ones we fail to find. found = [SCons.Node.FS.find_file(lib, libpath) for lib in libs] return [lib for lib in found if lib is not None] # This is a modified copy of the class TempFileMunge in # third_party/scons-2.0.1/engine/SCons/Platform/__init__.py. # It differs in using quote_for_at_file (below) in place of # SCons.Subst.quote_spaces. class NaClTempFileMunge(object): """A callable class. You can set an Environment variable to this, then call it with a string argument, then it will perform temporary file substitution on it. This is used to circumvent the long command line limitation. Example usage: env["TEMPFILE"] = TempFileMunge env["LINKCOM"] = "${TEMPFILE('$LINK $TARGET $SOURCES')}" By default, the name of the temporary file used begins with a prefix of '@'. This may be configred for other tool chains by setting '$TEMPFILEPREFIX'. env["TEMPFILEPREFIX"] = '-@' # diab compiler env["TEMPFILEPREFIX"] = '-via' # arm tool chain """ def __init__(self, cmd): self.cmd = cmd def __call__(self, target, source, env, for_signature): if for_signature: # If we're being called for signature calculation, it's # because we're being called by the string expansion in # Subst.py, which has the logic to strip any $( $) that # may be in the command line we squirreled away. So we # just return the raw command line and let the upper # string substitution layers do their thing. return self.cmd # Now we're actually being called because someone is actually # going to try to execute the command, so we have to do our # own expansion. cmd = env.subst_list(self.cmd, SCons.Subst.SUBST_CMD, target, source)[0] try: maxline = int(env.subst('$MAXLINELENGTH')) except ValueError: maxline = 2048 length = 0 for c in cmd: length += len(c) if length <= maxline: return self.cmd # We do a normpath because mktemp() has what appears to be # a bug in Windows that will use a forward slash as a path # delimiter. Windows's link mistakes that for a command line # switch and barfs. # # We use the .lnk suffix for the benefit of the Phar Lap # linkloc linker, which likes to append an .lnk suffix if # none is given. (fd, tmp) = tempfile.mkstemp('.lnk', text=True) native_tmp = SCons.Util.get_native_path(os.path.normpath(tmp)) if env['SHELL'] and env['SHELL'] == 'sh': # The sh shell will try to escape the backslashes in the # path, so unescape them. native_tmp = native_tmp.replace('\\', r'\\\\') # In Cygwin, we want to use rm to delete the temporary # file, because del does not exist in the sh shell. rm = env.Detect('rm') or 'del' else: # Don't use 'rm' if the shell is not sh, because rm won't # work with the Windows shells (cmd.exe or command.com) or # Windows path names. rm = 'del' prefix = env.subst('$TEMPFILEPREFIX') if not prefix: prefix = '@' # The @file is sometimes handled by a GNU tool itself, using # the libiberty/argv.c code, and sometimes handled implicitly # by Cygwin before the tool's own main even sees it. These # two treat the contents differently, so there is no single # perfect way to quote. The libiberty @file code uses a very # regular scheme: a \ in any context is always swallowed and # quotes the next character, whatever it is; '...' or "..." # quote whitespace in ... and the outer quotes are swallowed. # The Cygwin @file code uses a vaguely similar scheme, but its # treatment of \ is much less consistent: a \ outside a quoted # string is never stripped, and a \ inside a quoted string is # only stripped when it quoted something (Cygwin's definition # of "something" here is nontrivial). In our uses the only # appearances of \ we expect are in Windows-style file names. # Fortunately, an extra doubling of \\ that doesn't get # stripped is harmless in the middle of a file name. def quote_for_at_file(s): s = str(s) if ' ' in s or '\t' in s: return '"' + re.sub('([ \t"])', r'\\\1', s) + '"' return s.replace('\\', '\\\\') args = list(map(quote_for_at_file, cmd[1:])) os.write(fd, " ".join(args) + "\n") os.close(fd) # XXX Using the SCons.Action.print_actions value directly # like this is bogus, but expedient. This class should # really be rewritten as an Action that defines the # __call__() and strfunction() methods and lets the # normal action-execution logic handle whether or not to # print/execute the action. The problem, though, is all # of that is decided before we execute this method as # part of expanding the $TEMPFILE construction variable. # Consequently, refactoring this will have to wait until # we get more flexible with allowing Actions to exist # independently and get strung together arbitrarily like # Ant tasks. In the meantime, it's going to be more # user-friendly to not let obsession with architectural # purity get in the way of just being helpful, so we'll # reach into SCons.Action directly. if SCons.Action.print_actions: print("Using tempfile "+native_tmp+" for command line:\n"+ str(cmd[0]) + " " + " ".join(args)) return [ cmd[0], prefix + native_tmp + '\n' + rm, native_tmp ] def generate(env): """SCons entry point for this tool. Args: env: The SCons environment in question. NOTE: SCons requires the use of this name, which fails lint. """ # make these methods to the top level scons file env.AddMethod(ValidateSdk) env.AddMethod(AddBiasForPNaCl) env.AddMethod(PNaClForceNative) env.AddMethod(PNaClGetNNaClEnv) # Invoke the various unix tools that the NativeClient SDK resembles. env.Tool('g++') env.Tool('gcc') env.Tool('gnulink') env.Tool('ar') env.Tool('as') if env.Bit('pnacl_generate_pexe'): suffix = '.nonfinal.pexe' else: suffix = '.nexe' env.Replace( COMPONENT_LINKFLAGS=[''], COMPONENT_LIBRARY_LINK_SUFFIXES=['.pso', '.so', '.a'], _RPATH='', COMPONENT_LIBRARY_DEBUG_SUFFIXES=[], PROGSUFFIX=suffix, # adding BASE_ AND EXTRA_ flags to common command lines # The suggested usage pattern is: # BASE_XXXFLAGS can only be set in this file # EXTRA_XXXFLAGS can only be set in a ComponentXXX call # NOTE: we also have EXTRA_LIBS which is handles separately in # site_scons/site_tools/component_builders.py # NOTE: the command lines were gleaned from: # * ../third_party/scons-2.0.1/engine/SCons/Tool/cc.py # * ../third_party/scons-2.0.1/engine/SCons/Tool/c++.py # * etc. CCCOM='$CC $BASE_CFLAGS $CFLAGS $EXTRA_CFLAGS ' + '$CCFLAGS $_CCCOMCOM -c -o $TARGET $SOURCES', SHCCCOM='$SHCC $BASE_CFLAGS $SHCFLAGS $EXTRA_CFLAGS ' + '$SHCCFLAGS $_CCCOMCOM -c -o $TARGET $SOURCES', CXXCOM='$CXX $BASE_CXXFLAGS $CXXFLAGS $EXTRA_CXXFLAGS ' + '$CCFLAGS $_CCCOMCOM -c -o $TARGET $SOURCES', SHCXXCOM='$SHCXX $BASE_CXXFLAGS $SHCXXFLAGS $EXTRA_CXXFLAGS ' + '$SHCCFLAGS $_CCCOMCOM -c -o $TARGET $SOURCES', LINKCOM='$LINK $BASE_LINKFLAGS $LINKFLAGS $EXTRA_LINKFLAGS ' + '$SOURCES $_LIBDIRFLAGS $_LIBFLAGS -o $TARGET', SHLINKCOM='$SHLINK $BASE_LINKFLAGS $SHLINKFLAGS $EXTRA_LINKFLAGS ' + '$SOURCES $_LIBDIRFLAGS $_LIBFLAGS -o $TARGET', ASCOM='$AS $BASE_ASFLAGS $ASFLAGS $EXTRA_ASFLAGS -o $TARGET $SOURCES', ASPPCOM='$ASPP $BASE_ASPPFLAGS $ASPPFLAGS $EXTRA_ASPPFLAGS ' + '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES', # Strip doesn't seem to be a first-class citizen in SCons country, # so we have to add these *COM, *COMSTR manually. # Note: it appears we cannot add this in component_setup.py STRIPFLAGS=['--strip-all'], STRIPCOM='${STRIP} ${STRIPFLAGS}', TRANSLATECOM='${TRANSLATE} ${TRANSLATEFLAGS} ${SOURCES} -o ${TARGET}', PNACLFINALIZEFLAGS=[], PNACLFINALIZECOM='${PNACLFINALIZE} ${PNACLFINALIZEFLAGS} ' + '${SOURCES} -o ${TARGET}', ) # Windows has a small limit on the command line size. The linking and AR # commands can get quite large. So bring in the SCons machinery to put # most of a command line into a temporary file and pass it with # @filename, which works with gcc. if env['PLATFORM'] in ['win32', 'cygwin']: env['TEMPFILE'] = NaClTempFileMunge for com in ['LINKCOM', 'SHLINKCOM', 'ARCOM']: env[com] = "${TEMPFILE('%s')}" % env[com] # Get root of the SDK. root = env.GetToolchainDir() # if bitcode=1 use pnacl toolchain if env.Bit('bitcode'): _SetEnvForPnacl(env, root) elif env.Bit('built_elsewhere'): def FakeInstall(dest, source, env): print 'Not installing', dest _StubOutEnvToolsForBuiltElsewhere(env) env.Replace(INSTALL=FakeInstall) else: _SetEnvForNativeSdk(env, root) if (env.Bit('bitcode') or env.Bit('nacl_clang')) and env.Bit('build_x86'): # Get GDB from the nacl-gcc toolchain even when using PNaCl. # TODO(mseaborn): We really want the nacl-gdb binary to be in a # separate tarball from the nacl-gcc toolchain, then this step # will not be necessary. # See http://code.google.com/p/nativeclient/issues/detail?id=2773 temp_env = env.Clone() temp_env.ClearBits('bitcode', 'nacl_clang') temp_root = temp_env.GetToolchainDir() _SetEnvForNativeSdk(temp_env, temp_root) env.Replace(GDB=temp_env['GDB']) env.Prepend(LIBPATH='${NACL_SDK_LIB}') # Install our scanner for (potential) linker scripts. # It applies to "source" files ending in .a or .so. # Dependency files it produces are to be found in ${LIBPATH}. # It is applied recursively to those dependencies in case # some of them are linker scripts too. ldscript_scanner = SCons.Scanner.Base( function=ScanLinkerScript, skeys=['.a', '.so', '.pso'], path_function=SCons.Scanner.FindPathDirs('LIBPATH'), recursive=True ) env.Append(SCANNERS=ldscript_scanner) # Scons tests can check this version number to decide whether to # enable tests for toolchain bug fixes or new features. See # description in pnacl/build.sh. if 'toolchain_feature_version' in SCons.Script.ARGUMENTS: version = int(SCons.Script.ARGUMENTS['toolchain_feature_version']) else: version_file = os.path.join(root, 'FEATURE_VERSION') # There is no pnacl_newlib toolchain on ARM, only a pnacl_translator, so # use that if necessary. Otherwise use it if we are doing sandboxed # translation. if not os.path.exists(version_file) or env.Bit('use_sandboxed_translator'): version_file = os.path.join(os.path.dirname(root), 'pnacl_translator', 'FEATURE_VERSION') if os.path.exists(version_file): with open(version_file, 'r') as fh: version = int(fh.read()) else: version = 0 env.Replace(TOOLCHAIN_FEATURE_VERSION=version)
bsd-3-clause
ameya30/IMaX_pole_data_scripts
my_scripts/snr_quiet_pulpo.py
1
1119
import numpy as np from astropy.io import fits from matplotlib import pyplot as plt fima = fits.open('/scratch/prabhu/HollyWaller/IMaX_pole_data_scripts/primary_scripts/saves_Oct11/post_demod_tr2_output_21.fits')[0].data st = int(input("Choose stokes: ")) stokes = {0:'I',1:'Q',2:'U',3:'V'} dim = fima.shape print(dim) maif = np.zeros(shape=(dim[0],dim[1],dim[2],dim[3])) print(maif.shape) if st==0: maif[st,:,:,:] = fima[st,:,:,:]/np.mean(fima[0,4,230:880,83:859]) up,down=1.5,0.5 elif st==1: maif[st,:,:,:] = fima[st,:,:,:]/fima[0,4,:,:] up,down=0.04,-0.04 elif st==2: maif[st,:,:,:] = fima[st,:,:,:]/fima[0,4,:,:] up,down=0.04,-0.04 else: maif[st,:,:,:] = fima[st,:,:,:]/fima[0,4,:,:] up,down=0.08,-0.08 fig = plt.figure(figsize=(12,12)) ax = plt.axes() im = ax.imshow(maif[st,4,:,:],cmap='gray',vmax=up,vmin=down) fig.colorbar(im) fig.tight_layout(pad=1.8) plt.gca().invert_yaxis() plt.show() y1 = 200 y2 = 280 x1 = 340 x2 = 500 std = np.std(maif[st,4,y1:y2,x1:x2]) meanie = np.mean(maif[st,4,y1:y2,x1:x2]) rms = std/meanie print("rms is {}".format(rms)) print("std is {}".format(std))
mit
travc/paper-Predicted-MF-Quarantine-Length-Data-and-Code
data/MedFoes/collate_longrun_output.py
1
3371
#!/bin/env python3 import sys import os import glob import numpy as np import pandas as pd from collections import OrderedDict RUNSET = sys.argv[1].rstrip('/') BASEDIR = './' OUTDIR = 'out' INTERPOLATION_METHOD = 'nearest' STEP_FILENAME_GLOB = 'step_*' MEDFOESP_DETAIL_FILE_GLOB = 'MED-FOESp_*_detail.txt' DATA_OUT_FILENAME = RUNSET+'_collated_data_out.npz' TFILE = os.path.join(BASEDIR, RUNSET, 'temperature_file.csv') STEP_SIZE = 24*7 # Each step is one week RUNS_PER_STEP = 2500 # read in the temperature file tempdf = pd.read_csv(TFILE, index_col='datetime', parse_dates=True) print("Read temperature file '{}'".format(TFILE)) # Get list of all the run directories rootpath = os.path.join(BASEDIR, RUNSET, OUTDIR) dirs = sorted([os.path.split(x)[1] for x in glob.glob(os.path.join(rootpath, STEP_FILENAME_GLOB))]) #print(rootpath) #print(dirs) # ensure step numbers make sense (consecutive starting from 1) tmp = min(dirs).split('_')[1] assert int(tmp) == 1, "ERROR?: First step number should be 1, right?" num_steps = int(max(dirs).split('_')[1]) assert num_steps == len(dirs), "ERROR?: Last step number should be the number of steps... ie. no missing steps." # determine the start datetime for each step stepdir2startdate = {} tempfile_startdt = tempdf.index[0] task_nums = [int(x.split('_')[1]) for x in dirs] date2step = pd.DataFrame(index=[tempfile_startdt+pd.Timedelta(hours=STEP_SIZE*(x-1)) for x in task_nums], data=list(zip(task_nums, dirs)), columns=['step_num','step_dir']).sort_index() max_run_length = 0 prop_extinct = OrderedDict() # key is runset start datetime (value) start_times = [] # For each step, read the medfoesp detail file for start_time, row in date2step.iterrows(): step_dir = row['step_dir'] print(start_time, step_dir) # find the medfoesp detail file for this step mfpdetail_fn = glob.glob(os.path.join(BASEDIR,RUNSET,OUTDIR,step_dir,MEDFOESP_DETAIL_FILE_GLOB)) assert len(mfpdetail_fn) == 1, "Error: didn't find, or found more than one, MEDFOESP 'detial' file: {}".format(mfpdetail_fn) mfpdetail_fn = mfpdetail_fn[0] # read it tmp = pd.read_csv(mfpdetail_fn, sep='\t') # add an extirpation time column tmp['ext_time'] = tmp['run_time'] tmp.loc[tmp['end_condition']!=0, 'ext_time'] = np.nan # This is a space (and time) efficient way of computing the proportion of runs going extinct # in the most accurate way possible... But it is overkill here ext_cnts = tmp['ext_time'].dropna().value_counts(sort=False).sort_index() if len(ext_cnts) == 0: print("NO RUNS GOING TO EXTRIPATION FOR STEP "+step_dir) break cumcnt = np.cumsum(ext_cnts.values).astype(float) #prop_extinct[run_start_datetime] foo = np.array(list(zip(ext_cnts.index, cumcnt/cumcnt[-1]))) start_times.append(start_time) prop_extinct[start_time] = foo run_length_max = ext_cnts.index.max() if max_run_length < run_length_max: max_run_length = run_length_max np.savez_compressed(DATA_OUT_FILENAME, runset_name=os.path.join(BASEDIR, RUNSET), max_run_length=max_run_length, prop_extinct=prop_extinct, step2startdate=stepdir2startdate, ) print("Data saved to: '{}'".format(DATA_OUT_FILENAME))
mit
google/nerfactor
third_party/xiuminglib/xiuminglib/vis/pt.py
1
6738
from os.path import join, dirname import numpy as np from .. import const, os as xm_os from .general import _savefig from ..imprt import preset_import from ..log import get_logger logger = get_logger() def scatter_on_img(pts, im, size=2, bgr=(0, 0, 255), outpath=None): r"""Plots scatter on top of an image or just a white canvas, if you are being creative by feeding in just a white image. Args: pts (array_like): Pixel coordinates of the scatter point(s), of length 2 for just one point or shape N-by-2 for multiple points. Convention: .. code-block:: none +-----------> dim1 | | | v dim0 im (numpy.ndarray): Image to scatter on. H-by-W (grayscale) or H-by-W-by-3 (RGB) arrays of ``unint`` type. size (float or array_like(float), optional): Size(s) of scatter points. If *array_like*, must be of length N. bgr (tuple or array_like(tuple), optional): BGR color(s) of scatter points. Each element :math:`\in [0, 255]`. If *array_like*, must be of shape N-by-3. outpath (str, optional): Path to which the visualization is saved to. ``None`` means ``os.path.join(const.Dir.tmp, 'scatter_on_img.png')``. Writes - The scatter plot overlaid over the image. """ cv2 = preset_import('cv2', assert_success=True) if outpath is None: outpath = join(const.Dir.tmp, 'scatter_on_img.png') thickness = -1 # for filled circles # Standardize inputs if im.ndim == 2: # grayscale im = np.dstack((im, im, im)) # to BGR pts = np.array(pts) if pts.ndim == 1: pts = pts.reshape(-1, 2) n_pts = pts.shape[0] if im.dtype != 'uint8' and im.dtype != 'uint16': logger.warning("Input image type may cause obscure cv2 errors") if isinstance(size, int): size = np.array([size] * n_pts) else: size = np.array(size) bgr = np.array(bgr) if bgr.ndim == 1: bgr = np.tile(bgr, (n_pts, 1)) # FIXME: necessary, probably due to OpenCV bugs? im = im.copy() # Put on scatter points for i in range(pts.shape[0]): xy = tuple(pts[i, ::-1].astype(int)) color = (int(bgr[i, 0]), int(bgr[i, 1]), int(bgr[i, 2])) cv2.circle(im, xy, size[i], color, thickness) # Make directory, if necessary outdir = dirname(outpath) xm_os.makedirs(outdir) # Write to disk cv2.imwrite(outpath, im) # TODO: switch to xm.io.img def uv_on_texmap(uvs, texmap, ft=None, outpath=None, max_n_lines=None, dotsize=4, dotcolor='r', linewidth=1, linecolor='b'): """Visualizes which points on texture map the vertices map to. Args: uvs (numpy.ndarray): N-by-2 array of UV coordinates. See :func:`xiuminglib.blender.object.smart_uv_unwrap` for the UV coordinate convention. texmap (numpy.ndarray or str): Loaded texture map or its path. If *numpy.ndarray*, can be H-by-W (grayscale) or H-by-W-by-3 (color). ft (list(list(int)), optional): Texture faces used to connect the UV points. Values start from 1, e.g., ``'[[1, 2, 3], [], [2, 3, 4, 5], ...]'``. outpath (str, optional): Path to which the visualization is saved to. ``None`` means ``os.path.join(const.Dir.tmp, 'uv_on_texmap.png')``. max_n_lines (int, optional): Plotting a huge number of lines can be slow, so set this to uniformly sample a subset to plot. Useless if ``ft`` is ``None``. dotsize (int or list(int), optional): Size(s) of the UV dots. dotcolor (str or list(str), optional): Their color(s). linewidth (float, optional): Width of the lines connecting the dots. linecolor (str, optional): Their color. Writes - An image of where the vertices map to on the texture map. """ import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from mpl_toolkits.axes_grid1 import make_axes_locatable if outpath is None: outpath = join(const.Dir.tmp, 'uv_on_texmap.png') # Preprocess input if isinstance(texmap, str): cv2 = preset_import('cv2', assert_success=True) texmap = cv2.imread( # TODO: switch to xm.io.img texmap, cv2.IMREAD_UNCHANGED)[:, :, ::-1] # made RGB if len(texmap.shape) == 2: add_colorbar = True # for grayscale elif len(texmap.shape) == 3: add_colorbar = False # for color texture maps else: raise ValueError( ("texmap must be either H-by-W (grayscale) or H-by-W-by-3 " "(color), or a path to such images")) dpi = 96 # assumed h, w = texmap.shape[:2] w_in, h_in = w / dpi, h / dpi fig = plt.figure(figsize=(w_in, h_in)) u, v = uvs[:, 0], uvs[:, 1] # ^ v # | # +---> u x, y = u * w, (1 - v) * h # +---> x # | # v y # UV dots ax = fig.gca() ax.set_xlim([min(0, min(x)), max(w, max(x))]) ax.set_ylim([max(h, max(y)), min(0, min(y))]) im = ax.imshow(texmap, cmap='gray') ax.scatter(x, y, c=dotcolor, s=dotsize, zorder=2) ax.set_aspect('equal') # Connect these dots if ft is not None: lines = [] for vert_id in [x for x in ft if x]: # non-empty ones assert min(vert_id) >= 1, "Indices in ft are 1-indexed" # For each face ind = [i - 1 for i in vert_id] n_verts = len(ind) for i in range(n_verts): lines.append([ (x[ind[i]], y[ind[i]]), (x[ind[(i + 1) % n_verts]], y[ind[(i + 1) % n_verts]]) ]) # line start and end if max_n_lines is not None: lines = [lines[i] for i in np.linspace( 0, len(lines) - 1, num=max_n_lines, dtype=int)] line_collection = LineCollection( lines, linewidths=linewidth, colors=linecolor, zorder=1) ax.add_collection(line_collection) # Make directory, if necessary outdir = dirname(outpath) xm_os.makedirs(outdir) # Colorbar if add_colorbar: # Create an axes on the right side of ax. The width of cax will be 2% # of ax and the padding between cax and ax will be fixed at 0.1 inch. cax = make_axes_locatable(ax).append_axes('right', size='2%', pad=0.2) plt.colorbar(im, cax=cax) # Save contents_only = not add_colorbar _savefig(outpath, contents_only=contents_only) plt.close('all')
apache-2.0
tta/gnuradio-tta
gnuradio-examples/python/pfb/chirp_channelize.py
7
6936
#!/usr/bin/env python # # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, blks2 import sys, time try: import scipy from scipy import fftpack except ImportError: print "Error: Program requires scipy (see: www.scipy.org)." sys.exit(1) try: import pylab from pylab import mlab except ImportError: print "Error: Program requires matplotlib (see: matplotlib.sourceforge.net)." sys.exit(1) class pfb_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self._N = 200000 # number of samples to use self._fs = 9000 # initial sampling rate self._M = 9 # Number of channels to channelize # Create a set of taps for the PFB channelizer self._taps = gr.firdes.low_pass_2(1, self._fs, 500, 20, attenuation_dB=10, window=gr.firdes.WIN_BLACKMAN_hARRIS) # Calculate the number of taps per channel for our own information tpc = scipy.ceil(float(len(self._taps)) / float(self._M)) print "Number of taps: ", len(self._taps) print "Number of channels: ", self._M print "Taps per channel: ", tpc repeated = True if(repeated): self.vco_input = gr.sig_source_f(self._fs, gr.GR_SIN_WAVE, 0.25, 110) else: amp = 100 data = scipy.arange(0, amp, amp/float(self._N)) self.vco_input = gr.vector_source_f(data, False) # Build a VCO controlled by either the sinusoid or single chirp tone # Then convert this to a complex signal self.vco = gr.vco_f(self._fs, 225, 1) self.f2c = gr.float_to_complex() self.head = gr.head(gr.sizeof_gr_complex, self._N) # Construct the channelizer filter self.pfb = blks2.pfb_channelizer_ccf(self._M, self._taps) # Construct a vector sink for the input signal to the channelizer self.snk_i = gr.vector_sink_c() # Connect the blocks self.connect(self.vco_input, self.vco, self.f2c) self.connect(self.f2c, self.head, self.pfb) self.connect(self.f2c, self.snk_i) # Create a vector sink for each of M output channels of the filter and connect it self.snks = list() for i in xrange(self._M): self.snks.append(gr.vector_sink_c()) self.connect((self.pfb, i), self.snks[i]) def main(): tstart = time.time() tb = pfb_top_block() tb.run() tend = time.time() print "Run time: %f" % (tend - tstart) if 1: fig_in = pylab.figure(1, figsize=(16,9), facecolor="w") fig1 = pylab.figure(2, figsize=(16,9), facecolor="w") fig2 = pylab.figure(3, figsize=(16,9), facecolor="w") fig3 = pylab.figure(4, figsize=(16,9), facecolor="w") Ns = 650 Ne = 20000 fftlen = 8192 winfunc = scipy.blackman fs = tb._fs # Plot the input signal on its own figure d = tb.snk_i.data()[Ns:Ne] spin_f = fig_in.add_subplot(2, 1, 1) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_in = 10.0*scipy.log10(abs(fftpack.fftshift(X))) f_in = scipy.arange(-fs/2.0, fs/2.0, fs/float(X_in.size)) pin_f = spin_f.plot(f_in, X_in, "b") spin_f.set_xlim([min(f_in), max(f_in)+1]) spin_f.set_ylim([-200.0, 50.0]) spin_f.set_title("Input Signal", weight="bold") spin_f.set_xlabel("Frequency (Hz)") spin_f.set_ylabel("Power (dBW)") Ts = 1.0/fs Tmax = len(d)*Ts t_in = scipy.arange(0, Tmax, Ts) x_in = scipy.array(d) spin_t = fig_in.add_subplot(2, 1, 2) pin_t = spin_t.plot(t_in, x_in.real, "b") pin_t = spin_t.plot(t_in, x_in.imag, "r") spin_t.set_xlabel("Time (s)") spin_t.set_ylabel("Amplitude") Ncols = int(scipy.floor(scipy.sqrt(tb._M))) Nrows = int(scipy.floor(tb._M / Ncols)) if(tb._M % Ncols != 0): Nrows += 1 # Plot each of the channels outputs. Frequencies on Figure 2 and # time signals on Figure 3 fs_o = tb._fs / tb._M Ts_o = 1.0/fs_o Tmax_o = len(d)*Ts_o for i in xrange(len(tb.snks)): # remove issues with the transients at the beginning # also remove some corruption at the end of the stream # this is a bug, probably due to the corner cases d = tb.snks[i].data()[Ns:Ne] sp1_f = fig1.add_subplot(Nrows, Ncols, 1+i) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs_o, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_o = 10.0*scipy.log10(abs(X)) f_o = freq p2_f = sp1_f.plot(f_o, X_o, "b") sp1_f.set_xlim([min(f_o), max(f_o)+1]) sp1_f.set_ylim([-200.0, 50.0]) sp1_f.set_title(("Channel %d" % i), weight="bold") sp1_f.set_xlabel("Frequency (Hz)") sp1_f.set_ylabel("Power (dBW)") x_o = scipy.array(d) t_o = scipy.arange(0, Tmax_o, Ts_o) sp2_o = fig2.add_subplot(Nrows, Ncols, 1+i) p2_o = sp2_o.plot(t_o, x_o.real, "b") p2_o = sp2_o.plot(t_o, x_o.imag, "r") sp2_o.set_xlim([min(t_o), max(t_o)+1]) sp2_o.set_ylim([-2, 2]) sp2_o.set_title(("Channel %d" % i), weight="bold") sp2_o.set_xlabel("Time (s)") sp2_o.set_ylabel("Amplitude") sp3 = fig3.add_subplot(1,1,1) p3 = sp3.plot(t_o, x_o.real) sp3.set_xlim([min(t_o), max(t_o)+1]) sp3.set_ylim([-2, 2]) sp3.set_title("All Channels") sp3.set_xlabel("Time (s)") sp3.set_ylabel("Amplitude") pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass
gpl-3.0
viswimmer1/PythonGenerator
data/python_files/34471319/plot_covariance.py
1
1489
import dataset; import numpy as np import scipy.io; import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt import networkx as nx import scipy.stats as ss #z = scipy.io.loadmat('tmp.dat'); #ccfull = z['ccfull'] #sx,sy = ccfull.shape ##x = np.arange(sx) ##delta = 0.025 ##X, Y = np.meshgrid(x, x) ##Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) ##Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) ##Z = Z2-Z1 # difference of Gaussians # #im = plt.imshow(ccfull, interpolation='bilinear', # origin='lower', extent=[1,sx,1,sx]) # #plt.savefig('corrcoeff.pdf') # #p = 1 - (ccfull*ccfull) # #im = plt.imshow(p, interpolation='bilinear', # origin='lower', extent=[1,sx,1,sx]) #plt.savefig('corrcoef2.pdf') #plt.show() z = scipy.io.loadmat('tmp2'); mi = z['mi'] sx,sy = mi.shape #im = plt.imshow(mi, interpolation='bilinear', # origin='lower', extent=[1,sx,1,sx]) #plt.savefig('mi.pdf') #plt.show() print "MI Loaded" mi = np.triu(mi) a = mi.ravel(); print a level = ss.scoreatpercentile(a,99.) indexes = np.transpose(np.find(mi<level)) #mi[mi<level]=0 plt.savefig('mi2.pdf') exit() print level print "MI prunned" G = nx.Graph(); for r in indexes: #for i in xrange(sx): #if i % 100 == 0: # print i #for j in xrange(i): # z = mi[i][j] # if z > 0: G.add_edge(r[0], r[1], weight=-mi[r]); print "Graph built" T = nx.minimum_spanning_tree(G); print T print "Tree found"
gpl-2.0
matthewghgriffiths/nestedbasinsampling
examples/Gaussian/gaussian_system.py
1
3374
import logging import numpy as np from pele.potentials import BasePotential from nestedbasinsampling import ( NBS_system, vector_random_uniform_hypersphere, LOG_CONFIG) class MyPot(BasePotential): def __init__(self, M): self.M = M def getEnergy(self, coords): return 0.5*np.dot(coords, coords*self.M) def getGradient(self, coords): return self.M*coords def getEnergyGradient(self, coords): G = self.getGradient(coords) E = 0.5 * np.dot(coords, G) return E, G M = np.array([ 11.63777605, 19.75825574, 22.2571117 , 24.41295908, 26.32612811, 31.30715704, 35.27360319, 37.34413361, 41.24811749, 42.66902559, 45.00513907, 48.71488414, 49.89979232, 53.0797042 , 55.39317634, 56.84512961, 60.77859882, 60.93608218, 62.49575527, 65.40116213, 69.59126898, 71.32244177, 71.59182786, 73.51372578, 81.19666404, 83.07758741, 84.5588217 , 86.37683242, 94.65859144, 95.40770789, 95.98119526, 102.45620344, 102.47916283, 104.40832154, 104.86404787, 112.80895254, 117.10380584, 123.6500204 , 124.0540132 , 132.17808513, 136.06966301, 136.60709658, 138.73165763, 141.45541009, 145.23595258, 150.31676718, 150.85458655, 155.15681296, 155.25203667, 155.87048385, 158.6880457 , 162.77205271, 164.92793349, 168.44191483, 171.4869683 , 186.92271992, 187.93659725, 199.78966333, 203.05115652, 205.41580397, 221.54815121, 232.16086835, 233.13187687, 238.45586414, 242.5562086 , 252.18391589, 264.91944949, 274.141751 , 287.58508273, 291.47971184, 296.03725173, 307.39663841, 319.38453549, 348.68884953, 360.54506854, 363.87206193, 381.72011237, 384.1627136 , 396.94159259, 444.72185599, 446.48921839, 464.50930109, 485.99776331, 513.57334376, 680.97359437, 740.68419553, 793.64807121]) pot = MyPot(M) n = len(M) u = M p = u > 1e-5 k = p.sum() v = np.eye(n) up = u[p] vp = v[:,p] up2 = (2./up)**0.5 def random_coords(E): x = vector_random_uniform_hypersphere(k) * E**0.5 return vp.dot(up2 * x) Ecut = 1000. stepsize = 0.1 random_config = lambda : random_coords(Ecut) system_kws = dict( pot=pot, random_configuration=random_config, stepsize=stepsize, sampler_kws=dict(max_depth=8, nsteps=30), nopt_kws=dict(iprint=10)) get_system = lambda : NBS_system(**system_kws) if __name__ == '__main__': import matplotlib.pyplot as plt from tqdm import tqdm system = get_system() pot = system.pot nuts = system.sampler plt.ion() Ecut=10000. k = 87 epsilon = 0.02 nsamples = 1000 a = np.arange(nsamples) + 1 b = nsamples + 1 - a l = np.log(a) - np.log(a+b) l2 = l + np.log(a+1) - np.log(a+b+1) lstd = np.log1p(np.sqrt(np.exp(l2 - 2 * l) - 1)) coords = random_coords(Ecut) nuts_results = [] for i in tqdm(xrange(nsamples)): nuts_results.append(nuts(Ecut, coords, stepsize=epsilon)) nEs = np.array([r.energies for r in nuts_results]) nEs.sort(0) for i in xrange(4, nEs.shape[1],5): Es = nEs.T[i] plt.plot( Es**(0.5*k), ((l - 0.5*k*(np.log(Es)-np.log(Ecut)))/lstd), label=i) plt.legend() plt.show()
gpl-3.0
Qwertycal/19520-Eye-Tracker
Filtering/eyeTrackingDemoGUI.py
1
5553
#author: Rachel Hutchinson #date created: 28th March #description: shows 4 stages in the eye tracking #process, and includes the code from the original main #calls other mehtods from their seperate scripts #Import necessary modules import matplotlib matplotlib.use("TkAgg") from matplotlib import pyplot as plt from Tkinter import * from PIL import Image, ImageTk import pyautogui import numpy as np import math import cv2 import removeOutliersThresh as outliers import bi_level_img_threshold as thresh import edgeDetection as edgeDet import imgThresholdVideo import AllTogetherEdit as ATE import getGazePoint as GGP #Find the screen width & set the approprite size for each feed screenwidth, screenheight = pyautogui.size() vidWidth = (screenwidth/2) - 5 vidHeight = (screenheight/2) - 30 #Open the video file global cap cap = cv2.VideoCapture('Eye.mov') #Set the frame counter, this determines when the video should be looped global frame_counter frame_counter = 0 #Solutions obtained from 'Eye.MOV' aOriginal = [576.217396, -24.047559, 1.0915599, -0.221105357, -0.025469321, 0.037511114] bOriginal = [995.77047, -1.67122664, 12.67059, 0.018357141, 0.028264854, 0.012302] #Set mouse toggle global mouseToggle mouseToggle = True #Toggles between the eye tracker controling mouse movements (mouseToggle = true) # and the cursor control being manual (mouseToggle = false) def mouseControlToggle(self): global mouseToggle if mouseToggle: mouseToggle = False print 'MCT false' else: mouseToggle = True print 'MCT true' #Set up the GUI root = Tk() root.title("Demo Mode") root.bind('<Escape>', lambda e: root.destroy()) #esc key quits program root.bind('m', mouseControlToggle) #'m' key toggles cursor control win = Toplevel(root) win.protocol('WM_DELETE_WINDOW', win.destroy) root.attributes("-fullscreen", True) #Create labels for each video feed to go in videoStream1 = Label(root) videoStream2 = Label(root) videoStream3 = Label(root) videoStream4 = Label(root) #Put all of the elements into the GUI videoStream1.grid(row = 0, column = 0) videoStream2.grid(row = 0, column = 1) videoStream3.grid(row = 1, column = 0) videoStream4.grid(row = 1, column = 1) #Show video feeds def show_frame(): global frame_counter global cap #Detects when near the end of the video file, and loops it if frame_counter >= (cap.get(cv2.CAP_PROP_FRAME_COUNT)-5): print 'loop condition' frame_counter = 0 cap = cv2.VideoCapture('Eye.MOV') #Read the input feed, flip it, resize it and show it in the corresponding label ret, frame = cap.read() frame_counter += 1 flipFrame = cv2.flip(frame, 1) cv2image = cv2.resize(flipFrame, (vidWidth, vidHeight)) img1 = Image.fromarray(cv2image) imgtk1 = ImageTk.PhotoImage(image=img1) videoStream1.imgtk1 = imgtk1 videoStream1.configure(image=imgtk1) #Call the threholding function (altered for the video feed) threshPupil, threshGlint = imgThresholdVideo.imgThresholdVideo(frame) #Show the thresholded pupil, same method as above frame_resized = cv2.resize(threshPupil, (vidWidth, vidHeight), interpolation = cv2.INTER_AREA) frame_resized = cv2.flip(frame_resized, 1) img2 = Image.fromarray(frame_resized) imgtk2 = ImageTk.PhotoImage(image=img2) videoStream2.imgtk2 = imgtk2 videoStream2.configure(image=imgtk2) #Show the thresholded glint, same method as above frameB_resized = cv2.resize(threshGlint, (vidWidth, vidHeight), interpolation = cv2.INTER_AREA) frameB_resized = cv2.flip(frameB_resized, 1) img3 = Image.fromarray(frameB_resized) imgtk3 = ImageTk.PhotoImage(image=img3) videoStream3.imgtk3 = imgtk3 videoStream3.configure(image=imgtk3) # Call the edge detection of binary frame (altered for the video feed) cpX,cpY,cp,ccX,ccY,cc,successfullyDetected = edgeDet.edgeDetectionAlgorithmVideo(threshPupil,threshGlint) #Implement functionality that was used in main to draw around the pupil and glint print('cpX: ', cpX, ' cpY: ', cpY, ' ccX: ', ccX, ' ccY: ', ccY) print successfullyDetected if cpX is None or cpY is None or ccX is None or ccY is None: print('pupil or corneal not detected, skipping...') else: # Ellipse Fitting frameCopy = frame.copy() #draw pupil centre cv2.circle(frameCopy, (cpX,cpY),3,(0,255,0),-1) #draw pupil circumference cv2.drawContours(frameCopy,cp,-1,(0,0,255),3) #draw corneal centre cv2.circle(frameCopy, (ccX,ccY),3,(0,255,0),-1) #draw corneal circumference cv2.drawContours(frameCopy,cc,-1,(0,0,255),3) #If there is a frame to show, show it. if(frameCopy != None): frameC_resized = cv2.resize(frameCopy, (vidWidth, vidHeight), interpolation = cv2.INTER_AREA) frameC_resized = cv2.flip(frameC_resized, 1) img4 = Image.fromarray(frameC_resized) imgtk4 = ImageTk.PhotoImage(image=img4) videoStream4.imgtk4 = imgtk4 videoStream4.configure(image=imgtk4) # Centre points of glint and pupil pass to vector x, y = GGP.getGazePoint(aOriginal, bOriginal, cpX, cpY, ccX, ccY) # Move to coordinates on screen, depending on mouseToggle if mouseToggle: ATE.move_mouse(x,y) #Loop the show fram code videoStream1.after(5, show_frame) show_frame() root.mainloop() cap.release()
gpl-2.0
icdishb/scikit-learn
examples/applications/plot_tomography_l1_reconstruction.py
45
5463
""" ====================================================================== Compressive sensing: tomography reconstruction with L1 prior (Lasso) ====================================================================== This example shows the reconstruction of an image from a set of parallel projections, acquired along different angles. Such a dataset is acquired in **computed tomography** (CT). Without any prior information on the sample, the number of projections required to reconstruct the image is of the order of the linear size ``l`` of the image (in pixels). For simplicity we consider here a sparse image, where only pixels on the boundary of objects have a non-zero value. Such data could correspond for example to a cellular material. Note however that most images are sparse in a different basis, such as the Haar wavelets. Only ``l/7`` projections are acquired, therefore it is necessary to use prior information available on the sample (its sparsity): this is an example of **compressive sensing**. The tomography projection operation is a linear transformation. In addition to the data-fidelity term corresponding to a linear regression, we penalize the L1 norm of the image to account for its sparsity. The resulting optimization problem is called the :ref:`lasso`. We use the class :class:`sklearn.linear_model.Lasso`, that uses the coordinate descent algorithm. Importantly, this implementation is more computationally efficient on a sparse matrix, than the projection operator used here. The reconstruction with L1 penalization gives a result with zero error (all pixels are successfully labeled with 0 or 1), even if noise was added to the projections. In comparison, an L2 penalization (:class:`sklearn.linear_model.Ridge`) produces a large number of labeling errors for the pixels. Important artifacts are observed on the reconstructed image, contrary to the L1 penalization. Note in particular the circular artifact separating the pixels in the corners, that have contributed to fewer projections than the central disk. """ print(__doc__) # Author: Emmanuelle Gouillart <[email protected]> # License: BSD 3 clause import numpy as np from scipy import sparse from scipy import ndimage from sklearn.linear_model import Lasso from sklearn.linear_model import Ridge import matplotlib.pyplot as plt def _weights(x, dx=1, orig=0): x = np.ravel(x) floor_x = np.floor((x - orig) / dx) alpha = (x - orig - floor_x * dx) / dx return np.hstack((floor_x, floor_x + 1)), np.hstack((1 - alpha, alpha)) def _generate_center_coordinates(l_x): l_x = float(l_x) X, Y = np.mgrid[:l_x, :l_x] center = l_x / 2. X += 0.5 - center Y += 0.5 - center return X, Y def build_projection_operator(l_x, n_dir): """ Compute the tomography design matrix. Parameters ---------- l_x : int linear size of image array n_dir : int number of angles at which projections are acquired. Returns ------- p : sparse matrix of shape (n_dir l_x, l_x**2) """ X, Y = _generate_center_coordinates(l_x) angles = np.linspace(0, np.pi, n_dir, endpoint=False) data_inds, weights, camera_inds = [], [], [] data_unravel_indices = np.arange(l_x ** 2) data_unravel_indices = np.hstack((data_unravel_indices, data_unravel_indices)) for i, angle in enumerate(angles): Xrot = np.cos(angle) * X - np.sin(angle) * Y inds, w = _weights(Xrot, dx=1, orig=X.min()) mask = np.logical_and(inds >= 0, inds < l_x) weights += list(w[mask]) camera_inds += list(inds[mask] + i * l_x) data_inds += list(data_unravel_indices[mask]) proj_operator = sparse.coo_matrix((weights, (camera_inds, data_inds))) return proj_operator def generate_synthetic_data(): """ Synthetic binary data """ rs = np.random.RandomState(0) n_pts = 36. x, y = np.ogrid[0:l, 0:l] mask_outer = (x - l / 2) ** 2 + (y - l / 2) ** 2 < (l / 2) ** 2 mask = np.zeros((l, l)) points = l * rs.rand(2, n_pts) mask[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 mask = ndimage.gaussian_filter(mask, sigma=l / n_pts) res = np.logical_and(mask > mask.mean(), mask_outer) return res - ndimage.binary_erosion(res) # Generate synthetic images, and projections l = 128 proj_operator = build_projection_operator(l, l / 7.) data = generate_synthetic_data() proj = proj_operator * data.ravel()[:, np.newaxis] proj += 0.15 * np.random.randn(*proj.shape) # Reconstruction with L2 (Ridge) penalization rgr_ridge = Ridge(alpha=0.2) rgr_ridge.fit(proj_operator, proj.ravel()) rec_l2 = rgr_ridge.coef_.reshape(l, l) # Reconstruction with L1 (Lasso) penalization # the best value of alpha was determined using cross validation # with LassoCV rgr_lasso = Lasso(alpha=0.001) rgr_lasso.fit(proj_operator, proj.ravel()) rec_l1 = rgr_lasso.coef_.reshape(l, l) plt.figure(figsize=(8, 3.3)) plt.subplot(131) plt.imshow(data, cmap=plt.cm.gray, interpolation='nearest') plt.axis('off') plt.title('original image') plt.subplot(132) plt.imshow(rec_l2, cmap=plt.cm.gray, interpolation='nearest') plt.title('L2 penalization') plt.axis('off') plt.subplot(133) plt.imshow(rec_l1, cmap=plt.cm.gray, interpolation='nearest') plt.title('L1 penalization') plt.axis('off') plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1) plt.show()
bsd-3-clause
maxlikely/scikit-learn
sklearn/metrics/pairwise.py
1
28395
# -*- coding: utf-8 -*- """ The :mod:`sklearn.metrics.pairwise` submodule implements utilities to evaluate pairwise distances or affinity of sets of samples. This module contains both distance metrics and kernels. A brief summary is given on the two here. Distance metrics are a function d(a, b) such that d(a, b) < d(a, c) if objects a and b are considered "more similar" to objects a and c. Two objects exactly alike would have a distance of zero. One of the most popular examples is Euclidean distance. To be a 'true' metric, it must obey the following four conditions:: 1. d(a, b) >= 0, for all a and b 2. d(a, b) == 0, if and only if a = b, positive definiteness 3. d(a, b) == d(b, a), symmetry 4. d(a, c) <= d(a, b) + d(b, c), the triangle inequality Kernels are measures of similarity, i.e. ``s(a, b) > s(a, c)`` if objects ``a`` and ``b`` are considered "more similar" to objects ``a`` and ``c``. A kernel must also be positive semi-definite. There are a number of ways to convert between a distance metric and a similarity measure, such as a kernel. Let D be the distance, and S be the kernel: 1. ``S = np.exp(-D * gamma)``, where one heuristic for choosing ``gamma`` is ``1 / num_features`` 2. ``S = 1. / (D / np.max(D))`` """ # Authors: Alexandre Gramfort <[email protected]> # Mathieu Blondel <[email protected]> # Robert Layton <[email protected]> # Andreas Mueller <[email protected]> # License: BSD Style. import numpy as np from scipy.spatial import distance from scipy.sparse import csr_matrix from scipy.sparse import issparse from ..utils import atleast2d_or_csr from ..utils import gen_even_slices from ..utils.extmath import safe_sparse_dot from ..utils.validation import array2d from ..preprocessing import normalize from ..externals.joblib import Parallel from ..externals.joblib import delayed from ..externals.joblib.parallel import cpu_count from .pairwise_fast import _chi2_kernel_fast # Utility Functions def check_pairwise_arrays(X, Y): """ Set X and Y appropriately and checks inputs If Y is None, it is set as a pointer to X (i.e. not a copy). If Y is given, this does not happen. All distance metrics should use this function first to assert that the given parameters are correct and safe to use. Specifically, this function first ensures that both X and Y are arrays, then checks that they are at least two dimensional while ensuring that their elements are floats. Finally, the function checks that the size of the second dimension of the two arrays is equal. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples_a, n_features] Y : {array-like, sparse matrix}, shape = [n_samples_b, n_features] Returns ------- safe_X : {array-like, sparse matrix}, shape = [n_samples_a, n_features] An array equal to X, guarenteed to be a numpy array. safe_Y : {array-like, sparse matrix}, shape = [n_samples_b, n_features] An array equal to Y if Y was not None, guarenteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ if Y is X or Y is None: X = Y = atleast2d_or_csr(X, dtype=np.float) else: X = atleast2d_or_csr(X, dtype=np.float) Y = atleast2d_or_csr(Y, dtype=np.float) if X.shape[1] != Y.shape[1]: raise ValueError("Incompatible dimension for X and Y matrices: " "X.shape[1] == %d while Y.shape[1] == %d" % ( X.shape[1], Y.shape[1])) return X, Y # Distances def euclidean_distances(X, Y=None, Y_norm_squared=None, squared=False): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. For efficiency reasons, the euclidean distance between a pair of row vector x and y is computed as:: dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y)) This formulation has two main advantages. First, it is computationally efficient when dealing with sparse data. Second, if x varies but y remains unchanged, then the right-most dot-product `dot(y, y)` can be pre-computed. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples_1, n_features] Y : {array-like, sparse matrix}, shape = [n_samples_2, n_features] Y_norm_squared : array-like, shape = [n_samples_2], optional Pre-computed dot-products of vectors in Y (e.g., ``(Y**2).sum(axis=1)``) squared : boolean, optional Return squared Euclidean distances. Returns ------- distances : {array, sparse matrix}, shape = [n_samples_1, n_samples_2] Examples -------- >>> from sklearn.metrics.pairwise import euclidean_distances >>> X = [[0, 1], [1, 1]] >>> # distance between rows of X >>> euclidean_distances(X, X) array([[ 0., 1.], [ 1., 0.]]) >>> # get distance to origin >>> euclidean_distances(X, [[0, 0]]) array([[ 1. ], [ 1.41421356]]) """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. X, Y = check_pairwise_arrays(X, Y) if issparse(X): XX = X.multiply(X).sum(axis=1) else: XX = np.sum(X * X, axis=1)[:, np.newaxis] if X is Y: # shortcut in the common case euclidean_distances(X, X) YY = XX.T elif Y_norm_squared is None: if issparse(Y): # scipy.sparse matrices don't have element-wise scalar # exponentiation, and tocsr has a copy kwarg only on CSR matrices. YY = Y.copy() if isinstance(Y, csr_matrix) else Y.tocsr() YY.data **= 2 YY = np.asarray(YY.sum(axis=1)).T else: YY = np.sum(Y ** 2, axis=1)[np.newaxis, :] else: YY = atleast2d_or_csr(Y_norm_squared) if YY.shape != (1, Y.shape[0]): raise ValueError( "Incompatible dimensions for Y and Y_norm_squared") # TODO: a faster Cython implementation would do the clipping of negative # values in a single pass over the output matrix. distances = safe_sparse_dot(X, Y.T, dense_output=True) distances *= -2 distances += XX distances += YY np.maximum(distances, 0, distances) if X is Y: # Ensure that distances between vectors and themselves are set to 0.0. # This may not be the case due to floating point rounding errors. distances.flat[::distances.shape[0] + 1] = 0.0 return distances if squared else np.sqrt(distances) def manhattan_distances(X, Y=None, sum_over_features=True): """ Compute the L1 distances between the vectors in X and Y. With sum_over_features equal to False it returns the componentwise distances. Parameters ---------- X : array_like An array with shape (n_samples_X, n_features). Y : array_like, optional An array with shape (n_samples_Y, n_features). sum_over_features : bool, default=True If True the function returns the pairwise distance matrix else it returns the componentwise L1 pairwise-distances. Returns ------- D : array If sum_over_features is False shape is (n_samples_X * n_samples_Y, n_features) and D contains the componentwise L1 pairwise-distances (ie. absolute difference), else shape is (n_samples_X, n_samples_Y) and D contains the pairwise l1 distances. Examples -------- >>> from sklearn.metrics.pairwise import manhattan_distances >>> manhattan_distances(3, 3)#doctest:+ELLIPSIS array([[ 0.]]) >>> manhattan_distances(3, 2)#doctest:+ELLIPSIS array([[ 1.]]) >>> manhattan_distances(2, 3)#doctest:+ELLIPSIS array([[ 1.]]) >>> manhattan_distances([[1, 2], [3, 4]],\ [[1, 2], [0, 3]])#doctest:+ELLIPSIS array([[ 0., 2.], [ 4., 4.]]) >>> import numpy as np >>> X = np.ones((1, 2)) >>> y = 2 * np.ones((2, 2)) >>> manhattan_distances(X, y, sum_over_features=False)#doctest:+ELLIPSIS array([[ 1., 1.], [ 1., 1.]]...) """ if issparse(X) or issparse(Y): raise ValueError("manhattan_distance does not support sparse" " matrices.") X, Y = check_pairwise_arrays(X, Y) D = np.abs(X[:, np.newaxis, :] - Y[np.newaxis, :, :]) if sum_over_features: D = np.sum(D, axis=2) else: D = D.reshape((-1, X.shape[1])) return D # Kernels def linear_kernel(X, Y=None): """ Compute the linear kernel between X and Y. Parameters ---------- X : array of shape (n_samples_1, n_features) Y : array of shape (n_samples_2, n_features) Returns ------- Gram matrix : array of shape (n_samples_1, n_samples_2) """ X, Y = check_pairwise_arrays(X, Y) return safe_sparse_dot(X, Y.T, dense_output=True) def polynomial_kernel(X, Y=None, degree=3, gamma=None, coef0=1): """ Compute the polynomial kernel between X and Y:: K(X, Y) = (gamma <X, Y> + coef0)^degree Parameters ---------- X : array of shape (n_samples_1, n_features) Y : array of shape (n_samples_2, n_features) degree : int Returns ------- Gram matrix : array of shape (n_samples_1, n_samples_2) """ X, Y = check_pairwise_arrays(X, Y) if gamma is None: gamma = 1.0 / X.shape[1] K = linear_kernel(X, Y) K *= gamma K += coef0 K **= degree return K def sigmoid_kernel(X, Y=None, gamma=None, coef0=1): """ Compute the sigmoid kernel between X and Y:: K(X, Y) = tanh(gamma <X, Y> + coef0) Parameters ---------- X : array of shape (n_samples_1, n_features) Y : array of shape (n_samples_2, n_features) degree : int Returns ------- Gram matrix: array of shape (n_samples_1, n_samples_2) """ X, Y = check_pairwise_arrays(X, Y) if gamma is None: gamma = 1.0 / X.shape[1] K = linear_kernel(X, Y) K *= gamma K += coef0 np.tanh(K, K) # compute tanh in-place return K def rbf_kernel(X, Y=None, gamma=None): """ Compute the rbf (gaussian) kernel between X and Y:: K(x, y) = exp(-γ ||x-y||²) for each pair of rows x in X and y in Y. Parameters ---------- X : array of shape (n_samples_X, n_features) Y : array of shape (n_samples_Y, n_features) gamma : float Returns ------- kernel_matrix : array of shape (n_samples_X, n_samples_Y) """ X, Y = check_pairwise_arrays(X, Y) if gamma is None: gamma = 1.0 / X.shape[1] K = euclidean_distances(X, Y, squared=True) K *= -gamma np.exp(K, K) # exponentiate K in-place return K def cosine_similarity(X, Y=None): """Compute cosine similarity between samples in X and Y. Cosine similarity, or the cosine kernel, computes similarity as the normalized dot product of X and Y: K(X, Y) = <X, Y> / (||X||*||Y||) On L2-normalized data, this function is equivalent to linear_kernel. Parameters ---------- X : array_like, sparse matrix with shape (n_samples_X, n_features). Y : array_like, sparse matrix (optional) with shape (n_samples_Y, n_features). Returns ------- kernel matrix : array_like An array with shape (n_samples_X, n_samples_Y). """ # to avoid recursive import X, Y = check_pairwise_arrays(X, Y) X_normalized = normalize(X, copy=True) if X is Y: Y_normalized = X_normalized else: Y_normalized = normalize(Y, copy=True) K = linear_kernel(X_normalized, Y_normalized) return K def additive_chi2_kernel(X, Y=None): """Computes the additive chi-squared kernel between observations in X and Y The chi-squared kernel is computed between each pair of rows in X and Y. X and Y have to be non-negative. This kernel is most commonly applied to histograms. The chi-squared kernel is given by:: k(x, y) = -∑ᵢ [(xᵢ - yᵢ)² / (xᵢ + yᵢ)] It can be interpreted as a weighted difference per entry. Notes ----- As the negative of a distance, this kernel is only conditionally positive definite. Parameters ---------- X : array-like of shape (n_samples_X, n_features) Y : array of shape (n_samples_Y, n_features) Returns ------- kernel_matrix : array of shape (n_samples_X, n_samples_Y) References ---------- * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 http://eprints.pascal-network.org/archive/00002309/01/Zhang06-IJCV.pdf See also -------- chi2_kernel : The exponentiated version of the kernel, which is usually preferrable. sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation to this kernel. """ if issparse(X) or issparse(Y): raise ValueError("additive_chi2 does not support sparse matrices.") ### we don't use check_pairwise to preserve float32. if Y is None: # optimize this case! X = array2d(X) if X.dtype != np.float32: X.astype(np.float) Y = X if (X < 0).any(): raise ValueError("X contains negative values.") else: X = array2d(X) Y = array2d(Y) if X.shape[1] != Y.shape[1]: raise ValueError("Incompatible dimension for X and Y matrices: " "X.shape[1] == %d while Y.shape[1] == %d" % ( X.shape[1], Y.shape[1])) if X.dtype != np.float32 or Y.dtype != np.float32: # if not both are 32bit float, convert to 64bit float X = X.astype(np.float) Y = Y.astype(np.float) if (X < 0).any(): raise ValueError("X contains negative values.") if (Y < 0).any(): raise ValueError("Y contains negative values.") result = np.zeros((X.shape[0], Y.shape[0]), dtype=X.dtype) _chi2_kernel_fast(X, Y, result) return result def chi2_kernel(X, Y=None, gamma=1.): """Computes the exponential chi-squared kernel X and Y. The chi-squared kernel is computed between each pair of rows in X and Y. X and Y have to be non-negative. This kernel is most commonly applied to histograms. The chi-squared kernel is given by:: k(x, y) = exp(-γ ∑ᵢ [(xᵢ - yᵢ)² / (xᵢ + yᵢ)]) It can be interpreted as a weighted difference per entry. Parameters ---------- X : array-like of shape (n_samples_X, n_features) Y : array of shape (n_samples_Y, n_features) gamma : float, default=1. Scaling parameter of the chi2 kernel. Returns ------- kernel_matrix : array of shape (n_samples_X, n_samples_Y) References ---------- * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. Local features and kernels for classification of texture and object categories: A comprehensive study International Journal of Computer Vision 2007 http://eprints.pascal-network.org/archive/00002309/01/Zhang06-IJCV.pdf See also -------- additive_chi2_kernel : The additive version of this kernel sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation to the additive version of this kernel. """ K = additive_chi2_kernel(X, Y) K *= gamma return np.exp(K, K) # Helper functions - distance PAIRWISE_DISTANCE_FUNCTIONS = { # If updating this dictionary, update the doc in both distance_metrics() # and also in pairwise_distances()! 'euclidean': euclidean_distances, 'l2': euclidean_distances, 'l1': manhattan_distances, 'manhattan': manhattan_distances, 'cityblock': manhattan_distances, } def distance_metrics(): """Valid metrics for pairwise_distances. This function simply returns the valid pairwise distance metrics. It exists to allow for a description of the mapping for each of the valid strings. The valid distance metrics, and the function they map to, are: ============ ==================================== metric Function ============ ==================================== 'cityblock' metrics.pairwise.manhattan_distances 'euclidean' metrics.pairwise.euclidean_distances 'l1' metrics.pairwise.manhattan_distances 'l2' metrics.pairwise.euclidean_distances 'manhattan' metrics.pairwise.manhattan_distances ============ ==================================== """ return PAIRWISE_DISTANCE_FUNCTIONS def _parallel_pairwise(X, Y, func, n_jobs, **kwds): """Break the pairwise matrix in n_jobs even slices and compute them in parallel""" if n_jobs < 0: n_jobs = max(cpu_count() + 1 + n_jobs, 1) if Y is None: Y = X ret = Parallel(n_jobs=n_jobs, verbose=0)( delayed(func)(X, Y[s], **kwds) for s in gen_even_slices(Y.shape[0], n_jobs)) return np.hstack(ret) def pairwise_distances(X, Y=None, metric="euclidean", n_jobs=1, **kwds): """ Compute the distance matrix from a vector array X and optional Y. This method takes either a vector array or a distance matrix, and returns a distance matrix. If the input is a vector array, the distances are computed. If the input is a distances matrix, it is returned instead. This method provides a safe way to take a distance matrix as input, while preserving compatability with many other algorithms that take a vector array. If Y is given (default is None), then the returned matrix is the pairwise distance between the arrays from both X and Y. Please note that support for sparse matrices is currently limited to those metrics listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS. Valid values for metric are: - from scikit-learn: ['euclidean', 'l2', 'l1', 'manhattan', 'cityblock'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'cosine', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. Note in the case of 'euclidean' and 'cityblock' (which are valid scipy.spatial.distance metrics), the values will use the scikit-learn implementation, which is faster and has support for sparse matrices. For a verbose description of the metrics from scikit-learn, see the __doc__ of the sklearn.pairwise.distance_metrics function. Parameters ---------- X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise distances between samples, or a feature array. Y : array [n_samples_b, n_features] A second feature array only if X has shape [n_samples_a, n_features]. metric : string, or callable The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by scipy.spatial.distance.pdist for its metric parameter, or a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS. If metric is "precomputed", X is assumed to be a distance matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays from X as input and return a value indicating the distance between them. n_jobs : int The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debuging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. `**kwds` : optional keyword parameters Any further parameters are passed directly to the distance function. If using a scipy.spatial.distance metric, the parameters are still metric dependent. See the scipy docs for usage examples. Returns ------- D : array [n_samples_a, n_samples_a] or [n_samples_a, n_samples_b] A distance matrix D such that D_{i, j} is the distance between the ith and jth vectors of the given matrix X, if Y is None. If Y is not None, then D_{i, j} is the distance between the ith array from X and the jth array from Y. """ if metric == "precomputed": return X elif metric in PAIRWISE_DISTANCE_FUNCTIONS: func = PAIRWISE_DISTANCE_FUNCTIONS[metric] if n_jobs == 1: return func(X, Y, **kwds) else: return _parallel_pairwise(X, Y, func, n_jobs, **kwds) elif callable(metric): # Check matrices first (this is usually done by the metric). X, Y = check_pairwise_arrays(X, Y) n_x, n_y = X.shape[0], Y.shape[0] # Calculate distance for each element in X and Y. # FIXME: can use n_jobs here too D = np.zeros((n_x, n_y), dtype='float') for i in range(n_x): start = 0 if X is Y: start = i for j in range(start, n_y): # distance assumed to be symmetric. D[i][j] = metric(X[i], Y[j], **kwds) if X is Y: D[j][i] = D[i][j] return D else: # Note: the distance module doesn't support sparse matrices! if type(X) is csr_matrix: raise TypeError("scipy distance metrics do not" " support sparse matrices.") if Y is None: return distance.squareform(distance.pdist(X, metric=metric, **kwds)) else: if type(Y) is csr_matrix: raise TypeError("scipy distance metrics do not" " support sparse matrices.") return distance.cdist(X, Y, metric=metric, **kwds) # Helper functions - distance PAIRWISE_KERNEL_FUNCTIONS = { # If updating this dictionary, update the doc in both distance_metrics() # and also in pairwise_distances()! 'additive_chi2': additive_chi2_kernel, 'chi2': chi2_kernel, 'linear': linear_kernel, 'polynomial': polynomial_kernel, 'poly': polynomial_kernel, 'rbf': rbf_kernel, 'sigmoid': sigmoid_kernel, 'cosine': cosine_similarity, } def kernel_metrics(): """ Valid metrics for pairwise_kernels This function simply returns the valid pairwise distance metrics. It exists, however, to allow for a verbose description of the mapping for each of the valid strings. The valid distance metrics, and the function they map to, are: =============== ======================================== metric Function =============== ======================================== 'additive_chi2' sklearn.pairwise.additive_chi2_kernel 'chi2' sklearn.pairwise.chi2_kernel 'linear' sklearn.pairwise.linear_kernel 'poly' sklearn.pairwise.polynomial_kernel 'polynomial' sklearn.pairwise.polynomial_kernel 'rbf' sklearn.pairwise.rbf_kernel 'sigmoid' sklearn.pairwise.sigmoid_kernel 'cosine' sklearn.pairwise.cosine_similarity =============== ======================================== """ return PAIRWISE_KERNEL_FUNCTIONS KERNEL_PARAMS = { "chi2": (), "exp_chi2": set(("gamma", )), "linear": (), "rbf": set(("gamma",)), "sigmoid": set(("gamma", "coef0")), "polynomial": set(("gamma", "degree", "coef0")), "poly": set(("gamma", "degree", "coef0")), "cosine": set(), } def pairwise_kernels(X, Y=None, metric="linear", filter_params=False, n_jobs=1, **kwds): """ Compute the kernel between arrays X and optional array Y. This method takes either a vector array or a kernel matrix, and returns a kernel matrix. If the input is a vector array, the kernels are computed. If the input is a kernel matrix, it is returned instead. This method provides a safe way to take a kernel matrix as input, while preserving compatability with many other algorithms that take a vector array. If Y is given (default is None), then the returned matrix is the pairwise kernel between the arrays from both X and Y. Valid values for metric are:: ['rbf', 'sigmoid', 'polynomial', 'poly', 'linear', 'cosine'] Parameters ---------- X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \ [n_samples_a, n_features] otherwise Array of pairwise kernels between samples, or a feature array. Y : array [n_samples_b, n_features] A second feature array only if X has shape [n_samples_a, n_features]. metric : string, or callable The metric to use when calculating kernel between instances in a feature array. If metric is a string, it must be one of the metrics in pairwise.PAIRWISE_KERNEL_FUNCTIONS. If metric is "precomputed", X is assumed to be a kernel matrix. Alternatively, if metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays from X as input and return a value indicating the distance between them. n_jobs : int The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debuging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. filter_params: boolean Whether to filter invalid parameters or not. `**kwds` : optional keyword parameters Any further parameters are passed directly to the kernel function. Returns ------- K : array [n_samples_a, n_samples_a] or [n_samples_a, n_samples_b] A kernel matrix K such that K_{i, j} is the kernel between the ith and jth vectors of the given matrix X, if Y is None. If Y is not None, then K_{i, j} is the kernel between the ith array from X and the jth array from Y. Notes ----- If metric is 'precomputed', Y is ignored and X is returned. """ if metric == "precomputed": return X elif metric in PAIRWISE_KERNEL_FUNCTIONS: if filter_params: kwds = dict((k, kwds[k]) for k in kwds if k in KERNEL_PARAMS[metric]) func = PAIRWISE_KERNEL_FUNCTIONS[metric] if n_jobs == 1: return func(X, Y, **kwds) else: return _parallel_pairwise(X, Y, func, n_jobs, **kwds) elif callable(metric): # Check matrices first (this is usually done by the metric). X, Y = check_pairwise_arrays(X, Y) n_x, n_y = X.shape[0], Y.shape[0] # Calculate kernel for each element in X and Y. K = np.zeros((n_x, n_y), dtype='float') for i in range(n_x): start = 0 if X is Y: start = i for j in range(start, n_y): # Kernel assumed to be symmetric. K[i][j] = metric(X[i], Y[j], **kwds) if X is Y: K[j][i] = K[i][j] return K else: raise AttributeError("Unknown metric %s" % metric)
bsd-3-clause
gclenaghan/scikit-learn
sklearn/decomposition/tests/test_incremental_pca.py
297
8265
"""Tests for Incremental PCA.""" import numpy as np from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_raises from sklearn import datasets from sklearn.decomposition import PCA, IncrementalPCA iris = datasets.load_iris() def test_incremental_pca(): # Incremental PCA on dense arrays. X = iris.data batch_size = X.shape[0] // 3 ipca = IncrementalPCA(n_components=2, batch_size=batch_size) pca = PCA(n_components=2) pca.fit_transform(X) X_transformed = ipca.fit_transform(X) np.testing.assert_equal(X_transformed.shape, (X.shape[0], 2)) assert_almost_equal(ipca.explained_variance_ratio_.sum(), pca.explained_variance_ratio_.sum(), 1) for n_components in [1, 2, X.shape[1]]: ipca = IncrementalPCA(n_components, batch_size=batch_size) ipca.fit(X) cov = ipca.get_covariance() precision = ipca.get_precision() assert_array_almost_equal(np.dot(cov, precision), np.eye(X.shape[1])) def test_incremental_pca_check_projection(): # Test that the projection of data is correct. rng = np.random.RandomState(1999) n, p = 100, 3 X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5]) Xt = 0.1 * rng.randn(1, p) + np.array([3, 4, 5]) # Get the reconstruction of the generated data X # Note that Xt has the same "components" as X, just separated # This is what we want to ensure is recreated correctly Yt = IncrementalPCA(n_components=2).fit(X).transform(Xt) # Normalize Yt /= np.sqrt((Yt ** 2).sum()) # Make sure that the first element of Yt is ~1, this means # the reconstruction worked as expected assert_almost_equal(np.abs(Yt[0][0]), 1., 1) def test_incremental_pca_inverse(): # Test that the projection of data can be inverted. rng = np.random.RandomState(1999) n, p = 50, 3 X = rng.randn(n, p) # spherical data X[:, 1] *= .00001 # make middle component relatively small X += [5, 4, 3] # make a large mean # same check that we can find the original data from the transformed # signal (since the data is almost of rank n_components) ipca = IncrementalPCA(n_components=2, batch_size=10).fit(X) Y = ipca.transform(X) Y_inverse = ipca.inverse_transform(Y) assert_almost_equal(X, Y_inverse, decimal=3) def test_incremental_pca_validation(): # Test that n_components is >=1 and <= n_features. X = [[0, 1], [1, 0]] for n_components in [-1, 0, .99, 3]: assert_raises(ValueError, IncrementalPCA(n_components, batch_size=10).fit, X) def test_incremental_pca_set_params(): # Test that components_ sign is stable over batch sizes. rng = np.random.RandomState(1999) n_samples = 100 n_features = 20 X = rng.randn(n_samples, n_features) X2 = rng.randn(n_samples, n_features) X3 = rng.randn(n_samples, n_features) ipca = IncrementalPCA(n_components=20) ipca.fit(X) # Decreasing number of components ipca.set_params(n_components=10) assert_raises(ValueError, ipca.partial_fit, X2) # Increasing number of components ipca.set_params(n_components=15) assert_raises(ValueError, ipca.partial_fit, X3) # Returning to original setting ipca.set_params(n_components=20) ipca.partial_fit(X) def test_incremental_pca_num_features_change(): # Test that changing n_components will raise an error. rng = np.random.RandomState(1999) n_samples = 100 X = rng.randn(n_samples, 20) X2 = rng.randn(n_samples, 50) ipca = IncrementalPCA(n_components=None) ipca.fit(X) assert_raises(ValueError, ipca.partial_fit, X2) def test_incremental_pca_batch_signs(): # Test that components_ sign is stable over batch sizes. rng = np.random.RandomState(1999) n_samples = 100 n_features = 3 X = rng.randn(n_samples, n_features) all_components = [] batch_sizes = np.arange(10, 20) for batch_size in batch_sizes: ipca = IncrementalPCA(n_components=None, batch_size=batch_size).fit(X) all_components.append(ipca.components_) for i, j in zip(all_components[:-1], all_components[1:]): assert_almost_equal(np.sign(i), np.sign(j), decimal=6) def test_incremental_pca_batch_values(): # Test that components_ values are stable over batch sizes. rng = np.random.RandomState(1999) n_samples = 100 n_features = 3 X = rng.randn(n_samples, n_features) all_components = [] batch_sizes = np.arange(20, 40, 3) for batch_size in batch_sizes: ipca = IncrementalPCA(n_components=None, batch_size=batch_size).fit(X) all_components.append(ipca.components_) for i, j in zip(all_components[:-1], all_components[1:]): assert_almost_equal(i, j, decimal=1) def test_incremental_pca_partial_fit(): # Test that fit and partial_fit get equivalent results. rng = np.random.RandomState(1999) n, p = 50, 3 X = rng.randn(n, p) # spherical data X[:, 1] *= .00001 # make middle component relatively small X += [5, 4, 3] # make a large mean # same check that we can find the original data from the transformed # signal (since the data is almost of rank n_components) batch_size = 10 ipca = IncrementalPCA(n_components=2, batch_size=batch_size).fit(X) pipca = IncrementalPCA(n_components=2, batch_size=batch_size) # Add one to make sure endpoint is included batch_itr = np.arange(0, n + 1, batch_size) for i, j in zip(batch_itr[:-1], batch_itr[1:]): pipca.partial_fit(X[i:j, :]) assert_almost_equal(ipca.components_, pipca.components_, decimal=3) def test_incremental_pca_against_pca_iris(): # Test that IncrementalPCA and PCA are approximate (to a sign flip). X = iris.data Y_pca = PCA(n_components=2).fit_transform(X) Y_ipca = IncrementalPCA(n_components=2, batch_size=25).fit_transform(X) assert_almost_equal(np.abs(Y_pca), np.abs(Y_ipca), 1) def test_incremental_pca_against_pca_random_data(): # Test that IncrementalPCA and PCA are approximate (to a sign flip). rng = np.random.RandomState(1999) n_samples = 100 n_features = 3 X = rng.randn(n_samples, n_features) + 5 * rng.rand(1, n_features) Y_pca = PCA(n_components=3).fit_transform(X) Y_ipca = IncrementalPCA(n_components=3, batch_size=25).fit_transform(X) assert_almost_equal(np.abs(Y_pca), np.abs(Y_ipca), 1) def test_explained_variances(): # Test that PCA and IncrementalPCA calculations match X = datasets.make_low_rank_matrix(1000, 100, tail_strength=0., effective_rank=10, random_state=1999) prec = 3 n_samples, n_features = X.shape for nc in [None, 99]: pca = PCA(n_components=nc).fit(X) ipca = IncrementalPCA(n_components=nc, batch_size=100).fit(X) assert_almost_equal(pca.explained_variance_, ipca.explained_variance_, decimal=prec) assert_almost_equal(pca.explained_variance_ratio_, ipca.explained_variance_ratio_, decimal=prec) assert_almost_equal(pca.noise_variance_, ipca.noise_variance_, decimal=prec) def test_whitening(): # Test that PCA and IncrementalPCA transforms match to sign flip. X = datasets.make_low_rank_matrix(1000, 10, tail_strength=0., effective_rank=2, random_state=1999) prec = 3 n_samples, n_features = X.shape for nc in [None, 9]: pca = PCA(whiten=True, n_components=nc).fit(X) ipca = IncrementalPCA(whiten=True, n_components=nc, batch_size=250).fit(X) Xt_pca = pca.transform(X) Xt_ipca = ipca.transform(X) assert_almost_equal(np.abs(Xt_pca), np.abs(Xt_ipca), decimal=prec) Xinv_ipca = ipca.inverse_transform(Xt_ipca) Xinv_pca = pca.inverse_transform(Xt_pca) assert_almost_equal(X, Xinv_ipca, decimal=prec) assert_almost_equal(X, Xinv_pca, decimal=prec) assert_almost_equal(Xinv_pca, Xinv_ipca, decimal=prec)
bsd-3-clause
courtarro/gnuradio
gr-filter/examples/channelize.py
58
7003
#!/usr/bin/env python # # Copyright 2009,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter import sys, time try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: import scipy from scipy import fftpack except ImportError: sys.stderr.write("Error: Program requires scipy (see: www.scipy.org).\n") sys.exit(1) try: import pylab from pylab import mlab except ImportError: sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) class pfb_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self._N = 2000000 # number of samples to use self._fs = 1000 # initial sampling rate self._M = M = 9 # Number of channels to channelize self._ifs = M*self._fs # initial sampling rate # Create a set of taps for the PFB channelizer self._taps = filter.firdes.low_pass_2(1, self._ifs, 475.50, 50, attenuation_dB=100, window=filter.firdes.WIN_BLACKMAN_hARRIS) # Calculate the number of taps per channel for our own information tpc = scipy.ceil(float(len(self._taps)) / float(self._M)) print "Number of taps: ", len(self._taps) print "Number of channels: ", self._M print "Taps per channel: ", tpc # Create a set of signals at different frequencies # freqs lists the frequencies of the signals that get stored # in the list "signals", which then get summed together self.signals = list() self.add = blocks.add_cc() freqs = [-70, -50, -30, -10, 10, 20, 40, 60, 80] for i in xrange(len(freqs)): f = freqs[i] + (M/2-M+i+1)*self._fs self.signals.append(analog.sig_source_c(self._ifs, analog.GR_SIN_WAVE, f, 1)) self.connect(self.signals[i], (self.add,i)) self.head = blocks.head(gr.sizeof_gr_complex, self._N) # Construct the channelizer filter self.pfb = filter.pfb.channelizer_ccf(self._M, self._taps, 1) # Construct a vector sink for the input signal to the channelizer self.snk_i = blocks.vector_sink_c() # Connect the blocks self.connect(self.add, self.head, self.pfb) self.connect(self.add, self.snk_i) # Use this to play with the channel mapping #self.pfb.set_channel_map([5,6,7,8,0,1,2,3,4]) # Create a vector sink for each of M output channels of the filter and connect it self.snks = list() for i in xrange(self._M): self.snks.append(blocks.vector_sink_c()) self.connect((self.pfb, i), self.snks[i]) def main(): tstart = time.time() tb = pfb_top_block() tb.run() tend = time.time() print "Run time: %f" % (tend - tstart) if 1: fig_in = pylab.figure(1, figsize=(16,9), facecolor="w") fig1 = pylab.figure(2, figsize=(16,9), facecolor="w") fig2 = pylab.figure(3, figsize=(16,9), facecolor="w") Ns = 1000 Ne = 10000 fftlen = 8192 winfunc = scipy.blackman fs = tb._ifs # Plot the input signal on its own figure d = tb.snk_i.data()[Ns:Ne] spin_f = fig_in.add_subplot(2, 1, 1) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_in = 10.0*scipy.log10(abs(X)) f_in = scipy.arange(-fs/2.0, fs/2.0, fs/float(X_in.size)) pin_f = spin_f.plot(f_in, X_in, "b") spin_f.set_xlim([min(f_in), max(f_in)+1]) spin_f.set_ylim([-200.0, 50.0]) spin_f.set_title("Input Signal", weight="bold") spin_f.set_xlabel("Frequency (Hz)") spin_f.set_ylabel("Power (dBW)") Ts = 1.0/fs Tmax = len(d)*Ts t_in = scipy.arange(0, Tmax, Ts) x_in = scipy.array(d) spin_t = fig_in.add_subplot(2, 1, 2) pin_t = spin_t.plot(t_in, x_in.real, "b") pin_t = spin_t.plot(t_in, x_in.imag, "r") spin_t.set_xlabel("Time (s)") spin_t.set_ylabel("Amplitude") Ncols = int(scipy.floor(scipy.sqrt(tb._M))) Nrows = int(scipy.floor(tb._M / Ncols)) if(tb._M % Ncols != 0): Nrows += 1 # Plot each of the channels outputs. Frequencies on Figure 2 and # time signals on Figure 3 fs_o = tb._fs Ts_o = 1.0/fs_o Tmax_o = len(d)*Ts_o for i in xrange(len(tb.snks)): # remove issues with the transients at the beginning # also remove some corruption at the end of the stream # this is a bug, probably due to the corner cases d = tb.snks[i].data()[Ns:Ne] sp1_f = fig1.add_subplot(Nrows, Ncols, 1+i) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs_o, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_o = 10.0*scipy.log10(abs(X)) f_o = scipy.arange(-fs_o/2.0, fs_o/2.0, fs_o/float(X_o.size)) p2_f = sp1_f.plot(f_o, X_o, "b") sp1_f.set_xlim([min(f_o), max(f_o)+1]) sp1_f.set_ylim([-200.0, 50.0]) sp1_f.set_title(("Channel %d" % i), weight="bold") sp1_f.set_xlabel("Frequency (Hz)") sp1_f.set_ylabel("Power (dBW)") x_o = scipy.array(d) t_o = scipy.arange(0, Tmax_o, Ts_o) sp2_o = fig2.add_subplot(Nrows, Ncols, 1+i) p2_o = sp2_o.plot(t_o, x_o.real, "b") p2_o = sp2_o.plot(t_o, x_o.imag, "r") sp2_o.set_xlim([min(t_o), max(t_o)+1]) sp2_o.set_ylim([-2, 2]) sp2_o.set_title(("Channel %d" % i), weight="bold") sp2_o.set_xlabel("Time (s)") sp2_o.set_ylabel("Amplitude") pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass
gpl-3.0
rhiever/bokeh
examples/plotting/file/glucose.py
18
1552
import pandas as pd from bokeh.sampledata.glucose import data from bokeh.plotting import figure, show, output_file, vplot output_file("glucose.html", title="glucose.py example") TOOLS = "pan,wheel_zoom,box_zoom,reset,save" p1 = figure(x_axis_type="datetime", tools=TOOLS) p1.line(data.index, data['glucose'], color='red', legend='glucose') p1.line(data.index, data['isig'], color='blue', legend='isig') p1.title = "Glucose Measurements" p1.xaxis.axis_label = 'Date' p1.yaxis.axis_label = 'Value' day = data.ix['2010-10-06'] highs = day[day['glucose'] > 180] lows = day[day['glucose'] < 80] p2 = figure(x_axis_type="datetime", tools=TOOLS) p2.line(day.index.to_series(), day['glucose'], line_color="gray", line_dash="4 4", line_width=1, legend="glucose") p2.circle(highs.index, highs['glucose'], size=6, color='tomato', legend="high") p2.circle(lows.index, lows['glucose'], size=6, color='navy', legend="low") p2.title = "Glucose Range" p2.xgrid[0].grid_line_color=None p2.ygrid[0].grid_line_alpha=0.5 p2.xaxis.axis_label = 'Time' p2.yaxis.axis_label = 'Value' data['inrange'] = (data['glucose'] < 180) & (data['glucose'] > 80) window = 30.5*288 #288 is average number of samples in a month inrange = pd.rolling_sum(data.inrange, window) inrange = inrange.dropna() inrange = inrange/float(window) p3 = figure(x_axis_type="datetime", tools=TOOLS) p3.line(inrange.index, inrange, line_color="navy") p3.title = "Glucose In-Range Rolling Sum" p3.xaxis.axis_label = 'Date' p3.yaxis.axis_label = 'Proportion In-Range' show(vplot(p1,p2,p3))
bsd-3-clause
kuntzer/SALSA-public
3c_angle_usage.py
1
2662
''' 3c_angle_usage.py ========================= AIM: Plots the diagonistic angle usage of the PST in SALSA. Requires the monitor_angle_usage=True in 1_compute_<p>.py and log_all_data = .true. in straylight_<orbit_id>_<p>/CODE/parameter. INPUT: files: - <orbit_id>_misc/orbits.dat - <orbit_id>_flux/angles_<orbit_number>.dat variables: see section PARAMETERS (below) OUTPUT: in <orbit_id>_misc/ : file one stat file in <orbit_id>_figures/ : step distribution, step in function of time CMD: python 3b_angle_usage.py ISSUES: <none known> REQUIRES:- LATEX, epstopdf, pdfcrop, standard python libraries, specific libraries in resources/ - Structure of the root folder: * <orbit_id>_flux/ --> flux files * <orbit_id>_figures/ --> figures * <orbit_id>_misc/ --> storages of data * all_figures/ --> comparison figures REMARKS: This is a better version than the 3b_angle_usage.py ''' ########################################################################### ### INCLUDES import numpy as np import pylab as plt from resources.routines import * from resources.TimeStepping import * import resources.figures as figures from matplotlib import cm ########################################################################### orbit_id = 704 sl_angle = 35 fancy = True show = True save = True # Bins and their legends orbit_ini = [1,441,891,1331,1771,2221,2661,3111,3551,3991,4441,4881,1] orbit_end = [441,891,1331,1771,2221,2661,3111,3551,3991,4441,4881,5322,5322] legends = ['Jan','Feb','Mar','Avr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Year'] ########################################################################### if fancy: figures.set_fancy() # Formatted folders definitions folder_flux, folder_figures, folder_misc = init_folders(orbit_id) fig, ax = plt.subplots(1) ii = 0. size = len(orbit_ini) minv=100 maxv=0 for ini, end,label in zip(orbit_ini,orbit_end,legends): print ini, end, label c = cm.rainbow(ii/float(size)) fname = '%sangle_usage_%d_%d_%d-%d.dat' % (folder_misc,orbit_id,sl_angle,ini,end) values = np.loadtxt(fname) plt.plot(values[:,0], values[:,1],label=label, lw=2, c=c) if np.min(values[:,1]) < minv: minv = np.min(values[:,1]) if np.max(values[:,1]) > maxv: maxv = np.max(values[:,1]) ii += 1 plt.ylim( [ np.floor(minv), np.ceil(maxv) ] ) plt.xlabel(r'$\theta\ \mathrm{Angular}\ \mathrm{distance}\ \mathrm{to}\ \mathrm{limb}\ \mathrm{[deg]}$') plt.ylabel('\% of calls') plt.legend(loc=2,prop={'size':14}, ncol=2) plt.grid() if show: plt.show() # Saves the figure if save: fname = '%stot_angle_usage_%d_%d' % (folder_figures,orbit_id,sl_angle) figures.savefig(fname,fig,fancy)
bsd-3-clause
MechCoder/scikit-learn
benchmarks/bench_plot_omp_lars.py
72
4514
"""Benchmarks of orthogonal matching pursuit (:ref:`OMP`) versus least angle regression (:ref:`least_angle_regression`) The input data is mostly low rank but is a fat infinite tail. """ from __future__ import print_function import gc import sys from time import time import six import numpy as np from sklearn.linear_model import lars_path, orthogonal_mp from sklearn.datasets.samples_generator import make_sparse_coded_signal def compute_bench(samples_range, features_range): it = 0 results = dict() lars = np.empty((len(features_range), len(samples_range))) lars_gram = lars.copy() omp = lars.copy() omp_gram = lars.copy() max_it = len(samples_range) * len(features_range) for i_s, n_samples in enumerate(samples_range): for i_f, n_features in enumerate(features_range): it += 1 n_informative = n_features / 10 print('====================') print('Iteration %03d of %03d' % (it, max_it)) print('====================') # dataset_kwargs = { # 'n_train_samples': n_samples, # 'n_test_samples': 2, # 'n_features': n_features, # 'n_informative': n_informative, # 'effective_rank': min(n_samples, n_features) / 10, # #'effective_rank': None, # 'bias': 0.0, # } dataset_kwargs = { 'n_samples': 1, 'n_components': n_features, 'n_features': n_samples, 'n_nonzero_coefs': n_informative, 'random_state': 0 } print("n_samples: %d" % n_samples) print("n_features: %d" % n_features) y, X, _ = make_sparse_coded_signal(**dataset_kwargs) X = np.asfortranarray(X) gc.collect() print("benchmarking lars_path (with Gram):", end='') sys.stdout.flush() tstart = time() G = np.dot(X.T, X) # precomputed Gram matrix Xy = np.dot(X.T, y) lars_path(X, y, Xy=Xy, Gram=G, max_iter=n_informative) delta = time() - tstart print("%0.3fs" % delta) lars_gram[i_f, i_s] = delta gc.collect() print("benchmarking lars_path (without Gram):", end='') sys.stdout.flush() tstart = time() lars_path(X, y, Gram=None, max_iter=n_informative) delta = time() - tstart print("%0.3fs" % delta) lars[i_f, i_s] = delta gc.collect() print("benchmarking orthogonal_mp (with Gram):", end='') sys.stdout.flush() tstart = time() orthogonal_mp(X, y, precompute=True, n_nonzero_coefs=n_informative) delta = time() - tstart print("%0.3fs" % delta) omp_gram[i_f, i_s] = delta gc.collect() print("benchmarking orthogonal_mp (without Gram):", end='') sys.stdout.flush() tstart = time() orthogonal_mp(X, y, precompute=False, n_nonzero_coefs=n_informative) delta = time() - tstart print("%0.3fs" % delta) omp[i_f, i_s] = delta results['time(LARS) / time(OMP)\n (w/ Gram)'] = (lars_gram / omp_gram) results['time(LARS) / time(OMP)\n (w/o Gram)'] = (lars / omp) return results if __name__ == '__main__': samples_range = np.linspace(1000, 5000, 5).astype(np.int) features_range = np.linspace(1000, 5000, 5).astype(np.int) results = compute_bench(samples_range, features_range) max_time = max(np.max(t) for t in results.values()) import matplotlib.pyplot as plt fig = plt.figure('scikit-learn OMP vs. LARS benchmark results') for i, (label, timings) in enumerate(sorted(six.iteritems(results))): ax = fig.add_subplot(1, 2, i+1) vmax = max(1 - timings.min(), -1 + timings.max()) plt.matshow(timings, fignum=False, vmin=1 - vmax, vmax=1 + vmax) ax.set_xticklabels([''] + [str(each) for each in samples_range]) ax.set_yticklabels([''] + [str(each) for each in features_range]) plt.xlabel('n_samples') plt.ylabel('n_features') plt.title(label) plt.subplots_adjust(0.1, 0.08, 0.96, 0.98, 0.4, 0.63) ax = plt.axes([0.1, 0.08, 0.8, 0.06]) plt.colorbar(cax=ax, orientation='horizontal') plt.show()
bsd-3-clause
datapythonista/pandas
pandas/tests/arrays/boolean/test_logical.py
7
8486
import operator import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.arrays import BooleanArray from pandas.tests.extension.base import BaseOpsUtil class TestLogicalOps(BaseOpsUtil): def test_numpy_scalars_ok(self, all_logical_operators): a = pd.array([True, False, None], dtype="boolean") op = getattr(a, all_logical_operators) tm.assert_extension_array_equal(op(True), op(np.bool_(True))) tm.assert_extension_array_equal(op(False), op(np.bool_(False))) def get_op_from_name(self, op_name): short_opname = op_name.strip("_") short_opname = short_opname if "xor" in short_opname else short_opname + "_" try: op = getattr(operator, short_opname) except AttributeError: # Assume it is the reverse operator rop = getattr(operator, short_opname[1:]) op = lambda x, y: rop(y, x) return op def test_empty_ok(self, all_logical_operators): a = pd.array([], dtype="boolean") op_name = all_logical_operators result = getattr(a, op_name)(True) tm.assert_extension_array_equal(a, result) result = getattr(a, op_name)(False) tm.assert_extension_array_equal(a, result) # FIXME: dont leave commented-out # TODO: pd.NA # result = getattr(a, op_name)(pd.NA) # tm.assert_extension_array_equal(a, result) def test_logical_length_mismatch_raises(self, all_logical_operators): op_name = all_logical_operators a = pd.array([True, False, None], dtype="boolean") msg = "Lengths must match to compare" with pytest.raises(ValueError, match=msg): getattr(a, op_name)([True, False]) with pytest.raises(ValueError, match=msg): getattr(a, op_name)(np.array([True, False])) with pytest.raises(ValueError, match=msg): getattr(a, op_name)(pd.array([True, False], dtype="boolean")) def test_logical_nan_raises(self, all_logical_operators): op_name = all_logical_operators a = pd.array([True, False, None], dtype="boolean") msg = "Got float instead" with pytest.raises(TypeError, match=msg): getattr(a, op_name)(np.nan) @pytest.mark.parametrize("other", ["a", 1]) def test_non_bool_or_na_other_raises(self, other, all_logical_operators): a = pd.array([True, False], dtype="boolean") with pytest.raises(TypeError, match=str(type(other).__name__)): getattr(a, all_logical_operators)(other) def test_kleene_or(self): # A clear test of behavior. a = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean") b = pd.array([True, False, None] * 3, dtype="boolean") result = a | b expected = pd.array( [True, True, True, True, False, None, True, None, None], dtype="boolean" ) tm.assert_extension_array_equal(result, expected) result = b | a tm.assert_extension_array_equal(result, expected) # ensure we haven't mutated anything inplace tm.assert_extension_array_equal( a, pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean") ) tm.assert_extension_array_equal( b, pd.array([True, False, None] * 3, dtype="boolean") ) @pytest.mark.parametrize( "other, expected", [ (pd.NA, [True, None, None]), (True, [True, True, True]), (np.bool_(True), [True, True, True]), (False, [True, False, None]), (np.bool_(False), [True, False, None]), ], ) def test_kleene_or_scalar(self, other, expected): # TODO: test True & False a = pd.array([True, False, None], dtype="boolean") result = a | other expected = pd.array(expected, dtype="boolean") tm.assert_extension_array_equal(result, expected) result = other | a tm.assert_extension_array_equal(result, expected) # ensure we haven't mutated anything inplace tm.assert_extension_array_equal( a, pd.array([True, False, None], dtype="boolean") ) def test_kleene_and(self): # A clear test of behavior. a = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean") b = pd.array([True, False, None] * 3, dtype="boolean") result = a & b expected = pd.array( [True, False, None, False, False, False, None, False, None], dtype="boolean" ) tm.assert_extension_array_equal(result, expected) result = b & a tm.assert_extension_array_equal(result, expected) # ensure we haven't mutated anything inplace tm.assert_extension_array_equal( a, pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean") ) tm.assert_extension_array_equal( b, pd.array([True, False, None] * 3, dtype="boolean") ) @pytest.mark.parametrize( "other, expected", [ (pd.NA, [None, False, None]), (True, [True, False, None]), (False, [False, False, False]), (np.bool_(True), [True, False, None]), (np.bool_(False), [False, False, False]), ], ) def test_kleene_and_scalar(self, other, expected): a = pd.array([True, False, None], dtype="boolean") result = a & other expected = pd.array(expected, dtype="boolean") tm.assert_extension_array_equal(result, expected) result = other & a tm.assert_extension_array_equal(result, expected) # ensure we haven't mutated anything inplace tm.assert_extension_array_equal( a, pd.array([True, False, None], dtype="boolean") ) def test_kleene_xor(self): a = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean") b = pd.array([True, False, None] * 3, dtype="boolean") result = a ^ b expected = pd.array( [False, True, None, True, False, None, None, None, None], dtype="boolean" ) tm.assert_extension_array_equal(result, expected) result = b ^ a tm.assert_extension_array_equal(result, expected) # ensure we haven't mutated anything inplace tm.assert_extension_array_equal( a, pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean") ) tm.assert_extension_array_equal( b, pd.array([True, False, None] * 3, dtype="boolean") ) @pytest.mark.parametrize( "other, expected", [ (pd.NA, [None, None, None]), (True, [False, True, None]), (np.bool_(True), [False, True, None]), (np.bool_(False), [True, False, None]), ], ) def test_kleene_xor_scalar(self, other, expected): a = pd.array([True, False, None], dtype="boolean") result = a ^ other expected = pd.array(expected, dtype="boolean") tm.assert_extension_array_equal(result, expected) result = other ^ a tm.assert_extension_array_equal(result, expected) # ensure we haven't mutated anything inplace tm.assert_extension_array_equal( a, pd.array([True, False, None], dtype="boolean") ) @pytest.mark.parametrize("other", [True, False, pd.NA, [True, False, None] * 3]) def test_no_masked_assumptions(self, other, all_logical_operators): # The logical operations should not assume that masked values are False! a = pd.arrays.BooleanArray( np.array([True, True, True, False, False, False, True, False, True]), np.array([False] * 6 + [True, True, True]), ) b = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean") if isinstance(other, list): other = pd.array(other, dtype="boolean") result = getattr(a, all_logical_operators)(other) expected = getattr(b, all_logical_operators)(other) tm.assert_extension_array_equal(result, expected) if isinstance(other, BooleanArray): other._data[other._mask] = True a._data[a._mask] = False result = getattr(a, all_logical_operators)(other) expected = getattr(b, all_logical_operators)(other) tm.assert_extension_array_equal(result, expected)
bsd-3-clause
zasdfgbnm/tensorflow
tensorflow/contrib/learn/python/learn/estimators/__init__.py
34
12484
# 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. # ============================================================================== """An estimator is a rule for calculating an estimate of a given quantity. # Estimators * **Estimators** are used to train and evaluate TensorFlow models. They support regression and classification problems. * **Classifiers** are functions that have discrete outcomes. * **Regressors** are functions that predict continuous values. ## Choosing the correct estimator * For **Regression** problems use one of the following: * `LinearRegressor`: Uses linear model. * `DNNRegressor`: Uses DNN. * `DNNLinearCombinedRegressor`: Uses Wide & Deep. * `TensorForestEstimator`: Uses RandomForest. See tf.contrib.tensor_forest.client.random_forest.TensorForestEstimator. * `Estimator`: Use when you need a custom model. * For **Classification** problems use one of the following: * `LinearClassifier`: Multiclass classifier using Linear model. * `DNNClassifier`: Multiclass classifier using DNN. * `DNNLinearCombinedClassifier`: Multiclass classifier using Wide & Deep. * `TensorForestEstimator`: Uses RandomForest. See tf.contrib.tensor_forest.client.random_forest.TensorForestEstimator. * `SVM`: Binary classifier using linear SVMs. * `LogisticRegressor`: Use when you need custom model for binary classification. * `Estimator`: Use when you need custom model for N class classification. ## Pre-canned Estimators Pre-canned estimators are machine learning estimators premade for general purpose problems. If you need more customization, you can always write your own custom estimator as described in the section below. Pre-canned estimators are tested and optimized for speed and quality. ### Define the feature columns Here are some possible types of feature columns used as inputs to a pre-canned estimator. Feature columns may vary based on the estimator used. So you can see which feature columns are fed to each estimator in the below section. ```python sparse_feature_a = sparse_column_with_keys( column_name="sparse_feature_a", keys=["AB", "CD", ...]) embedding_feature_a = embedding_column( sparse_id_column=sparse_feature_a, dimension=3, combiner="sum") sparse_feature_b = sparse_column_with_hash_bucket( column_name="sparse_feature_b", hash_bucket_size=1000) embedding_feature_b = embedding_column( sparse_id_column=sparse_feature_b, dimension=16, combiner="sum") crossed_feature_a_x_b = crossed_column( columns=[sparse_feature_a, sparse_feature_b], hash_bucket_size=10000) real_feature = real_valued_column("real_feature") real_feature_buckets = bucketized_column( source_column=real_feature, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65]) ``` ### Create the pre-canned estimator DNNClassifier, DNNRegressor, and DNNLinearCombinedClassifier are all pretty similar to each other in how you use them. You can easily plug in an optimizer and/or regularization to those estimators. #### DNNClassifier A classifier for TensorFlow DNN models. ```python my_features = [embedding_feature_a, embedding_feature_b] estimator = DNNClassifier( feature_columns=my_features, hidden_units=[1024, 512, 256], optimizer=tf.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) ``` #### DNNRegressor A regressor for TensorFlow DNN models. ```python my_features = [embedding_feature_a, embedding_feature_b] estimator = DNNRegressor( feature_columns=my_features, hidden_units=[1024, 512, 256]) # Or estimator using the ProximalAdagradOptimizer optimizer with # regularization. estimator = DNNRegressor( feature_columns=my_features, hidden_units=[1024, 512, 256], optimizer=tf.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) ``` #### DNNLinearCombinedClassifier A classifier for TensorFlow Linear and DNN joined training models. * Wide and deep model * Multi class (2 by default) ```python my_linear_features = [crossed_feature_a_x_b] my_deep_features = [embedding_feature_a, embedding_feature_b] estimator = DNNLinearCombinedClassifier( # Common settings n_classes=n_classes, weight_column_name=weight_column_name, # Wide settings linear_feature_columns=my_linear_features, linear_optimizer=tf.train.FtrlOptimizer(...), # Deep settings dnn_feature_columns=my_deep_features, dnn_hidden_units=[1000, 500, 100], dnn_optimizer=tf.train.AdagradOptimizer(...)) ``` #### LinearClassifier Train a linear model to classify instances into one of multiple possible classes. When number of possible classes is 2, this is binary classification. ```python my_features = [sparse_feature_b, crossed_feature_a_x_b] estimator = LinearClassifier( feature_columns=my_features, optimizer=tf.train.FtrlOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) ``` #### LinearRegressor Train a linear regression model to predict a label value given observation of feature values. ```python my_features = [sparse_feature_b, crossed_feature_a_x_b] estimator = LinearRegressor( feature_columns=my_features) ``` ### LogisticRegressor Logistic regression estimator for binary classification. ```python # See tf.contrib.learn.Estimator(...) for details on model_fn structure def my_model_fn(...): pass estimator = LogisticRegressor(model_fn=my_model_fn) # Input builders def input_fn_train: pass estimator.fit(input_fn=input_fn_train) estimator.predict(x=x) ``` #### SVM - Support Vector Machine Support Vector Machine (SVM) model for binary classification. Currently only linear SVMs are supported. ```python my_features = [real_feature, sparse_feature_a] estimator = SVM( example_id_column='example_id', feature_columns=my_features, l2_regularization=10.0) ``` #### DynamicRnnEstimator An `Estimator` that uses a recurrent neural network with dynamic unrolling. ```python problem_type = ProblemType.CLASSIFICATION # or REGRESSION prediction_type = PredictionType.SINGLE_VALUE # or MULTIPLE_VALUE estimator = DynamicRnnEstimator(problem_type, prediction_type, my_feature_columns) ``` ### Use the estimator There are two main functions for using estimators, one of which is for training, and one of which is for evaluation. You can specify different data sources for each one in order to use different datasets for train and eval. ```python # Input builders def input_fn_train: # returns x, Y ... estimator.fit(input_fn=input_fn_train) def input_fn_eval: # returns x, Y ... estimator.evaluate(input_fn=input_fn_eval) estimator.predict(x=x) ``` ## Creating Custom Estimator To create a custom `Estimator`, provide a function to `Estimator`'s constructor that builds your model (`model_fn`, below): ```python estimator = tf.contrib.learn.Estimator( model_fn=model_fn, model_dir=model_dir) # Where the model's data (e.g., checkpoints) # are saved. ``` Here is a skeleton of this function, with descriptions of its arguments and return values in the accompanying tables: ```python def model_fn(features, targets, mode, params): # Logic to do the following: # 1. Configure the model via TensorFlow operations # 2. Define the loss function for training/evaluation # 3. Define the training operation/optimizer # 4. Generate predictions return predictions, loss, train_op ``` You may use `mode` and check against `tf.contrib.learn.ModeKeys.{TRAIN, EVAL, INFER}` to parameterize `model_fn`. In the Further Reading section below, there is an end-to-end TensorFlow tutorial for building a custom estimator. ## Additional Estimators There is an additional estimators under `tensorflow.contrib.factorization.python.ops`: * Gaussian mixture model (GMM) clustering ## Further reading For further reading, there are several tutorials with relevant topics, including: * [Overview of linear models](../../../tutorials/linear/overview.md) * [Linear model tutorial](../../../tutorials/wide/index.md) * [Wide and deep learning tutorial](../../../tutorials/wide_and_deep/index.md) * [Custom estimator tutorial](../../../tutorials/estimators/index.md) * [Building input functions](../../../tutorials/input_fn/index.md) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.estimators._sklearn import NotFittedError from tensorflow.contrib.learn.python.learn.estimators.constants import ProblemType from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNClassifier from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNEstimator from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNRegressor from tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined import DNNLinearCombinedClassifier from tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined import DNNLinearCombinedEstimator from tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined import DNNLinearCombinedRegressor from tensorflow.contrib.learn.python.learn.estimators.dynamic_rnn_estimator import DynamicRnnEstimator from tensorflow.contrib.learn.python.learn.estimators.estimator import BaseEstimator from tensorflow.contrib.learn.python.learn.estimators.estimator import Estimator from tensorflow.contrib.learn.python.learn.estimators.estimator import GraphRewriteSpec from tensorflow.contrib.learn.python.learn.estimators.estimator import infer_real_valued_columns_from_input from tensorflow.contrib.learn.python.learn.estimators.estimator import infer_real_valued_columns_from_input_fn from tensorflow.contrib.learn.python.learn.estimators.estimator import SKCompat from tensorflow.contrib.learn.python.learn.estimators.head import binary_svm_head from tensorflow.contrib.learn.python.learn.estimators.head import Head from tensorflow.contrib.learn.python.learn.estimators.head import loss_only_head from tensorflow.contrib.learn.python.learn.estimators.head import multi_class_head from tensorflow.contrib.learn.python.learn.estimators.head import multi_head from tensorflow.contrib.learn.python.learn.estimators.head import multi_label_head from tensorflow.contrib.learn.python.learn.estimators.head import no_op_train_fn from tensorflow.contrib.learn.python.learn.estimators.head import poisson_regression_head from tensorflow.contrib.learn.python.learn.estimators.head import regression_head from tensorflow.contrib.learn.python.learn.estimators.kmeans import KMeansClustering from tensorflow.contrib.learn.python.learn.estimators.linear import LinearClassifier from tensorflow.contrib.learn.python.learn.estimators.linear import LinearEstimator from tensorflow.contrib.learn.python.learn.estimators.linear import LinearRegressor from tensorflow.contrib.learn.python.learn.estimators.logistic_regressor import LogisticRegressor from tensorflow.contrib.learn.python.learn.estimators.metric_key import MetricKey from tensorflow.contrib.learn.python.learn.estimators.model_fn import ModeKeys from tensorflow.contrib.learn.python.learn.estimators.model_fn import ModelFnOps from tensorflow.contrib.learn.python.learn.estimators.prediction_key import PredictionKey from tensorflow.contrib.learn.python.learn.estimators.rnn_common import PredictionType from tensorflow.contrib.learn.python.learn.estimators.run_config import ClusterConfig from tensorflow.contrib.learn.python.learn.estimators.run_config import Environment from tensorflow.contrib.learn.python.learn.estimators.run_config import RunConfig from tensorflow.contrib.learn.python.learn.estimators.run_config import TaskType from tensorflow.contrib.learn.python.learn.estimators.svm import SVM
apache-2.0
thaihungle/deepexp
drl/qdl.py
1
7102
import gym import numpy as np import random import tensorflow as tf import matplotlib.pyplot as plt # Create model def multilayer_perceptron(x, weights, biases): #somehow drl performs worse with complex layers # Hidden layer with RELU activation layer_1 = tf.matmul(x, weights['h1']) layer_1 = tf.nn.relu(layer_1) # Hidden layer with RELU activation layer_2 = tf.matmul(layer_1, weights['h2']) layer_2 = tf.nn.relu(layer_2) # Output layer with linear activation out_layer = tf.matmul(x, weights['out']) #+ biases['out'] return out_layer def build_model(env): tf.reset_default_graph() # always call it first inputs1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tensor symbol for input state # Store layers weight & bias n_input = env.observation_space.n n_hidden_1 = 10 n_hidden_2 = 10 weights = { 'h1': tf.Variable(tf.random_uniform([n_input, n_hidden_1], -0.01, 0.01)), 'h2': tf.Variable(tf.random_uniform([n_hidden_1, n_hidden_2], -0.01, 0.01)), 'out': tf.Variable(tf.random_uniform([n_input, env.action_space.n], -0.01, 0.01)), } biases = { 'b1': tf.Variable(tf.random_uniform([n_hidden_1], -0.01, 0.01)), 'b2': tf.Variable(tf.random_uniform([n_hidden_2], -0.01, 0.01)), 'out': tf.Variable(tf.random_uniform([env.action_space.n], -0.01, 0.01)) } Qout = multilayer_perceptron(inputs1, weights, biases) predict = tf.argmax(Qout, 1) # given input_state, get best action id # Below we obtain the loss by taking the sum of squares difference between the target and prediction Q values. nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # tensor symbol for input Q loss = tf.reduce_sum(tf.square(nextQ - Qout)) # mean square loss function updateModel = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss) return inputs1, nextQ, Qout, predict, updateModel, weights, biases def q_deep_learning(env, sess, inputs1, nextQ, Qout, predict, updateModel, weights, biases, y = .99, e = 0.1, num_episodes = 2000): # create lists to contain total rewards and steps per episode jList = [] rList = [] numlost = numwin = 0 for i in range(num_episodes): # Reset environment and get first new observation s = env.reset() rAll = 0 # d = False j = 0 stop = False # The Q-Network while j < 99: j += 1 # Choose an action by greedily (with e chance of random action) from the Q-network # predict, Qout need input1 --> need feed_dict, s1 is id of state -->get onehot vector 1 at that id # get Qout as variable filled with values allQ --> Q values given current state a, allQ = sess.run([predict, Qout], feed_dict={inputs1: np.identity(env.observation_space.n)[s:s + 1]}) if np.random.rand(1) < e: a[0] = env.action_space.sample()# random action still # Get new state and reward from environment s1, r, d, _ = env.step(a[0])# index 0 is index of max action # Obtain the Q' values by feeding the new state through our network # Q values given new state Q1 = sess.run(Qout, feed_dict={inputs1: np.identity(env.observation_space.n)[s1:s1 + 1]}) # Obtain maxQ' and set our target value for chosen action. maxQ1 = np.max(Q1) targetQ = allQ targetQ[0, a[0]] = r + y * maxQ1 # assume model follow the rule --> next q values of (next state) # follow reward rules --> NN must predict q values of current state match this real value # if match --> Q converge --> reinforcement learning done!!! # Train our network using target and predicted Q values sess.run([updateModel], feed_dict={inputs1: np.identity(env.observation_space.n)[s:s + 1], nextQ: targetQ}) rAll += r s = s1 if d: # Reduce chance of random action as we train the model. e = 1. / ((i / 50) + 10) if r == 0: numlost += 1 else: numwin += 1 stop = True break jList.append(j) rList.append(rAll/j) if not stop: numlost += 1 print("Score over time: " + str(sum(rList) / num_episodes)) print("Num win {} vs lost {} ".format(numwin / num_episodes, numlost / num_episodes)) return updateModel def q_table_learning(Q, env, lr = .5, y = .99, num_episodes = 2000): # Initialize table with all zeros # Set learning parameters # create lists to contain total rewards and steps per episode # jList = [] rList = [] numwin = 0 numlost = 0 for i in range(num_episodes): # Reset environment and get first new observation s = env.reset() rAll = 0 j = 0 stop=False # The Q-Table learning algorithm while j < 99: j += 1 # Choose an action by greedily (with noise) picking from Q table a = np.argmax(Q[s, :] + np.random.randn(1, env.action_space.n) * (1. / (i + 1))) # Get new state and reward from environment s1, r, d, _ = env.step(a) # Update Q-Table with new knowledge Q[s, a] = Q[s, a] + lr * (r + y * np.max(Q[s1, :]) - Q[s, a]) rAll += r s = s1 if d: if r==0: numlost+=1 else: numwin+=1 stop=True break if not stop: numlost+=1 rList.append(rAll/j) # jList.append(j) print("Score over time: " + str(sum(rList) / num_episodes)) print("Num win {} vs lost {} ".format(numwin / num_episodes, numlost / num_episodes)) # print("Step to win over time: " + str(sum(jList) / num_episodes)) def test_qtable(): env = gym.make('FrozenLake-v0') numloop = 100 Q = np.zeros([env.observation_space.n, env.action_space.n]) print('start q table learning...') for i in range(numloop): print('============Loop: {} / {}================'.format(i, numloop)) q_table_learning(Q, env) def test_qdl(): env = gym.make('FrozenLake-v0') inputs1, nextQ, Qout, predict, updateModel, weights, bias = build_model(env) init = tf.global_variables_initializer() # auto init for all variable appear in tensorflow with tf.Session() as sess:# tensorflow run is based on session sess.run(init) numloop = 100 print('start q deep learning...') for i in range(numloop): print('============Loop: {} / {}================'.format(i, numloop)) q_deep_learning(env, sess, inputs1, nextQ, Qout, predict, updateModel, weights, bias) if __name__ == '__main__': #test_qtable() test_qdl()
mit
PyPSA/PyPSA
setup.py
1
1531
from __future__ import absolute_import from setuptools import setup, find_packages from codecs import open with open('README.rst', encoding='utf-8') as f: long_description = f.read() setup( name='pypsa', version='0.17.1', author='Tom Brown (FIAS, KIT), Jonas Hoersch (FIAS, KIT), Fabian Hofmann (FIAS), Fabian Neumann (KIT), David Schlachtberger (FIAS)', author_email='[email protected]', description='Python for Power Systems Analysis', long_description=long_description, long_description_content_type='text/x-rst', url='https://github.com/PyPSA/PyPSA', license='GPLv3', packages=find_packages(exclude=['doc', 'test']), include_package_data=True, python_requires='>=3.6', install_requires=[ 'numpy', 'scipy', 'pandas>=0.24.0', 'xarray', 'netcdf4', 'tables', 'pyomo>=5.7', 'matplotlib', 'networkx>=1.10', 'deprecation' ], extras_require = { "dev": ["pytest", "pypower", "pandapower"], "cartopy": ['cartopy>=0.16'], "docs": ["numpydoc", "sphinx", "sphinx_rtd_theme", "nbsphinx", "nbsphinx-link"], 'gurobipy':['gurobipy'] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Natural Language :: English', 'Operating System :: OS Independent', ])
gpl-3.0
makokal/funzo
examples/gridworld/gridworld_planning.py
1
1745
from __future__ import division import argparse import matplotlib matplotlib.use('Qt4Agg') from matplotlib import pyplot as plt plt.style.use('fivethirtyeight') import numpy as np from funzo.domains.gridworld import GridWorld, GridWorldMDP from funzo.domains.gridworld import GReward, GRewardLFA, GTransition from funzo.planners.dp import PolicyIteration, ValueIteration def main(map_name, planner): gmap = np.loadtxt(map_name) with GridWorld(gmap=gmap) as world: # R = GReward(rmax=1.0) R = GRewardLFA(weights=[-0.01, -10.0, 1.0], rmax=1.0) T = GTransition(wind=0.1) g_mdp = GridWorldMDP(reward=R, transition=T, discount=0.95) # ------------------------ mdp_planner = PolicyIteration(max_iter=200, random_state=None) if planner == 'VI': mdp_planner = ValueIteration(verbose=2) res = mdp_planner.solve(g_mdp) V = res['V'] print('Policy: ', res['pi']) fig = plt.figure(figsize=(8, 8)) ax = fig.gca() ax = world.visualize(ax, policy=res['pi']) plt.figure(figsize=(8, 8)) plt.imshow(V.reshape(gmap.shape), interpolation='nearest', cmap='viridis', origin='lower', vmin=np.min(V), vmax=np.max(V)) plt.grid(False) plt.title('Value function') plt.colorbar(orientation='horizontal') plt.show() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-m", "--map", type=str, required=True, help="Grid Map file") parser.add_argument("-p", "--planner", type=str, default="PI", help="Planner to use: [PI, VI], default: PI") args = parser.parse_args() main(args.map, args.planner)
mit
andrewcbennett/iris
lib/iris/tests/test_analysis.py
3
50729
# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # # Iris 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. # # Iris 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 Iris. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa import six # import iris tests first so that some things can be initialised before importing anything else import iris.tests as tests import cartopy.crs as ccrs import cf_units import numpy as np import numpy.ma as ma import iris import iris.analysis.cartography import iris.analysis.maths import iris.coord_systems import iris.coords import iris.cube import iris.tests.stock # Run tests in no graphics mode if matplotlib is not available. if tests.MPL_AVAILABLE: import matplotlib import matplotlib.pyplot as plt class TestAnalysisCubeCoordComparison(tests.IrisTest): def assertComparisonDict(self, comparison_dict, reference_filename): string = '' for key in sorted(comparison_dict): coord_groups = comparison_dict[key] string += ('%40s ' % key) names = [[coord.name() if coord is not None else 'None' for coord in coords] for coords in coord_groups] string += str(sorted(names)) string += '\n' self.assertString(string, reference_filename) def test_coord_comparison(self): cube1 = iris.cube.Cube(np.zeros((41, 41))) lonlat_cs = iris.coord_systems.GeogCS(6371229) lon_points1 = -180 + 4.5 * np.arange(41, dtype=np.float32) lat_points = -90 + 4.5 * np.arange(41, dtype=np.float32) cube1.add_dim_coord(iris.coords.DimCoord(lon_points1, 'longitude', units='degrees', coord_system=lonlat_cs), 0) cube1.add_dim_coord(iris.coords.DimCoord(lat_points, 'latitude', units='degrees', coord_system=lonlat_cs), 1) cube1.add_aux_coord(iris.coords.AuxCoord(0, long_name='z')) cube1.add_aux_coord(iris.coords.AuxCoord(['foobar'], long_name='f', units='no_unit')) cube2 = iris.cube.Cube(np.zeros((41, 41, 5))) lonlat_cs = iris.coord_systems.GeogCS(6371229) lon_points2 = -160 + 4.5 * np.arange(41, dtype=np.float32) cube2.add_dim_coord(iris.coords.DimCoord(lon_points2, 'longitude', units='degrees', coord_system=lonlat_cs), 0) cube2.add_dim_coord(iris.coords.DimCoord(lat_points, 'latitude', units='degrees', coord_system=lonlat_cs), 1) cube2.add_dim_coord(iris.coords.DimCoord([5, 7, 9, 11, 13], long_name='z'), 2) cube3 = cube1.copy() lon = cube3.coord("longitude") lat = cube3.coord("latitude") cube3.remove_coord(lon) cube3.remove_coord(lat) cube3.add_dim_coord(lon, 1) cube3.add_dim_coord(lat, 0) cube3.coord('z').points = [20] cube4 = cube2.copy() lon = cube4.coord("longitude") lat = cube4.coord("latitude") cube4.remove_coord(lon) cube4.remove_coord(lat) cube4.add_dim_coord(lon, 1) cube4.add_dim_coord(lat, 0) coord_comparison = iris.analysis.coord_comparison self.assertComparisonDict(coord_comparison(cube1, cube1), ('analysis', 'coord_comparison', 'cube1_cube1.txt')) self.assertComparisonDict(coord_comparison(cube1, cube2), ('analysis', 'coord_comparison', 'cube1_cube2.txt')) self.assertComparisonDict(coord_comparison(cube1, cube3), ('analysis', 'coord_comparison', 'cube1_cube3.txt')) self.assertComparisonDict(coord_comparison(cube1, cube4), ('analysis', 'coord_comparison', 'cube1_cube4.txt')) self.assertComparisonDict(coord_comparison(cube2, cube3), ('analysis', 'coord_comparison', 'cube2_cube3.txt')) self.assertComparisonDict(coord_comparison(cube2, cube4), ('analysis', 'coord_comparison', 'cube2_cube4.txt')) self.assertComparisonDict(coord_comparison(cube3, cube4), ('analysis', 'coord_comparison', 'cube3_cube4.txt')) self.assertComparisonDict(coord_comparison(cube1, cube1, cube1), ('analysis', 'coord_comparison', 'cube1_cube1_cube1.txt')) self.assertComparisonDict(coord_comparison(cube1, cube2, cube1), ('analysis', 'coord_comparison', 'cube1_cube2_cube1.txt')) # get a coord comparison result and check that we are getting back what was expected coord_group = coord_comparison(cube1, cube2)['grouped_coords'][0] self.assertIsInstance(coord_group, iris.analysis._CoordGroup) self.assertIsInstance(list(coord_group)[0], iris.coords.Coord) class TestAnalysisWeights(tests.IrisTest): def test_weighted_mean_little(self): data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32) weights = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]], dtype=np.float32) cube = iris.cube.Cube(data, long_name="test_data", units="1") hcs = iris.coord_systems.GeogCS(6371229) lat_coord = iris.coords.DimCoord(np.array([1, 2, 3], dtype=np.float32), long_name="lat", units="1", coord_system=hcs) lon_coord = iris.coords.DimCoord(np.array([1, 2, 3], dtype=np.float32), long_name="lon", units="1", coord_system=hcs) cube.add_dim_coord(lat_coord, 0) cube.add_dim_coord(lon_coord, 1) cube.add_aux_coord(iris.coords.AuxCoord(np.arange(3, dtype=np.float32), long_name="dummy", units=1), 1) self.assertCML(cube, ('analysis', 'weighted_mean_source.cml')) a = cube.collapsed('lat', iris.analysis.MEAN, weights=weights) self.assertCMLApproxData(a, ('analysis', 'weighted_mean_lat.cml')) b = cube.collapsed(lon_coord, iris.analysis.MEAN, weights=weights) b.data = np.asarray(b.data) self.assertCMLApproxData(b, ('analysis', 'weighted_mean_lon.cml')) self.assertEqual(b.coord('dummy').shape, (1, )) # test collapsing multiple coordinates (and the fact that one of the coordinates isn't the same coordinate instance as on the cube) c = cube.collapsed([lat_coord[:], lon_coord], iris.analysis.MEAN, weights=weights) self.assertCMLApproxData(c, ('analysis', 'weighted_mean_latlon.cml')) self.assertEqual(c.coord('dummy').shape, (1, )) # Check new coord bounds - made from points self.assertArrayEqual(c.coord('lat').bounds, [[1, 3]]) # Check new coord bounds - made from bounds cube.coord('lat').bounds = [[0.5, 1.5], [1.5, 2.5], [2.5, 3.5]] c = cube.collapsed(['lat', 'lon'], iris.analysis.MEAN, weights=weights) self.assertArrayEqual(c.coord('lat').bounds, [[0.5, 3.5]]) cube.coord('lat').bounds = None # Check there was no residual change self.assertCML(cube, ('analysis', 'weighted_mean_source.cml')) @tests.skip_data def test_weighted_mean(self): ### compare with pp_area_avg - which collapses both lat and lon # # pp = ppa('/data/local/dataZoo/PP/simple_pp/global.pp', 0) # print, pp_area(pp, /box) # print, pp_area_avg(pp, /box) #287.927 # ;gives an answer of 287.927 # ### e = iris.tests.stock.simple_pp() self.assertCML(e, ('analysis', 'weighted_mean_original.cml')) e.coord('latitude').guess_bounds() e.coord('longitude').guess_bounds() area_weights = iris.analysis.cartography.area_weights(e) e.coord('latitude').bounds = None e.coord('longitude').bounds = None f, collapsed_area_weights = e.collapsed('latitude', iris.analysis.MEAN, weights=area_weights, returned=True) g = f.collapsed('longitude', iris.analysis.MEAN, weights=collapsed_area_weights) # check it's a 0d, scalar cube self.assertEqual(g.shape, ()) # check the value - pp_area_avg's result of 287.927 differs by factor of 1.00002959 np.testing.assert_approx_equal(g.data, 287.935, significant=5) #check we get summed weights even if we don't give any h, summed_weights = e.collapsed('latitude', iris.analysis.MEAN, returned=True) assert(summed_weights is not None) # Check there was no residual change e.coord('latitude').bounds = None e.coord('longitude').bounds = None self.assertCML(e, ('analysis', 'weighted_mean_original.cml')) # Test collapsing of missing coord self.assertRaises(iris.exceptions.CoordinateNotFoundError, e.collapsed, 'platitude', iris.analysis.MEAN) # Test collpasing of non data coord self.assertRaises(iris.exceptions.CoordinateCollapseError, e.collapsed, 'pressure', iris.analysis.MEAN) @tests.skip_data class TestAnalysisBasic(tests.IrisTest): def setUp(self): file = tests.get_data_path(('PP', 'aPProt1', 'rotatedMHtimecube.pp')) cubes = iris.load(file) self.cube = cubes[0] self.assertCML(self.cube, ('analysis', 'original.cml')) def _common(self, name, aggregate, original_name='original_common.cml', *args, **kwargs): self.cube.data = self.cube.data.astype(np.float64) self.assertCML(self.cube, ('analysis', original_name)) a = self.cube.collapsed('grid_latitude', aggregate) self.assertCMLApproxData(a, ('analysis', '%s_latitude.cml' % name), *args, **kwargs) b = a.collapsed('grid_longitude', aggregate) self.assertCMLApproxData(b, ('analysis', '%s_latitude_longitude.cml' % name), *args, **kwargs) c = self.cube.collapsed(['grid_latitude', 'grid_longitude'], aggregate) self.assertCMLApproxData(c, ('analysis', '%s_latitude_longitude_1call.cml' % name), *args, **kwargs) # Check there was no residual change self.assertCML(self.cube, ('analysis', original_name)) def test_mean(self): self._common('mean', iris.analysis.MEAN, decimal=1) def test_std_dev(self): # as the numbers are so high, trim off some trailing digits & compare to 0dp self._common('std_dev', iris.analysis.STD_DEV, decimal=1) def test_hmean(self): # harmonic mean requires data > 0 self.cube.data *= self.cube.data self._common('hmean', iris.analysis.HMEAN, 'original_hmean.cml', decimal=1) def test_gmean(self): self._common('gmean', iris.analysis.GMEAN, decimal=1) def test_variance(self): # as the numbers are so high, trim off some trailing digits & compare to 0dp self._common('variance', iris.analysis.VARIANCE, decimal=1) def test_median(self): self._common('median', iris.analysis.MEDIAN) def test_sum(self): # as the numbers are so high, trim off some trailing digits & compare to 0dp self._common('sum', iris.analysis.SUM, decimal=1) def test_max(self): self._common('max', iris.analysis.MAX) def test_min(self): self._common('min', iris.analysis.MIN) def test_rms(self): self._common('rms', iris.analysis.RMS) def test_duplicate_coords(self): self.assertRaises(ValueError, tests.stock.track_1d, duplicate_x=True) class TestMissingData(tests.IrisTest): def setUp(self): self.cube_with_nan = tests.stock.simple_2d() data = self.cube_with_nan.data.astype(np.float32) self.cube_with_nan.data = data.copy() self.cube_with_nan.data[1, 0] = np.nan self.cube_with_nan.data[2, 2] = np.nan self.cube_with_nan.data[2, 3] = np.nan self.cube_with_mask = tests.stock.simple_2d() self.cube_with_mask.data = ma.array(self.cube_with_nan.data, mask=np.isnan(self.cube_with_nan.data)) def test_max(self): cube = self.cube_with_nan.collapsed('foo', iris.analysis.MAX) np.testing.assert_array_equal(cube.data, np.array([3, np.nan, np.nan])) cube = self.cube_with_mask.collapsed('foo', iris.analysis.MAX) np.testing.assert_array_equal(cube.data, np.array([3, 7, 9])) def test_min(self): cube = self.cube_with_nan.collapsed('foo', iris.analysis.MIN) np.testing.assert_array_equal(cube.data, np.array([0, np.nan, np.nan])) cube = self.cube_with_mask.collapsed('foo', iris.analysis.MIN) np.testing.assert_array_equal(cube.data, np.array([0, 5, 8])) def test_sum(self): cube = self.cube_with_nan.collapsed('foo', iris.analysis.SUM) np.testing.assert_array_equal(cube.data, np.array([6, np.nan, np.nan])) cube = self.cube_with_mask.collapsed('foo', iris.analysis.SUM) np.testing.assert_array_equal(cube.data, np.array([6, 18, 17])) class TestAggregator_mdtol_keyword(tests.IrisTest): def setUp(self): data = ma.array([[1, 2], [4, 5]], dtype=np.float32, mask=[[False, True], [False, True]]) cube = iris.cube.Cube(data, long_name="test_data", units="1") lat_coord = iris.coords.DimCoord(np.array([1, 2], dtype=np.float32), long_name="lat", units="1") lon_coord = iris.coords.DimCoord(np.array([3, 4], dtype=np.float32), long_name="lon", units="1") cube.add_dim_coord(lat_coord, 0) cube.add_dim_coord(lon_coord, 1) self.cube = cube def test_single_coord_no_mdtol(self): collapsed = self.cube.collapsed( self.cube.coord('lat'), iris.analysis.MEAN) t = ma.array([2.5, 5.], mask=[False, True]) self.assertMaskedArrayEqual(collapsed.data, t) def test_single_coord_mdtol(self): self.cube.data.mask = np.array([[False, True], [False, False]]) collapsed = self.cube.collapsed( self.cube.coord('lat'), iris.analysis.MEAN, mdtol=0.5) t = ma.array([2.5, 5], mask=[False, False]) self.assertMaskedArrayEqual(collapsed.data, t) def test_single_coord_mdtol_alt(self): self.cube.data.mask = np.array([[False, True], [False, False]]) collapsed = self.cube.collapsed( self.cube.coord('lat'), iris.analysis.MEAN, mdtol=0.4) t = ma.array([2.5, 5], mask=[False, True]) self.assertMaskedArrayEqual(collapsed.data, t) def test_multi_coord_no_mdtol(self): collapsed = self.cube.collapsed( [self.cube.coord('lat'), self.cube.coord('lon')], iris.analysis.MEAN) t = np.array(2.5) self.assertArrayEqual(collapsed.data, t) def test_multi_coord_mdtol(self): collapsed = self.cube.collapsed( [self.cube.coord('lat'), self.cube.coord('lon')], iris.analysis.MEAN, mdtol=0.4) t = ma.array(2.5, mask=True) self.assertMaskedArrayEqual(collapsed.data, t) class TestAggregators(tests.IrisTest): def test_percentile_1d(self): cube = tests.stock.simple_1d() first_quartile = cube.collapsed('foo', iris.analysis.PERCENTILE, percent=25) np.testing.assert_array_almost_equal(first_quartile.data, np.array([2.5], dtype=np.float32)) self.assertCML(first_quartile, ('analysis', 'first_quartile_foo_1d.cml'), checksum=False) third_quartile = cube.collapsed('foo', iris.analysis.PERCENTILE, percent=75) np.testing.assert_array_almost_equal(third_quartile.data, np.array([7.5], dtype=np.float32)) self.assertCML(third_quartile, ('analysis', 'third_quartile_foo_1d.cml'), checksum=False) def test_percentile_2d(self): cube = tests.stock.simple_2d() first_quartile = cube.collapsed('foo', iris.analysis.PERCENTILE, percent=25) np.testing.assert_array_almost_equal(first_quartile.data, np.array([0.75, 4.75, 8.75], dtype=np.float32)) self.assertCML(first_quartile, ('analysis', 'first_quartile_foo_2d.cml'), checksum=False) first_quartile = cube.collapsed(('foo', 'bar'), iris.analysis.PERCENTILE, percent=25) np.testing.assert_array_almost_equal(first_quartile.data, np.array([2.75], dtype=np.float32)) self.assertCML(first_quartile, ('analysis', 'first_quartile_foo_bar_2d.cml'), checksum=False) def test_percentile_3d(self): array_3d = np.arange(24, dtype=np.int32).reshape((2, 3, 4)) last_quartile = iris.analysis._percentile(array_3d, 0, 50) np.testing.assert_array_almost_equal(last_quartile, np.array([[6., 7., 8., 9.], [10., 11., 12., 13.], [14., 15., 16., 17.]], dtype=np.float32)) def test_percentile_3d_axis_one(self): array_3d = np.arange(24, dtype=np.int32).reshape((2, 3, 4)) last_quartile = iris.analysis._percentile(array_3d, 1, 50) np.testing.assert_array_almost_equal(last_quartile, np.array([[4., 5., 6., 7.], [16., 17., 18., 19.]], dtype=np.float32)) def test_percentile_3d_axis_two(self): array_3d = np.arange(24, dtype=np.int32).reshape((2, 3, 4)) last_quartile = iris.analysis._percentile(array_3d, 2, 50) np.testing.assert_array_almost_equal(last_quartile, np.array([[1.5, 5.5, 9.5], [13.5, 17.5, 21.5]], dtype=np.float32)) def test_percentile_3d_masked(self): cube = tests.stock.simple_3d_mask() last_quartile = cube.collapsed('wibble', iris.analysis.PERCENTILE, percent=75) np.testing.assert_array_almost_equal(last_quartile.data, np.array([[12., 13., 14., 15.], [16., 17., 18., 19.], [20., 18., 19., 20.]], dtype=np.float32)) self.assertCML(last_quartile, ('analysis', 'last_quartile_foo_3d_masked.cml'), checksum=False) def test_percentile_3d_notmasked(self): cube = tests.stock.simple_3d() last_quartile = cube.collapsed('wibble', iris.analysis.PERCENTILE, percent=75) np.testing.assert_array_almost_equal(last_quartile.data, np.array([[9., 10., 11., 12.], [13., 14., 15., 16.], [17., 18., 19., 20.]], dtype=np.float32)) self.assertCML(last_quartile, ('analysis', 'last_quartile_foo_3d_notmasked.cml'), checksum=False) def test_proportion(self): cube = tests.stock.simple_1d() r = cube.data >= 5 gt5 = cube.collapsed('foo', iris.analysis.PROPORTION, function=lambda val: val >= 5) np.testing.assert_array_almost_equal(gt5.data, np.array([6 / 11.])) self.assertCML(gt5, ('analysis', 'proportion_foo_1d.cml'), checksum=False) def test_proportion_2d(self): cube = tests.stock.simple_2d() gt6 = cube.collapsed('foo', iris.analysis.PROPORTION, function=lambda val: val >= 6) np.testing.assert_array_almost_equal(gt6.data, np.array([0, 0.5, 1], dtype=np.float32)) self.assertCML(gt6, ('analysis', 'proportion_foo_2d.cml'), checksum=False) gt6 = cube.collapsed('bar', iris.analysis.PROPORTION, function=lambda val: val >= 6) np.testing.assert_array_almost_equal(gt6.data, np.array([1 / 3, 1 / 3, 2 / 3, 2 / 3], dtype=np.float32)) self.assertCML(gt6, ('analysis', 'proportion_bar_2d.cml'), checksum=False) gt6 = cube.collapsed(('foo', 'bar'), iris.analysis.PROPORTION, function=lambda val: val >= 6) np.testing.assert_array_almost_equal(gt6.data, np.array([0.5], dtype=np.float32)) self.assertCML(gt6, ('analysis', 'proportion_foo_bar_2d.cml'), checksum=False) # mask the data cube.data = ma.array(cube.data, mask=cube.data % 2) cube.data.mask[1, 2] = True gt6_masked = cube.collapsed('bar', iris.analysis.PROPORTION, function=lambda val: val >= 6) np.testing.assert_array_almost_equal(gt6_masked.data, ma.array([1 / 3, None, 1 / 2, None], mask=[False, True, False, True], dtype=np.float32)) self.assertCML(gt6_masked, ('analysis', 'proportion_foo_2d_masked.cml'), checksum=False) def test_count(self): cube = tests.stock.simple_1d() gt5 = cube.collapsed('foo', iris.analysis.COUNT, function=lambda val: val >= 5) np.testing.assert_array_almost_equal(gt5.data, np.array([6])) gt5.data = gt5.data.astype('i8') self.assertCML(gt5, ('analysis', 'count_foo_1d.cml'), checksum=False) def test_count_2d(self): cube = tests.stock.simple_2d() gt6 = cube.collapsed('foo', iris.analysis.COUNT, function=lambda val: val >= 6) np.testing.assert_array_almost_equal(gt6.data, np.array([0, 2, 4], dtype=np.float32)) gt6.data = gt6.data.astype('i8') self.assertCML(gt6, ('analysis', 'count_foo_2d.cml'), checksum=False) gt6 = cube.collapsed('bar', iris.analysis.COUNT, function=lambda val: val >= 6) np.testing.assert_array_almost_equal(gt6.data, np.array([1, 1, 2, 2], dtype=np.float32)) gt6.data = gt6.data.astype('i8') self.assertCML(gt6, ('analysis', 'count_bar_2d.cml'), checksum=False) gt6 = cube.collapsed(('foo', 'bar'), iris.analysis.COUNT, function=lambda val: val >= 6) np.testing.assert_array_almost_equal(gt6.data, np.array([6], dtype=np.float32)) gt6.data = gt6.data.astype('i8') self.assertCML(gt6, ('analysis', 'count_foo_bar_2d.cml'), checksum=False) def test_weighted_sum_consistency(self): # weighted sum with unit weights should be the same as a sum cube = tests.stock.simple_1d() normal_sum = cube.collapsed('foo', iris.analysis.SUM) weights = np.ones_like(cube.data) weighted_sum = cube.collapsed('foo', iris.analysis.SUM, weights=weights) self.assertArrayAlmostEqual(normal_sum.data, weighted_sum.data) def test_weighted_sum_1d(self): # verify 1d weighted sum is correct cube = tests.stock.simple_1d() weights = np.array([.05, .05, .1, .1, .2, .3, .2, .1, .1, .05, .05]) result = cube.collapsed('foo', iris.analysis.SUM, weights=weights) self.assertAlmostEqual(result.data, 6.5) self.assertCML(result, ('analysis', 'sum_weighted_1d.cml'), checksum=False) def test_weighted_sum_2d(self): # verify 2d weighted sum is correct cube = tests.stock.simple_2d() weights = np.array([.3, .4, .3]) weights = iris.util.broadcast_to_shape(weights, cube.shape, [0]) result = cube.collapsed('bar', iris.analysis.SUM, weights=weights) self.assertArrayAlmostEqual(result.data, np.array([4., 5., 6., 7.])) self.assertCML(result, ('analysis', 'sum_weighted_2d.cml'), checksum=False) def test_weighted_rms(self): cube = tests.stock.simple_2d() # modify cube data so that the results are nice numbers cube.data = np.array([[4, 7, 10, 8], [21, 30, 12, 24], [14, 16, 20, 8]], dtype=np.float64) weights = np.array([[1, 4, 3, 2], [6, 4.5, 1.5, 3], [2, 1, 1.5, 0.5]], dtype=np.float64) expected_result = np.array([8.0, 24.0, 16.0]) result = cube.collapsed('foo', iris.analysis.RMS, weights=weights) self.assertArrayAlmostEqual(result.data, expected_result) self.assertCML(result, ('analysis', 'rms_weighted_2d.cml'), checksum=False) @tests.skip_data class TestRotatedPole(tests.GraphicsTest): @tests.skip_plot def _check_both_conversions(self, cube): rlons, rlats = iris.analysis.cartography.get_xy_grids(cube) rcs = cube.coord_system('RotatedGeogCS') x, y = iris.analysis.cartography.unrotate_pole( rlons, rlats, rcs.grid_north_pole_longitude, rcs.grid_north_pole_latitude) plt.scatter(x, y) self.check_graphic() plt.scatter(rlons, rlats) self.check_graphic() def test_all(self): path = tests.get_data_path(('PP', 'ukVorog', 'ukv_orog_refonly.pp')) master_cube = iris.load_cube(path) # Check overall behaviour. cube = master_cube[::10, ::10] self._check_both_conversions(cube) # Check numerical stability. cube = master_cube[210:238, 424:450] self._check_both_conversions(cube) def test_unrotate_nd(self): rlons = np.array([[350., 352.], [350., 352.]]) rlats = np.array([[-5., -0.], [-4., -1.]]) resx, resy = iris.analysis.cartography.unrotate_pole(rlons, rlats, 178.0, 38.0) # Solutions derived by proj4 direct. solx = np.array([[-16.42176094, -14.85892262], [-16.71055023, -14.58434624]]) soly = np.array([[ 46.00724251, 51.29188893], [ 46.98728486, 50.30706042]]) self.assertArrayAlmostEqual(resx, solx) self.assertArrayAlmostEqual(resy, soly) def test_unrotate_1d(self): rlons = np.array([350., 352., 354., 356.]) rlats = np.array([-5., -0., 5., 10.]) resx, resy = iris.analysis.cartography.unrotate_pole( rlons.flatten(), rlats.flatten(), 178.0, 38.0) # Solutions derived by proj4 direct. solx = np.array([-16.42176094, -14.85892262, -12.88946157, -10.35078336]) soly = np.array([46.00724251, 51.29188893, 56.55031485, 61.77015703]) self.assertArrayAlmostEqual(resx, solx) self.assertArrayAlmostEqual(resy, soly) def test_rotate_nd(self): rlons = np.array([[350., 351.], [352., 353.]]) rlats = np.array([[10., 15.], [20., 25.]]) resx, resy = iris.analysis.cartography.rotate_pole(rlons, rlats, 20., 80.) # Solutions derived by proj4 direct. solx = np.array([[148.69672569, 149.24727087], [149.79067025, 150.31754368]]) soly = np.array([[18.60905789, 23.67749384], [28.74419024, 33.8087963 ]]) self.assertArrayAlmostEqual(resx, solx) self.assertArrayAlmostEqual(resy, soly) def test_rotate_1d(self): rlons = np.array([350., 351., 352., 353.]) rlats = np.array([10., 15., 20., 25.]) resx, resy = iris.analysis.cartography.rotate_pole(rlons.flatten(), rlats.flatten(), 20., 80.) # Solutions derived by proj4 direct. solx = np.array([148.69672569, 149.24727087, 149.79067025, 150.31754368]) soly = np.array([18.60905789, 23.67749384, 28.74419024, 33.8087963 ]) self.assertArrayAlmostEqual(resx, solx) self.assertArrayAlmostEqual(resy, soly) @tests.skip_data class TestAreaWeights(tests.IrisTest): def test_area_weights(self): small_cube = iris.tests.stock.simple_pp() # Get offset, subsampled region: small enough to test against literals small_cube = small_cube[10:, 35:] small_cube = small_cube[::8, ::8] small_cube = small_cube[:5, :4] # pre-check non-data properties self.assertCML(small_cube, ('analysis', 'areaweights_original.cml'), checksum=False) # check area-weights values small_cube.coord('latitude').guess_bounds() small_cube.coord('longitude').guess_bounds() area_weights = iris.analysis.cartography.area_weights(small_cube) expected_results = np.array( [[3.11955916e+12, 3.11956058e+12, 3.11955916e+12, 3.11956058e+12], [5.21950793e+12, 5.21951031e+12, 5.21950793e+12, 5.21951031e+12], [6.68991432e+12, 6.68991737e+12, 6.68991432e+12, 6.68991737e+12], [7.35341320e+12, 7.35341655e+12, 7.35341320e+12, 7.35341655e+12], [7.12998265e+12, 7.12998589e+12, 7.12998265e+12, 7.12998589e+12]], dtype=np.float64) self.assertArrayAllClose(area_weights, expected_results, rtol=1e-8) # Check there was no residual change small_cube.coord('latitude').bounds = None small_cube.coord('longitude').bounds = None self.assertCML(small_cube, ('analysis', 'areaweights_original.cml'), checksum=False) class TestAreaWeightGeneration(tests.IrisTest): def setUp(self): self.cube = iris.tests.stock.realistic_4d() def test_area_weights_std(self): # weights for stock 4d data weights = iris.analysis.cartography.area_weights(self.cube) self.assertEqual(weights.shape, self.cube.shape) def test_area_weights_order(self): # weights for data with dimensions in a different order order = [3, 2, 1, 0] # (lon, lat, level, time) self.cube.transpose(order) weights = iris.analysis.cartography.area_weights(self.cube) self.assertEqual(weights.shape, self.cube.shape) def test_area_weights_non_adjacent(self): # weights for cube with non-adjacent latitude/longitude dimensions order = [0, 3, 1, 2] # (time, lon, level, lat) self.cube.transpose(order) weights = iris.analysis.cartography.area_weights(self.cube) self.assertEqual(weights.shape, self.cube.shape) def test_area_weights_scalar_latitude(self): # weights for cube with a scalar latitude dimension cube = self.cube[:, :, 0, :] weights = iris.analysis.cartography.area_weights(cube) self.assertEqual(weights.shape, cube.shape) def test_area_weights_scalar_longitude(self): # weights for cube with a scalar longitude dimension cube = self.cube[:, :, :, 0] weights = iris.analysis.cartography.area_weights(cube) self.assertEqual(weights.shape, cube.shape) def test_area_weights_scalar(self): # weights for cube with scalar latitude and longitude dimensions cube = self.cube[:, :, 0, 0] weights = iris.analysis.cartography.area_weights(cube) self.assertEqual(weights.shape, cube.shape) def test_area_weights_singleton_latitude(self): # singleton (1-point) latitude dimension cube = self.cube[:, :, 0:1, :] weights = iris.analysis.cartography.area_weights(cube) self.assertEqual(weights.shape, cube.shape) def test_area_weights_singleton_longitude(self): # singleton (1-point) longitude dimension cube = self.cube[:, :, :, 0:1] weights = iris.analysis.cartography.area_weights(cube) self.assertEqual(weights.shape, cube.shape) def test_area_weights_singletons(self): # singleton (1-point) latitude and longitude dimensions cube = self.cube[:, :, 0:1, 0:1] weights = iris.analysis.cartography.area_weights(cube) self.assertEqual(weights.shape, cube.shape) def test_area_weights_normalized(self): # normalized area weights must sum to one over lat/lon dimensions. weights = iris.analysis.cartography.area_weights(self.cube, normalize=True) sumweights = weights.sum(axis=3).sum(axis=2) # sum over lon and lat self.assertArrayAlmostEqual(sumweights, 1) def test_area_weights_non_contiguous(self): # Slice the cube so that we have non-contiguous longitude # bounds. ind = (0, 1, 2, -3, -2, -1) cube = self.cube[..., ind] weights = iris.analysis.cartography.area_weights(cube) expected = iris.analysis.cartography.area_weights(self.cube)[..., ind] self.assertArrayEqual(weights, expected) def test_area_weights_no_lon_bounds(self): self.cube.coord('grid_longitude').bounds = None with self.assertRaises(ValueError): iris.analysis.cartography.area_weights(self.cube) def test_area_weights_no_lat_bounds(self): self.cube.coord('grid_latitude').bounds = None with self.assertRaises(ValueError): iris.analysis.cartography.area_weights(self.cube) @tests.skip_data class TestLatitudeWeightGeneration(tests.IrisTest): def setUp(self): path = iris.tests.get_data_path(['NetCDF', 'rotated', 'xyt', 'small_rotPole_precipitation.nc']) self.cube = iris.load_cube(path) self.cube_dim_lat = self.cube.copy() self.cube_dim_lat.remove_coord('latitude') self.cube_dim_lat.remove_coord('longitude') # The 2d cubes are unrealistic, you would not want to weight by # anything other than grid latitude in real-world scenarios. However, # the technical details are suitable for testing purposes, providing # a nice analog for a 2d latitude coordinate from a curvilinear grid. self.cube_aux_lat = self.cube.copy() self.cube_aux_lat.remove_coord('grid_latitude') self.cube_aux_lat.remove_coord('grid_longitude') self.lat1d = self.cube.coord('grid_latitude').points self.lat2d = self.cube.coord('latitude').points def test_cosine_latitude_weights_range(self): # check the range of returned values, needs a cube that spans the full # latitude range lat_coord = iris.coords.DimCoord(np.linspace(-90, 90, 73), standard_name='latitude', units=cf_units.Unit('degrees_north')) cube = iris.cube.Cube(np.ones([73], dtype=np.float64), long_name='test_cube', units='1') cube.add_dim_coord(lat_coord, 0) weights = iris.analysis.cartography.cosine_latitude_weights(cube) self.assertTrue(weights.max() <= 1) self.assertTrue(weights.min() >= 0) def test_cosine_latitude_weights_0d(self): # 0d latitude dimension (scalar coordinate) weights = iris.analysis.cartography.cosine_latitude_weights( self.cube_dim_lat[:, 0, :]) self.assertEqual(weights.shape, self.cube_dim_lat[:, 0, :].shape) self.assertAlmostEqual(weights[0, 0], np.cos(np.deg2rad(self.lat1d[0]))) def test_cosine_latitude_weights_1d_singleton(self): # singleton (1-point) 1d latitude coordinate (time, lat, lon) cube = self.cube_dim_lat[:, 0:1, :] weights = iris.analysis.cartography.cosine_latitude_weights(cube) self.assertEqual(weights.shape, cube.shape) self.assertAlmostEqual(weights[0, 0, 0], np.cos(np.deg2rad(self.lat1d[0]))) def test_cosine_latitude_weights_1d(self): # 1d latitude coordinate (time, lat, lon) weights = iris.analysis.cartography.cosine_latitude_weights( self.cube_dim_lat) self.assertEqual(weights.shape, self.cube.shape) self.assertArrayAlmostEqual(weights[0, :, 0], np.cos(np.deg2rad(self.lat1d))) def test_cosine_latitude_weights_1d_latitude_first(self): # 1d latitude coordinate with latitude first (lat, time, lon) order = [1, 0, 2] # (lat, time, lon) self.cube_dim_lat.transpose(order) weights = iris.analysis.cartography.cosine_latitude_weights( self.cube_dim_lat) self.assertEqual(weights.shape, self.cube_dim_lat.shape) self.assertArrayAlmostEqual(weights[:, 0, 0], np.cos(np.deg2rad(self.lat1d))) def test_cosine_latitude_weights_1d_latitude_last(self): # 1d latitude coordinate with latitude last (time, lon, lat) order = [0, 2, 1] # (time, lon, lat) self.cube_dim_lat.transpose(order) weights = iris.analysis.cartography.cosine_latitude_weights( self.cube_dim_lat) self.assertEqual(weights.shape, self.cube_dim_lat.shape) self.assertArrayAlmostEqual(weights[0, 0, :], np.cos(np.deg2rad(self.lat1d))) def test_cosine_latitude_weights_2d_singleton1(self): # 2d latitude coordinate with first dimension singleton cube = self.cube_aux_lat[:, 0:1, :] weights = iris.analysis.cartography.cosine_latitude_weights(cube) self.assertEqual(weights.shape, cube.shape) self.assertArrayAlmostEqual(weights[0, :, :], np.cos(np.deg2rad(self.lat2d[0:1, :]))) def test_cosine_latitude_weights_2d_singleton2(self): # 2d latitude coordinate with second dimension singleton cube = self.cube_aux_lat[:, :, 0:1] weights = iris.analysis.cartography.cosine_latitude_weights(cube) self.assertEqual(weights.shape, cube.shape) self.assertArrayAlmostEqual(weights[0, :, :], np.cos(np.deg2rad(self.lat2d[:, 0:1]))) def test_cosine_latitude_weights_2d_singleton3(self): # 2d latitude coordinate with both dimensions singleton cube = self.cube_aux_lat[:, 0:1, 0:1] weights = iris.analysis.cartography.cosine_latitude_weights(cube) self.assertEqual(weights.shape, cube.shape) self.assertArrayAlmostEqual(weights[0, :, :], np.cos(np.deg2rad(self.lat2d[0:1, 0:1]))) def test_cosine_latitude_weights_2d(self): # 2d latitude coordinate (time, lat, lon) weights = iris.analysis.cartography.cosine_latitude_weights( self.cube_aux_lat) self.assertEqual(weights.shape, self.cube_aux_lat.shape) self.assertArrayAlmostEqual(weights[0, :, :], np.cos(np.deg2rad(self.lat2d))) def test_cosine_latitude_weights_2d_latitude_first(self): # 2d latitude coordinate with latitude first (lat, time, lon) order = [1, 0, 2] # (lat, time, lon) self.cube_aux_lat.transpose(order) weights = iris.analysis.cartography.cosine_latitude_weights( self.cube_aux_lat) self.assertEqual(weights.shape, self.cube_aux_lat.shape) self.assertArrayAlmostEqual(weights[:, 0, :], np.cos(np.deg2rad(self.lat2d))) def test_cosine_latitude_weights_2d_latitude_last(self): # 2d latitude coordinate with latitude last (time, lon, lat) order = [0, 2, 1] # (time, lon, lat) self.cube_aux_lat.transpose(order) weights = iris.analysis.cartography.cosine_latitude_weights( self.cube_aux_lat) self.assertEqual(weights.shape, self.cube_aux_lat.shape) self.assertArrayAlmostEqual(weights[0, :, :], np.cos(np.deg2rad(self.lat2d.T))) def test_cosine_latitude_weights_no_latitude(self): # no coordinate identified as latitude self.cube_dim_lat.remove_coord('grid_latitude') with self.assertRaises(ValueError): weights = iris.analysis.cartography.cosine_latitude_weights( self.cube_dim_lat) def test_cosine_latitude_weights_multiple_latitude(self): # two coordinates identified as latitude with self.assertRaises(ValueError): weights = iris.analysis.cartography.cosine_latitude_weights( self.cube) class TestRollingWindow(tests.IrisTest): def setUp(self): # XXX Comes from test_aggregated_by cube = iris.cube.Cube(np.array([[6, 10, 12, 18], [8, 12, 14, 20], [18, 12, 10, 6]]), long_name='temperature', units='kelvin') cube.add_dim_coord(iris.coords.DimCoord(np.array([0, 5, 10], dtype=np.float64), 'latitude', units='degrees'), 0) cube.add_dim_coord(iris.coords.DimCoord(np.array([0, 2, 4, 6], dtype=np.float64), 'longitude', units='degrees'), 1) self.cube = cube def test_non_mean_operator(self): res_cube = self.cube.rolling_window('longitude', iris.analysis.MAX, window=2) expected_result = np.array([[10, 12, 18], [12, 14, 20], [18, 12, 10]], dtype=np.float64) self.assertArrayEqual(expected_result, res_cube.data) def test_longitude_simple(self): res_cube = self.cube.rolling_window('longitude', iris.analysis.MEAN, window=2) expected_result = np.array([[ 8., 11., 15.], [ 10., 13., 17.], [ 15., 11., 8.]], dtype=np.float64) self.assertArrayEqual(expected_result, res_cube.data) self.assertCML(res_cube, ('analysis', 'rolling_window', 'simple_longitude.cml')) self.assertRaises(ValueError, self.cube.rolling_window, 'longitude', iris.analysis.MEAN, window=0) def test_longitude_masked(self): self.cube.data = ma.array(self.cube.data, mask=[[True, True, True, True], [True, False, True, True], [False, False, False, False]]) res_cube = self.cube.rolling_window('longitude', iris.analysis.MEAN, window=2) expected_result = np.ma.array([[-99., -99., -99.], [12., 12., -99.], [15., 11., 8.]], mask=[[True, True, True], [False, False, True], [False, False, False]], dtype=np.float64) self.assertMaskedArrayEqual(expected_result, res_cube.data) def test_longitude_circular(self): cube = self.cube cube.coord('longitude').circular = True self.assertRaises(iris.exceptions.NotYetImplementedError, self.cube.rolling_window, 'longitude', iris.analysis.MEAN, window=0) def test_different_length_windows(self): res_cube = self.cube.rolling_window('longitude', iris.analysis.MEAN, window=4) expected_result = np.array([[ 11.5], [ 13.5], [ 11.5]], dtype=np.float64) self.assertArrayEqual(expected_result, res_cube.data) self.assertCML(res_cube, ('analysis', 'rolling_window', 'size_4_longitude.cml')) # Window too long: self.assertRaises(ValueError, self.cube.rolling_window, 'longitude', iris.analysis.MEAN, window=6) # Window too small: self.assertRaises(ValueError, self.cube.rolling_window, 'longitude', iris.analysis.MEAN, window=0) def test_bad_coordinate(self): self.assertRaises(KeyError, self.cube.rolling_window, 'wibble', iris.analysis.MEAN, window=0) def test_latitude_simple(self): res_cube = self.cube.rolling_window('latitude', iris.analysis.MEAN, window=2) expected_result = np.array([[ 7., 11., 13., 19.], [ 13., 12., 12., 13.]], dtype=np.float64) self.assertArrayEqual(expected_result, res_cube.data) self.assertCML(res_cube, ('analysis', 'rolling_window', 'simple_latitude.cml')) def test_mean_with_weights_consistency(self): # equal weights should be the same as the mean with no weights wts = np.array([0.5, 0.5], dtype=np.float64) res_cube = self.cube.rolling_window('longitude', iris.analysis.MEAN, window=2, weights=wts) expected_result = self.cube.rolling_window('longitude', iris.analysis.MEAN, window=2) self.assertArrayEqual(expected_result.data, res_cube.data) def test_mean_with_weights(self): # rolling window mean with weights wts = np.array([0.1, 0.6, 0.3], dtype=np.float64) res_cube = self.cube.rolling_window('longitude', iris.analysis.MEAN, window=3, weights=wts) expected_result = np.array([[10.2, 13.6], [12.2, 15.6], [12.0, 9.0]], dtype=np.float64) # use almost equal to compare floats self.assertArrayAlmostEqual(expected_result, res_cube.data) class TestProject(tests.GraphicsTest): def setUp(self): cube = iris.tests.stock.realistic_4d_no_derived() # Remove some slices to speed testing. self.cube = cube[0:2, 0:3] self.target_proj = ccrs.Robinson() def test_bad_resolution(self): with self.assertRaises(ValueError): iris.analysis.cartography.project(self.cube, self.target_proj, nx=-200, ny=200) with self.assertRaises(ValueError): iris.analysis.cartography.project(self.cube, self.target_proj, nx=200, ny='abc') def test_missing_latlon(self): cube = self.cube.copy() cube.remove_coord('grid_latitude') with self.assertRaises(ValueError): iris.analysis.cartography.project(cube, self.target_proj) cube = self.cube.copy() cube.remove_coord('grid_longitude') with self.assertRaises(ValueError): iris.analysis.cartography.project(cube, self.target_proj) self.cube.remove_coord('grid_longitude') self.cube.remove_coord('grid_latitude') with self.assertRaises(ValueError): iris.analysis.cartography.project(self.cube, self.target_proj) def test_default_resolution(self): new_cube, extent = iris.analysis.cartography.project(self.cube, self.target_proj) self.assertEqual(new_cube.shape, self.cube.shape) @tests.skip_data @tests.skip_plot def test_cartopy_projection(self): cube = iris.load_cube(tests.get_data_path(('PP', 'aPPglob1', 'global.pp'))) projections = {} projections['RotatedPole'] = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) projections['Robinson'] = ccrs.Robinson() projections['PlateCarree'] = ccrs.PlateCarree() projections['NorthPolarStereo'] = ccrs.NorthPolarStereo() projections['Orthographic'] = ccrs.Orthographic(central_longitude=-90, central_latitude=45) projections['InterruptedGoodeHomolosine'] = ccrs.InterruptedGoodeHomolosine() projections['LambertCylindrical'] = ccrs.LambertCylindrical() # Set up figure fig = plt.figure(figsize=(10, 10)) gs = matplotlib.gridspec.GridSpec(nrows=3, ncols=3, hspace=1.5, wspace=0.5) for subplot_spec, name in zip(gs, sorted(projections)): target_proj = projections[name] # Set up axes and title ax = plt.subplot(subplot_spec, frameon=False, projection=target_proj) ax.set_title(name) # Transform cube to target projection new_cube, extent = iris.analysis.cartography.project(cube, target_proj, nx=150, ny=150) # Plot plt.pcolor(new_cube.coord('projection_x_coordinate').points, new_cube.coord('projection_y_coordinate').points, new_cube.data) # Add coastlines ax.coastlines() # Tighten up layout gs.tight_layout(plt.gcf()) # Verify resulting plot self.check_graphic(tol=1.0) @tests.skip_data def test_no_coord_system(self): cube = iris.load_cube(tests.get_data_path(('PP', 'aPPglob1', 'global.pp'))) cube.coord('longitude').coord_system = None cube.coord('latitude').coord_system = None new_cube, extent = iris.analysis.cartography.project(cube, self.target_proj) self.assertCML(new_cube, ('analysis', 'project', 'default_source_cs.cml')) if __name__ == "__main__": tests.main()
gpl-3.0
herberthudson/pynance
pynance/opt/price.py
2
7070
""" .. Copyright (c) 2014, 2015 Marshall Farrier license http://opensource.org/licenses/MIT Options - price (:mod:`pynance.opt.price`) ================================================== .. currentmodule:: pynance.opt.price """ from __future__ import absolute_import import pandas as pd from ._common import _getprice from ._common import _relevant_rows from . import _constants class Price(object): """ Wrapper class for :class:`pandas.DataFrame` for retrieving options prices. Objects of this class are not intended for direct instantiation but are created as attributes of objects of type :class:`~pynance.opt.core.Options`. .. versionadded:: 0.3.0 Parameters ---------- df : :class:`pandas.DataFrame` Options data. Attributes ---------- data : :class:`pandas.DataFrame` Options data. Methods ------- .. automethod:: exps .. automethod:: get .. automethod:: metrics .. automethod:: strikes """ def __init__(self, df): self.data = df def get(self, opttype, strike, expiry): """ Price as midpoint between bid and ask. Parameters ---------- opttype : str 'call' or 'put'. strike : numeric Strike price. expiry : date-like Expiration date. Can be a :class:`datetime.datetime` or a string that :mod:`pandas` can interpret as such, e.g. '2015-01-01'. Returns ------- out : float Examples -------- >>> geopts = pn.opt.get('ge') >>> geopts.price.get('call', 26., '2015-09-18') 0.94 """ _optrow = _relevant_rows(self.data, (strike, expiry, opttype,), "No key for {} strike {} {}".format(expiry, strike, opttype)) return _getprice(_optrow) def metrics(self, opttype, strike, expiry): """ Basic metrics for a specific option. Parameters ---------- opttype : str ('call' or 'put') strike : numeric Strike price. expiry : date-like Expiration date. Can be a :class:`datetime.datetime` or a string that :mod:`pandas` can interpret as such, e.g. '2015-01-01'. Returns ------- out : :class:`pandas.DataFrame` """ _optrow = _relevant_rows(self.data, (strike, expiry, opttype,), "No key for {} strike {} {}".format(expiry, strike, opttype)) _index = ['Opt_Price', 'Time_Val', 'Last', 'Bid', 'Ask', 'Vol', 'Open_Int', 'Underlying_Price', 'Quote_Time'] _out = pd.DataFrame(index=_index, columns=['Value']) _out.loc['Opt_Price', 'Value'] = _opt_price = _getprice(_optrow) for _name in _index[2:]: _out.loc[_name, 'Value'] = _optrow.loc[:, _name].values[0] _eq_price = _out.loc['Underlying_Price', 'Value'] if opttype == 'put': _out.loc['Time_Val'] = _get_put_time_val(_opt_price, strike, _eq_price) else: _out.loc['Time_Val'] = _get_call_time_val(_opt_price, strike, _eq_price) return _out def strikes(self, opttype, expiry): """ Retrieve option prices for all strikes of a given type with a given expiration. Parameters ---------- opttype : str ('call' or 'put') expiry : date-like Expiration date. Can be a :class:`datetime.datetime` or a string that :mod:`pandas` can interpret as such, e.g. '2015-01-01'. Returns ---------- df : :class:`pandas.DataFrame` eq : float Price of underlying. qt : datetime.datetime Time of quote. See Also -------- :meth:`exps` """ _relevant = _relevant_rows(self.data, (slice(None), expiry, opttype,), "No key for {} {}".format(expiry, opttype)) _index = _relevant.index.get_level_values('Strike') _columns = ['Price', 'Time_Val', 'Last', 'Bid', 'Ask', 'Vol', 'Open_Int'] _df = pd.DataFrame(index=_index, columns=_columns) _underlying = _relevant.loc[:, 'Underlying_Price'].values[0] _quotetime = pd.to_datetime(_relevant.loc[:, 'Quote_Time'].values[0], utc=True).to_datetime() for _col in _columns[2:]: _df.loc[:, _col] = _relevant.loc[:, _col].values _df.loc[:, 'Price'] = (_df.loc[:, 'Bid'] + _df.loc[:, 'Ask']) / 2. _set_tv_strike_ix(_df, opttype, 'Price', 'Time_Val', _underlying) return _df, _underlying, _quotetime def exps(self, opttype, strike): """ Prices for given strike on all available dates. Parameters ---------- opttype : str ('call' or 'put') strike : numeric Returns ---------- df : :class:`pandas.DataFrame` eq : float Price of underlying. qt : :class:`datetime.datetime` Time of quote. See Also -------- :meth:`strikes` """ _relevant = _relevant_rows(self.data, (strike, slice(None), opttype,), "No key for {} {}".format(strike, opttype)) _index = _relevant.index.get_level_values('Expiry') _columns = ['Price', 'Time_Val', 'Last', 'Bid', 'Ask', 'Vol', 'Open_Int'] _df = pd.DataFrame(index=_index, columns=_columns) _eq = _relevant.loc[:, 'Underlying_Price'].values[0] _qt = pd.to_datetime(_relevant.loc[:, 'Quote_Time'].values[0], utc=True).to_datetime() for _col in _columns[2:]: _df.loc[:, _col] = _relevant.loc[:, _col].values _df.loc[:, 'Price'] = (_df.loc[:, 'Bid'] + _df.loc[:, 'Ask']) / 2. _set_tv_other_ix(_df, opttype, 'Price', 'Time_Val', _eq, strike) return _df, _eq, _qt def _set_tv_other_ix(df, opttype, pricecol, tvcol, eqprice, strike): if opttype == 'put': if strike <= eqprice: df.loc[:, tvcol] = df.loc[:, pricecol] else: _diff = eqprice - strike df.loc[:, tvcol] = df.loc[:, pricecol] + _diff else: if eqprice <= strike: df.loc[:, tvcol] = df.loc[:, pricecol] else: _diff = strike - eqprice df.loc[:, tvcol] = df.loc[:, pricecol] + _diff def _set_tv_strike_ix(df, opttype, pricecol, tvcol, eqprice): df.loc[:, tvcol] = df.loc[:, pricecol] if opttype == 'put': _mask = (df.index > eqprice) df.loc[_mask, tvcol] += eqprice - df.index[_mask] else: _mask = (df.index < eqprice) df.loc[_mask, tvcol] += df.index[_mask] - eqprice return def _get_put_time_val(putprice, strike, eqprice): if strike <= eqprice: return putprice return round(putprice + eqprice - strike, _constants.NDIGITS_SIG) def _get_call_time_val(callprice, strike, eqprice): if eqprice <= strike: return callprice return round(callprice + strike - eqprice, _constants.NDIGITS_SIG)
mit
wesleybowman/karsten
turbine_array/UTide/plotTest.py
1
2694
import netCDF4 as nc import matplotlib.pyplot as plt import matplotlib.tri as Tri import matplotlib.ticker as ticker #from mpl_toolkits.basemap import Basemap import numpy as np import cPickle as pickle import seaborn import time filename = '/home/wesley/github/aidan-projects/grid/dngrid_0001.nc' data = nc.Dataset(filename,'r') lat = data.variables['lat'][:] lon = data.variables['lon'][:] nv = data.variables['nv'][:].T -1 h = data.variables['h'][:] el = data.variables['zeta'][:] x = data.variables['x'][:] y = data.variables['y'][:] trinodes = nv xc = np.mean(x[trinodes], axis=1) yc = np.mean(y[trinodes], axis=1) hc = np.mean(h[trinodes], axis=1) lonc = np.mean(lon[trinodes], axis=1) latc = np.mean(lat[trinodes], axis=1) loci = pickle.load(open('loci.p', 'rb')) loci = loci.astype(int) latind = np.argwhere(((45.2<lat[:]), (lat<45.4))) lonind = np.argwhere(((-64.8<lon), (lon<-64.1))) lat[latind] lon[lonind] #tri = Tri.Triangulation(lon,lat,triangles=nv) tri = Tri.Triangulation(lon[lonind], lat[latind], triangles=nv) levels = np.arange(-100, -8, 1) fig = plt.figure(figsize=(18,10)) #plt.ion() plt.rc('font',size='22') #ax = fig.add_subplot(111,aspect=(1.0/np.cos(np.mean(lat)*np.pi/180.0))) ax = fig.add_subplot(111) #plt.tricontourf(tri, -h,levels=levels,shading='faceted',cmap=plt.cm.gist_earth) plt.tricontourf(tri, -h,levels=levels,shading='faceted') plt.triplot(tri) plt.ylabel('Latitude') plt.xlabel('Longitude') plt.gca().patch.set_facecolor('0.5') cbar = plt.colorbar() cbar.set_label('Water Depth (m)', rotation=-90, labelpad=30) scale = 1 ticks = ticker.FuncFormatter(lambda lon, pos: '{0:g}'.format(lon/scale)) ax.xaxis.set_major_formatter(ticks) ax.yaxis.set_major_formatter(ticks) plt.grid() #plt.plot(xc[loci], yc[loci], 'ko') #plt.plot(lonc[loci], latc[loci], 'ko') #plt.plot(lonc[loci[0]], latc[loci[0]], 'ko') plt.show() for i,v in enumerate(loci): print i plt.tricontourf(tri, -h,levels=levels,shading='faceted') plt.triplot(tri) plt.ylabel('Latitude') plt.xlabel('Longitude') plt.gca().patch.set_facecolor('0.5') cbar = plt.colorbar() cbar.set_label('Water Depth (m)', rotation=-90, labelpad=30) scale = 1 ticks = ticker.FuncFormatter(lambda lon, pos: '{0:g}'.format(lon/scale)) ax.xaxis.set_major_formatter(ticks) ax.yaxis.set_major_formatter(ticks) plt.grid() plt.plot(lonc[loci[0:i]], latc[loci[0:i]], 'ko') #time.sleep(0.5) #plt.draw() plt.show() #plt.show() #fig=plt.figure() #plt.axis([0,1000,0,1]) # #i=0 #x=list() #y=list() # #while i <1000: # temp_y=np.random.random() # x.append(i) # y.append(temp_y) # plt.scatter(i,temp_y) # i+=1 # plt.show()
mit
valexandersaulys/airbnb_kaggle_contest
venv/lib/python3.4/site-packages/sklearn/linear_model/tests/test_passive_aggressive.py
169
8809
import numpy as np import scipy.sparse as sp from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_array_almost_equal, assert_array_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_raises from sklearn.base import ClassifierMixin from sklearn.utils import check_random_state from sklearn.datasets import load_iris from sklearn.linear_model import PassiveAggressiveClassifier from sklearn.linear_model import PassiveAggressiveRegressor iris = load_iris() random_state = check_random_state(12) indices = np.arange(iris.data.shape[0]) random_state.shuffle(indices) X = iris.data[indices] y = iris.target[indices] X_csr = sp.csr_matrix(X) class MyPassiveAggressive(ClassifierMixin): def __init__(self, C=1.0, epsilon=0.01, loss="hinge", fit_intercept=True, n_iter=1, random_state=None): self.C = C self.epsilon = epsilon self.loss = loss self.fit_intercept = fit_intercept self.n_iter = n_iter def fit(self, X, y): n_samples, n_features = X.shape self.w = np.zeros(n_features, dtype=np.float64) self.b = 0.0 for t in range(self.n_iter): for i in range(n_samples): p = self.project(X[i]) if self.loss in ("hinge", "squared_hinge"): loss = max(1 - y[i] * p, 0) else: loss = max(np.abs(p - y[i]) - self.epsilon, 0) sqnorm = np.dot(X[i], X[i]) if self.loss in ("hinge", "epsilon_insensitive"): step = min(self.C, loss / sqnorm) elif self.loss in ("squared_hinge", "squared_epsilon_insensitive"): step = loss / (sqnorm + 1.0 / (2 * self.C)) if self.loss in ("hinge", "squared_hinge"): step *= y[i] else: step *= np.sign(y[i] - p) self.w += step * X[i] if self.fit_intercept: self.b += step def project(self, X): return np.dot(X, self.w) + self.b def test_classifier_accuracy(): for data in (X, X_csr): for fit_intercept in (True, False): clf = PassiveAggressiveClassifier(C=1.0, n_iter=30, fit_intercept=fit_intercept, random_state=0) clf.fit(data, y) score = clf.score(data, y) assert_greater(score, 0.79) def test_classifier_partial_fit(): classes = np.unique(y) for data in (X, X_csr): clf = PassiveAggressiveClassifier(C=1.0, fit_intercept=True, random_state=0) for t in range(30): clf.partial_fit(data, y, classes) score = clf.score(data, y) assert_greater(score, 0.79) def test_classifier_refit(): # Classifier can be retrained on different labels and features. clf = PassiveAggressiveClassifier().fit(X, y) assert_array_equal(clf.classes_, np.unique(y)) clf.fit(X[:, :-1], iris.target_names[y]) assert_array_equal(clf.classes_, iris.target_names) def test_classifier_correctness(): y_bin = y.copy() y_bin[y != 1] = -1 for loss in ("hinge", "squared_hinge"): clf1 = MyPassiveAggressive(C=1.0, loss=loss, fit_intercept=True, n_iter=2) clf1.fit(X, y_bin) for data in (X, X_csr): clf2 = PassiveAggressiveClassifier(C=1.0, loss=loss, fit_intercept=True, n_iter=2, shuffle=False) clf2.fit(data, y_bin) assert_array_almost_equal(clf1.w, clf2.coef_.ravel(), decimal=2) def test_classifier_undefined_methods(): clf = PassiveAggressiveClassifier() for meth in ("predict_proba", "predict_log_proba", "transform"): assert_raises(AttributeError, lambda x: getattr(clf, x), meth) def test_class_weights(): # Test class weights. X2 = np.array([[-1.0, -1.0], [-1.0, 0], [-.8, -1.0], [1.0, 1.0], [1.0, 0.0]]) y2 = [1, 1, 1, -1, -1] clf = PassiveAggressiveClassifier(C=0.1, n_iter=100, class_weight=None, random_state=100) clf.fit(X2, y2) assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([1])) # we give a small weights to class 1 clf = PassiveAggressiveClassifier(C=0.1, n_iter=100, class_weight={1: 0.001}, random_state=100) clf.fit(X2, y2) # now the hyperplane should rotate clock-wise and # the prediction on this point should shift assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([-1])) def test_partial_fit_weight_class_balanced(): # partial_fit with class_weight='balanced' not supported clf = PassiveAggressiveClassifier(class_weight="balanced") assert_raises(ValueError, clf.partial_fit, X, y, classes=np.unique(y)) def test_equal_class_weight(): X2 = [[1, 0], [1, 0], [0, 1], [0, 1]] y2 = [0, 0, 1, 1] clf = PassiveAggressiveClassifier(C=0.1, n_iter=1000, class_weight=None) clf.fit(X2, y2) # Already balanced, so "balanced" weights should have no effect clf_balanced = PassiveAggressiveClassifier(C=0.1, n_iter=1000, class_weight="balanced") clf_balanced.fit(X2, y2) clf_weighted = PassiveAggressiveClassifier(C=0.1, n_iter=1000, class_weight={0: 0.5, 1: 0.5}) clf_weighted.fit(X2, y2) # should be similar up to some epsilon due to learning rate schedule assert_almost_equal(clf.coef_, clf_weighted.coef_, decimal=2) assert_almost_equal(clf.coef_, clf_balanced.coef_, decimal=2) def test_wrong_class_weight_label(): # ValueError due to wrong class_weight label. X2 = np.array([[-1.0, -1.0], [-1.0, 0], [-.8, -1.0], [1.0, 1.0], [1.0, 0.0]]) y2 = [1, 1, 1, -1, -1] clf = PassiveAggressiveClassifier(class_weight={0: 0.5}) assert_raises(ValueError, clf.fit, X2, y2) def test_wrong_class_weight_format(): # ValueError due to wrong class_weight argument type. X2 = np.array([[-1.0, -1.0], [-1.0, 0], [-.8, -1.0], [1.0, 1.0], [1.0, 0.0]]) y2 = [1, 1, 1, -1, -1] clf = PassiveAggressiveClassifier(class_weight=[0.5]) assert_raises(ValueError, clf.fit, X2, y2) clf = PassiveAggressiveClassifier(class_weight="the larch") assert_raises(ValueError, clf.fit, X2, y2) def test_regressor_mse(): y_bin = y.copy() y_bin[y != 1] = -1 for data in (X, X_csr): for fit_intercept in (True, False): reg = PassiveAggressiveRegressor(C=1.0, n_iter=50, fit_intercept=fit_intercept, random_state=0) reg.fit(data, y_bin) pred = reg.predict(data) assert_less(np.mean((pred - y_bin) ** 2), 1.7) def test_regressor_partial_fit(): y_bin = y.copy() y_bin[y != 1] = -1 for data in (X, X_csr): reg = PassiveAggressiveRegressor(C=1.0, fit_intercept=True, random_state=0) for t in range(50): reg.partial_fit(data, y_bin) pred = reg.predict(data) assert_less(np.mean((pred - y_bin) ** 2), 1.7) def test_regressor_correctness(): y_bin = y.copy() y_bin[y != 1] = -1 for loss in ("epsilon_insensitive", "squared_epsilon_insensitive"): reg1 = MyPassiveAggressive(C=1.0, loss=loss, fit_intercept=True, n_iter=2) reg1.fit(X, y_bin) for data in (X, X_csr): reg2 = PassiveAggressiveRegressor(C=1.0, loss=loss, fit_intercept=True, n_iter=2, shuffle=False) reg2.fit(data, y_bin) assert_array_almost_equal(reg1.w, reg2.coef_.ravel(), decimal=2) def test_regressor_undefined_methods(): reg = PassiveAggressiveRegressor() for meth in ("transform",): assert_raises(AttributeError, lambda x: getattr(reg, x), meth)
gpl-2.0
google-research/electra
finetune/qa/squad_official_eval.py
1
12022
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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. """Official evaluation script for SQuAD version 2.0. In addition to basic functionality, we also compute additional statistics and plot precision-recall curves if an additional na_prob.json file is provided. This file is expected to map question ID's to the model's predicted probability that a question is unanswerable. Modified slightly for the ELECTRA codebase. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import collections import json import numpy as np import os import re import string import sys import tensorflow.compat.v1 as tf import configure_finetuning OPTS = None def parse_args(): parser = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.') parser.add_argument('data_file', metavar='data.json', help='Input data JSON file.') parser.add_argument('pred_file', metavar='pred.json', help='Model predictions.') parser.add_argument('--out-file', '-o', metavar='eval.json', help='Write accuracy metrics to file (default is stdout).') parser.add_argument('--na-prob-file', '-n', metavar='na_prob.json', help='Model estimates of probability of no answer.') parser.add_argument('--na-prob-thresh', '-t', type=float, default=1.0, help='Predict "" if no-answer probability exceeds this (default = 1.0).') parser.add_argument('--out-image-dir', '-p', metavar='out_images', default=None, help='Save precision-recall curves to directory.') parser.add_argument('--verbose', '-v', action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def set_opts(config: configure_finetuning.FinetuningConfig, split): global OPTS Options = collections.namedtuple("Options", [ "data_file", "pred_file", "out_file", "na_prob_file", "na_prob_thresh", "out_image_dir", "verbose"]) OPTS = Options( data_file=os.path.join( config.raw_data_dir("squad"), split + ("-debug" if config.debug else "") + ".json"), pred_file=config.qa_preds_file("squad"), out_file=config.qa_eval_file("squad"), na_prob_file=config.qa_na_file("squad"), na_prob_thresh=config.qa_na_threshold, out_image_dir=None, verbose=False ) def make_qid_to_has_ans(dataset): qid_to_has_ans = {} for article in dataset: for p in article['paragraphs']: for qa in p['qas']: qid_to_has_ans[qa['id']] = bool(qa['answers']) return qid_to_has_ans def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): regex = re.compile(r'\b(a|an|the)\b', re.UNICODE) return re.sub(regex, ' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): exclude = set(string.punctuation) return ''.join(ch for ch in text if ch not in exclude) def lower(text): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(s)))) def get_tokens(s): if not s: return [] return normalize_answer(s).split() def compute_exact(a_gold, a_pred): return int(normalize_answer(a_gold) == normalize_answer(a_pred)) def compute_f1(a_gold, a_pred): gold_toks = get_tokens(a_gold) pred_toks = get_tokens(a_pred) common = collections.Counter(gold_toks) & collections.Counter(pred_toks) num_same = sum(common.values()) if len(gold_toks) == 0 or len(pred_toks) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 precision = 1.0 * num_same / len(pred_toks) recall = 1.0 * num_same / len(gold_toks) f1 = (2 * precision * recall) / (precision + recall) return f1 def get_raw_scores(dataset, preds): exact_scores = {} f1_scores = {} for article in dataset: for p in article['paragraphs']: for qa in p['qas']: qid = qa['id'] gold_answers = [a['text'] for a in qa['answers'] if normalize_answer(a['text'])] if not gold_answers: # For unanswerable questions, only correct answer is empty string gold_answers = [''] if qid not in preds: print('Missing prediction for %s' % qid) continue a_pred = preds[qid] # Take max over all gold answers exact_scores[qid] = max(compute_exact(a, a_pred) for a in gold_answers) f1_scores[qid] = max(compute_f1(a, a_pred) for a in gold_answers) return exact_scores, f1_scores def apply_no_ans_threshold(scores, na_probs, qid_to_has_ans, na_prob_thresh): new_scores = {} for qid, s in scores.items(): pred_na = na_probs[qid] > na_prob_thresh if pred_na: new_scores[qid] = float(not qid_to_has_ans[qid]) else: new_scores[qid] = s return new_scores def make_eval_dict(exact_scores, f1_scores, qid_list=None): if not qid_list: total = len(exact_scores) return collections.OrderedDict([ ('exact', 100.0 * sum(exact_scores.values()) / total), ('f1', 100.0 * sum(f1_scores.values()) / total), ('total', total), ]) else: total = len(qid_list) return collections.OrderedDict([ ('exact', 100.0 * sum(exact_scores[k] for k in qid_list) / total), ('f1', 100.0 * sum(f1_scores[k] for k in qid_list) / total), ('total', total), ]) def merge_eval(main_eval, new_eval, prefix): for k in new_eval: main_eval['%s_%s' % (prefix, k)] = new_eval[k] def plot_pr_curve(precisions, recalls, out_image, title): plt.step(recalls, precisions, color='b', alpha=0.2, where='post') plt.fill_between(recalls, precisions, step='post', alpha=0.2, color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.title(title) plt.savefig(out_image) plt.clf() def make_precision_recall_eval(scores, na_probs, num_true_pos, qid_to_has_ans, out_image=None, title=None): qid_list = sorted(na_probs, key=lambda k: na_probs[k]) true_pos = 0.0 cur_p = 1.0 cur_r = 0.0 precisions = [1.0] recalls = [0.0] avg_prec = 0.0 for i, qid in enumerate(qid_list): if qid_to_has_ans[qid]: true_pos += scores[qid] cur_p = true_pos / float(i+1) cur_r = true_pos / float(num_true_pos) if i == len(qid_list) - 1 or na_probs[qid] != na_probs[qid_list[i+1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(cur_p) recalls.append(cur_r) if out_image: plot_pr_curve(precisions, recalls, out_image, title) return {'ap': 100.0 * avg_prec} def run_precision_recall_analysis(main_eval, exact_raw, f1_raw, na_probs, qid_to_has_ans, out_image_dir): if out_image_dir and not os.path.exists(out_image_dir): os.makedirs(out_image_dir) num_true_pos = sum(1 for v in qid_to_has_ans.values() if v) if num_true_pos == 0: return pr_exact = make_precision_recall_eval( exact_raw, na_probs, num_true_pos, qid_to_has_ans, out_image=os.path.join(out_image_dir, 'pr_exact.png'), title='Precision-Recall curve for Exact Match score') pr_f1 = make_precision_recall_eval( f1_raw, na_probs, num_true_pos, qid_to_has_ans, out_image=os.path.join(out_image_dir, 'pr_f1.png'), title='Precision-Recall curve for F1 score') oracle_scores = {k: float(v) for k, v in qid_to_has_ans.items()} pr_oracle = make_precision_recall_eval( oracle_scores, na_probs, num_true_pos, qid_to_has_ans, out_image=os.path.join(out_image_dir, 'pr_oracle.png'), title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)') merge_eval(main_eval, pr_exact, 'pr_exact') merge_eval(main_eval, pr_f1, 'pr_f1') merge_eval(main_eval, pr_oracle, 'pr_oracle') def histogram_na_prob(na_probs, qid_list, image_dir, name): if not qid_list: return x = [na_probs[k] for k in qid_list] weights = np.ones_like(x) / float(len(x)) plt.hist(x, weights=weights, bins=20, range=(0.0, 1.0)) plt.xlabel('Model probability of no-answer') plt.ylabel('Proportion of dataset') plt.title('Histogram of no-answer probability: %s' % name) plt.savefig(os.path.join(image_dir, 'na_prob_hist_%s.png' % name)) plt.clf() def find_best_thresh(preds, scores, na_probs, qid_to_has_ans): num_no_ans = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) cur_score = num_no_ans best_score = cur_score best_thresh = 0.0 qid_list = sorted(na_probs, key=lambda k: na_probs[k]) for i, qid in enumerate(qid_list): if qid not in scores: continue if qid_to_has_ans[qid]: diff = scores[qid] else: if preds[qid]: diff = -1 else: diff = 0 cur_score += diff if cur_score > best_score: best_score = cur_score best_thresh = na_probs[qid] return 100.0 * best_score / len(scores), best_thresh def find_all_best_thresh(main_eval, preds, exact_raw, f1_raw, na_probs, qid_to_has_ans): best_exact, exact_thresh = find_best_thresh(preds, exact_raw, na_probs, qid_to_has_ans) best_f1, f1_thresh = find_best_thresh(preds, f1_raw, na_probs, qid_to_has_ans) main_eval['best_exact'] = best_exact main_eval['best_exact_thresh'] = exact_thresh main_eval['best_f1'] = best_f1 main_eval['best_f1_thresh'] = f1_thresh def main(): with tf.io.gfile.GFile(OPTS.data_file) as f: dataset_json = json.load(f) dataset = dataset_json['data'] with tf.io.gfile.GFile(OPTS.pred_file) as f: preds = json.load(f) if OPTS.na_prob_file: with tf.io.gfile.GFile(OPTS.na_prob_file) as f: na_probs = json.load(f) else: na_probs = {k: 0.0 for k in preds} qid_to_has_ans = make_qid_to_has_ans(dataset) # maps qid to True/False has_ans_qids = [k for k, v in qid_to_has_ans.items() if v] no_ans_qids = [k for k, v in qid_to_has_ans.items() if not v] exact_raw, f1_raw = get_raw_scores(dataset, preds) exact_thresh = apply_no_ans_threshold(exact_raw, na_probs, qid_to_has_ans, OPTS.na_prob_thresh) f1_thresh = apply_no_ans_threshold(f1_raw, na_probs, qid_to_has_ans, OPTS.na_prob_thresh) out_eval = make_eval_dict(exact_thresh, f1_thresh) if has_ans_qids: has_ans_eval = make_eval_dict(exact_thresh, f1_thresh, qid_list=has_ans_qids) merge_eval(out_eval, has_ans_eval, 'HasAns') if no_ans_qids: no_ans_eval = make_eval_dict(exact_thresh, f1_thresh, qid_list=no_ans_qids) merge_eval(out_eval, no_ans_eval, 'NoAns') if OPTS.na_prob_file: find_all_best_thresh(out_eval, preds, exact_raw, f1_raw, na_probs, qid_to_has_ans) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(out_eval, exact_raw, f1_raw, na_probs, qid_to_has_ans, OPTS.out_image_dir) histogram_na_prob(na_probs, has_ans_qids, OPTS.out_image_dir, 'hasAns') histogram_na_prob(na_probs, no_ans_qids, OPTS.out_image_dir, 'noAns') if OPTS.out_file: with tf.io.gfile.GFile(OPTS.out_file, 'w') as f: json.dump(out_eval, f) else: print(json.dumps(out_eval, indent=2)) if __name__ == '__main__': OPTS = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
apache-2.0
GuessWhoSamFoo/pandas
pandas/core/internals/blocks.py
1
114866
# -*- coding: utf-8 -*- from datetime import date, datetime, timedelta import functools import inspect import re import warnings import numpy as np from pandas._libs import internals as libinternals, lib, tslib, tslibs from pandas._libs.tslibs import Timedelta, conversion, is_null_datetimelike import pandas.compat as compat from pandas.compat import range, zip from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.cast import ( astype_nansafe, find_common_type, infer_dtype_from, infer_dtype_from_scalar, maybe_convert_objects, maybe_downcast_to_dtype, maybe_infer_dtype_type, maybe_promote, maybe_upcast, soft_convert_objects) from pandas.core.dtypes.common import ( _NS_DTYPE, _TD_DTYPE, ensure_platform_int, is_bool_dtype, is_categorical, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_dtype_equal, is_extension_array_dtype, is_extension_type, is_float_dtype, is_integer, is_integer_dtype, is_interval_dtype, is_list_like, is_numeric_v_string_like, is_object_dtype, is_period_dtype, is_re, is_re_compilable, is_sparse, is_timedelta64_dtype, pandas_dtype) import pandas.core.dtypes.concat as _concat from pandas.core.dtypes.dtypes import ( CategoricalDtype, ExtensionDtype, PandasExtensionDtype) from pandas.core.dtypes.generic import ( ABCDataFrame, ABCDatetimeIndex, ABCExtensionArray, ABCIndexClass, ABCSeries) from pandas.core.dtypes.missing import ( _isna_compat, array_equivalent, isna, notna) import pandas.core.algorithms as algos from pandas.core.arrays import ( Categorical, DatetimeArray, ExtensionArray, TimedeltaArray) from pandas.core.base import PandasObject import pandas.core.common as com from pandas.core.indexes.datetimes import DatetimeIndex from pandas.core.indexing import check_setitem_lengths from pandas.core.internals.arrays import extract_array import pandas.core.missing as missing from pandas.core.nanops import nanpercentile from pandas.io.formats.printing import pprint_thing class Block(PandasObject): """ Canonical n-dimensional unit of homogeneous dtype contained in a pandas data structure Index-ignorant; let the container take care of that """ __slots__ = ['_mgr_locs', 'values', 'ndim'] is_numeric = False is_float = False is_integer = False is_complex = False is_datetime = False is_datetimetz = False is_timedelta = False is_bool = False is_object = False is_categorical = False is_sparse = False is_extension = False _box_to_block_values = True _can_hold_na = False _can_consolidate = True _verify_integrity = True _validate_ndim = True _ftype = 'dense' _concatenator = staticmethod(np.concatenate) def __init__(self, values, placement, ndim=None): self.ndim = self._check_ndim(values, ndim) self.mgr_locs = placement self.values = values if (self._validate_ndim and self.ndim and len(self.mgr_locs) != len(self.values)): raise ValueError( 'Wrong number of items passed {val}, placement implies ' '{mgr}'.format(val=len(self.values), mgr=len(self.mgr_locs))) def _check_ndim(self, values, ndim): """ ndim inference and validation. Infers ndim from 'values' if not provided to __init__. Validates that values.ndim and ndim are consistent if and only if the class variable '_validate_ndim' is True. Parameters ---------- values : array-like ndim : int or None Returns ------- ndim : int Raises ------ ValueError : the number of dimensions do not match """ if ndim is None: ndim = values.ndim if self._validate_ndim and values.ndim != ndim: msg = ("Wrong number of dimensions. values.ndim != ndim " "[{} != {}]") raise ValueError(msg.format(values.ndim, ndim)) return ndim @property def _holder(self): """The array-like that can hold the underlying values. None for 'Block', overridden by subclasses that don't use an ndarray. """ return None @property def _consolidate_key(self): return (self._can_consolidate, self.dtype.name) @property def _is_single_block(self): return self.ndim == 1 @property def is_view(self): """ return a boolean if I am possibly a view """ return self.values.base is not None @property def is_datelike(self): """ return True if I am a non-datelike """ return self.is_datetime or self.is_timedelta def is_categorical_astype(self, dtype): """ validate that we have a astypeable to categorical, returns a boolean if we are a categorical """ if dtype is Categorical or dtype is CategoricalDtype: # this is a pd.Categorical, but is not # a valid type for astypeing raise TypeError("invalid type {0} for astype".format(dtype)) elif is_categorical_dtype(dtype): return True return False def external_values(self, dtype=None): """ return an outside world format, currently just the ndarray """ return self.values def internal_values(self, dtype=None): """ return an internal format, currently just the ndarray this should be the pure internal API format """ return self.values def formatting_values(self): """Return the internal values used by the DataFrame/SeriesFormatter""" return self.internal_values() def get_values(self, dtype=None): """ return an internal format, currently just the ndarray this is often overridden to handle to_dense like operations """ if is_object_dtype(dtype): return self.values.astype(object) return self.values def to_dense(self): return self.values.view() @property def _na_value(self): return np.nan @property def fill_value(self): return np.nan @property def mgr_locs(self): return self._mgr_locs @mgr_locs.setter def mgr_locs(self, new_mgr_locs): if not isinstance(new_mgr_locs, libinternals.BlockPlacement): new_mgr_locs = libinternals.BlockPlacement(new_mgr_locs) self._mgr_locs = new_mgr_locs @property def array_dtype(self): """ the dtype to return if I want to construct this block as an array """ return self.dtype def make_block(self, values, placement=None, ndim=None): """ Create a new block, with type inference propagate any values that are not specified """ if placement is None: placement = self.mgr_locs if ndim is None: ndim = self.ndim return make_block(values, placement=placement, ndim=ndim) def make_block_same_class(self, values, placement=None, ndim=None, dtype=None): """ Wrap given values in a block of same type as self. """ if dtype is not None: # issue 19431 fastparquet is passing this warnings.warn("dtype argument is deprecated, will be removed " "in a future release.", DeprecationWarning) if placement is None: placement = self.mgr_locs return make_block(values, placement=placement, ndim=ndim, klass=self.__class__, dtype=dtype) def __unicode__(self): # don't want to print out all of the items here name = pprint_thing(self.__class__.__name__) if self._is_single_block: result = '{name}: {len} dtype: {dtype}'.format( name=name, len=len(self), dtype=self.dtype) else: shape = ' x '.join(pprint_thing(s) for s in self.shape) result = '{name}: {index}, {shape}, dtype: {dtype}'.format( name=name, index=pprint_thing(self.mgr_locs.indexer), shape=shape, dtype=self.dtype) return result def __len__(self): return len(self.values) def __getstate__(self): return self.mgr_locs.indexer, self.values def __setstate__(self, state): self.mgr_locs = libinternals.BlockPlacement(state[0]) self.values = state[1] self.ndim = self.values.ndim def _slice(self, slicer): """ return a slice of my values """ return self.values[slicer] def reshape_nd(self, labels, shape, ref_items): """ Parameters ---------- labels : list of new axis labels shape : new shape ref_items : new ref_items return a new block that is transformed to a nd block """ return _block2d_to_blocknd(values=self.get_values().T, placement=self.mgr_locs, shape=shape, labels=labels, ref_items=ref_items) def getitem_block(self, slicer, new_mgr_locs=None): """ Perform __getitem__-like, return result as block. As of now, only supports slices that preserve dimensionality. """ if new_mgr_locs is None: if isinstance(slicer, tuple): axis0_slicer = slicer[0] else: axis0_slicer = slicer new_mgr_locs = self.mgr_locs[axis0_slicer] new_values = self._slice(slicer) if self._validate_ndim and new_values.ndim != self.ndim: raise ValueError("Only same dim slicing is allowed") return self.make_block_same_class(new_values, new_mgr_locs) @property def shape(self): return self.values.shape @property def dtype(self): return self.values.dtype @property def ftype(self): if getattr(self.values, '_pandas_ftype', False): dtype = self.dtype.subtype else: dtype = self.dtype return "{dtype}:{ftype}".format(dtype=dtype, ftype=self._ftype) def merge(self, other): return _merge_blocks([self, other]) def concat_same_type(self, to_concat, placement=None): """ Concatenate list of single blocks of the same type. """ values = self._concatenator([blk.values for blk in to_concat], axis=self.ndim - 1) return self.make_block_same_class( values, placement=placement or slice(0, len(values), 1)) def iget(self, i): return self.values[i] def set(self, locs, values): """ Modify Block in-place with new item value Returns ------- None """ self.values[locs] = values def delete(self, loc): """ Delete given loc(-s) from block in-place. """ self.values = np.delete(self.values, loc, 0) self.mgr_locs = self.mgr_locs.delete(loc) def apply(self, func, **kwargs): """ apply the function to my values; return a block if we are not one """ with np.errstate(all='ignore'): result = func(self.values, **kwargs) if not isinstance(result, Block): result = self.make_block(values=_block_shape(result, ndim=self.ndim)) return result def fillna(self, value, limit=None, inplace=False, downcast=None): """ fillna on the block with the value. If we fail, then convert to ObjectBlock and try again """ inplace = validate_bool_kwarg(inplace, 'inplace') if not self._can_hold_na: if inplace: return self else: return self.copy() mask = isna(self.values) if limit is not None: if not is_integer(limit): raise ValueError('Limit must be an integer') if limit < 1: raise ValueError('Limit must be greater than 0') if self.ndim > 2: raise NotImplementedError("number of dimensions for 'fillna' " "is currently limited to 2") mask[mask.cumsum(self.ndim - 1) > limit] = False # fillna, but if we cannot coerce, then try again as an ObjectBlock try: values, _ = self._try_coerce_args(self.values, value) blocks = self.putmask(mask, value, inplace=inplace) blocks = [b.make_block(values=self._try_coerce_result(b.values)) for b in blocks] return self._maybe_downcast(blocks, downcast) except (TypeError, ValueError): # we can't process the value, but nothing to do if not mask.any(): return self if inplace else self.copy() # operate column-by-column def f(m, v, i): block = self.coerce_to_target_dtype(value) # slice out our block if i is not None: block = block.getitem_block(slice(i, i + 1)) return block.fillna(value, limit=limit, inplace=inplace, downcast=None) return self.split_and_operate(mask, f, inplace) def split_and_operate(self, mask, f, inplace): """ split the block per-column, and apply the callable f per-column, return a new block for each. Handle masking which will not change a block unless needed. Parameters ---------- mask : 2-d boolean mask f : callable accepting (1d-mask, 1d values, indexer) inplace : boolean Returns ------- list of blocks """ if mask is None: mask = np.ones(self.shape, dtype=bool) new_values = self.values def make_a_block(nv, ref_loc): if isinstance(nv, Block): block = nv elif isinstance(nv, list): block = nv[0] else: # Put back the dimension that was taken from it and make # a block out of the result. try: nv = _block_shape(nv, ndim=self.ndim) except (AttributeError, NotImplementedError): pass block = self.make_block(values=nv, placement=ref_loc) return block # ndim == 1 if self.ndim == 1: if mask.any(): nv = f(mask, new_values, None) else: nv = new_values if inplace else new_values.copy() block = make_a_block(nv, self.mgr_locs) return [block] # ndim > 1 new_blocks = [] for i, ref_loc in enumerate(self.mgr_locs): m = mask[i] v = new_values[i] # need a new block if m.any(): nv = f(m, v, i) else: nv = v if inplace else v.copy() block = make_a_block(nv, [ref_loc]) new_blocks.append(block) return new_blocks def _maybe_downcast(self, blocks, downcast=None): # no need to downcast our float # unless indicated if downcast is None and self.is_float: return blocks elif downcast is None and (self.is_timedelta or self.is_datetime): return blocks if not isinstance(blocks, list): blocks = [blocks] return _extend_blocks([b.downcast(downcast) for b in blocks]) def downcast(self, dtypes=None): """ try to downcast each item to the dict of dtypes if present """ # turn it off completely if dtypes is False: return self values = self.values # single block handling if self._is_single_block: # try to cast all non-floats here if dtypes is None: dtypes = 'infer' nv = maybe_downcast_to_dtype(values, dtypes) return self.make_block(nv) # ndim > 1 if dtypes is None: return self if not (dtypes == 'infer' or isinstance(dtypes, dict)): raise ValueError("downcast must have a dictionary or 'infer' as " "its argument") # operate column-by-column # this is expensive as it splits the blocks items-by-item def f(m, v, i): if dtypes == 'infer': dtype = 'infer' else: raise AssertionError("dtypes as dict is not supported yet") if dtype is not None: v = maybe_downcast_to_dtype(v, dtype) return v return self.split_and_operate(None, f, False) def astype(self, dtype, copy=False, errors='raise', values=None, **kwargs): return self._astype(dtype, copy=copy, errors=errors, values=values, **kwargs) def _astype(self, dtype, copy=False, errors='raise', values=None, **kwargs): """Coerce to the new type Parameters ---------- dtype : str, dtype convertible copy : boolean, default False copy if indicated errors : str, {'raise', 'ignore'}, default 'ignore' - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object Returns ------- Block """ errors_legal_values = ('raise', 'ignore') if errors not in errors_legal_values: invalid_arg = ("Expected value of kwarg 'errors' to be one of {}. " "Supplied value is '{}'".format( list(errors_legal_values), errors)) raise ValueError(invalid_arg) if (inspect.isclass(dtype) and issubclass(dtype, (PandasExtensionDtype, ExtensionDtype))): msg = ("Expected an instance of {}, but got the class instead. " "Try instantiating 'dtype'.".format(dtype.__name__)) raise TypeError(msg) # may need to convert to categorical if self.is_categorical_astype(dtype): # deprecated 17636 if ('categories' in kwargs or 'ordered' in kwargs): if isinstance(dtype, CategoricalDtype): raise TypeError( "Cannot specify a CategoricalDtype and also " "`categories` or `ordered`. Use " "`dtype=CategoricalDtype(categories, ordered)`" " instead.") warnings.warn("specifying 'categories' or 'ordered' in " ".astype() is deprecated; pass a " "CategoricalDtype instead", FutureWarning, stacklevel=7) categories = kwargs.get('categories', None) ordered = kwargs.get('ordered', None) if com._any_not_none(categories, ordered): dtype = CategoricalDtype(categories, ordered) if is_categorical_dtype(self.values): # GH 10696/18593: update an existing categorical efficiently return self.make_block(self.values.astype(dtype, copy=copy)) return self.make_block(Categorical(self.values, dtype=dtype)) # convert dtypes if needed dtype = pandas_dtype(dtype) # astype processing if is_dtype_equal(self.dtype, dtype): if copy: return self.copy() return self klass = None if is_sparse(self.values): # special case sparse, Series[Sparse].astype(object) is sparse klass = ExtensionBlock elif is_object_dtype(dtype): klass = ObjectBlock elif is_extension_array_dtype(dtype): klass = ExtensionBlock try: # force the copy here if values is None: if self.is_extension: values = self.values.astype(dtype) else: if issubclass(dtype.type, (compat.text_type, compat.string_types)): # use native type formatting for datetime/tz/timedelta if self.is_datelike: values = self.to_native_types() # astype formatting else: values = self.get_values() else: values = self.get_values(dtype=dtype) # _astype_nansafe works fine with 1-d only values = astype_nansafe(values.ravel(), dtype, copy=True) # TODO(extension) # should we make this attribute? try: values = values.reshape(self.shape) except AttributeError: pass newb = make_block(values, placement=self.mgr_locs, klass=klass, ndim=self.ndim) except Exception: # noqa: E722 if errors == 'raise': raise newb = self.copy() if copy else self if newb.is_numeric and self.is_numeric: if newb.shape != self.shape: raise TypeError( "cannot set astype for copy = [{copy}] for dtype " "({dtype} [{shape}]) to different shape " "({newb_dtype} [{newb_shape}])".format( copy=copy, dtype=self.dtype.name, shape=self.shape, newb_dtype=newb.dtype.name, newb_shape=newb.shape)) return newb def convert(self, copy=True, **kwargs): """ attempt to coerce any object types to better types return a copy of the block (if copy = True) by definition we are not an ObjectBlock here! """ return self.copy() if copy else self def _can_hold_element(self, element): """ require the same dtype as ourselves """ dtype = self.values.dtype.type tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, dtype) return isinstance(element, dtype) def _try_cast_result(self, result, dtype=None): """ try to cast the result to our original type, we may have roundtripped thru object in the mean-time """ if dtype is None: dtype = self.dtype if self.is_integer or self.is_bool or self.is_datetime: pass elif self.is_float and result.dtype == self.dtype: # protect against a bool/object showing up here if isinstance(dtype, compat.string_types) and dtype == 'infer': return result if not isinstance(dtype, type): dtype = dtype.type if issubclass(dtype, (np.bool_, np.object_)): if issubclass(dtype, np.bool_): if isna(result).all(): return result.astype(np.bool_) else: result = result.astype(np.object_) result[result == 1] = True result[result == 0] = False return result else: return result.astype(np.object_) return result # may need to change the dtype here return maybe_downcast_to_dtype(result, dtype) def _try_coerce_args(self, values, other): """ provide coercion to our input arguments """ if np.any(notna(other)) and not self._can_hold_element(other): # coercion issues # let higher levels handle raise TypeError("cannot convert {} to an {}".format( type(other).__name__, type(self).__name__.lower().replace('Block', ''))) return values, other def _try_coerce_result(self, result): """ reverse of try_coerce_args """ return result def _try_coerce_and_cast_result(self, result, dtype=None): result = self._try_coerce_result(result) result = self._try_cast_result(result, dtype=dtype) return result def to_native_types(self, slicer=None, na_rep='nan', quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.get_values() if slicer is not None: values = values[:, slicer] mask = isna(values) if not self.is_object and not quoting: values = values.astype(str) else: values = np.array(values, dtype='object') values[mask] = na_rep return values # block actions #### def copy(self, deep=True): """ copy constructor """ values = self.values if deep: values = values.copy() return self.make_block_same_class(values) def replace(self, to_replace, value, inplace=False, filter=None, regex=False, convert=True): """replace the to_replace value with value, possible to create new blocks here this is just a call to putmask. regex is not used here. It is used in ObjectBlocks. It is here for API compatibility. """ inplace = validate_bool_kwarg(inplace, 'inplace') original_to_replace = to_replace # try to replace, if we raise an error, convert to ObjectBlock and # retry try: values, to_replace = self._try_coerce_args(self.values, to_replace) mask = missing.mask_missing(values, to_replace) if filter is not None: filtered_out = ~self.mgr_locs.isin(filter) mask[filtered_out.nonzero()[0]] = False blocks = self.putmask(mask, value, inplace=inplace) if convert: blocks = [b.convert(by_item=True, numeric=False, copy=not inplace) for b in blocks] return blocks except (TypeError, ValueError): # GH 22083, TypeError or ValueError occurred within error handling # causes infinite loop. Cast and retry only if not objectblock. if is_object_dtype(self): raise # try again with a compatible block block = self.astype(object) return block.replace(to_replace=original_to_replace, value=value, inplace=inplace, filter=filter, regex=regex, convert=convert) def _replace_single(self, *args, **kwargs): """ no-op on a non-ObjectBlock """ return self if kwargs['inplace'] else self.copy() def setitem(self, indexer, value): """Set the value inplace, returning a a maybe different typed block. Parameters ---------- indexer : tuple, list-like, array-like, slice The subset of self.values to set value : object The value being set Returns ------- Block Notes ----- `indexer` is a direct slice/positional indexer. `value` must be a compatible shape. """ # coerce None values, if appropriate if value is None: if self.is_numeric: value = np.nan # coerce if block dtype can store value values = self.values try: values, value = self._try_coerce_args(values, value) # can keep its own dtype if hasattr(value, 'dtype') and is_dtype_equal(values.dtype, value.dtype): dtype = self.dtype else: dtype = 'infer' except (TypeError, ValueError): # current dtype cannot store value, coerce to common dtype find_dtype = False if hasattr(value, 'dtype'): dtype = value.dtype find_dtype = True elif lib.is_scalar(value): if isna(value): # NaN promotion is handled in latter path dtype = False else: dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True) find_dtype = True else: dtype = 'infer' if find_dtype: dtype = find_common_type([values.dtype, dtype]) if not is_dtype_equal(self.dtype, dtype): b = self.astype(dtype) return b.setitem(indexer, value) # value must be storeable at this moment arr_value = np.array(value) # cast the values to a type that can hold nan (if necessary) if not self._can_hold_element(value): dtype, _ = maybe_promote(arr_value.dtype) values = values.astype(dtype) transf = (lambda x: x.T) if self.ndim == 2 else (lambda x: x) values = transf(values) # length checking check_setitem_lengths(indexer, value, values) def _is_scalar_indexer(indexer): # return True if we are all scalar indexers if arr_value.ndim == 1: if not isinstance(indexer, tuple): indexer = tuple([indexer]) return any(isinstance(idx, np.ndarray) and len(idx) == 0 for idx in indexer) return False def _is_empty_indexer(indexer): # return a boolean if we have an empty indexer if is_list_like(indexer) and not len(indexer): return True if arr_value.ndim == 1: if not isinstance(indexer, tuple): indexer = tuple([indexer]) return any(isinstance(idx, np.ndarray) and len(idx) == 0 for idx in indexer) return False # empty indexers # 8669 (empty) if _is_empty_indexer(indexer): pass # setting a single element for each dim and with a rhs that could # be say a list # GH 6043 elif _is_scalar_indexer(indexer): values[indexer] = value # if we are an exact match (ex-broadcasting), # then use the resultant dtype elif (len(arr_value.shape) and arr_value.shape[0] == values.shape[0] and np.prod(arr_value.shape) == np.prod(values.shape)): values[indexer] = value try: values = values.astype(arr_value.dtype) except ValueError: pass # set else: values[indexer] = value # coerce and try to infer the dtypes of the result values = self._try_coerce_and_cast_result(values, dtype) block = self.make_block(transf(values)) return block def putmask(self, mask, new, align=True, inplace=False, axis=0, transpose=False): """ putmask the data to the block; it is possible that we may create a new dtype of block return the resulting block(s) Parameters ---------- mask : the condition to respect new : a ndarray/object align : boolean, perform alignment on other/cond, default is True inplace : perform inplace modification, default is False axis : int transpose : boolean Set to True if self is stored with axes reversed Returns ------- a list of new blocks, the result of the putmask """ new_values = self.values if inplace else self.values.copy() new = getattr(new, 'values', new) mask = getattr(mask, 'values', mask) # if we are passed a scalar None, convert it here if not is_list_like(new) and isna(new) and not self.is_object: new = self.fill_value if self._can_hold_element(new): _, new = self._try_coerce_args(new_values, new) if transpose: new_values = new_values.T # If the default repeat behavior in np.putmask would go in the # wrong direction, then explicitly repeat and reshape new instead if getattr(new, 'ndim', 0) >= 1: if self.ndim - 1 == new.ndim and axis == 1: new = np.repeat( new, new_values.shape[-1]).reshape(self.shape) new = new.astype(new_values.dtype) # we require exact matches between the len of the # values we are setting (or is compat). np.putmask # doesn't check this and will simply truncate / pad # the output, but we want sane error messages # # TODO: this prob needs some better checking # for 2D cases if ((is_list_like(new) and np.any(mask[mask]) and getattr(new, 'ndim', 1) == 1)): if not (mask.shape[-1] == len(new) or mask[mask].shape[-1] == len(new) or len(new) == 1): raise ValueError("cannot assign mismatch " "length to masked array") np.putmask(new_values, mask, new) # maybe upcast me elif mask.any(): if transpose: mask = mask.T if isinstance(new, np.ndarray): new = new.T axis = new_values.ndim - axis - 1 # Pseudo-broadcast if getattr(new, 'ndim', 0) >= 1: if self.ndim - 1 == new.ndim: new_shape = list(new.shape) new_shape.insert(axis, 1) new = new.reshape(tuple(new_shape)) # operate column-by-column def f(m, v, i): if i is None: # ndim==1 case. n = new else: if isinstance(new, np.ndarray): n = np.squeeze(new[i % new.shape[0]]) else: n = np.array(new) # type of the new block dtype, _ = maybe_promote(n.dtype) # we need to explicitly astype here to make a copy n = n.astype(dtype) nv = _putmask_smart(v, m, n) return nv new_blocks = self.split_and_operate(mask, f, inplace) return new_blocks if inplace: return [self] if transpose: new_values = new_values.T return [self.make_block(new_values)] def coerce_to_target_dtype(self, other): """ coerce the current block to a dtype compat for other we will return a block, possibly object, and not raise we can also safely try to coerce to the same dtype and will receive the same block """ # if we cannot then coerce to object dtype, _ = infer_dtype_from(other, pandas_dtype=True) if is_dtype_equal(self.dtype, dtype): return self if self.is_bool or is_object_dtype(dtype) or is_bool_dtype(dtype): # we don't upcast to bool return self.astype(object) elif ((self.is_float or self.is_complex) and (is_integer_dtype(dtype) or is_float_dtype(dtype))): # don't coerce float/complex to int return self elif (self.is_datetime or is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype)): # not a datetime if not ((is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype)) and self.is_datetime): return self.astype(object) # don't upcast timezone with different timezone or no timezone mytz = getattr(self.dtype, 'tz', None) othertz = getattr(dtype, 'tz', None) if str(mytz) != str(othertz): return self.astype(object) raise AssertionError("possible recursion in " "coerce_to_target_dtype: {} {}".format( self, other)) elif (self.is_timedelta or is_timedelta64_dtype(dtype)): # not a timedelta if not (is_timedelta64_dtype(dtype) and self.is_timedelta): return self.astype(object) raise AssertionError("possible recursion in " "coerce_to_target_dtype: {} {}".format( self, other)) try: return self.astype(dtype) except (ValueError, TypeError): pass return self.astype(object) def interpolate(self, method='pad', axis=0, index=None, values=None, inplace=False, limit=None, limit_direction='forward', limit_area=None, fill_value=None, coerce=False, downcast=None, **kwargs): inplace = validate_bool_kwarg(inplace, 'inplace') def check_int_bool(self, inplace): # Only FloatBlocks will contain NaNs. # timedelta subclasses IntBlock if (self.is_bool or self.is_integer) and not self.is_timedelta: if inplace: return self else: return self.copy() # a fill na type method try: m = missing.clean_fill_method(method) except ValueError: m = None if m is not None: r = check_int_bool(self, inplace) if r is not None: return r return self._interpolate_with_fill(method=m, axis=axis, inplace=inplace, limit=limit, fill_value=fill_value, coerce=coerce, downcast=downcast) # try an interp method try: m = missing.clean_interp_method(method, **kwargs) except ValueError: m = None if m is not None: r = check_int_bool(self, inplace) if r is not None: return r return self._interpolate(method=m, index=index, values=values, axis=axis, limit=limit, limit_direction=limit_direction, limit_area=limit_area, fill_value=fill_value, inplace=inplace, downcast=downcast, **kwargs) raise ValueError("invalid method '{0}' to interpolate.".format(method)) def _interpolate_with_fill(self, method='pad', axis=0, inplace=False, limit=None, fill_value=None, coerce=False, downcast=None): """ fillna but using the interpolate machinery """ inplace = validate_bool_kwarg(inplace, 'inplace') # if we are coercing, then don't force the conversion # if the block can't hold the type if coerce: if not self._can_hold_na: if inplace: return [self] else: return [self.copy()] values = self.values if inplace else self.values.copy() values, fill_value = self._try_coerce_args(values, fill_value) values = missing.interpolate_2d(values, method=method, axis=axis, limit=limit, fill_value=fill_value, dtype=self.dtype) values = self._try_coerce_result(values) blocks = [self.make_block_same_class(values, ndim=self.ndim)] return self._maybe_downcast(blocks, downcast) def _interpolate(self, method=None, index=None, values=None, fill_value=None, axis=0, limit=None, limit_direction='forward', limit_area=None, inplace=False, downcast=None, **kwargs): """ interpolate using scipy wrappers """ inplace = validate_bool_kwarg(inplace, 'inplace') data = self.values if inplace else self.values.copy() # only deal with floats if not self.is_float: if not self.is_integer: return self data = data.astype(np.float64) if fill_value is None: fill_value = self.fill_value if method in ('krogh', 'piecewise_polynomial', 'pchip'): if not index.is_monotonic: raise ValueError("{0} interpolation requires that the " "index be monotonic.".format(method)) # process 1-d slices in the axis direction def func(x): # process a 1-d slice, returning it # should the axis argument be handled below in apply_along_axis? # i.e. not an arg to missing.interpolate_1d return missing.interpolate_1d(index, x, method=method, limit=limit, limit_direction=limit_direction, limit_area=limit_area, fill_value=fill_value, bounds_error=False, **kwargs) # interp each column independently interp_values = np.apply_along_axis(func, axis, data) blocks = [self.make_block_same_class(interp_values)] return self._maybe_downcast(blocks, downcast) def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None): """ Take values according to indexer and return them as a block.bb """ # algos.take_nd dispatches for DatetimeTZBlock, CategoricalBlock # so need to preserve types # sparse is treated like an ndarray, but needs .get_values() shaping values = self.values if self.is_sparse: values = self.get_values() if fill_tuple is None: fill_value = self.fill_value new_values = algos.take_nd(values, indexer, axis=axis, allow_fill=False, fill_value=fill_value) else: fill_value = fill_tuple[0] new_values = algos.take_nd(values, indexer, axis=axis, allow_fill=True, fill_value=fill_value) if new_mgr_locs is None: if axis == 0: slc = libinternals.indexer_as_slice(indexer) if slc is not None: new_mgr_locs = self.mgr_locs[slc] else: new_mgr_locs = self.mgr_locs[indexer] else: new_mgr_locs = self.mgr_locs if not is_dtype_equal(new_values.dtype, self.dtype): return self.make_block(new_values, new_mgr_locs) else: return self.make_block_same_class(new_values, new_mgr_locs) def diff(self, n, axis=1): """ return block for the diff of the values """ new_values = algos.diff(self.values, n, axis=axis) return [self.make_block(values=new_values)] def shift(self, periods, axis=0, fill_value=None): """ shift the block by periods, possibly upcast """ # convert integer to float if necessary. need to do a lot more than # that, handle boolean etc also new_values, fill_value = maybe_upcast(self.values, fill_value) # make sure array sent to np.roll is c_contiguous f_ordered = new_values.flags.f_contiguous if f_ordered: new_values = new_values.T axis = new_values.ndim - axis - 1 if np.prod(new_values.shape): new_values = np.roll(new_values, ensure_platform_int(periods), axis=axis) axis_indexer = [slice(None)] * self.ndim if periods > 0: axis_indexer[axis] = slice(None, periods) else: axis_indexer[axis] = slice(periods, None) new_values[tuple(axis_indexer)] = fill_value # restore original order if f_ordered: new_values = new_values.T return [self.make_block(new_values)] def where(self, other, cond, align=True, errors='raise', try_cast=False, axis=0, transpose=False): """ evaluate the block; return result block(s) from the result Parameters ---------- other : a ndarray/object cond : the condition to respect align : boolean, perform alignment on other/cond errors : str, {'raise', 'ignore'}, default 'raise' - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object axis : int transpose : boolean Set to True if self is stored with axes reversed Returns ------- a new block(s), the result of the func """ import pandas.core.computation.expressions as expressions assert errors in ['raise', 'ignore'] values = self.values orig_other = other if transpose: values = values.T other = getattr(other, '_values', getattr(other, 'values', other)) cond = getattr(cond, 'values', cond) # If the default broadcasting would go in the wrong direction, then # explicitly reshape other instead if getattr(other, 'ndim', 0) >= 1: if values.ndim - 1 == other.ndim and axis == 1: other = other.reshape(tuple(other.shape + (1, ))) elif transpose and values.ndim == self.ndim - 1: cond = cond.T if not hasattr(cond, 'shape'): raise ValueError("where must have a condition that is ndarray " "like") # our where function def func(cond, values, other): if cond.ravel().all(): return values values, other = self._try_coerce_args(values, other) try: return self._try_coerce_result(expressions.where( cond, values, other)) except Exception as detail: if errors == 'raise': raise TypeError( 'Could not operate [{other!r}] with block values ' '[{detail!s}]'.format(other=other, detail=detail)) else: # return the values result = np.empty(values.shape, dtype='float64') result.fill(np.nan) return result # see if we can operate on the entire block, or need item-by-item # or if we are a single block (ndim == 1) try: result = func(cond, values, other) except TypeError: # we cannot coerce, return a compat dtype # we are explicitly ignoring errors block = self.coerce_to_target_dtype(other) blocks = block.where(orig_other, cond, align=align, errors=errors, try_cast=try_cast, axis=axis, transpose=transpose) return self._maybe_downcast(blocks, 'infer') if self._can_hold_na or self.ndim == 1: if transpose: result = result.T # try to cast if requested if try_cast: result = self._try_cast_result(result) return self.make_block(result) # might need to separate out blocks axis = cond.ndim - 1 cond = cond.swapaxes(axis, 0) mask = np.array([cond[i].all() for i in range(cond.shape[0])], dtype=bool) result_blocks = [] for m in [mask, ~mask]: if m.any(): r = self._try_cast_result(result.take(m.nonzero()[0], axis=axis)) result_blocks.append( self.make_block(r.T, placement=self.mgr_locs[m])) return result_blocks def equals(self, other): if self.dtype != other.dtype or self.shape != other.shape: return False return array_equivalent(self.values, other.values) def _unstack(self, unstacker_func, new_columns, n_rows, fill_value): """Return a list of unstacked blocks of self Parameters ---------- unstacker_func : callable Partially applied unstacker. new_columns : Index All columns of the unstacked BlockManager. n_rows : int Only used in ExtensionBlock.unstack fill_value : int Only used in ExtensionBlock.unstack Returns ------- blocks : list of Block New blocks of unstacked values. mask : array_like of bool The mask of columns of `blocks` we should keep. """ unstacker = unstacker_func(self.values.T) new_items = unstacker.get_new_columns() new_placement = new_columns.get_indexer(new_items) new_values, mask = unstacker.get_new_values() mask = mask.any(0) new_values = new_values.T[mask] new_placement = new_placement[mask] blocks = [make_block(new_values, placement=new_placement)] return blocks, mask def quantile(self, qs, interpolation='linear', axis=0): """ compute the quantiles of the Parameters ---------- qs: a scalar or list of the quantiles to be computed interpolation: type of interpolation, default 'linear' axis: axis to compute, default 0 Returns ------- Block """ if self.is_datetimetz: # TODO: cleanup this special case. # We need to operate on i8 values for datetimetz # but `Block.get_values()` returns an ndarray of objects # right now. We need an API for "values to do numeric-like ops on" values = self.values.asi8 # TODO: NonConsolidatableMixin shape # Usual shape inconsistencies for ExtensionBlocks if self.ndim > 1: values = values[None, :] else: values = self.get_values() values, _ = self._try_coerce_args(values, values) is_empty = values.shape[axis] == 0 orig_scalar = not is_list_like(qs) if orig_scalar: # make list-like, unpack later qs = [qs] if is_empty: if self.ndim == 1: result = self._na_value else: # create the array of na_values # 2d len(values) * len(qs) result = np.repeat(np.array([self.fill_value] * len(qs)), len(values)).reshape(len(values), len(qs)) else: # asarray needed for Sparse, see GH#24600 # TODO: Why self.values and not values? mask = np.asarray(isna(self.values)) result = nanpercentile(values, np.array(qs) * 100, axis=axis, na_value=self.fill_value, mask=mask, ndim=self.ndim, interpolation=interpolation) result = np.array(result, copy=False) if self.ndim > 1: result = result.T if orig_scalar and not lib.is_scalar(result): # result could be scalar in case with is_empty and self.ndim == 1 assert result.shape[-1] == 1, result.shape result = result[..., 0] result = lib.item_from_zerodim(result) ndim = getattr(result, 'ndim', None) or 0 result = self._try_coerce_result(result) return make_block(result, placement=np.arange(len(result)), ndim=ndim) def _replace_coerce(self, to_replace, value, inplace=True, regex=False, convert=False, mask=None): """ Replace value corresponding to the given boolean array with another value. Parameters ---------- to_replace : object or pattern Scalar to replace or regular expression to match. value : object Replacement object. inplace : bool, default False Perform inplace modification. regex : bool, default False If true, perform regular expression substitution. convert : bool, default True If true, try to coerce any object types to better types. mask : array-like of bool, optional True indicate corresponding element is ignored. Returns ------- A new block if there is anything to replace or the original block. """ if mask.any(): if not regex: self = self.coerce_to_target_dtype(value) return self.putmask(mask, value, inplace=inplace) else: return self._replace_single(to_replace, value, inplace=inplace, regex=regex, convert=convert, mask=mask) return self class NonConsolidatableMixIn(object): """ hold methods for the nonconsolidatable blocks """ _can_consolidate = False _verify_integrity = False _validate_ndim = False def __init__(self, values, placement, ndim=None): """Initialize a non-consolidatable block. 'ndim' may be inferred from 'placement'. This will call continue to call __init__ for the other base classes mixed in with this Mixin. """ # Placement must be converted to BlockPlacement so that we can check # its length if not isinstance(placement, libinternals.BlockPlacement): placement = libinternals.BlockPlacement(placement) # Maybe infer ndim from placement if ndim is None: if len(placement) != 1: ndim = 1 else: ndim = 2 super(NonConsolidatableMixIn, self).__init__(values, placement, ndim=ndim) @property def shape(self): if self.ndim == 1: return (len(self.values)), return (len(self.mgr_locs), len(self.values)) def iget(self, col): if self.ndim == 2 and isinstance(col, tuple): col, loc = col if not com.is_null_slice(col) and col != 0: raise IndexError("{0} only contains one item".format(self)) return self.values[loc] else: if col != 0: raise IndexError("{0} only contains one item".format(self)) return self.values def should_store(self, value): return isinstance(value, self._holder) def set(self, locs, values, check=False): assert locs.tolist() == [0] self.values = values def putmask(self, mask, new, align=True, inplace=False, axis=0, transpose=False): """ putmask the data to the block; we must be a single block and not generate other blocks return the resulting block Parameters ---------- mask : the condition to respect new : a ndarray/object align : boolean, perform alignment on other/cond, default is True inplace : perform inplace modification, default is False Returns ------- a new block, the result of the putmask """ inplace = validate_bool_kwarg(inplace, 'inplace') # use block's copy logic. # .values may be an Index which does shallow copy by default new_values = self.values if inplace else self.copy().values new_values, new = self._try_coerce_args(new_values, new) if isinstance(new, np.ndarray) and len(new) == len(mask): new = new[mask] mask = _safe_reshape(mask, new_values.shape) new_values[mask] = new new_values = self._try_coerce_result(new_values) return [self.make_block(values=new_values)] def _try_cast_result(self, result, dtype=None): return result def _get_unstack_items(self, unstacker, new_columns): """ Get the placement, values, and mask for a Block unstack. This is shared between ObjectBlock and ExtensionBlock. They differ in that ObjectBlock passes the values, while ExtensionBlock passes the dummy ndarray of positions to be used by a take later. Parameters ---------- unstacker : pandas.core.reshape.reshape._Unstacker new_columns : Index All columns of the unstacked BlockManager. Returns ------- new_placement : ndarray[int] The placement of the new columns in `new_columns`. new_values : Union[ndarray, ExtensionArray] The first return value from _Unstacker.get_new_values. mask : ndarray[bool] The second return value from _Unstacker.get_new_values. """ # shared with ExtensionBlock new_items = unstacker.get_new_columns() new_placement = new_columns.get_indexer(new_items) new_values, mask = unstacker.get_new_values() mask = mask.any(0) return new_placement, new_values, mask class ExtensionBlock(NonConsolidatableMixIn, Block): """Block for holding extension types. Notes ----- This holds all 3rd-party extension array types. It's also the immediate parent class for our internal extension types' blocks, CategoricalBlock. ExtensionArrays are limited to 1-D. """ is_extension = True def __init__(self, values, placement, ndim=None): values = self._maybe_coerce_values(values) super(ExtensionBlock, self).__init__(values, placement, ndim) def _maybe_coerce_values(self, values): """Unbox to an extension array. This will unbox an ExtensionArray stored in an Index or Series. ExtensionArrays pass through. No dtype coercion is done. Parameters ---------- values : Index, Series, ExtensionArray Returns ------- ExtensionArray """ if isinstance(values, (ABCIndexClass, ABCSeries)): values = values._values return values @property def _holder(self): # For extension blocks, the holder is values-dependent. return type(self.values) @property def fill_value(self): # Used in reindex_indexer return self.values.dtype.na_value @property def _can_hold_na(self): # The default ExtensionArray._can_hold_na is True return self._holder._can_hold_na @property def is_view(self): """Extension arrays are never treated as views.""" return False @property def is_numeric(self): return self.values.dtype._is_numeric def setitem(self, indexer, value): """Set the value inplace, returning a same-typed block. This differs from Block.setitem by not allowing setitem to change the dtype of the Block. Parameters ---------- indexer : tuple, list-like, array-like, slice The subset of self.values to set value : object The value being set Returns ------- Block Notes ----- `indexer` is a direct slice/positional indexer. `value` must be a compatible shape. """ if isinstance(indexer, tuple): # we are always 1-D indexer = indexer[0] check_setitem_lengths(indexer, value, self.values) self.values[indexer] = value return self def get_values(self, dtype=None): # ExtensionArrays must be iterable, so this works. values = np.asarray(self.values) if values.ndim == self.ndim - 1: values = values.reshape((1,) + values.shape) return values def to_dense(self): return np.asarray(self.values) def take_nd(self, indexer, axis=0, new_mgr_locs=None, fill_tuple=None): """ Take values according to indexer and return them as a block. """ if fill_tuple is None: fill_value = None else: fill_value = fill_tuple[0] # axis doesn't matter; we are really a single-dim object # but are passed the axis depending on the calling routing # if its REALLY axis 0, then this will be a reindex and not a take new_values = self.values.take(indexer, fill_value=fill_value, allow_fill=True) if self.ndim == 1 and new_mgr_locs is None: new_mgr_locs = [0] else: if new_mgr_locs is None: new_mgr_locs = self.mgr_locs return self.make_block_same_class(new_values, new_mgr_locs) def _can_hold_element(self, element): # XXX: We may need to think about pushing this onto the array. # We're doing the same as CategoricalBlock here. return True def _slice(self, slicer): """ return a slice of my values """ # slice the category # return same dims as we currently have if isinstance(slicer, tuple) and len(slicer) == 2: if not com.is_null_slice(slicer[0]): raise AssertionError("invalid slicing for a 1-ndim " "categorical") slicer = slicer[1] return self.values[slicer] def formatting_values(self): # Deprecating the ability to override _formatting_values. # Do the warning here, it's only user in pandas, since we # have to check if the subclass overrode it. fv = getattr(type(self.values), '_formatting_values', None) if fv and fv != ExtensionArray._formatting_values: msg = ( "'ExtensionArray._formatting_values' is deprecated. " "Specify 'ExtensionArray._formatter' instead." ) warnings.warn(msg, DeprecationWarning, stacklevel=10) return self.values._formatting_values() return self.values def concat_same_type(self, to_concat, placement=None): """ Concatenate list of single blocks of the same type. """ values = self._holder._concat_same_type( [blk.values for blk in to_concat]) placement = placement or slice(0, len(values), 1) return self.make_block_same_class(values, ndim=self.ndim, placement=placement) def fillna(self, value, limit=None, inplace=False, downcast=None): values = self.values if inplace else self.values.copy() values = values.fillna(value=value, limit=limit) return [self.make_block_same_class(values=values, placement=self.mgr_locs, ndim=self.ndim)] def interpolate(self, method='pad', axis=0, inplace=False, limit=None, fill_value=None, **kwargs): values = self.values if inplace else self.values.copy() return self.make_block_same_class( values=values.fillna(value=fill_value, method=method, limit=limit), placement=self.mgr_locs) def shift(self, periods, axis=0, fill_value=None): """ Shift the block by `periods`. Dispatches to underlying ExtensionArray and re-boxes in an ExtensionBlock. """ # type: (int, Optional[BlockPlacement]) -> List[ExtensionBlock] return [ self.make_block_same_class( self.values.shift(periods=periods, fill_value=fill_value), placement=self.mgr_locs, ndim=self.ndim) ] def where(self, other, cond, align=True, errors='raise', try_cast=False, axis=0, transpose=False): if isinstance(other, ABCDataFrame): # ExtensionArrays are 1-D, so if we get here then # `other` should be a DataFrame with a single column. assert other.shape[1] == 1 other = other.iloc[:, 0] other = extract_array(other, extract_numpy=True) if isinstance(cond, ABCDataFrame): assert cond.shape[1] == 1 cond = cond.iloc[:, 0] cond = extract_array(cond, extract_numpy=True) if lib.is_scalar(other) and isna(other): # The default `other` for Series / Frame is np.nan # we want to replace that with the correct NA value # for the type other = self.dtype.na_value if is_sparse(self.values): # TODO(SparseArray.__setitem__): remove this if condition # We need to re-infer the type of the data after doing the # where, for cases where the subtypes don't match dtype = None else: dtype = self.dtype try: result = self.values.copy() icond = ~cond if lib.is_scalar(other): result[icond] = other else: result[icond] = other[icond] except (NotImplementedError, TypeError): # NotImplementedError for class not implementing `__setitem__` # TypeError for SparseArray, which implements just to raise # a TypeError result = self._holder._from_sequence( np.where(cond, self.values, other), dtype=dtype, ) return self.make_block_same_class(result, placement=self.mgr_locs) @property def _ftype(self): return getattr(self.values, '_pandas_ftype', Block._ftype) def _unstack(self, unstacker_func, new_columns, n_rows, fill_value): # ExtensionArray-safe unstack. # We override ObjectBlock._unstack, which unstacks directly on the # values of the array. For EA-backed blocks, this would require # converting to a 2-D ndarray of objects. # Instead, we unstack an ndarray of integer positions, followed by # a `take` on the actual values. dummy_arr = np.arange(n_rows) dummy_unstacker = functools.partial(unstacker_func, fill_value=-1) unstacker = dummy_unstacker(dummy_arr) new_placement, new_values, mask = self._get_unstack_items( unstacker, new_columns ) blocks = [ self.make_block_same_class( self.values.take(indices, allow_fill=True, fill_value=fill_value), [place]) for indices, place in zip(new_values.T, new_placement) ] return blocks, mask class ObjectValuesExtensionBlock(ExtensionBlock): """ Block providing backwards-compatibility for `.values`. Used by PeriodArray and IntervalArray to ensure that Series[T].values is an ndarray of objects. """ def external_values(self, dtype=None): return self.values.astype(object) class NumericBlock(Block): __slots__ = () is_numeric = True _can_hold_na = True class FloatOrComplexBlock(NumericBlock): __slots__ = () def equals(self, other): if self.dtype != other.dtype or self.shape != other.shape: return False left, right = self.values, other.values return ((left == right) | (np.isnan(left) & np.isnan(right))).all() class FloatBlock(FloatOrComplexBlock): __slots__ = () is_float = True def _can_hold_element(self, element): tipo = maybe_infer_dtype_type(element) if tipo is not None: return (issubclass(tipo.type, (np.floating, np.integer)) and not issubclass(tipo.type, (np.datetime64, np.timedelta64))) return ( isinstance( element, (float, int, np.floating, np.int_, compat.long)) and not isinstance(element, (bool, np.bool_, datetime, timedelta, np.datetime64, np.timedelta64))) def to_native_types(self, slicer=None, na_rep='', float_format=None, decimal='.', quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values if slicer is not None: values = values[:, slicer] # see gh-13418: no special formatting is desired at the # output (important for appropriate 'quoting' behaviour), # so do not pass it through the FloatArrayFormatter if float_format is None and decimal == '.': mask = isna(values) if not quoting: values = values.astype(str) else: values = np.array(values, dtype='object') values[mask] = na_rep return values from pandas.io.formats.format import FloatArrayFormatter formatter = FloatArrayFormatter(values, na_rep=na_rep, float_format=float_format, decimal=decimal, quoting=quoting, fixed_width=False) return formatter.get_result_as_array() def should_store(self, value): # when inserting a column should not coerce integers to floats # unnecessarily return (issubclass(value.dtype.type, np.floating) and value.dtype == self.dtype) class ComplexBlock(FloatOrComplexBlock): __slots__ = () is_complex = True def _can_hold_element(self, element): tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, (np.floating, np.integer, np.complexfloating)) return ( isinstance( element, (float, int, complex, np.float_, np.int_, compat.long)) and not isinstance(element, (bool, np.bool_))) def should_store(self, value): return issubclass(value.dtype.type, np.complexfloating) class IntBlock(NumericBlock): __slots__ = () is_integer = True _can_hold_na = False def _can_hold_element(self, element): tipo = maybe_infer_dtype_type(element) if tipo is not None: return (issubclass(tipo.type, np.integer) and not issubclass(tipo.type, (np.datetime64, np.timedelta64)) and self.dtype.itemsize >= tipo.itemsize) return is_integer(element) def should_store(self, value): return is_integer_dtype(value) and value.dtype == self.dtype class DatetimeLikeBlockMixin(object): """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock.""" @property def _holder(self): return DatetimeArray @property def _na_value(self): return tslibs.NaT @property def fill_value(self): return tslibs.iNaT def get_values(self, dtype=None): """ return object dtype as boxed values, such as Timestamps/Timedelta """ if is_object_dtype(dtype): values = self.values.ravel() result = self._holder(values).astype(object) return result.reshape(self.values.shape) return self.values class DatetimeBlock(DatetimeLikeBlockMixin, Block): __slots__ = () is_datetime = True _can_hold_na = True def __init__(self, values, placement, ndim=None): values = self._maybe_coerce_values(values) super(DatetimeBlock, self).__init__(values, placement=placement, ndim=ndim) def _maybe_coerce_values(self, values): """Input validation for values passed to __init__. Ensure that we have datetime64ns, coercing if necessary. Parameters ---------- values : array-like Must be convertible to datetime64 Returns ------- values : ndarray[datetime64ns] Overridden by DatetimeTZBlock. """ if values.dtype != _NS_DTYPE: values = conversion.ensure_datetime64ns(values) if isinstance(values, DatetimeArray): values = values._data assert isinstance(values, np.ndarray), type(values) return values def _astype(self, dtype, **kwargs): """ these automatically copy, so copy=True has no effect raise on an except if raise == True """ dtype = pandas_dtype(dtype) # if we are passed a datetime64[ns, tz] if is_datetime64tz_dtype(dtype): values = self.values if getattr(values, 'tz', None) is None: values = DatetimeIndex(values).tz_localize('UTC') values = values.tz_convert(dtype.tz) return self.make_block(values) # delegate return super(DatetimeBlock, self)._astype(dtype=dtype, **kwargs) def _can_hold_element(self, element): tipo = maybe_infer_dtype_type(element) if tipo is not None: return tipo == _NS_DTYPE or tipo == np.int64 return (is_integer(element) or isinstance(element, datetime) or isna(element)) def _try_coerce_args(self, values, other): """ Coerce values and other to dtype 'i8'. NaN and NaT convert to the smallest i8, and will correctly round-trip to NaT if converted back in _try_coerce_result. values is always ndarray-like, other may not be Parameters ---------- values : ndarray-like other : ndarray-like or scalar Returns ------- base-type values, base-type other """ values = values.view('i8') if isinstance(other, bool): raise TypeError elif is_null_datetimelike(other): other = tslibs.iNaT elif isinstance(other, (datetime, np.datetime64, date)): other = self._box_func(other) if getattr(other, 'tz') is not None: raise TypeError("cannot coerce a Timestamp with a tz on a " "naive Block") other = other.asm8.view('i8') elif hasattr(other, 'dtype') and is_datetime64_dtype(other): other = other.astype('i8', copy=False).view('i8') else: # coercion issues # let higher levels handle raise TypeError(other) return values, other def _try_coerce_result(self, result): """ reverse of try_coerce_args """ if isinstance(result, np.ndarray): if result.dtype.kind in ['i', 'f']: result = result.astype('M8[ns]') elif isinstance(result, (np.integer, np.float, np.datetime64)): result = self._box_func(result) return result @property def _box_func(self): return tslibs.Timestamp def to_native_types(self, slicer=None, na_rep=None, date_format=None, quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values i8values = self.values.view('i8') if slicer is not None: i8values = i8values[..., slicer] from pandas.io.formats.format import _get_format_datetime64_from_values fmt = _get_format_datetime64_from_values(values, date_format) result = tslib.format_array_from_datetime( i8values.ravel(), tz=getattr(self.values, 'tz', None), format=fmt, na_rep=na_rep).reshape(i8values.shape) return np.atleast_2d(result) def should_store(self, value): return (issubclass(value.dtype.type, np.datetime64) and not is_datetime64tz_dtype(value) and not is_extension_array_dtype(value)) def set(self, locs, values): """ Modify Block in-place with new item value Returns ------- None """ values = conversion.ensure_datetime64ns(values, copy=False) self.values[locs] = values def external_values(self): return np.asarray(self.values.astype('datetime64[ns]', copy=False)) class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): """ implement a datetime64 block with a tz attribute """ __slots__ = () is_datetimetz = True is_extension = True @property def _holder(self): return DatetimeArray def _maybe_coerce_values(self, values): """Input validation for values passed to __init__. Ensure that we have datetime64TZ, coercing if necessary. Parametetrs ----------- values : array-like Must be convertible to datetime64 Returns ------- values : DatetimeArray """ if not isinstance(values, self._holder): values = self._holder(values) if values.tz is None: raise ValueError("cannot create a DatetimeTZBlock without a tz") return values @property def is_view(self): """ return a boolean if I am possibly a view """ # check the ndarray values of the DatetimeIndex values return self.values._data.base is not None def copy(self, deep=True): """ copy constructor """ values = self.values if deep: values = values.copy(deep=True) return self.make_block_same_class(values) def get_values(self, dtype=None): """ Returns an ndarray of values. Parameters ---------- dtype : np.dtype Only `object`-like dtypes are respected here (not sure why). Returns ------- values : ndarray When ``dtype=object``, then and object-dtype ndarray of boxed values is returned. Otherwise, an M8[ns] ndarray is returned. DatetimeArray is always 1-d. ``get_values`` will reshape the return value to be the same dimensionality as the block. """ values = self.values if is_object_dtype(dtype): values = values._box_values(values._data) values = np.asarray(values) if self.ndim == 2: # Ensure that our shape is correct for DataFrame. # ExtensionArrays are always 1-D, even in a DataFrame when # the analogous NumPy-backed column would be a 2-D ndarray. values = values.reshape(1, -1) return values def to_dense(self): # we request M8[ns] dtype here, even though it discards tzinfo, # as lots of code (e.g. anything using values_from_object) # expects that behavior. return np.asarray(self.values, dtype=_NS_DTYPE) def _slice(self, slicer): """ return a slice of my values """ if isinstance(slicer, tuple): col, loc = slicer if not com.is_null_slice(col) and col != 0: raise IndexError("{0} only contains one item".format(self)) return self.values[loc] return self.values[slicer] def _try_coerce_args(self, values, other): """ localize and return i8 for the values Parameters ---------- values : ndarray-like other : ndarray-like or scalar Returns ------- base-type values, base-type other """ # asi8 is a view, needs copy values = _block_shape(values.view("i8"), ndim=self.ndim) if isinstance(other, ABCSeries): other = self._holder(other) if isinstance(other, bool): raise TypeError elif is_datetime64_dtype(other): # add the tz back other = self._holder(other, dtype=self.dtype) elif is_null_datetimelike(other): other = tslibs.iNaT elif isinstance(other, self._holder): if other.tz != self.values.tz: raise ValueError("incompatible or non tz-aware value") other = _block_shape(other.asi8, ndim=self.ndim) elif isinstance(other, (np.datetime64, datetime, date)): other = tslibs.Timestamp(other) tz = getattr(other, 'tz', None) # test we can have an equal time zone if tz is None or str(tz) != str(self.values.tz): raise ValueError("incompatible or non tz-aware value") other = other.value else: raise TypeError(other) return values, other def _try_coerce_result(self, result): """ reverse of try_coerce_args """ if isinstance(result, np.ndarray): if result.dtype.kind in ['i', 'f']: result = result.astype('M8[ns]') elif isinstance(result, (np.integer, np.float, np.datetime64)): result = self._box_func(result) if isinstance(result, np.ndarray): # allow passing of > 1dim if its trivial if result.ndim > 1: result = result.reshape(np.prod(result.shape)) # GH#24096 new values invalidates a frequency result = self._holder._simple_new(result, freq=None, dtype=self.values.dtype) return result @property def _box_func(self): return lambda x: tslibs.Timestamp(x, tz=self.dtype.tz) def diff(self, n, axis=0): """1st discrete difference Parameters ---------- n : int, number of periods to diff axis : int, axis to diff upon. default 0 Return ------ A list with a new TimeDeltaBlock. Note ---- The arguments here are mimicking shift so they are called correctly by apply. """ if axis == 0: # Cannot currently calculate diff across multiple blocks since this # function is invoked via apply raise NotImplementedError new_values = (self.values - self.shift(n, axis=axis)[0].values).asi8 # Reshape the new_values like how algos.diff does for timedelta data new_values = new_values.reshape(1, len(new_values)) new_values = new_values.astype('timedelta64[ns]') return [TimeDeltaBlock(new_values, placement=self.mgr_locs.indexer)] def concat_same_type(self, to_concat, placement=None): # need to handle concat([tz1, tz2]) here, since DatetimeArray # only handles cases where all the tzs are the same. # Instead of placing the condition here, it could also go into the # is_uniform_join_units check, but I'm not sure what is better. if len({x.dtype for x in to_concat}) > 1: values = _concat._concat_datetime([x.values for x in to_concat]) placement = placement or slice(0, len(values), 1) if self.ndim > 1: values = np.atleast_2d(values) return ObjectBlock(values, ndim=self.ndim, placement=placement) return super(DatetimeTZBlock, self).concat_same_type(to_concat, placement) def fillna(self, value, limit=None, inplace=False, downcast=None): # We support filling a DatetimeTZ with a `value` whose timezone # is different by coercing to object. try: return super(DatetimeTZBlock, self).fillna( value, limit, inplace, downcast ) except (ValueError, TypeError): # different timezones, or a non-tz return self.astype(object).fillna( value, limit=limit, inplace=inplace, downcast=downcast ) def setitem(self, indexer, value): # https://github.com/pandas-dev/pandas/issues/24020 # Need a dedicated setitem until #24020 (type promotion in setitem # for extension arrays) is designed and implemented. try: return super(DatetimeTZBlock, self).setitem(indexer, value) except (ValueError, TypeError): newb = make_block(self.values.astype(object), placement=self.mgr_locs, klass=ObjectBlock,) return newb.setitem(indexer, value) def equals(self, other): # override for significant performance improvement if self.dtype != other.dtype or self.shape != other.shape: return False return (self.values.view('i8') == other.values.view('i8')).all() class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock): __slots__ = () is_timedelta = True _can_hold_na = True is_numeric = False def __init__(self, values, placement, ndim=None): if values.dtype != _TD_DTYPE: values = conversion.ensure_timedelta64ns(values) if isinstance(values, TimedeltaArray): values = values._data assert isinstance(values, np.ndarray), type(values) super(TimeDeltaBlock, self).__init__(values, placement=placement, ndim=ndim) @property def _holder(self): return TimedeltaArray @property def _box_func(self): return lambda x: Timedelta(x, unit='ns') def _can_hold_element(self, element): tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, (np.timedelta64, np.int64)) return is_integer(element) or isinstance( element, (timedelta, np.timedelta64, np.int64)) def fillna(self, value, **kwargs): # allow filling with integers to be # interpreted as nanoseconds if is_integer(value) and not isinstance(value, np.timedelta64): # Deprecation GH#24694, GH#19233 warnings.warn("Passing integers to fillna is deprecated, will " "raise a TypeError in a future version. To retain " "the old behavior, pass pd.Timedelta(seconds=n) " "instead.", FutureWarning, stacklevel=6) value = Timedelta(value, unit='s') return super(TimeDeltaBlock, self).fillna(value, **kwargs) def _try_coerce_args(self, values, other): """ Coerce values and other to int64, with null values converted to iNaT. values is always ndarray-like, other may not be Parameters ---------- values : ndarray-like other : ndarray-like or scalar Returns ------- base-type values, base-type other """ values = values.view('i8') if isinstance(other, bool): raise TypeError elif is_null_datetimelike(other): other = tslibs.iNaT elif isinstance(other, (timedelta, np.timedelta64)): other = Timedelta(other).value elif hasattr(other, 'dtype') and is_timedelta64_dtype(other): other = other.astype('i8', copy=False).view('i8') else: # coercion issues # let higher levels handle raise TypeError(other) return values, other def _try_coerce_result(self, result): """ reverse of try_coerce_args / try_operate """ if isinstance(result, np.ndarray): mask = isna(result) if result.dtype.kind in ['i', 'f']: result = result.astype('m8[ns]') result[mask] = tslibs.iNaT elif isinstance(result, (np.integer, np.float)): result = self._box_func(result) return result def should_store(self, value): return (issubclass(value.dtype.type, np.timedelta64) and not is_extension_array_dtype(value)) def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values if slicer is not None: values = values[:, slicer] mask = isna(values) rvalues = np.empty(values.shape, dtype=object) if na_rep is None: na_rep = 'NaT' rvalues[mask] = na_rep imask = (~mask).ravel() # FIXME: # should use the formats.format.Timedelta64Formatter here # to figure what format to pass to the Timedelta # e.g. to not show the decimals say rvalues.flat[imask] = np.array([Timedelta(val)._repr_base(format='all') for val in values.ravel()[imask]], dtype=object) return rvalues def external_values(self, dtype=None): return np.asarray(self.values.astype("timedelta64[ns]", copy=False)) class BoolBlock(NumericBlock): __slots__ = () is_bool = True _can_hold_na = False def _can_hold_element(self, element): tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, np.bool_) return isinstance(element, (bool, np.bool_)) def should_store(self, value): return (issubclass(value.dtype.type, np.bool_) and not is_extension_array_dtype(value)) def replace(self, to_replace, value, inplace=False, filter=None, regex=False, convert=True): inplace = validate_bool_kwarg(inplace, 'inplace') to_replace_values = np.atleast_1d(to_replace) if not np.can_cast(to_replace_values, bool): return self return super(BoolBlock, self).replace(to_replace, value, inplace=inplace, filter=filter, regex=regex, convert=convert) class ObjectBlock(Block): __slots__ = () is_object = True _can_hold_na = True def __init__(self, values, placement=None, ndim=2): if issubclass(values.dtype.type, compat.string_types): values = np.array(values, dtype=object) super(ObjectBlock, self).__init__(values, ndim=ndim, placement=placement) @property def is_bool(self): """ we can be a bool if we have only bool values but are of type object """ return lib.is_bool_array(self.values.ravel()) # TODO: Refactor when convert_objects is removed since there will be 1 path def convert(self, *args, **kwargs): """ attempt to coerce any object types to better types return a copy of the block (if copy = True) by definition we ARE an ObjectBlock!!!!! can return multiple blocks! """ if args: raise NotImplementedError by_item = kwargs.get('by_item', True) new_inputs = ['coerce', 'datetime', 'numeric', 'timedelta'] new_style = False for kw in new_inputs: new_style |= kw in kwargs if new_style: fn = soft_convert_objects fn_inputs = new_inputs else: fn = maybe_convert_objects fn_inputs = ['convert_dates', 'convert_numeric', 'convert_timedeltas'] fn_inputs += ['copy'] fn_kwargs = {key: kwargs[key] for key in fn_inputs if key in kwargs} # operate column-by-column def f(m, v, i): shape = v.shape values = fn(v.ravel(), **fn_kwargs) try: values = values.reshape(shape) values = _block_shape(values, ndim=self.ndim) except (AttributeError, NotImplementedError): pass return values if by_item and not self._is_single_block: blocks = self.split_and_operate(None, f, False) else: values = f(None, self.values.ravel(), None) blocks = [make_block(values, ndim=self.ndim, placement=self.mgr_locs)] return blocks def set(self, locs, values): """ Modify Block in-place with new item value Returns ------- None """ try: self.values[locs] = values except (ValueError): # broadcasting error # see GH6171 new_shape = list(values.shape) new_shape[0] = len(self.items) self.values = np.empty(tuple(new_shape), dtype=self.dtype) self.values.fill(np.nan) self.values[locs] = values def _maybe_downcast(self, blocks, downcast=None): if downcast is not None: return blocks # split and convert the blocks return _extend_blocks([b.convert(datetime=True, numeric=False) for b in blocks]) def _can_hold_element(self, element): return True def _try_coerce_args(self, values, other): """ provide coercion to our input arguments """ if isinstance(other, ABCDatetimeIndex): # May get a DatetimeIndex here. Unbox it. other = other.array if isinstance(other, DatetimeArray): # hit in pandas/tests/indexing/test_coercion.py # ::TestWhereCoercion::test_where_series_datetime64[datetime64tz] # when falling back to ObjectBlock.where other = other.astype(object) return values, other def should_store(self, value): return not (issubclass(value.dtype.type, (np.integer, np.floating, np.complexfloating, np.datetime64, np.bool_)) or # TODO(ExtensionArray): remove is_extension_type # when all extension arrays have been ported. is_extension_type(value) or is_extension_array_dtype(value)) def replace(self, to_replace, value, inplace=False, filter=None, regex=False, convert=True): to_rep_is_list = is_list_like(to_replace) value_is_list = is_list_like(value) both_lists = to_rep_is_list and value_is_list either_list = to_rep_is_list or value_is_list result_blocks = [] blocks = [self] if not either_list and is_re(to_replace): return self._replace_single(to_replace, value, inplace=inplace, filter=filter, regex=True, convert=convert) elif not (either_list or regex): return super(ObjectBlock, self).replace(to_replace, value, inplace=inplace, filter=filter, regex=regex, convert=convert) elif both_lists: for to_rep, v in zip(to_replace, value): result_blocks = [] for b in blocks: result = b._replace_single(to_rep, v, inplace=inplace, filter=filter, regex=regex, convert=convert) result_blocks = _extend_blocks(result, result_blocks) blocks = result_blocks return result_blocks elif to_rep_is_list and regex: for to_rep in to_replace: result_blocks = [] for b in blocks: result = b._replace_single(to_rep, value, inplace=inplace, filter=filter, regex=regex, convert=convert) result_blocks = _extend_blocks(result, result_blocks) blocks = result_blocks return result_blocks return self._replace_single(to_replace, value, inplace=inplace, filter=filter, convert=convert, regex=regex) def _replace_single(self, to_replace, value, inplace=False, filter=None, regex=False, convert=True, mask=None): """ Replace elements by the given value. Parameters ---------- to_replace : object or pattern Scalar to replace or regular expression to match. value : object Replacement object. inplace : bool, default False Perform inplace modification. filter : list, optional regex : bool, default False If true, perform regular expression substitution. convert : bool, default True If true, try to coerce any object types to better types. mask : array-like of bool, optional True indicate corresponding element is ignored. Returns ------- a new block, the result after replacing """ inplace = validate_bool_kwarg(inplace, 'inplace') # to_replace is regex compilable to_rep_re = regex and is_re_compilable(to_replace) # regex is regex compilable regex_re = is_re_compilable(regex) # only one will survive if to_rep_re and regex_re: raise AssertionError('only one of to_replace and regex can be ' 'regex compilable') # if regex was passed as something that can be a regex (rather than a # boolean) if regex_re: to_replace = regex regex = regex_re or to_rep_re # try to get the pattern attribute (compiled re) or it's a string try: pattern = to_replace.pattern except AttributeError: pattern = to_replace # if the pattern is not empty and to_replace is either a string or a # regex if regex and pattern: rx = re.compile(to_replace) else: # if the thing to replace is not a string or compiled regex call # the superclass method -> to_replace is some kind of object return super(ObjectBlock, self).replace(to_replace, value, inplace=inplace, filter=filter, regex=regex) new_values = self.values if inplace else self.values.copy() # deal with replacing values with objects (strings) that match but # whose replacement is not a string (numeric, nan, object) if isna(value) or not isinstance(value, compat.string_types): def re_replacer(s): try: return value if rx.search(s) is not None else s except TypeError: return s else: # value is guaranteed to be a string here, s can be either a string # or null if it's null it gets returned def re_replacer(s): try: return rx.sub(value, s) except TypeError: return s f = np.vectorize(re_replacer, otypes=[self.dtype]) if filter is None: filt = slice(None) else: filt = self.mgr_locs.isin(filter).nonzero()[0] if mask is None: new_values[filt] = f(new_values[filt]) else: new_values[filt][mask] = f(new_values[filt][mask]) # convert block = self.make_block(new_values) if convert: block = block.convert(by_item=True, numeric=False) return block def _replace_coerce(self, to_replace, value, inplace=True, regex=False, convert=False, mask=None): """ Replace value corresponding to the given boolean array with another value. Parameters ---------- to_replace : object or pattern Scalar to replace or regular expression to match. value : object Replacement object. inplace : bool, default False Perform inplace modification. regex : bool, default False If true, perform regular expression substitution. convert : bool, default True If true, try to coerce any object types to better types. mask : array-like of bool, optional True indicate corresponding element is ignored. Returns ------- A new block if there is anything to replace or the original block. """ if mask.any(): block = super(ObjectBlock, self)._replace_coerce( to_replace=to_replace, value=value, inplace=inplace, regex=regex, convert=convert, mask=mask) if convert: block = [b.convert(by_item=True, numeric=False, copy=True) for b in block] return block return self class CategoricalBlock(ExtensionBlock): __slots__ = () is_categorical = True _verify_integrity = True _can_hold_na = True _concatenator = staticmethod(_concat._concat_categorical) def __init__(self, values, placement, ndim=None): from pandas.core.arrays.categorical import _maybe_to_categorical # coerce to categorical if we can super(CategoricalBlock, self).__init__(_maybe_to_categorical(values), placement=placement, ndim=ndim) @property def _holder(self): return Categorical @property def array_dtype(self): """ the dtype to return if I want to construct this block as an array """ return np.object_ def _try_coerce_result(self, result): """ reverse of try_coerce_args """ # GH12564: CategoricalBlock is 1-dim only # while returned results could be any dim if ((not is_categorical_dtype(result)) and isinstance(result, np.ndarray)): result = _block_shape(result, ndim=self.ndim) return result def to_dense(self): # Categorical.get_values returns a DatetimeIndex for datetime # categories, so we can't simply use `np.asarray(self.values)` like # other types. return self.values.get_values() def to_native_types(self, slicer=None, na_rep='', quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values if slicer is not None: # Categorical is always one dimension values = values[slicer] mask = isna(values) values = np.array(values, dtype='object') values[mask] = na_rep # we are expected to return a 2-d ndarray return values.reshape(1, len(values)) def concat_same_type(self, to_concat, placement=None): """ Concatenate list of single blocks of the same type. Note that this CategoricalBlock._concat_same_type *may* not return a CategoricalBlock. When the categories in `to_concat` differ, this will return an object ndarray. If / when we decide we don't like that behavior: 1. Change Categorical._concat_same_type to use union_categoricals 2. Delete this method. """ values = self._concatenator([blk.values for blk in to_concat], axis=self.ndim - 1) # not using self.make_block_same_class as values can be object dtype return make_block( values, placement=placement or slice(0, len(values), 1), ndim=self.ndim) def where(self, other, cond, align=True, errors='raise', try_cast=False, axis=0, transpose=False): # TODO(CategoricalBlock.where): # This can all be deleted in favor of ExtensionBlock.where once # we enforce the deprecation. object_msg = ( "Implicitly converting categorical to object-dtype ndarray. " "One or more of the values in 'other' are not present in this " "categorical's categories. A future version of pandas will raise " "a ValueError when 'other' contains different categories.\n\n" "To preserve the current behavior, add the new categories to " "the categorical before calling 'where', or convert the " "categorical to a different dtype." ) try: # Attempt to do preserve categorical dtype. result = super(CategoricalBlock, self).where( other, cond, align, errors, try_cast, axis, transpose ) except (TypeError, ValueError): warnings.warn(object_msg, FutureWarning, stacklevel=6) result = self.astype(object).where(other, cond, align=align, errors=errors, try_cast=try_cast, axis=axis, transpose=transpose) return result # ----------------------------------------------------------------- # Constructor Helpers def get_block_type(values, dtype=None): """ Find the appropriate Block subclass to use for the given values and dtype. Parameters ---------- values : ndarray-like dtype : numpy or pandas dtype Returns ------- cls : class, subclass of Block """ dtype = dtype or values.dtype vtype = dtype.type if is_sparse(dtype): # Need this first(ish) so that Sparse[datetime] is sparse cls = ExtensionBlock elif is_categorical(values): cls = CategoricalBlock elif issubclass(vtype, np.datetime64): assert not is_datetime64tz_dtype(values) cls = DatetimeBlock elif is_datetime64tz_dtype(values): cls = DatetimeTZBlock elif is_interval_dtype(dtype) or is_period_dtype(dtype): cls = ObjectValuesExtensionBlock elif is_extension_array_dtype(values): cls = ExtensionBlock elif issubclass(vtype, np.floating): cls = FloatBlock elif issubclass(vtype, np.timedelta64): assert issubclass(vtype, np.integer) cls = TimeDeltaBlock elif issubclass(vtype, np.complexfloating): cls = ComplexBlock elif issubclass(vtype, np.integer): cls = IntBlock elif dtype == np.bool_: cls = BoolBlock else: cls = ObjectBlock return cls def make_block(values, placement, klass=None, ndim=None, dtype=None, fastpath=None): if fastpath is not None: # GH#19265 pyarrow is passing this warnings.warn("fastpath argument is deprecated, will be removed " "in a future release.", DeprecationWarning) if klass is None: dtype = dtype or values.dtype klass = get_block_type(values, dtype) elif klass is DatetimeTZBlock and not is_datetime64tz_dtype(values): # TODO: This is no longer hit internally; does it need to be retained # for e.g. pyarrow? values = DatetimeArray._simple_new(values, dtype=dtype) return klass(values, ndim=ndim, placement=placement) # ----------------------------------------------------------------- def _extend_blocks(result, blocks=None): """ return a new extended blocks, givin the result """ from pandas.core.internals import BlockManager if blocks is None: blocks = [] if isinstance(result, list): for r in result: if isinstance(r, list): blocks.extend(r) else: blocks.append(r) elif isinstance(result, BlockManager): blocks.extend(result.blocks) else: blocks.append(result) return blocks def _block_shape(values, ndim=1, shape=None): """ guarantee the shape of the values to be at least 1 d """ if values.ndim < ndim: if shape is None: shape = values.shape if not is_extension_array_dtype(values): # TODO: https://github.com/pandas-dev/pandas/issues/23023 # block.shape is incorrect for "2D" ExtensionArrays # We can't, and don't need to, reshape. values = values.reshape(tuple((1, ) + shape)) return values def _merge_blocks(blocks, dtype=None, _can_consolidate=True): if len(blocks) == 1: return blocks[0] if _can_consolidate: if dtype is None: if len({b.dtype for b in blocks}) != 1: raise AssertionError("_merge_blocks are invalid!") dtype = blocks[0].dtype # FIXME: optimization potential in case all mgrs contain slices and # combination of those slices is a slice, too. new_mgr_locs = np.concatenate([b.mgr_locs.as_array for b in blocks]) new_values = np.vstack([b.values for b in blocks]) argsort = np.argsort(new_mgr_locs) new_values = new_values[argsort] new_mgr_locs = new_mgr_locs[argsort] return make_block(new_values, placement=new_mgr_locs) # no merge return blocks def _block2d_to_blocknd(values, placement, shape, labels, ref_items): """ pivot to the labels shape """ panel_shape = (len(placement),) + shape # TODO: lexsort depth needs to be 2!! # Create observation selection vector using major and minor # labels, for converting to panel format. selector = _factor_indexer(shape[1:], labels) mask = np.zeros(np.prod(shape), dtype=bool) mask.put(selector, True) if mask.all(): pvalues = np.empty(panel_shape, dtype=values.dtype) else: dtype, fill_value = maybe_promote(values.dtype) pvalues = np.empty(panel_shape, dtype=dtype) pvalues.fill(fill_value) for i in range(len(placement)): pvalues[i].flat[mask] = values[:, i] return make_block(pvalues, placement=placement) def _safe_reshape(arr, new_shape): """ If possible, reshape `arr` to have shape `new_shape`, with a couple of exceptions (see gh-13012): 1) If `arr` is a ExtensionArray or Index, `arr` will be returned as is. 2) If `arr` is a Series, the `_values` attribute will be reshaped and returned. Parameters ---------- arr : array-like, object to be reshaped new_shape : int or tuple of ints, the new shape """ if isinstance(arr, ABCSeries): arr = arr._values if not isinstance(arr, ABCExtensionArray): arr = arr.reshape(new_shape) return arr def _factor_indexer(shape, labels): """ given a tuple of shape and a list of Categorical labels, return the expanded label indexer """ mult = np.array(shape)[::-1].cumprod()[::-1] return ensure_platform_int( np.sum(np.array(labels).T * np.append(mult, [1]), axis=1).T) def _putmask_smart(v, m, n): """ Return a new ndarray, try to preserve dtype if possible. Parameters ---------- v : `values`, updated in-place (array like) m : `mask`, applies to both sides (array like) n : `new values` either scalar or an array like aligned with `values` Returns ------- values : ndarray with updated values this *may* be a copy of the original See Also -------- ndarray.putmask """ # we cannot use np.asarray() here as we cannot have conversions # that numpy does when numeric are mixed with strings # n should be the length of the mask or a scalar here if not is_list_like(n): n = np.repeat(n, len(m)) elif isinstance(n, np.ndarray) and n.ndim == 0: # numpy scalar n = np.repeat(np.array(n, ndmin=1), len(m)) # see if we are only masking values that if putted # will work in the current dtype try: nn = n[m] # make sure that we have a nullable type # if we have nulls if not _isna_compat(v, nn[0]): raise ValueError # we ignore ComplexWarning here with warnings.catch_warnings(record=True): warnings.simplefilter("ignore", np.ComplexWarning) nn_at = nn.astype(v.dtype) # avoid invalid dtype comparisons # between numbers & strings # only compare integers/floats # don't compare integers to datetimelikes if (not is_numeric_v_string_like(nn, nn_at) and (is_float_dtype(nn.dtype) or is_integer_dtype(nn.dtype) and is_float_dtype(nn_at.dtype) or is_integer_dtype(nn_at.dtype))): comp = (nn == nn_at) if is_list_like(comp) and comp.all(): nv = v.copy() nv[m] = nn_at return nv except (ValueError, IndexError, TypeError): pass n = np.asarray(n) def _putmask_preserve(nv, n): try: nv[m] = n[m] except (IndexError, ValueError): nv[m] = n return nv # preserves dtype if possible if v.dtype.kind == n.dtype.kind: return _putmask_preserve(v, n) # change the dtype if needed dtype, _ = maybe_promote(n.dtype) if is_extension_type(v.dtype) and is_object_dtype(dtype): v = v.get_values(dtype) else: v = v.astype(dtype) return _putmask_preserve(v, n)
bsd-3-clause
ellisk42/TikZ
synthesizer.py
1
30155
from learnedRanking import learnToRank from similarity import analyzeFeatures from render import render #from fastRender import fastRender from sketch import synthesizeProgram from language import * from utilities import showImage,loadImage,saveMatrixAsImage,mergeDictionaries,frameImageNicely from recognitionModel import Particle from groundTruthParses import groundTruthSequence,getGroundTruthParse from extrapolate import * from DSL import * import traceback import re import os import argparse import pickle import time from pathos.multiprocessing import ProcessingPool as Pool import matplotlib.pyplot as plot import sys class SynthesisResult(): def __init__(self, job, time = None, source = None, program = None, cost = None): self.job = job self.program = program self.time = time self.source = source self.cost = cost def __str__(self): return "SynthesisResult(%s)"%(self.job) def exportToFile(self,f): with open(f,"w") as handle: handle.write("Found the following cost-%d program after %f seconds:\n%s"% (self.cost, self.time, self.program.pretty())) class SynthesisJob(): def __init__(self, parse, originalDrawing, usePrior = True, maximumDepth = 3, canLoop = True, canReflect = True, incremental = False): self.incremental = incremental self.maximumDepth = maximumDepth self.canLoop = canLoop self.canReflect = canReflect self.parse = parse self.originalDrawing = originalDrawing self.usePrior = usePrior def __str__(self): return "SynthesisJob(%s,incremental = %s,maximumD = %s,loops = %s,reflects = %s,prior = %s)"%(self.originalDrawing, self.incremental, self.maximumDepth, self.canLoop, self.canReflect, self.usePrior) def subsumes(self,other): assert self.originalDrawing == other.originalDrawing if self.incremental: return False # ??? need to understand this better... return self.incremental == other.incremental and self.maximumDepth >= other.maximumDepth and self.canLoop >= other.canLoop and self.canReflect >= other.canReflect #and not self.incremental def execute(self, timeout = 60, parallelSolving = 1): if self.incremental: return self.executeIncrementally(timeout = timeout, parallelSolving = parallelSolving) else: return self.executeJoint(timeout = timeout, parallelSolving = parallelSolving) def executeJoint(self, timeout = 60, parallelSolving = 1): startTime = time.time() result = synthesizeProgram(self.parse,self.usePrior, maximumDepth = self.maximumDepth, canLoop = self.canLoop, canReflect = self.canReflect, CPUs = parallelSolving, timeout = timeout) elapsedTime = time.time() - startTime return SynthesisResult(self, time = elapsedTime, source = result[1] if result != None else None, cost = result[0] if result != None else None, program = parseSketchOutput(result[1]) if result != None else None) def executeIncrementally(self, timeout = 60, parallelSolving = 1): jobs = {} for l in self.parse.lines: if isinstance(l,Circle): jobs['Circle'] = jobs.get('Circle',[]) + [l] elif isinstance(l,Rectangle): jobs['Rectangle'] = jobs.get('Rectangle',[]) + [l] elif isinstance(l,Line): jobs['Line%s%s'%(l.solid,l.arrow)] = jobs.get('Line%s%s'%(l.solid,l.arrow),[]) + [l] else: assert False # Heuristic: try to solve the "big enough" problems first # Break ties by absolute size jobOrdering = sorted(jobs.keys(),key = lambda stuff: (len(stuff) < 3,len(stuff))) jobResults = {} startTime = time.time() xCoefficients = set([]) yCoefficients = set([]) usedReflections = set([]) usedLoops = [] for k in jobOrdering: print "Synthesizing for:\n",Sequence(jobs[k]) print "xCoefficients",xCoefficients print "yCoefficients",yCoefficients print "usedReflections",usedReflections print "usedLoops",usedLoops print "canLoop",self.canLoop print "canReflect",self.canReflect jobResults[k] = synthesizeProgram(Sequence(jobs[k]), self.usePrior, entireParse = self.parse, xCoefficients = xCoefficients, yCoefficients = yCoefficients, usedReflections = usedReflections, usedLoops = usedLoops, CPUs = parallelSolving, maximumDepth = self.maximumDepth, canLoop = self.canLoop, canReflect = self.canReflect, timeout = timeout) if jobResults[k] == None: print " [-] Incremental synthesis failure: %s"%self return SynthesisResult(self, time = time.time() - startTime, source = [ s[1] for s in jobResults.values() if s != None ], program = None, cost = None) parsedOutput = parseSketchOutput(jobResults[k][1]) xs,ys = parsedOutput.usedCoefficients() xCoefficients = xCoefficients|xs yCoefficients = yCoefficients|ys xr,yr = parsedOutput.usedReflections() usedReflections = usedReflections|set([(x,0) for x in xr ]) usedReflections = usedReflections|set([(0,y) for y in yr ]) usedLoops += list(parsedOutput.usedLoops()) usedLoops = removeDuplicateStrings(usedLoops) elapsedTime = time.time() - startTime print "Optimizing using rewrites..." try: gluedTogether = Block([ x for _,result in jobResults.values() for x in parseSketchOutput(result).items ]) optimalCost,optimalProgram = gluedTogether.optimizeUsingRewrites() print optimalProgram.pretty() except: e = sys.exc_info()[0] print " [-] Problem parsing or optimizing %s: %s"%(self.originalDrawing,e) optimalProgram = None optimalCost = None return SynthesisResult(self, time = elapsedTime, source = [ s for _,s in jobResults.values() ], program = optimalProgram, cost = optimalCost) def invokeExecuteMethod(k, timeout = 60, parallelSolving = 1): try: return k.execute(timeout = timeout, parallelSolving = parallelSolving) except Exception as exception: t = traceback.format_exc() print "Exception while executing job:\n%s\n%s\n%s\n"%(exception,t,k) return exception def parallelExecute(jobs): if arguments.cores == 1: return map(lambda j: invokeExecuteMethod(j, timeout = arguments.timeout), jobs) else: return Pool(arguments.cores).map(lambda j: invokeExecuteMethod(j,timeout = arguments.timeout),jobs) # Loads all of the particles in the directory, up to the first 200 # Returns the top K as measured by a linear combination of image distance and neural network likelihood def loadTopParticles(directory, k): particles = [] if directory.endswith('/'): directory = directory[:-1] for j in range(k): f = directory + '/particle' + str(j) + '.p' if not os.path.isfile(f): break particles.append(pickle.load(open(f,'rb'))) print " [+] Loaded %s"%(f) return particles[:k] # Synthesize based on the top k particles in drawings/expert* # Just returns the jobs to synthesize these things def expertSynthesisJobs(k): jobs = [] for j in range(100): originalDrawing = 'drawings/expert-%d.png'%j particleDirectory = 'drawings/expert-%d-parses'%j if not os.path.exists(originalDrawing) or not os.path.exists(particleDirectory): continue newJobs = [] for p in loadTopParticles(particleDirectory, k): newJobs.append(SynthesisJob(p.sequence(), originalDrawing, usePrior = not arguments.noPrior)) # but we don't care about synthesizing if there wasn't a ground truth in them if any([ newJob.parse == getGroundTruthParse(originalDrawing) for newJob in newJobs ]): jobs += newJobs return jobs def synthesizeTopK(k): if k == 0: name = 'groundTruthSynthesisResults.p' else: name = 'top%dSynthesisResults.p'%k jobs = expertSynthesisJobs(k) if k > 0 else [] # synthesized from the ground truth? if k == 0: for k in groundTruthSequence: sequence = groundTruthSequence[k] if all([ not (r.parse == sequence) for r in results ]): jobs.append(SynthesisJob(sequence,k,usePrior = True)) if arguments.noPrior: jobs.append(SynthesisJob(sequence,k,usePrior = False)) else: print "top jobs",len(jobs) print "# jobs",len(jobs) flushEverything() results = parallelExecute(jobs) + results with open(name,'wb') as handle: pickle.dump(results, handle) print "Dumped %d results to %s"%(len(results),name) def makePolicyTrainingData(): jobs = [ SynthesisJob(getGroundTruthParse(f), f, usePrior = True, maximumDepth = d, canLoop = l, canReflect = r, incremental = i) for j in range(100) for f in ['drawings/expert-%d.png'%j] for d in [1,2,3] for i in [True,False] for l in [True,False] for r in [True,False] ] print " [+] Constructed %d job objects for the purpose of training a policy"%(len(jobs)) results = parallelExecute(jobs) fn = 'policyTrainingData.p' with open(fn,'wb') as handle: pickle.dump(results, handle) print " [+] Dumped results to %s."%fn def viewSynthesisResults(arguments): results = pickle.load(open(arguments.name,'rb')) print " [+] Loaded %d synthesis results."%(len(results)) interestingExtrapolations = [7, #14, 17, 29, #35, 52, 57, 63, 70, 72, 88, #99] ] interestingExtrapolations = [(16,12),#* #(17,0), (18,0),#* #(22,0), #(23,0), #(29,12), #(31,27), (34,0),#* #(36,0), #(38,12), (39,0),#* #(41,1), #(51,1), #(52,12), #(57,0), #(58,0), (60,0),#* #(63,0), (66,2),#* (71,1),#* #(72,0), #(73,0), #(74,10), #(75,5), #(79,0), #(85,1), (86,0),#* #(88,0), (90,2),#* #(92,0), #(95,8) ] #interestingExtrapolations = list(range(100)) latex = [] extrapolationMatrix = [] programFeatures = {} for expertIndex in list(range(100)): f = 'drawings/expert-%d.png'%expertIndex parse = getGroundTruthParse(f) if parse == None: print "No ground truth for %d"%expertIndex assert False relevantResults = [ r for r in results if r.job.originalDrawing == f and r.cost != None ] if relevantResults == []: print "No synthesis result for %s"%f result = None else: result = min(relevantResults, key = lambda r: r.cost) equallyGoodResults = [ r for r in relevantResults if r.cost <= result.cost + 1 ] if len(equallyGoodResults) > 1: print "Got %d results for %d"%(len(equallyGoodResults),expertIndex) programs = [ r.program.fixStringParameters().\ fixReflections(result.job.parse.canonicalTranslation()).removeDeadCode() for r in equallyGoodResults ] gt = result.job.parse.canonicalTranslation() badPrograms = [ p for p in programs if p.convertToSequence().canonicalTranslation() != gt ] if badPrograms: print " [-] WARNING: Got %d programs that are inconsistent with ground truth"%(len(badPrograms)) if False: for program in programs: prediction = program.convertToSequence().canonicalTranslation() actual = gt if not (prediction == actual): print "FATAL: program does notproduce spec" print "Specification:" print actual print "Program:" print program print program.pretty() print "Program output:" print prediction print set(map(str,prediction.lines)) print set(map(str,actual.lines)) print set(map(str,actual.lines))^set(map(str,prediction.lines)) assert False if result == None and arguments.extrapolate: print "Synthesis failure for %s"%f continue print " [+] %s"%f print "\t(synthesis time: %s)"%(result.time if result else None) print if arguments.debug: print result.source if result != None: syntaxTree = result.program.fixStringParameters() syntaxTree = syntaxTree.fixReflections(result.job.parse.canonicalTranslation()) print syntaxTree.pretty() print syntaxTree.features() print syntaxTree.convertToSequence() #showImage(fastRender(syntaxTree.convertToSequence()) + loadImage(f)*0.5 + fastRender(result.parse)) programFeatures[f] = syntaxTree.features() if arguments.extrapolate: extrapolations = proposeExtrapolations(programs) if extrapolations: framedExtrapolations = [1 - frameImageNicely(loadImage(f))] + \ [ frameImageNicely(t.draw(adjustCanvasSize = True)) for t in extrapolations ] a = 255*makeImageArray(framedExtrapolations) extrapolationMatrix.append(a) print "Saving extrapolation column to",'extrapolations/expert-%d-extrapolation.png'%expertIndex saveMatrixAsImage(a,'extrapolations/expert-%d-extrapolation.png'%expertIndex) if not arguments.extrapolate: rightEntryOfTable = ''' \\begin{minipage}{10cm} \\begin{verbatim} %s \\end{verbatim} \\end{minipage} '''%(syntaxTree.pretty() if result != None else "Solver timeout") else: rightEntryOfTable = "" if False and extrapolations != [] and arguments.extrapolate: #print e rightEntryOfTable = '\\includegraphics[width = 5cm]{../TikZ/extrapolations/expert-%d-extrapolation.png}'%expertIndex if rightEntryOfTable != "": parseImage = '\\includegraphics[width = 5cm]{../TikZ/drawings/expert-%d-parses/0.png}'%expertIndex if not os.path.exists('drawings/expert-%d-parses/0.png'%expertIndex): parseImage = "Sampled no finished traces." latex.append(''' \\begin{tabular}{lll} \\includegraphics[width = 5cm]{../TikZ/drawings/expert-%d.png}& %s& %s \\end{tabular} '''%(expertIndex, parseImage, rightEntryOfTable)) print if arguments.latex: latex = '%s'%("\\\\\n".join(latex)) name = "extrapolations.tex" if arguments.extrapolate else "synthesizerOutputs.tex" with open('../TikZpaper/%s'%name,'w') as handle: handle.write(latex) print "Wrote output to ../TikZpaper/%s"%name if arguments.similarity: analyzeFeatures(programFeatures) if arguments.extrapolate: #}make the big matrix bigMatrix = np.zeros((max([m.shape[0] for m in extrapolationMatrix ]),256*len(extrapolationMatrix))) for j,r in enumerate(extrapolationMatrix): bigMatrix[0:r.shape[0],256*j:256*(j+1)] = r saveMatrixAsImage(bigMatrix,'extrapolations/allTheExtrapolations.png') def rankUsingPrograms(): results = pickle.load(open(arguments.name,'rb')) print " [+] Loaded %d synthesis results from %s."%(len(results),arguments.name) def getProgramForParse(sequence): for r in results: if sequence == r.parse and r.usedPrior(): return r return None def featuresOfParticle(p): r = getProgramForParse(p.sequence()) if r != None and r.cost != None and r.source != None: programFeatures = mergeDictionaries({'failure': 0.0}, parseSketchOutput(r.source).features()) else: programFeatures = {'failure': 1.0} parseFeatures = {'distance': p.distance[0] + p.distance[1], 'logPrior': p.sequence().logPrior(), 'logLikelihood': p.logLikelihood} return mergeDictionaries(parseFeatures,programFeatures) k = arguments.learnToRank topParticles = [loadTopParticles('drawings/expert-%d-parses'%j,k) for j in range(100) ] learningProblems = [] for j,ps in enumerate(topParticles): gt = getGroundTruthParse('drawings/expert-%d.png'%j) positives = [] negatives = [] for p in ps: if p.sequence() == gt: positives.append(p) else: negatives.append(p) if positives != [] and negatives != []: learningProblems.append((map(featuresOfParticle,positives), map(featuresOfParticle,negatives))) featureIndices = list(set([ f for pn in learningProblems for exs in pn for ex in exs for f in ex.keys() ])) def dictionaryToVector(featureMap): return [ featureMap.get(f,0.0) for f in featureIndices ] learningProblems = [ (map(dictionaryToVector,positives), map(dictionaryToVector,negatives)) for positives,negatives in learningProblems ] parameters = learnToRank(learningProblems) for f,p in zip(featureIndices,parameters): print f,p # showcases where it succeeds programAccuracy = 0 oldAccuracy = 0 for j,tp in enumerate(topParticles): if tp == []: continue gt = getGroundTruthParse('drawings/expert-%d.png'%j) # the_top_particles_according_to_the_learned_weights featureVectors = np.array([ dictionaryToVector(featuresOfParticle(p)) for p in tp ]) particleScores = featureVectors.dot(parameters) bestParticleUsingPrograms = max(zip(particleScores.tolist(),tp))[1] programPredictionCorrect = False if bestParticleUsingPrograms.sequence() == gt: print "Prediction using the program is correct." programPredictionCorrect = True programAccuracy += 1 else: print "Prediction using the program is incorrect." oldPredictionCorrect = tp[0].sequence() == gt print "Was the old prediction correct?",oldPredictionCorrect oldAccuracy += int(oldPredictionCorrect) visualization = np.zeros((256,256*3)) visualization[:,:256] = 1 - frameImageNicely(loadImage('drawings/expert-%d.png'%j)) visualization[:,256:(256*2)] = frameImageNicely(fastRender(tp[0].sequence())) visualization[:,(256*2):(256*3)] = frameImageNicely(fastRender(bestParticleUsingPrograms.sequence())) visualization[:,256] = 0.5 visualization[:,256*2] = 0.5 visualization = 255*visualization if not oldPredictionCorrect and programPredictionCorrect: fp = "../TikZpaper/figures/programSuccess%d.png"%j print "Great success! see %s"%fp saveMatrixAsImage(visualization,fp) if oldPredictionCorrect and not programPredictionCorrect: print "Minor setback!" print particleScores print programAccuracy,"vs",oldAccuracy def induceAbstractions(): results = pickle.load(open(arguments.name,'rb')) print " [+] Loaded %d synthesis results from %s."%(len(results),arguments.name) def getProgram(index): for r in results: if r.originalDrawing == 'drawings/expert-%d.png'%index: if r.source == None: return None return parseSketchOutput(r.source) return None abstractions = [] for i in range(100): p1 = getProgram(i) if p1 == None: print "No synthesis result for %d"%i continue print "Trying to induce abstractions using:" print p1.pretty() for j in range(i+1,100): p2 = getProgram(j) if p2 == None: continue try: a,e = p1.abstract(p2,Environment()) print "SUCCESS:" print p2.pretty() print a.pretty() abstractions.append((i,j,a,e)) except AbstractionFailure: pass abstractionMatrix = [] for i,j,a,e in abstractions: p = a.pretty() if 'for ' in p: print p,"\n" firstProgram = a.substitute(e.firstInstantiation()).convertToSequence() secondProgram = a.substitute(e.secondInstantiation()).convertToSequence() allowUnattached = firstProgram.haveUnattachedLines() or secondProgram.haveUnattachedLines() samples = [] desiredNumberOfSamples = 20 samplingAttempts = 0 while len(samples) < desiredNumberOfSamples and samplingAttempts < 10000: samplingAttempts += 1 concrete = a.substitute(e.randomInstantiation()).convertToSequence() if (not concrete.hasCollisions()\ and (allowUnattached or (not concrete.haveUnattachedLines())))\ or samplingAttempts > 90000: (x0,y0,_,_) = concrete.extent() concrete = concrete.translate(-x0 + 1,-y0 + 1) try: samples.append(concrete.draw()) except ZeroDivisionError: pass samples += [np.zeros((256,256)) + 0.5]*(desiredNumberOfSamples - len(samples)) samples = [1 - loadExpert(i),1 - loadExpert(j)] + samples print firstProgram print firstProgram.haveUnattachedLines() print i print secondProgram print secondProgram.haveUnattachedLines() print j showImage(np.concatenate([firstProgram.draw(),secondProgram.draw()],axis = 1)) abstractionMatrix.append(np.concatenate(samples,axis = 1)) #.showImage(np.concatenate(abstractionMatrix,axis = 0),) saveMatrixAsImage(255*np.concatenate(abstractionMatrix,axis = 0),'abstractions.png') def analyzeSynthesisTime(): results = pickle.load(open(arguments.name,'rb')) print " [+] Loaded %d synthesis results from %s."%(len(results),arguments.name) times = [] traceSizes = [] programSizes = [] for r in results: if not hasattr(r,'time'): print "missing time attribute...",r,r.__class__.__name__ continue if isinstance(r.time,list): times.append(sum(r.time)) else: times.append(r.time) traceSizes.append(len(r.parse.lines)) programSizes.append(r.cost) successfulResults = set([r.originalDrawing for r in results if hasattr(r,'time') ]) print set(['drawings/expert-%d.png'%j for j in range(100) ]) - successfulResults plot.subplot(211) plot.title(arguments.name) plot.scatter([c for c,t in zip(programSizes,times) if programSizes ], [t for c,t in zip(programSizes,times) if programSizes ]) plot.xlabel('program cost') plot.ylabel('synthesis time in seconds') plot.gca().set_yscale('log') plot.subplot(212) plot.scatter(traceSizes,times) plot.xlabel('# of primitives in image') plot.ylabel('synthesis time in seconds') plot.gca().set_yscale('log') plot.show() if __name__ == '__main__': parser = argparse.ArgumentParser(description = 'Synthesis of high-level code from low-level parses') parser.add_argument('-f', '--file', default = None) parser.add_argument('-m', '--cores', default = 1, type = int) parser.add_argument('--parallelSolving', default = 1, type = int) parser.add_argument('-n', '--name', default = "groundTruthSynthesisResults.p", type = str) parser.add_argument('-v', '--view', default = False, action = 'store_true') parser.add_argument('--latex', default = False, action = 'store_true') parser.add_argument('-k','--synthesizeTopK', default = None,type = int) parser.add_argument('-e','--extrapolate', default = False, action = 'store_true') parser.add_argument('--noPrior', default = False, action = 'store_true') parser.add_argument('--debug', default = False, action = 'store_true') parser.add_argument('--similarity', default = False, action = 'store_true') parser.add_argument('--learnToRank', default = None, type = int) parser.add_argument('--incremental', default = False, action = 'store_true') parser.add_argument('--abstract', default = False, action = 'store_true') parser.add_argument('--timeout', default = 60, type = int) parser.add_argument('--analyzeSynthesisTime', action = 'store_true') parser.add_argument('--makePolicyTrainingData', action = 'store_true') arguments = parser.parse_args() if arguments.view: viewSynthesisResults(arguments) elif arguments.makePolicyTrainingData: makePolicyTrainingData() elif arguments.analyzeSynthesisTime: analyzeSynthesisTime() elif arguments.learnToRank != None: rankUsingPrograms() elif arguments.abstract: induceAbstractions() elif arguments.synthesizeTopK != None: synthesizeTopK(arguments.synthesizeTopK) elif arguments.file != None: if "drawings/expert-%s.png"%(arguments.file) in groundTruthSequence: j = SynthesisJob(groundTruthSequence["drawings/expert-%s.png"%(arguments.file)],'', usePrior = not arguments.noPrior, incremental = arguments.incremental) print j s = j.execute() if arguments.incremental: print "Sketch output for each job:" for o in s.source: print o print str(parseSketchOutput(o)) print print "Pretty printed merged output:" print s.program.pretty() else: print "Parsed sketch output:" print str(parseSketchOutput(s.source)) print s.time,'sec' else: j = SynthesisJob(pickle.load(open(arguments.file,'rb')).program,'', usePrior = not arguments.noPrior, incremental = arguments.incremental) print j r = j.execute(timeout = arguments.timeout,parallelSolving = arguments.parallelSolving) print "Synthesis time:",r.time print "Program:" print r.program.pretty()
gpl-3.0
oemof/examples
oemof_examples/oemof.solph/v0.2.x/storage_investment/v1_invest_optimize_all_technologies.py
2
6732
# -*- coding: utf-8 -*- """ General description ------------------- This example shows how to perform a capacity optimization for an energy system with storage. The following energy system is modeled: input/output bgas bel | | | | | | | | wind(FixedSource) |------------------>| | | | | | pv(FixedSource) |------------------>| | | | | | gas_resource |--------->| | | (Commodity) | | | | | | | | demand(Sink) |<------------------| | | | | | | | | | pp_gas(Transformer) |<---------| | | |------------------>| | | | | | storage(Storage) |<------------------| | |------------------>| | The example exists in four variations. The following parameters describe the main setting for the optimization variation 1: - optimize wind, pv, gas_resource and storage - set investment cost for wind, pv and storage - set gas price for kWh Results show an installation of wind and the use of the gas resource. A renewable energy share of 51% is achieved. Have a look at different parameter settings. There are four variations of this example in the same folder. Data ---- storage_investment.csv Installation requirements ------------------------- This example requires oemof v0.2.3 Install by: pip install oemof """ ############################################################################### # Imports ############################################################################### # Default logger of oemof from oemof.tools import logger from oemof.tools import economics import oemof.solph as solph from oemof.outputlib import processing, views import logging import os import pandas as pd import pprint as pp number_timesteps = 8760 ########################################################################## # Initialize the energy system and read/calculate necessary parameters ########################################################################## logger.define_logging() logging.info('Initialize the energy system') date_time_index = pd.date_range('1/1/2012', periods=number_timesteps, freq='H') energysystem = solph.EnergySystem(timeindex=date_time_index) # Read data file full_filename = os.path.join(os.path.dirname(__file__), 'storage_investment.csv') data = pd.read_csv(full_filename, sep=",") price_gas = 0.04 # If the period is one year the equivalent periodical costs (epc) of an # investment are equal to the annuity. Use oemof's economic tools. epc_wind = economics.annuity(capex=1000, n=20, wacc=0.05) epc_pv = economics.annuity(capex=1000, n=20, wacc=0.05) epc_storage = economics.annuity(capex=1000, n=20, wacc=0.05) ########################################################################## # Create oemof objects ########################################################################## logging.info('Create oemof objects') # create natural gas bus bgas = solph.Bus(label="natural_gas") # create electricity bus bel = solph.Bus(label="electricity") energysystem.add(bgas, bel) # create excess component for the electricity bus to allow overproduction excess = solph.Sink(label='excess_bel', inputs={bel: solph.Flow()}) # create source object representing the natural gas commodity (annual limit) gas_resource = solph.Source(label='rgas', outputs={bgas: solph.Flow( variable_costs=price_gas)}) # create fixed source object representing wind power plants wind = solph.Source(label='wind', outputs={bel: solph.Flow( actual_value=data['wind'], fixed=True, investment=solph.Investment(ep_costs=epc_wind))}) # create fixed source object representing pv power plants pv = solph.Source(label='pv', outputs={bel: solph.Flow( actual_value=data['pv'], fixed=True, investment=solph.Investment(ep_costs=epc_pv))}) # create simple sink object representing the electrical demand demand = solph.Sink(label='demand', inputs={bel: solph.Flow( actual_value=data['demand_el'], fixed=True, nominal_value=1)}) # create simple transformer object representing a gas power plant pp_gas = solph.Transformer( label="pp_gas", inputs={bgas: solph.Flow()}, outputs={bel: solph.Flow(nominal_value=10e10, variable_costs=0)}, conversion_factors={bel: 0.58}) # create storage object representing a battery storage = solph.components.GenericStorage( label='storage', inputs={bel: solph.Flow(variable_costs=0.0001)}, outputs={bel: solph.Flow()}, capacity_loss=0.00, initial_capacity=0, invest_relation_input_capacity=1/6, invest_relation_output_capacity=1/6, inflow_conversion_factor=1, outflow_conversion_factor=0.8, investment=solph.Investment(ep_costs=epc_storage), ) energysystem.add(excess, gas_resource, wind, pv, demand, pp_gas, storage) ########################################################################## # Optimise the energy system ########################################################################## logging.info('Optimise the energy system') # initialise the operational model om = solph.Model(energysystem) # if tee_switch is true solver messages will be displayed logging.info('Solve the optimization problem') om.solve(solver='cbc', solve_kwargs={'tee': True}) ########################################################################## # Check and plot the results ########################################################################## # check if the new result object is working for custom components results = processing.results(om) custom_storage = views.node(results, 'storage') electricity_bus = views.node(results, 'electricity') meta_results = processing.meta_results(om) pp.pprint(meta_results) my_results = electricity_bus['scalars'] # installed capacity of storage in GWh my_results['storage_invest_GWh'] = (results[(storage, None)] ['scalars']['invest']/1e6) # installed capacity of wind power plant in MW my_results['wind_invest_MW'] = (results[(wind, bel)] ['scalars']['invest']/1e3) # resulting renewable energy share my_results['res_share'] = (1 - results[(pp_gas, bel)] ['sequences'].sum()/results[(bel, demand)] ['sequences'].sum()) pp.pprint(my_results)
gpl-3.0
vossman/ctfeval
appionlib/apCtf/canny.py
1
5510
#!/usr/bin/env python import math import time import numpy import random from scipy import ndimage #from appionlib.apImage import imagefile """ adapted from: http://code.google.com/p/python-for-matlab-users/source/browse/Examples/scipy_canny.py """ #======================= #======================= def getRadialAndAngles(shape): ## create a grid of distance from the center xhalfshape = shape[0]/2.0 x = numpy.arange(-xhalfshape, xhalfshape, 1) + 0.5 yhalfshape = shape[1]/2.0 y = numpy.arange(-yhalfshape, yhalfshape, 1) + 0.5 xx, yy = numpy.meshgrid(x, y) radialsq = xx**2 + yy**2 - 0.5 angles = numpy.arctan2(yy,xx) return radialsq, angles #======================= #======================= def non_maximal_edge_suppresion(mag, orient, minEdgeRadius=20, maxEdgeRadius=None): """ Non Maximal suppression of gradient magnitude and orientation. """ t0 = time.time() ## bin orientations into 4 discrete directions abin = ((orient + math.pi) * 4 / math.pi + 0.5).astype('int') % 4 radialsq, angles = getRadialAndAngles(mag.shape) ### create circular mask if maxEdgeRadius is None: maxEdgeRadiusSq = radialsq[mag.shape[0]/2,mag.shape[0]/10] else: maxEdgeRadiusSq = maxEdgeRadius**2 outermask = numpy.where(radialsq > maxEdgeRadiusSq, False, True) ## probably a bad idea here innermask = numpy.where(radialsq < minEdgeRadius**2, False, True) ### create directional filters to go with offsets horz = numpy.where(numpy.abs(angles) < 3*math.pi/4., numpy.abs(angles), 0) horz = numpy.where(horz > math.pi/4., True, False) vert = -horz upright = numpy.where(angles < math.pi/2, False, True) upleft = numpy.flipud(upright) upleft = numpy.fliplr(upleft) upright = numpy.logical_or(upright, upleft) upleft = -upright # for rotational edges filters = [horz, upleft, vert, upright] # for radial edges #filters = [vert, upright, horz, upleft] offsets = ((1,0), (1,1), (0,1), (-1,1)) edge_map = numpy.zeros(mag.shape, dtype='bool') for a in range(4): di, dj = offsets[a] footprint = numpy.zeros((3,3), dtype="int") footprint[1,1] = 0 footprint[1+di,1+dj] = 1 footprint[1-di,1-dj] = 1 ## get adjacent maximums maxfilt = ndimage.maximum_filter(mag, footprint=footprint) ## select points larger than adjacent maximums newedge_map = numpy.where(mag>maxfilt, True, False) ## filter by edge orientation newedge_map = numpy.where(abin==a, newedge_map, False) ## filter by location newedge_map = numpy.where(filters[a], newedge_map, False) ## add to main map edge_map = numpy.where(newedge_map, True, edge_map) ## remove corner edges edge_map = numpy.where(outermask, edge_map, False) edge_map = numpy.where(innermask, edge_map, False) #print time.time() - t0 return edge_map #======================= #======================= def canny_edges(image, minedges=5000, maxedges=15000, low_thresh=50, minEdgeRadius=20, maxEdgeRadius=None): """ Compute Canny edge detection on an image """ t0 = time.time() dx = ndimage.sobel(image,0) dy = ndimage.sobel(image,1) mag = numpy.hypot(dx, dy) mag = mag / mag.max() ort = numpy.arctan2(dy, dx) edge_map = non_maximal_edge_suppresion(mag, ort, minEdgeRadius, maxEdgeRadius) edge_map = numpy.logical_and(edge_map, mag > low_thresh) labels, numlabels = ndimage.measurements.label(edge_map, numpy.ones((3,3))) #print "labels", len(labels) #print maxs maxs = ndimage.measurements.maximum(mag, labels, range(1,numlabels+1)) maxs = numpy.array(maxs, dtype=numpy.float64) high_thresh = maxs.mean() minThresh = maxs.min() #print time.time() - t0 edge_count = edge_map.sum() count = 0 while count < 25: t0 = time.time() count += 1 maxs = ndimage.measurements.maximum(mag, labels, range(1,numlabels+1)) maxs = numpy.array(maxs, dtype=numpy.float64) good_label = (maxs > high_thresh) good_label = numpy.append([False, ], good_label) numgood = good_label.sum() if numgood == numlabels and high_thresh > minThresh: print "ERROR" maxs.sort() print high_thresh print maxs[:3], maxs[-3:] print maxs[0], ">", high_thresh, "=", maxs[0] > high_thresh good_label = numpy.zeros((numlabels+1,), dtype=numpy.bool) good_label[1:] = maxs > high_thresh print good_label[:3], good_label[-3:] time.sleep(10) newedge_map = good_label[labels] #for i in range(len(maxs)): # #if max(mag[labels==i]) < high_thresh: # if maxs[i] < high_thresh: # edge_map[labels==i] = False edge_count = newedge_map.sum() print "canny edges=%d, (thresh=%.3f) time=%.6f"%(edge_count, high_thresh, time.time() - t0) if edge_count > maxedges: rand = math.sqrt(random.random()) new_thresh = high_thresh / rand # fix for too large values #print rand, new_thresh if new_thresh < 1.0: high_thresh = new_thresh else: high_thresh = math.sqrt(high_thresh) elif edge_count < minedges and high_thresh > minThresh: rand = math.sqrt(random.random()) new_thresh = high_thresh * rand #print rand, new_thresh, minThresh high_thresh = new_thresh else: break #print time.time() - t0 return newedge_map #======================= #======================= #======================= #======================= if __name__ == "__main__": from scipy.misc import lena from matplotlib import pyplot lena = lena() image = ndimage.filters.gaussian_filter(lena, 6) edgeimage = canny_edges(image, minedges=2500, maxedges=15000, low_thresh=0.001, minEdgeRadius=20, maxEdgeRadius=None) pyplot.imshow(edgeimage) pyplot.gray() pyplot.show()
apache-2.0
AIML/scikit-learn
examples/decomposition/plot_pca_iris.py
253
1801
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= PCA example with Iris Data-set ========================================================= Principal Component Analysis applied to the Iris dataset. See `here <http://en.wikipedia.org/wiki/Iris_flower_data_set>`_ for more information on this dataset. """ print(__doc__) # Code source: Gaël Varoquaux # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import decomposition from sklearn import datasets np.random.seed(5) centers = [[1, 1], [-1, -1], [1, -1]] iris = datasets.load_iris() X = iris.data y = iris.target fig = plt.figure(1, figsize=(4, 3)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) plt.cla() pca = decomposition.PCA(n_components=3) pca.fit(X) X = pca.transform(X) for name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]: ax.text3D(X[y == label, 0].mean(), X[y == label, 1].mean() + 1.5, X[y == label, 2].mean(), name, horizontalalignment='center', bbox=dict(alpha=.5, edgecolor='w', facecolor='w')) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(np.float) ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=plt.cm.spectral) x_surf = [X[:, 0].min(), X[:, 0].max(), X[:, 0].min(), X[:, 0].max()] y_surf = [X[:, 0].max(), X[:, 0].max(), X[:, 0].min(), X[:, 0].min()] x_surf = np.array(x_surf) y_surf = np.array(y_surf) v0 = pca.transform(pca.components_[0]) v0 /= v0[-1] v1 = pca.transform(pca.components_[1]) v1 /= v1[-1] ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) plt.show()
bsd-3-clause
gclenaghan/scikit-learn
sklearn/feature_extraction/dict_vectorizer.py
234
12267
# Authors: Lars Buitinck # Dan Blanchard <[email protected]> # License: BSD 3 clause from array import array from collections import Mapping from operator import itemgetter import numpy as np import scipy.sparse as sp from ..base import BaseEstimator, TransformerMixin from ..externals import six from ..externals.six.moves import xrange from ..utils import check_array, tosequence from ..utils.fixes import frombuffer_empty def _tosequence(X): """Turn X into a sequence or ndarray, avoiding a copy if possible.""" if isinstance(X, Mapping): # single sample return [X] else: return tosequence(X) class DictVectorizer(BaseEstimator, TransformerMixin): """Transforms lists of feature-value mappings to vectors. This transformer turns lists of mappings (dict-like objects) of feature names to feature values into Numpy arrays or scipy.sparse matrices for use with scikit-learn estimators. When feature values are strings, this transformer will do a binary one-hot (aka one-of-K) coding: one boolean-valued feature is constructed for each of the possible string values that the feature can take on. For instance, a feature "f" that can take on the values "ham" and "spam" will become two features in the output, one signifying "f=ham", the other "f=spam". Features that do not occur in a sample (mapping) will have a zero value in the resulting array/matrix. Read more in the :ref:`User Guide <dict_feature_extraction>`. Parameters ---------- dtype : callable, optional The type of feature values. Passed to Numpy array/scipy.sparse matrix constructors as the dtype argument. separator: string, optional Separator string used when constructing new features for one-hot coding. sparse: boolean, optional. Whether transform should produce scipy.sparse matrices. True by default. sort: boolean, optional. Whether ``feature_names_`` and ``vocabulary_`` should be sorted when fitting. True by default. Attributes ---------- vocabulary_ : dict A dictionary mapping feature names to feature indices. feature_names_ : list A list of length n_features containing the feature names (e.g., "f=ham" and "f=spam"). Examples -------- >>> from sklearn.feature_extraction import DictVectorizer >>> v = DictVectorizer(sparse=False) >>> D = [{'foo': 1, 'bar': 2}, {'foo': 3, 'baz': 1}] >>> X = v.fit_transform(D) >>> X array([[ 2., 0., 1.], [ 0., 1., 3.]]) >>> v.inverse_transform(X) == \ [{'bar': 2.0, 'foo': 1.0}, {'baz': 1.0, 'foo': 3.0}] True >>> v.transform({'foo': 4, 'unseen_feature': 3}) array([[ 0., 0., 4.]]) See also -------- FeatureHasher : performs vectorization using only a hash function. sklearn.preprocessing.OneHotEncoder : handles nominal/categorical features encoded as columns of integers. """ def __init__(self, dtype=np.float64, separator="=", sparse=True, sort=True): self.dtype = dtype self.separator = separator self.sparse = sparse self.sort = sort def fit(self, X, y=None): """Learn a list of feature name -> indices mappings. Parameters ---------- X : Mapping or iterable over Mappings Dict(s) or Mapping(s) from feature names (arbitrary Python objects) to feature values (strings or convertible to dtype). y : (ignored) Returns ------- self """ feature_names = [] vocab = {} for x in X: for f, v in six.iteritems(x): if isinstance(v, six.string_types): f = "%s%s%s" % (f, self.separator, v) if f not in vocab: feature_names.append(f) vocab[f] = len(vocab) if self.sort: feature_names.sort() vocab = dict((f, i) for i, f in enumerate(feature_names)) self.feature_names_ = feature_names self.vocabulary_ = vocab return self def _transform(self, X, fitting): # Sanity check: Python's array has no way of explicitly requesting the # signed 32-bit integers that scipy.sparse needs, so we use the next # best thing: typecode "i" (int). However, if that gives larger or # smaller integers than 32-bit ones, np.frombuffer screws up. assert array("i").itemsize == 4, ( "sizeof(int) != 4 on your platform; please report this at" " https://github.com/scikit-learn/scikit-learn/issues and" " include the output from platform.platform() in your bug report") dtype = self.dtype if fitting: feature_names = [] vocab = {} else: feature_names = self.feature_names_ vocab = self.vocabulary_ # Process everything as sparse regardless of setting X = [X] if isinstance(X, Mapping) else X indices = array("i") indptr = array("i", [0]) # XXX we could change values to an array.array as well, but it # would require (heuristic) conversion of dtype to typecode... values = [] # collect all the possible feature names and build sparse matrix at # same time for x in X: for f, v in six.iteritems(x): if isinstance(v, six.string_types): f = "%s%s%s" % (f, self.separator, v) v = 1 if f in vocab: indices.append(vocab[f]) values.append(dtype(v)) else: if fitting: feature_names.append(f) vocab[f] = len(vocab) indices.append(vocab[f]) values.append(dtype(v)) indptr.append(len(indices)) if len(indptr) == 1: raise ValueError("Sample sequence X is empty.") indices = frombuffer_empty(indices, dtype=np.intc) indptr = np.frombuffer(indptr, dtype=np.intc) shape = (len(indptr) - 1, len(vocab)) result_matrix = sp.csr_matrix((values, indices, indptr), shape=shape, dtype=dtype) # Sort everything if asked if fitting and self.sort: feature_names.sort() map_index = np.empty(len(feature_names), dtype=np.int32) for new_val, f in enumerate(feature_names): map_index[new_val] = vocab[f] vocab[f] = new_val result_matrix = result_matrix[:, map_index] if self.sparse: result_matrix.sort_indices() else: result_matrix = result_matrix.toarray() if fitting: self.feature_names_ = feature_names self.vocabulary_ = vocab return result_matrix def fit_transform(self, X, y=None): """Learn a list of feature name -> indices mappings and transform X. Like fit(X) followed by transform(X), but does not require materializing X in memory. Parameters ---------- X : Mapping or iterable over Mappings Dict(s) or Mapping(s) from feature names (arbitrary Python objects) to feature values (strings or convertible to dtype). y : (ignored) Returns ------- Xa : {array, sparse matrix} Feature vectors; always 2-d. """ return self._transform(X, fitting=True) def inverse_transform(self, X, dict_type=dict): """Transform array or sparse matrix X back to feature mappings. X must have been produced by this DictVectorizer's transform or fit_transform method; it may only have passed through transformers that preserve the number of features and their order. In the case of one-hot/one-of-K coding, the constructed feature names and values are returned rather than the original ones. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Sample matrix. dict_type : callable, optional Constructor for feature mappings. Must conform to the collections.Mapping API. Returns ------- D : list of dict_type objects, length = n_samples Feature mappings for the samples in X. """ # COO matrix is not subscriptable X = check_array(X, accept_sparse=['csr', 'csc']) n_samples = X.shape[0] names = self.feature_names_ dicts = [dict_type() for _ in xrange(n_samples)] if sp.issparse(X): for i, j in zip(*X.nonzero()): dicts[i][names[j]] = X[i, j] else: for i, d in enumerate(dicts): for j, v in enumerate(X[i, :]): if v != 0: d[names[j]] = X[i, j] return dicts def transform(self, X, y=None): """Transform feature->value dicts to array or sparse matrix. Named features not encountered during fit or fit_transform will be silently ignored. Parameters ---------- X : Mapping or iterable over Mappings, length = n_samples Dict(s) or Mapping(s) from feature names (arbitrary Python objects) to feature values (strings or convertible to dtype). y : (ignored) Returns ------- Xa : {array, sparse matrix} Feature vectors; always 2-d. """ if self.sparse: return self._transform(X, fitting=False) else: dtype = self.dtype vocab = self.vocabulary_ X = _tosequence(X) Xa = np.zeros((len(X), len(vocab)), dtype=dtype) for i, x in enumerate(X): for f, v in six.iteritems(x): if isinstance(v, six.string_types): f = "%s%s%s" % (f, self.separator, v) v = 1 try: Xa[i, vocab[f]] = dtype(v) except KeyError: pass return Xa def get_feature_names(self): """Returns a list of feature names, ordered by their indices. If one-of-K coding is applied to categorical features, this will include the constructed feature names but not the original ones. """ return self.feature_names_ def restrict(self, support, indices=False): """Restrict the features to those in support using feature selection. This function modifies the estimator in-place. Parameters ---------- support : array-like Boolean mask or list of indices (as returned by the get_support member of feature selectors). indices : boolean, optional Whether support is a list of indices. Returns ------- self Examples -------- >>> from sklearn.feature_extraction import DictVectorizer >>> from sklearn.feature_selection import SelectKBest, chi2 >>> v = DictVectorizer() >>> D = [{'foo': 1, 'bar': 2}, {'foo': 3, 'baz': 1}] >>> X = v.fit_transform(D) >>> support = SelectKBest(chi2, k=2).fit(X, [0, 1]) >>> v.get_feature_names() ['bar', 'baz', 'foo'] >>> v.restrict(support.get_support()) # doctest: +ELLIPSIS DictVectorizer(dtype=..., separator='=', sort=True, sparse=True) >>> v.get_feature_names() ['bar', 'foo'] """ if not indices: support = np.where(support)[0] names = self.feature_names_ new_vocab = {} for i in support: new_vocab[names[i]] = len(new_vocab) self.vocabulary_ = new_vocab self.feature_names_ = [f for f, i in sorted(six.iteritems(new_vocab), key=itemgetter(1))] return self
bsd-3-clause
pprett/scikit-learn
sklearn/utils/validation.py
8
26078
"""Utilities for input validation""" # Authors: Olivier Grisel # Gael Varoquaux # Andreas Mueller # Lars Buitinck # Alexandre Gramfort # Nicolas Tresegnie # License: BSD 3 clause import warnings import numbers import numpy as np import scipy.sparse as sp from ..externals import six from ..utils.fixes import signature from ..exceptions import NonBLASDotWarning from ..exceptions import NotFittedError from ..exceptions import DataConversionWarning FLOAT_DTYPES = (np.float64, np.float32, np.float16) # Silenced by default to reduce verbosity. Turn on at runtime for # performance profiling. warnings.simplefilter('ignore', NonBLASDotWarning) def _assert_all_finite(X): """Like assert_all_finite, but only for ndarray.""" X = np.asanyarray(X) # First try an O(n) time, O(1) space solution for the common case that # everything is finite; fall back to O(n) space np.isfinite to prevent # false positives from overflow in sum method. if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum()) and not np.isfinite(X).all()): raise ValueError("Input contains NaN, infinity" " or a value too large for %r." % X.dtype) def assert_all_finite(X): """Throw a ValueError if X contains NaN or infinity. Input MUST be an np.ndarray instance or a scipy.sparse matrix.""" _assert_all_finite(X.data if sp.issparse(X) else X) def as_float_array(X, copy=True, force_all_finite=True): """Converts an array-like to an array of floats The new dtype will be np.float32 or np.float64, depending on the original type. The function can create a copy or modify the argument depending on the argument copy. Parameters ---------- X : {array-like, sparse matrix} copy : bool, optional If True, a copy of X will be created. If False, a copy may still be returned if X's dtype is not a floating point type. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. Returns ------- XT : {array, sparse matrix} An array of type np.float """ if isinstance(X, np.matrix) or (not isinstance(X, np.ndarray) and not sp.issparse(X)): return check_array(X, ['csr', 'csc', 'coo'], dtype=np.float64, copy=copy, force_all_finite=force_all_finite, ensure_2d=False) elif sp.issparse(X) and X.dtype in [np.float32, np.float64]: return X.copy() if copy else X elif X.dtype in [np.float32, np.float64]: # is numpy array return X.copy('F' if X.flags['F_CONTIGUOUS'] else 'C') if copy else X else: if X.dtype.kind in 'uib' and X.dtype.itemsize <= 4: return_dtype = np.float32 else: return_dtype = np.float64 return X.astype(return_dtype) def _is_arraylike(x): """Returns whether the input is array-like""" return (hasattr(x, '__len__') or hasattr(x, 'shape') or hasattr(x, '__array__')) def _num_samples(x): """Return number of samples in array-like x.""" if hasattr(x, 'fit') and callable(x.fit): # Don't get num_samples from an ensembles length! raise TypeError('Expected sequence or array-like, got ' 'estimator %s' % x) if not hasattr(x, '__len__') and not hasattr(x, 'shape'): if hasattr(x, '__array__'): x = np.asarray(x) else: raise TypeError("Expected sequence or array-like, got %s" % type(x)) if hasattr(x, 'shape'): if len(x.shape) == 0: raise TypeError("Singleton array %r cannot be considered" " a valid collection." % x) return x.shape[0] else: return len(x) def _shape_repr(shape): """Return a platform independent representation of an array shape Under Python 2, the `long` type introduces an 'L' suffix when using the default %r format for tuples of integers (typically used to store the shape of an array). Under Windows 64 bit (and Python 2), the `long` type is used by default in numpy shapes even when the integer dimensions are well below 32 bit. The platform specific type causes string messages or doctests to change from one platform to another which is not desirable. Under Python 3, there is no more `long` type so the `L` suffix is never introduced in string representation. >>> _shape_repr((1, 2)) '(1, 2)' >>> one = 2 ** 64 / 2 ** 64 # force an upcast to `long` under Python 2 >>> _shape_repr((one, 2 * one)) '(1, 2)' >>> _shape_repr((1,)) '(1,)' >>> _shape_repr(()) '()' """ if len(shape) == 0: return "()" joined = ", ".join("%d" % e for e in shape) if len(shape) == 1: # special notation for singleton tuples joined += ',' return "(%s)" % joined def check_consistent_length(*arrays): """Check that all arrays have consistent first dimensions. Checks whether all objects in arrays have the same shape or length. Parameters ---------- *arrays : list or tuple of input objects. Objects that will be checked for consistent length. """ lengths = [_num_samples(X) for X in arrays if X is not None] uniques = np.unique(lengths) if len(uniques) > 1: raise ValueError("Found input variables with inconsistent numbers of" " samples: %r" % [int(l) for l in lengths]) def indexable(*iterables): """Make arrays indexable for cross-validation. Checks consistent length, passes through None, and ensures that everything can be indexed by converting sparse matrices to csr and converting non-interable objects to arrays. Parameters ---------- *iterables : lists, dataframes, arrays, sparse matrices List of objects to ensure sliceability. """ result = [] for X in iterables: if sp.issparse(X): result.append(X.tocsr()) elif hasattr(X, "__getitem__") or hasattr(X, "iloc"): result.append(X) elif X is None: result.append(X) else: result.append(np.array(X)) check_consistent_length(*result) return result def _ensure_sparse_format(spmatrix, accept_sparse, dtype, copy, force_all_finite): """Convert a sparse matrix to a given format. Checks the sparse format of spmatrix and converts if necessary. Parameters ---------- spmatrix : scipy sparse matrix Input to validate and convert. accept_sparse : string, boolean or list/tuple of strings String[s] representing allowed sparse matrix formats ('csc', 'csr', 'coo', 'dok', 'bsr', 'lil', 'dia'). If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error. dtype : string, type or None Data type of result. If None, the dtype of the input is preserved. copy : boolean Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean Whether to raise an error on np.inf and np.nan in X. Returns ------- spmatrix_converted : scipy sparse matrix. Matrix that is ensured to have an allowed type. """ if dtype is None: dtype = spmatrix.dtype changed_format = False if isinstance(accept_sparse, six.string_types): accept_sparse = [accept_sparse] if accept_sparse is False: raise TypeError('A sparse matrix was passed, but dense ' 'data is required. Use X.toarray() to ' 'convert to a dense numpy array.') elif isinstance(accept_sparse, (list, tuple)): if len(accept_sparse) == 0: raise ValueError("When providing 'accept_sparse' " "as a tuple or list, it must contain at " "least one string value.") # ensure correct sparse format if spmatrix.format not in accept_sparse: # create new with correct sparse spmatrix = spmatrix.asformat(accept_sparse[0]) changed_format = True elif accept_sparse is not True: # any other type raise ValueError("Parameter 'accept_sparse' should be a string, " "boolean or list of strings. You provided " "'accept_sparse={}'.".format(accept_sparse)) if dtype != spmatrix.dtype: # convert dtype spmatrix = spmatrix.astype(dtype) elif copy and not changed_format: # force copy spmatrix = spmatrix.copy() if force_all_finite: if not hasattr(spmatrix, "data"): warnings.warn("Can't check %s sparse matrix for nan or inf." % spmatrix.format) else: _assert_all_finite(spmatrix.data) return spmatrix def check_array(array, accept_sparse=False, dtype="numeric", order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False, ensure_min_samples=1, ensure_min_features=1, warn_on_dtype=False, estimator=None): """Input validation on an array, list, sparse matrix or similar. By default, the input is converted to an at least 2D numpy array. If the dtype of the array is object, attempt converting to float, raising on failure. Parameters ---------- array : object Input object to check / convert. accept_sparse : string, boolean or list/tuple of strings (default=False) String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error. dtype : string, type, list of types or None (default="numeric") Data type of result. If None, the dtype of the input is preserved. If "numeric", dtype is preserved unless array.dtype is object. If dtype is a list of types, conversion on the first type is only performed if the dtype of the input is not in the list. order : 'F', 'C' or None (default=None) Whether an array will be forced to be fortran or c-style. When order is None (default), then if copy=False, nothing is ensured about the memory layout of the output array; otherwise (copy=True) the memory layout of the returned array is kept as close as possible to the original array. copy : boolean (default=False) Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. ensure_2d : boolean (default=True) Whether to raise a value error if X is not 2d. allow_nd : boolean (default=False) Whether to allow X.ndim > 2. ensure_min_samples : int (default=1) Make sure that the array has a minimum number of samples in its first axis (rows for a 2D array). Setting to 0 disables this check. ensure_min_features : int (default=1) Make sure that the 2D array has some minimum number of features (columns). The default value of 1 rejects empty datasets. This check is only enforced when the input data has effectively 2 dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0 disables this check. warn_on_dtype : boolean (default=False) Raise DataConversionWarning if the dtype of the input data structure does not match the requested dtype, causing a memory copy. estimator : str or estimator instance (default=None) If passed, include the name of the estimator in warning messages. Returns ------- X_converted : object The converted and validated X. """ # accept_sparse 'None' deprecation check if accept_sparse is None: warnings.warn( "Passing 'None' to parameter 'accept_sparse' in methods " "check_array and check_X_y is deprecated in version 0.19 " "and will be removed in 0.21. Use 'accept_sparse=False' " " instead.", DeprecationWarning) accept_sparse = False # store whether originally we wanted numeric dtype dtype_numeric = dtype == "numeric" dtype_orig = getattr(array, "dtype", None) if not hasattr(dtype_orig, 'kind'): # not a data type (e.g. a column named dtype in a pandas DataFrame) dtype_orig = None if dtype_numeric: if dtype_orig is not None and dtype_orig.kind == "O": # if input is object, convert to float. dtype = np.float64 else: dtype = None if isinstance(dtype, (list, tuple)): if dtype_orig is not None and dtype_orig in dtype: # no dtype conversion required dtype = None else: # dtype conversion required. Let's select the first element of the # list of accepted types. dtype = dtype[0] if estimator is not None: if isinstance(estimator, six.string_types): estimator_name = estimator else: estimator_name = estimator.__class__.__name__ else: estimator_name = "Estimator" context = " by %s" % estimator_name if estimator is not None else "" if sp.issparse(array): array = _ensure_sparse_format(array, accept_sparse, dtype, copy, force_all_finite) else: array = np.array(array, dtype=dtype, order=order, copy=copy) if ensure_2d: if array.ndim == 1: raise ValueError( "Got X with X.ndim=1. Reshape your data either using " "X.reshape(-1, 1) if your data has a single feature or " "X.reshape(1, -1) if it contains a single sample.") array = np.atleast_2d(array) # To ensure that array flags are maintained array = np.array(array, dtype=dtype, order=order, copy=copy) # make sure we actually converted to numeric: if dtype_numeric and array.dtype.kind == "O": array = array.astype(np.float64) if not allow_nd and array.ndim >= 3: raise ValueError("Found array with dim %d. %s expected <= 2." % (array.ndim, estimator_name)) if force_all_finite: _assert_all_finite(array) shape_repr = _shape_repr(array.shape) if ensure_min_samples > 0: n_samples = _num_samples(array) if n_samples < ensure_min_samples: raise ValueError("Found array with %d sample(s) (shape=%s) while a" " minimum of %d is required%s." % (n_samples, shape_repr, ensure_min_samples, context)) if ensure_min_features > 0 and array.ndim == 2: n_features = array.shape[1] if n_features < ensure_min_features: raise ValueError("Found array with %d feature(s) (shape=%s) while" " a minimum of %d is required%s." % (n_features, shape_repr, ensure_min_features, context)) if warn_on_dtype and dtype_orig is not None and array.dtype != dtype_orig: msg = ("Data with input dtype %s was converted to %s%s." % (dtype_orig, array.dtype, context)) warnings.warn(msg, DataConversionWarning) return array def check_X_y(X, y, accept_sparse=False, dtype="numeric", order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False, multi_output=False, ensure_min_samples=1, ensure_min_features=1, y_numeric=False, warn_on_dtype=False, estimator=None): """Input validation for standard estimators. Checks X and y for consistent length, enforces X 2d and y 1d. Standard input checks are only applied to y, such as checking that y does not have np.nan or np.inf targets. For multi-label y, set multi_output=True to allow 2d and sparse y. If the dtype of X is object, attempt converting to float, raising on failure. Parameters ---------- X : nd-array, list or sparse matrix Input data. y : nd-array, list or sparse matrix Labels. accept_sparse : string, boolean or list of string (default=False) String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error. dtype : string, type, list of types or None (default="numeric") Data type of result. If None, the dtype of the input is preserved. If "numeric", dtype is preserved unless array.dtype is object. If dtype is a list of types, conversion on the first type is only performed if the dtype of the input is not in the list. order : 'F', 'C' or None (default=None) Whether an array will be forced to be fortran or c-style. copy : boolean (default=False) Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. This parameter does not influence whether y can have np.inf or np.nan values. ensure_2d : boolean (default=True) Whether to make X at least 2d. allow_nd : boolean (default=False) Whether to allow X.ndim > 2. multi_output : boolean (default=False) Whether to allow 2-d y (array or sparse matrix). If false, y will be validated as a vector. y cannot have np.nan or np.inf values if multi_output=True. ensure_min_samples : int (default=1) Make sure that X has a minimum number of samples in its first axis (rows for a 2D array). ensure_min_features : int (default=1) Make sure that the 2D array has some minimum number of features (columns). The default value of 1 rejects empty datasets. This check is only enforced when X has effectively 2 dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0 disables this check. y_numeric : boolean (default=False) Whether to ensure that y has a numeric type. If dtype of y is object, it is converted to float64. Should only be used for regression algorithms. warn_on_dtype : boolean (default=False) Raise DataConversionWarning if the dtype of the input data structure does not match the requested dtype, causing a memory copy. estimator : str or estimator instance (default=None) If passed, include the name of the estimator in warning messages. Returns ------- X_converted : object The converted and validated X. y_converted : object The converted and validated y. """ X = check_array(X, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator) if multi_output: y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False, dtype=None) else: y = column_or_1d(y, warn=True) _assert_all_finite(y) if y_numeric and y.dtype.kind == 'O': y = y.astype(np.float64) check_consistent_length(X, y) return X, y def column_or_1d(y, warn=False): """ Ravel column or 1d numpy array, else raises an error Parameters ---------- y : array-like warn : boolean, default False To control display of warnings. Returns ------- y : array """ shape = np.shape(y) if len(shape) == 1: return np.ravel(y) if len(shape) == 2 and shape[1] == 1: if warn: warnings.warn("A column-vector y was passed when a 1d array was" " expected. Please change the shape of y to " "(n_samples, ), for example using ravel().", DataConversionWarning, stacklevel=2) return np.ravel(y) raise ValueError("bad input shape {0}".format(shape)) def check_random_state(seed): """Turn seed into a np.random.RandomState instance If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. If seed is already a RandomState instance, return it. Otherwise raise ValueError. """ if seed is None or seed is np.random: return np.random.mtrand._rand if isinstance(seed, (numbers.Integral, np.integer)): return np.random.RandomState(seed) if isinstance(seed, np.random.RandomState): return seed raise ValueError('%r cannot be used to seed a numpy.random.RandomState' ' instance' % seed) def has_fit_parameter(estimator, parameter): """Checks whether the estimator's fit method supports the given parameter. Examples -------- >>> from sklearn.svm import SVC >>> has_fit_parameter(SVC(), "sample_weight") True """ return parameter in signature(estimator.fit).parameters def check_symmetric(array, tol=1E-10, raise_warning=True, raise_exception=False): """Make sure that array is 2D, square and symmetric. If the array is not symmetric, then a symmetrized version is returned. Optionally, a warning or exception is raised if the matrix is not symmetric. Parameters ---------- array : nd-array or sparse matrix Input object to check / convert. Must be two-dimensional and square, otherwise a ValueError will be raised. tol : float Absolute tolerance for equivalence of arrays. Default = 1E-10. raise_warning : boolean (default=True) If True then raise a warning if conversion is required. raise_exception : boolean (default=False) If True then raise an exception if array is not symmetric. Returns ------- array_sym : ndarray or sparse matrix Symmetrized version of the input array, i.e. the average of array and array.transpose(). If sparse, then duplicate entries are first summed and zeros are eliminated. """ if (array.ndim != 2) or (array.shape[0] != array.shape[1]): raise ValueError("array must be 2-dimensional and square. " "shape = {0}".format(array.shape)) if sp.issparse(array): diff = array - array.T # only csr, csc, and coo have `data` attribute if diff.format not in ['csr', 'csc', 'coo']: diff = diff.tocsr() symmetric = np.all(abs(diff.data) < tol) else: symmetric = np.allclose(array, array.T, atol=tol) if not symmetric: if raise_exception: raise ValueError("Array must be symmetric") if raise_warning: warnings.warn("Array is not symmetric, and will be converted " "to symmetric by average with its transpose.") if sp.issparse(array): conversion = 'to' + array.format array = getattr(0.5 * (array + array.T), conversion)() else: array = 0.5 * (array + array.T) return array def check_is_fitted(estimator, attributes, msg=None, all_or_any=all): """Perform is_fitted validation for estimator. Checks if the estimator is fitted by verifying the presence of "all_or_any" of the passed attributes and raises a NotFittedError with the given message. Parameters ---------- estimator : estimator instance. estimator instance for which the check is performed. attributes : attribute name(s) given as string or a list/tuple of strings Eg. : ["coef_", "estimator_", ...], "coef_" msg : string The default error message is, "This %(name)s instance is not fitted yet. Call 'fit' with appropriate arguments before using this method." For custom messages if "%(name)s" is present in the message string, it is substituted for the estimator name. Eg. : "Estimator, %(name)s, must be fitted before sparsifying". all_or_any : callable, {all, any}, default all Specify whether all or any of the given attributes must exist. """ if msg is None: msg = ("This %(name)s instance is not fitted yet. Call 'fit' with " "appropriate arguments before using this method.") if not hasattr(estimator, 'fit'): raise TypeError("%s is not an estimator instance." % (estimator)) if not isinstance(attributes, (list, tuple)): attributes = [attributes] if not all_or_any([hasattr(estimator, attr) for attr in attributes]): raise NotFittedError(msg % {'name': type(estimator).__name__}) def check_non_negative(X, whom): """ Check if there is any negative value in an array. Parameters ---------- X : array-like or sparse matrix Input data. whom : string Who passed X to this function. """ X = X.data if sp.issparse(X) else X if (X < 0).any(): raise ValueError("Negative values in data passed to %s" % whom)
bsd-3-clause
datapythonista/pandas
pandas/tests/dtypes/test_generic.py
6
4327
from warnings import catch_warnings import numpy as np import pytest from pandas.core.dtypes import generic as gt import pandas as pd import pandas._testing as tm class TestABCClasses: tuples = [[1, 2, 2], ["red", "blue", "red"]] multi_index = pd.MultiIndex.from_arrays(tuples, names=("number", "color")) datetime_index = pd.to_datetime(["2000/1/1", "2010/1/1"]) timedelta_index = pd.to_timedelta(np.arange(5), unit="s") period_index = pd.period_range("2000/1/1", "2010/1/1/", freq="M") categorical = pd.Categorical([1, 2, 3], categories=[2, 3, 1]) categorical_df = pd.DataFrame({"values": [1, 2, 3]}, index=categorical) df = pd.DataFrame({"names": ["a", "b", "c"]}, index=multi_index) sparse_array = pd.arrays.SparseArray(np.random.randn(10)) datetime_array = pd.core.arrays.DatetimeArray(datetime_index) timedelta_array = pd.core.arrays.TimedeltaArray(timedelta_index) abc_pairs = [ ("ABCInt64Index", pd.Int64Index([1, 2, 3])), ("ABCUInt64Index", pd.UInt64Index([1, 2, 3])), ("ABCFloat64Index", pd.Float64Index([1, 2, 3])), ("ABCMultiIndex", multi_index), ("ABCDatetimeIndex", datetime_index), ("ABCRangeIndex", pd.RangeIndex(3)), ("ABCTimedeltaIndex", timedelta_index), ("ABCIntervalIndex", pd.interval_range(start=0, end=3)), ("ABCPeriodArray", pd.arrays.PeriodArray([2000, 2001, 2002], freq="D")), ("ABCPandasArray", pd.arrays.PandasArray(np.array([0, 1, 2]))), ("ABCPeriodIndex", period_index), ("ABCCategoricalIndex", categorical_df.index), ("ABCSeries", pd.Series([1, 2, 3])), ("ABCDataFrame", df), ("ABCCategorical", categorical), ("ABCDatetimeArray", datetime_array), ("ABCTimedeltaArray", timedelta_array), ] @pytest.mark.parametrize("abctype1, inst", abc_pairs) @pytest.mark.parametrize("abctype2, _", abc_pairs) def test_abc_pairs(self, abctype1, abctype2, inst, _): # GH 38588 if abctype1 == abctype2: assert isinstance(inst, getattr(gt, abctype2)) else: assert not isinstance(inst, getattr(gt, abctype2)) abc_subclasses = { "ABCIndex": [ abctype for abctype, _ in abc_pairs if "Index" in abctype and abctype != "ABCIndex" ], "ABCNDFrame": ["ABCSeries", "ABCDataFrame"], "ABCExtensionArray": [ "ABCCategorical", "ABCDatetimeArray", "ABCPeriodArray", "ABCTimedeltaArray", ], } @pytest.mark.parametrize("parent, subs", abc_subclasses.items()) @pytest.mark.parametrize("abctype, inst", abc_pairs) def test_abc_hierarchy(self, parent, subs, abctype, inst): # GH 38588 if abctype in subs: assert isinstance(inst, getattr(gt, parent)) else: assert not isinstance(inst, getattr(gt, parent)) @pytest.mark.parametrize("abctype", [e for e in gt.__dict__ if e.startswith("ABC")]) def test_abc_coverage(self, abctype): # GH 38588 assert ( abctype in (e for e, _ in self.abc_pairs) or abctype in self.abc_subclasses ) def test_setattr_warnings(): # GH7175 - GOTCHA: You can't use dot notation to add a column... d = { "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]), "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]), } df = pd.DataFrame(d) with catch_warnings(record=True) as w: # successfully add new column # this should not raise a warning df["three"] = df.two + 1 assert len(w) == 0 assert df.three.sum() > df.two.sum() with catch_warnings(record=True) as w: # successfully modify column in place # this should not raise a warning df.one += 1 assert len(w) == 0 assert df.one.iloc[0] == 2 with catch_warnings(record=True) as w: # successfully add an attribute to a series # this should not raise a warning df.two.not_an_index = [1, 2] assert len(w) == 0 with tm.assert_produces_warning(UserWarning): # warn when setting column to nonexistent name df.four = df.two + 2 assert df.four.sum() > df.two.sum()
bsd-3-clause
juanamari94/mlaas-example
models.py
1
2418
from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score import data_parser class BaseModel: def __init__(self, model): self.model = model def train(self): return self.model.fit(self.x_train, self.y_train) class SupervisedBinaryClassificationModel(BaseModel): def __init__(self, raw_training_set, raw_predict_set, model): super().__init__(model) self.column_names = raw_training_set.pop(0) raw_labels = data_parser.parse_labels(raw_training_set) self.classes = list(set(raw_labels)) if len(self.classes) != 2: raise Exception("A binary classificator can only have two classes.") self.labels = data_parser.parse_classification_labels(raw_labels, self.classes) self.features = data_parser.parse_features(raw_training_set) self.predict_set = data_parser.parse_features(raw_predict_set) self.x_train, self.x_test, self.y_train, self.y_test = train_test_split(self.features, self.labels) def predict(self): predictions = self.model.predict(self.predict_set) results = [] for i in range(0, len(predictions)): results.append((int(predictions[i]), self.predict_set[i])) return results def accuracy_metrics(self): return self.model.score(self.x_test, self.y_test) def calculate_f1_score(self): test_predictions = self.model.predict(self.x_test) return f1_score(self.y_test, test_predictions) class SupervisedEstimationModel(BaseModel): def __init__(self, raw_training_set, raw_predict_set, model): super().__init__(model) self.column_names = raw_training_set.pop(0) raw_labels = data_parser.parse_labels(raw_training_set) self.labels = data_parser.parse_estimation_labels(raw_labels) self.features = data_parser.parse_features(raw_training_set) self.predict_set = data_parser.parse_features(raw_predict_set) self.x_train, self.x_test, self.y_train, self.y_test = train_test_split(self.features, self.labels) def predict(self): predictions = self.model.predict(self.predict_set) results = [] for i in range(0, len(predictions)): results.append((float(predictions[i]), self.predict_set[i])) return results def calculate_r2_score(self, X, y): return self.model.score(X, y)
mit
Canas/kaftools
kaftools/utils/shortcuts.py
1
2226
# -*- coding: utf-8 -*- """ kaftools.utils.shortcuts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module provides utility functions that are used within kaftools that can be useful for external scripts. """ import time import re import numpy as np import matplotlib.pyplot as plt def plot_series(data, prediction, **kwargs): """Shortcut to plot 2D series estimate vs target """ if 'figsize' in kwargs: fig = plt.figure(figsize=kwargs['figsize']) else: fig = plt.figure() if 'title' in kwargs: plt.title(kwargs['title']) if 'xlim' in kwargs: plt.xlim(kwargs['xlim']) if 'ylim' in kwargs: plt.ylim(kwargs['ylim']) markersize = kwargs.pop('markersize', 5.0) linewidth = kwargs.pop('linewidth', 2.0) plt.plot(data, 'ro', markersize=markersize) plt.plot(prediction, 'b-', linewidth=linewidth) #return fig def plot_squared_error(error_history, **kwargs): sqerror = np.asarray(error_history)**2 """Shortcut to plot squared error """ if 'figsize' in kwargs: fig = plt.figure(figsize=kwargs['figsize']) else: fig = plt.figure() if 'title' in kwargs: plt.title(kwargs['title']) if 'xlim' in kwargs: plt.xlim(kwargs['xlim']) if 'ylim' in kwargs: plt.ylim(kwargs['ylim']) linewidth = kwargs.pop('linewidth', 2.0) plt.semilogy(sqerror, 'b-', linewidth=linewidth) plt.show() return fig def timeit(f): """Decorator for timing execution of a function. """ def wrap(*args, **kwargs): regex_str = '<(\w+ [A-Za-z]*.[a-z]*)' regex = re.search(regex_str, f.__str__()) time1 = time.time() ret = f(*args, **kwargs) time2 = time.time() print('{0} took {1:.2f} secs'.format(regex.group(1), (time2-time1))) return ret return wrap def distance_to_dictionary(s, x): """Calculates distance from vector/matrix to list of vectors/matrices :param s: list of vector/matrices of shape (n_samples, n_delays, n_channels) :param x: vector of shape (n_delays, n_channels) :return: norm of vector """ s = np.asarray(s) x = np.asarray([x]*len(s)) return np.linalg.norm(s - x, axis=1)
mit
droter/trading-with-python
spreadApp/makeDist.py
77
1720
from distutils.core import setup import py2exe manifest_template = ''' <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="5.0.0.0" processorArchitecture="x86" name="%(prog)s" type="win32" /> <description>%(prog)s Program</description> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /> </dependentAssembly> </dependency> </assembly> ''' RT_MANIFEST = 24 import matplotlib opts = { 'py2exe': { "compressed": 1, "bundle_files" : 3, "includes" : ["sip", "matplotlib.backends", "matplotlib.backends.backend_qt4agg", "pylab", "numpy", "matplotlib.backends.backend_tkagg"], 'excludes': ['_gtkagg', '_tkagg', '_agg2', '_cairo', '_cocoaagg', '_fltkagg', '_gtk', '_gtkcairo', ], 'dll_excludes': ['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll'] } } setup(name="triton", version = "0.1", scripts=["spreadScanner.pyw"], windows=[{"script": "spreadScanner.pyw"}], options=opts, data_files=matplotlib.get_py2exe_datafiles(), other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog="spreadDetective"))], zipfile = None)
bsd-3-clause
TomAugspurger/pandas
asv_bench/benchmarks/period.py
4
2889
""" Period benchmarks with non-tslibs dependencies. See benchmarks.tslibs.period for benchmarks that rely only on tslibs. """ from pandas import DataFrame, Period, PeriodIndex, Series, date_range, period_range from pandas.tseries.frequencies import to_offset class PeriodIndexConstructor: params = [["D"], [True, False]] param_names = ["freq", "is_offset"] def setup(self, freq, is_offset): self.rng = date_range("1985", periods=1000) self.rng2 = date_range("1985", periods=1000).to_pydatetime() self.ints = list(range(2000, 3000)) self.daily_ints = ( date_range("1/1/2000", periods=1000, freq=freq).strftime("%Y%m%d").map(int) ) if is_offset: self.freq = to_offset(freq) else: self.freq = freq def time_from_date_range(self, freq, is_offset): PeriodIndex(self.rng, freq=freq) def time_from_pydatetime(self, freq, is_offset): PeriodIndex(self.rng2, freq=freq) def time_from_ints(self, freq, is_offset): PeriodIndex(self.ints, freq=freq) def time_from_ints_daily(self, freq, is_offset): PeriodIndex(self.daily_ints, freq=freq) class DataFramePeriodColumn: def setup(self): self.rng = period_range(start="1/1/1990", freq="S", periods=20000) self.df = DataFrame(index=range(len(self.rng))) def time_setitem_period_column(self): self.df["col"] = self.rng def time_set_index(self): # GH#21582 limited by comparisons of Period objects self.df["col2"] = self.rng self.df.set_index("col2", append=True) class Algorithms: params = ["index", "series"] param_names = ["typ"] def setup(self, typ): data = [ Period("2011-01", freq="M"), Period("2011-02", freq="M"), Period("2011-03", freq="M"), Period("2011-04", freq="M"), ] if typ == "index": self.vector = PeriodIndex(data * 1000, freq="M") elif typ == "series": self.vector = Series(data * 1000) def time_drop_duplicates(self, typ): self.vector.drop_duplicates() def time_value_counts(self, typ): self.vector.value_counts() class Indexing: def setup(self): self.index = period_range(start="1985", periods=1000, freq="D") self.series = Series(range(1000), index=self.index) self.period = self.index[500] def time_get_loc(self): self.index.get_loc(self.period) def time_shallow_copy(self): self.index._shallow_copy() def time_series_loc(self): self.series.loc[self.period] def time_align(self): DataFrame({"a": self.series, "b": self.series[:500]}) def time_intersection(self): self.index[:750].intersection(self.index[250:]) def time_unique(self): self.index.unique()
bsd-3-clause
sarahgrogan/scikit-learn
sklearn/neighbors/tests/test_kde.py
208
5556
import numpy as np from sklearn.utils.testing import (assert_allclose, assert_raises, assert_equal) from sklearn.neighbors import KernelDensity, KDTree, NearestNeighbors from sklearn.neighbors.ball_tree import kernel_norm from sklearn.pipeline import make_pipeline from sklearn.datasets import make_blobs from sklearn.grid_search import GridSearchCV from sklearn.preprocessing import StandardScaler def compute_kernel_slow(Y, X, kernel, h): d = np.sqrt(((Y[:, None, :] - X) ** 2).sum(-1)) norm = kernel_norm(h, X.shape[1], kernel) / X.shape[0] if kernel == 'gaussian': return norm * np.exp(-0.5 * (d * d) / (h * h)).sum(-1) elif kernel == 'tophat': return norm * (d < h).sum(-1) elif kernel == 'epanechnikov': return norm * ((1.0 - (d * d) / (h * h)) * (d < h)).sum(-1) elif kernel == 'exponential': return norm * (np.exp(-d / h)).sum(-1) elif kernel == 'linear': return norm * ((1 - d / h) * (d < h)).sum(-1) elif kernel == 'cosine': return norm * (np.cos(0.5 * np.pi * d / h) * (d < h)).sum(-1) else: raise ValueError('kernel not recognized') def test_kernel_density(n_samples=100, n_features=3): rng = np.random.RandomState(0) X = rng.randn(n_samples, n_features) Y = rng.randn(n_samples, n_features) for kernel in ['gaussian', 'tophat', 'epanechnikov', 'exponential', 'linear', 'cosine']: for bandwidth in [0.01, 0.1, 1]: dens_true = compute_kernel_slow(Y, X, kernel, bandwidth) def check_results(kernel, bandwidth, atol, rtol): kde = KernelDensity(kernel=kernel, bandwidth=bandwidth, atol=atol, rtol=rtol) log_dens = kde.fit(X).score_samples(Y) assert_allclose(np.exp(log_dens), dens_true, atol=atol, rtol=max(1E-7, rtol)) assert_allclose(np.exp(kde.score(Y)), np.prod(dens_true), atol=atol, rtol=max(1E-7, rtol)) for rtol in [0, 1E-5]: for atol in [1E-6, 1E-2]: for breadth_first in (True, False): yield (check_results, kernel, bandwidth, atol, rtol) def test_kernel_density_sampling(n_samples=100, n_features=3): rng = np.random.RandomState(0) X = rng.randn(n_samples, n_features) bandwidth = 0.2 for kernel in ['gaussian', 'tophat']: # draw a tophat sample kde = KernelDensity(bandwidth, kernel=kernel).fit(X) samp = kde.sample(100) assert_equal(X.shape, samp.shape) # check that samples are in the right range nbrs = NearestNeighbors(n_neighbors=1).fit(X) dist, ind = nbrs.kneighbors(X, return_distance=True) if kernel == 'tophat': assert np.all(dist < bandwidth) elif kernel == 'gaussian': # 5 standard deviations is safe for 100 samples, but there's a # very small chance this test could fail. assert np.all(dist < 5 * bandwidth) # check unsupported kernels for kernel in ['epanechnikov', 'exponential', 'linear', 'cosine']: kde = KernelDensity(bandwidth, kernel=kernel).fit(X) assert_raises(NotImplementedError, kde.sample, 100) # non-regression test: used to return a scalar X = rng.randn(4, 1) kde = KernelDensity(kernel="gaussian").fit(X) assert_equal(kde.sample().shape, (1, 1)) def test_kde_algorithm_metric_choice(): # Smoke test for various metrics and algorithms rng = np.random.RandomState(0) X = rng.randn(10, 2) # 2 features required for haversine dist. Y = rng.randn(10, 2) for algorithm in ['auto', 'ball_tree', 'kd_tree']: for metric in ['euclidean', 'minkowski', 'manhattan', 'chebyshev', 'haversine']: if algorithm == 'kd_tree' and metric not in KDTree.valid_metrics: assert_raises(ValueError, KernelDensity, algorithm=algorithm, metric=metric) else: kde = KernelDensity(algorithm=algorithm, metric=metric) kde.fit(X) y_dens = kde.score_samples(Y) assert_equal(y_dens.shape, Y.shape[:1]) def test_kde_score(n_samples=100, n_features=3): pass #FIXME #np.random.seed(0) #X = np.random.random((n_samples, n_features)) #Y = np.random.random((n_samples, n_features)) def test_kde_badargs(): assert_raises(ValueError, KernelDensity, algorithm='blah') assert_raises(ValueError, KernelDensity, bandwidth=0) assert_raises(ValueError, KernelDensity, kernel='blah') assert_raises(ValueError, KernelDensity, metric='blah') assert_raises(ValueError, KernelDensity, algorithm='kd_tree', metric='blah') def test_kde_pipeline_gridsearch(): # test that kde plays nice in pipelines and grid-searches X, _ = make_blobs(cluster_std=.1, random_state=1, centers=[[0, 1], [1, 0], [0, 0]]) pipe1 = make_pipeline(StandardScaler(with_mean=False, with_std=False), KernelDensity(kernel="gaussian")) params = dict(kerneldensity__bandwidth=[0.001, 0.01, 0.1, 1, 10]) search = GridSearchCV(pipe1, param_grid=params, cv=5) search.fit(X) assert_equal(search.best_params_['kerneldensity__bandwidth'], .1)
bsd-3-clause
LeeMendelowitz/DCMetroMetrics
dcmetrometrics/common/DataWriter.py
2
4877
""" Methods to convert an object to csv """ import datetime from pandas import Series, DataFrame import os from .utils import mkdir_p from datetime import timedelta, datetime from collections import defaultdict from ..eles.models import (Unit, UnitStatus, KeyStatuses, Station, DailyServiceReport, SystemServiceReport) from ..hotcars.models import HotCarReport from ..hotcars.models import (HotCarReport, Temperature) from ..common.metroTimes import tzutc, isNaive, toUtc, utcnow def s(v): if v is None: return 'NA' return unicode(v) def q(v): """Quote strings""" if v is None: return '"NA"' if isinstance(v, (unicode, str)): return u'"%s"'%v return unicode(v) class DataWriter(object): """Write csv files """ def __init__(self, basedir = None): self.basedir = os.path.abspath(basedir) if basedir else os.getcwd() self.outdir = os.path.join(self.basedir, 'download') def write_timestamp(self): # Create the directory if necessary outdir = self.outdir mkdir_p(outdir) fname = 'timestamp' outpath = os.path.join(outdir, fname) with open(outpath, 'w') as fout: fout.write(utcnow().isoformat() + '\n') def write_units(self): fields = Unit.data_fields # Create the directory if necessary outdir = self.outdir mkdir_p(outdir) fname = 'units.csv' outpath = os.path.join(outdir, fname) with open(outpath, 'w') as fout: # Write Header fout.write(','.join(fields) + '\n') for unit in Unit.objects.no_cache(): unit_data = unit.to_data_record() outs = ','.join(q(unit_data[k]) for k in fields) + '\n' fout.write(outs.encode('utf-8')) def write_hot_cars(self): fields = HotCarReport.data_fields # Create the directory if necessary outdir = os.path.join(self.basedir, 'download') mkdir_p(outdir) fname = 'hotcars.csv' outpath = os.path.join(outdir, fname) with open(outpath, 'w') as fout: # Write Header fout.write(','.join(fields) + '\n') for report in HotCarReport.objects.no_cache().order_by('time'): report.clean() report_data = report.to_data_record() df = DataFrame([report_data], columns = fields) df.to_csv(fout, index = False, header=False, encoding='utf-8') # let pandas do the escaping def write_unit_statuses(self): fields = UnitStatus.data_fields # Create the directory if necessary outdir = self.outdir mkdir_p(outdir) fname = 'unit_statuses.csv' outpath = os.path.join(outdir, fname) with open(outpath, 'w') as fout: # Write Header fout.write(','.join(fields) + '\n') statuses = UnitStatus.objects.timeout(False).order_by('time').no_cache() for status in statuses: status.clean() status_data = status.to_data_record() outs = ','.join(q(status_data[k]) for k in fields) + '\n' fout.write(outs.encode('utf-8')) statuses._cursor.close() def write_stations(self): fields = Station.data_fields # Create the directory if necessary outdir = self.outdir mkdir_p(outdir) fname = 'stations.csv' outpath = os.path.join(outdir, fname) with open(outpath, 'w') as fout: # Write Header fout.write(','.join(fields) + '\n') stations = Station.objects for station in stations: station_data = station.to_data_record() outs = ','.join(q(station_data[k]) for k in fields) + '\n' fout.write(outs.encode('utf-8')) def write_system_daily_service_report(self): # Create the directory if necessary outdir = self.outdir mkdir_p(outdir) fname = 'daily_system_reports.csv' outpath = os.path.join(outdir, fname) with open(outpath, 'w') as fout: keys = None reports = SystemServiceReport.objects.timeout(False).order_by('day').no_cache() for report in reports: report_data = report.to_data_record() if not keys: keys = report_data.keys() fout.write(','.join(keys) + '\n') outs = ','.join(q(report_data[k]) for k in keys) + '\n' fout.write(outs.encode('utf-8')) reports._cursor.close() def write_unit_daily_service_report(self): # Create the directory if necessary outdir = self.outdir mkdir_p(outdir) fname = 'daily_unit_reports.csv' outpath = os.path.join(outdir, fname) with open(outpath, 'w') as fout: keys = None reports = DailyServiceReport.objects.timeout(False).order_by('day').no_cache() for report in reports: report_data = report.to_data_record() if not keys: keys = report_data.keys() fout.write(','.join(keys) + '\n') outs = ','.join(q(report_data[k]) for k in keys) + '\n' fout.write(outs.encode('utf-8')) reports._cursor.close()
gpl-2.0
cswiercz/abelfunctions
abelfunctions/riemann_theta/tests/presentation.py
3
4024
import numpy as np from riemanntheta import RiemannTheta_Function import pylab as p import matplotlib.pyplot as plt from pycuda import gpuarray import time def demo1(): theta = RiemannTheta_Function() Omega = np.array([[1.j, .5], [.5, 1.j]]) print print "Calculating 3,600 points of the Riemann Theta Function in C..." print print "Omega = [i .5]" print " [.5 i]" print print "z = (x + iy, 0) where (0 < x < 1) and (0 < y < 5)" SIZE = 60 x = np.linspace(0,1,SIZE) y = np.linspace(0,5,SIZE) X,Y = p.meshgrid(x,y) Z = X + Y*1.0j Z = Z.flatten() start = time.clock() U,V = theta.exp_and_osc_at_point([[z,0] for z in Z], Omega, gpu=False, batch=True) done = time.clock() - start print "Time to perform the calculation: " + str(done) print Z = (V.reshape(60,60)).imag print "\Plotting the imaginary part of the function..." plt.contourf(X,Y,Z,7,antialiased=True) plt.show() def demo2(): theta = RiemannTheta_Function() Omega = np.array([[1.j, .5], [.5, 1.j]]) print print "Calculating 3,600 points of the Riemann Theta Function on GPU..." print print "Omega = [i .5]" print " [.5 i]" print print "z = (x + iy, 0) where (0 < x < 1) and (0 < y < 5)" SIZE = 60 x = np.linspace(0,1,SIZE) y = np.linspace(0,5,SIZE) X,Y = p.meshgrid(x,y) Z = X + Y*1.0j Z = Z.flatten() start = time.clock() U,V = theta.exp_and_osc_at_point([[z,0] for z in Z], Omega, batch=True) done = time.clock() - start print "Time to perform the calculation: " + str(done) print Z = (V.reshape(60,60)).imag print "\Plotting the imaginary part of the function..." plt.contourf(X,Y,Z,7,antialiased=True) plt.show() def demo3(): theta = RiemannTheta_Function() Omega = np.array([[1.j, .5], [.5, 1.j]]) print print "Calculating 1,000,000 points of the Riemann Theta Function on GPU..." print print "Omega = [i .5]" print " [.5 i]" print print "z = (x + iy, 0) where (0 < x < 1) and (0 < y < 5)" SIZE = 1000 x = np.linspace(0,1,SIZE) y = np.linspace(0,5,SIZE) X,Y = p.meshgrid(x,y) Z = X + Y*1.0j Z = Z.flatten() Z = [[z,0] for z in Z] print "Starting computation on the GPU" start = time.clock() U,V = theta.exp_and_osc_at_point(Z, Omega, batch=True) done = time.clock() - start print "Time to perform the calculation: " + str(done) print print "Starting computation on the CPU" start = time.clock() U,V = theta.exp_and_osc_at_point(Z, Omega, batch=True, gpu=False) done = time.clock() - start print "Time to perform the calculation: " + str(done) print def demo4(): theta = RiemannTheta_Function() z = np.array([1.j, .5*1.j, 1.j]) omegas = [] I = 1.j t_vals = np.linspace(1, 0, 10000) for t in t_vals: a = np.array([[-0.5*t + I, 0.5*t*(1-I), -0.5*t*(1 + I)], [0.5*t*(1-I), I, 0], [-0.5*t*(1+I), 0, I]]) omegas.append(a) print "z = (i, i, i), calculating z for 10,000 different Omegas" print print "Omegas = [-0.5*(1-t) + i 0.5*t*(1-i) -0.5*(1-t)*(1 + i)]" print " [0.5*(1-t)*(1-i) i 0]" print " [-0.5*(1-t)*(1+i) 0 i]" print "for 0 <= t <= 1" print print "Beginning Computation on the GPU" start = time.clock() v = theta.multiple_omega_process1(z, omegas, 3) print "Computation Finished, elapsed time: " + str(time.clock() - start) print print v print print "=================================" print "Beginning Computation on the CPU" start = time.clock() u = [] for i in range(10000): U,V = theta.exp_and_osc_at_point(z,omegas[i]) u.append(V) print "Computation Finished, elapsed time: " + str(time.clock() - start) print print np.array(v)
bsd-3-clause
Alexsaphir/TP_EDP_Python
TP1.py
1
3456
# -*- coding: utf-8 -*- from numpy import * from numpy.linalg import * from numpy.random import * from matplotlib.pyplot import * print('Valeur de pi :', pi) print(finfo(float).eps) #Create a Vector X1 = array([1, 2, 3, 4, 5]) print('Simple vecteur :',X1) X2 = arange(0,1,.25) print('Subdvision uniforme :', X2) X3 = linspace(0,10,3) print('Vecteur n-pts :',X3) X4 = zeros(5) print('Vecteur zeros :',X4) #Matrice M1=array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print('Simple matrice', M1) M2=zeros((2,3)) print('Matrice zeros', M2) #Exercice 1 A=-1*(diag(ones(9),1)+diag(ones(9),-1))+2.*eye(10); A[9,9] = 1 print(A) #Fonctions def fonc(x, y, m): z = x**2 + y**2 t = x - y + m return z, t #Test if(1<2) : print('1<2') elif (1<3) : print('1<3') else : print('Aussi non !') ################## ################## ## Exercice 3 ## ################## ################## def f(x, m) : if (m == 0) : y = zeros(size(x)) elif (m == 1) : y = ones(size(x)) elif (m == 2) : y = x elif (m == 3) : y = x**2 elif (m == 4) : y = 4.*pi*pi*sin(2.*pi*x) else : print('valeur de m indéfinie') return y def solex(x, ug , m) : if (m == 0): y = ug*ones(size(x)) elif (m == 1) : y = -0.5*x**2+x+ug elif (m == 2) : y = -(1/6)*x**3+(1/2)*x+ug elif (m == 3 ) : y = -(1/12)*x**4+(1/3)*x+ug elif (m == 4) : y = sin(2*pi*x)-2*pi*x+ug else : print('valeur de m indéfinie') return y ################## ################## ## Exercice 2 ## ################## ################## print('Pour le second membre, choix de la fonction f') print('Pour m=0 : f=0') print('Pour m=1 : f=1') print('Pour m=2 : f=x') print('Pour m=3 : f=x^2') print('Pour m=4 : f=4*pi^2*sin(2*pi*x)') m = int(input("Choix de m = ")) print('Choix de la condition a gauche') ug = float(input('ug = u(0) =')) print("Methode pour l'approximation de u'(1) : ") print("1- decentre d'ordre 1") print("2- centre d'ordre 2") meth = int(input('Choix = ')) print('Choix du nombre Ns de points interieurs du maillage') Ns = int(input('Ns = ')) # Maillage h=1./(Ns+1) X=linspace(0, 1., Ns+2) Xh=linspace(h,1.,Ns+1) # Matrice du systeme lineaire : A=-1*(diag(ones(Ns),1)+diag(ones(Ns),-1))+2.*eye(Ns+1); A[Ns, Ns] = 1 A=1./h/h*A #Conditionement de la matrice cond_A=cond(A) print('Conditionnement de la matrice A :', cond_A) # Second membre # b = ... (plus loin, exercice 3) b = f(Xh, m) b[0] = b[0] + (Ns + 1)**2*ug # Transformation de b[Ns] pour prendre en compte u'(1) = 0 (cf TD) if (meth == 2): b[Ns] = b[Ns]/2 # Resolution du syteme lineaire Uh = solve(A, b) # ceci calcule Uh solution du systeme AU=b # Calcul de la solution exacte aux points d'approximation Uex = solex(Xh, ug, m) # Calcul de l'erreur en norme infini Uerr = abs(Uex - Uh) disp(max(Uerr)) #Graphes Uh = concatenate((array([ug]),Uh)) # on complete le vecteur solution avec la valeur ug en 0 # On trace le graphe de la fonction solex sur un maillage fin de 100 points plot(linspace(0,1,100),solex(linspace(0,1,100), ug, m), label = 'sol ex') # et le graphe de la solution approchée obtenue plot(X, Uh, label = 'sol approchee') plot(Xh, Uerr, label = 'Erreur') # On ajoute un titre title('d²u(x)/dx²=f(x)') # On ajoute les labels sur les axes xlabel('X') ylabel('Y') # Pour faire afficher les labels legend() show() # Pour afficher la figure
lgpl-3.0
muku42/bokeh
bokeh/charts/builder/step_builder.py
43
5445
"""This is the Bokeh charts interface. It gives you a high level API to build complex plot is a simple way. This is the Step class which lets you build your Step charts just passing the arguments to the Chart class and calling the proper functions. """ #----------------------------------------------------------------------------- # 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 six import string_types from ..utils import cycle_colors from .._builder import create_and_build, Builder from ...models import ColumnDataSource, DataRange1d, GlyphRenderer from ...models.glyphs import Line from ...properties import Any #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- def Step(values, index=None, **kws): """ Create a step chart using :class:`StepBuilder <bokeh.charts.builder.step_builder.StepBuilder>` render the geometry from values and index. Args: values (iterable): iterable 2d representing the data series values matrix. index (str|1d iterable, optional): can be used to specify a common custom index for all data series as an **1d iterable** of any sort that will be used as series common index or a **string** that corresponds to the key of the mapping to be used as index (and not as data series) if area.values is a mapping (like a dict, an OrderedDict or a pandas DataFrame) In addition the the parameters specific to this chart, :ref:`userguide_charts_generic_arguments` are also accepted as keyword parameters. Returns: a new :class:`Chart <bokeh.charts.Chart>` Examples: .. bokeh-plot:: :source-position: above from collections import OrderedDict from bokeh.charts import Step, output_file, show # (dict, OrderedDict, lists, arrays and DataFrames are valid inputs) xyvalues = [[2, 3, 7, 5, 26], [12, 33, 47, 15, 126], [22, 43, 10, 25, 26]] step = Step(xyvalues, title="Steps", legend="top_left", ylabel='Languages') output_file('step.html') show(step) """ return create_and_build(StepBuilder, values, index=index, **kws) class StepBuilder(Builder): """This is the Step class and it is in charge of plotting Step charts in an easy and intuitive way. Essentially, we provide a way to ingest the data, make the proper calculations and push the references into a source object. We additionally make calculations for the ranges. And finally add the needed lines taking the references from the source. """ index = Any(help=""" An index to be used for all data series as follows: - A 1d iterable of any sort that will be used as series common index - As a string that corresponds to the key of the mapping to be used as index (and not as data series) if area.values is a mapping (like a dict, an OrderedDict or a pandas DataFrame) """) def _process_data(self): """It calculates the chart properties accordingly from Step.values. Then build a dict containing references to all the points to be used by the segment glyph inside the ``_yield_renderers`` method. """ self._data = dict() self._groups = [] orig_xs = self._values_index xs = np.empty(2*len(orig_xs)-1, dtype=np.int) xs[::2] = orig_xs[:] xs[1::2] = orig_xs[1:] self._data['x'] = xs for i, col in enumerate(self._values.keys()): if isinstance(self.index, string_types) and col == self.index: continue # save every new group we find self._groups.append(col) orig_ys = np.array([self._values[col][x] for x in orig_xs]) ys = np.empty(2*len(orig_ys)-1) ys[::2] = orig_ys[:] ys[1::2] = orig_ys[:-1] self._data['y_%s' % col] = ys def _set_sources(self): """ Push the Step data into the ColumnDataSource and calculate the proper ranges. """ self._source = ColumnDataSource(self._data) self.x_range = DataRange1d() #y_sources = [sc.columns("y_%s" % col) for col in self._groups] self.y_range = DataRange1d() def _yield_renderers(self): """Use the line glyphs to connect the xy points in the Step. Takes reference points from the data loaded at the ColumnDataSource. """ colors = cycle_colors(self._groups, self.palette) for i, name in enumerate(self._groups): # draw the step horizontal segment glyph = Line(x="x", y="y_%s" % name, line_color=colors[i], line_width=2) renderer = GlyphRenderer(data_source=self._source, glyph=glyph) self._legends.append((self._groups[i], [renderer])) yield renderer
bsd-3-clause
macks22/scikit-learn
examples/tree/plot_iris.py
271
2186
""" ================================================================ Plot the decision surface of a decision tree on the iris dataset ================================================================ Plot the decision surface of a decision tree trained on pairs of features of the iris dataset. See :ref:`decision tree <tree>` for more information on the estimator. For each pair of iris features, the decision tree learns decision boundaries made of combinations of simple thresholding rules inferred from the training samples. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier # Parameters n_classes = 3 plot_colors = "bry" plot_step = 0.02 # Load data iris = load_iris() for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]): # We only take the two corresponding features X = iris.data[:, pair] y = iris.target # Shuffle idx = np.arange(X.shape[0]) np.random.seed(13) np.random.shuffle(idx) X = X[idx] y = y[idx] # Standardize mean = X.mean(axis=0) std = X.std(axis=0) X = (X - mean) / std # Train clf = DecisionTreeClassifier().fit(X, y) # Plot the decision boundary plt.subplot(2, 3, pairidx + 1) 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 = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired) plt.xlabel(iris.feature_names[pair[0]]) plt.ylabel(iris.feature_names[pair[1]]) plt.axis("tight") # Plot the training points for i, color in zip(range(n_classes), plot_colors): idx = np.where(y == i) plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i], cmap=plt.cm.Paired) plt.axis("tight") plt.suptitle("Decision surface of a decision tree using paired features") plt.legend() plt.show()
bsd-3-clause
arabenjamin/scikit-learn
examples/semi_supervised/plot_label_propagation_structure.py
247
2432
""" ============================================== Label Propagation learning a complex structure ============================================== Example of LabelPropagation learning a complex internal structure to demonstrate "manifold learning". The outer circle should be labeled "red" and the inner circle "blue". Because both label groups lie inside their own distinct shape, we can see that the labels propagate correctly around the circle. """ print(__doc__) # Authors: Clay Woolam <[email protected]> # Andreas Mueller <[email protected]> # Licence: BSD import numpy as np import matplotlib.pyplot as plt from sklearn.semi_supervised import label_propagation from sklearn.datasets import make_circles # generate ring with inner box n_samples = 200 X, y = make_circles(n_samples=n_samples, shuffle=False) outer, inner = 0, 1 labels = -np.ones(n_samples) labels[0] = outer labels[-1] = inner ############################################################################### # Learn with LabelSpreading label_spread = label_propagation.LabelSpreading(kernel='knn', alpha=1.0) label_spread.fit(X, labels) ############################################################################### # Plot output labels output_labels = label_spread.transduction_ plt.figure(figsize=(8.5, 4)) plt.subplot(1, 2, 1) plot_outer_labeled, = plt.plot(X[labels == outer, 0], X[labels == outer, 1], 'rs') plot_unlabeled, = plt.plot(X[labels == -1, 0], X[labels == -1, 1], 'g.') plot_inner_labeled, = plt.plot(X[labels == inner, 0], X[labels == inner, 1], 'bs') plt.legend((plot_outer_labeled, plot_inner_labeled, plot_unlabeled), ('Outer Labeled', 'Inner Labeled', 'Unlabeled'), 'upper left', numpoints=1, shadow=False) plt.title("Raw data (2 classes=red and blue)") plt.subplot(1, 2, 2) output_label_array = np.asarray(output_labels) outer_numbers = np.where(output_label_array == outer)[0] inner_numbers = np.where(output_label_array == inner)[0] plot_outer, = plt.plot(X[outer_numbers, 0], X[outer_numbers, 1], 'rs') plot_inner, = plt.plot(X[inner_numbers, 0], X[inner_numbers, 1], 'bs') plt.legend((plot_outer, plot_inner), ('Outer Learned', 'Inner Learned'), 'upper left', numpoints=1, shadow=False) plt.title("Labels learned with Label Spreading (KNN)") plt.subplots_adjust(left=0.07, bottom=0.07, right=0.93, top=0.92) plt.show()
bsd-3-clause