repo_name
stringlengths
6
67
path
stringlengths
5
185
copies
stringlengths
1
3
size
stringlengths
4
6
content
stringlengths
1.02k
962k
license
stringclasses
15 values
dimkal/mne-python
tutorials/plot_cluster_1samp_test_time_frequency.py
16
4759
""" .. _tut_stats_cluster_sensor_1samp_tfr: =============================================================== Non-parametric 1 sample cluster statistic on single trial power =============================================================== This script shows how to estimate significant clusters in time-frequency power estimates. It uses a non-parametric statistical procedure based on permutations and cluster level statistics. The procedure consists in: - extracting epochs - compute single trial power estimates - baseline line correct the power estimates (power ratios) - compute stats to see if ratio deviates from 1. """ # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne import io from mne.time_frequency import single_trial_power from mne.stats import permutation_cluster_1samp_test from mne.datasets import sample print(__doc__) ############################################################################### # Set parameters data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif' event_id = 1 tmin = -0.3 tmax = 0.6 # Setup for reading the raw data raw = io.Raw(raw_fname) events = mne.find_events(raw, stim_channel='STI 014') include = [] raw.info['bads'] += ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True, stim=False, include=include, exclude='bads') # Load condition 1 event_id = 1 epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6)) data = epochs.get_data() # as 3D matrix data *= 1e13 # change unit to fT / cm # Time vector times = 1e3 * epochs.times # change unit to ms # Take only one channel ch_name = raw.info['ch_names'][97] data = data[:, 97:98, :] evoked_data = np.mean(data, 0) # data -= evoked_data[None,:,:] # remove evoked component # evoked_data = np.mean(data, 0) # Factor to down-sample the temporal dimension of the PSD computed by # single_trial_power. Decimation occurs after frequency decomposition and can # be used to reduce memory usage (and possibly computational time of downstream # operations such as nonparametric statistics) if you don't need high # spectrotemporal resolution. decim = 5 frequencies = np.arange(8, 40, 2) # define frequencies of interest sfreq = raw.info['sfreq'] # sampling in Hz epochs_power = single_trial_power(data, sfreq=sfreq, frequencies=frequencies, n_cycles=4, n_jobs=1, baseline=(-100, 0), times=times, baseline_mode='ratio', decim=decim) # Crop in time to keep only what is between 0 and 400 ms time_mask = (times > 0) & (times < 400) evoked_data = evoked_data[:, time_mask] times = times[time_mask] # The time vector reflects the original time points, not the decimated time # points returned by single trial power. Be sure to decimate the time mask # appropriately. epochs_power = epochs_power[..., time_mask[::decim]] epochs_power = epochs_power[:, 0, :, :] epochs_power = np.log10(epochs_power) # take log of ratio # under the null hypothesis epochs_power should be now be 0 ############################################################################### # Compute statistic threshold = 2.5 T_obs, clusters, cluster_p_values, H0 = \ permutation_cluster_1samp_test(epochs_power, n_permutations=100, threshold=threshold, tail=0) ############################################################################### # View time-frequency plots plt.clf() plt.subplots_adjust(0.12, 0.08, 0.96, 0.94, 0.2, 0.43) plt.subplot(2, 1, 1) plt.plot(times, evoked_data.T) plt.title('Evoked response (%s)' % ch_name) plt.xlabel('time (ms)') plt.ylabel('Magnetic Field (fT/cm)') plt.xlim(times[0], times[-1]) plt.ylim(-100, 250) plt.subplot(2, 1, 2) # Create new stats image with only significant clusters T_obs_plot = np.nan * np.ones_like(T_obs) for c, p_val in zip(clusters, cluster_p_values): if p_val <= 0.05: T_obs_plot[c] = T_obs[c] vmax = np.max(np.abs(T_obs)) vmin = -vmax plt.imshow(T_obs, cmap=plt.cm.gray, extent=[times[0], times[-1], frequencies[0], frequencies[-1]], aspect='auto', origin='lower', vmin=vmin, vmax=vmax) plt.imshow(T_obs_plot, cmap=plt.cm.RdBu_r, extent=[times[0], times[-1], frequencies[0], frequencies[-1]], aspect='auto', origin='lower', vmin=vmin, vmax=vmax) plt.colorbar() plt.xlabel('time (ms)') plt.ylabel('Frequency (Hz)') plt.title('Induced power (%s)' % ch_name) plt.show()
bsd-3-clause
0asa/scikit-learn
sklearn/utils/testing.py
2
22085
"""Testing utilities.""" # Copyright (c) 2011, 2012 # Authors: Pietro Berkes, # Andreas Muller # Mathieu Blondel # Olivier Grisel # Arnaud Joly # Denis Engemann # License: BSD 3 clause import os import inspect import pkgutil import warnings import sys import re import platform import scipy as sp import scipy.io from functools import wraps try: # Python 2 from urllib2 import urlopen from urllib2 import HTTPError except ImportError: # Python 3+ from urllib.request import urlopen from urllib.error import HTTPError import sklearn from sklearn.base import BaseEstimator # Conveniently import all assertions in one place. from nose.tools import assert_equal from nose.tools import assert_not_equal from nose.tools import assert_true from nose.tools import assert_false from nose.tools import assert_raises from nose.tools import raises from nose import SkipTest from nose import with_setup from numpy.testing import assert_almost_equal from numpy.testing import assert_array_equal from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_less import numpy as np from sklearn.base import (ClassifierMixin, RegressorMixin, TransformerMixin, ClusterMixin) __all__ = ["assert_equal", "assert_not_equal", "assert_raises", "assert_raises_regexp", "raises", "with_setup", "assert_true", "assert_false", "assert_almost_equal", "assert_array_equal", "assert_array_almost_equal", "assert_array_less", "assert_less", "assert_less_equal", "assert_greater", "assert_greater_equal"] try: from nose.tools import assert_in, assert_not_in except ImportError: # Nose < 1.0.0 def assert_in(x, container): assert_true(x in container, msg="%r in %r" % (x, container)) def assert_not_in(x, container): assert_false(x in container, msg="%r in %r" % (x, container)) try: from nose.tools import assert_raises_regex except ImportError: # for Py 2.6 def assert_raises_regex(expected_exception, expected_regexp, callable_obj=None, *args, **kwargs): """Helper function to check for message patterns in exceptions""" not_raised = False try: callable_obj(*args, **kwargs) not_raised = True except Exception as e: error_message = str(e) if not re.compile(expected_regexp).search(error_message): raise AssertionError("Error message should match pattern " "%r. %r does not." % (expected_regexp, error_message)) if not_raised: raise AssertionError("Should have raised %r" % expected_exception(expected_regexp)) # assert_raises_regexp is deprecated in Python 3.4 in favor of # assert_raises_regex but lets keep the bacward compat in scikit-learn with # the old name for now assert_raises_regexp = assert_raises_regex def _assert_less(a, b, msg=None): message = "%r is not lower than %r" % (a, b) if msg is not None: message += ": " + msg assert a < b, message def _assert_greater(a, b, msg=None): message = "%r is not greater than %r" % (a, b) if msg is not None: message += ": " + msg assert a > b, message def assert_less_equal(a, b, msg=None): message = "%r is not lower than or equal to %r" % (a, b) if msg is not None: message += ": " + msg assert a <= b, message def assert_greater_equal(a, b, msg=None): message = "%r is not greater than or equal to %r" % (a, b) if msg is not None: message += ": " + msg assert a >= b, message def assert_warns(warning_class, func, *args, **kw): """Test that a certain warning occurs. Parameters ---------- warning_class : the warning class The class to test for, e.g. UserWarning. func : callable Calable object to trigger warnings. *args : the positional arguments to `func`. **kw : the keyword arguments to `func` Returns ------- result : the return value of `func` """ # very important to avoid uncontrolled state propagation clean_warning_registry() with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Trigger a warning. result = func(*args, **kw) if hasattr(np, 'VisibleDeprecationWarning'): # Filter out numpy-specific warnings in numpy >= 1.9 w = [e for e in w if e.category is not np.VisibleDeprecationWarning] # Verify some things if not len(w) > 0: raise AssertionError("No warning raised when calling %s" % func.__name__) found = any(warning.category is warning_class for warning in w) if not found: raise AssertionError("%s did not give warning: %s( is %s)" % (func.__name__, warning_class, w)) return result def assert_warns_message(warning_class, message, func, *args, **kw): # very important to avoid uncontrolled state propagation """Test that a certain warning occurs and with a certain message. Parameters ---------- warning_class : the warning class The class to test for, e.g. UserWarning. message : str | callable The entire message or a substring to test for. If callable, it takes a string as argument and will trigger an assertion error if it returns `False`. func : callable Calable object to trigger warnings. *args : the positional arguments to `func`. **kw : the keyword arguments to `func`. Returns ------- result : the return value of `func` """ clean_warning_registry() with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") if hasattr(np, 'VisibleDeprecationWarning'): # Let's not catch the numpy internal DeprecationWarnings warnings.simplefilter('ignore', np.VisibleDeprecationWarning) # Trigger a warning. result = func(*args, **kw) # Verify some things if not len(w) > 0: raise AssertionError("No warning raised when calling %s" % func.__name__) found = [warning.category is warning_class for warning in w] if not any(found): raise AssertionError("No warning raised for %s with class " "%s" % (func.__name__, warning_class)) message_found = False # Checks the message of all warnings belong to warning_class for index in [i for i, x in enumerate(found) if x]: # substring will match, the entire message with typo won't msg = w[index].message # For Python 3 compatibility msg = str(msg.args[0] if hasattr(msg, 'args') else msg) if callable(message): # add support for certain tests check_in_message = message else: check_in_message = lambda msg: message in msg if check_in_message(msg): message_found = True break if not message_found: raise AssertionError("Did not receive the message you expected " "('%s') for <%s>." % (message, func.__name__)) return result # To remove when we support numpy 1.7 def assert_no_warnings(func, *args, **kw): # XXX: once we may depend on python >= 2.6, this can be replaced by the # warnings module context manager. # very important to avoid uncontrolled state propagation clean_warning_registry() with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') result = func(*args, **kw) if hasattr(np, 'VisibleDeprecationWarning'): # Filter out numpy-specific warnings in numpy >= 1.9 w = [e for e in w if e.category is not np.VisibleDeprecationWarning] if len(w) > 0: raise AssertionError("Got warnings when calling %s: %s" % (func.__name__, w)) return result def ignore_warnings(obj=None): """ Context manager and decorator to ignore warnings Note. Using this (in both variants) will clear all warnings from all python modules loaded. In case you need to test cross-module-warning-logging this is not your tool of choice. Examples -------- >>> with ignore_warnings(): ... warnings.warn('buhuhuhu') >>> def nasty_warn(): ... warnings.warn('buhuhuhu') ... print(42) >>> ignore_warnings(nasty_warn)() 42 """ if callable(obj): return _ignore_warnings(obj) else: return _IgnoreWarnings() def _ignore_warnings(fn): """Decorator to catch and hide warnings without visual nesting""" @wraps(fn) def wrapper(*args, **kwargs): # very important to avoid uncontrolled state propagation clean_warning_registry() with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') return fn(*args, **kwargs) w[:] = [] return wrapper class _IgnoreWarnings(object): """Improved and simplified Python warnings context manager Copied from Python 2.7.5 and modified as required. """ def __init__(self): """ Parameters ========== category : warning class The category to filter. Defaults to Warning. If None, all categories will be muted. """ self._record = True self._module = sys.modules['warnings'] self._entered = False self.log = [] def __repr__(self): args = [] if self._record: args.append("record=True") if self._module is not sys.modules['warnings']: args.append("module=%r" % self._module) name = type(self).__name__ return "%s(%s)" % (name, ", ".join(args)) def __enter__(self): clean_warning_registry() # be safe and not propagate state + chaos warnings.simplefilter('always') if self._entered: raise RuntimeError("Cannot enter %r twice" % self) self._entered = True self._filters = self._module.filters self._module.filters = self._filters[:] self._showwarning = self._module.showwarning if self._record: self.log = [] def showwarning(*args, **kwargs): self.log.append(warnings.WarningMessage(*args, **kwargs)) self._module.showwarning = showwarning return self.log else: return None def __exit__(self, *exc_info): if not self._entered: raise RuntimeError("Cannot exit %r without entering first" % self) self._module.filters = self._filters self._module.showwarning = self._showwarning self.log[:] = [] clean_warning_registry() # be safe and not propagate state + chaos try: from nose.tools import assert_less except ImportError: assert_less = _assert_less try: from nose.tools import assert_greater except ImportError: assert_greater = _assert_greater def _assert_allclose(actual, desired, rtol=1e-7, atol=0, err_msg='', verbose=True): actual, desired = np.asanyarray(actual), np.asanyarray(desired) if np.allclose(actual, desired, rtol=rtol, atol=atol): return msg = ('Array not equal to tolerance rtol=%g, atol=%g: ' 'actual %s, desired %s') % (rtol, atol, actual, desired) raise AssertionError(msg) if hasattr(np.testing, 'assert_allclose'): assert_allclose = np.testing.assert_allclose else: assert_allclose = _assert_allclose def assert_raise_message(exception, message, function, *args, **kwargs): """Helper function to test error messages in exceptions""" try: function(*args, **kwargs) raise AssertionError("Should have raised %r" % exception(message)) except exception as e: error_message = str(e) assert_in(message, error_message) def fake_mldata(columns_dict, dataname, matfile, ordering=None): """Create a fake mldata data set. Parameters ---------- columns_dict: contains data as columns_dict[column_name] = array of data dataname: name of data set matfile: file-like object or file name ordering: list of column_names, determines the ordering in the data set Note: this function transposes all arrays, while fetch_mldata only transposes 'data', keep that into account in the tests. """ datasets = dict(columns_dict) # transpose all variables for name in datasets: datasets[name] = datasets[name].T if ordering is None: ordering = sorted(list(datasets.keys())) # NOTE: setting up this array is tricky, because of the way Matlab # re-packages 1D arrays datasets['mldata_descr_ordering'] = sp.empty((1, len(ordering)), dtype='object') for i, name in enumerate(ordering): datasets['mldata_descr_ordering'][0, i] = name scipy.io.savemat(matfile, datasets, oned_as='column') class mock_mldata_urlopen(object): def __init__(self, mock_datasets): """Object that mocks the urlopen function to fake requests to mldata. `mock_datasets` is a dictionary of {dataset_name: data_dict}, or {dataset_name: (data_dict, ordering). `data_dict` itself is a dictionary of {column_name: data_array}, and `ordering` is a list of column_names to determine the ordering in the data set (see `fake_mldata` for details). When requesting a dataset with a name that is in mock_datasets, this object creates a fake dataset in a StringIO object and returns it. Otherwise, it raises an HTTPError. """ self.mock_datasets = mock_datasets def __call__(self, urlname): dataset_name = urlname.split('/')[-1] if dataset_name in self.mock_datasets: resource_name = '_' + dataset_name from io import BytesIO matfile = BytesIO() dataset = self.mock_datasets[dataset_name] ordering = None if isinstance(dataset, tuple): dataset, ordering = dataset fake_mldata(dataset, resource_name, matfile, ordering) matfile.seek(0) return matfile else: raise HTTPError(urlname, 404, dataset_name + " is not available", [], None) def install_mldata_mock(mock_datasets): # Lazy import to avoid mutually recursive imports from sklearn import datasets datasets.mldata.urlopen = mock_mldata_urlopen(mock_datasets) def uninstall_mldata_mock(): # Lazy import to avoid mutually recursive imports from sklearn import datasets datasets.mldata.urlopen = urlopen # Meta estimators need another estimator to be instantiated. META_ESTIMATORS = ["OneVsOneClassifier", "OutputCodeClassifier", "OneVsRestClassifier", "RFE", "RFECV", "BaseEnsemble"] # estimators that there is no way to default-construct sensibly OTHER = ["Pipeline", "FeatureUnion", "GridSearchCV", "RandomizedSearchCV"] # some trange ones DONT_TEST = ['SparseCoder', 'EllipticEnvelope', 'DictVectorizer', 'LabelBinarizer', 'LabelEncoder', 'MultiLabelBinarizer', 'TfidfTransformer', 'IsotonicRegression', 'OneHotEncoder', 'RandomTreesEmbedding', 'FeatureHasher', 'DummyClassifier', 'DummyRegressor', 'TruncatedSVD', 'PolynomialFeatures', 'GaussianRandomProjectionHash'] def all_estimators(include_meta_estimators=False, include_other=False, type_filter=None, include_dont_test=False): """Get a list of all estimators from sklearn. This function crawls the module and gets all classes that inherit from BaseEstimator. Classes that are defined in test-modules are not included. By default meta_estimators such as GridSearchCV are also not included. Parameters ---------- include_meta_estimators : boolean, default=False Whether to include meta-estimators that can be constructed using an estimator as their first argument. These are currently BaseEnsemble, OneVsOneClassifier, OutputCodeClassifier, OneVsRestClassifier, RFE, RFECV. include_other : boolean, default=False Wether to include meta-estimators that are somehow special and can not be default-constructed sensibly. These are currently Pipeline, FeatureUnion and GridSearchCV include_dont_test : boolean, default=False Whether to include "special" label estimator or test processors. type_filter : string, list of string, or None, default=None Which kind of estimators should be returned. If None, no filter is applied and all estimators are returned. Possible values are 'classifier', 'regressor', 'cluster' and 'transformer' to get estimators only of these specific types, or a list of these to get the estimators that fit at least one of the types. Returns ------- estimators : list of tuples List of (name, class), where ``name`` is the class name as string and ``class`` is the actuall type of the class. """ def is_abstract(c): if not(hasattr(c, '__abstractmethods__')): return False if not len(c.__abstractmethods__): return False return True all_classes = [] # get parent folder path = sklearn.__path__ for importer, modname, ispkg in pkgutil.walk_packages( path=path, prefix='sklearn.', onerror=lambda x: None): if ".tests." in modname: continue module = __import__(modname, fromlist="dummy") classes = inspect.getmembers(module, inspect.isclass) all_classes.extend(classes) all_classes = set(all_classes) estimators = [c for c in all_classes if (issubclass(c[1], BaseEstimator) and c[0] != 'BaseEstimator')] # get rid of abstract base classes estimators = [c for c in estimators if not is_abstract(c[1])] if not include_dont_test: estimators = [c for c in estimators if not c[0] in DONT_TEST] if not include_other: estimators = [c for c in estimators if not c[0] in OTHER] # possibly get rid of meta estimators if not include_meta_estimators: estimators = [c for c in estimators if not c[0] in META_ESTIMATORS] if type_filter is not None: if not isinstance(type_filter, list): type_filter = [type_filter] else: type_filter = list(type_filter) # copy filtered_estimators = [] filters = {'classifier': ClassifierMixin, 'regressor': RegressorMixin, 'transformer': TransformerMixin, 'cluster': ClusterMixin} for name, mixin in filters.items(): if name in type_filter: type_filter.remove(name) filtered_estimators.extend([est for est in estimators if issubclass(est[1], mixin)]) estimators = filtered_estimators if type_filter: raise ValueError("Parameter type_filter must be 'classifier', " "'regressor', 'transformer', 'cluster' or None, got" " %s." % repr(type_filter)) # drop duplicates, sort for reproducibility return sorted(set(estimators)) def set_random_state(estimator, random_state=0): if "random_state" in estimator.get_params().keys(): estimator.set_params(random_state=random_state) def if_matplotlib(func): """Test decorator that skips test if matplotlib not installed. """ @wraps(func) def run_test(*args, **kwargs): try: import matplotlib matplotlib.use('Agg', warn=False) # this fails if no $DISPLAY specified matplotlib.pylab.figure() except: raise SkipTest('Matplotlib not available.') else: return func(*args, **kwargs) return run_test def if_not_mac_os(versions=('10.7', '10.8', '10.9'), message='Multi-process bug in Mac OS X >= 10.7 ' '(see issue #636)'): """Test decorator that skips test if OS is Mac OS X and its major version is one of ``versions``. """ mac_version, _, _ = platform.mac_ver() skip = '.'.join(mac_version.split('.')[:2]) in versions def decorator(func): if skip: @wraps(func) def func(*args, **kwargs): raise SkipTest(message) return func return decorator def clean_warning_registry(): """Safe way to reset warnings """ warnings.resetwarnings() reg = "__warningregistry__" for mod_name, mod in list(sys.modules.items()): if 'six.moves' in mod_name: continue if hasattr(mod, reg): getattr(mod, reg).clear() def check_skip_network(): if int(os.environ.get('SKLEARN_SKIP_NETWORK_TESTS', 0)): raise SkipTest("Text tutorial requires large dataset download") def check_skip_travis(): """Skip test if being run on Travis.""" if os.environ.get('TRAVIS') == "true": raise SkipTest("This test needs to be skipped on Travis") with_network = with_setup(check_skip_network) with_travis = with_setup(check_skip_travis)
bsd-3-clause
bnaul/scikit-learn
sklearn/ensemble/tests/test_weight_boosting.py
9
21205
"""Testing for the boost module (sklearn.ensemble.boost).""" import numpy as np import pytest from scipy.sparse import csc_matrix from scipy.sparse import csr_matrix from scipy.sparse import coo_matrix from scipy.sparse import dok_matrix from scipy.sparse import lil_matrix from sklearn.utils._testing import assert_array_equal, assert_array_less from sklearn.utils._testing import assert_array_almost_equal from sklearn.utils._testing import assert_raises, assert_raises_regexp from sklearn.base import BaseEstimator from sklearn.base import clone from sklearn.dummy import DummyClassifier, DummyRegressor from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import AdaBoostRegressor from sklearn.ensemble._weight_boosting import _samme_proba from sklearn.svm import SVC, SVR from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.utils import shuffle from sklearn.utils._mocking import NoSampleWeightWrapper from sklearn import datasets # Common random state rng = np.random.RandomState(0) # Toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y_class = ["foo", "foo", "foo", 1, 1, 1] # test string class labels y_regr = [-1, -1, -1, 1, 1, 1] T = [[-1, -1], [2, 2], [3, 2]] y_t_class = ["foo", 1, 1] y_t_regr = [-1, 1, 1] # Load the iris dataset and randomly permute it iris = datasets.load_iris() perm = rng.permutation(iris.target.size) iris.data, iris.target = shuffle(iris.data, iris.target, random_state=rng) # Load the diabetes dataset and randomly permute it diabetes = datasets.load_diabetes() diabetes.data, diabetes.target = shuffle(diabetes.data, diabetes.target, random_state=rng) def test_samme_proba(): # Test the `_samme_proba` helper function. # Define some example (bad) `predict_proba` output. probs = np.array([[1, 1e-6, 0], [0.19, 0.6, 0.2], [-999, 0.51, 0.5], [1e-6, 1, 1e-9]]) probs /= np.abs(probs.sum(axis=1))[:, np.newaxis] # _samme_proba calls estimator.predict_proba. # Make a mock object so I can control what gets returned. class MockEstimator: def predict_proba(self, X): assert_array_equal(X.shape, probs.shape) return probs mock = MockEstimator() samme_proba = _samme_proba(mock, 3, np.ones_like(probs)) assert_array_equal(samme_proba.shape, probs.shape) assert np.isfinite(samme_proba).all() # Make sure that the correct elements come out as smallest -- # `_samme_proba` should preserve the ordering in each example. assert_array_equal(np.argmin(samme_proba, axis=1), [2, 0, 0, 2]) assert_array_equal(np.argmax(samme_proba, axis=1), [0, 1, 1, 1]) def test_oneclass_adaboost_proba(): # Test predict_proba robustness for one class label input. # In response to issue #7501 # https://github.com/scikit-learn/scikit-learn/issues/7501 y_t = np.ones(len(X)) clf = AdaBoostClassifier().fit(X, y_t) assert_array_almost_equal(clf.predict_proba(X), np.ones((len(X), 1))) @pytest.mark.parametrize("algorithm", ["SAMME", "SAMME.R"]) def test_classification_toy(algorithm): # Check classification on a toy dataset. clf = AdaBoostClassifier(algorithm=algorithm, random_state=0) clf.fit(X, y_class) assert_array_equal(clf.predict(T), y_t_class) assert_array_equal(np.unique(np.asarray(y_t_class)), clf.classes_) assert clf.predict_proba(T).shape == (len(T), 2) assert clf.decision_function(T).shape == (len(T),) def test_regression_toy(): # Check classification on a toy dataset. clf = AdaBoostRegressor(random_state=0) clf.fit(X, y_regr) assert_array_equal(clf.predict(T), y_t_regr) def test_iris(): # Check consistency on dataset iris. classes = np.unique(iris.target) clf_samme = prob_samme = None for alg in ['SAMME', 'SAMME.R']: clf = AdaBoostClassifier(algorithm=alg) clf.fit(iris.data, iris.target) assert_array_equal(classes, clf.classes_) proba = clf.predict_proba(iris.data) if alg == "SAMME": clf_samme = clf prob_samme = proba assert proba.shape[1] == len(classes) assert clf.decision_function(iris.data).shape[1] == len(classes) score = clf.score(iris.data, iris.target) assert score > 0.9, "Failed with algorithm %s and score = %f" % \ (alg, score) # Check we used multiple estimators assert len(clf.estimators_) > 1 # Check for distinct random states (see issue #7408) assert (len(set(est.random_state for est in clf.estimators_)) == len(clf.estimators_)) # Somewhat hacky regression test: prior to # ae7adc880d624615a34bafdb1d75ef67051b8200, # predict_proba returned SAMME.R values for SAMME. clf_samme.algorithm = "SAMME.R" assert_array_less(0, np.abs(clf_samme.predict_proba(iris.data) - prob_samme)) @pytest.mark.parametrize('loss', ['linear', 'square', 'exponential']) def test_diabetes(loss): # Check consistency on dataset diabetes. reg = AdaBoostRegressor(loss=loss, random_state=0) reg.fit(diabetes.data, diabetes.target) score = reg.score(diabetes.data, diabetes.target) assert score > 0.6 # Check we used multiple estimators assert len(reg.estimators_) > 1 # Check for distinct random states (see issue #7408) assert (len(set(est.random_state for est in reg.estimators_)) == len(reg.estimators_)) @pytest.mark.parametrize("algorithm", ["SAMME", "SAMME.R"]) def test_staged_predict(algorithm): # Check staged predictions. rng = np.random.RandomState(0) iris_weights = rng.randint(10, size=iris.target.shape) diabetes_weights = rng.randint(10, size=diabetes.target.shape) clf = AdaBoostClassifier(algorithm=algorithm, n_estimators=10) clf.fit(iris.data, iris.target, sample_weight=iris_weights) predictions = clf.predict(iris.data) staged_predictions = [p for p in clf.staged_predict(iris.data)] proba = clf.predict_proba(iris.data) staged_probas = [p for p in clf.staged_predict_proba(iris.data)] score = clf.score(iris.data, iris.target, sample_weight=iris_weights) staged_scores = [ s for s in clf.staged_score( iris.data, iris.target, sample_weight=iris_weights)] assert len(staged_predictions) == 10 assert_array_almost_equal(predictions, staged_predictions[-1]) assert len(staged_probas) == 10 assert_array_almost_equal(proba, staged_probas[-1]) assert len(staged_scores) == 10 assert_array_almost_equal(score, staged_scores[-1]) # AdaBoost regression clf = AdaBoostRegressor(n_estimators=10, random_state=0) clf.fit(diabetes.data, diabetes.target, sample_weight=diabetes_weights) predictions = clf.predict(diabetes.data) staged_predictions = [p for p in clf.staged_predict(diabetes.data)] score = clf.score(diabetes.data, diabetes.target, sample_weight=diabetes_weights) staged_scores = [ s for s in clf.staged_score( diabetes.data, diabetes.target, sample_weight=diabetes_weights)] assert len(staged_predictions) == 10 assert_array_almost_equal(predictions, staged_predictions[-1]) assert len(staged_scores) == 10 assert_array_almost_equal(score, staged_scores[-1]) def test_gridsearch(): # Check that base trees can be grid-searched. # AdaBoost classification boost = AdaBoostClassifier(base_estimator=DecisionTreeClassifier()) parameters = {'n_estimators': (1, 2), 'base_estimator__max_depth': (1, 2), 'algorithm': ('SAMME', 'SAMME.R')} clf = GridSearchCV(boost, parameters) clf.fit(iris.data, iris.target) # AdaBoost regression boost = AdaBoostRegressor(base_estimator=DecisionTreeRegressor(), random_state=0) parameters = {'n_estimators': (1, 2), 'base_estimator__max_depth': (1, 2)} clf = GridSearchCV(boost, parameters) clf.fit(diabetes.data, diabetes.target) def test_pickle(): # Check pickability. import pickle # Adaboost classifier for alg in ['SAMME', 'SAMME.R']: obj = AdaBoostClassifier(algorithm=alg) obj.fit(iris.data, iris.target) score = obj.score(iris.data, iris.target) s = pickle.dumps(obj) obj2 = pickle.loads(s) assert type(obj2) == obj.__class__ score2 = obj2.score(iris.data, iris.target) assert score == score2 # Adaboost regressor obj = AdaBoostRegressor(random_state=0) obj.fit(diabetes.data, diabetes.target) score = obj.score(diabetes.data, diabetes.target) s = pickle.dumps(obj) obj2 = pickle.loads(s) assert type(obj2) == obj.__class__ score2 = obj2.score(diabetes.data, diabetes.target) assert score == score2 def test_importances(): # Check variable importances. X, y = datasets.make_classification(n_samples=2000, n_features=10, n_informative=3, n_redundant=0, n_repeated=0, shuffle=False, random_state=1) for alg in ['SAMME', 'SAMME.R']: clf = AdaBoostClassifier(algorithm=alg) clf.fit(X, y) importances = clf.feature_importances_ assert importances.shape[0] == 10 assert (importances[:3, np.newaxis] >= importances[3:]).all() def test_error(): # Test that it gives proper exception on deficient input. assert_raises(ValueError, AdaBoostClassifier(learning_rate=-1).fit, X, y_class) assert_raises(ValueError, AdaBoostClassifier(algorithm="foo").fit, X, y_class) assert_raises(ValueError, AdaBoostClassifier().fit, X, y_class, sample_weight=np.asarray([-1])) def test_base_estimator(): # Test different base estimators. from sklearn.ensemble import RandomForestClassifier # XXX doesn't work with y_class because RF doesn't support classes_ # Shouldn't AdaBoost run a LabelBinarizer? clf = AdaBoostClassifier(RandomForestClassifier()) clf.fit(X, y_regr) clf = AdaBoostClassifier(SVC(), algorithm="SAMME") clf.fit(X, y_class) from sklearn.ensemble import RandomForestRegressor clf = AdaBoostRegressor(RandomForestRegressor(), random_state=0) clf.fit(X, y_regr) clf = AdaBoostRegressor(SVR(), random_state=0) clf.fit(X, y_regr) # Check that an empty discrete ensemble fails in fit, not predict. X_fail = [[1, 1], [1, 1], [1, 1], [1, 1]] y_fail = ["foo", "bar", 1, 2] clf = AdaBoostClassifier(SVC(), algorithm="SAMME") assert_raises_regexp(ValueError, "worse than random", clf.fit, X_fail, y_fail) def test_sparse_classification(): # Check classification with sparse input. class CustomSVC(SVC): """SVC variant that records the nature of the training set.""" def fit(self, X, y, sample_weight=None): """Modification on fit caries data type for later verification.""" super().fit(X, y, sample_weight=sample_weight) self.data_type_ = type(X) return self X, y = datasets.make_multilabel_classification(n_classes=1, n_samples=15, n_features=5, random_state=42) # Flatten y to a 1d array y = np.ravel(y) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) for sparse_format in [csc_matrix, csr_matrix, lil_matrix, coo_matrix, dok_matrix]: X_train_sparse = sparse_format(X_train) X_test_sparse = sparse_format(X_test) # Trained on sparse format sparse_classifier = AdaBoostClassifier( base_estimator=CustomSVC(probability=True), random_state=1, algorithm="SAMME" ).fit(X_train_sparse, y_train) # Trained on dense format dense_classifier = AdaBoostClassifier( base_estimator=CustomSVC(probability=True), random_state=1, algorithm="SAMME" ).fit(X_train, y_train) # predict sparse_results = sparse_classifier.predict(X_test_sparse) dense_results = dense_classifier.predict(X_test) assert_array_equal(sparse_results, dense_results) # decision_function sparse_results = sparse_classifier.decision_function(X_test_sparse) dense_results = dense_classifier.decision_function(X_test) assert_array_almost_equal(sparse_results, dense_results) # predict_log_proba sparse_results = sparse_classifier.predict_log_proba(X_test_sparse) dense_results = dense_classifier.predict_log_proba(X_test) assert_array_almost_equal(sparse_results, dense_results) # predict_proba sparse_results = sparse_classifier.predict_proba(X_test_sparse) dense_results = dense_classifier.predict_proba(X_test) assert_array_almost_equal(sparse_results, dense_results) # score sparse_results = sparse_classifier.score(X_test_sparse, y_test) dense_results = dense_classifier.score(X_test, y_test) assert_array_almost_equal(sparse_results, dense_results) # staged_decision_function sparse_results = sparse_classifier.staged_decision_function( X_test_sparse) dense_results = dense_classifier.staged_decision_function(X_test) for sprase_res, dense_res in zip(sparse_results, dense_results): assert_array_almost_equal(sprase_res, dense_res) # staged_predict sparse_results = sparse_classifier.staged_predict(X_test_sparse) dense_results = dense_classifier.staged_predict(X_test) for sprase_res, dense_res in zip(sparse_results, dense_results): assert_array_equal(sprase_res, dense_res) # staged_predict_proba sparse_results = sparse_classifier.staged_predict_proba(X_test_sparse) dense_results = dense_classifier.staged_predict_proba(X_test) for sprase_res, dense_res in zip(sparse_results, dense_results): assert_array_almost_equal(sprase_res, dense_res) # staged_score sparse_results = sparse_classifier.staged_score(X_test_sparse, y_test) dense_results = dense_classifier.staged_score(X_test, y_test) for sprase_res, dense_res in zip(sparse_results, dense_results): assert_array_equal(sprase_res, dense_res) # Verify sparsity of data is maintained during training types = [i.data_type_ for i in sparse_classifier.estimators_] assert all([(t == csc_matrix or t == csr_matrix) for t in types]) def test_sparse_regression(): # Check regression with sparse input. class CustomSVR(SVR): """SVR variant that records the nature of the training set.""" def fit(self, X, y, sample_weight=None): """Modification on fit caries data type for later verification.""" super().fit(X, y, sample_weight=sample_weight) self.data_type_ = type(X) return self X, y = datasets.make_regression(n_samples=15, n_features=50, n_targets=1, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) for sparse_format in [csc_matrix, csr_matrix, lil_matrix, coo_matrix, dok_matrix]: X_train_sparse = sparse_format(X_train) X_test_sparse = sparse_format(X_test) # Trained on sparse format sparse_classifier = AdaBoostRegressor( base_estimator=CustomSVR(), random_state=1 ).fit(X_train_sparse, y_train) # Trained on dense format dense_classifier = dense_results = AdaBoostRegressor( base_estimator=CustomSVR(), random_state=1 ).fit(X_train, y_train) # predict sparse_results = sparse_classifier.predict(X_test_sparse) dense_results = dense_classifier.predict(X_test) assert_array_almost_equal(sparse_results, dense_results) # staged_predict sparse_results = sparse_classifier.staged_predict(X_test_sparse) dense_results = dense_classifier.staged_predict(X_test) for sprase_res, dense_res in zip(sparse_results, dense_results): assert_array_almost_equal(sprase_res, dense_res) types = [i.data_type_ for i in sparse_classifier.estimators_] assert all([(t == csc_matrix or t == csr_matrix) for t in types]) def test_sample_weight_adaboost_regressor(): """ AdaBoostRegressor should work without sample_weights in the base estimator The random weighted sampling is done internally in the _boost method in AdaBoostRegressor. """ class DummyEstimator(BaseEstimator): def fit(self, X, y): pass def predict(self, X): return np.zeros(X.shape[0]) boost = AdaBoostRegressor(DummyEstimator(), n_estimators=3) boost.fit(X, y_regr) assert len(boost.estimator_weights_) == len(boost.estimator_errors_) def test_multidimensional_X(): """ Check that the AdaBoost estimators can work with n-dimensional data matrix """ rng = np.random.RandomState(0) X = rng.randn(50, 3, 3) yc = rng.choice([0, 1], 50) yr = rng.randn(50) boost = AdaBoostClassifier(DummyClassifier(strategy='most_frequent')) boost.fit(X, yc) boost.predict(X) boost.predict_proba(X) boost = AdaBoostRegressor(DummyRegressor()) boost.fit(X, yr) boost.predict(X) @pytest.mark.parametrize("algorithm", ['SAMME', 'SAMME.R']) def test_adaboostclassifier_without_sample_weight(algorithm): X, y = iris.data, iris.target base_estimator = NoSampleWeightWrapper(DummyClassifier()) clf = AdaBoostClassifier( base_estimator=base_estimator, algorithm=algorithm ) err_msg = ("{} doesn't support sample_weight" .format(base_estimator.__class__.__name__)) with pytest.raises(ValueError, match=err_msg): clf.fit(X, y) def test_adaboostregressor_sample_weight(): # check that giving weight will have an influence on the error computed # for a weak learner rng = np.random.RandomState(42) X = np.linspace(0, 100, num=1000) y = (.8 * X + 0.2) + (rng.rand(X.shape[0]) * 0.0001) X = X.reshape(-1, 1) # add an arbitrary outlier X[-1] *= 10 y[-1] = 10000 # random_state=0 ensure that the underlying bootstrap will use the outlier regr_no_outlier = AdaBoostRegressor( base_estimator=LinearRegression(), n_estimators=1, random_state=0 ) regr_with_weight = clone(regr_no_outlier) regr_with_outlier = clone(regr_no_outlier) # fit 3 models: # - a model containing the outlier # - a model without the outlier # - a model containing the outlier but with a null sample-weight regr_with_outlier.fit(X, y) regr_no_outlier.fit(X[:-1], y[:-1]) sample_weight = np.ones_like(y) sample_weight[-1] = 0 regr_with_weight.fit(X, y, sample_weight=sample_weight) score_with_outlier = regr_with_outlier.score(X[:-1], y[:-1]) score_no_outlier = regr_no_outlier.score(X[:-1], y[:-1]) score_with_weight = regr_with_weight.score(X[:-1], y[:-1]) assert score_with_outlier < score_no_outlier assert score_with_outlier < score_with_weight assert score_no_outlier == pytest.approx(score_with_weight) @pytest.mark.parametrize("algorithm", ["SAMME", "SAMME.R"]) def test_adaboost_consistent_predict(algorithm): # check that predict_proba and predict give consistent results # regression test for: # https://github.com/scikit-learn/scikit-learn/issues/14084 X_train, X_test, y_train, y_test = train_test_split( *datasets.load_digits(return_X_y=True), random_state=42 ) model = AdaBoostClassifier(algorithm=algorithm, random_state=42) model.fit(X_train, y_train) assert_array_equal( np.argmax(model.predict_proba(X_test), axis=1), model.predict(X_test) ) @pytest.mark.parametrize( 'model, X, y', [(AdaBoostClassifier(), iris.data, iris.target), (AdaBoostRegressor(), diabetes.data, diabetes.target)] ) def test_adaboost_negative_weight_error(model, X, y): sample_weight = np.ones_like(y) sample_weight[-1] = -10 err_msg = "sample_weight cannot contain negative weight" with pytest.raises(ValueError, match=err_msg): model.fit(X, y, sample_weight=sample_weight)
bsd-3-clause
ioreshnikov/wells
publish_xfrog.py
1
2084
#!/usr/bin/env python3 import argparse import scipy as s import scipy.fftpack as fft import matplotlib.pyplot as plot import wells.publisher as publisher parser = argparse.ArgumentParser() parser.add_argument("--t", type=float, help="Time at which diagram should be plotted") parser.add_argument("--width", type=float, default=1.0, help="Window width") parser.add_argument("--ext", help="output file extension", type=str, default="png") parser.add_argument("input", type=str, help="Path to the input file") args = parser.parse_args() workspace = s.load(args.input) t = workspace["t"] x = workspace["x"] k = workspace["k"] states = workspace["states"] background = workspace["background"] idx = abs(t - args.t).argmin() t = t[idx] state = states[idx, :] def xfrog(x0, state, delay, width): window = lambda x: s.exp(-(x/width)**2) diagram = s.zeros((len(x), len(delay)), dtype=complex) for idx in range(len(delay)): diagram[:, idx] = window(x - delay[idx]) * state diagram = fft.fft(diagram, axis=0) diagram = fft.fftshift(diagram, axes=[0]) return diagram delay = s.linspace(-64, +64, 2**11) image = xfrog(t, state, delay, args.width) image = abs(image) image = image / image.max() image = 20 * s.log10(image) publisher.init({"figure.figsize": (2.8, 2.4)}) prefix = args.input.replace(".npz", "") filename = prefix + "_xfrog=%.2f" % args.t plot.figure() axs = plot.subplot(1, 1, 1) plot.title(r"$t=%.2f$" % args.t, y=1.05) plot.pcolormesh( delay, k, image, cmap="magma", rasterized=True) plot.xlim(-20, +20) plot.xticks(s.arange(-40, +41, 20)) plot.ylim(-40, +40) plot.yticks(s.arange(-40, +41, 20)) plot.clim(-80, 0) plot.colorbar().set_ticks(s.arange(-80, 1, 20)) plot.xlabel(r"$z$") plot.ylabel(r"$k_z$") axs.tick_params(direction="out") publisher.publish(filename, args.ext) plot.close() print(filename + "." + args.ext)
mit
rajat1994/scikit-learn
sklearn/covariance/graph_lasso_.py
127
25626
"""GraphLasso: sparse inverse covariance estimation with an l1-penalized estimator. """ # Author: Gael Varoquaux <gael.varoquaux@normalesup.org> # License: BSD 3 clause # Copyright: INRIA import warnings import operator import sys import time import numpy as np from scipy import linalg from .empirical_covariance_ import (empirical_covariance, EmpiricalCovariance, log_likelihood) from ..utils import ConvergenceWarning from ..utils.extmath import pinvh from ..utils.validation import check_random_state, check_array from ..linear_model import lars_path from ..linear_model import cd_fast from ..cross_validation import check_cv, cross_val_score from ..externals.joblib import Parallel, delayed import collections # Helper functions to compute the objective and dual objective functions # of the l1-penalized estimator def _objective(mle, precision_, alpha): """Evaluation of the graph-lasso objective function the objective function is made of a shifted scaled version of the normalized log-likelihood (i.e. its empirical mean over the samples) and a penalisation term to promote sparsity """ p = precision_.shape[0] cost = - 2. * log_likelihood(mle, precision_) + p * np.log(2 * np.pi) cost += alpha * (np.abs(precision_).sum() - np.abs(np.diag(precision_)).sum()) return cost def _dual_gap(emp_cov, precision_, alpha): """Expression of the dual gap convergence criterion The specific definition is given in Duchi "Projected Subgradient Methods for Learning Sparse Gaussians". """ gap = np.sum(emp_cov * precision_) gap -= precision_.shape[0] gap += alpha * (np.abs(precision_).sum() - np.abs(np.diag(precision_)).sum()) return gap def alpha_max(emp_cov): """Find the maximum alpha for which there are some non-zeros off-diagonal. Parameters ---------- emp_cov : 2D array, (n_features, n_features) The sample covariance matrix Notes ----- This results from the bound for the all the Lasso that are solved in GraphLasso: each time, the row of cov corresponds to Xy. As the bound for alpha is given by `max(abs(Xy))`, the result follows. """ A = np.copy(emp_cov) A.flat[::A.shape[0] + 1] = 0 return np.max(np.abs(A)) # The g-lasso algorithm def graph_lasso(emp_cov, alpha, cov_init=None, mode='cd', tol=1e-4, enet_tol=1e-4, max_iter=100, verbose=False, return_costs=False, eps=np.finfo(np.float64).eps, return_n_iter=False): """l1-penalized covariance estimator Read more in the :ref:`User Guide <sparse_inverse_covariance>`. Parameters ---------- emp_cov : 2D ndarray, shape (n_features, n_features) Empirical covariance from which to compute the covariance estimate. alpha : positive float The regularization parameter: the higher alpha, the more regularization, the sparser the inverse covariance. cov_init : 2D array (n_features, n_features), optional The initial guess for the covariance. mode : {'cd', 'lars'} The Lasso solver to use: coordinate descent or LARS. Use LARS for very sparse underlying graphs, where p > n. Elsewhere prefer cd which is more numerically stable. tol : positive float, optional The tolerance to declare convergence: if the dual gap goes below this value, iterations are stopped. enet_tol : positive float, optional The tolerance for the elastic net solver used to calculate the descent direction. This parameter controls the accuracy of the search direction for a given column update, not of the overall parameter estimate. Only used for mode='cd'. max_iter : integer, optional The maximum number of iterations. verbose : boolean, optional If verbose is True, the objective function and dual gap are printed at each iteration. return_costs : boolean, optional If return_costs is True, the objective function and dual gap at each iteration are returned. eps : float, optional The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. return_n_iter : bool, optional Whether or not to return the number of iterations. Returns ------- covariance : 2D ndarray, shape (n_features, n_features) The estimated covariance matrix. precision : 2D ndarray, shape (n_features, n_features) The estimated (sparse) precision matrix. costs : list of (objective, dual_gap) pairs The list of values of the objective function and the dual gap at each iteration. Returned only if return_costs is True. n_iter : int Number of iterations. Returned only if `return_n_iter` is set to True. See Also -------- GraphLasso, GraphLassoCV Notes ----- The algorithm employed to solve this problem is the GLasso algorithm, from the Friedman 2008 Biostatistics paper. It is the same algorithm as in the R `glasso` package. One possible difference with the `glasso` R package is that the diagonal coefficients are not penalized. """ _, n_features = emp_cov.shape if alpha == 0: if return_costs: precision_ = linalg.inv(emp_cov) cost = - 2. * log_likelihood(emp_cov, precision_) cost += n_features * np.log(2 * np.pi) d_gap = np.sum(emp_cov * precision_) - n_features if return_n_iter: return emp_cov, precision_, (cost, d_gap), 0 else: return emp_cov, precision_, (cost, d_gap) else: if return_n_iter: return emp_cov, linalg.inv(emp_cov), 0 else: return emp_cov, linalg.inv(emp_cov) if cov_init is None: covariance_ = emp_cov.copy() else: covariance_ = cov_init.copy() # As a trivial regularization (Tikhonov like), we scale down the # off-diagonal coefficients of our starting point: This is needed, as # in the cross-validation the cov_init can easily be # ill-conditioned, and the CV loop blows. Beside, this takes # conservative stand-point on the initial conditions, and it tends to # make the convergence go faster. covariance_ *= 0.95 diagonal = emp_cov.flat[::n_features + 1] covariance_.flat[::n_features + 1] = diagonal precision_ = pinvh(covariance_) indices = np.arange(n_features) costs = list() # The different l1 regression solver have different numerical errors if mode == 'cd': errors = dict(over='raise', invalid='ignore') else: errors = dict(invalid='raise') try: # be robust to the max_iter=0 edge case, see: # https://github.com/scikit-learn/scikit-learn/issues/4134 d_gap = np.inf for i in range(max_iter): for idx in range(n_features): sub_covariance = covariance_[indices != idx].T[indices != idx] row = emp_cov[idx, indices != idx] with np.errstate(**errors): if mode == 'cd': # Use coordinate descent coefs = -(precision_[indices != idx, idx] / (precision_[idx, idx] + 1000 * eps)) coefs, _, _, _ = cd_fast.enet_coordinate_descent_gram( coefs, alpha, 0, sub_covariance, row, row, max_iter, enet_tol, check_random_state(None), False) else: # Use LARS _, _, coefs = lars_path( sub_covariance, row, Xy=row, Gram=sub_covariance, alpha_min=alpha / (n_features - 1), copy_Gram=True, method='lars', return_path=False) # Update the precision matrix precision_[idx, idx] = ( 1. / (covariance_[idx, idx] - np.dot(covariance_[indices != idx, idx], coefs))) precision_[indices != idx, idx] = (- precision_[idx, idx] * coefs) precision_[idx, indices != idx] = (- precision_[idx, idx] * coefs) coefs = np.dot(sub_covariance, coefs) covariance_[idx, indices != idx] = coefs covariance_[indices != idx, idx] = coefs d_gap = _dual_gap(emp_cov, precision_, alpha) cost = _objective(emp_cov, precision_, alpha) if verbose: print( '[graph_lasso] Iteration % 3i, cost % 3.2e, dual gap %.3e' % (i, cost, d_gap)) if return_costs: costs.append((cost, d_gap)) if np.abs(d_gap) < tol: break if not np.isfinite(cost) and i > 0: raise FloatingPointError('Non SPD result: the system is ' 'too ill-conditioned for this solver') else: warnings.warn('graph_lasso: did not converge after %i iteration:' ' dual gap: %.3e' % (max_iter, d_gap), ConvergenceWarning) except FloatingPointError as e: e.args = (e.args[0] + '. The system is too ill-conditioned for this solver',) raise e if return_costs: if return_n_iter: return covariance_, precision_, costs, i + 1 else: return covariance_, precision_, costs else: if return_n_iter: return covariance_, precision_, i + 1 else: return covariance_, precision_ class GraphLasso(EmpiricalCovariance): """Sparse inverse covariance estimation with an l1-penalized estimator. Read more in the :ref:`User Guide <sparse_inverse_covariance>`. Parameters ---------- alpha : positive float, default 0.01 The regularization parameter: the higher alpha, the more regularization, the sparser the inverse covariance. mode : {'cd', 'lars'}, default 'cd' The Lasso solver to use: coordinate descent or LARS. Use LARS for very sparse underlying graphs, where p > n. Elsewhere prefer cd which is more numerically stable. tol : positive float, default 1e-4 The tolerance to declare convergence: if the dual gap goes below this value, iterations are stopped. enet_tol : positive float, optional The tolerance for the elastic net solver used to calculate the descent direction. This parameter controls the accuracy of the search direction for a given column update, not of the overall parameter estimate. Only used for mode='cd'. max_iter : integer, default 100 The maximum number of iterations. verbose : boolean, default False If verbose is True, the objective function and dual gap are plotted at each iteration. assume_centered : boolean, default False If True, data are not centered before computation. Useful when working with data whose mean is almost, but not exactly zero. If False, data are centered before computation. Attributes ---------- covariance_ : array-like, shape (n_features, n_features) Estimated covariance matrix precision_ : array-like, shape (n_features, n_features) Estimated pseudo inverse matrix. n_iter_ : int Number of iterations run. See Also -------- graph_lasso, GraphLassoCV """ def __init__(self, alpha=.01, mode='cd', tol=1e-4, enet_tol=1e-4, max_iter=100, verbose=False, assume_centered=False): self.alpha = alpha self.mode = mode self.tol = tol self.enet_tol = enet_tol self.max_iter = max_iter self.verbose = verbose self.assume_centered = assume_centered # The base class needs this for the score method self.store_precision = True def fit(self, X, y=None): X = check_array(X) if self.assume_centered: self.location_ = np.zeros(X.shape[1]) else: self.location_ = X.mean(0) emp_cov = empirical_covariance( X, assume_centered=self.assume_centered) self.covariance_, self.precision_, self.n_iter_ = graph_lasso( emp_cov, alpha=self.alpha, mode=self.mode, tol=self.tol, enet_tol=self.enet_tol, max_iter=self.max_iter, verbose=self.verbose, return_n_iter=True) return self # Cross-validation with GraphLasso def graph_lasso_path(X, alphas, cov_init=None, X_test=None, mode='cd', tol=1e-4, enet_tol=1e-4, max_iter=100, verbose=False): """l1-penalized covariance estimator along a path of decreasing alphas Read more in the :ref:`User Guide <sparse_inverse_covariance>`. Parameters ---------- X : 2D ndarray, shape (n_samples, n_features) Data from which to compute the covariance estimate. alphas : list of positive floats The list of regularization parameters, decreasing order. X_test : 2D array, shape (n_test_samples, n_features), optional Optional test matrix to measure generalisation error. mode : {'cd', 'lars'} The Lasso solver to use: coordinate descent or LARS. Use LARS for very sparse underlying graphs, where p > n. Elsewhere prefer cd which is more numerically stable. tol : positive float, optional The tolerance to declare convergence: if the dual gap goes below this value, iterations are stopped. enet_tol : positive float, optional The tolerance for the elastic net solver used to calculate the descent direction. This parameter controls the accuracy of the search direction for a given column update, not of the overall parameter estimate. Only used for mode='cd'. max_iter : integer, optional The maximum number of iterations. verbose : integer, optional The higher the verbosity flag, the more information is printed during the fitting. Returns ------- covariances_ : List of 2D ndarray, shape (n_features, n_features) The estimated covariance matrices. precisions_ : List of 2D ndarray, shape (n_features, n_features) The estimated (sparse) precision matrices. scores_ : List of float The generalisation error (log-likelihood) on the test data. Returned only if test data is passed. """ inner_verbose = max(0, verbose - 1) emp_cov = empirical_covariance(X) if cov_init is None: covariance_ = emp_cov.copy() else: covariance_ = cov_init covariances_ = list() precisions_ = list() scores_ = list() if X_test is not None: test_emp_cov = empirical_covariance(X_test) for alpha in alphas: try: # Capture the errors, and move on covariance_, precision_ = graph_lasso( emp_cov, alpha=alpha, cov_init=covariance_, mode=mode, tol=tol, enet_tol=enet_tol, max_iter=max_iter, verbose=inner_verbose) covariances_.append(covariance_) precisions_.append(precision_) if X_test is not None: this_score = log_likelihood(test_emp_cov, precision_) except FloatingPointError: this_score = -np.inf covariances_.append(np.nan) precisions_.append(np.nan) if X_test is not None: if not np.isfinite(this_score): this_score = -np.inf scores_.append(this_score) if verbose == 1: sys.stderr.write('.') elif verbose > 1: if X_test is not None: print('[graph_lasso_path] alpha: %.2e, score: %.2e' % (alpha, this_score)) else: print('[graph_lasso_path] alpha: %.2e' % alpha) if X_test is not None: return covariances_, precisions_, scores_ return covariances_, precisions_ class GraphLassoCV(GraphLasso): """Sparse inverse covariance w/ cross-validated choice of the l1 penalty Read more in the :ref:`User Guide <sparse_inverse_covariance>`. Parameters ---------- alphas : integer, or list positive float, optional If an integer is given, it fixes the number of points on the grids of alpha to be used. If a list is given, it gives the grid to be used. See the notes in the class docstring for more details. n_refinements: strictly positive integer The number of times the grid is refined. Not used if explicit values of alphas are passed. cv : cross-validation generator, optional see sklearn.cross_validation module. If None is passed, defaults to a 3-fold strategy tol: positive float, optional The tolerance to declare convergence: if the dual gap goes below this value, iterations are stopped. enet_tol : positive float, optional The tolerance for the elastic net solver used to calculate the descent direction. This parameter controls the accuracy of the search direction for a given column update, not of the overall parameter estimate. Only used for mode='cd'. max_iter: integer, optional Maximum number of iterations. mode: {'cd', 'lars'} The Lasso solver to use: coordinate descent or LARS. Use LARS for very sparse underlying graphs, where number of features is greater than number of samples. Elsewhere prefer cd which is more numerically stable. n_jobs: int, optional number of jobs to run in parallel (default 1). verbose: boolean, optional If verbose is True, the objective function and duality gap are printed at each iteration. assume_centered : Boolean If True, data are not centered before computation. Useful when working with data whose mean is almost, but not exactly zero. If False, data are centered before computation. Attributes ---------- covariance_ : numpy.ndarray, shape (n_features, n_features) Estimated covariance matrix. precision_ : numpy.ndarray, shape (n_features, n_features) Estimated precision matrix (inverse covariance). alpha_ : float Penalization parameter selected. cv_alphas_ : list of float All penalization parameters explored. `grid_scores`: 2D numpy.ndarray (n_alphas, n_folds) Log-likelihood score on left-out data across folds. n_iter_ : int Number of iterations run for the optimal alpha. See Also -------- graph_lasso, GraphLasso Notes ----- The search for the optimal penalization parameter (alpha) is done on an iteratively refined grid: first the cross-validated scores on a grid are computed, then a new refined grid is centered around the maximum, and so on. One of the challenges which is faced here is that the solvers can fail to converge to a well-conditioned estimate. The corresponding values of alpha then come out as missing values, but the optimum may be close to these missing values. """ def __init__(self, alphas=4, n_refinements=4, cv=None, tol=1e-4, enet_tol=1e-4, max_iter=100, mode='cd', n_jobs=1, verbose=False, assume_centered=False): self.alphas = alphas self.n_refinements = n_refinements self.mode = mode self.tol = tol self.enet_tol = enet_tol self.max_iter = max_iter self.verbose = verbose self.cv = cv self.n_jobs = n_jobs self.assume_centered = assume_centered # The base class needs this for the score method self.store_precision = True def fit(self, X, y=None): """Fits the GraphLasso covariance model to X. Parameters ---------- X : ndarray, shape (n_samples, n_features) Data from which to compute the covariance estimate """ X = check_array(X) if self.assume_centered: self.location_ = np.zeros(X.shape[1]) else: self.location_ = X.mean(0) emp_cov = empirical_covariance( X, assume_centered=self.assume_centered) cv = check_cv(self.cv, X, y, classifier=False) # List of (alpha, scores, covs) path = list() n_alphas = self.alphas inner_verbose = max(0, self.verbose - 1) if isinstance(n_alphas, collections.Sequence): alphas = self.alphas n_refinements = 1 else: n_refinements = self.n_refinements alpha_1 = alpha_max(emp_cov) alpha_0 = 1e-2 * alpha_1 alphas = np.logspace(np.log10(alpha_0), np.log10(alpha_1), n_alphas)[::-1] t0 = time.time() for i in range(n_refinements): with warnings.catch_warnings(): # No need to see the convergence warnings on this grid: # they will always be points that will not converge # during the cross-validation warnings.simplefilter('ignore', ConvergenceWarning) # Compute the cross-validated loss on the current grid # NOTE: Warm-restarting graph_lasso_path has been tried, and # this did not allow to gain anything (same execution time with # or without). this_path = Parallel( n_jobs=self.n_jobs, verbose=self.verbose )( delayed(graph_lasso_path)( X[train], alphas=alphas, X_test=X[test], mode=self.mode, tol=self.tol, enet_tol=self.enet_tol, max_iter=int(.1 * self.max_iter), verbose=inner_verbose) for train, test in cv) # Little danse to transform the list in what we need covs, _, scores = zip(*this_path) covs = zip(*covs) scores = zip(*scores) path.extend(zip(alphas, scores, covs)) path = sorted(path, key=operator.itemgetter(0), reverse=True) # Find the maximum (avoid using built in 'max' function to # have a fully-reproducible selection of the smallest alpha # in case of equality) best_score = -np.inf last_finite_idx = 0 for index, (alpha, scores, _) in enumerate(path): this_score = np.mean(scores) if this_score >= .1 / np.finfo(np.float64).eps: this_score = np.nan if np.isfinite(this_score): last_finite_idx = index if this_score >= best_score: best_score = this_score best_index = index # Refine the grid if best_index == 0: # We do not need to go back: we have chosen # the highest value of alpha for which there are # non-zero coefficients alpha_1 = path[0][0] alpha_0 = path[1][0] elif (best_index == last_finite_idx and not best_index == len(path) - 1): # We have non-converged models on the upper bound of the # grid, we need to refine the grid there alpha_1 = path[best_index][0] alpha_0 = path[best_index + 1][0] elif best_index == len(path) - 1: alpha_1 = path[best_index][0] alpha_0 = 0.01 * path[best_index][0] else: alpha_1 = path[best_index - 1][0] alpha_0 = path[best_index + 1][0] if not isinstance(n_alphas, collections.Sequence): alphas = np.logspace(np.log10(alpha_1), np.log10(alpha_0), n_alphas + 2) alphas = alphas[1:-1] if self.verbose and n_refinements > 1: print('[GraphLassoCV] Done refinement % 2i out of %i: % 3is' % (i + 1, n_refinements, time.time() - t0)) path = list(zip(*path)) grid_scores = list(path[1]) alphas = list(path[0]) # Finally, compute the score with alpha = 0 alphas.append(0) grid_scores.append(cross_val_score(EmpiricalCovariance(), X, cv=cv, n_jobs=self.n_jobs, verbose=inner_verbose)) self.grid_scores = np.array(grid_scores) best_alpha = alphas[best_index] self.alpha_ = best_alpha self.cv_alphas_ = alphas # Finally fit the model with the selected alpha self.covariance_, self.precision_, self.n_iter_ = graph_lasso( emp_cov, alpha=best_alpha, mode=self.mode, tol=self.tol, enet_tol=self.enet_tol, max_iter=self.max_iter, verbose=inner_verbose, return_n_iter=True) return self
bsd-3-clause
Achuth17/scikit-learn
sklearn/metrics/__init__.py
52
3394
""" The :mod:`sklearn.metrics` module includes score functions, performance metrics and pairwise metrics and distance computations. """ from .ranking import auc from .ranking import average_precision_score from .ranking import coverage_error from .ranking import label_ranking_average_precision_score from .ranking import label_ranking_loss from .ranking import precision_recall_curve from .ranking import roc_auc_score from .ranking import roc_curve from .classification import accuracy_score from .classification import classification_report from .classification import confusion_matrix from .classification import f1_score from .classification import fbeta_score from .classification import hamming_loss from .classification import hinge_loss from .classification import jaccard_similarity_score from .classification import log_loss from .classification import matthews_corrcoef from .classification import precision_recall_fscore_support from .classification import precision_score from .classification import recall_score from .classification import zero_one_loss from .classification import brier_score_loss from . import cluster from .cluster import adjusted_mutual_info_score from .cluster import adjusted_rand_score from .cluster import completeness_score from .cluster import consensus_score from .cluster import homogeneity_completeness_v_measure from .cluster import homogeneity_score from .cluster import mutual_info_score from .cluster import normalized_mutual_info_score from .cluster import silhouette_samples from .cluster import silhouette_score from .cluster import v_measure_score from .pairwise import euclidean_distances from .pairwise import pairwise_distances from .pairwise import pairwise_distances_argmin from .pairwise import pairwise_distances_argmin_min from .pairwise import pairwise_kernels from .regression import explained_variance_score from .regression import mean_absolute_error from .regression import mean_squared_error from .regression import median_absolute_error from .regression import r2_score from .scorer import make_scorer from .scorer import SCORERS from .scorer import get_scorer __all__ = [ 'accuracy_score', 'adjusted_mutual_info_score', 'adjusted_rand_score', 'auc', 'average_precision_score', 'classification_report', 'cluster', 'completeness_score', 'confusion_matrix', 'consensus_score', 'coverage_error', 'euclidean_distances', 'explained_variance_score', 'f1_score', 'fbeta_score', 'get_scorer', 'hamming_loss', 'hinge_loss', 'homogeneity_completeness_v_measure', 'homogeneity_score', 'jaccard_similarity_score', 'label_ranking_average_precision_score', 'label_ranking_loss', 'log_loss', 'make_scorer', 'matthews_corrcoef', 'mean_absolute_error', 'mean_squared_error', 'median_absolute_error', 'mutual_info_score', 'normalized_mutual_info_score', 'pairwise_distances', 'pairwise_distances_argmin', 'pairwise_distances_argmin_min', 'pairwise_distances_argmin_min', 'pairwise_kernels', 'precision_recall_curve', 'precision_recall_fscore_support', 'precision_score', 'r2_score', 'recall_score', 'roc_auc_score', 'roc_curve', 'SCORERS', 'silhouette_samples', 'silhouette_score', 'v_measure_score', 'zero_one_loss', 'brier_score_loss', ]
bsd-3-clause
gigglesninja/senior-design
MissionPlanner/Lib/site-packages/numpy/lib/recfunctions.py
58
34495
""" Collection of utilities to manipulate structured arrays. Most of these functions were initially implemented by John Hunter for matplotlib. They have been rewritten and extended for convenience. """ import sys import itertools import numpy as np import numpy.ma as ma from numpy import ndarray, recarray from numpy.ma import MaskedArray from numpy.ma.mrecords import MaskedRecords from numpy.lib._iotools import _is_string_like _check_fill_value = np.ma.core._check_fill_value __all__ = ['append_fields', 'drop_fields', 'find_duplicates', 'get_fieldstructure', 'join_by', 'merge_arrays', 'rec_append_fields', 'rec_drop_fields', 'rec_join', 'recursive_fill_fields', 'rename_fields', 'stack_arrays', ] def recursive_fill_fields(input, output): """ Fills fields from output with fields from input, with support for nested structures. Parameters ---------- input : ndarray Input array. output : ndarray Output array. Notes ----- * `output` should be at least the same size as `input` Examples -------- >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, 10.), (2, 20.)], dtype=[('A', int), ('B', float)]) >>> b = np.zeros((3,), dtype=a.dtype) >>> rfn.recursive_fill_fields(a, b) array([(1, 10.0), (2, 20.0), (0, 0.0)], dtype=[('A', '<i4'), ('B', '<f8')]) """ newdtype = output.dtype for field in newdtype.names: try: current = input[field] except ValueError: continue if current.dtype.names: recursive_fill_fields(current, output[field]) else: output[field][:len(current)] = current return output def get_names(adtype): """ Returns the field names of the input datatype as a tuple. Parameters ---------- adtype : dtype Input datatype Examples -------- >>> from numpy.lib import recfunctions as rfn >>> rfn.get_names(np.empty((1,), dtype=int)) is None True >>> rfn.get_names(np.empty((1,), dtype=[('A',int), ('B', float)])) ('A', 'B') >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names(adtype) ('a', ('b', ('ba', 'bb'))) """ listnames = [] names = adtype.names for name in names: current = adtype[name] if current.names: listnames.append((name, tuple(get_names(current)))) else: listnames.append(name) return tuple(listnames) or None def get_names_flat(adtype): """ Returns the field names of the input datatype as a tuple. Nested structure are flattend beforehand. Parameters ---------- adtype : dtype Input datatype Examples -------- >>> from numpy.lib import recfunctions as rfn >>> rfn.get_names_flat(np.empty((1,), dtype=int)) is None True >>> rfn.get_names_flat(np.empty((1,), dtype=[('A',int), ('B', float)])) ('A', 'B') >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names_flat(adtype) ('a', 'b', 'ba', 'bb') """ listnames = [] names = adtype.names for name in names: listnames.append(name) current = adtype[name] if current.names: listnames.extend(get_names_flat(current)) return tuple(listnames) or None def flatten_descr(ndtype): """ Flatten a structured data-type description. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('a', '<i4'), ('b', [('ba', '<f8'), ('bb', '<i4')])]) >>> rfn.flatten_descr(ndtype) (('a', dtype('int32')), ('ba', dtype('float64')), ('bb', dtype('int32'))) """ names = ndtype.names if names is None: return ndtype.descr else: descr = [] for field in names: (typ, _) = ndtype.fields[field] if typ.names: descr.extend(flatten_descr(typ)) else: descr.append((field, typ)) return tuple(descr) def zip_descr(seqarrays, flatten=False): """ Combine the dtype description of a series of arrays. Parameters ---------- seqarrays : sequence of arrays Sequence of arrays flatten : {boolean}, optional Whether to collapse nested descriptions. """ newdtype = [] if flatten: for a in seqarrays: newdtype.extend(flatten_descr(a.dtype)) else: for a in seqarrays: current = a.dtype names = current.names or () if len(names) > 1: newdtype.append(('', current.descr)) else: newdtype.extend(current.descr) return np.dtype(newdtype).descr def get_fieldstructure(adtype, lastname=None, parents=None,): """ Returns a dictionary with fields as keys and a list of parent fields as values. This function is used to simplify access to fields nested in other fields. Parameters ---------- adtype : np.dtype Input datatype lastname : optional Last processed field name (used internally during recursion). parents : dictionary Dictionary of parent fields (used interbally during recursion). Examples -------- >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('A', int), ... ('B', [('BA', int), ... ('BB', [('BBA', int), ('BBB', int)])])]) >>> rfn.get_fieldstructure(ndtype) ... # XXX: possible regression, order of BBA and BBB is swapped {'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'], 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']} """ if parents is None: parents = {} names = adtype.names for name in names: current = adtype[name] if current.names: if lastname: parents[name] = [lastname, ] else: parents[name] = [] parents.update(get_fieldstructure(current, name, parents)) else: lastparent = [_ for _ in (parents.get(lastname, []) or [])] if lastparent: # if (lastparent[-1] != lastname): lastparent.append(lastname) elif lastname: lastparent = [lastname, ] parents[name] = lastparent or [] return parents or None def _izip_fields_flat(iterable): """ Returns an iterator of concatenated fields from a sequence of arrays, collapsing any nested structure. """ for element in iterable: if isinstance(element, np.void): for f in _izip_fields_flat(tuple(element)): yield f else: yield element def _izip_fields(iterable): """ Returns an iterator of concatenated fields from a sequence of arrays. """ for element in iterable: if hasattr(element, '__iter__') and not isinstance(element, basestring): for f in _izip_fields(element): yield f elif isinstance(element, np.void) and len(tuple(element)) == 1: for f in _izip_fields(element): yield f else: yield element def izip_records(seqarrays, fill_value=None, flatten=True): """ Returns an iterator of concatenated items from a sequence of arrays. Parameters ---------- seqarray : sequence of arrays Sequence of arrays. fill_value : {None, integer} Value used to pad shorter iterables. flatten : {True, False}, Whether to """ # OK, that's a complete ripoff from Python2.6 itertools.izip_longest def sentinel(counter=([fill_value] * (len(seqarrays) - 1)).pop): "Yields the fill_value or raises IndexError" yield counter() # fillers = itertools.repeat(fill_value) iters = [itertools.chain(it, sentinel(), fillers) for it in seqarrays] # Should we flatten the items, or just use a nested approach if flatten: zipfunc = _izip_fields_flat else: zipfunc = _izip_fields # try: for tup in itertools.izip(*iters): yield tuple(zipfunc(tup)) except IndexError: pass def _fix_output(output, usemask=True, asrecarray=False): """ Private function: return a recarray, a ndarray, a MaskedArray or a MaskedRecords depending on the input parameters """ if not isinstance(output, MaskedArray): usemask = False if usemask: if asrecarray: output = output.view(MaskedRecords) else: output = ma.filled(output) if asrecarray: output = output.view(recarray) return output def _fix_defaults(output, defaults=None): """ Update the fill_value and masked data of `output` from the default given in a dictionary defaults. """ names = output.dtype.names (data, mask, fill_value) = (output.data, output.mask, output.fill_value) for (k, v) in (defaults or {}).iteritems(): if k in names: fill_value[k] = v data[k][mask[k]] = v return output def merge_arrays(seqarrays, fill_value= -1, flatten=False, usemask=False, asrecarray=False): """ Merge arrays field by field. Parameters ---------- seqarrays : sequence of ndarrays Sequence of arrays fill_value : {float}, optional Filling value used to pad missing data on the shorter arrays. flatten : {False, True}, optional Whether to collapse nested fields. usemask : {False, True}, optional Whether to return a masked array or not. asrecarray : {False, True}, optional Whether to return a recarray (MaskedRecords) or not. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.]))) masked_array(data = [(1, 10.0) (2, 20.0) (--, 30.0)], mask = [(False, False) (False, False) (True, False)], fill_value = (999999, 1e+20), dtype = [('f0', '<i4'), ('f1', '<f8')]) >>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.])), ... usemask=False) array([(1, 10.0), (2, 20.0), (-1, 30.0)], dtype=[('f0', '<i4'), ('f1', '<f8')]) >>> rfn.merge_arrays((np.array([1, 2]).view([('a', int)]), ... np.array([10., 20., 30.])), ... usemask=False, asrecarray=True) rec.array([(1, 10.0), (2, 20.0), (-1, 30.0)], dtype=[('a', '<i4'), ('f1', '<f8')]) Notes ----- * Without a mask, the missing value will be filled with something, * depending on what its corresponding type: -1 for integers -1.0 for floating point numbers '-' for characters '-1' for strings True for boolean values * XXX: I just obtained these values empirically """ # Only one item in the input sequence ? if (len(seqarrays) == 1): seqarrays = np.asanyarray(seqarrays[0]) # Do we have a single ndarary as input ? if isinstance(seqarrays, (ndarray, np.void)): seqdtype = seqarrays.dtype if (not flatten) or \ (zip_descr((seqarrays,), flatten=True) == seqdtype.descr): # Minimal processing needed: just make sure everythng's a-ok seqarrays = seqarrays.ravel() # Make sure we have named fields if not seqdtype.names: seqdtype = [('', seqdtype)] # Find what type of array we must return if usemask: if asrecarray: seqtype = MaskedRecords else: seqtype = MaskedArray elif asrecarray: seqtype = recarray else: seqtype = ndarray return seqarrays.view(dtype=seqdtype, type=seqtype) else: seqarrays = (seqarrays,) else: # Make sure we have arrays in the input sequence seqarrays = map(np.asanyarray, seqarrays) # Find the sizes of the inputs and their maximum sizes = tuple(a.size for a in seqarrays) maxlength = max(sizes) # Get the dtype of the output (flattening if needed) newdtype = zip_descr(seqarrays, flatten=flatten) # Initialize the sequences for data and mask seqdata = [] seqmask = [] # If we expect some kind of MaskedArray, make a special loop. if usemask: for (a, n) in itertools.izip(seqarrays, sizes): nbmissing = (maxlength - n) # Get the data and mask data = a.ravel().__array__() mask = ma.getmaskarray(a).ravel() # Get the filling value (if needed) if nbmissing: fval = _check_fill_value(fill_value, a.dtype) if isinstance(fval, (ndarray, np.void)): if len(fval.dtype) == 1: fval = fval.item()[0] fmsk = True else: fval = np.array(fval, dtype=a.dtype, ndmin=1) fmsk = np.ones((1,), dtype=mask.dtype) else: fval = None fmsk = True # Store an iterator padding the input to the expected length seqdata.append(itertools.chain(data, [fval] * nbmissing)) seqmask.append(itertools.chain(mask, [fmsk] * nbmissing)) # Create an iterator for the data data = tuple(izip_records(seqdata, flatten=flatten)) output = ma.array(np.fromiter(data, dtype=newdtype, count=maxlength), mask=list(izip_records(seqmask, flatten=flatten))) if asrecarray: output = output.view(MaskedRecords) else: # Same as before, without the mask we don't need... for (a, n) in itertools.izip(seqarrays, sizes): nbmissing = (maxlength - n) data = a.ravel().__array__() if nbmissing: fval = _check_fill_value(fill_value, a.dtype) if isinstance(fval, (ndarray, np.void)): if len(fval.dtype) == 1: fval = fval.item()[0] else: fval = np.array(fval, dtype=a.dtype, ndmin=1) else: fval = None seqdata.append(itertools.chain(data, [fval] * nbmissing)) output = np.fromiter(tuple(izip_records(seqdata, flatten=flatten)), dtype=newdtype, count=maxlength) if asrecarray: output = output.view(recarray) # And we're done... return output def drop_fields(base, drop_names, usemask=True, asrecarray=False): """ Return a new array with fields in `drop_names` dropped. Nested fields are supported. Parameters ---------- base : array Input array drop_names : string or sequence String or sequence of strings corresponding to the names of the fields to drop. usemask : {False, True}, optional Whether to return a masked array or not. asrecarray : string or sequence Whether to return a recarray or a mrecarray (`asrecarray=True`) or a plain ndarray or masked array with flexible dtype (`asrecarray=False`) Examples -------- >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], ... dtype=[('a', int), ('b', [('ba', float), ('bb', int)])]) >>> rfn.drop_fields(a, 'a') array([((2.0, 3),), ((5.0, 6),)], dtype=[('b', [('ba', '<f8'), ('bb', '<i4')])]) >>> rfn.drop_fields(a, 'ba') array([(1, (3,)), (4, (6,))], dtype=[('a', '<i4'), ('b', [('bb', '<i4')])]) >>> rfn.drop_fields(a, ['ba', 'bb']) array([(1,), (4,)], dtype=[('a', '<i4')]) """ if _is_string_like(drop_names): drop_names = [drop_names, ] else: drop_names = set(drop_names) # def _drop_descr(ndtype, drop_names): names = ndtype.names newdtype = [] for name in names: current = ndtype[name] if name in drop_names: continue if current.names: descr = _drop_descr(current, drop_names) if descr: newdtype.append((name, descr)) else: newdtype.append((name, current)) return newdtype # newdtype = _drop_descr(base.dtype, drop_names) if not newdtype: return None # output = np.empty(base.shape, dtype=newdtype) output = recursive_fill_fields(base, output) return _fix_output(output, usemask=usemask, asrecarray=asrecarray) def rec_drop_fields(base, drop_names): """ Returns a new numpy.recarray with fields in `drop_names` dropped. """ return drop_fields(base, drop_names, usemask=False, asrecarray=True) def rename_fields(base, namemapper): """ Rename the fields from a flexible-datatype ndarray or recarray. Nested fields are supported. Parameters ---------- base : ndarray Input array whose fields must be modified. namemapper : dictionary Dictionary mapping old field names to their new version. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, [3.0, 30.])), (4, (5, [6.0, 60.]))], ... dtype=[('a', int),('b', [('ba', float), ('bb', (float, 2))])]) >>> rfn.rename_fields(a, {'a':'A', 'bb':'BB'}) array([(1, (2.0, [3.0, 30.0])), (4, (5.0, [6.0, 60.0]))], dtype=[('A', '<i4'), ('b', [('ba', '<f8'), ('BB', '<f8', 2)])]) """ def _recursive_rename_fields(ndtype, namemapper): newdtype = [] for name in ndtype.names: newname = namemapper.get(name, name) current = ndtype[name] if current.names: newdtype.append((newname, _recursive_rename_fields(current, namemapper))) else: newdtype.append((newname, current)) return newdtype newdtype = _recursive_rename_fields(base.dtype, namemapper) return base.view(newdtype) def append_fields(base, names, data=None, dtypes=None, fill_value= -1, usemask=True, asrecarray=False): """ Add new fields to an existing array. The names of the fields are given with the `names` arguments, the corresponding values with the `data` arguments. If a single field is appended, `names`, `data` and `dtypes` do not have to be lists but just values. Parameters ---------- base : array Input array to extend. names : string, sequence String or sequence of strings corresponding to the names of the new fields. data : array or sequence of arrays Array or sequence of arrays storing the fields to add to the base. dtypes : sequence of datatypes Datatype or sequence of datatypes. If None, the datatypes are estimated from the `data`. fill_value : {float}, optional Filling value used to pad missing data on the shorter arrays. usemask : {False, True}, optional Whether to return a masked array or not. asrecarray : {False, True}, optional Whether to return a recarray (MaskedRecords) or not. """ # Check the names if isinstance(names, (tuple, list)): if len(names) != len(data): err_msg = "The number of arrays does not match the number of names" raise ValueError(err_msg) elif isinstance(names, basestring): names = [names, ] data = [data, ] # if dtypes is None: data = [np.array(a, copy=False, subok=True) for a in data] data = [a.view([(name, a.dtype)]) for (name, a) in zip(names, data)] elif not hasattr(dtypes, '__iter__'): dtypes = [dtypes, ] if len(data) != len(dtypes): if len(dtypes) == 1: dtypes = dtypes * len(data) else: msg = "The dtypes argument must be None, "\ "a single dtype or a list." raise ValueError(msg) data = [np.array(a, copy=False, subok=True, dtype=d).view([(n, d)]) for (a, n, d) in zip(data, names, dtypes)] # base = merge_arrays(base, usemask=usemask, fill_value=fill_value) if len(data) > 1: data = merge_arrays(data, flatten=True, usemask=usemask, fill_value=fill_value) else: data = data.pop() # output = ma.masked_all(max(len(base), len(data)), dtype=base.dtype.descr + data.dtype.descr) output = recursive_fill_fields(base, output) output = recursive_fill_fields(data, output) # return _fix_output(output, usemask=usemask, asrecarray=asrecarray) def rec_append_fields(base, names, data, dtypes=None): """ Add new fields to an existing array. The names of the fields are given with the `names` arguments, the corresponding values with the `data` arguments. If a single field is appended, `names`, `data` and `dtypes` do not have to be lists but just values. Parameters ---------- base : array Input array to extend. names : string, sequence String or sequence of strings corresponding to the names of the new fields. data : array or sequence of arrays Array or sequence of arrays storing the fields to add to the base. dtypes : sequence of datatypes, optional Datatype or sequence of datatypes. If None, the datatypes are estimated from the `data`. See Also -------- append_fields Returns ------- appended_array : np.recarray """ return append_fields(base, names, data=data, dtypes=dtypes, asrecarray=True, usemask=False) def stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False, autoconvert=False): """ Superposes arrays fields by fields Parameters ---------- seqarrays : array or sequence Sequence of input arrays. defaults : dictionary, optional Dictionary mapping field names to the corresponding default values. usemask : {True, False}, optional Whether to return a MaskedArray (or MaskedRecords is `asrecarray==True`) or a ndarray. asrecarray : {False, True}, optional Whether to return a recarray (or MaskedRecords if `usemask==True`) or just a flexible-type ndarray. autoconvert : {False, True}, optional Whether automatically cast the type of the field to the maximum. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> x = np.array([1, 2,]) >>> rfn.stack_arrays(x) is x True >>> z = np.array([('A', 1), ('B', 2)], dtype=[('A', '|S3'), ('B', float)]) >>> zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)], ... dtype=[('A', '|S3'), ('B', float), ('C', float)]) >>> test = rfn.stack_arrays((z,zz)) >>> test masked_array(data = [('A', 1.0, --) ('B', 2.0, --) ('a', 10.0, 100.0) ('b', 20.0, 200.0) ('c', 30.0, 300.0)], mask = [(False, False, True) (False, False, True) (False, False, False) (False, False, False) (False, False, False)], fill_value = ('N/A', 1e+20, 1e+20), dtype = [('A', '|S3'), ('B', '<f8'), ('C', '<f8')]) """ if isinstance(arrays, ndarray): return arrays elif len(arrays) == 1: return arrays[0] seqarrays = [np.asanyarray(a).ravel() for a in arrays] nrecords = [len(a) for a in seqarrays] ndtype = [a.dtype for a in seqarrays] fldnames = [d.names for d in ndtype] # dtype_l = ndtype[0] newdescr = dtype_l.descr names = [_[0] for _ in newdescr] for dtype_n in ndtype[1:]: for descr in dtype_n.descr: name = descr[0] or '' if name not in names: newdescr.append(descr) names.append(name) else: nameidx = names.index(name) current_descr = newdescr[nameidx] if autoconvert: if np.dtype(descr[1]) > np.dtype(current_descr[-1]): current_descr = list(current_descr) current_descr[-1] = descr[1] newdescr[nameidx] = tuple(current_descr) elif descr[1] != current_descr[-1]: raise TypeError("Incompatible type '%s' <> '%s'" % \ (dict(newdescr)[name], descr[1])) # Only one field: use concatenate if len(newdescr) == 1: output = ma.concatenate(seqarrays) else: # output = ma.masked_all((np.sum(nrecords),), newdescr) offset = np.cumsum(np.r_[0, nrecords]) seen = [] for (a, n, i, j) in zip(seqarrays, fldnames, offset[:-1], offset[1:]): names = a.dtype.names if names is None: output['f%i' % len(seen)][i:j] = a else: for name in n: output[name][i:j] = a[name] if name not in seen: seen.append(name) # return _fix_output(_fix_defaults(output, defaults), usemask=usemask, asrecarray=asrecarray) def find_duplicates(a, key=None, ignoremask=True, return_index=False): """ Find the duplicates in a structured array along a given key Parameters ---------- a : array-like Input array key : {string, None}, optional Name of the fields along which to check the duplicates. If None, the search is performed by records ignoremask : {True, False}, optional Whether masked data should be discarded or considered as duplicates. return_index : {False, True}, optional Whether to return the indices of the duplicated values. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> ndtype = [('a', int)] >>> a = np.ma.array([1, 1, 1, 2, 2, 3, 3], ... mask=[0, 0, 1, 0, 0, 0, 1]).view(ndtype) >>> rfn.find_duplicates(a, ignoremask=True, return_index=True) ... # XXX: judging by the output, the ignoremask flag has no effect """ a = np.asanyarray(a).ravel() # Get a dictionary of fields fields = get_fieldstructure(a.dtype) # Get the sorting data (by selecting the corresponding field) base = a if key: for f in fields[key]: base = base[f] base = base[key] # Get the sorting indices and the sorted data sortidx = base.argsort() sortedbase = base[sortidx] sorteddata = sortedbase.filled() # Compare the sorting data flag = (sorteddata[:-1] == sorteddata[1:]) # If masked data must be ignored, set the flag to false where needed if ignoremask: sortedmask = sortedbase.recordmask flag[sortedmask[1:]] = False flag = np.concatenate(([False], flag)) # We need to take the point on the left as well (else we're missing it) flag[:-1] = flag[:-1] + flag[1:] duplicates = a[sortidx][flag] if return_index: return (duplicates, sortidx[flag]) else: return duplicates def join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None, usemask=True, asrecarray=False): """ Join arrays `r1` and `r2` on key `key`. The key should be either a string or a sequence of string corresponding to the fields used to join the array. An exception is raised if the `key` field cannot be found in the two input arrays. Neither `r1` nor `r2` should have any duplicates along `key`: the presence of duplicates will make the output quite unreliable. Note that duplicates are not looked for by the algorithm. Parameters ---------- key : {string, sequence} A string or a sequence of strings corresponding to the fields used for comparison. r1, r2 : arrays Structured arrays. jointype : {'inner', 'outer', 'leftouter'}, optional If 'inner', returns the elements common to both r1 and r2. If 'outer', returns the common elements as well as the elements of r1 not in r2 and the elements of not in r2. If 'leftouter', returns the common elements and the elements of r1 not in r2. r1postfix : string, optional String appended to the names of the fields of r1 that are present in r2 but absent of the key. r2postfix : string, optional String appended to the names of the fields of r2 that are present in r1 but absent of the key. defaults : {dictionary}, optional Dictionary mapping field names to the corresponding default values. usemask : {True, False}, optional Whether to return a MaskedArray (or MaskedRecords is `asrecarray==True`) or a ndarray. asrecarray : {False, True}, optional Whether to return a recarray (or MaskedRecords if `usemask==True`) or just a flexible-type ndarray. Notes ----- * The output is sorted along the key. * A temporary array is formed by dropping the fields not in the key for the two arrays and concatenating the result. This array is then sorted, and the common entries selected. The output is constructed by filling the fields with the selected entries. Matching is not preserved if there are some duplicates... """ # Check jointype if jointype not in ('inner', 'outer', 'leftouter'): raise ValueError("The 'jointype' argument should be in 'inner', "\ "'outer' or 'leftouter' (got '%s' instead)" % jointype) # If we have a single key, put it in a tuple if isinstance(key, basestring): key = (key,) # Check the keys for name in key: if name not in r1.dtype.names: raise ValueError('r1 does not have key field %s' % name) if name not in r2.dtype.names: raise ValueError('r2 does not have key field %s' % name) # Make sure we work with ravelled arrays r1 = r1.ravel() r2 = r2.ravel() (nb1, nb2) = (len(r1), len(r2)) (r1names, r2names) = (r1.dtype.names, r2.dtype.names) # Make temporary arrays of just the keys r1k = drop_fields(r1, [n for n in r1names if n not in key]) r2k = drop_fields(r2, [n for n in r2names if n not in key]) # Concatenate the two arrays for comparison aux = ma.concatenate((r1k, r2k)) idx_sort = aux.argsort(order=key) aux = aux[idx_sort] # # Get the common keys flag_in = ma.concatenate(([False], aux[1:] == aux[:-1])) flag_in[:-1] = flag_in[1:] + flag_in[:-1] idx_in = idx_sort[flag_in] idx_1 = idx_in[(idx_in < nb1)] idx_2 = idx_in[(idx_in >= nb1)] - nb1 (r1cmn, r2cmn) = (len(idx_1), len(idx_2)) if jointype == 'inner': (r1spc, r2spc) = (0, 0) elif jointype == 'outer': idx_out = idx_sort[~flag_in] idx_1 = np.concatenate((idx_1, idx_out[(idx_out < nb1)])) idx_2 = np.concatenate((idx_2, idx_out[(idx_out >= nb1)] - nb1)) (r1spc, r2spc) = (len(idx_1) - r1cmn, len(idx_2) - r2cmn) elif jointype == 'leftouter': idx_out = idx_sort[~flag_in] idx_1 = np.concatenate((idx_1, idx_out[(idx_out < nb1)])) (r1spc, r2spc) = (len(idx_1) - r1cmn, 0) # Select the entries from each input (s1, s2) = (r1[idx_1], r2[idx_2]) # # Build the new description of the output array ....... # Start with the key fields ndtype = [list(_) for _ in r1k.dtype.descr] # Add the other fields ndtype.extend(list(_) for _ in r1.dtype.descr if _[0] not in key) # Find the new list of names (it may be different from r1names) names = list(_[0] for _ in ndtype) for desc in r2.dtype.descr: desc = list(desc) name = desc[0] # Have we seen the current name already ? if name in names: nameidx = names.index(name) current = ndtype[nameidx] # The current field is part of the key: take the largest dtype if name in key: current[-1] = max(desc[1], current[-1]) # The current field is not part of the key: add the suffixes else: current[0] += r1postfix desc[0] += r2postfix ndtype.insert(nameidx + 1, desc) #... we haven't: just add the description to the current list else: names.extend(desc[0]) ndtype.append(desc) # Revert the elements to tuples ndtype = [tuple(_) for _ in ndtype] # Find the largest nb of common fields : r1cmn and r2cmn should be equal, but... cmn = max(r1cmn, r2cmn) # Construct an empty array output = ma.masked_all((cmn + r1spc + r2spc,), dtype=ndtype) names = output.dtype.names for f in r1names: selected = s1[f] if f not in names: f += r1postfix current = output[f] current[:r1cmn] = selected[:r1cmn] if jointype in ('outer', 'leftouter'): current[cmn:cmn + r1spc] = selected[r1cmn:] for f in r2names: selected = s2[f] if f not in names: f += r2postfix current = output[f] current[:r2cmn] = selected[:r2cmn] if (jointype == 'outer') and r2spc: current[-r2spc:] = selected[r2cmn:] # Sort and finalize the output output.sort(order=key) kwargs = dict(usemask=usemask, asrecarray=asrecarray) return _fix_output(_fix_defaults(output, defaults), **kwargs) def rec_join(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None): """ Join arrays `r1` and `r2` on keys. Alternative to join_by, that always returns a np.recarray. See Also -------- join_by : equivalent function """ kwargs = dict(jointype=jointype, r1postfix=r1postfix, r2postfix=r2postfix, defaults=defaults, usemask=False, asrecarray=True) return join_by(key, r1, r2, **kwargs)
gpl-2.0
khkaminska/scikit-learn
sklearn/decomposition/tests/test_nmf.py
47
8566
import numpy as np from scipy import linalg from sklearn.decomposition import nmf from scipy.sparse import csc_matrix from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_raise_message from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_less from sklearn.utils.testing import ignore_warnings from sklearn.base import clone random_state = np.random.mtrand.RandomState(0) def test_initialize_nn_output(): # Test that initialization does not return negative values data = np.abs(random_state.randn(10, 10)) for init in ('random', 'nndsvd', 'nndsvda', 'nndsvdar'): W, H = nmf._initialize_nmf(data, 10, init=init, random_state=0) assert_false((W < 0).any() or (H < 0).any()) @ignore_warnings def test_parameter_checking(): A = np.ones((2, 2)) name = 'spam' msg = "Invalid solver parameter: got 'spam' instead of one of" assert_raise_message(ValueError, msg, nmf.NMF(solver=name).fit, A) msg = "Invalid init parameter: got 'spam' instead of one of" assert_raise_message(ValueError, msg, nmf.NMF(init=name).fit, A) msg = "Invalid sparseness parameter: got 'spam' instead of one of" assert_raise_message(ValueError, msg, nmf.NMF(sparseness=name).fit, A) msg = "Negative values in data passed to" assert_raise_message(ValueError, msg, nmf.NMF().fit, -A) assert_raise_message(ValueError, msg, nmf._initialize_nmf, -A, 2, 'nndsvd') clf = nmf.NMF(2, tol=0.1).fit(A) assert_raise_message(ValueError, msg, clf.transform, -A) def test_initialize_close(): # Test NNDSVD error # Test that _initialize_nmf error is less than the standard deviation of # the entries in the matrix. A = np.abs(random_state.randn(10, 10)) W, H = nmf._initialize_nmf(A, 10, init='nndsvd') error = linalg.norm(np.dot(W, H) - A) sdev = linalg.norm(A - A.mean()) assert_true(error <= sdev) def test_initialize_variants(): # Test NNDSVD variants correctness # Test that the variants 'nndsvda' and 'nndsvdar' differ from basic # 'nndsvd' only where the basic version has zeros. data = np.abs(random_state.randn(10, 10)) W0, H0 = nmf._initialize_nmf(data, 10, init='nndsvd') Wa, Ha = nmf._initialize_nmf(data, 10, init='nndsvda') War, Har = nmf._initialize_nmf(data, 10, init='nndsvdar', random_state=0) for ref, evl in ((W0, Wa), (W0, War), (H0, Ha), (H0, Har)): assert_true(np.allclose(evl[ref != 0], ref[ref != 0])) @ignore_warnings def test_nmf_fit_nn_output(): # Test that the decomposition does not contain negative values A = np.c_[5 * np.ones(5) - np.arange(1, 6), 5 * np.ones(5) + np.arange(1, 6)] for solver in ('pg', 'cd'): for init in (None, 'nndsvd', 'nndsvda', 'nndsvdar'): model = nmf.NMF(n_components=2, solver=solver, init=init, random_state=0) transf = model.fit_transform(A) assert_false((model.components_ < 0).any() or (transf < 0).any()) @ignore_warnings def test_nmf_fit_close(): # Test that the fit is not too far away for solver in ('pg', 'cd'): pnmf = nmf.NMF(5, solver=solver, init='nndsvd', random_state=0) X = np.abs(random_state.randn(6, 5)) assert_less(pnmf.fit(X).reconstruction_err_, 0.05) def test_nls_nn_output(): # Test that NLS solver doesn't return negative values A = np.arange(1, 5).reshape(1, -1) Ap, _, _ = nmf._nls_subproblem(np.dot(A.T, -A), A.T, A, 0.001, 100) assert_false((Ap < 0).any()) def test_nls_close(): # Test that the NLS results should be close A = np.arange(1, 5).reshape(1, -1) Ap, _, _ = nmf._nls_subproblem(np.dot(A.T, A), A.T, np.zeros_like(A), 0.001, 100) assert_true((np.abs(Ap - A) < 0.01).all()) @ignore_warnings def test_nmf_transform(): # Test that NMF.transform returns close values A = np.abs(random_state.randn(6, 5)) for solver in ('pg', 'cd'): m = nmf.NMF(solver=solver, n_components=4, init='nndsvd', random_state=0) ft = m.fit_transform(A) t = m.transform(A) assert_array_almost_equal(ft, t, decimal=2) @ignore_warnings def test_n_components_greater_n_features(): # Smoke test for the case of more components than features. A = np.abs(random_state.randn(30, 10)) nmf.NMF(n_components=15, random_state=0, tol=1e-2).fit(A) @ignore_warnings def test_projgrad_nmf_sparseness(): # Test sparseness # Test that sparsity constraints actually increase sparseness in the # part where they are applied. tol = 1e-2 A = np.abs(random_state.randn(10, 10)) m = nmf.ProjectedGradientNMF(n_components=5, random_state=0, tol=tol).fit(A) data_sp = nmf.ProjectedGradientNMF(n_components=5, sparseness='data', random_state=0, tol=tol).fit(A).data_sparseness_ comp_sp = nmf.ProjectedGradientNMF(n_components=5, sparseness='components', random_state=0, tol=tol).fit(A).comp_sparseness_ assert_greater(data_sp, m.data_sparseness_) assert_greater(comp_sp, m.comp_sparseness_) @ignore_warnings def test_sparse_input(): # Test that sparse matrices are accepted as input from scipy.sparse import csc_matrix A = np.abs(random_state.randn(10, 10)) A[:, 2 * np.arange(5)] = 0 A_sparse = csc_matrix(A) for solver in ('pg', 'cd'): est1 = nmf.NMF(solver=solver, n_components=5, init='random', random_state=0, tol=1e-2) est2 = clone(est1) W1 = est1.fit_transform(A) W2 = est2.fit_transform(A_sparse) H1 = est1.components_ H2 = est2.components_ assert_array_almost_equal(W1, W2) assert_array_almost_equal(H1, H2) @ignore_warnings def test_sparse_transform(): # Test that transform works on sparse data. Issue #2124 A = np.abs(random_state.randn(3, 2)) A[A > 1.0] = 0 A = csc_matrix(A) for solver in ('pg', 'cd'): model = nmf.NMF(solver=solver, random_state=0, tol=1e-4, n_components=2) A_fit_tr = model.fit_transform(A) A_tr = model.transform(A) assert_array_almost_equal(A_fit_tr, A_tr, decimal=1) @ignore_warnings def test_non_negative_factorization_consistency(): # Test that the function is called in the same way, either directly # or through the NMF class A = np.abs(random_state.randn(10, 10)) A[:, 2 * np.arange(5)] = 0 for solver in ('pg', 'cd'): W_nmf, H, _ = nmf.non_negative_factorization( A, solver=solver, random_state=1, tol=1e-2) W_nmf_2, _, _ = nmf.non_negative_factorization( A, H=H, update_H=False, solver=solver, random_state=1, tol=1e-2) model_class = nmf.NMF(solver=solver, random_state=1, tol=1e-2) W_cls = model_class.fit_transform(A) W_cls_2 = model_class.transform(A) assert_array_almost_equal(W_nmf, W_cls, decimal=10) assert_array_almost_equal(W_nmf_2, W_cls_2, decimal=10) @ignore_warnings def test_non_negative_factorization_checking(): A = np.ones((2, 2)) # Test parameters checking is public function nnmf = nmf.non_negative_factorization msg = "Number of components must be positive; got (n_components='2')" assert_raise_message(ValueError, msg, nnmf, A, A, A, '2') msg = "Negative values in data passed to NMF (input H)" assert_raise_message(ValueError, msg, nnmf, A, A, -A, 2, 'custom') msg = "Negative values in data passed to NMF (input W)" assert_raise_message(ValueError, msg, nnmf, A, -A, A, 2, 'custom') msg = "Array passed to NMF (input H) is full of zeros" assert_raise_message(ValueError, msg, nnmf, A, A, 0 * A, 2, 'custom') def test_safe_compute_error(): A = np.abs(random_state.randn(10, 10)) A[:, 2 * np.arange(5)] = 0 A_sparse = csc_matrix(A) W, H = nmf._initialize_nmf(A, 5, init='random', random_state=0) error = nmf._safe_compute_error(A, W, H) error_sparse = nmf._safe_compute_error(A_sparse, W, H) assert_almost_equal(error, error_sparse)
bsd-3-clause
liang42hao/bokeh
examples/compat/seaborn/violin.py
34
1153
import seaborn as sns from bokeh import mpl from bokeh.plotting import output_file, show tips = sns.load_dataset("tips") sns.set_style("whitegrid") # ax = sns.violinplot(x="size", y="tip", data=tips.sort("size")) # ax = sns.violinplot(x="size", y="tip", data=tips, # order=np.arange(1, 7), palette="Blues_d") # ax = sns.violinplot(x="day", y="total_bill", hue="sex", # data=tips, palette="Set2", split=True, # scale="count") ax = sns.violinplot(x="day", y="total_bill", hue="sex", data=tips, palette="Set2", split=True, scale="count", inner="stick") # ax = sns.violinplot(x="day", y="total_bill", hue="smoker", # data=tips, palette="muted", split=True) # ax = sns.violinplot(x="day", y="total_bill", hue="smoker", # data=tips, palette="muted") # planets = sns.load_dataset("planets") # ax = sns.violinplot(x="orbital_period", y="method", # data=planets[planets.orbital_period < 1000], # scale="width", palette="Set3") output_file("violin.html") show(mpl.to_bokeh())
bsd-3-clause
Adai0808/scikit-learn
examples/feature_selection/plot_feature_selection.py
249
2827
""" =============================== Univariate Feature Selection =============================== An example showing univariate feature selection. Noisy (non informative) features are added to the iris data and univariate feature selection is applied. For each feature, we plot the p-values for the univariate feature selection and the corresponding weights of an SVM. We can see that univariate feature selection selects the informative features and that these have larger SVM weights. In the total set of features, only the 4 first ones are significant. We can see that they have the highest score with univariate feature selection. The SVM assigns a large weight to one of these features, but also Selects many of the non-informative features. Applying univariate feature selection before the SVM increases the SVM weight attributed to the significant features, and will thus improve classification. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, svm from sklearn.feature_selection import SelectPercentile, f_classif ############################################################################### # import some data to play with # The iris dataset iris = datasets.load_iris() # Some noisy data not correlated E = np.random.uniform(0, 0.1, size=(len(iris.data), 20)) # Add the noisy data to the informative features X = np.hstack((iris.data, E)) y = iris.target ############################################################################### plt.figure(1) plt.clf() X_indices = np.arange(X.shape[-1]) ############################################################################### # Univariate feature selection with F-test for feature scoring # We use the default selection function: the 10% most significant features selector = SelectPercentile(f_classif, percentile=10) selector.fit(X, y) scores = -np.log10(selector.pvalues_) scores /= scores.max() plt.bar(X_indices - .45, scores, width=.2, label=r'Univariate score ($-Log(p_{value})$)', color='g') ############################################################################### # Compare to the weights of an SVM clf = svm.SVC(kernel='linear') clf.fit(X, y) svm_weights = (clf.coef_ ** 2).sum(axis=0) svm_weights /= svm_weights.max() plt.bar(X_indices - .25, svm_weights, width=.2, label='SVM weight', color='r') clf_selected = svm.SVC(kernel='linear') clf_selected.fit(selector.transform(X), y) svm_weights_selected = (clf_selected.coef_ ** 2).sum(axis=0) svm_weights_selected /= svm_weights_selected.max() plt.bar(X_indices[selector.get_support()] - .05, svm_weights_selected, width=.2, label='SVM weights after selection', color='b') plt.title("Comparing feature selection") plt.xlabel('Feature number') plt.yticks(()) plt.axis('tight') plt.legend(loc='upper right') plt.show()
bsd-3-clause
sniemi/EuclidVisibleInstrument
analysis/analyse.py
1
10786
""" Object finding and measuring ellipticity ======================================== This script provides a class that can be used to analyse VIS data. One can either choose to use a Python based source finding algorithm or give a SExtractor catalog as an input. If an input catalog is provided then the program assumes that X_IMAGE and Y_IMAGE columns are present in the input file. :requires: PyFITS :requires: NumPy :requires: matplotlib :author: Sami-Matias Niemi :contact: smn2@mssl.ucl.ac.uk :version: 0.2 """ import matplotlib matplotlib.rc('text', usetex=True) matplotlib.rcParams['font.size'] = 17 matplotlib.rc('xtick', labelsize=14) matplotlib.rc('axes', linewidth=1.1) matplotlib.rcParams['legend.fontsize'] = 11 matplotlib.rcParams['legend.handlelength'] = 3 matplotlib.rcParams['xtick.major.size'] = 5 matplotlib.rcParams['ytick.major.size'] = 5 matplotlib.use('PDF') import pyfits as pf import numpy as np import sys import matplotlib.pyplot as plt from optparse import OptionParser from sourceFinder import sourceFinder from support import sextutils from support import logger as lg from analysis import shape class analyseVISdata(): """ Simple class that can be used to find objects and measure their ellipticities. One can either choose to use a Python based source finding algorithm or give a SExtractor catalog as an input. If an input catalog is provided then the program assumes that X_IMAGE and Y_IMAGE columns are present in the input file. :param filename: name of the FITS file to be analysed. :type filename: string :param log: logger :type log: instance :param kwargs: additional keyword arguments :type kwargs: dict Settings dictionary contains all parameter values needed for source finding and analysis. """ def __init__(self, filename, log, **kwargs): """ :param filename: name of the FITS file to be analysed. :type filename: string :param log: logger :type log: instance :param kwargs: additional keyword arguments :type kwargs: dict Settings dictionary contains all parameter values needed for source finding and analysis. """ self.log = log self.settings = dict(filename=filename, extension=0, above_background=2.5, clean_size_min=3, clean_size_max=200, sigma=2.7, disk_struct=3, xcutout=50, ycutout=50, bins=20, sampling=1.0, output='foundsources.txt', outputPlot='ellipticities.pdf', ellipticityOutput='ellipticities.txt') self.settings.update(kwargs) self._loadData() def _loadData(self): """ Load data from a given FITS file. Assumes that the data are in a FITS file. Filename and FITS extension are read from the settings dictionary initiated when the class instance was generated. This method is called automatically when the class is being initiated. Read data are stored in self.data. :return: None """ self.log.info('Reading data from %s extension=%i' % (self.settings['filename'], self.settings['extension'])) fh = pf.open(self.settings['filename']) self.data = fh[self.settings['extension']].data ysize, xsize = self.data.shape self.settings['sizeX'] = xsize self.settings['sizeY'] = ysize self.log.debug('Image dimensions (x,y) = (%i, %i)' % (xsize, ysize)) def findSources(self): """ Finds sources from data that has been read in when the class was initiated. Saves results such as x and y coordinates of the objects to self.sources. x and y coordinates are also available directly in self.x and self.y. """ self.log.info('Finding sources from data...') source = sourceFinder(self.data, self.log, **self.settings) self.sources = source.runAll() #add one because the numbering starts from zero self.x = np.asarray(self.sources['xcms']) + 1. self.y = np.asarray(self.sources['ycms']) + 1. def readSources(self): """ Reads in a list of sources from an external file. This method assumes that the input source file is in SExtractor format. Input catalog is saves to self.sources. x and y coordinates are also available directly in self.x and self.y. """ self.log.info('Reading source information from %s' % self.settings['sourceFile']) self.sources = sextutils.se_catalog(self.settings['sourceFile']) self.x = self.sources.x_image self.y = self.sources.y_image #write out a DS reg file rg = open('sources.reg', 'w') for x, y in zip(self.sources.x_image, self.sources.y_image): rg.write('circle({0:.3f},{1:.3f},5)\n'.format(x, y)) rg.close() def measureEllipticity(self): """ Measures ellipticity for all objects with coordinates (self.x, self.y). Ellipticity is measured using Guassian weighted quadrupole moments. See shape.py and especially the ShapeMeasurement class for more details. """ ells = [] xs = [] ys = [] R2s = [] for x, y in zip(self.x, self.y): #cut out a square region around x and y coordinates #force the region to be symmetric around the galaxy xmin = max(x - self.settings['xcutout'], 0.) ymin = max(y - self.settings['ycutout'], 0.) xmax = min(x + self.settings['xcutout'] + 1., self.settings['sizeX']) ymax = min(y + self.settings['ycutout'] + 1., self.settings['sizeY']) xsize = min(x-xmin, xmax-x) ysize = min(y-ymin, ymax-y) xcutmin = int(x - xsize) xcutmax = int(x + xsize) ycutmin = int(y - ysize) ycutmax = int(y + ysize) if xcutmax - xcutmin < 10 or ycutmax - ycutmin < 10: self.log.warning('Very few pixels around the object, will skip this one...') continue self.log.info('Measuring ellipticity of an object located at (x, y) = (%f, %f)' % (x, y)) img = self.data[ycutmin:ycutmax, xcutmin:xcutmax].copy() sh = shape.shapeMeasurement(img, self.log, **dict(sampling=self.settings['sampling'])) results = sh.measureRefinedEllipticity() #get shifts for x and y centroids for the cutout image cutsizey, cutsizex = img.shape xcent = int(x - cutsizex/2.) ycent = int(y - cutsizey/2.) self.log.info('Centroiding (x, y) = (%f, %f), e=%f, R2=%f' % (results['centreX']+xcent, results['centreY']+ycent, results['ellipticity'], results['R2'])) #print x - results['centreX']-xcent, y -results['centreY']-ycent #save the results ells.append(results['ellipticity']) xs.append(results['centreX']+xcent) ys.append(results['centreY']+ycent) R2s.append(results['R2']) out = dict(Xcentres=xs, Ycentres=ys, ellipticities=ells, R2s=R2s) self.results = out return self.results def writeResults(self): """ Outputs results to an ascii file defined in self.settings. This ascii file is in SExtractor format and contains the following columns:: 1. X coordinate 2. Y coordinate 3. ellipticity 4. R_{2} """ fh = open(self.settings['ellipticityOutput'], 'w') #write header fh.write('# 1 X\n') fh.write('# 2 Y\n') fh.write('# 3 ELLIPTICITY\n') fh.write('# 4 R2\n') #loop over data for x, y, e, R2 in zip(self.results['Xcentres'], self.results['Ycentres'], self.results['ellipticities'], self.results['R2s']): fh.write('%f %f %f %f\n' % (x, y, e, R2)) fh.close() def plotEllipticityDistribution(self): """ Creates a simple plot showing the derived ellipticity distribution. """ fig = plt.figure() ax = fig.add_subplot(111) ax.hist(self.results['ellipticities'], bins=self.settings['bins'], normed=True, range=(0,1), alpha=0.7, hatch='/', label='Ellipticity') ax.set_xlabel('Ellipticity') ax.set_ylabel('Probability Density') plt.savefig(self.settings['outputPlot']) plt.close() def doAll(self): """ Run all class methods sequentially. """ if self.settings['sourceFile']: self.readSources() else: self.findSources() results = self.measureEllipticity() self.writeResults() self.plotEllipticityDistribution() for key, value in self.settings.iteritems(): self.log.info('%s = %s' % (key, value)) return results def processArgs(printHelp=False): """ Processes command line arguments. """ parser = OptionParser() parser.add_option('-f', '--file', dest='input', help="Input file to process", metavar='string') parser.add_option('-s', '--sourcefile', dest='sourcefile', help='Name of input source file [optional]', metavar='string') parser.add_option('-a', '--sampling', dest='sampling', help='Change the sampling in the shape measuring algorithm', metavar='sampling') if printHelp: parser.print_help() else: return parser.parse_args() if __name__ == '__main__': opts, args = processArgs() if opts.input is None: processArgs(True) sys.exit(8) settings = {} if opts.sourcefile is None: settings['sourceFile'] = None else: settings['sourceFile'] = opts.sourcefile if not opts.sampling is None: settings['sampling'] = float(opts.sampling) log = lg.setUpLogger('analyse.log') log.info('\n\nStarting to analyse %s' % opts.input) analyse = analyseVISdata(opts.input, log, **settings) results = analyse.doAll() log.info('All done...')
bsd-2-clause
open-lambda/open-lambda
test.py
1
15018
#!/usr/bin/env python3 import os, sys, json, time, requests, copy, traceback, tempfile, threading, subprocess from collections import OrderedDict from subprocess import check_output from multiprocessing import Pool from contextlib import contextmanager OLDIR = 'test-dir' results = OrderedDict({"runs": []}) curr_conf = None def post(path, data=None): return requests.post('http://localhost:5000/'+path, json.dumps(data)) def raise_for_status(r): if r.status_code != 200: raise Exception("STATUS %d: %s" % (r.status_code, r.text)) def test_in_filter(name): if len(sys.argv) < 2: return True return name in sys.argv[1:] def get_mem_stat_mb(stat): with open('/proc/meminfo') as f: for l in f: if l.startswith(stat+":"): parts = l.strip().split() assert(parts[-1] == 'kB') return int(parts[1]) / 1024 raise Exception('could not get stat') def ol_oom_killer(): while True: if get_mem_stat_mb('MemAvailable') < 128: print("out of memory, trying to kill OL") os.system('pkill ol') time.sleep(1) def test(fn): def wrapper(*args, **kwargs): if len(args): raise Exception("positional args not supported for tests") name = fn.__name__ if not test_in_filter(name): return None print('='*40) if len(kwargs): print(name, kwargs) else: print(name) print('='*40) result = OrderedDict() result["test"] = name result["params"] = kwargs result["pass"] = None result["conf"] = curr_conf result["seconds"] = None result["total_seconds"] = None result["stats"] = None result["ol-stats"] = None result["errors"] = [] result["worker_tail"] = None total_t0 = time.time() mounts0 = mounts() try: # setup worker run(['./ol', 'worker', '-p='+OLDIR, '--detach']) # run test/benchmark test_t0 = time.time() rv = fn(**kwargs) test_t1 = time.time() result["seconds"] = test_t1 - test_t0 result["pass"] = True except Exception: rv = None result["pass"] = False result["errors"].append(traceback.format_exc().split("\n")) # cleanup worker try: run(['./ol', 'kill', '-p='+OLDIR]) except Exception: result["pass"] = False result["errors"].append(traceback.format_exc().split("\n")) mounts1 = mounts() if len(mounts0) != len(mounts1): result["pass"] = False result["errors"].append(["mounts are leaking (%d before, %d after), leaked: %s" % (len(mounts0), len(mounts1), str(mounts1 - mounts0))]) # get internal stats from OL if os.path.exists(OLDIR+"/worker/stats.json"): with open(OLDIR+"/worker/stats.json") as f: olstats = json.load(f) result["ol-stats"] = OrderedDict(sorted(list(olstats.items()))) total_t1 = time.time() result["total_seconds"] = total_t1-total_t0 result["stats"] = rv with open(os.path.join(OLDIR, "worker.out")) as f: result["worker_tail"] = f.read().split("\n") if result["pass"]: # truncate because we probably won't use it for debugging result["worker_tail"] = result["worker_tail"][-10:] results["runs"].append(result) print(json.dumps(result, indent=2)) return rv return wrapper def put_conf(conf): global curr_conf with open(os.path.join(OLDIR, "config.json"), "w") as f: json.dump(conf, f, indent=2) curr_conf = conf def mounts(): output = check_output(["mount"]) output = str(output, "utf-8") output = output.split("\n") return set(output) @contextmanager def TestConf(**keywords): with open(os.path.join(OLDIR, "config.json")) as f: orig = json.load(f) new = copy.deepcopy(orig) for k in keywords: if not k in new: raise Exception("unknown config param: %s" % k) if type(keywords[k]) == dict: for k2 in keywords[k]: new[k][k2] = keywords[k][k2] else: new[k] = keywords[k] # setup print("PUSH conf:", keywords) put_conf(new) yield new # cleanup print("POP conf:", keywords) put_conf(orig) def run(cmd): print("RUN", " ".join(cmd)) try: out = check_output(cmd, stderr=subprocess.STDOUT) fail = False except subprocess.CalledProcessError as e: out = e.output fail = True out = str(out, 'utf-8') if len(out) > 500: out = out[:500] + "..." if fail: raise Exception("command (%s) failed: %s" % (" ".join(cmd), out)) @test def install_tests(): # we want to make sure we see the expected number of pip installs, # so we don't want installs lying around from before rc = os.system('rm -rf test-dir/lambda/packages/*') assert(rc == 0) # try something that doesn't install anything msg = 'hello world' r = post("run/echo", msg) raise_for_status(r) if r.json() != msg: raise Exception("found %s but expected %s" % (r.json(), msg)) r = post("stats", None) raise_for_status(r) installs = r.json().get('pull-package.cnt', 0) assert(installs == 0) for i in range(3): name = "install" if i != 0: name += str(i+1) r = post("run/"+name, {}) raise_for_status(r) assert r.json() == "imported" r = post("stats", None) raise_for_status(r) installs = r.json()['pull-package.cnt'] if i < 2: # with deps, requests should give us these: # certifi, chardet, idna, requests, urllib3 assert(installs == 5) else: assert(installs == 6) @test def numpy_test(): # try adding the nums in a few different matrixes. Also make sure # we can have two different numpy versions co-existing. r = post("run/numpy15", [1, 2]) if r.status_code != 200: raise Exception("STATUS %d: %s" % (r.status_code, r.text)) j = r.json() assert j['result'] == 3 assert j['version'].startswith('1.15') r = post("run/numpy16", [[1, 2], [3, 4]]) if r.status_code != 200: raise Exception("STATUS %d: %s" % (r.status_code, r.text)) j = r.json() assert j['result'] == 10 assert j['version'].startswith('1.16') r = post("run/numpy15", [[[1, 2], [3, 4]], [[1, 2], [3, 4]]]) if r.status_code != 200: raise Exception("STATUS %d: %s" % (r.status_code, r.text)) j = r.json() assert j['result'] == 20 assert j['version'].startswith('1.15') r = post("run/pandas", [[0, 1, 2], [3, 4, 5]]) if r.status_code != 200: raise Exception("STATUS %d: %s" % (r.status_code, r.text)) j = r.json() print(j) assert j['result'] == 15 assert float(".".join(j['version'].split('.')[:2])) >= 1.19 r = post("run/pandas18", [[1, 2, 3],[1, 2, 3]]) if r.status_code != 200: raise Exception("STATUS %d: %s" % (r.status_code, r.text)) j = r.json() assert j['result'] == 12 assert j['version'].startswith('1.18') def stress_one_lambda_task(args): t0, seconds = args i = 0 while time.time() < t0 + seconds: r = post("run/echo", i) raise_for_status(r) assert r.text == str(i) i += 1 return i @test def stress_one_lambda(procs, seconds): t0 = time.time() with Pool(procs) as p: reqs = sum(p.map(stress_one_lambda_task, [(t0, seconds)] * procs, chunksize=1)) return {"reqs_per_sec": reqs/seconds} @test def call_each_once_exec(lambda_count, alloc_mb): # TODO: do in parallel t0 = time.time() for i in range(lambda_count): r = post("run/L%d"%i, {"alloc_mb": alloc_mb}) raise_for_status(r) assert r.text == str(i) seconds = time.time() - t0 return {"reqs_per_sec": lambda_count/seconds} def call_each_once(lambda_count, alloc_mb=0): with tempfile.TemporaryDirectory() as reg_dir: # create dummy lambdas for i in range(lambda_count): with open(os.path.join(reg_dir, "L%d.py"%i), "w") as f: f.write("def f(event):\n") f.write(" global s\n") f.write(" s = '*' * %d * 1024**2\n" % alloc_mb) f.write(" return %d\n" % i) with TestConf(registry=reg_dir): call_each_once_exec(lambda_count=lambda_count, alloc_mb=alloc_mb) @test def fork_bomb(): limit = curr_conf["limits"]["procs"] r = post("run/fbomb", {"times": limit*2}) raise_for_status(r) # the function returns the number of children that we were able to fork actual = int(r.text) assert(1 <= actual <= limit) @test def max_mem_alloc(): limit = curr_conf["limits"]["mem_mb"] r = post("run/max_mem_alloc", None) raise_for_status(r) # the function returns the MB that was able to be allocated actual = int(r.text) assert(limit-16 <= actual <= limit) @test def ping_test(): pings = 1000 t0 = time.time() for i in range(pings): r = requests.get("http://localhost:5000/status") raise_for_status(r) seconds = time.time() - t0 return {"pings_per_sec": pings/seconds} def sock_churn_task(args): echo_path, parent, t0, seconds = args i = 0 while time.time() < t0 + seconds: args = {"code": echo_path, "leaf": True, "parent": parent} r = post("create", args) raise_for_status(r) sandbox_id = r.text.strip() r = post("destroy/"+sandbox_id, {}) raise_for_status(r) i += 1 return i @test def sock_churn(baseline, procs, seconds, fork): # baseline: how many sandboxes are sitting idly throughout the experiment # procs: how many procs are concurrently creating and deleting other sandboxes echo_path = os.path.abspath("test-registry/echo") if fork: r = post("create", {"code": "", "leaf": False}) raise_for_status(r) parent = r.text.strip() else: parent = "" for i in range(baseline): r = post("create", {"code": echo_path, "leaf": True, "parent": parent}) raise_for_status(r) sandbox_id = r.text.strip() r = post("pause/"+sandbox_id) raise_for_status(r) t0 = time.time() with Pool(procs) as p: reqs = sum(p.map(sock_churn_task, [(echo_path, parent, t0, seconds)] * procs, chunksize=1)) return {"sandboxes_per_sec": reqs/seconds} @test def update_code(): reg_dir = curr_conf['registry'] cache_seconds = curr_conf['registry_cache_ms'] / 1000 latencies = [] for i in range(3): # update function code with open(os.path.join(reg_dir, "version.py"), "w") as f: f.write("def f(event):\n") f.write(" return %d\n" % i) # how long does it take for us to start seeing the latest code? t0 = time.time() while True: r = post("run/version", None) raise_for_status(r) num = int(r.text) assert(num >= i-1) t1 = time.time() # make sure the time to grab new code is about the time # specified for the registry cache (within ~1 second) assert(t1 - t0 <= cache_seconds + 1) if num == i: if i > 0: assert(t1 - t0 >= cache_seconds - 1) break @test def recursive_kill(depth): parent = "" for i in range(depth): r = post("create", {"code": "", "leaf": False, "parent": parent}) raise_for_status(r) if parent: # don't need this parent any more, so pause it to get # memory back (so we can run this test with low memory) post("pause/"+parent) parent = r.text.strip() r = post("destroy/1", None) raise_for_status(r) r = post("stats", None) raise_for_status(r) destroys = r.json()['Destroy():ms.cnt'] assert destroys == depth def tests(): test_reg = os.path.abspath("test-registry") with TestConf(registry=test_reg): ping_test() # do smoke tests under various configs with TestConf(features={"import_cache": False}): install_tests() with TestConf(mem_pool_mb=500): install_tests() with TestConf(sandbox="docker", features={"import_cache": False}): install_tests() # test resource limits fork_bomb() max_mem_alloc() # numpy pip install needs a larger mem cap with TestConf(mem_pool_mb=500): numpy_test() # test SOCK directly (without lambdas) with TestConf(server_mode="sock", mem_pool_mb=500): sock_churn(baseline=0, procs=1, seconds=5, fork=False) sock_churn(baseline=0, procs=1, seconds=10, fork=True) sock_churn(baseline=0, procs=15, seconds=10, fork=True) sock_churn(baseline=32, procs=1, seconds=10, fork=True) sock_churn(baseline=32, procs=15, seconds=10, fork=True) # make sure code updates get pulled within the cache time with tempfile.TemporaryDirectory() as reg_dir: with TestConf(registry=reg_dir, registry_cache_ms=3000): update_code() # test heavy load with TestConf(registry=test_reg): stress_one_lambda(procs=1, seconds=15) stress_one_lambda(procs=2, seconds=15) stress_one_lambda(procs=8, seconds=15) with TestConf(features={"reuse_cgroups": True}): call_each_once(lambda_count=100, alloc_mb=1) call_each_once(lambda_count=1000, alloc_mb=10) def main(): t0 = time.time() # so our test script doesn't hang if we have a memory leak timerThread = threading.Thread(target=ol_oom_killer, daemon=True) timerThread.start() # general setup if os.path.exists(OLDIR): try: run(['./ol', 'kill', '-p='+OLDIR]) except: print('could not kill cluster') run(['rm', '-rf', OLDIR]) run(['./ol', 'new', '-p='+OLDIR]) # run tests with various configs with TestConf(limits={"installer_mem_mb": 250}): tests() # save test results passed = len([t for t in results["runs"] if t["pass"]]) failed = len([t for t in results["runs"] if not t["pass"]]) results["passed"] = passed results["failed"] = failed results["seconds"] = time.time() - t0 print("PASSED: %d, FAILED: %d" % (passed, failed)) with open("test.json", "w") as f: json.dump(results, f, indent=2) sys.exit(failed) if __name__ == '__main__': main()
apache-2.0
Mecanon/morphing_wing
experimental/comparison_model/static_model.py
1
8433
# -*- coding: utf-8 -*- """ - dynamics of a flap with two actuators in different positions - can take in to account initial strain - calculates necessary spring stiffness for a given linear actuator length and for defined positions for the actuators ends. Will have: - coupling with Edwin matlab code - coupling with Aeropy Created on Wed Feb 17 13:10:30 2016 @author: Pedro Leal """ import math import numpy as np import pickle import airfoil_module as af from flap import flap def run(inputs, parameters = None): """Function to be callled by DOE and optimization. Design Variables are the only inputs. :param inputs: {'sma', 'linear', 'sigma_o'}""" def thickness(x, t, chord): y = af.Naca00XX(chord, t, [x], return_dict = 'y') thickness_at_x = y['u'] - y['l'] return thickness_at_x if parameters != None: eng = parameters[0] import_matlab = False else: eng = None import_matlab = True sma = inputs['sma'] linear = inputs['linear'] spring = inputs['spring'] airfoil = "naca0012" chord = 1.#0.6175 t = 0.12*chord J = {'x':0.75, 'y':0.} # # need to transform normalized coordiantes in to global coordinates # sma['y+'] = sma['y+']*thickness(sma['x+'], t, chord)/2. # sma['y-'] = sma['y-']*thickness(sma['x-'], t, chord)/2. # # linear['y+'] = linear['y+']*thickness(linear['x+'], t, chord)/2. # linear['y-'] = linear['y-']*thickness(linear['x-'], t, chord)/2. #Adding the area key to the dictionaries sma['area'] = math.pi*(0.000381/2)**2 linear['area'] = 0.001 # Design constants #arm length to center of gravity r_w = 0.1 #Aicraft weight (mass times gravity) W = 0.0523*9.8 #0.06*9.8 alpha = 0. V = 10 #m/s altitude = 10000. #feet # Temperature T_0 = 273.15 + 30 T_final = 273.15 + 140 #Initial martensitic volume fraction MVF_init = 1. # Number of steps and cycles n = 200 n_cycles = 0 #~~~~~~~~~~~~~~~~~~~~~bb~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Parameters to select how to output stuff all_outputs = True save_data = True #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if all_outputs: # print "SMA: real y dimensions: ", sma['y-'], sma['y+'],sma['y+']*thickness(sma['x+'], t, chord)/2., sma['y-']*thickness(sma['x-'], t, chord)/2. # print "linear: real y dimensions: ", linear['y-'], linear['y+'], linear['y+']*thickness(linear['x+'], t, chord)/2., linear['y-']*thickness(linear['x-'], t, chord)/2. eps_s, eps_l, theta, sigma, MVF, T, eps_t, theta, F_l, k, L_s = flap(airfoil, chord, J, sma, linear, spring, W, r_w, V, altitude, alpha, T_0, T_final, MVF_init, n, all_outputs = True, import_matlab = import_matlab, eng=eng, n_cycles = n_cycles, aero_loads = False) import matplotlib.pyplot as plt plt.figure() plt.plot(np.rad2deg(theta), eps_s, lw=2., label = "$\epsilon_s$") plt.plot(np.rad2deg(theta), eps_l, 'b--',lw=2, label = "$\epsilon_l$") # plt.scatter(theta, eps_s, c = 'b') # plt.scatter(theta, eps_l, c = 'b') plt.ylabel('$\epsilon$', fontsize=24) plt.xlabel(r'$\theta ({}^{\circ})$', fontsize=20) plt.legend(loc = 'best', fontsize = 'x-large') plt.grid() print len(T), len(eps_s), len(eps_l), len(theta), len(eps_t) plt.figure() plt.plot(np.rad2deg(theta), eps_t, lw=2.) # plt.scatter(theta, eps_t, c = 'b') plt.ylabel('$\epsilon_t$', fontsize=24) plt.xlabel(r'$\theta ({}^{\circ})$', fontsize=20) plt.legend(loc = 'best', fontsize = 'x-large') plt.grid() plt.figure() plt.plot(np.rad2deg(theta), MVF, lw=2.) # plt.scatter(theta, MVF, c = 'b') plt.ylabel('$MVF$', fontsize=24) plt.xlabel(r'$\theta ({}^{\circ})$', fontsize=20) plt.legend(loc = 'best', fontsize = 'x-large') plt.grid() plt.figure() plt.plot(T, MVF, lw=2.) # plt.scatter(T, MVF, c = 'b') plt.ylabel('$MVF$', fontsize=24) plt.xlabel('$T (K)$', fontsize=20) plt.legend(loc = 'best', fontsize = 'x-large') plt.grid() plt.figure() plt.plot(T, sigma, lw=2.) # plt.scatter(T, sigma, c = 'b') plt.ylabel('$\sigma$', fontsize=24) plt.xlabel('$T (K)$', fontsize=20) plt.legend(loc = 'best', fontsize = 'x-large') plt.grid() plt.figure() plt.plot(T, eps_s, 'b', lw=2., label = "$\epsilon_s$") plt.plot(T, eps_l, 'b--',lw=2, label = "$\epsilon_l$") # plt.scatter(T, eps_s, c = 'b') # plt.scatter(T, eps_l, c = 'b') plt.xlabel('$T (K)$', fontsize=20) plt.ylabel('$\epsilon$', fontsize=24) plt.legend(loc = 'best', fontsize = 'x-large') plt.grid() plt.figure() plt.plot(T, np.rad2deg(theta), lw=2.) # plt.scatter(T, theta, c = 'b') plt.xlabel('$T (K)$', fontsize=20) plt.ylabel(r'$\theta ({}^{\circ})$', fontsize=20) plt.grid() F_s = [] for i in range(len(sigma)): F_s.append(sigma[i]*sma['area']) # sigma_MPa = [] # for sigma_i in sigma: # sigma_MPa.append(sigma_i/1e6) plt.figure() plt.plot(np.rad2deg(theta), F_s, 'b', lw=2., label = "$F_s$") plt.plot(np.rad2deg(theta), F_l, 'b--', lw=2., label = "$F_l$") # plt.scatter(theta, F_s, c = 'b') # plt.scatter(theta, F_l, c = 'b') plt.ylabel('$F (N)$', fontsize=20) plt.xlabel(r'$\theta ({}^{\circ})$', fontsize=20) plt.legend(loc = 'best', fontsize = 'x-large') plt.grid() else: theta, k= flap(airfoil, chord, J, sma, linear, spring, W, r_w, V, altitude, alpha, T_0, T_final, MVF_init, n, all_outputs = False, import_matlab = import_matlab, eng=eng, n_cycles = n_cycles, aero_loads = False) if save_data == True: Data = {'theta': theta, 'eps_s': eps_s, 'eps_l': eps_l, 'sigma': sigma, 'xi': MVF, 'T': T, 'eps_t': eps_t, 'F_l': F_l, 'k': k, 'L_s':L_s} pickle.dump(Data, open( "data.p", "wb" ) ) return {'theta': theta, 'k': k} if __name__ == '__main__': J = {'x':0.75, 'y':0.} # Real positioning on flap model (y coordinates are not normalized) sma = {'x-': J['x'] - 0.018, 'y-': -0.02, 'x+': J['x'] + 0.152, 'y+': 0.006} linear = {'x-': J['x'] - 0.018, 'y-': 0.03, 'x+': J['x'] + 0.152, 'y+': -0.006} # Spring stiffness (N/m) k = 127.33 spring = {'k': k, 'L_0': 0.0588, 'L_solid': 0.05030} data = run({'sma':sma, 'linear':linear, 'spring':spring}) print 'k: ', data['k'], 'theta:', data['theta'][-1] DataFile = open('data.txt','a') ##============================================================================== ## Run withou run function ##============================================================================== # #Hole positioning # J = {'x':0.25, 'y':0.} # #y coordinates are percentual # sma = {'x-': J['x'], 'y-': -0.02*2, 'x+': 0.1225 + J['x'], # 'y+': 0.0135*2, 'area':math.pi*0.00025**2} # linear = {'x-': J['x'], 'y-': 0.032*2, 'x+': 0.146 + J['x'], # 'y+': -0.0135*2, 'area':0.001} # # #original bias spring length # length_l = 0.06 # # # #arm length to center of gravity # r_w = 0.15 # # #Aicraft weight (mass times gravity) # W = 0.06*9.8 # alpha = 0. # V = 10 #m/s # altitude = 10000. #feet # # airfoil = "naca0012" # chord = 0.6175 # # ## Temperature # T_0 = 220.15 # T_final = 400.15 # # #Initial martensitic volume fraction # MVF_init = 1. # # # Number of steps # n = 200 # # data = flap(airfoil, chord, J, sma, linear, sigma_o, length_l, W, r_w, # V, altitude, alpha, T_0, T_final, MVF_init, n, # all_outputs = True)
mit
Erotemic/utool
utool/util_project.py
1
34436
# -*- coding: utf-8 -*- """ Ignore: ~/local/init/REPOS1.py """ from __future__ import absolute_import, division, print_function # , unicode_literals from six.moves import zip, filter, filterfalse, map, range # NOQA import six # NOQA #from os.path import split, dirname, join from os.path import dirname, join from utool import util_class # NOQA from utool import util_dev from utool import util_inject print, rrr, profile = util_inject.inject2(__name__) __GLOBAL_PROFILE__ = None def ensure_text(fname, text, repo_dpath='.', force=None, locals_={}, chmod=None): """ Args: fname (str): file name text (str): repo_dpath (str): directory path string(default = '.') force (bool): (default = False) locals_ (dict): (default = {}) Example: >>> # DISABLE_DOCTEST >>> from utool.util_project import * # NOQA >>> import utool as ut >>> result = setup_repo() >>> print(result) """ import utool as ut ut.colorprint('Ensuring fname=%r' % (fname), 'yellow') # if not fname.endswith('__init__.py'): # # HACK # return if force is None and ut.get_argflag('--force-%s' % (fname,)): force = True text_ = ut.remove_codeblock_syntax_sentinals(text) fmtkw = locals_.copy() fmtkw['fname'] = fname text_ = text_.format(**fmtkw) + '\n' fpath = join(repo_dpath, fname) ut.dump_autogen_code(fpath, text_) # if force or not ut.checkpath(fpath, verbose=2, n=5): # ut.writeto(fpath, text_) # try: # if chmod: # ut.chmod(fpath, chmod) # except Exception as ex: # ut.printex(ex, iswarning=True) # else: # print(ut.color_diff_text(ut.difftext(ut.readfrom(fpath), text_))) # print('use -w to force write') class SetupRepo(object): """ Maybe make a new interface to SetupRepo? Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_project import * # NOQA >>> import utool as ut >>> self = SetupRepo() >>> print(self) """ def __init__(self): import utool as ut self.modname = None code_dpath = ut.truepath(ut.get_argval('--code-dir', default='~/code')) self.code_dpath = ut.unexpanduser(code_dpath) self.repo_fname = (ut.get_argval(('--repo', '--repo-name'), type_=str)) self.repo_dpath = join(code_dpath, self.repo_fname) self.modname = ut.get_argval('--modname', default=self.repo_fname) self.regenfmt = 'python -m utool SetupRepo.{cmd} --modname={modname} --repo={repo_fname} --codedir={code_dpath}' ut.ensuredir(self.repo_dpath, verbose=True) def all(self): pass def ensure_text(self, fname, text, **kwargs): ensure_text(fname, text, locals_=self.__dict__, repo_dpath=self.repo_dpath, **kwargs) def main(self): """ python -m utool SetupRepo.main --modname=sklearn --repo=scikit-learn --codedir=~/code -w python -m utool SetupRepo.main --repo=ubelt --codedir=~/code --modname=ubelt -w Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_project import * # NOQA >>> SetupRepo().main() """ self.regencmd = self.regenfmt.format(cmd='main', **self.__dict__) import utool as ut self.ensure_text( fname=join(self.modname, '__main__.py'), chmod='+x', text=ut.codeblock( r''' # STARTBLOCK #!/usr/bin/env python # -*- coding: utf-8 -*- """ Initially Generated By: {regencmd} """ from __future__ import absolute_import, division, print_function, unicode_literals def {modname}_main(): ignore_prefix = [] ignore_suffix = [] import utool as ut ut.main_function_tester('{modname}', ignore_prefix, ignore_suffix) if __name__ == '__main__': """ Usage: python -m {modname} <funcname> """ print('Running {modname} main') {modname}_main() # ENDBLOCK ''' ) ) def setup_repo(): r""" Creates default structure for a new repo CommandLine: python -m utool setup_repo --repo=dtool --codedir=~/code python -m utool setup_repo --repo=dtool --codedir=~/code python -m utool setup_repo --repo=ibeis-flukematch-module --codedir=~/code --modname=ibeis_flukematch python -m utool setup_repo --repo=mtgmonte --codedir=~/code --modname=mtgmonte python -m utool setup_repo --repo=pydarknet --codedir=~/code --modname=pydarknet python -m utool setup_repo --repo=sandbox_utools --codedir=~/code --modname=sandbox_utools python -m utool setup_repo --repo=ubelt --codedir=~/code --modname=ubelt -w python -m utool setup_repo Python: ipython import utool as ut ut.rrrr(0); ut.setup_repo() Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_project import * # NOQA >>> import utool as ut >>> result = setup_repo() >>> print(result) """ print('\n [setup_repo]!') # import os from functools import partial import utool as ut # import os code_dpath = ut.truepath(ut.get_argval('--code-dir', default='~/code')) _code_dpath = ut.unexpanduser(code_dpath) repo_fname = (ut.get_argval(('--repo', '--repo-name'), type_=str)) repo_dpath = join(code_dpath, repo_fname) modname = ut.get_argval('--modname', default=repo_fname) ut.ensuredir(repo_dpath, verbose=True) _regencmd = 'python -m utool --tf setup_repo --repo={repo_fname} --codedir={_code_dpath} --modname={modname}' flake8_noqacmd = 'flake8' + ':noqa' regencmd = _regencmd.format(**locals()) with ut.ChdirContext(repo_dpath): # os.chdir(repo_fname) locals_ = locals() force = True _ensure_text = partial(ensure_text, repo_dpath='.', force=None, locals_=locals_) _ensure_text( fname='todo.md', text=ut.codeblock( r''' # STARTBLOCK # {modname} TODO File * Add TODOS! # ENDBLOCK ''') ) _ensure_text( fname='README.md', text=ut.codeblock( r''' # STARTBLOCK # {modname} README FILE # ENDBLOCK ''') ) _ensure_text( fname='setup.py', chmod='+x', text=ut.codeblock( r''' # STARTBLOCK #!/usr/bin/env python """ Initially Generated By: {regencmd} --force-{fname} """ from __future__ import absolute_import, division, print_function, unicode_literals from setuptools import setup try: from utool import util_setup except ImportError: print('ERROR: setup requires utool') raise INSTALL_REQUIRES = [ #'cython >= 0.21.1', #'numpy >= 1.9.0', #'scipy >= 0.16.0', ] CLUTTER_PATTERNS = [ # Patterns removed by python setup.py clean ] if __name__ == '__main__': kwargs = util_setup.setuptools_setup( setup_fpath=__file__, name='{modname}', packages=util_setup.find_packages(), version=util_setup.parse_package_for_version('{modname}'), license=util_setup.read_license('LICENSE'), long_description=util_setup.parse_readme('README.md'), ext_modules=util_setup.find_ext_modules(), cmdclass=util_setup.get_cmdclass(), #description='description of module', #url='https://github.com/<username>/{repo_fname}.git', #author='<author>', #author_email='<author_email>', keywords='', install_requires=INSTALL_REQUIRES, clutter_patterns=CLUTTER_PATTERNS, #package_data={{'build': ut.get_dynamic_lib_globstrs()}}, #build_command=lambda: ut.std_build_command(dirname(__file__)), classifiers=[], ) setup(**kwargs) # ENDBLOCK ''' ) ) _ensure_text( fname='.gitignore', text=ut.codeblock( r''' # STARTBLOCK *.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 __pycache__ # Installer logs pip-log.txt # Print Logs logs # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject .DS_Store *.dump.txt *.sqlite3 # profiler *.lprof *.prof *.flann *.npz # utool output _timeings.txt failed.txt *.orig _doc timeings.txt failed_doctests.txt # ENDBLOCK ''' ) ) _ensure_text( fname=join(repo_dpath, modname, '__init__.py'), text=ut.codeblock( r''' # STARTBLOCK # -*- coding: utf-8 -*- # {flake8_noqacmd} """ Initially Generated By: {regencmd} """ from __future__ import absolute_import, division, print_function, unicode_literals import sys __version__ = '0.0.0' IMPORT_TUPLES = [ # ('<modname>', None), ] __DYNAMIC__ = '--nodyn' not in sys.argv """ python -c "import {modname}" --dump-{modname}-init python -c "import {modname}" --update-{modname}-init """ DOELSE = False if __DYNAMIC__: # Dynamically import listed util libraries and their members. from utool._internal import util_importer ignore_endswith = [] import_execstr = util_importer.dynamic_import( __name__, IMPORT_TUPLES, ignore_endswith=ignore_endswith) exec(import_execstr) DOELSE = False else: DOELSE = True if DOELSE: # <AUTOGEN_INIT> pass # </AUTOGEN_INIT> # ENDBLOCK ''' ) ) _ensure_text( fname=join(repo_dpath, modname, '__main__.py'), chmod='+x', text=ut.codeblock( r''' # STARTBLOCK #!/usr/bin/env python # -*- coding: utf-8 -*- """ Initially Generated By: {regencmd} """ from __future__ import absolute_import, division, print_function, unicode_literals def {modname}_main(): ignore_prefix = [] ignore_suffix = [] import utool as ut ut.main_function_tester('{modname}', ignore_prefix, ignore_suffix) if __name__ == '__main__': """ Usage: python -m {modname} <funcname> """ print('Running {modname} main') {modname}_main() # ENDBLOCK ''' ) ) _ensure_text( fname='run_tests.py', chmod='+x', text=ut.codeblock( r''' # STARTBLOCK #!/usr/bin/env python """ Initially Generated By: {regencmd} --force-{fname} """ from __future__ import absolute_import, division, print_function import sys import utool as ut def run_tests(): # Build module list and run tests import sys ut.change_term_title('RUN {modname} TESTS') exclude_doctests_fnames = set([ ]) exclude_dirs = [ '_broken', 'old', 'tests', 'timeits', '_scripts', '_timeits', '_doc', 'notebook', ] dpath_list = ['{modname}'] doctest_modname_list = ut.find_doctestable_modnames( dpath_list, exclude_doctests_fnames, exclude_dirs) coverage = ut.get_argflag(('--coverage', '--cov',)) if coverage: import coverage cov = coverage.Coverage(source=doctest_modname_list) cov.start() print('Starting coverage') exclude_lines = [ 'pragma: no cover', 'def __repr__', 'if self.debug:', 'if settings.DEBUG', 'raise AssertionError', 'raise NotImplementedError', 'if 0:', 'if ut.VERBOSE', 'if _debug:', 'if __name__ == .__main__.:', 'print(.*)', ] for line in exclude_lines: cov.exclude(line) for modname in doctest_modname_list: exec('import ' + modname, globals()) module_list = [sys.modules[name] for name in doctest_modname_list] nPass, nTotal, failed_cmd_list = ut.doctest_module_list(module_list) if coverage: print('Stoping coverage') cov.stop() print('Saving coverage') cov.save() print('Generating coverage html report') cov.html_report() if nPass != nTotal: return 1 else: return 0 if __name__ == '__main__': import multiprocessing multiprocessing.freeze_support() retcode = run_tests() sys.exit(retcode) # ENDBLOCK ''' ) ) ut.ensuredir(join(repo_dpath, modname), verbose=True) #@util_class.ReloadingMetaclass class UserProfile(util_dev.NiceRepr): def __nice__(self): num_repos = 0 if self.project_dpaths is None else len(self.project_dpaths) return str(self.project_name) + ' %d repos' % (num_repos,) def __init__(self, name=None): self.project_name = name self.project_dpaths = None self.project_include_patterns = None self.project_exclude_dirs = [] self.project_exclude_patterns = [] def grep(self, *args, **kwargs): return grep_projects(user_profile=self, *args, **kwargs) def glob(self, *args, **kwargs): r""" # Ensure that .gitignore has certain lines git_ignore_lines = [ 'timeings.txt' ] fpath_list = profile.glob('.gitignore', recursive=False) for fpath in fpath_list: lines = ut.readfrom(fpath, verbose=False).split('\n') lines = [line.strip() for line in lines] missing = ut.setdiff(git_ignore_lines, lines) if missing: print('fpath = %r' % (fpath,)) ut.writeto(fpath, '\n'.join(lines + missing)) """ return glob_projects(user_profile=self, *args, **kwargs) # def __str__(self): # return def ibeis_user_profile(): import utool as ut import sys addpath = True module_fpath = ut.truepath('~/local/init/REPOS1.py') if addpath: module_dpath = dirname(module_fpath) sys.path.append(module_dpath) REPOS1 = ut.import_module_from_fpath(module_fpath) self = UserProfile(name='ibeis') #self.project_dpaths = REPOS1.PROJECT_REPOS self.project_dpaths = REPOS1.IBEIS_REPOS # self.project_dpaths += [ut.truepath('~/latex/crall-candidacy-2015/')] self.project_dpaths += [ ut.truepath('~/local'), ut.truepath('~/code/fixtex'), ut.truepath('~/code/pyrf'), ut.truepath('~/code/detecttools'), ut.truepath('~/code/pydarknet'), ] self.project_dpaths = ut.unique(self.project_dpaths) # self.project_dpaths += [ut.truepath('~/local/vim/rc')] self.project_include_patterns = [ '*.py', '*.cxx', '*.cpp', '*.hxx', '*.hpp', '*.c', '*.h', '*.vim' #'*.py', # '*.cxx', '*.cpp', '*.hxx', '*.hpp', '*.c', '*.h', '*.vim' ] self.project_exclude_dirs = [ '_graveyard', '_broken', 'CompilerIdCXX', 'CompilerIdC', 'build', 'old', '_old_qt_hs_matcher', 'htmlcov' ] self.project_exclude_patterns = ['_grave*', '_autogen_explicit_controller*'] return self def ensure_user_profile(user_profile=None): r""" Args: user_profile (UserProfile): (default = None) Returns: UserProfile: user_profile CommandLine: python -m utool.util_project --exec-ensure_user_profile --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_project import * # NOQA >>> import utool as ut >>> user_profile = None >>> user_profile = ensure_user_profile(user_profile) >>> result = ('user_profile = %s' % (ut.repr2(user_profile),)) >>> print(ut.repr3(user_profile.project_dpaths)) >>> print(result) """ global __GLOBAL_PROFILE__ if __GLOBAL_PROFILE__ is None: import utool as ut if ut.is_developer(): __GLOBAL_PROFILE__ = ibeis_user_profile() else: __GLOBAL_PROFILE__ = UserProfile('default') if user_profile is None: user_profile = __GLOBAL_PROFILE__ return user_profile def grep_projects(tofind_list, user_profile=None, verbose=True, new=False, **kwargs): r""" Greps the projects defined in the current UserProfile Args: tofind_list (list): user_profile (None): (default = None) Kwargs: user_profile CommandLine: python -m utool --tf grep_projects grep_projects Example: >>> # DISABLE_DOCTEST >>> from utool.util_project import * # NOQA >>> import utool as ut >>> import sys >>> tofind_list = ut.get_argval('--find', type_=list, >>> default=[sys.argv[-1]]) >>> grep_projects(tofind_list) """ import utool as ut user_profile = ensure_user_profile(user_profile) print('user_profile = {!r}'.format(user_profile)) kwargs = kwargs.copy() colored = kwargs.pop('colored', True) grepkw = {} grepkw['greater_exclude_dirs'] = user_profile.project_exclude_dirs grepkw['exclude_dirs'] = user_profile.project_exclude_dirs grepkw['dpath_list'] = user_profile.project_dpaths grepkw['include_patterns'] = user_profile.project_include_patterns grepkw['exclude_patterns'] = user_profile.project_exclude_patterns grepkw.update(kwargs) msg_list1 = [] msg_list2 = [] print_ = msg_list1.append print_('Greping Projects') print_('tofind_list = %s' % (ut.repr4(tofind_list, nl=True),)) #print_('grepkw = %s' % ut.repr4(grepkw, nl=True)) if verbose: print('\n'.join(msg_list1)) #with ut.Timer('greping', verbose=True): grep_result = ut.grep(tofind_list, **grepkw) found_fpath_list, found_lines_list, found_lxs_list = grep_result # HACK, duplicate behavior. TODO: write grep print result function reflags = grepkw.get('reflags', 0) _exprs_flags = [ut.extend_regex2(expr, reflags) for expr in tofind_list] extended_regex_list = ut.take_column(_exprs_flags, 0) reflags_list = ut.take_column(_exprs_flags, 1) # HACK # pat = ut.util_regex.regex_or(extended_regex_list) reflags = reflags_list[0] # from utool import util_regex resultstr = ut.make_grep_resultstr(grep_result, extended_regex_list, reflags, colored=colored) msg_list2.append(resultstr) print_ = msg_list2.append #for fpath, lines, lxs in zip(found_fpath_list, found_lines_list, # found_lxs_list): # print_('----------------------') # print_('found %d line(s) in %r: ' % (len(lines), fpath)) # name = split(fpath)[1] # max_line = len(lines) # ndigits = str(len(str(max_line))) # for (lx, line) in zip(lxs, lines): # line = line.replace('\n', '') # print_(('%s : %' + ndigits + 'd |%s') % (name, lx, line)) # iter_ = zip(found_fpath_list, found_lines_list, found_lxs_list) # for fpath, lines, lxs in iter_: # print_('----------------------') # print_('found %d line(s) in %r: ' % (len(lines), fpath)) # name = split(fpath)[1] # max_line = len(lines) # ndigits = str(len(str(max_line))) # for (lx, line) in zip(lxs, lines): # line = line.replace('\n', '') # colored_line = ut.highlight_regex( # line.rstrip('\n'), pat, reflags=reflags) # print_(('%s : %' + ndigits + 'd |%s') % (name, lx, colored_line)) print_('====================') print_('found_fpath_list = ' + ut.repr4(found_fpath_list)) print_('') #print_('gvim -o ' + ' '.join(found_fpath_list)) if verbose: print('\n'.join(msg_list2)) msg_list = msg_list1 + msg_list2 if new: return GrepResult(found_fpath_list, found_lines_list, found_lxs_list, extended_regex_list, reflags) else: return msg_list def glob_projects(pat, user_profile=None, recursive=True): """ def testenv(modname, funcname): ut.import_modname(modname) exec(ut.execstr_funckw(table.get_rowid), globals()) Ignore: >>> import utool as ut >>> ut.testenv('utool.util_project', 'glob_projects', globals()) >>> from utool.util_project import * # NOQA """ import utool as ut # NOQA user_profile = ensure_user_profile(user_profile) glob_results = ut.flatten([ut.glob(dpath, pat, recursive=recursive, exclude_dirs=user_profile.project_exclude_dirs) for dpath in user_profile.project_dpaths]) return glob_results class GrepResult(util_dev.NiceRepr): def __init__(self, found_fpath_list, found_lines_list, found_lxs_list, extended_regex_list, reflags): self.found_fpath_list = found_fpath_list self.found_lines_list = found_lines_list self.found_lxs_list = found_lxs_list self.extended_regex_list = extended_regex_list self.reflags = reflags self.filter_pats = [] def __nice__(self): return '(%d)' % (len(self),) def __str__(self): return self.make_resultstr() def __len__(self): return len(self.found_fpath_list) def __delitem__(self, index): import utool as ut index = ut.ensure_iterable(index) ut.delete_items_by_index(self.found_fpath_list, index) ut.delete_items_by_index(self.found_lines_list, index) ut.delete_items_by_index(self.found_lxs_list, index) def __getitem__(self, index): return ( ut.take(self.found_fpath_list, index), ut.take(self.found_lines_list, index), ut.take(self.found_lxs_list, index), ) def remove_results(self, indicies): del self[indicies] def make_resultstr(self, colored=True): import utool as ut tup = (self.found_fpath_list, self.found_lines_list, self.found_lxs_list) return ut.make_grep_resultstr(tup, self.extended_regex_list, self.reflags, colored=colored) # def make_big_resultstr(): # pass def pattern_filterflags(self, filter_pat): self.filter_pats.append(filter_pat) import re flags_list = [[re.search(filter_pat, line) is None for line in lines] for fpath, lines, lxs in zip(self.found_fpath_list, self.found_lines_list, self.found_lxs_list)] return flags_list def inplace_filter_results(self, filter_pat): import utool as ut self.filter_pats.append(filter_pat) # Get zipflags flags_list = self.pattern_filterflags(filter_pat) # Check to see if there are any survivors flags = ut.lmap(any, flags_list) # found_lines_list = ut.zipcompress(self.found_lines_list, flags_list) found_lxs_list = ut.zipcompress(self.found_lxs_list, flags_list) # found_fpath_list = ut.compress(self.found_fpath_list, flags) found_lines_list = ut.compress(found_lines_list, flags) found_lxs_list = ut.compress(found_lxs_list, flags) # In place modification self.found_fpath_list = found_fpath_list self.found_lines_list = found_lines_list self.found_lxs_list = found_lxs_list def hack_remove_pystuff(self): import utool as ut # Hack of a method new_lines = [] for lines in self.found_lines_list: # remove comment results flags = [not line.strip().startswith('# ') for line in lines] lines = ut.compress(lines, flags) # remove doctest results flags = [not line.strip().startswith('>>> ') for line in lines] lines = ut.compress(lines, flags) # remove cmdline tests import re flags = [not re.search('--test-' + self.extended_regex_list[0], line) for line in lines] lines = ut.compress(lines, flags) flags = [not re.search('--exec-' + self.extended_regex_list[0], line) for line in lines] lines = ut.compress(lines, flags) flags = [not re.search('--exec-[a-zA-z]*\.' + self.extended_regex_list[0], line) for line in lines] lines = ut.compress(lines, flags) flags = [not re.search('--test-[a-zA-z]*\.' + self.extended_regex_list[0], line) for line in lines] lines = ut.compress(lines, flags) # remove func defs flags = [not re.search('def ' + self.extended_regex_list[0], line) for line in lines] lines = ut.compress(lines, flags) new_lines += [lines] self.found_lines_list = new_lines # compress self flags = [len(lines_) > 0 for lines_ in self.found_lines_list] idxs = ut.list_where(ut.not_list(flags)) del self[idxs] ## Grep my projects #def gp(r, regexp): # rob_nav._grep(r, [regexp], recursive=True, dpath_list=project_dpaths(), regex=True) ## Sed my projects #def sp(r, regexpr, repl, force=False): # rob_nav._sed(r, regexpr, repl, force=force, recursive=True, dpath_list=project_dpaths()) def sed_projects(regexpr, repl, force=False, recursive=True, user_profile=None, **kwargs): r""" Args: regexpr (?): repl (?): force (bool): (default = False) recursive (bool): (default = True) user_profile (None): (default = None) CommandLine: python -m utool.util_project --exec-sed_projects Example: >>> # DISABLE_DOCTEST >>> from utool.util_project import * # NOQA >>> regexpr = ut.get_argval('--find', type_=str, default=sys.argv[-1]) >>> repl = ut.get_argval('--repl', type_=str, default=sys.argv[-2]) >>> force = False >>> recursive = True >>> user_profile = None >>> result = sed_projects(regexpr, repl, force, recursive, user_profile) >>> print(result) Ignore: regexpr = 'annotation match_scores' repl = 'draw_annot_scoresep' """ # FIXME: finishme import utool as ut user_profile = ensure_user_profile(user_profile) sedkw = {} sedkw['exclude_dirs'] = user_profile.project_exclude_dirs sedkw['dpath_list'] = user_profile.project_dpaths sedkw['include_patterns'] = user_profile.project_include_patterns sedkw.update(kwargs) msg_list1 = [] #msg_list2 = [] print_ = msg_list1.append print_('Seding Projects') print(' * regular expression : %r' % (regexpr,)) print(' * replacement : %r' % (repl,)) print_('sedkw = %s' % ut.repr4(sedkw, nl=True)) print(' * recursive: %r' % (recursive,)) print(' * force: %r' % (force,)) # Walk through each directory recursively for fpath in ut.matching_fpaths(sedkw['dpath_list'], sedkw['include_patterns'], sedkw['exclude_dirs'], recursive=recursive): ut.sedfile(fpath, regexpr, repl, force) #def extend_regex(regexpr): # regex_map = { # r'\<': r'\b(?=\w)', # r'\>': r'\b(?!\w)', # ('UNSAFE', r'\x08'): r'\b', # } # for key, repl in six.iteritems(regex_map): # if isinstance(key, tuple): # search = key[1] # else: # search = key # if regexpr.find(search) != -1: # if isinstance(key, tuple): # print('WARNING! Unsafe regex with: %r' % (key,)) # regexpr = regexpr.replace(search, repl) # return regexpr #regexpr = extend_regex(regexpr) #if '\x08' in regexpr: # print('Remember \\x08 != \\b') # print('subsituting for you for you') # regexpr = regexpr.replace('\x08', '\\b') # print(' * regular expression : %r' % (regexpr,)) if False: def ensure_vim_plugins(): """ python ~/local/init/ensure_vim_plugins.py '~/local/init/ensure_vim_plugins.py' '~/local/init/REPOS1.py' """ # TODO pass def find_module_callers(): """ TODO: attempt to build a call graph between module functions to make it easy to see what can be removed and what cannot. """ import utool as ut from os.path import normpath mod_fpath = ut.truepath('~/code/ibeis/ibeis/expt/results_analyzer.py') mod_fpath = ut.truepath('~/code/ibeis/ibeis/expt/results_all.py') mod_fpath = ut.truepath('~/code/ibeis/ibeis/expt/results_organizer.py') module = ut.import_module_from_fpath(mod_fpath) user_profile = ut.ensure_user_profile() doctestables = list(ut.iter_module_doctestable(module, include_builtin=False)) grepkw = {} grepkw['exclude_dirs'] = user_profile.project_exclude_dirs grepkw['dpath_list'] = user_profile.project_dpaths grepkw['verbose'] = True usage_map = {} for funcname, func in doctestables: print('Searching for funcname = %r' % (funcname,)) found_fpath_list, found_lines_list, found_lxs_list = ut.grep([funcname], **grepkw) used_in = (found_fpath_list, found_lines_list, found_lxs_list) usage_map[funcname] = used_in external_usage_map = {} for funcname, used_in in usage_map.items(): (found_fpath_list, found_lines_list, found_lxs_list) = used_in isexternal_flag = [normpath(fpath) != normpath(mod_fpath) for fpath in found_fpath_list] ext_used_in = (ut.compress(found_fpath_list, isexternal_flag), ut.compress(found_lines_list, isexternal_flag), ut.compress(found_lxs_list, isexternal_flag)) external_usage_map[funcname] = ext_used_in for funcname, used_in in external_usage_map.items(): (found_fpath_list, found_lines_list, found_lxs_list) = used_in print('Calling modules: \n' + ut.repr2(ut.unique_ordered(ut.flatten([used_in[0] for used_in in external_usage_map.values()])), nl=True)) if __name__ == '__main__': """ CommandLine: python -m utool.util_project python -m utool.util_project --allexamples python -m utool.util_project --allexamples --noface --nosrc """ import multiprocessing multiprocessing.freeze_support() # for win32 import utool as ut # NOQA ut.doctest_funcs()
apache-2.0
rhshah/Miscellaneous
check_cDNA_Contamination/check_cDNA_contamination.py
3
4630
""" Created on 11/01/2015. @author: Ronak H Shah ###Required Input columns in the structural variant file TumorId NormalId Chr1 Pos1 Chr2 Pos2 SV_Type Gene1 Gene2 Transcript1 Transcript2 Site1Description Site2Description Fusion Confidence Comments Connection_Type SV_LENGTH MAPQ PairEndReadSupport SplitReadSupport BrkptType ConsensusSequence TumorVariantCount TumorSplitVariantCount TumorReadCount TumorGenotypeQScore NormalVariantCount NormalSplitVariantCount NormalReadCount NormalGenotypeQScore ###Output columns "TumorId Genes_with_cDNA_contamination" """ import argparse import pandas as pd import time import sys def main(): parser = argparse.ArgumentParser( prog='check_cDNA_contamination.py', description='Calculate cDNA contamination per sample based of the Structural Variants Pipeline result', usage='%(prog)s [options]') parser.add_argument( "-v", "--verbose", action="store_true", dest="verbose", default=True, help="make lots of noise [default]") parser.add_argument( "-s", "--svFile", action="store", dest="svFilename", required=True, metavar='SVfile.txt', help="Location of the structural variant file to be used") parser.add_argument( "-o", "--outputFileName", action="store", dest="outFileName", required=True, metavar='cDNA_contamination', help="Full path name for the output file") args = parser.parse_args() # Read the structural variant file (dataDF) = ReadSV(args.svFilename, args) # Process the structural variant file (dataDict) = ProcessData(dataDF) # Write results in the output file specified WriteResults(dataDict, args) # Read the structural variant file def ReadSV(file, args): dataDF = pd.read_csv(file, sep='\t', header=0, keep_default_na='True') return(dataDF) # Process the pandas dataframe to get contaminataed genes def ProcessData(dataDF): # Group the data by tumor id, gene1 name, type of sv gDF = dataDF.groupby(['TumorId', 'Gene1', 'SV_Type']).groups # initialize and empty dictionary resultdict = {} # traverse through gDF dictionary for key, value in gDF.iteritems(): # get name of the sample its meta data (tumorID, gene1, svtype) = key # check how many entries are there of sv type entires = len(value) # initialize the number of cDNA events and a list of corresponding genes count = 0 geneList = [] # run only if the event is deletion and has more then 2 entries for the same gene if(svtype == 'DEL' and entires >= 2): for idx in value: record = dataDF.loc[idx] site1 = str(record.loc['Site1Description']) site2 = str(record.loc['Site2Description']) fusion = str(record.loc['Fusion']) brkptType = str(record.loc['BrkptType']) # Skip entries that are within exon or are in-frame or out-of frame or are IMPRECISE. if(("Exon" in site1 and "Exon" in site2) or ("in frame" in fusion or "out of frame" in fusion) or (brkptType == "IMPRECISE")): continue else: count = count + 1 # count the entries,genes and fill the resultdict if tumorID in resultdict: geneList = resultdict[tumorID] if(count >= 2): geneList.append(gene1) resultdict[tumorID] = geneList else: if(count >= 2): geneList.append(gene1) resultdict[tumorID] = geneList return(resultdict) def WriteResults(dataDict, args): if not dataDict: print "No contamination found\n" return() else: # Convert the dictionaries values which are as list to string for key, value in dataDict.iteritems(): newvalue = ', '.join(value) dataDict[key] = newvalue resultDF = pd.DataFrame(dataDict.items(), columns=['TumorId', 'Genes_with_cDNA_contamination']).sort('TumorId') # Print to TSV file resultDF.to_csv(args.outFileName, sep='\t', index=False) return() #Run the main program if __name__ == "__main__": start_time = time.time() main() end_time = time.time() seconds = end_time - start_time print "Elapsed time was ", time.strftime("%H:%M:%S", time.gmtime(seconds))
apache-2.0
joernhees/scikit-learn
examples/model_selection/plot_roc_crossval.py
28
3697
""" ============================================================= Receiver Operating Characteristic (ROC) with cross validation ============================================================= Example of Receiver Operating Characteristic (ROC) metric to evaluate classifier output quality using cross-validation. ROC curves typically feature true positive rate on the Y axis, and false positive rate on the X axis. This means that the top left corner of the plot is the "ideal" point - a false positive rate of zero, and a true positive rate of one. This is not very realistic, but it does mean that a larger area under the curve (AUC) is usually better. The "steepness" of ROC curves is also important, since it is ideal to maximize the true positive rate while minimizing the false positive rate. This example shows the ROC response of different datasets, created from K-fold cross-validation. Taking all of these curves, it is possible to calculate the mean area under curve, and see the variance of the curve when the training set is split into different subsets. This roughly shows how the classifier output is affected by changes in the training data, and how different the splits generated by K-fold cross-validation are from one another. .. note:: See also :func:`sklearn.metrics.auc_score`, :func:`sklearn.model_selection.cross_val_score`, :ref:`sphx_glr_auto_examples_model_selection_plot_roc.py`, """ print(__doc__) import numpy as np from scipy import interp import matplotlib.pyplot as plt from itertools import cycle from sklearn import svm, datasets from sklearn.metrics import roc_curve, auc from sklearn.model_selection import StratifiedKFold ############################################################################### # Data IO and generation # import some data to play with iris = datasets.load_iris() X = iris.data y = iris.target X, y = X[y != 2], y[y != 2] n_samples, n_features = X.shape # Add noisy features random_state = np.random.RandomState(0) X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] ############################################################################### # Classification and ROC analysis # Run classifier with cross-validation and plot ROC curves cv = StratifiedKFold(n_splits=6) classifier = svm.SVC(kernel='linear', probability=True, random_state=random_state) tprs = [] aucs = [] mean_fpr = np.linspace(0, 1, 100) i = 0 for train, test in cv.split(X, y): probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test]) # Compute ROC curve and area the curve fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1]) tprs.append(interp(mean_fpr, fpr, tpr)) tprs[-1][0] = 0.0 roc_auc = auc(fpr, tpr) aucs.append(roc_auc) plt.plot(fpr, tpr, lw=1, alpha=0.3, label='ROC fold %d (AUC = %0.2f)' % (i, roc_auc)) i += 1 plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r', label='Luck', alpha=.8) mean_tpr = np.mean(tprs, axis=0) mean_tpr[-1] = 1.0 mean_auc = auc(mean_fpr, mean_tpr) std_auc = np.std(aucs) plt.plot(mean_fpr, mean_tpr, color='b', label=r'Mean ROC (AUC = %0.2f $\pm$ %0.2f)' % (mean_auc, std_auc), lw=2, alpha=.8) std_tpr = np.std(tprs, axis=0) tprs_upper = np.minimum(mean_tpr + std_tpr, 1) tprs_lower = np.maximum(mean_tpr - std_tpr, 0) plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2, label=r'$\pm$ 1 std. dev.') plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show()
bsd-3-clause
GuessWhoSamFoo/pandas
pandas/tests/indexing/test_partial.py
1
23612
""" test setting *parts* of objects both positionally and label based TOD: these should be split among the indexer tests """ from warnings import catch_warnings import numpy as np import pytest import pandas as pd from pandas import DataFrame, Index, Panel, Series, date_range from pandas.util import testing as tm class TestPartialSetting(object): @pytest.mark.filterwarnings("ignore:\\nPanel:FutureWarning") @pytest.mark.filterwarnings("ignore:\\n.ix:DeprecationWarning") def test_partial_setting(self): # GH2578, allow ix and friends to partially set # series s_orig = Series([1, 2, 3]) s = s_orig.copy() s[5] = 5 expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) s = s_orig.copy() s.loc[5] = 5 expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) s = s_orig.copy() s[5] = 5. expected = Series([1, 2, 3, 5.], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) s = s_orig.copy() s.loc[5] = 5. expected = Series([1, 2, 3, 5.], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) # iloc/iat raise s = s_orig.copy() with pytest.raises(IndexError): s.iloc[3] = 5. with pytest.raises(IndexError): s.iat[3] = 5. # ## frame ## df_orig = DataFrame( np.arange(6).reshape(3, 2), columns=['A', 'B'], dtype='int64') # iloc/iat raise df = df_orig.copy() with pytest.raises(IndexError): df.iloc[4, 2] = 5. with pytest.raises(IndexError): df.iat[4, 2] = 5. # row setting where it exists expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]})) df = df_orig.copy() df.iloc[1] = df.iloc[2] tm.assert_frame_equal(df, expected) expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]})) df = df_orig.copy() df.loc[1] = df.loc[2] tm.assert_frame_equal(df, expected) # like 2578, partial setting with dtype preservation expected = DataFrame(dict({'A': [0, 2, 4, 4], 'B': [1, 3, 5, 5]})) df = df_orig.copy() df.loc[3] = df.loc[2] tm.assert_frame_equal(df, expected) # single dtype frame, overwrite expected = DataFrame(dict({'A': [0, 2, 4], 'B': [0, 2, 4]})) df = df_orig.copy() with catch_warnings(record=True): df.ix[:, 'B'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) # mixed dtype frame, overwrite expected = DataFrame(dict({'A': [0, 2, 4], 'B': Series([0, 2, 4])})) df = df_orig.copy() df['B'] = df['B'].astype(np.float64) with catch_warnings(record=True): df.ix[:, 'B'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) # single dtype frame, partial setting expected = df_orig.copy() expected['C'] = df['A'] df = df_orig.copy() with catch_warnings(record=True): df.ix[:, 'C'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) # mixed frame, partial setting expected = df_orig.copy() expected['C'] = df['A'] df = df_orig.copy() with catch_warnings(record=True): df.ix[:, 'C'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) with catch_warnings(record=True): # ## panel ## p_orig = Panel(np.arange(16).reshape(2, 4, 2), items=['Item1', 'Item2'], major_axis=pd.date_range('2001/1/12', periods=4), minor_axis=['A', 'B'], dtype='float64') # panel setting via item p_orig = Panel(np.arange(16).reshape(2, 4, 2), items=['Item1', 'Item2'], major_axis=pd.date_range('2001/1/12', periods=4), minor_axis=['A', 'B'], dtype='float64') expected = p_orig.copy() expected['Item3'] = expected['Item1'] p = p_orig.copy() p.loc['Item3'] = p['Item1'] tm.assert_panel_equal(p, expected) # panel with aligned series expected = p_orig.copy() expected = expected.transpose(2, 1, 0) expected['C'] = DataFrame({'Item1': [30, 30, 30, 30], 'Item2': [32, 32, 32, 32]}, index=p_orig.major_axis) expected = expected.transpose(2, 1, 0) p = p_orig.copy() p.loc[:, :, 'C'] = Series([30, 32], index=p_orig.items) tm.assert_panel_equal(p, expected) # GH 8473 dates = date_range('1/1/2000', periods=8) df_orig = DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D']) expected = pd.concat([df_orig, DataFrame({'A': 7}, index=[dates[-1] + dates.freq])], sort=True) df = df_orig.copy() df.loc[dates[-1] + dates.freq, 'A'] = 7 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.at[dates[-1] + dates.freq, 'A'] = 7 tm.assert_frame_equal(df, expected) exp_other = DataFrame({0: 7}, index=[dates[-1] + dates.freq]) expected = pd.concat([df_orig, exp_other], axis=1) df = df_orig.copy() df.loc[dates[-1] + dates.freq, 0] = 7 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.at[dates[-1] + dates.freq, 0] = 7 tm.assert_frame_equal(df, expected) def test_partial_setting_mixed_dtype(self): # in a mixed dtype environment, try to preserve dtypes # by appending df = DataFrame([[True, 1], [False, 2]], columns=["female", "fitness"]) s = df.loc[1].copy() s.name = 2 expected = df.append(s) df.loc[2] = df.loc[1] tm.assert_frame_equal(df, expected) # columns will align df = DataFrame(columns=['A', 'B']) df.loc[0] = Series(1, index=range(4)) tm.assert_frame_equal(df, DataFrame(columns=['A', 'B'], index=[0])) # columns will align df = DataFrame(columns=['A', 'B']) df.loc[0] = Series(1, index=['B']) exp = DataFrame([[np.nan, 1]], columns=['A', 'B'], index=[0], dtype='float64') tm.assert_frame_equal(df, exp) # list-like must conform df = DataFrame(columns=['A', 'B']) with pytest.raises(ValueError): df.loc[0] = [1, 2, 3] # TODO: #15657, these are left as object and not coerced df = DataFrame(columns=['A', 'B']) df.loc[3] = [6, 7] exp = DataFrame([[6, 7]], index=[3], columns=['A', 'B'], dtype='object') tm.assert_frame_equal(df, exp) def test_series_partial_set(self): # partial set with new index # Regression from GH4825 ser = Series([0.1, 0.2], index=[1, 2]) # loc equiv to .reindex expected = Series([np.nan, 0.2, np.nan], index=[3, 2, 3]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = ser.loc[[3, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) result = ser.reindex([3, 2, 3]) tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([np.nan, 0.2, np.nan, np.nan], index=[3, 2, 3, 'x']) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = ser.loc[[3, 2, 3, 'x']] tm.assert_series_equal(result, expected, check_index_type=True) result = ser.reindex([3, 2, 3, 'x']) tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.2, 0.2, 0.1], index=[2, 2, 1]) result = ser.loc[[2, 2, 1]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.2, 0.2, np.nan, 0.1], index=[2, 2, 'x', 1]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = ser.loc[[2, 2, 'x', 1]] tm.assert_series_equal(result, expected, check_index_type=True) result = ser.reindex([2, 2, 'x', 1]) tm.assert_series_equal(result, expected, check_index_type=True) # raises as nothing in in the index msg = (r"\"None of \[Int64Index\(\[3, 3, 3\], dtype='int64'\)\] are" r" in the \[index\]\"") with pytest.raises(KeyError, match=msg): ser.loc[[3, 3, 3]] expected = Series([0.2, 0.2, np.nan], index=[2, 2, 3]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = ser.loc[[2, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) result = ser.reindex([2, 2, 3]) tm.assert_series_equal(result, expected, check_index_type=True) s = Series([0.1, 0.2, 0.3], index=[1, 2, 3]) expected = Series([0.3, np.nan, np.nan], index=[3, 4, 4]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = s.loc[[3, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) result = s.reindex([3, 4, 4]) tm.assert_series_equal(result, expected, check_index_type=True) s = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]) expected = Series([np.nan, 0.3, 0.3], index=[5, 3, 3]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = s.loc[[5, 3, 3]] tm.assert_series_equal(result, expected, check_index_type=True) result = s.reindex([5, 3, 3]) tm.assert_series_equal(result, expected, check_index_type=True) s = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]) expected = Series([np.nan, 0.4, 0.4], index=[5, 4, 4]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = s.loc[[5, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) result = s.reindex([5, 4, 4]) tm.assert_series_equal(result, expected, check_index_type=True) s = Series([0.1, 0.2, 0.3, 0.4], index=[4, 5, 6, 7]) expected = Series([0.4, np.nan, np.nan], index=[7, 2, 2]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = s.loc[[7, 2, 2]] tm.assert_series_equal(result, expected, check_index_type=True) result = s.reindex([7, 2, 2]) tm.assert_series_equal(result, expected, check_index_type=True) s = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]) expected = Series([0.4, np.nan, np.nan], index=[4, 5, 5]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = s.loc[[4, 5, 5]] tm.assert_series_equal(result, expected, check_index_type=True) result = s.reindex([4, 5, 5]) tm.assert_series_equal(result, expected, check_index_type=True) # iloc expected = Series([0.2, 0.2, 0.1, 0.1], index=[2, 2, 1, 1]) result = ser.iloc[[1, 1, 0, 0]] tm.assert_series_equal(result, expected, check_index_type=True) def test_series_partial_set_with_name(self): # GH 11497 idx = Index([1, 2], dtype='int64', name='idx') ser = Series([0.1, 0.2], index=idx, name='s') # loc exp_idx = Index([3, 2, 3], dtype='int64', name='idx') expected = Series([np.nan, 0.2, np.nan], index=exp_idx, name='s') with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = ser.loc[[3, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([3, 2, 3, 'x'], dtype='object', name='idx') expected = Series([np.nan, 0.2, np.nan, np.nan], index=exp_idx, name='s') with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = ser.loc[[3, 2, 3, 'x']] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([2, 2, 1], dtype='int64', name='idx') expected = Series([0.2, 0.2, 0.1], index=exp_idx, name='s') result = ser.loc[[2, 2, 1]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([2, 2, 'x', 1], dtype='object', name='idx') expected = Series([0.2, 0.2, np.nan, 0.1], index=exp_idx, name='s') with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = ser.loc[[2, 2, 'x', 1]] tm.assert_series_equal(result, expected, check_index_type=True) # raises as nothing in in the index msg = (r"\"None of \[Int64Index\(\[3, 3, 3\], dtype='int64'," r" name=u?'idx'\)\] are in the \[index\]\"") with pytest.raises(KeyError, match=msg): ser.loc[[3, 3, 3]] exp_idx = Index([2, 2, 3], dtype='int64', name='idx') expected = Series([0.2, 0.2, np.nan], index=exp_idx, name='s') with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = ser.loc[[2, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([3, 4, 4], dtype='int64', name='idx') expected = Series([0.3, np.nan, np.nan], index=exp_idx, name='s') idx = Index([1, 2, 3], dtype='int64', name='idx') with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = Series([0.1, 0.2, 0.3], index=idx, name='s').loc[[3, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([5, 3, 3], dtype='int64', name='idx') expected = Series([np.nan, 0.3, 0.3], index=exp_idx, name='s') idx = Index([1, 2, 3, 4], dtype='int64', name='idx') with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[5, 3, 3]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([5, 4, 4], dtype='int64', name='idx') expected = Series([np.nan, 0.4, 0.4], index=exp_idx, name='s') idx = Index([1, 2, 3, 4], dtype='int64', name='idx') with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[5, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([7, 2, 2], dtype='int64', name='idx') expected = Series([0.4, np.nan, np.nan], index=exp_idx, name='s') idx = Index([4, 5, 6, 7], dtype='int64', name='idx') with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[7, 2, 2]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([4, 5, 5], dtype='int64', name='idx') expected = Series([0.4, np.nan, np.nan], index=exp_idx, name='s') idx = Index([1, 2, 3, 4], dtype='int64', name='idx') with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[4, 5, 5]] tm.assert_series_equal(result, expected, check_index_type=True) # iloc exp_idx = Index([2, 2, 1, 1], dtype='int64', name='idx') expected = Series([0.2, 0.2, 0.1, 0.1], index=exp_idx, name='s') result = ser.iloc[[1, 1, 0, 0]] tm.assert_series_equal(result, expected, check_index_type=True) @pytest.mark.filterwarnings("ignore:\\n.ix") def test_partial_set_invalid(self): # GH 4940 # allow only setting of 'valid' values orig = tm.makeTimeDataFrame() df = orig.copy() # don't allow not string inserts with pytest.raises(TypeError): with catch_warnings(record=True): df.loc[100.0, :] = df.ix[0] with pytest.raises(TypeError): with catch_warnings(record=True): df.loc[100, :] = df.ix[0] with pytest.raises(TypeError): with catch_warnings(record=True): df.ix[100.0, :] = df.ix[0] with pytest.raises(ValueError): with catch_warnings(record=True): df.ix[100, :] = df.ix[0] # allow object conversion here df = orig.copy() with catch_warnings(record=True): df.loc['a', :] = df.ix[0] exp = orig.append(Series(df.ix[0], name='a')) tm.assert_frame_equal(df, exp) tm.assert_index_equal(df.index, Index(orig.index.tolist() + ['a'])) assert df.index.dtype == 'object' def test_partial_set_empty_series(self): # GH5226 # partially set with an empty object series s = Series() s.loc[1] = 1 tm.assert_series_equal(s, Series([1], index=[1])) s.loc[3] = 3 tm.assert_series_equal(s, Series([1, 3], index=[1, 3])) s = Series() s.loc[1] = 1. tm.assert_series_equal(s, Series([1.], index=[1])) s.loc[3] = 3. tm.assert_series_equal(s, Series([1., 3.], index=[1, 3])) s = Series() s.loc['foo'] = 1 tm.assert_series_equal(s, Series([1], index=['foo'])) s.loc['bar'] = 3 tm.assert_series_equal(s, Series([1, 3], index=['foo', 'bar'])) s.loc[3] = 4 tm.assert_series_equal(s, Series([1, 3, 4], index=['foo', 'bar', 3])) def test_partial_set_empty_frame(self): # partially set with an empty object # frame df = DataFrame() with pytest.raises(ValueError): df.loc[1] = 1 with pytest.raises(ValueError): df.loc[1] = Series([1], index=['foo']) with pytest.raises(ValueError): df.loc[:, 1] = 1 # these work as they don't really change # anything but the index # GH5632 expected = DataFrame(columns=['foo'], index=Index([], dtype='int64')) def f(): df = DataFrame() df['foo'] = Series([], dtype='object') return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() df['foo'] = Series(df.index) return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() df['foo'] = df.index return df tm.assert_frame_equal(f(), expected) expected = DataFrame(columns=['foo'], index=Index([], dtype='int64')) expected['foo'] = expected['foo'].astype('float64') def f(): df = DataFrame() df['foo'] = [] return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() df['foo'] = Series(np.arange(len(df)), dtype='float64') return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() tm.assert_index_equal(df.index, Index([], dtype='object')) df['foo'] = range(len(df)) return df expected = DataFrame(columns=['foo'], index=Index([], dtype='int64')) expected['foo'] = expected['foo'].astype('float64') tm.assert_frame_equal(f(), expected) df = DataFrame() tm.assert_index_equal(df.columns, Index([], dtype=object)) df2 = DataFrame() df2[1] = Series([1], index=['foo']) df.loc[:, 1] = Series([1], index=['foo']) tm.assert_frame_equal(df, DataFrame([[1]], index=['foo'], columns=[1])) tm.assert_frame_equal(df, df2) # no index to start expected = DataFrame({0: Series(1, index=range(4))}, columns=['A', 'B', 0]) df = DataFrame(columns=['A', 'B']) df[0] = Series(1, index=range(4)) df.dtypes str(df) tm.assert_frame_equal(df, expected) df = DataFrame(columns=['A', 'B']) df.loc[:, 0] = Series(1, index=range(4)) df.dtypes str(df) tm.assert_frame_equal(df, expected) def test_partial_set_empty_frame_row(self): # GH5720, GH5744 # don't create rows when empty expected = DataFrame(columns=['A', 'B', 'New'], index=Index([], dtype='int64')) expected['A'] = expected['A'].astype('int64') expected['B'] = expected['B'].astype('float64') expected['New'] = expected['New'].astype('float64') df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]}) y = df[df.A > 5] y['New'] = np.nan tm.assert_frame_equal(y, expected) # tm.assert_frame_equal(y,expected) expected = DataFrame(columns=['a', 'b', 'c c', 'd']) expected['d'] = expected['d'].astype('int64') df = DataFrame(columns=['a', 'b', 'c c']) df['d'] = 3 tm.assert_frame_equal(df, expected) tm.assert_series_equal(df['c c'], Series(name='c c', dtype=object)) # reindex columns is ok df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]}) y = df[df.A > 5] result = y.reindex(columns=['A', 'B', 'C']) expected = DataFrame(columns=['A', 'B', 'C'], index=Index([], dtype='int64')) expected['A'] = expected['A'].astype('int64') expected['B'] = expected['B'].astype('float64') expected['C'] = expected['C'].astype('float64') tm.assert_frame_equal(result, expected) def test_partial_set_empty_frame_set_series(self): # GH 5756 # setting with empty Series df = DataFrame(Series()) tm.assert_frame_equal(df, DataFrame({0: Series()})) df = DataFrame(Series(name='foo')) tm.assert_frame_equal(df, DataFrame({'foo': Series()})) def test_partial_set_empty_frame_empty_copy_assignment(self): # GH 5932 # copy on empty with assignment fails df = DataFrame(index=[0]) df = df.copy() df['a'] = 0 expected = DataFrame(0, index=[0], columns=['a']) tm.assert_frame_equal(df, expected) def test_partial_set_empty_frame_empty_consistencies(self): # GH 6171 # consistency on empty frames df = DataFrame(columns=['x', 'y']) df['x'] = [1, 2] expected = DataFrame(dict(x=[1, 2], y=[np.nan, np.nan])) tm.assert_frame_equal(df, expected, check_dtype=False) df = DataFrame(columns=['x', 'y']) df['x'] = ['1', '2'] expected = DataFrame( dict(x=['1', '2'], y=[np.nan, np.nan]), dtype=object) tm.assert_frame_equal(df, expected) df = DataFrame(columns=['x', 'y']) df.loc[0, 'x'] = 1 expected = DataFrame(dict(x=[1], y=[np.nan])) tm.assert_frame_equal(df, expected, check_dtype=False)
bsd-3-clause
jlevy44/Joshua-Levy-Synteny-Analysis
hybridumAnalysisScripts/FixBhydTest/bhybridumMappingProbs.py
1
1094
from collections import defaultdict import numpy as np import matplotlib.pyplot as plt sortList = open('q.PAC4GC.001.sort2','r').read().split('\n') sortDict = defaultdict(list) for line in sortList: if line: lineList = line.split() sortDict[lineList[0]] = [lineList[1]] + [int(item) for item in lineList[2:3]] geneList = [] geneCompareFiles = open('BhD001003Analysis.txt','r').read().split('\n') genelinesList = [line.split()[0].split(',')[2] for line in geneCompareFiles if len(line.split())>2 and ':' in line.split()[1] and line.split()[0].split(',')[0] == 'BhD1'] geneList = set(genelinesList) totalGeneList = set(sortDict.keys()) finalGeneList = list(geneList & totalGeneList) coordinategrab = [] for gene in finalGeneList: coordinategrab += sortDict[gene][1:2] hist,bins = np.histogram(coordinategrab,bins=80) width = 0.7 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 plt.bar(center, hist, align='center', width=width) plt.title('Chromosome 1 on ABR113 for 001-003 Mapping UnOut') plt.xlabel('Position on Chromosome') plt.ylabel('Count') plt.show()
mit
thomasbarillot/DAQ
eTOF/FuncDetectPeaks.py
3
6694
# -*- coding: utf-8 -*- """ Created on Wed Mar 23 12:53:10 2016 @author: tbarillot """ """Detect peaks in data based on their amplitude and other features.""" #from __future__ import division, print_function import numpy as np __author__ = "Marcos Duarte, https://github.com/demotu/BMC" __version__ = "1.0.4" __license__ = "MIT" def detect_peaks(x, mph=None, mpd=1, threshold=0, edge='rising', kpsh=False, valley=False, show=False, ax=None): """Detect peaks in data based on their amplitude and other features. Parameters ---------- x : 1D array_like data. mph : {None, number}, optional (default = None) detect peaks that are greater than minimum peak height. mpd : positive integer, optional (default = 1) detect peaks that are at least separated by minimum peak distance (in number of data). threshold : positive number, optional (default = 0) detect peaks (valleys) that are greater (smaller) than `threshold` in relation to their immediate neighbors. edge : {None, 'rising', 'falling', 'both'}, optional (default = 'rising') for a flat peak, keep only the rising edge ('rising'), only the falling edge ('falling'), both edges ('both'), or don't detect a flat peak (None). kpsh : bool, optional (default = False) keep peaks with same height even if they are closer than `mpd`. valley : bool, optional (default = False) if True (1), detect valleys (local minima) instead of peaks. show : bool, optional (default = False) if True (1), plot data in matplotlib figure. ax : a matplotlib.axes.Axes instance, optional (default = None). Returns ------- ind : 1D array_like indeces of the peaks in `x`. Notes ----- The detection of valleys instead of peaks is performed internally by simply negating the data: `ind_valleys = detect_peaks(-x)` The function can handle NaN's See this IPython Notebook [1]_. References ---------- .. [1] http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/DetectPeaks.ipynb Examples -------- >>> from detect_peaks import detect_peaks >>> x = np.random.randn(100) >>> x[60:81] = np.nan >>> # detect all peaks and plot data >>> ind = detect_peaks(x, show=True) >>> print(ind) >>> x = np.sin(2*np.pi*5*np.linspace(0, 1, 200)) + np.random.randn(200)/5 >>> # set minimum peak height = 0 and minimum peak distance = 20 >>> detect_peaks(x, mph=0, mpd=20, show=True) >>> x = [0, 1, 0, 2, 0, 3, 0, 2, 0, 1, 0] >>> # set minimum peak distance = 2 >>> detect_peaks(x, mpd=2, show=True) >>> x = np.sin(2*np.pi*5*np.linspace(0, 1, 200)) + np.random.randn(200)/5 >>> # detection of valleys instead of peaks >>> detect_peaks(x, mph=0, mpd=20, valley=True, show=True) >>> x = [0, 1, 1, 0, 1, 1, 0] >>> # detect both edges >>> detect_peaks(x, edge='both', show=True) >>> x = [-2, 1, -2, 2, 1, 1, 3, 0] >>> # set threshold = 2 >>> detect_peaks(x, threshold = 2, show=True) """ x = np.atleast_1d(x).astype('float64') if x.size < 3: return np.array([], dtype=int) if valley: x = -x # find indexes of all peaks dx = x[1:] - x[:-1] # handle NaN's indnan = np.where(np.isnan(x))[0] if indnan.size: x[indnan] = np.inf dx[np.where(np.isnan(dx))[0]] = np.inf ine, ire, ife = np.array([[], [], []], dtype=int) if not edge: ine = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) > 0))[0] else: if edge.lower() in ['rising', 'both']: ire = np.where((np.hstack((dx, 0)) <= 0) & (np.hstack((0, dx)) > 0))[0] if edge.lower() in ['falling', 'both']: ife = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) >= 0))[0] ind = np.unique(np.hstack((ine, ire, ife))) # handle NaN's if ind.size and indnan.size: # NaN's and values close to NaN's cannot be peaks ind = ind[np.in1d(ind, np.unique(np.hstack((indnan, indnan-1, indnan+1))), invert=True)] # first and last values of x cannot be peaks if ind.size and ind[0] == 0: ind = ind[1:] if ind.size and ind[-1] == x.size-1: ind = ind[:-1] # remove peaks < minimum peak height if ind.size and mph is not None: ind = ind[x[ind] >= mph] # remove peaks - neighbors < threshold if ind.size and threshold > 0: dx = np.min(np.vstack([x[ind]-x[ind-1], x[ind]-x[ind+1]]), axis=0) ind = np.delete(ind, np.where(dx < threshold)[0]) # detect small peaks closer than minimum peak distance if ind.size and mpd > 1: ind = ind[np.argsort(x[ind])][::-1] # sort ind by peak height idel = np.zeros(ind.size, dtype=bool) for i in range(ind.size): if not idel[i]: # keep peaks with the same height if kpsh is True idel = idel | (ind >= ind[i] - mpd) & (ind <= ind[i] + mpd) \ & (x[ind[i]] > x[ind] if kpsh else True) idel[i] = 0 # Keep current peak # remove the small peaks and sort back the indexes by their occurrence ind = np.sort(ind[~idel]) if show: if indnan.size: x[indnan] = np.nan if valley: x = -x _plot(x, mph, mpd, threshold, edge, valley, ax, ind) return ind def _plot(x, mph, mpd, threshold, edge, valley, ax, ind): """Plot results of the detect_peaks function, see its help.""" try: import matplotlib.pyplot as plt except ImportError: print('matplotlib is not available.') else: if ax is None: _, ax = plt.subplots(1, 1, figsize=(8, 4)) ax.plot(x, 'b', lw=1) if ind.size: label = 'valley' if valley else 'peak' label = label + 's' if ind.size > 1 else label ax.plot(ind, x[ind], '+', mfc=None, mec='r', mew=2, ms=8, label='%d %s' % (ind.size, label)) ax.legend(loc='best', framealpha=.5, numpoints=1) ax.set_xlim(-.02*x.size, x.size*1.02-1) ymin, ymax = x[np.isfinite(x)].min(), x[np.isfinite(x)].max() yrange = ymax - ymin if ymax > ymin else 1 ax.set_ylim(ymin - 0.1*yrange, ymax + 0.1*yrange) ax.set_xlabel('Data #', fontsize=14) ax.set_ylabel('Amplitude', fontsize=14) mode = 'Valley detection' if valley else 'Peak detection' ax.set_title("%s (mph=%s, mpd=%d, threshold=%s, edge='%s')" % (mode, str(mph), mpd, str(threshold), edge)) # plt.grid() plt.show()
mit
ViennaRNA/forgi
test/forgi/projection/projection2d_test.py
1
18261
from __future__ import absolute_import, division, print_function, unicode_literals from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str, super, zip) import unittest import sys import numpy as np import numpy.testing as nptest import networkx as nx import forgi.threedee.model.coarse_grain as ftmc import forgi.projection.projection2d as fpp import forgi.threedee.utilities.vector as ftuv import matplotlib.pyplot as plt # TODO: Add tests for the label of the projected segments!!! class Projection2DBasicTest(unittest.TestCase): def setUp(self): self.longMessage = True def test_init_projection(self): cg, = ftmc.CoarseGrainRNA.from_pdb('test/forgi/threedee/data/2X1F.pdb') proj = fpp.Projection2D(cg, [1., 1., 1.]) self.assertTrue(ftuv.is_almost_parallel(proj.proj_direction, np.array([1., 1., 1.])), msg="The projection direction was not stored correctly. Should be coliniar" " with {}, got {}".format(np.array([1., 1., 1.]), proj.proj_direction)) def test_init_projection2(self): cg, = ftmc.CoarseGrainRNA.from_pdb('test/forgi/threedee/data/2X1F.pdb') cg.project_from = [1., 1., 1.] proj = fpp.Projection2D(cg) self.assertTrue(ftuv.is_almost_parallel(proj.proj_direction, np.array([1., 1., 1.])), msg="The projection direction was not stored correctly. Should be coliniar" " with {}, got {}".format(np.array([1., 1., 1.]), proj.proj_direction)) @unittest.skip("Skipping projection tests that take long") def test_init_with_rotate_for_coords(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.]) projRot = fpp.Projection2D(cg, [1., 1., 1.], rotation=90) define = list(cg.defines.keys())[0] self.assertAlmostEqual(np.dot(proj._coords[define][1] - proj._coords[define][0], projRot._coords[define][1] - projRot._coords[define][0]), 0., msg="Rotating the projection by 90 degrees does not make " "corresponding coord-vectors orthogonal!") @unittest.skip("Skipping projection tests that take long (~1min)") def test_init_with_rotate_for_virtual_atoms(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.], project_virtual_atoms=True) projRot = fpp.Projection2D( cg, [1., 1., 1.], rotation=90, project_virtual_atoms=True) self.assertAlmostEqual(np.dot(proj._virtual_atoms[100] - proj._virtual_atoms[0], projRot._virtual_atoms[100] - projRot._virtual_atoms[0]), 0., msg="Rotating the projection by 90 degrees does not make " "corresponding virtual atoms vectors orthogonal!") def test_init_with_rotate_for_virtual_residues(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D( cg, [1., 1., 1.], project_virtual_residues=[1, 30]) projRot = fpp.Projection2D( cg, [1., 1., 1.], rotation=90, project_virtual_residues=[1, 30]) self.assertAlmostEqual(np.dot(proj.get_vres_by_position(1) - proj.get_vres_by_position(30), projRot.get_vres_by_position(1) - projRot.get_vres_by_position(30)), 0., msg="Rotating the projection by 90 degrees does not make " "corresponding virtual residue vectors orthogonal!") def test_init_raises_if_no_proj_dir(self): cg, = ftmc.CoarseGrainRNA.from_pdb('test/forgi/threedee/data/2X1F.pdb') with self.assertRaises(ValueError): proj = fpp.Projection2D(cg) @unittest.skip("Skipping projection tests that take long") def test_projection_with_virtual_atoms(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.], project_virtual_atoms=True) all_vas = sum(len(cg.virtual_atoms(i).keys()) for d in cg.defines.keys() for i in cg.define_residue_num_iterator(d)) self.assertEqual(all_vas, proj._virtual_atoms.shape[0]) self.assertGreater(proj._virtual_atoms.shape[0], 5) @unittest.skip("Skipping projection tests that take long") def test_projection_with_some_virtual_atoms(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D( cg, [1., 1., 1.], project_virtual_atoms="selected") proj_all = fpp.Projection2D( cg, [1., 1., 1.], project_virtual_atoms=True) all_vas = sum(len(cg.virtual_atoms(i).keys()) for d in cg.defines.keys() for i in cg.define_residue_num_iterator(d)) self.assertLess(proj._virtual_atoms.shape[0], all_vas) self.assertLess( proj._virtual_atoms.shape[0], proj_all._virtual_atoms.shape[0]) # At least some atoms self.assertGreater(proj._virtual_atoms.shape[0], 5) @unittest.skip("Skipping projection tests that take long") def test_projection_with_virtual_residues(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.], project_virtual_residues=[ 1, len(cg.seq) // 2]) elem1 = cg.get_node_from_residue_num(1) elem2 = cg.get_node_from_residue_num(len(cg.seq) // 2) self.assertLess(ftuv.vec_distance(proj._coords[elem1][0], proj.get_vres_by_position(1)), ftuv.vec_distance( proj._coords[elem2][0], proj.get_vres_by_position(1)), msg="Projected virtual residue is closer to projection of a cg-element " "far away than to the projection of corresponding cg element.") self.assertLess(ftuv.vec_distance(proj._coords[elem2][0], proj.get_vres_by_position(len(cg.seq) // 2)), ftuv.vec_distance(proj._coords[elem1][0], proj.get_vres_by_position(len(cg.seq) // 2)), msg="Projected virtual residue is closer to projection of a cg-element " "far away than to the corresponding cg element.") def test_projection_with_nonexisting_virtual_residues(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') with self.assertRaises(LookupError): proj = fpp.Projection2D( cg, [1., 1., 1.], project_virtual_residues=[len(cg.seq) + 2]) with self.assertRaises(LookupError): proj = fpp.Projection2D( cg, [1., 1., 1.], project_virtual_residues=[0]) def test_get_vres_by_position(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D( cg, [1., 1., 1.], project_virtual_residues=[1, 4, 23]) self.assertEqual(proj.get_vres_by_position(1).shape, (2,)) self.assertEqual(proj.get_vres_by_position(4).shape, (2,)) self.assertEqual(proj.get_vres_by_position(23).shape, (2,)) def test_get_vres_by_position_raises_if_this_vres_not_projected(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D( cg, [1., 1., 1.], project_virtual_residues=[1, 4, 23]) with self.assertRaises(LookupError): proj.get_vres_by_position(7) def test_get_vres_by_position_raises_if_no_vres_projected(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.]) with self.assertRaises(LookupError): proj.get_vres_by_position(1) def test_vres_iterator(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D( cg, [1., 1., 1.], project_virtual_residues=[3, 7, 26]) self.assertEqual(sorted(list(x[0] for x in proj.vres_iterator)), [3, 7, 26]) def test_projection_longest_axis(self): cg = ftmc.CoarseGrainRNA.from_dotbracket("((()))") cg.coords["s0"] = np.array([0., 0, -1]), np.array([0., 0, 1]) proj = fpp.Projection2D(cg, [0., 1., 0.]) self.assertAlmostEqual(proj.longest_axis, 2) proj = fpp.Projection2D(cg, [0., 0., 1.]) self.assertAlmostEqual(proj.longest_axis, 0) @unittest.skip("TODO") class Projection2DTestWithData(unittest.TestCase): def setUp(self): cg, = ftmc.CoarseGrainRNA.from_pdb('test/forgi/threedee/data/1y26_two_chains.pdb', dissolve_length_one_stems=False, load_chains="X") self.proj = fpp.Projection2D(cg, [1., 1., 1.]) self.proj2 = fpp.Projection2D(cg, [0., 0., 1.]) def test_get_bounding_square(self): s1 = self.proj.get_bounding_square() s2 = self.proj.get_bounding_square(5) # is a square self.assertAlmostEqual(s1[1] - s1[0], s1[3] - s1[2]) self.assertAlmostEqual(s2[1] - s2[0], s2[3] - s2[2]) # s2 around s1 self.assertTrue(s2[0] < s1[0] and s1[0] < s2[1]) self.assertTrue(s2[1] > s1[1] and s1[1] > s2[0]) self.assertTrue(s2[2] < s1[2] and s1[2] < s2[3]) self.assertTrue(s2[3] > s1[3] and s1[3] > s2[2]) # All points inside s1 for point in self.proj.proj_graph.nodes(): self.assertLessEqual(round(s1[0], 7), round(point[0], 7), msg="Point {} outside of " "bounding square {} at the LEFT".format(point, s1)) self.assertLessEqual(round(point[0], 7), round(s1[1], 7), msg="Point {} outside of " "bounding square {} at the RIGHT".format(point, s1)) self.assertLessEqual(round(s1[2], 7), round(point[1], 7), msg="Point {} outside of " "bounding square {} at the BOTTOM".format(point, s1)) self.assertLessEqual(round(point[1], 7), round(s1[3], 7), msg="Point {} outside of " "bounding square {} at the TOP".format(point, s1)) def test_condense_points(self): self.proj.condense_points() self.assertEqual(len(self.proj.proj_graph.nodes()), 12) self.proj.condense_points(100) self.assertEqual(len(self.proj.proj_graph.nodes()), 1) def test_condense(self): self.proj2.condense_points(1) self.assertEqual(self.proj2.get_cyclebasis_len(), 1) self.assertAlmostEqual( self.proj2.get_longest_arm_length()[0], 35.9, places=1) # self.proj.plot(show=True) self.proj2.condense(5) # self.proj2.plot(show=True) self.assertEqual(self.proj2.get_cyclebasis_len(), 2) self.assertAlmostEqual(self.proj2.get_longest_arm_length()[ 0], 20.393064351368327) @unittest.skip("TODO. Changes code for PDB-loading probably changed made projection direction ") class Projection2DTestOnCondensedProjection(unittest.TestCase): def setUp(self): cg, = ftmc.CoarseGrainRNA.from_pdb('test/forgi/threedee/data/1y26_two_chains.pdb', dissolve_length_one_stems=False, load_chains="X") self.proj = fpp.Projection2D(cg, [1., 1., 1.]) self.proj.condense_points(1) @unittest.skip("This is a Manual Test") def test_plot(self): cg, = ftmc.CoarseGrainRNA.from_pdb( 'test/forgi/threedee/data/1y26_two_chains.pdb') for dire in [(1., 0., 0.), (0., 0., 1.), (0., 1., 0.), (1., 1., 0.), (1., 0., 1.), (0., 1., 1.), (1., 1., 1.)]: self.proj = fpp.Projection2D(cg, dire) self.proj.condense_points(1) self.proj.plot(show=True, add_labels=True) # plt.show() def test_get_cyclebasis_len(self): self.assertEqual(self.proj.get_cyclebasis_len(), 2) def test_get_branchpoint_count(self): self.assertEqual(self.proj.get_branchpoint_count(), 4) self.assertEqual(self.proj.get_branchpoint_count(3), 3) self.assertEqual(self.proj.get_branchpoint_count(4), 1) def test_get_total_length(self): self.assertAlmostEqual(self.proj.get_total_length(), 134.45, places=1) def test_get_maximal_path_length(self): self.assertAlmostEqual( self.proj.get_maximal_path_length(), 95.4, places=1) def test_get_longest_arm_length(self): self.assertAlmostEqual(self.proj.get_longest_arm_length()[ 0], 20.123454285158793) class Projection2DImageHelperfunctionTests(unittest.TestCase): def setUp(self): self.img_bw = np.array([[0., 0., 0., 1.], [1., 0., 0., 1.], [1., 0., 0., 0.], [0.5, 0.5, 0., 0.]]) self.img_rgb = np.array([[[0, 0, 0], [0, 0, 0], [0, 0, 0], [255, 255, 255]], [[255, 255, 255], [0, 0, 0], [ 0, 0, 0], [255, 255, 255]], [[255, 255, 255], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[127, 127, 127], [127, 127, 127], [0, 0, 0], [0, 0, 0]]]) def test_to_rgb(self): np.testing.assert_array_equal(fpp.to_rgb(self.img_bw), self.img_rgb) def test_to_grayscale(self): np.testing.assert_almost_equal(fpp.to_grayscale( self.img_rgb), self.img_bw, decimal=2) def test_rgb_to_rgb(self): np.testing.assert_array_equal(fpp.to_rgb(self.img_rgb), self.img_rgb) def test_grayscale_to_grayscale(self): np.testing.assert_array_equal( fpp.to_grayscale(self.img_bw), self.img_bw) class Projection2DHelperfunctionsTests(unittest.TestCase): def test_rasterize_2d_coordinates_single_point_X1(self): a = np.array([[100., 0.]]) a_rast = fpp.rasterized_2d_coordinates(a, 10) nptest.assert_array_equal(a_rast, np.array([[10, 0]])) def test_rasterize_2d_coordinates_single_point_X2(self): a = np.array([[109.99, 0.]]) a_rast = fpp.rasterized_2d_coordinates(a, 10) nptest.assert_array_equal(a_rast, np.array([[10, 0]])) def test_rasterize_2d_coordinates_single_point_X3(self): a = np.array([[110., 0.]]) a_rast = fpp.rasterized_2d_coordinates(a, 10) nptest.assert_array_equal(a_rast, np.array([[11, 0]])) def test_rasterize_2d_coordinates_single_point_Y1(self): a = np.array([[0., 100.]]) a_rast = fpp.rasterized_2d_coordinates(a, 10) nptest.assert_array_equal(a_rast, np.array([[0, 10]])) def test_rasterize_2d_coordinates_single_point_Y2(self): a = np.array([[0., 109.99]]) a_rast = fpp.rasterized_2d_coordinates(a, 10) nptest.assert_array_equal(a_rast, np.array([[0, 10]])) def test_rasterize_2d_coordinates_single_point_Y3(self): a = np.array([[0., 110.]]) a_rast = fpp.rasterized_2d_coordinates(a, 10) nptest.assert_array_equal(a_rast, np.array([[0, 11]])) def test_rasterize_2d_coordinates_many_points(self): a = np.array([[100., 0.], [109.99, 0.], [110., 0.], [0., 100.], [0., 109.99], [0., 110.]]) a_rast = fpp.rasterized_2d_coordinates(a, 10) nptest.assert_array_equal(a_rast, np.array( [[10, 0], [10, 0], [11, 0], [0, 10], [0, 10], [0, 11]])) def test_rasterize_2d_coordinates_many_points_with_origin(self): a = np.array([[100., 0.], [109.99, 0.], [110., 0.], [0., 100.], [0., 109.99], [0., 110.]]) a_rast = fpp.rasterized_2d_coordinates(a, 10, np.array([-0.5, -25])) nptest.assert_array_equal(a_rast, np.array( [[10, 2], [11, 2], [11, 2], [0, 12], [0, 13], [0, 13]])) def test_rasterize_2d_coordinates_single_point_with_origin(self): a = np.array([[109.99, 0.]]) b = np.array([[0., 109.99]]) a_rast = fpp.rasterized_2d_coordinates(a, 10, np.array([-0.5, -25])) b_rast = fpp.rasterized_2d_coordinates(b, 10, np.array([-0.5, -25])) nptest.assert_array_equal(a_rast, np.array([[11, 2]])) nptest.assert_array_equal(b_rast, np.array([[0, 13]])) def test_rasterize_2d_coordinates_many_points_with_rotation(self): a = np.array([[100., 0.], [109.99, 0.], [110., 0.], [0., 100.], [0., 109.99], [0., 110.]]) a_rast = fpp.rasterized_2d_coordinates(a, 10, rotate=90) print(a_rast) nptest.assert_array_equal(a_rast, np.array( [[0, -10], [0, -11], [0, -11], [10, 0], [10, 0], [11, 0]])) def test_rasterize_2d_coordinates_many_points_with_rotation2(self): a = np.array([[100., 0.], [109.99, 0.], [110., 0.], [0., 100.], [0., 109.99], [0., 110.]]) a_rast = fpp.rasterized_2d_coordinates(a, 10, rotate=-90) print(a_rast) nptest.assert_array_equal(a_rast, np.array( [[0, 10], [0, 10], [0, 11], [-10, 0], [-11, 0], [-11, 0]])) def test_rasterize_2d_coordinates_many_points_with_rotation_and_origin(self): a = np.array([[100., 0.], [109.99, 0.], [110., 0.], [0., 100.], [0., 109.99], [0., 110.]]) a_rast = fpp.rasterized_2d_coordinates( a, 10, np.array([-0.5, -25]), rotate=-90) print(a_rast) nptest.assert_array_equal(a_rast, np.array( [[0, 12], [0, 13], [0, 13], [-10, 2], [-11, 2], [-11, 2]]))
gpl-3.0
pratapvardhan/pandas
doc/sphinxext/numpydoc/docscrape_sphinx.py
7
15301
from __future__ import division, absolute_import, print_function import sys import re import inspect import textwrap import pydoc import collections import os from jinja2 import FileSystemLoader from jinja2.sandbox import SandboxedEnvironment import sphinx from sphinx.jinja2glue import BuiltinTemplateLoader from .docscrape import NumpyDocString, FunctionDoc, ClassDoc if sys.version_info[0] >= 3: sixu = lambda s: s else: sixu = lambda s: unicode(s, 'unicode_escape') IMPORT_MATPLOTLIB_RE = r'\b(import +matplotlib|from +matplotlib +import)\b' class SphinxDocString(NumpyDocString): def __init__(self, docstring, config={}): NumpyDocString.__init__(self, docstring, config=config) self.load_config(config) def load_config(self, config): self.use_plots = config.get('use_plots', False) self.use_blockquotes = config.get('use_blockquotes', False) self.class_members_toctree = config.get('class_members_toctree', True) self.attributes_as_param_list = config.get('attributes_as_param_list', True) self.template = config.get('template', None) if self.template is None: template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')] template_loader = FileSystemLoader(template_dirs) template_env = SandboxedEnvironment(loader=template_loader) self.template = template_env.get_template('numpydoc_docstring.rst') # string conversion routines def _str_header(self, name, symbol='`'): return ['.. rubric:: ' + name, ''] def _str_field_list(self, name): return [':' + name + ':'] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): return [''] if self['Signature']: return ['``%s``' % self['Signature']] + [''] else: return [''] def _str_summary(self): return self['Summary'] + [''] def _str_extended_summary(self): return self['Extended Summary'] + [''] def _str_returns(self, name='Returns'): if self.use_blockquotes: typed_fmt = '**%s** : %s' untyped_fmt = '**%s**' else: typed_fmt = '%s : %s' untyped_fmt = '%s' out = [] if self[name]: out += self._str_field_list(name) out += [''] for param, param_type, desc in self[name]: if param_type: out += self._str_indent([typed_fmt % (param.strip(), param_type)]) else: out += self._str_indent([untyped_fmt % param.strip()]) if desc and self.use_blockquotes: out += [''] elif not desc: desc = ['..'] out += self._str_indent(desc, 8) out += [''] return out def _process_param(self, param, desc, fake_autosummary): """Determine how to display a parameter Emulates autosummary behavior if fake_autosummary Parameters ---------- param : str The name of the parameter desc : list of str The parameter description as given in the docstring. This is ignored when autosummary logic applies. fake_autosummary : bool If True, autosummary-style behaviour will apply for params that are attributes of the class and have a docstring. Returns ------- display_param : str The marked up parameter name for display. This may include a link to the corresponding attribute's own documentation. desc : list of str A list of description lines. This may be identical to the input ``desc``, if ``autosum is None`` or ``param`` is not a class attribute, or it will be a summary of the class attribute's docstring. Notes ----- This does not have the autosummary functionality to display a method's signature, and hence is not used to format methods. It may be complicated to incorporate autosummary's signature mangling, as it relies on Sphinx's plugin mechanism. """ param = param.strip() display_param = ('**%s**' if self.use_blockquotes else '%s') % param if not fake_autosummary: return display_param, desc param_obj = getattr(self._obj, param, None) if not (callable(param_obj) or isinstance(param_obj, property) or inspect.isgetsetdescriptor(param_obj)): param_obj = None obj_doc = pydoc.getdoc(param_obj) if not (param_obj and obj_doc): return display_param, desc prefix = getattr(self, '_name', '') if prefix: autosum_prefix = '~%s.' % prefix link_prefix = '%s.' % prefix else: autosum_prefix = '' link_prefix = '' # Referenced object has a docstring display_param = ':obj:`%s <%s%s>`' % (param, link_prefix, param) if obj_doc: # Overwrite desc. Take summary logic of autosummary desc = re.split('\n\s*\n', obj_doc.strip(), 1)[0] # XXX: Should this have DOTALL? # It does not in autosummary m = re.search(r"^([A-Z].*?\.)(?:\s|$)", ' '.join(desc.split())) if m: desc = m.group(1).strip() else: desc = desc.partition('\n')[0] desc = desc.split('\n') return display_param, desc def _str_param_list(self, name, fake_autosummary=False): """Generate RST for a listing of parameters or similar Parameter names are displayed as bold text, and descriptions are in blockquotes. Descriptions may therefore contain block markup as well. Parameters ---------- name : str Section name (e.g. Parameters) fake_autosummary : bool When True, the parameter names may correspond to attributes of the object beign documented, usually ``property`` instances on a class. In this case, names will be linked to fuller descriptions. Returns ------- rst : list of str """ out = [] if self[name]: out += self._str_field_list(name) out += [''] for param, param_type, desc in self[name]: display_param, desc = self._process_param(param, desc, fake_autosummary) if param_type: out += self._str_indent(['%s : %s' % (display_param, param_type)]) else: out += self._str_indent([display_param]) if desc and self.use_blockquotes: out += [''] elif not desc: # empty definition desc = ['..'] out += self._str_indent(desc, 8) out += [''] return out @property def _obj(self): if hasattr(self, '_cls'): return self._cls elif hasattr(self, '_f'): return self._f return None def _str_member_list(self, name): """ Generate a member listing, autosummary:: table where possible, and a table where not. """ out = [] if self[name]: out += ['.. rubric:: %s' % name, ''] prefix = getattr(self, '_name', '') if prefix: prefix = '~%s.' % prefix autosum = [] others = [] for param, param_type, desc in self[name]: param = param.strip() # Check if the referenced member can have a docstring or not param_obj = getattr(self._obj, param, None) if not (callable(param_obj) or isinstance(param_obj, property) or inspect.isdatadescriptor(param_obj)): param_obj = None if param_obj and pydoc.getdoc(param_obj): # Referenced object has a docstring autosum += [" %s%s" % (prefix, param)] else: others.append((param, param_type, desc)) if autosum: out += ['.. autosummary::'] if self.class_members_toctree: out += [' :toctree:'] out += [''] + autosum if others: maxlen_0 = max(3, max([len(x[0]) + 4 for x in others])) hdr = sixu("=") * maxlen_0 + sixu(" ") + sixu("=") * 10 fmt = sixu('%%%ds %%s ') % (maxlen_0,) out += ['', '', hdr] for param, param_type, desc in others: desc = sixu(" ").join(x.strip() for x in desc).strip() if param_type: desc = "(%s) %s" % (param_type, desc) out += [fmt % ("**" + param.strip() + "**", desc)] out += [hdr] out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) content = textwrap.dedent("\n".join(self[name])).split("\n") out += content out += [''] return out def _str_see_also(self, func_role): out = [] if self['See Also']: see_also = super(SphinxDocString, self)._str_see_also(func_role) out = ['.. seealso::', ''] out += self._str_indent(see_also[2:]) return out def _str_warnings(self): out = [] if self['Warnings']: out = ['.. warning::', ''] out += self._str_indent(self['Warnings']) out += [''] return out def _str_index(self): idx = self['index'] out = [] if len(idx) == 0: return out out += ['.. index:: %s' % idx.get('default', '')] for section, references in idx.items(): if section == 'default': continue elif section == 'refguide': out += [' single: %s' % (', '.join(references))] else: out += [' %s: %s' % (section, ','.join(references))] out += [''] return out def _str_references(self): out = [] if self['References']: out += self._str_header('References') if isinstance(self['References'], str): self['References'] = [self['References']] out.extend(self['References']) out += [''] # Latex collects all references to a separate bibliography, # so we need to insert links to it if sphinx.__version__ >= "0.6": out += ['.. only:: latex', ''] else: out += ['.. latexonly::', ''] items = [] for line in self['References']: m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I) if m: items.append(m.group(1)) out += [' ' + ", ".join(["[%s]_" % item for item in items]), ''] return out def _str_examples(self): examples_str = "\n".join(self['Examples']) if (self.use_plots and re.search(IMPORT_MATPLOTLIB_RE, examples_str) and 'plot::' not in examples_str): out = [] out += self._str_header('Examples') out += ['.. plot::', ''] out += self._str_indent(self['Examples']) out += [''] return out else: return self._str_section('Examples') def __str__(self, indent=0, func_role="obj"): ns = { 'signature': self._str_signature(), 'index': self._str_index(), 'summary': self._str_summary(), 'extended_summary': self._str_extended_summary(), 'parameters': self._str_param_list('Parameters'), 'returns': self._str_returns('Returns'), 'yields': self._str_returns('Yields'), 'other_parameters': self._str_param_list('Other Parameters'), 'raises': self._str_param_list('Raises'), 'warns': self._str_param_list('Warns'), 'warnings': self._str_warnings(), 'see_also': self._str_see_also(func_role), 'notes': self._str_section('Notes'), 'references': self._str_references(), 'examples': self._str_examples(), 'attributes': self._str_param_list('Attributes', fake_autosummary=True) if self.attributes_as_param_list else self._str_member_list('Attributes'), 'methods': self._str_member_list('Methods'), } ns = dict((k, '\n'.join(v)) for k, v in ns.items()) rendered = self.template.render(**ns) return '\n'.join(self._str_indent(rendered.split('\n'), indent)) class SphinxFunctionDoc(SphinxDocString, FunctionDoc): def __init__(self, obj, doc=None, config={}): self.load_config(config) FunctionDoc.__init__(self, obj, doc=doc, config=config) class SphinxClassDoc(SphinxDocString, ClassDoc): def __init__(self, obj, doc=None, func_doc=None, config={}): self.load_config(config) ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config) class SphinxObjDoc(SphinxDocString): def __init__(self, obj, doc=None, config={}): self._f = obj self.load_config(config) SphinxDocString.__init__(self, doc, config=config) def get_doc_object(obj, what=None, doc=None, config={}, builder=None): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif isinstance(obj, collections.Callable): what = 'function' else: what = 'object' template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')] if builder is not None: template_loader = BuiltinTemplateLoader() template_loader.init(builder, dirs=template_dirs) else: template_loader = FileSystemLoader(template_dirs) template_env = SandboxedEnvironment(loader=template_loader) config['template'] = template_env.get_template('numpydoc_docstring.rst') if what == 'class': return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc, config=config) elif what in ('function', 'method'): return SphinxFunctionDoc(obj, doc=doc, config=config) else: if doc is None: doc = pydoc.getdoc(obj) return SphinxObjDoc(obj, doc, config=config)
bsd-3-clause
xzh86/scikit-learn
sklearn/feature_extraction/tests/test_text.py
110
34127
from __future__ import unicode_literals import warnings from sklearn.feature_extraction.text import strip_tags from sklearn.feature_extraction.text import strip_accents_unicode from sklearn.feature_extraction.text import strip_accents_ascii from sklearn.feature_extraction.text import HashingVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS from sklearn.cross_validation import train_test_split from sklearn.cross_validation import cross_val_score from sklearn.grid_search import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.svm import LinearSVC from sklearn.base import clone import numpy as np from nose import SkipTest from nose.tools import assert_equal from nose.tools import assert_false from nose.tools import assert_not_equal from nose.tools import assert_true from nose.tools import assert_almost_equal from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_equal from numpy.testing import assert_raises from sklearn.utils.testing import (assert_in, assert_less, assert_greater, assert_warns_message, assert_raise_message, clean_warning_registry) from collections import defaultdict, Mapping from functools import partial import pickle from io import StringIO JUNK_FOOD_DOCS = ( "the pizza pizza beer copyright", "the pizza burger beer copyright", "the the pizza beer beer copyright", "the burger beer beer copyright", "the coke burger coke copyright", "the coke burger burger", ) NOTJUNK_FOOD_DOCS = ( "the salad celeri copyright", "the salad salad sparkling water copyright", "the the celeri celeri copyright", "the tomato tomato salad water", "the tomato salad water copyright", ) ALL_FOOD_DOCS = JUNK_FOOD_DOCS + NOTJUNK_FOOD_DOCS def uppercase(s): return strip_accents_unicode(s).upper() def strip_eacute(s): return s.replace('\xe9', 'e') def split_tokenize(s): return s.split() def lazy_analyze(s): return ['the_ultimate_feature'] def test_strip_accents(): # check some classical latin accentuated symbols a = '\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9\xea\xeb' expected = 'aaaaaaceeee' assert_equal(strip_accents_unicode(a), expected) a = '\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf9\xfa\xfb\xfc\xfd' expected = 'iiiinooooouuuuy' assert_equal(strip_accents_unicode(a), expected) # check some arabic a = '\u0625' # halef with a hamza below expected = '\u0627' # simple halef assert_equal(strip_accents_unicode(a), expected) # mix letters accentuated and not a = "this is \xe0 test" expected = 'this is a test' assert_equal(strip_accents_unicode(a), expected) def test_to_ascii(): # check some classical latin accentuated symbols a = '\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9\xea\xeb' expected = 'aaaaaaceeee' assert_equal(strip_accents_ascii(a), expected) a = '\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf9\xfa\xfb\xfc\xfd' expected = 'iiiinooooouuuuy' assert_equal(strip_accents_ascii(a), expected) # check some arabic a = '\u0625' # halef with a hamza below expected = '' # halef has no direct ascii match assert_equal(strip_accents_ascii(a), expected) # mix letters accentuated and not a = "this is \xe0 test" expected = 'this is a test' assert_equal(strip_accents_ascii(a), expected) def test_word_analyzer_unigrams(): for Vectorizer in (CountVectorizer, HashingVectorizer): wa = Vectorizer(strip_accents='ascii').build_analyzer() text = ("J'ai mang\xe9 du kangourou ce midi, " "c'\xe9tait pas tr\xeas bon.") expected = ['ai', 'mange', 'du', 'kangourou', 'ce', 'midi', 'etait', 'pas', 'tres', 'bon'] assert_equal(wa(text), expected) text = "This is a test, really.\n\n I met Harry yesterday." expected = ['this', 'is', 'test', 'really', 'met', 'harry', 'yesterday'] assert_equal(wa(text), expected) wa = Vectorizer(input='file').build_analyzer() text = StringIO("This is a test with a file-like object!") expected = ['this', 'is', 'test', 'with', 'file', 'like', 'object'] assert_equal(wa(text), expected) # with custom preprocessor wa = Vectorizer(preprocessor=uppercase).build_analyzer() text = ("J'ai mang\xe9 du kangourou ce midi, " " c'\xe9tait pas tr\xeas bon.") expected = ['AI', 'MANGE', 'DU', 'KANGOUROU', 'CE', 'MIDI', 'ETAIT', 'PAS', 'TRES', 'BON'] assert_equal(wa(text), expected) # with custom tokenizer wa = Vectorizer(tokenizer=split_tokenize, strip_accents='ascii').build_analyzer() text = ("J'ai mang\xe9 du kangourou ce midi, " "c'\xe9tait pas tr\xeas bon.") expected = ["j'ai", 'mange', 'du', 'kangourou', 'ce', 'midi,', "c'etait", 'pas', 'tres', 'bon.'] assert_equal(wa(text), expected) def test_word_analyzer_unigrams_and_bigrams(): wa = CountVectorizer(analyzer="word", strip_accents='unicode', ngram_range=(1, 2)).build_analyzer() text = "J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon." expected = ['ai', 'mange', 'du', 'kangourou', 'ce', 'midi', 'etait', 'pas', 'tres', 'bon', 'ai mange', 'mange du', 'du kangourou', 'kangourou ce', 'ce midi', 'midi etait', 'etait pas', 'pas tres', 'tres bon'] assert_equal(wa(text), expected) def test_unicode_decode_error(): # decode_error default to strict, so this should fail # First, encode (as bytes) a unicode string. text = "J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon." text_bytes = text.encode('utf-8') # Then let the Analyzer try to decode it as ascii. It should fail, # because we have given it an incorrect encoding. wa = CountVectorizer(ngram_range=(1, 2), encoding='ascii').build_analyzer() assert_raises(UnicodeDecodeError, wa, text_bytes) ca = CountVectorizer(analyzer='char', ngram_range=(3, 6), encoding='ascii').build_analyzer() assert_raises(UnicodeDecodeError, ca, text_bytes) def test_char_ngram_analyzer(): cnga = CountVectorizer(analyzer='char', strip_accents='unicode', ngram_range=(3, 6)).build_analyzer() text = "J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon" expected = ["j'a", "'ai", 'ai ', 'i m', ' ma'] assert_equal(cnga(text)[:5], expected) expected = ['s tres', ' tres ', 'tres b', 'res bo', 'es bon'] assert_equal(cnga(text)[-5:], expected) text = "This \n\tis a test, really.\n\n I met Harry yesterday" expected = ['thi', 'his', 'is ', 's i', ' is'] assert_equal(cnga(text)[:5], expected) expected = [' yeste', 'yester', 'esterd', 'sterda', 'terday'] assert_equal(cnga(text)[-5:], expected) cnga = CountVectorizer(input='file', analyzer='char', ngram_range=(3, 6)).build_analyzer() text = StringIO("This is a test with a file-like object!") expected = ['thi', 'his', 'is ', 's i', ' is'] assert_equal(cnga(text)[:5], expected) def test_char_wb_ngram_analyzer(): cnga = CountVectorizer(analyzer='char_wb', strip_accents='unicode', ngram_range=(3, 6)).build_analyzer() text = "This \n\tis a test, really.\n\n I met Harry yesterday" expected = [' th', 'thi', 'his', 'is ', ' thi'] assert_equal(cnga(text)[:5], expected) expected = ['yester', 'esterd', 'sterda', 'terday', 'erday '] assert_equal(cnga(text)[-5:], expected) cnga = CountVectorizer(input='file', analyzer='char_wb', ngram_range=(3, 6)).build_analyzer() text = StringIO("A test with a file-like object!") expected = [' a ', ' te', 'tes', 'est', 'st ', ' tes'] assert_equal(cnga(text)[:6], expected) def test_countvectorizer_custom_vocabulary(): vocab = {"pizza": 0, "beer": 1} terms = set(vocab.keys()) # Try a few of the supported types. for typ in [dict, list, iter, partial(defaultdict, int)]: v = typ(vocab) vect = CountVectorizer(vocabulary=v) vect.fit(JUNK_FOOD_DOCS) if isinstance(v, Mapping): assert_equal(vect.vocabulary_, vocab) else: assert_equal(set(vect.vocabulary_), terms) X = vect.transform(JUNK_FOOD_DOCS) assert_equal(X.shape[1], len(terms)) def test_countvectorizer_custom_vocabulary_pipeline(): what_we_like = ["pizza", "beer"] pipe = Pipeline([ ('count', CountVectorizer(vocabulary=what_we_like)), ('tfidf', TfidfTransformer())]) X = pipe.fit_transform(ALL_FOOD_DOCS) assert_equal(set(pipe.named_steps['count'].vocabulary_), set(what_we_like)) assert_equal(X.shape[1], len(what_we_like)) def test_countvectorizer_custom_vocabulary_repeated_indeces(): vocab = {"pizza": 0, "beer": 0} try: CountVectorizer(vocabulary=vocab) except ValueError as e: assert_in("vocabulary contains repeated indices", str(e).lower()) def test_countvectorizer_custom_vocabulary_gap_index(): vocab = {"pizza": 1, "beer": 2} try: CountVectorizer(vocabulary=vocab) except ValueError as e: assert_in("doesn't contain index", str(e).lower()) def test_countvectorizer_stop_words(): cv = CountVectorizer() cv.set_params(stop_words='english') assert_equal(cv.get_stop_words(), ENGLISH_STOP_WORDS) cv.set_params(stop_words='_bad_str_stop_') assert_raises(ValueError, cv.get_stop_words) cv.set_params(stop_words='_bad_unicode_stop_') assert_raises(ValueError, cv.get_stop_words) stoplist = ['some', 'other', 'words'] cv.set_params(stop_words=stoplist) assert_equal(cv.get_stop_words(), set(stoplist)) def test_countvectorizer_empty_vocabulary(): try: vect = CountVectorizer(vocabulary=[]) vect.fit(["foo"]) assert False, "we shouldn't get here" except ValueError as e: assert_in("empty vocabulary", str(e).lower()) try: v = CountVectorizer(max_df=1.0, stop_words="english") # fit on stopwords only v.fit(["to be or not to be", "and me too", "and so do you"]) assert False, "we shouldn't get here" except ValueError as e: assert_in("empty vocabulary", str(e).lower()) def test_fit_countvectorizer_twice(): cv = CountVectorizer() X1 = cv.fit_transform(ALL_FOOD_DOCS[:5]) X2 = cv.fit_transform(ALL_FOOD_DOCS[5:]) assert_not_equal(X1.shape[1], X2.shape[1]) def test_tf_idf_smoothing(): X = [[1, 1, 1], [1, 1, 0], [1, 0, 0]] tr = TfidfTransformer(smooth_idf=True, norm='l2') tfidf = tr.fit_transform(X).toarray() assert_true((tfidf >= 0).all()) # check normalization assert_array_almost_equal((tfidf ** 2).sum(axis=1), [1., 1., 1.]) # this is robust to features with only zeros X = [[1, 1, 0], [1, 1, 0], [1, 0, 0]] tr = TfidfTransformer(smooth_idf=True, norm='l2') tfidf = tr.fit_transform(X).toarray() assert_true((tfidf >= 0).all()) def test_tfidf_no_smoothing(): X = [[1, 1, 1], [1, 1, 0], [1, 0, 0]] tr = TfidfTransformer(smooth_idf=False, norm='l2') tfidf = tr.fit_transform(X).toarray() assert_true((tfidf >= 0).all()) # check normalization assert_array_almost_equal((tfidf ** 2).sum(axis=1), [1., 1., 1.]) # the lack of smoothing make IDF fragile in the presence of feature with # only zeros X = [[1, 1, 0], [1, 1, 0], [1, 0, 0]] tr = TfidfTransformer(smooth_idf=False, norm='l2') clean_warning_registry() with warnings.catch_warnings(record=True) as w: 1. / np.array([0.]) numpy_provides_div0_warning = len(w) == 1 in_warning_message = 'divide by zero' tfidf = assert_warns_message(RuntimeWarning, in_warning_message, tr.fit_transform, X).toarray() if not numpy_provides_div0_warning: raise SkipTest("Numpy does not provide div 0 warnings.") def test_sublinear_tf(): X = [[1], [2], [3]] tr = TfidfTransformer(sublinear_tf=True, use_idf=False, norm=None) tfidf = tr.fit_transform(X).toarray() assert_equal(tfidf[0], 1) assert_greater(tfidf[1], tfidf[0]) assert_greater(tfidf[2], tfidf[1]) assert_less(tfidf[1], 2) assert_less(tfidf[2], 3) def test_vectorizer(): # raw documents as an iterator train_data = iter(ALL_FOOD_DOCS[:-1]) test_data = [ALL_FOOD_DOCS[-1]] n_train = len(ALL_FOOD_DOCS) - 1 # test without vocabulary v1 = CountVectorizer(max_df=0.5) counts_train = v1.fit_transform(train_data) if hasattr(counts_train, 'tocsr'): counts_train = counts_train.tocsr() assert_equal(counts_train[0, v1.vocabulary_["pizza"]], 2) # build a vectorizer v1 with the same vocabulary as the one fitted by v1 v2 = CountVectorizer(vocabulary=v1.vocabulary_) # compare that the two vectorizer give the same output on the test sample for v in (v1, v2): counts_test = v.transform(test_data) if hasattr(counts_test, 'tocsr'): counts_test = counts_test.tocsr() vocabulary = v.vocabulary_ assert_equal(counts_test[0, vocabulary["salad"]], 1) assert_equal(counts_test[0, vocabulary["tomato"]], 1) assert_equal(counts_test[0, vocabulary["water"]], 1) # stop word from the fixed list assert_false("the" in vocabulary) # stop word found automatically by the vectorizer DF thresholding # words that are high frequent across the complete corpus are likely # to be not informative (either real stop words of extraction # artifacts) assert_false("copyright" in vocabulary) # not present in the sample assert_equal(counts_test[0, vocabulary["coke"]], 0) assert_equal(counts_test[0, vocabulary["burger"]], 0) assert_equal(counts_test[0, vocabulary["beer"]], 0) assert_equal(counts_test[0, vocabulary["pizza"]], 0) # test tf-idf t1 = TfidfTransformer(norm='l1') tfidf = t1.fit(counts_train).transform(counts_train).toarray() assert_equal(len(t1.idf_), len(v1.vocabulary_)) assert_equal(tfidf.shape, (n_train, len(v1.vocabulary_))) # test tf-idf with new data tfidf_test = t1.transform(counts_test).toarray() assert_equal(tfidf_test.shape, (len(test_data), len(v1.vocabulary_))) # test tf alone t2 = TfidfTransformer(norm='l1', use_idf=False) tf = t2.fit(counts_train).transform(counts_train).toarray() assert_equal(t2.idf_, None) # test idf transform with unlearned idf vector t3 = TfidfTransformer(use_idf=True) assert_raises(ValueError, t3.transform, counts_train) # test idf transform with incompatible n_features X = [[1, 1, 5], [1, 1, 0]] t3.fit(X) X_incompt = [[1, 3], [1, 3]] assert_raises(ValueError, t3.transform, X_incompt) # L1-normalized term frequencies sum to one assert_array_almost_equal(np.sum(tf, axis=1), [1.0] * n_train) # test the direct tfidf vectorizer # (equivalent to term count vectorizer + tfidf transformer) train_data = iter(ALL_FOOD_DOCS[:-1]) tv = TfidfVectorizer(norm='l1') tv.max_df = v1.max_df tfidf2 = tv.fit_transform(train_data).toarray() assert_false(tv.fixed_vocabulary_) assert_array_almost_equal(tfidf, tfidf2) # test the direct tfidf vectorizer with new data tfidf_test2 = tv.transform(test_data).toarray() assert_array_almost_equal(tfidf_test, tfidf_test2) # test transform on unfitted vectorizer with empty vocabulary v3 = CountVectorizer(vocabulary=None) assert_raises(ValueError, v3.transform, train_data) # ascii preprocessor? v3.set_params(strip_accents='ascii', lowercase=False) assert_equal(v3.build_preprocessor(), strip_accents_ascii) # error on bad strip_accents param v3.set_params(strip_accents='_gabbledegook_', preprocessor=None) assert_raises(ValueError, v3.build_preprocessor) # error with bad analyzer type v3.set_params = '_invalid_analyzer_type_' assert_raises(ValueError, v3.build_analyzer) def test_tfidf_vectorizer_setters(): tv = TfidfVectorizer(norm='l2', use_idf=False, smooth_idf=False, sublinear_tf=False) tv.norm = 'l1' assert_equal(tv._tfidf.norm, 'l1') tv.use_idf = True assert_true(tv._tfidf.use_idf) tv.smooth_idf = True assert_true(tv._tfidf.smooth_idf) tv.sublinear_tf = True assert_true(tv._tfidf.sublinear_tf) def test_hashing_vectorizer(): v = HashingVectorizer() X = v.transform(ALL_FOOD_DOCS) token_nnz = X.nnz assert_equal(X.shape, (len(ALL_FOOD_DOCS), v.n_features)) assert_equal(X.dtype, v.dtype) # By default the hashed values receive a random sign and l2 normalization # makes the feature values bounded assert_true(np.min(X.data) > -1) assert_true(np.min(X.data) < 0) assert_true(np.max(X.data) > 0) assert_true(np.max(X.data) < 1) # Check that the rows are normalized for i in range(X.shape[0]): assert_almost_equal(np.linalg.norm(X[0].data, 2), 1.0) # Check vectorization with some non-default parameters v = HashingVectorizer(ngram_range=(1, 2), non_negative=True, norm='l1') X = v.transform(ALL_FOOD_DOCS) assert_equal(X.shape, (len(ALL_FOOD_DOCS), v.n_features)) assert_equal(X.dtype, v.dtype) # ngrams generate more non zeros ngrams_nnz = X.nnz assert_true(ngrams_nnz > token_nnz) assert_true(ngrams_nnz < 2 * token_nnz) # makes the feature values bounded assert_true(np.min(X.data) > 0) assert_true(np.max(X.data) < 1) # Check that the rows are normalized for i in range(X.shape[0]): assert_almost_equal(np.linalg.norm(X[0].data, 1), 1.0) def test_feature_names(): cv = CountVectorizer(max_df=0.5) # test for Value error on unfitted/empty vocabulary assert_raises(ValueError, cv.get_feature_names) X = cv.fit_transform(ALL_FOOD_DOCS) n_samples, n_features = X.shape assert_equal(len(cv.vocabulary_), n_features) feature_names = cv.get_feature_names() assert_equal(len(feature_names), n_features) assert_array_equal(['beer', 'burger', 'celeri', 'coke', 'pizza', 'salad', 'sparkling', 'tomato', 'water'], feature_names) for idx, name in enumerate(feature_names): assert_equal(idx, cv.vocabulary_.get(name)) def test_vectorizer_max_features(): vec_factories = ( CountVectorizer, TfidfVectorizer, ) expected_vocabulary = set(['burger', 'beer', 'salad', 'pizza']) expected_stop_words = set([u'celeri', u'tomato', u'copyright', u'coke', u'sparkling', u'water', u'the']) for vec_factory in vec_factories: # test bounded number of extracted features vectorizer = vec_factory(max_df=0.6, max_features=4) vectorizer.fit(ALL_FOOD_DOCS) assert_equal(set(vectorizer.vocabulary_), expected_vocabulary) assert_equal(vectorizer.stop_words_, expected_stop_words) def test_count_vectorizer_max_features(): # Regression test: max_features didn't work correctly in 0.14. cv_1 = CountVectorizer(max_features=1) cv_3 = CountVectorizer(max_features=3) cv_None = CountVectorizer(max_features=None) counts_1 = cv_1.fit_transform(JUNK_FOOD_DOCS).sum(axis=0) counts_3 = cv_3.fit_transform(JUNK_FOOD_DOCS).sum(axis=0) counts_None = cv_None.fit_transform(JUNK_FOOD_DOCS).sum(axis=0) features_1 = cv_1.get_feature_names() features_3 = cv_3.get_feature_names() features_None = cv_None.get_feature_names() # The most common feature is "the", with frequency 7. assert_equal(7, counts_1.max()) assert_equal(7, counts_3.max()) assert_equal(7, counts_None.max()) # The most common feature should be the same assert_equal("the", features_1[np.argmax(counts_1)]) assert_equal("the", features_3[np.argmax(counts_3)]) assert_equal("the", features_None[np.argmax(counts_None)]) def test_vectorizer_max_df(): test_data = ['abc', 'dea', 'eat'] vect = CountVectorizer(analyzer='char', max_df=1.0) vect.fit(test_data) assert_true('a' in vect.vocabulary_.keys()) assert_equal(len(vect.vocabulary_.keys()), 6) assert_equal(len(vect.stop_words_), 0) vect.max_df = 0.5 # 0.5 * 3 documents -> max_doc_count == 1.5 vect.fit(test_data) assert_true('a' not in vect.vocabulary_.keys()) # {ae} ignored assert_equal(len(vect.vocabulary_.keys()), 4) # {bcdt} remain assert_true('a' in vect.stop_words_) assert_equal(len(vect.stop_words_), 2) vect.max_df = 1 vect.fit(test_data) assert_true('a' not in vect.vocabulary_.keys()) # {ae} ignored assert_equal(len(vect.vocabulary_.keys()), 4) # {bcdt} remain assert_true('a' in vect.stop_words_) assert_equal(len(vect.stop_words_), 2) def test_vectorizer_min_df(): test_data = ['abc', 'dea', 'eat'] vect = CountVectorizer(analyzer='char', min_df=1) vect.fit(test_data) assert_true('a' in vect.vocabulary_.keys()) assert_equal(len(vect.vocabulary_.keys()), 6) assert_equal(len(vect.stop_words_), 0) vect.min_df = 2 vect.fit(test_data) assert_true('c' not in vect.vocabulary_.keys()) # {bcdt} ignored assert_equal(len(vect.vocabulary_.keys()), 2) # {ae} remain assert_true('c' in vect.stop_words_) assert_equal(len(vect.stop_words_), 4) vect.min_df = 0.8 # 0.8 * 3 documents -> min_doc_count == 2.4 vect.fit(test_data) assert_true('c' not in vect.vocabulary_.keys()) # {bcdet} ignored assert_equal(len(vect.vocabulary_.keys()), 1) # {a} remains assert_true('c' in vect.stop_words_) assert_equal(len(vect.stop_words_), 5) def test_count_binary_occurrences(): # by default multiple occurrences are counted as longs test_data = ['aaabc', 'abbde'] vect = CountVectorizer(analyzer='char', max_df=1.0) X = vect.fit_transform(test_data).toarray() assert_array_equal(['a', 'b', 'c', 'd', 'e'], vect.get_feature_names()) assert_array_equal([[3, 1, 1, 0, 0], [1, 2, 0, 1, 1]], X) # using boolean features, we can fetch the binary occurrence info # instead. vect = CountVectorizer(analyzer='char', max_df=1.0, binary=True) X = vect.fit_transform(test_data).toarray() assert_array_equal([[1, 1, 1, 0, 0], [1, 1, 0, 1, 1]], X) # check the ability to change the dtype vect = CountVectorizer(analyzer='char', max_df=1.0, binary=True, dtype=np.float32) X_sparse = vect.fit_transform(test_data) assert_equal(X_sparse.dtype, np.float32) def test_hashed_binary_occurrences(): # by default multiple occurrences are counted as longs test_data = ['aaabc', 'abbde'] vect = HashingVectorizer(analyzer='char', non_negative=True, norm=None) X = vect.transform(test_data) assert_equal(np.max(X[0:1].data), 3) assert_equal(np.max(X[1:2].data), 2) assert_equal(X.dtype, np.float64) # using boolean features, we can fetch the binary occurrence info # instead. vect = HashingVectorizer(analyzer='char', non_negative=True, binary=True, norm=None) X = vect.transform(test_data) assert_equal(np.max(X.data), 1) assert_equal(X.dtype, np.float64) # check the ability to change the dtype vect = HashingVectorizer(analyzer='char', non_negative=True, binary=True, norm=None, dtype=np.float64) X = vect.transform(test_data) assert_equal(X.dtype, np.float64) def test_vectorizer_inverse_transform(): # raw documents data = ALL_FOOD_DOCS for vectorizer in (TfidfVectorizer(), CountVectorizer()): transformed_data = vectorizer.fit_transform(data) inversed_data = vectorizer.inverse_transform(transformed_data) analyze = vectorizer.build_analyzer() for doc, inversed_terms in zip(data, inversed_data): terms = np.sort(np.unique(analyze(doc))) inversed_terms = np.sort(np.unique(inversed_terms)) assert_array_equal(terms, inversed_terms) # Test that inverse_transform also works with numpy arrays transformed_data = transformed_data.toarray() inversed_data2 = vectorizer.inverse_transform(transformed_data) for terms, terms2 in zip(inversed_data, inversed_data2): assert_array_equal(np.sort(terms), np.sort(terms2)) def test_count_vectorizer_pipeline_grid_selection(): # raw documents data = JUNK_FOOD_DOCS + NOTJUNK_FOOD_DOCS # label junk food as -1, the others as +1 target = [-1] * len(JUNK_FOOD_DOCS) + [1] * len(NOTJUNK_FOOD_DOCS) # split the dataset for model development and final evaluation train_data, test_data, target_train, target_test = train_test_split( data, target, test_size=.2, random_state=0) pipeline = Pipeline([('vect', CountVectorizer()), ('svc', LinearSVC())]) parameters = { 'vect__ngram_range': [(1, 1), (1, 2)], 'svc__loss': ('hinge', 'squared_hinge') } # find the best parameters for both the feature extraction and the # classifier grid_search = GridSearchCV(pipeline, parameters, n_jobs=1) # Check that the best model found by grid search is 100% correct on the # held out evaluation set. pred = grid_search.fit(train_data, target_train).predict(test_data) assert_array_equal(pred, target_test) # on this toy dataset bigram representation which is used in the last of # the grid_search is considered the best estimator since they all converge # to 100% accuracy models assert_equal(grid_search.best_score_, 1.0) best_vectorizer = grid_search.best_estimator_.named_steps['vect'] assert_equal(best_vectorizer.ngram_range, (1, 1)) def test_vectorizer_pipeline_grid_selection(): # raw documents data = JUNK_FOOD_DOCS + NOTJUNK_FOOD_DOCS # label junk food as -1, the others as +1 target = [-1] * len(JUNK_FOOD_DOCS) + [1] * len(NOTJUNK_FOOD_DOCS) # split the dataset for model development and final evaluation train_data, test_data, target_train, target_test = train_test_split( data, target, test_size=.1, random_state=0) pipeline = Pipeline([('vect', TfidfVectorizer()), ('svc', LinearSVC())]) parameters = { 'vect__ngram_range': [(1, 1), (1, 2)], 'vect__norm': ('l1', 'l2'), 'svc__loss': ('hinge', 'squared_hinge'), } # find the best parameters for both the feature extraction and the # classifier grid_search = GridSearchCV(pipeline, parameters, n_jobs=1) # Check that the best model found by grid search is 100% correct on the # held out evaluation set. pred = grid_search.fit(train_data, target_train).predict(test_data) assert_array_equal(pred, target_test) # on this toy dataset bigram representation which is used in the last of # the grid_search is considered the best estimator since they all converge # to 100% accuracy models assert_equal(grid_search.best_score_, 1.0) best_vectorizer = grid_search.best_estimator_.named_steps['vect'] assert_equal(best_vectorizer.ngram_range, (1, 1)) assert_equal(best_vectorizer.norm, 'l2') assert_false(best_vectorizer.fixed_vocabulary_) def test_vectorizer_pipeline_cross_validation(): # raw documents data = JUNK_FOOD_DOCS + NOTJUNK_FOOD_DOCS # label junk food as -1, the others as +1 target = [-1] * len(JUNK_FOOD_DOCS) + [1] * len(NOTJUNK_FOOD_DOCS) pipeline = Pipeline([('vect', TfidfVectorizer()), ('svc', LinearSVC())]) cv_scores = cross_val_score(pipeline, data, target, cv=3) assert_array_equal(cv_scores, [1., 1., 1.]) def test_vectorizer_unicode(): # tests that the count vectorizer works with cyrillic. document = ( "\xd0\x9c\xd0\xb0\xd1\x88\xd0\xb8\xd0\xbd\xd0\xbd\xd0\xbe\xd0" "\xb5 \xd0\xbe\xd0\xb1\xd1\x83\xd1\x87\xd0\xb5\xd0\xbd\xd0\xb8\xd0" "\xb5 \xe2\x80\x94 \xd0\xbe\xd0\xb1\xd1\x88\xd0\xb8\xd1\x80\xd0\xbd" "\xd1\x8b\xd0\xb9 \xd0\xbf\xd0\xbe\xd0\xb4\xd1\x80\xd0\xb0\xd0\xb7" "\xd0\xb4\xd0\xb5\xd0\xbb \xd0\xb8\xd1\x81\xd0\xba\xd1\x83\xd1\x81" "\xd1\x81\xd1\x82\xd0\xb2\xd0\xb5\xd0\xbd\xd0\xbd\xd0\xbe\xd0\xb3" "\xd0\xbe \xd0\xb8\xd0\xbd\xd1\x82\xd0\xb5\xd0\xbb\xd0\xbb\xd0" "\xb5\xd0\xba\xd1\x82\xd0\xb0, \xd0\xb8\xd0\xb7\xd1\x83\xd1\x87" "\xd0\xb0\xd1\x8e\xd1\x89\xd0\xb8\xd0\xb9 \xd0\xbc\xd0\xb5\xd1\x82" "\xd0\xbe\xd0\xb4\xd1\x8b \xd0\xbf\xd0\xbe\xd1\x81\xd1\x82\xd1\x80" "\xd0\xbe\xd0\xb5\xd0\xbd\xd0\xb8\xd1\x8f \xd0\xb0\xd0\xbb\xd0\xb3" "\xd0\xbe\xd1\x80\xd0\xb8\xd1\x82\xd0\xbc\xd0\xbe\xd0\xb2, \xd1\x81" "\xd0\xbf\xd0\xbe\xd1\x81\xd0\xbe\xd0\xb1\xd0\xbd\xd1\x8b\xd1\x85 " "\xd0\xbe\xd0\xb1\xd1\x83\xd1\x87\xd0\xb0\xd1\x82\xd1\x8c\xd1\x81\xd1" "\x8f.") vect = CountVectorizer() X_counted = vect.fit_transform([document]) assert_equal(X_counted.shape, (1, 15)) vect = HashingVectorizer(norm=None, non_negative=True) X_hashed = vect.transform([document]) assert_equal(X_hashed.shape, (1, 2 ** 20)) # No collisions on such a small dataset assert_equal(X_counted.nnz, X_hashed.nnz) # When norm is None and non_negative, the tokens are counted up to # collisions assert_array_equal(np.sort(X_counted.data), np.sort(X_hashed.data)) def test_tfidf_vectorizer_with_fixed_vocabulary(): # non regression smoke test for inheritance issues vocabulary = ['pizza', 'celeri'] vect = TfidfVectorizer(vocabulary=vocabulary) X_1 = vect.fit_transform(ALL_FOOD_DOCS) X_2 = vect.transform(ALL_FOOD_DOCS) assert_array_almost_equal(X_1.toarray(), X_2.toarray()) assert_true(vect.fixed_vocabulary_) def test_pickling_vectorizer(): instances = [ HashingVectorizer(), HashingVectorizer(norm='l1'), HashingVectorizer(binary=True), HashingVectorizer(ngram_range=(1, 2)), CountVectorizer(), CountVectorizer(preprocessor=strip_tags), CountVectorizer(analyzer=lazy_analyze), CountVectorizer(preprocessor=strip_tags).fit(JUNK_FOOD_DOCS), CountVectorizer(strip_accents=strip_eacute).fit(JUNK_FOOD_DOCS), TfidfVectorizer(), TfidfVectorizer(analyzer=lazy_analyze), TfidfVectorizer().fit(JUNK_FOOD_DOCS), ] for orig in instances: s = pickle.dumps(orig) copy = pickle.loads(s) assert_equal(type(copy), orig.__class__) assert_equal(copy.get_params(), orig.get_params()) assert_array_equal( copy.fit_transform(JUNK_FOOD_DOCS).toarray(), orig.fit_transform(JUNK_FOOD_DOCS).toarray()) def test_stop_words_removal(): # Ensure that deleting the stop_words_ attribute doesn't affect transform fitted_vectorizers = ( TfidfVectorizer().fit(JUNK_FOOD_DOCS), CountVectorizer(preprocessor=strip_tags).fit(JUNK_FOOD_DOCS), CountVectorizer(strip_accents=strip_eacute).fit(JUNK_FOOD_DOCS) ) for vect in fitted_vectorizers: vect_transform = vect.transform(JUNK_FOOD_DOCS).toarray() vect.stop_words_ = None stop_None_transform = vect.transform(JUNK_FOOD_DOCS).toarray() delattr(vect, 'stop_words_') stop_del_transform = vect.transform(JUNK_FOOD_DOCS).toarray() assert_array_equal(stop_None_transform, vect_transform) assert_array_equal(stop_del_transform, vect_transform) def test_pickling_transformer(): X = CountVectorizer().fit_transform(JUNK_FOOD_DOCS) orig = TfidfTransformer().fit(X) s = pickle.dumps(orig) copy = pickle.loads(s) assert_equal(type(copy), orig.__class__) assert_array_equal( copy.fit_transform(X).toarray(), orig.fit_transform(X).toarray()) def test_non_unique_vocab(): vocab = ['a', 'b', 'c', 'a', 'a'] vect = CountVectorizer(vocabulary=vocab) assert_raises(ValueError, vect.fit, []) def test_hashingvectorizer_nan_in_docs(): # np.nan can appear when using pandas to load text fields from a csv file # with missing values. message = "np.nan is an invalid document, expected byte or unicode string." exception = ValueError def func(): hv = HashingVectorizer() hv.fit_transform(['hello world', np.nan, 'hello hello']) assert_raise_message(exception, message, func) def test_tfidfvectorizer_binary(): # Non-regression test: TfidfVectorizer used to ignore its "binary" param. v = TfidfVectorizer(binary=True, use_idf=False, norm=None) assert_true(v.binary) X = v.fit_transform(['hello world', 'hello hello']).toarray() assert_array_equal(X.ravel(), [1, 1, 1, 0]) X2 = v.transform(['hello world', 'hello hello']).toarray() assert_array_equal(X2.ravel(), [1, 1, 1, 0]) def test_tfidfvectorizer_export_idf(): vect = TfidfVectorizer(use_idf=True) vect.fit(JUNK_FOOD_DOCS) assert_array_almost_equal(vect.idf_, vect._tfidf.idf_) def test_vectorizer_vocab_clone(): vect_vocab = TfidfVectorizer(vocabulary=["the"]) vect_vocab_clone = clone(vect_vocab) vect_vocab.fit(ALL_FOOD_DOCS) vect_vocab_clone.fit(ALL_FOOD_DOCS) assert_equal(vect_vocab_clone.vocabulary_, vect_vocab.vocabulary_)
bsd-3-clause
lepmik/nest-simulator
pynest/examples/intrinsic_currents_spiking.py
13
5954
# -*- coding: utf-8 -*- # # intrinsic_currents_spiking.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # NEST is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <http://www.gnu.org/licenses/>. # ''' Intrinsic currents spiking -------------------------- This example illustrates a neuron receiving spiking input through several different receptors (AMPA, NMDA, GABA_A, GABA_B), provoking spike output. The model, `ht_neuron`, also has intrinsic currents (I_NaP, I_KNa, I_T, and I_h). It is a slightly simplified implementation of neuron model proposed in Hill and Tononi (2005) **Modeling Sleep and Wakefulness in the Thalamocortical System** *J Neurophysiol* 93:1671 http://dx.doi.org/10.1152/jn.00915.2004. The neuron is bombarded with spike trains from four Poisson generators, which are connected to the AMPA, NMDA, GABA_A, and GABA_B receptors, respectively. See also: intrinsic_currents_subthreshold.py ''' ''' We imported all necessary modules for simulation, analysis and plotting. ''' import nest import numpy as np import matplotlib.pyplot as plt ''' Additionally, we set the verbosity using `set_verbosity` to suppress info messages. We also reset the kernel to be sure to start with a clean NEST. ''' nest.set_verbosity("M_WARNING") nest.ResetKernel() ''' We define the simulation parameters: - The rate of the input spike trains - The weights of the different receptors (names must match receptor types) - The time to simulate Note that all parameter values should be doubles, since NEST expects doubles. ''' rate_in = 100. w_recep = {'AMPA': 30., 'NMDA': 30., 'GABA_A': 5., 'GABA_B': 10.} t_sim = 250. num_recep = len(w_recep) ''' We create - one neuron instance - one Poisson generator instance for each synapse type - one multimeter to record from the neuron: - membrane potential - threshold potential - synaptic conductances - intrinsic currents See `intrinsic_currents_subthreshold.py` for more details on `multimeter` configuration. ''' nrn = nest.Create('ht_neuron') p_gens = nest.Create('poisson_generator', 4, params={'rate': rate_in}) mm = nest.Create('multimeter', params={'interval': 0.1, 'record_from': ['V_m', 'theta', 'g_AMPA', 'g_NMDA', 'g_GABA_A', 'g_GABA_B', 'I_NaP', 'I_KNa', 'I_T', 'I_h']}) ''' We now connect each Poisson generator with the neuron through a different receptor type. First, we need to obtain the numerical codes for the receptor types from the model. The `receptor_types` entry of the default dictionary for the `ht_neuron` model is a dictionary mapping receptor names to codes. In the loop, we use Python's tuple unpacking mechanism to unpack dictionary entries from our w_recep dictionary. Note that we need to pack the ``pg`` variable into a list before passing it to `Connect`, because iterating over the `p_gens` list makes `pg` a "naked" GID. ''' receptors = nest.GetDefaults('ht_neuron')['receptor_types'] for pg, (rec_name, rec_wgt) in zip(p_gens, w_recep.items()): nest.Connect([pg], nrn, syn_spec={'receptor_type': receptors[rec_name], 'weight': rec_wgt}) ''' We then connnect the multimeter. Note that the multimeter is connected to the neuron, not the other way around. ''' nest.Connect(mm, nrn) ''' We are now ready to simulate. ''' nest.Simulate(t_sim) ''' We now fetch the data recorded by the multimeter. The data are returned as a dictionary with entry ``'times'`` containing timestamps for all recorded data, plus one entry per recorded quantity. All data is contained in the ``'events'`` entry of the status dictionary returned by the multimeter. Because all NEST function return arrays, we need to pick out element ``0`` from the result of `GetStatus`. ''' data = nest.GetStatus(mm)[0]['events'] t = data['times'] ''' The following function turns a name such as I_NaP into proper TeX code $I_{\mathrm{NaP}}$ for a pretty label. ''' def texify_name(name): return r'${}_{{\mathrm{{{}}}}}$'.format(*name.split('_')) ''' The next step is to plot the results. We create a new figure, and add one subplot each for membrane and threshold potential, synaptic conductances, and intrinsic currents. ''' fig = plt.figure() Vax = fig.add_subplot(311) Vax.plot(t, data['V_m'], 'b', lw=2, label=r'$V_m$') Vax.plot(t, data['theta'], 'g', lw=2, label=r'$\Theta$') Vax.set_ylabel('Potential [mV]') try: Vax.legend(fontsize='small') except TypeError: Vax.legend() # work-around for older Matplotlib versions Vax.set_title('ht_neuron driven by Poisson processes') Gax = fig.add_subplot(312) for gname in ('g_AMPA', 'g_NMDA', 'g_GABA_A', 'g_GABA_B'): Gax.plot(t, data[gname], lw=2, label=texify_name(gname)) try: Gax.legend(fontsize='small') except TypeError: Gax.legend() # work-around for older Matplotlib versions Gax.set_ylabel('Conductance [nS]') Iax = fig.add_subplot(313) for iname, color in (('I_h', 'maroon'), ('I_T', 'orange'), ('I_NaP', 'crimson'), ('I_KNa', 'aqua')): Iax.plot(t, data[iname], color=color, lw=2, label=texify_name(iname)) try: Iax.legend(fontsize='small') except TypeError: Iax.legend() # work-around for older Matplotlib versions Iax.set_ylabel('Current [pA]') Iax.set_xlabel('Time [ms]')
gpl-2.0
rs2/pandas
pandas/tests/plotting/test_converter.py
1
12196
from datetime import date, datetime import subprocess import sys import numpy as np import pytest import pandas._config.config as cf from pandas.compat.numpy import np_datetime64_compat import pandas.util._test_decorators as td from pandas import Index, Period, Series, Timestamp, date_range import pandas._testing as tm from pandas.plotting import ( deregister_matplotlib_converters, register_matplotlib_converters, ) from pandas.tseries.offsets import Day, Micro, Milli, Second try: from pandas.plotting._matplotlib import converter except ImportError: # try / except, rather than skip, to avoid internal refactoring # causing an improper skip pass pytest.importorskip("matplotlib.pyplot") dates = pytest.importorskip("matplotlib.dates") def test_registry_mpl_resets(): # Check that Matplotlib converters are properly reset (see issue #27481) code = ( "import matplotlib.units as units; " "import matplotlib.dates as mdates; " "n_conv = len(units.registry); " "import pandas as pd; " "pd.plotting.register_matplotlib_converters(); " "pd.plotting.deregister_matplotlib_converters(); " "assert len(units.registry) == n_conv" ) call = [sys.executable, "-c", code] subprocess.check_output(call) def test_timtetonum_accepts_unicode(): assert converter.time2num("00:01") == converter.time2num("00:01") class TestRegistration: def test_register_by_default(self): # Run in subprocess to ensure a clean state code = ( "'import matplotlib.units; " "import pandas as pd; " "units = dict(matplotlib.units.registry); " "assert pd.Timestamp in units)'" ) call = [sys.executable, "-c", code] assert subprocess.check_call(call) == 0 @td.skip_if_no("matplotlib", min_version="3.1.3") def test_registering_no_warning(self): plt = pytest.importorskip("matplotlib.pyplot") s = Series(range(12), index=date_range("2017", periods=12)) _, ax = plt.subplots() # Set to the "warn" state, in case this isn't the first test run register_matplotlib_converters() ax.plot(s.index, s.values) def test_pandas_plots_register(self): pytest.importorskip("matplotlib.pyplot") s = Series(range(12), index=date_range("2017", periods=12)) # Set to the "warn" state, in case this isn't the first test run with tm.assert_produces_warning(None) as w: s.plot() assert len(w) == 0 def test_matplotlib_formatters(self): units = pytest.importorskip("matplotlib.units") # Can't make any assertion about the start state. # We we check that toggling converters off removes it, and toggling it # on restores it. with cf.option_context("plotting.matplotlib.register_converters", True): with cf.option_context("plotting.matplotlib.register_converters", False): assert Timestamp not in units.registry assert Timestamp in units.registry @td.skip_if_no("matplotlib", min_version="3.1.3") def test_option_no_warning(self): pytest.importorskip("matplotlib.pyplot") ctx = cf.option_context("plotting.matplotlib.register_converters", False) plt = pytest.importorskip("matplotlib.pyplot") s = Series(range(12), index=date_range("2017", periods=12)) _, ax = plt.subplots() # Test without registering first, no warning with ctx: ax.plot(s.index, s.values) # Now test with registering register_matplotlib_converters() with ctx: ax.plot(s.index, s.values) def test_registry_resets(self): units = pytest.importorskip("matplotlib.units") dates = pytest.importorskip("matplotlib.dates") # make a copy, to reset to original = dict(units.registry) try: # get to a known state units.registry.clear() date_converter = dates.DateConverter() units.registry[datetime] = date_converter units.registry[date] = date_converter register_matplotlib_converters() assert units.registry[date] is not date_converter deregister_matplotlib_converters() assert units.registry[date] is date_converter finally: # restore original stater units.registry.clear() for k, v in original.items(): units.registry[k] = v class TestDateTimeConverter: def setup_method(self, method): self.dtc = converter.DatetimeConverter() self.tc = converter.TimeFormatter(None) def test_convert_accepts_unicode(self): r1 = self.dtc.convert("12:22", None, None) r2 = self.dtc.convert("12:22", None, None) assert r1 == r2, "DatetimeConverter.convert should accept unicode" def test_conversion(self): rs = self.dtc.convert(["2012-1-1"], None, None)[0] xp = dates.date2num(datetime(2012, 1, 1)) assert rs == xp rs = self.dtc.convert("2012-1-1", None, None) assert rs == xp rs = self.dtc.convert(date(2012, 1, 1), None, None) assert rs == xp rs = self.dtc.convert("2012-1-1", None, None) assert rs == xp rs = self.dtc.convert(Timestamp("2012-1-1"), None, None) assert rs == xp # also testing datetime64 dtype (GH8614) rs = self.dtc.convert(np_datetime64_compat("2012-01-01"), None, None) assert rs == xp rs = self.dtc.convert( np_datetime64_compat("2012-01-01 00:00:00+0000"), None, None ) assert rs == xp rs = self.dtc.convert( np.array( [ np_datetime64_compat("2012-01-01 00:00:00+0000"), np_datetime64_compat("2012-01-02 00:00:00+0000"), ] ), None, None, ) assert rs[0] == xp # we have a tz-aware date (constructed to that when we turn to utc it # is the same as our sample) ts = Timestamp("2012-01-01").tz_localize("UTC").tz_convert("US/Eastern") rs = self.dtc.convert(ts, None, None) assert rs == xp rs = self.dtc.convert(ts.to_pydatetime(), None, None) assert rs == xp rs = self.dtc.convert(Index([ts - Day(1), ts]), None, None) assert rs[1] == xp rs = self.dtc.convert(Index([ts - Day(1), ts]).to_pydatetime(), None, None) assert rs[1] == xp def test_conversion_float(self): rtol = 0.5 * 10 ** -9 rs = self.dtc.convert(Timestamp("2012-1-1 01:02:03", tz="UTC"), None, None) xp = converter.dates.date2num(Timestamp("2012-1-1 01:02:03", tz="UTC")) tm.assert_almost_equal(rs, xp, rtol=rtol) rs = self.dtc.convert( Timestamp("2012-1-1 09:02:03", tz="Asia/Hong_Kong"), None, None ) tm.assert_almost_equal(rs, xp, rtol=rtol) rs = self.dtc.convert(datetime(2012, 1, 1, 1, 2, 3), None, None) tm.assert_almost_equal(rs, xp, rtol=rtol) def test_conversion_outofbounds_datetime(self): # 2579 values = [date(1677, 1, 1), date(1677, 1, 2)] rs = self.dtc.convert(values, None, None) xp = converter.dates.date2num(values) tm.assert_numpy_array_equal(rs, xp) rs = self.dtc.convert(values[0], None, None) xp = converter.dates.date2num(values[0]) assert rs == xp values = [datetime(1677, 1, 1, 12), datetime(1677, 1, 2, 12)] rs = self.dtc.convert(values, None, None) xp = converter.dates.date2num(values) tm.assert_numpy_array_equal(rs, xp) rs = self.dtc.convert(values[0], None, None) xp = converter.dates.date2num(values[0]) assert rs == xp @pytest.mark.parametrize( "time,format_expected", [ (0, "00:00"), # time2num(datetime.time.min) (86399.999999, "23:59:59.999999"), # time2num(datetime.time.max) (90000, "01:00"), (3723, "01:02:03"), (39723.2, "11:02:03.200"), ], ) def test_time_formatter(self, time, format_expected): # issue 18478 result = self.tc(time) assert result == format_expected def test_dateindex_conversion(self): rtol = 10 ** -9 for freq in ("B", "L", "S"): dateindex = tm.makeDateIndex(k=10, freq=freq) rs = self.dtc.convert(dateindex, None, None) xp = converter.dates.date2num(dateindex._mpl_repr()) tm.assert_almost_equal(rs, xp, rtol=rtol) def test_resolution(self): def _assert_less(ts1, ts2): val1 = self.dtc.convert(ts1, None, None) val2 = self.dtc.convert(ts2, None, None) if not val1 < val2: raise AssertionError(f"{val1} is not less than {val2}.") # Matplotlib's time representation using floats cannot distinguish # intervals smaller than ~10 microsecond in the common range of years. ts = Timestamp("2012-1-1") _assert_less(ts, ts + Second()) _assert_less(ts, ts + Milli()) _assert_less(ts, ts + Micro(50)) def test_convert_nested(self): inner = [Timestamp("2017-01-01"), Timestamp("2017-01-02")] data = [inner, inner] result = self.dtc.convert(data, None, None) expected = [self.dtc.convert(x, None, None) for x in data] assert (np.array(result) == expected).all() class TestPeriodConverter: def setup_method(self, method): self.pc = converter.PeriodConverter() class Axis: pass self.axis = Axis() self.axis.freq = "D" def test_convert_accepts_unicode(self): r1 = self.pc.convert("2012-1-1", None, self.axis) r2 = self.pc.convert("2012-1-1", None, self.axis) assert r1 == r2 def test_conversion(self): rs = self.pc.convert(["2012-1-1"], None, self.axis)[0] xp = Period("2012-1-1").ordinal assert rs == xp rs = self.pc.convert("2012-1-1", None, self.axis) assert rs == xp rs = self.pc.convert([date(2012, 1, 1)], None, self.axis)[0] assert rs == xp rs = self.pc.convert(date(2012, 1, 1), None, self.axis) assert rs == xp rs = self.pc.convert([Timestamp("2012-1-1")], None, self.axis)[0] assert rs == xp rs = self.pc.convert(Timestamp("2012-1-1"), None, self.axis) assert rs == xp rs = self.pc.convert(np_datetime64_compat("2012-01-01"), None, self.axis) assert rs == xp rs = self.pc.convert( np_datetime64_compat("2012-01-01 00:00:00+0000"), None, self.axis ) assert rs == xp rs = self.pc.convert( np.array( [ np_datetime64_compat("2012-01-01 00:00:00+0000"), np_datetime64_compat("2012-01-02 00:00:00+0000"), ] ), None, self.axis, ) assert rs[0] == xp def test_integer_passthrough(self): # GH9012 rs = self.pc.convert([0, 1], None, self.axis) xp = [0, 1] assert rs == xp def test_convert_nested(self): data = ["2012-1-1", "2012-1-2"] r1 = self.pc.convert([data, data], None, self.axis) r2 = [self.pc.convert(data, None, self.axis) for _ in range(2)] assert r1 == r2 class TestTimeDeltaConverter: """Test timedelta converter""" @pytest.mark.parametrize( "x, decimal, format_expected", [ (0.0, 0, "00:00:00"), (3972320000000, 1, "01:06:12.3"), (713233432000000, 2, "8 days 06:07:13.43"), (32423432000000, 4, "09:00:23.4320"), ], ) def test_format_timedelta_ticks(self, x, decimal, format_expected): tdc = converter.TimeSeries_TimedeltaFormatter result = tdc.format_timedelta_ticks(x, pos=None, n_decimals=decimal) assert result == format_expected
bsd-3-clause
nDroidProject/android_external_blktrace
btt/btt_plot.py
43
11282
#! /usr/bin/env python # # btt_plot.py: Generate matplotlib plots for BTT generate data files # # (C) Copyright 2009 Hewlett-Packard Development Company, L.P. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """ btt_plot.py: Generate matplotlib plots for BTT generated data files Files handled: AQD - Average Queue Depth Running average of queue depths BNOS - Block numbers accessed Markers for each block Q2D - Queue to Issue latencies Running averages D2C - Issue to Complete latencies Running averages Q2C - Queue to Complete latencies Running averages Usage: btt_plot_aqd.py equivalent to: btt_plot.py -t aqd <type>=aqd btt_plot_bnos.py equivalent to: btt_plot.py -t bnos <type>=bnos btt_plot_q2d.py equivalent to: btt_plot.py -t q2d <type>=q2d btt_plot_d2c.py equivalent to: btt_plot.py -t d2c <type>=d2c btt_plot_q2c.py equivalent to: btt_plot.py -t q2c <type>=q2c Arguments: [ -A | --generate-all ] Default: False [ -L | --no-legend ] Default: Legend table produced [ -o <file> | --output=<file> ] Default: <type>.png [ -T <string> | --title=<string> ] Default: Based upon <type> [ -v | --verbose ] Default: False <data-files...> The -A (--generate-all) argument is different: when this is specified, an attempt is made to generate default plots for all 5 types (aqd, bnos, q2d, d2c and q2c). It will find files with the appropriate suffix for each type ('aqd.dat' for example). If such files are found, a plot for that type will be made. The output file name will be the default for each type. The -L (--no-legend) option will be obeyed for all plots, but the -o (--output) and -T (--title) options will be ignored. """ __author__ = 'Alan D. Brunelle <alan.brunelle@hp.com>' #------------------------------------------------------------------------------ import matplotlib matplotlib.use('Agg') import getopt, glob, os, sys import matplotlib.pyplot as plt plot_size = [10.9, 8.4] # inches... add_legend = True generate_all = False output_file = None title_str = None type = None verbose = False types = [ 'aqd', 'q2d', 'd2c', 'q2c', 'bnos' ] progs = [ 'btt_plot_%s.py' % t for t in types ] get_base = lambda file: file[file.find('_')+1:file.rfind('_')] #------------------------------------------------------------------------------ def fatal(msg): """Generate fatal error message and exit""" print >>sys.stderr, 'FATAL: %s' % msg sys.exit(1) #---------------------------------------------------------------------- def get_data(files): """Retrieve data from files provided. Returns a database containing: 'min_x', 'max_x' - Minimum and maximum X values found 'min_y', 'max_y' - Minimum and maximum Y values found 'x', 'y' - X & Y value arrays 'ax', 'ay' - Running average over X & Y -- if > 10 values provided... """ #-------------------------------------------------------------- def check(mn, mx, v): """Returns new min, max, and float value for those passed in""" v = float(v) if mn == None or v < mn: mn = v if mx == None or v > mx: mx = v return mn, mx, v #-------------------------------------------------------------- def avg(xs, ys): """Computes running average for Xs and Ys""" #------------------------------------------------------ def _avg(vals): """Computes average for array of values passed""" total = 0.0 for val in vals: total += val return total / len(vals) #------------------------------------------------------ if len(xs) < 1000: return xs, ys axs = [xs[0]] ays = [ys[0]] _xs = [xs[0]] _ys = [ys[0]] x_range = (xs[-1] - xs[0]) / 100 for idx in range(1, len(ys)): if (xs[idx] - _xs[0]) > x_range: axs.append(_avg(_xs)) ays.append(_avg(_ys)) del _xs, _ys _xs = [xs[idx]] _ys = [ys[idx]] else: _xs.append(xs[idx]) _ys.append(ys[idx]) if len(_xs) > 1: axs.append(_avg(_xs)) ays.append(_avg(_ys)) return axs, ays #-------------------------------------------------------------- global verbose db = {} min_x = max_x = min_y = max_y = None for file in files: if not os.path.exists(file): fatal('%s not found' % file) elif verbose: print 'Processing %s' % file xs = [] ys = [] for line in open(file, 'r'): f = line.rstrip().split(None) if line.find('#') == 0 or len(f) < 2: continue (min_x, max_x, x) = check(min_x, max_x, f[0]) (min_y, max_y, y) = check(min_y, max_y, f[1]) xs.append(x) ys.append(y) db[file] = {'x':xs, 'y':ys} if len(xs) > 10: db[file]['ax'], db[file]['ay'] = avg(xs, ys) else: db[file]['ax'] = db[file]['ay'] = None db['min_x'] = min_x db['max_x'] = max_x db['min_y'] = min_y db['max_y'] = max_y return db #---------------------------------------------------------------------- def parse_args(args): """Parse command line arguments. Returns list of (data) files that need to be processed -- /unless/ the -A (--generate-all) option is passed, in which case superfluous data files are ignored... """ global add_legend, output_file, title_str, type, verbose global generate_all prog = args[0][args[0].rfind('/')+1:] if prog == 'btt_plot.py': pass elif not prog in progs: fatal('%s not a valid command name' % prog) else: type = prog[prog.rfind('_')+1:prog.rfind('.py')] s_opts = 'ALo:t:T:v' l_opts = [ 'generate-all', 'type', 'no-legend', 'output', 'title', 'verbose' ] try: (opts, args) = getopt.getopt(args[1:], s_opts, l_opts) except getopt.error, msg: print >>sys.stderr, msg fatal(__doc__) for (o, a) in opts: if o in ('-A', '--generate-all'): generate_all = True elif o in ('-L', '--no-legend'): add_legend = False elif o in ('-o', '--output'): output_file = a elif o in ('-t', '--type'): if not a in types: fatal('Type %s not supported' % a) type = a elif o in ('-T', '--title'): title_str = a elif o in ('-v', '--verbose'): verbose = True if type == None and not generate_all: fatal('Need type of data files to process - (-t <type>)') return args #------------------------------------------------------------------------------ def gen_title(fig, type, title_str): """Sets the title for the figure based upon the type /or/ user title""" if title_str != None: pass elif type == 'aqd': title_str = 'Average Queue Depth' elif type == 'bnos': title_str = 'Block Numbers Accessed' elif type == 'q2d': title_str = 'Queue (Q) To Issue (D) Average Latencies' elif type == 'd2c': title_str = 'Issue (D) To Complete (C) Average Latencies' elif type == 'q2c': title_str = 'Queue (Q) To Complete (C) Average Latencies' title = fig.text(.5, .95, title_str, horizontalalignment='center') title.set_fontsize('large') #------------------------------------------------------------------------------ def gen_labels(db, ax, type): """Generate X & Y 'axis'""" #---------------------------------------------------------------------- def gen_ylabel(ax, type): """Set the Y axis label based upon the type""" if type == 'aqd': str = 'Number of Requests Queued' elif type == 'bnos': str = 'Block Number' else: str = 'Seconds' ax.set_ylabel(str) #---------------------------------------------------------------------- xdelta = 0.1 * (db['max_x'] - db['min_x']) ydelta = 0.1 * (db['max_y'] - db['min_y']) ax.set_xlim(db['min_x'] - xdelta, db['max_x'] + xdelta) ax.set_ylim(db['min_y'] - ydelta, db['max_y'] + ydelta) ax.set_xlabel('Runtime (seconds)') ax.grid(True) gen_ylabel(ax, type) #------------------------------------------------------------------------------ def generate_output(type, db): """Generate the output plot based upon the type and database""" #---------------------------------------------------------------------- def color(idx, style): """Returns a color/symbol type based upon the index passed.""" colors = [ 'b', 'g', 'r', 'c', 'm', 'y', 'k' ] l_styles = [ '-', ':', '--', '-.' ] m_styles = [ 'o', '+', '.', ',', 's', 'v', 'x', '<', '>' ] color = colors[idx % len(colors)] if style == 'line': style = l_styles[(idx / len(l_styles)) % len(l_styles)] elif style == 'marker': style = m_styles[(idx / len(m_styles)) % len(m_styles)] return '%s%s' % (color, style) #---------------------------------------------------------------------- def gen_legends(a, legends): leg = ax.legend(legends, 'best', shadow=True) frame = leg.get_frame() frame.set_facecolor('0.80') for t in leg.get_texts(): t.set_fontsize('xx-small') #---------------------------------------------------------------------- global add_legend, output_file, title_str, verbose if output_file != None: ofile = output_file else: ofile = '%s.png' % type if verbose: print 'Generating plot into %s' % ofile fig = plt.figure(figsize=plot_size) ax = fig.add_subplot(111) gen_title(fig, type, title_str) gen_labels(db, ax, type) idx = 0 if add_legend: legends = [] else: legends = None keys = [] for file in db.iterkeys(): if not file in ['min_x', 'max_x', 'min_y', 'max_y']: keys.append(file) keys.sort() for file in keys: dat = db[file] if type == 'bnos': ax.plot(dat['x'], dat['y'], color(idx, 'marker'), markersize=1) elif dat['ax'] == None: continue # Don't add legend else: ax.plot(dat['ax'], dat['ay'], color(idx, 'line'), linewidth=1.0) if add_legend: legends.append(get_base(file)) idx += 1 if add_legend and len(legends) > 0: gen_legends(ax, legends) plt.savefig(ofile) #------------------------------------------------------------------------------ def get_files(type): """Returns the list of files for the -A option based upon type""" if type == 'bnos': files = [] for fn in glob.glob('*c.dat'): for t in [ 'q2q', 'd2d', 'q2c', 'd2c' ]: if fn.find(t) >= 0: break else: files.append(fn) else: files = glob.glob('*%s.dat' % type) return files #------------------------------------------------------------------------------ if __name__ == '__main__': files = parse_args(sys.argv) if generate_all: output_file = title_str = type = None for t in types: files = get_files(t) if len(files) == 0: continue elif t != 'bnos': generate_output(t, get_data(files)) continue for file in files: base = get_base(file) title_str = 'Block Numbers Accessed: %s' % base output_file = 'bnos_%s.png' % base generate_output(t, get_data([file])) elif len(files) < 1: fatal('Need data files to process') else: generate_output(type, get_data(files)) sys.exit(0)
gpl-2.0
jdfekete/progressivis
tests/test_02_table_merge.py
1
1859
from collections import OrderedDict import pandas as pd from progressivis import Scheduler from progressivis.table.table import Table from progressivis.table.merge import merge from . import ProgressiveTest df_left1 = pd.DataFrame(OrderedDict([('A', ['A0', 'A1', 'A2', 'A3']), ('B', ['B0', 'B1', 'B2', 'B3']), ('C', ['C0', 'C1', 'C2', 'C3'])]), index=[0, 1, 2, 3]) df_right1 = pd.DataFrame({'X': ['X0', 'X1', 'X2', 'X3'], 'Y': ['Y0', 'Y2', 'Y3', 'Y4'], 'Z': ['Z0', 'Z2', 'Z3', 'Z4']}, index=[2, 3, 4, 5]) df_right2 = pd.DataFrame(OrderedDict([('X', ['X0', 'X1', 'X2', 'X3']), ('Y', ['Y0', 'Y2', 'Y3', 'Y4']), ('B', ['Br0', 'Br2', 'Br3', 'Br4']), ('Z', ['Z0', 'Z2', 'Z3', 'Z4'])]), index=[2, 3, 4, 5]) class TestMergeTable(ProgressiveTest): def setUp(self): super(TestMergeTable, self).setUp() self.scheduler = Scheduler.default def test_merge1(self): table_left = Table(name='table_left', data=df_left1, create=True) print(repr(table_left)) table_right = Table(name='table_right', data=df_right1, create=True, indices=df_right1.index.values) print(repr(table_right)) #table_right2 = Table(name='table_right2', data=df_right2, create=True) table_merge = merge(table_left, table_right, name='table_merge', left_index=True, right_index=True) print(repr(table_merge)) if __name__ == '__main__': ProgressiveTest.main()
bsd-2-clause
kingfink/Newport-Folk-Festival
wikipedia_origins.py
1
1064
import urllib import urllib2 from bs4 import BeautifulSoup import pandas as pd def get_location(article): article = urllib.quote(article) opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] #wikipedia needs this str_ret = '' try: resource = opener.open("http://en.wikipedia.org/wiki/" + article) data = resource.read() resource.close() soup = BeautifulSoup(data) # get birth try: str_ret = soup.find("th", text="Born").parent.find("a").get_text() except: str_ret = "Not Available" # get origin try: str_ret = str_ret + ' | ' + soup.find("th", text="Origin").parent.find("td").get_text() except: str_ret = str_ret + ' | ' + "Not Available" except: str_ret = "Artist not Found" return str_ret if __name__ == "__main__": df = pd.read_csv('artists.csv') for x in df.T.iteritems(): print x[1][0] + ' | ' + get_location(x[1][0])
mit
bjornaa/polarmap
polar_bathymetry.py
1
1753
# -*- coding: utf-8 -*- # Plot bathymetry on a polar map # ----------------------------------- # Bjørn Ådlandsvik <bjorn@imr.no> # Institute of Marine Research # ----------------------------------- # --------- # Imports # --------- import numpy as np from netCDF4 import Dataset import matplotlib.pyplot as plt from polarmap import PolarMap # --------------- # User settings # --------------- # Define geographical extent lon0, lon1 = -10, 30 # Longitude range lat0, lat1 = 54, 72 # Latitude range lons = range(-10, 31, 10) lats = range(55, 71, 5) # Topography file topo_file = 'topo.nc' # Select vertical levels levels = [1, 5, 10, 20, 50, 100, 200, 500, 1000, 2000] # --- End user settings -------- # Level treatment loglevels = [np.log10(v) for v in levels] level_labels = ['0'] + [str(v) for v in levels[1:]] # Use '0' instead of '1' # Load the topography with Dataset(topo_file) as fid: lon = fid.variables['lon'][:] lat = fid.variables['lat'][:] topo = fid.variables['topo'][:, :] llon, llat = np.meshgrid(lon, lat) # Depth is positive and only defined at sea topo = np.where(topo >= 0, np.nan, -topo) # Define the PolarMap instance pmap = PolarMap(lon0, lon1, lat0, lat1, 'coast.npy') # Contour the bathymetry pmap.contourf(llon, llat, np.log10(topo), cmap=plt.get_cmap('Blues'), levels=loglevels, extend='max') # Colorbar plt.colorbar(ticks=loglevels, format=plt.FixedFormatter(level_labels), extend='max', shrink=0.8) # Put a yellow colour on land with a black coast line pmap.fillcontinents(facecolor=(0.8, 0.8, 0.2), edgecolor='black') # Draw graticule pmap.drawparallels(lats) pmap.drawmeridians(lons) plt.show()
mit
chrisburr/scikit-learn
sklearn/tests/test_multiclass.py
14
21802
import numpy as np import scipy.sparse as sp from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_warns from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_raise_message from sklearn.multiclass import OneVsRestClassifier from sklearn.multiclass import OneVsOneClassifier from sklearn.multiclass import OutputCodeClassifier from sklearn.utils.multiclass import check_classification_targets, type_of_target from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.svm import LinearSVC, SVC from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import (LinearRegression, Lasso, ElasticNet, Ridge, Perceptron, LogisticRegression) from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from sklearn import svm from sklearn import datasets from sklearn.externals.six.moves import zip iris = datasets.load_iris() rng = np.random.RandomState(0) perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] n_classes = 3 def test_ovr_exceptions(): ovr = OneVsRestClassifier(LinearSVC(random_state=0)) assert_raises(ValueError, ovr.predict, []) # Fail on multioutput data assert_raises(ValueError, OneVsRestClassifier(MultinomialNB()).fit, np.array([[1, 0], [0, 1]]), np.array([[1, 2], [3, 1]])) assert_raises(ValueError, OneVsRestClassifier(MultinomialNB()).fit, np.array([[1, 0], [0, 1]]), np.array([[1.5, 2.4], [3.1, 0.8]])) def test_check_classification_targets(): # Test that check_classification_target return correct type. #5782 y = np.array([0.0, 1.1, 2.0, 3.0]) msg = type_of_target(y) assert_raise_message(ValueError, msg, check_classification_targets, y) def test_ovr_fit_predict(): # A classifier which implements decision_function. ovr = OneVsRestClassifier(LinearSVC(random_state=0)) pred = ovr.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovr.estimators_), n_classes) clf = LinearSVC(random_state=0) pred2 = clf.fit(iris.data, iris.target).predict(iris.data) assert_equal(np.mean(iris.target == pred), np.mean(iris.target == pred2)) # A classifier which implements predict_proba. ovr = OneVsRestClassifier(MultinomialNB()) pred = ovr.fit(iris.data, iris.target).predict(iris.data) assert_greater(np.mean(iris.target == pred), 0.65) def test_ovr_ovo_regressor(): # test that ovr and ovo work on regressors which don't have a decision_function ovr = OneVsRestClassifier(DecisionTreeRegressor()) pred = ovr.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovr.estimators_), n_classes) assert_array_equal(np.unique(pred), [0, 1, 2]) # we are doing something sensible assert_greater(np.mean(pred == iris.target), .9) ovr = OneVsOneClassifier(DecisionTreeRegressor()) pred = ovr.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovr.estimators_), n_classes * (n_classes - 1) / 2) assert_array_equal(np.unique(pred), [0, 1, 2]) # we are doing something sensible assert_greater(np.mean(pred == iris.target), .9) def test_ovr_fit_predict_sparse(): for sparse in [sp.csr_matrix, sp.csc_matrix, sp.coo_matrix, sp.dok_matrix, sp.lil_matrix]: base_clf = MultinomialNB(alpha=1) X, Y = datasets.make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, n_labels=3, length=50, allow_unlabeled=True, random_state=0) X_train, Y_train = X[:80], Y[:80] X_test = X[80:] clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) Y_pred = clf.predict(X_test) clf_sprs = OneVsRestClassifier(base_clf).fit(X_train, sparse(Y_train)) Y_pred_sprs = clf_sprs.predict(X_test) assert_true(clf.multilabel_) assert_true(sp.issparse(Y_pred_sprs)) assert_array_equal(Y_pred_sprs.toarray(), Y_pred) # Test predict_proba Y_proba = clf_sprs.predict_proba(X_test) # predict assigns a label if the probability that the # sample has the label is greater than 0.5. pred = Y_proba > .5 assert_array_equal(pred, Y_pred_sprs.toarray()) # Test decision_function clf_sprs = OneVsRestClassifier(svm.SVC()).fit(X_train, sparse(Y_train)) dec_pred = (clf_sprs.decision_function(X_test) > 0).astype(int) assert_array_equal(dec_pred, clf_sprs.predict(X_test).toarray()) def test_ovr_always_present(): # Test that ovr works with classes that are always present or absent. # Note: tests is the case where _ConstantPredictor is utilised X = np.ones((10, 2)) X[:5, :] = 0 # Build an indicator matrix where two features are always on. # As list of lists, it would be: [[int(i >= 5), 2, 3] for i in range(10)] y = np.zeros((10, 3)) y[5:, 0] = 1 y[:, 1] = 1 y[:, 2] = 1 ovr = OneVsRestClassifier(LogisticRegression()) assert_warns(UserWarning, ovr.fit, X, y) y_pred = ovr.predict(X) assert_array_equal(np.array(y_pred), np.array(y)) y_pred = ovr.decision_function(X) assert_equal(np.unique(y_pred[:, -2:]), 1) y_pred = ovr.predict_proba(X) assert_array_equal(y_pred[:, -1], np.ones(X.shape[0])) # y has a constantly absent label y = np.zeros((10, 2)) y[5:, 0] = 1 # variable label ovr = OneVsRestClassifier(LogisticRegression()) assert_warns(UserWarning, ovr.fit, X, y) y_pred = ovr.predict_proba(X) assert_array_equal(y_pred[:, -1], np.zeros(X.shape[0])) def test_ovr_multiclass(): # Toy dataset where features correspond directly to labels. X = np.array([[0, 0, 5], [0, 5, 0], [3, 0, 0], [0, 0, 6], [6, 0, 0]]) y = ["eggs", "spam", "ham", "eggs", "ham"] Y = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, 1], [1, 0, 0]]) classes = set("ham eggs spam".split()) for base_clf in (MultinomialNB(), LinearSVC(random_state=0), LinearRegression(), Ridge(), ElasticNet()): clf = OneVsRestClassifier(base_clf).fit(X, y) assert_equal(set(clf.classes_), classes) y_pred = clf.predict(np.array([[0, 0, 4]]))[0] assert_equal(set(y_pred), set("eggs")) # test input as label indicator matrix clf = OneVsRestClassifier(base_clf).fit(X, Y) y_pred = clf.predict([[0, 0, 4]])[0] assert_array_equal(y_pred, [0, 0, 1]) def test_ovr_binary(): # Toy dataset where features correspond directly to labels. X = np.array([[0, 0, 5], [0, 5, 0], [3, 0, 0], [0, 0, 6], [6, 0, 0]]) y = ["eggs", "spam", "spam", "eggs", "spam"] Y = np.array([[0, 1, 1, 0, 1]]).T classes = set("eggs spam".split()) def conduct_test(base_clf, test_predict_proba=False): clf = OneVsRestClassifier(base_clf).fit(X, y) assert_equal(set(clf.classes_), classes) y_pred = clf.predict(np.array([[0, 0, 4]]))[0] assert_equal(set(y_pred), set("eggs")) if test_predict_proba: X_test = np.array([[0, 0, 4]]) probabilities = clf.predict_proba(X_test) assert_equal(2, len(probabilities[0])) assert_equal(clf.classes_[np.argmax(probabilities, axis=1)], clf.predict(X_test)) # test input as label indicator matrix clf = OneVsRestClassifier(base_clf).fit(X, Y) y_pred = clf.predict([[3, 0, 0]])[0] assert_equal(y_pred, 1) for base_clf in (LinearSVC(random_state=0), LinearRegression(), Ridge(), ElasticNet()): conduct_test(base_clf) for base_clf in (MultinomialNB(), SVC(probability=True), LogisticRegression()): conduct_test(base_clf, test_predict_proba=True) def test_ovr_multilabel(): # Toy dataset where features correspond directly to labels. X = np.array([[0, 4, 5], [0, 5, 0], [3, 3, 3], [4, 0, 6], [6, 0, 0]]) y = np.array([[0, 1, 1], [0, 1, 0], [1, 1, 1], [1, 0, 1], [1, 0, 0]]) for base_clf in (MultinomialNB(), LinearSVC(random_state=0), LinearRegression(), Ridge(), ElasticNet(), Lasso(alpha=0.5)): clf = OneVsRestClassifier(base_clf).fit(X, y) y_pred = clf.predict([[0, 4, 4]])[0] assert_array_equal(y_pred, [0, 1, 1]) assert_true(clf.multilabel_) def test_ovr_fit_predict_svc(): ovr = OneVsRestClassifier(svm.SVC()) ovr.fit(iris.data, iris.target) assert_equal(len(ovr.estimators_), 3) assert_greater(ovr.score(iris.data, iris.target), .9) def test_ovr_multilabel_dataset(): base_clf = MultinomialNB(alpha=1) for au, prec, recall in zip((True, False), (0.51, 0.66), (0.51, 0.80)): X, Y = datasets.make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, n_labels=2, length=50, allow_unlabeled=au, random_state=0) X_train, Y_train = X[:80], Y[:80] X_test, Y_test = X[80:], Y[80:] clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) Y_pred = clf.predict(X_test) assert_true(clf.multilabel_) assert_almost_equal(precision_score(Y_test, Y_pred, average="micro"), prec, decimal=2) assert_almost_equal(recall_score(Y_test, Y_pred, average="micro"), recall, decimal=2) def test_ovr_multilabel_predict_proba(): base_clf = MultinomialNB(alpha=1) for au in (False, True): X, Y = datasets.make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, n_labels=3, length=50, allow_unlabeled=au, random_state=0) X_train, Y_train = X[:80], Y[:80] X_test = X[80:] clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) # decision function only estimator. Fails in current implementation. decision_only = OneVsRestClassifier(svm.SVR()).fit(X_train, Y_train) assert_raises(AttributeError, decision_only.predict_proba, X_test) # Estimator with predict_proba disabled, depending on parameters. decision_only = OneVsRestClassifier(svm.SVC(probability=False)) decision_only.fit(X_train, Y_train) assert_raises(AttributeError, decision_only.predict_proba, X_test) Y_pred = clf.predict(X_test) Y_proba = clf.predict_proba(X_test) # predict assigns a label if the probability that the # sample has the label is greater than 0.5. pred = Y_proba > .5 assert_array_equal(pred, Y_pred) def test_ovr_single_label_predict_proba(): base_clf = MultinomialNB(alpha=1) X, Y = iris.data, iris.target X_train, Y_train = X[:80], Y[:80] X_test = X[80:] clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) # decision function only estimator. Fails in current implementation. decision_only = OneVsRestClassifier(svm.SVR()).fit(X_train, Y_train) assert_raises(AttributeError, decision_only.predict_proba, X_test) Y_pred = clf.predict(X_test) Y_proba = clf.predict_proba(X_test) assert_almost_equal(Y_proba.sum(axis=1), 1.0) # predict assigns a label if the probability that the # sample has the label is greater than 0.5. pred = np.array([l.argmax() for l in Y_proba]) assert_false((pred - Y_pred).any()) def test_ovr_multilabel_decision_function(): X, Y = datasets.make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, n_labels=3, length=50, allow_unlabeled=True, random_state=0) X_train, Y_train = X[:80], Y[:80] X_test = X[80:] clf = OneVsRestClassifier(svm.SVC()).fit(X_train, Y_train) assert_array_equal((clf.decision_function(X_test) > 0).astype(int), clf.predict(X_test)) def test_ovr_single_label_decision_function(): X, Y = datasets.make_classification(n_samples=100, n_features=20, random_state=0) X_train, Y_train = X[:80], Y[:80] X_test = X[80:] clf = OneVsRestClassifier(svm.SVC()).fit(X_train, Y_train) assert_array_equal(clf.decision_function(X_test).ravel() > 0, clf.predict(X_test)) def test_ovr_gridsearch(): ovr = OneVsRestClassifier(LinearSVC(random_state=0)) Cs = [0.1, 0.5, 0.8] cv = GridSearchCV(ovr, {'estimator__C': Cs}) cv.fit(iris.data, iris.target) best_C = cv.best_estimator_.estimators_[0].C assert_true(best_C in Cs) def test_ovr_pipeline(): # Test with pipeline of length one # This test is needed because the multiclass estimators may fail to detect # the presence of predict_proba or decision_function. clf = Pipeline([("tree", DecisionTreeClassifier())]) ovr_pipe = OneVsRestClassifier(clf) ovr_pipe.fit(iris.data, iris.target) ovr = OneVsRestClassifier(DecisionTreeClassifier()) ovr.fit(iris.data, iris.target) assert_array_equal(ovr.predict(iris.data), ovr_pipe.predict(iris.data)) def test_ovr_coef_(): for base_classifier in [SVC(kernel='linear', random_state=0), LinearSVC(random_state=0)]: # SVC has sparse coef with sparse input data ovr = OneVsRestClassifier(base_classifier) for X in [iris.data, sp.csr_matrix(iris.data)]: # test with dense and sparse coef ovr.fit(X, iris.target) shape = ovr.coef_.shape assert_equal(shape[0], n_classes) assert_equal(shape[1], iris.data.shape[1]) # don't densify sparse coefficients assert_equal(sp.issparse(ovr.estimators_[0].coef_), sp.issparse(ovr.coef_)) def test_ovr_coef_exceptions(): # Not fitted exception! ovr = OneVsRestClassifier(LinearSVC(random_state=0)) # lambda is needed because we don't want coef_ to be evaluated right away assert_raises(ValueError, lambda x: ovr.coef_, None) # Doesn't have coef_ exception! ovr = OneVsRestClassifier(DecisionTreeClassifier()) ovr.fit(iris.data, iris.target) assert_raises(AttributeError, lambda x: ovr.coef_, None) def test_ovo_exceptions(): ovo = OneVsOneClassifier(LinearSVC(random_state=0)) assert_raises(ValueError, ovo.predict, []) def test_ovo_fit_on_list(): # Test that OneVsOne fitting works with a list of targets and yields the # same output as predict from an array ovo = OneVsOneClassifier(LinearSVC(random_state=0)) prediction_from_array = ovo.fit(iris.data, iris.target).predict(iris.data) prediction_from_list = ovo.fit(iris.data, list(iris.target)).predict(iris.data) assert_array_equal(prediction_from_array, prediction_from_list) def test_ovo_fit_predict(): # A classifier which implements decision_function. ovo = OneVsOneClassifier(LinearSVC(random_state=0)) ovo.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovo.estimators_), n_classes * (n_classes - 1) / 2) # A classifier which implements predict_proba. ovo = OneVsOneClassifier(MultinomialNB()) ovo.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovo.estimators_), n_classes * (n_classes - 1) / 2) def test_ovo_decision_function(): n_samples = iris.data.shape[0] ovo_clf = OneVsOneClassifier(LinearSVC(random_state=0)) ovo_clf.fit(iris.data, iris.target) decisions = ovo_clf.decision_function(iris.data) assert_equal(decisions.shape, (n_samples, n_classes)) assert_array_equal(decisions.argmax(axis=1), ovo_clf.predict(iris.data)) # Compute the votes votes = np.zeros((n_samples, n_classes)) k = 0 for i in range(n_classes): for j in range(i + 1, n_classes): pred = ovo_clf.estimators_[k].predict(iris.data) votes[pred == 0, i] += 1 votes[pred == 1, j] += 1 k += 1 # Extract votes and verify assert_array_equal(votes, np.round(decisions)) for class_idx in range(n_classes): # For each sample and each class, there only 3 possible vote levels # because they are only 3 distinct class pairs thus 3 distinct # binary classifiers. # Therefore, sorting predictions based on votes would yield # mostly tied predictions: assert_true(set(votes[:, class_idx]).issubset(set([0., 1., 2.]))) # The OVO decision function on the other hand is able to resolve # most of the ties on this data as it combines both the vote counts # and the aggregated confidence levels of the binary classifiers # to compute the aggregate decision function. The iris dataset # has 150 samples with a couple of duplicates. The OvO decisions # can resolve most of the ties: assert_greater(len(np.unique(decisions[:, class_idx])), 146) def test_ovo_gridsearch(): ovo = OneVsOneClassifier(LinearSVC(random_state=0)) Cs = [0.1, 0.5, 0.8] cv = GridSearchCV(ovo, {'estimator__C': Cs}) cv.fit(iris.data, iris.target) best_C = cv.best_estimator_.estimators_[0].C assert_true(best_C in Cs) def test_ovo_ties(): # Test that ties are broken using the decision function, # not defaulting to the smallest label X = np.array([[1, 2], [2, 1], [-2, 1], [-2, -1]]) y = np.array([2, 0, 1, 2]) multi_clf = OneVsOneClassifier(Perceptron(shuffle=False)) ovo_prediction = multi_clf.fit(X, y).predict(X) ovo_decision = multi_clf.decision_function(X) # Classifiers are in order 0-1, 0-2, 1-2 # Use decision_function to compute the votes and the normalized # sum_of_confidences, which is used to disambiguate when there is a tie in # votes. votes = np.round(ovo_decision) normalized_confidences = ovo_decision - votes # For the first point, there is one vote per class assert_array_equal(votes[0, :], 1) # For the rest, there is no tie and the prediction is the argmax assert_array_equal(np.argmax(votes[1:], axis=1), ovo_prediction[1:]) # For the tie, the prediction is the class with the highest score assert_equal(ovo_prediction[0], normalized_confidences[0].argmax()) def test_ovo_ties2(): # test that ties can not only be won by the first two labels X = np.array([[1, 2], [2, 1], [-2, 1], [-2, -1]]) y_ref = np.array([2, 0, 1, 2]) # cycle through labels so that each label wins once for i in range(3): y = (y_ref + i) % 3 multi_clf = OneVsOneClassifier(Perceptron(shuffle=False)) ovo_prediction = multi_clf.fit(X, y).predict(X) assert_equal(ovo_prediction[0], i % 3) def test_ovo_string_y(): # Test that the OvO doesn't mess up the encoding of string labels X = np.eye(4) y = np.array(['a', 'b', 'c', 'd']) ovo = OneVsOneClassifier(LinearSVC()) ovo.fit(X, y) assert_array_equal(y, ovo.predict(X)) def test_ecoc_exceptions(): ecoc = OutputCodeClassifier(LinearSVC(random_state=0)) assert_raises(ValueError, ecoc.predict, []) def test_ecoc_fit_predict(): # A classifier which implements decision_function. ecoc = OutputCodeClassifier(LinearSVC(random_state=0), code_size=2, random_state=0) ecoc.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ecoc.estimators_), n_classes * 2) # A classifier which implements predict_proba. ecoc = OutputCodeClassifier(MultinomialNB(), code_size=2, random_state=0) ecoc.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ecoc.estimators_), n_classes * 2) def test_ecoc_gridsearch(): ecoc = OutputCodeClassifier(LinearSVC(random_state=0), random_state=0) Cs = [0.1, 0.5, 0.8] cv = GridSearchCV(ecoc, {'estimator__C': Cs}) cv.fit(iris.data, iris.target) best_C = cv.best_estimator_.estimators_[0].C assert_true(best_C in Cs)
bsd-3-clause
lancezlin/ml_template_py
lib/python2.7/site-packages/sklearn/manifold/tests/test_locally_linear.py
85
5600
from itertools import product import numpy as np from numpy.testing import assert_almost_equal, assert_array_almost_equal from scipy import linalg from sklearn import neighbors, manifold from sklearn.manifold.locally_linear import barycenter_kneighbors_graph from sklearn.utils.testing import assert_less from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_raise_message from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_true eigen_solvers = ['dense', 'arpack'] # ---------------------------------------------------------------------- # Test utility routines def test_barycenter_kneighbors_graph(): X = np.array([[0, 1], [1.01, 1.], [2, 0]]) A = barycenter_kneighbors_graph(X, 1) assert_array_almost_equal( A.toarray(), [[0., 1., 0.], [1., 0., 0.], [0., 1., 0.]]) A = barycenter_kneighbors_graph(X, 2) # check that columns sum to one assert_array_almost_equal(np.sum(A.toarray(), 1), np.ones(3)) pred = np.dot(A.toarray(), X) assert_less(linalg.norm(pred - X) / X.shape[0], 1) # ---------------------------------------------------------------------- # Test LLE by computing the reconstruction error on some manifolds. def test_lle_simple_grid(): # note: ARPACK is numerically unstable, so this test will fail for # some random seeds. We choose 2 because the tests pass. rng = np.random.RandomState(2) # grid of equidistant points in 2D, n_components = n_dim X = np.array(list(product(range(5), repeat=2))) X = X + 1e-10 * rng.uniform(size=X.shape) n_components = 2 clf = manifold.LocallyLinearEmbedding(n_neighbors=5, n_components=n_components, random_state=rng) tol = 0.1 N = barycenter_kneighbors_graph(X, clf.n_neighbors).toarray() reconstruction_error = linalg.norm(np.dot(N, X) - X, 'fro') assert_less(reconstruction_error, tol) for solver in eigen_solvers: clf.set_params(eigen_solver=solver) clf.fit(X) assert_true(clf.embedding_.shape[1] == n_components) reconstruction_error = linalg.norm( np.dot(N, clf.embedding_) - clf.embedding_, 'fro') ** 2 assert_less(reconstruction_error, tol) assert_almost_equal(clf.reconstruction_error_, reconstruction_error, decimal=1) # re-embed a noisy version of X using the transform method noise = rng.randn(*X.shape) / 100 X_reembedded = clf.transform(X + noise) assert_less(linalg.norm(X_reembedded - clf.embedding_), tol) def test_lle_manifold(): rng = np.random.RandomState(0) # similar test on a slightly more complex manifold X = np.array(list(product(np.arange(18), repeat=2))) X = np.c_[X, X[:, 0] ** 2 / 18] X = X + 1e-10 * rng.uniform(size=X.shape) n_components = 2 for method in ["standard", "hessian", "modified", "ltsa"]: clf = manifold.LocallyLinearEmbedding(n_neighbors=6, n_components=n_components, method=method, random_state=0) tol = 1.5 if method == "standard" else 3 N = barycenter_kneighbors_graph(X, clf.n_neighbors).toarray() reconstruction_error = linalg.norm(np.dot(N, X) - X) assert_less(reconstruction_error, tol) for solver in eigen_solvers: clf.set_params(eigen_solver=solver) clf.fit(X) assert_true(clf.embedding_.shape[1] == n_components) reconstruction_error = linalg.norm( np.dot(N, clf.embedding_) - clf.embedding_, 'fro') ** 2 details = ("solver: %s, method: %s" % (solver, method)) assert_less(reconstruction_error, tol, msg=details) assert_less(np.abs(clf.reconstruction_error_ - reconstruction_error), tol * reconstruction_error, msg=details) # Test the error raised when parameter passed to lle is invalid def test_lle_init_parameters(): X = np.random.rand(5, 3) clf = manifold.LocallyLinearEmbedding(eigen_solver="error") msg = "unrecognized eigen_solver 'error'" assert_raise_message(ValueError, msg, clf.fit, X) clf = manifold.LocallyLinearEmbedding(method="error") msg = "unrecognized method 'error'" assert_raise_message(ValueError, msg, clf.fit, X) def test_pipeline(): # check that LocallyLinearEmbedding works fine as a Pipeline # only checks that no error is raised. # TODO check that it actually does something useful from sklearn import pipeline, datasets X, y = datasets.make_blobs(random_state=0) clf = pipeline.Pipeline( [('filter', manifold.LocallyLinearEmbedding(random_state=0)), ('clf', neighbors.KNeighborsClassifier())]) clf.fit(X, y) assert_less(.9, clf.score(X, y)) # Test the error raised when the weight matrix is singular def test_singular_matrix(): M = np.ones((10, 3)) f = ignore_warnings assert_raises(ValueError, f(manifold.locally_linear_embedding), M, 2, 1, method='standard', eigen_solver='arpack') # regression test for #6033 def test_integer_input(): rand = np.random.RandomState(0) X = rand.randint(0, 100, size=(20, 3)) for method in ["standard", "hessian", "modified", "ltsa"]: clf = manifold.LocallyLinearEmbedding(method=method, n_neighbors=10) clf.fit(X) # this previously raised a TypeError
mit
jblackburne/scikit-learn
sklearn/neural_network/tests/test_rbm.py
225
6278
import sys import re import numpy as np from scipy.sparse import csc_matrix, csr_matrix, lil_matrix from sklearn.utils.testing import (assert_almost_equal, assert_array_equal, assert_true) from sklearn.datasets import load_digits from sklearn.externals.six.moves import cStringIO as StringIO from sklearn.neural_network import BernoulliRBM from sklearn.utils.validation import assert_all_finite np.seterr(all='warn') Xdigits = load_digits().data Xdigits -= Xdigits.min() Xdigits /= Xdigits.max() def test_fit(): X = Xdigits.copy() rbm = BernoulliRBM(n_components=64, learning_rate=0.1, batch_size=10, n_iter=7, random_state=9) rbm.fit(X) assert_almost_equal(rbm.score_samples(X).mean(), -21., decimal=0) # in-place tricks shouldn't have modified X assert_array_equal(X, Xdigits) def test_partial_fit(): X = Xdigits.copy() rbm = BernoulliRBM(n_components=64, learning_rate=0.1, batch_size=20, random_state=9) n_samples = X.shape[0] n_batches = int(np.ceil(float(n_samples) / rbm.batch_size)) batch_slices = np.array_split(X, n_batches) for i in range(7): for batch in batch_slices: rbm.partial_fit(batch) assert_almost_equal(rbm.score_samples(X).mean(), -21., decimal=0) assert_array_equal(X, Xdigits) def test_transform(): X = Xdigits[:100] rbm1 = BernoulliRBM(n_components=16, batch_size=5, n_iter=5, random_state=42) rbm1.fit(X) Xt1 = rbm1.transform(X) Xt2 = rbm1._mean_hiddens(X) assert_array_equal(Xt1, Xt2) def test_small_sparse(): # BernoulliRBM should work on small sparse matrices. X = csr_matrix(Xdigits[:4]) BernoulliRBM().fit(X) # no exception def test_small_sparse_partial_fit(): for sparse in [csc_matrix, csr_matrix]: X_sparse = sparse(Xdigits[:100]) X = Xdigits[:100].copy() rbm1 = BernoulliRBM(n_components=64, learning_rate=0.1, batch_size=10, random_state=9) rbm2 = BernoulliRBM(n_components=64, learning_rate=0.1, batch_size=10, random_state=9) rbm1.partial_fit(X_sparse) rbm2.partial_fit(X) assert_almost_equal(rbm1.score_samples(X).mean(), rbm2.score_samples(X).mean(), decimal=0) def test_sample_hiddens(): rng = np.random.RandomState(0) X = Xdigits[:100] rbm1 = BernoulliRBM(n_components=2, batch_size=5, n_iter=5, random_state=42) rbm1.fit(X) h = rbm1._mean_hiddens(X[0]) hs = np.mean([rbm1._sample_hiddens(X[0], rng) for i in range(100)], 0) assert_almost_equal(h, hs, decimal=1) def test_fit_gibbs(): # Gibbs on the RBM hidden layer should be able to recreate [[0], [1]] # from the same input rng = np.random.RandomState(42) X = np.array([[0.], [1.]]) rbm1 = BernoulliRBM(n_components=2, batch_size=2, n_iter=42, random_state=rng) # you need that much iters rbm1.fit(X) assert_almost_equal(rbm1.components_, np.array([[0.02649814], [0.02009084]]), decimal=4) assert_almost_equal(rbm1.gibbs(X), X) return rbm1 def test_fit_gibbs_sparse(): # Gibbs on the RBM hidden layer should be able to recreate [[0], [1]] from # the same input even when the input is sparse, and test against non-sparse rbm1 = test_fit_gibbs() rng = np.random.RandomState(42) from scipy.sparse import csc_matrix X = csc_matrix([[0.], [1.]]) rbm2 = BernoulliRBM(n_components=2, batch_size=2, n_iter=42, random_state=rng) rbm2.fit(X) assert_almost_equal(rbm2.components_, np.array([[0.02649814], [0.02009084]]), decimal=4) assert_almost_equal(rbm2.gibbs(X), X.toarray()) assert_almost_equal(rbm1.components_, rbm2.components_) def test_gibbs_smoke(): # Check if we don't get NaNs sampling the full digits dataset. # Also check that sampling again will yield different results. X = Xdigits rbm1 = BernoulliRBM(n_components=42, batch_size=40, n_iter=20, random_state=42) rbm1.fit(X) X_sampled = rbm1.gibbs(X) assert_all_finite(X_sampled) X_sampled2 = rbm1.gibbs(X) assert_true(np.all((X_sampled != X_sampled2).max(axis=1))) def test_score_samples(): # Test score_samples (pseudo-likelihood) method. # Assert that pseudo-likelihood is computed without clipping. # See Fabian's blog, http://bit.ly/1iYefRk rng = np.random.RandomState(42) X = np.vstack([np.zeros(1000), np.ones(1000)]) rbm1 = BernoulliRBM(n_components=10, batch_size=2, n_iter=10, random_state=rng) rbm1.fit(X) assert_true((rbm1.score_samples(X) < -300).all()) # Sparse vs. dense should not affect the output. Also test sparse input # validation. rbm1.random_state = 42 d_score = rbm1.score_samples(X) rbm1.random_state = 42 s_score = rbm1.score_samples(lil_matrix(X)) assert_almost_equal(d_score, s_score) # Test numerical stability (#2785): would previously generate infinities # and crash with an exception. with np.errstate(under='ignore'): rbm1.score_samples([np.arange(1000) * 100]) def test_rbm_verbose(): rbm = BernoulliRBM(n_iter=2, verbose=10) old_stdout = sys.stdout sys.stdout = StringIO() try: rbm.fit(Xdigits) finally: sys.stdout = old_stdout def test_sparse_and_verbose(): # Make sure RBM works with sparse input when verbose=True old_stdout = sys.stdout sys.stdout = StringIO() from scipy.sparse import csc_matrix X = csc_matrix([[0.], [1.]]) rbm = BernoulliRBM(n_components=2, batch_size=2, n_iter=1, random_state=42, verbose=True) try: rbm.fit(X) s = sys.stdout.getvalue() # make sure output is sound assert_true(re.match(r"\[BernoulliRBM\] Iteration 1," r" pseudo-likelihood = -?(\d)+(\.\d+)?," r" time = (\d|\.)+s", s)) finally: sys.stdout = old_stdout
bsd-3-clause
robin-lai/scikit-learn
sklearn/metrics/metrics.py
233
1262
import warnings warnings.warn("sklearn.metrics.metrics is deprecated and will be removed in " "0.18. Please import from sklearn.metrics", DeprecationWarning) from .ranking import auc from .ranking import average_precision_score from .ranking import label_ranking_average_precision_score from .ranking import precision_recall_curve from .ranking import roc_auc_score from .ranking import roc_curve from .classification import accuracy_score from .classification import classification_report from .classification import confusion_matrix from .classification import f1_score from .classification import fbeta_score from .classification import hamming_loss from .classification import hinge_loss from .classification import jaccard_similarity_score from .classification import log_loss from .classification import matthews_corrcoef from .classification import precision_recall_fscore_support from .classification import precision_score from .classification import recall_score from .classification import zero_one_loss from .regression import explained_variance_score from .regression import mean_absolute_error from .regression import mean_squared_error from .regression import median_absolute_error from .regression import r2_score
bsd-3-clause
xya/sms-tools
lectures/05-Sinusoidal-model/plots-code/sineModel-anal-synth.py
24
1483
import numpy as np import matplotlib.pyplot as plt from scipy.signal import hamming, triang, blackmanharris import sys, os, functools, time sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/')) import sineModel as SM import utilFunctions as UF (fs, x) = UF.wavread(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../sounds/bendir.wav')) x1 = x[0:50000] w = np.blackman(2001) N = 2048 H = 500 t = -90 minSineDur = .01 maxnSines = 150 freqDevOffset = 20 freqDevSlope = 0.02 Ns = 512 H = Ns/4 tfreq, tmag, tphase = SM.sineModelAnal(x1, fs, w, N, H, t, maxnSines, minSineDur, freqDevOffset, freqDevSlope) y = SM.sineModelSynth(tfreq, tmag, tphase, Ns, H, fs) numFrames = int(tfreq[:,0].size) frmTime = H*np.arange(numFrames)/float(fs) maxplotfreq = 3000.0 plt.figure(1, figsize=(9, 7)) plt.subplot(3,1,1) plt.plot(np.arange(x1.size)/float(fs), x1, 'b', lw=1.5) plt.axis([0,x1.size/float(fs),min(x1),max(x1)]) plt.title('x (bendir.wav)') plt.subplot(3,1,2) tracks = tfreq*np.less(tfreq, maxplotfreq) tracks[tracks<=0] = np.nan plt.plot(frmTime, tracks, color='k', lw=1.5) plt.autoscale(tight=True) plt.title('f_t, sine frequencies') plt.subplot(3,1,3) plt.plot(np.arange(y.size)/float(fs), y, 'b', lw=1.5) plt.axis([0,y.size/float(fs),min(y),max(y)]) plt.title('y') plt.tight_layout() UF.wavwrite(y, fs, 'bendir-sine-synthesis.wav') plt.savefig('sineModel-anal-synth.png') plt.show()
agpl-3.0
salceson/PJN
lab6/main.py
1
3801
# coding: utf-8 import codecs import sys import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit from operator import itemgetter from ngrams import n_grams_stats from stats import stats _FILENAME = "data/potop.txt" _STATS_FILENAME = "out/stats.csv" _ENCODING = "utf-8" __author__ = "Michał Ciołczyk" _actions = ["ngrams", "words", "stats", "plots"] def _usage(argv): print("Usage: python %s <action>" % argv[0]) print("Action is one of: %s" % repr(_actions)) exit(1) if __name__ == "__main__": argv = sys.argv argc = len(argv) if argc != 2: _usage(argv) action = argv[1] if action not in _actions: _usage(argv) if action == "words": print("Creating words stats...") stats, corpus_len = stats(_FILENAME, _ENCODING) print("\tDone") print("Saving results to file %s..." % _STATS_FILENAME) with codecs.open(_STATS_FILENAME, 'w', encoding=_ENCODING) as f: for rank, (word, count) in enumerate(sorted(stats.items(), key=itemgetter(1), reverse=True), 1): f.write('%s,%d,%d,%f\n' % (word, rank, count, count * 1. / corpus_len)) print("\tDone") if action == "ngrams": print("Creating ngrams stats...") n_grams_stats(_FILENAME, _ENCODING) print("Done") if action == "stats": words = [] hapax_legomena = [] total_sum = 0 half_sum = 0 half_words = 0 print("Reading stats file %s..." % _STATS_FILENAME) with codecs.open(_STATS_FILENAME, encoding=_ENCODING) as f: for line in f: word, rank, count, percent = line.split(',') rank = int(rank) count = int(count) percent = float(percent) words.append((word, rank, count, percent)) if count == 1: hapax_legomena.append(word) total_sum += count print("\tDone") print("Hapax legomena: %s" % ', '.join(hapax_legomena)) print("Total hapax legomena count: %d" % len(hapax_legomena)) print() for _, _, count, _ in words: if half_sum >= total_sum / 2: break half_sum += count half_words += 1 print("50%% is covered by %d words (out of total %d words)" % (half_words, len(words))) print() if action == "plots": def zipf(x, k): return 1.0 * k / x def mandelbrot(x, B, d, P): return 1.0 * P / ((x + d) ** B) print("Reading stats file %s..." % _STATS_FILENAME) words = [] with codecs.open(_STATS_FILENAME, encoding=_ENCODING) as f: for line in f: word, rank, count, percent = line.split(',') rank = int(rank) count = int(count) percent = float(percent) words.append((word, rank, count, percent)) print("\tDone") xdata = np.array([i[1] for i in words]) ydata = np.array([i[2] for i in words]) zipf_popt, _ = curve_fit(zipf, xdata, ydata, p0=(1.0)) mandelbrot_popt, _ = curve_fit(mandelbrot, xdata, ydata, p0=(1.0, 0.0, 2000.0)) print("Zipf fit: k=%f" % tuple(zipf_popt)) print("Mandelbrot fit: B=%f, d=%f, p=%f" % tuple(mandelbrot_popt)) plt.plot(xdata, ydata, '-', label="Real data") plt.plot(xdata, zipf(xdata, *zipf_popt), '-', label="Zipf law") plt.plot(xdata, mandelbrot(xdata, *mandelbrot_popt), '-', label="Mandelbrot law") plt.xlabel("Rank") plt.ylabel("Frequency") plt.yscale('log') plt.ylim(ymin=0.1) plt.legend() plt.show() plt.savefig("out/plot.png")
mit
jjgomera/pychemqt
setup.py
1
2013
from setuptools import setup, find_packages import io __version__ = "0.1.0" with io.open('README.rst', encoding="utf8") as file: long_description = file.read() setup( name='pychemqt', author='Juan José Gómez Romera', author_email='jjgomera@gmail.com', url='https://github.com/jjgomera/pychemqt', description='pychemqt is intended to be a free software tool for ' 'calculation and design of unit operations in chemical ' 'engineering.', long_description=long_description, license="gpl v3", version=__version__, packages=find_packages(exclude=["iapws"]), package_data={'': ['../README.rst', '../LICENSE'], 'images': ["*.png", "*/*.png", "*.jpg", "*/*.jpg", "*/*.svg", "*/*.gif"], 'docs': ["*.rst"], 'dat': ["*"], 'i18n': ["*"], 'Samples': ["*.pcq"], }, exclude_package_data={'docs': ['*.mEoS.*.rst', "*_ref.rst"]}, install_requires=['scipy>=0.14', 'numpy>=1.8', 'matplotlib>=1.4', 'iapws>=1.3'], extras_require={ 'CoolProp': ["CoolProp>=6.1.0"], 'openbabel': ["openbabel>=2.4.1"], 'spreadsheet': ["openpyxl>=2.3.0", "xlwt>=1.2.0", "ezodf>=0.3.2"], 'icu': ["PyICU>=2.1"], 'reportlab': ["reportlab>=3.5.8"]}, classifiers=[ "Development Status :: 3 - Alpha", "Environment :: X11 Applications :: Qt", "Intended Audience :: Education", "Intended Audience :: Science/Research", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Topic :: Scientific/Engineering", "Topic :: Scientific/Engineering :: Chemistry", "Topic :: Scientific/Engineering :: Physics"] )
gpl-3.0
CodeMonkeyJan/hyperspy
hyperspy/drawing/_widgets/label.py
3
3731
# -*- coding: utf-8 -*- # Copyright 2007-2016 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # HyperSpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with HyperSpy. If not, see <http://www.gnu.org/licenses/>. import numpy as np import matplotlib.transforms as transforms from hyperspy.drawing.widgets import Widget1DBase class LabelWidget(Widget1DBase): """A draggable text widget. Adds the attributes 'string', 'text_color' and 'bbox'. These are all arguments for matplotlib's Text artist. The default y-coordinate of the label is set to 0.9. """ def __init__(self, axes_manager): super(LabelWidget, self).__init__(axes_manager) self._string = '' self._snap_position = False if not self.axes: self._pos = np.array((0, 0.9)) self.text_color = 'black' self.bbox = None def _get_string(self): return self._string def _set_string(self, value): if self._string == value: return self._string = value self._update_patch_string() string = property(lambda s: s._get_string(), lambda s, v: s._set_string(v)) def _set_position(self, position): try: size = len(position) except TypeError: position = (position, self._pos[1]) else: if size < 2: position = np.concatenate((position, self._pos[1:])) super(LabelWidget, self)._set_position(position) def _set_axes(self, axes): super(LabelWidget, self)._set_axes(axes) if len(self.axes) == 1: self._pos = np.array((self.axes[0].offset, 0.9)) else: self._pos = np.array((self.axes[0].offset, self.axes[1].offset)) def _validate_pos(self, pos): if len(self.axes) == 1: pos = np.maximum(pos, self.axes[0].low_value) pos = np.minimum(pos, self.axes[0].high_value) elif len(self.axes) > 1: pos = np.maximum(pos, [a.low_value for a in self.axes[0:2]]) pos = np.minimum(pos, [a.high_value for a in self.axes[0:2]]) else: raise ValueError() return pos def _update_patch_position(self): if self.is_on() and self.patch: self.patch[0].set_x(self._pos[0]) self.patch[0].set_y(self._pos[1]) self.draw_patch() def _update_patch_string(self): if self.is_on() and self.patch: self.patch[0].set_text(self.string) self.draw_patch() def _set_patch(self): ax = self.ax trans = transforms.blended_transform_factory( ax.transData, ax.transAxes) self.patch = [ax.text( self._pos[0], self._pos[1], self.string, color=self.text_color, picker=5, transform=trans, horizontalalignment='left', bbox=self.bbox, animated=self.blit)] def _onmousemove(self, event): """on mouse motion draw the cursor if picked""" if self.picked is True and event.inaxes: self.position = (event.xdata, event.ydata)
gpl-3.0
davidlmorton/spikepy
spikepy/plotting_utils/import_matplotlib.py
1
1221
# Copyright (C) 2012 David Morton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import matplotlib # breaks pep-8 to put code here, but matplotlib # requires this before importing wxagg backend matplotlib.use('WXAgg', warn=False) from matplotlib.backends.backend_wxagg import \ FigureCanvasWxAgg as Canvas, \ NavigationToolbar2WxAgg as Toolbar from matplotlib.figure import Figure from matplotlib.ticker import MaxNLocator from matplotlib import ticker from matplotlib.dates import num2date __all__ = ['matplotlib', 'Canvas', 'Toolbar', 'Figure', 'MaxNLocator', 'ticker', 'num2date']
gpl-3.0
boomsbloom/dtm-fmri
DTM/for_gensim/lib/python2.7/site-packages/pandas/tests/formats/test_format.py
7
165663
# -*- coding: utf-8 -*- # TODO(wesm): lots of issues making flake8 hard # flake8: noqa from __future__ import print_function from distutils.version import LooseVersion import re from pandas.compat import (range, zip, lrange, StringIO, PY3, u, lzip, is_platform_windows, is_platform_32bit) import pandas.compat as compat import itertools from operator import methodcaller import os import sys from textwrap import dedent import warnings from numpy import nan from numpy.random import randn import numpy as np import codecs div_style = '' try: import IPython if IPython.__version__ < LooseVersion('3.0.0'): div_style = ' style="max-width:1500px;overflow:auto;"' except (ImportError, AttributeError): pass from pandas import DataFrame, Series, Index, Timestamp, MultiIndex, date_range, NaT import pandas.formats.format as fmt import pandas.util.testing as tm import pandas.core.common as com import pandas.formats.printing as printing from pandas.util.terminal import get_terminal_size import pandas as pd from pandas.core.config import (set_option, get_option, option_context, reset_option) from datetime import datetime import nose use_32bit_repr = is_platform_windows() or is_platform_32bit() _frame = DataFrame(tm.getSeriesData()) def curpath(): pth, _ = os.path.split(os.path.abspath(__file__)) return pth def has_info_repr(df): r = repr(df) c1 = r.split('\n')[0].startswith("<class") c2 = r.split('\n')[0].startswith(r"&lt;class") # _repr_html_ return c1 or c2 def has_non_verbose_info_repr(df): has_info = has_info_repr(df) r = repr(df) nv = len(r.split( '\n')) == 6 # 1. <class>, 2. Index, 3. Columns, 4. dtype, 5. memory usage, 6. trailing newline return has_info and nv def has_horizontally_truncated_repr(df): try: # Check header row fst_line = np.array(repr(df).splitlines()[0].split()) cand_col = np.where(fst_line == '...')[0][0] except: return False # Make sure each row has this ... in the same place r = repr(df) for ix, l in enumerate(r.splitlines()): if not r.split()[cand_col] == '...': return False return True def has_vertically_truncated_repr(df): r = repr(df) only_dot_row = False for row in r.splitlines(): if re.match(r'^[\.\ ]+$', row): only_dot_row = True return only_dot_row def has_truncated_repr(df): return has_horizontally_truncated_repr( df) or has_vertically_truncated_repr(df) def has_doubly_truncated_repr(df): return has_horizontally_truncated_repr( df) and has_vertically_truncated_repr(df) def has_expanded_repr(df): r = repr(df) for line in r.split('\n'): if line.endswith('\\'): return True return False class TestDataFrameFormatting(tm.TestCase): _multiprocess_can_split_ = True def setUp(self): self.warn_filters = warnings.filters warnings.filterwarnings('ignore', category=FutureWarning, module=".*format") self.frame = _frame.copy() def tearDown(self): warnings.filters = self.warn_filters def test_repr_embedded_ndarray(self): arr = np.empty(10, dtype=[('err', object)]) for i in range(len(arr)): arr['err'][i] = np.random.randn(i) df = DataFrame(arr) repr(df['err']) repr(df) df.to_string() def test_eng_float_formatter(self): self.frame.ix[5] = 0 fmt.set_eng_float_format() repr(self.frame) fmt.set_eng_float_format(use_eng_prefix=True) repr(self.frame) fmt.set_eng_float_format(accuracy=0) repr(self.frame) self.reset_display_options() def test_show_null_counts(self): df = DataFrame(1, columns=range(10), index=range(10)) df.iloc[1, 1] = np.nan def check(null_counts, result): buf = StringIO() df.info(buf=buf, null_counts=null_counts) self.assertTrue(('non-null' in buf.getvalue()) is result) with option_context('display.max_info_rows', 20, 'display.max_info_columns', 20): check(None, True) check(True, True) check(False, False) with option_context('display.max_info_rows', 5, 'display.max_info_columns', 5): check(None, False) check(True, False) check(False, False) def test_repr_tuples(self): buf = StringIO() df = DataFrame({'tups': lzip(range(10), range(10))}) repr(df) df.to_string(col_space=10, buf=buf) def test_repr_truncation(self): max_len = 20 with option_context("display.max_colwidth", max_len): df = DataFrame({'A': np.random.randn(10), 'B': [tm.rands(np.random.randint( max_len - 1, max_len + 1)) for i in range(10) ]}) r = repr(df) r = r[r.find('\n') + 1:] adj = fmt._get_adjustment() for line, value in lzip(r.split('\n'), df['B']): if adj.len(value) + 1 > max_len: self.assertIn('...', line) else: self.assertNotIn('...', line) with option_context("display.max_colwidth", 999999): self.assertNotIn('...', repr(df)) with option_context("display.max_colwidth", max_len + 2): self.assertNotIn('...', repr(df)) def test_repr_chop_threshold(self): df = DataFrame([[0.1, 0.5], [0.5, -0.1]]) pd.reset_option("display.chop_threshold") # default None self.assertEqual(repr(df), ' 0 1\n0 0.1 0.5\n1 0.5 -0.1') with option_context("display.chop_threshold", 0.2): self.assertEqual(repr(df), ' 0 1\n0 0.0 0.5\n1 0.5 0.0') with option_context("display.chop_threshold", 0.6): self.assertEqual(repr(df), ' 0 1\n0 0.0 0.0\n1 0.0 0.0') with option_context("display.chop_threshold", None): self.assertEqual(repr(df), ' 0 1\n0 0.1 0.5\n1 0.5 -0.1') def test_repr_obeys_max_seq_limit(self): with option_context("display.max_seq_items", 2000): self.assertTrue(len(printing.pprint_thing(lrange(1000))) > 1000) with option_context("display.max_seq_items", 5): self.assertTrue(len(printing.pprint_thing(lrange(1000))) < 100) def test_repr_set(self): self.assertEqual(printing.pprint_thing(set([1])), '{1}') def test_repr_is_valid_construction_code(self): # for the case of Index, where the repr is traditional rather then # stylized idx = Index(['a', 'b']) res = eval("pd." + repr(idx)) tm.assert_series_equal(Series(res), Series(idx)) def test_repr_should_return_str(self): # http://docs.python.org/py3k/reference/datamodel.html#object.__repr__ # http://docs.python.org/reference/datamodel.html#object.__repr__ # "...The return value must be a string object." # (str on py2.x, str (unicode) on py3) data = [8, 5, 3, 5] index1 = [u("\u03c3"), u("\u03c4"), u("\u03c5"), u("\u03c6")] cols = [u("\u03c8")] df = DataFrame(data, columns=cols, index=index1) self.assertTrue(type(df.__repr__()) == str) # both py2 / 3 def test_repr_no_backslash(self): with option_context('mode.sim_interactive', True): df = DataFrame(np.random.randn(10, 4)) self.assertTrue('\\' not in repr(df)) def test_expand_frame_repr(self): df_small = DataFrame('hello', [0], [0]) df_wide = DataFrame('hello', [0], lrange(10)) df_tall = DataFrame('hello', lrange(30), lrange(5)) with option_context('mode.sim_interactive', True): with option_context('display.max_columns', 10, 'display.width', 20, 'display.max_rows', 20, 'display.show_dimensions', True): with option_context('display.expand_frame_repr', True): self.assertFalse(has_truncated_repr(df_small)) self.assertFalse(has_expanded_repr(df_small)) self.assertFalse(has_truncated_repr(df_wide)) self.assertTrue(has_expanded_repr(df_wide)) self.assertTrue(has_vertically_truncated_repr(df_tall)) self.assertTrue(has_expanded_repr(df_tall)) with option_context('display.expand_frame_repr', False): self.assertFalse(has_truncated_repr(df_small)) self.assertFalse(has_expanded_repr(df_small)) self.assertFalse(has_horizontally_truncated_repr(df_wide)) self.assertFalse(has_expanded_repr(df_wide)) self.assertTrue(has_vertically_truncated_repr(df_tall)) self.assertFalse(has_expanded_repr(df_tall)) def test_repr_non_interactive(self): # in non interactive mode, there can be no dependency on the # result of terminal auto size detection df = DataFrame('hello', lrange(1000), lrange(5)) with option_context('mode.sim_interactive', False, 'display.width', 0, 'display.height', 0, 'display.max_rows', 5000): self.assertFalse(has_truncated_repr(df)) self.assertFalse(has_expanded_repr(df)) def test_repr_max_columns_max_rows(self): term_width, term_height = get_terminal_size() if term_width < 10 or term_height < 10: raise nose.SkipTest("terminal size too small, " "{0} x {1}".format(term_width, term_height)) def mkframe(n): index = ['%05d' % i for i in range(n)] return DataFrame(0, index, index) df6 = mkframe(6) df10 = mkframe(10) with option_context('mode.sim_interactive', True): with option_context('display.width', term_width * 2): with option_context('display.max_rows', 5, 'display.max_columns', 5): self.assertFalse(has_expanded_repr(mkframe(4))) self.assertFalse(has_expanded_repr(mkframe(5))) self.assertFalse(has_expanded_repr(df6)) self.assertTrue(has_doubly_truncated_repr(df6)) with option_context('display.max_rows', 20, 'display.max_columns', 10): # Out off max_columns boundary, but no extending # since not exceeding width self.assertFalse(has_expanded_repr(df6)) self.assertFalse(has_truncated_repr(df6)) with option_context('display.max_rows', 9, 'display.max_columns', 10): # out vertical bounds can not result in exanded repr self.assertFalse(has_expanded_repr(df10)) self.assertTrue(has_vertically_truncated_repr(df10)) # width=None in terminal, auto detection with option_context('display.max_columns', 100, 'display.max_rows', term_width * 20, 'display.width', None): df = mkframe((term_width // 7) - 2) self.assertFalse(has_expanded_repr(df)) df = mkframe((term_width // 7) + 2) printing.pprint_thing(df._repr_fits_horizontal_()) self.assertTrue(has_expanded_repr(df)) def test_str_max_colwidth(self): # GH 7856 df = pd.DataFrame([{'a': 'foo', 'b': 'bar', 'c': 'uncomfortably long line with lots of stuff', 'd': 1}, {'a': 'foo', 'b': 'bar', 'c': 'stuff', 'd': 1}]) df.set_index(['a', 'b', 'c']) self.assertTrue( str(df) == ' a b c d\n' '0 foo bar uncomfortably long line with lots of stuff 1\n' '1 foo bar stuff 1') with option_context('max_colwidth', 20): self.assertTrue(str(df) == ' a b c d\n' '0 foo bar uncomfortably lo... 1\n' '1 foo bar stuff 1') def test_auto_detect(self): term_width, term_height = get_terminal_size() fac = 1.05 # Arbitrary large factor to exceed term widht cols = range(int(term_width * fac)) index = range(10) df = DataFrame(index=index, columns=cols) with option_context('mode.sim_interactive', True): with option_context('max_rows', None): with option_context('max_columns', None): # Wrap around with None self.assertTrue(has_expanded_repr(df)) with option_context('max_rows', 0): with option_context('max_columns', 0): # Truncate with auto detection. self.assertTrue(has_horizontally_truncated_repr(df)) index = range(int(term_height * fac)) df = DataFrame(index=index, columns=cols) with option_context('max_rows', 0): with option_context('max_columns', None): # Wrap around with None self.assertTrue(has_expanded_repr(df)) # Truncate vertically self.assertTrue(has_vertically_truncated_repr(df)) with option_context('max_rows', None): with option_context('max_columns', 0): self.assertTrue(has_horizontally_truncated_repr(df)) def test_to_string_repr_unicode(self): buf = StringIO() unicode_values = [u('\u03c3')] * 10 unicode_values = np.array(unicode_values, dtype=object) df = DataFrame({'unicode': unicode_values}) df.to_string(col_space=10, buf=buf) # it works! repr(df) idx = Index(['abc', u('\u03c3a'), 'aegdvg']) ser = Series(np.random.randn(len(idx)), idx) rs = repr(ser).split('\n') line_len = len(rs[0]) for line in rs[1:]: try: line = line.decode(get_option("display.encoding")) except: pass if not line.startswith('dtype:'): self.assertEqual(len(line), line_len) # it works even if sys.stdin in None _stdin = sys.stdin try: sys.stdin = None repr(df) finally: sys.stdin = _stdin def test_to_string_unicode_columns(self): df = DataFrame({u('\u03c3'): np.arange(10.)}) buf = StringIO() df.to_string(buf=buf) buf.getvalue() buf = StringIO() df.info(buf=buf) buf.getvalue() result = self.frame.to_string() tm.assertIsInstance(result, compat.text_type) def test_to_string_utf8_columns(self): n = u("\u05d0").encode('utf-8') with option_context('display.max_rows', 1): df = DataFrame([1, 2], columns=[n]) repr(df) def test_to_string_unicode_two(self): dm = DataFrame({u('c/\u03c3'): []}) buf = StringIO() dm.to_string(buf) def test_to_string_unicode_three(self): dm = DataFrame(['\xc2']) buf = StringIO() dm.to_string(buf) def test_to_string_with_formatters(self): df = DataFrame({'int': [1, 2, 3], 'float': [1.0, 2.0, 3.0], 'object': [(1, 2), True, False]}, columns=['int', 'float', 'object']) formatters = [('int', lambda x: '0x%x' % x), ('float', lambda x: '[% 4.1f]' % x), ('object', lambda x: '-%s-' % str(x))] result = df.to_string(formatters=dict(formatters)) result2 = df.to_string(formatters=lzip(*formatters)[1]) self.assertEqual(result, (' int float object\n' '0 0x1 [ 1.0] -(1, 2)-\n' '1 0x2 [ 2.0] -True-\n' '2 0x3 [ 3.0] -False-')) self.assertEqual(result, result2) def test_to_string_with_datetime64_monthformatter(self): months = [datetime(2016, 1, 1), datetime(2016, 2, 2)] x = DataFrame({'months': months}) def format_func(x): return x.strftime('%Y-%m') result = x.to_string(formatters={'months': format_func}) expected = 'months\n0 2016-01\n1 2016-02' self.assertEqual(result.strip(), expected) def test_to_string_with_datetime64_hourformatter(self): x = DataFrame({'hod': pd.to_datetime(['10:10:10.100', '12:12:12.120'], format='%H:%M:%S.%f')}) def format_func(x): return x.strftime('%H:%M') result = x.to_string(formatters={'hod': format_func}) expected = 'hod\n0 10:10\n1 12:12' self.assertEqual(result.strip(), expected) def test_to_string_with_formatters_unicode(self): df = DataFrame({u('c/\u03c3'): [1, 2, 3]}) result = df.to_string(formatters={u('c/\u03c3'): lambda x: '%s' % x}) self.assertEqual(result, u(' c/\u03c3\n') + '0 1\n1 2\n2 3') def test_east_asian_unicode_frame(self): if PY3: _rep = repr else: _rep = unicode # not alighned properly because of east asian width # mid col df = DataFrame({'a': [u'あ', u'いいい', u'う', u'ええええええ'], 'b': [1, 222, 33333, 4]}, index=['a', 'bb', 'c', 'ddd']) expected = (u" a b\na あ 1\n" u"bb いいい 222\nc う 33333\n" u"ddd ええええええ 4") self.assertEqual(_rep(df), expected) # last col df = DataFrame({'a': [1, 222, 33333, 4], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=['a', 'bb', 'c', 'ddd']) expected = (u" a b\na 1 あ\n" u"bb 222 いいい\nc 33333 う\n" u"ddd 4 ええええええ") self.assertEqual(_rep(df), expected) # all col df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=['a', 'bb', 'c', 'ddd']) expected = (u" a b\na あああああ あ\n" u"bb い いいい\nc う う\n" u"ddd えええ ええええええ") self.assertEqual(_rep(df), expected) # column name df = DataFrame({u'あああああ': [1, 222, 33333, 4], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=['a', 'bb', 'c', 'ddd']) expected = (u" b あああああ\na あ 1\n" u"bb いいい 222\nc う 33333\n" u"ddd ええええええ 4") self.assertEqual(_rep(df), expected) # index df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=[u'あああ', u'いいいいいい', u'うう', u'え']) expected = (u" a b\nあああ あああああ あ\n" u"いいいいいい い いいい\nうう う う\n" u"え えええ ええええええ") self.assertEqual(_rep(df), expected) # index name df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=pd.Index([u'あ', u'い', u'うう', u'え'], name=u'おおおお')) expected = (u" a b\nおおおお \nあ あああああ あ\n" u"い い いいい\nうう う う\nえ えええ ええええええ" ) self.assertEqual(_rep(df), expected) # all df = DataFrame({u'あああ': [u'あああ', u'い', u'う', u'えええええ'], u'いいいいい': [u'あ', u'いいい', u'う', u'ええ']}, index=pd.Index([u'あ', u'いいい', u'うう', u'え'], name=u'お')) expected = (u" あああ いいいいい\nお \nあ あああ あ\n" u"いいい い いいい\nうう う う\nえ えええええ ええ") self.assertEqual(_rep(df), expected) # MultiIndex idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), ( u'おおお', u'かかかか'), (u'き', u'くく')]) df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=idx) expected = (u" a b\nあ いい あああああ あ\n" u"う え い いいい\nおおお かかかか う う\n" u"き くく えええ ええええええ") self.assertEqual(_rep(df), expected) # truncate with option_context('display.max_rows', 3, 'display.max_columns', 3): df = pd.DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], 'b': [u'あ', u'いいい', u'う', u'ええええええ'], 'c': [u'お', u'か', u'ききき', u'くくくくくく'], u'ああああ': [u'さ', u'し', u'す', u'せ']}, columns=['a', 'b', 'c', u'ああああ']) expected = (u" a ... ああああ\n0 あああああ ... さ\n" u".. ... ... ...\n3 えええ ... せ\n" u"\n[4 rows x 4 columns]") self.assertEqual(_rep(df), expected) df.index = [u'あああ', u'いいいい', u'う', 'aaa'] expected = (u" a ... ああああ\nあああ あああああ ... さ\n" u".. ... ... ...\naaa えええ ... せ\n" u"\n[4 rows x 4 columns]") self.assertEqual(_rep(df), expected) # Emable Unicode option ----------------------------------------- with option_context('display.unicode.east_asian_width', True): # mid col df = DataFrame({'a': [u'あ', u'いいい', u'う', u'ええええええ'], 'b': [1, 222, 33333, 4]}, index=['a', 'bb', 'c', 'ddd']) expected = (u" a b\na あ 1\n" u"bb いいい 222\nc う 33333\n" u"ddd ええええええ 4") self.assertEqual(_rep(df), expected) # last col df = DataFrame({'a': [1, 222, 33333, 4], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=['a', 'bb', 'c', 'ddd']) expected = (u" a b\na 1 あ\n" u"bb 222 いいい\nc 33333 う\n" u"ddd 4 ええええええ") self.assertEqual(_rep(df), expected) # all col df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=['a', 'bb', 'c', 'ddd']) expected = (u" a b\na あああああ あ\n" u"bb い いいい\nc う う\n" u"ddd えええ ええええええ" "") self.assertEqual(_rep(df), expected) # column name df = DataFrame({u'あああああ': [1, 222, 33333, 4], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=['a', 'bb', 'c', 'ddd']) expected = (u" b あああああ\na あ 1\n" u"bb いいい 222\nc う 33333\n" u"ddd ええええええ 4") self.assertEqual(_rep(df), expected) # index df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=[u'あああ', u'いいいいいい', u'うう', u'え']) expected = (u" a b\nあああ あああああ あ\n" u"いいいいいい い いいい\nうう う う\n" u"え えええ ええええええ") self.assertEqual(_rep(df), expected) # index name df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=pd.Index([u'あ', u'い', u'うう', u'え'], name=u'おおおお')) expected = (u" a b\nおおおお \n" u"あ あああああ あ\nい い いいい\n" u"うう う う\nえ えええ ええええええ" ) self.assertEqual(_rep(df), expected) # all df = DataFrame({u'あああ': [u'あああ', u'い', u'う', u'えええええ'], u'いいいいい': [u'あ', u'いいい', u'う', u'ええ']}, index=pd.Index([u'あ', u'いいい', u'うう', u'え'], name=u'お')) expected = (u" あああ いいいいい\nお \n" u"あ あああ あ\nいいい い いいい\n" u"うう う う\nえ えええええ ええ") self.assertEqual(_rep(df), expected) # MultiIndex idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), ( u'おおお', u'かかかか'), (u'き', u'くく')]) df = DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], 'b': [u'あ', u'いいい', u'う', u'ええええええ']}, index=idx) expected = (u" a b\nあ いい あああああ あ\n" u"う え い いいい\nおおお かかかか う う\n" u"き くく えええ ええええええ") self.assertEqual(_rep(df), expected) # truncate with option_context('display.max_rows', 3, 'display.max_columns', 3): df = pd.DataFrame({'a': [u'あああああ', u'い', u'う', u'えええ'], 'b': [u'あ', u'いいい', u'う', u'ええええええ'], 'c': [u'お', u'か', u'ききき', u'くくくくくく'], u'ああああ': [u'さ', u'し', u'す', u'せ']}, columns=['a', 'b', 'c', u'ああああ']) expected = (u" a ... ああああ\n0 あああああ ... さ\n" u".. ... ... ...\n3 えええ ... せ\n" u"\n[4 rows x 4 columns]") self.assertEqual(_rep(df), expected) df.index = [u'あああ', u'いいいい', u'う', 'aaa'] expected = (u" a ... ああああ\nあああ あああああ ... さ\n" u"... ... ... ...\naaa えええ ... せ\n" u"\n[4 rows x 4 columns]") self.assertEqual(_rep(df), expected) # ambiguous unicode df = DataFrame({u'あああああ': [1, 222, 33333, 4], 'b': [u'あ', u'いいい', u'¡¡', u'ええええええ']}, index=['a', 'bb', 'c', '¡¡¡']) expected = (u" b あああああ\na あ 1\n" u"bb いいい 222\nc ¡¡ 33333\n" u"¡¡¡ ええええええ 4") self.assertEqual(_rep(df), expected) def test_to_string_buffer_all_unicode(self): buf = StringIO() empty = DataFrame({u('c/\u03c3'): Series()}) nonempty = DataFrame({u('c/\u03c3'): Series([1, 2, 3])}) print(empty, file=buf) print(nonempty, file=buf) # this should work buf.getvalue() def test_to_string_with_col_space(self): df = DataFrame(np.random.random(size=(1, 3))) c10 = len(df.to_string(col_space=10).split("\n")[1]) c20 = len(df.to_string(col_space=20).split("\n")[1]) c30 = len(df.to_string(col_space=30).split("\n")[1]) self.assertTrue(c10 < c20 < c30) # GH 8230 # col_space wasn't being applied with header=False with_header = df.to_string(col_space=20) with_header_row1 = with_header.splitlines()[1] no_header = df.to_string(col_space=20, header=False) self.assertEqual(len(with_header_row1), len(no_header)) def test_to_string_truncate_indices(self): for index in [tm.makeStringIndex, tm.makeUnicodeIndex, tm.makeIntIndex, tm.makeDateIndex, tm.makePeriodIndex]: for column in [tm.makeStringIndex]: for h in [10, 20]: for w in [10, 20]: with option_context("display.expand_frame_repr", False): df = DataFrame(index=index(h), columns=column(w)) with option_context("display.max_rows", 15): if h == 20: self.assertTrue( has_vertically_truncated_repr(df)) else: self.assertFalse( has_vertically_truncated_repr(df)) with option_context("display.max_columns", 15): if w == 20: self.assertTrue( has_horizontally_truncated_repr(df)) else: self.assertFalse( has_horizontally_truncated_repr(df)) with option_context("display.max_rows", 15, "display.max_columns", 15): if h == 20 and w == 20: self.assertTrue(has_doubly_truncated_repr( df)) else: self.assertFalse(has_doubly_truncated_repr( df)) def test_to_string_truncate_multilevel(self): arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] df = DataFrame(index=arrays, columns=arrays) with option_context("display.max_rows", 7, "display.max_columns", 7): self.assertTrue(has_doubly_truncated_repr(df)) def test_truncate_with_different_dtypes(self): # 11594, 12045 # when truncated the dtypes of the splits can differ # 11594 import datetime s = Series([datetime.datetime(2012, 1, 1)]*10 + [datetime.datetime(1012,1,2)] + [datetime.datetime(2012, 1, 3)]*10) with pd.option_context('display.max_rows', 8): result = str(s) self.assertTrue('object' in result) # 12045 df = DataFrame({'text': ['some words'] + [None]*9}) with pd.option_context('display.max_rows', 8, 'display.max_columns', 3): result = str(df) self.assertTrue('None' in result) self.assertFalse('NaN' in result) def test_datetimelike_frame(self): # GH 12211 df = DataFrame({'date' : [pd.Timestamp('20130101').tz_localize('UTC')] + [pd.NaT]*5}) with option_context("display.max_rows", 5): result = str(df) self.assertTrue('2013-01-01 00:00:00+00:00' in result) self.assertTrue('NaT' in result) self.assertTrue('...' in result) self.assertTrue('[6 rows x 1 columns]' in result) dts = [pd.Timestamp('2011-01-01', tz='US/Eastern')] * 5 + [pd.NaT] * 5 df = pd.DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}) with option_context('display.max_rows', 5): expected = (' dt x\n' '0 2011-01-01 00:00:00-05:00 1\n' '1 2011-01-01 00:00:00-05:00 2\n' '.. ... ..\n' '8 NaT 9\n' '9 NaT 10\n\n' '[10 rows x 2 columns]') self.assertEqual(repr(df), expected) dts = [pd.NaT] * 5 + [pd.Timestamp('2011-01-01', tz='US/Eastern')] * 5 df = pd.DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}) with option_context('display.max_rows', 5): expected = (' dt x\n' '0 NaT 1\n' '1 NaT 2\n' '.. ... ..\n' '8 2011-01-01 00:00:00-05:00 9\n' '9 2011-01-01 00:00:00-05:00 10\n\n' '[10 rows x 2 columns]') self.assertEqual(repr(df), expected) dts = ([pd.Timestamp('2011-01-01', tz='Asia/Tokyo')] * 5 + [pd.Timestamp('2011-01-01', tz='US/Eastern')] * 5) df = pd.DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}) with option_context('display.max_rows', 5): expected = (' dt x\n' '0 2011-01-01 00:00:00+09:00 1\n' '1 2011-01-01 00:00:00+09:00 2\n' '.. ... ..\n' '8 2011-01-01 00:00:00-05:00 9\n' '9 2011-01-01 00:00:00-05:00 10\n\n' '[10 rows x 2 columns]') self.assertEqual(repr(df), expected) def test_to_html_with_col_space(self): def check_with_width(df, col_space): import re # check that col_space affects HTML generation # and be very brittle about it. html = df.to_html(col_space=col_space) hdrs = [x for x in html.split(r"\n") if re.search(r"<th[>\s]", x)] self.assertTrue(len(hdrs) > 0) for h in hdrs: self.assertTrue("min-width" in h) self.assertTrue(str(col_space) in h) df = DataFrame(np.random.random(size=(1, 3))) check_with_width(df, 30) check_with_width(df, 50) def test_to_html_with_empty_string_label(self): # GH3547, to_html regards empty string labels as repeated labels data = {'c1': ['a', 'b'], 'c2': ['a', ''], 'data': [1, 2]} df = DataFrame(data).set_index(['c1', 'c2']) res = df.to_html() self.assertTrue("rowspan" not in res) def test_to_html_unicode(self): df = DataFrame({u('\u03c3'): np.arange(10.)}) expected = u'<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>\u03c3</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0.0</td>\n </tr>\n <tr>\n <th>1</th>\n <td>1.0</td>\n </tr>\n <tr>\n <th>2</th>\n <td>2.0</td>\n </tr>\n <tr>\n <th>3</th>\n <td>3.0</td>\n </tr>\n <tr>\n <th>4</th>\n <td>4.0</td>\n </tr>\n <tr>\n <th>5</th>\n <td>5.0</td>\n </tr>\n <tr>\n <th>6</th>\n <td>6.0</td>\n </tr>\n <tr>\n <th>7</th>\n <td>7.0</td>\n </tr>\n <tr>\n <th>8</th>\n <td>8.0</td>\n </tr>\n <tr>\n <th>9</th>\n <td>9.0</td>\n </tr>\n </tbody>\n</table>' self.assertEqual(df.to_html(), expected) df = DataFrame({'A': [u('\u03c3')]}) expected = u'<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>A</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>\u03c3</td>\n </tr>\n </tbody>\n</table>' self.assertEqual(df.to_html(), expected) def test_to_html_decimal(self): # GH 12031 df = DataFrame({'A': [6.0, 3.1, 2.2]}) result = df.to_html(decimal=',') expected = ('<table border="1" class="dataframe">\n' ' <thead>\n' ' <tr style="text-align: right;">\n' ' <th></th>\n' ' <th>A</th>\n' ' </tr>\n' ' </thead>\n' ' <tbody>\n' ' <tr>\n' ' <th>0</th>\n' ' <td>6,0</td>\n' ' </tr>\n' ' <tr>\n' ' <th>1</th>\n' ' <td>3,1</td>\n' ' </tr>\n' ' <tr>\n' ' <th>2</th>\n' ' <td>2,2</td>\n' ' </tr>\n' ' </tbody>\n' '</table>') self.assertEqual(result, expected) def test_to_html_escaped(self): a = 'str<ing1 &amp;' b = 'stri>ng2 &amp;' test_dict = {'co<l1': {a: "<type 'str'>", b: "<type 'str'>"}, 'co>l2': {a: "<type 'str'>", b: "<type 'str'>"}} rs = DataFrame(test_dict).to_html() xp = """<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>co&lt;l1</th> <th>co&gt;l2</th> </tr> </thead> <tbody> <tr> <th>str&lt;ing1 &amp;amp;</th> <td>&lt;type 'str'&gt;</td> <td>&lt;type 'str'&gt;</td> </tr> <tr> <th>stri&gt;ng2 &amp;amp;</th> <td>&lt;type 'str'&gt;</td> <td>&lt;type 'str'&gt;</td> </tr> </tbody> </table>""" self.assertEqual(xp, rs) def test_to_html_escape_disabled(self): a = 'str<ing1 &amp;' b = 'stri>ng2 &amp;' test_dict = {'co<l1': {a: "<b>bold</b>", b: "<b>bold</b>"}, 'co>l2': {a: "<b>bold</b>", b: "<b>bold</b>"}} rs = DataFrame(test_dict).to_html(escape=False) xp = """<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>co<l1</th> <th>co>l2</th> </tr> </thead> <tbody> <tr> <th>str<ing1 &amp;</th> <td><b>bold</b></td> <td><b>bold</b></td> </tr> <tr> <th>stri>ng2 &amp;</th> <td><b>bold</b></td> <td><b>bold</b></td> </tr> </tbody> </table>""" self.assertEqual(xp, rs) def test_to_html_multiindex_index_false(self): # issue 8452 df = DataFrame({ 'a': range(2), 'b': range(3, 5), 'c': range(5, 7), 'd': range(3, 5) }) df.columns = MultiIndex.from_product([['a', 'b'], ['c', 'd']]) result = df.to_html(index=False) expected = """\ <table border="1" class="dataframe"> <thead> <tr> <th colspan="2" halign="left">a</th> <th colspan="2" halign="left">b</th> </tr> <tr> <th>c</th> <th>d</th> <th>c</th> <th>d</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>3</td> <td>5</td> <td>3</td> </tr> <tr> <td>1</td> <td>4</td> <td>6</td> <td>4</td> </tr> </tbody> </table>""" self.assertEqual(result, expected) df.index = Index(df.index.values, name='idx') result = df.to_html(index=False) self.assertEqual(result, expected) def test_to_html_multiindex_sparsify_false_multi_sparse(self): with option_context('display.multi_sparse', False): index = MultiIndex.from_arrays([[0, 0, 1, 1], [0, 1, 0, 1]], names=['foo', None]) df = DataFrame([[0, 1], [2, 3], [4, 5], [6, 7]], index=index) result = df.to_html() expected = """\ <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th></th> <th>0</th> <th>1</th> </tr> <tr> <th>foo</th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>0</th> <th>0</th> <td>0</td> <td>1</td> </tr> <tr> <th>0</th> <th>1</th> <td>2</td> <td>3</td> </tr> <tr> <th>1</th> <th>0</th> <td>4</td> <td>5</td> </tr> <tr> <th>1</th> <th>1</th> <td>6</td> <td>7</td> </tr> </tbody> </table>""" self.assertEqual(result, expected) df = DataFrame([[0, 1], [2, 3], [4, 5], [6, 7]], columns=index[::2], index=index) result = df.to_html() expected = """\ <table border="1" class="dataframe"> <thead> <tr> <th></th> <th>foo</th> <th>0</th> <th>1</th> </tr> <tr> <th></th> <th></th> <th>0</th> <th>0</th> </tr> <tr> <th>foo</th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>0</th> <th>0</th> <td>0</td> <td>1</td> </tr> <tr> <th>0</th> <th>1</th> <td>2</td> <td>3</td> </tr> <tr> <th>1</th> <th>0</th> <td>4</td> <td>5</td> </tr> <tr> <th>1</th> <th>1</th> <td>6</td> <td>7</td> </tr> </tbody> </table>""" self.assertEqual(result, expected) def test_to_html_multiindex_sparsify(self): index = MultiIndex.from_arrays([[0, 0, 1, 1], [0, 1, 0, 1]], names=['foo', None]) df = DataFrame([[0, 1], [2, 3], [4, 5], [6, 7]], index=index) result = df.to_html() expected = """<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th></th> <th>0</th> <th>1</th> </tr> <tr> <th>foo</th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th rowspan="2" valign="top">0</th> <th>0</th> <td>0</td> <td>1</td> </tr> <tr> <th>1</th> <td>2</td> <td>3</td> </tr> <tr> <th rowspan="2" valign="top">1</th> <th>0</th> <td>4</td> <td>5</td> </tr> <tr> <th>1</th> <td>6</td> <td>7</td> </tr> </tbody> </table>""" self.assertEqual(result, expected) df = DataFrame([[0, 1], [2, 3], [4, 5], [6, 7]], columns=index[::2], index=index) result = df.to_html() expected = """\ <table border="1" class="dataframe"> <thead> <tr> <th></th> <th>foo</th> <th>0</th> <th>1</th> </tr> <tr> <th></th> <th></th> <th>0</th> <th>0</th> </tr> <tr> <th>foo</th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th rowspan="2" valign="top">0</th> <th>0</th> <td>0</td> <td>1</td> </tr> <tr> <th>1</th> <td>2</td> <td>3</td> </tr> <tr> <th rowspan="2" valign="top">1</th> <th>0</th> <td>4</td> <td>5</td> </tr> <tr> <th>1</th> <td>6</td> <td>7</td> </tr> </tbody> </table>""" self.assertEqual(result, expected) def test_to_html_index_formatter(self): df = DataFrame([[0, 1], [2, 3], [4, 5], [6, 7]], columns=['foo', None], index=lrange(4)) f = lambda x: 'abcd' [x] result = df.to_html(formatters={'__index__': f}) expected = """\ <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>foo</th> <th>None</th> </tr> </thead> <tbody> <tr> <th>a</th> <td>0</td> <td>1</td> </tr> <tr> <th>b</th> <td>2</td> <td>3</td> </tr> <tr> <th>c</th> <td>4</td> <td>5</td> </tr> <tr> <th>d</th> <td>6</td> <td>7</td> </tr> </tbody> </table>""" self.assertEqual(result, expected) def test_to_html_datetime64_monthformatter(self): months = [datetime(2016, 1, 1), datetime(2016, 2, 2)] x = DataFrame({'months': months}) def format_func(x): return x.strftime('%Y-%m') result = x.to_html(formatters={'months': format_func}) expected = """\ <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>months</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>2016-01</td> </tr> <tr> <th>1</th> <td>2016-02</td> </tr> </tbody> </table>""" self.assertEqual(result, expected) def test_to_html_datetime64_hourformatter(self): x = DataFrame({'hod': pd.to_datetime(['10:10:10.100', '12:12:12.120'], format='%H:%M:%S.%f')}) def format_func(x): return x.strftime('%H:%M') result = x.to_html(formatters={'hod': format_func}) expected = """\ <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>hod</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>10:10</td> </tr> <tr> <th>1</th> <td>12:12</td> </tr> </tbody> </table>""" self.assertEqual(result, expected) def test_to_html_regression_GH6098(self): df = DataFrame({u('clé1'): [u('a'), u('a'), u('b'), u('b'), u('a')], u('clé2'): [u('1er'), u('2ème'), u('1er'), u('2ème'), u('1er')], 'données1': np.random.randn(5), 'données2': np.random.randn(5)}) # it works df.pivot_table(index=[u('clé1')], columns=[u('clé2')])._repr_html_() def test_to_html_truncate(self): raise nose.SkipTest("unreliable on travis") index = pd.DatetimeIndex(start='20010101', freq='D', periods=20) df = DataFrame(index=index, columns=range(20)) fmt.set_option('display.max_rows', 8) fmt.set_option('display.max_columns', 4) result = df._repr_html_() expected = '''\ <div{0}> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>0</th> <th>1</th> <th>...</th> <th>18</th> <th>19</th> </tr> </thead> <tbody> <tr> <th>2001-01-01</th> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>2001-01-02</th> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>2001-01-03</th> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>2001-01-04</th> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>2001-01-17</th> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>2001-01-18</th> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>2001-01-19</th> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>2001-01-20</th> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> </tr> </tbody> </table> <p>20 rows × 20 columns</p> </div>'''.format(div_style) if compat.PY2: expected = expected.decode('utf-8') self.assertEqual(result, expected) def test_to_html_truncate_multi_index(self): raise nose.SkipTest("unreliable on travis") arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] df = DataFrame(index=arrays, columns=arrays) fmt.set_option('display.max_rows', 7) fmt.set_option('display.max_columns', 7) result = df._repr_html_() expected = '''\ <div{0}> <table border="1" class="dataframe"> <thead> <tr> <th></th> <th></th> <th colspan="2" halign="left">bar</th> <th>baz</th> <th>...</th> <th>foo</th> <th colspan="2" halign="left">qux</th> </tr> <tr> <th></th> <th></th> <th>one</th> <th>two</th> <th>one</th> <th>...</th> <th>two</th> <th>one</th> <th>two</th> </tr> </thead> <tbody> <tr> <th rowspan="2" valign="top">bar</th> <th>one</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>two</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>baz</th> <th>one</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>...</th> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>foo</th> <th>two</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th rowspan="2" valign="top">qux</th> <th>one</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>two</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> </tbody> </table> <p>8 rows × 8 columns</p> </div>'''.format(div_style) if compat.PY2: expected = expected.decode('utf-8') self.assertEqual(result, expected) def test_to_html_truncate_multi_index_sparse_off(self): raise nose.SkipTest("unreliable on travis") arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] df = DataFrame(index=arrays, columns=arrays) fmt.set_option('display.max_rows', 7) fmt.set_option('display.max_columns', 7) fmt.set_option('display.multi_sparse', False) result = df._repr_html_() expected = '''\ <div{0}> <table border="1" class="dataframe"> <thead> <tr> <th></th> <th></th> <th>bar</th> <th>bar</th> <th>baz</th> <th>...</th> <th>foo</th> <th>qux</th> <th>qux</th> </tr> <tr> <th></th> <th></th> <th>one</th> <th>two</th> <th>one</th> <th>...</th> <th>two</th> <th>one</th> <th>two</th> </tr> </thead> <tbody> <tr> <th>bar</th> <th>one</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>bar</th> <th>two</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>baz</th> <th>one</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>foo</th> <th>two</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>qux</th> <th>one</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <th>qux</th> <th>two</th> <td>NaN</td> <td>NaN</td> <td>NaN</td> <td>...</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> </tbody> </table> <p>8 rows × 8 columns</p> </div>'''.format(div_style) if compat.PY2: expected = expected.decode('utf-8') self.assertEqual(result, expected) def test_to_html_border(self): df = DataFrame({'A': [1, 2]}) result = df.to_html() assert 'border="1"' in result def test_to_html_border_option(self): df = DataFrame({'A': [1, 2]}) with pd.option_context('html.border', 0): result = df.to_html() self.assertTrue('border="0"' in result) self.assertTrue('border="0"' in df._repr_html_()) def test_to_html_border_zero(self): df = DataFrame({'A': [1, 2]}) result = df.to_html(border=0) self.assertTrue('border="0"' in result) def test_nonunicode_nonascii_alignment(self): df = DataFrame([["aa\xc3\xa4\xc3\xa4", 1], ["bbbb", 2]]) rep_str = df.to_string() lines = rep_str.split('\n') self.assertEqual(len(lines[1]), len(lines[2])) def test_unicode_problem_decoding_as_ascii(self): dm = DataFrame({u('c/\u03c3'): Series({'test': np.NaN})}) compat.text_type(dm.to_string()) def test_string_repr_encoding(self): filepath = tm.get_data_path('unicode_series.csv') df = pd.read_csv(filepath, header=None, encoding='latin1') repr(df) repr(df[1]) def test_repr_corner(self): # representing infs poses no problems df = DataFrame({'foo': [-np.inf, np.inf]}) repr(df) def test_frame_info_encoding(self): index = ['\'Til There Was You (1997)', 'ldum klaka (Cold Fever) (1994)'] fmt.set_option('display.max_rows', 1) df = DataFrame(columns=['a', 'b', 'c'], index=index) repr(df) repr(df.T) fmt.set_option('display.max_rows', 200) def test_pprint_thing(self): from pandas.formats.printing import pprint_thing as pp_t if PY3: raise nose.SkipTest("doesn't work on Python 3") self.assertEqual(pp_t('a'), u('a')) self.assertEqual(pp_t(u('a')), u('a')) self.assertEqual(pp_t(None), 'None') self.assertEqual(pp_t(u('\u05d0'), quote_strings=True), u("u'\u05d0'")) self.assertEqual(pp_t(u('\u05d0'), quote_strings=False), u('\u05d0')) self.assertEqual(pp_t((u('\u05d0'), u('\u05d1')), quote_strings=True), u("(u'\u05d0', u'\u05d1')")) self.assertEqual(pp_t((u('\u05d0'), (u('\u05d1'), u('\u05d2'))), quote_strings=True), u("(u'\u05d0', (u'\u05d1', u'\u05d2'))")) self.assertEqual(pp_t(('foo', u('\u05d0'), (u('\u05d0'), u('\u05d0'))), quote_strings=True), u("(u'foo', u'\u05d0', (u'\u05d0', u'\u05d0'))")) # escape embedded tabs in string # GH #2038 self.assertTrue(not "\t" in pp_t("a\tb", escape_chars=("\t", ))) def test_wide_repr(self): with option_context('mode.sim_interactive', True, 'display.show_dimensions', True): max_cols = get_option('display.max_columns') df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1))) set_option('display.expand_frame_repr', False) rep_str = repr(df) assert "10 rows x %d columns" % (max_cols - 1) in rep_str set_option('display.expand_frame_repr', True) wide_repr = repr(df) self.assertNotEqual(rep_str, wide_repr) with option_context('display.width', 120): wider_repr = repr(df) self.assertTrue(len(wider_repr) < len(wide_repr)) reset_option('display.expand_frame_repr') def test_wide_repr_wide_columns(self): with option_context('mode.sim_interactive', True): df = DataFrame(randn(5, 3), columns=['a' * 90, 'b' * 90, 'c' * 90]) rep_str = repr(df) self.assertEqual(len(rep_str.splitlines()), 20) def test_wide_repr_named(self): with option_context('mode.sim_interactive', True): max_cols = get_option('display.max_columns') df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1))) df.index.name = 'DataFrame Index' set_option('display.expand_frame_repr', False) rep_str = repr(df) set_option('display.expand_frame_repr', True) wide_repr = repr(df) self.assertNotEqual(rep_str, wide_repr) with option_context('display.width', 150): wider_repr = repr(df) self.assertTrue(len(wider_repr) < len(wide_repr)) for line in wide_repr.splitlines()[1::13]: self.assertIn('DataFrame Index', line) reset_option('display.expand_frame_repr') def test_wide_repr_multiindex(self): with option_context('mode.sim_interactive', True): midx = MultiIndex.from_arrays(tm.rands_array(5, size=(2, 10))) max_cols = get_option('display.max_columns') df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1)), index=midx) df.index.names = ['Level 0', 'Level 1'] set_option('display.expand_frame_repr', False) rep_str = repr(df) set_option('display.expand_frame_repr', True) wide_repr = repr(df) self.assertNotEqual(rep_str, wide_repr) with option_context('display.width', 150): wider_repr = repr(df) self.assertTrue(len(wider_repr) < len(wide_repr)) for line in wide_repr.splitlines()[1::13]: self.assertIn('Level 0 Level 1', line) reset_option('display.expand_frame_repr') def test_wide_repr_multiindex_cols(self): with option_context('mode.sim_interactive', True): max_cols = get_option('display.max_columns') midx = MultiIndex.from_arrays(tm.rands_array(5, size=(2, 10))) mcols = MultiIndex.from_arrays(tm.rands_array(3, size=(2, max_cols - 1))) df = DataFrame(tm.rands_array(25, (10, max_cols - 1)), index=midx, columns=mcols) df.index.names = ['Level 0', 'Level 1'] set_option('display.expand_frame_repr', False) rep_str = repr(df) set_option('display.expand_frame_repr', True) wide_repr = repr(df) self.assertNotEqual(rep_str, wide_repr) with option_context('display.width', 150): wider_repr = repr(df) self.assertTrue(len(wider_repr) < len(wide_repr)) reset_option('display.expand_frame_repr') def test_wide_repr_unicode(self): with option_context('mode.sim_interactive', True): max_cols = get_option('display.max_columns') df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1))) set_option('display.expand_frame_repr', False) rep_str = repr(df) set_option('display.expand_frame_repr', True) wide_repr = repr(df) self.assertNotEqual(rep_str, wide_repr) with option_context('display.width', 150): wider_repr = repr(df) self.assertTrue(len(wider_repr) < len(wide_repr)) reset_option('display.expand_frame_repr') def test_wide_repr_wide_long_columns(self): with option_context('mode.sim_interactive', True): df = DataFrame({'a': ['a' * 30, 'b' * 30], 'b': ['c' * 70, 'd' * 80]}) result = repr(df) self.assertTrue('ccccc' in result) self.assertTrue('ddddd' in result) def test_long_series(self): n = 1000 s = Series( np.random.randint(-50, 50, n), index=['s%04d' % x for x in range(n)], dtype='int64') import re str_rep = str(s) nmatches = len(re.findall('dtype', str_rep)) self.assertEqual(nmatches, 1) def test_index_with_nan(self): # GH 2850 df = DataFrame({'id1': {0: '1a3', 1: '9h4'}, 'id2': {0: np.nan, 1: 'd67'}, 'id3': {0: '78d', 1: '79d'}, 'value': {0: 123, 1: 64}}) # multi-index y = df.set_index(['id1', 'id2', 'id3']) result = y.to_string() expected = u( ' value\nid1 id2 id3 \n1a3 NaN 78d 123\n9h4 d67 79d 64') self.assertEqual(result, expected) # index y = df.set_index('id2') result = y.to_string() expected = u( ' id1 id3 value\nid2 \nNaN 1a3 78d 123\nd67 9h4 79d 64') self.assertEqual(result, expected) # with append (this failed in 0.12) y = df.set_index(['id1', 'id2']).set_index('id3', append=True) result = y.to_string() expected = u( ' value\nid1 id2 id3 \n1a3 NaN 78d 123\n9h4 d67 79d 64') self.assertEqual(result, expected) # all-nan in mi df2 = df.copy() df2.ix[:, 'id2'] = np.nan y = df2.set_index('id2') result = y.to_string() expected = u( ' id1 id3 value\nid2 \nNaN 1a3 78d 123\nNaN 9h4 79d 64') self.assertEqual(result, expected) # partial nan in mi df2 = df.copy() df2.ix[:, 'id2'] = np.nan y = df2.set_index(['id2', 'id3']) result = y.to_string() expected = u( ' id1 value\nid2 id3 \nNaN 78d 1a3 123\n 79d 9h4 64') self.assertEqual(result, expected) df = DataFrame({'id1': {0: np.nan, 1: '9h4'}, 'id2': {0: np.nan, 1: 'd67'}, 'id3': {0: np.nan, 1: '79d'}, 'value': {0: 123, 1: 64}}) y = df.set_index(['id1', 'id2', 'id3']) result = y.to_string() expected = u( ' value\nid1 id2 id3 \nNaN NaN NaN 123\n9h4 d67 79d 64') self.assertEqual(result, expected) def test_to_string(self): from pandas import read_table import re # big mixed biggie = DataFrame({'A': randn(200), 'B': tm.makeStringIndex(200)}, index=lrange(200)) biggie.loc[:20, 'A'] = nan biggie.loc[:20, 'B'] = nan s = biggie.to_string() buf = StringIO() retval = biggie.to_string(buf=buf) self.assertIsNone(retval) self.assertEqual(buf.getvalue(), s) tm.assertIsInstance(s, compat.string_types) # print in right order result = biggie.to_string(columns=['B', 'A'], col_space=17, float_format='%.5f'.__mod__) lines = result.split('\n') header = lines[0].strip().split() joined = '\n'.join([re.sub(r'\s+', ' ', x).strip() for x in lines[1:]]) recons = read_table(StringIO(joined), names=header, header=None, sep=' ') tm.assert_series_equal(recons['B'], biggie['B']) self.assertEqual(recons['A'].count(), biggie['A'].count()) self.assertTrue((np.abs(recons['A'].dropna() - biggie['A'].dropna()) < 0.1).all()) # expected = ['B', 'A'] # self.assertEqual(header, expected) result = biggie.to_string(columns=['A'], col_space=17) header = result.split('\n')[0].strip().split() expected = ['A'] self.assertEqual(header, expected) biggie.to_string(columns=['B', 'A'], formatters={'A': lambda x: '%.1f' % x}) biggie.to_string(columns=['B', 'A'], float_format=str) biggie.to_string(columns=['B', 'A'], col_space=12, float_format=str) frame = DataFrame(index=np.arange(200)) frame.to_string() def test_to_string_no_header(self): df = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]}) df_s = df.to_string(header=False) expected = "0 1 4\n1 2 5\n2 3 6" self.assertEqual(df_s, expected) def test_to_string_no_index(self): df = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]}) df_s = df.to_string(index=False) expected = "x y\n1 4\n2 5\n3 6" self.assertEqual(df_s, expected) def test_to_string_line_width_no_index(self): df = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]}) df_s = df.to_string(line_width=1, index=False) expected = "x \\\n1 \n2 \n3 \n\ny \n4 \n5 \n6" self.assertEqual(df_s, expected) def test_to_string_float_formatting(self): self.reset_display_options() fmt.set_option('display.precision', 5, 'display.column_space', 12, 'display.notebook_repr_html', False) df = DataFrame({'x': [0, 0.25, 3456.000, 12e+45, 1.64e+6, 1.7e+8, 1.253456, np.pi, -1e6]}) df_s = df.to_string() # Python 2.5 just wants me to be sad. And debian 32-bit # sys.version_info[0] == 2 and sys.version_info[1] < 6: if _three_digit_exp(): expected = (' x\n0 0.00000e+000\n1 2.50000e-001\n' '2 3.45600e+003\n3 1.20000e+046\n4 1.64000e+006\n' '5 1.70000e+008\n6 1.25346e+000\n7 3.14159e+000\n' '8 -1.00000e+006') else: expected = (' x\n0 0.00000e+00\n1 2.50000e-01\n' '2 3.45600e+03\n3 1.20000e+46\n4 1.64000e+06\n' '5 1.70000e+08\n6 1.25346e+00\n7 3.14159e+00\n' '8 -1.00000e+06') self.assertEqual(df_s, expected) df = DataFrame({'x': [3234, 0.253]}) df_s = df.to_string() expected = (' x\n' '0 3234.000\n' '1 0.253') self.assertEqual(df_s, expected) self.reset_display_options() self.assertEqual(get_option("display.precision"), 6) df = DataFrame({'x': [1e9, 0.2512]}) df_s = df.to_string() # Python 2.5 just wants me to be sad. And debian 32-bit # sys.version_info[0] == 2 and sys.version_info[1] < 6: if _three_digit_exp(): expected = (' x\n' '0 1.000000e+009\n' '1 2.512000e-001') else: expected = (' x\n' '0 1.000000e+09\n' '1 2.512000e-01') self.assertEqual(df_s, expected) def test_to_string_small_float_values(self): df = DataFrame({'a': [1.5, 1e-17, -5.5e-7]}) result = df.to_string() # sadness per above if '%.4g' % 1.7e8 == '1.7e+008': expected = (' a\n' '0 1.500000e+000\n' '1 1.000000e-017\n' '2 -5.500000e-007') else: expected = (' a\n' '0 1.500000e+00\n' '1 1.000000e-17\n' '2 -5.500000e-07') self.assertEqual(result, expected) # but not all exactly zero df = df * 0 result = df.to_string() expected = (' 0\n' '0 0\n' '1 0\n' '2 -0') def test_to_string_float_index(self): index = Index([1.5, 2, 3, 4, 5]) df = DataFrame(lrange(5), index=index) result = df.to_string() expected = (' 0\n' '1.5 0\n' '2.0 1\n' '3.0 2\n' '4.0 3\n' '5.0 4') self.assertEqual(result, expected) def test_to_string_ascii_error(self): data = [('0 ', u(' .gitignore '), u(' 5 '), ' \xe2\x80\xa2\xe2\x80\xa2\xe2\x80' '\xa2\xe2\x80\xa2\xe2\x80\xa2')] df = DataFrame(data) # it works! repr(df) def test_to_string_int_formatting(self): df = DataFrame({'x': [-15, 20, 25, -35]}) self.assertTrue(issubclass(df['x'].dtype.type, np.integer)) output = df.to_string() expected = (' x\n' '0 -15\n' '1 20\n' '2 25\n' '3 -35') self.assertEqual(output, expected) def test_to_string_index_formatter(self): df = DataFrame([lrange(5), lrange(5, 10), lrange(10, 15)]) rs = df.to_string(formatters={'__index__': lambda x: 'abc' [x]}) xp = """\ 0 1 2 3 4 a 0 1 2 3 4 b 5 6 7 8 9 c 10 11 12 13 14\ """ self.assertEqual(rs, xp) def test_to_string_left_justify_cols(self): self.reset_display_options() df = DataFrame({'x': [3234, 0.253]}) df_s = df.to_string(justify='left') expected = (' x \n' '0 3234.000\n' '1 0.253') self.assertEqual(df_s, expected) def test_to_string_format_na(self): self.reset_display_options() df = DataFrame({'A': [np.nan, -1, -2.1234, 3, 4], 'B': [np.nan, 'foo', 'foooo', 'fooooo', 'bar']}) result = df.to_string() expected = (' A B\n' '0 NaN NaN\n' '1 -1.0000 foo\n' '2 -2.1234 foooo\n' '3 3.0000 fooooo\n' '4 4.0000 bar') self.assertEqual(result, expected) df = DataFrame({'A': [np.nan, -1., -2., 3., 4.], 'B': [np.nan, 'foo', 'foooo', 'fooooo', 'bar']}) result = df.to_string() expected = (' A B\n' '0 NaN NaN\n' '1 -1.0 foo\n' '2 -2.0 foooo\n' '3 3.0 fooooo\n' '4 4.0 bar') self.assertEqual(result, expected) def test_to_string_line_width(self): df = DataFrame(123, lrange(10, 15), lrange(30)) s = df.to_string(line_width=80) self.assertEqual(max(len(l) for l in s.split('\n')), 80) def test_show_dimensions(self): df = DataFrame(123, lrange(10, 15), lrange(30)) with option_context('display.max_rows', 10, 'display.max_columns', 40, 'display.width', 500, 'display.expand_frame_repr', 'info', 'display.show_dimensions', True): self.assertTrue('5 rows' in str(df)) self.assertTrue('5 rows' in df._repr_html_()) with option_context('display.max_rows', 10, 'display.max_columns', 40, 'display.width', 500, 'display.expand_frame_repr', 'info', 'display.show_dimensions', False): self.assertFalse('5 rows' in str(df)) self.assertFalse('5 rows' in df._repr_html_()) with option_context('display.max_rows', 2, 'display.max_columns', 2, 'display.width', 500, 'display.expand_frame_repr', 'info', 'display.show_dimensions', 'truncate'): self.assertTrue('5 rows' in str(df)) self.assertTrue('5 rows' in df._repr_html_()) with option_context('display.max_rows', 10, 'display.max_columns', 40, 'display.width', 500, 'display.expand_frame_repr', 'info', 'display.show_dimensions', 'truncate'): self.assertFalse('5 rows' in str(df)) self.assertFalse('5 rows' in df._repr_html_()) def test_to_html(self): # big mixed biggie = DataFrame({'A': randn(200), 'B': tm.makeStringIndex(200)}, index=lrange(200)) biggie.loc[:20, 'A'] = nan biggie.loc[:20, 'B'] = nan s = biggie.to_html() buf = StringIO() retval = biggie.to_html(buf=buf) self.assertIsNone(retval) self.assertEqual(buf.getvalue(), s) tm.assertIsInstance(s, compat.string_types) biggie.to_html(columns=['B', 'A'], col_space=17) biggie.to_html(columns=['B', 'A'], formatters={'A': lambda x: '%.1f' % x}) biggie.to_html(columns=['B', 'A'], float_format=str) biggie.to_html(columns=['B', 'A'], col_space=12, float_format=str) frame = DataFrame(index=np.arange(200)) frame.to_html() def test_to_html_filename(self): biggie = DataFrame({'A': randn(200), 'B': tm.makeStringIndex(200)}, index=lrange(200)) biggie.loc[:20, 'A'] = nan biggie.loc[:20, 'B'] = nan with tm.ensure_clean('test.html') as path: biggie.to_html(path) with open(path, 'r') as f: s = biggie.to_html() s2 = f.read() self.assertEqual(s, s2) frame = DataFrame(index=np.arange(200)) with tm.ensure_clean('test.html') as path: frame.to_html(path) with open(path, 'r') as f: self.assertEqual(frame.to_html(), f.read()) def test_to_html_with_no_bold(self): x = DataFrame({'x': randn(5)}) ashtml = x.to_html(bold_rows=False) self.assertFalse('<strong' in ashtml[ashtml.find("</thead>")]) def test_to_html_columns_arg(self): result = self.frame.to_html(columns=['A']) self.assertNotIn('<th>B</th>', result) def test_to_html_multiindex(self): columns = MultiIndex.from_tuples(list(zip(np.arange(2).repeat(2), np.mod(lrange(4), 2))), names=['CL0', 'CL1']) df = DataFrame([list('abcd'), list('efgh')], columns=columns) result = df.to_html(justify='left') expected = ('<table border="1" class="dataframe">\n' ' <thead>\n' ' <tr>\n' ' <th>CL0</th>\n' ' <th colspan="2" halign="left">0</th>\n' ' <th colspan="2" halign="left">1</th>\n' ' </tr>\n' ' <tr>\n' ' <th>CL1</th>\n' ' <th>0</th>\n' ' <th>1</th>\n' ' <th>0</th>\n' ' <th>1</th>\n' ' </tr>\n' ' </thead>\n' ' <tbody>\n' ' <tr>\n' ' <th>0</th>\n' ' <td>a</td>\n' ' <td>b</td>\n' ' <td>c</td>\n' ' <td>d</td>\n' ' </tr>\n' ' <tr>\n' ' <th>1</th>\n' ' <td>e</td>\n' ' <td>f</td>\n' ' <td>g</td>\n' ' <td>h</td>\n' ' </tr>\n' ' </tbody>\n' '</table>') self.assertEqual(result, expected) columns = MultiIndex.from_tuples(list(zip( range(4), np.mod( lrange(4), 2)))) df = DataFrame([list('abcd'), list('efgh')], columns=columns) result = df.to_html(justify='right') expected = ('<table border="1" class="dataframe">\n' ' <thead>\n' ' <tr>\n' ' <th></th>\n' ' <th>0</th>\n' ' <th>1</th>\n' ' <th>2</th>\n' ' <th>3</th>\n' ' </tr>\n' ' <tr>\n' ' <th></th>\n' ' <th>0</th>\n' ' <th>1</th>\n' ' <th>0</th>\n' ' <th>1</th>\n' ' </tr>\n' ' </thead>\n' ' <tbody>\n' ' <tr>\n' ' <th>0</th>\n' ' <td>a</td>\n' ' <td>b</td>\n' ' <td>c</td>\n' ' <td>d</td>\n' ' </tr>\n' ' <tr>\n' ' <th>1</th>\n' ' <td>e</td>\n' ' <td>f</td>\n' ' <td>g</td>\n' ' <td>h</td>\n' ' </tr>\n' ' </tbody>\n' '</table>') self.assertEqual(result, expected) def test_to_html_justify(self): df = DataFrame({'A': [6, 30000, 2], 'B': [1, 2, 70000], 'C': [223442, 0, 1]}, columns=['A', 'B', 'C']) result = df.to_html(justify='left') expected = ('<table border="1" class="dataframe">\n' ' <thead>\n' ' <tr style="text-align: left;">\n' ' <th></th>\n' ' <th>A</th>\n' ' <th>B</th>\n' ' <th>C</th>\n' ' </tr>\n' ' </thead>\n' ' <tbody>\n' ' <tr>\n' ' <th>0</th>\n' ' <td>6</td>\n' ' <td>1</td>\n' ' <td>223442</td>\n' ' </tr>\n' ' <tr>\n' ' <th>1</th>\n' ' <td>30000</td>\n' ' <td>2</td>\n' ' <td>0</td>\n' ' </tr>\n' ' <tr>\n' ' <th>2</th>\n' ' <td>2</td>\n' ' <td>70000</td>\n' ' <td>1</td>\n' ' </tr>\n' ' </tbody>\n' '</table>') self.assertEqual(result, expected) result = df.to_html(justify='right') expected = ('<table border="1" class="dataframe">\n' ' <thead>\n' ' <tr style="text-align: right;">\n' ' <th></th>\n' ' <th>A</th>\n' ' <th>B</th>\n' ' <th>C</th>\n' ' </tr>\n' ' </thead>\n' ' <tbody>\n' ' <tr>\n' ' <th>0</th>\n' ' <td>6</td>\n' ' <td>1</td>\n' ' <td>223442</td>\n' ' </tr>\n' ' <tr>\n' ' <th>1</th>\n' ' <td>30000</td>\n' ' <td>2</td>\n' ' <td>0</td>\n' ' </tr>\n' ' <tr>\n' ' <th>2</th>\n' ' <td>2</td>\n' ' <td>70000</td>\n' ' <td>1</td>\n' ' </tr>\n' ' </tbody>\n' '</table>') self.assertEqual(result, expected) def test_to_html_index(self): index = ['foo', 'bar', 'baz'] df = DataFrame({'A': [1, 2, 3], 'B': [1.2, 3.4, 5.6], 'C': ['one', 'two', np.NaN]}, columns=['A', 'B', 'C'], index=index) expected_with_index = ('<table border="1" class="dataframe">\n' ' <thead>\n' ' <tr style="text-align: right;">\n' ' <th></th>\n' ' <th>A</th>\n' ' <th>B</th>\n' ' <th>C</th>\n' ' </tr>\n' ' </thead>\n' ' <tbody>\n' ' <tr>\n' ' <th>foo</th>\n' ' <td>1</td>\n' ' <td>1.2</td>\n' ' <td>one</td>\n' ' </tr>\n' ' <tr>\n' ' <th>bar</th>\n' ' <td>2</td>\n' ' <td>3.4</td>\n' ' <td>two</td>\n' ' </tr>\n' ' <tr>\n' ' <th>baz</th>\n' ' <td>3</td>\n' ' <td>5.6</td>\n' ' <td>NaN</td>\n' ' </tr>\n' ' </tbody>\n' '</table>') self.assertEqual(df.to_html(), expected_with_index) expected_without_index = ('<table border="1" class="dataframe">\n' ' <thead>\n' ' <tr style="text-align: right;">\n' ' <th>A</th>\n' ' <th>B</th>\n' ' <th>C</th>\n' ' </tr>\n' ' </thead>\n' ' <tbody>\n' ' <tr>\n' ' <td>1</td>\n' ' <td>1.2</td>\n' ' <td>one</td>\n' ' </tr>\n' ' <tr>\n' ' <td>2</td>\n' ' <td>3.4</td>\n' ' <td>two</td>\n' ' </tr>\n' ' <tr>\n' ' <td>3</td>\n' ' <td>5.6</td>\n' ' <td>NaN</td>\n' ' </tr>\n' ' </tbody>\n' '</table>') result = df.to_html(index=False) for i in index: self.assertNotIn(i, result) self.assertEqual(result, expected_without_index) df.index = Index(['foo', 'bar', 'baz'], name='idx') expected_with_index = ('<table border="1" class="dataframe">\n' ' <thead>\n' ' <tr style="text-align: right;">\n' ' <th></th>\n' ' <th>A</th>\n' ' <th>B</th>\n' ' <th>C</th>\n' ' </tr>\n' ' <tr>\n' ' <th>idx</th>\n' ' <th></th>\n' ' <th></th>\n' ' <th></th>\n' ' </tr>\n' ' </thead>\n' ' <tbody>\n' ' <tr>\n' ' <th>foo</th>\n' ' <td>1</td>\n' ' <td>1.2</td>\n' ' <td>one</td>\n' ' </tr>\n' ' <tr>\n' ' <th>bar</th>\n' ' <td>2</td>\n' ' <td>3.4</td>\n' ' <td>two</td>\n' ' </tr>\n' ' <tr>\n' ' <th>baz</th>\n' ' <td>3</td>\n' ' <td>5.6</td>\n' ' <td>NaN</td>\n' ' </tr>\n' ' </tbody>\n' '</table>') self.assertEqual(df.to_html(), expected_with_index) self.assertEqual(df.to_html(index=False), expected_without_index) tuples = [('foo', 'car'), ('foo', 'bike'), ('bar', 'car')] df.index = MultiIndex.from_tuples(tuples) expected_with_index = ('<table border="1" class="dataframe">\n' ' <thead>\n' ' <tr style="text-align: right;">\n' ' <th></th>\n' ' <th></th>\n' ' <th>A</th>\n' ' <th>B</th>\n' ' <th>C</th>\n' ' </tr>\n' ' </thead>\n' ' <tbody>\n' ' <tr>\n' ' <th rowspan="2" valign="top">foo</th>\n' ' <th>car</th>\n' ' <td>1</td>\n' ' <td>1.2</td>\n' ' <td>one</td>\n' ' </tr>\n' ' <tr>\n' ' <th>bike</th>\n' ' <td>2</td>\n' ' <td>3.4</td>\n' ' <td>two</td>\n' ' </tr>\n' ' <tr>\n' ' <th>bar</th>\n' ' <th>car</th>\n' ' <td>3</td>\n' ' <td>5.6</td>\n' ' <td>NaN</td>\n' ' </tr>\n' ' </tbody>\n' '</table>') self.assertEqual(df.to_html(), expected_with_index) result = df.to_html(index=False) for i in ['foo', 'bar', 'car', 'bike']: self.assertNotIn(i, result) # must be the same result as normal index self.assertEqual(result, expected_without_index) df.index = MultiIndex.from_tuples(tuples, names=['idx1', 'idx2']) expected_with_index = ('<table border="1" class="dataframe">\n' ' <thead>\n' ' <tr style="text-align: right;">\n' ' <th></th>\n' ' <th></th>\n' ' <th>A</th>\n' ' <th>B</th>\n' ' <th>C</th>\n' ' </tr>\n' ' <tr>\n' ' <th>idx1</th>\n' ' <th>idx2</th>\n' ' <th></th>\n' ' <th></th>\n' ' <th></th>\n' ' </tr>\n' ' </thead>\n' ' <tbody>\n' ' <tr>\n' ' <th rowspan="2" valign="top">foo</th>\n' ' <th>car</th>\n' ' <td>1</td>\n' ' <td>1.2</td>\n' ' <td>one</td>\n' ' </tr>\n' ' <tr>\n' ' <th>bike</th>\n' ' <td>2</td>\n' ' <td>3.4</td>\n' ' <td>two</td>\n' ' </tr>\n' ' <tr>\n' ' <th>bar</th>\n' ' <th>car</th>\n' ' <td>3</td>\n' ' <td>5.6</td>\n' ' <td>NaN</td>\n' ' </tr>\n' ' </tbody>\n' '</table>') self.assertEqual(df.to_html(), expected_with_index) self.assertEqual(df.to_html(index=False), expected_without_index) def test_repr_html(self): self.frame._repr_html_() fmt.set_option('display.max_rows', 1, 'display.max_columns', 1) self.frame._repr_html_() fmt.set_option('display.notebook_repr_html', False) self.frame._repr_html_() self.reset_display_options() df = DataFrame([[1, 2], [3, 4]]) fmt.set_option('display.show_dimensions', True) self.assertTrue('2 rows' in df._repr_html_()) fmt.set_option('display.show_dimensions', False) self.assertFalse('2 rows' in df._repr_html_()) self.reset_display_options() def test_repr_html_wide(self): max_cols = get_option('display.max_columns') df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1))) reg_repr = df._repr_html_() assert "..." not in reg_repr wide_df = DataFrame(tm.rands_array(25, size=(10, max_cols + 1))) wide_repr = wide_df._repr_html_() assert "..." in wide_repr def test_repr_html_wide_multiindex_cols(self): max_cols = get_option('display.max_columns') mcols = MultiIndex.from_product([np.arange(max_cols // 2), ['foo', 'bar']], names=['first', 'second']) df = DataFrame(tm.rands_array(25, size=(10, len(mcols))), columns=mcols) reg_repr = df._repr_html_() assert '...' not in reg_repr mcols = MultiIndex.from_product((np.arange(1 + (max_cols // 2)), ['foo', 'bar']), names=['first', 'second']) df = DataFrame(tm.rands_array(25, size=(10, len(mcols))), columns=mcols) wide_repr = df._repr_html_() assert '...' in wide_repr def test_repr_html_long(self): max_rows = get_option('display.max_rows') h = max_rows - 1 df = DataFrame({'A': np.arange(1, 1 + h), 'B': np.arange(41, 41 + h)}) reg_repr = df._repr_html_() assert '..' not in reg_repr assert str(41 + max_rows // 2) in reg_repr h = max_rows + 1 df = DataFrame({'A': np.arange(1, 1 + h), 'B': np.arange(41, 41 + h)}) long_repr = df._repr_html_() assert '..' in long_repr assert str(41 + max_rows // 2) not in long_repr assert u('%d rows ') % h in long_repr assert u('2 columns') in long_repr def test_repr_html_float(self): max_rows = get_option('display.max_rows') h = max_rows - 1 df = DataFrame({'idx': np.linspace(-10, 10, h), 'A': np.arange(1, 1 + h), 'B': np.arange(41, 41 + h)}).set_index('idx') reg_repr = df._repr_html_() assert '..' not in reg_repr assert str(40 + h) in reg_repr h = max_rows + 1 df = DataFrame({'idx': np.linspace(-10, 10, h), 'A': np.arange(1, 1 + h), 'B': np.arange(41, 41 + h)}).set_index('idx') long_repr = df._repr_html_() assert '..' in long_repr assert '31' not in long_repr assert u('%d rows ') % h in long_repr assert u('2 columns') in long_repr def test_repr_html_long_multiindex(self): max_rows = get_option('display.max_rows') max_L1 = max_rows // 2 tuples = list(itertools.product(np.arange(max_L1), ['foo', 'bar'])) idx = MultiIndex.from_tuples(tuples, names=['first', 'second']) df = DataFrame(np.random.randn(max_L1 * 2, 2), index=idx, columns=['A', 'B']) reg_repr = df._repr_html_() assert '...' not in reg_repr tuples = list(itertools.product(np.arange(max_L1 + 1), ['foo', 'bar'])) idx = MultiIndex.from_tuples(tuples, names=['first', 'second']) df = DataFrame(np.random.randn((max_L1 + 1) * 2, 2), index=idx, columns=['A', 'B']) long_repr = df._repr_html_() assert '...' in long_repr def test_repr_html_long_and_wide(self): max_cols = get_option('display.max_columns') max_rows = get_option('display.max_rows') h, w = max_rows - 1, max_cols - 1 df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) assert '...' not in df._repr_html_() h, w = max_rows + 1, max_cols + 1 df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) assert '...' in df._repr_html_() def test_info_repr(self): max_rows = get_option('display.max_rows') max_cols = get_option('display.max_columns') # Long h, w = max_rows + 1, max_cols - 1 df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) assert has_vertically_truncated_repr(df) with option_context('display.large_repr', 'info'): assert has_info_repr(df) # Wide h, w = max_rows - 1, max_cols + 1 df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) assert has_horizontally_truncated_repr(df) with option_context('display.large_repr', 'info'): assert has_info_repr(df) def test_info_repr_max_cols(self): # GH #6939 df = DataFrame(randn(10, 5)) with option_context('display.large_repr', 'info', 'display.max_columns', 1, 'display.max_info_columns', 4): self.assertTrue(has_non_verbose_info_repr(df)) with option_context('display.large_repr', 'info', 'display.max_columns', 1, 'display.max_info_columns', 5): self.assertFalse(has_non_verbose_info_repr(df)) # test verbose overrides # fmt.set_option('display.max_info_columns', 4) # exceeded def test_info_repr_html(self): max_rows = get_option('display.max_rows') max_cols = get_option('display.max_columns') # Long h, w = max_rows + 1, max_cols - 1 df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) assert r'&lt;class' not in df._repr_html_() with option_context('display.large_repr', 'info'): assert r'&lt;class' in df._repr_html_() # Wide h, w = max_rows - 1, max_cols + 1 df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) assert '<class' not in df._repr_html_() with option_context('display.large_repr', 'info'): assert '&lt;class' in df._repr_html_() def test_fake_qtconsole_repr_html(self): def get_ipython(): return {'config': {'KernelApp': {'parent_appname': 'ipython-qtconsole'}}} repstr = self.frame._repr_html_() self.assertIsNotNone(repstr) fmt.set_option('display.max_rows', 5, 'display.max_columns', 2) repstr = self.frame._repr_html_() self.assertIn('class', repstr) # info fallback self.reset_display_options() def test_to_html_with_classes(self): df = DataFrame() result = df.to_html(classes="sortable draggable") expected = dedent(""" <table border="1" class="dataframe sortable draggable"> <thead> <tr style="text-align: right;"> <th></th> </tr> </thead> <tbody> </tbody> </table> """).strip() self.assertEqual(result, expected) result = df.to_html(classes=["sortable", "draggable"]) self.assertEqual(result, expected) def test_pprint_pathological_object(self): """ if the test fails, the stack will overflow and nose crash, but it won't hang. """ class A: def __getitem__(self, key): return 3 # obviously simplified df = DataFrame([A()]) repr(df) # just don't dine def test_float_trim_zeros(self): vals = [2.08430917305e+10, 3.52205017305e+10, 2.30674817305e+10, 2.03954217305e+10, 5.59897817305e+10] skip = True for line in repr(DataFrame({'A': vals})).split('\n')[:-2]: if line.startswith('dtype:'): continue if _three_digit_exp(): self.assertTrue(('+010' in line) or skip) else: self.assertTrue(('+10' in line) or skip) skip = False def test_dict_entries(self): df = DataFrame({'A': [{'a': 1, 'b': 2}]}) val = df.to_string() self.assertTrue("'a': 1" in val) self.assertTrue("'b': 2" in val) def test_to_latex_filename(self): with tm.ensure_clean('test.tex') as path: self.frame.to_latex(path) with open(path, 'r') as f: self.assertEqual(self.frame.to_latex(), f.read()) # test with utf-8 and encoding option (GH 7061) df = DataFrame([[u'au\xdfgangen']]) with tm.ensure_clean('test.tex') as path: df.to_latex(path, encoding='utf-8') with codecs.open(path, 'r', encoding='utf-8') as f: self.assertEqual(df.to_latex(), f.read()) # test with utf-8 without encoding option if compat.PY3: # python3: pandas default encoding is utf-8 with tm.ensure_clean('test.tex') as path: df.to_latex(path) with codecs.open(path, 'r', encoding='utf-8') as f: self.assertEqual(df.to_latex(), f.read()) else: # python2 default encoding is ascii, so an error should be raised with tm.ensure_clean('test.tex') as path: self.assertRaises(UnicodeEncodeError, df.to_latex, path) def test_to_latex(self): # it works! self.frame.to_latex() df = DataFrame({'a': [1, 2], 'b': ['b1', 'b2']}) withindex_result = df.to_latex() withindex_expected = r"""\begin{tabular}{lrl} \toprule {} & a & b \\ \midrule 0 & 1 & b1 \\ 1 & 2 & b2 \\ \bottomrule \end{tabular} """ self.assertEqual(withindex_result, withindex_expected) withoutindex_result = df.to_latex(index=False) withoutindex_expected = r"""\begin{tabular}{rl} \toprule a & b \\ \midrule 1 & b1 \\ 2 & b2 \\ \bottomrule \end{tabular} """ self.assertEqual(withoutindex_result, withoutindex_expected) def test_to_latex_format(self): # GH Bug #9402 self.frame.to_latex(column_format='ccc') df = DataFrame({'a': [1, 2], 'b': ['b1', 'b2']}) withindex_result = df.to_latex(column_format='ccc') withindex_expected = r"""\begin{tabular}{ccc} \toprule {} & a & b \\ \midrule 0 & 1 & b1 \\ 1 & 2 & b2 \\ \bottomrule \end{tabular} """ self.assertEqual(withindex_result, withindex_expected) def test_to_latex_with_formatters(self): df = DataFrame({'int': [1, 2, 3], 'float': [1.0, 2.0, 3.0], 'object': [(1, 2), True, False], 'datetime64': [datetime(2016, 1, 1), datetime(2016, 2, 5), datetime(2016, 3, 3)]}) formatters = {'int': lambda x: '0x%x' % x, 'float': lambda x: '[% 4.1f]' % x, 'object': lambda x: '-%s-' % str(x), 'datetime64': lambda x: x.strftime('%Y-%m'), '__index__': lambda x: 'index: %s' % x} result = df.to_latex(formatters=dict(formatters)) expected = r"""\begin{tabular}{llrrl} \toprule {} & datetime64 & float & int & object \\ \midrule index: 0 & 2016-01 & [ 1.0] & 0x1 & -(1, 2)- \\ index: 1 & 2016-02 & [ 2.0] & 0x2 & -True- \\ index: 2 & 2016-03 & [ 3.0] & 0x3 & -False- \\ \bottomrule \end{tabular} """ self.assertEqual(result, expected) def test_to_latex_multiindex(self): df = DataFrame({('x', 'y'): ['a']}) result = df.to_latex() expected = r"""\begin{tabular}{ll} \toprule {} & x \\ {} & y \\ \midrule 0 & a \\ \bottomrule \end{tabular} """ self.assertEqual(result, expected) result = df.T.to_latex() expected = r"""\begin{tabular}{lll} \toprule & & 0 \\ \midrule x & y & a \\ \bottomrule \end{tabular} """ self.assertEqual(result, expected) df = DataFrame.from_dict({ ('c1', 0): pd.Series(dict((x, x) for x in range(4))), ('c1', 1): pd.Series(dict((x, x + 4) for x in range(4))), ('c2', 0): pd.Series(dict((x, x) for x in range(4))), ('c2', 1): pd.Series(dict((x, x + 4) for x in range(4))), ('c3', 0): pd.Series(dict((x, x) for x in range(4))), }).T result = df.to_latex() expected = r"""\begin{tabular}{llrrrr} \toprule & & 0 & 1 & 2 & 3 \\ \midrule c1 & 0 & 0 & 1 & 2 & 3 \\ & 1 & 4 & 5 & 6 & 7 \\ c2 & 0 & 0 & 1 & 2 & 3 \\ & 1 & 4 & 5 & 6 & 7 \\ c3 & 0 & 0 & 1 & 2 & 3 \\ \bottomrule \end{tabular} """ self.assertEqual(result, expected) # GH 10660 df = pd.DataFrame({'a': [0, 0, 1, 1], 'b': list('abab'), 'c': [1, 2, 3, 4]}) result = df.set_index(['a', 'b']).to_latex() expected = r"""\begin{tabular}{llr} \toprule & & c \\ a & b & \\ \midrule 0 & a & 1 \\ & b & 2 \\ 1 & a & 3 \\ & b & 4 \\ \bottomrule \end{tabular} """ self.assertEqual(result, expected) result = df.groupby('a').describe().to_latex() expected = r"""\begin{tabular}{llr} \toprule & & c \\ a & {} & \\ \midrule 0 & count & 2.000000 \\ & mean & 1.500000 \\ & std & 0.707107 \\ & min & 1.000000 \\ & 25\% & 1.250000 \\ & 50\% & 1.500000 \\ & 75\% & 1.750000 \\ & max & 2.000000 \\ 1 & count & 2.000000 \\ & mean & 3.500000 \\ & std & 0.707107 \\ & min & 3.000000 \\ & 25\% & 3.250000 \\ & 50\% & 3.500000 \\ & 75\% & 3.750000 \\ & max & 4.000000 \\ \bottomrule \end{tabular} """ self.assertEqual(result, expected) def test_to_latex_escape(self): a = 'a' b = 'b' test_dict = {u('co^l1'): {a: "a", b: "b"}, u('co$e^x$'): {a: "a", b: "b"}} unescaped_result = DataFrame(test_dict).to_latex(escape=False) escaped_result = DataFrame(test_dict).to_latex( ) # default: escape=True unescaped_expected = r'''\begin{tabular}{lll} \toprule {} & co$e^x$ & co^l1 \\ \midrule a & a & a \\ b & b & b \\ \bottomrule \end{tabular} ''' escaped_expected = r'''\begin{tabular}{lll} \toprule {} & co\$e\textasciicircumx\$ & co\textasciicircuml1 \\ \midrule a & a & a \\ b & b & b \\ \bottomrule \end{tabular} ''' self.assertEqual(unescaped_result, unescaped_expected) self.assertEqual(escaped_result, escaped_expected) def test_to_latex_longtable(self): self.frame.to_latex(longtable=True) df = DataFrame({'a': [1, 2], 'b': ['b1', 'b2']}) withindex_result = df.to_latex(longtable=True) withindex_expected = r"""\begin{longtable}{lrl} \toprule {} & a & b \\ \midrule \endhead \midrule \multicolumn{3}{r}{{Continued on next page}} \\ \midrule \endfoot \bottomrule \endlastfoot 0 & 1 & b1 \\ 1 & 2 & b2 \\ \end{longtable} """ self.assertEqual(withindex_result, withindex_expected) withoutindex_result = df.to_latex(index=False, longtable=True) withoutindex_expected = r"""\begin{longtable}{rl} \toprule a & b \\ \midrule \endhead \midrule \multicolumn{3}{r}{{Continued on next page}} \\ \midrule \endfoot \bottomrule \endlastfoot 1 & b1 \\ 2 & b2 \\ \end{longtable} """ self.assertEqual(withoutindex_result, withoutindex_expected) def test_to_latex_escape_special_chars(self): special_characters = ['&', '%', '$', '#', '_', '{', '}', '~', '^', '\\'] df = DataFrame(data=special_characters) observed = df.to_latex() expected = r"""\begin{tabular}{ll} \toprule {} & 0 \\ \midrule 0 & \& \\ 1 & \% \\ 2 & \$ \\ 3 & \# \\ 4 & \_ \\ 5 & \{ \\ 6 & \} \\ 7 & \textasciitilde \\ 8 & \textasciicircum \\ 9 & \textbackslash \\ \bottomrule \end{tabular} """ self.assertEqual(observed, expected) def test_to_latex_no_header(self): # GH 7124 df = DataFrame({'a': [1, 2], 'b': ['b1', 'b2']}) withindex_result = df.to_latex(header=False) withindex_expected = r"""\begin{tabular}{lrl} \toprule 0 & 1 & b1 \\ 1 & 2 & b2 \\ \bottomrule \end{tabular} """ self.assertEqual(withindex_result, withindex_expected) withoutindex_result = df.to_latex(index=False, header=False) withoutindex_expected = r"""\begin{tabular}{rl} \toprule 1 & b1 \\ 2 & b2 \\ \bottomrule \end{tabular} """ self.assertEqual(withoutindex_result, withoutindex_expected) def test_to_latex_decimal(self): # GH 12031 self.frame.to_latex() df = DataFrame({'a': [1.0, 2.1], 'b': ['b1', 'b2']}) withindex_result = df.to_latex(decimal=',') print("WHAT THE") withindex_expected = r"""\begin{tabular}{lrl} \toprule {} & a & b \\ \midrule 0 & 1,0 & b1 \\ 1 & 2,1 & b2 \\ \bottomrule \end{tabular} """ self.assertEqual(withindex_result, withindex_expected) def test_to_csv_quotechar(self): df = DataFrame({'col': [1, 2]}) expected = """\ "","col" "0","1" "1","2" """ with tm.ensure_clean('test.csv') as path: df.to_csv(path, quoting=1) # 1=QUOTE_ALL with open(path, 'r') as f: self.assertEqual(f.read(), expected) expected = """\ $$,$col$ $0$,$1$ $1$,$2$ """ with tm.ensure_clean('test.csv') as path: df.to_csv(path, quoting=1, quotechar="$") with open(path, 'r') as f: self.assertEqual(f.read(), expected) with tm.ensure_clean('test.csv') as path: with tm.assertRaisesRegexp(TypeError, 'quotechar'): df.to_csv(path, quoting=1, quotechar=None) def test_to_csv_doublequote(self): df = DataFrame({'col': ['a"a', '"bb"']}) expected = '''\ "","col" "0","a""a" "1","""bb""" ''' with tm.ensure_clean('test.csv') as path: df.to_csv(path, quoting=1, doublequote=True) # QUOTE_ALL with open(path, 'r') as f: self.assertEqual(f.read(), expected) from _csv import Error with tm.ensure_clean('test.csv') as path: with tm.assertRaisesRegexp(Error, 'escapechar'): df.to_csv(path, doublequote=False) # no escapechar set def test_to_csv_escapechar(self): df = DataFrame({'col': ['a"a', '"bb"']}) expected = '''\ "","col" "0","a\\"a" "1","\\"bb\\"" ''' with tm.ensure_clean('test.csv') as path: # QUOTE_ALL df.to_csv(path, quoting=1, doublequote=False, escapechar='\\') with open(path, 'r') as f: self.assertEqual(f.read(), expected) df = DataFrame({'col': ['a,a', ',bb,']}) expected = """\ ,col 0,a\\,a 1,\\,bb\\, """ with tm.ensure_clean('test.csv') as path: df.to_csv(path, quoting=3, escapechar='\\') # QUOTE_NONE with open(path, 'r') as f: self.assertEqual(f.read(), expected) def test_csv_to_string(self): df = DataFrame({'col': [1, 2]}) expected = ',col\n0,1\n1,2\n' self.assertEqual(df.to_csv(), expected) def test_to_csv_decimal(self): # GH 781 df = DataFrame({'col1': [1], 'col2': ['a'], 'col3': [10.1]}) expected_default = ',col1,col2,col3\n0,1,a,10.1\n' self.assertEqual(df.to_csv(), expected_default) expected_european_excel = ';col1;col2;col3\n0;1;a;10,1\n' self.assertEqual( df.to_csv(decimal=',', sep=';'), expected_european_excel) expected_float_format_default = ',col1,col2,col3\n0,1,a,10.10\n' self.assertEqual( df.to_csv(float_format='%.2f'), expected_float_format_default) expected_float_format = ';col1;col2;col3\n0;1;a;10,10\n' self.assertEqual( df.to_csv(decimal=',', sep=';', float_format='%.2f'), expected_float_format) # GH 11553: testing if decimal is taken into account for '0.0' df = pd.DataFrame({'a': [0, 1.1], 'b': [2.2, 3.3], 'c': 1}) expected = 'a,b,c\n0^0,2^2,1\n1^1,3^3,1\n' self.assertEqual(df.to_csv(index=False, decimal='^'), expected) # same but for an index self.assertEqual(df.set_index('a').to_csv(decimal='^'), expected) # same for a multi-index self.assertEqual( df.set_index(['a', 'b']).to_csv(decimal="^"), expected) def test_to_csv_float_format(self): # testing if float_format is taken into account for the index # GH 11553 df = pd.DataFrame({'a': [0, 1], 'b': [2.2, 3.3], 'c': 1}) expected = 'a,b,c\n0,2.20,1\n1,3.30,1\n' self.assertEqual( df.set_index('a').to_csv(float_format='%.2f'), expected) # same for a multi-index self.assertEqual( df.set_index(['a', 'b']).to_csv(float_format='%.2f'), expected) def test_to_csv_na_rep(self): # testing if NaN values are correctly represented in the index # GH 11553 df = DataFrame({'a': [0, np.NaN], 'b': [0, 1], 'c': [2, 3]}) expected = "a,b,c\n0.0,0,2\n_,1,3\n" self.assertEqual(df.set_index('a').to_csv(na_rep='_'), expected) self.assertEqual(df.set_index(['a', 'b']).to_csv(na_rep='_'), expected) # now with an index containing only NaNs df = DataFrame({'a': np.NaN, 'b': [0, 1], 'c': [2, 3]}) expected = "a,b,c\n_,0,2\n_,1,3\n" self.assertEqual(df.set_index('a').to_csv(na_rep='_'), expected) self.assertEqual(df.set_index(['a', 'b']).to_csv(na_rep='_'), expected) # check if na_rep parameter does not break anything when no NaN df = DataFrame({'a': 0, 'b': [0, 1], 'c': [2, 3]}) expected = "a,b,c\n0,0,2\n0,1,3\n" self.assertEqual(df.set_index('a').to_csv(na_rep='_'), expected) self.assertEqual(df.set_index(['a', 'b']).to_csv(na_rep='_'), expected) def test_to_csv_date_format(self): # GH 10209 df_sec = DataFrame({'A': pd.date_range('20130101', periods=5, freq='s') }) df_day = DataFrame({'A': pd.date_range('20130101', periods=5, freq='d') }) expected_default_sec = ',A\n0,2013-01-01 00:00:00\n1,2013-01-01 00:00:01\n2,2013-01-01 00:00:02' + \ '\n3,2013-01-01 00:00:03\n4,2013-01-01 00:00:04\n' self.assertEqual(df_sec.to_csv(), expected_default_sec) expected_ymdhms_day = ',A\n0,2013-01-01 00:00:00\n1,2013-01-02 00:00:00\n2,2013-01-03 00:00:00' + \ '\n3,2013-01-04 00:00:00\n4,2013-01-05 00:00:00\n' self.assertEqual( df_day.to_csv( date_format='%Y-%m-%d %H:%M:%S'), expected_ymdhms_day) expected_ymd_sec = ',A\n0,2013-01-01\n1,2013-01-01\n2,2013-01-01\n3,2013-01-01\n4,2013-01-01\n' self.assertEqual( df_sec.to_csv(date_format='%Y-%m-%d'), expected_ymd_sec) expected_default_day = ',A\n0,2013-01-01\n1,2013-01-02\n2,2013-01-03\n3,2013-01-04\n4,2013-01-05\n' self.assertEqual(df_day.to_csv(), expected_default_day) self.assertEqual( df_day.to_csv(date_format='%Y-%m-%d'), expected_default_day) # testing if date_format parameter is taken into account for # multi-indexed dataframes (GH 7791) df_sec['B'] = 0 df_sec['C'] = 1 expected_ymd_sec = 'A,B,C\n2013-01-01,0,1\n' df_sec_grouped = df_sec.groupby([pd.Grouper(key='A', freq='1h'), 'B']) self.assertEqual(df_sec_grouped.mean().to_csv(date_format='%Y-%m-%d'), expected_ymd_sec) def test_to_csv_multi_index(self): # see gh-6618 df = DataFrame([1], columns=pd.MultiIndex.from_arrays([[1],[2]])) exp = ",1\n,2\n0,1\n" self.assertEqual(df.to_csv(), exp) exp = "1\n2\n1\n" self.assertEqual(df.to_csv(index=False), exp) df = DataFrame([1], columns=pd.MultiIndex.from_arrays([[1],[2]]), index=pd.MultiIndex.from_arrays([[1],[2]])) exp = ",,1\n,,2\n1,2,1\n" self.assertEqual(df.to_csv(), exp) exp = "1\n2\n1\n" self.assertEqual(df.to_csv(index=False), exp) df = DataFrame([1], columns=pd.MultiIndex.from_arrays([['foo'],['bar']])) exp = ",foo\n,bar\n0,1\n" self.assertEqual(df.to_csv(), exp) exp = "foo\nbar\n1\n" self.assertEqual(df.to_csv(index=False), exp) def test_period(self): # GH 12615 df = pd.DataFrame({'A': pd.period_range('2013-01', periods=4, freq='M'), 'B': [pd.Period('2011-01', freq='M'), pd.Period('2011-02-01', freq='D'), pd.Period('2011-03-01 09:00', freq='H'), pd.Period('2011-04', freq='M')], 'C': list('abcd')}) exp = (" A B C\n0 2013-01 2011-01 a\n" "1 2013-02 2011-02-01 b\n2 2013-03 2011-03-01 09:00 c\n" "3 2013-04 2011-04 d") self.assertEqual(str(df), exp) class TestSeriesFormatting(tm.TestCase): _multiprocess_can_split_ = True def setUp(self): self.ts = tm.makeTimeSeries() def test_repr_unicode(self): s = Series([u('\u03c3')] * 10) repr(s) a = Series([u("\u05d0")] * 1000) a.name = 'title1' repr(a) def test_to_string(self): buf = StringIO() s = self.ts.to_string() retval = self.ts.to_string(buf=buf) self.assertIsNone(retval) self.assertEqual(buf.getvalue().strip(), s) # pass float_format format = '%.4f'.__mod__ result = self.ts.to_string(float_format=format) result = [x.split()[1] for x in result.split('\n')[:-1]] expected = [format(x) for x in self.ts] self.assertEqual(result, expected) # empty string result = self.ts[:0].to_string() self.assertEqual(result, 'Series([], Freq: B)') result = self.ts[:0].to_string(length=0) self.assertEqual(result, 'Series([], Freq: B)') # name and length cp = self.ts.copy() cp.name = 'foo' result = cp.to_string(length=True, name=True, dtype=True) last_line = result.split('\n')[-1].strip() self.assertEqual(last_line, "Freq: B, Name: foo, Length: %d, dtype: float64" % len(cp)) def test_freq_name_separation(self): s = Series(np.random.randn(10), index=date_range('1/1/2000', periods=10), name=0) result = repr(s) self.assertTrue('Freq: D, Name: 0' in result) def test_to_string_mixed(self): s = Series(['foo', np.nan, -1.23, 4.56]) result = s.to_string() expected = (u('0 foo\n') + u('1 NaN\n') + u('2 -1.23\n') + u('3 4.56')) self.assertEqual(result, expected) # but don't count NAs as floats s = Series(['foo', np.nan, 'bar', 'baz']) result = s.to_string() expected = (u('0 foo\n') + '1 NaN\n' + '2 bar\n' + '3 baz') self.assertEqual(result, expected) s = Series(['foo', 5, 'bar', 'baz']) result = s.to_string() expected = (u('0 foo\n') + '1 5\n' + '2 bar\n' + '3 baz') self.assertEqual(result, expected) def test_to_string_float_na_spacing(self): s = Series([0., 1.5678, 2., -3., 4.]) s[::2] = np.nan result = s.to_string() expected = (u('0 NaN\n') + '1 1.5678\n' + '2 NaN\n' + '3 -3.0000\n' + '4 NaN') self.assertEqual(result, expected) def test_to_string_without_index(self): # GH 11729 Test index=False option s = Series([1, 2, 3, 4]) result = s.to_string(index=False) expected = (u('1\n') + '2\n' + '3\n' + '4') self.assertEqual(result, expected) def test_unicode_name_in_footer(self): s = Series([1, 2], name=u('\u05e2\u05d1\u05e8\u05d9\u05ea')) sf = fmt.SeriesFormatter(s, name=u('\u05e2\u05d1\u05e8\u05d9\u05ea')) sf._get_footer() # should not raise exception def test_east_asian_unicode_series(self): if PY3: _rep = repr else: _rep = unicode # not alighned properly because of east asian width # unicode index s = Series(['a', 'bb', 'CCC', 'D'], index=[u'あ', u'いい', u'ううう', u'ええええ']) expected = (u"あ a\nいい bb\nううう CCC\n" u"ええええ D\ndtype: object") self.assertEqual(_rep(s), expected) # unicode values s = Series([u'あ', u'いい', u'ううう', u'ええええ'], index=['a', 'bb', 'c', 'ddd']) expected = (u"a あ\nbb いい\nc ううう\n" u"ddd ええええ\ndtype: object") self.assertEqual(_rep(s), expected) # both s = Series([u'あ', u'いい', u'ううう', u'ええええ'], index=[u'ああ', u'いいいい', u'う', u'えええ']) expected = (u"ああ あ\nいいいい いい\nう ううう\n" u"えええ ええええ\ndtype: object") self.assertEqual(_rep(s), expected) # unicode footer s = Series([u'あ', u'いい', u'ううう', u'ええええ'], index=[u'ああ', u'いいいい', u'う', u'えええ'], name=u'おおおおおおお') expected = (u"ああ あ\nいいいい いい\nう ううう\n" u"えええ ええええ\nName: おおおおおおお, dtype: object") self.assertEqual(_rep(s), expected) # MultiIndex idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), ( u'おおお', u'かかかか'), (u'き', u'くく')]) s = Series([1, 22, 3333, 44444], index=idx) expected = (u"あ いい 1\nう え 22\nおおお かかかか 3333\n" u"き くく 44444\ndtype: int64") self.assertEqual(_rep(s), expected) # object dtype, shorter than unicode repr s = Series([1, 22, 3333, 44444], index=[1, 'AB', np.nan, u'あああ']) expected = (u"1 1\nAB 22\nNaN 3333\n" u"あああ 44444\ndtype: int64") self.assertEqual(_rep(s), expected) # object dtype, longer than unicode repr s = Series([1, 22, 3333, 44444], index=[1, 'AB', pd.Timestamp('2011-01-01'), u'あああ']) expected = (u"1 1\nAB 22\n" u"2011-01-01 00:00:00 3333\nあああ 44444\ndtype: int64" ) self.assertEqual(_rep(s), expected) # truncate with option_context('display.max_rows', 3): s = Series([u'あ', u'いい', u'ううう', u'ええええ'], name=u'おおおおおおお') expected = (u"0 あ\n ... \n" u"3 ええええ\nName: おおおおおおお, dtype: object") self.assertEqual(_rep(s), expected) s.index = [u'ああ', u'いいいい', u'う', u'えええ'] expected = (u"ああ あ\n ... \n" u"えええ ええええ\nName: おおおおおおお, dtype: object") self.assertEqual(_rep(s), expected) # Emable Unicode option ----------------------------------------- with option_context('display.unicode.east_asian_width', True): # unicode index s = Series(['a', 'bb', 'CCC', 'D'], index=[u'あ', u'いい', u'ううう', u'ええええ']) expected = (u"あ a\nいい bb\nううう CCC\n" u"ええええ D\ndtype: object") self.assertEqual(_rep(s), expected) # unicode values s = Series([u'あ', u'いい', u'ううう', u'ええええ'], index=['a', 'bb', 'c', 'ddd']) expected = (u"a あ\nbb いい\nc ううう\n" u"ddd ええええ\ndtype: object") self.assertEqual(_rep(s), expected) # both s = Series([u'あ', u'いい', u'ううう', u'ええええ'], index=[u'ああ', u'いいいい', u'う', u'えええ']) expected = (u"ああ あ\nいいいい いい\nう ううう\n" u"えええ ええええ\ndtype: object") self.assertEqual(_rep(s), expected) # unicode footer s = Series([u'あ', u'いい', u'ううう', u'ええええ'], index=[u'ああ', u'いいいい', u'う', u'えええ'], name=u'おおおおおおお') expected = (u"ああ あ\nいいいい いい\nう ううう\n" u"えええ ええええ\nName: おおおおおおお, dtype: object") self.assertEqual(_rep(s), expected) # MultiIndex idx = pd.MultiIndex.from_tuples([(u'あ', u'いい'), (u'う', u'え'), ( u'おおお', u'かかかか'), (u'き', u'くく')]) s = Series([1, 22, 3333, 44444], index=idx) expected = (u"あ いい 1\nう え 22\nおおお かかかか 3333\n" u"き くく 44444\ndtype: int64") self.assertEqual(_rep(s), expected) # object dtype, shorter than unicode repr s = Series([1, 22, 3333, 44444], index=[1, 'AB', np.nan, u'あああ']) expected = (u"1 1\nAB 22\nNaN 3333\n" u"あああ 44444\ndtype: int64") self.assertEqual(_rep(s), expected) # object dtype, longer than unicode repr s = Series([1, 22, 3333, 44444], index=[1, 'AB', pd.Timestamp('2011-01-01'), u'あああ']) expected = (u"1 1\nAB 22\n" u"2011-01-01 00:00:00 3333\nあああ 44444\ndtype: int64" ) self.assertEqual(_rep(s), expected) # truncate with option_context('display.max_rows', 3): s = Series([u'あ', u'いい', u'ううう', u'ええええ'], name=u'おおおおおおお') expected = (u"0 あ\n ... \n" u"3 ええええ\nName: おおおおおおお, dtype: object") self.assertEqual(_rep(s), expected) s.index = [u'ああ', u'いいいい', u'う', u'えええ'] expected = (u"ああ あ\n ... \n" u"えええ ええええ\nName: おおおおおおお, dtype: object") self.assertEqual(_rep(s), expected) # ambiguous unicode s = Series([u'¡¡', u'い¡¡', u'ううう', u'ええええ'], index=[u'ああ', u'¡¡¡¡いい', u'¡¡', u'えええ']) expected = (u"ああ ¡¡\n¡¡¡¡いい い¡¡\n¡¡ ううう\n" u"えええ ええええ\ndtype: object") self.assertEqual(_rep(s), expected) def test_float_trim_zeros(self): vals = [2.08430917305e+10, 3.52205017305e+10, 2.30674817305e+10, 2.03954217305e+10, 5.59897817305e+10] for line in repr(Series(vals)).split('\n'): if line.startswith('dtype:'): continue if _three_digit_exp(): self.assertIn('+010', line) else: self.assertIn('+10', line) def test_datetimeindex(self): index = date_range('20130102', periods=6) s = Series(1, index=index) result = s.to_string() self.assertTrue('2013-01-02' in result) # nat in index s2 = Series(2, index=[Timestamp('20130111'), NaT]) s = s2.append(s) result = s.to_string() self.assertTrue('NaT' in result) # nat in summary result = str(s2.index) self.assertTrue('NaT' in result) def test_timedelta64(self): from datetime import datetime, timedelta Series(np.array([1100, 20], dtype='timedelta64[ns]')).to_string() s = Series(date_range('2012-1-1', periods=3, freq='D')) # GH2146 # adding NaTs y = s - s.shift(1) result = y.to_string() self.assertTrue('1 days' in result) self.assertTrue('00:00:00' not in result) self.assertTrue('NaT' in result) # with frac seconds o = Series([datetime(2012, 1, 1, microsecond=150)] * 3) y = s - o result = y.to_string() self.assertTrue('-1 days +23:59:59.999850' in result) # rounding? o = Series([datetime(2012, 1, 1, 1)] * 3) y = s - o result = y.to_string() self.assertTrue('-1 days +23:00:00' in result) self.assertTrue('1 days 23:00:00' in result) o = Series([datetime(2012, 1, 1, 1, 1)] * 3) y = s - o result = y.to_string() self.assertTrue('-1 days +22:59:00' in result) self.assertTrue('1 days 22:59:00' in result) o = Series([datetime(2012, 1, 1, 1, 1, microsecond=150)] * 3) y = s - o result = y.to_string() self.assertTrue('-1 days +22:58:59.999850' in result) self.assertTrue('0 days 22:58:59.999850' in result) # neg time td = timedelta(minutes=5, seconds=3) s2 = Series(date_range('2012-1-1', periods=3, freq='D')) + td y = s - s2 result = y.to_string() self.assertTrue('-1 days +23:54:57' in result) td = timedelta(microseconds=550) s2 = Series(date_range('2012-1-1', periods=3, freq='D')) + td y = s - td result = y.to_string() self.assertTrue('2012-01-01 23:59:59.999450' in result) # no boxing of the actual elements td = Series(pd.timedelta_range('1 days', periods=3)) result = td.to_string() self.assertEqual(result, u("0 1 days\n1 2 days\n2 3 days")) def test_mixed_datetime64(self): df = DataFrame({'A': [1, 2], 'B': ['2012-01-01', '2012-01-02']}) df['B'] = pd.to_datetime(df.B) result = repr(df.ix[0]) self.assertTrue('2012-01-01' in result) def test_period(self): # GH 12615 index = pd.period_range('2013-01', periods=6, freq='M') s = Series(np.arange(6, dtype='int64'), index=index) exp = ("2013-01 0\n2013-02 1\n2013-03 2\n2013-04 3\n" "2013-05 4\n2013-06 5\nFreq: M, dtype: int64") self.assertEqual(str(s), exp) s = Series(index) exp = ("0 2013-01\n1 2013-02\n2 2013-03\n3 2013-04\n" "4 2013-05\n5 2013-06\ndtype: object") self.assertEqual(str(s), exp) # periods with mixed freq s = Series([pd.Period('2011-01', freq='M'), pd.Period('2011-02-01', freq='D'), pd.Period('2011-03-01 09:00', freq='H')]) exp = ("0 2011-01\n1 2011-02-01\n" "2 2011-03-01 09:00\ndtype: object") self.assertEqual(str(s), exp) def test_max_multi_index_display(self): # GH 7101 # doc example (indexing.rst) # multi-index arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = list(zip(*arrays)) index = MultiIndex.from_tuples(tuples, names=['first', 'second']) s = Series(randn(8), index=index) with option_context("display.max_rows", 10): self.assertEqual(len(str(s).split('\n')), 10) with option_context("display.max_rows", 3): self.assertEqual(len(str(s).split('\n')), 5) with option_context("display.max_rows", 2): self.assertEqual(len(str(s).split('\n')), 5) with option_context("display.max_rows", 1): self.assertEqual(len(str(s).split('\n')), 4) with option_context("display.max_rows", 0): self.assertEqual(len(str(s).split('\n')), 10) # index s = Series(randn(8), None) with option_context("display.max_rows", 10): self.assertEqual(len(str(s).split('\n')), 9) with option_context("display.max_rows", 3): self.assertEqual(len(str(s).split('\n')), 4) with option_context("display.max_rows", 2): self.assertEqual(len(str(s).split('\n')), 4) with option_context("display.max_rows", 1): self.assertEqual(len(str(s).split('\n')), 3) with option_context("display.max_rows", 0): self.assertEqual(len(str(s).split('\n')), 9) # Make sure #8532 is fixed def test_consistent_format(self): s = pd.Series([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9999, 1, 1] * 10) with option_context("display.max_rows", 10): res = repr(s) exp = ('0 1.0000\n1 1.0000\n2 1.0000\n3 ' '1.0000\n4 1.0000\n ... \n125 ' '1.0000\n126 1.0000\n127 0.9999\n128 ' '1.0000\n129 1.0000\ndtype: float64') self.assertEqual(res, exp) @staticmethod def gen_test_series(): s1 = pd.Series(['a'] * 100) s2 = pd.Series(['ab'] * 100) s3 = pd.Series(['a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef']) s4 = s3[::-1] test_sers = {'onel': s1, 'twol': s2, 'asc': s3, 'desc': s4} return test_sers def chck_ncols(self, s): with option_context("display.max_rows", 10): res = repr(s) lines = res.split('\n') lines = [line for line in repr(s).split('\n') if not re.match(r'[^\.]*\.+', line)][:-1] ncolsizes = len(set(len(line.strip()) for line in lines)) self.assertEqual(ncolsizes, 1) def test_format_explicit(self): test_sers = self.gen_test_series() with option_context("display.max_rows", 4): res = repr(test_sers['onel']) exp = '0 a\n1 a\n ..\n98 a\n99 a\ndtype: object' self.assertEqual(exp, res) res = repr(test_sers['twol']) exp = ('0 ab\n1 ab\n ..\n98 ab\n99 ab\ndtype:' ' object') self.assertEqual(exp, res) res = repr(test_sers['asc']) exp = ('0 a\n1 ab\n ... \n4 abcde\n5' ' abcdef\ndtype: object') self.assertEqual(exp, res) res = repr(test_sers['desc']) exp = ('5 abcdef\n4 abcde\n ... \n1 ab\n0' ' a\ndtype: object') self.assertEqual(exp, res) def test_ncols(self): test_sers = self.gen_test_series() for s in test_sers.values(): self.chck_ncols(s) def test_max_rows_eq_one(self): s = Series(range(10), dtype='int64') with option_context("display.max_rows", 1): strrepr = repr(s).split('\n') exp1 = ['0', '0'] res1 = strrepr[0].split() self.assertEqual(exp1, res1) exp2 = ['..'] res2 = strrepr[1].split() self.assertEqual(exp2, res2) def test_truncate_ndots(self): def getndots(s): return len(re.match(r'[^\.]*(\.*)', s).groups()[0]) s = Series([0, 2, 3, 6]) with option_context("display.max_rows", 2): strrepr = repr(s).replace('\n', '') self.assertEqual(getndots(strrepr), 2) s = Series([0, 100, 200, 400]) with option_context("display.max_rows", 2): strrepr = repr(s).replace('\n', '') self.assertEqual(getndots(strrepr), 3) def test_to_string_name(self): s = Series(range(100), dtype='int64') s.name = 'myser' res = s.to_string(max_rows=2, name=True) exp = '0 0\n ..\n99 99\nName: myser' self.assertEqual(res, exp) res = s.to_string(max_rows=2, name=False) exp = '0 0\n ..\n99 99' self.assertEqual(res, exp) def test_to_string_dtype(self): s = Series(range(100), dtype='int64') res = s.to_string(max_rows=2, dtype=True) exp = '0 0\n ..\n99 99\ndtype: int64' self.assertEqual(res, exp) res = s.to_string(max_rows=2, dtype=False) exp = '0 0\n ..\n99 99' self.assertEqual(res, exp) def test_to_string_length(self): s = Series(range(100), dtype='int64') res = s.to_string(max_rows=2, length=True) exp = '0 0\n ..\n99 99\nLength: 100' self.assertEqual(res, exp) def test_to_string_na_rep(self): s = pd.Series(index=range(100)) res = s.to_string(na_rep='foo', max_rows=2) exp = '0 foo\n ..\n99 foo' self.assertEqual(res, exp) def test_to_string_float_format(self): s = pd.Series(range(10), dtype='float64') res = s.to_string(float_format=lambda x: '{0:2.1f}'.format(x), max_rows=2) exp = '0 0.0\n ..\n9 9.0' self.assertEqual(res, exp) def test_to_string_header(self): s = pd.Series(range(10), dtype='int64') s.index.name = 'foo' res = s.to_string(header=True, max_rows=2) exp = 'foo\n0 0\n ..\n9 9' self.assertEqual(res, exp) res = s.to_string(header=False, max_rows=2) exp = '0 0\n ..\n9 9' self.assertEqual(res, exp) class TestEngFormatter(tm.TestCase): _multiprocess_can_split_ = True def test_eng_float_formatter(self): df = DataFrame({'A': [1.41, 141., 14100, 1410000.]}) fmt.set_eng_float_format() result = df.to_string() expected = (' A\n' '0 1.410E+00\n' '1 141.000E+00\n' '2 14.100E+03\n' '3 1.410E+06') self.assertEqual(result, expected) fmt.set_eng_float_format(use_eng_prefix=True) result = df.to_string() expected = (' A\n' '0 1.410\n' '1 141.000\n' '2 14.100k\n' '3 1.410M') self.assertEqual(result, expected) fmt.set_eng_float_format(accuracy=0) result = df.to_string() expected = (' A\n' '0 1E+00\n' '1 141E+00\n' '2 14E+03\n' '3 1E+06') self.assertEqual(result, expected) self.reset_display_options() def compare(self, formatter, input, output): formatted_input = formatter(input) msg = ("formatting of %s results in '%s', expected '%s'" % (str(input), formatted_input, output)) self.assertEqual(formatted_input, output, msg) def compare_all(self, formatter, in_out): """ Parameters: ----------- formatter: EngFormatter under test in_out: list of tuples. Each tuple = (number, expected_formatting) It is tested if 'formatter(number) == expected_formatting'. *number* should be >= 0 because formatter(-number) == fmt is also tested. *fmt* is derived from *expected_formatting* """ for input, output in in_out: self.compare(formatter, input, output) self.compare(formatter, -input, "-" + output[1:]) def test_exponents_with_eng_prefix(self): formatter = fmt.EngFormatter(accuracy=3, use_eng_prefix=True) f = np.sqrt(2) in_out = [(f * 10 ** -24, " 1.414y"), (f * 10 ** -23, " 14.142y"), (f * 10 ** -22, " 141.421y"), (f * 10 ** -21, " 1.414z"), (f * 10 ** -20, " 14.142z"), (f * 10 ** -19, " 141.421z"), (f * 10 ** -18, " 1.414a"), (f * 10 ** -17, " 14.142a"), (f * 10 ** -16, " 141.421a"), (f * 10 ** -15, " 1.414f"), (f * 10 ** -14, " 14.142f"), (f * 10 ** -13, " 141.421f"), (f * 10 ** -12, " 1.414p"), (f * 10 ** -11, " 14.142p"), (f * 10 ** -10, " 141.421p"), (f * 10 ** -9, " 1.414n"), (f * 10 ** -8, " 14.142n"), (f * 10 ** -7, " 141.421n"), (f * 10 ** -6, " 1.414u"), (f * 10 ** -5, " 14.142u"), (f * 10 ** -4, " 141.421u"), (f * 10 ** -3, " 1.414m"), (f * 10 ** -2, " 14.142m"), (f * 10 ** -1, " 141.421m"), (f * 10 ** 0, " 1.414"), (f * 10 ** 1, " 14.142"), (f * 10 ** 2, " 141.421"), (f * 10 ** 3, " 1.414k"), (f * 10 ** 4, " 14.142k"), (f * 10 ** 5, " 141.421k"), (f * 10 ** 6, " 1.414M"), (f * 10 ** 7, " 14.142M"), (f * 10 ** 8, " 141.421M"), (f * 10 ** 9, " 1.414G"), ( f * 10 ** 10, " 14.142G"), (f * 10 ** 11, " 141.421G"), (f * 10 ** 12, " 1.414T"), (f * 10 ** 13, " 14.142T"), ( f * 10 ** 14, " 141.421T"), (f * 10 ** 15, " 1.414P"), ( f * 10 ** 16, " 14.142P"), (f * 10 ** 17, " 141.421P"), ( f * 10 ** 18, " 1.414E"), (f * 10 ** 19, " 14.142E"), (f * 10 ** 20, " 141.421E"), (f * 10 ** 21, " 1.414Z"), ( f * 10 ** 22, " 14.142Z"), (f * 10 ** 23, " 141.421Z"), ( f * 10 ** 24, " 1.414Y"), (f * 10 ** 25, " 14.142Y"), ( f * 10 ** 26, " 141.421Y")] self.compare_all(formatter, in_out) def test_exponents_without_eng_prefix(self): formatter = fmt.EngFormatter(accuracy=4, use_eng_prefix=False) f = np.pi in_out = [(f * 10 ** -24, " 3.1416E-24"), (f * 10 ** -23, " 31.4159E-24"), (f * 10 ** -22, " 314.1593E-24"), (f * 10 ** -21, " 3.1416E-21"), (f * 10 ** -20, " 31.4159E-21"), (f * 10 ** -19, " 314.1593E-21"), (f * 10 ** -18, " 3.1416E-18"), (f * 10 ** -17, " 31.4159E-18"), (f * 10 ** -16, " 314.1593E-18"), (f * 10 ** -15, " 3.1416E-15"), (f * 10 ** -14, " 31.4159E-15"), (f * 10 ** -13, " 314.1593E-15"), (f * 10 ** -12, " 3.1416E-12"), (f * 10 ** -11, " 31.4159E-12"), (f * 10 ** -10, " 314.1593E-12"), (f * 10 ** -9, " 3.1416E-09"), (f * 10 ** -8, " 31.4159E-09"), (f * 10 ** -7, " 314.1593E-09"), (f * 10 ** -6, " 3.1416E-06"), (f * 10 ** -5, " 31.4159E-06"), (f * 10 ** -4, " 314.1593E-06"), (f * 10 ** -3, " 3.1416E-03"), (f * 10 ** -2, " 31.4159E-03"), (f * 10 ** -1, " 314.1593E-03"), (f * 10 ** 0, " 3.1416E+00"), ( f * 10 ** 1, " 31.4159E+00"), (f * 10 ** 2, " 314.1593E+00"), (f * 10 ** 3, " 3.1416E+03"), (f * 10 ** 4, " 31.4159E+03"), ( f * 10 ** 5, " 314.1593E+03"), (f * 10 ** 6, " 3.1416E+06"), (f * 10 ** 7, " 31.4159E+06"), (f * 10 ** 8, " 314.1593E+06"), ( f * 10 ** 9, " 3.1416E+09"), (f * 10 ** 10, " 31.4159E+09"), (f * 10 ** 11, " 314.1593E+09"), (f * 10 ** 12, " 3.1416E+12"), (f * 10 ** 13, " 31.4159E+12"), (f * 10 ** 14, " 314.1593E+12"), (f * 10 ** 15, " 3.1416E+15"), (f * 10 ** 16, " 31.4159E+15"), (f * 10 ** 17, " 314.1593E+15"), (f * 10 ** 18, " 3.1416E+18"), (f * 10 ** 19, " 31.4159E+18"), (f * 10 ** 20, " 314.1593E+18"), (f * 10 ** 21, " 3.1416E+21"), (f * 10 ** 22, " 31.4159E+21"), (f * 10 ** 23, " 314.1593E+21"), (f * 10 ** 24, " 3.1416E+24"), (f * 10 ** 25, " 31.4159E+24"), (f * 10 ** 26, " 314.1593E+24")] self.compare_all(formatter, in_out) def test_rounding(self): formatter = fmt.EngFormatter(accuracy=3, use_eng_prefix=True) in_out = [(5.55555, ' 5.556'), (55.5555, ' 55.556'), (555.555, ' 555.555'), (5555.55, ' 5.556k'), (55555.5, ' 55.556k'), (555555, ' 555.555k')] self.compare_all(formatter, in_out) formatter = fmt.EngFormatter(accuracy=1, use_eng_prefix=True) in_out = [(5.55555, ' 5.6'), (55.5555, ' 55.6'), (555.555, ' 555.6'), (5555.55, ' 5.6k'), (55555.5, ' 55.6k'), (555555, ' 555.6k')] self.compare_all(formatter, in_out) formatter = fmt.EngFormatter(accuracy=0, use_eng_prefix=True) in_out = [(5.55555, ' 6'), (55.5555, ' 56'), (555.555, ' 556'), (5555.55, ' 6k'), (55555.5, ' 56k'), (555555, ' 556k')] self.compare_all(formatter, in_out) formatter = fmt.EngFormatter(accuracy=3, use_eng_prefix=True) result = formatter(0) self.assertEqual(result, u(' 0.000')) def test_nan(self): # Issue #11981 formatter = fmt.EngFormatter(accuracy=1, use_eng_prefix=True) result = formatter(np.nan) self.assertEqual(result, u('NaN')) df = pd.DataFrame({'a':[1.5, 10.3, 20.5], 'b':[50.3, 60.67, 70.12], 'c':[100.2, 101.33, 120.33]}) pt = df.pivot_table(values='a', index='b', columns='c') fmt.set_eng_float_format(accuracy=1) result = pt.to_string() self.assertTrue('NaN' in result) self.reset_display_options() def test_inf(self): # Issue #11981 formatter = fmt.EngFormatter(accuracy=1, use_eng_prefix=True) result = formatter(np.inf) self.assertEqual(result, u('inf')) def _three_digit_exp(): return '%.4g' % 1.7e8 == '1.7e+008' class TestFloatArrayFormatter(tm.TestCase): def test_misc(self): obj = fmt.FloatArrayFormatter(np.array([], dtype=np.float64)) result = obj.get_result() self.assertTrue(len(result) == 0) def test_format(self): obj = fmt.FloatArrayFormatter(np.array([12, 0], dtype=np.float64)) result = obj.get_result() self.assertEqual(result[0], " 12.0") self.assertEqual(result[1], " 0.0") def test_output_significant_digits(self): # Issue #9764 # In case default display precision changes: with pd.option_context('display.precision', 6): # DataFrame example from issue #9764 d = pd.DataFrame( {'col1': [9.999e-8, 1e-7, 1.0001e-7, 2e-7, 4.999e-7, 5e-7, 5.0001e-7, 6e-7, 9.999e-7, 1e-6, 1.0001e-6, 2e-6, 4.999e-6, 5e-6, 5.0001e-6, 6e-6]}) expected_output = { (0, 6): ' col1\n0 9.999000e-08\n1 1.000000e-07\n2 1.000100e-07\n3 2.000000e-07\n4 4.999000e-07\n5 5.000000e-07', (1, 6): ' col1\n1 1.000000e-07\n2 1.000100e-07\n3 2.000000e-07\n4 4.999000e-07\n5 5.000000e-07', (1, 8): ' col1\n1 1.000000e-07\n2 1.000100e-07\n3 2.000000e-07\n4 4.999000e-07\n5 5.000000e-07\n6 5.000100e-07\n7 6.000000e-07', (8, 16): ' col1\n8 9.999000e-07\n9 1.000000e-06\n10 1.000100e-06\n11 2.000000e-06\n12 4.999000e-06\n13 5.000000e-06\n14 5.000100e-06\n15 6.000000e-06', (9, 16): ' col1\n9 0.000001\n10 0.000001\n11 0.000002\n12 0.000005\n13 0.000005\n14 0.000005\n15 0.000006' } for (start, stop), v in expected_output.items(): self.assertEqual(str(d[start:stop]), v) def test_too_long(self): # GH 10451 with pd.option_context('display.precision', 4): # need both a number > 1e6 and something that normally formats to # having length > display.precision + 6 df = pd.DataFrame(dict(x=[12345.6789])) self.assertEqual(str(df), ' x\n0 12345.6789') df = pd.DataFrame(dict(x=[2e6])) self.assertEqual(str(df), ' x\n0 2000000.0') df = pd.DataFrame(dict(x=[12345.6789, 2e6])) self.assertEqual( str(df), ' x\n0 1.2346e+04\n1 2.0000e+06') class TestRepr_timedelta64(tm.TestCase): def test_none(self): delta_1d = pd.to_timedelta(1, unit='D') delta_0d = pd.to_timedelta(0, unit='D') delta_1s = pd.to_timedelta(1, unit='s') delta_500ms = pd.to_timedelta(500, unit='ms') drepr = lambda x: x._repr_base() self.assertEqual(drepr(delta_1d), "1 days") self.assertEqual(drepr(-delta_1d), "-1 days") self.assertEqual(drepr(delta_0d), "0 days") self.assertEqual(drepr(delta_1s), "0 days 00:00:01") self.assertEqual(drepr(delta_500ms), "0 days 00:00:00.500000") self.assertEqual(drepr(delta_1d + delta_1s), "1 days 00:00:01") self.assertEqual( drepr(delta_1d + delta_500ms), "1 days 00:00:00.500000") def test_even_day(self): delta_1d = pd.to_timedelta(1, unit='D') delta_0d = pd.to_timedelta(0, unit='D') delta_1s = pd.to_timedelta(1, unit='s') delta_500ms = pd.to_timedelta(500, unit='ms') drepr = lambda x: x._repr_base(format='even_day') self.assertEqual(drepr(delta_1d), "1 days") self.assertEqual(drepr(-delta_1d), "-1 days") self.assertEqual(drepr(delta_0d), "0 days") self.assertEqual(drepr(delta_1s), "0 days 00:00:01") self.assertEqual(drepr(delta_500ms), "0 days 00:00:00.500000") self.assertEqual(drepr(delta_1d + delta_1s), "1 days 00:00:01") self.assertEqual( drepr(delta_1d + delta_500ms), "1 days 00:00:00.500000") def test_sub_day(self): delta_1d = pd.to_timedelta(1, unit='D') delta_0d = pd.to_timedelta(0, unit='D') delta_1s = pd.to_timedelta(1, unit='s') delta_500ms = pd.to_timedelta(500, unit='ms') drepr = lambda x: x._repr_base(format='sub_day') self.assertEqual(drepr(delta_1d), "1 days") self.assertEqual(drepr(-delta_1d), "-1 days") self.assertEqual(drepr(delta_0d), "00:00:00") self.assertEqual(drepr(delta_1s), "00:00:01") self.assertEqual(drepr(delta_500ms), "00:00:00.500000") self.assertEqual(drepr(delta_1d + delta_1s), "1 days 00:00:01") self.assertEqual( drepr(delta_1d + delta_500ms), "1 days 00:00:00.500000") def test_long(self): delta_1d = pd.to_timedelta(1, unit='D') delta_0d = pd.to_timedelta(0, unit='D') delta_1s = pd.to_timedelta(1, unit='s') delta_500ms = pd.to_timedelta(500, unit='ms') drepr = lambda x: x._repr_base(format='long') self.assertEqual(drepr(delta_1d), "1 days 00:00:00") self.assertEqual(drepr(-delta_1d), "-1 days +00:00:00") self.assertEqual(drepr(delta_0d), "0 days 00:00:00") self.assertEqual(drepr(delta_1s), "0 days 00:00:01") self.assertEqual(drepr(delta_500ms), "0 days 00:00:00.500000") self.assertEqual(drepr(delta_1d + delta_1s), "1 days 00:00:01") self.assertEqual( drepr(delta_1d + delta_500ms), "1 days 00:00:00.500000") def test_all(self): delta_1d = pd.to_timedelta(1, unit='D') delta_0d = pd.to_timedelta(0, unit='D') delta_1ns = pd.to_timedelta(1, unit='ns') drepr = lambda x: x._repr_base(format='all') self.assertEqual(drepr(delta_1d), "1 days 00:00:00.000000000") self.assertEqual(drepr(delta_0d), "0 days 00:00:00.000000000") self.assertEqual(drepr(delta_1ns), "0 days 00:00:00.000000001") class TestTimedelta64Formatter(tm.TestCase): def test_days(self): x = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='D') result = fmt.Timedelta64Formatter(x, box=True).get_result() self.assertEqual(result[0].strip(), "'0 days'") self.assertEqual(result[1].strip(), "'1 days'") result = fmt.Timedelta64Formatter(x[1:2], box=True).get_result() self.assertEqual(result[0].strip(), "'1 days'") result = fmt.Timedelta64Formatter(x, box=False).get_result() self.assertEqual(result[0].strip(), "0 days") self.assertEqual(result[1].strip(), "1 days") result = fmt.Timedelta64Formatter(x[1:2], box=False).get_result() self.assertEqual(result[0].strip(), "1 days") def test_days_neg(self): x = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='D') result = fmt.Timedelta64Formatter(-x, box=True).get_result() self.assertEqual(result[0].strip(), "'0 days'") self.assertEqual(result[1].strip(), "'-1 days'") def test_subdays(self): y = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='s') result = fmt.Timedelta64Formatter(y, box=True).get_result() self.assertEqual(result[0].strip(), "'00:00:00'") self.assertEqual(result[1].strip(), "'00:00:01'") def test_subdays_neg(self): y = pd.to_timedelta(list(range(5)) + [pd.NaT], unit='s') result = fmt.Timedelta64Formatter(-y, box=True).get_result() self.assertEqual(result[0].strip(), "'00:00:00'") self.assertEqual(result[1].strip(), "'-1 days +23:59:59'") def test_zero(self): x = pd.to_timedelta(list(range(1)) + [pd.NaT], unit='D') result = fmt.Timedelta64Formatter(x, box=True).get_result() self.assertEqual(result[0].strip(), "'0 days'") x = pd.to_timedelta(list(range(1)), unit='D') result = fmt.Timedelta64Formatter(x, box=True).get_result() self.assertEqual(result[0].strip(), "'0 days'") class TestDatetime64Formatter(tm.TestCase): def test_mixed(self): x = Series([datetime(2013, 1, 1), datetime(2013, 1, 1, 12), pd.NaT]) result = fmt.Datetime64Formatter(x).get_result() self.assertEqual(result[0].strip(), "2013-01-01 00:00:00") self.assertEqual(result[1].strip(), "2013-01-01 12:00:00") def test_dates(self): x = Series([datetime(2013, 1, 1), datetime(2013, 1, 2), pd.NaT]) result = fmt.Datetime64Formatter(x).get_result() self.assertEqual(result[0].strip(), "2013-01-01") self.assertEqual(result[1].strip(), "2013-01-02") def test_date_nanos(self): x = Series([Timestamp(200)]) result = fmt.Datetime64Formatter(x).get_result() self.assertEqual(result[0].strip(), "1970-01-01 00:00:00.000000200") def test_dates_display(self): # 10170 # make sure that we are consistently display date formatting x = Series(date_range('20130101 09:00:00', periods=5, freq='D')) x.iloc[1] = np.nan result = fmt.Datetime64Formatter(x).get_result() self.assertEqual(result[0].strip(), "2013-01-01 09:00:00") self.assertEqual(result[1].strip(), "NaT") self.assertEqual(result[4].strip(), "2013-01-05 09:00:00") x = Series(date_range('20130101 09:00:00', periods=5, freq='s')) x.iloc[1] = np.nan result = fmt.Datetime64Formatter(x).get_result() self.assertEqual(result[0].strip(), "2013-01-01 09:00:00") self.assertEqual(result[1].strip(), "NaT") self.assertEqual(result[4].strip(), "2013-01-01 09:00:04") x = Series(date_range('20130101 09:00:00', periods=5, freq='ms')) x.iloc[1] = np.nan result = fmt.Datetime64Formatter(x).get_result() self.assertEqual(result[0].strip(), "2013-01-01 09:00:00.000") self.assertEqual(result[1].strip(), "NaT") self.assertEqual(result[4].strip(), "2013-01-01 09:00:00.004") x = Series(date_range('20130101 09:00:00', periods=5, freq='us')) x.iloc[1] = np.nan result = fmt.Datetime64Formatter(x).get_result() self.assertEqual(result[0].strip(), "2013-01-01 09:00:00.000000") self.assertEqual(result[1].strip(), "NaT") self.assertEqual(result[4].strip(), "2013-01-01 09:00:00.000004") x = Series(date_range('20130101 09:00:00', periods=5, freq='N')) x.iloc[1] = np.nan result = fmt.Datetime64Formatter(x).get_result() self.assertEqual(result[0].strip(), "2013-01-01 09:00:00.000000000") self.assertEqual(result[1].strip(), "NaT") self.assertEqual(result[4].strip(), "2013-01-01 09:00:00.000000004") def test_datetime64formatter_yearmonth(self): x = Series([datetime(2016, 1, 1), datetime(2016, 2, 2)]) def format_func(x): return x.strftime('%Y-%m') formatter = fmt.Datetime64Formatter(x, formatter=format_func) result = formatter.get_result() self.assertEqual(result, ['2016-01', '2016-02']) def test_datetime64formatter_hoursecond(self): x = Series(pd.to_datetime(['10:10:10.100', '12:12:12.120'], format='%H:%M:%S.%f')) def format_func(x): return x.strftime('%H:%M') formatter = fmt.Datetime64Formatter(x, formatter=format_func) result = formatter.get_result() self.assertEqual(result, ['10:10', '12:12']) class TestNaTFormatting(tm.TestCase): def test_repr(self): self.assertEqual(repr(pd.NaT), "NaT") def test_str(self): self.assertEqual(str(pd.NaT), "NaT") class TestDatetimeIndexFormat(tm.TestCase): def test_datetime(self): formatted = pd.to_datetime([datetime(2003, 1, 1, 12), pd.NaT]).format() self.assertEqual(formatted[0], "2003-01-01 12:00:00") self.assertEqual(formatted[1], "NaT") def test_date(self): formatted = pd.to_datetime([datetime(2003, 1, 1), pd.NaT]).format() self.assertEqual(formatted[0], "2003-01-01") self.assertEqual(formatted[1], "NaT") def test_date_tz(self): formatted = pd.to_datetime([datetime(2013, 1, 1)], utc=True).format() self.assertEqual(formatted[0], "2013-01-01 00:00:00+00:00") formatted = pd.to_datetime( [datetime(2013, 1, 1), pd.NaT], utc=True).format() self.assertEqual(formatted[0], "2013-01-01 00:00:00+00:00") def test_date_explict_date_format(self): formatted = pd.to_datetime([datetime(2003, 2, 1), pd.NaT]).format( date_format="%m-%d-%Y", na_rep="UT") self.assertEqual(formatted[0], "02-01-2003") self.assertEqual(formatted[1], "UT") class TestDatetimeIndexUnicode(tm.TestCase): def test_dates(self): text = str(pd.to_datetime([datetime(2013, 1, 1), datetime(2014, 1, 1) ])) self.assertTrue("['2013-01-01'," in text) self.assertTrue(", '2014-01-01']" in text) def test_mixed(self): text = str(pd.to_datetime([datetime(2013, 1, 1), datetime( 2014, 1, 1, 12), datetime(2014, 1, 1)])) self.assertTrue("'2013-01-01 00:00:00'," in text) self.assertTrue("'2014-01-01 00:00:00']" in text) class TestStringRepTimestamp(tm.TestCase): def test_no_tz(self): dt_date = datetime(2013, 1, 2) self.assertEqual(str(dt_date), str(Timestamp(dt_date))) dt_datetime = datetime(2013, 1, 2, 12, 1, 3) self.assertEqual(str(dt_datetime), str(Timestamp(dt_datetime))) dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45) self.assertEqual(str(dt_datetime_us), str(Timestamp(dt_datetime_us))) ts_nanos_only = Timestamp(200) self.assertEqual(str(ts_nanos_only), "1970-01-01 00:00:00.000000200") ts_nanos_micros = Timestamp(1200) self.assertEqual(str(ts_nanos_micros), "1970-01-01 00:00:00.000001200") def test_tz_pytz(self): tm._skip_if_no_pytz() import pytz dt_date = datetime(2013, 1, 2, tzinfo=pytz.utc) self.assertEqual(str(dt_date), str(Timestamp(dt_date))) dt_datetime = datetime(2013, 1, 2, 12, 1, 3, tzinfo=pytz.utc) self.assertEqual(str(dt_datetime), str(Timestamp(dt_datetime))) dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45, tzinfo=pytz.utc) self.assertEqual(str(dt_datetime_us), str(Timestamp(dt_datetime_us))) def test_tz_dateutil(self): tm._skip_if_no_dateutil() import dateutil utc = dateutil.tz.tzutc() dt_date = datetime(2013, 1, 2, tzinfo=utc) self.assertEqual(str(dt_date), str(Timestamp(dt_date))) dt_datetime = datetime(2013, 1, 2, 12, 1, 3, tzinfo=utc) self.assertEqual(str(dt_datetime), str(Timestamp(dt_datetime))) dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45, tzinfo=utc) self.assertEqual(str(dt_datetime_us), str(Timestamp(dt_datetime_us))) def test_nat_representations(self): for f in (str, repr, methodcaller('isoformat')): self.assertEqual(f(pd.NaT), 'NaT') def test_format_percentiles(): result = fmt.format_percentiles([0.01999, 0.02001, 0.5, 0.666666, 0.9999]) expected = ['1.999%', '2.001%', '50%', '66.667%', '99.99%'] tm.assert_equal(result, expected) result = fmt.format_percentiles([0, 0.5, 0.02001, 0.5, 0.666666, 0.9999]) expected = ['0%', '50%', '2.0%', '50%', '66.67%', '99.99%'] tm.assert_equal(result, expected) tm.assertRaises(ValueError, fmt.format_percentiles, [0.1, np.nan, 0.5]) tm.assertRaises(ValueError, fmt.format_percentiles, [-0.001, 0.1, 0.5]) tm.assertRaises(ValueError, fmt.format_percentiles, [2, 0.1, 0.5]) tm.assertRaises(ValueError, fmt.format_percentiles, [0.1, 0.5, 'a']) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
mit
rlabbe/filterpy
filterpy/kalman/tests/test_enkf.py
2
3356
# -*- coding: utf-8 -*- """Copyright 2015 Roger R Labbe Jr. FilterPy library. http://github.com/rlabbe/filterpy Documentation at: https://filterpy.readthedocs.org Supporting book at: https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python This is licensed under an MIT license. See the readme.MD file for more information. """ from numpy.random import randn import numpy as np import matplotlib.pyplot as plt from filterpy.kalman import EnsembleKalmanFilter as EnKF from filterpy.common import Q_discrete_white_noise, Saver from math import cos, sin DO_PLOT = False def test_1d_const_vel(): def hx(x): return np.array([x[0]]) F = np.array([[1., 1.],[0., 1.]]) def fx(x, dt): return np.dot(F, x) x = np.array([0., 1.]) P = np.eye(2)* 100. f = EnKF(x=x, P=P, dim_z=1, dt=1., N=8, hx=hx, fx=fx) std_noise = 10. f.R *= std_noise**2 f.Q = Q_discrete_white_noise(2, 1., .001) measurements = [] results = [] ps = [] zs = [] s = Saver(f) for t in range (0,100): # create measurement = t plus white noise z = t + randn()*std_noise zs.append(z) f.predict() f.update(np.asarray([z])) # save data results.append (f.x[0]) measurements.append(z) ps.append(3*(f.P[0,0]**.5)) s.save() s.to_array() results = np.asarray(results) ps = np.asarray(ps) if DO_PLOT: plt.plot(results, label='EnKF') plt.plot(measurements, c='r', label='z') plt.plot (results-ps, c='k',linestyle='--', label='3$\sigma$') plt.plot(results+ps, c='k', linestyle='--') plt.legend(loc='best') #print(ps) return f def test_circle(): def hx(x): return np.array([x[0], x[3]]) F = np.array([[1., 1., .5, 0., 0., 0.], [0., 1., 1., 0., 0., 0.], [0., 0., 1., 0., 0., 0.], [0., 0., 0., 1., 1., .5], [0., 0., 0., 0., 1., 1.], [0., 0., 0., 0., 0., 1.]]) def fx(x, dt): return np.dot(F, x) x = np.array([50., 0., 0, 0, .0, 0.]) P = np.eye(6)* 100. f = EnKF(x=x, P=P, dim_z=2, dt=1., N=30, hx=hx, fx=fx) std_noise = .1 f.R *= std_noise**2 f.Q[0:3, 0:3] = Q_discrete_white_noise(3, 1., .001) f.Q[3:6, 3:6] = Q_discrete_white_noise(3, 1., .001) measurements = [] results = [] zs = [] for t in range (0,300): a = t / 300000 x = cos(a) * 50. y = sin(a) * 50. # create measurement = t plus white noise z = np.array([x,y]) zs.append(z) f.predict() f.update(z) # save data results.append (f.x) measurements.append(z) #test that __repr__ doesn't assert str(f) results = np.asarray(results) measurements = np.asarray(measurements) if DO_PLOT: plt.plot(results[:,0], results[:,2], label='EnKF') plt.plot(measurements[:,0], measurements[:,1], c='r', label='z') #plt.plot (results-ps, c='k',linestyle='--', label='3$\sigma$') #plt.plot(results+ps, c='k', linestyle='--') plt.legend(loc='best') plt.axis('equal') #print(ps) if __name__ == '__main__': DO_PLOT = True test_circle () test_1d_const_vel() #test_noisy_1d()
mit
bigdataelephants/scikit-learn
sklearn/neural_network/tests/test_rbm.py
8
6202
import sys import re import numpy as np from scipy.sparse import csc_matrix, csr_matrix, lil_matrix from sklearn.utils.testing import (assert_almost_equal, assert_array_equal, assert_true) from sklearn.datasets import load_digits from sklearn.externals.six.moves import cStringIO as StringIO from sklearn.neural_network import BernoulliRBM from sklearn.utils.validation import assert_all_finite np.seterr(all='warn') Xdigits = load_digits().data Xdigits -= Xdigits.min() Xdigits /= Xdigits.max() def test_fit(): X = Xdigits.copy() rbm = BernoulliRBM(n_components=64, learning_rate=0.1, batch_size=10, n_iter=7, random_state=9) rbm.fit(X) assert_almost_equal(rbm.score_samples(X).mean(), -21., decimal=0) # in-place tricks shouldn't have modified X assert_array_equal(X, Xdigits) def test_partial_fit(): X = Xdigits.copy() rbm = BernoulliRBM(n_components=64, learning_rate=0.1, batch_size=20, random_state=9) n_samples = X.shape[0] n_batches = int(np.ceil(float(n_samples) / rbm.batch_size)) batch_slices = np.array_split(X, n_batches) for i in range(7): for batch in batch_slices: rbm.partial_fit(batch) assert_almost_equal(rbm.score_samples(X).mean(), -21., decimal=0) assert_array_equal(X, Xdigits) def test_transform(): X = Xdigits[:100] rbm1 = BernoulliRBM(n_components=16, batch_size=5, n_iter=5, random_state=42) rbm1.fit(X) Xt1 = rbm1.transform(X) Xt2 = rbm1._mean_hiddens(X) assert_array_equal(Xt1, Xt2) def test_small_sparse(): """BernoulliRBM should work on small sparse matrices.""" X = csr_matrix(Xdigits[:4]) BernoulliRBM().fit(X) # no exception def test_small_sparse_partial_fit(): for sparse in [csc_matrix, csr_matrix]: X_sparse = sparse(Xdigits[:100]) X = Xdigits[:100].copy() rbm1 = BernoulliRBM(n_components=64, learning_rate=0.1, batch_size=10, random_state=9) rbm2 = BernoulliRBM(n_components=64, learning_rate=0.1, batch_size=10, random_state=9) rbm1.partial_fit(X_sparse) rbm2.partial_fit(X) assert_almost_equal(rbm1.score_samples(X).mean(), rbm2.score_samples(X).mean(), decimal=0) def test_sample_hiddens(): rng = np.random.RandomState(0) X = Xdigits[:100] rbm1 = BernoulliRBM(n_components=2, batch_size=5, n_iter=5, random_state=42) rbm1.fit(X) h = rbm1._mean_hiddens(X[0]) hs = np.mean([rbm1._sample_hiddens(X[0], rng) for i in range(100)], 0) assert_almost_equal(h, hs, decimal=1) def test_fit_gibbs(): """ Gibbs on the RBM hidden layer should be able to recreate [[0], [1]] from the same input """ rng = np.random.RandomState(42) X = np.array([[0.], [1.]]) rbm1 = BernoulliRBM(n_components=2, batch_size=2, n_iter=42, random_state=rng) # you need that much iters rbm1.fit(X) assert_almost_equal(rbm1.components_, np.array([[0.02649814], [0.02009084]]), decimal=4) assert_almost_equal(rbm1.gibbs(X), X) return rbm1 def test_fit_gibbs_sparse(): """ Gibbs on the RBM hidden layer should be able to recreate [[0], [1]] from the same input even when the input is sparse, and test against non-sparse """ rbm1 = test_fit_gibbs() rng = np.random.RandomState(42) from scipy.sparse import csc_matrix X = csc_matrix([[0.], [1.]]) rbm2 = BernoulliRBM(n_components=2, batch_size=2, n_iter=42, random_state=rng) rbm2.fit(X) assert_almost_equal(rbm2.components_, np.array([[0.02649814], [0.02009084]]), decimal=4) assert_almost_equal(rbm2.gibbs(X), X.toarray()) assert_almost_equal(rbm1.components_, rbm2.components_) def test_gibbs_smoke(): """Check if we don't get NaNs sampling the full digits dataset.""" rng = np.random.RandomState(42) X = Xdigits rbm1 = BernoulliRBM(n_components=42, batch_size=40, n_iter=20, random_state=rng) rbm1.fit(X) X_sampled = rbm1.gibbs(X) assert_all_finite(X_sampled) def test_score_samples(): """Test score_samples (pseudo-likelihood) method.""" # Assert that pseudo-likelihood is computed without clipping. # See Fabian's blog, http://bit.ly/1iYefRk rng = np.random.RandomState(42) X = np.vstack([np.zeros(1000), np.ones(1000)]) rbm1 = BernoulliRBM(n_components=10, batch_size=2, n_iter=10, random_state=rng) rbm1.fit(X) assert_true((rbm1.score_samples(X) < -300).all()) # Sparse vs. dense should not affect the output. Also test sparse input # validation. rbm1.random_state = 42 d_score = rbm1.score_samples(X) rbm1.random_state = 42 s_score = rbm1.score_samples(lil_matrix(X)) assert_almost_equal(d_score, s_score) # Test numerical stability (#2785): would previously generate infinities # and crash with an exception. with np.errstate(under='ignore'): rbm1.score_samples(np.arange(1000) * 100) def test_rbm_verbose(): rbm = BernoulliRBM(n_iter=2, verbose=10) old_stdout = sys.stdout sys.stdout = StringIO() try: rbm.fit(Xdigits) finally: sys.stdout = old_stdout def test_sparse_and_verbose(): """ Make sure RBM works with sparse input when verbose=True """ old_stdout = sys.stdout sys.stdout = StringIO() from scipy.sparse import csc_matrix X = csc_matrix([[0.], [1.]]) rbm = BernoulliRBM(n_components=2, batch_size=2, n_iter=1, random_state=42, verbose=True) try: rbm.fit(X) s = sys.stdout.getvalue() # make sure output is sound assert_true(re.match(r"\[BernoulliRBM\] Iteration 1," r" pseudo-likelihood = -?(\d)+(\.\d+)?," r" time = (\d|\.)+s", s)) finally: sys.stdout = old_stdout
bsd-3-clause
mfittere/SixDeskDB
old/riccardo1/sixdeskdb.py
2
10486
import sqlite3 import numpy as np import matplotlib.pyplot as pl import scipy.signal from sqltable import SQLTable def guess_range(l): l=sorted(set(l)) start=l[0] if len(l)>1: step=np.diff(l).min() else: step=None stop=l[-1] return start,stop,step class Fort10(object): fields=[ ('turn_max', 'int', 'Maximum turn number'), ('sflag', 'int', 'Stability Flag (0=stable, 1=lost)'), ('qx', 'float', 'Horizontal Tune'), ('qy', 'float', 'Vertical Tune'), ('betx', 'float', 'Horizontal beta-function'), ('bety', 'float', 'Vertical beta-function'), ('sigx1', 'float', 'Horizontal amplitude 1st particle'), ('sigy1', 'float', 'Vertical amplitude 1st particle'), ('deltap', 'float', 'Relative momentum deviation Deltap'), ('dist', 'float', 'Final distance in phase space'), ('distp', 'float', 'Maximumslope of distance in phase space'), ('qx_det', 'float', 'Horizontal detuning'), ('qx_spread', 'float', 'Spread of horizontal detuning'), ('qy_det', 'float', 'Vertical detuning'), ('qy_spread', 'float', 'Spread of vertical detuning'), ('resxfact', 'float', 'Horizontal factor to nearest resonance'), ('resyfact', 'float', 'Vertical factor to nearest resonance'), ('resorder', 'int', 'Order of nearest resonance'), ('smearx', 'float', 'Horizontal smear'), ('smeary', 'float', 'Vertical smear'), ('smeart', 'float', 'Transverse smear'), ('sturns1', 'int', 'Survived turns 1st particle'), ('sturns2', 'int', 'Survived turns 2nd particle'), ('sseed', 'float', 'Starting seed for random generator'), ('qs', 'float', 'Synchrotron tune'), ('sigx2', 'float', 'Horizontal amplitude 2nd particle'), ('sigy2', 'float', 'Vertical amplitude 2nd particle'), ('sigxmin', 'float', 'Minimum horizontal amplitude'), ('sigxavg', 'float', 'Mean horizontal amplitude'), ('sigxmax', 'float', 'Maximum horizontal amplitude'), ('sigymin', 'float', 'Minimum vertical amplitude'), ('sigyavg', 'float', 'Mean vertical amplitude'), ('sigymax', 'float', 'Maximum vertical amplitude'), ('sigxminld', 'float', 'Minimum horizontal amplitude (linear decoupled)'), ('sigxavgld', 'float', 'Mean horizontal amplitude (linear decoupled)'), ('sigxmaxld', 'float', 'Maximum horizontal amplitude (linear decoupled)'), ('sigyminld', 'float', 'Minimum vertical amplitude (linear decoupled)'), ('sigyavgld', 'float', 'Mean vertical amplitude (linear decoupled)'), ('sigymaxld', 'float', 'Maximum vertical amplitude (linear decoupled)'), ('sigxminnld', 'float','Minimum horizontal amplitude (nonlinear decoupled)'), ('sigxavgnld', 'float', 'Mean horizontal amplitude (nonlinear decoupled)'), ('sigxmaxnld', 'float','Maximum horizontal amplitude (nonlinear decoupled)'), ('sigyminnld', 'float', 'Minimum vertical amplitude (nonlinear decoupled)'), ('sigyavgnld', 'float', 'Mean vertical amplitude (nonlinear decoupled)'), ('sigymaxnld', 'float', 'Maximum vertical amplitude (nonlinear decoupled)'), ('emitx', 'float', 'Emittance Mode I'), ('emity', 'float', 'Emittance Mode II'), ('betx2', 'float', 'Secondary horizontal beta-function'), ('bety2', 'float', 'Secondary vertical beta-function'), ('qpx', 'float', "Q'x"), ('qpy', 'float', "Q'y"), ('dum1', 'float', 'Dummy1'), ('dum2', 'float', 'Dummy2'), ('dum3', 'float', 'Dummy3'), ('dum4', 'float', 'Dummy4'), ('dum5', 'float', 'Dummy5'), ('dum6', 'float', 'Dummy6'), ('dum7', 'float', 'Dummy7'), ('int1', 'float', 'Internal1'), ('int2', 'float', 'Internal2')] class JobParams(object): fields=[ ('study','str',''), ('seed','int',''), ('tunex','float',''), ('tuney','float',''), ('amp1','float',''), ('amp2','float',''), ('joined','str',''), ('turns','int',''), ('angle','float',''), ('row','int','') ] class Study(object): fields=[ ('trackdir','str','path hosting the tracking results e.g. name/'), ('LHCDescrip','str','name of the job and mask file'), ('sixtrack_input','str','path hosting the sixtrack input'), ('ista','int','initial seed number'), ('iend','int','final seed number'), ('tunex','float','initial tunex'), ('tuney','float','initial tuney'), ('deltax','float','step in tunex'), ('deltay','float','step in tuney'), ('tunex1','float','final tunex'), ('tuney1','float','final tuney'), ('kinil','float','initial angle index'), ('kendl','float','final angle index'), ('kmaxl','float','max angle index'), ('kstep','float','final angle step'), ('ns1l','float','initial amplitude'), ('ns2l','float','final amplitude'), ('nsincl','float','amplitude step'), ('turnsl','int','turns for long run')] class SixDeskDB(object): def __init__(self,dbname): self.dbname=dbname self.db=sqlite3.connect(dbname) self.make_result_table() def make_result_table(self): jobnames=[c[0] for c in JobParams.fields] res=JobParams.fields+Fort10.fields cols=SQLTable.cols_from_fields(res) self.results=SQLTable(self.db,'results',cols,keys=jobnames) def add_results(self,data): db=self.db;table='results' sql="REPLACE INTO %s VALUES (%s)" vals=','.join(('?')*len(self.results.cols)) sql_cmd=sql%(table,vals) cur=db.cursor() cur.executemany(sql_cmd, data) db.commit() def execute(self,sql): cur=self.db.cursor() cur.execute(sql) self.db.commit() return list(cur) def inspect_results(self): names='seed,tunex,tuney,amp1,amp2,turns,angle' for name in names.split(','): sql="SELECT DISTINCT %s FROM results"%name print sql data=[d[0] for d in self.execute(sql)] print name, guess_range(data) def iter_job_params(self): names='study,seed,tunex,tuney,amp1,amp2,turns,angle,row' sql='SELECT DISTINCT %s FROM results'%names return self.db.cursor().execute(sql) def iter_job_params_comp(self): names='seed,tunex,tuney,amp1,amp2,turns,angle' sql='SELECT DISTINCT %s FROM results'%names return self.db.cursor().execute(sql) def get_num_results(self): return self.execute('SELECT count(*) from results')[0][0] def inspect_jobparams(self): data=list(self.iter_job_params()) names='study,seed,tunex,tuney,amp1,amp2,turns,angle,row'.split(',') data=dict(zip(names,zip(*data))) # for name in names: # print name, guess_range(data[name]) # print 'results found',len(data['seed']) turns=list(set(data['turns'])) p={} p['ista'],p['iend'],p['istep']=guess_range(data['seed']) p['tunex'],p['tunex1'],p['deltax']=guess_range(data['tunex']) p['tuney'],p['tuney1'],p['deltay']=guess_range(data['tuney']) if p['deltax'] is None: p['deltax']=0.0001 if p['deltay'] is None: p['deltay']=0.0001 a1,a2,ast=guess_range(data['angle']) p['kmaxl']=90/ast-1 p['kinil']=a1/ast p['kendl']=a2/ast p['kstep']=1 p['ns1l'],p['ns2l'],p['nsincl']=guess_range(data['amp1']+data['amp2']) p['turnsl']=max(data['turns']) p['sixdeskpairs']=max(data['row'])+1 p['LHCDescrip']=data['study'][0] return p def get_survival_turns(self,seed): cmd="""SELECT angle,amp1+(amp2-amp1)*row/30, CASE WHEN sturns1 < sturns2 THEN sturns1 ELSE sturns2 END FROM results WHERE seed=%s ORDER BY angle,sigx1""" cmd="""SELECT angle,sqrt(sigx1**2+sigy1**2), CASE WHEN sturns1 < sturns2 THEN sturns1 ELSE sturns2 END FROM results WHERE seed=%s ORDER BY angle,sigx1""" cur=self.db.cursor().execute(cmd%seed) ftype=[('angle',float),('amp',float),('surv',float)] data=np.fromiter(cur,dtype=ftype) angles=len(set(data['angle'])) return data.reshape(angles,-1) def plot_survival_2d(self,seed,smooth=None): data=self.get_survival_turns(seed) a,s,t=data['angle'],data['amp'],data['surv'] self._plot_survival_2d(a,s,t,smooth=smooth) pl.title('Seed %d survived turns'%seed) def plot_survival_2d_avg(self,smooth=None): cmd="""SELECT seed,angle,amp1+(amp2-amp1)*row/30, CASE WHEN sturns1 < sturns2 THEN sturns1 ELSE sturns2 END FROM results ORDER BY seed,angle,sigx1""" cur=self.db.cursor().execute(cmd) ftype=[('seed',float),('angle',float),('amp',float),('surv',float)] data=np.fromiter(cur,dtype=ftype) angles=len(set(data['angle'])) seeds=len(set(data['seed'])) data=data.reshape(seeds,angles,-1) a,s,t=data['angle'],data['amp'],data['surv'] a=a.mean(axis=0); s=s.mean(axis=0); t=t.mean(axis=0); self._plot_survival_2d(a,s,t,smooth=smooth) pl.title('Survived turns') def _plot_survival_2d(self,a,s,t,smooth=None): rad=np.pi*a/180 x=s*np.cos(rad) y=s*np.sin(rad) #t=np.log10(t) if smooth is not None: if type(smooth)==int: smooth=np.ones((1.,smooth))/smooth elif type(smooth)==tuple: smooth=np.ones(smooth)/float(smooth[0]*smooth[1]) t=scipy.signal.fftconvolve(smooth,t,mode='full') pl.pcolormesh(x,y,t,antialiased=True) pl.xlabel(r'$\sigma_x$') pl.ylabel(r'$\sigma_y$') pl.colorbar() def plot_survival_avg(self,seed): data=self.get_survival_turns(seed) a,s,t=data['angle'],data['amp'],data['surv'] rad=np.pi*a/180 drad=rad[0,0] slab='Seed %d'%seed #savg2=s**4*np.sin(2*rad)*drad pl.plot(s.mean(axis=0),t.min(axis=0) ,label='min') pl.plot(s.mean(axis=0),t.mean(axis=0),label='avg') pl.plot(s.mean(axis=0),t.max(axis=0) ,label='max') pl.ylim(0,pl.ylim()[1]*1.1) pl.xlabel(r'$\sigma$') pl.ylabel(r'survived turns') pl.legend(loc='lower left') return data def plot_survival_avg2(self,seed): def mk_tuple(a,s,t,nlim): region=[] for ia,ts in enumerate(t): cond=np.where(ts<=nlim)[0] #print ts[cond] if len(cond)>0: it=cond[0] else: it=-1 region.append((ia,it)) #print ts[it],s[ia,it] region=zip(*region) #print t[region] tmin=t[region].min() tavg=t[region].mean() tmax=t[region].max() savg=s[region].mean() rad=np.pi*a[region]/180 drad=rad[0] savg2=np.sum(s[region]**4*np.sin(2*rad)*drad)**.25 return nlim,tmin,tavg,tmax,savg,savg2 data=self.get_survival_turns(seed) a,s,t=data['angle'],data['amp'],data['surv'] table=np.array([mk_tuple(a,s,t,nlim) for nlim in np.arange(0,1.1e6,1e4)]).T nlim,tmin,tavg,tmax,savg,savg2=table pl.plot(savg,tmin,label='min') pl.plot(savg,tavg,label='avg') pl.plot(savg,tmax,label='max') return table
lgpl-2.1
deepcharles/ruptures
tests/test_display.py
1
2596
import pytest from ruptures.datasets import pw_constant from ruptures.show import display from ruptures.show.display import MatplotlibMissingError @pytest.fixture(scope="module") def signal_bkps(): signal, bkps = pw_constant() return signal, bkps def test_display_with_options(signal_bkps): try: signal, bkps = signal_bkps fig, axarr = display(signal, bkps) fig, axarr = display(signal, bkps, bkps) figsize = (20, 10) # figure size fig, axarr = display( signal, bkps, figsize=figsize, ) fig, axarr = display( signal[:, 0], bkps, figsize=figsize, ) except MatplotlibMissingError: pytest.skip("matplotlib is not installed") def test_display_without_options(signal_bkps): try: signal, bkps = signal_bkps fig, axarr = display(signal, bkps) fig, axarr = display(signal, bkps, bkps) figsize = (20, 10) # figure size fig, axarr = display(signal, bkps) fig, axarr = display(signal[:, 0], bkps) except MatplotlibMissingError: pytest.skip("matplotlib is not installed") def test_display_with_new_options(signal_bkps): try: signal, bkps = signal_bkps fig, axarr = display(signal, bkps) fig, axarr = display(signal, bkps, bkps) fig, axarr = display(signal, bkps, facecolor="k", edgecolor="b") fig, axarr = display(signal[:, 0], bkps, facecolor="k", edgecolor="b") except MatplotlibMissingError: pytest.skip("matplotlib is not installed") def test_display_with_computed_chg_pts_options(signal_bkps): try: signal, bkps = signal_bkps fig, axarr = display(signal, bkps) fig, axarr = display(signal, bkps, bkps) fig, axarr = display(signal, bkps, bkps, computed_chg_pts_color="k") fig, axarr = display( signal, bkps, bkps, computed_chg_pts_color="k", computed_chg_pts_linewidth=3 ) fig, axarr = display( signal, bkps, bkps, computed_chg_pts_color="k", computed_chg_pts_linewidth=3, computed_chg_pts_linestyle="--", ) fig, axarr = display( signal, bkps, bkps, computed_chg_pts_color="k", computed_chg_pts_linewidth=3, computed_chg_pts_linestyle="--", computed_chg_pts_alpha=1.0, ) except MatplotlibMissingError: pytest.skip("matplotlib is not installed")
bsd-2-clause
wmvanvliet/mne-python
tutorials/source-modeling/plot_mne_dspm_source_localization.py
1
5668
""" .. _tut-inverse-methods: Source localization with MNE/dSPM/sLORETA/eLORETA ================================================= The aim of this tutorial is to teach you how to compute and apply a linear minimum-norm inverse method on evoked/raw/epochs data. """ import os.path as op import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse ############################################################################### # Process MEG data data_path = sample.data_path() raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_filt-0-40_raw.fif') raw = mne.io.read_raw_fif(raw_fname) # already has an average reference events = mne.find_events(raw, stim_channel='STI 014') event_id = dict(aud_l=1) # event trigger and conditions tmin = -0.2 # start of each epoch (200ms before the trigger) tmax = 0.5 # end of each epoch (500ms after the trigger) raw.info['bads'] = ['MEG 2443', 'EEG 053'] baseline = (None, 0) # means from the first instant to t = 0 reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=('meg', 'eog'), baseline=baseline, reject=reject) ############################################################################### # Compute regularized noise covariance # ------------------------------------ # # For more details see :ref:`tut_compute_covariance`. noise_cov = mne.compute_covariance( epochs, tmax=0., method=['shrunk', 'empirical'], rank=None, verbose=True) fig_cov, fig_spectra = mne.viz.plot_cov(noise_cov, raw.info) ############################################################################### # Compute the evoked response # --------------------------- # Let's just use the MEG channels for simplicity. evoked = epochs.average().pick('meg') evoked.plot(time_unit='s') evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag', time_unit='s') ############################################################################### # It's also a good idea to look at whitened data: evoked.plot_white(noise_cov, time_unit='s') del epochs, raw # to save memory ############################################################################### # Inverse modeling: MNE/dSPM on evoked and raw data # ------------------------------------------------- # Here we first read the forward solution. You will likely need to compute # one for your own data -- see :ref:`tut-forward` for information on how # to do it. fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif' fwd = mne.read_forward_solution(fname_fwd) ############################################################################### # Next, we make an MEG inverse operator. inverse_operator = make_inverse_operator( evoked.info, fwd, noise_cov, loose=0.2, depth=0.8) del fwd # You can write it to disk with:: # # >>> from mne.minimum_norm import write_inverse_operator # >>> write_inverse_operator('sample_audvis-meg-oct-6-inv.fif', # inverse_operator) ############################################################################### # Compute inverse solution # ------------------------ # We can use this to compute the inverse solution and obtain source time # courses: method = "dSPM" snr = 3. lambda2 = 1. / snr ** 2 stc, residual = apply_inverse(evoked, inverse_operator, lambda2, method=method, pick_ori=None, return_residual=True, verbose=True) ############################################################################### # Visualization # ------------- # We can look at different dipole activations: fig, ax = plt.subplots() ax.plot(1e3 * stc.times, stc.data[::100, :].T) ax.set(xlabel='time (ms)', ylabel='%s value' % method) ############################################################################### # Examine the original data and the residual after fitting: fig, axes = plt.subplots(2, 1) evoked.plot(axes=axes) for ax in axes: ax.texts = [] for line in ax.lines: line.set_color('#98df81') residual.plot(axes=axes) ############################################################################### # Here we use peak getter to move visualization to the time point of the peak # and draw a marker at the maximum peak vertex. # sphinx_gallery_thumbnail_number = 9 vertno_max, time_max = stc.get_peak(hemi='rh') subjects_dir = data_path + '/subjects' surfer_kwargs = dict( hemi='rh', subjects_dir=subjects_dir, clim=dict(kind='value', lims=[8, 12, 15]), views='lateral', initial_time=time_max, time_unit='s', size=(800, 800), smoothing_steps=10) brain = stc.plot(**surfer_kwargs) brain.add_foci(vertno_max, coords_as_verts=True, hemi='rh', color='blue', scale_factor=0.6, alpha=0.5) brain.add_text(0.1, 0.9, 'dSPM (plus location of maximal activation)', 'title', font_size=14) # The documentation website's movie is generated with: # brain.save_movie(..., tmin=0.05, tmax=0.15, interpolation='linear', # time_dilation=20, framerate=10, time_viewer=True) ############################################################################### # There are many other ways to visualize and work with source data, see # for example: # # - :ref:`tut-viz-stcs` # - :ref:`ex-morph-surface` # - :ref:`ex-morph-volume` # - :ref:`ex-vector-mne-solution` # - :ref:`tut-dipole-orientations` # - :ref:`tut-mne-fixed-free` # - :ref:`examples using apply_inverse # <sphx_glr_backreferences_mne.minimum_norm.apply_inverse>`.
bsd-3-clause
stargaser/astropy
astropy/modeling/utils.py
2
25636
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module provides utility functions for the models package """ from collections import deque, UserDict from collections.abc import MutableMapping from inspect import signature import numpy as np from astropy.utils.decorators import deprecated from astropy.utils import isiterable, check_broadcast from astropy import units as u __all__ = ['ExpressionTree', 'AliasDict', 'check_broadcast', 'poly_map_domain', 'comb', 'ellipse_extent'] @deprecated('4.0') class ExpressionTree: __slots__ = ['left', 'right', 'value', 'inputs', 'outputs'] def __init__(self, value, left=None, right=None, inputs=None, outputs=None): self.value = value self.inputs = inputs self.outputs = outputs self.left = left # Two subtrees can't be the same *object* or else traverse_postorder # breaks, so we just always copy the right subtree to subvert that. if right is not None and left is right: right = right.copy() self.right = right def __getstate__(self): # For some reason the default pickle protocol on Python 2 does not just # do this. On Python 3 it's not a problem. return dict((slot, getattr(self, slot)) for slot in self.__slots__) def __setstate__(self, state): for slot, value in state.items(): setattr(self, slot, value) @staticmethod def _recursive_lookup(branch, adict, key): if isinstance(branch, ExpressionTree): return adict[key] else: return branch, key @property def inputs_map(self): """ Map the names of the inputs to this ExpressionTree to the inputs to the leaf models. """ inputs_map = {} if not isinstance(self.value, str): # If we don't have an operator the mapping is trivial return {inp: (self.value, inp) for inp in self.inputs} elif self.value == '|': l_inputs_map = self.left.inputs_map for inp in self.inputs: m, inp2 = self._recursive_lookup(self.left, l_inputs_map, inp) inputs_map[inp] = m, inp2 elif self.value == '&': l_inputs_map = self.left.inputs_map r_inputs_map = self.right.inputs_map for i, inp in enumerate(self.inputs): if i < len(self.left.inputs): # Get from left m, inp2 = self._recursive_lookup(self.left, l_inputs_map, self.left.inputs[i]) inputs_map[inp] = m, inp2 else: # Get from right m, inp2 = self._recursive_lookup(self.right, r_inputs_map, self.right.inputs[i - len(self.left.inputs)]) inputs_map[inp] = m, inp2 else: l_inputs_map = self.left.inputs_map for inp in self.left.inputs: m, inp2 = self._recursive_lookup(self.left, l_inputs_map, inp) inputs_map[inp] = m, inp2 return inputs_map @property def outputs_map(self): """ Map the names of the outputs to this ExpressionTree to the outputs to the leaf models. """ outputs_map = {} if not isinstance(self.value, str): # If we don't have an operator the mapping is trivial return {out: (self.value, out) for out in self.outputs} elif self.value == '|': r_outputs_map = self.right.outputs_map for out in self.outputs: m, out2 = self._recursive_lookup(self.right, r_outputs_map, out) outputs_map[out] = m, out2 elif self.value == '&': r_outputs_map = self.right.outputs_map l_outputs_map = self.left.outputs_map for i, out in enumerate(self.outputs): if i < len(self.left.outputs): # Get from left m, out2 = self._recursive_lookup(self.left, l_outputs_map, self.left.outputs[i]) outputs_map[out] = m, out2 else: # Get from right m, out2 = self._recursive_lookup(self.right, r_outputs_map, self.right.outputs[i - len(self.left.outputs)]) outputs_map[out] = m, out2 else: l_outputs_map = self.left.outputs_map for out in self.left.outputs: m, out2 = self._recursive_lookup(self.left, l_outputs_map, out) outputs_map[out] = m, out2 return outputs_map @property def isleaf(self): return self.left is None and self.right is None def traverse_preorder(self): stack = deque([self]) while stack: node = stack.pop() yield node if node.right is not None: stack.append(node.right) if node.left is not None: stack.append(node.left) def traverse_inorder(self): stack = deque() node = self while stack or node is not None: if node is not None: stack.append(node) node = node.left else: node = stack.pop() yield node node = node.right def traverse_postorder(self): stack = deque([self]) last = None while stack: node = stack[-1] if last is None or node is last.left or node is last.right: if node.left is not None: stack.append(node.left) elif node.right is not None: stack.append(node.right) elif node.left is last and node.right is not None: stack.append(node.right) else: yield stack.pop() last = node def evaluate(self, operators, getter=None, start=0, stop=None): """Evaluate the expression represented by this tree. ``Operators`` should be a dictionary mapping operator names ('tensor', 'product', etc.) to a function that implements that operator for the correct number of operands. If given, ``getter`` is a function evaluated on each *leaf* node's value before applying the operator between them. This could be used, for example, to operate on an attribute of the node values rather than directly on the node values. The ``getter`` is passed both the index of the leaf (a count starting at 0 that is incremented after each leaf is found) and the leaf node itself. The ``start`` and ``stop`` arguments allow evaluating a sub-expression within the expression tree. TODO: Document this better. """ stack = deque() if getter is None: getter = lambda idx, value: value if start is None: start = 0 leaf_idx = 0 for node in self.traverse_postorder(): if node.isleaf: # For a "tree" containing just a single operator at the root # Also push the index of this leaf onto the stack, which will # prove useful for evaluating subexpressions stack.append((getter(leaf_idx, node.value), leaf_idx)) leaf_idx += 1 else: operator = operators[node.value] if len(stack) < 2: # Skip this operator if there are not enough operands on # the stack; this can happen if some operands were skipped # when evaluating a sub-expression continue right = stack.pop() left = stack.pop() operands = [] for operand in (left, right): # idx is the leaf index; -1 if not a leaf node if operand[-1] == -1: operands.append(operand) else: operand, idx = operand if start <= idx and (stop is None or idx < stop): operands.append((operand, idx)) if len(operands) == 2: # evaluate the operator with the given operands and place # the result on the stack (with -1 for the "leaf index" # since this result is not a leaf node left, right = operands stack.append((operator(left[0], right[0]), -1)) elif len(operands) == 0: # Just push the left one back on the stack # TODO: Explain and/or refactor this better # This is here because even if both operands were "skipped" # due to being outside the (start, stop) range, we've only # skipped one operator. But there should be at least 2 # operators involving these operands, so we push the one # from the left back onto the stack so that the next # operator will be skipped as well. Should probably come # up with an easier to follow way to write this algorithm stack.append(left) else: # one or more of the operands was not included in the # sub-expression slice, so don't evaluate the operator; # instead place left over operands (if any) back on the # stack for later use stack.extend(operands) return stack.pop()[0] def copy(self): # Hopefully this won't blow the stack for any practical case; if such a # case arises that this won't work then I suppose we can find an # iterative approach. children = [] for child in (self.left, self.right): if isinstance(child, ExpressionTree): children.append(child.copy()) else: children.append(child) return self.__class__(self.value, left=children[0], right=children[1]) def format_expression(self, operator_precedence, format_leaf=None): leaf_idx = 0 operands = deque() if format_leaf is None: format_leaf = lambda i, l: f'[{i}]' for node in self.traverse_postorder(): if node.isleaf: operands.append(format_leaf(leaf_idx, node)) leaf_idx += 1 continue oper_order = operator_precedence[node.value] right = operands.pop() left = operands.pop() if (node.left is not None and not node.left.isleaf and operator_precedence[node.left.value] < oper_order): left = f'({left})' if (node.right is not None and not node.right.isleaf and operator_precedence[node.right.value] < oper_order): right = f'({right})' operands.append(' '.join((left, node.value, right))) return ''.join(operands) class AliasDict(MutableMapping): """ Creates a `dict` like object that wraps an existing `dict` or other `MutableMapping`, along with a `dict` of *key aliases* that translate between specific keys in this dict to different keys in the underlying dict. In other words, keys that do not have an associated alias are accessed and stored like a normal `dict`. However, a key that has an alias is accessed and stored to the "parent" dict via the alias. Parameters ---------- parent : dict-like The parent `dict` that aliased keys and accessed from and stored to. aliases : dict-like Maps keys in this dict to their associated keys in the parent dict. Examples -------- >>> parent = {'a': 1, 'b': 2, 'c': 3} >>> aliases = {'foo': 'a', 'bar': 'c'} >>> alias_dict = AliasDict(parent, aliases) >>> alias_dict['foo'] 1 >>> alias_dict['bar'] 3 Keys in the original parent dict are not visible if they were not aliased:: >>> alias_dict['b'] Traceback (most recent call last): ... KeyError: 'b' Likewise, updates to aliased keys are reflected back in the parent dict:: >>> alias_dict['foo'] = 42 >>> alias_dict['foo'] 42 >>> parent['a'] 42 However, updates/insertions to keys that are *not* aliased are not reflected in the parent dict:: >>> alias_dict['qux'] = 99 >>> alias_dict['qux'] 99 >>> 'qux' in parent False In particular, updates on the `AliasDict` to a key that is equal to one of the aliased keys in the parent dict does *not* update the parent dict. For example, ``alias_dict`` aliases ``'foo'`` to ``'a'``. But assigning to a key ``'a'`` on the `AliasDict` does not impact the parent:: >>> alias_dict['a'] = 'nope' >>> alias_dict['a'] 'nope' >>> parent['a'] 42 """ _store_type = dict """ Subclasses may override this to use other mapping types as the underlying storage, for example an `OrderedDict`. However, even in this case additional work may be needed to get things like the ordering right. """ def __init__(self, parent, aliases): self._parent = parent self._store = self._store_type() self._aliases = dict(aliases) def __getitem__(self, key): if key in self._aliases: try: return self._parent[self._aliases[key]] except KeyError: raise KeyError(key) return self._store[key] def __setitem__(self, key, value): if key in self._aliases: self._parent[self._aliases[key]] = value else: self._store[key] = value def __delitem__(self, key): if key in self._aliases: try: del self._parent[self._aliases[key]] except KeyError: raise KeyError(key) else: del self._store[key] def __iter__(self): """ First iterates over keys from the parent dict (if the aliased keys are present in the parent), followed by any keys in the local store. """ for key, alias in self._aliases.items(): if alias in self._parent: yield key for key in self._store: yield key def __len__(self): # TODO: # This could be done more efficiently, but at present the use case for # it is narrow if non-existent. return len(list(iter(self))) def __repr__(self): # repr() just like any other dict--this should look transparent store_copy = self._store_type() for key, alias in self._aliases.items(): if alias in self._parent: store_copy[key] = self._parent[alias] store_copy.update(self._store) return repr(store_copy) class _BoundingBox(tuple): """ Base class for models with custom bounding box templates (methods that return an actual bounding box tuple given some adjustable parameters--see for example `~astropy.modeling.models.Gaussian1D.bounding_box`). On these classes the ``bounding_box`` property still returns a `tuple` giving the default bounding box for that instance of the model. But that tuple may also be a subclass of this class that is callable, and allows a new tuple to be returned using a user-supplied value for any adjustable parameters to the bounding box. """ _model = None def __new__(cls, input_, _model=None): self = super().__new__(cls, input_) if _model is not None: # Bind this _BoundingBox (most likely a subclass) to a Model # instance so that its __call__ can access the model self._model = _model return self def __call__(self, *args, **kwargs): raise NotImplementedError( "This bounding box is fixed by the model and does not have " "adjustable parameters.") @classmethod def validate(cls, model, bounding_box): """ Validate a given bounding box sequence against the given model (which may be either a subclass of `~astropy.modeling.Model` or an instance thereof, so long as the ``.inputs`` attribute is defined. Currently this just checks that the bounding_box is either a 2-tuple of lower and upper bounds for 1-D models, or an N-tuple of 2-tuples for N-D models. This also returns a normalized version of the bounding_box input to ensure it is always an N-tuple (even for the 1-D case). """ nd = model.n_inputs if nd == 1: MESSAGE = "Bounding box for {0} model must be a sequence of length " "2 consisting of a lower and upper bound, or a 1-tuple " f"containing such a sequence as its sole element." try: valid_shape = np.shape(bounding_box) in ((2,), (1, 2)) except TypeError: # np.shape does not work with lists of Quantities valid_shape = np.shape([b.to_value() for b in bounding_box]) in ((2,), (1, 2)) except ValueError: raise ValueError(MESSAGE) if not isiterable(bounding_box) or not valid_shape: raise ValueError(MESSAGE) if len(bounding_box) == 1: return cls((tuple(bounding_box[0]),)) else: return cls(tuple(bounding_box)) else: MESSAGE = "Bounding box for {0} model must be a sequence of length " "{1} (the number of model inputs) consisting of pairs of " "lower and upper bounds for those inputs on which to " f"evaluate the model." try: valid_shape = all([len(i) == 2 for i in bounding_box]) except TypeError: valid_shape = False if len(bounding_box) != nd: valid_shape = False if not isiterable(bounding_box) or not valid_shape: raise ValueError(MESSAGE) return cls(tuple(bounds) for bounds in bounding_box) def make_binary_operator_eval(oper, f, g): """ Given a binary operator (as a callable of two arguments) ``oper`` and two callables ``f`` and ``g`` which accept the same arguments, returns a *new* function that takes the same arguments as ``f`` and ``g``, but passes the outputs of ``f`` and ``g`` in the given ``oper``. ``f`` and ``g`` are assumed to return tuples (which may be 1-tuples). The given operator is applied element-wise to tuple outputs). Example ------- >>> from operator import add >>> def prod(x, y): ... return (x * y,) ... >>> sum_of_prod = make_binary_operator_eval(add, prod, prod) >>> sum_of_prod(3, 5) (30,) """ return lambda inputs, params: \ tuple(oper(x, y) for x, y in zip(f(inputs, params), g(inputs, params))) def poly_map_domain(oldx, domain, window): """ Map domain into window by shifting and scaling. Parameters ---------- oldx : array original coordinates domain : list or tuple of length 2 function domain window : list or tuple of length 2 range into which to map the domain """ domain = np.array(domain, dtype=np.float64) window = np.array(window, dtype=np.float64) scl = (window[1] - window[0]) / (domain[1] - domain[0]) off = (window[0] * domain[1] - window[1] * domain[0]) / (domain[1] - domain[0]) return off + scl * oldx def comb(N, k): """ The number of combinations of N things taken k at a time. Parameters ---------- N : int, array Number of things. k : int, array Number of elements taken. """ if (k > N) or (N < 0) or (k < 0): return 0 val = 1 for j in range(min(k, N - k)): val = (val * (N - j)) / (j + 1) return val def array_repr_oneline(array): """ Represents a multi-dimensional Numpy array flattened onto a single line. """ r = np.array2string(array, separator=', ', suppress_small=True) return ' '.join(l.strip() for l in r.splitlines()) def combine_labels(left, right): """ For use with the join operator &: Combine left input/output labels with right input/output labels. If none of the labels conflict then this just returns a sum of tuples. However if *any* of the labels conflict, this appends '0' to the left-hand labels and '1' to the right-hand labels so there is no ambiguity). """ if set(left).intersection(right): left = tuple(l + '0' for l in left) right = tuple(r + '1' for r in right) return left + right def ellipse_extent(a, b, theta): """ Calculates the extent of a box encapsulating a rotated 2D ellipse. Parameters ---------- a : float or `~astropy.units.Quantity` Major axis. b : float or `~astropy.units.Quantity` Minor axis. theta : float or `~astropy.units.Quantity` Rotation angle. If given as a floating-point value, it is assumed to be in radians. Returns ------- offsets : tuple The absolute value of the offset distances from the ellipse center that define its bounding box region, ``(dx, dy)``. Examples -------- .. plot:: :include-source: import numpy as np import matplotlib.pyplot as plt from astropy.modeling.models import Ellipse2D from astropy.modeling.utils import ellipse_extent, render_model amplitude = 1 x0 = 50 y0 = 50 a = 30 b = 10 theta = np.pi/4 model = Ellipse2D(amplitude, x0, y0, a, b, theta) dx, dy = ellipse_extent(a, b, theta) limits = [x0 - dx, x0 + dx, y0 - dy, y0 + dy] model.bounding_box = limits image = render_model(model) plt.imshow(image, cmap='binary', interpolation='nearest', alpha=.5, extent = limits) plt.show() """ t = np.arctan2(-b * np.tan(theta), a) dx = a * np.cos(t) * np.cos(theta) - b * np.sin(t) * np.sin(theta) t = np.arctan2(b, a * np.tan(theta)) dy = b * np.sin(t) * np.cos(theta) + a * np.cos(t) * np.sin(theta) if isinstance(dx, u.Quantity) or isinstance(dy, u.Quantity): return np.abs(u.Quantity([dx, dy])) else: return np.abs([dx, dy]) def get_inputs_and_params(func): """ Given a callable, determine the input variables and the parameters. Parameters ---------- func : callable Returns ------- inputs, params : tuple Each entry is a list of inspect.Parameter objects """ sig = signature(func) inputs = [] params = [] for param in sig.parameters.values(): if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD): raise ValueError("Signature must not have *args or **kwargs") if param.default == param.empty: inputs.append(param) else: params.append(param) return inputs, params def _parameter_with_unit(parameter, unit): if parameter.unit is None: return parameter.value * unit else: return parameter.quantity.to(unit) def _parameter_without_unit(value, old_unit, new_unit): if old_unit is None: return value else: return value * old_unit.to(new_unit) def _combine_equivalency_dict(keys, eq1=None, eq2=None): # Given two dictionaries that give equivalencies for a set of keys, for # example input value names, return a dictionary that includes all the # equivalencies eq = {} for key in keys: eq[key] = [] if eq1 is not None and key in eq1: eq[key].extend(eq1[key]) if eq2 is not None and key in eq2: eq[key].extend(eq2[key]) return eq def _to_radian(value): """ Convert ``value`` to radian. """ if isinstance(value, u.Quantity): return value.to(u.rad) else: return np.deg2rad(value) def _to_orig_unit(value, raw_unit=None, orig_unit=None): """ Convert value with ``raw_unit`` to ``orig_unit``. """ if raw_unit is not None: return (value * raw_unit).to(orig_unit) else: return np.rad2deg(value) class _ConstraintsDict(UserDict): """ Wrapper around UserDict to allow updating the constraints on a Parameter when the dictionary is updated. """ def __init__(self, model, constraint_type): self._model = model self.constraint_type = constraint_type c = {} for name in model.param_names: param = getattr(model, name) c[name] = getattr(param, constraint_type) super().__init__(c) def __setitem__(self, key, val): super().__setitem__(key, val) param = getattr(self._model, key) setattr(param, self.constraint_type, val)
bsd-3-clause
adi-foundry/nycodex
nycodex/scrape/dataset.py
1
6364
import os import tempfile from typing import Iterable, List, Tuple import geoalchemy2 import geopandas as gpd import pandas as pd import sqlalchemy as sa from nycodex import db from nycodex.logging import get_logger from . import exceptions, utils BASE = "https://data.cityofnewyork.us/api" RAW_SCHEMA = 'raw' NULL_VALUES = frozenset({"null", "", "n/a", "na", "nan", "none"}) logger = get_logger(__name__) def scrape(conn, dataset_id: str) -> None: session = db.Session(bind=conn) dataset = session.query( db.Dataset).filter(db.Dataset.id == dataset_id).first() log = logger.bind(dataset_id=dataset.id, dataset_type=dataset.asset_type) log.info(f"Scraping dataset {dataset_id}") if dataset.column_names: scrape_dataset(conn, dataset.id, dataset.column_names, dataset.column_sql_names, dataset.column_types) log.info("Successfully inserted") elif dataset.asset_type == db.AssetType.MAP.value: scrape_geojson(conn, dataset.id) log.info("Successfully inserted") else: log.warning("Illegal dataset_type") def scrape_geojson(conn: sa.engine.base.Connection, dataset_id: str) -> None: log = logger.bind(dataset_id=dataset_id, method="scrape_geojson") params = {"method": "export", "format": "GeoJSON"} url = f"{BASE}/geospatial/{dataset_id}" with utils.download_file(url, params=params) as fname: try: df = gpd.read_file(fname) except ValueError as e: raise exceptions.SocrataParseError from e for column in df.columns: if column == 'geometry': continue # Bad type inference try: df[column] = df[column].astype(int) continue except (ValueError, TypeError): pass try: df[column] = df[column].astype(float) continue except (ValueError, TypeError): pass try: df[column] = pd.to_datetime(df[column]) continue except (ValueError, TypeError): pass log.info("Inserting") # TODO: Use ogr2ogr2? # srid 4326 for latitude/longitude coordinates ty = df.geometry.map(lambda x: x.geometryType()).unique() if len(ty) != 1: msg = f"Too many geometry types detected: {ty}" raise exceptions.SocrataParseError(msg) ty = ty[0] df['geometry'] = df['geometry'].map( lambda x: geoalchemy2.WKTElement(x.wkt, srid=4326)) trans = conn.begin() try: conn.execute(f'DROP TABLE IF EXISTS "{RAW_SCHEMA}.{dataset_id}"') df.to_sql( f"{dataset_id}", conn, if_exists='replace', index=False, schema=RAW_SCHEMA, dtype={ "geometry": geoalchemy2.Geometry(geometry_type=ty, srid=4326) }) except Exception: trans.rollback() raise trans.commit() def scrape_dataset(conn, dataset_id, names, fields, types) -> None: assert all(len(f) <= 63 for f in fields) url = f"{BASE}/views/{dataset_id}/rows.csv" with utils.download_file(url, params={"accessType": "DOWNLOAD"}) as fname: try: df = pd.read_csv(fname, dtype={name: str for name in names}) except pd.errors.ParserError as e: raise exceptions.SocrataParseError from e df = df[names] # Reorder columns df.columns = fields # replace with normalized names columns, df = dataset_columns(df, types) schema = ", ".join( f'"{name}" {ty}' for name, ty in zip(df.columns, columns)) with tempfile.TemporaryDirectory() as tmpdir: path = os.path.abspath(os.path.join(tmpdir, "data.csv")) df.to_csv(path, header=False, index=False) # Handle Postgresql permission denied errors os.chmod(tmpdir, 0o775) os.chmod(path, 0o775) trans = conn.begin() conn.execute(f'DROP TABLE IF EXISTS {RAW_SCHEMA}."{dataset_id}"') conn.execute(f'CREATE TABLE {RAW_SCHEMA}."{dataset_id}" ({schema})') conn.execute(f""" COPY {RAW_SCHEMA}."{dataset_id}" FROM '{path}' WITH CSV NULL AS '' """) trans.commit() def dataset_columns(df: pd.DataFrame, types: Iterable[str]) -> Tuple[List[str], pd.DataFrame]: columns = [] for field, ty in zip(df.columns, types): column = df[field] mask = column.isnull() | column.str.lower().isin(NULL_VALUES) column_nonull = column[~mask] sql_type, column_nonull = _dataset_column(column_nonull, ty, field) df[field][mask] = "" df[field][~mask] = column_nonull columns.append(sql_type) return columns, df def _dataset_column(column: pd.Series, ty: str, field: str) -> Tuple[str, pd.Series]: if ty == db.DataType.CALENDAR_DATE: return "DATE", column elif ty == db.DataType.CHECKBOX: return "BOOLEAN", column elif ty == db.DataType.DATE: return "TIMESTAMP WITH TIME ZONE", column elif ty in { db.DataType.EMAIL, db.DataType.HTML, db.DataType.LOCATION, db.DataType.PHONE, db.DataType.TEXT, db.DataType.URL }: return "TEXT", column elif ty == db.DataType.MONEY: return "MONEY", column elif ty == db.DataType.NUMBER: try: ncolumn = pd.to_numeric(column) except (ValueError, TypeError) as e: raise exceptions.SocrataTypeError(field, ty, column.dtype) if pd.api.types.is_integer_dtype(ncolumn): min, max = ncolumn.min(), ncolumn.max() if -32768 < min and max < 32767: return "SMALLINT", column elif -2147483648 < min and max < 2147483647: return "INTEGER", column else: return "BIGINT", column return "DOUBLE PRECISION", column elif ty == db.DataType.PERCENT: if (column.str[-1] != "%").any(): raise exceptions.SocrataTypeError(field, ty, column.dtype) try: column = pd.to_numeric(column.str[:-1]) except (ValueError, TypeError) as e: raise exceptions.SocrataTypeError(field, ty, column.dtype) return "NUMERIC(6, 3)", column else: raise RuntimeError(f"Unknown datatype {ty}")
apache-2.0
zhangzhihan/computationalphysics_n2014301020035
Chapter3/chapter3-1/harmonic motion_RK method.py
2
1534
from matplotlib.pyplot import* g=-9.8;l=1;dt=0.04; def h_motion_RKmethod1(index1,end_time1,ango1): ang=[];ang_v=[];t=[] ang.append(ango1);ang_v.append(0);t.append(0) for i in range(int(end_time1/dt)): angm=ang[-1]+1/2*dt*ang_v[-1] ang_vm=ang_v[-1]+g/l*dt*ang[-1]**index1 ang_tmp=ang[-1]+ang_vm*dt ang.append(ang_tmp) ang_v_tmp=ang_v[-1]+g/l*dt*angm**index1 ang_v.append(ang_v_tmp) t.append(dt*(i+1)) plot(t,ang,'r-') def h_motion_RKmethod2(index2,end_time2,ango2): ang=[];ang_v=[];t=[] ang.append(ango2);ang_v.append(0);t.append(0) for i in range(int(end_time2/dt)): angm=ang[-1]+1/2*dt*ang_v[-1] ang_vm=ang_v[-1]+g/l*dt*ang[-1]**index2 ang_tmp=ang[-1]+ang_vm*dt ang.append(ang_tmp) ang_v_tmp=ang_v[-1]+g/l*dt*angm**index2 ang_v.append(ang_v_tmp) t.append(dt*(i+1)) plot(t,ang,'g-') def h_motion_RKmethod3(index3,end_time3,ango3): ang=[];ang_v=[];t=[] ang.append(ango3);ang_v.append(0);t.append(0) for i in range(int(end_time3/dt)): angm=ang[-1]+1/2*dt*ang_v[-1] ang_vm=ang_v[-1]+1*g/l*dt*ang[-1]**index3 ang_tmp=ang[-1]+ang_vm*dt ang.append(ang_tmp) ang_v_tmp=ang_v[-1]+g/l*dt*angm**index3 ang_v.append(ang_v_tmp) t.append(dt*(i+1)) plot(t,ang,'b-') def display_AT(A1,A2,A3): h_motion_RKmethod1(3,20,A1) h_motion_RKmethod2(3,20,A2) h_motion_RKmethod3(3,20,A3) show() display_AT(0.2,0.4,1.0)
mit
Upward-Spiral-Science/claritycontrol
assignments/textureHist.py
2
26420
#IMPORTANT: THE ABOVE PORTION IS A SCRIPT FROM SOLEM'S VISION BLOG # http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html import SimpleITK as sitk import clarity as cl # I wrote this module for easier operations on data import clarity.resources as rs import csv,gc # garbage memory collection :) import numpy as np import matplotlib.pyplot as plt import jgraph as ig from ipywidgets import interact, fixed from IPython.display import clear_output def display_images(fixed_image_z, moving_image_z, fixed_npa, moving_npa): # Create a figure with two subplots and the specified size. plt.subplots(1,2,figsize=(10,8)) # Draw the fixed image in the first subplot. plt.subplot(1,2,1) plt.imshow(fixed_npa[fixed_image_z,:,:],cmap=plt.cm.Greys_r); plt.title('fixed image') plt.axis('off') # Draw the moving image in the second subplot. plt.subplot(1,2,2) plt.imshow(moving_npa[moving_image_z,:,:],cmap=plt.cm.Greys_r); plt.title('moving image') plt.axis('off') plt.show() # Callback invoked by the IPython interact method for scrolling and modifying the alpha blending # of an image stack of two images that occupy the same physical space. def display_images_with_alpha(image_z, alpha, fixed, moving): img = (1.0 - alpha)*fixed[:,:,image_z] + alpha*moving[:,:,image_z] plt.imshow(sitk.GetArrayFromImage(img),cmap=plt.cm.Greys_r); plt.axis('off') plt.show() # Callback invoked when the StartEvent happens, sets up our new data. def start_plot(): global metric_values, multires_iterations metric_values = [] multires_iterations = [] # Callback invoked when the EndEvent happens, do cleanup of data and figure. def end_plot(): global metric_values, multires_iterations del metric_values del multires_iterations # Close figure, we don't want to get a duplicate of the plot latter on. plt.close() # Callback invoked when the IterationEvent happens, update our data and display new figure. def plot_values(registration_method): global metric_values, multires_iterations metric_values.append(registration_method.GetMetricValue()) # Clear the output area (wait=True, to reduce flickering), and plot current data clear_output(wait=True) # Plot the similarity metric values plt.plot(metric_values, 'r') plt.plot(multires_iterations, [metric_values[index] for index in multires_iterations], 'b*') plt.xlabel('Iteration Number',fontsize=12) plt.ylabel('Metric Value',fontsize=12) plt.show() # Callback invoked when the sitkMultiResolutionIterationEvent happens, update the index into the # metric_values list. def update_multires_iterations(): global metric_values, multires_iterations multires_iterations.append(len(metric_values)) def histeq(im,nbr_bins=256): #get image histogram imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) cdf = imhist.cumsum() #cumulative distribution function cdf = 255 * cdf / cdf[-1] #normalize #use linear interpolation of cdf to find new pixel values im2 = interp(im.flatten(),bins[:-1],cdf) return im2.reshape(im.shape), cdf from PIL import Image from numpy import * import nibabel as nb im = nb.load('../data/raw/Fear199.hdr') im = im.get_data() img = im[:,:,:,0] im2,cdf = histeq(img) print im print im2 nb.save(img,'../data/raw/HistFear199.hdr') ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
apache-2.0
fabianp/scikit-learn
examples/svm/plot_rbf_parameters.py
57
8096
''' ================== RBF SVM parameters ================== This example illustrates the effect of the parameters ``gamma`` and ``C`` of the Radius Basis Function (RBF) kernel SVM. Intuitively, the ``gamma`` parameter defines how far the influence of a single training example reaches, with low values meaning 'far' and high values meaning 'close'. The ``gamma`` parameters can be seen as the inverse of the radius of influence of samples selected by the model as support vectors. The ``C`` parameter trades off misclassification of training examples against simplicity of the decision surface. A low ``C`` makes the decision surface smooth, while a high ``C`` aims at classifying all training examples correctly by giving the model freedom to select more samples as support vectors. The first plot is a visualization of the decision function for a variety of parameter values on a simplified classification problem involving only 2 input features and 2 possible target classes (binary classification). Note that this kind of plot is not possible to do for problems with more features or target classes. The second plot is a heatmap of the classifier's cross-validation accuracy as a function of ``C`` and ``gamma``. For this example we explore a relatively large grid for illustration purposes. In practice, a logarithmic grid from :math:`10^{-3}` to :math:`10^3` is usually sufficient. If the best parameters lie on the boundaries of the grid, it can be extended in that direction in a subsequent search. Note that the heat map plot has a special colorbar with a midpoint value close to the score values of the best performing models so as to make it easy to tell them appart in the blink of an eye. The behavior of the model is very sensitive to the ``gamma`` parameter. If ``gamma`` is too large, the radius of the area of influence of the support vectors only includes the support vector itself and no amount of regularization with ``C`` will be able to prevent overfitting. When ``gamma`` is very small, the model is too constrained and cannot capture the complexity or "shape" of the data. The region of influence of any selected support vector would include the whole training set. The resulting model will behave similarly to a linear model with a set of hyperplanes that separate the centers of high density of any pair of two classes. For intermediate values, we can see on the second plot that good models can be found on a diagonal of ``C`` and ``gamma``. Smooth models (lower ``gamma`` values) can be made more complex by selecting a larger number of support vectors (larger ``C`` values) hence the diagonal of good performing models. Finally one can also observe that for some intermediate values of ``gamma`` we get equally performing models when ``C`` becomes very large: it is not necessary to regularize by limiting the number of support vectors. The radius of the RBF kernel alone acts as a good structural regularizer. In practice though it might still be interesting to limit the number of support vectors with a lower value of ``C`` so as to favor models that use less memory and that are faster to predict. We should also note that small differences in scores results from the random splits of the cross-validation procedure. Those spurious variations can be smoothed out by increasing the number of CV iterations ``n_iter`` at the expense of compute time. Increasing the value number of ``C_range`` and ``gamma_range`` steps will increase the resolution of the hyper-parameter heat map. ''' print(__doc__) import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import Normalize from sklearn.svm import SVC from sklearn.preprocessing import StandardScaler from sklearn.datasets import load_iris from sklearn.cross_validation import StratifiedShuffleSplit from sklearn.grid_search import GridSearchCV # Utility function to move the midpoint of a colormap to be around # the values of interest. class MidpointNormalize(Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint Normalize.__init__(self, vmin, vmax, clip) def __call__(self, value, clip=None): x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) ############################################################################## # Load and prepare data set # # dataset for grid search iris = load_iris() X = iris.data y = iris.target # Dataset for decision function visualization: we only keep the first two # features in X and sub-sample the dataset to keep only 2 classes and # make it a binary classification problem. X_2d = X[:, :2] X_2d = X_2d[y > 0] y_2d = y[y > 0] y_2d -= 1 # It is usually a good idea to scale the data for SVM training. # We are cheating a bit in this example in scaling all of the data, # instead of fitting the transformation on the training set and # just applying it on the test set. scaler = StandardScaler() X = scaler.fit_transform(X) X_2d = scaler.fit_transform(X_2d) ############################################################################## # Train classifiers # # For an initial search, a logarithmic grid with basis # 10 is often helpful. Using a basis of 2, a finer # tuning can be achieved but at a much higher cost. C_range = np.logspace(-2, 10, 13) gamma_range = np.logspace(-9, 3, 13) param_grid = dict(gamma=gamma_range, C=C_range) cv = StratifiedShuffleSplit(y, n_iter=5, test_size=0.2, random_state=42) grid = GridSearchCV(SVC(), param_grid=param_grid, cv=cv) grid.fit(X, y) print("The best parameters are %s with a score of %0.2f" % (grid.best_params_, grid.best_score_)) # Now we need to fit a classifier for all parameters in the 2d version # (we use a smaller set of parameters here because it takes a while to train) C_2d_range = [1e-2, 1, 1e2] gamma_2d_range = [1e-1, 1, 1e1] classifiers = [] for C in C_2d_range: for gamma in gamma_2d_range: clf = SVC(C=C, gamma=gamma) clf.fit(X_2d, y_2d) classifiers.append((C, gamma, clf)) ############################################################################## # visualization # # draw visualization of parameter effects plt.figure(figsize=(8, 6)) xx, yy = np.meshgrid(np.linspace(-3, 3, 200), np.linspace(-3, 3, 200)) for (k, (C, gamma, clf)) in enumerate(classifiers): # evaluate decision function in a grid Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # visualize decision function for these parameters plt.subplot(len(C_2d_range), len(gamma_2d_range), k + 1) plt.title("gamma=10^%d, C=10^%d" % (np.log10(gamma), np.log10(C)), size='medium') # visualize parameter's effect on decision function plt.pcolormesh(xx, yy, -Z, cmap=plt.cm.RdBu) plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y_2d, cmap=plt.cm.RdBu_r) plt.xticks(()) plt.yticks(()) plt.axis('tight') # plot the scores of the grid # grid_scores_ contains parameter settings and scores # We extract just the scores scores = [x[1] for x in grid.grid_scores_] scores = np.array(scores).reshape(len(C_range), len(gamma_range)) # Draw heatmap of the validation accuracy as a function of gamma and C # # The score are encoded as colors with the hot colormap which varies from dark # red to bright yellow. As the most interesting scores are all located in the # 0.92 to 0.97 range we use a custom normalizer to set the mid-point to 0.92 so # as to make it easier to visualize the small variations of score values in the # interesting range while not brutally collapsing all the low score values to # the same color. plt.figure(figsize=(8, 6)) plt.subplots_adjust(left=.2, right=0.95, bottom=0.15, top=0.95) plt.imshow(scores, interpolation='nearest', cmap=plt.cm.hot, norm=MidpointNormalize(vmin=0.2, midpoint=0.92)) plt.xlabel('gamma') plt.ylabel('C') plt.colorbar() plt.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45) plt.yticks(np.arange(len(C_range)), C_range) plt.title('Validation accuracy') plt.show()
bsd-3-clause
ccd-utexas/tsphot
lc_online2.py
3
14102
#!/usr/bin/env python import matplotlib matplotlib.use('Agg') from matplotlib.pyplot import * from matplotlib.transforms import offset_copy import numpy as np import scipy from scipy.signal import lombscargle import scipy.optimize as sco import matplotlib.gridspec as gridspec import os def fwhm_fit2(aplist,targs): nlc = len(targs[:,0]) fwhm_vec = [] for j in np.arange(nlc): apvec = targs[j,:] f = apvec ndim = len(f) i = np.arange(ndim) ip = i + 1 aplist2 = np.concatenate([ [0],aplist]) apvec2 = np.concatenate([ [0],apvec]) dapvec2 = (apvec2[ip]-apvec2[i])/(aplist2[ip]**2-aplist2[i]**2) aplist_shifted = (2./3.)*(aplist2[ip]**3-aplist2[i]**3)/(aplist2[ip]**2-aplist2[i]**2) s0 = 10. s1 = dapvec2[0] w = 3. pinitial = np.array([ s0, s1, w ]) # Hack to get around non convergence for non-first frame # STH, 2014-07-04 try: popt, pcov = sco.curve_fit(psf, aplist_shifted, dapvec2, p0=pinitial) (popt_old, pcov_old) = (popt, pcov) except RuntimeError: (popt, pcov) = (popt_old, pcov_old) w = popt[2] fwhm = 2. * np.sqrt(2.*np.log(2.)) * w fwhm_vec.append(fwhm) fwhm_vec = np.array(fwhm_vec) apfine = np.arange(0,max(aplist),0.1) psf_fit = psf((apfine),*popt) print 'FWHM = ',fwhm fig=figure(3) ax1 = fig.add_subplot() plot(aplist_shifted,dapvec2,'o') plot(apfine,psf_fit,'-') xlabel('radius (pixels)') ylabel('profile') tstring = 'FWHM is {0:.3f} pixels\n'.format(fwhm) totstring = tstring x1,x2=xlim() y1,y2=ylim() xs=0.5 ys=0.8 xpos = x1 + xs*(x2-x1) ypos = y1 + ys*(y2-y1) text(xpos,ypos,totstring, horizontalalignment='center', verticalalignment='center') psffile='psf_fit.pdf' savefig(psffile,transparent=True,bbox_inches='tight') close() print 'PSF fit stored in',psffile,'\n' return fwhm_vec def fwhm_fit(aplist,apvec): f = apvec ndim = len(f) i = np.arange(ndim) ip = i + 1 aplist2 = np.concatenate([ [0],aplist]) apvec2 = np.concatenate([ [0],apvec]) dapvec2 = (apvec2[ip]-apvec2[i])/(aplist2[ip]**2-aplist2[i]**2) aplist_shifted = 0.5*(aplist2[ip]+aplist2[i]) s0 = 10. s1 = dapvec2[0] w = 3. pinitial = np.array([ s0, s1, w ]) popt, pcov = sco.curve_fit(psf, aplist_shifted, dapvec2, p0=pinitial) w = popt[2] fwhm = 2. * w * np.sqrt(np.log(2.)) apfine = np.arange(0,max(aplist),0.1) psf_fit = psf((apfine),*popt) print 'FWHM = ',fwhm fig=figure(3) ax1 = fig.add_subplot() plot(aplist_shifted,dapvec2,'o') plot(apfine,psf_fit,'-') xlabel('radius (pixels)') ylabel('profile') tstring = 'FWHM is {0:.3f} pixels\n'.format(fwhm) totstring = tstring x1,x2=xlim() y1,y2=ylim() xs=0.5 ys=0.8 xpos = x1 + xs*(x2-x1) ypos = y1 + ys*(y2-y1) text(xpos,ypos,totstring, horizontalalignment='center', verticalalignment='center') psffile='psf_fit.pdf' savefig(psffile,transparent=True,bbox_inches='tight') close() print 'PSF fit stored in',psffile,'\n' # Gaussian functional form assumed for PSF fits def psf((rr),s0,s1,w): elow = -50. #arg = - (rr/w)**2 arg = - rr**2/(2.*w**2) arg[arg <= elow] = elow intensity = s0 + s1 * np.exp( arg ) fwhm = 2. * np.sqrt(2.*np.log(2.)) * w return intensity # Total integrated flux and fwhm for the assumed Gaussian PSF def psf_flux(s0,s1,x0,y0,w): flux = np.pi * s1/np.abs(w) fwhm = 2. * np.sqrt(np.log(2.)/np.abs(w)) return fwhm, flux def comb_string(combs): ic = 0 for i in combs: if ic == 0: cstring = str(i) else: cstring = cstring + ' + ' + str(i) ic = ic + 1 return cstring def list_powerset2(lst): return reduce(lambda result, x: result + [subset + [x] for subset in result], lst, [[]]) # Make a plot of light curve scatter versus aperture size def applot(fap_pdf, aplist,sigvec,apmin,cstring): apfile = fap_pdf fig=figure(1) ax1 = fig.add_subplot() plot(aplist,sigvec,'-o') xlabel('Aperture size') ylabel('Scatter') tstring = 'optimal aperture is {0} pixels\n'.format(apmin) cstring = 'optimal comparison star =\n' + cstring totstring = tstring + '\n' + cstring x1,x2=xlim() y1,y2=ylim() xs=0.5 ys=0.8 xpos = x1 + xs*(x2-x1) ypos = y1 + ys*(y2-y1) text(xpos,ypos,totstring, horizontalalignment='center', verticalalignment='center') savefig(apfile,transparent=True,bbox_inches='tight') close() print 'Aperture optimization stored in',apfile # Make a plot of the optimal light curve file def lcplot(flc_pdf, time,target,comp,sky,fwhm_vec,cstring): ratio = target/comp ratio_norm = ratio/np.mean(ratio) - 1. #scipy.convolve(y, ones(N)/N) nfilt=5 ratio_norm_smooth = scipy.convolve(ratio_norm, np.ones(nfilt)/nfilt) time_smooth = scipy.convolve(time, np.ones(nfilt)/nfilt) target_norm = target/np.mean(target) - 1. comp_norm = comp/np.mean(comp) - 1. #sky_norm = sky/np.mean(sky) - 1. sky_norm = sky/np.amin(sky) ndata = len(time) dt = time[1]-time[0] fmax = 1./(2.*dt) #fmax = 0.01 #df = 1./(5.*(time[-1]-time[0])) df = 1./(2.*(time[-1]-time[0])) fmin = df fmin = 0.01*df df = (fmax-fmin)/1000. farray = np.arange(fmin,fmax,df) omarray = 2.* np.pi * farray pow = lombscargle(time,ratio_norm,omarray) pow = pow * 4/ndata amp = np.sqrt(pow) fig=figure(1,figsize=(14, 14),frameon=False) gs1 = gridspec.GridSpec(6, 1,hspace=0.0) ax1 = fig.add_subplot(gs1[0]) ax1.get_xaxis().set_ticklabels([]) plot(time,ratio_norm) ylabel(r'$\delta I/I$',size='x-large') leg=ax1.legend(['target'],'best',fancybox=True,shadow=False,handlelength=0.0) leg.draw_frame(False) ax2 = fig.add_subplot(gs1[1],sharex=ax1) plot(time_smooth[0:-nfilt],ratio_norm_smooth[:-nfilt]) ylabel(r'$\delta I/I$',size='x-large') leg=ax2.legend(['target smoothed'],'best',fancybox=True,shadow=False,handlelength=0.0) leg.draw_frame(False) ax3 = fig.add_subplot(gs1[2],sharex=ax1) plot(time,comp_norm) ylabel(r'$\delta I/I$',size='x-large') comstring = 'comparison\n' + '= ' + cstring leg=ax3.legend([comstring],'best',fancybox=True,shadow=False,handlelength=0.0) leg.draw_frame(False) ax4 = fig.add_subplot(gs1[3]) pl1=ax4.plot(time,sky_norm,label = 'Sky') ylabel('Sky',size='large') xlabel(r'${\rm time \, (sec)}$',size='x-large') fwhm_string = 'FWHM={0:.3f}'.format(fwhm_vec[-1]) ax6 = ax4.twinx() pl2 = ax6.plot(time, fwhm_vec, 'r-',label = fwhm_string) pls = pl1 + pl2 ax6.set_ylabel('FWHM', color='r') for tl in ax6.get_yticklabels(): tl.set_color('r') labs = [l.get_label() for l in pls] leg=ax4.legend(pls, labs, 'best', loc=0) leg.draw_frame(False) gs2 = gridspec.GridSpec(4, 1,hspace=0.1) ax5 = fig.add_subplot(gs2[3]) freqs = farray * 1.e+6 plot(freqs,amp) xlabel(r'Frequency ($\mu$Hz)',size='large') ylabel('Amplitude',size='large') leg=ax5.legend(['FT'],'best',fancybox=True,shadow=False,handlelength=0.0) leg.draw_frame(False) filebase = 'lc.pdf' savefig(filebase,transparent=True,bbox_inches='tight') close() print 'Optimal light curve plot stored in',filebase,'\n' # ysig is normalized so that it represents the point-to-point # scatter sigma_i, assuming uncorrelated, random noise def scatter(lcvec): ndata = len(lcvec) ivec = np.arange(0,ndata-1) ivecp = ivec + 1 dy = lcvec[ivecp] - lcvec[ivec] ysig = np.sqrt(np.dot(dy,dy)/(2.*(ndata-1.))) return ysig def main(args): """ Read lightcurve file and create plots. """ # Get number of stars f = open(args.flc,'r') line = f.readline() s = line.split() nstars = int(s[-1]) f.close() print '\nThe Number of stars is',nstars cols=range(0,3*nstars+1) cols=range(0,3*nstars+1) var = np.loadtxt(args.flc,usecols=cols) jdarr = var[:,0] aparr = var[:,1] fluxes = var[:,2:2+nstars] sky = var[:,2+nstars:2+2*nstars] pos = var[:,2+2*nstars:2+4*nstars] fwhm = var[:,2+4*nstars:2+5*nstars] # Get the list of unique aperture sizes apset = set(aparr) aplist = list(apset) aplist = np.array(aplist) print '\nUsing the following apertures:' print aplist # Cyle through all possible combinations of comparison stars and choose the one # that minimizes the point-to-point scatter ysig starlist = np.arange(1,nstars) pset = list_powerset2(starlist) del pset[0] # Now that we've got the list of comparison stars, let's find the optimal aperture # create arrays to store lightcurves for different apertures # Use median aperture for this apmed = float(int(np.median(aplist))) mask = np.where(aparr == apmed) stars = fluxes[mask,:][0] target = stars[:,0] ntarg = len(target) nap = len(aplist) ncom = len(pset) nlcs = nap*ncom targs = np.zeros((ntarg,nap)) comps = np.zeros((ntarg,nap,ncom)) skyvals = np.zeros((ntarg,nap)) ysigarr = np.ones((nap,ncom)) ysigarr = 1000000.*ysigarr # counter for apertures iap = 0 for app in aplist: mask = np.where(aparr == app) jd = jdarr[mask] ap = aparr[mask] stars = fluxes[mask,:][0] skys = sky[mask,:][0] xpos = pos[mask,:][0] fw = fwhm[mask] ta = stars[:,0] # store target and sky lightcurves targs[:,iap]=ta skyvals[:,iap]=skys[:,0] # Loop over all possible comparison stars # counter for combination of comparison stars nc = 0 for term in pset: compstar = 0.*ta for ii in term: compstar = compstar + stars[:,ii] # divide by comparison, normalize, and shift to zero ratio = ta/compstar ratio = ratio/np.mean(ratio) - 1.0 ysig = scatter(ratio) #sigvec.append(ysig) ysigarr[iap,nc] = ysig # print iap, nc, term, ysig # store comparison lightcurve comps[:,iap,nc]=compstar nc = nc + 1 iap = iap + 1 # Find optimal aperture and its index sigmin = np.amin(ysigarr) isigmin = np.argmin(ysigarr) iarg = np.unravel_index(isigmin,(nap,ncom)) iapmin, ncmin = iarg combs = pset[ncmin] apmin = aplist[iapmin] report = '\nThe optimal aperture is {0} pixels, the point-to-point scatter is {1:0.5f},'.format(apmin,sigmin) print report print 'and the optimal comparison star combination is',pset[ncmin],'\n' # Store "combination string" for the optimal combination of comparison stars cstring = comb_string(combs) # Make plot of scatter versus aperture size sigvec = ysigarr[:,ncmin] applot(args.fap_pdf, aplist,sigvec,apmin,cstring) time = 86400.*(jd-jd[0]) target = targs[:,iapmin] compstar = comps[:,iapmin,ncmin] sky0 = skyvals[:,iapmin] # Calculate scatter for composite comparison star ncompstar = compstar/np.mean(compstar) - 1.0 comp_ysig = scatter(ncompstar) print 'Scatter: target=',sigmin,' Comparison=',comp_ysig # Do FWHM fits for target star at all points of light curve # Choose comparison or target star based on lower level of scatter. if comp_ysig <= sigmin: fwhm_vec = fwhm_fit2(aplist,comps[:,:,ncmin]) # FWHM of composite comparison star else: fwhm_vec = fwhm_fit2(aplist,targs) # FWHM of target star # Make online plot of lightcurves, sky, and the FT lcplot(args.flc_pdf, time,target,compstar,sky0,fwhm_vec,cstring) return None if __name__ == '__main__': arg_default_map = {} arg_default_map['flc'] = "lightcurve.txt" arg_default_map['flc_pdf'] = "lc.pdf" arg_default_map['fap_pdf'] = "aperture.pdf" parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, description=("Read lightcurve file and create plots.")) parser.add_argument("--flc", default=arg_default_map['flc'], help=(("Input fixed-width-format text file" +" with columns of star intensities by aperture size.\n" +"Default: {fname}").format(fname=arg_default_map['flc']))) parser.add_argument("--flc_pdf", default=arg_default_map['flc_pdf'], help=(("Output .pdf file with plots of the lightcurve.\n" +"Default: {fname}").format(fname=arg_default_map['flc_pdf']))) parser.add_argument("--fap_pdf", default=arg_default_map['fap_pdf'], help=(("Output .pdf file with plot of scatter vs aperture size.\n" +"Default: {fname}").format(fname=arg_default_map['fap_pdf']))) parser.add_argument("--verbose", "-v", action='store_true', help=("Print 'INFO:' messages to stdout.")) args = parser.parse_args() if args.verbose: print "INFO: Arguments:" for arg in args.__dict__: print ' ', arg, args.__dict__[arg] if not os.path.isfile(args.flc): raise IOError(("File does not exist: {fname}").format(fname=args.flc)) main(args=args)
mit
shanqing-cai/MRI_analysis
aparc12_surface_stats.py
1
11734
#!/usr/bin/python import os import sys import glob import argparse import tempfile import numpy as np import matplotlib.pyplot as plt import pickle import scipy.stats as stats from copy import deepcopy from subprocess import Popen, PIPE from get_qdec_info import get_qdec_info from fs_load_stats import fs_load_stats from aparc12 import * from scai_utils import * from scai_stats import cohens_d BASE_DIR = "/users/cais/STUT/analysis/aparc12_tracts" DATA_DIR = "/users/cais/STUT/DATA" FSDATA_DIR = "/users/cais/STUT/FSDATA" CTAB = "/users/cais/STUT/slaparc_550.ctab" SEGSTATS_SUM_WC = "aparc12_wm%dmm.segstats.txt" P_THRESH_UNC = 0.05 hemis = ["lh", "rh"] grps = ["PFS", "PWS"] grpColors = {"PFS": [0, 0, 0], "PWS": [1, 0, 0]} if __name__ == "__main__": ap = argparse.ArgumentParser(description="Analyze aparc12 surface annotation: Surface area and average thickness") ap.add_argument("-r", dest="bReload", action="store_true", \ help="Reload data (time-consuming)") # ap.add_argument("hemi", help="Hemisphere {lh, rh}") # if len(sys.argv) == 1: # ap.print_help() # sys.exit(0) # === Args input arguments === # args = ap.parse_args() bReload = args.bReload # hemi = args.hemi # assert(hemis.count(hemi) == 1) # === Determine the subject list and their group memberships === # check_dir(BASE_DIR) ds = glob.glob(os.path.join(BASE_DIR, "S??")) ds.sort() sIDs = [] isPWS = [] SSI4 = [] for (i0, t_path) in enumerate(ds): (t_path_0, t_sID) = os.path.split(t_path) sIDs.append(t_sID) SSI4.append(get_qdec_info(t_sID, "SSI")) if get_qdec_info(t_sID, "diagnosis") == "PWS": isPWS.append(1) else: isPWS.append(0) isPWS = np.array(isPWS) SSI4 = np.array(SSI4) assert(len(sIDs) > 0) assert(len(sIDs) == len(isPWS)) # === Get the list of cortical ROIs (Speech network only) === rois0 = get_aparc12_cort_rois(bSpeech=True) check_file(CTAB) (ctab_roi_nums, ctab_roi_names) = read_ctab(CTAB) # Duplex into both hemispheres roi_names = [] roi_nums = [] for (i0, hemi) in enumerate(hemis): for (i1, roi) in enumerate(rois0): t_roi_name = "%s_%s" % (hemi, roi) assert(ctab_roi_names.count(t_roi_name) == 1) idx = ctab_roi_names.index(t_roi_name) roi_names.append(t_roi_name) roi_nums.append(ctab_roi_nums[idx]) assert(len(roi_names) == len(roi_nums)) # === Load data: Loop through all subjects === # cachePklFN = "aparc12_surface_stats_dset.pkl" nROIs = len(roi_names) ns = len(sIDs) if bReload: print("INFO: bReload = True: Reloading data (time-consuming)\n") labArea = np.zeros([ns, nROIs]) labAvgThick = np.zeros([ns, nROIs]) # Label area normalized by hemisphere surface area labAreaNorm = np.zeros([ns, nROIs]) for (i0, sID) in enumerate(sIDs): t_rois = [] t_roi_nums = [] t_area = [] t_area_norm = [] t_thick = [] for (i1, hemi) in enumerate(hemis): # == Load hemisphere total surface area == # hemiStatsFN = os.path.join(FSDATA_DIR, sID, \ "stats", "%s.aparc.stats" % hemi) check_file(hemiStatsFN) t_hemiSurfArea = fs_load_stats(hemiStatsFN, "SurfArea") tmpfn = tempfile.mktemp() hthick = os.path.join(FSDATA_DIR, sID, "surf", \ "%s.thickness" % hemi) check_file(hthick) print("Loading data from subject %s, hemisphere %s" \ % (sID, hemi)) (sout, serr) = Popen(["mri_segstats", "--annot", \ sID, hemi, "aparc12", \ "--in", hthick, \ "--sum", tmpfn], \ stdout=PIPE, stderr=PIPE).communicate() sout = read_text_file(tmpfn) os.system("rm -rf %s" % tmpfn) k0 = 0 while (sout[k0].startswith("# ")): k0 = k0 + 1 sout = sout[k0 :] for tline in sout: if len(tline) == 0: break; t_items = remove_empty_strings(\ tline.replace('\t', ' ').split(' ')) if len(t_items) == 10: t_rois.append(hemi + "_" + t_items[4]) if hemi == "lh": t_roi_nums.append(1000 + int(t_items[1])) else: t_roi_nums.append(2000 + int(t_items[1])) t_area.append(float(t_items[3])) t_area_norm.append(float(t_items[3]) / t_hemiSurfArea) t_thick.append(float(t_items[5])) # == Matching and filling values == # for (i2, t_rn) in enumerate(roi_nums): if t_roi_nums.count(t_rn) > 0: idx = t_roi_nums.index(t_rn) labArea[i0][i2] = t_area[idx] labAreaNorm[i0][i2] = t_area_norm[idx] labAvgThick[i0][i2] = t_thick[idx] # === Save to pkl file === # dset = {"labArea": labArea, \ "labAreaNorm": labAreaNorm, \ "labAvgThick": labAvgThick} os.system("rm -rf %s" % cachePklFN) cachePklF = open(cachePklFN, "wb") pickle.dump(dset, cachePklF) cachePklF.close() check_file(cachePklFN) print("INFO: Saved loaded data to file: %s\n" % os.path.abspath(cachePklFN)) else: print("INFO: Loading saved data from file: %s\n" % os.path.abspath(cachePklFN)) cachePklF = open(cachePklFN, "rb") dset = pickle.load(cachePklF) cachePklF.close() labArea = dset["labArea"] labAreaNorm = dset["labAreaNorm"] labAvgThick = dset["labAvgThick"] # === Check data validity === # assert(len(labArea) == ns) assert(len(labAreaNorm) == ns) assert(len(labAvgThick) == ns) # === Statistical comparison === # mean_area = {} std_area = {} nsg = {} for (i0, grp) in enumerate(grps): nsg[grp] = len(np.nonzero(isPWS == i0)) mean_area[grp] = np.mean(labArea[isPWS == i0], axis=0) # std_area[grp] = np.std(labArea[isPWS == i0], axis=0) / np.sqrt(nsg[grp]) std_area[grp] = np.std(labArea[isPWS == i0], axis=0) cmprItems = ["labArea", "labAreaNorm", "labAvgThick"] for (h0, cmprItem) in enumerate(cmprItems): print("--- List of significant differences in %s (p < %f uncorrected) ---" \ % (cmprItem, P_THRESH_UNC)) p_tt_val = np.zeros([nROIs]) t_tt_val = np.zeros([nROIs]) for (i0, t_roi) in enumerate(roi_names): if h0 == 0: dat_PWS = labArea[isPWS == 1, i0] dat_PFS = labArea[isPWS == 0, i0] elif h0 == 1: dat_PWS = labAreaNorm[isPWS == 1, i0] dat_PFS = labAreaNorm[isPWS == 0, i0] elif h0 == 2: dat_PWS = labAvgThick[isPWS == 1, i0] dat_PFS = labAvgThick[isPWS == 0, i0] (t_tt, p_tt) = stats.ttest_ind(dat_PWS, dat_PFS) p_tt_val[i0] = p_tt t_tt_val[i0] = t_tt if p_tt_val[i0] < P_THRESH_UNC: if t_tt_val[i0] < 0: dirString = "PWS < PFS" else: dirString = "PWS > PFS" print("%s: p = %f; t = %f (%s)" \ % (t_roi, p_tt_val[i0], t_tt_val[i0], dirString)) print("\tMean +/- SD: PWS: %.5f +/- %.5f; PFS: %.5f +/- %.5f" \ % (np.mean(dat_PWS), np.std(dat_PWS), \ np.mean(dat_PFS), np.std(dat_PFS))) print("\tCohens_d = %.3f" % cohens_d(dat_PWS, dat_PFS)) print("\n") # === Spearman correlation === # for (h0, cmprItem) in enumerate(cmprItems): print("--- Spearman correlations with SSI4 in %s (p < %f uncorrected) ---" \ % (cmprItem, P_THRESH_UNC)) p_spc_val = np.zeros([nROIs]) rho_spc_val = np.zeros([nROIs]) for (i0, t_roi) in enumerate(roi_names): if h0 == 0: (r_spc, p_spc) = stats.spearmanr(SSI4[isPWS == 1], \ labArea[isPWS == 1, i0]) elif h0 == 1: (r_spc, p_spc) = stats.spearmanr(SSI4[isPWS == 1], \ labAreaNorm[isPWS == 1, i0]) elif h0 == 2: (r_spc, p_spc) = stats.spearmanr(SSI4[isPWS == 1], \ labAvgThick[isPWS == 1, i0]) p_spc_val[i0] = p_spc rho_spc_val[i0] = r_spc if p_spc_val[i0] < P_THRESH_UNC: if rho_spc_val[i0] < 0: dirString = "-" else: dirString = "+" print("%s: p = %f; rho = %f (%s)" \ % (t_roi, p_spc_val[i0], rho_spc_val[i0], dirString)) print("\n") # === Compare combined dIFo and vIFo === # lh_IFo_area = {} lh_IFo_areaNorm = {} for (i0, grp) in enumerate(grps): lh_IFo_area[grp] = labArea[isPWS == i0, roi_names.index("lh_vIFo")] + \ labArea[isPWS == i0, roi_names.index("lh_dIFo")] lh_IFo_areaNorm[grp] = labAreaNorm[isPWS == i0, roi_names.index("lh_vIFo")] + \ labAreaNorm[isPWS == i0, roi_names.index("lh_dIFo")] (t_tt, p_tt) = stats.ttest_ind(lh_IFo_area["PWS"], \ lh_IFo_area["PFS"]) print("-- Comparing lh_IFo area: --") print("\tp = %f; t = %f" % (p_tt, t_tt)) print("\tPWS: %.1f +/- %.1f; PFS: %.1f +/- %.1f" \ % (np.mean(lh_IFo_area["PWS"]), np.std(lh_IFo_area["PWS"]), \ np.mean(lh_IFo_area["PFS"]), np.std(lh_IFo_area["PFS"]))) print("\n") (t_tt, p_tt) = stats.ttest_ind(lh_IFo_areaNorm["PWS"], \ lh_IFo_areaNorm["PFS"]) print("-- Comparing lh_IFo areaNorm: --") print("\tp = %f; t = %f" % (p_tt, t_tt)) print("\tPWS: %.1e +/- %.1e; PFS: %.1e +/- %.1e" \ % (np.mean(lh_IFo_areaNorm["PWS"]), np.std(lh_IFo_areaNorm["PWS"]), \ np.mean(lh_IFo_areaNorm["PFS"]), np.std(lh_IFo_areaNorm["PFS"]))) # === Correlating combined IFo with SSI4 === # (r_spc, p_spc) = stats.spearmanr(SSI4[isPWS == 1], lh_IFo_area["PWS"]) print("-- Correlating SSI4 with lh_IFo area: --") print("\tp = %f; rho = %f" % (p_spc, r_spc)) print("\n") (r_spc, p_spc) = stats.spearmanr(SSI4[isPWS == 1], lh_IFo_areaNorm["PWS"]) print("-- Correlating SSI4 with lh_IFo areaNorm: --") print("\tp = %f; rho = %f" % (p_spc, r_spc)) print("\n") # === Visualiation === # """ for (i0, grp) in enumerate(grps): plt.errorbar(range(nROIs), mean_area[grp], yerr=std_area[grp], \ color=grpColors[grp]) plt.xticks(range(nROIs), roi_names, rotation=90.0) plt.show() """
bsd-3-clause
abhishekkrthakur/scikit-learn
examples/cluster/plot_kmeans_stability_low_dim_dense.py
338
4324
""" ============================================================ Empirical evaluation of the impact of k-means initialization ============================================================ Evaluate the ability of k-means initializations strategies to make the algorithm convergence robust as measured by the relative standard deviation of the inertia of the clustering (i.e. the sum of distances to the nearest cluster center). The first plot shows the best inertia reached for each combination of the model (``KMeans`` or ``MiniBatchKMeans``) and the init method (``init="random"`` or ``init="kmeans++"``) for increasing values of the ``n_init`` parameter that controls the number of initializations. The second plot demonstrate one single run of the ``MiniBatchKMeans`` estimator using a ``init="random"`` and ``n_init=1``. This run leads to a bad convergence (local optimum) with estimated centers stuck between ground truth clusters. The dataset used for evaluation is a 2D grid of isotropic Gaussian clusters widely spaced. """ print(__doc__) # Author: Olivier Grisel <olivier.grisel@ensta.org> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from sklearn.utils import shuffle from sklearn.utils import check_random_state from sklearn.cluster import MiniBatchKMeans from sklearn.cluster import KMeans random_state = np.random.RandomState(0) # Number of run (with randomly generated dataset) for each strategy so as # to be able to compute an estimate of the standard deviation n_runs = 5 # k-means models can do several random inits so as to be able to trade # CPU time for convergence robustness n_init_range = np.array([1, 5, 10, 15, 20]) # Datasets generation parameters n_samples_per_center = 100 grid_size = 3 scale = 0.1 n_clusters = grid_size ** 2 def make_data(random_state, n_samples_per_center, grid_size, scale): random_state = check_random_state(random_state) centers = np.array([[i, j] for i in range(grid_size) for j in range(grid_size)]) n_clusters_true, n_features = centers.shape noise = random_state.normal( scale=scale, size=(n_samples_per_center, centers.shape[1])) X = np.concatenate([c + noise for c in centers]) y = np.concatenate([[i] * n_samples_per_center for i in range(n_clusters_true)]) return shuffle(X, y, random_state=random_state) # Part 1: Quantitative evaluation of various init methods fig = plt.figure() plots = [] legends = [] cases = [ (KMeans, 'k-means++', {}), (KMeans, 'random', {}), (MiniBatchKMeans, 'k-means++', {'max_no_improvement': 3}), (MiniBatchKMeans, 'random', {'max_no_improvement': 3, 'init_size': 500}), ] for factory, init, params in cases: print("Evaluation of %s with %s init" % (factory.__name__, init)) inertia = np.empty((len(n_init_range), n_runs)) for run_id in range(n_runs): X, y = make_data(run_id, n_samples_per_center, grid_size, scale) for i, n_init in enumerate(n_init_range): km = factory(n_clusters=n_clusters, init=init, random_state=run_id, n_init=n_init, **params).fit(X) inertia[i, run_id] = km.inertia_ p = plt.errorbar(n_init_range, inertia.mean(axis=1), inertia.std(axis=1)) plots.append(p[0]) legends.append("%s with %s init" % (factory.__name__, init)) plt.xlabel('n_init') plt.ylabel('inertia') plt.legend(plots, legends) plt.title("Mean inertia for various k-means init across %d runs" % n_runs) # Part 2: Qualitative visual inspection of the convergence X, y = make_data(random_state, n_samples_per_center, grid_size, scale) km = MiniBatchKMeans(n_clusters=n_clusters, init='random', n_init=1, random_state=random_state).fit(X) fig = plt.figure() for k in range(n_clusters): my_members = km.labels_ == k color = cm.spectral(float(k) / n_clusters, 1) plt.plot(X[my_members, 0], X[my_members, 1], 'o', marker='.', c=color) cluster_center = km.cluster_centers_[k] plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=color, markeredgecolor='k', markersize=6) plt.title("Example cluster allocation with a single random init\n" "with MiniBatchKMeans") plt.show()
bsd-3-clause
hcxiong/skyline
src/analyzer/algorithms.py
9
9794
import pandas import numpy as np import scipy import statsmodels.api as sm import traceback import logging from time import time from msgpack import unpackb, packb from redis import StrictRedis from settings import ( ALGORITHMS, CONSENSUS, FULL_DURATION, MAX_TOLERABLE_BOREDOM, MIN_TOLERABLE_LENGTH, STALE_PERIOD, REDIS_SOCKET_PATH, ENABLE_SECOND_ORDER, BOREDOM_SET_SIZE, ) from algorithm_exceptions import * logger = logging.getLogger("AnalyzerLog") redis_conn = StrictRedis(unix_socket_path=REDIS_SOCKET_PATH) """ This is no man's land. Do anything you want in here, as long as you return a boolean that determines whether the input timeseries is anomalous or not. To add an algorithm, define it here, and add its name to settings.ALGORITHMS. """ def tail_avg(timeseries): """ This is a utility function used to calculate the average of the last three datapoints in the series as a measure, instead of just the last datapoint. It reduces noise, but it also reduces sensitivity and increases the delay to detection. """ try: t = (timeseries[-1][1] + timeseries[-2][1] + timeseries[-3][1]) / 3 return t except IndexError: return timeseries[-1][1] def median_absolute_deviation(timeseries): """ A timeseries is anomalous if the deviation of its latest datapoint with respect to the median is X times larger than the median of deviations. """ series = pandas.Series([x[1] for x in timeseries]) median = series.median() demedianed = np.abs(series - median) median_deviation = demedianed.median() # The test statistic is infinite when the median is zero, # so it becomes super sensitive. We play it safe and skip when this happens. if median_deviation == 0: return False test_statistic = demedianed.iget(-1) / median_deviation # Completely arbitary...triggers if the median deviation is # 6 times bigger than the median if test_statistic > 6: return True def grubbs(timeseries): """ A timeseries is anomalous if the Z score is greater than the Grubb's score. """ series = scipy.array([x[1] for x in timeseries]) stdDev = scipy.std(series) mean = np.mean(series) tail_average = tail_avg(timeseries) z_score = (tail_average - mean) / stdDev len_series = len(series) threshold = scipy.stats.t.isf(.05 / (2 * len_series), len_series - 2) threshold_squared = threshold * threshold grubbs_score = ((len_series - 1) / np.sqrt(len_series)) * np.sqrt(threshold_squared / (len_series - 2 + threshold_squared)) return z_score > grubbs_score def first_hour_average(timeseries): """ Calcuate the simple average over one hour, FULL_DURATION seconds ago. A timeseries is anomalous if the average of the last three datapoints are outside of three standard deviations of this value. """ last_hour_threshold = time() - (FULL_DURATION - 3600) series = pandas.Series([x[1] for x in timeseries if x[0] < last_hour_threshold]) mean = (series).mean() stdDev = (series).std() t = tail_avg(timeseries) return abs(t - mean) > 3 * stdDev def stddev_from_average(timeseries): """ A timeseries is anomalous if the absolute value of the average of the latest three datapoint minus the moving average is greater than three standard deviations of the average. This does not exponentially weight the MA and so is better for detecting anomalies with respect to the entire series. """ series = pandas.Series([x[1] for x in timeseries]) mean = series.mean() stdDev = series.std() t = tail_avg(timeseries) return abs(t - mean) > 3 * stdDev def stddev_from_moving_average(timeseries): """ A timeseries is anomalous if the absolute value of the average of the latest three datapoint minus the moving average is greater than three standard deviations of the moving average. This is better for finding anomalies with respect to the short term trends. """ series = pandas.Series([x[1] for x in timeseries]) expAverage = pandas.stats.moments.ewma(series, com=50) stdDev = pandas.stats.moments.ewmstd(series, com=50) return abs(series.iget(-1) - expAverage.iget(-1)) > 3 * stdDev.iget(-1) def mean_subtraction_cumulation(timeseries): """ A timeseries is anomalous if the value of the next datapoint in the series is farther than three standard deviations out in cumulative terms after subtracting the mean from each data point. """ series = pandas.Series([x[1] if x[1] else 0 for x in timeseries]) series = series - series[0:len(series) - 1].mean() stdDev = series[0:len(series) - 1].std() expAverage = pandas.stats.moments.ewma(series, com=15) return abs(series.iget(-1)) > 3 * stdDev def least_squares(timeseries): """ A timeseries is anomalous if the average of the last three datapoints on a projected least squares model is greater than three sigma. """ x = np.array([t[0] for t in timeseries]) y = np.array([t[1] for t in timeseries]) A = np.vstack([x, np.ones(len(x))]).T results = np.linalg.lstsq(A, y) residual = results[1] m, c = np.linalg.lstsq(A, y)[0] errors = [] for i, value in enumerate(y): projected = m * x[i] + c error = value - projected errors.append(error) if len(errors) < 3: return False std_dev = scipy.std(errors) t = (errors[-1] + errors[-2] + errors[-3]) / 3 return abs(t) > std_dev * 3 and round(std_dev) != 0 and round(t) != 0 def histogram_bins(timeseries): """ A timeseries is anomalous if the average of the last three datapoints falls into a histogram bin with less than 20 other datapoints (you'll need to tweak that number depending on your data) Returns: the size of the bin which contains the tail_avg. Smaller bin size means more anomalous. """ series = scipy.array([x[1] for x in timeseries]) t = tail_avg(timeseries) h = np.histogram(series, bins=15) bins = h[1] for index, bin_size in enumerate(h[0]): if bin_size <= 20: # Is it in the first bin? if index == 0: if t <= bins[0]: return True # Is it in the current bin? elif t >= bins[index] and t < bins[index + 1]: return True return False def ks_test(timeseries): """ A timeseries is anomalous if 2 sample Kolmogorov-Smirnov test indicates that data distribution for last 10 minutes is different from last hour. It produces false positives on non-stationary series so Augmented Dickey-Fuller test applied to check for stationarity. """ hour_ago = time() - 3600 ten_minutes_ago = time() - 600 reference = scipy.array([x[1] for x in timeseries if x[0] >= hour_ago and x[0] < ten_minutes_ago]) probe = scipy.array([x[1] for x in timeseries if x[0] >= ten_minutes_ago]) if reference.size < 20 or probe.size < 20: return False ks_d, ks_p_value = scipy.stats.ks_2samp(reference, probe) if ks_p_value < 0.05 and ks_d > 0.5: adf = sm.tsa.stattools.adfuller(reference, 10) if adf[1] < 0.05: return True return False def is_anomalously_anomalous(metric_name, ensemble, datapoint): """ This method runs a meta-analysis on the metric to determine whether the metric has a past history of triggering. TODO: weight intervals based on datapoint """ # We want the datapoint to avoid triggering twice on the same data new_trigger = [time(), datapoint] # Get the old history raw_trigger_history = redis_conn.get('trigger_history.' + metric_name) if not raw_trigger_history: redis_conn.set('trigger_history.' + metric_name, packb([(time(), datapoint)])) return True trigger_history = unpackb(raw_trigger_history) # Are we (probably) triggering on the same data? if (new_trigger[1] == trigger_history[-1][1] and new_trigger[0] - trigger_history[-1][0] <= 300): return False # Update the history trigger_history.append(new_trigger) redis_conn.set('trigger_history.' + metric_name, packb(trigger_history)) # Should we surface the anomaly? trigger_times = [x[0] for x in trigger_history] intervals = [ trigger_times[i + 1] - trigger_times[i] for i, v in enumerate(trigger_times) if (i + 1) < len(trigger_times) ] series = pandas.Series(intervals) mean = series.mean() stdDev = series.std() return abs(intervals[-1] - mean) > 3 * stdDev def run_selected_algorithm(timeseries, metric_name): """ Filter timeseries and run selected algorithm. """ # Get rid of short series if len(timeseries) < MIN_TOLERABLE_LENGTH: raise TooShort() # Get rid of stale series if time() - timeseries[-1][0] > STALE_PERIOD: raise Stale() # Get rid of boring series if len(set(item[1] for item in timeseries[-MAX_TOLERABLE_BOREDOM:])) == BOREDOM_SET_SIZE: raise Boring() try: ensemble = [globals()[algorithm](timeseries) for algorithm in ALGORITHMS] threshold = len(ensemble) - CONSENSUS if ensemble.count(False) <= threshold: if ENABLE_SECOND_ORDER: if is_anomalously_anomalous(metric_name, ensemble, timeseries[-1][1]): return True, ensemble, timeseries[-1][1] else: return True, ensemble, timeseries[-1][1] return False, ensemble, timeseries[-1][1] except: logging.error("Algorithm error: " + traceback.format_exc()) return False, [], 1
mit
MediffRobotics/DeepRobotics
DeepLearnMaterials/tutorials/numpy&pandas/16_concat.py
3
1436
# View more python tutorials on my Youtube and Youku channel!!! # Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg # Youku video tutorial: http://i.youku.com/pythontutorial """ Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly. """ from __future__ import print_function import pandas as pd import numpy as np # concatenating # ignore index df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d']) df2 = pd.DataFrame(np.ones((3,4))*1, columns=['a','b','c','d']) df3 = pd.DataFrame(np.ones((3,4))*2, columns=['a','b','c','d']) res = pd.concat([df1, df2, df3], axis=0, ignore_index=True) # join, ('inner', 'outer') df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'], index=[1,2,3]) df2 = pd.DataFrame(np.ones((3,4))*1, columns=['b','c','d', 'e'], index=[2,3,4]) res = pd.concat([df1, df2], axis=1, join='outer') res = pd.concat([df1, df2], axis=1, join='inner') # join_axes res = pd.concat([df1, df2], axis=1, join_axes=[df1.index]) # append df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d']) df2 = pd.DataFrame(np.ones((3,4))*1, columns=['a','b','c','d']) df2 = pd.DataFrame(np.ones((3,4))*1, columns=['b','c','d', 'e'], index=[2,3,4]) res = df1.append(df2, ignore_index=True) res = df1.append([df2, df3]) s1 = pd.Series([1,2,3,4], index=['a','b','c','d']) res = df1.append(s1, ignore_index=True) print(res)
gpl-3.0
qiqi/fds
apps/charles_cylinder3D_Lyapunov/draw_Lyapunov/drawCLV.py
1
4385
# This file reads the checkpoint files, computes CLVs, call charles.exe for 0 step, # and genereate the flow field solution for state variables: rho, rhoE, rhoU from __future__ import division import os import sys import time import shutil import string import tempfile import argparse import subprocess from multiprocessing import Manager from numpy import * from charles import * import matplotlib matplotlib.use('Agg') from matplotlib.pyplot import * rcParams.update({'axes.labelsize':'xx-large'}) rcParams.update({'xtick.labelsize':'xx-large'}) rcParams.update({'ytick.labelsize':'xx-large'}) rcParams.update({'legend.fontsize':'xx-large'}) rc('font', family='sans-serif') sys.path.append("/scratch/niangxiu/fds_4CLV_finer_reso") from fds import * from fds.checkpoint import * from fds.cti_restart_io import * from fds.compute import run_compute sys.setrecursionlimit(12000) M_MODES = array([0,7,16,39]) total_MODES = 40 K_SEGMENTS = (400,) # K_SEGMENTS = range(350, 451) MPI_NP = 1 MY_PATH = os.path.abspath('/scratch/niangxiu/fds_4CLV_finer_reso/apps') BASE_PATH = os.path.join(MY_PATH, 'charles') CLV_PATH = os.path.join(MY_PATH, 'CLV') if os.path.exists(CLV_PATH): shutil.rmtree(CLV_PATH) os.mkdir(CLV_PATH) RESULT_PATH = [] for j in M_MODES: RESULT_PATH.append(os.path.join(CLV_PATH, 'CLV'+str(j))) os.mkdir(RESULT_PATH[-1]) REF_PATH = os.path.join(MY_PATH, 'ref') REF_DATA_FILE = os.path.join(REF_PATH, 'initial.les') REF_SUPP_FILE = os.path.join(REF_PATH, 'charles.in') CHARLES_BIN = os.path.join(REF_PATH, 'charles.exe') checkpoint = load_last_checkpoint(BASE_PATH, total_MODES) assert verify_checkpoint(checkpoint) C = checkpoint.lss.lyapunov_covariant_vectors() # someone evilly rolled the axis in the lyapunov_covariant_vectors function C = rollaxis(C,2) C = rollaxis(C,2) # now the shape is [K_SEGMENTS, M_MODES, M_MODES] I = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 9, 12, 13, 14, 15, 18, 17, 16, 22, 21, 19, 20, 23, 24, 26, 25, 31, 27, 28, 30, 35, 29, 37, 33, 38, 36, 34, 32, 39] I = array(I) print('C.shape = ', C.shape) def les2vtu(work_path, solut_path, j): # run charles for 0 step outfile = os.path.join(work_path, 'out') with open(outfile, 'w', 8) as f: subprocess.call(['mpiexec', '-n', str(MPI_NP), charles_bin], cwd=work_path, stdout=f, stderr=f) # copy the results file and delete the working folder result_file = os.path.join(solut_path, 'z0_plane.000000.vtu') shutil.copy(result_file, os.path.join(RESULT_PATH[j], 'z0_plane_seg.'+str(i_segment)+'.vtu')) shutil.rmtree(work_path) # draw CLV field for i_segment in K_SEGMENTS: print('i_segment = ', i_segment) checkpoint = load_checkpoint(os.path.join(BASE_PATH, 'm'+str(total_MODES)+'_segment'+str(i_segment))) assert verify_checkpoint(checkpoint) u0, V, v, lss, G_lss, g_lss, J_hist, G_dil, g_dil = checkpoint manager = Manager() interprocess = (manager.Lock(), manager.dict()) run_compute([V], spawn_compute_job=None, interprocess=interprocess) V = V.field print(V.shape) # construct CLV at this segment CLV = dot(V.T, C[i_segment, :, :]) CLV = CLV.T # plot CLV for j, j_mode in enumerate(I[M_MODES]): run_id = 'CLV'+str(j_mode)+'_seg'+str(i_segment) print('runid:', run_id) work_path = os.path.join(CLV_PATH, run_id) os.mkdir(work_path) solut_path = os.path.join(work_path, 'SOLUT_2') os.mkdir(solut_path) initial_data_file = os.path.join(work_path, 'initial.les') shutil.copy(REF_DATA_FILE, initial_data_file) shutil.copy(REF_SUPP_FILE, work_path) print(CLV[j_mode].shape) save_compressible_les_normalized(initial_data_file, make_data(CLV[j_mode]), verbose=False) les2vtu(work_path, solut_path, j) # plot flow field run_id = 'primal'+'_seg'+str(i_segment) print('runid:', run_id) work_path = os.path.join(CLV_PATH, run_id) os.mkdir(work_path) solut_path = os.path.join(work_path, 'SOLUT_2') os.mkdir(solut_path) initial_data_file = os.path.join(work_path, 'initial.les') shutil.copy(REF_DATA_FILE, initial_data_file) shutil.copy(REF_SUPP_FILE, work_path) # print('u0 shape: ', u0.field.shape) save_compressible_les(initial_data_file, make_data(u0.field), verbose=False) les2vtu(work_path, solut_path, j)
gpl-3.0
suiyuan2009/tensorflow
tensorflow/examples/tutorials/word2vec/word2vec_basic.py
13
9596
# Copyright 2015 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. # ============================================================================== """Basic word2vec example.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import math import os import random import zipfile import numpy as np from six.moves import urllib from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf # Step 1: Download the data. url = 'http://mattmahoney.net/dc/' def maybe_download(filename, expected_bytes): """Download a file if not present, and make sure it's the right size.""" if not os.path.exists(filename): filename, _ = urllib.request.urlretrieve(url + filename, filename) statinfo = os.stat(filename) if statinfo.st_size == expected_bytes: print('Found and verified', filename) else: print(statinfo.st_size) raise Exception( 'Failed to verify ' + filename + '. Can you get to it with a browser?') return filename filename = maybe_download('text8.zip', 31344016) # Read the data into a list of strings. def read_data(filename): """Extract the first file enclosed in a zip file as a list of words.""" with zipfile.ZipFile(filename) as f: data = tf.compat.as_str(f.read(f.namelist()[0])).split() return data vocabulary = read_data(filename) print('Data size', len(vocabulary)) # Step 2: Build the dictionary and replace rare words with UNK token. vocabulary_size = 50000 def build_dataset(words, n_words): """Process raw inputs into a dataset.""" count = [['UNK', -1]] count.extend(collections.Counter(words).most_common(n_words - 1)) dictionary = dict() for word, _ in count: dictionary[word] = len(dictionary) data = list() unk_count = 0 for word in words: if word in dictionary: index = dictionary[word] else: index = 0 # dictionary['UNK'] unk_count += 1 data.append(index) count[0][1] = unk_count reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys())) return data, count, dictionary, reversed_dictionary data, count, dictionary, reverse_dictionary = build_dataset(vocabulary, vocabulary_size) del vocabulary # Hint to reduce memory. print('Most common words (+UNK)', count[:5]) print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]]) data_index = 0 # Step 3: Function to generate a training batch for the skip-gram model. def generate_batch(batch_size, num_skips, skip_window): global data_index assert batch_size % num_skips == 0 assert num_skips <= 2 * skip_window batch = np.ndarray(shape=(batch_size), dtype=np.int32) labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32) span = 2 * skip_window + 1 # [ skip_window target skip_window ] buffer = collections.deque(maxlen=span) if data_index + span > len(data): data_index = 0 buffer.extend(data[data_index:data_index + span]) data_index += span for i in range(batch_size // num_skips): target = skip_window # target label at the center of the buffer targets_to_avoid = [skip_window] for j in range(num_skips): while target in targets_to_avoid: target = random.randint(0, span - 1) targets_to_avoid.append(target) batch[i * num_skips + j] = buffer[skip_window] labels[i * num_skips + j, 0] = buffer[target] if data_index == len(data): buffer[:] = data[:span] data_index = span else: buffer.append(data[data_index]) data_index += 1 # Backtrack a little bit to avoid skipping words in the end of a batch data_index = (data_index + len(data) - span) % len(data) return batch, labels batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1) for i in range(8): print(batch[i], reverse_dictionary[batch[i]], '->', labels[i, 0], reverse_dictionary[labels[i, 0]]) # Step 4: Build and train a skip-gram model. batch_size = 128 embedding_size = 128 # Dimension of the embedding vector. skip_window = 1 # How many words to consider left and right. num_skips = 2 # How many times to reuse an input to generate a label. # We pick a random validation set to sample nearest neighbors. Here we limit the # validation samples to the words that have a low numeric ID, which by # construction are also the most frequent. valid_size = 16 # Random set of words to evaluate similarity on. valid_window = 100 # Only pick dev samples in the head of the distribution. valid_examples = np.random.choice(valid_window, valid_size, replace=False) num_sampled = 64 # Number of negative examples to sample. graph = tf.Graph() with graph.as_default(): # Input data. train_inputs = tf.placeholder(tf.int32, shape=[batch_size]) train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1]) valid_dataset = tf.constant(valid_examples, dtype=tf.int32) # Ops and variables pinned to the CPU because of missing GPU implementation with tf.device('/cpu:0'): # Look up embeddings for inputs. embeddings = tf.Variable( tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0)) embed = tf.nn.embedding_lookup(embeddings, train_inputs) # Construct the variables for the NCE loss nce_weights = tf.Variable( tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size))) nce_biases = tf.Variable(tf.zeros([vocabulary_size])) # Compute the average NCE loss for the batch. # tf.nce_loss automatically draws a new sample of the negative labels each # time we evaluate the loss. loss = tf.reduce_mean( tf.nn.nce_loss(weights=nce_weights, biases=nce_biases, labels=train_labels, inputs=embed, num_sampled=num_sampled, num_classes=vocabulary_size)) # Construct the SGD optimizer using a learning rate of 1.0. optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss) # Compute the cosine similarity between minibatch examples and all embeddings. norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True)) normalized_embeddings = embeddings / norm valid_embeddings = tf.nn.embedding_lookup( normalized_embeddings, valid_dataset) similarity = tf.matmul( valid_embeddings, normalized_embeddings, transpose_b=True) # Add variable initializer. init = tf.global_variables_initializer() # Step 5: Begin training. num_steps = 100001 with tf.Session(graph=graph) as session: # We must initialize all variables before we use them. init.run() print('Initialized') average_loss = 0 for step in xrange(num_steps): batch_inputs, batch_labels = generate_batch( batch_size, num_skips, skip_window) feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels} # We perform one update step by evaluating the optimizer op (including it # in the list of returned values for session.run() _, loss_val = session.run([optimizer, loss], feed_dict=feed_dict) average_loss += loss_val if step % 2000 == 0: if step > 0: average_loss /= 2000 # The average loss is an estimate of the loss over the last 2000 batches. print('Average loss at step ', step, ': ', average_loss) average_loss = 0 # Note that this is expensive (~20% slowdown if computed every 500 steps) if step % 10000 == 0: sim = similarity.eval() for i in xrange(valid_size): valid_word = reverse_dictionary[valid_examples[i]] top_k = 8 # number of nearest neighbors nearest = (-sim[i, :]).argsort()[1:top_k + 1] log_str = 'Nearest to %s:' % valid_word for k in xrange(top_k): close_word = reverse_dictionary[nearest[k]] log_str = '%s %s,' % (log_str, close_word) print(log_str) final_embeddings = normalized_embeddings.eval() # Step 6: Visualize the embeddings. def plot_with_labels(low_dim_embs, labels, filename='tsne.png'): assert low_dim_embs.shape[0] >= len(labels), 'More labels than embeddings' plt.figure(figsize=(18, 18)) # in inches for i, label in enumerate(labels): x, y = low_dim_embs[i, :] plt.scatter(x, y) plt.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom') plt.savefig(filename) try: # pylint: disable=g-import-not-at-top from sklearn.manifold import TSNE import matplotlib.pyplot as plt tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000, method='exact') plot_only = 500 low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :]) labels = [reverse_dictionary[i] for i in xrange(plot_only)] plot_with_labels(low_dim_embs, labels) except ImportError: print('Please install sklearn, matplotlib, and scipy to show embeddings.')
apache-2.0
dknez/libmesh
doc/statistics/libmesh_sflogos.py
7
6095
#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np # Import stuff for working with dates from datetime import datetime from matplotlib.dates import date2num # SF.net pages and SFLogo Impressions. # On the site, located under "Sourceforge Traffic". Number of logos # (last column) seems to be the most useful one. # # This view should give you the last 12 months data # https://sourceforge.net/project/stats/detail.php?group_id=71130&ugn=libmesh&mode=12months&type=sfweb # This data has now changed to Google-analytics style... # After you select the proper date range, scroll down to the bottom # of the screen and it should show the totals for the two categories, # which are listed as "SF Logo" and "other" # Other SF Logo data = [ 'Jan 2003', 681, 479, 'Feb 2003', 659, 1939, 'Mar 2003', 488, 1754, 'Apr 2003', 667, 3202, 'May 2003', 608, 2552, 'Jun 2003', 562, 2190, 'Jul 2003', 997, 3097, 'Aug 2003', 745, 4708, 'Sep 2003', 906, 4937, 'Oct 2003', 892, 6834, 'Nov 2003', 1257, 8495, 'Dec 2003', 1147, 6439, 'Jan 2004', 823, 7791, 'Feb 2004', 906, 8787, 'Mar 2004', 979, 11309, 'Apr 2004', 835, 9393, 'May 2004', 851, 9796, 'Jun 2004', 750, 9961, 'Jul 2004', 618, 6337, 'Aug 2004', 912, 6647, 'Sep 2004', 554, 5736, 'Oct 2004', 524, 6144, 'Nov 2004', 685, 8122, 'Dec 2004', 583, 6136, 'Jan 2005', 215, 2668, 'Feb 2005', 732, 7618, 'Mar 2005', 944, 10283, 'Apr 2005', 837, 9605, 'May 2005', 1420, 9994, 'Jun 2005', 1691, 12031, 'Jul 2005', 849, 6740, 'Aug 2005', 1068, 11771, 'Sep 2005', 1119, 11459, 'Oct 2005', 772, 8614, 'Nov 2005', 845, 9383, 'Dec 2005', 814, 10606, 'Jan 2006', 1004, 11511, 'Feb 2006', 819, 10693, 'Mar 2006', 1097, 11925, 'Apr 2006', 960, 15664, 'May 2006', 1091, 14194, 'Jun 2006', 906, 12118, 'Jul 2006', 1022, 8935, 'Aug 2006', 914, 9370, 'Sep 2006', 1087, 11397, 'Oct 2006', 1311, 11516, 'Nov 2006', 1182, 10795, 'Dec 2006', 811, 9418, 'Jan 2007', 1236, 11522, 'Feb 2007', 1410, 10669, 'Mar 2007', 1568, 13141, 'Apr 2007', 1544, 12285, 'May 2007', 1362, 14992, 'Jun 2007', 2229, 17716, 'Jul 2007', 1822, 15192, 'Aug 2007', 1446, 12300, 'Sep 2007', 2045, 19599, 'Oct 2007', 2680, 14694, 'Nov 2007', 2344, 15211, 'Dec 2007', 2235, 10683, 'Jan 2008', 1582, 11290, 'Feb 2008', 1712, 12376, 'Mar 2008', 1908, 13204, 'Apr 2008', 2308, 13046, 'May 2008', 2013, 10312, 'Jun 2008', 2082, 11522, 'Jul 2008', 1880, 10859, 'Aug 2008', 2083, 11677, 'Sep 2008', 1739, 11446, 'Oct 2008', 2546, 13463, 'Nov 2008', 2152, 14491, 'Dec 2008', 2600, 15275, 'Jan 2009', 1897, 12910, 'Feb 2009', 1880, 12008, 'Mar 2009', 6348, 12696, 'Apr 2009', 1799, 14048, 'May 2009', 1771, 13122, 'Jun 2009', 1811, 12114, 'Jul 2009', 1878, 13600, 'Aug 2009', 2047, 10828, 'Sep 2009', 2807, 12914, 'Oct 2009', 4025, 17326, 'Nov 2009', 3702, 15648, 'Dec 2009', 3409, 12510, 'Jan 2010', 3737, 31211, 'Feb 2010', 5015, 28772, 'Mar 2010', 5652, 17882, 'Apr 2010', 4019, 17495, 'May 2010', 3336, 18117, 'Jun 2010', 2174, 21288, 'Jul 2010', 874, 13900, 'Aug 2010', 1160, 15153, 'Sep 2010', 1317, 13836, 'Oct 2010', 3543, 15279, 'Nov 2010', 3072, 18663, 'Dec 2010', 2257, 16381, 'Jan 2011', 2513, 19798, 'Feb 2011', 1678, 17870, 'Mar 2011', 1878, 17759, 'Apr 2011', 1948, 21264, 'May 2011', 2696, 15953, 'Jun 2011', 1514, 18409, 'Jul 2011', 1422, 13071, 'Aug 2011', 906, 7857, 'Sep 2011', 976, 9764, 'Oct 2011', 1699, 13285, 'Nov 2011', 1952, 16431, 'Dec 2011', 2735, 17849, 'Jan 2012', 1741, 14358, 'Feb 2012', 1017, 14262, 'Mar 2012', 1361, 14379, 'Apr 2012', 967, 15483, 'May 2012', 2384, 13656, 'Jun 2012', 1337, 14370, 'Jul 2012', 2107, 17286, 'Aug 2012', 8165, 53331, 'Sep 2012', 2268, 14704, 'Oct 2012', 738, 7333, # No data recorded from Oct 10 thru 28? 'Nov 2012', 6104, 39650, 'Dec 2012', 3439, 24706, # libmesh switched to github Dec 10, 2012 'Jan 2013', 2552, 31993, 'Feb 2013', 2107, 24913, 'Mar 2013', 1376, 23953, 'Apr 2013', 1582, 19285, 'May 2013', 1257, 16753, 'Jun 2013', 482, 14458, 'Jul 2013', 465, 11325, 'Aug 2013', 306, 7653, 'Sep 2013', 731, 11332, 'Oct 2013', 795, 15619, 'Nov 2013', 753, 16199, 'Dec 2013', 593, 11596, 'Jan 2014', 489, 11195, 'Feb 2014', 484, 14375, 'Mar 2014', 363, 13050, 'Apr 2014', 357, 15700, # As of June 1, 2014 the site above no longer exists... ] # Extract list of date strings date_strings = data[0::3] # Convert date strings into numbers date_nums = [] for d in date_strings: date_nums.append(date2num(datetime.strptime(d, '%b %Y'))) # Strip out number of logos/month for plotting n_logos_month = data[2::3] # Scale by 1000 n_logos_month = np.divide(n_logos_month, 1000.) # Get a reference to the figure fig = plt.figure() # 111 is equivalent to Matlab's subplot(1,1,1) command ax = fig.add_subplot(111) # Make the bar chart. One number/month, so width=30 # makes sense. ax.bar(date_nums, n_logos_month, width=30, color='b') # Set tick labels at desired locations xticklabels = ['Jan\n2003', 'Jan\n2005', 'Jan\n2007', 'Jan\n2009', 'Jan\n2011', 'Jan\n2013'] # Get numerical values for the tick labels tick_nums = [] for x in xticklabels: tick_nums.append(date2num(datetime.strptime(x, '%b\n%Y'))) ax.set_xticks(tick_nums) ax.set_xticklabels(xticklabels) # Make x-axis tick marks point outward ax.get_xaxis().set_tick_params(direction='out') # Set the xlimits plt.xlim(date_nums[0], date_nums[-1]+30); # Create title fig.suptitle('SFLogo Pages/Month (in Thousands)') # Save as PDF plt.savefig('libmesh_sflogos.pdf') # Local Variables: # python-indent: 2 # End:
lgpl-2.1
matthiasdiener/spack
var/spack/repos/builtin/packages/py-localcider/package.py
5
1786
############################################################################## # 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, tgamblin@llnl.gov, 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 PyLocalcider(PythonPackage): """Tools for calculating sequence properties of disordered proteins""" homepage = "http://pappulab.github.io/localCIDER" url = "https://pypi.io/packages/source/l/localcider/localcider-0.1.14.tar.gz" version('0.1.14', 'cd3c992595c5cb280374de3750663cfa') depends_on('py-setuptools', type='build') depends_on('py-numpy', type=('build', 'run')) depends_on('py-matplotlib', type=('build', 'run')) depends_on('py-scipy', type=('build', 'run'))
lgpl-2.1
bigfishman/oceanbase
oceanbase_0.4/tools/deploy/perf/1.py
12
1857
import datetime import re import sys try: import matplotlib.pyplot as plt except ImportError: plt = None time_format = "%Y-%m-%d %H:%M:%S" d = dict() start_time = None start_time = None sql_count = 0 sql_time = 0 sql_time_dist = dict() rpc_time = 0 urpc_time = 0 wait_time = 0 qps2time = dict() rpc_times = [] urpc_times = [] wait_times = [] for l in sys.stdin: m = re.search(r'trace_id=\[(\d+)\] sql=\[.*\] sql_to_logicalplan=\[\d+\] logicalplan_to_physicalplan=\[\d+\] handle_sql_time=\[(\d+)\] wait_sql_queue_time=\[(\d+)\] rpc:channel_id=\[\d+\] latency=\[(\d+)\] print_time=\[(\d+)\]', l) if m is not None: end_time = int(m.group(5)) if start_time is None: start_time = end_time trace_id = m.group(1) ts = m.group(5)[:-6] d[trace_id] = dict( sql_time = int(m.group(2)), wait_time = int(m.group(3)), rpc_time = int(m.group(4)), ) sql_count += 1 sql_time += d[trace_id]['sql_time'] if sql_time_dist.has_key(d[trace_id]['sql_time']): sql_time_dist[d[trace_id]['sql_time']] += 1 else: sql_time_dist[d[trace_id]['sql_time']] = 0 wait_time += d[trace_id]['wait_time'] wait_times.append(d[trace_id]['wait_time']) rpc_time += d[trace_id]['rpc_time'] rpc_times.append(d[trace_id]['rpc_time']) if qps2time.has_key(ts): qps2time[ts] += 1 else: qps2time[ts] = 0 elapsed_seconds = (end_time - start_time) / 10**6 qps = sql_count / elapsed_seconds avg_sql_time = float(sql_time) / sql_count avg_rpc_time = float(rpc_time) / sql_count avg_urpc_time = float(urpc_time) / sql_count avg_wait_time = float(wait_time) / sql_count print "QPS: %d" % (qps) print "AVG TIME: %f" % (avg_sql_time) print "AVG RPC TIME: %f" % (avg_rpc_time) print "AVG WAIT TIME: %f" % (avg_wait_time)
gpl-2.0
liamneath1/hailey.io
server-side/stock_market/TTSE_Parser.py
1
5362
import IndexScraper as iScrape import constants as const import urllib.request import pandas as pd import pprint as pp import datetime from bs4 import BeautifulSoup from pandas.tseries.offsets import BDay import sys import util import os class TTSE_Parser(iScrape.IndexScraper): def __init__(self, queryFreq, tableName, miscArgs): iScrape.IndexScraper.__init__(self, queryFreq, tableName, miscArgs) def multi_procR(self, ingest, extractArgs): # ingest is a 2 member list [start_date, end_date] self.extract_infoinRange(ingest[0], ingest[1]) def flush_index(self, tableName): print("IMPLEMENT ME") def extract_info(self, dateStr, addArgs={}): print("[" + str(os.getpid()) + "] : (NEW DATE) Scraping Info For: " + dateStr) url = const.TTSE_URL_ROOT + dateStr try: soup = BeautifulSoup(urllib.request.urlopen(url).read(), "lxml") content = soup.findAll("table") self.doHeavyExtraction(content, dateStr) except: print("Unexpected error:", sys.exc_info()[0]) pass def formatInfo(self, tableElements, conds, dateStr): inputStr = "" if (conds[1]): for element in tableElements[2:]: inputStr += element.get_text().strip('\n').strip("<br>").strip() + "," else: indices = [2, 12, 3, 4, 11] inputStr += "'" + dateStr + "'," for index in indices: text = tableElements[index].get_text().strip( '\n').strip("<br>").strip().replace(',', '') if (text == ""): inputStr += "NULL," else: inputStr += text + "," return inputStr[0:len(inputStr) - 1] + ",NULL" def add_element(self, entryKey, sqlFormatDateStr, rowEntry, bucket): if sqlFormatDateStr in self.extractedInfo: if entryKey in self.extractedInfo[sqlFormatDateStr][bucket]: storedVals = self.extractedInfo[sqlFormatDateStr][bucket][entryKey] storedVals.append(rowEntry) self.extractedInfo[sqlFormatDateStr][bucket][entryKey] = storedVals else: self.extractedInfo[sqlFormatDateStr][bucket][entryKey] = [ rowEntry] else: self.extractedInfo[sqlFormatDateStr] = { "indexInfo": {}, "companyInfo": {}} self.extractedInfo[sqlFormatDateStr][bucket][entryKey] = [ rowEntry] def doHeavyExtraction(self, content, dateStr): date = datetime.datetime.strptime(dateStr, "%m/%d/%y").date() sqlFormatDateStr = date.strftime("%Y-%m-%d") for table in content: pageResult = [] firstCond = table.find('td', text="Ordinary Shares") != None secondCond = len(table.findAll('b')) > 2 and len( table.find("tr").findAll("td")) == 8 bucket = "indexInfo" if secondCond else "companyInfo" if firstCond or secondCond: tableRows = table.findAll('tr') # this should give us all for index, row in enumerate(tableRows): tableElements = row.findAll('td') if len(tableElements) > 1: entryKey = str(tableElements[1].get_text()).strip() if(entryKey != "Security"): rowEntry = self.formatInfo( tableElements, [firstCond, secondCond], sqlFormatDateStr) self.add_element(entryKey, sqlFormatDateStr, rowEntry, bucket) def saveParsedDataToDb(self): companyInfo = {"tableName": self.tableName, "index_code": 1, } sqlQuery = "" append_info = 0 for date in self.extractedInfo: sqlCheck = "SELECT * from " + self.tableName + " WHERE index_code = " + \ str(companyInfo["index_code"]) + " and date = '" + date + "' LIMIT 1" if (len(self.dbUtil.makeQuery(sqlCheck, return_val=1)) < 1): # REMEMBER TO CHANGE THIS! sqlQuery += util.generateSqlStatement(self.extractedInfo[date]["companyInfo"], companyInfo, 1, append=append_info) append_info = 1 if (sqlQuery != ""): sqlQuery = sqlQuery[0:len(sqlQuery) - 2] + ";" self.dbUtil.makeQuery(sqlQuery) else: pp.pprint("NO INSERTION!") def extract_infoinRange(self, start_date, end_date): arr = self.createBuisDayArr(pd.to_datetime( start_date), pd.to_datetime(end_date)) for date in arr: self.extract_info(date.strftime("%m/%d/%y")) # date format set by TTSE ! if len(list(self.extractedInfo.keys())) > 0: self.saveParsedDataToDb() self.extractedInfo = {} # clear the dicitonary for fresh values to come def createBuisDayArr(self, start_date, end_date): arr = [] for n in self.generateBusiDays(start_date, end_date): arr.append(n.date()) return arr def generateBusiDays(self, start_date, end_date): curr_date = start_date while(curr_date < end_date): # [start_date: end_date] yield curr_date curr_date += BDay(1)
mit
QianruZhou333/ASleep
my_importData_small.py
2
1639
import numpy as np import pandas as pd input_file = "3_floor.csv" # comma delimited is the default df = pd.read_csv(input_file, header = 0) # for space delimited use: # df = pd.read_csv(input_file, header = 0, delimiter = " ") # for tab delimited use: # df = pd.read_csv(input_file, header = 0, delimiter = "\t") # put the original column names in a python list original_headers = list(df.columns.values) # remove the non-numeric columns df = df._get_numeric_data() # put the numeric column names in a python list numeric_headers = list(df.columns.values) # create a numpy array with the numeric values for input into scikit-learn numpy_array = df.as_matrix() # reverse the order of the columns #numeric_headers.reverse() #reverse_df = df[numeric_headers] # throughput random forest regression t = numpy_array[0:160, 3] x = np.linspace(0, 159, 160) xall = np.linspace(0, 181, 182) xtest = np.linspace(160, 181, 22) from sklearn.ensemble import RandomForestRegressor #tfit = RandomForestRegressor(100).fit(x[:, None], t).predict(x[:, None]) tfit = RandomForestRegressor(100).fit(numpy_array[0:160, 0:2 ], t).predict(numpy_array[160:182, 0:2]) import matplotlib.pyplot as plt fig, ax = plt.subplots() #ax.errorbar(x, t, 0.3, fmt='*', label="Training traffic") ax.plot(xtest, tfit, '-r', label="Predicted traffic") ax.errorbar(xtest, numpy_array[160:182, 3], fmt='g-o', label="Test traffic") #ax.set_ylabel('Throughput (kbits/second)') #ax.set_xlabel('Time in hours') #ax.set_title('Taffic Prediction with Random Forest Regression on 3rd floor') #ax.legend(loc="upper left") plt.savefig('0_floor_small.jpg', dpi=300) plt.show()
apache-2.0
fizz-ml/policybandit
bayestorch/hmc.py
1
3828
import torch as t import torch.nn.functional as f from torch.autograd import Variable from torch.optim import Optimizer import math import matplotlib.pyplot as plt import numpy as np class HMCSampler(object): """updates the model parameters by preforming n hcmc updates (larger description) """ def __init__(self,parameters,epsilon=0.01,n=100): self.epsilon = epsilon self.n = n self.p_list = parameters def resample_r(self): p_list = self.p_list self.r_list = [] for param in p_list: s = param.size() means = t.zeros(s) self.r_list.append(t.normal(means,1))#todo verify that this is correct def zero_grad(self): for param in self.p_list: if param.grad is not None: param.grad.data.zero_() def data_pass(self,closure_gen): p_list = self.p_list self.zero_grad() loss = 0 for closure in closure_gen(): loss += closure() loss.backward(retain_variables=True) g_list = list(map((lambda x: x.grad.data),p_list)) return g_list,loss def step(self,closure_gen): #TODO: add MC rejection self.resample_r() p_list = [x.data for x in self.p_list] r_list = self.r_list def assign(x,y): x.data = y epsilon = self.epsilon for i in range(self.n): #TODO: Clean up implementation with getter and setters g_list,_ = self.data_pass(closure_gen) r_list = list(map(lambda x,y: x-y*epsilon/2,r_list,g_list)) p_list = list(map(lambda x,y: x+y*epsilon,p_list,r_list)) list(map(assign,self.p_list,p_list)) g_list,loss = self.data_pass(closure_gen) r_list = list(map(lambda x,y: x-y*epsilon/2,r_list,g_list)) class ParameterGroup: def __init__(self,parameter_dict): self.parameters = parameter_dict def get_prior_llh(self): prior = 0 for value in self.parameters.values(): prior += value.get_prior_llh() return prior def parameter_list(self): p_list = [] for value in self.parameters.values(): p_list += value.parameter_list() return p_list def cuda(self): for value in self.parameters.values(): value.cuda() def cpu(self): for value in self.parameters.values(): value.cpu() def __getitem__(self,key): return self.parameters[key] class TensorParameter: def __init__(self,shape,std_dev,zeros = True): if zeros: print(type(shape), type(std_dev), type(zeros)) print(shape) self.parameter = Variable(t.FloatTensor(np.random.normal(size=shape, scale=std_dev/100.)),requires_grad = True) else: self.parameter = Variable(t.FloatTensor(np.random.normal(size=shape, scale=std_dev)),requires_grad = True) self.var = std_dev*std_dev self.shape = shape def parameter_list(self): return [self.parameter] def val(self): return self.parameter def cuda(self): self.parameter = self.parameter.cuda() def cpu(self): self.parameter = self.parameter.cpu() def get_prior_llh(self): prob = -t.log(self.parameter)**2 \ /(2*self.var) return t.sum(prob) def test_hmc(): p = Variable(t.FloatTensor([0]),requires_grad = True) sampler = HMCSampler([p]) p_values = [] closure = lambda: p**2/2 for i in range(20000): sampler.step(closure) p_values.append(scalar(p)) plt.hist(p_values) plt.show() def scalar(x): return x.data.cpu().numpy()[0] if __name__ == "__main__": test_hmc()
mit
anhaidgroup/py_entitymatching
py_entitymatching/tests/test_black_box_blocker.py
1
16764
import os from nose.tools import * import pandas as pd import unittest import py_entitymatching as em import py_entitymatching.feature.simfunctions as sim p = em.get_install_path() path_a = os.sep.join([p, 'tests', 'test_datasets', 'A.csv']) path_b = os.sep.join([p, 'tests', 'test_datasets', 'B.csv']) l_output_attrs = ['name', 'address'] r_output_attrs = ['name', 'address'] l_output_prefix = 'l_' r_output_prefix = 'r_' def _block_fn(x, y): if (sim.monge_elkan(x['name'], y['name']) < 0.6): return True else: return False # block tables using _block_fn expected_ids_1 = [('a2', 'b1'), ('a2', 'b3'), ('a2', 'b6'), ('a3', 'b2'), ('a3', 'b6'), ('a4', 'b2'), ('a5', 'b5')] # attribute equivalence on 'zipcode' expected_ids_zip = [('a1', 'b1'), ('a1', 'b2'), ('a1', 'b6'), ('a2', 'b3'), ('a2', 'b4'), ('a2', 'b5'), ('a3', 'b1'), ('a3', 'b2'), ('a3', 'b6'), ('a4', 'b3'), ('a4', 'b4'), ('a4', 'b5'), ('a5', 'b3'), ('a5', 'b4'), ('a5', 'b5')] # block tables using attr equiv on zipcode, then block candset using _block_fn expected_ids_2 = [('a2', 'b3'), ('a3', 'b2'), ('a3', 'b6'), ('a5', 'b5')] # drops all the tuple pairs def _evil_block_fn(x, y): return True class BlackBoxBlockerTestCases(unittest.TestCase): def setUp(self): self.A = em.read_csv_metadata(path_a) em.set_key(self.A, 'ID') self.B = em.read_csv_metadata(path_b) em.set_key(self.B, 'ID') self.bb = em.BlackBoxBlocker() def tearDown(self): del self.A del self.B del self.bb @raises(AssertionError) def test_bb_block_tables_invalid_ltable_1(self): self.bb.block_tables(None, self.B) @raises(AssertionError) def test_bb_block_tables_invalid_ltable_2(self): self.bb.block_tables([10, 10], self.B) @raises(AssertionError) def test_bb_block_tables_invalid_ltable_3(self): self.bb.block_tables(pd.DataFrame(), self.B) @raises(AssertionError) def test_bb_block_tables_invalid_rtable_1(self): self.bb.block_tables(self.A, None) @raises(AssertionError) def test_bb_block_tables_invalid_rtable_2(self): self.bb.block_tables(self.A, [10, 10]) @raises(AssertionError) def test_bb_block_tables_invalid_rtable_3(self): self.bb.block_tables(self.A, pd.DataFrame()) @raises(AssertionError) def test_bb_block_tables_invalid_l_output_attrs_1(self): self.bb.block_tables(self.A, self.B, l_output_attrs=1) @raises(AssertionError) def test_bb_block_tables_invalid_l_output_attrs_2(self): self.bb.block_tables(self.A, self.B, l_output_attrs='name') @raises(AssertionError) def test_bb_block_tables_invalid_l_output_attrs_3(self): self.bb.block_tables(self.A, self.B, l_output_attrs=[1, 2]) @raises(AssertionError) def test_bb_block_tables_bogus_l_output_attrs(self): self.bb.block_tables(self.A, self.B, l_output_attrs=['bogus_attr']) @raises(AssertionError) def test_bb_block_tables_invalid_r_output_attrs_1(self): self.bb.block_tables(self.A, self.B, r_output_attrs=1) @raises(AssertionError) def test_bb_block_tables_invalid_r_output_attrs_2(self): self.bb.block_tables(self.A, self.B, r_output_attrs='name') @raises(AssertionError) def test_bb_block_tables_invalid_r_output_attrs_3(self): self.bb.block_tables(self.A, self.B, r_output_attrs=[1, 2]) @raises(AssertionError) def test_bb_block_tables_bogus_r_output_attrs(self): self.bb.block_tables(self.A, self.B, r_output_attrs=['bogus_attr']) @raises(AssertionError) def test_bb_block_tables_invalid_l_output_prefix_1(self): self.bb.block_tables(self.A, self.B, l_output_prefix=None) @raises(AssertionError) def test_bb_block_tables_invalid_l_output_prefix_2(self): self.bb.block_tables(self.A, self.B, l_output_prefix=1) @raises(AssertionError) def test_bb_block_tables_invalid_l_output_prefix_3(self): self.bb.block_tables(self.A, self.B, l_output_prefix=True) @raises(AssertionError) def test_bb_block_tables_invalid_r_output_prefix_1(self): self.bb.block_tables(self.A, self.B, r_output_prefix=None) @raises(AssertionError) def test_bb_block_tables_invalid_r_output_prefix_2(self): self.bb.block_tables(self.A, self.B, r_output_prefix=1) @raises(AssertionError) def test_bb_block_tables_invalid_r_output_prefix_3(self): self.bb.block_tables(self.A, self.B, r_output_prefix=True) @raises(AssertionError) def test_bb_block_tables_invalid_verbose_1(self): self.bb.block_tables(self.A, self.B, verbose=None) @raises(AssertionError) def test_bb_block_tables_invalid_verbose_2(self): self.bb.block_tables(self.A, self.B, verbose=1) @raises(AssertionError) def test_bb_block_tables_invalid_verbose_3(self): self.bb.block_tables(self.A, self.B, verbose='yes') def test_bb_block_tables(self): self.bb.set_black_box_function(_block_fn) C = self.bb.block_tables(self.A, self.B, l_output_attrs=l_output_attrs, r_output_attrs=r_output_attrs, l_output_prefix=l_output_prefix, r_output_prefix=r_output_prefix) validate_metadata(C, l_output_attrs, r_output_attrs, l_output_prefix, r_output_prefix) validate_data(C, expected_ids_1) def test_bb_block_tables_empty_ltable(self): empty_A = pd.DataFrame(columns=self.A.columns) em.set_key(empty_A, 'ID') self.bb.set_black_box_function(_block_fn) C = self.bb.block_tables(empty_A, self.B) validate_metadata(C) validate_data(C) def test_bb_block_tables_empty_rtable(self): empty_B = pd.DataFrame(columns=self.B.columns) em.set_key(empty_B, 'ID') self.bb.set_black_box_function(_block_fn) C = self.bb.block_tables(self.A, empty_B) validate_metadata(C) validate_data(C) def test_bb_block_tables_wi_no_output_tuples(self): self.bb.set_black_box_function(_evil_block_fn) C = self.bb.block_tables(self.A, self.B) validate_metadata(C) validate_data(C) def test_bb_block_tables_wi_null_l_output_attrs(self): self.bb.set_black_box_function(_block_fn) C = self.bb.block_tables(self.A, self.B, r_output_attrs=r_output_attrs) validate_metadata(C, r_output_attrs=r_output_attrs) validate_data(C, expected_ids_1) def test_bb_block_tables_wi_null_r_output_attrs(self): self.bb.set_black_box_function(_block_fn) C = self.bb.block_tables(self.A, self.B, l_output_attrs) validate_metadata(C, l_output_attrs) validate_data(C, expected_ids_1) def test_bb_block_tables_wi_empty_l_output_attrs(self): self.bb.set_black_box_function(_block_fn) C = self.bb.block_tables(self.A, self.B, [], r_output_attrs) validate_metadata(C, [], r_output_attrs) validate_data(C, expected_ids_1) def test_bb_block_tables_wi_empty_r_output_attrs(self): self.bb.set_black_box_function(_block_fn) C = self.bb.block_tables(self.A, self.B, l_output_attrs, []) validate_metadata(C, l_output_attrs, []) validate_data(C, expected_ids_1) @raises(AssertionError) def test_bb_block_candset_invalid_candset_1(self): self.bb.block_candset(None) @raises(AssertionError) def test_bb_block_candset_invalid_candset_2(self): self.bb.block_candset([10, 10]) @raises(KeyError) def test_bb_block_candset_invalid_candset_3(self): self.bb.set_black_box_function(_block_fn) self.bb.block_candset(pd.DataFrame()) @raises(AssertionError) def test_bb_block_candset_invalid_verbose_1(self): C = self.bb.block_tables(self.A, self.B) self.bb.block_candset(C, verbose=None) @raises(AssertionError) def test_bb_block_candset_invalid_verbose_2(self): C = self.bb.block_tables(self.A, self.B) self.bb.block_candset(C, verbose=1) @raises(AssertionError) def test_bb_block_candset_invalid_verbose_3(self): C = self.bb.block_tables(self.A, self.B) self.bb.block_candset(C, verbose='yes') @raises(AssertionError) def test_bb_block_candset_invalid_show_progress_1(self): C = self.bb.block_tables(self.A, self.B) self.bb.block_candset(C, show_progress=None) @raises(AssertionError) def test_bb_block_candset_invalid_show_progress_2(self): C = self.bb.block_tables(self.A, self.B) self.bb.block_candset(C, show_progress=1) @raises(AssertionError) def test_bb_block_candset_invalid_show_progress_3(self): C = self.bb.block_tables(self.A, self.B) self.bb.block_candset(C, show_progress='yes') def test_bb_block_candset(self): ab = em.AttrEquivalenceBlocker() C = ab.block_tables(self.A, self.B, 'zipcode', 'zipcode', l_output_attrs, r_output_attrs, l_output_prefix, r_output_prefix) validate_metadata(C, l_output_attrs, r_output_attrs, l_output_prefix, r_output_prefix) validate_data(C, expected_ids_zip) self.bb.set_black_box_function(_block_fn) D = self.bb.block_candset(C) validate_metadata_two_candsets(C, D) validate_data(D, expected_ids_2) def test_bb_block_candset_empty_input(self): self.bb.set_black_box_function(_evil_block_fn) C = self.bb.block_tables(self.A, self.B) validate_metadata(C) validate_data(C) self.bb.set_black_box_function(_block_fn) D = self.bb.block_candset(C) validate_metadata_two_candsets(C, D) validate_data(D) def test_bb_block_candset_empty_output(self): self.bb.set_black_box_function(_block_fn) C = self.bb.block_tables(self.A, self.B) validate_metadata(C) validate_data(C, expected_ids_1) self.bb.set_black_box_function(_evil_block_fn) D = self.bb.block_candset(C) validate_metadata_two_candsets(C, D) validate_data(D) def test_bb_block_tuples(self): self.bb.set_black_box_function(_block_fn) assert_equal(self.bb.block_tuples(self.A.loc[1], self.B.loc[2]), False) assert_equal(self.bb.block_tuples(self.A.loc[2], self.B.loc[2]), True) class BlackBoxBlockerMulticoreTestCases(unittest.TestCase): def setUp(self): self.A = em.read_csv_metadata(path_a) em.set_key(self.A, 'ID') self.B = em.read_csv_metadata(path_b) em.set_key(self.B, 'ID') self.bb = em.BlackBoxBlocker() def tearDown(self): del self.A del self.B del self.bb def test_bb_block_tables_wi_global_black_box_fn_njobs_2(self): self.bb.set_black_box_function(_block_fn) C = self.bb.block_tables(self.A, self.B, l_output_attrs=l_output_attrs, r_output_attrs=r_output_attrs, l_output_prefix=l_output_prefix, r_output_prefix=r_output_prefix, n_jobs=2) validate_metadata(C, l_output_attrs, r_output_attrs, l_output_prefix, r_output_prefix) validate_data(C, expected_ids_1) def test_bb_block_tables_wi_local_black_box_fn_njobs_2(self): def block_fn(x, y): if (sim.monge_elkan(x['name'], y['name']) < 0.6): return True else: return False self.bb.set_black_box_function(block_fn) C = self.bb.block_tables(self.A, self.B, l_output_attrs=l_output_attrs, r_output_attrs=r_output_attrs, l_output_prefix=l_output_prefix, r_output_prefix=r_output_prefix, n_jobs=2) validate_metadata(C, l_output_attrs, r_output_attrs, l_output_prefix, r_output_prefix) validate_data(C, expected_ids_1) def test_bb_block_tables_wi_class_black_box_fn_njobs_2(self): class dummy: def block_fn(self, x, y): if (sim.monge_elkan(x['name'], y['name']) < 0.6): return True else: return False self.bb.set_black_box_function(dummy().block_fn) C = self.bb.block_tables(self.A, self.B, l_output_attrs=l_output_attrs, r_output_attrs=r_output_attrs, l_output_prefix=l_output_prefix, r_output_prefix=r_output_prefix, n_jobs=2) validate_metadata(C, l_output_attrs, r_output_attrs, l_output_prefix, r_output_prefix) validate_data(C, expected_ids_1) def test_bb_block_tables_njobs_all(self): self.bb.set_black_box_function(_block_fn) C = self.bb.block_tables(self.A, self.B, l_output_attrs=l_output_attrs, r_output_attrs=r_output_attrs, l_output_prefix=l_output_prefix, r_output_prefix=r_output_prefix, n_jobs=-1) validate_metadata(C, l_output_attrs, r_output_attrs, l_output_prefix, r_output_prefix) validate_data(C, expected_ids_1) def test_bb_block_candset_njobs_2(self): ab = em.AttrEquivalenceBlocker() C = ab.block_tables(self.A, self.B, 'zipcode', 'zipcode', l_output_attrs, r_output_attrs, l_output_prefix, r_output_prefix) validate_metadata(C, l_output_attrs, r_output_attrs, l_output_prefix, r_output_prefix) validate_data(C, expected_ids_zip) self.bb.set_black_box_function(_block_fn) D = self.bb.block_candset(C, n_jobs=2) validate_metadata_two_candsets(C, D) validate_data(D, expected_ids_2) def test_bb_block_candset_njobs_all(self): ab = em.AttrEquivalenceBlocker() C = ab.block_tables(self.A, self.B, 'zipcode', 'zipcode', l_output_attrs, r_output_attrs, l_output_prefix, r_output_prefix) validate_metadata(C, l_output_attrs, r_output_attrs, l_output_prefix, r_output_prefix) validate_data(C, expected_ids_zip) self.bb.set_black_box_function(_block_fn) D = self.bb.block_candset(C, n_jobs=-1) validate_metadata_two_candsets(C, D) validate_data(D, expected_ids_2) # helper functions for validating the output def validate_metadata(C, l_output_attrs=None, r_output_attrs=None, l_output_prefix='ltable_', r_output_prefix='rtable_', l_key='ID', r_key='ID'): s1 = ['_id', l_output_prefix + l_key, r_output_prefix + r_key] if l_output_attrs: s1 += [l_output_prefix + x for x in l_output_attrs if x != l_key] if r_output_attrs: s1 += [r_output_prefix + x for x in r_output_attrs if x != r_key] s1 = sorted(s1) assert_equal(s1, sorted(C.columns)) assert_equal(em.get_key(C), '_id') assert_equal(em.get_property(C, 'fk_ltable'), l_output_prefix + l_key) assert_equal(em.get_property(C, 'fk_rtable'), r_output_prefix + r_key) def validate_data(C, expected_ids=None): if expected_ids: lid = em.get_property(C, 'fk_ltable') rid = em.get_property(C, 'fk_rtable') C_ids = C[[lid, rid]].set_index([lid, rid]) actual_ids = sorted(C_ids.index.values.tolist()) assert_equal(expected_ids, actual_ids) else: assert_equal(len(C), 0) def validate_metadata_two_candsets(C, D): assert_equal(sorted(C.columns), sorted(D.columns)) assert_equal(em.get_key(D), em.get_key(C)) assert_equal(em.get_property(D, 'fk_ltable'), em.get_property(C, 'fk_ltable')) assert_equal(em.get_property(D, 'fk_rtable'), em.get_property(C, 'fk_rtable'))
bsd-3-clause
CenterForTheBuiltEnvironment/comfort_tool
comfort.py
1
5570
from io import TextIOWrapper from flask import ( Flask, request, render_template, send_from_directory, abort, jsonify, make_response, ) from pythermalcomfort.models import pmv_ppd, set_tmp, cooling_effect from pythermalcomfort.psychrometrics import v_relative, clo_dynamic import pandas as pd ALLOWED_EXTENSIONS = {"csv"} STATIC_URL_PATH = "/static" app = Flask(__name__, static_url_path=STATIC_URL_PATH) # define the extension files that can be uploaded by users def allowed_file(filename): return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS @app.route("/download/<path:filename>") def download_file(filename): if ".." in filename: abort(404) return send_from_directory( "./media/", filename, mimetype="application/octet-stream" ) @app.route("/api/v1/comfort/pmv", methods=["GET"]) def api_id(): # Check if an ID was provided as part of the URL. # If ID is provided, assign it to a variable. # If no ID is provided, display an error in the browser. try: clo = float(request.args["clo"]) ta = float(request.args["ta"]) tr = float(request.args["tr"]) v = float(request.args["v"]) met = float(request.args["met"]) rh = float(request.args["rh"]) except KeyError: return "Error: You did not provided all the input parameters" # Create an empty list for our results results = dict() value = pmv_ppd(ta, tr, v, rh, met, clo, wme=0, standard="ASHRAE") results["data"] = [] results["data"].append(value) results["message"] = "success" # Use the jsonify function from Flask to convert our list of # Python dictionaries to the JSON format. return jsonify(results) # Upload page - The user can upload a csv with input environmental parameters and # returns a csv with indexes calculated @app.route( "/upload" ) # tutorial https://stackoverflow.com/questions/27628053/uploading-and # -downloading-files-with-flask def upload(): return render_template("upload.html") # Upload page - The user can upload a csv with input environmental parameters and # returns a csv with indexes calculated @app.route( "/other_tools" ) # tutorial https://stackoverflow.com/questions/27628053/uploading-and # -downloading-files-with-flask def other_tools(): return render_template("other_tools.html") # this function process the uploaded file and automatically downloads the file with the # results @app.route("/transform", methods=["POST"]) def transform_view(): # get the uploaded file request_file = request.files["data_file"] # check file if not request_file: return "No file selected" if not allowed_file(request_file.filename): return "The file format is not allowed. Please upload a csv" # read file csv_file = TextIOWrapper(request_file, encoding="utf-8") df = pd.read_csv(csv_file) fields = { "Air temperature": "ta", "MRT": "tr", "Air speed": "vel", "Relative humidity": "rh", "Metabolic rate": "met", "Clothing level": "clo", } si_unit = any( [ True if ("Air temperature" in x) and (x.split(" [")[1] == "C]") else False for x in df.columns ] ) df.columns = [fields[x.split(" [")[0]] if " [" in x else x for x in df.columns] df["clo_dynamic"] = df.apply( lambda row: clo_dynamic(clo=row["clo"], met=row["met"]), axis=1 ) results = [] ta = df["ta"].values tr = df["tr"].values vel = df["vel"].values rh = df["rh"].values met = df["met"].values clo = df["clo"].values for ix in range(df.shape[0]): if si_unit: units = "SI" _vr = v_relative(vel[ix], met[ix]) else: units = "IP" _vr = v_relative(vel[ix] / 60 * 0.3048, met[ix]) * 3.28084 try: _set = set_tmp(ta[ix], tr[ix], _vr, rh[ix], met[ix], clo[ix], units=units) except: _set = 9999 try: _ce = cooling_effect( ta[ix], tr[ix], _vr, rh[ix], met[ix], clo[ix], units=units ) except: _ce = 9999 try: _pmv_ppd = pmv_ppd( ta[ix], tr[ix], _vr, rh[ix], met[ix], clo[ix], standard="ashrae", units=units, ) _pmv = _pmv_ppd["pmv"] _ppd = _pmv_ppd["ppd"] except: _pmv, _ppd = [9999, 9999] results.append({"pmv": _pmv, "ppd": _ppd, "ce": _ce, "vr": _vr, "set": _set}) # split the pmv column in two since currently contains both pmv and ppd values df_ = pd.DataFrame(results) df = pd.concat([df, df_], axis=1, sort=False) df["LEED compliance"] = [True if x < 10 else False for x in df.ppd] df.loc[df.ppd == 9999, ["pmv", "ppd", "ce", "LEED compliance"]] = None resp = make_response(df.to_csv(index=False)) resp.headers["Content-Disposition"] = "attachment; filename=export.csv" resp.headers["Content-Type"] = "text/csv" return resp @app.route("/compare") def compare(): return render_template("compare.html") @app.route("/ranges") def ranges(): return render_template("ranges.html") @app.route("/EN") def en(): return render_template("en.html") @app.route("/") def index(): return render_template("ashrae.html") if __name__ == "__main__": app.run(debug=False)
gpl-2.0
rgerkin/python-neo
examples/roi_demo.py
6
1105
""" Example of working with RegionOfInterest objects """ import matplotlib.pyplot as plt import numpy as np from neo.core import CircularRegionOfInterest, RectangularRegionOfInterest, PolygonRegionOfInterest from numpy.random import rand def plot_roi(roi, shape): img = rand(120, 100) pir = np.array(roi.pixels_in_region()).T img[pir[1], pir[0]] = 5 plt.imshow(img, cmap='gray_r') plt.clim(0, 5) ax = plt.gca() ax.add_artist(shape) roi = CircularRegionOfInterest(x=50.3, y=50.8, radius=30.2) shape = plt.Circle(roi.centre, roi.radius, color='r', fill=False) plt.subplot(1, 3, 1) plot_roi(roi, shape) roi = RectangularRegionOfInterest(x=50.3, y=40.2, width=40.1, height=50.3) shape = plt.Rectangle((roi.x - roi.width/2.0, roi.y - roi.height/2.0), roi.width, roi.height, color='r', fill=False) plt.subplot(1, 3, 2) plot_roi(roi, shape) roi = PolygonRegionOfInterest( (20.3, 30.2), (80.7, 30.1), (55.2, 59.4) ) shape = plt.Polygon(np.array(roi.vertices), closed=True, color='r', fill=False) plt.subplot(1, 3, 3) plot_roi(roi, shape) plt.show()
bsd-3-clause
raphaelvalentin/qtlayout
syntax/interpolate/plotting/contour.py
1
1449
#!/usr/local/bin/python import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter from matplotlib.figure import SubplotParams from matplotlib.ticker import MaxNLocator import os from function import * from xplot import * class contour(plot): def __init__(self, **kwargs): plot.__init__(self, **kwargs) def setProperties(self): plot.setProperties(self) plt.rcParams['xtick.direction'] = 'out' plt.rcParams['ytick.direction'] = 'out' plt.rcParams['contour.negative_linestyle'] = 'solid' def plot(self, x, y, z): if not(len(z) == len(x) == len(y)): raise Exception('contour plot: x, y, z sizes are not equal.') size = (len(distinct(x)), len(distinct(y))) if not(size[0]*size[1] == len(z)): raise Exception('contour plot: x, y, z sizes are not coherent.') x = np.array(x); y = np.array(y); z = np.array(z) x.resize(size); y.resize(size); z.resize(size) self['plots'] = [(x, y, z, 10, {'color':'r'})] def getFigure(self): if not os.path.exists(self['filename']): self.setProperties() [(x, y, z, i, color)] = self['plots'] color['colors'] = 'r' CS = plt.contour(x, y, z, i, **color) plt.clabel(CS, fontsize=19, inline=1, fmt='%g', colors='r') plt.draw() plt.savefig(self['filename'], dpi=self['dpi']) return self
gpl-2.0
shikhardb/scikit-learn
sklearn/neighbors/tests/test_ball_tree.py
10
9723
import numpy as np from numpy.testing import assert_array_almost_equal from sklearn.neighbors.ball_tree import (BallTree, NeighborsHeap, simultaneous_sort, kernel_norm, nodeheap_sort, DTYPE, ITYPE) from sklearn.neighbors.dist_metrics import DistanceMetric from sklearn.utils.testing import SkipTest, assert_allclose rng = np.random.RandomState(10) V = rng.rand(3, 3) V = np.dot(V, V.T) DIMENSION = 3 METRICS = {'euclidean': {}, 'manhattan': {}, 'minkowski': dict(p=3), 'chebyshev': {}, 'seuclidean': dict(V=np.random.random(DIMENSION)), 'wminkowski': dict(p=3, w=np.random.random(DIMENSION)), 'mahalanobis': dict(V=V)} DISCRETE_METRICS = ['hamming', 'canberra', 'braycurtis'] BOOLEAN_METRICS = ['matching', 'jaccard', 'dice', 'kulsinski', 'rogerstanimoto', 'russellrao', 'sokalmichener', 'sokalsneath'] def brute_force_neighbors(X, Y, k, metric, **kwargs): D = DistanceMetric.get_metric(metric, **kwargs).pairwise(Y, X) ind = np.argsort(D, axis=1)[:, :k] dist = D[np.arange(Y.shape[0])[:, None], ind] return dist, ind def test_ball_tree_query(): np.random.seed(0) X = np.random.random((40, DIMENSION)) Y = np.random.random((10, DIMENSION)) def check_neighbors(dualtree, breadth_first, k, metric, kwargs): bt = BallTree(X, leaf_size=1, metric=metric, **kwargs) dist1, ind1 = bt.query(Y, k, dualtree=dualtree, breadth_first=breadth_first) dist2, ind2 = brute_force_neighbors(X, Y, k, metric, **kwargs) # don't check indices here: if there are any duplicate distances, # the indices may not match. Distances should not have this problem. assert_array_almost_equal(dist1, dist2) for (metric, kwargs) in METRICS.items(): for k in (1, 3, 5): for dualtree in (True, False): for breadth_first in (True, False): yield (check_neighbors, dualtree, breadth_first, k, metric, kwargs) def test_ball_tree_query_boolean_metrics(): np.random.seed(0) X = np.random.random((40, 10)).round(0) Y = np.random.random((10, 10)).round(0) k = 5 def check_neighbors(metric): bt = BallTree(X, leaf_size=1, metric=metric) dist1, ind1 = bt.query(Y, k) dist2, ind2 = brute_force_neighbors(X, Y, k, metric) assert_array_almost_equal(dist1, dist2) for metric in BOOLEAN_METRICS: yield check_neighbors, metric def test_ball_tree_query_discrete_metrics(): np.random.seed(0) X = (4 * np.random.random((40, 10))).round(0) Y = (4 * np.random.random((10, 10))).round(0) k = 5 def check_neighbors(metric): bt = BallTree(X, leaf_size=1, metric=metric) dist1, ind1 = bt.query(Y, k) dist2, ind2 = brute_force_neighbors(X, Y, k, metric) assert_array_almost_equal(dist1, dist2) for metric in DISCRETE_METRICS: yield check_neighbors, metric def test_ball_tree_query_radius(n_samples=100, n_features=10): np.random.seed(0) X = 2 * np.random.random(size=(n_samples, n_features)) - 1 query_pt = np.zeros(n_features, dtype=float) eps = 1E-15 # roundoff error can cause test to fail bt = BallTree(X, leaf_size=5) rad = np.sqrt(((X - query_pt) ** 2).sum(1)) for r in np.linspace(rad[0], rad[-1], 100): ind = bt.query_radius(query_pt, r + eps)[0] i = np.where(rad <= r + eps)[0] ind.sort() i.sort() assert_array_almost_equal(i, ind) def test_ball_tree_query_radius_distance(n_samples=100, n_features=10): np.random.seed(0) X = 2 * np.random.random(size=(n_samples, n_features)) - 1 query_pt = np.zeros(n_features, dtype=float) eps = 1E-15 # roundoff error can cause test to fail bt = BallTree(X, leaf_size=5) rad = np.sqrt(((X - query_pt) ** 2).sum(1)) for r in np.linspace(rad[0], rad[-1], 100): ind, dist = bt.query_radius(query_pt, r + eps, return_distance=True) ind = ind[0] dist = dist[0] d = np.sqrt(((query_pt - X[ind]) ** 2).sum(1)) assert_array_almost_equal(d, dist) 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) 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_ball_tree_kde(n_samples=100, n_features=3): np.random.seed(0) X = np.random.random((n_samples, n_features)) Y = np.random.random((n_samples, n_features)) bt = BallTree(X, leaf_size=10) for kernel in ['gaussian', 'tophat', 'epanechnikov', 'exponential', 'linear', 'cosine']: for h in [0.01, 0.1, 1]: dens_true = compute_kernel_slow(Y, X, kernel, h) def check_results(kernel, h, atol, rtol, breadth_first): dens = bt.kernel_density(Y, h, atol=atol, rtol=rtol, kernel=kernel, breadth_first=breadth_first) assert_allclose(dens, dens_true, atol=atol, rtol=max(rtol, 1e-7)) for rtol in [0, 1E-5]: for atol in [1E-6, 1E-2]: for breadth_first in (True, False): yield (check_results, kernel, h, atol, rtol, breadth_first) def test_gaussian_kde(n_samples=1000): # Compare gaussian KDE results to scipy.stats.gaussian_kde from scipy.stats import gaussian_kde np.random.seed(0) x_in = np.random.normal(0, 1, n_samples) x_out = np.linspace(-5, 5, 30) for h in [0.01, 0.1, 1]: bt = BallTree(x_in[:, None]) try: gkde = gaussian_kde(x_in, bw_method=h / np.std(x_in)) except TypeError: raise SkipTest("Old version of scipy, doesn't accept " "explicit bandwidth.") dens_bt = bt.kernel_density(x_out[:, None], h) / n_samples dens_gkde = gkde.evaluate(x_out) assert_array_almost_equal(dens_bt, dens_gkde, decimal=3) def test_ball_tree_two_point(n_samples=100, n_features=3): np.random.seed(0) X = np.random.random((n_samples, n_features)) Y = np.random.random((n_samples, n_features)) r = np.linspace(0, 1, 10) bt = BallTree(X, leaf_size=10) D = DistanceMetric.get_metric("euclidean").pairwise(Y, X) counts_true = [(D <= ri).sum() for ri in r] def check_two_point(r, dualtree): counts = bt.two_point_correlation(Y, r=r, dualtree=dualtree) assert_array_almost_equal(counts, counts_true) for dualtree in (True, False): yield check_two_point, r, dualtree def test_ball_tree_pickle(): import pickle np.random.seed(0) X = np.random.random((10, 3)) bt1 = BallTree(X, leaf_size=1) ind1, dist1 = bt1.query(X) def check_pickle_protocol(protocol): s = pickle.dumps(bt1, protocol=protocol) bt2 = pickle.loads(s) ind2, dist2 = bt2.query(X) assert_array_almost_equal(ind1, ind2) assert_array_almost_equal(dist1, dist2) for protocol in (0, 1, 2): yield check_pickle_protocol, protocol def test_neighbors_heap(n_pts=5, n_nbrs=10): heap = NeighborsHeap(n_pts, n_nbrs) for row in range(n_pts): d_in = np.random.random(2 * n_nbrs).astype(DTYPE) i_in = np.arange(2 * n_nbrs, dtype=ITYPE) for d, i in zip(d_in, i_in): heap.push(row, d, i) ind = np.argsort(d_in) d_in = d_in[ind] i_in = i_in[ind] d_heap, i_heap = heap.get_arrays(sort=True) assert_array_almost_equal(d_in[:n_nbrs], d_heap[row]) assert_array_almost_equal(i_in[:n_nbrs], i_heap[row]) def test_node_heap(n_nodes=50): vals = np.random.random(n_nodes).astype(DTYPE) i1 = np.argsort(vals) vals2, i2 = nodeheap_sort(vals) assert_array_almost_equal(i1, i2) assert_array_almost_equal(vals[i1], vals2) def test_simultaneous_sort(n_rows=10, n_pts=201): dist = np.random.random((n_rows, n_pts)).astype(DTYPE) ind = (np.arange(n_pts) + np.zeros((n_rows, 1))).astype(ITYPE) dist2 = dist.copy() ind2 = ind.copy() # simultaneous sort rows using function simultaneous_sort(dist, ind) # simultaneous sort rows using numpy i = np.argsort(dist2, axis=1) row_ind = np.arange(n_rows)[:, None] dist2 = dist2[row_ind, i] ind2 = ind2[row_ind, i] assert_array_almost_equal(dist, dist2) assert_array_almost_equal(ind, ind2) def test_query_haversine(): np.random.seed(0) X = 2 * np.pi * np.random.random((40, 2)) bt = BallTree(X, leaf_size=1, metric='haversine') dist1, ind1 = bt.query(X, k=5) dist2, ind2 = brute_force_neighbors(X, X, k=5, metric='haversine') assert_array_almost_equal(dist1, dist2) assert_array_almost_equal(ind1, ind2) if __name__ == '__main__': import nose nose.runmodule()
bsd-3-clause
davebrent/aubio
python/demos/demo_sink_create_woodblock.py
10
1580
#! /usr/bin/env python import sys from math import pi, e from aubio import sink from numpy import arange, resize, sin, exp, zeros if len(sys.argv) < 2: print 'usage: %s <outputfile> [samplerate]' % sys.argv[0] sys.exit(1) samplerate = 44100 # samplerate in Hz if len( sys.argv ) > 2: samplerate = int(sys.argv[2]) pitch = 2200 # in Hz blocksize = 256 # in samples duration = 0.02 # in seconds twopi = pi * 2. duration = int ( samplerate * duration ) # convert to samples attack = int (samplerate * .001 ) decay = .5 period = float(samplerate) / pitch # create a sine lookup table tablelen = 1000 sinetable = arange(tablelen + 1, dtype = 'float32') sinetable = 0.7 * sin(twopi * sinetable/tablelen) sinetone = zeros((duration,), dtype = 'float32') # compute sinetone at floating point period for i in range(duration): x = int((i % period) / float(period) * tablelen) idx = int(x) frac = x - idx a = sinetable[idx] b = sinetable[idx + 1] sinetone[i] = a + frac * (b -a) # apply some envelope float_ramp = arange(duration, dtype = 'float32') sinetone *= exp( - e * float_ramp / duration / decay) sinetone[:attack] *= exp( e * ( float_ramp[:attack] / attack - 1 ) ) if 1: import matplotlib.pyplot as plt plt.plot(sinetone) plt.show() my_sink = sink(sys.argv[1], samplerate) total_frames = 0 while total_frames + blocksize < duration: my_sink(sinetone[total_frames:total_frames+blocksize], blocksize) total_frames += blocksize my_sink(sinetone[total_frames:duration], duration - total_frames)
gpl-3.0
moreati/pandashells
pandashells/lib/outlier_lib.py
7
2092
#! /usr/bin/env python # standard library imports from collections import Counter from pandashells.lib import module_checker_lib # import required dependencies module_checker_lib.check_for_modules(['pandas', 'numpy']) import pandas as pd import numpy as np # disable the chained assignment warning because raises fale alarm pd.options.mode.chained_assignment = None # recursive edit a series def sigma_edit_series(sigma_thresh, in_series, iter_counter=None, max_iter=20): iter_counter = Counter() if iter_counter is None else iter_counter if in_series.count() == 0: msg = "Error: No non-NaN values from which to remove outliers" raise ValueError(msg) iter_counter.update('n') if iter_counter['n'] > max_iter: msg = "Error: Max Number of iterations exceeded in sigma-editing" raise ValueError(msg) resid = in_series - in_series.mean() std = resid.std() sigma_t = sigma_thresh * std outside = resid.abs() >= sigma_t if any(outside): in_series.loc[outside] = np.NaN in_series = sigma_edit_series( sigma_thresh, in_series, iter_counter, max_iter) return in_series def ensure_col_exists(df, col, df_name='dataframe'): if not df.empty and col not in list(df.columns): msg = 'in sigma_edit: {} does not have column {}'.format( df_name, repr(col)) raise ValueError(msg) def sigma_edit_dataframe(sigma_thresh, columns, df, max_iter=20): """ :type sigma_thresh: float :param sigma_thresh: The sigma threshold :type columns: list :param columns: a list of columns to sigma edit :type df: pandas.DataFrame :param df: The dataframe with columns of data to sigma-edit :type max_iter: int :param max_iter: Cap the number of iteration at this number :rtype: Pandas DataFrame :returns: A dataframe with ouliers set to NaN """ for col in columns: ensure_col_exists(df, col, 'df') ser = df[col] df.loc[:, col] = sigma_edit_series(sigma_thresh, ser, max_iter=max_iter) return df
bsd-2-clause
besser82/shogun
applications/easysvm/esvm/plots.py
7
6555
""" This module contains code for commonly used plots """ # This software is distributed under BSD 3-clause license (see LICENSE file). # # Authors: Soeren Sonnenburg import sys import random import numpy import warnings import shutil from shogun import Labels from shogun import * def plotroc(output, LTE, draw_random=False, figure_fname="", roc_label='ROC'): """Plot the receiver operating characteristic curve""" import pylab import matplotlib pylab.figure(1,dpi=150,figsize=(4,4)) fontdict=dict(family="cursive",weight="bold",size=7,y=1.05) ; pm=PerformanceMeasures(Labels(numpy.array(LTE)), Labels(numpy.array(output))) points=pm.get_ROC() points=numpy.array(points).T # for pylab.plot pylab.plot(points[0], points[1], 'b-', label=roc_label) if draw_random: pylab.plot([0, 1], [0, 1], 'r-', label='random guessing') pylab.axis([0, 1, 0, 1]) ticks=numpy.arange(0., 1., .1, dtype=numpy.float64) pylab.xticks(ticks,size=10) pylab.yticks(ticks,size=10) pylab.xlabel('1 - specificity (false positive rate)',size=10) pylab.ylabel('sensitivity (true positive rate)',size=10) pylab.legend(loc='lower right', prop = matplotlib.font_manager.FontProperties('tiny')) if figure_fname!=None: warnings.filterwarnings('ignore','Could not match*') tempfname = figure_fname + '.png' pylab.savefig(tempfname) shutil.move(tempfname,figure_fname) auROC=pm.get_auROC() return auROC ; def plotprc(output, LTE, figure_fname="", prc_label='PRC'): """Plot the precision recall curve""" import pylab import matplotlib pylab.figure(2,dpi=150,figsize=(4,4)) pm=PerformanceMeasures(Labels(numpy.array(LTE)), Labels(numpy.array(output))) points=pm.get_PRC() points=numpy.array(points).T # for pylab.plot pylab.plot(points[0], points[1], 'b-', label=prc_label) pylab.axis([0, 1, 0, 1]) ticks=numpy.arange(0., 1., .1, dtype=numpy.float64) pylab.xticks(ticks,size=10) pylab.yticks(ticks,size=10) pylab.xlabel('sensitivity (true positive rate)',size=10) pylab.ylabel('precision (1 - false discovery rate)',size=10) pylab.legend(loc='lower right') if figure_fname!=None: warnings.filterwarnings('ignore','Could not match*') tempfname = figure_fname + '.png' pylab.savefig(tempfname) shutil.move(tempfname,figure_fname) auPRC=pm.get_auPRC() return auPRC ; def plotcloud(cloud, figure_fname="", label='cloud'): """Plot the cloud of points (the first two dimensions only)""" import pylab import matplotlib pylab.figure(1,dpi=150,figsize=(4,4)) pos = [] neg = [] for i in xrange(len(cloud)): if cloud[i][0]==1: pos.append(cloud[i][1:]) elif cloud[i][0]==-1: neg.append(cloud[i][1:]) fontdict=dict(family="cursive",weight="bold",size=10,y=1.05) ; pylab.title(label, fontdict) points=numpy.array(pos).T # for pylab.plot pylab.plot(points[0], points[1], 'b+', label='positive') points=numpy.array(neg).T # for pylab.plot pylab.plot(points[0], points[1], 'rx', label='negative') #pylab.axis([0, 1, 0, 1]) #ticks=numpy.arange(0., 1., .1, dtype=numpy.float64) #pylab.xticks(ticks,size=10) #pylab.yticks(ticks,size=10) pylab.xlabel('dimension 1',size=10) pylab.ylabel('dimension 2',size=10) pylab.legend(loc='lower right') if figure_fname!=None: warnings.filterwarnings('ignore','Could not match*') tempfname = figure_fname + '.png' pylab.savefig(tempfname) shutil.move(tempfname,figure_fname) def plot_poims(poimfilename, poim, max_poim, diff_poim, poim_totalmass, poimdegree, max_len): """Plot a summary of the information in poims""" import pylab import matplotlib pylab.figure(3, dpi=150, figsize=(4,5)) # summary figures fontdict=dict(family="cursive",weight="bold",size=7,y=1.05) ; pylab.subplot(3,2,1) pylab.title('Total POIM Mass', fontdict) pylab.plot(poim_totalmass) ; pylab.ylabel('weight mass', size=5) pylab.subplot(3,2,3) pylab.title('POIMs', fontdict) pylab.pcolor(max_poim, shading='flat') ; pylab.subplot(3,2,5) pylab.title('Differential POIMs', fontdict) pylab.pcolor(diff_poim, shading='flat') ; for plot in [3, 5]: pylab.subplot(3,2,plot) ticks=numpy.arange(1., poimdegree+1, 1, dtype=numpy.float64) ticks_str = [] for i in xrange(0, poimdegree): ticks_str.append("%i" % (i+1)) ticks[i] = i + 0.5 pylab.yticks(ticks, ticks_str) pylab.ylabel('degree', size=5) # per k-mer figures fontdict=dict(family="cursive",weight="bold",size=7,y=1.04) ; # 1-mers pylab.subplot(3,2,2) pylab.title('1-mer Positional Importance', fontdict) pylab.pcolor(poim[0], shading='flat') ; ticks_str = ['A', 'C', 'G', 'T'] ticks = [0.5, 1.5, 2.5, 3.5] pylab.yticks(ticks, ticks_str, size=5) pylab.axis([0, max_len, 0, 4]) # 2-mers pylab.subplot(3,2,4) pylab.title('2-mer Positional Importance', fontdict) pylab.pcolor(poim[1], shading='flat') ; i=0 ; ticks=[] ; ticks_str=[] ; for l1 in ['A', 'C', 'G', 'T']: for l2 in ['A', 'C', 'G', 'T']: ticks_str.append(l1+l2) ticks.append(0.5+i) ; i+=1 ; pylab.yticks(ticks, ticks_str, fontsize=5) pylab.axis([0, max_len, 0, 16]) # 3-mers pylab.subplot(3,2,6) pylab.title('3-mer Positional Importance', fontdict) pylab.pcolor(poim[2], shading='flat') ; i=0 ; ticks=[] ; ticks_str=[] ; for l1 in ['A', 'C', 'G', 'T']: for l2 in ['A', 'C', 'G', 'T']: for l3 in ['A', 'C', 'G', 'T']: if numpy.mod(i,4)==0: ticks_str.append(l1+l2+l3) ticks.append(0.5+i) ; i+=1 ; pylab.yticks(ticks, ticks_str, fontsize=5) pylab.axis([0, max_len, 0, 64]) # x-axis on last two figures for plot in [5, 6]: pylab.subplot(3,2,plot) pylab.xlabel('sequence position', size=5) # finishing up for plot in xrange(0,6): pylab.subplot(3,2,plot+1) pylab.xticks(fontsize=5) for plot in [1,3,5]: pylab.subplot(3,2,plot) pylab.yticks(fontsize=5) pylab.subplots_adjust(hspace=0.35) ; # write to file warnings.filterwarnings('ignore','Could not match*') pylab.savefig('/tmp/temppylabfig.png') shutil.move('/tmp/temppylabfig.png',poimfilename)
bsd-3-clause
liangz0707/scikit-learn
sklearn/semi_supervised/tests/test_label_propagation.py
307
1974
""" test the label propagation module """ import nose import numpy as np from sklearn.semi_supervised import label_propagation from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_equal ESTIMATORS = [ (label_propagation.LabelPropagation, {'kernel': 'rbf'}), (label_propagation.LabelPropagation, {'kernel': 'knn', 'n_neighbors': 2}), (label_propagation.LabelSpreading, {'kernel': 'rbf'}), (label_propagation.LabelSpreading, {'kernel': 'knn', 'n_neighbors': 2}) ] def test_fit_transduction(): samples = [[1., 0.], [0., 2.], [1., 3.]] labels = [0, 1, -1] for estimator, parameters in ESTIMATORS: clf = estimator(**parameters).fit(samples, labels) nose.tools.assert_equal(clf.transduction_[2], 1) def test_distribution(): samples = [[1., 0.], [0., 1.], [1., 1.]] labels = [0, 1, -1] for estimator, parameters in ESTIMATORS: clf = estimator(**parameters).fit(samples, labels) if parameters['kernel'] == 'knn': continue # unstable test; changes in k-NN ordering break it assert_array_almost_equal(clf.predict_proba([[1., 0.0]]), np.array([[1., 0.]]), 2) else: assert_array_almost_equal(np.asarray(clf.label_distributions_[2]), np.array([.5, .5]), 2) def test_predict(): samples = [[1., 0.], [0., 2.], [1., 3.]] labels = [0, 1, -1] for estimator, parameters in ESTIMATORS: clf = estimator(**parameters).fit(samples, labels) assert_array_equal(clf.predict([[0.5, 2.5]]), np.array([1])) def test_predict_proba(): samples = [[1., 0.], [0., 1.], [1., 2.5]] labels = [0, 1, -1] for estimator, parameters in ESTIMATORS: clf = estimator(**parameters).fit(samples, labels) assert_array_almost_equal(clf.predict_proba([[1., 1.]]), np.array([[0.5, 0.5]]))
bsd-3-clause
eerimoq/cantools
tests/test_plot_without_mock.py
1
2943
#!/usr/bin/env python3 import os import sys import unittest from unittest import mock from io import StringIO import cantools import matplotlib.pyplot as plt class CanToolsPlotTest(unittest.TestCase): DBC_FILE = os.path.join(os.path.split(__file__)[0], 'files/dbc/abs.dbc') FN_OUT = "out.pdf" def test_plot_tz(self): self.assertFalse(os.path.exists(self.FN_OUT)) argv = ['cantools', 'plot', '-o', self.FN_OUT, self.DBC_FILE] input_data = """\ (000.000000) vcan0 00000343 [8] C5 04 B7 04 9B 04 C5 04 (001.001787) vcan0 00000343 [8] 69 04 69 04 77 04 7E 04 (002.003592) vcan0 00000343 [8] 29 04 30 04 29 04 22 04 (003.005400) vcan0 00000343 [8] FC 03 20 04 20 04 FC 03 (004.006942) vcan0 00000343 [8] DE 03 D0 03 D0 03 C9 03 (005.008400) vcan0 00000343 [8] 7E 03 85 03 8C 03 77 03 (006.009926) vcan0 00000343 [8] 65 03 3B 03 50 03 65 03 (007.011457) vcan0 00000343 [8] 17 03 3B 03 34 03 10 03 (008.013215) vcan0 00000343 [8] 00 03 F2 02 15 03 F9 02 (009.014779) vcan0 00000343 [8] CB 02 BC 02 B5 02 D2 02 """ with mock.patch('sys.stdin', StringIO(input_data)): with mock.patch('sys.argv', argv): cantools._main() self.assertTrue(os.path.exists(self.FN_OUT)) os.remove(self.FN_OUT) def test_plot_style(self): self.assertFalse(os.path.exists(self.FN_OUT)) argv = ['cantools', 'plot', '--style', 'seaborn', '-o', self.FN_OUT, self.DBC_FILE] input_data = """\ (000.000000) vcan0 00000343 [8] C5 04 B7 04 9B 04 C5 04 (001.001787) vcan0 00000343 [8] 69 04 69 04 77 04 7E 04 (002.003592) vcan0 00000343 [8] 29 04 30 04 29 04 22 04 (003.005400) vcan0 00000343 [8] FC 03 20 04 20 04 FC 03 (004.006942) vcan0 00000343 [8] DE 03 D0 03 D0 03 C9 03 (005.008400) vcan0 00000343 [8] 7E 03 85 03 8C 03 77 03 (006.009926) vcan0 00000343 [8] 65 03 3B 03 50 03 65 03 (007.011457) vcan0 00000343 [8] 17 03 3B 03 34 03 10 03 (008.013215) vcan0 00000343 [8] 00 03 F2 02 15 03 F9 02 (009.014779) vcan0 00000343 [8] CB 02 BC 02 B5 02 D2 02 """ with mock.patch('sys.stdin', StringIO(input_data)): with mock.patch('sys.argv', argv): cantools._main() self.assertTrue(os.path.exists(self.FN_OUT)) os.remove(self.FN_OUT) def test_plot_list_styles(self): self.assertFalse(os.path.exists(self.FN_OUT)) argv = ['cantools', 'plot', '--list-styles', ''] stdout = StringIO() expected = "available matplotlib styles:" expected += "".join("\n- %s" % s for s in plt.style.available) expected += "\n" with mock.patch('sys.stdout', stdout): with mock.patch('sys.argv', argv): cantools._main() self.assertEqual(stdout.getvalue(), expected) if __name__ == '__main__': unittest.main()
mit
NSLS-II-CHX/ipython_ophyd
profile_collection/ipython_qtconsole_config.py
13
24674
# Configuration file for ipython-qtconsole. c = get_config() #------------------------------------------------------------------------------ # IPythonQtConsoleApp configuration #------------------------------------------------------------------------------ # IPythonQtConsoleApp will inherit config from: BaseIPythonApplication, # Application, IPythonConsoleApp, ConnectionFileMixin # Set the kernel's IP address [default localhost]. If the IP address is # something other than localhost, then Consoles on other machines will be able # to connect to the Kernel, so be careful! # c.IPythonQtConsoleApp.ip = u'' # Create a massive crash report when IPython encounters what may be an internal # error. The default is to append a short message to the usual traceback # c.IPythonQtConsoleApp.verbose_crash = False # Start the console window maximized. # c.IPythonQtConsoleApp.maximize = False # The date format used by logging formatters for %(asctime)s # c.IPythonQtConsoleApp.log_datefmt = '%Y-%m-%d %H:%M:%S' # set the shell (ROUTER) port [default: random] # c.IPythonQtConsoleApp.shell_port = 0 # The SSH server to use to connect to the kernel. # c.IPythonQtConsoleApp.sshserver = '' # set the stdin (DEALER) port [default: random] # c.IPythonQtConsoleApp.stdin_port = 0 # Set the log level by value or name. # c.IPythonQtConsoleApp.log_level = 30 # Path to the ssh key to use for logging in to the ssh server. # c.IPythonQtConsoleApp.sshkey = '' # Path to an extra config file to load. # # If specified, load this config file in addition to any other IPython config. # c.IPythonQtConsoleApp.extra_config_file = u'' # Whether to create profile dir if it doesn't exist # c.IPythonQtConsoleApp.auto_create = False # path to a custom CSS stylesheet # c.IPythonQtConsoleApp.stylesheet = '' # set the heartbeat port [default: random] # c.IPythonQtConsoleApp.hb_port = 0 # Whether to overwrite existing config files when copying # c.IPythonQtConsoleApp.overwrite = False # set the iopub (PUB) port [default: random] # c.IPythonQtConsoleApp.iopub_port = 0 # The IPython profile to use. # c.IPythonQtConsoleApp.profile = u'default' # JSON file in which to store connection info [default: kernel-<pid>.json] # # This file will contain the IP, ports, and authentication key needed to connect # clients to this kernel. By default, this file will be created in the security- # dir of the current profile, but can be specified by absolute path. # c.IPythonQtConsoleApp.connection_file = '' # Set to display confirmation dialog on exit. You can always use 'exit' or # 'quit', to force a direct exit without any confirmation. # c.IPythonQtConsoleApp.confirm_exit = True # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This options can also be specified through the environment # variable IPYTHONDIR. # c.IPythonQtConsoleApp.ipython_dir = u'' # Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.IPythonQtConsoleApp.copy_config_files = False # Connect to an already running kernel # c.IPythonQtConsoleApp.existing = '' # Use a plaintext widget instead of rich text (plain can't print/save). # c.IPythonQtConsoleApp.plain = False # Start the console window with the menu bar hidden. # c.IPythonQtConsoleApp.hide_menubar = False # The Logging format template # c.IPythonQtConsoleApp.log_format = '[%(name)s]%(highlevel)s %(message)s' # # c.IPythonQtConsoleApp.transport = 'tcp' #------------------------------------------------------------------------------ # IPythonWidget configuration #------------------------------------------------------------------------------ # A FrontendWidget for an IPython kernel. # IPythonWidget will inherit config from: FrontendWidget, HistoryConsoleWidget, # ConsoleWidget # The type of completer to use. Valid values are: # # 'plain' : Show the available completion as a text list # Below the editing area. # 'droplist': Show the completion in a drop down list navigable # by the arrow keys, and from which you can select # completion by pressing Return. # 'ncurses' : Show the completion as a text list which is navigable by # `tab` and arrow keys. # c.IPythonWidget.gui_completion = 'ncurses' # Whether to process ANSI escape codes. # c.IPythonWidget.ansi_codes = True # A CSS stylesheet. The stylesheet can contain classes for: # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc # 2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) # 3. IPython: .error, .in-prompt, .out-prompt, etc # c.IPythonWidget.style_sheet = u'' # The height of the console at start time in number of characters (will double # with `vsplit` paging) # c.IPythonWidget.height = 25 # # c.IPythonWidget.out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' # # c.IPythonWidget.input_sep = '\n' # Whether to draw information calltips on open-parentheses. # c.IPythonWidget.enable_calltips = True # # c.IPythonWidget.in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' # The width of the console at start time in number of characters (will double # with `hsplit` paging) # c.IPythonWidget.width = 81 # A command for invoking a system text editor. If the string contains a # {filename} format specifier, it will be used. Otherwise, the filename will be # appended to the end the command. # c.IPythonWidget.editor = '' # If not empty, use this Pygments style for syntax highlighting. Otherwise, the # style sheet is queried for Pygments style information. # c.IPythonWidget.syntax_style = u'' # The font family to use for the console. On OSX this defaults to Monaco, on # Windows the default is Consolas with fallback of Courier, and on other # platforms the default is Monospace. # c.IPythonWidget.font_family = u'' # The pygments lexer class to use. # c.IPythonWidget.lexer_class = <IPython.utils.traitlets.Undefined object at 0x1866810> # # c.IPythonWidget.output_sep2 = '' # Whether to automatically execute on syntactically complete input. # # If False, Shift-Enter is required to submit each execution. Disabling this is # mainly useful for non-Python kernels, where the completion check would be # wrong. # c.IPythonWidget.execute_on_complete_input = True # The maximum number of lines of text before truncation. Specifying a non- # positive number disables text truncation (not recommended). # c.IPythonWidget.buffer_size = 500 # # c.IPythonWidget.history_lock = False # # c.IPythonWidget.banner = u'' # The type of underlying text widget to use. Valid values are 'plain', which # specifies a QPlainTextEdit, and 'rich', which specifies a QTextEdit. # c.IPythonWidget.kind = 'plain' # Whether to ask for user confirmation when restarting kernel # c.IPythonWidget.confirm_restart = True # The font size. If unconfigured, Qt will be entrusted with the size of the # font. # c.IPythonWidget.font_size = 0 # The editor command to use when a specific line number is requested. The string # should contain two format specifiers: {line} and {filename}. If this parameter # is not specified, the line number option to the %edit magic will be ignored. # c.IPythonWidget.editor_line = u'' # Whether to clear the console when the kernel is restarted # c.IPythonWidget.clear_on_kernel_restart = True # The type of paging to use. Valid values are: # # 'inside' # The widget pages like a traditional terminal. # 'hsplit' # When paging is requested, the widget is split horizontally. The top # pane contains the console, and the bottom pane contains the paged text. # 'vsplit' # Similar to 'hsplit', except that a vertical splitter is used. # 'custom' # No action is taken by the widget beyond emitting a # 'custom_page_requested(str)' signal. # 'none' # The text is written directly to the console. # c.IPythonWidget.paging = 'inside' # # c.IPythonWidget.output_sep = '' #------------------------------------------------------------------------------ # IPKernelApp configuration #------------------------------------------------------------------------------ # IPython: an enhanced interactive Python shell. # IPKernelApp will inherit config from: BaseIPythonApplication, Application, # InteractiveShellApp # Run the file referenced by the PYTHONSTARTUP environment variable at IPython # startup. # c.IPKernelApp.exec_PYTHONSTARTUP = True # The importstring for the DisplayHook factory # c.IPKernelApp.displayhook_class = 'IPython.kernel.zmq.displayhook.ZMQDisplayHook' # Set the IP or interface on which the kernel will listen. # c.IPKernelApp.ip = u'' # Pre-load matplotlib and numpy for interactive use, selecting a particular # matplotlib backend and loop integration. # c.IPKernelApp.pylab = None # Create a massive crash report when IPython encounters what may be an internal # error. The default is to append a short message to the usual traceback # c.IPKernelApp.verbose_crash = False # The Kernel subclass to be used. # # This should allow easy re-use of the IPKernelApp entry point to configure and # launch kernels other than IPython's own. # c.IPKernelApp.kernel_class = 'IPython.kernel.zmq.ipkernel.Kernel' # Run the module as a script. # c.IPKernelApp.module_to_run = '' # The date format used by logging formatters for %(asctime)s # c.IPKernelApp.log_datefmt = '%Y-%m-%d %H:%M:%S' # set the shell (ROUTER) port [default: random] # c.IPKernelApp.shell_port = 0 # set the control (ROUTER) port [default: random] # c.IPKernelApp.control_port = 0 # Whether to overwrite existing config files when copying # c.IPKernelApp.overwrite = False # Execute the given command string. # c.IPKernelApp.code_to_run = '' # set the stdin (ROUTER) port [default: random] # c.IPKernelApp.stdin_port = 0 # Set the log level by value or name. # c.IPKernelApp.log_level = 30 # lines of code to run at IPython startup. # c.IPKernelApp.exec_lines = [] # Path to an extra config file to load. # # If specified, load this config file in addition to any other IPython config. # c.IPKernelApp.extra_config_file = u'' # The importstring for the OutStream factory # c.IPKernelApp.outstream_class = 'IPython.kernel.zmq.iostream.OutStream' # Whether to create profile dir if it doesn't exist # c.IPKernelApp.auto_create = False # set the heartbeat port [default: random] # c.IPKernelApp.hb_port = 0 # # c.IPKernelApp.transport = 'tcp' # redirect stdout to the null device # c.IPKernelApp.no_stdout = False # Should variables loaded at startup (by startup files, exec_lines, etc.) be # hidden from tools like %who? # c.IPKernelApp.hide_initial_ns = True # dotted module name of an IPython extension to load. # c.IPKernelApp.extra_extension = '' # A file to be run # c.IPKernelApp.file_to_run = '' # The IPython profile to use. # c.IPKernelApp.profile = u'default' # # c.IPKernelApp.parent_appname = u'' # kill this process if its parent dies. On Windows, the argument specifies the # HANDLE of the parent process, otherwise it is simply boolean. # c.IPKernelApp.parent_handle = 0 # JSON file in which to store connection info [default: kernel-<pid>.json] # # This file will contain the IP, ports, and authentication key needed to connect # clients to this kernel. By default, this file will be created in the security # dir of the current profile, but can be specified by absolute path. # c.IPKernelApp.connection_file = '' # If true, IPython will populate the user namespace with numpy, pylab, etc. and # an ``import *`` is done from numpy and pylab, when using pylab mode. # # When False, pylab mode should not import any names into the user namespace. # c.IPKernelApp.pylab_import_all = True # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This options can also be specified through the environment # variable IPYTHONDIR. # c.IPKernelApp.ipython_dir = u'' # Configure matplotlib for interactive use with the default matplotlib backend. # c.IPKernelApp.matplotlib = None # ONLY USED ON WINDOWS Interrupt this process when the parent is signaled. # c.IPKernelApp.interrupt = 0 # Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.IPKernelApp.copy_config_files = False # List of files to run at IPython startup. # c.IPKernelApp.exec_files = [] # Enable GUI event loop integration with any of ('glut', 'gtk', 'gtk3', 'none', # 'osx', 'pyglet', 'qt', 'qt4', 'tk', 'wx'). # c.IPKernelApp.gui = None # A list of dotted module names of IPython extensions to load. # c.IPKernelApp.extensions = [] # redirect stderr to the null device # c.IPKernelApp.no_stderr = False # The Logging format template # c.IPKernelApp.log_format = '[%(name)s]%(highlevel)s %(message)s' # set the iopub (PUB) port [default: random] # c.IPKernelApp.iopub_port = 0 #------------------------------------------------------------------------------ # ZMQInteractiveShell configuration #------------------------------------------------------------------------------ # A subclass of InteractiveShell for ZMQ. # ZMQInteractiveShell will inherit config from: InteractiveShell # Use colors for displaying information about objects. Because this information # is passed through a pager (like 'less'), and some pagers get confused with # color codes, this capability can be turned off. # c.ZMQInteractiveShell.color_info = True # A list of ast.NodeTransformer subclass instances, which will be applied to # user input before code is run. # c.ZMQInteractiveShell.ast_transformers = [] # # c.ZMQInteractiveShell.history_length = 10000 # Don't call post-execute functions that have failed in the past. # c.ZMQInteractiveShell.disable_failing_post_execute = False # Show rewritten input, e.g. for autocall. # c.ZMQInteractiveShell.show_rewritten_input = True # Set the color scheme (NoColor, Linux, or LightBG). # c.ZMQInteractiveShell.colors = 'Linux' # # c.ZMQInteractiveShell.separate_in = '\n' # Deprecated, use PromptManager.in2_template # c.ZMQInteractiveShell.prompt_in2 = ' .\\D.: ' # # c.ZMQInteractiveShell.separate_out = '' # Deprecated, use PromptManager.in_template # c.ZMQInteractiveShell.prompt_in1 = 'In [\\#]: ' # Enable deep (recursive) reloading by default. IPython can use the deep_reload # module which reloads changes in modules recursively (it replaces the reload() # function, so you don't need to change anything to use it). deep_reload() # forces a full reload of modules whose code may have changed, which the default # reload() function does not. When deep_reload is off, IPython will use the # normal reload(), but deep_reload will still be available as dreload(). # c.ZMQInteractiveShell.deep_reload = False # Make IPython automatically call any callable object even if you didn't type # explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically. # The value can be '0' to disable the feature, '1' for 'smart' autocall, where # it is not applied if there are no more arguments on the line, and '2' for # 'full' autocall, where all callable objects are automatically called (even if # no arguments are present). # c.ZMQInteractiveShell.autocall = 0 # # c.ZMQInteractiveShell.separate_out2 = '' # Deprecated, use PromptManager.justify # c.ZMQInteractiveShell.prompts_pad_left = True # # c.ZMQInteractiveShell.readline_parse_and_bind = ['tab: complete', '"\\C-l": clear-screen', 'set show-all-if-ambiguous on', '"\\C-o": tab-insert', '"\\C-r": reverse-search-history', '"\\C-s": forward-search-history', '"\\C-p": history-search-backward', '"\\C-n": history-search-forward', '"\\e[A": history-search-backward', '"\\e[B": history-search-forward', '"\\C-k": kill-line', '"\\C-u": unix-line-discard'] # Enable magic commands to be called without the leading %. # c.ZMQInteractiveShell.automagic = True # # c.ZMQInteractiveShell.debug = False # # c.ZMQInteractiveShell.object_info_string_level = 0 # # c.ZMQInteractiveShell.ipython_dir = '' # # c.ZMQInteractiveShell.readline_remove_delims = '-/~' # Start logging to the default log file. # c.ZMQInteractiveShell.logstart = False # The name of the logfile to use. # c.ZMQInteractiveShell.logfile = '' # # c.ZMQInteractiveShell.wildcards_case_sensitive = True # Save multi-line entries as one entry in readline history # c.ZMQInteractiveShell.multiline_history = True # Start logging to the given file in append mode. # c.ZMQInteractiveShell.logappend = '' # # c.ZMQInteractiveShell.xmode = 'Context' # # c.ZMQInteractiveShell.quiet = False # Deprecated, use PromptManager.out_template # c.ZMQInteractiveShell.prompt_out = 'Out[\\#]: ' # Set the size of the output cache. The default is 1000, you can change it # permanently in your config file. Setting it to 0 completely disables the # caching system, and the minimum value accepted is 20 (if you provide a value # less than 20, it is reset to 0 and a warning is issued). This limit is # defined because otherwise you'll spend more time re-flushing a too small cache # than working # c.ZMQInteractiveShell.cache_size = 1000 # 'all', 'last', 'last_expr' or 'none', specifying which nodes should be run # interactively (displaying output from expressions). # c.ZMQInteractiveShell.ast_node_interactivity = 'last_expr' # Automatically call the pdb debugger after every exception. # c.ZMQInteractiveShell.pdb = False #------------------------------------------------------------------------------ # KernelManager configuration #------------------------------------------------------------------------------ # Manages a single kernel in a subprocess on this host. # # This version starts kernels with Popen. # KernelManager will inherit config from: ConnectionFileMixin # The Popen Command to launch the kernel. Override this if you have a custom # kernel. If kernel_cmd is specified in a configuration file, IPython does not # pass any arguments to the kernel, because it cannot make any assumptions about # the arguments that the kernel understands. In particular, this means that the # kernel does not receive the option --debug if it given on the IPython command # line. # c.KernelManager.kernel_cmd = [] # Set the kernel's IP address [default localhost]. If the IP address is # something other than localhost, then Consoles on other machines will be able # to connect to the Kernel, so be careful! # c.KernelManager.ip = u'' # # c.KernelManager.transport = 'tcp' # Should we autorestart the kernel if it dies. # c.KernelManager.autorestart = False #------------------------------------------------------------------------------ # ProfileDir configuration #------------------------------------------------------------------------------ # An object to manage the profile directory and its resources. # # The profile directory is used by all IPython applications, to manage # configuration, logging and security. # # This object knows how to find, create and manage these directories. This # should be used by any code that wants to handle profiles. # Set the profile location directly. This overrides the logic used by the # `profile` option. # c.ProfileDir.location = u'' #------------------------------------------------------------------------------ # Session configuration #------------------------------------------------------------------------------ # Object for handling serialization and sending of messages. # # The Session object handles building messages and sending them with ZMQ sockets # or ZMQStream objects. Objects can communicate with each other over the # network via Session objects, and only need to work with the dict-based IPython # message spec. The Session will handle serialization/deserialization, security, # and metadata. # # Sessions support configurable serialization via packer/unpacker traits, and # signing with HMAC digests via the key/keyfile traits. # # Parameters ---------- # # debug : bool # whether to trigger extra debugging statements # packer/unpacker : str : 'json', 'pickle' or import_string # importstrings for methods to serialize message parts. If just # 'json' or 'pickle', predefined JSON and pickle packers will be used. # Otherwise, the entire importstring must be used. # # The functions must accept at least valid JSON input, and output *bytes*. # # For example, to use msgpack: # packer = 'msgpack.packb', unpacker='msgpack.unpackb' # pack/unpack : callables # You can also set the pack/unpack callables for serialization directly. # session : bytes # the ID of this Session object. The default is to generate a new UUID. # username : unicode # username added to message headers. The default is to ask the OS. # key : bytes # The key used to initialize an HMAC signature. If unset, messages # will not be signed or checked. # keyfile : filepath # The file containing a key. If this is set, `key` will be initialized # to the contents of the file. # Username for the Session. Default is your system username. # c.Session.username = u'swilkins' # The name of the unpacker for unserializing messages. Only used with custom # functions for `packer`. # c.Session.unpacker = 'json' # Threshold (in bytes) beyond which a buffer should be sent without copying. # c.Session.copy_threshold = 65536 # The name of the packer for serializing messages. Should be one of 'json', # 'pickle', or an import name for a custom callable serializer. # c.Session.packer = 'json' # The maximum number of digests to remember. # # The digest history will be culled when it exceeds this value. # c.Session.digest_history_size = 65536 # The UUID identifying this session. # c.Session.session = u'' # The digest scheme used to construct the message signatures. Must have the form # 'hmac-HASH'. # c.Session.signature_scheme = 'hmac-sha256' # execution key, for extra authentication. # c.Session.key = '' # Debug output in the Session # c.Session.debug = False # The maximum number of items for a container to be introspected for custom # serialization. Containers larger than this are pickled outright. # c.Session.item_threshold = 64 # path to file containing execution key. # c.Session.keyfile = '' # Threshold (in bytes) beyond which an object's buffer should be extracted to # avoid pickling. # c.Session.buffer_threshold = 1024 # Metadata dictionary, which serves as the default top-level metadata dict for # each message. # c.Session.metadata = {} #------------------------------------------------------------------------------ # InlineBackend configuration #------------------------------------------------------------------------------ # An object to store configuration of the inline backend. # The figure format to enable (deprecated use `figure_formats` instead) # c.InlineBackend.figure_format = u'' # A set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. # c.InlineBackend.figure_formats = set(['png']) # Extra kwargs to be passed to fig.canvas.print_figure. # # Logical examples include: bbox_inches, quality (for jpeg figures), etc. # c.InlineBackend.print_figure_kwargs = {'bbox_inches': 'tight'} # Close all figures at the end of each cell. # # When True, ensures that each cell starts with no active figures, but it also # means that one must keep track of references in order to edit or redraw # figures in subsequent cells. This mode is ideal for the notebook, where # residual plots from other cells might be surprising. # # When False, one must call figure() to create new figures. This means that # gcf() and getfigs() can reference figures created in other cells, and the # active figure can continue to be edited with pylab/pyplot methods that # reference the current active figure. This mode facilitates iterative editing # of figures, and behaves most consistently with other matplotlib backends, but # figure barriers between cells must be explicit. # c.InlineBackend.close_figures = True # Subset of matplotlib rcParams that should be different for the inline backend. # c.InlineBackend.rc = {'font.size': 10, 'figure.figsize': (6.0, 4.0), 'figure.facecolor': (1, 1, 1, 0), 'savefig.dpi': 72, 'figure.subplot.bottom': 0.125, 'figure.edgecolor': (1, 1, 1, 0)}
bsd-2-clause
komsas/OpenUpgrade
addons/resource/faces/timescale.py
170
3902
############################################################################ # Copyright (C) 2005 by Reithinger GmbH # mreithinger@web.de # # This file is part of faces. # # faces is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # faces is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ############################################################################ import faces.pcalendar as pcal import matplotlib.cbook as cbook import datetime import sys class TimeScale(object): def __init__(self, calendar): self.data_calendar = calendar self._create_chart_calendar() self.now = self.to_num(self.data_calendar.now) def to_datetime(self, xval): return xval.to_datetime() def to_num(self, date): return self.chart_calendar.WorkingDate(date) def is_free_slot(self, value): dt1 = self.chart_calendar.to_starttime(value) dt2 = self.data_calendar.to_starttime\ (self.data_calendar.from_datetime(dt1)) return dt1 != dt2 def is_free_day(self, value): dt1 = self.chart_calendar.to_starttime(value) dt2 = self.data_calendar.to_starttime\ (self.data_calendar.from_datetime(dt1)) return dt1.date() != dt2.date() def _create_chart_calendar(self): dcal = self.data_calendar ccal = self.chart_calendar = pcal.Calendar() ccal.minimum_time_unit = 1 #pad worktime slots of calendar (all days should be equally long) slot_sum = lambda slots: sum(map(lambda slot: slot[1] - slot[0], slots)) day_sum = lambda day: slot_sum(dcal.get_working_times(day)) max_work_time = max(map(day_sum, range(7))) #working_time should have 2/3 sum_time = 3 * max_work_time / 2 #now create timeslots for ccal def create_time_slots(day): src_slots = dcal.get_working_times(day) slots = [0, src_slots, 24*60] slots = tuple(cbook.flatten(slots)) slots = zip(slots[:-1], slots[1:]) #balance non working slots work_time = slot_sum(src_slots) non_work_time = sum_time - work_time non_slots = filter(lambda s: s not in src_slots, slots) non_slots = map(lambda s: (s[1] - s[0], s), non_slots) non_slots.sort() slots = [] i = 0 for l, s in non_slots: delta = non_work_time / (len(non_slots) - i) delta = min(l, delta) non_work_time -= delta slots.append((s[0], s[0] + delta)) i += 1 slots.extend(src_slots) slots.sort() return slots min_delta = sys.maxint for i in range(7): slots = create_time_slots(i) ccal.working_times[i] = slots min_delta = min(min_delta, min(map(lambda s: s[1] - s[0], slots))) ccal._recalc_working_time() self.slot_delta = min_delta self.day_delta = sum_time self.week_delta = ccal.week_time _default_scale = TimeScale(pcal._default_calendar) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
dongjoon-hyun/spark
python/pyspark/pandas/generic.py
9
104900
# # 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. # """ A base class of DataFrame/Column to behave similar to pandas DataFrame/Series. """ from abc import ABCMeta, abstractmethod from collections import Counter from distutils.version import LooseVersion from functools import reduce from typing import ( Any, Callable, Iterable, IO, List, Optional, NoReturn, Tuple, Union, TYPE_CHECKING, cast, ) import warnings import numpy as np # noqa: F401 import pandas as pd from pandas.api.types import is_list_like from pyspark.sql import Column, functions as F from pyspark.sql.types import ( BooleanType, DataType, DoubleType, FloatType, IntegralType, LongType, NumericType, ) from pyspark import pandas as ps # For running doctests and reference resolution in PyCharm. from pyspark.pandas._typing import ( Axis, DataFrameOrSeries, Dtype, FrameLike, Label, Name, Scalar, ) from pyspark.pandas.indexing import AtIndexer, iAtIndexer, iLocIndexer, LocIndexer from pyspark.pandas.internal import InternalFrame from pyspark.pandas.spark import functions as SF from pyspark.pandas.typedef import spark_type_to_pandas_dtype from pyspark.pandas.utils import ( is_name_like_tuple, is_name_like_value, name_like_string, scol_for, sql_conf, validate_arguments_and_invoke_function, validate_axis, SPARK_CONF_ARROW_ENABLED, ) if TYPE_CHECKING: from pyspark.pandas.frame import DataFrame # noqa: F401 (SPARK-34943) from pyspark.pandas.indexes.base import Index # noqa: F401 (SPARK-34943) from pyspark.pandas.groupby import GroupBy # noqa: F401 (SPARK-34943) from pyspark.pandas.series import Series # noqa: F401 (SPARK-34943) from pyspark.pandas.window import Rolling, Expanding # noqa: F401 (SPARK-34943) bool_type = bool class Frame(object, metaclass=ABCMeta): """ The base class for both DataFrame and Series. """ @abstractmethod def __getitem__(self, key: Any) -> Any: pass @property @abstractmethod def _internal(self) -> InternalFrame: pass @abstractmethod def _apply_series_op( self: FrameLike, op: Callable[["Series"], Union["Series", Column]], should_resolve: bool = False, ) -> FrameLike: pass @abstractmethod def _reduce_for_stat_function( self, sfun: Union[Callable[[Column], Column], Callable[[Column, DataType], Column]], name: str, axis: Optional[Axis] = None, numeric_only: bool = True, **kwargs: Any ) -> Union["Series", Scalar]: pass @property @abstractmethod def dtypes(self) -> Union[pd.Series, Dtype]: pass @abstractmethod def to_pandas(self) -> Union[pd.DataFrame, pd.Series]: pass @property @abstractmethod def index(self) -> "Index": pass @abstractmethod def copy(self: FrameLike) -> FrameLike: pass @abstractmethod def _to_internal_pandas(self) -> Union[pd.DataFrame, pd.Series]: pass @abstractmethod def head(self: FrameLike, n: int = 5) -> FrameLike: pass # TODO: add 'axis' parameter def cummin(self: FrameLike, skipna: bool = True) -> FrameLike: """ Return cumulative minimum over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative minimum. .. note:: the current implementation of cummin uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single machine and could cause serious performance degradation. Avoid this method against very large dataset. Parameters ---------- skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame or Series See Also -------- DataFrame.min : Return the minimum over DataFrame axis. DataFrame.cummax : Return cumulative maximum over DataFrame axis. DataFrame.cummin : Return cumulative minimum over DataFrame axis. DataFrame.cumsum : Return cumulative sum over DataFrame axis. Series.min : Return the minimum over Series axis. Series.cummax : Return cumulative maximum over Series axis. Series.cummin : Return cumulative minimum over Series axis. Series.cumsum : Return cumulative sum over Series axis. Series.cumprod : Return cumulative product over Series axis. Examples -------- >>> df = ps.DataFrame([[2.0, 1.0], [3.0, None], [1.0, 0.0]], columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the minimum in each column. >>> df.cummin() A B 0 2.0 1.0 1 2.0 NaN 2 1.0 0.0 It works identically in Series. >>> df.A.cummin() 0 2.0 1 2.0 2 1.0 Name: A, dtype: float64 """ return self._apply_series_op(lambda psser: psser._cum(F.min, skipna), should_resolve=True) # TODO: add 'axis' parameter def cummax(self: FrameLike, skipna: bool = True) -> FrameLike: """ Return cumulative maximum over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative maximum. .. note:: the current implementation of cummax uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single machine and could cause serious performance degradation. Avoid this method against very large dataset. Parameters ---------- skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame or Series See Also -------- DataFrame.max : Return the maximum over DataFrame axis. DataFrame.cummax : Return cumulative maximum over DataFrame axis. DataFrame.cummin : Return cumulative minimum over DataFrame axis. DataFrame.cumsum : Return cumulative sum over DataFrame axis. DataFrame.cumprod : Return cumulative product over DataFrame axis. Series.max : Return the maximum over Series axis. Series.cummax : Return cumulative maximum over Series axis. Series.cummin : Return cumulative minimum over Series axis. Series.cumsum : Return cumulative sum over Series axis. Series.cumprod : Return cumulative product over Series axis. Examples -------- >>> df = ps.DataFrame([[2.0, 1.0], [3.0, None], [1.0, 0.0]], columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the maximum in each column. >>> df.cummax() A B 0 2.0 1.0 1 3.0 NaN 2 3.0 1.0 It works identically in Series. >>> df.B.cummax() 0 1.0 1 NaN 2 1.0 Name: B, dtype: float64 """ return self._apply_series_op(lambda psser: psser._cum(F.max, skipna), should_resolve=True) # TODO: add 'axis' parameter def cumsum(self: FrameLike, skipna: bool = True) -> FrameLike: """ Return cumulative sum over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative sum. .. note:: the current implementation of cumsum uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single machine and could cause serious performance degradation. Avoid this method against very large dataset. Parameters ---------- skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame or Series See Also -------- DataFrame.sum : Return the sum over DataFrame axis. DataFrame.cummax : Return cumulative maximum over DataFrame axis. DataFrame.cummin : Return cumulative minimum over DataFrame axis. DataFrame.cumsum : Return cumulative sum over DataFrame axis. DataFrame.cumprod : Return cumulative product over DataFrame axis. Series.sum : Return the sum over Series axis. Series.cummax : Return cumulative maximum over Series axis. Series.cummin : Return cumulative minimum over Series axis. Series.cumsum : Return cumulative sum over Series axis. Series.cumprod : Return cumulative product over Series axis. Examples -------- >>> df = ps.DataFrame([[2.0, 1.0], [3.0, None], [1.0, 0.0]], columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 1.0 0.0 By default, iterates over rows and finds the sum in each column. >>> df.cumsum() A B 0 2.0 1.0 1 5.0 NaN 2 6.0 1.0 It works identically in Series. >>> df.A.cumsum() 0 2.0 1 5.0 2 6.0 Name: A, dtype: float64 """ return self._apply_series_op(lambda psser: psser._cumsum(skipna), should_resolve=True) # TODO: add 'axis' parameter # TODO: use pandas_udf to support negative values and other options later # other window except unbounded ones is supported as of Spark 3.0. def cumprod(self: FrameLike, skipna: bool = True) -> FrameLike: """ Return cumulative product over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative product. .. note:: the current implementation of cumprod uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single machine and could cause serious performance degradation. Avoid this method against very large dataset. .. note:: unlike pandas', pandas-on-Spark's emulates cumulative product by ``exp(sum(log(...)))`` trick. Therefore, it only works for positive numbers. Parameters ---------- skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. Returns ------- DataFrame or Series See Also -------- DataFrame.cummax : Return cumulative maximum over DataFrame axis. DataFrame.cummin : Return cumulative minimum over DataFrame axis. DataFrame.cumsum : Return cumulative sum over DataFrame axis. DataFrame.cumprod : Return cumulative product over DataFrame axis. Series.cummax : Return cumulative maximum over Series axis. Series.cummin : Return cumulative minimum over Series axis. Series.cumsum : Return cumulative sum over Series axis. Series.cumprod : Return cumulative product over Series axis. Raises ------ Exception : If the values is equal to or lower than 0. Examples -------- >>> df = ps.DataFrame([[2.0, 1.0], [3.0, None], [4.0, 10.0]], columns=list('AB')) >>> df A B 0 2.0 1.0 1 3.0 NaN 2 4.0 10.0 By default, iterates over rows and finds the sum in each column. >>> df.cumprod() A B 0 2.0 1.0 1 6.0 NaN 2 24.0 10.0 It works identically in Series. >>> df.A.cumprod() 0 2.0 1 6.0 2 24.0 Name: A, dtype: float64 """ return self._apply_series_op(lambda psser: psser._cumprod(skipna), should_resolve=True) # TODO: Although this has removed pandas >= 1.0.0, but we're keeping this as deprecated # since we're using this for `DataFrame.info` internally. # We can drop it once our minimal pandas version becomes 1.0.0. def get_dtype_counts(self) -> pd.Series: """ Return counts of unique dtypes in this object. .. deprecated:: 0.14.0 Returns ------- dtype : pd.Series Series with the count of columns with each dtype. See Also -------- dtypes : Return the dtypes in this object. Examples -------- >>> a = [['a', 1, 1], ['b', 2, 2], ['c', 3, 3]] >>> df = ps.DataFrame(a, columns=['str', 'int1', 'int2']) >>> df str int1 int2 0 a 1 1 1 b 2 2 2 c 3 3 >>> df.get_dtype_counts().sort_values() object 1 int64 2 dtype: int64 >>> df.str.get_dtype_counts().sort_values() object 1 dtype: int64 """ warnings.warn( "`get_dtype_counts` has been deprecated and will be " "removed in a future version. For DataFrames use " "`.dtypes.value_counts()", FutureWarning, ) if not isinstance(self.dtypes, Iterable): dtypes = [self.dtypes] else: dtypes = list(self.dtypes) return pd.Series(dict(Counter([d.name for d in dtypes]))) def pipe(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: r""" Apply func(self, \*args, \*\*kwargs). Parameters ---------- func : function function to apply to the DataFrame. ``args``, and ``kwargs`` are passed into ``func``. Alternatively a ``(callable, data_keyword)`` tuple where ``data_keyword`` is a string indicating the keyword of ``callable`` that expects the DataFrames. args : iterable, optional positional arguments passed into ``func``. kwargs : mapping, optional a dictionary of keyword arguments passed into ``func``. Returns ------- object : the return type of ``func``. Notes ----- Use ``.pipe`` when chaining together functions that expect Series, DataFrames or GroupBy objects. For example, given >>> df = ps.DataFrame({'category': ['A', 'A', 'B'], ... 'col1': [1, 2, 3], ... 'col2': [4, 5, 6]}, ... columns=['category', 'col1', 'col2']) >>> def keep_category_a(df): ... return df[df['category'] == 'A'] >>> def add_one(df, column): ... return df.assign(col3=df[column] + 1) >>> def multiply(df, column1, column2): ... return df.assign(col4=df[column1] * df[column2]) instead of writing >>> multiply(add_one(keep_category_a(df), column="col1"), column1="col2", column2="col3") category col1 col2 col3 col4 0 A 1 4 2 8 1 A 2 5 3 15 You can write >>> (df.pipe(keep_category_a) ... .pipe(add_one, column="col1") ... .pipe(multiply, column1="col2", column2="col3") ... ) category col1 col2 col3 col4 0 A 1 4 2 8 1 A 2 5 3 15 If you have a function that takes the data as (say) the second argument, pass a tuple indicating which keyword expects the data. For example, suppose ``f`` takes its data as ``df``: >>> def multiply_2(column1, df, column2): ... return df.assign(col4=df[column1] * df[column2]) Then you can write >>> (df.pipe(keep_category_a) ... .pipe(add_one, column="col1") ... .pipe((multiply_2, 'df'), column1="col2", column2="col3") ... ) category col1 col2 col3 col4 0 A 1 4 2 8 1 A 2 5 3 15 You can use lambda as wel >>> ps.Series([1, 2, 3]).pipe(lambda x: (x + 1).rename("value")) 0 2 1 3 2 4 Name: value, dtype: int64 """ if isinstance(func, tuple): func, target = func if target in kwargs: raise ValueError("%s is both the pipe target and a keyword " "argument" % target) kwargs[target] = self return func(*args, **kwargs) else: return func(self, *args, **kwargs) def to_numpy(self) -> np.ndarray: """ A NumPy ndarray representing the values in this DataFrame or Series. .. note:: This method should only be used if the resulting NumPy ndarray is expected to be small, as all the data is loaded into the driver's memory. Returns ------- numpy.ndarray Examples -------- >>> ps.DataFrame({"A": [1, 2], "B": [3, 4]}).to_numpy() array([[1, 3], [2, 4]]) With heterogeneous data, the lowest common type will have to be used. >>> ps.DataFrame({"A": [1, 2], "B": [3.0, 4.5]}).to_numpy() array([[1. , 3. ], [2. , 4.5]]) For a mix of numeric and non-numeric types, the output array will have object dtype. >>> df = ps.DataFrame({"A": [1, 2], "B": [3.0, 4.5], "C": pd.date_range('2000', periods=2)}) >>> df.to_numpy() array([[1, 3.0, Timestamp('2000-01-01 00:00:00')], [2, 4.5, Timestamp('2000-01-02 00:00:00')]], dtype=object) For Series, >>> ps.Series(['a', 'b', 'a']).to_numpy() array(['a', 'b', 'a'], dtype=object) """ return self.to_pandas().values @property def values(self) -> np.ndarray: """ Return a Numpy representation of the DataFrame or the Series. .. warning:: We recommend using `DataFrame.to_numpy()` or `Series.to_numpy()` instead. .. note:: This method should only be used if the resulting NumPy ndarray is expected to be small, as all the data is loaded into the driver's memory. Returns ------- numpy.ndarray Examples -------- A DataFrame where all columns are the same type (e.g., int64) results in an array of the same type. >>> df = ps.DataFrame({'age': [ 3, 29], ... 'height': [94, 170], ... 'weight': [31, 115]}) >>> df age height weight 0 3 94 31 1 29 170 115 >>> df.dtypes age int64 height int64 weight int64 dtype: object >>> df.values array([[ 3, 94, 31], [ 29, 170, 115]]) A DataFrame with mixed type columns(e.g., str/object, int64, float32) results in an ndarray of the broadest type that accommodates these mixed types (e.g., object). >>> df2 = ps.DataFrame([('parrot', 24.0, 'second'), ... ('lion', 80.5, 'first'), ... ('monkey', np.nan, None)], ... columns=('name', 'max_speed', 'rank')) >>> df2.dtypes name object max_speed float64 rank object dtype: object >>> df2.values array([['parrot', 24.0, 'second'], ['lion', 80.5, 'first'], ['monkey', nan, None]], dtype=object) For Series, >>> ps.Series([1, 2, 3]).values array([1, 2, 3]) >>> ps.Series(list('aabc')).values array(['a', 'a', 'b', 'c'], dtype=object) """ warnings.warn("We recommend using `{}.to_numpy()` instead.".format(type(self).__name__)) return self.to_numpy() def to_csv( self, path: Optional[str] = None, sep: str = ",", na_rep: str = "", columns: Optional[List[Name]] = None, header: bool = True, quotechar: str = '"', date_format: Optional[str] = None, escapechar: Optional[str] = None, num_files: Optional[int] = None, mode: str = "overwrite", partition_cols: Optional[Union[str, List[str]]] = None, index_col: Optional[Union[str, List[str]]] = None, **options: Any ) -> Optional[str]: r""" Write object to a comma-separated values (csv) file. .. note:: pandas-on-Spark `to_csv` writes files to a path or URI. Unlike pandas', pandas-on-Spark respects HDFS's property such as 'fs.default.name'. .. note:: pandas-on-Spark writes CSV files into the directory, `path`, and writes multiple `part-...` files in the directory when `path` is specified. This behaviour was inherited from Apache Spark. The number of files can be controlled by `num_files`. Parameters ---------- path : str, default None File path. If None is provided the result is returned as a string. sep : str, default ',' String of length 1. Field delimiter for the output file. na_rep : str, default '' Missing data representation. columns : sequence, optional Columns to write. header : bool or list of str, default True Write out the column names. If a list of strings is given it is assumed to be aliases for the column names. quotechar : str, default '\"' String of length 1. Character used to quote fields. date_format : str, default None Format string for datetime objects. escapechar : str, default None String of length 1. Character used to escape `sep` and `quotechar` when appropriate. num_files : the number of files to be written in `path` directory when this is a path. mode : str {'append', 'overwrite', 'ignore', 'error', 'errorifexists'}, default 'overwrite'. Specifies the behavior of the save operation when the destination exists already. - 'append': Append the new data to existing data. - 'overwrite': Overwrite existing data. - 'ignore': Silently ignore this operation if data already exists. - 'error' or 'errorifexists': Throw an exception if data already exists. partition_cols : str or list of str, optional, default None Names of partitioning columns index_col: str or list of str, optional, default: None Column names to be used in Spark to represent pandas-on-Spark's index. The index name in pandas-on-Spark is ignored. By default, the index is always lost. options: keyword arguments for additional options specific to PySpark. This kwargs are specific to PySpark's CSV options to pass. Check the options in PySpark's API documentation for spark.write.csv(...). It has higher priority and overwrites all other options. This parameter only works when `path` is specified. Returns ------- str or None See Also -------- read_csv DataFrame.to_delta DataFrame.to_table DataFrame.to_parquet DataFrame.to_spark_io Examples -------- >>> df = ps.DataFrame(dict( ... date=list(pd.date_range('2012-1-1 12:00:00', periods=3, freq='M')), ... country=['KR', 'US', 'JP'], ... code=[1, 2 ,3]), columns=['date', 'country', 'code']) >>> df.sort_values(by="date") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE date country code ... 2012-01-31 12:00:00 KR 1 ... 2012-02-29 12:00:00 US 2 ... 2012-03-31 12:00:00 JP 3 >>> print(df.to_csv()) # doctest: +NORMALIZE_WHITESPACE date,country,code 2012-01-31 12:00:00,KR,1 2012-02-29 12:00:00,US,2 2012-03-31 12:00:00,JP,3 >>> df.cummax().to_csv(path=r'%s/to_csv/foo.csv' % path, num_files=1) >>> ps.read_csv( ... path=r'%s/to_csv/foo.csv' % path ... ).sort_values(by="date") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE date country code ... 2012-01-31 12:00:00 KR 1 ... 2012-02-29 12:00:00 US 2 ... 2012-03-31 12:00:00 US 3 In case of Series, >>> print(df.date.to_csv()) # doctest: +NORMALIZE_WHITESPACE date 2012-01-31 12:00:00 2012-02-29 12:00:00 2012-03-31 12:00:00 >>> df.date.to_csv(path=r'%s/to_csv/foo.csv' % path, num_files=1) >>> ps.read_csv( ... path=r'%s/to_csv/foo.csv' % path ... ).sort_values(by="date") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE date ... 2012-01-31 12:00:00 ... 2012-02-29 12:00:00 ... 2012-03-31 12:00:00 You can preserve the index in the roundtrip as below. >>> df.set_index("country", append=True, inplace=True) >>> df.date.to_csv( ... path=r'%s/to_csv/bar.csv' % path, ... num_files=1, ... index_col=["index1", "index2"]) >>> ps.read_csv( ... path=r'%s/to_csv/bar.csv' % path, index_col=["index1", "index2"] ... ).sort_values(by="date") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE date index1 index2 ... ... 2012-01-31 12:00:00 ... ... 2012-02-29 12:00:00 ... ... 2012-03-31 12:00:00 """ if "options" in options and isinstance(options.get("options"), dict) and len(options) == 1: options = options.get("options") # type: ignore if path is None: # If path is none, just collect and use pandas's to_csv. psdf_or_ser = self if (LooseVersion("0.24") > LooseVersion(pd.__version__)) and isinstance( self, ps.Series ): # 0.23 seems not having 'columns' parameter in Series' to_csv. return psdf_or_ser.to_pandas().to_csv( # type: ignore None, sep=sep, na_rep=na_rep, header=header, date_format=date_format, index=False, ) else: return psdf_or_ser.to_pandas().to_csv( # type: ignore None, sep=sep, na_rep=na_rep, columns=columns, header=header, quotechar=quotechar, date_format=date_format, escapechar=escapechar, index=False, ) psdf = self if isinstance(self, ps.Series): psdf = self.to_frame() if columns is None: column_labels = psdf._internal.column_labels else: column_labels = [] for col in columns: if is_name_like_tuple(col): label = cast(Label, col) else: label = cast(Label, (col,)) if label not in psdf._internal.column_labels: raise KeyError(name_like_string(label)) column_labels.append(label) if isinstance(index_col, str): index_cols = [index_col] elif index_col is None: index_cols = [] else: index_cols = index_col if header is True and psdf._internal.column_labels_level > 1: raise ValueError("to_csv only support one-level index column now") elif isinstance(header, list): sdf = psdf.to_spark(index_col) # type: ignore sdf = sdf.select( [scol_for(sdf, name_like_string(label)) for label in index_cols] + [ scol_for(sdf, str(i) if label is None else name_like_string(label)).alias( new_name ) for i, (label, new_name) in enumerate(zip(column_labels, header)) ] ) header = True else: sdf = psdf.to_spark(index_col) # type: ignore sdf = sdf.select( [scol_for(sdf, name_like_string(label)) for label in index_cols] + [ scol_for(sdf, str(i) if label is None else name_like_string(label)) for i, label in enumerate(column_labels) ] ) if num_files is not None: sdf = sdf.repartition(num_files) builder = sdf.write.mode(mode) if partition_cols is not None: builder.partitionBy(partition_cols) builder._set_opts( sep=sep, nullValue=na_rep, header=header, quote=quotechar, dateFormat=date_format, charToEscapeQuoteEscaping=escapechar, ) builder.options(**options).format("csv").save(path) return None def to_json( self, path: Optional[str] = None, compression: str = "uncompressed", num_files: Optional[int] = None, mode: str = "overwrite", orient: str = "records", lines: bool = True, partition_cols: Optional[Union[str, List[str]]] = None, index_col: Optional[Union[str, List[str]]] = None, **options: Any ) -> Optional[str]: """ Convert the object to a JSON string. .. note:: pandas-on-Spark `to_json` writes files to a path or URI. Unlike pandas', pandas-on-Spark respects HDFS's property such as 'fs.default.name'. .. note:: pandas-on-Spark writes JSON files into the directory, `path`, and writes multiple `part-...` files in the directory when `path` is specified. This behaviour was inherited from Apache Spark. The number of files can be controlled by `num_files`. .. note:: output JSON format is different from pandas'. It always use `orient='records'` for its output. This behaviour might have to change in the near future. Note NaN's and None will be converted to null and datetime objects will be converted to UNIX timestamps. Parameters ---------- path : string, optional File path. If not specified, the result is returned as a string. lines : bool, default True If ‘orient’ is ‘records’ write out line delimited json format. Will throw ValueError if incorrect ‘orient’ since others are not list like. It should be always True for now. orient : str, default 'records' It should be always 'records' for now. compression : {'gzip', 'bz2', 'xz', None} A string representing the compression to use in the output file, only used when the first argument is a filename. By default, the compression is inferred from the filename. num_files : the number of files to be written in `path` directory when this is a path. mode : str {'append', 'overwrite', 'ignore', 'error', 'errorifexists'}, default 'overwrite'. Specifies the behavior of the save operation when the destination exists already. - 'append': Append the new data to existing data. - 'overwrite': Overwrite existing data. - 'ignore': Silently ignore this operation if data already exists. - 'error' or 'errorifexists': Throw an exception if data already exists. partition_cols : str or list of str, optional, default None Names of partitioning columns index_col: str or list of str, optional, default: None Column names to be used in Spark to represent pandas-on-Spark's index. The index name in pandas-on-Spark is ignored. By default, the index is always lost. options: keyword arguments for additional options specific to PySpark. It is specific to PySpark's JSON options to pass. Check the options in PySpark's API documentation for `spark.write.json(...)`. It has a higher priority and overwrites all other options. This parameter only works when `path` is specified. Returns -------- str or None Examples -------- >>> df = ps.DataFrame([['a', 'b'], ['c', 'd']], ... columns=['col 1', 'col 2']) >>> df.to_json() '[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]' >>> df['col 1'].to_json() '[{"col 1":"a"},{"col 1":"c"}]' >>> df.to_json(path=r'%s/to_json/foo.json' % path, num_files=1) >>> ps.read_json( ... path=r'%s/to_json/foo.json' % path ... ).sort_values(by="col 1") col 1 col 2 0 a b 1 c d >>> df['col 1'].to_json(path=r'%s/to_json/foo.json' % path, num_files=1, index_col="index") >>> ps.read_json( ... path=r'%s/to_json/foo.json' % path, index_col="index" ... ).sort_values(by="col 1") # doctest: +NORMALIZE_WHITESPACE col 1 index 0 a 1 c """ if "options" in options and isinstance(options.get("options"), dict) and len(options) == 1: options = options.get("options") # type: ignore if not lines: raise NotImplementedError("lines=False is not implemented yet.") if orient != "records": raise NotImplementedError("orient='records' is supported only for now.") if path is None: # If path is none, just collect and use pandas's to_json. psdf_or_ser = self pdf = psdf_or_ser.to_pandas() # type: ignore if isinstance(self, ps.Series): pdf = pdf.to_frame() # To make the format consistent and readable by `read_json`, convert it to pandas' and # use 'records' orient for now. return pdf.to_json(orient="records") psdf = self if isinstance(self, ps.Series): psdf = self.to_frame() sdf = psdf.to_spark(index_col=index_col) # type: ignore if num_files is not None: sdf = sdf.repartition(num_files) builder = sdf.write.mode(mode) if partition_cols is not None: builder.partitionBy(partition_cols) builder._set_opts(compression=compression) builder.options(**options).format("json").save(path) return None def to_excel( self, excel_writer: Union[str, pd.ExcelWriter], sheet_name: str = "Sheet1", na_rep: str = "", float_format: Optional[str] = None, columns: Optional[Union[str, List[str]]] = None, header: bool = True, index: bool = True, index_label: Optional[Union[str, List[str]]] = None, startrow: int = 0, startcol: int = 0, engine: Optional[str] = None, merge_cells: bool = True, encoding: Optional[str] = None, inf_rep: str = "inf", verbose: bool = True, freeze_panes: Optional[Tuple[int, int]] = None, ) -> None: """ Write object to an Excel sheet. .. note:: This method should only be used if the resulting DataFrame is expected to be small, as all the data is loaded into the driver's memory. To write a single object to an Excel .xlsx file it is only necessary to specify a target file name. To write to multiple sheets it is necessary to create an `ExcelWriter` object with a target file name, and specify a sheet in the file to write to. Multiple sheets may be written to by specifying unique `sheet_name`. With all data written to the file it is necessary to save the changes. Note that creating an `ExcelWriter` object with a file name that already exists will result in the contents of the existing file being erased. Parameters ---------- excel_writer : str or ExcelWriter object File path or existing ExcelWriter. sheet_name : str, default 'Sheet1' Name of sheet which will contain DataFrame. na_rep : str, default '' Missing data representation. float_format : str, optional Format string for floating point numbers. For example ``float_format="%%.2f"`` will format 0.1234 to 0.12. columns : sequence or list of str, optional Columns to write. header : bool or list of str, default True Write out the column names. If a list of string is given it is assumed to be aliases for the column names. index : bool, default True Write row names (index). index_label : str or sequence, optional Column label for index column(s) if desired. If not specified, and `header` and `index` are True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. startrow : int, default 0 Upper left cell row to dump data frame. startcol : int, default 0 Upper left cell column to dump data frame. engine : str, optional Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and ``io.excel.xlsm.writer``. merge_cells : bool, default True Write MultiIndex and Hierarchical Rows as merged cells. encoding : str, optional Encoding of the resulting excel file. Only necessary for xlwt, other writers support unicode natively. inf_rep : str, default 'inf' Representation for infinity (there is no native representation for infinity in Excel). verbose : bool, default True Display more information in the error logs. freeze_panes : tuple of int (length 2), optional Specifies the one-based bottommost row and rightmost column that is to be frozen. Notes ----- Once a workbook has been saved it is not possible write further data without rewriting the whole workbook. See Also -------- read_excel : Read Excel file. Examples -------- Create, write to and save a workbook: >>> df1 = ps.DataFrame([['a', 'b'], ['c', 'd']], ... index=['row 1', 'row 2'], ... columns=['col 1', 'col 2']) >>> df1.to_excel("output.xlsx") # doctest: +SKIP To specify the sheet name: >>> df1.to_excel("output.xlsx") # doctest: +SKIP >>> df1.to_excel("output.xlsx", ... sheet_name='Sheet_name_1') # doctest: +SKIP If you wish to write to more than one sheet in the workbook, it is necessary to specify an ExcelWriter object: >>> with pd.ExcelWriter('output.xlsx') as writer: # doctest: +SKIP ... df1.to_excel(writer, sheet_name='Sheet_name_1') ... df2.to_excel(writer, sheet_name='Sheet_name_2') To set the library that is used to write the Excel file, you can pass the `engine` keyword (the default engine is automatically chosen depending on the file extension): >>> df1.to_excel('output1.xlsx', engine='xlsxwriter') # doctest: +SKIP """ # Make sure locals() call is at the top of the function so we don't capture local variables. args = locals() psdf = self if isinstance(self, ps.DataFrame): f = pd.DataFrame.to_excel elif isinstance(self, ps.Series): f = pd.Series.to_excel else: raise TypeError( "Constructor expects DataFrame or Series; however, " "got [%s]" % (self,) ) return validate_arguments_and_invoke_function( psdf._to_internal_pandas(), self.to_excel, f, args ) def mean( self, axis: Optional[Axis] = None, numeric_only: bool = None ) -> Union[Scalar, "Series"]: """ Return the mean of the values. Parameters ---------- axis : {index (0), columns (1)} Axis for the function to be applied on. numeric_only : bool, default None Include only float, int, boolean columns. False is not supported. This parameter is mainly for pandas compatibility. Returns ------- mean : scalar for a Series, and a Series for a DataFrame. Examples -------- >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]}, ... columns=['a', 'b']) On a DataFrame: >>> df.mean() a 2.0 b 0.2 dtype: float64 >>> df.mean(axis=1) 0 0.55 1 1.10 2 1.65 3 NaN dtype: float64 On a Series: >>> df['a'].mean() 2.0 """ axis = validate_axis(axis) if numeric_only is None and axis == 0: numeric_only = True def mean(spark_column: Column, spark_type: DataType) -> Column: if isinstance(spark_type, BooleanType): spark_column = spark_column.cast(LongType()) elif not isinstance(spark_type, NumericType): raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(spark_type), spark_type.simpleString() ) ) return F.mean(spark_column) return self._reduce_for_stat_function( mean, name="mean", axis=axis, numeric_only=numeric_only ) def sum( self, axis: Optional[Axis] = None, numeric_only: bool = None, min_count: int = 0 ) -> Union[Scalar, "Series"]: """ Return the sum of the values. Parameters ---------- axis : {index (0), columns (1)} Axis for the function to be applied on. numeric_only : bool, default None Include only float, int, boolean columns. False is not supported. This parameter is mainly for pandas compatibility. min_count : int, default 0 The required number of valid values to perform the operation. If fewer than ``min_count`` non-NA values are present the result will be NA. Returns ------- sum : scalar for a Series, and a Series for a DataFrame. Examples -------- >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, np.nan, 0.3, np.nan]}, ... columns=['a', 'b']) On a DataFrame: >>> df.sum() a 6.0 b 0.4 dtype: float64 >>> df.sum(axis=1) 0 1.1 1 2.0 2 3.3 3 0.0 dtype: float64 >>> df.sum(min_count=3) a 6.0 b NaN dtype: float64 >>> df.sum(axis=1, min_count=1) 0 1.1 1 2.0 2 3.3 3 NaN dtype: float64 On a Series: >>> df['a'].sum() 6.0 >>> df['a'].sum(min_count=3) 6.0 >>> df['b'].sum(min_count=3) nan """ axis = validate_axis(axis) if numeric_only is None and axis == 0: numeric_only = True elif numeric_only is True and axis == 1: numeric_only = None def sum(spark_column: Column, spark_type: DataType) -> Column: if isinstance(spark_type, BooleanType): spark_column = spark_column.cast(LongType()) elif not isinstance(spark_type, NumericType): raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(spark_type), spark_type.simpleString() ) ) return F.coalesce(F.sum(spark_column), SF.lit(0)) return self._reduce_for_stat_function( sum, name="sum", axis=axis, numeric_only=numeric_only, min_count=min_count ) def product( self, axis: Optional[Axis] = None, numeric_only: bool = None, min_count: int = 0 ) -> Union[Scalar, "Series"]: """ Return the product of the values. .. note:: unlike pandas', pandas-on-Spark's emulates product by ``exp(sum(log(...)))`` trick. Therefore, it only works for positive numbers. Parameters ---------- axis : {index (0), columns (1)} Axis for the function to be applied on. numeric_only : bool, default None Include only float, int, boolean columns. False is not supported. This parameter is mainly for pandas compatibility. min_count : int, default 0 The required number of valid values to perform the operation. If fewer than ``min_count`` non-NA values are present the result will be NA. Examples -------- On a DataFrame: Non-numeric type column is not included to the result. >>> psdf = ps.DataFrame({'A': [1, 2, 3, 4, 5], ... 'B': [10, 20, 30, 40, 50], ... 'C': ['a', 'b', 'c', 'd', 'e']}) >>> psdf A B C 0 1 10 a 1 2 20 b 2 3 30 c 3 4 40 d 4 5 50 e >>> psdf.prod() A 120 B 12000000 dtype: int64 If there is no numeric type columns, returns empty Series. >>> ps.DataFrame({"key": ['a', 'b', 'c'], "val": ['x', 'y', 'z']}).prod() Series([], dtype: float64) On a Series: >>> ps.Series([1, 2, 3, 4, 5]).prod() 120 By default, the product of an empty or all-NA Series is ``1`` >>> ps.Series([]).prod() 1.0 This can be controlled with the ``min_count`` parameter >>> ps.Series([]).prod(min_count=1) nan """ axis = validate_axis(axis) if numeric_only is None and axis == 0: numeric_only = True elif numeric_only is True and axis == 1: numeric_only = None def prod(spark_column: Column, spark_type: DataType) -> Column: if isinstance(spark_type, BooleanType): scol = F.min(F.coalesce(spark_column, SF.lit(True))).cast(LongType()) elif isinstance(spark_type, NumericType): num_zeros = F.sum(F.when(spark_column == 0, 1).otherwise(0)) sign = F.when( F.sum(F.when(spark_column < 0, 1).otherwise(0)) % 2 == 0, 1 ).otherwise(-1) scol = F.when(num_zeros > 0, 0).otherwise( sign * F.exp(F.sum(F.log(F.abs(spark_column)))) ) if isinstance(spark_type, IntegralType): scol = F.round(scol).cast(LongType()) else: raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(spark_type), spark_type.simpleString() ) ) return F.coalesce(scol, SF.lit(1)) return self._reduce_for_stat_function( prod, name="prod", axis=axis, numeric_only=numeric_only, min_count=min_count ) prod = product def skew( self, axis: Optional[Axis] = None, numeric_only: bool = None ) -> Union[Scalar, "Series"]: """ Return unbiased skew normalized by N-1. Parameters ---------- axis : {index (0), columns (1)} Axis for the function to be applied on. numeric_only : bool, default None Include only float, int, boolean columns. False is not supported. This parameter is mainly for pandas compatibility. Returns ------- skew : scalar for a Series, and a Series for a DataFrame. Examples -------- >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]}, ... columns=['a', 'b']) On a DataFrame: >>> df.skew() # doctest: +SKIP a 0.000000e+00 b -3.319678e-16 dtype: float64 On a Series: >>> df['a'].skew() 0.0 """ axis = validate_axis(axis) if numeric_only is None and axis == 0: numeric_only = True def skew(spark_column: Column, spark_type: DataType) -> Column: if isinstance(spark_type, BooleanType): spark_column = spark_column.cast(LongType()) elif not isinstance(spark_type, NumericType): raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(spark_type), spark_type.simpleString() ) ) return F.skewness(spark_column) return self._reduce_for_stat_function( skew, name="skew", axis=axis, numeric_only=numeric_only ) def kurtosis( self, axis: Optional[Axis] = None, numeric_only: bool = None ) -> Union[Scalar, "Series"]: """ Return unbiased kurtosis using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1. Parameters ---------- axis : {index (0), columns (1)} Axis for the function to be applied on. numeric_only : bool, default None Include only float, int, boolean columns. False is not supported. This parameter is mainly for pandas compatibility. Returns ------- kurt : scalar for a Series, and a Series for a DataFrame. Examples -------- >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]}, ... columns=['a', 'b']) On a DataFrame: >>> df.kurtosis() a -1.5 b -1.5 dtype: float64 On a Series: >>> df['a'].kurtosis() -1.5 """ axis = validate_axis(axis) if numeric_only is None and axis == 0: numeric_only = True def kurtosis(spark_column: Column, spark_type: DataType) -> Column: if isinstance(spark_type, BooleanType): spark_column = spark_column.cast(LongType()) elif not isinstance(spark_type, NumericType): raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(spark_type), spark_type.simpleString() ) ) return F.kurtosis(spark_column) return self._reduce_for_stat_function( kurtosis, name="kurtosis", axis=axis, numeric_only=numeric_only ) kurt = kurtosis def min( self, axis: Optional[Axis] = None, numeric_only: bool = None ) -> Union[Scalar, "Series"]: """ Return the minimum of the values. Parameters ---------- axis : {index (0), columns (1)} Axis for the function to be applied on. numeric_only : bool, default None If True, include only float, int, boolean columns. This parameter is mainly for pandas compatibility. False is supported; however, the columns should be all numeric or all non-numeric. Returns ------- min : scalar for a Series, and a Series for a DataFrame. Examples -------- >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]}, ... columns=['a', 'b']) On a DataFrame: >>> df.min() a 1.0 b 0.1 dtype: float64 >>> df.min(axis=1) 0 0.1 1 0.2 2 0.3 3 NaN dtype: float64 On a Series: >>> df['a'].min() 1.0 """ axis = validate_axis(axis) if numeric_only is None and axis == 0: numeric_only = True elif numeric_only is True and axis == 1: numeric_only = None return self._reduce_for_stat_function( F.min, name="min", axis=axis, numeric_only=numeric_only ) def max( self, axis: Optional[Axis] = None, numeric_only: bool = None ) -> Union[Scalar, "Series"]: """ Return the maximum of the values. Parameters ---------- axis : {index (0), columns (1)} Axis for the function to be applied on. numeric_only : bool, default None If True, include only float, int, boolean columns. This parameter is mainly for pandas compatibility. False is supported; however, the columns should be all numeric or all non-numeric. Returns ------- max : scalar for a Series, and a Series for a DataFrame. Examples -------- >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]}, ... columns=['a', 'b']) On a DataFrame: >>> df.max() a 3.0 b 0.3 dtype: float64 >>> df.max(axis=1) 0 1.0 1 2.0 2 3.0 3 NaN dtype: float64 On a Series: >>> df['a'].max() 3.0 """ axis = validate_axis(axis) if numeric_only is None and axis == 0: numeric_only = True elif numeric_only is True and axis == 1: numeric_only = None return self._reduce_for_stat_function( F.max, name="max", axis=axis, numeric_only=numeric_only ) def count( self, axis: Optional[Axis] = None, numeric_only: bool = False ) -> Union[Scalar, "Series"]: """ Count non-NA cells for each column. The values `None`, `NaN` are considered NA. Parameters ---------- axis : {0 or ‘index’, 1 or ‘columns’}, default 0 If 0 or ‘index’ counts are generated for each column. If 1 or ‘columns’ counts are generated for each row. numeric_only : bool, default False If True, include only float, int, boolean columns. This parameter is mainly for pandas compatibility. Returns ------- max : scalar for a Series, and a Series for a DataFrame. See Also -------- DataFrame.shape: Number of DataFrame rows and columns (including NA elements). DataFrame.isna: Boolean same-sized DataFrame showing places of NA elements. Examples -------- Constructing DataFrame from a dictionary: >>> df = ps.DataFrame({"Person": ... ["John", "Myla", "Lewis", "John", "Myla"], ... "Age": [24., np.nan, 21., 33, 26], ... "Single": [False, True, True, True, False]}, ... columns=["Person", "Age", "Single"]) >>> df Person Age Single 0 John 24.0 False 1 Myla NaN True 2 Lewis 21.0 True 3 John 33.0 True 4 Myla 26.0 False Notice the uncounted NA values: >>> df.count() Person 5 Age 4 Single 5 dtype: int64 >>> df.count(axis=1) 0 3 1 2 2 3 3 3 4 3 dtype: int64 On a Series: >>> df['Person'].count() 5 >>> df['Age'].count() 4 """ return self._reduce_for_stat_function( Frame._count_expr, name="count", axis=axis, numeric_only=numeric_only ) def std( self, axis: Optional[Axis] = None, ddof: int = 1, numeric_only: bool = None ) -> Union[Scalar, "Series"]: """ Return sample standard deviation. Parameters ---------- axis : {index (0), columns (1)} Axis for the function to be applied on. ddof : int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. numeric_only : bool, default None Include only float, int, boolean columns. False is not supported. This parameter is mainly for pandas compatibility. Returns ------- std : scalar for a Series, and a Series for a DataFrame. Examples -------- >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]}, ... columns=['a', 'b']) On a DataFrame: >>> df.std() a 1.0 b 0.1 dtype: float64 >>> df.std(axis=1) 0 0.636396 1 1.272792 2 1.909188 3 NaN dtype: float64 >>> df.std(ddof=0) a 0.816497 b 0.081650 dtype: float64 On a Series: >>> df['a'].std() 1.0 >>> df['a'].std(ddof=0) 0.816496580927726 """ assert ddof in (0, 1) axis = validate_axis(axis) if numeric_only is None and axis == 0: numeric_only = True def std(spark_column: Column, spark_type: DataType) -> Column: if isinstance(spark_type, BooleanType): spark_column = spark_column.cast(LongType()) elif not isinstance(spark_type, NumericType): raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(spark_type), spark_type.simpleString() ) ) if ddof == 0: return F.stddev_pop(spark_column) else: return F.stddev_samp(spark_column) return self._reduce_for_stat_function( std, name="std", axis=axis, numeric_only=numeric_only, ddof=ddof ) def var( self, axis: Optional[Axis] = None, ddof: int = 1, numeric_only: bool = None ) -> Union[Scalar, "Series"]: """ Return unbiased variance. Parameters ---------- axis : {index (0), columns (1)} Axis for the function to be applied on. ddof : int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. numeric_only : bool, default None Include only float, int, boolean columns. False is not supported. This parameter is mainly for pandas compatibility. Returns ------- var : scalar for a Series, and a Series for a DataFrame. Examples -------- >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]}, ... columns=['a', 'b']) On a DataFrame: >>> df.var() a 1.00 b 0.01 dtype: float64 >>> df.var(axis=1) 0 0.405 1 1.620 2 3.645 3 NaN dtype: float64 >>> df.var(ddof=0) a 0.666667 b 0.006667 dtype: float64 On a Series: >>> df['a'].var() 1.0 >>> df['a'].var(ddof=0) 0.6666666666666666 """ assert ddof in (0, 1) axis = validate_axis(axis) if numeric_only is None and axis == 0: numeric_only = True def var(spark_column: Column, spark_type: DataType) -> Column: if isinstance(spark_type, BooleanType): spark_column = spark_column.cast(LongType()) elif not isinstance(spark_type, NumericType): raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(spark_type), spark_type.simpleString() ) ) if ddof == 0: return F.var_pop(spark_column) else: return F.var_samp(spark_column) return self._reduce_for_stat_function( var, name="var", axis=axis, numeric_only=numeric_only, ddof=ddof ) def median( self, axis: Optional[Axis] = None, numeric_only: bool = None, accuracy: int = 10000 ) -> Union[Scalar, "Series"]: """ Return the median of the values for the requested axis. .. note:: Unlike pandas', the median in pandas-on-Spark is an approximated median based upon approximate percentile computation because computing median across a large dataset is extremely expensive. Parameters ---------- axis : {index (0), columns (1)} Axis for the function to be applied on. numeric_only : bool, default None Include only float, int, boolean columns. False is not supported. This parameter is mainly for pandas compatibility. accuracy : int, optional Default accuracy of approximation. Larger value means better accuracy. The relative error can be deduced by 1.0 / accuracy. Returns ------- median : scalar or Series Examples -------- >>> df = ps.DataFrame({ ... 'a': [24., 21., 25., 33., 26.], 'b': [1, 2, 3, 4, 5]}, columns=['a', 'b']) >>> df a b 0 24.0 1 1 21.0 2 2 25.0 3 3 33.0 4 4 26.0 5 On a DataFrame: >>> df.median() a 25.0 b 3.0 dtype: float64 On a Series: >>> df['a'].median() 25.0 >>> (df['b'] + 100).median() 103.0 For multi-index columns, >>> df.columns = pd.MultiIndex.from_tuples([('x', 'a'), ('y', 'b')]) >>> df x y a b 0 24.0 1 1 21.0 2 2 25.0 3 3 33.0 4 4 26.0 5 On a DataFrame: >>> df.median() x a 25.0 y b 3.0 dtype: float64 >>> df.median(axis=1) 0 12.5 1 11.5 2 14.0 3 18.5 4 15.5 dtype: float64 On a Series: >>> df[('x', 'a')].median() 25.0 >>> (df[('y', 'b')] + 100).median() 103.0 """ axis = validate_axis(axis) if numeric_only is None and axis == 0: numeric_only = True if not isinstance(accuracy, int): raise TypeError( "accuracy must be an integer; however, got [%s]" % type(accuracy).__name__ ) def median(spark_column: Column, spark_type: DataType) -> Column: if isinstance(spark_type, (BooleanType, NumericType)): return F.percentile_approx(spark_column.cast(DoubleType()), 0.5, accuracy) else: raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(spark_type), spark_type.simpleString() ) ) return self._reduce_for_stat_function( median, name="median", numeric_only=numeric_only, axis=axis ) def sem( self, axis: Optional[Axis] = None, ddof: int = 1, numeric_only: bool = None ) -> Union[Scalar, "Series"]: """ Return unbiased standard error of the mean over requested axis. Parameters ---------- axis : {index (0), columns (1)} Axis for the function to be applied on. ddof : int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. numeric_only : bool, default None Include only float, int, boolean columns. False is not supported. This parameter is mainly for pandas compatibility. Returns ------- scalar(for Series) or Series(for DataFrame) Examples -------- >>> psdf = ps.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) >>> psdf a b 0 1 4 1 2 5 2 3 6 >>> psdf.sem() a 0.57735 b 0.57735 dtype: float64 >>> psdf.sem(ddof=0) a 0.471405 b 0.471405 dtype: float64 >>> psdf.sem(axis=1) 0 1.5 1 1.5 2 1.5 dtype: float64 Support for Series >>> psser = psdf.a >>> psser 0 1 1 2 2 3 Name: a, dtype: int64 >>> psser.sem() 0.5773502691896258 >>> psser.sem(ddof=0) 0.47140452079103173 """ assert ddof in (0, 1) axis = validate_axis(axis) if numeric_only is None and axis == 0: numeric_only = True def std(spark_column: Column, spark_type: DataType) -> Column: if isinstance(spark_type, BooleanType): spark_column = spark_column.cast(LongType()) elif not isinstance(spark_type, NumericType): raise TypeError( "Could not convert {} ({}) to numeric".format( spark_type_to_pandas_dtype(spark_type), spark_type.simpleString() ) ) if ddof == 0: return F.stddev_pop(spark_column) else: return F.stddev_samp(spark_column) def sem(spark_column: Column, spark_type: DataType) -> Column: return std(spark_column, spark_type) / pow( Frame._count_expr(spark_column, spark_type), 0.5 ) return self._reduce_for_stat_function( sem, name="sem", numeric_only=numeric_only, axis=axis, ddof=ddof ) @property def size(self) -> int: """ Return an int representing the number of elements in this object. Return the number of rows if Series. Otherwise return the number of rows times number of columns if DataFrame. Examples -------- >>> s = ps.Series({'a': 1, 'b': 2, 'c': None}) >>> s.size 3 >>> df = ps.DataFrame({'col1': [1, 2, None], 'col2': [3, 4, None]}) >>> df.size 6 >>> df = ps.DataFrame(index=[1, 2, None]) >>> df.size 0 """ num_columns = len(self._internal.data_spark_columns) if num_columns == 0: return 0 else: return len(self) * num_columns # type: ignore def abs(self: FrameLike) -> FrameLike: """ Return a Series/DataFrame with absolute numeric value of each element. Returns ------- abs : Series/DataFrame containing the absolute value of each element. Examples -------- Absolute numeric values in a Series. >>> s = ps.Series([-1.10, 2, -3.33, 4]) >>> s.abs() 0 1.10 1 2.00 2 3.33 3 4.00 dtype: float64 Absolute numeric values in a DataFrame. >>> df = ps.DataFrame({ ... 'a': [4, 5, 6, 7], ... 'b': [10, 20, 30, 40], ... 'c': [100, 50, -30, -50] ... }, ... columns=['a', 'b', 'c']) >>> df.abs() a b c 0 4 10 100 1 5 20 50 2 6 30 30 3 7 40 50 """ def abs(psser: "Series") -> Union["Series", Column]: if isinstance(psser.spark.data_type, BooleanType): return psser elif isinstance(psser.spark.data_type, NumericType): return psser._with_new_scol( F.abs(psser.spark.column), field=psser._internal.data_fields[0] ) else: raise TypeError( "bad operand type for abs(): {} ({})".format( spark_type_to_pandas_dtype(psser.spark.data_type), psser.spark.data_type.simpleString(), ) ) return self._apply_series_op(abs) # TODO: by argument only support the grouping name and as_index only for now. Documentation # should be updated when it's supported. def groupby( self: FrameLike, by: Union[Name, "Series", List[Union[Name, "Series"]]], axis: Axis = 0, as_index: bool = True, dropna: bool = True, ) -> "GroupBy[FrameLike]": """ Group DataFrame or Series using a Series of columns. A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters ---------- by : Series, label, or list of labels Used to determine the groups for the groupby. If Series is passed, the Series or dict VALUES will be used to determine the groups. A label or list of labels may be passed to group by the columns in ``self``. axis : int, default 0 or 'index' Can only be set to 0 at the moment. as_index : bool, default True For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively "SQL-style" grouped output. dropna : bool, default True If True, and if group keys contain NA values, NA values together with row/column will be dropped. If False, NA values will also be treated as the key in groups. Returns ------- DataFrameGroupBy or SeriesGroupBy Depends on the calling object and returns groupby object that contains information about the groups. See Also -------- pyspark.pandas.groupby.GroupBy Examples -------- >>> df = ps.DataFrame({'Animal': ['Falcon', 'Falcon', ... 'Parrot', 'Parrot'], ... 'Max Speed': [380., 370., 24., 26.]}, ... columns=['Animal', 'Max Speed']) >>> df Animal Max Speed 0 Falcon 380.0 1 Falcon 370.0 2 Parrot 24.0 3 Parrot 26.0 >>> df.groupby(['Animal']).mean().sort_index() # doctest: +NORMALIZE_WHITESPACE Max Speed Animal Falcon 375.0 Parrot 25.0 >>> df.groupby(['Animal'], as_index=False).mean().sort_values('Animal') ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE Animal Max Speed ...Falcon 375.0 ...Parrot 25.0 We can also choose to include NA in group keys or not by setting dropna parameter, the default setting is True: >>> l = [[1, 2, 3], [1, None, 4], [2, 1, 3], [1, 2, 2]] >>> df = ps.DataFrame(l, columns=["a", "b", "c"]) >>> df.groupby(by=["b"]).sum().sort_index() # doctest: +NORMALIZE_WHITESPACE a c b 1.0 2 3 2.0 2 5 >>> df.groupby(by=["b"], dropna=False).sum().sort_index() # doctest: +NORMALIZE_WHITESPACE a c b 1.0 2 3 2.0 2 5 NaN 1 4 """ if isinstance(by, ps.DataFrame): raise ValueError("Grouper for '{}' not 1-dimensional".format(type(by).__name__)) elif isinstance(by, ps.Series): new_by = [by] # type: List[Union[Label, ps.Series]] elif is_name_like_tuple(by): if isinstance(self, ps.Series): raise KeyError(by) new_by = [cast(Label, by)] elif is_name_like_value(by): if isinstance(self, ps.Series): raise KeyError(by) new_by = [cast(Label, (by,))] elif is_list_like(by): new_by = [] for key in by: if isinstance(key, ps.DataFrame): raise ValueError( "Grouper for '{}' not 1-dimensional".format(type(key).__name__) ) elif isinstance(key, ps.Series): new_by.append(key) elif is_name_like_tuple(key): if isinstance(self, ps.Series): raise KeyError(key) new_by.append(cast(Label, key)) elif is_name_like_value(key): if isinstance(self, ps.Series): raise KeyError(key) new_by.append(cast(Label, (key,))) else: raise ValueError( "Grouper for '{}' not 1-dimensional".format(type(key).__name__) ) else: raise ValueError("Grouper for '{}' not 1-dimensional".format(type(by).__name__)) if not len(new_by): raise ValueError("No group keys passed!") axis = validate_axis(axis) if axis != 0: raise NotImplementedError('axis should be either 0 or "index" currently.') return self._build_groupby(by=new_by, as_index=as_index, dropna=dropna) @abstractmethod def _build_groupby( self: FrameLike, by: List[Union["Series", Label]], as_index: bool, dropna: bool ) -> "GroupBy[FrameLike]": pass def bool(self) -> bool: """ Return the bool of a single element in the current object. This must be a boolean scalar value, either True or False. Raise a ValueError if the object does not have exactly 1 element, or that element is not boolean Returns -------- bool Examples -------- >>> ps.DataFrame({'a': [True]}).bool() True >>> ps.Series([False]).bool() False If there are non-boolean or multiple values exist, it raises an exception in all cases as below. >>> ps.DataFrame({'a': ['a']}).bool() Traceback (most recent call last): ... ValueError: bool cannot act on a non-boolean single element DataFrame >>> ps.DataFrame({'a': [True], 'b': [False]}).bool() # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). >>> ps.Series([1]).bool() Traceback (most recent call last): ... ValueError: bool cannot act on a non-boolean single element DataFrame """ if isinstance(self, ps.DataFrame): df = self elif isinstance(self, ps.Series): df = self.to_dataframe() else: raise TypeError("bool() expects DataFrame or Series; however, " "got [%s]" % (self,)) return df.head(2)._to_internal_pandas().bool() def first_valid_index(self) -> Optional[Union[Scalar, Tuple[Scalar, ...]]]: """ Retrieves the index of the first valid value. Returns ------- scalar, tuple, or None Examples -------- Support for DataFrame >>> psdf = ps.DataFrame({'a': [None, 2, 3, 2], ... 'b': [None, 2.0, 3.0, 1.0], ... 'c': [None, 200, 400, 200]}, ... index=['Q', 'W', 'E', 'R']) >>> psdf a b c Q NaN NaN NaN W 2.0 2.0 200.0 E 3.0 3.0 400.0 R 2.0 1.0 200.0 >>> psdf.first_valid_index() 'W' Support for MultiIndex columns >>> psdf.columns = pd.MultiIndex.from_tuples([('a', 'x'), ('b', 'y'), ('c', 'z')]) >>> psdf a b c x y z Q NaN NaN NaN W 2.0 2.0 200.0 E 3.0 3.0 400.0 R 2.0 1.0 200.0 >>> psdf.first_valid_index() 'W' Support for Series. >>> s = ps.Series([None, None, 3, 4, 5], index=[100, 200, 300, 400, 500]) >>> s 100 NaN 200 NaN 300 3.0 400 4.0 500 5.0 dtype: float64 >>> s.first_valid_index() 300 Support for MultiIndex >>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... [[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> s = ps.Series([None, None, None, None, 250, 1.5, 320, 1, 0.3], index=midx) >>> s lama speed NaN weight NaN length NaN cow speed NaN weight 250.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 dtype: float64 >>> s.first_valid_index() ('cow', 'weight') """ data_spark_columns = self._internal.data_spark_columns if len(data_spark_columns) == 0: return None cond = reduce(lambda x, y: x & y, map(lambda x: x.isNotNull(), data_spark_columns)) with sql_conf({SPARK_CONF_ARROW_ENABLED: False}): # Disable Arrow to keep row ordering. first_valid_row = cast( pd.DataFrame, self._internal.spark_frame.filter(cond) .select(self._internal.index_spark_columns) .limit(1) .toPandas(), ) # For Empty Series or DataFrame, returns None. if len(first_valid_row) == 0: return None first_valid_row = first_valid_row.iloc[0] if len(first_valid_row) == 1: return first_valid_row.iloc[0] else: return tuple(first_valid_row) def last_valid_index(self) -> Optional[Union[Scalar, Tuple[Scalar, ...]]]: """ Return index for last non-NA/null value. Returns ------- scalar, tuple, or None Notes ----- This API only works with PySpark >= 3.0. Examples -------- Support for DataFrame >>> psdf = ps.DataFrame({'a': [1, 2, 3, None], ... 'b': [1.0, 2.0, 3.0, None], ... 'c': [100, 200, 400, None]}, ... index=['Q', 'W', 'E', 'R']) >>> psdf a b c Q 1.0 1.0 100.0 W 2.0 2.0 200.0 E 3.0 3.0 400.0 R NaN NaN NaN >>> psdf.last_valid_index() # doctest: +SKIP 'E' Support for MultiIndex columns >>> psdf.columns = pd.MultiIndex.from_tuples([('a', 'x'), ('b', 'y'), ('c', 'z')]) >>> psdf a b c x y z Q 1.0 1.0 100.0 W 2.0 2.0 200.0 E 3.0 3.0 400.0 R NaN NaN NaN >>> psdf.last_valid_index() # doctest: +SKIP 'E' Support for Series. >>> s = ps.Series([1, 2, 3, None, None], index=[100, 200, 300, 400, 500]) >>> s 100 1.0 200 2.0 300 3.0 400 NaN 500 NaN dtype: float64 >>> s.last_valid_index() # doctest: +SKIP 300 Support for MultiIndex >>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... [[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> s = ps.Series([250, 1.5, 320, 1, 0.3, None, None, None, None], index=midx) >>> s lama speed 250.0 weight 1.5 length 320.0 cow speed 1.0 weight 0.3 length NaN falcon speed NaN weight NaN length NaN dtype: float64 >>> s.last_valid_index() # doctest: +SKIP ('cow', 'weight') """ data_spark_columns = self._internal.data_spark_columns if len(data_spark_columns) == 0: return None cond = reduce(lambda x, y: x & y, map(lambda x: x.isNotNull(), data_spark_columns)) last_valid_rows = ( self._internal.spark_frame.filter(cond) .select(self._internal.index_spark_columns) .tail(1) ) # For Empty Series or DataFrame, returns None. if len(last_valid_rows) == 0: return None last_valid_row = last_valid_rows[0] if len(last_valid_row) == 1: return last_valid_row[0] else: return tuple(last_valid_row) # TODO: 'center', 'win_type', 'on', 'axis' parameter should be implemented. def rolling( self: FrameLike, window: int, min_periods: Optional[int] = None ) -> "Rolling[FrameLike]": """ Provide rolling transformations. .. note:: 'min_periods' in pandas-on-Spark works as a fixed window size unlike pandas. Unlike pandas, NA is also counted as the period. This might be changed in the near future. Parameters ---------- window : int, or offset Size of the moving window. This is the number of observations used for calculating the statistic. Each window will be a fixed size. min_periods : int, default None Minimum number of observations in window required to have a value (otherwise result is NA). For a window that is specified by an offset, min_periods will default to 1. Otherwise, min_periods will default to the size of the window. Returns ------- a Window sub-classed for the particular operation """ from pyspark.pandas.window import Rolling return Rolling(self, window=window, min_periods=min_periods) # TODO: 'center' and 'axis' parameter should be implemented. # 'axis' implementation, refer https://github.com/pyspark.pandas/pull/607 def expanding(self: FrameLike, min_periods: int = 1) -> "Expanding[FrameLike]": """ Provide expanding transformations. .. note:: 'min_periods' in pandas-on-Spark works as a fixed window size unlike pandas. Unlike pandas, NA is also counted as the period. This might be changed in the near future. Parameters ---------- min_periods : int, default 1 Minimum number of observations in window required to have a value (otherwise result is NA). Returns ------- a Window sub-classed for the particular operation """ from pyspark.pandas.window import Expanding return Expanding(self, min_periods=min_periods) def get(self, key: Any, default: Optional[Any] = None) -> Any: """ Get item from object for given key (DataFrame column, Panel slice, etc.). Returns default value if not found. Parameters ---------- key : object Returns ------- value : same type as items contained in object Examples -------- >>> df = ps.DataFrame({'x':range(3), 'y':['a','b','b'], 'z':['a','b','b']}, ... columns=['x', 'y', 'z'], index=[10, 20, 20]) >>> df x y z 10 0 a a 20 1 b b 20 2 b b >>> df.get('x') 10 0 20 1 20 2 Name: x, dtype: int64 >>> df.get(['x', 'y']) x y 10 0 a 20 1 b 20 2 b >>> df.x.get(10) 0 >>> df.x.get(20) 20 1 20 2 Name: x, dtype: int64 >>> df.x.get(15, -1) -1 """ try: return self[key] except (KeyError, ValueError, IndexError): return default def squeeze(self, axis: Optional[Axis] = None) -> Union[Scalar, "DataFrame", "Series"]: """ Squeeze 1 dimensional axis objects into scalars. Series or DataFrames with a single element are squeezed to a scalar. DataFrames with a single column or a single row are squeezed to a Series. Otherwise the object is unchanged. This method is most useful when you don't know if your object is a Series or DataFrame, but you do know it has just a single column. In that case you can safely call `squeeze` to ensure you have a Series. Parameters ---------- axis : {0 or 'index', 1 or 'columns', None}, default None A specific axis to squeeze. By default, all length-1 axes are squeezed. Returns ------- DataFrame, Series, or scalar The projection after squeezing `axis` or all the axes. See Also -------- Series.iloc : Integer-location based indexing for selecting scalars. DataFrame.iloc : Integer-location based indexing for selecting Series. Series.to_frame : Inverse of DataFrame.squeeze for a single-column DataFrame. Examples -------- >>> primes = ps.Series([2, 3, 5, 7]) Slicing might produce a Series with a single value: >>> even_primes = primes[primes % 2 == 0] >>> even_primes 0 2 dtype: int64 >>> even_primes.squeeze() 2 Squeezing objects with more than one value in every axis does nothing: >>> odd_primes = primes[primes % 2 == 1] >>> odd_primes 1 3 2 5 3 7 dtype: int64 >>> odd_primes.squeeze() 1 3 2 5 3 7 dtype: int64 Squeezing is even more effective when used with DataFrames. >>> df = ps.DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) >>> df a b 0 1 2 1 3 4 Slicing a single column will produce a DataFrame with the columns having only one value: >>> df_a = df[['a']] >>> df_a a 0 1 1 3 So the columns can be squeezed down, resulting in a Series: >>> df_a.squeeze('columns') 0 1 1 3 Name: a, dtype: int64 Slicing a single row from a single column will produce a single scalar DataFrame: >>> df_1a = df.loc[[1], ['a']] >>> df_1a a 1 3 Squeezing the rows produces a single scalar Series: >>> df_1a.squeeze('rows') a 3 Name: 1, dtype: int64 Squeezing all axes will project directly into a scalar: >>> df_1a.squeeze() 3 """ if axis is not None: axis = "index" if axis == "rows" else axis axis = validate_axis(axis) if isinstance(self, ps.DataFrame): from pyspark.pandas.series import first_series is_squeezable = len(self.columns[:2]) == 1 # If DataFrame has multiple columns, there is no change. if not is_squeezable: return self series_from_column = first_series(self) has_single_value = len(series_from_column.head(2)) == 1 # If DataFrame has only a single value, use pandas API directly. if has_single_value: result = self._to_internal_pandas().squeeze(axis) return ps.Series(result) if isinstance(result, pd.Series) else result elif axis == 0: return self else: return series_from_column else: # The case of Series is simple. # If Series has only a single value, just return it as a scalar. # Otherwise, there is no change. self_top_two = cast("Series", self).head(2) has_single_value = len(self_top_two) == 1 return cast(Union[Scalar, ps.Series], self_top_two[0] if has_single_value else self) def truncate( self, before: Optional[Any] = None, after: Optional[Any] = None, axis: Optional[Axis] = None, copy: bool_type = True, ) -> DataFrameOrSeries: """ Truncate a Series or DataFrame before and after some index value. This is a useful shorthand for boolean indexing based on index values above or below certain thresholds. .. note:: This API is dependent on :meth:`Index.is_monotonic_increasing` which can be expensive. Parameters ---------- before : date, str, int Truncate all rows before this index value. after : date, str, int Truncate all rows after this index value. axis : {0 or 'index', 1 or 'columns'}, optional Axis to truncate. Truncates the index (rows) by default. copy : bool, default is True, Return a copy of the truncated section. Returns ------- type of caller The truncated Series or DataFrame. See Also -------- DataFrame.loc : Select a subset of a DataFrame by label. DataFrame.iloc : Select a subset of a DataFrame by position. Examples -------- >>> df = ps.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'], ... 'B': ['f', 'g', 'h', 'i', 'j'], ... 'C': ['k', 'l', 'm', 'n', 'o']}, ... index=[1, 2, 3, 4, 5]) >>> df A B C 1 a f k 2 b g l 3 c h m 4 d i n 5 e j o >>> df.truncate(before=2, after=4) A B C 2 b g l 3 c h m 4 d i n The columns of a DataFrame can be truncated. >>> df.truncate(before="A", after="B", axis="columns") A B 1 a f 2 b g 3 c h 4 d i 5 e j For Series, only rows can be truncated. >>> df['A'].truncate(before=2, after=4) 2 b 3 c 4 d Name: A, dtype: object A Series has index that sorted integers. >>> s = ps.Series([10, 20, 30, 40, 50, 60, 70], ... index=[1, 2, 3, 4, 5, 6, 7]) >>> s 1 10 2 20 3 30 4 40 5 50 6 60 7 70 dtype: int64 >>> s.truncate(2, 5) 2 20 3 30 4 40 5 50 dtype: int64 A Series has index that sorted strings. >>> s = ps.Series([10, 20, 30, 40, 50, 60, 70], ... index=['a', 'b', 'c', 'd', 'e', 'f', 'g']) >>> s a 10 b 20 c 30 d 40 e 50 f 60 g 70 dtype: int64 >>> s.truncate('b', 'e') b 20 c 30 d 40 e 50 dtype: int64 """ from pyspark.pandas.series import first_series axis = validate_axis(axis) indexes = self.index indexes_increasing = indexes.is_monotonic_increasing if not indexes_increasing and not indexes.is_monotonic_decreasing: raise ValueError("truncate requires a sorted index") if (before is None) and (after is None): return cast(Union[ps.DataFrame, ps.Series], self.copy() if copy else self) if (before is not None and after is not None) and before > after: raise ValueError("Truncate: %s must be after %s" % (after, before)) if isinstance(self, ps.Series): if indexes_increasing: result = first_series(self.to_frame().loc[before:after]).rename(self.name) else: result = first_series(self.to_frame().loc[after:before]).rename(self.name) elif isinstance(self, ps.DataFrame): if axis == 0: if indexes_increasing: result = self.loc[before:after] else: result = self.loc[after:before] elif axis == 1: result = self.loc[:, before:after] return cast(DataFrameOrSeries, result.copy() if copy else result) def to_markdown( self, buf: Optional[Union[IO[str], str]] = None, mode: Optional[str] = None ) -> str: """ Print Series or DataFrame in Markdown-friendly format. .. note:: This method should only be used if the resulting pandas object is expected to be small, as all the data is loaded into the driver's memory. Parameters ---------- buf : writable buffer, defaults to sys.stdout Where to send the output. By default, the output is printed to sys.stdout. Pass a writable buffer if you need to further process the output. mode : str, optional Mode in which file is opened. **kwargs These parameters will be passed to `tabulate`. Returns ------- str Series or DataFrame in Markdown-friendly format. Notes ----- Requires the `tabulate <https://pypi.org/project/tabulate>`_ package. Examples -------- >>> psser = ps.Series(["elk", "pig", "dog", "quetzal"], name="animal") >>> print(psser.to_markdown()) # doctest: +SKIP | | animal | |---:|:---------| | 0 | elk | | 1 | pig | | 2 | dog | | 3 | quetzal | >>> psdf = ps.DataFrame( ... data={"animal_1": ["elk", "pig"], "animal_2": ["dog", "quetzal"]} ... ) >>> print(psdf.to_markdown()) # doctest: +SKIP | | animal_1 | animal_2 | |---:|:-----------|:-----------| | 0 | elk | dog | | 1 | pig | quetzal | """ # `to_markdown` is supported in pandas >= 1.0.0 since it's newly added in pandas 1.0.0. if LooseVersion(pd.__version__) < LooseVersion("1.0.0"): raise NotImplementedError( "`to_markdown()` only supported in pandas-on-Spark with pandas >= 1.0.0" ) # Make sure locals() call is at the top of the function so we don't capture local variables. args = locals() psser_or_psdf = self internal_pandas = psser_or_psdf._to_internal_pandas() return validate_arguments_and_invoke_function( internal_pandas, self.to_markdown, type(internal_pandas).to_markdown, args ) @abstractmethod def fillna( self: FrameLike, value: Optional[Any] = None, method: Optional[str] = None, axis: Optional[Axis] = None, inplace: bool_type = False, limit: Optional[int] = None, ) -> FrameLike: pass # TODO: add 'downcast' when value parameter exists def bfill( self: FrameLike, axis: Optional[Axis] = None, inplace: bool_type = False, limit: Optional[int] = None, ) -> FrameLike: """ Synonym for `DataFrame.fillna()` or `Series.fillna()` with ``method=`bfill```. .. note:: the current implementation of 'bfill' uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single machine and could cause serious performance degradation. Avoid this method against very large dataset. Parameters ---------- axis : {0 or `index`} 1 and `columns` are not supported. inplace : boolean, default False Fill in place (do not create a new object) limit : int, default None If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None Returns ------- DataFrame or Series DataFrame or Series with NA entries filled. Examples -------- >>> psdf = ps.DataFrame({ ... 'A': [None, 3, None, None], ... 'B': [2, 4, None, 3], ... 'C': [None, None, None, 1], ... 'D': [0, 1, 5, 4] ... }, ... columns=['A', 'B', 'C', 'D']) >>> psdf A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 NaN NaN NaN 5 3 NaN 3.0 1.0 4 Propagate non-null values backward. >>> psdf.bfill() A B C D 0 3.0 2.0 1.0 0 1 3.0 4.0 1.0 1 2 NaN 3.0 1.0 5 3 NaN 3.0 1.0 4 For Series >>> psser = ps.Series([None, None, None, 1]) >>> psser 0 NaN 1 NaN 2 NaN 3 1.0 dtype: float64 >>> psser.bfill() 0 1.0 1 1.0 2 1.0 3 1.0 dtype: float64 """ return self.fillna(method="bfill", axis=axis, inplace=inplace, limit=limit) backfill = bfill # TODO: add 'downcast' when value parameter exists def ffill( self: FrameLike, axis: Optional[Axis] = None, inplace: bool_type = False, limit: Optional[int] = None, ) -> FrameLike: """ Synonym for `DataFrame.fillna()` or `Series.fillna()` with ``method=`ffill```. .. note:: the current implementation of 'ffill' uses Spark's Window without specifying partition specification. This leads to move all data into single partition in single machine and could cause serious performance degradation. Avoid this method against very large dataset. Parameters ---------- axis : {0 or `index`} 1 and `columns` are not supported. inplace : boolean, default False Fill in place (do not create a new object) limit : int, default None If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None Returns ------- DataFrame or Series DataFrame or Series with NA entries filled. Examples -------- >>> psdf = ps.DataFrame({ ... 'A': [None, 3, None, None], ... 'B': [2, 4, None, 3], ... 'C': [None, None, None, 1], ... 'D': [0, 1, 5, 4] ... }, ... columns=['A', 'B', 'C', 'D']) >>> psdf A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 NaN NaN NaN 5 3 NaN 3.0 1.0 4 Propagate non-null values forward. >>> psdf.ffill() A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 3.0 4.0 NaN 5 3 3.0 3.0 1.0 4 For Series >>> psser = ps.Series([2, 4, None, 3]) >>> psser 0 2.0 1 4.0 2 NaN 3 3.0 dtype: float64 >>> psser.ffill() 0 2.0 1 4.0 2 4.0 3 3.0 dtype: float64 """ return self.fillna(method="ffill", axis=axis, inplace=inplace, limit=limit) pad = ffill @property def at(self) -> AtIndexer: return AtIndexer(self) # type: ignore at.__doc__ = AtIndexer.__doc__ @property def iat(self) -> iAtIndexer: return iAtIndexer(self) # type: ignore iat.__doc__ = iAtIndexer.__doc__ @property def iloc(self) -> iLocIndexer: return iLocIndexer(self) # type: ignore iloc.__doc__ = iLocIndexer.__doc__ @property def loc(self) -> LocIndexer: return LocIndexer(self) # type: ignore loc.__doc__ = LocIndexer.__doc__ def __bool__(self) -> NoReturn: raise ValueError( "The truth value of a {0} is ambiguous. " "Use a.empty, a.bool(), a.item(), a.any() or a.all().".format(self.__class__.__name__) ) @staticmethod def _count_expr(spark_column: Column, spark_type: DataType) -> Column: # Special handle floating point types because Spark's count treats nan as a valid value, # whereas pandas count doesn't include nan. if isinstance(spark_type, (FloatType, DoubleType)): return F.count(F.nanvl(spark_column, SF.lit(None))) else: return F.count(spark_column) def _test() -> None: import os import doctest import shutil import sys import tempfile from pyspark.sql import SparkSession import pyspark.pandas.generic os.chdir(os.environ["SPARK_HOME"]) globs = pyspark.pandas.generic.__dict__.copy() globs["ps"] = pyspark.pandas spark = ( SparkSession.builder.master("local[4]") .appName("pyspark.pandas.generic tests") .getOrCreate() ) path = tempfile.mkdtemp() globs["path"] = path (failure_count, test_count) = doctest.testmod( pyspark.pandas.generic, globs=globs, optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE, ) shutil.rmtree(path, ignore_errors=True) spark.stop() if failure_count: sys.exit(-1) if __name__ == "__main__": _test()
apache-2.0
lenovor/scikit-learn
sklearn/metrics/pairwise.py
104
42995
# -*- coding: utf-8 -*- # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Mathieu Blondel <mathieu@mblondel.org> # Robert Layton <robertlayton@gmail.com> # Andreas Mueller <amueller@ais.uni-bonn.de> # Philippe Gervais <philippe.gervais@inria.fr> # Lars Buitinck <larsmans@gmail.com> # Joel Nothman <joel.nothman@gmail.com> # License: BSD 3 clause import itertools import numpy as np from scipy.spatial import distance from scipy.sparse import csr_matrix from scipy.sparse import issparse from ..utils import check_array from ..utils import gen_even_slices from ..utils import gen_batches from ..utils.fixes import partial from ..utils.extmath import row_norms, safe_sparse_dot 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, _sparse_manhattan # Utility Functions def _return_float_dtype(X, Y): """ 1. If dtype of X and Y is float32, then dtype float32 is returned. 2. Else dtype float is returned. """ if not issparse(X) and not isinstance(X, np.ndarray): X = np.asarray(X) if Y is None: Y_dtype = X.dtype elif not issparse(Y) and not isinstance(Y, np.ndarray): Y = np.asarray(Y) Y_dtype = Y.dtype else: Y_dtype = Y.dtype if X.dtype == Y_dtype == np.float32: dtype = np.float32 else: dtype = np.float return X, Y, dtype 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, guaranteed 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, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ X, Y, dtype = _return_float_dtype(X, Y) if Y is X or Y is None: X = Y = check_array(X, accept_sparse='csr', dtype=dtype) else: X = check_array(X, accept_sparse='csr', dtype=dtype) Y = check_array(Y, accept_sparse='csr', dtype=dtype) 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 def check_paired_arrays(X, Y): """ Set X and Y appropriately and checks inputs for paired distances All paired 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 dimensions of the two arrays are 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, guaranteed 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, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ X, Y = check_pairwise_arrays(X, Y) if X.shape != Y.shape: raise ValueError("X and Y should be of same shape. They were " "respectively %r and %r long." % (X.shape, Y.shape)) return X, Y # Pairwise 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 advantages over other ways of computing distances. 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. However, this is not the most precise way of doing this computation, and the distance matrix returned by this function may not be exactly symmetric as required by, e.g., ``scipy.spatial.distance`` functions. Read more in the :ref:`User Guide <metrics>`. 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]]) See also -------- paired_distances : distances betweens pairs of elements of X and Y. """ # 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 Y_norm_squared is not None: YY = check_array(Y_norm_squared) if YY.shape != (1, Y.shape[0]): raise ValueError( "Incompatible dimensions for Y and Y_norm_squared") else: YY = row_norms(Y, squared=True)[np.newaxis, :] if X is Y: # shortcut in the common case euclidean_distances(X, X) XX = YY.T else: XX = row_norms(X, squared=True)[:, np.newaxis] distances = safe_sparse_dot(X, Y.T, dense_output=True) distances *= -2 distances += XX distances += YY np.maximum(distances, 0, out=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, out=distances) def pairwise_distances_argmin_min(X, Y, axis=1, metric="euclidean", batch_size=500, metric_kwargs=None): """Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). The minimal distances are also returned. This is mostly equivalent to calling: (pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis), pairwise_distances(X, Y=Y, metric=metric).min(axis=axis)) but uses much less memory, and is faster for large arrays. Parameters ---------- X, Y : {array-like, sparse matrix} Arrays containing points. Respective shapes (n_samples1, n_features) and (n_samples2, n_features) batch_size : integer To reduce memory consumption over the naive solution, data are processed in batches, comprising batch_size rows of X and batch_size rows of Y. The default value is quite conservative, but can be changed for fine-tuning. The larger the number, the larger the memory usage. metric : string or callable, default 'euclidean' metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. 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 as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', '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. metric_kwargs : dict, optional Keyword arguments to pass to specified metric function. axis : int, optional, default 1 Axis along which the argmin and distances are to be computed. Returns ------- argmin : numpy.ndarray Y[argmin[i], :] is the row in Y that is closest to X[i, :]. distances : numpy.ndarray distances[i] is the distance between the i-th row in X and the argmin[i]-th row in Y. See also -------- sklearn.metrics.pairwise_distances sklearn.metrics.pairwise_distances_argmin """ dist_func = None if metric in PAIRWISE_DISTANCE_FUNCTIONS: dist_func = PAIRWISE_DISTANCE_FUNCTIONS[metric] elif not callable(metric) and not isinstance(metric, str): raise ValueError("'metric' must be a string or a callable") X, Y = check_pairwise_arrays(X, Y) if metric_kwargs is None: metric_kwargs = {} if axis == 0: X, Y = Y, X # Allocate output arrays indices = np.empty(X.shape[0], dtype=np.intp) values = np.empty(X.shape[0]) values.fill(np.infty) for chunk_x in gen_batches(X.shape[0], batch_size): X_chunk = X[chunk_x, :] for chunk_y in gen_batches(Y.shape[0], batch_size): Y_chunk = Y[chunk_y, :] if dist_func is not None: if metric == 'euclidean': # special case, for speed d_chunk = safe_sparse_dot(X_chunk, Y_chunk.T, dense_output=True) d_chunk *= -2 d_chunk += row_norms(X_chunk, squared=True)[:, np.newaxis] d_chunk += row_norms(Y_chunk, squared=True)[np.newaxis, :] np.maximum(d_chunk, 0, d_chunk) else: d_chunk = dist_func(X_chunk, Y_chunk, **metric_kwargs) else: d_chunk = pairwise_distances(X_chunk, Y_chunk, metric=metric, **metric_kwargs) # Update indices and minimum values using chunk min_indices = d_chunk.argmin(axis=1) min_values = d_chunk[np.arange(chunk_x.stop - chunk_x.start), min_indices] flags = values[chunk_x] > min_values indices[chunk_x][flags] = min_indices[flags] + chunk_y.start values[chunk_x][flags] = min_values[flags] if metric == "euclidean" and not metric_kwargs.get("squared", False): np.sqrt(values, values) return indices, values def pairwise_distances_argmin(X, Y, axis=1, metric="euclidean", batch_size=500, metric_kwargs=None): """Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). This is mostly equivalent to calling: pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis) but uses much less memory, and is faster for large arrays. This function works with dense 2D arrays only. Parameters ---------- X : array-like Arrays containing points. Respective shapes (n_samples1, n_features) and (n_samples2, n_features) Y : array-like Arrays containing points. Respective shapes (n_samples1, n_features) and (n_samples2, n_features) batch_size : integer To reduce memory consumption over the naive solution, data are processed in batches, comprising batch_size rows of X and batch_size rows of Y. The default value is quite conservative, but can be changed for fine-tuning. The larger the number, the larger the memory usage. metric : string or callable metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. 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 as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', '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. metric_kwargs : dict keyword arguments to pass to specified metric function. axis : int, optional, default 1 Axis along which the argmin and distances are to be computed. Returns ------- argmin : numpy.ndarray Y[argmin[i], :] is the row in Y that is closest to X[i, :]. See also -------- sklearn.metrics.pairwise_distances sklearn.metrics.pairwise_distances_argmin_min """ if metric_kwargs is None: metric_kwargs = {} return pairwise_distances_argmin_min(X, Y, axis, metric, batch_size, metric_kwargs)[0] def manhattan_distances(X, Y=None, sum_over_features=True, size_threshold=5e8): """ Compute the L1 distances between the vectors in X and Y. With sum_over_features equal to False it returns the componentwise distances. Read more in the :ref:`User Guide <metrics>`. 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. Not supported for sparse matrix inputs. size_threshold : int, default=5e8 Unused parameter. 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.]]...) """ X, Y = check_pairwise_arrays(X, Y) if issparse(X) or issparse(Y): if not sum_over_features: raise TypeError("sum_over_features=%r not supported" " for sparse matrices" % sum_over_features) X = csr_matrix(X, copy=False) Y = csr_matrix(Y, copy=False) D = np.zeros((X.shape[0], Y.shape[0])) _sparse_manhattan(X.data, X.indices, X.indptr, Y.data, Y.indices, Y.indptr, X.shape[1], D) return D if sum_over_features: return distance.cdist(X, Y, 'cityblock') D = X[:, np.newaxis, :] - Y[np.newaxis, :, :] D = np.abs(D, D) return D.reshape((-1, X.shape[1])) def cosine_distances(X, Y=None): """ Compute cosine distance between samples in X and Y. Cosine distance is defined as 1.0 minus the cosine similarity. Read more in the :ref:`User Guide <metrics>`. 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 ------- distance matrix : array An array with shape (n_samples_X, n_samples_Y). See also -------- sklearn.metrics.pairwise.cosine_similarity scipy.spatial.distance.cosine (dense matrices only) """ # 1.0 - cosine_similarity(X, Y) without copy S = cosine_similarity(X, Y) S *= -1 S += 1 return S # Paired distances def paired_euclidean_distances(X, Y): """ Computes the paired euclidean distances between X and Y Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : array-like, shape (n_samples, n_features) Y : array-like, shape (n_samples, n_features) Returns ------- distances : ndarray (n_samples, ) """ X, Y = check_paired_arrays(X, Y) return row_norms(X - Y) def paired_manhattan_distances(X, Y): """Compute the L1 distances between the vectors in X and Y. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : array-like, shape (n_samples, n_features) Y : array-like, shape (n_samples, n_features) Returns ------- distances : ndarray (n_samples, ) """ X, Y = check_paired_arrays(X, Y) diff = X - Y if issparse(diff): diff.data = np.abs(diff.data) return np.squeeze(np.array(diff.sum(axis=1))) else: return np.abs(diff).sum(axis=-1) def paired_cosine_distances(X, Y): """ Computes the paired cosine distances between X and Y Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : array-like, shape (n_samples, n_features) Y : array-like, shape (n_samples, n_features) Returns ------- distances : ndarray, shape (n_samples, ) Notes ------ The cosine distance is equivalent to the half the squared euclidean distance if each sample is normalized to unit norm """ X, Y = check_paired_arrays(X, Y) return .5 * row_norms(normalize(X) - normalize(Y), squared=True) PAIRED_DISTANCES = { 'cosine': paired_cosine_distances, 'euclidean': paired_euclidean_distances, 'l2': paired_euclidean_distances, 'l1': paired_manhattan_distances, 'manhattan': paired_manhattan_distances, 'cityblock': paired_manhattan_distances} def paired_distances(X, Y, metric="euclidean", **kwds): """ Computes the paired distances between X and Y. Computes the distances between (X[0], Y[0]), (X[1], Y[1]), etc... Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : ndarray (n_samples, n_features) Array 1 for distance computation. Y : ndarray (n_samples, n_features) Array 2 for distance computation. 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 specified in PAIRED_DISTANCES, including "euclidean", "manhattan", or "cosine". 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. Returns ------- distances : ndarray (n_samples, ) Examples -------- >>> from sklearn.metrics.pairwise import paired_distances >>> X = [[0, 1], [1, 1]] >>> Y = [[0, 1], [2, 1]] >>> paired_distances(X, Y) array([ 0., 1.]) See also -------- pairwise_distances : pairwise distances. """ if metric in PAIRED_DISTANCES: func = PAIRED_DISTANCES[metric] return func(X, Y) elif callable(metric): # Check the matrix first (it is usually done by the metric) X, Y = check_paired_arrays(X, Y) distances = np.zeros(len(X)) for i in range(len(X)): distances[i] = metric(X[i], Y[i]) return distances else: raise ValueError('Unknown distance %s' % metric) # Kernels def linear_kernel(X, Y=None): """ Compute the linear kernel between X and Y. Read more in the :ref:`User Guide <linear_kernel>`. 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 Read more in the :ref:`User Guide <polynomial_kernel>`. Parameters ---------- X : ndarray of shape (n_samples_1, n_features) Y : ndarray of shape (n_samples_2, n_features) coef0 : int, default 1 degree : int, default 3 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 = safe_sparse_dot(X, Y.T, dense_output=True) 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) Read more in the :ref:`User Guide <sigmoid_kernel>`. Parameters ---------- X : ndarray of shape (n_samples_1, n_features) Y : ndarray of shape (n_samples_2, n_features) coef0 : int, default 1 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 = safe_sparse_dot(X, Y.T, dense_output=True) 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(-gamma ||x-y||^2) for each pair of rows x in X and y in Y. Read more in the :ref:`User Guide <rbf_kernel>`. 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, dense_output=True): """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. Read more in the :ref:`User Guide <cosine_similarity>`. Parameters ---------- X : ndarray or sparse array, shape: (n_samples_X, n_features) Input data. Y : ndarray or sparse array, shape: (n_samples_Y, n_features) Input data. If ``None``, the output will be the pairwise similarities between all samples in ``X``. dense_output : boolean (optional), default True Whether to return dense output even when the input is sparse. If ``False``, the output is sparse if both input arrays are sparse. Returns ------- kernel matrix : array 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 = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=dense_output) 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) = -Sum [(x - y)^2 / (x + y)] It can be interpreted as a weighted difference per entry. Read more in the :ref:`User Guide <chi2_kernel>`. 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 preferable. 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.") X, Y = check_pairwise_arrays(X, Y) if (X < 0).any(): raise ValueError("X contains negative values.") if Y is not X and (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(-gamma Sum [(x - y)^2 / (x + y)]) It can be interpreted as a weighted difference per entry. Read more in the :ref:`User Guide <chi2_kernel>`. 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()! 'cityblock': manhattan_distances, 'cosine': cosine_distances, 'euclidean': euclidean_distances, 'l2': euclidean_distances, 'l1': manhattan_distances, 'manhattan': 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 'cosine' metrics.pairwise.cosine_distances 'euclidean' metrics.pairwise.euclidean_distances 'l1' metrics.pairwise.manhattan_distances 'l2' metrics.pairwise.euclidean_distances 'manhattan' metrics.pairwise.manhattan_distances ============ ==================================== Read more in the :ref:`User Guide <metrics>`. """ 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 if n_jobs == 1: # Special case to avoid picklability checks in delayed return func(X, Y, **kwds) # TODO: in some cases, backend='threading' may be appropriate fd = delayed(func) ret = Parallel(n_jobs=n_jobs, verbose=0)( fd(X, Y[s], **kwds) for s in gen_even_slices(Y.shape[0], n_jobs)) return np.hstack(ret) def _pairwise_callable(X, Y, metric, **kwds): """Handle the callable case for pairwise_{distances,kernels} """ X, Y = check_pairwise_arrays(X, Y) if X is Y: # Only calculate metric for upper triangle out = np.zeros((X.shape[0], Y.shape[0]), dtype='float') iterator = itertools.combinations(range(X.shape[0]), 2) for i, j in iterator: out[i, j] = metric(X[i], Y[j], **kwds) # Make symmetric # NB: out += out.T will produce incorrect results out = out + out.T # Calculate diagonal # NB: nonzero diagonals are allowed for both metrics and kernels for i in range(X.shape[0]): x = X[i] out[i, i] = metric(x, x, **kwds) else: # Calculate all cells out = np.empty((X.shape[0], Y.shape[0]), dtype='float') iterator = itertools.product(range(X.shape[0]), range(Y.shape[0])) for i, j in iterator: out[i, j] = metric(X[i], Y[j], **kwds) return out _VALID_METRICS = ['euclidean', 'l2', 'l1', 'manhattan', 'cityblock', 'braycurtis', 'canberra', 'chebyshev', 'correlation', 'cosine', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule', "wminkowski"] 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 compatibility 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. Valid values for metric are: - From scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan']. These metrics support sparse matrix inputs. - From scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', '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. These metrics do not support sparse matrix inputs. Note that in the case of 'cityblock', 'cosine' and 'euclidean' (which are valid scipy.spatial.distance metrics), the scikit-learn implementation will be used, which is faster and has support for sparse matrices (except for 'cityblock'). For a verbose description of the metrics from scikit-learn, see the __doc__ of the sklearn.pairwise.distance_metrics function. Read more in the :ref:`User Guide <metrics>`. 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], optional An optional second feature array. Only allowed if metric != "precomputed". 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 debugging. 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 not in _VALID_METRICS and not callable(metric) and metric != "precomputed"): raise ValueError("Unknown metric %s. " "Valid metrics are %s, or 'precomputed', or a " "callable" % (metric, _VALID_METRICS)) if metric == "precomputed": return X elif metric in PAIRWISE_DISTANCE_FUNCTIONS: func = PAIRWISE_DISTANCE_FUNCTIONS[metric] elif callable(metric): func = partial(_pairwise_callable, metric=metric, **kwds) else: if issparse(X) or issparse(Y): raise TypeError("scipy distance metrics do not" " support sparse matrices.") X, Y = check_pairwise_arrays(X, Y) if n_jobs == 1 and X is Y: return distance.squareform(distance.pdist(X, metric=metric, **kwds)) func = partial(distance.cdist, metric=metric, **kwds) return _parallel_pairwise(X, Y, func, n_jobs, **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 =============== ======================================== Read more in the :ref:`User Guide <metrics>`. """ return PAIRWISE_KERNEL_FUNCTIONS KERNEL_PARAMS = { "additive_chi2": (), "chi2": (), "cosine": (), "exp_chi2": frozenset(["gamma"]), "linear": (), "poly": frozenset(["gamma", "degree", "coef0"]), "polynomial": frozenset(["gamma", "degree", "coef0"]), "rbf": frozenset(["gamma"]), "sigmoid": frozenset(["gamma", "coef0"]), } 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 compatibility 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'] Read more in the :ref:`User Guide <metrics>`. 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 debugging. 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] elif callable(metric): func = partial(_pairwise_callable, metric=metric, **kwds) else: raise ValueError("Unknown kernel %r" % metric) return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
bsd-3-clause
justincassidy/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
dls-controls/pymalcolm
malcolm/modules/pandablocks/controllers/pandablockcontroller.py
1
13688
import os from typing import Any, Dict, Optional, Union, cast from annotypes import Anno from malcolm.core import ( Alarm, AMri, BooleanMeta, ChoiceMeta, NumberMeta, Port, StringMeta, TableMeta, TimeStamp, VMeta, Widget, badge_value_tag, config_tag, group_tag, linked_value_tag, snake_to_camel, without_linked_value_tags, ) from malcolm.modules import builtin from ..pandablocksclient import BlockData, FieldData from ..parts.pandaactionpart import PandAActionPart from ..parts.pandafieldpart import PandAFieldPart from ..parts.pandaiconpart import PandAIconPart from ..parts.pandalabelpart import PandALabelPart from ..parts.pandaluticonpart import PandALutIconPart from ..parts.pandapulseiconpart import PandAPulseIconPart from ..parts.pandasrgateiconpart import PandASRGateIconPart from ..parts.pandatablepart import PandATablePart from ..util import SVG_DIR, ABlockName, AClient, ADocUrlBase ChangeHandler = Union[PandAFieldPart, PandALabelPart] with Anno("Prefix to put on the beginning of the Block Name to make MRI"): AMriPrefix = str with Anno("The BlockData object showing the fields of the Block"): ABlockData = BlockData # Pull re-used annotypes into our namespace in case we are subclassed AClient = AClient ADocUrlBase = ADocUrlBase ABlockName = ABlockName def make_meta(subtyp, description, tags, writeable=True, labels=None): if subtyp == "enum": meta = ChoiceMeta(description, labels) elif subtyp == "bit": meta = BooleanMeta(description) elif subtyp in ("uint", ""): meta = NumberMeta("uint32", description) elif subtyp in ("int", "pos"): meta = NumberMeta("int32", description) elif subtyp == "scalar": meta = NumberMeta("float64", description) elif subtyp == "lut": meta = StringMeta(description) else: raise ValueError("Unknown subtype %r" % subtyp) meta.set_writeable(writeable) tags.append(meta.default_widget().tag()) meta.set_tags(tags) return meta class PandABlockController(builtin.controllers.BasicController): def __init__( self, client: AClient, mri_prefix: AMri, block_name: ABlockName, block_data: ABlockData, doc_url_base: ADocUrlBase, ) -> None: super().__init__(mri="%s:%s" % (mri_prefix, block_name)) # Store self.client = client self.mri_prefix = mri_prefix self.block_name = block_name self.block_data = block_data self.doc_url_base = doc_url_base # {field_name: part} self.field_parts: Dict[str, Optional[ChangeHandler]] = {} # {field_name: attr.meta} self.mux_metas: Dict[str, VMeta] = {} # Make an icon, label and help for the Block self.icon_part: PandAIconPart = self._make_common_parts() # Create parts for each field for field_name, field_data in block_data.fields.items(): self._make_parts_for(field_name, field_data) def handle_changes(self, changes: Dict[str, Any], ts: TimeStamp) -> None: with self.changes_squashed: icon_needs_update = False if isinstance(changes, Dict): for k, v in changes.items(): # Health changes are for us if k.upper() == "HEALTH": if v.upper() == "OK": alarm = Alarm.ok else: alarm = Alarm.major(v) self.update_health( self, builtin.infos.HealthInfo(cast(Alarm, alarm), ts) ) continue # Work out if there is a part we need to notify try: part = self.field_parts[k] except KeyError: self.log.exception(f"Can't handle field {self.block_name}.{k}") part = None if part is None: continue part.handle_change(v, ts) if not icon_needs_update: icon_needs_update = k in self.icon_part.update_fields try: mux_meta = self.mux_metas[k] except KeyError: pass else: self._handle_mux_update(mux_meta, v) if icon_needs_update: d = {} for key in self.icon_part.update_fields: if key in self.field_parts: field_part = self.field_parts[key] if field_part: d[key] = field_part.attr.value icon = builtin.util.SVGIcon(self.icon_part.svg_text) self.icon_part.update_icon(icon, d) self.icon_part.attr.set_value(str(icon), ts=ts) def _handle_mux_update(self, mux_meta, v): # Mux changed its value, update its link to a different # Attribute tags = without_linked_value_tags(mux_meta.tags) split = v.split(".") if len(split) == 2: block_name, field_name = split attr_name = snake_to_camel(field_name.replace(".", "_")) block_mri = "%s:%s" % (self.mri_prefix, block_name) tags.append(linked_value_tag(block_mri, attr_name)) mux_meta.set_tags(tags) def _make_common_parts(self) -> PandAIconPart: block_type = self.block_name.rstrip("0123456789") block_number = self.block_name[len(block_type) :] svg_path = os.path.join(SVG_DIR, block_type + ".svg") if block_type == "LUT": icon_cls = PandALutIconPart elif block_type in ("PULSE", "PCAP"): icon_cls = PandAPulseIconPart elif block_type == "SRGATE": icon_cls = PandASRGateIconPart else: icon_cls = PandAIconPart icon_part = icon_cls(self.client, self.block_name, svg_path) self.add_part(icon_part) label = self.block_data.description metadata_field = "LABEL_%s" % self.block_name if block_number: # If we have multiple blocks, make the labels unique label += " %s" % block_number else: # If we only have one block, the metadata field still has numbers metadata_field += "1" label_part = PandALabelPart(self.client, metadata_field, value=label) self.add_part(label_part) self.field_parts["LABEL"] = label_part self.add_part( builtin.parts.HelpPart( "%s/build/%s_doc.html" % (self.doc_url_base, block_type.lower()) ) ) return icon_part def _make_parts_for(self, field_name, field_data): """Create the relevant parts for this field Args: field_name (str): Short field name, e.g. VAL field_data (FieldData): Field data object """ if field_name.upper() == "HEALTH": # Ignore health, as we already have a health field return typ = field_data.field_type subtyp = field_data.field_subtype if typ == "read": writeable = False else: writeable = True if typ == "time" or typ in ("param", "read") and subtyp == "time": self._make_time(field_name, field_data, writeable) elif typ == "write" and subtyp == "action": self._make_action(field_name, field_data) elif typ in ("param", "read", "write"): self._make_param(field_name, field_data, writeable) elif typ == "bit_out": self._make_out(field_name, field_data, "bit") elif typ == "pos_out": self._make_out(field_name, field_data, "pos") # Some attributes are handled by the top level busses table # so mark as present but ignored for suffix in ("CAPTURE", "UNITS", "SCALE", "OFFSET", "DATA_DELAY"): self.field_parts["%s.%s" % (field_name, suffix)] = None elif typ == "ext_out": if subtyp == "bits": # Bits is handled by the top level table, so mark it as being # present, but ignored self.field_parts[field_name + ".CAPTURE"] = None else: self._make_ext_capture(field_name, field_data) elif typ == "bit_mux": self._make_mux(field_name, field_data, Port.BOOL) self._make_mux_delay(field_name) elif typ == "pos_mux": self._make_mux(field_name, field_data, Port.INT32) elif typ == "table": self._make_table(field_name, field_data) else: raise ValueError("Unknown type %r subtype %r" % (typ, subtyp)) def _make_group(self, attr_name: str) -> str: if attr_name not in self.parts: self.add_part( builtin.parts.GroupPart(attr_name, "All %s attributes" % attr_name) ) group = group_tag(attr_name) return group def _make_field_part( self, field_name, meta, writeable, initial_value=None, iteration=1 ): if writeable: meta.set_tags(list(meta.tags) + [config_tag(iteration)]) meta.set_writeable(True) part = PandAFieldPart( self.client, meta, self.block_name, field_name, initial_value ) self.add_part(part) self.field_parts[field_name] = part def _make_time( self, field_name: str, field_data: FieldData, writeable: bool ) -> None: description = field_data.description if writeable: widget = Widget.TEXTINPUT group = self._make_group("parameters") else: widget = Widget.TEXTUPDATE group = self._make_group("readbacks") meta = NumberMeta("float64", description, [group, widget.tag()]) # We must change time units before value, so restore value in 2nd # iteration self._make_field_part(field_name, meta, writeable, iteration=2) meta = ChoiceMeta( description + " time units", ["s", "ms", "us"], tags=[group, Widget.COMBO.tag()], ) self._make_field_part(field_name + ".UNITS", meta, writeable=True) def _make_action(self, field_name: str, field_data: FieldData) -> None: group = self._make_group("parameters") self.add_part( PandAActionPart( self.client, self.block_name, field_name, field_data.description, [group], ) ) def _make_param( self, field_name: str, field_data: FieldData, writeable: bool ) -> None: if writeable: group = self._make_group("parameters") else: group = self._make_group("readbacks") meta = make_meta( field_data.field_subtype, field_data.description, [group], writeable, field_data.labels, ) self._make_field_part(field_name, meta, writeable) def _make_out(self, field_name: str, field_data: FieldData, typ: str) -> None: group = self._make_group("outputs") if typ == "bit": port_type = Port.BOOL else: port_type = Port.INT32 flow_tag = port_type.source_port_tag("%s.%s" % (self.block_name, field_name)) meta = make_meta( typ, field_data.description, tags=[group, flow_tag], writeable=False ) self._make_field_part(field_name, meta, writeable=False) def _make_ext_capture(self, field_name: str, field_data: FieldData) -> None: group = self._make_group("outputs") meta = ChoiceMeta( "Capture %s in PCAP?" % field_name, field_data.labels, tags=[group, Widget.COMBO.tag()], ) self._make_field_part(field_name + ".CAPTURE", meta, writeable=True) def _make_mux( self, field_name: str, field_data: FieldData, port_type: Port ) -> None: group = self._make_group("inputs") labels = [x for x in field_data.labels if x in ("ZERO", "ONE")] + sorted( x for x in field_data.labels if x not in ("ZERO", "ONE") ) tags = [group, port_type.sink_port_tag("ZERO"), Widget.COMBO.tag()] if port_type == Port.BOOL: # Bits have a delay, use it as a badge delay_name = snake_to_camel(field_name) + "Delay" tags.append(badge_value_tag(self.mri, delay_name)) meta = ChoiceMeta(field_data.description, labels, tags=tags) self._make_field_part(field_name, meta, writeable=True) self.mux_metas[field_name] = meta def _make_mux_delay(self, field_name: str) -> None: group = self._make_group("inputs") meta = NumberMeta( "uint8", "How many FPGA ticks to delay input", tags=[group, Widget.TEXTINPUT.tag()], ) self._make_field_part(field_name + ".DELAY", meta, writeable=True) def _make_table(self, field_name: str, field_data: FieldData) -> None: group = self._make_group("parameters") tags = [Widget.TABLE.tag(), group, config_tag()] meta = TableMeta(field_data.description, tags, writeable=True) part = PandATablePart(self.client, meta, self.block_name, field_name) self.add_part(part) self.field_parts[field_name] = part
apache-2.0
466152112/hyperopt
hyperopt/tests/test_tpe.py
7
23399
from functools import partial import os import unittest import nose import numpy as np try: import matplotlib.pyplot as plt except ImportError: pass from hyperopt import pyll from hyperopt.pyll import scope from hyperopt import Trials from hyperopt.base import miscs_to_idxs_vals, STATUS_OK from hyperopt import hp from hyperopt.tpe import adaptive_parzen_normal_orig from hyperopt.tpe import GMM1 from hyperopt.tpe import GMM1_lpdf from hyperopt.tpe import LGMM1 from hyperopt.tpe import LGMM1_lpdf import hyperopt.rand as rand import hyperopt.tpe as tpe from hyperopt import fmin from test_domains import ( domain_constructor, CasePerDomain) DO_SHOW = int(os.getenv('HYPEROPT_SHOW', '0')) def passthrough(x): return x def test_adaptive_parzen_normal_orig(): rng = np.random.RandomState(123) prior_mu = 7 prior_sigma = 2 mus = rng.randn(10) + 5 weights2, mus2, sigmas2 = adaptive_parzen_normal_orig( mus, 3.3, prior_mu, prior_sigma) print weights2 print mus2 print sigmas2 assert len(weights2) == len(mus2) == len(sigmas2) == 11 assert np.all(weights2[0] > weights2[1:]) assert mus2[0] == 7 assert np.all(mus2[1:] == mus) assert sigmas2[0] == 2 class TestGMM1(unittest.TestCase): def setUp(self): self.rng = np.random.RandomState(234) def test_mu_is_used_correctly(self): assert np.allclose(10, GMM1([1], [10.0], [0.0000001], rng=self.rng)) def test_sigma_is_used_correctly(self): samples = GMM1([1], [0.0], [10.0], size=[1000], rng=self.rng) assert 9 < np.std(samples) < 11 def test_mus_make_variance(self): samples = GMM1([.5, .5], [0.0, 1.0], [0.000001, 0.000001], rng=self.rng, size=[1000]) print samples.shape #import matplotlib.pyplot as plt #plt.hist(samples) #plt.show() assert .45 < np.mean(samples) < .55, np.mean(samples) assert .2 < np.var(samples) < .3, np.var(samples) def test_weights(self): samples = GMM1([.9999, .0001], [0.0, 1.0], [0.000001, 0.000001], rng=self.rng, size=[1000]) assert samples.shape == (1000,) #import matplotlib.pyplot as plt #plt.hist(samples) #plt.show() assert -.001 < np.mean(samples) < .001, np.mean(samples) assert np.var(samples) < .0001, np.var(samples) def test_mat_output(self): samples = GMM1([.9999, .0001], [0.0, 1.0], [0.000001, 0.000001], rng=self.rng, size=[40, 20]) assert samples.shape == (40, 20) assert -.001 < np.mean(samples) < .001, np.mean(samples) assert np.var(samples) < .0001, np.var(samples) def test_lpdf_scalar_one_component(self): llval = GMM1_lpdf(1.0, # x [1.], # weights [1.0], # mu [2.0], # sigma ) assert llval.shape == () assert np.allclose(llval, np.log(1.0 / np.sqrt(2 * np.pi * 2.0 ** 2))) def test_lpdf_scalar_N_components(self): llval = GMM1_lpdf(1.0, # x [0.25, 0.25, .5], # weights [0.0, 1.0, 2.0], # mu [1.0, 2.0, 5.0], # sigma ) a = (.25 / np.sqrt(2 * np.pi * 1.0 ** 2) * np.exp(-.5 * (1.0) ** 2)) a += (.25 / np.sqrt(2 * np.pi * 2.0 ** 2)) a += (.5 / np.sqrt(2 * np.pi * 5.0 ** 2) * np.exp(-.5 * (1.0 / 5.0) ** 2)) def test_lpdf_vector_N_components(self): llval = GMM1_lpdf([1.0, 0.0], # x [0.25, 0.25, .5], # weights [0.0, 1.0, 2.0], # mu [1.0, 2.0, 5.0], # sigma ) # case x = 1.0 a = (.25 / np.sqrt(2 * np.pi * 1.0 ** 2) * np.exp(-.5 * (1.0) ** 2)) a += (.25 / np.sqrt(2 * np.pi * 2.0 ** 2)) a += (.5 / np.sqrt(2 * np.pi * 5.0 ** 2) * np.exp(-.5 * (1.0 / 5.0) ** 2)) assert llval.shape == (2,) assert np.allclose(llval[0], np.log(a)) # case x = 0.0 a = (.25 / np.sqrt(2 * np.pi * 1.0 ** 2)) a += (.25 / np.sqrt(2 * np.pi * 2.0 ** 2) * np.exp(-.5 * (1.0 / 2.0) ** 2)) a += (.5 / np.sqrt(2 * np.pi * 5.0 ** 2) * np.exp(-.5 * (2.0 / 5.0) ** 2)) assert np.allclose(llval[1], np.log(a)) def test_lpdf_matrix_N_components(self): llval = GMM1_lpdf( [ [1.0, 0.0, 0.0], [0, 0, 1], [0, 0, 1000], ], [0.25, 0.25, .5], # weights [0.0, 1.0, 2.0], # mu [1.0, 2.0, 5.0], # sigma ) print llval assert llval.shape == (3, 3) a = (.25 / np.sqrt(2 * np.pi * 1.0 ** 2) * np.exp(-.5 * (1.0) ** 2)) a += (.25 / np.sqrt(2 * np.pi * 2.0 ** 2)) a += (.5 / np.sqrt(2 * np.pi * 5.0 ** 2) * np.exp(-.5 * (1.0 / 5.0) ** 2)) assert np.allclose(llval[0, 0], np.log(a)) assert np.allclose(llval[1, 2], np.log(a)) # case x = 0.0 a = (.25 / np.sqrt(2 * np.pi * 1.0 ** 2)) a += (.25 / np.sqrt(2 * np.pi * 2.0 ** 2) * np.exp(-.5 * (1.0 / 2.0) ** 2)) a += (.5 / np.sqrt(2 * np.pi * 5.0 ** 2) * np.exp(-.5 * (2.0 / 5.0) ** 2)) assert np.allclose(llval[0, 1], np.log(a)) assert np.allclose(llval[0, 2], np.log(a)) assert np.allclose(llval[1, 0], np.log(a)) assert np.allclose(llval[1, 1], np.log(a)) assert np.allclose(llval[2, 0], np.log(a)) assert np.allclose(llval[2, 1], np.log(a)) assert np.isfinite(llval[2, 2]) class TestGMM1Math(unittest.TestCase): def setUp(self): self.rng = np.random.RandomState(234) self.weights = [.1, .3, .4, .2] self.mus = [1.0, 2.0, 3.0, 4.0] self.sigmas = [.1, .4, .8, 2.0] self.q = None self.low = None self.high = None self.n_samples = 10001 self.samples_per_bin = 500 self.show = False # -- triggers error if test case forgets to call work() self.worked = False def tearDown(self): assert self.worked def work(self): self.worked = True kwargs = dict( weights=self.weights, mus=self.mus, sigmas=self.sigmas, low=self.low, high=self.high, q=self.q, ) samples = GMM1(rng=self.rng, size=(self.n_samples,), **kwargs) samples = np.sort(samples) edges = samples[::self.samples_per_bin] #print samples pdf = np.exp(GMM1_lpdf(edges[:-1], **kwargs)) dx = edges[1:] - edges[:-1] y = 1 / dx / len(dx) if self.show: plt.scatter(edges[:-1], y) plt.plot(edges[:-1], pdf) plt.show() err = (pdf - y) ** 2 print np.max(err) print np.mean(err) print np.median(err) if not self.show: assert np.max(err) < .1 assert np.mean(err) < .01 assert np.median(err) < .01 def test_basic(self): self.work() def test_bounded(self): self.low = 2.5 self.high = 3.5 self.work() class TestQGMM1Math(unittest.TestCase): def setUp(self): self.rng = np.random.RandomState(234) self.weights = [.1, .3, .4, .2] self.mus = [1.0, 2.0, 3.0, 4.0] self.sigmas = [.1, .4, .8, 2.0] self.low = None self.high = None self.n_samples = 1001 self.show = DO_SHOW # or put a string # -- triggers error if test case forgets to call work() self.worked = False def tearDown(self): assert self.worked def work(self, **kwargs): self.__dict__.update(kwargs) del kwargs self.worked = True gkwargs = dict( weights=self.weights, mus=self.mus, sigmas=self.sigmas, low=self.low, high=self.high, q=self.q, ) samples = GMM1(rng=self.rng, size=(self.n_samples,), **gkwargs) / self.q print 'drew', len(samples), 'samples' assert np.all(samples == samples.astype('int')) min_max = int(samples.min()), int(samples.max()) counts = np.bincount(samples.astype('int') - min_max[0]) print counts xcoords = np.arange(min_max[0], min_max[1] + 1) * self.q prob = np.exp(GMM1_lpdf(xcoords, **gkwargs)) assert counts.sum() == self.n_samples y = counts / float(self.n_samples) if self.show: plt.scatter(xcoords, y, c='r', label='empirical') plt.scatter(xcoords, prob, c='b', label='predicted') plt.legend() plt.title(str(self.show)) plt.show() err = (prob - y) ** 2 print np.max(err) print np.mean(err) print np.median(err) if self.show: raise nose.SkipTest() else: assert np.max(err) < .1 assert np.mean(err) < .01 assert np.median(err) < .01 def test_basic_1(self): self.work(q=1) def test_basic_2(self): self.work(q=2) def test_basic_pt5(self): self.work(q=0.5) def test_bounded_1(self): self.work(q=1, low=2, high=4) def test_bounded_2(self): self.work(q=2, low=2, high=4) def test_bounded_1b(self): self.work(q=1, low=1, high=4.1) def test_bounded_2b(self): self.work(q=2, low=1, high=4.1) def test_bounded_3(self): self.work( weights=[0.14285714, 0.28571429, 0.28571429, 0.28571429], mus=[5.505, 7., 2., 10.], sigmas=[8.99, 5., 8., 8.], q=1, low=1.01, high=10, n_samples=10000, #show='bounded_3', ) def test_bounded_3b(self): self.work( weights=[0.33333333, 0.66666667], mus=[5.505, 5.], sigmas=[8.99, 5.19], q=1, low=1.01, high=10, n_samples=10000, #show='bounded_3b', ) class TestLGMM1Math(unittest.TestCase): def setUp(self): self.rng = np.random.RandomState(234) self.weights = [.1, .3, .4, .2] self.mus = [-2.0, 1.0, 0.0, 3.0] self.sigmas = [.1, .4, .8, 2.0] self.low = None self.high = None self.n_samples = 10001 self.samples_per_bin = 200 self.show = False # -- triggers error if test case forgets to call work() self.worked = False def tearDown(self): assert self.worked @property def LGMM1_kwargs(self): return dict( weights=self.weights, mus=self.mus, sigmas=self.sigmas, low=self.low, high=self.high, ) def LGMM1_lpdf(self, samples): return self.LGMM1(samples, **self.LGMM1_kwargs) def work(self, **kwargs): self.__dict__.update(kwargs) self.worked = True samples = LGMM1(rng=self.rng, size=(self.n_samples,), **self.LGMM1_kwargs) samples = np.sort(samples) edges = samples[::self.samples_per_bin] centers = .5 * edges[:-1] + .5 * edges[1:] print edges pdf = np.exp(LGMM1_lpdf(centers, **self.LGMM1_kwargs)) dx = edges[1:] - edges[:-1] y = 1 / dx / len(dx) if self.show: plt.scatter(centers, y) plt.plot(centers, pdf) plt.show() err = (pdf - y) ** 2 print np.max(err) print np.mean(err) print np.median(err) if not self.show: assert np.max(err) < .1 assert np.mean(err) < .01 assert np.median(err) < .01 def test_basic(self): self.work() def test_bounded(self): self.work(low=2, high=4) class TestQLGMM1Math(unittest.TestCase): def setUp(self): self.rng = np.random.RandomState(234) self.weights = [.1, .3, .4, .2] self.mus = [-2, 0.0, -3.0, 1.0] self.sigmas = [2.1, .4, .8, 2.1] self.low = None self.high = None self.n_samples = 1001 self.show = DO_SHOW # -- triggers error if test case forgets to call work() self.worked = False def tearDown(self): assert self.worked @property def kwargs(self): return dict( weights=self.weights, mus=self.mus, sigmas=self.sigmas, low=self.low, high=self.high, q=self.q) def QLGMM1_lpdf(self, samples): return self.LGMM1(samples, **self.kwargs) def work(self, **kwargs): self.__dict__.update(kwargs) self.worked = True samples = LGMM1(rng=self.rng, size=(self.n_samples,), **self.kwargs) / self.q # -- we've divided the LGMM1 by self.q to get ints here assert np.all(samples == samples.astype('int')) min_max = int(samples.min()), int(samples.max()) print 'SAMPLES RANGE', min_max counts = np.bincount(samples.astype('int') - min_max[0]) #print samples #print counts xcoords = np.arange(min_max[0], min_max[1] + 0.5) * self.q prob = np.exp(LGMM1_lpdf(xcoords, **self.kwargs)) print xcoords print prob assert counts.sum() == self.n_samples y = counts / float(self.n_samples) if self.show: plt.scatter(xcoords, y, c='r', label='empirical') plt.scatter(xcoords, prob, c='b', label='predicted') plt.legend() plt.show() # -- calculate errors on the low end, don't take a mean # over all the range spanned by a few outliers. err = ((prob - y) ** 2)[:20] print np.max(err) print np.mean(err) print np.median(err) if self.show: raise nose.SkipTest() else: assert np.max(err) < .1 assert np.mean(err) < .01 assert np.median(err) < .01 def test_basic_1(self): self.work(q=1) def test_basic_2(self): self.work(q=2) def test_basic_pt5(self): self.work(q=0.5) def test_basic_pt125(self): self.work(q=0.125) def test_bounded_1(self): self.work(q=1, low=2, high=4) def test_bounded_2(self): self.work(q=2, low=2, high=4) def test_bounded_1b(self): self.work(q=1, low=1, high=4.1) def test_bounded_2b(self): self.work(q=2, low=1, high=4.1) class TestSuggest(unittest.TestCase, CasePerDomain): def work(self): # -- smoke test that things simply run, # for each type of several search spaces. trials = Trials() fmin(passthrough, space=self.bandit.expr, algo=partial(tpe.suggest, n_EI_candidates=3), trials=trials, max_evals=10) class TestOpt(unittest.TestCase, CasePerDomain): thresholds = dict( quadratic1=1e-5, q1_lognormal=0.01, distractor=-1.96, gauss_wave=-2.0, gauss_wave2=-2.0, n_arms=-2.5, many_dists=.0005, branin=0.7, ) LEN = dict( # -- running a long way out tests overflow/underflow # to some extent quadratic1=1000, many_dists=200, distractor=100, #XXX q1_lognormal=250, gauss_wave2=75, # -- boosted from 50 on Nov/2013 after new # sampling order made thresh test fail. branin=200, ) gammas = dict( distractor=.05, ) prior_weights = dict( distractor=.01, ) n_EIs = dict( #XXX # -- this can be low in a few dimensions quadratic1=5, # -- lower number encourages exploration # XXX: this is a damned finicky way to get TPE # to solve the Distractor problem distractor=15, ) def setUp(self): self.olderr = np.seterr('raise') np.seterr(under='ignore') def tearDown(self, *args): np.seterr(**self.olderr) def work(self): bandit = self.bandit assert bandit.name is not None algo = partial(tpe.suggest, gamma=self.gammas.get(bandit.name, tpe._default_gamma), prior_weight=self.prior_weights.get(bandit.name, tpe._default_prior_weight), n_EI_candidates=self.n_EIs.get(bandit.name, tpe._default_n_EI_candidates), ) LEN = self.LEN.get(bandit.name, 50) trials = Trials() fmin(passthrough, space=bandit.expr, algo=algo, trials=trials, max_evals=LEN, rstate=np.random.RandomState(123), catch_eval_exceptions=False) assert len(trials) == LEN if 1: rtrials = Trials() fmin(passthrough, space=bandit.expr, algo=rand.suggest, trials=rtrials, max_evals=LEN) print 'RANDOM MINS', list(sorted(rtrials.losses()))[:6] #logx = np.log([s['x'] for s in rtrials.specs]) #print 'RND MEAN', np.mean(logx) #print 'RND STD ', np.std(logx) if 0: plt.subplot(2, 2, 1) plt.scatter(range(LEN), trials.losses()) plt.title('TPE losses') plt.subplot(2, 2, 2) plt.scatter(range(LEN), ([s['x'] for s in trials.specs])) plt.title('TPE x') plt.subplot(2, 2, 3) plt.title('RND losses') plt.scatter(range(LEN), rtrials.losses()) plt.subplot(2, 2, 4) plt.title('RND x') plt.scatter(range(LEN), ([s['x'] for s in rtrials.specs])) plt.show() if 0: plt.hist( [t['x'] for t in self.experiment.trials], bins=20) #print trials.losses() print 'TPE MINS', list(sorted(trials.losses()))[:6] #logx = np.log([s['x'] for s in trials.specs]) #print 'TPE MEAN', np.mean(logx) #print 'TPE STD ', np.std(logx) thresh = self.thresholds[bandit.name] print 'Thresh', thresh assert min(trials.losses()) < thresh @domain_constructor(loss_target=0) def opt_q_uniform(target): rng = np.random.RandomState(123) x = hp.quniform('x', 1.01, 10, 1) return {'loss': (x - target) ** 2 + scope.normal(0, 1, rng=rng), 'status': STATUS_OK} class TestOptQUniform(): show_steps = False show_vars = DO_SHOW LEN = 25 def work(self, **kwargs): self.__dict__.update(kwargs) bandit = opt_q_uniform(self.target) prior_weight = 2.5 gamma = 0.20 algo = partial(tpe.suggest, prior_weight=prior_weight, n_startup_jobs=2, n_EI_candidates=128, gamma=gamma) #print algo.opt_idxs['x'] #print algo.opt_vals['x'] trials = Trials() fmin(passthrough, space=bandit.expr, algo=algo, trials=trials, max_evals=self.LEN) if self.show_vars: import hyperopt.plotting hyperopt.plotting.main_plot_vars(trials, bandit, do_show=1) idxs, vals = miscs_to_idxs_vals(trials.miscs) idxs = idxs['x'] vals = vals['x'] losses = trials.losses() from hyperopt.tpe import ap_filter_trials from hyperopt.tpe import adaptive_parzen_samplers qu = scope.quniform(1.01, 10, 1) fn = adaptive_parzen_samplers['quniform'] fn_kwargs = dict(size=(4,), rng=np.random) s_below = pyll.Literal() s_above = pyll.Literal() b_args = [s_below, prior_weight] + qu.pos_args b_post = fn(*b_args, **fn_kwargs) a_args = [s_above, prior_weight] + qu.pos_args a_post = fn(*a_args, **fn_kwargs) #print b_post #print a_post fn_lpdf = getattr(scope, a_post.name + '_lpdf') print fn_lpdf # calculate the llik of b_post under both distributions a_kwargs = dict([(n, a) for n, a in a_post.named_args if n not in ('rng', 'size')]) b_kwargs = dict([(n, a) for n, a in b_post.named_args if n not in ('rng', 'size')]) below_llik = fn_lpdf(*([b_post] + b_post.pos_args), **b_kwargs) above_llik = fn_lpdf(*([b_post] + a_post.pos_args), **a_kwargs) new_node = scope.broadcast_best(b_post, below_llik, above_llik) print '=' * 80 do_show = self.show_steps for ii in range(2, 9): if ii > len(idxs): break print '-' * 80 print 'ROUND', ii print '-' * 80 all_vals = [2, 3, 4, 5, 6, 7, 8, 9, 10] below, above = ap_filter_trials(idxs[:ii], vals[:ii], idxs[:ii], losses[:ii], gamma) below = below.astype('int') above = above.astype('int') print 'BB0', below print 'BB1', above #print 'BELOW', zip(range(100), np.bincount(below, minlength=11)) #print 'ABOVE', zip(range(100), np.bincount(above, minlength=11)) memo = {b_post: all_vals, s_below: below, s_above: above} bl, al, nv = pyll.rec_eval([below_llik, above_llik, new_node], memo=memo) #print bl - al print 'BB2', dict(zip(all_vals, bl - al)) print 'BB3', dict(zip(all_vals, bl)) print 'BB4', dict(zip(all_vals, al)) print 'ORIG PICKED', vals[ii] print 'PROPER OPT PICKS:', nv #assert np.allclose(below, [3, 3, 9]) #assert len(below) + len(above) == len(vals) if do_show: plt.subplot(8, 1, ii) #plt.scatter(all_vals, # np.bincount(below, minlength=11)[2:], c='b') #plt.scatter(all_vals, # np.bincount(above, minlength=11)[2:], c='c') plt.scatter(all_vals, bl, c='g') plt.scatter(all_vals, al, c='r') if do_show: plt.show() def test4(self): self.work(target=4, LEN=100) def test2(self): self.work(target=2, LEN=100) def test6(self): self.work(target=6, LEN=100) def test10(self): self.work(target=10, LEN=100)
bsd-3-clause
deepesch/scikit-learn
sklearn/cluster/spectral.py
233
18153
# -*- coding: utf-8 -*- """Algorithms for spectral clustering""" # Author: Gael Varoquaux gael.varoquaux@normalesup.org # Brian Cheung # Wei LI <kuantkid@gmail.com> # License: BSD 3 clause import warnings import numpy as np from ..base import BaseEstimator, ClusterMixin from ..utils import check_random_state, as_float_array from ..utils.validation import check_array from ..utils.extmath import norm from ..metrics.pairwise import pairwise_kernels from ..neighbors import kneighbors_graph from ..manifold import spectral_embedding from .k_means_ import k_means def discretize(vectors, copy=True, max_svd_restarts=30, n_iter_max=20, random_state=None): """Search for a partition matrix (clustering) which is closest to the eigenvector embedding. Parameters ---------- vectors : array-like, shape: (n_samples, n_clusters) The embedding space of the samples. copy : boolean, optional, default: True Whether to copy vectors, or perform in-place normalization. max_svd_restarts : int, optional, default: 30 Maximum number of attempts to restart SVD if convergence fails n_iter_max : int, optional, default: 30 Maximum number of iterations to attempt in rotation and partition matrix search if machine precision convergence is not reached random_state: int seed, RandomState instance, or None (default) A pseudo random number generator used for the initialization of the of the rotation matrix Returns ------- labels : array of integers, shape: n_samples The labels of the clusters. References ---------- - Multiclass spectral clustering, 2003 Stella X. Yu, Jianbo Shi http://www1.icsi.berkeley.edu/~stellayu/publication/doc/2003kwayICCV.pdf Notes ----- The eigenvector embedding is used to iteratively search for the closest discrete partition. First, the eigenvector embedding is normalized to the space of partition matrices. An optimal discrete partition matrix closest to this normalized embedding multiplied by an initial rotation is calculated. Fixing this discrete partition matrix, an optimal rotation matrix is calculated. These two calculations are performed until convergence. The discrete partition matrix is returned as the clustering solution. Used in spectral clustering, this method tends to be faster and more robust to random initialization than k-means. """ from scipy.sparse import csc_matrix from scipy.linalg import LinAlgError random_state = check_random_state(random_state) vectors = as_float_array(vectors, copy=copy) eps = np.finfo(float).eps n_samples, n_components = vectors.shape # Normalize the eigenvectors to an equal length of a vector of ones. # Reorient the eigenvectors to point in the negative direction with respect # to the first element. This may have to do with constraining the # eigenvectors to lie in a specific quadrant to make the discretization # search easier. norm_ones = np.sqrt(n_samples) for i in range(vectors.shape[1]): vectors[:, i] = (vectors[:, i] / norm(vectors[:, i])) \ * norm_ones if vectors[0, i] != 0: vectors[:, i] = -1 * vectors[:, i] * np.sign(vectors[0, i]) # Normalize the rows of the eigenvectors. Samples should lie on the unit # hypersphere centered at the origin. This transforms the samples in the # embedding space to the space of partition matrices. vectors = vectors / np.sqrt((vectors ** 2).sum(axis=1))[:, np.newaxis] svd_restarts = 0 has_converged = False # If there is an exception we try to randomize and rerun SVD again # do this max_svd_restarts times. while (svd_restarts < max_svd_restarts) and not has_converged: # Initialize first column of rotation matrix with a row of the # eigenvectors rotation = np.zeros((n_components, n_components)) rotation[:, 0] = vectors[random_state.randint(n_samples), :].T # To initialize the rest of the rotation matrix, find the rows # of the eigenvectors that are as orthogonal to each other as # possible c = np.zeros(n_samples) for j in range(1, n_components): # Accumulate c to ensure row is as orthogonal as possible to # previous picks as well as current one c += np.abs(np.dot(vectors, rotation[:, j - 1])) rotation[:, j] = vectors[c.argmin(), :].T last_objective_value = 0.0 n_iter = 0 while not has_converged: n_iter += 1 t_discrete = np.dot(vectors, rotation) labels = t_discrete.argmax(axis=1) vectors_discrete = csc_matrix( (np.ones(len(labels)), (np.arange(0, n_samples), labels)), shape=(n_samples, n_components)) t_svd = vectors_discrete.T * vectors try: U, S, Vh = np.linalg.svd(t_svd) svd_restarts += 1 except LinAlgError: print("SVD did not converge, randomizing and trying again") break ncut_value = 2.0 * (n_samples - S.sum()) if ((abs(ncut_value - last_objective_value) < eps) or (n_iter > n_iter_max)): has_converged = True else: # otherwise calculate rotation and continue last_objective_value = ncut_value rotation = np.dot(Vh.T, U.T) if not has_converged: raise LinAlgError('SVD did not converge') return labels def spectral_clustering(affinity, n_clusters=8, n_components=None, eigen_solver=None, random_state=None, n_init=10, eigen_tol=0.0, assign_labels='kmeans'): """Apply clustering to a projection to the normalized laplacian. In practice Spectral Clustering is very useful when the structure of the individual clusters is highly non-convex or more generally when a measure of the center and spread of the cluster is not a suitable description of the complete cluster. For instance when clusters are nested circles on the 2D plan. If affinity is the adjacency matrix of a graph, this method can be used to find normalized graph cuts. Read more in the :ref:`User Guide <spectral_clustering>`. Parameters ----------- affinity : array-like or sparse matrix, shape: (n_samples, n_samples) The affinity matrix describing the relationship of the samples to embed. **Must be symmetric**. Possible examples: - adjacency matrix of a graph, - heat kernel of the pairwise distance matrix of the samples, - symmetric k-nearest neighbours connectivity matrix of the samples. n_clusters : integer, optional Number of clusters to extract. n_components : integer, optional, default is n_clusters Number of eigen vectors to use for the spectral embedding eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'} The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities random_state : int seed, RandomState instance, or None (default) A pseudo random number generator used for the initialization of the lobpcg eigen vectors decomposition when eigen_solver == 'amg' and by the K-Means initialization. n_init : int, optional, default: 10 Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia. eigen_tol : float, optional, default: 0.0 Stopping criterion for eigendecomposition of the Laplacian matrix when using arpack eigen_solver. assign_labels : {'kmeans', 'discretize'}, default: 'kmeans' The strategy to use to assign labels in the embedding space. There are two ways to assign labels after the laplacian embedding. k-means can be applied and is a popular choice. But it can also be sensitive to initialization. Discretization is another approach which is less sensitive to random initialization. See the 'Multiclass spectral clustering' paper referenced below for more details on the discretization approach. Returns ------- labels : array of integers, shape: n_samples The labels of the clusters. References ---------- - Normalized cuts and image segmentation, 2000 Jianbo Shi, Jitendra Malik http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.160.2324 - A Tutorial on Spectral Clustering, 2007 Ulrike von Luxburg http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323 - Multiclass spectral clustering, 2003 Stella X. Yu, Jianbo Shi http://www1.icsi.berkeley.edu/~stellayu/publication/doc/2003kwayICCV.pdf Notes ------ The graph should contain only one connect component, elsewhere the results make little sense. This algorithm solves the normalized cut for k=2: it is a normalized spectral clustering. """ if assign_labels not in ('kmeans', 'discretize'): raise ValueError("The 'assign_labels' parameter should be " "'kmeans' or 'discretize', but '%s' was given" % assign_labels) random_state = check_random_state(random_state) n_components = n_clusters if n_components is None else n_components maps = spectral_embedding(affinity, n_components=n_components, eigen_solver=eigen_solver, random_state=random_state, eigen_tol=eigen_tol, drop_first=False) if assign_labels == 'kmeans': _, labels, _ = k_means(maps, n_clusters, random_state=random_state, n_init=n_init) else: labels = discretize(maps, random_state=random_state) return labels class SpectralClustering(BaseEstimator, ClusterMixin): """Apply clustering to a projection to the normalized laplacian. In practice Spectral Clustering is very useful when the structure of the individual clusters is highly non-convex or more generally when a measure of the center and spread of the cluster is not a suitable description of the complete cluster. For instance when clusters are nested circles on the 2D plan. If affinity is the adjacency matrix of a graph, this method can be used to find normalized graph cuts. When calling ``fit``, an affinity matrix is constructed using either kernel function such the Gaussian (aka RBF) kernel of the euclidean distanced ``d(X, X)``:: np.exp(-gamma * d(X,X) ** 2) or a k-nearest neighbors connectivity matrix. Alternatively, using ``precomputed``, a user-provided affinity matrix can be used. Read more in the :ref:`User Guide <spectral_clustering>`. Parameters ----------- n_clusters : integer, optional The dimension of the projection subspace. affinity : string, array-like or callable, default 'rbf' If a string, this may be one of 'nearest_neighbors', 'precomputed', 'rbf' or one of the kernels supported by `sklearn.metrics.pairwise_kernels`. Only kernels that produce similarity scores (non-negative values that increase with similarity) should be used. This property is not checked by the clustering algorithm. gamma : float Scaling factor of RBF, polynomial, exponential chi^2 and sigmoid affinity kernel. Ignored for ``affinity='nearest_neighbors'``. degree : float, default=3 Degree of the polynomial kernel. Ignored by other kernels. coef0 : float, default=1 Zero coefficient for polynomial and sigmoid kernels. Ignored by other kernels. n_neighbors : integer Number of neighbors to use when constructing the affinity matrix using the nearest neighbors method. Ignored for ``affinity='rbf'``. eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'} The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities random_state : int seed, RandomState instance, or None (default) A pseudo random number generator used for the initialization of the lobpcg eigen vectors decomposition when eigen_solver == 'amg' and by the K-Means initialization. n_init : int, optional, default: 10 Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia. eigen_tol : float, optional, default: 0.0 Stopping criterion for eigendecomposition of the Laplacian matrix when using arpack eigen_solver. assign_labels : {'kmeans', 'discretize'}, default: 'kmeans' The strategy to use to assign labels in the embedding space. There are two ways to assign labels after the laplacian embedding. k-means can be applied and is a popular choice. But it can also be sensitive to initialization. Discretization is another approach which is less sensitive to random initialization. kernel_params : dictionary of string to any, optional Parameters (keyword arguments) and values for kernel passed as callable object. Ignored by other kernels. Attributes ---------- affinity_matrix_ : array-like, shape (n_samples, n_samples) Affinity matrix used for clustering. Available only if after calling ``fit``. labels_ : Labels of each point Notes ----- If you have an affinity matrix, such as a distance matrix, for which 0 means identical elements, and high values means very dissimilar elements, it can be transformed in a similarity matrix that is well suited for the algorithm by applying the Gaussian (RBF, heat) kernel:: np.exp(- X ** 2 / (2. * delta ** 2)) Another alternative is to take a symmetric version of the k nearest neighbors connectivity matrix of the points. If the pyamg package is installed, it is used: this greatly speeds up computation. References ---------- - Normalized cuts and image segmentation, 2000 Jianbo Shi, Jitendra Malik http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.160.2324 - A Tutorial on Spectral Clustering, 2007 Ulrike von Luxburg http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323 - Multiclass spectral clustering, 2003 Stella X. Yu, Jianbo Shi http://www1.icsi.berkeley.edu/~stellayu/publication/doc/2003kwayICCV.pdf """ def __init__(self, n_clusters=8, eigen_solver=None, random_state=None, n_init=10, gamma=1., affinity='rbf', n_neighbors=10, eigen_tol=0.0, assign_labels='kmeans', degree=3, coef0=1, kernel_params=None): self.n_clusters = n_clusters self.eigen_solver = eigen_solver self.random_state = random_state self.n_init = n_init self.gamma = gamma self.affinity = affinity self.n_neighbors = n_neighbors self.eigen_tol = eigen_tol self.assign_labels = assign_labels self.degree = degree self.coef0 = coef0 self.kernel_params = kernel_params def fit(self, X, y=None): """Creates an affinity matrix for X using the selected affinity, then applies spectral clustering to this affinity matrix. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) OR, if affinity==`precomputed`, a precomputed affinity matrix of shape (n_samples, n_samples) """ X = check_array(X, accept_sparse=['csr', 'csc', 'coo'], dtype=np.float64) if X.shape[0] == X.shape[1] and self.affinity != "precomputed": warnings.warn("The spectral clustering API has changed. ``fit``" "now constructs an affinity matrix from data. To use" " a custom affinity matrix, " "set ``affinity=precomputed``.") if self.affinity == 'nearest_neighbors': connectivity = kneighbors_graph(X, n_neighbors=self.n_neighbors, include_self=True) self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T) elif self.affinity == 'precomputed': self.affinity_matrix_ = X else: params = self.kernel_params if params is None: params = {} if not callable(self.affinity): params['gamma'] = self.gamma params['degree'] = self.degree params['coef0'] = self.coef0 self.affinity_matrix_ = pairwise_kernels(X, metric=self.affinity, filter_params=True, **params) random_state = check_random_state(self.random_state) self.labels_ = spectral_clustering(self.affinity_matrix_, n_clusters=self.n_clusters, eigen_solver=self.eigen_solver, random_state=random_state, n_init=self.n_init, eigen_tol=self.eigen_tol, assign_labels=self.assign_labels) return self @property def _pairwise(self): return self.affinity == "precomputed"
bsd-3-clause
crichardson17/starburst_atlas
Low_resolution_sims/Dusty_LowRes/Geneva_inst_NoRot/Geneva_inst_NoRot_0/fullgrid/UV1.py
31
9315
import csv import matplotlib.pyplot as plt from numpy import * import scipy.interpolate import math from pylab import * from matplotlib.ticker import MultipleLocator, FormatStrFormatter import matplotlib.patches as patches from matplotlib.path import Path import os # ------------------------------------------------------------------------------------------------------ #inputs for file in os.listdir('.'): if file.endswith("1.grd"): gridfile1 = file for file in os.listdir('.'): if file.endswith("2.grd"): gridfile2 = file for file in os.listdir('.'): if file.endswith("3.grd"): gridfile3 = file # ------------------------ for file in os.listdir('.'): if file.endswith("1.txt"): Elines1 = file for file in os.listdir('.'): if file.endswith("2.txt"): Elines2 = file for file in os.listdir('.'): if file.endswith("3.txt"): Elines3 = file # ------------------------------------------------------------------------------------------------------ #Patches data #for the Kewley and Levesque data verts = [ (1., 7.97712125471966000000), # left, bottom (1., 9.57712125471966000000), # left, top (2., 10.57712125471970000000), # right, top (2., 8.97712125471966000000), # right, bottom (0., 0.), # ignored ] codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] path = Path(verts, codes) # ------------------------ #for the Kewley 01 data verts2 = [ (2.4, 9.243038049), # left, bottom (2.4, 11.0211893), # left, top (2.6, 11.0211893), # right, top (2.6, 9.243038049), # right, bottom (0, 0.), # ignored ] path = Path(verts, codes) path2 = Path(verts2, codes) # ------------------------- #for the Moy et al data verts3 = [ (1., 6.86712125471966000000), # left, bottom (1., 10.18712125471970000000), # left, top (3., 12.18712125471970000000), # right, top (3., 8.86712125471966000000), # right, bottom (0., 0.), # ignored ] path = Path(verts, codes) path3 = Path(verts3, codes) # ------------------------------------------------------------------------------------------------------ #the routine to add patches for others peoples' data onto our plots. def add_patches(ax): patch3 = patches.PathPatch(path3, facecolor='yellow', lw=0) patch2 = patches.PathPatch(path2, facecolor='green', lw=0) patch = patches.PathPatch(path, facecolor='red', lw=0) ax1.add_patch(patch3) ax1.add_patch(patch2) ax1.add_patch(patch) # ------------------------------------------------------------------------------------------------------ #the subplot routine def add_sub_plot(sub_num): numplots = 16 plt.subplot(numplots/4.,4,sub_num) rbf = scipy.interpolate.Rbf(x, y, z[:,sub_num-1], function='linear') zi = rbf(xi, yi) contour = plt.contour(xi,yi,zi, levels, colors='c', linestyles = 'dashed') contour2 = plt.contour(xi,yi,zi, levels2, colors='k', linewidths=1.5) plt.scatter(max_values[line[sub_num-1],2], max_values[line[sub_num-1],3], c ='k',marker = '*') plt.annotate(headers[line[sub_num-1]], xy=(8,11), xytext=(6,8.5), fontsize = 10) plt.annotate(max_values[line[sub_num-1],0], xy= (max_values[line[sub_num-1],2], max_values[line[sub_num-1],3]), xytext = (0, -10), textcoords = 'offset points', ha = 'right', va = 'bottom', fontsize=10) if sub_num == numplots / 2.: print "half the plots are complete" #axis limits yt_min = 8 yt_max = 23 xt_min = 0 xt_max = 12 plt.ylim(yt_min,yt_max) plt.xlim(xt_min,xt_max) plt.yticks(arange(yt_min+1,yt_max,1),fontsize=10) plt.xticks(arange(xt_min+1,xt_max,1), fontsize = 10) if sub_num in [2,3,4,6,7,8,10,11,12,14,15,16]: plt.tick_params(labelleft = 'off') else: plt.tick_params(labelleft = 'on') plt.ylabel('Log ($ \phi _{\mathrm{H}} $)') if sub_num in [1,2,3,4,5,6,7,8,9,10,11,12]: plt.tick_params(labelbottom = 'off') else: plt.tick_params(labelbottom = 'on') plt.xlabel('Log($n _{\mathrm{H}} $)') if sub_num == 1: plt.yticks(arange(yt_min+1,yt_max+1,1),fontsize=10) if sub_num == 13: plt.yticks(arange(yt_min,yt_max,1),fontsize=10) plt.xticks(arange(xt_min,xt_max,1), fontsize = 10) if sub_num == 16 : plt.xticks(arange(xt_min+1,xt_max+1,1), fontsize = 10) # --------------------------------------------------- #this is where the grid information (phi and hdens) is read in and saved to grid. grid1 = []; grid2 = []; grid3 = []; with open(gridfile1, 'rb') as f: csvReader = csv.reader(f,delimiter='\t') for row in csvReader: grid1.append(row); grid1 = asarray(grid1) with open(gridfile2, 'rb') as f: csvReader = csv.reader(f,delimiter='\t') for row in csvReader: grid2.append(row); grid2 = asarray(grid2) with open(gridfile3, 'rb') as f: csvReader = csv.reader(f,delimiter='\t') for row in csvReader: grid3.append(row); grid3 = asarray(grid3) #here is where the data for each line is read in and saved to dataEmissionlines dataEmissionlines1 = []; dataEmissionlines2 = []; dataEmissionlines3 = []; with open(Elines1, 'rb') as f: csvReader = csv.reader(f,delimiter='\t') headers = csvReader.next() for row in csvReader: dataEmissionlines1.append(row); dataEmissionlines1 = asarray(dataEmissionlines1) with open(Elines2, 'rb') as f: csvReader = csv.reader(f,delimiter='\t') headers2 = csvReader.next() for row in csvReader: dataEmissionlines2.append(row); dataEmissionlines2 = asarray(dataEmissionlines2) with open(Elines3, 'rb') as f: csvReader = csv.reader(f,delimiter='\t') headers3 = csvReader.next() for row in csvReader: dataEmissionlines3.append(row); dataEmissionlines3 = asarray(dataEmissionlines3) print "import files complete" # --------------------------------------------------- #for concatenating grid #pull the phi and hdens values from each of the runs. exclude header lines grid1new = zeros((len(grid1[:,0])-1,2)) grid1new[:,0] = grid1[1:,6] grid1new[:,1] = grid1[1:,7] grid2new = zeros((len(grid2[:,0])-1,2)) x = array(17.00000) grid2new[:,0] = repeat(x,len(grid2[:,0])-1) grid2new[:,1] = grid2[1:,6] grid3new = zeros((len(grid3[:,0])-1,2)) grid3new[:,0] = grid3[1:,6] grid3new[:,1] = grid3[1:,7] grid = concatenate((grid1new,grid2new,grid3new)) hdens_values = grid[:,1] phi_values = grid[:,0] # --------------------------------------------------- #for concatenating Emission lines data Emissionlines = concatenate((dataEmissionlines1[:,1:],dataEmissionlines2[:,1:],dataEmissionlines3[:,1:])) #for lines headers = headers[1:] concatenated_data = zeros((len(Emissionlines),len(Emissionlines[0]))) max_values = zeros((len(concatenated_data[0]),4)) # --------------------------------------------------- #constructing grid by scaling #select the scaling factor #for 1215 #incident = Emissionlines[1:,4] #for 4860 incident = concatenated_data[:,57] #take the ratio of incident and all the lines and put it all in an array concatenated_data for i in range(len(Emissionlines)): for j in range(len(Emissionlines[0])): if math.log(4860.*(float(Emissionlines[i,j])/float(Emissionlines[i,57])), 10) > 0: concatenated_data[i,j] = math.log(4860.*(float(Emissionlines[i,j])/float(Emissionlines[i,57])), 10) else: concatenated_data[i,j] == 0 # for 1215 #for i in range(len(Emissionlines)): # for j in range(len(Emissionlines[0])): # if math.log(1215.*(float(Emissionlines[i,j])/float(Emissionlines[i,4])), 10) > 0: # concatenated_data[i,j] = math.log(1215.*(float(Emissionlines[i,j])/float(Emissionlines[i,4])), 10) # else: # concatenated_data[i,j] == 0 # --------------------------------------------------- #find the maxima to plot onto the contour plots for j in range(len(concatenated_data[0])): max_values[j,0] = max(concatenated_data[:,j]) max_values[j,1] = argmax(concatenated_data[:,j], axis = 0) max_values[j,2] = hdens_values[max_values[j,1]] max_values[j,3] = phi_values[max_values[j,1]] #to round off the maxima max_values[:,0] = [ '%.1f' % elem for elem in max_values[:,0] ] print "data arranged" # --------------------------------------------------- #Creating the grid to interpolate with for contours. gridarray = zeros((len(concatenated_data),2)) gridarray[:,0] = hdens_values gridarray[:,1] = phi_values x = gridarray[:,0] y = gridarray[:,1] # --------------------------------------------------- #change desired lines here! line = [0, #977 1, #991 2, #1026 5, #1216 91, #1218 6, #1239 7, #1240 8, #1243 9, #1263 10, #1304 11,#1308 12, #1397 13, #1402 14, #1406 16, #1486 17] #1531 #create z array for this plot z = concatenated_data[:,line[:]] # --------------------------------------------------- # Interpolate print "starting interpolation" xi, yi = linspace(x.min(), x.max(), 10), linspace(y.min(), y.max(), 10) xi, yi = meshgrid(xi, yi) # --------------------------------------------------- print "interpolatation complete; now plotting" #plot plt.subplots_adjust(wspace=0, hspace=0) #remove space between plots levels = arange(10**-1,10, .2) levels2 = arange(10**-2,10**2, 1) plt.suptitle("Dusty UV Lines", fontsize=14) # --------------------------------------------------- for i in range(16): add_sub_plot(i) ax1 = plt.subplot(4,4,1) add_patches(ax1) print "complete" plt.savefig('Dusty_UV_Lines.pdf') plt.clf() print "figure saved"
gpl-2.0
iwonasob/BAD-masked-NMF
src/dataset.py
1
3288
''' Download, extract and partition the datasets ''' import config as cfg import os import sys import requests import zipfile from clint.textui import progress import numpy as np np.random.seed(1515) import pandas as pd class DatasetCreator: def __init__(self, dataset_name): """ Initialize class Args: dataset_name (string): Name of the dataset to prepare """ self.dataset_name = dataset_name self.root_path = os.path.join(cfg.home_path, self.dataset_name) self.wav_url = cfg.wav_url[self.dataset_name] self.csv_url = cfg.csv_url[self.dataset_name] path , zip_name = os.path.split(self.wav_url) self.wav_zip = os.path.join(cfg.home_path, zip_name) self.wav_path = os.path.join(self.root_path, "wav") self.csv_path = os.path.join(self.root_path, cfg.csv_path[self.dataset_name]) self.csv_10_path = os.path.join(self.root_path, "cv10.csv") if not os.path.isdir(self.root_path): os.makedirs(self.root_path) if not os.path.isdir(self.wav_path): os.makedirs(self.wav_path) def run(self): self.download() self.extract() self.partition() def download(self): """ Download the dataset and annotation file """ urls =[(self.csv_url,self.csv_path),(self.wav_url,self.wav_zip )] for u in urls: url=u[0] download_path=u[1] if not os.path.isfile(download_path): print("Downloading the file "+ u[1]) # open the link r = requests.get(url, stream=True) # save the content to a file with open(u[1], 'wb') as f: total_length = int(r.headers.get('content-length')) for chunk in progress.bar(r.iter_content(chunk_size=8192), expected_size=(total_length/8192) + 1): if chunk: f.write(chunk) f.flush() f.close() else: print(download_path + " is already there!") def extract(self): """ Extract the downloaded dataset """ if not os.listdir(os.path.join(self.root_path,"wav")): print("Extracting the dataset "+ self.dataset_name) zip= zipfile.ZipFile(self.wav_zip) zip.extractall(self.root_path) else: print(self.dataset_name + " has been already extracted!") def partition(self, n=10): """ Create a csv file with partitioning into n subsets Args: n: number of subsets """ if not os.path.isfile(self.csv_10_path): data_list = pd.read_csv(self.csv_path) data_list['fold'] = np.random.randint( low=0, high=n, size=len(data_list)) data_list.to_csv(self.csv_10_path) print("The partition into "+ str(n) + " is saved: "+ self.csv_10_path) else: print("The partition CSV file is already there! "+ self.csv_10_path)
mit
robin-lai/scikit-learn
sklearn/cluster/bicluster.py
211
19443
"""Spectral biclustering algorithms. Authors : Kemal Eren License: BSD 3 clause """ from abc import ABCMeta, abstractmethod import numpy as np from scipy.sparse import dia_matrix from scipy.sparse import issparse from . import KMeans, MiniBatchKMeans from ..base import BaseEstimator, BiclusterMixin from ..externals import six from ..utils.arpack import eigsh, svds from ..utils.extmath import (make_nonnegative, norm, randomized_svd, safe_sparse_dot) from ..utils.validation import assert_all_finite, check_array __all__ = ['SpectralCoclustering', 'SpectralBiclustering'] def _scale_normalize(X): """Normalize ``X`` by scaling rows and columns independently. Returns the normalized matrix and the row and column scaling factors. """ X = make_nonnegative(X) row_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=1))).squeeze() col_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=0))).squeeze() row_diag = np.where(np.isnan(row_diag), 0, row_diag) col_diag = np.where(np.isnan(col_diag), 0, col_diag) if issparse(X): n_rows, n_cols = X.shape r = dia_matrix((row_diag, [0]), shape=(n_rows, n_rows)) c = dia_matrix((col_diag, [0]), shape=(n_cols, n_cols)) an = r * X * c else: an = row_diag[:, np.newaxis] * X * col_diag return an, row_diag, col_diag def _bistochastic_normalize(X, max_iter=1000, tol=1e-5): """Normalize rows and columns of ``X`` simultaneously so that all rows sum to one constant and all columns sum to a different constant. """ # According to paper, this can also be done more efficiently with # deviation reduction and balancing algorithms. X = make_nonnegative(X) X_scaled = X dist = None for _ in range(max_iter): X_new, _, _ = _scale_normalize(X_scaled) if issparse(X): dist = norm(X_scaled.data - X.data) else: dist = norm(X_scaled - X_new) X_scaled = X_new if dist is not None and dist < tol: break return X_scaled def _log_normalize(X): """Normalize ``X`` according to Kluger's log-interactions scheme.""" X = make_nonnegative(X, min_value=1) if issparse(X): raise ValueError("Cannot compute log of a sparse matrix," " because log(x) diverges to -infinity as x" " goes to 0.") L = np.log(X) row_avg = L.mean(axis=1)[:, np.newaxis] col_avg = L.mean(axis=0) avg = L.mean() return L - row_avg - col_avg + avg class BaseSpectral(six.with_metaclass(ABCMeta, BaseEstimator, BiclusterMixin)): """Base class for spectral biclustering.""" @abstractmethod def __init__(self, n_clusters=3, svd_method="randomized", n_svd_vecs=None, mini_batch=False, init="k-means++", n_init=10, n_jobs=1, random_state=None): self.n_clusters = n_clusters self.svd_method = svd_method self.n_svd_vecs = n_svd_vecs self.mini_batch = mini_batch self.init = init self.n_init = n_init self.n_jobs = n_jobs self.random_state = random_state def _check_parameters(self): legal_svd_methods = ('randomized', 'arpack') if self.svd_method not in legal_svd_methods: raise ValueError("Unknown SVD method: '{0}'. svd_method must be" " one of {1}.".format(self.svd_method, legal_svd_methods)) def fit(self, X): """Creates a biclustering for X. Parameters ---------- X : array-like, shape (n_samples, n_features) """ X = check_array(X, accept_sparse='csr', dtype=np.float64) self._check_parameters() self._fit(X) def _svd(self, array, n_components, n_discard): """Returns first `n_components` left and right singular vectors u and v, discarding the first `n_discard`. """ if self.svd_method == 'randomized': kwargs = {} if self.n_svd_vecs is not None: kwargs['n_oversamples'] = self.n_svd_vecs u, _, vt = randomized_svd(array, n_components, random_state=self.random_state, **kwargs) elif self.svd_method == 'arpack': u, _, vt = svds(array, k=n_components, ncv=self.n_svd_vecs) if np.any(np.isnan(vt)): # some eigenvalues of A * A.T are negative, causing # sqrt() to be np.nan. This causes some vectors in vt # to be np.nan. _, v = eigsh(safe_sparse_dot(array.T, array), ncv=self.n_svd_vecs) vt = v.T if np.any(np.isnan(u)): _, u = eigsh(safe_sparse_dot(array, array.T), ncv=self.n_svd_vecs) assert_all_finite(u) assert_all_finite(vt) u = u[:, n_discard:] vt = vt[n_discard:] return u, vt.T def _k_means(self, data, n_clusters): if self.mini_batch: model = MiniBatchKMeans(n_clusters, init=self.init, n_init=self.n_init, random_state=self.random_state) else: model = KMeans(n_clusters, init=self.init, n_init=self.n_init, n_jobs=self.n_jobs, random_state=self.random_state) model.fit(data) centroid = model.cluster_centers_ labels = model.labels_ return centroid, labels class SpectralCoclustering(BaseSpectral): """Spectral Co-Clustering algorithm (Dhillon, 2001). Clusters rows and columns of an array `X` to solve the relaxed normalized cut of the bipartite graph created from `X` as follows: the edge between row vertex `i` and column vertex `j` has weight `X[i, j]`. The resulting bicluster structure is block-diagonal, since each row and each column belongs to exactly one bicluster. Supports sparse matrices, as long as they are nonnegative. Read more in the :ref:`User Guide <spectral_coclustering>`. Parameters ---------- n_clusters : integer, optional, default: 3 The number of biclusters to find. svd_method : string, optional, default: 'randomized' Selects the algorithm for finding singular vectors. May be 'randomized' or 'arpack'. If 'randomized', use :func:`sklearn.utils.extmath.randomized_svd`, which may be faster for large matrices. If 'arpack', use :func:`sklearn.utils.arpack.svds`, which is more accurate, but possibly slower in some cases. n_svd_vecs : int, optional, default: None Number of vectors to use in calculating the SVD. Corresponds to `ncv` when `svd_method=arpack` and `n_oversamples` when `svd_method` is 'randomized`. mini_batch : bool, optional, default: False Whether to use mini-batch k-means, which is faster but may get different results. init : {'k-means++', 'random' or an ndarray} Method for initialization of k-means algorithm; defaults to 'k-means++'. n_init : int, optional, default: 10 Number of random initializations that are tried with the k-means algorithm. If mini-batch k-means is used, the best initialization is chosen and the algorithm runs once. Otherwise, the algorithm is run for each initialization and the best solution chosen. n_jobs : int, optional, default: 1 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 debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. random_state : int seed, RandomState instance, or None (default) A pseudo random number generator used by the K-Means initialization. Attributes ---------- rows_ : array-like, shape (n_row_clusters, n_rows) Results of the clustering. `rows[i, r]` is True if cluster `i` contains row `r`. Available only after calling ``fit``. columns_ : array-like, shape (n_column_clusters, n_columns) Results of the clustering, like `rows`. row_labels_ : array-like, shape (n_rows,) The bicluster label of each row. column_labels_ : array-like, shape (n_cols,) The bicluster label of each column. References ---------- * Dhillon, Inderjit S, 2001. `Co-clustering documents and words using bipartite spectral graph partitioning <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.140.3011>`__. """ def __init__(self, n_clusters=3, svd_method='randomized', n_svd_vecs=None, mini_batch=False, init='k-means++', n_init=10, n_jobs=1, random_state=None): super(SpectralCoclustering, self).__init__(n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, n_jobs, random_state) def _fit(self, X): normalized_data, row_diag, col_diag = _scale_normalize(X) n_sv = 1 + int(np.ceil(np.log2(self.n_clusters))) u, v = self._svd(normalized_data, n_sv, n_discard=1) z = np.vstack((row_diag[:, np.newaxis] * u, col_diag[:, np.newaxis] * v)) _, labels = self._k_means(z, self.n_clusters) n_rows = X.shape[0] self.row_labels_ = labels[:n_rows] self.column_labels_ = labels[n_rows:] self.rows_ = np.vstack(self.row_labels_ == c for c in range(self.n_clusters)) self.columns_ = np.vstack(self.column_labels_ == c for c in range(self.n_clusters)) class SpectralBiclustering(BaseSpectral): """Spectral biclustering (Kluger, 2003). Partitions rows and columns under the assumption that the data has an underlying checkerboard structure. For instance, if there are two row partitions and three column partitions, each row will belong to three biclusters, and each column will belong to two biclusters. The outer product of the corresponding row and column label vectors gives this checkerboard structure. Read more in the :ref:`User Guide <spectral_biclustering>`. Parameters ---------- n_clusters : integer or tuple (n_row_clusters, n_column_clusters) The number of row and column clusters in the checkerboard structure. method : string, optional, default: 'bistochastic' Method of normalizing and converting singular vectors into biclusters. May be one of 'scale', 'bistochastic', or 'log'. The authors recommend using 'log'. If the data is sparse, however, log normalization will not work, which is why the default is 'bistochastic'. CAUTION: if `method='log'`, the data must not be sparse. n_components : integer, optional, default: 6 Number of singular vectors to check. n_best : integer, optional, default: 3 Number of best singular vectors to which to project the data for clustering. svd_method : string, optional, default: 'randomized' Selects the algorithm for finding singular vectors. May be 'randomized' or 'arpack'. If 'randomized', uses `sklearn.utils.extmath.randomized_svd`, which may be faster for large matrices. If 'arpack', uses `sklearn.utils.arpack.svds`, which is more accurate, but possibly slower in some cases. n_svd_vecs : int, optional, default: None Number of vectors to use in calculating the SVD. Corresponds to `ncv` when `svd_method=arpack` and `n_oversamples` when `svd_method` is 'randomized`. mini_batch : bool, optional, default: False Whether to use mini-batch k-means, which is faster but may get different results. init : {'k-means++', 'random' or an ndarray} Method for initialization of k-means algorithm; defaults to 'k-means++'. n_init : int, optional, default: 10 Number of random initializations that are tried with the k-means algorithm. If mini-batch k-means is used, the best initialization is chosen and the algorithm runs once. Otherwise, the algorithm is run for each initialization and the best solution chosen. n_jobs : int, optional, default: 1 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 debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. random_state : int seed, RandomState instance, or None (default) A pseudo random number generator used by the K-Means initialization. Attributes ---------- rows_ : array-like, shape (n_row_clusters, n_rows) Results of the clustering. `rows[i, r]` is True if cluster `i` contains row `r`. Available only after calling ``fit``. columns_ : array-like, shape (n_column_clusters, n_columns) Results of the clustering, like `rows`. row_labels_ : array-like, shape (n_rows,) Row partition labels. column_labels_ : array-like, shape (n_cols,) Column partition labels. References ---------- * Kluger, Yuval, et. al., 2003. `Spectral biclustering of microarray data: coclustering genes and conditions <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.135.1608>`__. """ def __init__(self, n_clusters=3, method='bistochastic', n_components=6, n_best=3, svd_method='randomized', n_svd_vecs=None, mini_batch=False, init='k-means++', n_init=10, n_jobs=1, random_state=None): super(SpectralBiclustering, self).__init__(n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, n_jobs, random_state) self.method = method self.n_components = n_components self.n_best = n_best def _check_parameters(self): super(SpectralBiclustering, self)._check_parameters() legal_methods = ('bistochastic', 'scale', 'log') if self.method not in legal_methods: raise ValueError("Unknown method: '{0}'. method must be" " one of {1}.".format(self.method, legal_methods)) try: int(self.n_clusters) except TypeError: try: r, c = self.n_clusters int(r) int(c) except (ValueError, TypeError): raise ValueError("Incorrect parameter n_clusters has value:" " {}. It should either be a single integer" " or an iterable with two integers:" " (n_row_clusters, n_column_clusters)") if self.n_components < 1: raise ValueError("Parameter n_components must be greater than 0," " but its value is {}".format(self.n_components)) if self.n_best < 1: raise ValueError("Parameter n_best must be greater than 0," " but its value is {}".format(self.n_best)) if self.n_best > self.n_components: raise ValueError("n_best cannot be larger than" " n_components, but {} > {}" "".format(self.n_best, self.n_components)) def _fit(self, X): n_sv = self.n_components if self.method == 'bistochastic': normalized_data = _bistochastic_normalize(X) n_sv += 1 elif self.method == 'scale': normalized_data, _, _ = _scale_normalize(X) n_sv += 1 elif self.method == 'log': normalized_data = _log_normalize(X) n_discard = 0 if self.method == 'log' else 1 u, v = self._svd(normalized_data, n_sv, n_discard) ut = u.T vt = v.T try: n_row_clusters, n_col_clusters = self.n_clusters except TypeError: n_row_clusters = n_col_clusters = self.n_clusters best_ut = self._fit_best_piecewise(ut, self.n_best, n_row_clusters) best_vt = self._fit_best_piecewise(vt, self.n_best, n_col_clusters) self.row_labels_ = self._project_and_cluster(X, best_vt.T, n_row_clusters) self.column_labels_ = self._project_and_cluster(X.T, best_ut.T, n_col_clusters) self.rows_ = np.vstack(self.row_labels_ == label for label in range(n_row_clusters) for _ in range(n_col_clusters)) self.columns_ = np.vstack(self.column_labels_ == label for _ in range(n_row_clusters) for label in range(n_col_clusters)) def _fit_best_piecewise(self, vectors, n_best, n_clusters): """Find the ``n_best`` vectors that are best approximated by piecewise constant vectors. The piecewise vectors are found by k-means; the best is chosen according to Euclidean distance. """ def make_piecewise(v): centroid, labels = self._k_means(v.reshape(-1, 1), n_clusters) return centroid[labels].ravel() piecewise_vectors = np.apply_along_axis(make_piecewise, axis=1, arr=vectors) dists = np.apply_along_axis(norm, axis=1, arr=(vectors - piecewise_vectors)) result = vectors[np.argsort(dists)[:n_best]] return result def _project_and_cluster(self, data, vectors, n_clusters): """Project ``data`` to ``vectors`` and cluster the result.""" projected = safe_sparse_dot(data, vectors) _, labels = self._k_means(projected, n_clusters) return labels
bsd-3-clause
marionleborgne/nupic.research
projects/l2_pooling/infer_hand_crafted_objects.py
1
5291
# Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2016, 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/ # ---------------------------------------------------------------------- from collections import defaultdict import itertools import random import os import matplotlib.pyplot as plt from htmresearch.frameworks.layers.l2_l4_inference import L4L2Experiment from htmresearch.frameworks.layers.sensor_placement import greedySensorPositions FEATURES = ("A", "B") LOCATIONS = tuple(xrange(9)) # Every object shares 3 feature-locations with every other object. OBJECTS = {"Object 1": ("A", "A", "A", "A", "A", "A", "A", "A", "A"), "Object 2": ("A", "A", "A", "B", "B", "B", "B", "B", "B"), "Object 3": ("B", "B", "B", "A", "A", "A", "B", "B", "B"), "Object 4": ("B", "B", "B", "B", "B", "B", "A", "A", "A"),} TIMESTEPS_PER_SENSATION = 3 def experiment(numColumns, sampleSize): locationSDRsByColumn = [dict((name, set(random.sample(xrange(1024), 40))) for name in LOCATIONS) for _ in xrange(numColumns)] featureSDRsByColumn = [dict((name, set(random.sample(xrange(1024), 40))) for name in FEATURES) for _ in xrange(numColumns)] exp = L4L2Experiment( "Hello", numCorticalColumns=numColumns, L2Overrides={ "sampleSizeDistal": sampleSize, }, seed=random.randint(2048, 4096) ) exp.learnObjects(dict((objectName, [dict((column, (locationSDRsByColumn[column][location], featureSDRsByColumn[column][features[location]])) for column in xrange(numColumns)) for location in LOCATIONS]) for objectName, features in OBJECTS.iteritems())) objectName = "Object 1" features = OBJECTS[objectName] inferredL2 = exp.objectL2Representations[objectName] touchCount = 0 for sensorPositions in greedySensorPositions(numColumns, len(LOCATIONS)): sensation = dict( (column, (locationSDRsByColumn[column][sensorPositions[column]], featureSDRsByColumn[column][features[sensorPositions[column]]])) for column in xrange(numColumns)) exp.infer([sensation]*TIMESTEPS_PER_SENSATION, reset=False, objectName=objectName) touchCount += 1 if exp.getL2Representations() == inferredL2: print "Inferred object after %d touches" % touchCount return touchCount if touchCount >= 60: print "Never inferred object" return None def go(): numColumnsOptions = range(1, len(LOCATIONS) + 1) # TODO If this runs for too long, Python eventually segfaults. # We might have C code overrunning a buffer somewhere. configs = (("Placeholder 13", 13), # ("Placeholder 20", 20), # ("Placeholder 30", 30), # ("Placeholder everything", -1), ) numTouchesLog = defaultdict(list) for config in configs: _, sampleSize = config print "sampleSize %d" % sampleSize for numColumns in numColumnsOptions: print "%d columns" % numColumns for _ in xrange(10): numTouches = experiment(numColumns, sampleSize) numTouchesLog[(numColumns, config)].append(numTouches) averages = dict((k, sum(numsTouches) / float(len(numsTouches))) for k, numsTouches in numTouchesLog.iteritems()) plt.figure() colorList = dict(zip(configs, ('r', 'k', 'g', 'b'))) markerList = dict(zip(configs, ('o', '*', 'D', 'x'))) for config in configs: plt.plot(numColumnsOptions, [averages[(numColumns, config)] for numColumns in numColumnsOptions], color=colorList[config], marker=markerList[config]) plt.legend([description for description, _ in configs], loc="upper right") plt.xlabel("Columns") plt.xticks(numColumnsOptions) plt.ylabel("Number of touches") plt.yticks([0, 1, 2, 3, 4, 5]) plt.title("Touches until inference") plotPath = os.path.join("plots", "infer_hand_crafted_objects.pdf") plt.savefig(plotPath) plt.close() if __name__ == "__main__": go()
agpl-3.0
mbayon/TFG-MachineLearning
vbig/lib/python2.7/site-packages/sklearn/svm/tests/test_svm.py
33
35916
""" Testing for Support Vector Machine module (sklearn.svm) TODO: remove hard coded numerical results when possible """ import numpy as np import itertools from numpy.testing import assert_array_equal, assert_array_almost_equal from numpy.testing import assert_almost_equal from numpy.testing import assert_allclose from scipy import sparse from sklearn import svm, linear_model, datasets, metrics, base from sklearn.model_selection import train_test_split from sklearn.datasets import make_classification, make_blobs from sklearn.metrics import f1_score from sklearn.metrics.pairwise import rbf_kernel from sklearn.utils import check_random_state from sklearn.utils.testing import assert_equal, assert_true, assert_false from sklearn.utils.testing import assert_greater, assert_in, assert_less from sklearn.utils.testing import assert_raises_regexp, assert_warns from sklearn.utils.testing import assert_warns_message, assert_raise_message from sklearn.utils.testing import ignore_warnings, assert_raises from sklearn.exceptions import ConvergenceWarning from sklearn.exceptions import NotFittedError from sklearn.multiclass import OneVsRestClassifier from sklearn.externals import six # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] Y = [1, 1, 1, 2, 2, 2] T = [[-1, -1], [2, 2], [3, 2]] true_result = [1, 2, 2] # also load the iris dataset iris = datasets.load_iris() rng = check_random_state(42) perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] def test_libsvm_parameters(): # Test parameters on classes that make use of libsvm. clf = svm.SVC(kernel='linear').fit(X, Y) assert_array_equal(clf.dual_coef_, [[-0.25, .25]]) assert_array_equal(clf.support_, [1, 3]) assert_array_equal(clf.support_vectors_, (X[1], X[3])) assert_array_equal(clf.intercept_, [0.]) assert_array_equal(clf.predict(X), Y) def test_libsvm_iris(): # Check consistency on dataset iris. # shuffle the dataset so that labels are not ordered for k in ('linear', 'rbf'): clf = svm.SVC(kernel=k).fit(iris.data, iris.target) assert_greater(np.mean(clf.predict(iris.data) == iris.target), 0.9) assert_true(hasattr(clf, "coef_") == (k == 'linear')) assert_array_equal(clf.classes_, np.sort(clf.classes_)) # check also the low-level API model = svm.libsvm.fit(iris.data, iris.target.astype(np.float64)) pred = svm.libsvm.predict(iris.data, *model) assert_greater(np.mean(pred == iris.target), .95) model = svm.libsvm.fit(iris.data, iris.target.astype(np.float64), kernel='linear') pred = svm.libsvm.predict(iris.data, *model, kernel='linear') assert_greater(np.mean(pred == iris.target), .95) pred = svm.libsvm.cross_validation(iris.data, iris.target.astype(np.float64), 5, kernel='linear', random_seed=0) assert_greater(np.mean(pred == iris.target), .95) # If random_seed >= 0, the libsvm rng is seeded (by calling `srand`), hence # we should get deterministic results (assuming that there is no other # thread calling this wrapper calling `srand` concurrently). pred2 = svm.libsvm.cross_validation(iris.data, iris.target.astype(np.float64), 5, kernel='linear', random_seed=0) assert_array_equal(pred, pred2) def test_precomputed(): # SVC with a precomputed kernel. # We test it with a toy dataset and with iris. clf = svm.SVC(kernel='precomputed') # Gram matrix for train data (square matrix) # (we use just a linear kernel) K = np.dot(X, np.array(X).T) clf.fit(K, Y) # Gram matrix for test data (rectangular matrix) KT = np.dot(T, np.array(X).T) pred = clf.predict(KT) assert_raises(ValueError, clf.predict, KT.T) assert_array_equal(clf.dual_coef_, [[-0.25, .25]]) assert_array_equal(clf.support_, [1, 3]) assert_array_equal(clf.intercept_, [0]) assert_array_almost_equal(clf.support_, [1, 3]) assert_array_equal(pred, true_result) # Gram matrix for test data but compute KT[i,j] # for support vectors j only. KT = np.zeros_like(KT) for i in range(len(T)): for j in clf.support_: KT[i, j] = np.dot(T[i], X[j]) pred = clf.predict(KT) assert_array_equal(pred, true_result) # same as before, but using a callable function instead of the kernel # matrix. kernel is just a linear kernel kfunc = lambda x, y: np.dot(x, y.T) clf = svm.SVC(kernel=kfunc) clf.fit(X, Y) pred = clf.predict(T) assert_array_equal(clf.dual_coef_, [[-0.25, .25]]) assert_array_equal(clf.intercept_, [0]) assert_array_almost_equal(clf.support_, [1, 3]) assert_array_equal(pred, true_result) # test a precomputed kernel with the iris dataset # and check parameters against a linear SVC clf = svm.SVC(kernel='precomputed') clf2 = svm.SVC(kernel='linear') K = np.dot(iris.data, iris.data.T) clf.fit(K, iris.target) clf2.fit(iris.data, iris.target) pred = clf.predict(K) assert_array_almost_equal(clf.support_, clf2.support_) assert_array_almost_equal(clf.dual_coef_, clf2.dual_coef_) assert_array_almost_equal(clf.intercept_, clf2.intercept_) assert_almost_equal(np.mean(pred == iris.target), .99, decimal=2) # Gram matrix for test data but compute KT[i,j] # for support vectors j only. K = np.zeros_like(K) for i in range(len(iris.data)): for j in clf.support_: K[i, j] = np.dot(iris.data[i], iris.data[j]) pred = clf.predict(K) assert_almost_equal(np.mean(pred == iris.target), .99, decimal=2) clf = svm.SVC(kernel=kfunc) clf.fit(iris.data, iris.target) assert_almost_equal(np.mean(pred == iris.target), .99, decimal=2) def test_svr(): # Test Support Vector Regression diabetes = datasets.load_diabetes() for clf in (svm.NuSVR(kernel='linear', nu=.4, C=1.0), svm.NuSVR(kernel='linear', nu=.4, C=10.), svm.SVR(kernel='linear', C=10.), svm.LinearSVR(C=10.), svm.LinearSVR(C=10.), ): clf.fit(diabetes.data, diabetes.target) assert_greater(clf.score(diabetes.data, diabetes.target), 0.02) # non-regression test; previously, BaseLibSVM would check that # len(np.unique(y)) < 2, which must only be done for SVC svm.SVR().fit(diabetes.data, np.ones(len(diabetes.data))) svm.LinearSVR().fit(diabetes.data, np.ones(len(diabetes.data))) def test_linearsvr(): # check that SVR(kernel='linear') and LinearSVC() give # comparable results diabetes = datasets.load_diabetes() lsvr = svm.LinearSVR(C=1e3).fit(diabetes.data, diabetes.target) score1 = lsvr.score(diabetes.data, diabetes.target) svr = svm.SVR(kernel='linear', C=1e3).fit(diabetes.data, diabetes.target) score2 = svr.score(diabetes.data, diabetes.target) assert_allclose(np.linalg.norm(lsvr.coef_), np.linalg.norm(svr.coef_), 1, 0.0001) assert_almost_equal(score1, score2, 2) def test_linearsvr_fit_sampleweight(): # check correct result when sample_weight is 1 # check that SVR(kernel='linear') and LinearSVC() give # comparable results diabetes = datasets.load_diabetes() n_samples = len(diabetes.target) unit_weight = np.ones(n_samples) lsvr = svm.LinearSVR(C=1e3).fit(diabetes.data, diabetes.target, sample_weight=unit_weight) score1 = lsvr.score(diabetes.data, diabetes.target) lsvr_no_weight = svm.LinearSVR(C=1e3).fit(diabetes.data, diabetes.target) score2 = lsvr_no_weight.score(diabetes.data, diabetes.target) assert_allclose(np.linalg.norm(lsvr.coef_), np.linalg.norm(lsvr_no_weight.coef_), 1, 0.0001) assert_almost_equal(score1, score2, 2) # check that fit(X) = fit([X1, X2, X3],sample_weight = [n1, n2, n3]) where # X = X1 repeated n1 times, X2 repeated n2 times and so forth random_state = check_random_state(0) random_weight = random_state.randint(0, 10, n_samples) lsvr_unflat = svm.LinearSVR(C=1e3).fit(diabetes.data, diabetes.target, sample_weight=random_weight) score3 = lsvr_unflat.score(diabetes.data, diabetes.target, sample_weight=random_weight) X_flat = np.repeat(diabetes.data, random_weight, axis=0) y_flat = np.repeat(diabetes.target, random_weight, axis=0) lsvr_flat = svm.LinearSVR(C=1e3).fit(X_flat, y_flat) score4 = lsvr_flat.score(X_flat, y_flat) assert_almost_equal(score3, score4, 2) def test_svr_errors(): X = [[0.0], [1.0]] y = [0.0, 0.5] # Bad kernel clf = svm.SVR(kernel=lambda x, y: np.array([[1.0]])) clf.fit(X, y) assert_raises(ValueError, clf.predict, X) def test_oneclass(): # Test OneClassSVM clf = svm.OneClassSVM() clf.fit(X) pred = clf.predict(T) assert_array_equal(pred, [-1, -1, -1]) assert_equal(pred.dtype, np.dtype('intp')) assert_array_almost_equal(clf.intercept_, [-1.008], decimal=3) assert_array_almost_equal(clf.dual_coef_, [[0.632, 0.233, 0.633, 0.234, 0.632, 0.633]], decimal=3) assert_raises(AttributeError, lambda: clf.coef_) def test_oneclass_decision_function(): # Test OneClassSVM decision function clf = svm.OneClassSVM() rnd = check_random_state(2) # Generate train data X = 0.3 * rnd.randn(100, 2) X_train = np.r_[X + 2, X - 2] # Generate some regular novel observations X = 0.3 * rnd.randn(20, 2) X_test = np.r_[X + 2, X - 2] # Generate some abnormal novel observations X_outliers = rnd.uniform(low=-4, high=4, size=(20, 2)) # fit the model clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1) clf.fit(X_train) # predict things y_pred_test = clf.predict(X_test) assert_greater(np.mean(y_pred_test == 1), .9) y_pred_outliers = clf.predict(X_outliers) assert_greater(np.mean(y_pred_outliers == -1), .9) dec_func_test = clf.decision_function(X_test) assert_array_equal((dec_func_test > 0).ravel(), y_pred_test == 1) dec_func_outliers = clf.decision_function(X_outliers) assert_array_equal((dec_func_outliers > 0).ravel(), y_pred_outliers == 1) def test_tweak_params(): # Make sure some tweaking of parameters works. # We change clf.dual_coef_ at run time and expect .predict() to change # accordingly. Notice that this is not trivial since it involves a lot # of C/Python copying in the libsvm bindings. # The success of this test ensures that the mapping between libsvm and # the python classifier is complete. clf = svm.SVC(kernel='linear', C=1.0) clf.fit(X, Y) assert_array_equal(clf.dual_coef_, [[-.25, .25]]) assert_array_equal(clf.predict([[-.1, -.1]]), [1]) clf._dual_coef_ = np.array([[.0, 1.]]) assert_array_equal(clf.predict([[-.1, -.1]]), [2]) def test_probability(): # Predict probabilities using SVC # This uses cross validation, so we use a slightly bigger testing set. for clf in (svm.SVC(probability=True, random_state=0, C=1.0), svm.NuSVC(probability=True, random_state=0)): clf.fit(iris.data, iris.target) prob_predict = clf.predict_proba(iris.data) assert_array_almost_equal( np.sum(prob_predict, 1), np.ones(iris.data.shape[0])) assert_true(np.mean(np.argmax(prob_predict, 1) == clf.predict(iris.data)) > 0.9) assert_almost_equal(clf.predict_proba(iris.data), np.exp(clf.predict_log_proba(iris.data)), 8) def test_decision_function(): # Test decision_function # Sanity check, test that decision_function implemented in python # returns the same as the one in libsvm # multi class: clf = svm.SVC(kernel='linear', C=0.1, decision_function_shape='ovo').fit(iris.data, iris.target) dec = np.dot(iris.data, clf.coef_.T) + clf.intercept_ assert_array_almost_equal(dec, clf.decision_function(iris.data)) # binary: clf.fit(X, Y) dec = np.dot(X, clf.coef_.T) + clf.intercept_ prediction = clf.predict(X) assert_array_almost_equal(dec.ravel(), clf.decision_function(X)) assert_array_almost_equal( prediction, clf.classes_[(clf.decision_function(X) > 0).astype(np.int)]) expected = np.array([-1., -0.66, -1., 0.66, 1., 1.]) assert_array_almost_equal(clf.decision_function(X), expected, 2) # kernel binary: clf = svm.SVC(kernel='rbf', gamma=1, decision_function_shape='ovo') clf.fit(X, Y) rbfs = rbf_kernel(X, clf.support_vectors_, gamma=clf.gamma) dec = np.dot(rbfs, clf.dual_coef_.T) + clf.intercept_ assert_array_almost_equal(dec.ravel(), clf.decision_function(X)) def test_decision_function_shape(): # check that decision_function_shape='ovr' gives # correct shape and is consistent with predict clf = svm.SVC(kernel='linear', C=0.1, decision_function_shape='ovr').fit(iris.data, iris.target) dec = clf.decision_function(iris.data) assert_equal(dec.shape, (len(iris.data), 3)) assert_array_equal(clf.predict(iris.data), np.argmax(dec, axis=1)) # with five classes: X, y = make_blobs(n_samples=80, centers=5, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = svm.SVC(kernel='linear', C=0.1, decision_function_shape='ovr').fit(X_train, y_train) dec = clf.decision_function(X_test) assert_equal(dec.shape, (len(X_test), 5)) assert_array_equal(clf.predict(X_test), np.argmax(dec, axis=1)) # check shape of ovo_decition_function=True clf = svm.SVC(kernel='linear', C=0.1, decision_function_shape='ovo').fit(X_train, y_train) dec = clf.decision_function(X_train) assert_equal(dec.shape, (len(X_train), 10)) def test_svr_predict(): # Test SVR's decision_function # Sanity check, test that predict implemented in python # returns the same as the one in libsvm X = iris.data y = iris.target # linear kernel reg = svm.SVR(kernel='linear', C=0.1).fit(X, y) dec = np.dot(X, reg.coef_.T) + reg.intercept_ assert_array_almost_equal(dec.ravel(), reg.predict(X).ravel()) # rbf kernel reg = svm.SVR(kernel='rbf', gamma=1).fit(X, y) rbfs = rbf_kernel(X, reg.support_vectors_, gamma=reg.gamma) dec = np.dot(rbfs, reg.dual_coef_.T) + reg.intercept_ assert_array_almost_equal(dec.ravel(), reg.predict(X).ravel()) def test_weight(): # Test class weights clf = svm.SVC(class_weight={1: 0.1}) # we give a small weights to class 1 clf.fit(X, Y) # so all predicted values belong to class 2 assert_array_almost_equal(clf.predict(X), [2] * 6) X_, y_ = make_classification(n_samples=200, n_features=10, weights=[0.833, 0.167], random_state=2) for clf in (linear_model.LogisticRegression(), svm.LinearSVC(random_state=0), svm.SVC()): clf.set_params(class_weight={0: .1, 1: 10}) clf.fit(X_[:100], y_[:100]) y_pred = clf.predict(X_[100:]) assert_true(f1_score(y_[100:], y_pred) > .3) def test_sample_weights(): # Test weights on individual samples # TODO: check on NuSVR, OneClass, etc. clf = svm.SVC() clf.fit(X, Y) assert_array_equal(clf.predict([X[2]]), [1.]) sample_weight = [.1] * 3 + [10] * 3 clf.fit(X, Y, sample_weight=sample_weight) assert_array_equal(clf.predict([X[2]]), [2.]) # test that rescaling all samples is the same as changing C clf = svm.SVC() clf.fit(X, Y) dual_coef_no_weight = clf.dual_coef_ clf.set_params(C=100) clf.fit(X, Y, sample_weight=np.repeat(0.01, len(X))) assert_array_almost_equal(dual_coef_no_weight, clf.dual_coef_) def test_auto_weight(): # Test class weights for imbalanced data from sklearn.linear_model import LogisticRegression # We take as dataset the two-dimensional projection of iris so # that it is not separable and remove half of predictors from # class 1. # We add one to the targets as a non-regression test: class_weight="balanced" # used to work only when the labels where a range [0..K). from sklearn.utils import compute_class_weight X, y = iris.data[:, :2], iris.target + 1 unbalanced = np.delete(np.arange(y.size), np.where(y > 2)[0][::2]) classes = np.unique(y[unbalanced]) class_weights = compute_class_weight('balanced', classes, y[unbalanced]) assert_true(np.argmax(class_weights) == 2) for clf in (svm.SVC(kernel='linear'), svm.LinearSVC(random_state=0), LogisticRegression()): # check that score is better when class='balanced' is set. y_pred = clf.fit(X[unbalanced], y[unbalanced]).predict(X) clf.set_params(class_weight='balanced') y_pred_balanced = clf.fit(X[unbalanced], y[unbalanced],).predict(X) assert_true(metrics.f1_score(y, y_pred, average='macro') <= metrics.f1_score(y, y_pred_balanced, average='macro')) def test_bad_input(): # Test that it gives proper exception on deficient input # impossible value of C assert_raises(ValueError, svm.SVC(C=-1).fit, X, Y) # impossible value of nu clf = svm.NuSVC(nu=0.0) assert_raises(ValueError, clf.fit, X, Y) Y2 = Y[:-1] # wrong dimensions for labels assert_raises(ValueError, clf.fit, X, Y2) # Test with arrays that are non-contiguous. for clf in (svm.SVC(), svm.LinearSVC(random_state=0)): Xf = np.asfortranarray(X) assert_false(Xf.flags['C_CONTIGUOUS']) yf = np.ascontiguousarray(np.tile(Y, (2, 1)).T) yf = yf[:, -1] assert_false(yf.flags['F_CONTIGUOUS']) assert_false(yf.flags['C_CONTIGUOUS']) clf.fit(Xf, yf) assert_array_equal(clf.predict(T), true_result) # error for precomputed kernelsx clf = svm.SVC(kernel='precomputed') assert_raises(ValueError, clf.fit, X, Y) # sample_weight bad dimensions clf = svm.SVC() assert_raises(ValueError, clf.fit, X, Y, sample_weight=range(len(X) - 1)) # predict with sparse input when trained with dense clf = svm.SVC().fit(X, Y) assert_raises(ValueError, clf.predict, sparse.lil_matrix(X)) Xt = np.array(X).T clf.fit(np.dot(X, Xt), Y) assert_raises(ValueError, clf.predict, X) clf = svm.SVC() clf.fit(X, Y) assert_raises(ValueError, clf.predict, Xt) def test_unicode_kernel(): # Test that a unicode kernel name does not cause a TypeError on clf.fit if six.PY2: # Test unicode (same as str on python3) clf = svm.SVC(kernel=unicode('linear')) clf.fit(X, Y) # Test ascii bytes (str is bytes in python2) clf = svm.SVC(kernel=str('linear')) clf.fit(X, Y) else: # Test unicode (str is unicode in python3) clf = svm.SVC(kernel=str('linear')) clf.fit(X, Y) # Test ascii bytes (same as str on python2) clf = svm.SVC(kernel=bytes('linear', 'ascii')) clf.fit(X, Y) # Test default behavior on both versions clf = svm.SVC(kernel='linear') clf.fit(X, Y) def test_sparse_precomputed(): clf = svm.SVC(kernel='precomputed') sparse_gram = sparse.csr_matrix([[1, 0], [0, 1]]) try: clf.fit(sparse_gram, [0, 1]) assert not "reached" except TypeError as e: assert_in("Sparse precomputed", str(e)) def test_linearsvc_parameters(): # Test possible parameter combinations in LinearSVC # Generate list of possible parameter combinations losses = ['hinge', 'squared_hinge', 'logistic_regression', 'foo'] penalties, duals = ['l1', 'l2', 'bar'], [True, False] X, y = make_classification(n_samples=5, n_features=5) for loss, penalty, dual in itertools.product(losses, penalties, duals): clf = svm.LinearSVC(penalty=penalty, loss=loss, dual=dual) if ((loss, penalty) == ('hinge', 'l1') or (loss, penalty, dual) == ('hinge', 'l2', False) or (penalty, dual) == ('l1', True) or loss == 'foo' or penalty == 'bar'): assert_raises_regexp(ValueError, "Unsupported set of arguments.*penalty='%s.*" "loss='%s.*dual=%s" % (penalty, loss, dual), clf.fit, X, y) else: clf.fit(X, y) # Incorrect loss value - test if explicit error message is raised assert_raises_regexp(ValueError, ".*loss='l3' is not supported.*", svm.LinearSVC(loss="l3").fit, X, y) # FIXME remove in 1.0 def test_linearsvx_loss_penalty_deprecations(): X, y = [[0.0], [1.0]], [0, 1] msg = ("loss='%s' has been deprecated in favor of " "loss='%s' as of 0.16. Backward compatibility" " for the %s will be removed in %s") # LinearSVC # loss l1 --> hinge assert_warns_message(DeprecationWarning, msg % ("l1", "hinge", "loss='l1'", "1.0"), svm.LinearSVC(loss="l1").fit, X, y) # loss l2 --> squared_hinge assert_warns_message(DeprecationWarning, msg % ("l2", "squared_hinge", "loss='l2'", "1.0"), svm.LinearSVC(loss="l2").fit, X, y) # LinearSVR # loss l1 --> epsilon_insensitive assert_warns_message(DeprecationWarning, msg % ("l1", "epsilon_insensitive", "loss='l1'", "1.0"), svm.LinearSVR(loss="l1").fit, X, y) # loss l2 --> squared_epsilon_insensitive assert_warns_message(DeprecationWarning, msg % ("l2", "squared_epsilon_insensitive", "loss='l2'", "1.0"), svm.LinearSVR(loss="l2").fit, X, y) def test_linear_svx_uppercase_loss_penality_raises_error(): # Check if Upper case notation raises error at _fit_liblinear # which is called by fit X, y = [[0.0], [1.0]], [0, 1] assert_raise_message(ValueError, "loss='SQuared_hinge' is not supported", svm.LinearSVC(loss="SQuared_hinge").fit, X, y) assert_raise_message(ValueError, ("The combination of penalty='L2'" " and loss='squared_hinge' is not supported"), svm.LinearSVC(penalty="L2").fit, X, y) def test_linearsvc(): # Test basic routines using LinearSVC clf = svm.LinearSVC(random_state=0).fit(X, Y) # by default should have intercept assert_true(clf.fit_intercept) assert_array_equal(clf.predict(T), true_result) assert_array_almost_equal(clf.intercept_, [0], decimal=3) # the same with l1 penalty clf = svm.LinearSVC(penalty='l1', loss='squared_hinge', dual=False, random_state=0).fit(X, Y) assert_array_equal(clf.predict(T), true_result) # l2 penalty with dual formulation clf = svm.LinearSVC(penalty='l2', dual=True, random_state=0).fit(X, Y) assert_array_equal(clf.predict(T), true_result) # l2 penalty, l1 loss clf = svm.LinearSVC(penalty='l2', loss='hinge', dual=True, random_state=0) clf.fit(X, Y) assert_array_equal(clf.predict(T), true_result) # test also decision function dec = clf.decision_function(T) res = (dec > 0).astype(np.int) + 1 assert_array_equal(res, true_result) def test_linearsvc_crammer_singer(): # Test LinearSVC with crammer_singer multi-class svm ovr_clf = svm.LinearSVC(random_state=0).fit(iris.data, iris.target) cs_clf = svm.LinearSVC(multi_class='crammer_singer', random_state=0) cs_clf.fit(iris.data, iris.target) # similar prediction for ovr and crammer-singer: assert_true((ovr_clf.predict(iris.data) == cs_clf.predict(iris.data)).mean() > .9) # classifiers shouldn't be the same assert_true((ovr_clf.coef_ != cs_clf.coef_).all()) # test decision function assert_array_equal(cs_clf.predict(iris.data), np.argmax(cs_clf.decision_function(iris.data), axis=1)) dec_func = np.dot(iris.data, cs_clf.coef_.T) + cs_clf.intercept_ assert_array_almost_equal(dec_func, cs_clf.decision_function(iris.data)) def test_linearsvc_fit_sampleweight(): # check correct result when sample_weight is 1 n_samples = len(X) unit_weight = np.ones(n_samples) clf = svm.LinearSVC(random_state=0).fit(X, Y) clf_unitweight = svm.LinearSVC(random_state=0).\ fit(X, Y, sample_weight=unit_weight) # check if same as sample_weight=None assert_array_equal(clf_unitweight.predict(T), clf.predict(T)) assert_allclose(clf.coef_, clf_unitweight.coef_, 1, 0.0001) # check that fit(X) = fit([X1, X2, X3],sample_weight = [n1, n2, n3]) where # X = X1 repeated n1 times, X2 repeated n2 times and so forth random_state = check_random_state(0) random_weight = random_state.randint(0, 10, n_samples) lsvc_unflat = svm.LinearSVC(random_state=0).\ fit(X, Y, sample_weight=random_weight) pred1 = lsvc_unflat.predict(T) X_flat = np.repeat(X, random_weight, axis=0) y_flat = np.repeat(Y, random_weight, axis=0) lsvc_flat = svm.LinearSVC(random_state=0).fit(X_flat, y_flat) pred2 = lsvc_flat.predict(T) assert_array_equal(pred1, pred2) assert_allclose(lsvc_unflat.coef_, lsvc_flat.coef_, 1, 0.0001) def test_crammer_singer_binary(): # Test Crammer-Singer formulation in the binary case X, y = make_classification(n_classes=2, random_state=0) for fit_intercept in (True, False): acc = svm.LinearSVC(fit_intercept=fit_intercept, multi_class="crammer_singer", random_state=0).fit(X, y).score(X, y) assert_greater(acc, 0.9) def test_linearsvc_iris(): # Test that LinearSVC gives plausible predictions on the iris dataset # Also, test symbolic class names (classes_). target = iris.target_names[iris.target] clf = svm.LinearSVC(random_state=0).fit(iris.data, target) assert_equal(set(clf.classes_), set(iris.target_names)) assert_greater(np.mean(clf.predict(iris.data) == target), 0.8) dec = clf.decision_function(iris.data) pred = iris.target_names[np.argmax(dec, 1)] assert_array_equal(pred, clf.predict(iris.data)) def test_dense_liblinear_intercept_handling(classifier=svm.LinearSVC): # Test that dense liblinear honours intercept_scaling param X = [[2, 1], [3, 1], [1, 3], [2, 3]] y = [0, 0, 1, 1] clf = classifier(fit_intercept=True, penalty='l1', loss='squared_hinge', dual=False, C=4, tol=1e-7, random_state=0) assert_true(clf.intercept_scaling == 1, clf.intercept_scaling) assert_true(clf.fit_intercept) # when intercept_scaling is low the intercept value is highly "penalized" # by regularization clf.intercept_scaling = 1 clf.fit(X, y) assert_almost_equal(clf.intercept_, 0, decimal=5) # when intercept_scaling is sufficiently high, the intercept value # is not affected by regularization clf.intercept_scaling = 100 clf.fit(X, y) intercept1 = clf.intercept_ assert_less(intercept1, -1) # when intercept_scaling is sufficiently high, the intercept value # doesn't depend on intercept_scaling value clf.intercept_scaling = 1000 clf.fit(X, y) intercept2 = clf.intercept_ assert_array_almost_equal(intercept1, intercept2, decimal=2) def test_liblinear_set_coef(): # multi-class case clf = svm.LinearSVC().fit(iris.data, iris.target) values = clf.decision_function(iris.data) clf.coef_ = clf.coef_.copy() clf.intercept_ = clf.intercept_.copy() values2 = clf.decision_function(iris.data) assert_array_almost_equal(values, values2) # binary-class case X = [[2, 1], [3, 1], [1, 3], [2, 3]] y = [0, 0, 1, 1] clf = svm.LinearSVC().fit(X, y) values = clf.decision_function(X) clf.coef_ = clf.coef_.copy() clf.intercept_ = clf.intercept_.copy() values2 = clf.decision_function(X) assert_array_equal(values, values2) def test_immutable_coef_property(): # Check that primal coef modification are not silently ignored svms = [ svm.SVC(kernel='linear').fit(iris.data, iris.target), svm.NuSVC(kernel='linear').fit(iris.data, iris.target), svm.SVR(kernel='linear').fit(iris.data, iris.target), svm.NuSVR(kernel='linear').fit(iris.data, iris.target), svm.OneClassSVM(kernel='linear').fit(iris.data), ] for clf in svms: assert_raises(AttributeError, clf.__setattr__, 'coef_', np.arange(3)) assert_raises((RuntimeError, ValueError), clf.coef_.__setitem__, (0, 0), 0) def test_linearsvc_verbose(): # stdout: redirect import os stdout = os.dup(1) # save original stdout os.dup2(os.pipe()[1], 1) # replace it # actual call clf = svm.LinearSVC(verbose=1) clf.fit(X, Y) # stdout: restore os.dup2(stdout, 1) # restore original stdout def test_svc_clone_with_callable_kernel(): # create SVM with callable linear kernel, check that results are the same # as with built-in linear kernel svm_callable = svm.SVC(kernel=lambda x, y: np.dot(x, y.T), probability=True, random_state=0, decision_function_shape='ovr') # clone for checking clonability with lambda functions.. svm_cloned = base.clone(svm_callable) svm_cloned.fit(iris.data, iris.target) svm_builtin = svm.SVC(kernel='linear', probability=True, random_state=0, decision_function_shape='ovr') svm_builtin.fit(iris.data, iris.target) assert_array_almost_equal(svm_cloned.dual_coef_, svm_builtin.dual_coef_) assert_array_almost_equal(svm_cloned.intercept_, svm_builtin.intercept_) assert_array_equal(svm_cloned.predict(iris.data), svm_builtin.predict(iris.data)) assert_array_almost_equal(svm_cloned.predict_proba(iris.data), svm_builtin.predict_proba(iris.data), decimal=4) assert_array_almost_equal(svm_cloned.decision_function(iris.data), svm_builtin.decision_function(iris.data)) def test_svc_bad_kernel(): svc = svm.SVC(kernel=lambda x, y: x) assert_raises(ValueError, svc.fit, X, Y) def test_timeout(): a = svm.SVC(kernel=lambda x, y: np.dot(x, y.T), probability=True, random_state=0, max_iter=1) assert_warns(ConvergenceWarning, a.fit, X, Y) def test_unfitted(): X = "foo!" # input validation not required when SVM not fitted clf = svm.SVC() assert_raises_regexp(Exception, r".*\bSVC\b.*\bnot\b.*\bfitted\b", clf.predict, X) clf = svm.NuSVR() assert_raises_regexp(Exception, r".*\bNuSVR\b.*\bnot\b.*\bfitted\b", clf.predict, X) # ignore convergence warnings from max_iter=1 @ignore_warnings def test_consistent_proba(): a = svm.SVC(probability=True, max_iter=1, random_state=0) proba_1 = a.fit(X, Y).predict_proba(X) a = svm.SVC(probability=True, max_iter=1, random_state=0) proba_2 = a.fit(X, Y).predict_proba(X) assert_array_almost_equal(proba_1, proba_2) def test_linear_svc_convergence_warnings(): # Test that warnings are raised if model does not converge lsvc = svm.LinearSVC(max_iter=2, verbose=1) assert_warns(ConvergenceWarning, lsvc.fit, X, Y) assert_equal(lsvc.n_iter_, 2) def test_svr_coef_sign(): # Test that SVR(kernel="linear") has coef_ with the right sign. # Non-regression test for #2933. X = np.random.RandomState(21).randn(10, 3) y = np.random.RandomState(12).randn(10) for svr in [svm.SVR(kernel='linear'), svm.NuSVR(kernel='linear'), svm.LinearSVR()]: svr.fit(X, y) assert_array_almost_equal(svr.predict(X), np.dot(X, svr.coef_.ravel()) + svr.intercept_) def test_linear_svc_intercept_scaling(): # Test that the right error message is thrown when intercept_scaling <= 0 for i in [-1, 0]: lsvc = svm.LinearSVC(intercept_scaling=i) msg = ('Intercept scaling is %r but needs to be greater than 0.' ' To disable fitting an intercept,' ' set fit_intercept=False.' % lsvc.intercept_scaling) assert_raise_message(ValueError, msg, lsvc.fit, X, Y) def test_lsvc_intercept_scaling_zero(): # Test that intercept_scaling is ignored when fit_intercept is False lsvc = svm.LinearSVC(fit_intercept=False) lsvc.fit(X, Y) assert_equal(lsvc.intercept_, 0.) def test_hasattr_predict_proba(): # Method must be (un)available before or after fit, switched by # `probability` param G = svm.SVC(probability=True) assert_true(hasattr(G, 'predict_proba')) G.fit(iris.data, iris.target) assert_true(hasattr(G, 'predict_proba')) G = svm.SVC(probability=False) assert_false(hasattr(G, 'predict_proba')) G.fit(iris.data, iris.target) assert_false(hasattr(G, 'predict_proba')) # Switching to `probability=True` after fitting should make # predict_proba available, but calling it must not work: G.probability = True assert_true(hasattr(G, 'predict_proba')) msg = "predict_proba is not available when fitted with probability=False" assert_raise_message(NotFittedError, msg, G.predict_proba, iris.data) def test_decision_function_shape_two_class(): for n_classes in [2, 3]: X, y = make_blobs(centers=n_classes, random_state=0) for estimator in [svm.SVC, svm.NuSVC]: clf = OneVsRestClassifier(estimator( decision_function_shape="ovr")).fit(X, y) assert_equal(len(clf.predict(X)), len(y)) def test_ovr_decision_function(): # One point from each quadrant represents one class X_train = np.array([[1, 1], [-1, 1], [-1, -1], [1, -1]]) y_train = [0, 1, 2, 3] # First point is closer to the decision boundaries than the second point base_points = np.array([[5, 5], [10, 10]]) # For all the quadrants (classes) X_test = np.vstack(( base_points * [1, 1], # Q1 base_points * [-1, 1], # Q2 base_points * [-1, -1], # Q3 base_points * [1, -1] # Q4 )) y_test = [0] * 2 + [1] * 2 + [2] * 2 + [3] * 2 clf = svm.SVC(kernel='linear', decision_function_shape='ovr') clf.fit(X_train, y_train) y_pred = clf.predict(X_test) # Test if the prediction is the same as y assert_array_equal(y_pred, y_test) deci_val = clf.decision_function(X_test) # Assert that the predicted class has the maximum value assert_array_equal(np.argmax(deci_val, axis=1), y_pred) # Get decision value at test points for the predicted class pred_class_deci_val = deci_val[range(8), y_pred].reshape((4, 2)) # Assert pred_class_deci_val > 0 here assert_greater(np.min(pred_class_deci_val), 0.0) # Test if the first point has lower decision value on every quadrant # compared to the second point assert_true(np.all(pred_class_deci_val[:, 0] < pred_class_deci_val[:, 1]))
mit
stephenjust/stk-stats
userreport/views/usercount.py
1
1645
from userreport.models import UserReport from django.http import HttpResponse from django.views.decorators.cache import cache_page from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter import matplotlib.artist @cache_page(60 * 120) def ReportUsercount(request): reports = UserReport.objects.\ order_by('upload_date') users_by_date = {} for report in reports: t = report.upload_date.date() # group by day users_by_date.setdefault(t, set()).add(report.user_id_hash) seen_users = set() data_scatter = ([], [], []) for date,users in sorted(users_by_date.items()): data_scatter[0].append(date) data_scatter[1].append(len(users)) data_scatter[2].append(len(users - seen_users)) seen_users |= users fig = Figure(figsize=(12,6)) ax = fig.add_subplot(111) fig.subplots_adjust(left = 0.08, right = 0.95, top = 0.95, bottom = 0.2) ax.plot(data_scatter[0], data_scatter[1], marker='o') ax.plot(data_scatter[0], data_scatter[2], marker='o') ax.legend(('Total users', 'New users'), 'upper left', frameon=False) matplotlib.artist.setp(ax.get_legend().get_texts(), fontsize='small') ax.set_ylabel('Number of users per day') for label in ax.get_xticklabels(): label.set_rotation(90) label.set_fontsize(9) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) canvas = FigureCanvas(fig) response = HttpResponse(content_type='image/png') canvas.print_png(response, dpi=80) return response
mit
lfairchild/PmagPy
programs/dmag_magic.py
1
9569
#!/usr/bin/env python # -*- python-indent-offset: 4; -*- # -*- mode: python-mode; python-indent-offset: 4 -*- import sys import os import matplotlib if matplotlib.get_backend() != "TKAgg": matplotlib.use("TKAgg") import pmagpy.pmag as pmag import pmagpy.pmagplotlib as pmagplotlib import pmagpy.contribution_builder as cb def plot(in_file="measurements.txt", dir_path=".", input_dir_path="", spec_file="specimens.txt", samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt", plot_by="loc", LT="AF", norm=True, XLP="", save_plots=True, fmt="svg"): """ plots intensity decay curves for demagnetization experiments Parameters ---------- in_file : str, default "measurements.txt" dir_path : str output directory, default "." input_dir_path : str input file directory (if different from dir_path), default "" spec_file : str input specimen file name, default "specimens.txt" samp_file: str input sample file name, default "samples.txt" site_file : str input site file name, default "sites.txt" loc_file : str input location file name, default "locations.txt" plot_by : str [spc, sam, sit, loc] (specimen, sample, site, location), default "loc" LT : str lab treatment [T, AF, M], default AF norm : bool normalize by NRM magnetization, default True XLP : str exclude specific lab protocols, (for example, method codes like LP-PI) default "" save_plots : bool plot and save non-interactively, default True fmt : str ["png", "svg", "pdf", "jpg"], default "svg" Returns --------- type - Tuple : (True or False indicating if conversion was sucessful, file name(s) written) """ dir_path = os.path.realpath(dir_path) if not input_dir_path: input_dir_path = dir_path input_dir_path = os.path.realpath(input_dir_path) # format plot_key name_dict = {'loc': 'location', 'sit': 'site', 'sam': 'sample', 'spc': 'specimen'} if plot_by not in name_dict.values(): try: plot_key = name_dict[plot_by] except KeyError: print('Unrecognized plot_by {}, falling back to plot by location'.format(plot_by)) plot_key = "loc" else: plot_key = plot_by # figure out what kind of experiment LT = "LT-" + LT + "-Z" print('LT', LT) if LT == "LT-T-Z": units, dmag_key = 'K', 'treat_temp' elif LT == "LT-AF-Z": units, dmag_key = 'T', 'treat_ac_field' elif LT == 'LT-M-Z': units, dmag_key = 'J', 'treat_mw_energy' else: units = 'U' # init FIG = {} # plot dictionary FIG['demag'] = 1 # demag is figure 1 # create contribution and add required headers fnames = {"specimens": spec_file, "samples": samp_file, 'sites': site_file, 'locations': loc_file} if not os.path.exists(pmag.resolve_file_name(in_file, input_dir_path)): print('-E- Could not find {}'.format(in_file)) return False, [] contribution = cb.Contribution(input_dir_path, single_file=in_file, custom_filenames=fnames) file_type = list(contribution.tables.keys())[0] print(len(contribution.tables['measurements'].df), ' records read from ', in_file) # add plot_key into measurements table if plot_key not in contribution.tables['measurements'].df.columns: #contribution.propagate_name_down(plot_key, 'measurements') contribution.propagate_location_to_measurements() data_container = contribution.tables[file_type] # pare down to only records with useful data # grab records that have the requested code data_slice = data_container.get_records_for_code(LT) # and don't have the offending code data = data_container.get_records_for_code(XLP, incl=False, use_slice=True, sli=data_slice, strict_match=False) # make sure quality is in the dataframe if 'quality' not in data.columns: data['quality'] = 'g' # get intensity key and make sure intensity data is not blank intlist = ['magn_moment', 'magn_volume', 'magn_mass'] IntMeths = [col_name for col_name in data.columns if col_name in intlist] # get rid of any entirely blank intensity columns for col_name in IntMeths: if not data[col_name].any(): data.drop(col_name, axis=1, inplace=True) IntMeths = [col_name for col_name in data.columns if col_name in intlist] if len(IntMeths) == 0: print('-E- No intensity headers found') return False, [] int_key = IntMeths[0] # plot first intensity method found - normalized to initial value anyway - doesn't matter which used data = data[data[int_key].notnull()] # make list of individual plots # by default, will be by location_name plotlist = data[plot_key].unique() plotlist.sort() pmagplotlib.plot_init(FIG['demag'], 5, 5) last_plot = False # iterate through and plot the data for plt in plotlist: if plt == plotlist[-1]: last_plot = True plot_data = data[data[plot_key] == plt].copy() if not save_plots: print(plt, 'plotting by: ', plot_key) if len(plot_data) > 2: title = plt spcs = [] spcs = plot_data['specimen'].unique() for spc in spcs: INTblock = [] spec_data = plot_data[plot_data['specimen'] == spc] for ind, rec in spec_data.iterrows(): INTblock.append([float(rec[dmag_key]), 0, 0, float(rec[int_key]), 1, rec['quality']]) if len(INTblock) > 2: pmagplotlib.plot_mag(FIG['demag'], INTblock, title, 0, units, norm) if save_plots: files = {} for key in list(FIG.keys()): if pmagplotlib.isServer: files[key] = title + '_' + LT + '.' + fmt incl_dir = False else: # if not server, include directory in output path files[key] = os.path.join(dir_path, title + '_' + LT + '.' + fmt) incl_dir = True pmagplotlib.save_plots(FIG, files, incl_directory=incl_dir) else: pmagplotlib.draw_figs(FIG) prompt = " S[a]ve to save plot, [q]uit, Return to continue: " ans = input(prompt) if ans == 'q': return True, [] if ans == "a": files = {} for key in list(FIG.keys()): if pmagplotlib.isServer: files[key] = title + '_' + LT + '.' + fmt incl_dir = False else: # if not server, include directory in output path files[key] = os.path.join(dir_path, title + '_' + LT + '.' + fmt) incl_dir = True pmagplotlib.save_plots(FIG, files, incl_directory=incl_dir) pmagplotlib.clearFIG(FIG['demag']) if last_plot: return True, [] def main(): """ NAME dmag_magic.py DESCRIPTION plots intensity decay curves for demagnetization experiments SYNTAX dmag_magic -h [command line options] INPUT takes magic formatted measurements.txt files OPTIONS -h prints help message and quits -f FILE: specify input file, default is: measurements.txt -obj OBJ: specify object [loc, sit, sam, spc] for plot, default is by location -LT [AF,T,M]: specify lab treatment type, default AF -XLP [PI]: exclude specific lab protocols, (for example, method codes like LP-PI) -N do not normalize by NRM magnetization -sav save plots silently and quit -fmt [svg,jpg,png,pdf] set figure format [default is svg] NOTE loc: location (study); sit: site; sam: sample; spc: specimen """ if '-h' in sys.argv: print(main.__doc__) sys.exit() # initialize variables from command line + defaults dir_path = pmag.get_named_arg("-WD", default_val=".") input_dir_path = pmag.get_named_arg('-ID', '') if not input_dir_path: input_dir_path = dir_path in_file = pmag.get_named_arg("-f", default_val="measurements.txt") in_file = pmag.resolve_file_name(in_file, input_dir_path) if "-ID" not in sys.argv: input_dir_path = os.path.split(in_file)[0] plot_by = pmag.get_named_arg("-obj", default_val="loc") LT = pmag.get_named_arg("-LT", "AF") no_norm = pmag.get_flag_arg_from_sys("-N") norm = False if no_norm else True save_plots = pmag.get_flag_arg_from_sys("-sav") fmt = pmag.get_named_arg("-fmt", "svg") XLP = pmag.get_named_arg("-XLP", "") spec_file = pmag.get_named_arg("-fsp", default_val="specimens.txt") samp_file = pmag.get_named_arg("-fsa", default_val="samples.txt") site_file = pmag.get_named_arg("-fsi", default_val="sites.txt") loc_file = pmag.get_named_arg("-flo", default_val="locations.txt") plot(in_file, dir_path, input_dir_path, spec_file, samp_file, site_file, loc_file, plot_by, LT, norm, XLP, save_plots, fmt) if __name__ == "__main__": main()
bsd-3-clause
rhambach/TEMareels
tools/remove_stripes.py
1
1747
""" IMPLEMENTATION: - crude method for removing periodic noise in images recorded on Tietz CMOS slave camera in wq-mode - integrates over several lines (e.g. 10x4096) of noise and substracts signal from each line in sector Copyright (c) 2013, pwachsmuth, rhambach This file is part of the TEMareels package and released under the MIT-Licence. See LICENCE file for details. """ import numpy as np import matplotlib.pylab as plt def remove_stripes(image, intwidth=10, intstart=[0,1025,2900,3800], sector_width=1024, mask = None, verbosity = 0): image = np.asarray(image) old_image = image.copy(); offset = 0; for j in range(0,4): ref_line = old_image[:,intstart[j]:intstart[j]+intwidth].sum(axis=1)*(1./(intwidth)); #ref_line[ref_line > thresh] = 0; imax = ref_line.argmax(); if mask is not None: ref_line[mask] = 0; for i in range(offset,offset+sector_width): image[:,i] = image[:,i]-ref_line; offset += sector_width; #print offset image[:,0:5]= image[:,-5:] = 0; if verbosity > 0: plt.title("Remove Stripes: difference between old and new image"); plt.imshow(image - old_image, aspect='auto') plt.show(); return image; # -- main ---------------------------------------- if __name__ == '__main__': import TEMareels.tools.tifffile as tiff from TEMareels.tools import tvips image_file = '../tests/wqmap.tif'; image = tiff.imread(image_file).astype(float); binning = 8; intstart= np.array([0,1025,2900,3800])/binning; img = remove_stripes(image, intwidth=100/binning, intstart=intstart, sector_width=1024/binning, verbosity=1); #outfile = "script_test_.tif"; #tvips.write_tiff(img, outfile);
mit
DavidLP/SourceSim
tools/charge_sharing_z_correction.py
1
1377
# Shows the correction of z to take into account a charge cloud with a sigma != 0 at the beginning import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d.axes3d import Axes3D from scipy.special import erf from itertools import product, combinations import mpl_toolkits.mplot3d.art3d as art3d from matplotlib.patches import Circle, PathPatch, Rectangle from matplotlib.widgets import Slider, Button, RadioButtons def normal(x, mu=0, A=1): sigma = get_sigma(A) return A * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) def get_sigma(length, temperature=330., voltage=80.): kb_K_e = 8.6173e-5 return length * np.sqrt(2 * temperature / voltage * kb_K_e) mu = 0. x = np.linspace(-30, 30, 5000) A0 = 23.72 sigma_0 = 1. A1 = np.linspace(A0, A0 + 500, 1000) def minimizeme(A1, A0, sigma_0): return 2 * get_sigma(A1)**2 * np.log(A1 / A0) - (sigma_0)**2 y = minimizeme(A1, A0, sigma_0) # plt.plot(A1, y) A_new = A1[(np.abs(y)).argmin()] print get_sigma(200); print A_new y1 = normal(x, mu, A0) y2 = normal(x, mu, A_new) # # plt.plot(x, y1, linewidth = 2, label='Original') plt.plot(x, y2, linewidth = 2, label='New') plt.plot([-sigma_0, sigma_0], [A0, A0], linewidth = 2, label='Start sigma = %1.1f' % sigma_0) plt.legend(loc=0) plt.xlabel('Position [um]') plt.ylabel('Charge density') plt.grid() plt.show()
bsd-2-clause
mxjl620/scikit-learn
sklearn/neighbors/regression.py
100
11017
"""Nearest Neighbor Regression""" # Authors: Jake Vanderplas <vanderplas@astro.washington.edu> # Fabian Pedregosa <fabian.pedregosa@inria.fr> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # Sparseness support by Lars Buitinck <L.J.Buitinck@uva.nl> # Multi-output support by Arnaud Joly <a.joly@ulg.ac.be> # # License: BSD 3 clause (C) INRIA, University of Amsterdam import numpy as np from .base import _get_weights, _check_weights, NeighborsBase, KNeighborsMixin from .base import RadiusNeighborsMixin, SupervisedFloatMixin from ..base import RegressorMixin from ..utils import check_array class KNeighborsRegressor(NeighborsBase, KNeighborsMixin, SupervisedFloatMixin, RegressorMixin): """Regression based on k-nearest neighbors. The target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set. Read more in the :ref:`User Guide <regression>`. Parameters ---------- n_neighbors : int, optional (default = 5) Number of neighbors to use by default for :meth:`k_neighbors` queries. weights : str or callable weight function used in prediction. Possible values: - 'uniform' : uniform weights. All points in each neighborhood are weighted equally. - 'distance' : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. - [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Uniform weights are used by default. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDtree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_size : int, optional (default = 30) Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. metric : string or DistanceMetric object (default='minkowski') the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of the DistanceMetric class for a list of available metrics. p : integer, optional (default = 2) Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_params : dict, optional (default = None) Additional keyword arguments for the metric function. n_jobs : int, optional (default = 1) The number of parallel jobs to run for neighbors search. If ``-1``, then the number of jobs is set to the number of CPU cores. Doesn't affect :meth:`fit` method. Examples -------- >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import KNeighborsRegressor >>> neigh = KNeighborsRegressor(n_neighbors=2) >>> neigh.fit(X, y) # doctest: +ELLIPSIS KNeighborsRegressor(...) >>> print(neigh.predict([[1.5]])) [ 0.5] See also -------- NearestNeighbors RadiusNeighborsRegressor KNeighborsClassifier RadiusNeighborsClassifier Notes ----- See :ref:`Nearest Neighbors <neighbors>` in the online documentation for a discussion of the choice of ``algorithm`` and ``leaf_size``. .. warning:: Regarding the Nearest Neighbors algorithms, if it is found that two neighbors, neighbor `k+1` and `k`, have identical distances but but different labels, the results will depend on the ordering of the training data. http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm """ def __init__(self, n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=1, **kwargs): self._init_params(n_neighbors=n_neighbors, algorithm=algorithm, leaf_size=leaf_size, metric=metric, p=p, metric_params=metric_params, n_jobs=n_jobs, **kwargs) self.weights = _check_weights(weights) def predict(self, X): """Predict the target for the provided data Parameters ---------- X : array-like, shape (n_query, n_features), \ or (n_query, n_indexed) if metric == 'precomputed' Test samples. Returns ------- y : array of int, shape = [n_samples] or [n_samples, n_outputs] Target values """ X = check_array(X, accept_sparse='csr') neigh_dist, neigh_ind = self.kneighbors(X) weights = _get_weights(neigh_dist, self.weights) _y = self._y if _y.ndim == 1: _y = _y.reshape((-1, 1)) if weights is None: y_pred = np.mean(_y[neigh_ind], axis=1) else: y_pred = np.empty((X.shape[0], _y.shape[1]), dtype=np.float) denom = np.sum(weights, axis=1) for j in range(_y.shape[1]): num = np.sum(_y[neigh_ind, j] * weights, axis=1) y_pred[:, j] = num / denom if self._y.ndim == 1: y_pred = y_pred.ravel() return y_pred class RadiusNeighborsRegressor(NeighborsBase, RadiusNeighborsMixin, SupervisedFloatMixin, RegressorMixin): """Regression based on neighbors within a fixed radius. The target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set. Read more in the :ref:`User Guide <regression>`. Parameters ---------- radius : float, optional (default = 1.0) Range of parameter space to use by default for :meth`radius_neighbors` queries. weights : str or callable weight function used in prediction. Possible values: - 'uniform' : uniform weights. All points in each neighborhood are weighted equally. - 'distance' : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. - [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Uniform weights are used by default. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDtree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_size : int, optional (default = 30) Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. metric : string or DistanceMetric object (default='minkowski') the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of the DistanceMetric class for a list of available metrics. p : integer, optional (default = 2) Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_params : dict, optional (default = None) Additional keyword arguments for the metric function. Examples -------- >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import RadiusNeighborsRegressor >>> neigh = RadiusNeighborsRegressor(radius=1.0) >>> neigh.fit(X, y) # doctest: +ELLIPSIS RadiusNeighborsRegressor(...) >>> print(neigh.predict([[1.5]])) [ 0.5] See also -------- NearestNeighbors KNeighborsRegressor KNeighborsClassifier RadiusNeighborsClassifier Notes ----- See :ref:`Nearest Neighbors <neighbors>` in the online documentation for a discussion of the choice of ``algorithm`` and ``leaf_size``. http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm """ def __init__(self, radius=1.0, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, **kwargs): self._init_params(radius=radius, algorithm=algorithm, leaf_size=leaf_size, p=p, metric=metric, metric_params=metric_params, **kwargs) self.weights = _check_weights(weights) def predict(self, X): """Predict the target for the provided data Parameters ---------- X : array-like, shape (n_query, n_features), \ or (n_query, n_indexed) if metric == 'precomputed' Test samples. Returns ------- y : array of int, shape = [n_samples] or [n_samples, n_outputs] Target values """ X = check_array(X, accept_sparse='csr') neigh_dist, neigh_ind = self.radius_neighbors(X) weights = _get_weights(neigh_dist, self.weights) _y = self._y if _y.ndim == 1: _y = _y.reshape((-1, 1)) if weights is None: y_pred = np.array([np.mean(_y[ind, :], axis=0) for ind in neigh_ind]) else: y_pred = np.array([(np.average(_y[ind, :], axis=0, weights=weights[i])) for (i, ind) in enumerate(neigh_ind)]) if self._y.ndim == 1: y_pred = y_pred.ravel() return y_pred
bsd-3-clause
mindriot101/batman
docs/quickstart.py
2
1823
# The batman package: fast computation of exoplanet transit light curves # Copyright (C) 2015 Laura Kreidberg # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import batman import numpy as np import matplotlib.pyplot as plt from pylab import * from matplotlib import rc rc('font',**{'family':'sans-serif','sans-serif':['Arial']}) matplotlib.rcParams.update({'font.size':14}) params = batman.TransitParams() params.t0 = 0. #time of inferior conjunction params.per = 1. #orbital period params.rp = 0.1 #planet radius (in units of stellar radii) params.a = 15. #semi-major axis (in units of stellar radii) params.inc = 87. #orbital inclination (in degrees) params.ecc = 0. #eccentricity params.w = 90. #longitude of periastron (in degrees) params.u = [0.1, 0.3] #limb darkening coefficients params.limb_dark = "quadratic" #limb darkening model t = np.linspace(-0.025, 0.025, 1000) #times at which to calculate light curve m = batman.TransitModel(params, t) #initializes model flux = m.light_curve(params) plt.plot(t, flux) plt.xlabel("Time from central transit (days)") plt.ylabel("Relative flux") plt.ylim((0.989, 1.001)) plt.savefig("lc.png") plt.show()
gpl-3.0
Akshay0724/scikit-learn
examples/neural_networks/plot_mnist_filters.py
79
2189
""" ===================================== Visualization of MLP weights on MNIST ===================================== Sometimes looking at the learned coefficients of a neural network can provide insight into the learning behavior. For example if weights look unstructured, maybe some were not used at all, or if very large coefficients exist, maybe regularization was too low or the learning rate too high. This example shows how to plot some of the first layer weights in a MLPClassifier trained on the MNIST dataset. The input data consists of 28x28 pixel handwritten digits, leading to 784 features in the dataset. Therefore the first layer weight matrix have the shape (784, hidden_layer_sizes[0]). We can therefore visualize a single column of the weight matrix as a 28x28 pixel image. To make the example run faster, we use very few hidden units, and train only for a very short time. Training longer would result in weights with a much smoother spatial appearance. """ print(__doc__) import matplotlib.pyplot as plt from sklearn.datasets import fetch_mldata from sklearn.neural_network import MLPClassifier mnist = fetch_mldata("MNIST original") # rescale the data, use the traditional train/test split X, y = mnist.data / 255., mnist.target X_train, X_test = X[:60000], X[60000:] y_train, y_test = y[:60000], y[60000:] # mlp = MLPClassifier(hidden_layer_sizes=(100, 100), max_iter=400, alpha=1e-4, # solver='sgd', verbose=10, tol=1e-4, random_state=1) mlp = MLPClassifier(hidden_layer_sizes=(50,), max_iter=10, alpha=1e-4, solver='sgd', verbose=10, tol=1e-4, random_state=1, learning_rate_init=.1) mlp.fit(X_train, y_train) print("Training set score: %f" % mlp.score(X_train, y_train)) print("Test set score: %f" % mlp.score(X_test, y_test)) fig, axes = plt.subplots(4, 4) # use global min / max to ensure all weights are shown on the same scale vmin, vmax = mlp.coefs_[0].min(), mlp.coefs_[0].max() for coef, ax in zip(mlp.coefs_[0].T, axes.ravel()): ax.matshow(coef.reshape(28, 28), cmap=plt.cm.gray, vmin=.5 * vmin, vmax=.5 * vmax) ax.set_xticks(()) ax.set_yticks(()) plt.show()
bsd-3-clause
wzbozon/statsmodels
statsmodels/sandbox/panel/panelmod.py
27
14526
""" Sandbox Panel Estimators References ----------- Baltagi, Badi H. `Econometric Analysis of Panel Data.` 4th ed. Wiley, 2008. """ from __future__ import print_function from statsmodels.compat.python import range, reduce from statsmodels.tools.tools import categorical from statsmodels.regression.linear_model import GLS, WLS import numpy as np __all__ = ["PanelModel"] from pandas import LongPanel, __version__ def group(X): """ Returns unique numeric values for groups without sorting. Examples -------- >>> X = np.array(['a','a','b','c','b','c']) >>> group(X) >>> g array([ 0., 0., 1., 2., 1., 2.]) """ uniq_dict = {} group = np.zeros(len(X)) for i in range(len(X)): if not X[i] in uniq_dict: uniq_dict.update({X[i] : len(uniq_dict)}) group[i] = uniq_dict[X[i]] return group def repanel_cov(groups, sigmas): '''calculate error covariance matrix for random effects model Parameters ---------- groups : array, (nobs, nre) or (nobs,) array of group/category observations sigma : array, (nre+1,) array of standard deviations of random effects, last element is the standard deviation of the idiosyncratic error Returns ------- omega : array, (nobs, nobs) covariance matrix of error omegainv : array, (nobs, nobs) inverse covariance matrix of error omegainvsqrt : array, (nobs, nobs) squareroot inverse covariance matrix of error such that omega = omegainvsqrt * omegainvsqrt.T Notes ----- This does not use sparse matrices and constructs nobs by nobs matrices. Also, omegainvsqrt is not sparse, i.e. elements are non-zero ''' if groups.ndim == 1: groups = groups[:,None] nobs, nre = groups.shape omega = sigmas[-1]*np.eye(nobs) for igr in range(nre): group = groups[:,igr:igr+1] groupuniq = np.unique(group) dummygr = sigmas[igr] * (group == groupuniq).astype(float) omega += np.dot(dummygr, dummygr.T) ev, evec = np.linalg.eigh(omega) #eig doesn't work omegainv = np.dot(evec, (1/ev * evec).T) omegainvhalf = evec/np.sqrt(ev) return omega, omegainv, omegainvhalf class PanelData(LongPanel): pass class PanelModel(object): """ An abstract statistical model class for panel (longitudinal) datasets. Parameters --------- endog : array-like or str If a pandas object is used then endog should be the name of the endogenous variable as a string. # exog # panel_arr # time_arr panel_data : pandas.LongPanel object Notes ----- If a pandas object is supplied it is assumed that the major_axis is time and that the minor_axis has the panel variable. """ def __init__(self, endog=None, exog=None, panel=None, time=None, xtnames=None, equation=None, panel_data=None): if panel_data == None: # if endog == None and exog == None and panel == None and \ # time == None: # raise ValueError("If pandel_data is False then endog, exog, \ #panel_arr, and time_arr cannot be None.") self.initialize(endog, exog, panel, time, xtnames, equation) # elif aspandas != False: # if not isinstance(endog, str): # raise ValueError("If a pandas object is supplied then endog \ #must be a string containing the name of the endogenous variable") # if not isinstance(aspandas, LongPanel): # raise ValueError("Only pandas.LongPanel objects are supported") # self.initialize_pandas(endog, aspandas, panel_name) def initialize(self, endog, exog, panel, time, xtnames, equation): """ Initialize plain array model. See PanelModel """ #TODO: for now, we are going assume a constant, and then make the first #panel the base, add a flag for this.... # get names names = equation.split(" ") self.endog_name = names[0] exog_names = names[1:] # this makes the order matter in the array self.panel_name = xtnames[0] self.time_name = xtnames[1] novar = exog.var(0) == 0 if True in novar: cons_index = np.where(novar == 1)[0][0] # constant col. num exog_names.insert(cons_index, 'cons') self._cons_index = novar # used again in fit_fixed self.exog_names = exog_names self.endog = np.squeeze(np.asarray(endog)) exog = np.asarray(exog) self.exog = exog self.panel = np.asarray(panel) self.time = np.asarray(time) self.paneluniq = np.unique(panel) self.timeuniq = np.unique(time) #TODO: this structure can possibly be extracted somewhat to deal with #names in general #TODO: add some dimension checks, etc. # def initialize_pandas(self, endog, aspandas): # """ # Initialize pandas objects. # # See PanelModel. # """ # self.aspandas = aspandas # endog = aspandas[endog].values # self.endog = np.squeeze(endog) # exog_name = aspandas.columns.tolist() # exog_name.remove(endog) # self.exog = aspandas.filterItems(exog_name).values #TODO: can the above be simplified to slice notation? # if panel_name != None: # self.panel_name = panel_name # self.exog_name = exog_name # self.endog_name = endog # self.time_arr = aspandas.major_axis #TODO: is time always handled correctly in fromRecords? # self.panel_arr = aspandas.minor_axis #TODO: all of this might need to be refactored to explicitly rely (internally) # on the pandas LongPanel structure for speed and convenience. # not sure this part is finished... #TODO: doesn't conform to new initialize def initialize_pandas(self, panel_data, endog_name, exog_name): self.panel_data = panel_data endog = panel_data[endog_name].values # does this create a copy? self.endog = np.squeeze(endog) if exog_name == None: exog_name = panel_data.columns.tolist() exog_name.remove(endog_name) self.exog = panel_data.filterItems(exog_name).values # copy? self._exog_name = exog_name self._endog_name = endog_name self._timeseries = panel_data.major_axis # might not need these self._panelseries = panel_data.minor_axis #TODO: this could be pulled out and just have a by kwd that takes # the panel or time array #TODO: this also needs to be expanded for 'twoway' def _group_mean(self, X, index='oneway', counts=False, dummies=False): """ Get group means of X by time or by panel. index default is panel """ if index == 'oneway': Y = self.panel uniq = self.paneluniq elif index == 'time': Y = self.time uniq = self.timeuniq else: raise ValueError("index %s not understood" % index) #TODO: use sparse matrices dummy = (Y == uniq[:,None]).astype(float) if X.ndim > 1: mean = np.dot(dummy,X)/dummy.sum(1)[:,None] else: mean = np.dot(dummy,X)/dummy.sum(1) if counts == False and dummies == False: return mean elif counts == True and dummies == False: return mean, dummy.sum(1) elif counts == True and dummies == True: return mean, dummy.sum(1), dummy elif counts == False and dummies == True: return mean, dummy #TODO: Use kwd arguments or have fit_method methods? def fit(self, model=None, method=None, effects='oneway'): """ method : LSDV, demeaned, MLE, GLS, BE, FE, optional model : between fixed random pooled [gmm] effects : oneway time twoway femethod : demeaned (only one implemented) WLS remethod : swar - amemiya nerlove walhus Notes ------ This is unfinished. None of the method arguments work yet. Only oneway effects should work. """ if method: # get rid of this with default method = method.lower() model = model.lower() if method and method not in ["lsdv", "demeaned", "mle", "gls", "be", "fe"]: # get rid of if method with default raise ValueError("%s not a valid method" % method) # if method == "lsdv": # self.fit_lsdv(model) if model == 'pooled': return GLS(self.endog, self.exog).fit() if model == 'between': return self._fit_btwn(method, effects) if model == 'fixed': return self._fit_fixed(method, effects) # def fit_lsdv(self, effects): # """ # Fit using least squares dummy variables. # # Notes # ----- # Should only be used for small `nobs`. # """ # pdummies = None # tdummies = None def _fit_btwn(self, method, effects): # group mean regression or WLS if effects != "twoway": endog = self._group_mean(self.endog, index=effects) exog = self._group_mean(self.exog, index=effects) else: raise ValueError("%s effects is not valid for the between \ estimator" % s) befit = GLS(endog, exog).fit() return befit def _fit_fixed(self, method, effects): endog = self.endog exog = self.exog demeantwice = False if effects in ["oneway","twoways"]: if effects == "twoways": demeantwice = True effects = "oneway" endog_mean, counts = self._group_mean(endog, index=effects, counts=True) exog_mean = self._group_mean(exog, index=effects) counts = counts.astype(int) endog = endog - np.repeat(endog_mean, counts) exog = exog - np.repeat(exog_mean, counts, axis=0) if demeantwice or effects == "time": endog_mean, dummies = self._group_mean(endog, index="time", dummies=True) exog_mean = self._group_mean(exog, index="time") # This allows unbalanced panels endog = endog - np.dot(endog_mean, dummies) exog = exog - np.dot(dummies.T, exog_mean) fefit = GLS(endog, exog[:,-self._cons_index]).fit() #TODO: might fail with one regressor return fefit class SURPanel(PanelModel): pass class SEMPanel(PanelModel): pass class DynamicPanel(PanelModel): pass if __name__ == "__main__": import pandas from pandas import LongPanel import statsmodels.api as sm import numpy.lib.recfunctions as nprf data = sm.datasets.grunfeld.load() # Baltagi doesn't include American Steel endog = data.endog[:-20] fullexog = data.exog[:-20] # fullexog.sort(order=['firm','year']) panel_arr = nprf.append_fields(fullexog, 'investment', endog, float, usemask=False) panel_panda = LongPanel.fromRecords(panel_arr, major_field='year', minor_field='firm') # the most cumbersome way of doing it as far as preprocessing by hand exog = fullexog[['value','capital']].view(float).reshape(-1,2) exog = sm.add_constant(exog, prepend=False) panel = group(fullexog['firm']) year = fullexog['year'] panel_mod = PanelModel(endog, exog, panel, year, xtnames=['firm','year'], equation='invest value capital') # note that equation doesn't actually do anything but name the variables panel_ols = panel_mod.fit(model='pooled') panel_be = panel_mod.fit(model='between', effects='oneway') panel_fe = panel_mod.fit(model='fixed', effects='oneway') panel_bet = panel_mod.fit(model='between', effects='time') panel_fet = panel_mod.fit(model='fixed', effects='time') panel_fe2 = panel_mod.fit(model='fixed', effects='twoways') #see also Baltagi (3rd edt) 3.3 THE RANDOM EFFECTS MODEL p.35 #for explicit formulas for spectral decomposition #but this works also for unbalanced panel # #I also just saw: 9.4.2 The Random Effects Model p.176 which is #partially almost the same as I did # #this needs to use sparse matrices for larger datasets # #""" # #import numpy as np # groups = np.array([0,0,0,1,1,2,2,2]) nobs = groups.shape[0] groupuniq = np.unique(groups) periods = np.array([0,1,2,1,2,0,1,2]) perioduniq = np.unique(periods) dummygr = (groups[:,None] == groupuniq).astype(float) dummype = (periods[:,None] == perioduniq).astype(float) sigma = 1. sigmagr = np.sqrt(2.) sigmape = np.sqrt(3.) #dummyall = np.c_[sigma*np.ones((nobs,1)), sigmagr*dummygr, # sigmape*dummype] #exclude constant ? dummyall = np.c_[sigmagr*dummygr, sigmape*dummype] # omega is the error variance-covariance matrix for the stacked # observations omega = np.dot(dummyall, dummyall.T) + sigma* np.eye(nobs) print(omega) print(np.linalg.cholesky(omega)) ev, evec = np.linalg.eigh(omega) #eig doesn't work omegainv = np.dot(evec, (1/ev * evec).T) omegainv2 = np.linalg.inv(omega) omegacomp = np.dot(evec, (ev * evec).T) print(np.max(np.abs(omegacomp - omega))) #check #print(np.dot(omegainv,omega) print(np.max(np.abs(np.dot(omegainv,omega) - np.eye(nobs)))) omegainvhalf = evec/np.sqrt(ev) #not sure whether ev shouldn't be column print(np.max(np.abs(np.dot(omegainvhalf,omegainvhalf.T) - omegainv))) # now we can use omegainvhalf in GLS (instead of the cholesky) sigmas2 = np.array([sigmagr, sigmape, sigma]) groups2 = np.column_stack((groups, periods)) omega_, omegainv_, omegainvhalf_ = repanel_cov(groups2, sigmas2) print(np.max(np.abs(omega_ - omega))) print(np.max(np.abs(omegainv_ - omegainv))) print(np.max(np.abs(omegainvhalf_ - omegainvhalf))) # notation Baltagi (3rd) section 9.4.1 (Fixed Effects Model) Pgr = reduce(np.dot,[dummygr, np.linalg.inv(np.dot(dummygr.T, dummygr)),dummygr.T]) Qgr = np.eye(nobs) - Pgr # within group effect: np.dot(Qgr, groups) # but this is not memory efficient, compared to groupstats print(np.max(np.abs(np.dot(Qgr, groups))))
bsd-3-clause
gviejo/ThalamusPhysio
python/main_make_THETA_HISTOGRAM.py
1
5163
#!/usr/bin/env python ''' File name: main_make_Thetainfo.py Author: Guillaume Viejo Date created: 16/08/2017 Python Version: 3.5.2 Theta modulation, returns angle Used to make figure 1 # TODO ASK ADRIEN ABOUT THE RESTRICTION BY SLEEP_EP ''' import numpy as np import pandas as pd import scipy.io from functions import * # from pylab import * import ipyparallel import os, sys import neuroseries as nts import time from Wavelets import MyMorlet as Morlet data_directory = '/mnt/DataGuillaume/MergedData/' datasets = np.loadtxt(data_directory+'datasets_ThalHpc.list', delimiter = '\n', dtype = str, comments = '#') datatosave = {} spikes_theta_phase = {'wake':{},'rem':{}} for session in datasets: print(session) start = time.time() generalinfo = scipy.io.loadmat(data_directory+session+'/Analysis/GeneralInfo.mat') shankStructure = loadShankStructure(generalinfo) if len(generalinfo['channelStructure'][0][0][1][0]) == 2: hpc_channel = generalinfo['channelStructure'][0][0][1][0][1][0][0] - 1 else: hpc_channel = generalinfo['channelStructure'][0][0][1][0][0][0][0] - 1 spikes,shank = loadSpikeData(data_directory+session+'/Analysis/SpikeData.mat', shankStructure['thalamus']) wake_ep = loadEpoch(data_directory+session, 'wake') sleep_ep = loadEpoch(data_directory+session, 'sleep') sws_ep = loadEpoch(data_directory+session, 'sws') rem_ep = loadEpoch(data_directory+session, 'rem') sleep_ep = sleep_ep.merge_close_intervals(threshold=1.e3) sws_ep = sleep_ep.intersect(sws_ep) rem_ep = sleep_ep.intersect(rem_ep) speed = loadSpeed(data_directory+session+'/Analysis/linspeed.mat').restrict(wake_ep) speed_ep = nts.IntervalSet(speed[speed>2.5].index.values[0:-1], speed[speed>2.5].index.values[1:]).drop_long_intervals(26000).merge_close_intervals(50000) wake_ep = wake_ep.intersect(speed_ep).drop_short_intervals(3000000) # to match main_make_SWRinfo.py sys.exit() spikes = {n:spikes[n] for n in spikes.keys() if len(spikes[n].restrict(sws_ep))} n_neuron = len(spikes) n_channel,fs, shank_to_channel = loadXML(data_directory+session+"/"+session.split("/")[1]+'.xml') lfp_hpc = loadLFP(data_directory+session+"/"+session.split("/")[1]+'.eeg', n_channel, hpc_channel, float(fs), 'int16') lfp_hpc = downsample(lfp_hpc, 1, 5) ################################################################################################## # DETECTION THETA ################################################################################################## lfp_filt_hpc = nts.Tsd(lfp_hpc.index.values, butter_bandpass_filter(lfp_hpc, 5, 15, fs/5, 2)) power = nts.Tsd(lfp_filt_hpc.index.values, np.abs(lfp_filt_hpc.values)) enveloppe,dummy = getPeaksandTroughs(power, 5) # index = (enveloppe > np.percentile(enveloppe, 50)).values*1.0 index = (enveloppe > np.percentile(enveloppe, 10)).values*1.0 start_cand = np.where((index[1:] - index[0:-1]) == 1)[0]+1 end_cand = np.where((index[1:] - index[0:-1]) == -1)[0] if end_cand[0] < start_cand[0]: end_cand = end_cand[1:] if end_cand[-1] < start_cand[-1]: start_cand = start_cand[0:-1] tmp = np.where(end_cand != start_cand) start_cand = enveloppe.index.values[start_cand[tmp]] end_cand = enveloppe.index.values[end_cand[tmp]] good_ep = nts.IntervalSet(start_cand, end_cand) good_ep = good_ep.drop_short_intervals(300000) theta_wake_ep = wake_ep.intersect(good_ep).merge_close_intervals(30000).drop_short_intervals(1000000) theta_rem_ep = rem_ep.intersect(good_ep).merge_close_intervals(30000).drop_short_intervals(1000000) # writeNeuroscopeEvents("/mnt/DataGuillaume/MergedData/"+session+"/"+session.split("/")[1]+".wake.evt.theta.2", theta_wake_ep, "Theta") # writeNeuroscopeEvents("/mnt/DataGuillaume/MergedData/"+session+"/"+session.split("/")[1]+".rem.evt.theta.2", theta_rem_ep, "Theta") phase = getPhase(lfp_hpc, 6, 14, 16, fs/5.) ep = { 'wake' : theta_wake_ep, 'rem' : theta_rem_ep} for e in ep.keys(): spikes_phase = {n:phase.realign(spikes[n], align = 'closest') for n in spikes.keys()} for n in range(len(spikes_phase.keys())): neuron = list(spikes_phase.keys())[n] ph = spikes_phase[neuron].restrict(ep[e]) spikes_theta_phase[e][session.split("/")[1]+"_"+str(neuron)] = ph.values stop = time.time() print(stop - start, ' s') # cPickle.dump(spikes_theta_phase, open('/mnt/DataGuillaume/MergedData/SPIKE_THETA_PHASE_2.pickle', 'wb')) # import _pickle as cPickle # cPickle.dump(datatosave, open('/mnt/DataGuillaume/MergedData/THETA_THAL_mod.pickle', 'wb')) # # COMPUTING THETA HISTOGRAM neurons = np.unique(list(spikes_theta_phase['rem'].keys())+list(spikes_theta_phase['wake'].keys())) bins = np.linspace(0, 2*np.pi, 20) df = pd.DataFrame(index = bins[0:-1], columns = pd.MultiIndex.from_product([neurons, ['wak', 'rem']])) for n in neurons: for ep in ['wake', 'rem']: tmp = spikes_theta_phase[ep][n] tmp += 2*np.pi tmp %= 2*np.pi a, b = np.histogram(tmp, bins, density = True) df[(n,ep[0:3])] = a * np.diff(b) df.to_hdf("/mnt/DataGuillaume/MergedData/THETA_THAL_HISTOGRAM_2.h5", 'theta')
gpl-3.0
valpasq/yatsm
yatsm/cli/pixel.py
2
12052
""" Command line interface for running YATSM algorithms on individual pixels """ import datetime as dt import logging import re import click import matplotlib as mpl import matplotlib.cm # noqa import matplotlib.pyplot as plt import numpy as np import patsy import yaml from . import options, console from ..algorithms import postprocess from ..config_parser import convert_config, parse_config_file from ..utils import csvfile_to_dataframe, get_image_IDs from ..regression.transforms import harm # noqa avail_plots = ['TS', 'DOY', 'VAL'] _DEFAULT_PLOT_CMAP = 'viridis' PLOT_CMAP = _DEFAULT_PLOT_CMAP if PLOT_CMAP not in mpl.cm.cmap_d: PLOT_CMAP = 'cubehelix' plot_styles = [] if hasattr(mpl, 'style'): plot_styles = mpl.style.available if hasattr(plt, 'xkcd'): plot_styles.append('xkcd') logger = logging.getLogger('yatsm') @click.command(short_help='Run YATSM algorithm on individual pixels') @options.arg_config_file @click.argument('px', metavar='<px>', nargs=1, type=click.INT) @click.argument('py', metavar='<py>', nargs=1, type=click.INT) @click.option('--band', metavar='<n>', nargs=1, type=click.INT, default=1, show_default=True, help='Band to plot') @click.option('--plot', default=('TS',), multiple=True, show_default=True, type=click.Choice(avail_plots), help='Plot type') @click.option('--ylim', metavar='<min> <max>', nargs=2, type=float, show_default=True, help='Y-axis limits') @click.option('--style', metavar='<style>', default='ggplot', show_default=True, type=click.Choice(plot_styles), help='Plot style') @click.option('--cmap', metavar='<cmap>', default=PLOT_CMAP, show_default=True, help='DOY/VAL plot colormap') @click.option('--embed', is_flag=True, help='Drop to (I)Python interpreter at various points') @click.option('--seed', help='Set NumPy RNG seed value') @click.option('--algo_kw', multiple=True, callback=options.callback_dict, help='Algorithm parameter overrides') @click.option('--result_prefix', type=str, default='', show_default=True, multiple=True, help='Plot coef/rmse from refit that used this prefix') @click.pass_context def pixel(ctx, config, px, py, band, plot, ylim, style, cmap, embed, seed, algo_kw, result_prefix): # Set seed np.random.seed(seed) # Convert band to index band -= 1 # Format result prefix if result_prefix: result_prefix = set((_pref if _pref[-1] == '_' else _pref + '_') for _pref in result_prefix) result_prefix.add('') # add in no prefix to show original fit else: result_prefix = ('', ) # Get colormap if cmap not in mpl.cm.cmap_d: raise click.ClickException('Cannot find specified colormap ({}) in ' 'matplotlib'.format(cmap)) # Parse config cfg = parse_config_file(config) # Apply algorithm overrides for kw in algo_kw: value = yaml.load(algo_kw[kw]) cfg = trawl_replace_keys(cfg, kw, value) if algo_kw: # revalidate configuration cfg = convert_config(cfg) # Dataset information df = csvfile_to_dataframe(cfg['dataset']['input_file'], date_format=cfg['dataset']['date_format']) df['image_ID'] = get_image_IDs(df['filename']) df['x'] = df['date'] dates = df['date'].values # Initialize timeseries model model = cfg['YATSM']['algorithm_cls'] algo_cfg = cfg[cfg['YATSM']['algorithm']] yatsm = model(estimator=cfg['YATSM']['estimator'], **algo_cfg.get('init', {})) yatsm.px = px yatsm.py = py # Setup algorithm and create design matrix (if needed) X = yatsm.setup(df, **cfg) design_info = getattr(X, 'design_info', None) # Read pixel data Y = read_pixel_timeseries(df['filename'], px, py) if Y.shape[0] != cfg['dataset']['n_bands']: raise click.ClickException( 'Number of bands in image {f} ({nf}) do not match number in ' 'configuration file ({nc})'.format( f=df['filename'][0], nf=Y.shape[0], nc=cfg['dataset']['n_bands'])) # Preprocess pixel data X, Y, dates = yatsm.preprocess(X, Y, dates, **cfg['dataset']) # Convert ordinal to datetime dt_dates = np.array([dt.datetime.fromordinal(d) for d in dates]) # Plot before fitting with plt.xkcd() if style == 'xkcd' else mpl.style.context(style): for _plot in plot: if _plot == 'TS': plot_TS(dt_dates, Y[band, :]) elif _plot == 'DOY': plot_DOY(dt_dates, Y[band, :], cmap) elif _plot == 'VAL': plot_VAL(dt_dates, Y[band, :], cmap) if ylim: plt.ylim(ylim) plt.title('Timeseries: px={px} py={py}'.format(px=px, py=py)) plt.ylabel('Band {b}'.format(b=band + 1)) plt.tight_layout() plt.show() # Fit model yatsm.fit(X, Y, dates, **algo_cfg.get('fit', {})) for prefix, estimator, stay_reg, fitopt in zip( cfg['YATSM']['refit']['prefix'], cfg['YATSM']['refit']['prediction_object'], cfg['YATSM']['refit']['stay_regularized'], cfg['YATSM']['refit']['fit']): yatsm.record = postprocess.refit_record( yatsm, prefix, estimator, fitopt=fitopt, keep_regularized=stay_reg) # Plot after predictions with plt.xkcd() if style == 'xkcd' else mpl.style.context(style): for _plot in plot: if _plot == 'TS': plot_TS(dt_dates, Y[band, :]) elif _plot == 'DOY': plot_DOY(dt_dates, Y[band, :], cmap) elif _plot == 'VAL': plot_VAL(dt_dates, Y[band, :], cmap) if ylim: plt.ylim(ylim) plt.title('Timeseries: px={px} py={py}'.format(px=px, py=py)) plt.ylabel('Band {b}'.format(b=band + 1)) for _prefix in set(result_prefix): plot_results(band, cfg, yatsm, design_info, result_prefix=_prefix, plot_type=_plot) plt.tight_layout() plt.show() if embed: console.open_interpreter( yatsm, message=("Additional functions:\n" "plot_TS, plot_DOY, plot_VAL, plot_results"), variables={ 'config': cfg, }, funcs={ 'plot_TS': plot_TS, 'plot_DOY': plot_DOY, 'plot_VAL': plot_VAL, 'plot_results': plot_results } ) def plot_TS(dates, y): """ Create a standard timeseries plot Args: dates (iterable): sequence of datetime y (np.ndarray): variable to plot """ # Plot data plt.scatter(dates, y, c='k', marker='o', edgecolors='none', s=35) plt.xlabel('Date') def plot_DOY(dates, y, mpl_cmap): """ Create a DOY plot Args: dates (iterable): sequence of datetime y (np.ndarray): variable to plot mpl_cmap (colormap): matplotlib colormap """ doy = np.array([d.timetuple().tm_yday for d in dates]) year = np.array([d.year for d in dates]) sp = plt.scatter(doy, y, c=year, cmap=mpl_cmap, marker='o', edgecolors='none', s=35) plt.colorbar(sp) months = mpl.dates.MonthLocator() # every month months_fmrt = mpl.dates.DateFormatter('%b') plt.tick_params(axis='x', which='minor', direction='in', pad=-10) plt.axes().xaxis.set_minor_locator(months) plt.axes().xaxis.set_minor_formatter(months_fmrt) plt.xlim(1, 366) plt.xlabel('Day of Year') def plot_VAL(dates, y, mpl_cmap, reps=2): """ Create a "Valerie Pasquarella" plot (repeated DOY plot) Args: dates (iterable): sequence of datetime y (np.ndarray): variable to plot mpl_cmap (colormap): matplotlib colormap reps (int, optional): number of additional repetitions """ doy = np.array([d.timetuple().tm_yday for d in dates]) year = np.array([d.year for d in dates]) # Replicate `reps` times _doy = doy.copy() for r in range(1, reps + 1): _doy = np.concatenate((_doy, doy + r * 366)) _year = np.tile(year, reps + 1) _y = np.tile(y, reps + 1) sp = plt.scatter(_doy, _y, c=_year, cmap=mpl_cmap, marker='o', edgecolors='none', s=35) plt.colorbar(sp) plt.xlabel('Day of Year') def plot_results(band, cfg, model, design_info, result_prefix='', plot_type='TS'): """ Plot model results Args: band (int): plot results for this band cfg (dict): YATSM configuration dictionary model (YATSM model): fitted YATSM timeseries model design_info (patsy.DesignInfo): patsy design information result_prefix (str): Prefix to 'coef' and 'rmse' plot_type (str): type of plot to add results to (TS, DOY, or VAL) """ # Results prefix result_k = model.record.dtype.names coef_k = result_prefix + 'coef' rmse_k = result_prefix + 'rmse' if coef_k not in result_k or rmse_k not in result_k: raise KeyError('Cannot find result prefix "{}" in results' .format(result_prefix)) if result_prefix: click.echo('Using "{}" re-fitted results'.format(result_prefix)) # Handle reverse step = -1 if cfg['YATSM']['reverse'] else 1 # Remove categorical info from predictions design = re.sub(r'[\+\-][\ ]+C\(.*\)', '', cfg['YATSM']['design_matrix']) i_coef = [] for k, v in design_info.column_name_indexes.iteritems(): if not re.match('C\(.*\)', k): i_coef.append(v) i_coef = np.sort(np.asarray(i_coef)) _prefix = result_prefix or cfg['YATSM']['prediction'] for i, r in enumerate(model.record): label = 'Model {i} ({prefix})'.format(i=i, prefix=_prefix) if plot_type == 'TS': # Prediction mx = np.arange(r['start'], r['end'], step) mX = patsy.dmatrix(design, {'x': mx}).T my = np.dot(r[coef_k][i_coef, band], mX) mx_date = np.array([dt.datetime.fromordinal(int(_x)) for _x in mx]) # Break if r['break']: bx = dt.datetime.fromordinal(r['break']) plt.axvline(bx, c='red', lw=2) elif plot_type in ('DOY', 'VAL'): yr_end = dt.datetime.fromordinal(r['end']).year yr_start = dt.datetime.fromordinal(r['start']).year yr_mid = int(yr_end - (yr_end - yr_start) / 2) mx = np.arange(dt.date(yr_mid, 1, 1).toordinal(), dt.date(yr_mid + 1, 1, 1).toordinal(), 1) mX = patsy.dmatrix(design, {'x': mx}).T my = np.dot(r[coef_k][i_coef, band], mX) mx_date = np.array([dt.datetime.fromordinal(d).timetuple().tm_yday for d in mx]) label = 'Model {i} - {yr} ({prefix})'.format(i=i, yr=yr_mid, prefix=_prefix) plt.plot(mx_date, my, lw=3, label=label) leg = plt.legend() leg.draggable(state=True) # UTILITY FUNCTIONS def trawl_replace_keys(d, key, value, s=''): """ Return modified dictionary ``d`` """ md = d.copy() for _key in md: if isinstance(md[_key], dict): # Recursively replace md[_key] = trawl_replace_keys(md[_key], key, value, s='{}[{}]'.format(s, _key)) else: if _key == key: s += '[{}]'.format(_key) click.echo('Replacing d{k}={ov} with {nv}' .format(k=s, ov=md[_key], nv=value)) md[_key] = value return md
mit
asimshankar/tensorflow
tensorflow/contrib/learn/__init__.py
18
2695
# 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. # ============================================================================== """High level API for learning (DEPRECATED). This module and all its submodules are deprecated. See [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md) for migration instructions. @@BaseEstimator @@Estimator @@Trainable @@Evaluable @@KMeansClustering @@ModeKeys @@ModelFnOps @@MetricSpec @@PredictionKey @@DNNClassifier @@DNNEstimator @@DNNRegressor @@DNNLinearCombinedRegressor @@DNNLinearCombinedEstimator @@DNNLinearCombinedClassifier @@DynamicRnnEstimator @@LinearClassifier @@LinearEstimator @@LinearRegressor @@LogisticRegressor @@StateSavingRnnEstimator @@SVM @@SKCompat @@Head @@multi_class_head @@multi_label_head @@binary_svm_head @@regression_head @@poisson_regression_head @@multi_head @@no_op_train_fn @@Experiment @@ExportStrategy @@TaskType @@NanLossDuringTrainingError @@RunConfig @@evaluate @@infer @@run_feeds @@run_n @@train @@extract_dask_data @@extract_dask_labels @@extract_pandas_data @@extract_pandas_labels @@extract_pandas_matrix @@infer_real_valued_columns_from_input @@infer_real_valued_columns_from_input_fn @@read_batch_examples @@read_batch_features @@read_batch_record_features @@read_keyed_batch_examples @@read_keyed_batch_examples_shared_queue @@read_keyed_batch_features @@read_keyed_batch_features_shared_queue @@InputFnOps @@ProblemType @@build_parsing_serving_input_fn @@make_export_strategy """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import from tensorflow.contrib.learn.python.learn import * # pylint: enable=wildcard-import from tensorflow.contrib.learn.python.learn import learn_runner_lib as learn_runner from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = ['datasets', 'head', 'io', 'learn_runner', 'models', 'monitors', 'NotFittedError', 'ops', 'preprocessing', 'utils', 'graph_actions'] remove_undocumented(__name__, _allowed_symbols)
apache-2.0
QISKit/qiskit-sdk-py
qiskit/pulse/commands/sample_pulse.py
1
6024
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Sample pulse. """ from typing import Callable, Union, List, Optional import numpy as np from qiskit.pulse.channels import PulseChannel from qiskit.pulse.exceptions import PulseError from .instruction import Instruction from .command import Command class SamplePulse(Command): """Container for functional pulse.""" prefix = 'p' def __init__(self, samples: Union[np.ndarray, List[complex]], name: Optional[str] = None, epsilon: float = 1e-7): """Create new sample pulse command. Args: samples: Complex array of pulse envelope name: Unique name to identify the pulse epsilon: Pulse sample norm tolerance for clipping. If any sample's norm exceeds unity by less than or equal to epsilon it will be clipped to unit norm. If the sample norm is greater than 1+epsilon an error will be raised """ super().__init__(duration=len(samples)) samples = np.asarray(samples, dtype=np.complex_) self._samples = self._clip(samples, epsilon=epsilon) self._name = SamplePulse.create_name(name) @property def samples(self): """Return sample values.""" return self._samples def _clip(self, samples: np.ndarray, epsilon: float = 1e-7): """If samples are within epsilon of unit norm, clip sample by reducing norm by (1-epsilon). If difference is greater than epsilon error is raised. Args: samples: Complex array of pulse envelope epsilon: Pulse sample norm tolerance for clipping. If any sample's norm exceeds unity by less than or equal to epsilon it will be clipped to unit norm. If the sample norm is greater than 1+epsilon an error will be raised Returns: np.ndarray: Clipped pulse samples Raises: PulseError: If there exists a pulse sample with a norm greater than 1+epsilon """ samples_norm = np.abs(samples) to_clip = (samples_norm > 1.) & (samples_norm <= 1. + epsilon) if np.any(to_clip): # first try normalizing by the abs value clip_where = np.argwhere(to_clip) clip_angle = np.angle(samples[clip_where]) clipped_samples = np.exp(1j*clip_angle, dtype=np.complex_) # if norm still exceed one subtract epsilon # required for some platforms clipped_sample_norms = np.abs(clipped_samples) to_clip_epsilon = clipped_sample_norms > 1. if np.any(to_clip_epsilon): clip_where_epsilon = np.argwhere(to_clip_epsilon) clipped_samples_epsilon = np.exp( (1-epsilon)*1j*clip_angle[clip_where_epsilon], dtype=np.complex_) clipped_samples[clip_where_epsilon] = clipped_samples_epsilon # update samples with clipped values samples[clip_where] = clipped_samples samples_norm[clip_where] = np.abs(clipped_samples) if np.any(samples_norm > 1.): raise PulseError('Pulse contains sample with norm greater than 1+epsilon.') return samples def draw(self, dt: float = 1, style: Optional['PulseStyle'] = None, filename: Optional[str] = None, interp_method: Optional[Callable] = None, scaling: float = 1, interactive: bool = False): """Plot the interpolated envelope of pulse. Args: dt: Time interval of samples. style: A style sheet to configure plot appearance filename: Name required to save pulse image interp_method: A function for interpolation scaling: Relative visual scaling of waveform amplitudes interactive: When set true show the circuit in a new window (this depends on the matplotlib backend being used supporting this) Returns: matplotlib.figure: A matplotlib figure object of the pulse envelope """ # pylint: disable=invalid-name, cyclic-import from qiskit import visualization return visualization.pulse_drawer(self, dt=dt, style=style, filename=filename, interp_method=interp_method, scaling=scaling, interactive=interactive) def __eq__(self, other: 'SamplePulse'): """Two SamplePulses are the same if they are of the same type and have the same name and samples. Args: other: other SamplePulse Returns: bool: are self and other equal """ return super().__eq__(other) and (self.samples == other.samples).all() def __hash__(self): return hash((super().__hash__(), self.samples.tostring())) def __repr__(self): return '%s(%s, duration=%d)' % (self.__class__.__name__, self.name, self.duration) # pylint: disable=arguments-differ def to_instruction(self, channel: PulseChannel, name: Optional[str] = None) -> 'PulseInstruction': return PulseInstruction(self, channel, name=name) # pylint: enable=arguments-differ class PulseInstruction(Instruction): """Instruction to drive a pulse to an `PulseChannel`.""" def __init__(self, command: SamplePulse, channel: PulseChannel, name: Optional[str] = None): super().__init__(command, channel, name=name)
apache-2.0
mbayon/TFG-MachineLearning
vbig/lib/python2.7/site-packages/sklearn/ensemble/forest.py
6
79027
"""Forest of trees-based ensemble methods Those methods include random forests and extremely randomized trees. The module structure is the following: - The ``BaseForest`` base class implements a common ``fit`` method for all the estimators in the module. The ``fit`` method of the base ``Forest`` class calls the ``fit`` method of each sub-estimator on random samples (with replacement, a.k.a. bootstrap) of the training set. The init of the sub-estimator is further delegated to the ``BaseEnsemble`` constructor. - The ``ForestClassifier`` and ``ForestRegressor`` base classes further implement the prediction logic by computing an average of the predicted outcomes of the sub-estimators. - The ``RandomForestClassifier`` and ``RandomForestRegressor`` derived classes provide the user with concrete implementations of the forest ensemble method using classical, deterministic ``DecisionTreeClassifier`` and ``DecisionTreeRegressor`` as sub-estimator implementations. - The ``ExtraTreesClassifier`` and ``ExtraTreesRegressor`` derived classes provide the user with concrete implementations of the forest ensemble method using the extremely randomized trees ``ExtraTreeClassifier`` and ``ExtraTreeRegressor`` as sub-estimator implementations. Single and multi-output problems are both handled. """ # Authors: Gilles Louppe <g.louppe@gmail.com> # Brian Holt <bdholt1@gmail.com> # Joly Arnaud <arnaud.v.joly@gmail.com> # Fares Hedayati <fares.hedayati@gmail.com> # # License: BSD 3 clause from __future__ import division import warnings from warnings import warn import threading from abc import ABCMeta, abstractmethod import numpy as np from scipy.sparse import issparse from scipy.sparse import hstack as sparse_hstack from ..base import ClassifierMixin, RegressorMixin from ..externals.joblib import Parallel, delayed from ..externals import six from ..metrics import r2_score from ..preprocessing import OneHotEncoder from ..tree import (DecisionTreeClassifier, DecisionTreeRegressor, ExtraTreeClassifier, ExtraTreeRegressor) from ..tree._tree import DTYPE, DOUBLE from ..utils import check_random_state, check_array, compute_sample_weight from ..exceptions import DataConversionWarning, NotFittedError from .base import BaseEnsemble, _partition_estimators from ..utils.fixes import parallel_helper from ..utils.multiclass import check_classification_targets from ..utils.validation import check_is_fitted __all__ = ["RandomForestClassifier", "RandomForestRegressor", "ExtraTreesClassifier", "ExtraTreesRegressor", "RandomTreesEmbedding"] MAX_INT = np.iinfo(np.int32).max def _generate_sample_indices(random_state, n_samples): """Private function used to _parallel_build_trees function.""" random_instance = check_random_state(random_state) sample_indices = random_instance.randint(0, n_samples, n_samples) return sample_indices def _generate_unsampled_indices(random_state, n_samples): """Private function used to forest._set_oob_score function.""" sample_indices = _generate_sample_indices(random_state, n_samples) sample_counts = np.bincount(sample_indices, minlength=n_samples) unsampled_mask = sample_counts == 0 indices_range = np.arange(n_samples) unsampled_indices = indices_range[unsampled_mask] return unsampled_indices def _parallel_build_trees(tree, forest, X, y, sample_weight, tree_idx, n_trees, verbose=0, class_weight=None): """Private function used to fit a single tree in parallel.""" if verbose > 1: print("building tree %d of %d" % (tree_idx + 1, n_trees)) if forest.bootstrap: n_samples = X.shape[0] if sample_weight is None: curr_sample_weight = np.ones((n_samples,), dtype=np.float64) else: curr_sample_weight = sample_weight.copy() indices = _generate_sample_indices(tree.random_state, n_samples) sample_counts = np.bincount(indices, minlength=n_samples) curr_sample_weight *= sample_counts if class_weight == 'subsample': with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) curr_sample_weight *= compute_sample_weight('auto', y, indices) elif class_weight == 'balanced_subsample': curr_sample_weight *= compute_sample_weight('balanced', y, indices) tree.fit(X, y, sample_weight=curr_sample_weight, check_input=False) else: tree.fit(X, y, sample_weight=sample_weight, check_input=False) return tree class BaseForest(six.with_metaclass(ABCMeta, BaseEnsemble)): """Base class for forests of trees. Warning: This class should not be used directly. Use derived classes instead. """ @abstractmethod def __init__(self, base_estimator, n_estimators=10, estimator_params=tuple(), bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False, class_weight=None): super(BaseForest, self).__init__( base_estimator=base_estimator, n_estimators=n_estimators, estimator_params=estimator_params) self.bootstrap = bootstrap self.oob_score = oob_score self.n_jobs = n_jobs self.random_state = random_state self.verbose = verbose self.warm_start = warm_start self.class_weight = class_weight def apply(self, X): """Apply trees in the forest to X, return leaf indices. Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- X_leaves : array_like, shape = [n_samples, n_estimators] For each datapoint x in X and for each tree in the forest, return the index of the leaf x ends up in. """ X = self._validate_X_predict(X) results = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, backend="threading")( delayed(parallel_helper)(tree, 'apply', X, check_input=False) for tree in self.estimators_) return np.array(results).T def decision_path(self, X): """Return the decision path in the forest .. versionadded:: 0.18 Parameters ---------- X : array-like or sparse matrix, shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- indicator : sparse csr array, shape = [n_samples, n_nodes] Return a node indicator matrix where non zero elements indicates that the samples goes through the nodes. n_nodes_ptr : array of size (n_estimators + 1, ) The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]] gives the indicator value for the i-th estimator. """ X = self._validate_X_predict(X) indicators = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, backend="threading")( delayed(parallel_helper)(tree, 'decision_path', X, check_input=False) for tree in self.estimators_) n_nodes = [0] n_nodes.extend([i.shape[1] for i in indicators]) n_nodes_ptr = np.array(n_nodes).cumsum() return sparse_hstack(indicators).tocsr(), n_nodes_ptr def fit(self, X, y, sample_weight=None): """Build a forest of trees from the training set (X, y). Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The training input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csc_matrix``. y : array-like, shape = [n_samples] or [n_samples, n_outputs] The target values (class labels in classification, real numbers in regression). sample_weight : array-like, shape = [n_samples] or None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns ------- self : object Returns self. """ # Validate or convert input data X = check_array(X, accept_sparse="csc", dtype=DTYPE) y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None) if sample_weight is not None: sample_weight = check_array(sample_weight, ensure_2d=False) if issparse(X): # Pre-sort indices to avoid that each individual tree of the # ensemble sorts the indices. X.sort_indices() # Remap output n_samples, self.n_features_ = X.shape y = np.atleast_1d(y) if y.ndim == 2 and y.shape[1] == 1: 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) if y.ndim == 1: # reshape is necessary to preserve the data contiguity against vs # [:, np.newaxis] that does not. y = np.reshape(y, (-1, 1)) self.n_outputs_ = y.shape[1] y, expanded_class_weight = self._validate_y_class_weight(y) if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous: y = np.ascontiguousarray(y, dtype=DOUBLE) if expanded_class_weight is not None: if sample_weight is not None: sample_weight = sample_weight * expanded_class_weight else: sample_weight = expanded_class_weight # Check parameters self._validate_estimator() if not self.bootstrap and self.oob_score: raise ValueError("Out of bag estimation only available" " if bootstrap=True") random_state = check_random_state(self.random_state) if not self.warm_start or not hasattr(self, "estimators_"): # Free allocated memory, if any self.estimators_ = [] n_more_estimators = self.n_estimators - len(self.estimators_) if n_more_estimators < 0: raise ValueError('n_estimators=%d must be larger or equal to ' 'len(estimators_)=%d when warm_start==True' % (self.n_estimators, len(self.estimators_))) elif n_more_estimators == 0: warn("Warm-start fitting without increasing n_estimators does not " "fit new trees.") else: if self.warm_start and len(self.estimators_) > 0: # We draw from the random state to get the random state we # would have got if we hadn't used a warm_start. random_state.randint(MAX_INT, size=len(self.estimators_)) trees = [] for i in range(n_more_estimators): tree = self._make_estimator(append=False, random_state=random_state) trees.append(tree) # Parallel loop: we use the threading backend as the Cython code # for fitting the trees is internally releasing the Python GIL # making threading always more efficient than multiprocessing in # that case. trees = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, backend="threading")( delayed(_parallel_build_trees)( t, self, X, y, sample_weight, i, len(trees), verbose=self.verbose, class_weight=self.class_weight) for i, t in enumerate(trees)) # Collect newly grown trees self.estimators_.extend(trees) if self.oob_score: self._set_oob_score(X, y) # Decapsulate classes_ attributes if hasattr(self, "classes_") and self.n_outputs_ == 1: self.n_classes_ = self.n_classes_[0] self.classes_ = self.classes_[0] return self @abstractmethod def _set_oob_score(self, X, y): """Calculate out of bag predictions and score.""" def _validate_y_class_weight(self, y): # Default implementation return y, None def _validate_X_predict(self, X): """Validate X whenever one tries to predict, apply, predict_proba""" if self.estimators_ is None or len(self.estimators_) == 0: raise NotFittedError("Estimator not fitted, " "call `fit` before exploiting the model.") return self.estimators_[0]._validate_X_predict(X, check_input=True) @property def feature_importances_(self): """Return the feature importances (the higher, the more important the feature). Returns ------- feature_importances_ : array, shape = [n_features] """ check_is_fitted(self, 'estimators_') all_importances = Parallel(n_jobs=self.n_jobs, backend="threading")( delayed(getattr)(tree, 'feature_importances_') for tree in self.estimators_) return sum(all_importances) / len(self.estimators_) # This is a utility function for joblib's Parallel. It can't go locally in # ForestClassifier or ForestRegressor, because joblib complains that it cannot # pickle it when placed there. def accumulate_prediction(predict, X, out, lock): prediction = predict(X, check_input=False) with lock: if len(out) == 1: out[0] += prediction else: for i in range(len(out)): out[i] += prediction[i] class ForestClassifier(six.with_metaclass(ABCMeta, BaseForest, ClassifierMixin)): """Base class for forest of trees-based classifiers. Warning: This class should not be used directly. Use derived classes instead. """ @abstractmethod def __init__(self, base_estimator, n_estimators=10, estimator_params=tuple(), bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False, class_weight=None): super(ForestClassifier, self).__init__( base_estimator, n_estimators=n_estimators, estimator_params=estimator_params, bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, class_weight=class_weight) def _set_oob_score(self, X, y): """Compute out-of-bag score""" X = check_array(X, dtype=DTYPE, accept_sparse='csr') n_classes_ = self.n_classes_ n_samples = y.shape[0] oob_decision_function = [] oob_score = 0.0 predictions = [] for k in range(self.n_outputs_): predictions.append(np.zeros((n_samples, n_classes_[k]))) for estimator in self.estimators_: unsampled_indices = _generate_unsampled_indices( estimator.random_state, n_samples) p_estimator = estimator.predict_proba(X[unsampled_indices, :], check_input=False) if self.n_outputs_ == 1: p_estimator = [p_estimator] for k in range(self.n_outputs_): predictions[k][unsampled_indices, :] += p_estimator[k] for k in range(self.n_outputs_): if (predictions[k].sum(axis=1) == 0).any(): warn("Some inputs do not have OOB scores. " "This probably means too few trees were used " "to compute any reliable oob estimates.") decision = (predictions[k] / predictions[k].sum(axis=1)[:, np.newaxis]) oob_decision_function.append(decision) oob_score += np.mean(y[:, k] == np.argmax(predictions[k], axis=1), axis=0) if self.n_outputs_ == 1: self.oob_decision_function_ = oob_decision_function[0] else: self.oob_decision_function_ = oob_decision_function self.oob_score_ = oob_score / self.n_outputs_ def _validate_y_class_weight(self, y): check_classification_targets(y) y = np.copy(y) expanded_class_weight = None if self.class_weight is not None: y_original = np.copy(y) self.classes_ = [] self.n_classes_ = [] y_store_unique_indices = np.zeros(y.shape, dtype=np.int) for k in range(self.n_outputs_): classes_k, y_store_unique_indices[:, k] = np.unique(y[:, k], return_inverse=True) self.classes_.append(classes_k) self.n_classes_.append(classes_k.shape[0]) y = y_store_unique_indices if self.class_weight is not None: valid_presets = ('balanced', 'balanced_subsample') if isinstance(self.class_weight, six.string_types): if self.class_weight not in valid_presets: raise ValueError('Valid presets for class_weight include ' '"balanced" and "balanced_subsample". Given "%s".' % self.class_weight) if self.warm_start: warn('class_weight presets "balanced" or "balanced_subsample" are ' 'not recommended for warm_start if the fitted data ' 'differs from the full dataset. In order to use ' '"balanced" weights, use compute_class_weight("balanced", ' 'classes, y). In place of y you can use a large ' 'enough sample of the full training set target to ' 'properly estimate the class frequency ' 'distributions. Pass the resulting weights as the ' 'class_weight parameter.') if (self.class_weight != 'balanced_subsample' or not self.bootstrap): if self.class_weight == "balanced_subsample": class_weight = "balanced" else: class_weight = self.class_weight expanded_class_weight = compute_sample_weight(class_weight, y_original) return y, expanded_class_weight def predict(self, X): """Predict class for X. The predicted class of an input sample is a vote by the trees in the forest, weighted by their probability estimates. That is, the predicted class is the one with highest mean probability estimate across the trees. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- y : array of shape = [n_samples] or [n_samples, n_outputs] The predicted classes. """ proba = self.predict_proba(X) if self.n_outputs_ == 1: return self.classes_.take(np.argmax(proba, axis=1), axis=0) else: n_samples = proba[0].shape[0] predictions = np.zeros((n_samples, self.n_outputs_)) for k in range(self.n_outputs_): predictions[:, k] = self.classes_[k].take(np.argmax(proba[k], axis=1), axis=0) return predictions def predict_proba(self, X): """Predict class probabilities for X. The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute `classes_`. """ check_is_fitted(self, 'estimators_') # Check data X = self._validate_X_predict(X) # Assign chunk of trees to jobs n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs) # avoid storing the output of every estimator by summing them here all_proba = [np.zeros((X.shape[0], j), dtype=np.float64) for j in np.atleast_1d(self.n_classes_)] lock = threading.Lock() Parallel(n_jobs=n_jobs, verbose=self.verbose, backend="threading")( delayed(accumulate_prediction)(e.predict_proba, X, all_proba, lock) for e in self.estimators_) for proba in all_proba: proba /= len(self.estimators_) if len(all_proba) == 1: return all_proba[0] else: return all_proba def predict_log_proba(self, X): """Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the trees in the forest. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : array of shape = [n_samples, n_classes], or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute `classes_`. """ proba = self.predict_proba(X) if self.n_outputs_ == 1: return np.log(proba) else: for k in range(self.n_outputs_): proba[k] = np.log(proba[k]) return proba class ForestRegressor(six.with_metaclass(ABCMeta, BaseForest, RegressorMixin)): """Base class for forest of trees-based regressors. Warning: This class should not be used directly. Use derived classes instead. """ @abstractmethod def __init__(self, base_estimator, n_estimators=10, estimator_params=tuple(), bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False): super(ForestRegressor, self).__init__( base_estimator, n_estimators=n_estimators, estimator_params=estimator_params, bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start) def predict(self, X): """Predict regression target for X. The predicted regression target of an input sample is computed as the mean predicted regression targets of the trees in the forest. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- y : array of shape = [n_samples] or [n_samples, n_outputs] The predicted values. """ check_is_fitted(self, 'estimators_') # Check data X = self._validate_X_predict(X) # Assign chunk of trees to jobs n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs) # avoid storing the output of every estimator by summing them here if self.n_outputs_ > 1: y_hat = np.zeros((X.shape[0], self.n_outputs_), dtype=np.float64) else: y_hat = np.zeros((X.shape[0]), dtype=np.float64) # Parallel loop lock = threading.Lock() Parallel(n_jobs=n_jobs, verbose=self.verbose, backend="threading")( delayed(accumulate_prediction)(e.predict, X, [y_hat], lock) for e in self.estimators_) y_hat /= len(self.estimators_) return y_hat def _set_oob_score(self, X, y): """Compute out-of-bag scores""" X = check_array(X, dtype=DTYPE, accept_sparse='csr') n_samples = y.shape[0] predictions = np.zeros((n_samples, self.n_outputs_)) n_predictions = np.zeros((n_samples, self.n_outputs_)) for estimator in self.estimators_: unsampled_indices = _generate_unsampled_indices( estimator.random_state, n_samples) p_estimator = estimator.predict( X[unsampled_indices, :], check_input=False) if self.n_outputs_ == 1: p_estimator = p_estimator[:, np.newaxis] predictions[unsampled_indices, :] += p_estimator n_predictions[unsampled_indices, :] += 1 if (n_predictions == 0).any(): warn("Some inputs do not have OOB scores. " "This probably means too few trees were used " "to compute any reliable oob estimates.") n_predictions[n_predictions == 0] = 1 predictions /= n_predictions self.oob_prediction_ = predictions if self.n_outputs_ == 1: self.oob_prediction_ = \ self.oob_prediction_.reshape((n_samples, )) self.oob_score_ = 0.0 for k in range(self.n_outputs_): self.oob_score_ += r2_score(y[:, k], predictions[:, k]) self.oob_score_ /= self.n_outputs_ class RandomForestClassifier(ForestClassifier): """A random forest classifier. A random forest is a meta estimator that fits a number of decision tree classifiers on various sub-samples of the dataset and use averaging to improve the predictive accuracy and control over-fitting. The sub-sample size is always the same as the original input sample size but the samples are drawn with replacement if `bootstrap=True` (default). Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : integer, optional (default=10) The number of trees in the forest. criterion : string, optional (default="gini") The function to measure the quality of a split. Supported criteria are "gini" for the Gini impurity and "entropy" for the information gain. Note: this parameter is tree-specific. max_features : int, float, string or None, optional (default="auto") The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a percentage and `int(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=sqrt(n_features)`. - If "sqrt", then `max_features=sqrt(n_features)` (same as "auto"). - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_depth : integer or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int, float, optional (default=2) The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a percentage and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for percentages. min_samples_leaf : int, float, optional (default=1) The minimum number of samples required to be at a leaf node: - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a percentage and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for percentages. min_weight_fraction_leaf : float, optional (default=0.) The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_leaf_nodes : int or None, optional (default=None) Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_split : float, Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19 and will be removed in 0.21. Use ``min_impurity_decrease`` instead. min_impurity_decrease : float, optional (default=0.) A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 bootstrap : boolean, optional (default=True) Whether bootstrap samples are used when building trees. oob_score : bool (default=False) Whether to use out-of-bag samples to estimate the generalization accuracy. n_jobs : integer, optional (default=1) The number of jobs to run in parallel for both `fit` and `predict`. If -1, then the number of jobs is set to the number of cores. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. verbose : int, optional (default=0) Controls the verbosity of the tree building process. warm_start : bool, optional (default=False) When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. class_weight : dict, list of dicts, "balanced", "balanced_subsample" or None, optional (default=None) Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` The "balanced_subsample" mode is the same as "balanced" except that weights are computed based on the bootstrap sample for every tree grown. For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. Attributes ---------- estimators_ : list of DecisionTreeClassifier The collection of fitted sub-estimators. classes_ : array of shape = [n_classes] or a list of such arrays The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). n_classes_ : int or list The number of classes (single output problem), or a list containing the number of classes for each output (multi-output problem). n_features_ : int The number of features when ``fit`` is performed. n_outputs_ : int The number of outputs when ``fit`` is performed. feature_importances_ : array of shape = [n_features] The feature importances (the higher, the more important the feature). oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. oob_decision_function_ : array of shape = [n_samples, n_classes] Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, `oob_decision_function_` might contain NaN. Examples -------- >>> from sklearn.ensemble import RandomForestClassifier >>> from sklearn.datasets import make_classification >>> >>> X, y = make_classification(n_samples=1000, n_features=4, ... n_informative=2, n_redundant=0, ... random_state=0, shuffle=False) >>> clf = RandomForestClassifier(max_depth=2, random_state=0) >>> clf.fit(X, y) RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=2, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=0, verbose=0, warm_start=False) >>> print(clf.feature_importances_) [ 0.17287856 0.80608704 0.01884792 0.00218648] >>> print(clf.predict([[0, 0, 0, 0]])) [1] Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. The features are always randomly permuted at each split. Therefore, the best found split may vary, even with the same training data, ``max_features=n_features`` and ``bootstrap=False``, if the improvement of the criterion is identical for several splits enumerated during the search of the best split. To obtain a deterministic behaviour during fitting, ``random_state`` has to be fixed. References ---------- .. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001. See also -------- DecisionTreeClassifier, ExtraTreesClassifier """ def __init__(self, n_estimators=10, criterion="gini", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False, class_weight=None): super(RandomForestClassifier, self).__init__( base_estimator=DecisionTreeClassifier(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, class_weight=class_weight) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split class RandomForestRegressor(ForestRegressor): """A random forest regressor. A random forest is a meta estimator that fits a number of classifying decision trees on various sub-samples of the dataset and use averaging to improve the predictive accuracy and control over-fitting. The sub-sample size is always the same as the original input sample size but the samples are drawn with replacement if `bootstrap=True` (default). Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : integer, optional (default=10) The number of trees in the forest. criterion : string, optional (default="mse") The function to measure the quality of a split. Supported criteria are "mse" for the mean squared error, which is equal to variance reduction as feature selection criterion, and "mae" for the mean absolute error. .. versionadded:: 0.18 Mean Absolute Error (MAE) criterion. max_features : int, float, string or None, optional (default="auto") The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a percentage and `int(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=n_features`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_depth : integer or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int, float, optional (default=2) The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a percentage and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for percentages. min_samples_leaf : int, float, optional (default=1) The minimum number of samples required to be at a leaf node: - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a percentage and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for percentages. min_weight_fraction_leaf : float, optional (default=0.) The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_leaf_nodes : int or None, optional (default=None) Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_split : float, Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19 and will be removed in 0.21. Use ``min_impurity_decrease`` instead. min_impurity_decrease : float, optional (default=0.) A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 bootstrap : boolean, optional (default=True) Whether bootstrap samples are used when building trees. oob_score : bool, optional (default=False) whether to use out-of-bag samples to estimate the R^2 on unseen data. n_jobs : integer, optional (default=1) The number of jobs to run in parallel for both `fit` and `predict`. If -1, then the number of jobs is set to the number of cores. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. verbose : int, optional (default=0) Controls the verbosity of the tree building process. warm_start : bool, optional (default=False) When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. Attributes ---------- estimators_ : list of DecisionTreeRegressor The collection of fitted sub-estimators. feature_importances_ : array of shape = [n_features] The feature importances (the higher, the more important the feature). n_features_ : int The number of features when ``fit`` is performed. n_outputs_ : int The number of outputs when ``fit`` is performed. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. oob_prediction_ : array of shape = [n_samples] Prediction computed with out-of-bag estimate on the training set. Examples -------- >>> from sklearn.ensemble import RandomForestRegressor >>> from sklearn.datasets import make_regression >>> >>> X, y = make_regression(n_features=4, n_informative=2, ... random_state=0, shuffle=False) >>> regr = RandomForestRegressor(max_depth=2, random_state=0) >>> regr.fit(X, y) RandomForestRegressor(bootstrap=True, criterion='mse', max_depth=2, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=0, verbose=0, warm_start=False) >>> print(regr.feature_importances_) [ 0.17339552 0.81594114 0. 0.01066333] >>> print(regr.predict([[0, 0, 0, 0]])) [-2.50699856] Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. The features are always randomly permuted at each split. Therefore, the best found split may vary, even with the same training data, ``max_features=n_features`` and ``bootstrap=False``, if the improvement of the criterion is identical for several splits enumerated during the search of the best split. To obtain a deterministic behaviour during fitting, ``random_state`` has to be fixed. References ---------- .. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001. See also -------- DecisionTreeRegressor, ExtraTreesRegressor """ def __init__(self, n_estimators=10, criterion="mse", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False): super(RandomForestRegressor, self).__init__( base_estimator=DecisionTreeRegressor(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split class ExtraTreesClassifier(ForestClassifier): """An extra-trees classifier. This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and use averaging to improve the predictive accuracy and control over-fitting. Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : integer, optional (default=10) The number of trees in the forest. criterion : string, optional (default="gini") The function to measure the quality of a split. Supported criteria are "gini" for the Gini impurity and "entropy" for the information gain. max_features : int, float, string or None, optional (default="auto") The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a percentage and `int(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=sqrt(n_features)`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_depth : integer or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int, float, optional (default=2) The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a percentage and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for percentages. min_samples_leaf : int, float, optional (default=1) The minimum number of samples required to be at a leaf node: - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a percentage and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for percentages. min_weight_fraction_leaf : float, optional (default=0.) The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_leaf_nodes : int or None, optional (default=None) Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_split : float, Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19 and will be removed in 0.21. Use ``min_impurity_decrease`` instead. min_impurity_decrease : float, optional (default=0.) A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 bootstrap : boolean, optional (default=False) Whether bootstrap samples are used when building trees. oob_score : bool, optional (default=False) Whether to use out-of-bag samples to estimate the generalization accuracy. n_jobs : integer, optional (default=1) The number of jobs to run in parallel for both `fit` and `predict`. If -1, then the number of jobs is set to the number of cores. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. verbose : int, optional (default=0) Controls the verbosity of the tree building process. warm_start : bool, optional (default=False) When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. class_weight : dict, list of dicts, "balanced", "balanced_subsample" or None, optional (default=None) Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` The "balanced_subsample" mode is the same as "balanced" except that weights are computed based on the bootstrap sample for every tree grown. For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. Attributes ---------- estimators_ : list of DecisionTreeClassifier The collection of fitted sub-estimators. classes_ : array of shape = [n_classes] or a list of such arrays The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). n_classes_ : int or list The number of classes (single output problem), or a list containing the number of classes for each output (multi-output problem). feature_importances_ : array of shape = [n_features] The feature importances (the higher, the more important the feature). n_features_ : int The number of features when ``fit`` is performed. n_outputs_ : int The number of outputs when ``fit`` is performed. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. oob_decision_function_ : array of shape = [n_samples, n_classes] Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, `oob_decision_function_` might contain NaN. Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. See also -------- sklearn.tree.ExtraTreeClassifier : Base classifier for this ensemble. RandomForestClassifier : Ensemble Classifier based on trees with optimal splits. """ def __init__(self, n_estimators=10, criterion="gini", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False, class_weight=None): super(ExtraTreesClassifier, self).__init__( base_estimator=ExtraTreeClassifier(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, class_weight=class_weight) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split class ExtraTreesRegressor(ForestRegressor): """An extra-trees regressor. This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and use averaging to improve the predictive accuracy and control over-fitting. Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : integer, optional (default=10) The number of trees in the forest. criterion : string, optional (default="mse") The function to measure the quality of a split. Supported criteria are "mse" for the mean squared error, which is equal to variance reduction as feature selection criterion, and "mae" for the mean absolute error. .. versionadded:: 0.18 Mean Absolute Error (MAE) criterion. max_features : int, float, string or None, optional (default="auto") The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a percentage and `int(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=n_features`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_depth : integer or None, optional (default=None) The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int, float, optional (default=2) The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a percentage and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for percentages. min_samples_leaf : int, float, optional (default=1) The minimum number of samples required to be at a leaf node: - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a percentage and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for percentages. min_weight_fraction_leaf : float, optional (default=0.) The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_leaf_nodes : int or None, optional (default=None) Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_split : float, Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19 and will be removed in 0.21. Use ``min_impurity_decrease`` instead. min_impurity_decrease : float, optional (default=0.) A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 bootstrap : boolean, optional (default=False) Whether bootstrap samples are used when building trees. oob_score : bool, optional (default=False) Whether to use out-of-bag samples to estimate the R^2 on unseen data. n_jobs : integer, optional (default=1) The number of jobs to run in parallel for both `fit` and `predict`. If -1, then the number of jobs is set to the number of cores. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. verbose : int, optional (default=0) Controls the verbosity of the tree building process. warm_start : bool, optional (default=False) When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. Attributes ---------- estimators_ : list of DecisionTreeRegressor The collection of fitted sub-estimators. feature_importances_ : array of shape = [n_features] The feature importances (the higher, the more important the feature). n_features_ : int The number of features. n_outputs_ : int The number of outputs. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. oob_prediction_ : array of shape = [n_samples] Prediction computed with out-of-bag estimate on the training set. Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. See also -------- sklearn.tree.ExtraTreeRegressor: Base estimator for this ensemble. RandomForestRegressor: Ensemble regressor using trees with optimal splits. """ def __init__(self, n_estimators=10, criterion="mse", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=False, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False): super(ExtraTreesRegressor, self).__init__( base_estimator=ExtraTreeRegressor(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split class RandomTreesEmbedding(BaseForest): """An ensemble of totally random trees. An unsupervised transformation of a dataset to a high-dimensional sparse representation. A datapoint is coded according to which leaf of each tree it is sorted into. Using a one-hot encoding of the leaves, this leads to a binary coding with as many ones as there are trees in the forest. The dimensionality of the resulting representation is ``n_out <= n_estimators * max_leaf_nodes``. If ``max_leaf_nodes == None``, the number of leaf nodes is at most ``n_estimators * 2 ** max_depth``. Read more in the :ref:`User Guide <random_trees_embedding>`. Parameters ---------- n_estimators : integer, optional (default=10) Number of trees in the forest. max_depth : integer, optional (default=5) The maximum depth of each tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int, float, optional (default=2) The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a percentage and `ceil(min_samples_split * n_samples)` is the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for percentages. min_samples_leaf : int, float, optional (default=1) The minimum number of samples required to be at a leaf node: - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a percentage and `ceil(min_samples_leaf * n_samples)` is the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for percentages. min_weight_fraction_leaf : float, optional (default=0.) The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_leaf_nodes : int or None, optional (default=None) Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_split : float, Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19 and will be removed in 0.21. Use ``min_impurity_decrease`` instead. min_impurity_decrease : float, optional (default=0.) A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 bootstrap : boolean, optional (default=True) Whether bootstrap samples are used when building trees. sparse_output : bool, optional (default=True) Whether or not to return a sparse CSR matrix, as default behavior, or to return a dense array compatible with dense pipeline operators. n_jobs : integer, optional (default=1) The number of jobs to run in parallel for both `fit` and `predict`. If -1, then the number of jobs is set to the number of cores. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. verbose : int, optional (default=0) Controls the verbosity of the tree building process. warm_start : bool, optional (default=False) When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. Attributes ---------- estimators_ : list of DecisionTreeClassifier The collection of fitted sub-estimators. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. .. [2] Moosmann, F. and Triggs, B. and Jurie, F. "Fast discriminative visual codebooks using randomized clustering forests" NIPS 2007 """ def __init__(self, n_estimators=10, max_depth=5, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, sparse_output=True, n_jobs=1, random_state=None, verbose=0, warm_start=False): super(RandomTreesEmbedding, self).__init__( base_estimator=ExtraTreeRegressor(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state"), bootstrap=False, oob_score=False, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start) self.criterion = 'mse' self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = 1 self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split self.sparse_output = sparse_output def _set_oob_score(self, X, y): raise NotImplementedError("OOB score not supported by tree embedding") def fit(self, X, y=None, sample_weight=None): """Fit estimator. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) The input samples. Use ``dtype=np.float32`` for maximum efficiency. Sparse matrices are also supported, use sparse ``csc_matrix`` for maximum efficiency. sample_weight : array-like, shape = [n_samples] or None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns ------- self : object Returns self. """ self.fit_transform(X, y, sample_weight=sample_weight) return self def fit_transform(self, X, y=None, sample_weight=None): """Fit estimator and transform dataset. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Input data used to build forests. Use ``dtype=np.float32`` for maximum efficiency. sample_weight : array-like, shape = [n_samples] or None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns ------- X_transformed : sparse matrix, shape=(n_samples, n_out) Transformed dataset. """ X = check_array(X, accept_sparse=['csc']) if issparse(X): # Pre-sort indices to avoid that each individual tree of the # ensemble sorts the indices. X.sort_indices() rnd = check_random_state(self.random_state) y = rnd.uniform(size=X.shape[0]) super(RandomTreesEmbedding, self).fit(X, y, sample_weight=sample_weight) self.one_hot_encoder_ = OneHotEncoder(sparse=self.sparse_output) return self.one_hot_encoder_.fit_transform(self.apply(X)) def transform(self, X): """Transform dataset. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Input data to be transformed. Use ``dtype=np.float32`` for maximum efficiency. Sparse matrices are also supported, use sparse ``csr_matrix`` for maximum efficiency. Returns ------- X_transformed : sparse matrix, shape=(n_samples, n_out) Transformed dataset. """ return self.one_hot_encoder_.transform(self.apply(X))
mit
relf/smt
smt/examples/b777_engine/b777_engine.py
3
8217
import numpy as np import os def get_b777_engine(): this_dir = os.path.split(__file__)[0] nt = 12 * 11 * 8 xt = np.loadtxt(os.path.join(this_dir, "b777_engine_inputs.dat")).reshape((nt, 3)) yt = np.loadtxt(os.path.join(this_dir, "b777_engine_outputs.dat")).reshape((nt, 2)) dyt_dxt = np.loadtxt(os.path.join(this_dir, "b777_engine_derivs.dat")).reshape( (nt, 2, 3) ) xlimits = np.array([[0, 0.9], [0, 15], [0, 1.0]]) return xt, yt, dyt_dxt, xlimits def plot_b777_engine(xt, yt, limits, interp): import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt val_M = np.array( [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 0.8, 0.85, 0.9] ) # 12 val_h = np.array( [0.0, 0.6096, 1.524, 3.048, 4.572, 6.096, 7.62, 9.144, 10.668, 11.8872, 13.1064] ) # 11 val_t = np.array([0.05, 0.2, 0.3, 0.4, 0.6, 0.8, 0.9, 1.0]) # 8 def get_pts(xt, yt, iy, ind_M=None, ind_h=None, ind_t=None): eps = 1e-5 if ind_M is not None: M = val_M[ind_M] keep = abs(xt[:, 0] - M) < eps xt = xt[keep, :] yt = yt[keep, :] if ind_h is not None: h = val_h[ind_h] keep = abs(xt[:, 1] - h) < eps xt = xt[keep, :] yt = yt[keep, :] if ind_t is not None: t = val_t[ind_t] keep = abs(xt[:, 2] - t) < eps xt = xt[keep, :] yt = yt[keep, :] if ind_M is None: data = xt[:, 0], yt[:, iy] elif ind_h is None: data = xt[:, 1], yt[:, iy] elif ind_t is None: data = xt[:, 2], yt[:, iy] if iy == 0: data = data[0], data[1] / 1e6 elif iy == 1: data = data[0], data[1] / 1e-4 return data num = 100 x = np.zeros((num, 3)) lins_M = np.linspace(0.0, 0.9, num) lins_h = np.linspace(0.0, 13.1064, num) lins_t = np.linspace(0.05, 1.0, num) def get_x(ind_M=None, ind_h=None, ind_t=None): x = np.zeros((num, 3)) x[:, 0] = lins_M x[:, 1] = lins_h x[:, 2] = lins_t if ind_M: x[:, 0] = val_M[ind_M] if ind_h: x[:, 1] = val_h[ind_h] if ind_t: x[:, 2] = val_t[ind_t] return x nrow = 6 ncol = 2 ind_M_1 = -2 ind_M_2 = -5 ind_t_1 = 1 ind_t_2 = -1 plt.close() # -------------------- fig, axs = plt.subplots(6, 2, gridspec_kw={"hspace": 0.5}, figsize=(15, 25)) axs[0, 0].set_title("M={}".format(val_M[ind_M_1])) axs[0, 0].set(xlabel="throttle", ylabel="thrust (x 1e6 N)") axs[0, 1].set_title("M={}".format(val_M[ind_M_1])) axs[0, 1].set(xlabel="throttle", ylabel="SFC (x 1e-3 N/N/s)") axs[1, 0].set_title("M={}".format(val_M[ind_M_2])) axs[1, 0].set(xlabel="throttle", ylabel="thrust (x 1e6 N)") axs[1, 1].set_title("M={}".format(val_M[ind_M_2])) axs[1, 1].set(xlabel="throttle", ylabel="SFC (x 1e-3 N/N/s)") # -------------------- axs[2, 0].set_title("throttle={}".format(val_t[ind_t_1])) axs[2, 0].set(xlabel="altitude (km)", ylabel="thrust (x 1e6 N)") axs[2, 1].set_title("throttle={}".format(val_t[ind_t_1])) axs[2, 1].set(xlabel="altitude (km)", ylabel="SFC (x 1e-3 N/N/s)") axs[3, 0].set_title("throttle={}".format(val_t[ind_t_2])) axs[3, 0].set(xlabel="altitude (km)", ylabel="thrust (x 1e6 N)") axs[3, 1].set_title("throttle={}".format(val_t[ind_t_2])) axs[3, 1].set(xlabel="altitude (km)", ylabel="SFC (x 1e-3 N/N/s)") # -------------------- axs[4, 0].set_title("throttle={}".format(val_t[ind_t_1])) axs[4, 0].set(xlabel="Mach number", ylabel="thrust (x 1e6 N)") axs[4, 1].set_title("throttle={}".format(val_t[ind_t_1])) axs[4, 1].set(xlabel="Mach number", ylabel="SFC (x 1e-3 N/N/s)") axs[5, 0].set_title("throttle={}".format(val_t[ind_t_2])) axs[5, 0].set(xlabel="Mach number", ylabel="thrust (x 1e6 N)") axs[5, 1].set_title("throttle={}".format(val_t[ind_t_2])) axs[5, 1].set(xlabel="Mach number", ylabel="SFC (x 1e-3 N/N/s)") ind_h_list = [0, 4, 7, 10] ind_h_list = [4, 7, 10] ind_M_list = [0, 3, 6, 11] ind_M_list = [3, 6, 11] colors = ["b", "r", "g", "c", "m"] # ----------------------------------------------------------------------------- # Throttle slices for k, ind_h in enumerate(ind_h_list): ind_M = ind_M_1 x = get_x(ind_M=ind_M, ind_h=ind_h) y = interp.predict_values(x) xt_, yt_ = get_pts(xt, yt, 0, ind_M=ind_M, ind_h=ind_h) axs[0, 0].plot(xt_, yt_, "o" + colors[k]) axs[0, 0].plot(lins_t, y[:, 0] / 1e6, colors[k]) xt_, yt_ = get_pts(xt, yt, 1, ind_M=ind_M, ind_h=ind_h) axs[0, 1].plot(xt_, yt_, "o" + colors[k]) axs[0, 1].plot(lins_t, y[:, 1] / 1e-4, colors[k]) ind_M = ind_M_2 x = get_x(ind_M=ind_M, ind_h=ind_h) y = interp.predict_values(x) xt_, yt_ = get_pts(xt, yt, 0, ind_M=ind_M, ind_h=ind_h) axs[1, 0].plot(xt_, yt_, "o" + colors[k]) axs[1, 0].plot(lins_t, y[:, 0] / 1e6, colors[k]) xt_, yt_ = get_pts(xt, yt, 1, ind_M=ind_M, ind_h=ind_h) axs[1, 1].plot(xt_, yt_, "o" + colors[k]) axs[1, 1].plot(lins_t, y[:, 1] / 1e-4, colors[k]) # ----------------------------------------------------------------------------- # Altitude slices for k, ind_M in enumerate(ind_M_list): ind_t = ind_t_1 x = get_x(ind_M=ind_M, ind_t=ind_t) y = interp.predict_values(x) xt_, yt_ = get_pts(xt, yt, 0, ind_M=ind_M, ind_t=ind_t) axs[2, 0].plot(xt_, yt_, "o" + colors[k]) axs[2, 0].plot(lins_h, y[:, 0] / 1e6, colors[k]) xt_, yt_ = get_pts(xt, yt, 1, ind_M=ind_M, ind_t=ind_t) axs[2, 1].plot(xt_, yt_, "o" + colors[k]) axs[2, 1].plot(lins_h, y[:, 1] / 1e-4, colors[k]) ind_t = ind_t_2 x = get_x(ind_M=ind_M, ind_t=ind_t) y = interp.predict_values(x) xt_, yt_ = get_pts(xt, yt, 0, ind_M=ind_M, ind_t=ind_t) axs[3, 0].plot(xt_, yt_, "o" + colors[k]) axs[3, 0].plot(lins_h, y[:, 0] / 1e6, colors[k]) xt_, yt_ = get_pts(xt, yt, 1, ind_M=ind_M, ind_t=ind_t) axs[3, 1].plot(xt_, yt_, "o" + colors[k]) axs[3, 1].plot(lins_h, y[:, 1] / 1e-4, colors[k]) # ----------------------------------------------------------------------------- # Mach number slices for k, ind_h in enumerate(ind_h_list): ind_t = ind_t_1 x = get_x(ind_t=ind_t, ind_h=ind_h) y = interp.predict_values(x) xt_, yt_ = get_pts(xt, yt, 0, ind_h=ind_h, ind_t=ind_t) axs[4, 0].plot(xt_, yt_, "o" + colors[k]) axs[4, 0].plot(lins_M, y[:, 0] / 1e6, colors[k]) xt_, yt_ = get_pts(xt, yt, 1, ind_h=ind_h, ind_t=ind_t) axs[4, 1].plot(xt_, yt_, "o" + colors[k]) axs[4, 1].plot(lins_M, y[:, 1] / 1e-4, colors[k]) ind_t = ind_t_2 x = get_x(ind_t=ind_t, ind_h=ind_h) y = interp.predict_values(x) xt_, yt_ = get_pts(xt, yt, 0, ind_h=ind_h, ind_t=ind_t) axs[5, 0].plot(xt_, yt_, "o" + colors[k]) axs[5, 0].plot(lins_M, y[:, 0] / 1e6, colors[k]) xt_, yt_ = get_pts(xt, yt, 1, ind_h=ind_h, ind_t=ind_t) axs[5, 1].plot(xt_, yt_, "o" + colors[k]) axs[5, 1].plot(lins_M, y[:, 1] / 1e-4, colors[k]) # ----------------------------------------------------------------------------- for k in range(2): legend_entries = [] for ind_h in ind_h_list: legend_entries.append("h={}".format(val_h[ind_h])) legend_entries.append("") axs[k, 0].legend(legend_entries) axs[k, 1].legend(legend_entries) axs[k + 4, 0].legend(legend_entries) axs[k + 4, 1].legend(legend_entries) legend_entries = [] for ind_M in ind_M_list: legend_entries.append("M={}".format(val_M[ind_M])) legend_entries.append("") axs[k + 2, 0].legend(legend_entries) axs[k + 2, 1].legend(legend_entries) plt.show()
bsd-3-clause
rahuldhote/scikit-learn
sklearn/feature_selection/__init__.py
244
1088
""" The :mod:`sklearn.feature_selection` module implements feature selection algorithms. It currently includes univariate filter selection methods and the recursive feature elimination algorithm. """ from .univariate_selection import chi2 from .univariate_selection import f_classif from .univariate_selection import f_oneway from .univariate_selection import f_regression from .univariate_selection import SelectPercentile from .univariate_selection import SelectKBest from .univariate_selection import SelectFpr from .univariate_selection import SelectFdr from .univariate_selection import SelectFwe from .univariate_selection import GenericUnivariateSelect from .variance_threshold import VarianceThreshold from .rfe import RFE from .rfe import RFECV __all__ = ['GenericUnivariateSelect', 'RFE', 'RFECV', 'SelectFdr', 'SelectFpr', 'SelectFwe', 'SelectKBest', 'SelectPercentile', 'VarianceThreshold', 'chi2', 'f_classif', 'f_oneway', 'f_regression']
bsd-3-clause
tmhm/scikit-learn
setup.py
143
7364
#! /usr/bin/env python # # Copyright (C) 2007-2009 Cournapeau David <cournape@gmail.com> # 2010 Fabian Pedregosa <fabian.pedregosa@inria.fr> # License: 3-clause BSD descr = """A set of python modules for machine learning and data mining""" import sys import os import shutil from distutils.command.clean import clean as Clean if sys.version_info[0] < 3: import __builtin__ as builtins else: import builtins # This is a bit (!) hackish: we are setting a global variable so that the main # sklearn __init__ can detect if it is being loaded by the setup routine, to # avoid attempting to load components that aren't built yet: # the numpy distutils extensions that are used by scikit-learn to recursively # build the compiled extensions in sub-packages is based on the Python import # machinery. builtins.__SKLEARN_SETUP__ = True DISTNAME = 'scikit-learn' DESCRIPTION = 'A set of python modules for machine learning and data mining' with open('README.rst') as f: LONG_DESCRIPTION = f.read() MAINTAINER = 'Andreas Mueller' MAINTAINER_EMAIL = 'amueller@ais.uni-bonn.de' URL = 'http://scikit-learn.org' LICENSE = 'new BSD' DOWNLOAD_URL = 'http://sourceforge.net/projects/scikit-learn/files/' # We can actually import a restricted version of sklearn that # does not need the compiled code import sklearn VERSION = sklearn.__version__ # Optional setuptools features # We need to import setuptools early, if we want setuptools features, # as it monkey-patches the 'setup' function # For some commands, use setuptools SETUPTOOLS_COMMANDS = set([ 'develop', 'release', 'bdist_egg', 'bdist_rpm', 'bdist_wininst', 'install_egg_info', 'build_sphinx', 'egg_info', 'easy_install', 'upload', 'bdist_wheel', '--single-version-externally-managed', ]) if SETUPTOOLS_COMMANDS.intersection(sys.argv): import setuptools extra_setuptools_args = dict( zip_safe=False, # the package can run out of an .egg file include_package_data=True, ) else: extra_setuptools_args = dict() # Custom clean command to remove build artifacts class CleanCommand(Clean): description = "Remove build artifacts from the source tree" def run(self): Clean.run(self) if os.path.exists('build'): shutil.rmtree('build') for dirpath, dirnames, filenames in os.walk('sklearn'): for filename in filenames: if (filename.endswith('.so') or filename.endswith('.pyd') or filename.endswith('.dll') or filename.endswith('.pyc')): os.unlink(os.path.join(dirpath, filename)) for dirname in dirnames: if dirname == '__pycache__': shutil.rmtree(os.path.join(dirpath, dirname)) cmdclass = {'clean': CleanCommand} # Optional wheelhouse-uploader features # To automate release of binary packages for scikit-learn we need a tool # to download the packages generated by travis and appveyor workers (with # version number matching the current release) and upload them all at once # to PyPI at release time. # The URL of the artifact repositories are configured in the setup.cfg file. WHEELHOUSE_UPLOADER_COMMANDS = set(['fetch_artifacts', 'upload_all']) if WHEELHOUSE_UPLOADER_COMMANDS.intersection(sys.argv): import wheelhouse_uploader.cmd cmdclass.update(vars(wheelhouse_uploader.cmd)) def configuration(parent_package='', top_path=None): if os.path.exists('MANIFEST'): os.remove('MANIFEST') from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path) # Avoid non-useful msg: # "Ignoring attempt to set 'name' (from ... " config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('sklearn') return config def is_scipy_installed(): try: import scipy except ImportError: return False return True def is_numpy_installed(): try: import numpy except ImportError: return False return True def setup_package(): metadata = dict(name=DISTNAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, license=LICENSE, url=URL, version=VERSION, download_url=DOWNLOAD_URL, long_description=LONG_DESCRIPTION, classifiers=['Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'License :: OSI Approved', 'Programming Language :: C', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Scientific/Engineering', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], cmdclass=cmdclass, **extra_setuptools_args) if (len(sys.argv) >= 2 and ('--help' in sys.argv[1:] or sys.argv[1] in ('--help-commands', 'egg_info', '--version', 'clean'))): # For these actions, NumPy is not required. # # They are required to succeed without Numpy for example when # pip is used to install Scikit-learn when Numpy is not yet present in # the system. try: from setuptools import setup except ImportError: from distutils.core import setup metadata['version'] = VERSION else: if is_numpy_installed() is False: raise ImportError("Numerical Python (NumPy) is not installed.\n" "scikit-learn requires NumPy.\n" "Installation instructions are available on scikit-learn website: " "http://scikit-learn.org/stable/install.html\n") if is_scipy_installed() is False: raise ImportError("Scientific Python (SciPy) is not installed.\n" "scikit-learn requires SciPy.\n" "Installation instructions are available on scikit-learn website: " "http://scikit-learn.org/stable/install.html\n") from numpy.distutils.core import setup metadata['configuration'] = configuration setup(**metadata) if __name__ == "__main__": setup_package()
bsd-3-clause