repo_name
stringlengths
6
100
path
stringlengths
4
191
copies
stringlengths
1
3
size
stringlengths
4
6
content
stringlengths
935
727k
license
stringclasses
15 values
WangWenjun559/Weiss
summary/sumy/sklearn/ensemble/tests/test_weight_boosting.py
32
15697
"""Testing for the boost module (sklearn.ensemble.boost).""" import numpy as np 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_equal from sklearn.utils.testing import assert_raises, assert_raises_regexp from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import AdaBoostRegressor 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.svm import SVC, SVR from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.utils import shuffle 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 boston dataset and randomly permute it boston = datasets.load_boston() boston.data, boston.target = shuffle(boston.data, boston.target, random_state=rng) def test_classification_toy(): # Check classification on a toy dataset. for alg in ['SAMME', 'SAMME.R']: clf = AdaBoostClassifier(algorithm=alg, 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_equal(clf.predict_proba(T).shape, (len(T), 2)) assert_equal(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_equal(proba.shape[1], len(classes)) assert_equal(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) # 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)) def test_boston(): # Check consistency on dataset boston house prices. clf = AdaBoostRegressor(random_state=0) clf.fit(boston.data, boston.target) score = clf.score(boston.data, boston.target) assert score > 0.85 def test_staged_predict(): # Check staged predictions. rng = np.random.RandomState(0) iris_weights = rng.randint(10, size=iris.target.shape) boston_weights = rng.randint(10, size=boston.target.shape) # AdaBoost classification for alg in ['SAMME', 'SAMME.R']: clf = AdaBoostClassifier(algorithm=alg, 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_equal(len(staged_predictions), 10) assert_array_almost_equal(predictions, staged_predictions[-1]) assert_equal(len(staged_probas), 10) assert_array_almost_equal(proba, staged_probas[-1]) assert_equal(len(staged_scores), 10) assert_array_almost_equal(score, staged_scores[-1]) # AdaBoost regression clf = AdaBoostRegressor(n_estimators=10, random_state=0) clf.fit(boston.data, boston.target, sample_weight=boston_weights) predictions = clf.predict(boston.data) staged_predictions = [p for p in clf.staged_predict(boston.data)] score = clf.score(boston.data, boston.target, sample_weight=boston_weights) staged_scores = [ s for s in clf.staged_score( boston.data, boston.target, sample_weight=boston_weights)] assert_equal(len(staged_predictions), 10) assert_array_almost_equal(predictions, staged_predictions[-1]) assert_equal(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(boston.data, boston.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_equal(type(obj2), obj.__class__) score2 = obj2.score(iris.data, iris.target) assert_equal(score, score2) # Adaboost regressor obj = AdaBoostRegressor(random_state=0) obj.fit(boston.data, boston.target) score = obj.score(boston.data, boston.target) s = pickle.dumps(obj) obj2 = pickle.loads(s) assert_equal(type(obj2), obj.__class__) score2 = obj2.score(boston.data, boston.target) assert_equal(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_equal(importances.shape[0], 10) assert_equal((importances[:3, np.newaxis] >= importances[3:]).all(), True) 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 from sklearn.svm import SVC # 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 from sklearn.svm import SVR 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_sample_weight_missing(): from sklearn.linear_model import LinearRegression from sklearn.cluster import KMeans clf = AdaBoostClassifier(LinearRegression(), algorithm="SAMME") assert_raises(ValueError, clf.fit, X, y_regr) clf = AdaBoostRegressor(LinearRegression()) assert_raises(ValueError, clf.fit, X, y_regr) clf = AdaBoostClassifier(KMeans(), algorithm="SAMME") assert_raises(ValueError, clf.fit, X, y_regr) clf = AdaBoostRegressor(KMeans()) assert_raises(ValueError, clf.fit, X, y_regr) 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(CustomSVC, self).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, return_indicator=True, 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_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_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_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_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_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_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(CustomSVR, self).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_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_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])
apache-2.0
vipullakhani/mi-instrument
mi/core/instrument/file_publisher.py
5
4306
""" @package mi.core.instrument.publisher @file /mi-instrument/mi/core/instrument/file_publisher.py @author Peter Cable @brief Event file publisher Release notes: initial release """ import cPickle as pickle import json import numpy as np import pandas as pd import xarray as xr from mi.core.instrument.publisher import Publisher from mi.logging import log class CountPublisher(Publisher): def __init__(self, allowed): super(CountPublisher, self).__init__(allowed) self.total = 0 def _publish(self, events, headers): for e in events: try: json.dumps(e) except (ValueError, UnicodeDecodeError) as err: log.exception('Unable to publish event: %r %r', e, err) count = len(events) self.total += count log.info('Publish %d events (%d total)', count, self.total) class FilePublisher(Publisher): def __init__(self, *args, **kwargs): super(FilePublisher, self).__init__(*args, **kwargs) self.samples = {} @staticmethod def _flatten(sample): values = sample.pop('values') for each in values: sample[each['value_id']] = each['value'] return sample def _publish(self, events, headers): for event in events: # file publisher only applicable to particles if event.get('type') != 'DRIVER_ASYNC_EVENT_SAMPLE': continue particle = event.get('value', {}) stream = particle.get('stream_name') if stream: particle = self._flatten(particle) self.samples.setdefault(stream, []).append(particle) def to_dataframes(self): data_frames = {} for particle_type in self.samples: data_frames[particle_type] = self.fix_arrays(pd.DataFrame(self.samples[particle_type])) return data_frames def to_datasets(self): datasets = {} for particle_type in self.samples: datasets[particle_type] = self.fix_arrays(pd.DataFrame(self.samples[particle_type]), return_as_xr=True) return datasets @staticmethod def fix_arrays(data_frame, return_as_xr=False): # round-trip the dataframe through xray to get the multidimensional indexing correct new_ds = xr.Dataset() for each in data_frame: if data_frame[each].dtype == 'object' and isinstance(data_frame[each].values[0], list): data = np.array([np.array(x) for x in data_frame[each].values]) new_ds[each] = xr.DataArray(data) else: new_ds[each] = data_frame[each] if return_as_xr: return new_ds return new_ds.to_dataframe() def write(self): log.info('Writing output files...') self._write() log.info('Done writing output files...') def _write(self): raise NotImplemented class CsvPublisher(FilePublisher): def _write(self): dataframes = self.to_dataframes() for particle_type in dataframes: file_path = '%s.csv' % particle_type dataframes[particle_type].to_csv(file_path) class PandasPublisher(FilePublisher): def _write(self): dataframes = self.to_dataframes() for particle_type in dataframes: # very large dataframes don't work with pickle # split if too large df = dataframes[particle_type] max_size = 5000000 if len(df) > max_size: num_slices = len(df) / max_size slices = np.array_split(df, num_slices) for index, df_slice in enumerate(slices): file_path = '%s_%d.pd' % (particle_type, index) df_slice.to_pickle(file_path) else: log.info('length of dataframe: %d', len(df)) file_path = '%s.pd' % particle_type dataframes[particle_type].to_pickle(file_path) class XarrayPublisher(FilePublisher): def _write(self): datasets = self.to_datasets() for particle_type in datasets: file_path = '%s.xr' % particle_type with open(file_path, 'w') as fh: pickle.dump(datasets[particle_type], fh, protocol=-1)
bsd-2-clause
18padx08/PPTex
PPTexEnv_x86_64/lib/python2.7/site-packages/matplotlib/backend_bases.py
10
106046
""" Abstract base classes define the primitives that renderers and graphics contexts must implement to serve as a matplotlib backend :class:`RendererBase` An abstract base class to handle drawing/rendering operations. :class:`FigureCanvasBase` The abstraction layer that separates the :class:`matplotlib.figure.Figure` from the backend specific details like a user interface drawing area :class:`GraphicsContextBase` An abstract base class that provides color, line styles, etc... :class:`Event` The base class for all of the matplotlib event handling. Derived classes suh as :class:`KeyEvent` and :class:`MouseEvent` store the meta data like keys and buttons pressed, x and y locations in pixel and :class:`~matplotlib.axes.Axes` coordinates. :class:`ShowBase` The base class for the Show class of each interactive backend; the 'show' callable is then set to Show.__call__, inherited from ShowBase. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import xrange import os import sys import warnings import time import io import numpy as np import matplotlib.cbook as cbook import matplotlib.colors as colors import matplotlib.transforms as transforms import matplotlib.widgets as widgets #import matplotlib.path as path from matplotlib import rcParams from matplotlib import is_interactive from matplotlib import get_backend from matplotlib._pylab_helpers import Gcf from matplotlib.transforms import Bbox, TransformedBbox, Affine2D import matplotlib.tight_bbox as tight_bbox import matplotlib.textpath as textpath from matplotlib.path import Path from matplotlib.cbook import mplDeprecation try: from importlib import import_module except: # simple python 2.6 implementation (no relative imports) def import_module(name): __import__(name) return sys.modules[name] try: from PIL import Image _has_pil = True except ImportError: _has_pil = False _default_filetypes = { 'ps': 'Postscript', 'eps': 'Encapsulated Postscript', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics' } _default_backends = { 'ps': 'matplotlib.backends.backend_ps', 'eps': 'matplotlib.backends.backend_ps', 'pdf': 'matplotlib.backends.backend_pdf', 'pgf': 'matplotlib.backends.backend_pgf', 'png': 'matplotlib.backends.backend_agg', 'raw': 'matplotlib.backends.backend_agg', 'rgba': 'matplotlib.backends.backend_agg', 'svg': 'matplotlib.backends.backend_svg', 'svgz': 'matplotlib.backends.backend_svg', } def register_backend(format, backend, description=None): """ Register a backend for saving to a given file format. format : str File extention backend : module string or canvas class Backend for handling file output description : str, optional Description of the file type. Defaults to an empty string """ if description is None: description = '' _default_backends[format] = backend _default_filetypes[format] = description def get_registered_canvas_class(format): """ Return the registered default canvas for given file format. Handles deferred import of required backend. """ if format not in _default_backends: return None backend_class = _default_backends[format] if cbook.is_string_like(backend_class): backend_class = import_module(backend_class).FigureCanvas _default_backends[format] = backend_class return backend_class class ShowBase(object): """ Simple base class to generate a show() callable in backends. Subclass must override mainloop() method. """ def __call__(self, block=None): """ Show all figures. If *block* is not None, then it is a boolean that overrides all other factors determining whether show blocks by calling mainloop(). The other factors are: it does not block if run inside ipython's "%pylab" mode it does not block in interactive mode. """ managers = Gcf.get_all_fig_managers() if not managers: return for manager in managers: manager.show() if block is not None: if block: self.mainloop() return else: return # Hack: determine at runtime whether we are # inside ipython in pylab mode. from matplotlib import pyplot try: ipython_pylab = not pyplot.show._needmain # IPython versions >= 0.10 tack the _needmain # attribute onto pyplot.show, and always set # it to False, when in %pylab mode. ipython_pylab = ipython_pylab and get_backend() != 'WebAgg' # TODO: The above is a hack to get the WebAgg backend # working with ipython's `%pylab` mode until proper # integration is implemented. except AttributeError: ipython_pylab = False # Leave the following as a separate step in case we # want to control this behavior with an rcParam. if ipython_pylab: return if not is_interactive() or get_backend() == 'WebAgg': self.mainloop() def mainloop(self): pass class RendererBase(object): """An abstract base class to handle drawing/rendering operations. The following methods must be implemented in the backend for full functionality (though just implementing :meth:`draw_path` alone would give a highly capable backend): * :meth:`draw_path` * :meth:`draw_image` * :meth:`draw_gouraud_triangle` The following methods *should* be implemented in the backend for optimization reasons: * :meth:`draw_text` * :meth:`draw_markers` * :meth:`draw_path_collection` * :meth:`draw_quad_mesh` """ def __init__(self): self._texmanager = None self._text2path = textpath.TextToPath() def open_group(self, s, gid=None): """ Open a grouping element with label *s*. If *gid* is given, use *gid* as the id of the group. Is only currently used by :mod:`~matplotlib.backends.backend_svg`. """ pass def close_group(self, s): """ Close a grouping element with label *s* Is only currently used by :mod:`~matplotlib.backends.backend_svg` """ pass def draw_path(self, gc, path, transform, rgbFace=None): """ Draws a :class:`~matplotlib.path.Path` instance using the given affine transform. """ raise NotImplementedError def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): """ Draws a marker at each of the vertices in path. This includes all vertices, including control points on curves. To avoid that behavior, those vertices should be removed before calling this function. *gc* the :class:`GraphicsContextBase` instance *marker_trans* is an affine transform applied to the marker. *trans* is an affine transform applied to the path. This provides a fallback implementation of draw_markers that makes multiple calls to :meth:`draw_path`. Some backends may want to override this method in order to draw the marker only once and reuse it multiple times. """ for vertices, codes in path.iter_segments(trans, simplify=False): if len(vertices): x, y = vertices[-2:] self.draw_path(gc, marker_path, marker_trans + transforms.Affine2D().translate(x, y), rgbFace) def draw_path_collection(self, gc, master_transform, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): """ Draws a collection of paths selecting drawing properties from the lists *facecolors*, *edgecolors*, *linewidths*, *linestyles* and *antialiaseds*. *offsets* is a list of offsets to apply to each of the paths. The offsets in *offsets* are first transformed by *offsetTrans* before being applied. *offset_position* may be either "screen" or "data" depending on the space that the offsets are in. This provides a fallback implementation of :meth:`draw_path_collection` that makes multiple calls to :meth:`draw_path`. Some backends may want to override this in order to render each set of path data only once, and then reference that path multiple times with the different offsets, colors, styles etc. The generator methods :meth:`_iter_collection_raw_paths` and :meth:`_iter_collection` are provided to help with (and standardize) the implementation across backends. It is highly recommended to use those generators, so that changes to the behavior of :meth:`draw_path_collection` can be made globally. """ path_ids = [] for path, transform in self._iter_collection_raw_paths( master_transform, paths, all_transforms): path_ids.append((path, transforms.Affine2D(transform))) for xo, yo, path_id, gc0, rgbFace in self._iter_collection( gc, master_transform, all_transforms, path_ids, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): path, transform = path_id transform = transforms.Affine2D( transform.get_matrix()).translate(xo, yo) self.draw_path(gc0, path, transform, rgbFace) def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight, coordinates, offsets, offsetTrans, facecolors, antialiased, edgecolors): """ This provides a fallback implementation of :meth:`draw_quad_mesh` that generates paths and then calls :meth:`draw_path_collection`. """ from matplotlib.collections import QuadMesh paths = QuadMesh.convert_mesh_to_paths( meshWidth, meshHeight, coordinates) if edgecolors is None: edgecolors = facecolors linewidths = np.array([gc.get_linewidth()], np.float_) return self.draw_path_collection( gc, master_transform, paths, [], offsets, offsetTrans, facecolors, edgecolors, linewidths, [], [antialiased], [None], 'screen') def draw_gouraud_triangle(self, gc, points, colors, transform): """ Draw a Gouraud-shaded triangle. *points* is a 3x2 array of (x, y) points for the triangle. *colors* is a 3x4 array of RGBA colors for each point of the triangle. *transform* is an affine transform to apply to the points. """ raise NotImplementedError def draw_gouraud_triangles(self, gc, triangles_array, colors_array, transform): """ Draws a series of Gouraud triangles. *points* is a Nx3x2 array of (x, y) points for the trianglex. *colors* is a Nx3x4 array of RGBA colors for each point of the triangles. *transform* is an affine transform to apply to the points. """ transform = transform.frozen() for tri, col in zip(triangles_array, colors_array): self.draw_gouraud_triangle(gc, tri, col, transform) def _iter_collection_raw_paths(self, master_transform, paths, all_transforms): """ This is a helper method (along with :meth:`_iter_collection`) to make it easier to write a space-efficent :meth:`draw_path_collection` implementation in a backend. This method yields all of the base path/transform combinations, given a master transform, a list of paths and list of transforms. The arguments should be exactly what is passed in to :meth:`draw_path_collection`. The backend should take each yielded path and transform and create an object that can be referenced (reused) later. """ Npaths = len(paths) Ntransforms = len(all_transforms) N = max(Npaths, Ntransforms) if Npaths == 0: return transform = transforms.IdentityTransform() for i in xrange(N): path = paths[i % Npaths] if Ntransforms: transform = Affine2D(all_transforms[i % Ntransforms]) yield path, transform + master_transform def _iter_collection_uses_per_path(self, paths, all_transforms, offsets, facecolors, edgecolors): """ Compute how many times each raw path object returned by _iter_collection_raw_paths would be used when calling _iter_collection. This is intended for the backend to decide on the tradeoff between using the paths in-line and storing them once and reusing. Rounds up in case the number of uses is not the same for every path. """ Npaths = len(paths) if Npaths == 0 or (len(facecolors) == 0 and len(edgecolors) == 0): return 0 Npath_ids = max(Npaths, len(all_transforms)) N = max(Npath_ids, len(offsets)) return (N + Npath_ids - 1) // Npath_ids def _iter_collection(self, gc, master_transform, all_transforms, path_ids, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): """ This is a helper method (along with :meth:`_iter_collection_raw_paths`) to make it easier to write a space-efficent :meth:`draw_path_collection` implementation in a backend. This method yields all of the path, offset and graphics context combinations to draw the path collection. The caller should already have looped over the results of :meth:`_iter_collection_raw_paths` to draw this collection. The arguments should be the same as that passed into :meth:`draw_path_collection`, with the exception of *path_ids*, which is a list of arbitrary objects that the backend will use to reference one of the paths created in the :meth:`_iter_collection_raw_paths` stage. Each yielded result is of the form:: xo, yo, path_id, gc, rgbFace where *xo*, *yo* is an offset; *path_id* is one of the elements of *path_ids*; *gc* is a graphics context and *rgbFace* is a color to use for filling the path. """ Ntransforms = len(all_transforms) Npaths = len(path_ids) Noffsets = len(offsets) N = max(Npaths, Noffsets) Nfacecolors = len(facecolors) Nedgecolors = len(edgecolors) Nlinewidths = len(linewidths) Nlinestyles = len(linestyles) Naa = len(antialiaseds) Nurls = len(urls) if (Nfacecolors == 0 and Nedgecolors == 0) or Npaths == 0: return if Noffsets: toffsets = offsetTrans.transform(offsets) gc0 = self.new_gc() gc0.copy_properties(gc) if Nfacecolors == 0: rgbFace = None if Nedgecolors == 0: gc0.set_linewidth(0.0) xo, yo = 0, 0 for i in xrange(N): path_id = path_ids[i % Npaths] if Noffsets: xo, yo = toffsets[i % Noffsets] if offset_position == 'data': if Ntransforms: transform = ( Affine2D(all_transforms[i % Ntransforms]) + master_transform) else: transform = master_transform xo, yo = transform.transform_point((xo, yo)) xp, yp = transform.transform_point((0, 0)) xo = -(xp - xo) yo = -(yp - yo) if not (np.isfinite(xo) and np.isfinite(yo)): continue if Nfacecolors: rgbFace = facecolors[i % Nfacecolors] if Nedgecolors: if Nlinewidths: gc0.set_linewidth(linewidths[i % Nlinewidths]) if Nlinestyles: gc0.set_dashes(*linestyles[i % Nlinestyles]) fg = edgecolors[i % Nedgecolors] if len(fg) == 4: if fg[3] == 0.0: gc0.set_linewidth(0) else: gc0.set_foreground(fg) else: gc0.set_foreground(fg) if rgbFace is not None and len(rgbFace) == 4: if rgbFace[3] == 0: rgbFace = None gc0.set_antialiased(antialiaseds[i % Naa]) if Nurls: gc0.set_url(urls[i % Nurls]) yield xo, yo, path_id, gc0, rgbFace gc0.restore() def get_image_magnification(self): """ Get the factor by which to magnify images passed to :meth:`draw_image`. Allows a backend to have images at a different resolution to other artists. """ return 1.0 def draw_image(self, gc, x, y, im): """ Draw the image instance into the current axes; *gc* a GraphicsContext containing clipping information *x* is the distance in pixels from the left hand side of the canvas. *y* the distance from the origin. That is, if origin is upper, y is the distance from top. If origin is lower, y is the distance from bottom *im* the :class:`matplotlib._image.Image` instance """ raise NotImplementedError def option_image_nocomposite(self): """ override this method for renderers that do not necessarily want to rescale and composite raster images. (like SVG) """ return False def option_scale_image(self): """ override this method for renderers that support arbitrary scaling of image (most of the vector backend). """ return False def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None): """ """ self._draw_text_as_path(gc, x, y, s, prop, angle, ismath="TeX") def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): """ Draw the text instance *gc* the :class:`GraphicsContextBase` instance *x* the x location of the text in display coords *y* the y location of the text baseline in display coords *s* the text string *prop* a :class:`matplotlib.font_manager.FontProperties` instance *angle* the rotation angle in degrees *mtext* a :class:`matplotlib.text.Text` instance **backend implementers note** When you are trying to determine if you have gotten your bounding box right (which is what enables the text layout/alignment to work properly), it helps to change the line in text.py:: if 0: bbox_artist(self, renderer) to if 1, and then the actual bounding box will be plotted along with your text. """ self._draw_text_as_path(gc, x, y, s, prop, angle, ismath) def _get_text_path_transform(self, x, y, s, prop, angle, ismath): """ return the text path and transform *prop* font property *s* text to be converted *usetex* If True, use matplotlib usetex mode. *ismath* If True, use mathtext parser. If "TeX", use *usetex* mode. """ text2path = self._text2path fontsize = self.points_to_pixels(prop.get_size_in_points()) if ismath == "TeX": verts, codes = text2path.get_text_path(prop, s, ismath=False, usetex=True) else: verts, codes = text2path.get_text_path(prop, s, ismath=ismath, usetex=False) path = Path(verts, codes) angle = angle / 180. * 3.141592 if self.flipy(): transform = Affine2D().scale(fontsize / text2path.FONT_SCALE, fontsize / text2path.FONT_SCALE) transform = transform.rotate(angle).translate(x, self.height - y) else: transform = Affine2D().scale(fontsize / text2path.FONT_SCALE, fontsize / text2path.FONT_SCALE) transform = transform.rotate(angle).translate(x, y) return path, transform def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath): """ draw the text by converting them to paths using textpath module. *prop* font property *s* text to be converted *usetex* If True, use matplotlib usetex mode. *ismath* If True, use mathtext parser. If "TeX", use *usetex* mode. """ path, transform = self._get_text_path_transform( x, y, s, prop, angle, ismath) color = gc.get_rgb() gc.set_linewidth(0.0) self.draw_path(gc, path, transform, rgbFace=color) def get_text_width_height_descent(self, s, prop, ismath): """ get the width and height, and the offset from the bottom to the baseline (descent), in display coords of the string s with :class:`~matplotlib.font_manager.FontProperties` prop """ if ismath == 'TeX': # todo: handle props size = prop.get_size_in_points() texmanager = self._text2path.get_texmanager() fontsize = prop.get_size_in_points() w, h, d = texmanager.get_text_width_height_descent(s, fontsize, renderer=self) return w, h, d dpi = self.points_to_pixels(72) if ismath: dims = self._text2path.mathtext_parser.parse(s, dpi, prop) return dims[0:3] # return width, height, descent flags = self._text2path._get_hinting_flag() font = self._text2path._get_font(prop) size = prop.get_size_in_points() font.set_size(size, dpi) # the width and height of unrotated string font.set_text(s, 0.0, flags=flags) w, h = font.get_width_height() d = font.get_descent() w /= 64.0 # convert from subpixels h /= 64.0 d /= 64.0 return w, h, d def flipy(self): """ Return true if y small numbers are top for renderer Is used for drawing text (:mod:`matplotlib.text`) and images (:mod:`matplotlib.image`) only """ return True def get_canvas_width_height(self): 'return the canvas width and height in display coords' return 1, 1 def get_texmanager(self): """ return the :class:`matplotlib.texmanager.TexManager` instance """ if self._texmanager is None: from matplotlib.texmanager import TexManager self._texmanager = TexManager() return self._texmanager def new_gc(self): """ Return an instance of a :class:`GraphicsContextBase` """ return GraphicsContextBase() def points_to_pixels(self, points): """ Convert points to display units *points* a float or a numpy array of float return points converted to pixels You need to override this function (unless your backend doesn't have a dpi, e.g., postscript or svg). Some imaging systems assume some value for pixels per inch:: points to pixels = points * pixels_per_inch/72.0 * dpi/72.0 """ return points def strip_math(self, s): return cbook.strip_math(s) def start_rasterizing(self): """ Used in MixedModeRenderer. Switch to the raster renderer. """ pass def stop_rasterizing(self): """ Used in MixedModeRenderer. Switch back to the vector renderer and draw the contents of the raster renderer as an image on the vector renderer. """ pass def start_filter(self): """ Used in AggRenderer. Switch to a temporary renderer for image filtering effects. """ pass def stop_filter(self, filter_func): """ Used in AggRenderer. Switch back to the original renderer. The contents of the temporary renderer is processed with the *filter_func* and is drawn on the original renderer as an image. """ pass class GraphicsContextBase: """ An abstract base class that provides color, line styles, etc... """ # a mapping from dash styles to suggested offset, dash pairs dashd = { 'solid': (None, None), 'dashed': (0, (6.0, 6.0)), 'dashdot': (0, (3.0, 5.0, 1.0, 5.0)), 'dotted': (0, (1.0, 3.0)), } def __init__(self): self._alpha = 1.0 self._forced_alpha = False # if True, _alpha overrides A from RGBA self._antialiased = 1 # use 0,1 not True, False for extension code self._capstyle = 'butt' self._cliprect = None self._clippath = None self._dashes = None, None self._joinstyle = 'round' self._linestyle = 'solid' self._linewidth = 1 self._rgb = (0.0, 0.0, 0.0, 1.0) self._orig_color = (0.0, 0.0, 0.0, 1.0) self._hatch = None self._url = None self._gid = None self._snap = None self._sketch = None def copy_properties(self, gc): 'Copy properties from gc to self' self._alpha = gc._alpha self._forced_alpha = gc._forced_alpha self._antialiased = gc._antialiased self._capstyle = gc._capstyle self._cliprect = gc._cliprect self._clippath = gc._clippath self._dashes = gc._dashes self._joinstyle = gc._joinstyle self._linestyle = gc._linestyle self._linewidth = gc._linewidth self._rgb = gc._rgb self._orig_color = gc._orig_color self._hatch = gc._hatch self._url = gc._url self._gid = gc._gid self._snap = gc._snap self._sketch = gc._sketch def restore(self): """ Restore the graphics context from the stack - needed only for backends that save graphics contexts on a stack """ pass def get_alpha(self): """ Return the alpha value used for blending - not supported on all backends """ return self._alpha def get_antialiased(self): "Return true if the object should try to do antialiased rendering" return self._antialiased def get_capstyle(self): """ Return the capstyle as a string in ('butt', 'round', 'projecting') """ return self._capstyle def get_clip_rectangle(self): """ Return the clip rectangle as a :class:`~matplotlib.transforms.Bbox` instance """ return self._cliprect def get_clip_path(self): """ Return the clip path in the form (path, transform), where path is a :class:`~matplotlib.path.Path` instance, and transform is an affine transform to apply to the path before clipping. """ if self._clippath is not None: return self._clippath.get_transformed_path_and_affine() return None, None def get_dashes(self): """ Return the dash information as an offset dashlist tuple. The dash list is a even size list that gives the ink on, ink off in pixels. See p107 of to PostScript `BLUEBOOK <http://www-cdf.fnal.gov/offline/PostScript/BLUEBOOK.PDF>`_ for more info. Default value is None """ return self._dashes def get_forced_alpha(self): """ Return whether the value given by get_alpha() should be used to override any other alpha-channel values. """ return self._forced_alpha def get_joinstyle(self): """ Return the line join style as one of ('miter', 'round', 'bevel') """ return self._joinstyle def get_linestyle(self, style): """ Return the linestyle: one of ('solid', 'dashed', 'dashdot', 'dotted'). """ return self._linestyle def get_linewidth(self): """ Return the line width in points as a scalar """ return self._linewidth def get_rgb(self): """ returns a tuple of three or four floats from 0-1. """ return self._rgb def get_url(self): """ returns a url if one is set, None otherwise """ return self._url def get_gid(self): """ Return the object identifier if one is set, None otherwise. """ return self._gid def get_snap(self): """ returns the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center """ return self._snap def set_alpha(self, alpha): """ Set the alpha value used for blending - not supported on all backends. If ``alpha=None`` (the default), the alpha components of the foreground and fill colors will be used to set their respective transparencies (where applicable); otherwise, ``alpha`` will override them. """ if alpha is not None: self._alpha = alpha self._forced_alpha = True else: self._alpha = 1.0 self._forced_alpha = False self.set_foreground(self._orig_color) def set_antialiased(self, b): """ True if object should be drawn with antialiased rendering """ # use 0, 1 to make life easier on extension code trying to read the gc if b: self._antialiased = 1 else: self._antialiased = 0 def set_capstyle(self, cs): """ Set the capstyle as a string in ('butt', 'round', 'projecting') """ if cs in ('butt', 'round', 'projecting'): self._capstyle = cs else: raise ValueError('Unrecognized cap style. Found %s' % cs) def set_clip_rectangle(self, rectangle): """ Set the clip rectangle with sequence (left, bottom, width, height) """ self._cliprect = rectangle def set_clip_path(self, path): """ Set the clip path and transformation. Path should be a :class:`~matplotlib.transforms.TransformedPath` instance. """ assert path is None or isinstance(path, transforms.TransformedPath) self._clippath = path def set_dashes(self, dash_offset, dash_list): """ Set the dash style for the gc. *dash_offset* is the offset (usually 0). *dash_list* specifies the on-off sequence as points. ``(None, None)`` specifies a solid line """ if dash_list is not None: dl = np.asarray(dash_list) if np.any(dl <= 0.0): raise ValueError("All values in the dash list must be positive") self._dashes = dash_offset, dash_list def set_foreground(self, fg, isRGBA=False): """ Set the foreground color. fg can be a MATLAB format string, a html hex color string, an rgb or rgba unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. If you know fg is rgba, set ``isRGBA=True`` for efficiency. """ self._orig_color = fg if self._forced_alpha: self._rgb = colors.colorConverter.to_rgba(fg, self._alpha) elif isRGBA: self._rgb = fg else: self._rgb = colors.colorConverter.to_rgba(fg) def set_graylevel(self, frac): """ Set the foreground color to be a gray level with *frac* """ self._orig_color = frac self._rgb = (frac, frac, frac, self._alpha) def set_joinstyle(self, js): """ Set the join style to be one of ('miter', 'round', 'bevel') """ if js in ('miter', 'round', 'bevel'): self._joinstyle = js else: raise ValueError('Unrecognized join style. Found %s' % js) def set_linewidth(self, w): """ Set the linewidth in points """ self._linewidth = w def set_linestyle(self, style): """ Set the linestyle to be one of ('solid', 'dashed', 'dashdot', 'dotted'). One may specify customized dash styles by providing a tuple of (offset, dash pairs). For example, the predefiend linestyles have following values.: 'dashed' : (0, (6.0, 6.0)), 'dashdot' : (0, (3.0, 5.0, 1.0, 5.0)), 'dotted' : (0, (1.0, 3.0)), """ if style in self.dashd: offset, dashes = self.dashd[style] elif isinstance(style, tuple): offset, dashes = style else: raise ValueError('Unrecognized linestyle: %s' % str(style)) self._linestyle = style self.set_dashes(offset, dashes) def set_url(self, url): """ Sets the url for links in compatible backends """ self._url = url def set_gid(self, id): """ Sets the id. """ self._gid = id def set_snap(self, snap): """ Sets the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center """ self._snap = snap def set_hatch(self, hatch): """ Sets the hatch style for filling """ self._hatch = hatch def get_hatch(self): """ Gets the current hatch style """ return self._hatch def get_hatch_path(self, density=6.0): """ Returns a Path for the current hatch. """ if self._hatch is None: return None return Path.hatch(self._hatch, density) def get_sketch_params(self): """ Returns the sketch parameters for the artist. Returns ------- sketch_params : tuple or `None` A 3-tuple with the following elements: * `scale`: The amplitude of the wiggle perpendicular to the source line. * `length`: The length of the wiggle along the line. * `randomness`: The scale factor by which the length is shrunken or expanded. May return `None` if no sketch parameters were set. """ return self._sketch def set_sketch_params(self, scale=None, length=None, randomness=None): """ Sets the the sketch parameters. Parameters ---------- scale : float, optional The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is `None`, or not provided, no sketch filter will be provided. length : float, optional The length of the wiggle along the line, in pixels (default 128.0) randomness : float, optional The scale factor by which the length is shrunken or expanded (default 16.0) """ if scale is None: self._sketch = None else: self._sketch = (scale, length or 128.0, randomness or 16.0) class TimerBase(object): ''' A base class for providing timer events, useful for things animations. Backends need to implement a few specific methods in order to use their own timing mechanisms so that the timer events are integrated into their event loops. Mandatory functions that must be implemented: * `_timer_start`: Contains backend-specific code for starting the timer * `_timer_stop`: Contains backend-specific code for stopping the timer Optional overrides: * `_timer_set_single_shot`: Code for setting the timer to single shot operating mode, if supported by the timer object. If not, the `Timer` class itself will store the flag and the `_on_timer` method should be overridden to support such behavior. * `_timer_set_interval`: Code for setting the interval on the timer, if there is a method for doing so on the timer object. * `_on_timer`: This is the internal function that any timer object should call, which will handle the task of running all callbacks that have been set. Attributes: * `interval`: The time between timer events in milliseconds. Default is 1000 ms. * `single_shot`: Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to `False`. * `callbacks`: Stores list of (func, args) tuples that will be called upon timer events. This list can be manipulated directly, or the functions `add_callback` and `remove_callback` can be used. ''' def __init__(self, interval=None, callbacks=None): #Initialize empty callbacks list and setup default settings if necssary if callbacks is None: self.callbacks = [] else: self.callbacks = callbacks[:] # Create a copy if interval is None: self._interval = 1000 else: self._interval = interval self._single = False # Default attribute for holding the GUI-specific timer object self._timer = None def __del__(self): 'Need to stop timer and possibly disconnect timer.' self._timer_stop() def start(self, interval=None): ''' Start the timer object. `interval` is optional and will be used to reset the timer interval first if provided. ''' if interval is not None: self._set_interval(interval) self._timer_start() def stop(self): ''' Stop the timer. ''' self._timer_stop() def _timer_start(self): pass def _timer_stop(self): pass def _get_interval(self): return self._interval def _set_interval(self, interval): # Force to int since none of the backends actually support fractional # milliseconds, and some error or give warnings. interval = int(interval) self._interval = interval self._timer_set_interval() interval = property(_get_interval, _set_interval) def _get_single_shot(self): return self._single def _set_single_shot(self, ss=True): self._single = ss self._timer_set_single_shot() single_shot = property(_get_single_shot, _set_single_shot) def add_callback(self, func, *args, **kwargs): ''' Register `func` to be called by timer when the event fires. Any additional arguments provided will be passed to `func`. ''' self.callbacks.append((func, args, kwargs)) def remove_callback(self, func, *args, **kwargs): ''' Remove `func` from list of callbacks. `args` and `kwargs` are optional and used to distinguish between copies of the same function registered to be called with different arguments. ''' if args or kwargs: self.callbacks.remove((func, args, kwargs)) else: funcs = [c[0] for c in self.callbacks] if func in funcs: self.callbacks.pop(funcs.index(func)) def _timer_set_interval(self): 'Used to set interval on underlying timer object.' pass def _timer_set_single_shot(self): 'Used to set single shot on underlying timer object.' pass def _on_timer(self): ''' Runs all function that have been registered as callbacks. Functions can return False (or 0) if they should not be called any more. If there are no callbacks, the timer is automatically stopped. ''' for func, args, kwargs in self.callbacks: ret = func(*args, **kwargs) # docstring above explains why we use `if ret == False` here, # instead of `if not ret`. if ret == False: self.callbacks.remove((func, args, kwargs)) if len(self.callbacks) == 0: self.stop() class Event: """ A matplotlib event. Attach additional attributes as defined in :meth:`FigureCanvasBase.mpl_connect`. The following attributes are defined and shown with their default values *name* the event name *canvas* the FigureCanvas instance generating the event *guiEvent* the GUI event that triggered the matplotlib event """ def __init__(self, name, canvas, guiEvent=None): self.name = name self.canvas = canvas self.guiEvent = guiEvent class IdleEvent(Event): """ An event triggered by the GUI backend when it is idle -- useful for passive animation """ pass class DrawEvent(Event): """ An event triggered by a draw operation on the canvas In addition to the :class:`Event` attributes, the following event attributes are defined: *renderer* the :class:`RendererBase` instance for the draw event """ def __init__(self, name, canvas, renderer): Event.__init__(self, name, canvas) self.renderer = renderer class ResizeEvent(Event): """ An event triggered by a canvas resize In addition to the :class:`Event` attributes, the following event attributes are defined: *width* width of the canvas in pixels *height* height of the canvas in pixels """ def __init__(self, name, canvas): Event.__init__(self, name, canvas) self.width, self.height = canvas.get_width_height() class CloseEvent(Event): """ An event triggered by a figure being closed In addition to the :class:`Event` attributes, the following event attributes are defined: """ def __init__(self, name, canvas, guiEvent=None): Event.__init__(self, name, canvas, guiEvent) class LocationEvent(Event): """ An event that has a screen location The following additional attributes are defined and shown with their default values. In addition to the :class:`Event` attributes, the following event attributes are defined: *x* x position - pixels from left of canvas *y* y position - pixels from bottom of canvas *inaxes* the :class:`~matplotlib.axes.Axes` instance if mouse is over axes *xdata* x coord of mouse in data coords *ydata* y coord of mouse in data coords """ x = None # x position - pixels from left of canvas y = None # y position - pixels from right of canvas inaxes = None # the Axes instance if mouse us over axes xdata = None # x coord of mouse in data coords ydata = None # y coord of mouse in data coords # the last event that was triggered before this one lastevent = None def __init__(self, name, canvas, x, y, guiEvent=None): """ *x*, *y* in figure coords, 0,0 = bottom, left """ Event.__init__(self, name, canvas, guiEvent=guiEvent) self.x = x self.y = y if x is None or y is None: # cannot check if event was in axes if no x,y info self.inaxes = None self._update_enter_leave() return # Find all axes containing the mouse if self.canvas.mouse_grabber is None: axes_list = [a for a in self.canvas.figure.get_axes() if a.in_axes(self)] else: axes_list = [self.canvas.mouse_grabber] if len(axes_list) == 0: # None found self.inaxes = None self._update_enter_leave() return elif (len(axes_list) > 1): # Overlap, get the highest zorder axes_list.sort(key=lambda x: x.zorder) self.inaxes = axes_list[-1] # Use the highest zorder else: # Just found one hit self.inaxes = axes_list[0] try: trans = self.inaxes.transData.inverted() xdata, ydata = trans.transform_point((x, y)) except ValueError: self.xdata = None self.ydata = None else: self.xdata = xdata self.ydata = ydata self._update_enter_leave() def _update_enter_leave(self): 'process the figure/axes enter leave events' if LocationEvent.lastevent is not None: last = LocationEvent.lastevent if last.inaxes != self.inaxes: # process axes enter/leave events try: if last.inaxes is not None: last.canvas.callbacks.process('axes_leave_event', last) except: pass # See ticket 2901582. # I think this is a valid exception to the rule # against catching all exceptions; if anything goes # wrong, we simply want to move on and process the # current event. if self.inaxes is not None: self.canvas.callbacks.process('axes_enter_event', self) else: # process a figure enter event if self.inaxes is not None: self.canvas.callbacks.process('axes_enter_event', self) LocationEvent.lastevent = self class MouseEvent(LocationEvent): """ A mouse event ('button_press_event', 'button_release_event', 'scroll_event', 'motion_notify_event'). In addition to the :class:`Event` and :class:`LocationEvent` attributes, the following attributes are defined: *button* button pressed None, 1, 2, 3, 'up', 'down' (up and down are used for scroll events) *key* the key depressed when the mouse event triggered (see :class:`KeyEvent`) *step* number of scroll steps (positive for 'up', negative for 'down') Example usage:: def on_press(event): print('you pressed', event.button, event.xdata, event.ydata) cid = fig.canvas.mpl_connect('button_press_event', on_press) """ x = None # x position - pixels from left of canvas y = None # y position - pixels from right of canvas button = None # button pressed None, 1, 2, 3 dblclick = None # whether or not the event is the result of a double click inaxes = None # the Axes instance if mouse us over axes xdata = None # x coord of mouse in data coords ydata = None # y coord of mouse in data coords step = None # scroll steps for scroll events def __init__(self, name, canvas, x, y, button=None, key=None, step=0, dblclick=False, guiEvent=None): """ x, y in figure coords, 0,0 = bottom, left button pressed None, 1, 2, 3, 'up', 'down' """ LocationEvent.__init__(self, name, canvas, x, y, guiEvent=guiEvent) self.button = button self.key = key self.step = step self.dblclick = dblclick def __str__(self): return ("MPL MouseEvent: xy=(%d,%d) xydata=(%s,%s) button=%s " + "dblclick=%s inaxes=%s") % (self.x, self.y, self.xdata, self.ydata, self.button, self.dblclick, self.inaxes) class PickEvent(Event): """ a pick event, fired when the user picks a location on the canvas sufficiently close to an artist. Attrs: all the :class:`Event` attributes plus *mouseevent* the :class:`MouseEvent` that generated the pick *artist* the :class:`~matplotlib.artist.Artist` picked other extra class dependent attrs -- e.g., a :class:`~matplotlib.lines.Line2D` pick may define different extra attributes than a :class:`~matplotlib.collections.PatchCollection` pick event Example usage:: line, = ax.plot(rand(100), 'o', picker=5) # 5 points tolerance def on_pick(event): thisline = event.artist xdata, ydata = thisline.get_data() ind = event.ind print('on pick line:', zip(xdata[ind], ydata[ind])) cid = fig.canvas.mpl_connect('pick_event', on_pick) """ def __init__(self, name, canvas, mouseevent, artist, guiEvent=None, **kwargs): Event.__init__(self, name, canvas, guiEvent) self.mouseevent = mouseevent self.artist = artist self.__dict__.update(kwargs) class KeyEvent(LocationEvent): """ A key event (key press, key release). Attach additional attributes as defined in :meth:`FigureCanvasBase.mpl_connect`. In addition to the :class:`Event` and :class:`LocationEvent` attributes, the following attributes are defined: *key* the key(s) pressed. Could be **None**, a single case sensitive ascii character ("g", "G", "#", etc.), a special key ("control", "shift", "f1", "up", etc.) or a combination of the above (e.g., "ctrl+alt+g", "ctrl+alt+G"). .. note:: Modifier keys will be prefixed to the pressed key and will be in the order "ctrl", "alt", "super". The exception to this rule is when the pressed key is itself a modifier key, therefore "ctrl+alt" and "alt+control" can both be valid key values. Example usage:: def on_key(event): print('you pressed', event.key, event.xdata, event.ydata) cid = fig.canvas.mpl_connect('key_press_event', on_key) """ def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None): LocationEvent.__init__(self, name, canvas, x, y, guiEvent=guiEvent) self.key = key class FigureCanvasBase(object): """ The canvas the figure renders into. Public attributes *figure* A :class:`matplotlib.figure.Figure` instance """ events = [ 'resize_event', 'draw_event', 'key_press_event', 'key_release_event', 'button_press_event', 'button_release_event', 'scroll_event', 'motion_notify_event', 'pick_event', 'idle_event', 'figure_enter_event', 'figure_leave_event', 'axes_enter_event', 'axes_leave_event', 'close_event' ] supports_blit = True fixed_dpi = None filetypes = _default_filetypes if _has_pil: # JPEG support register_backend('jpg', 'matplotlib.backends.backend_agg', 'Joint Photographic Experts Group') register_backend('jpeg', 'matplotlib.backends.backend_agg', 'Joint Photographic Experts Group') # TIFF support register_backend('tif', 'matplotlib.backends.backend_agg', 'Tagged Image File Format') register_backend('tiff', 'matplotlib.backends.backend_agg', 'Tagged Image File Format') def __init__(self, figure): figure.set_canvas(self) self.figure = figure # a dictionary from event name to a dictionary that maps cid->func self.callbacks = cbook.CallbackRegistry() self.widgetlock = widgets.LockDraw() self._button = None # the button pressed self._key = None # the key pressed self._lastx, self._lasty = None, None self.button_pick_id = self.mpl_connect('button_press_event', self.pick) self.scroll_pick_id = self.mpl_connect('scroll_event', self.pick) self.mouse_grabber = None # the axes currently grabbing mouse self.toolbar = None # NavigationToolbar2 will set me self._is_saving = False if False: ## highlight the artists that are hit self.mpl_connect('motion_notify_event', self.onHilite) ## delete the artists that are clicked on #self.mpl_disconnect(self.button_pick_id) #self.mpl_connect('button_press_event',self.onRemove) def is_saving(self): """ Returns `True` when the renderer is in the process of saving to a file, rather than rendering for an on-screen buffer. """ return self._is_saving def onRemove(self, ev): """ Mouse event processor which removes the top artist under the cursor. Connect this to the 'mouse_press_event' using:: canvas.mpl_connect('mouse_press_event',canvas.onRemove) """ def sort_artists(artists): # This depends on stable sort and artists returned # from get_children in z order. L = [(h.zorder, h) for h in artists] L.sort() return [h for zorder, h in L] # Find the top artist under the cursor under = sort_artists(self.figure.hitlist(ev)) h = None if under: h = under[-1] # Try deleting that artist, or its parent if you # can't delete the artist while h: if h.remove(): self.draw_idle() break parent = None for p in under: if h in p.get_children(): parent = p break h = parent def onHilite(self, ev): """ Mouse event processor which highlights the artists under the cursor. Connect this to the 'motion_notify_event' using:: canvas.mpl_connect('motion_notify_event',canvas.onHilite) """ if not hasattr(self, '_active'): self._active = dict() under = self.figure.hitlist(ev) enter = [a for a in under if a not in self._active] leave = [a for a in self._active if a not in under] #print "within:"," ".join([str(x) for x in under]) #print "entering:",[str(a) for a in enter] #print "leaving:",[str(a) for a in leave] # On leave restore the captured colour for a in leave: if hasattr(a, 'get_color'): a.set_color(self._active[a]) elif hasattr(a, 'get_edgecolor'): a.set_edgecolor(self._active[a][0]) a.set_facecolor(self._active[a][1]) del self._active[a] # On enter, capture the color and repaint the artist # with the highlight colour. Capturing colour has to # be done first in case the parent recolouring affects # the child. for a in enter: if hasattr(a, 'get_color'): self._active[a] = a.get_color() elif hasattr(a, 'get_edgecolor'): self._active[a] = (a.get_edgecolor(), a.get_facecolor()) else: self._active[a] = None for a in enter: if hasattr(a, 'get_color'): a.set_color('red') elif hasattr(a, 'get_edgecolor'): a.set_edgecolor('red') a.set_facecolor('lightblue') else: self._active[a] = None self.draw_idle() def pick(self, mouseevent): if not self.widgetlock.locked(): self.figure.pick(mouseevent) def blit(self, bbox=None): """ blit the canvas in bbox (default entire canvas) """ pass def resize(self, w, h): """ set the canvas size in pixels """ pass def draw_event(self, renderer): """ This method will be call all functions connected to the 'draw_event' with a :class:`DrawEvent` """ s = 'draw_event' event = DrawEvent(s, self, renderer) self.callbacks.process(s, event) def resize_event(self): """ This method will be call all functions connected to the 'resize_event' with a :class:`ResizeEvent` """ s = 'resize_event' event = ResizeEvent(s, self) self.callbacks.process(s, event) def close_event(self, guiEvent=None): """ This method will be called by all functions connected to the 'close_event' with a :class:`CloseEvent` """ s = 'close_event' try: event = CloseEvent(s, self, guiEvent=guiEvent) self.callbacks.process(s, event) except (TypeError, AttributeError): pass # Suppress the TypeError when the python session is being killed. # It may be that a better solution would be a mechanism to # disconnect all callbacks upon shutdown. # AttributeError occurs on OSX with qt4agg upon exiting # with an open window; 'callbacks' attribute no longer exists. def key_press_event(self, key, guiEvent=None): """ This method will be call all functions connected to the 'key_press_event' with a :class:`KeyEvent` """ self._key = key s = 'key_press_event' event = KeyEvent( s, self, key, self._lastx, self._lasty, guiEvent=guiEvent) self.callbacks.process(s, event) def key_release_event(self, key, guiEvent=None): """ This method will be call all functions connected to the 'key_release_event' with a :class:`KeyEvent` """ s = 'key_release_event' event = KeyEvent( s, self, key, self._lastx, self._lasty, guiEvent=guiEvent) self.callbacks.process(s, event) self._key = None def pick_event(self, mouseevent, artist, **kwargs): """ This method will be called by artists who are picked and will fire off :class:`PickEvent` callbacks registered listeners """ s = 'pick_event' event = PickEvent(s, self, mouseevent, artist, **kwargs) self.callbacks.process(s, event) def scroll_event(self, x, y, step, guiEvent=None): """ Backend derived classes should call this function on any scroll wheel event. x,y are the canvas coords: 0,0 is lower, left. button and key are as defined in MouseEvent. This method will be call all functions connected to the 'scroll_event' with a :class:`MouseEvent` instance. """ if step >= 0: self._button = 'up' else: self._button = 'down' s = 'scroll_event' mouseevent = MouseEvent(s, self, x, y, self._button, self._key, step=step, guiEvent=guiEvent) self.callbacks.process(s, mouseevent) def button_press_event(self, x, y, button, dblclick=False, guiEvent=None): """ Backend derived classes should call this function on any mouse button press. x,y are the canvas coords: 0,0 is lower, left. button and key are as defined in :class:`MouseEvent`. This method will be call all functions connected to the 'button_press_event' with a :class:`MouseEvent` instance. """ self._button = button s = 'button_press_event' mouseevent = MouseEvent(s, self, x, y, button, self._key, dblclick=dblclick, guiEvent=guiEvent) self.callbacks.process(s, mouseevent) def button_release_event(self, x, y, button, guiEvent=None): """ Backend derived classes should call this function on any mouse button release. *x* the canvas coordinates where 0=left *y* the canvas coordinates where 0=bottom *guiEvent* the native UI event that generated the mpl event This method will be call all functions connected to the 'button_release_event' with a :class:`MouseEvent` instance. """ s = 'button_release_event' event = MouseEvent(s, self, x, y, button, self._key, guiEvent=guiEvent) self.callbacks.process(s, event) self._button = None def motion_notify_event(self, x, y, guiEvent=None): """ Backend derived classes should call this function on any motion-notify-event. *x* the canvas coordinates where 0=left *y* the canvas coordinates where 0=bottom *guiEvent* the native UI event that generated the mpl event This method will be call all functions connected to the 'motion_notify_event' with a :class:`MouseEvent` instance. """ self._lastx, self._lasty = x, y s = 'motion_notify_event' event = MouseEvent(s, self, x, y, self._button, self._key, guiEvent=guiEvent) self.callbacks.process(s, event) def leave_notify_event(self, guiEvent=None): """ Backend derived classes should call this function when leaving canvas *guiEvent* the native UI event that generated the mpl event """ self.callbacks.process('figure_leave_event', LocationEvent.lastevent) LocationEvent.lastevent = None self._lastx, self._lasty = None, None def enter_notify_event(self, guiEvent=None, xy=None): """ Backend derived classes should call this function when entering canvas *guiEvent* the native UI event that generated the mpl event *xy* the coordinate location of the pointer when the canvas is entered """ if xy is not None: x, y = xy self._lastx, self._lasty = x, y event = Event('figure_enter_event', self, guiEvent) self.callbacks.process('figure_enter_event', event) def idle_event(self, guiEvent=None): """Called when GUI is idle.""" s = 'idle_event' event = IdleEvent(s, self, guiEvent=guiEvent) self.callbacks.process(s, event) def grab_mouse(self, ax): """ Set the child axes which are currently grabbing the mouse events. Usually called by the widgets themselves. It is an error to call this if the mouse is already grabbed by another axes. """ if self.mouse_grabber not in (None, ax): raise RuntimeError('two different attempted to grab mouse input') self.mouse_grabber = ax def release_mouse(self, ax): """ Release the mouse grab held by the axes, ax. Usually called by the widgets. It is ok to call this even if you ax doesn't have the mouse grab currently. """ if self.mouse_grabber is ax: self.mouse_grabber = None def draw(self, *args, **kwargs): """ Render the :class:`~matplotlib.figure.Figure` """ pass def draw_idle(self, *args, **kwargs): """ :meth:`draw` only if idle; defaults to draw but backends can overrride """ self.draw(*args, **kwargs) def draw_cursor(self, event): """ Draw a cursor in the event.axes if inaxes is not None. Use native GUI drawing for efficiency if possible """ pass def get_width_height(self): """ Return the figure width and height in points or pixels (depending on the backend), truncated to integers """ return int(self.figure.bbox.width), int(self.figure.bbox.height) @classmethod def get_supported_filetypes(cls): """Return dict of savefig file formats supported by this backend""" return cls.filetypes @classmethod def get_supported_filetypes_grouped(cls): """Return a dict of savefig file formats supported by this backend, where the keys are a file type name, such as 'Joint Photographic Experts Group', and the values are a list of filename extensions used for that filetype, such as ['jpg', 'jpeg'].""" groupings = {} for ext, name in six.iteritems(cls.filetypes): groupings.setdefault(name, []).append(ext) groupings[name].sort() return groupings def _get_output_canvas(self, format): """Return a canvas that is suitable for saving figures to a specified file format. If necessary, this function will switch to a registered backend that supports the format. """ method_name = 'print_%s' % format # check if this canvas supports the requested format if hasattr(self, method_name): return self # check if there is a default canvas for the requested format canvas_class = get_registered_canvas_class(format) if canvas_class: return self.switch_backends(canvas_class) # else report error for unsupported format formats = sorted(self.get_supported_filetypes()) raise ValueError('Format "%s" is not supported.\n' 'Supported formats: ' '%s.' % (format, ', '.join(formats))) def print_figure(self, filename, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', format=None, **kwargs): """ Render the figure to hardcopy. Set the figure patch face and edge colors. This is useful because some of the GUIs have a gray figure face color background and you'll probably want to override this on hardcopy. Arguments are: *filename* can also be a file object on image backends *orientation* only currently applies to PostScript printing. *dpi* the dots per inch to save the figure in; if None, use savefig.dpi *facecolor* the facecolor of the figure *edgecolor* the edgecolor of the figure *orientation* landscape' | 'portrait' (not supported on all backends) *format* when set, forcibly set the file format to save to *bbox_inches* Bbox in inches. Only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure. If None, use savefig.bbox *pad_inches* Amount of padding around the figure when bbox_inches is 'tight'. If None, use savefig.pad_inches *bbox_extra_artists* A list of extra artists that will be considered when the tight bbox is calculated. """ if format is None: # get format from filename, or from backend's default filetype if cbook.is_string_like(filename): format = os.path.splitext(filename)[1][1:] if format is None or format == '': format = self.get_default_filetype() if cbook.is_string_like(filename): filename = filename.rstrip('.') + '.' + format format = format.lower() # get canvas object and print method for format canvas = self._get_output_canvas(format) print_method = getattr(canvas, 'print_%s' % format) if dpi is None: dpi = rcParams['savefig.dpi'] origDPI = self.figure.dpi origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() self.figure.dpi = dpi self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) bbox_inches = kwargs.pop("bbox_inches", None) if bbox_inches is None: bbox_inches = rcParams['savefig.bbox'] if bbox_inches: # call adjust_bbox to save only the given area if bbox_inches == "tight": # when bbox_inches == "tight", it saves the figure # twice. The first save command is just to estimate # the bounding box of the figure. A stringIO object is # used as a temporary file object, but it causes a # problem for some backends (ps backend with # usetex=True) if they expect a filename, not a # file-like object. As I think it is best to change # the backend to support file-like object, i'm going # to leave it as it is. However, a better solution # than stringIO seems to be needed. -JJL #result = getattr(self, method_name) result = print_method( io.BytesIO(), dpi=dpi, facecolor=facecolor, edgecolor=edgecolor, orientation=orientation, dryrun=True, **kwargs) renderer = self.figure._cachedRenderer bbox_inches = self.figure.get_tightbbox(renderer) bbox_artists = kwargs.pop("bbox_extra_artists", None) if bbox_artists is None: bbox_artists = self.figure.get_default_bbox_extra_artists() bbox_filtered = [] for a in bbox_artists: bbox = a.get_window_extent(renderer) if a.get_clip_on(): clip_box = a.get_clip_box() if clip_box is not None: bbox = Bbox.intersection(bbox, clip_box) clip_path = a.get_clip_path() if clip_path is not None and bbox is not None: clip_path = clip_path.get_fully_transformed_path() bbox = Bbox.intersection(bbox, clip_path.get_extents()) if bbox is not None and (bbox.width != 0 or bbox.height != 0): bbox_filtered.append(bbox) if bbox_filtered: _bbox = Bbox.union(bbox_filtered) trans = Affine2D().scale(1.0 / self.figure.dpi) bbox_extra = TransformedBbox(_bbox, trans) bbox_inches = Bbox.union([bbox_inches, bbox_extra]) pad = kwargs.pop("pad_inches", None) if pad is None: pad = rcParams['savefig.pad_inches'] bbox_inches = bbox_inches.padded(pad) restore_bbox = tight_bbox.adjust_bbox(self.figure, bbox_inches, canvas.fixed_dpi) _bbox_inches_restore = (bbox_inches, restore_bbox) else: _bbox_inches_restore = None self._is_saving = True try: #result = getattr(self, method_name)( result = print_method( filename, dpi=dpi, facecolor=facecolor, edgecolor=edgecolor, orientation=orientation, bbox_inches_restore=_bbox_inches_restore, **kwargs) finally: if bbox_inches and restore_bbox: restore_bbox() self.figure.dpi = origDPI self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) self.figure.set_canvas(self) self._is_saving = False #self.figure.canvas.draw() ## seems superfluous return result @classmethod def get_default_filetype(cls): """ Get the default savefig file format as specified in rcParam ``savefig.format``. Returned string excludes period. Overridden in backends that only support a single file type. """ return rcParams['savefig.format'] def get_window_title(self): """ Get the title text of the window containing the figure. Return None if there is no window (e.g., a PS backend). """ if hasattr(self, "manager"): return self.manager.get_window_title() def set_window_title(self, title): """ Set the title text of the window containing the figure. Note that this has no effect if there is no window (e.g., a PS backend). """ if hasattr(self, "manager"): self.manager.set_window_title(title) def get_default_filename(self): """ Return a string, which includes extension, suitable for use as a default filename. """ default_filename = self.get_window_title() or 'image' default_filename = default_filename.lower().replace(' ', '_') return default_filename + '.' + self.get_default_filetype() def switch_backends(self, FigureCanvasClass): """ Instantiate an instance of FigureCanvasClass This is used for backend switching, e.g., to instantiate a FigureCanvasPS from a FigureCanvasGTK. Note, deep copying is not done, so any changes to one of the instances (e.g., setting figure size or line props), will be reflected in the other """ newCanvas = FigureCanvasClass(self.figure) newCanvas._is_saving = self._is_saving return newCanvas def mpl_connect(self, s, func): """ Connect event with string *s* to *func*. The signature of *func* is:: def func(event) where event is a :class:`matplotlib.backend_bases.Event`. The following events are recognized - 'button_press_event' - 'button_release_event' - 'draw_event' - 'key_press_event' - 'key_release_event' - 'motion_notify_event' - 'pick_event' - 'resize_event' - 'scroll_event' - 'figure_enter_event', - 'figure_leave_event', - 'axes_enter_event', - 'axes_leave_event' - 'close_event' For the location events (button and key press/release), if the mouse is over the axes, the variable ``event.inaxes`` will be set to the :class:`~matplotlib.axes.Axes` the event occurs is over, and additionally, the variables ``event.xdata`` and ``event.ydata`` will be defined. This is the mouse location in data coords. See :class:`~matplotlib.backend_bases.KeyEvent` and :class:`~matplotlib.backend_bases.MouseEvent` for more info. Return value is a connection id that can be used with :meth:`~matplotlib.backend_bases.Event.mpl_disconnect`. Example usage:: def on_press(event): print('you pressed', event.button, event.xdata, event.ydata) cid = canvas.mpl_connect('button_press_event', on_press) """ return self.callbacks.connect(s, func) def mpl_disconnect(self, cid): """ Disconnect callback id cid Example usage:: cid = canvas.mpl_connect('button_press_event', on_press) #...later canvas.mpl_disconnect(cid) """ return self.callbacks.disconnect(cid) def new_timer(self, *args, **kwargs): """ Creates a new backend-specific subclass of :class:`backend_bases.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. optional arguments: *interval* Timer interval in milliseconds *callbacks* Sequence of (func, args, kwargs) where func(*args, **kwargs) will be executed by the timer every *interval*. """ return TimerBase(*args, **kwargs) def flush_events(self): """ Flush the GUI events for the figure. Implemented only for backends with GUIs. """ raise NotImplementedError def start_event_loop(self, timeout): """ Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. This is implemented only for backends with GUIs. """ raise NotImplementedError def stop_event_loop(self): """ Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This is implemented only for backends with GUIs. """ raise NotImplementedError def start_event_loop_default(self, timeout=0): """ Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. This function provides default event loop functionality based on time.sleep that is meant to be used until event loop functions for each of the GUI backends can be written. As such, it throws a deprecated warning. Call signature:: start_event_loop_default(self,timeout=0) This call blocks until a callback function triggers stop_event_loop() or *timeout* is reached. If *timeout* is <=0, never timeout. """ str = "Using default event loop until function specific" str += " to this GUI is implemented" warnings.warn(str, mplDeprecation) if timeout <= 0: timeout = np.inf timestep = 0.01 counter = 0 self._looping = True while self._looping and counter * timestep < timeout: self.flush_events() time.sleep(timestep) counter += 1 def stop_event_loop_default(self): """ Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. Call signature:: stop_event_loop_default(self) """ self._looping = False def key_press_handler(event, canvas, toolbar=None): """ Implement the default mpl key bindings for the canvas and toolbar described at :ref:`key-event-handling` *event* a :class:`KeyEvent` instance *canvas* a :class:`FigureCanvasBase` instance *toolbar* a :class:`NavigationToolbar2` instance """ # these bindings happen whether you are over an axes or not if event.key is None: return # Load key-mappings from your matplotlibrc file. fullscreen_keys = rcParams['keymap.fullscreen'] home_keys = rcParams['keymap.home'] back_keys = rcParams['keymap.back'] forward_keys = rcParams['keymap.forward'] pan_keys = rcParams['keymap.pan'] zoom_keys = rcParams['keymap.zoom'] save_keys = rcParams['keymap.save'] quit_keys = rcParams['keymap.quit'] grid_keys = rcParams['keymap.grid'] toggle_yscale_keys = rcParams['keymap.yscale'] toggle_xscale_keys = rcParams['keymap.xscale'] all = rcParams['keymap.all_axes'] # toggle fullscreen mode (default key 'f') if event.key in fullscreen_keys: canvas.manager.full_screen_toggle() # quit the figure (defaut key 'ctrl+w') if event.key in quit_keys: Gcf.destroy_fig(canvas.figure) if toolbar is not None: # home or reset mnemonic (default key 'h', 'home' and 'r') if event.key in home_keys: toolbar.home() # forward / backward keys to enable left handed quick navigation # (default key for backward: 'left', 'backspace' and 'c') elif event.key in back_keys: toolbar.back() # (default key for forward: 'right' and 'v') elif event.key in forward_keys: toolbar.forward() # pan mnemonic (default key 'p') elif event.key in pan_keys: toolbar.pan() toolbar._set_cursor(event) # zoom mnemonic (default key 'o') elif event.key in zoom_keys: toolbar.zoom() toolbar._set_cursor(event) # saving current figure (default key 's') elif event.key in save_keys: toolbar.save_figure() if event.inaxes is None: return # these bindings require the mouse to be over an axes to trigger # switching on/off a grid in current axes (default key 'g') if event.key in grid_keys: event.inaxes.grid() canvas.draw() # toggle scaling of y-axes between 'log and 'linear' (default key 'l') elif event.key in toggle_yscale_keys: ax = event.inaxes scale = ax.get_yscale() if scale == 'log': ax.set_yscale('linear') ax.figure.canvas.draw() elif scale == 'linear': ax.set_yscale('log') ax.figure.canvas.draw() # toggle scaling of x-axes between 'log and 'linear' (default key 'k') elif event.key in toggle_xscale_keys: ax = event.inaxes scalex = ax.get_xscale() if scalex == 'log': ax.set_xscale('linear') ax.figure.canvas.draw() elif scalex == 'linear': ax.set_xscale('log') ax.figure.canvas.draw() elif (event.key.isdigit() and event.key != '0') or event.key in all: # keys in list 'all' enables all axes (default key 'a'), # otherwise if key is a number only enable this particular axes # if it was the axes, where the event was raised if not (event.key in all): n = int(event.key) - 1 for i, a in enumerate(canvas.figure.get_axes()): # consider axes, in which the event was raised # FIXME: Why only this axes? if event.x is not None and event.y is not None \ and a.in_axes(event): if event.key in all: a.set_navigate(True) else: a.set_navigate(i == n) class NonGuiException(Exception): pass class FigureManagerBase(object): """ Helper class for pyplot mode, wraps everything up into a neat bundle Public attibutes: *canvas* A :class:`FigureCanvasBase` instance *num* The figure number """ def __init__(self, canvas, num): self.canvas = canvas canvas.manager = self # store a pointer to parent self.num = num self.key_press_handler_id = self.canvas.mpl_connect('key_press_event', self.key_press) """ The returned id from connecting the default key handler via :meth:`FigureCanvasBase.mpl_connnect`. To disable default key press handling:: manager, canvas = figure.canvas.manager, figure.canvas canvas.mpl_disconnect(manager.key_press_handler_id) """ def show(self): """ For GUI backends, show the figure window and redraw. For non-GUI backends, raise an exception to be caught by :meth:`~matplotlib.figure.Figure.show`, for an optional warning. """ raise NonGuiException() def destroy(self): pass def full_screen_toggle(self): pass def resize(self, w, h): """"For gui backends, resize the window (in pixels).""" pass def key_press(self, event): """ Implement the default mpl key bindings defined at :ref:`key-event-handling` """ key_press_handler(event, self.canvas, self.canvas.toolbar) def show_popup(self, msg): """ Display message in a popup -- GUI only """ pass def get_window_title(self): """ Get the title text of the window containing the figure. Return None for non-GUI backends (e.g., a PS backend). """ return 'image' def set_window_title(self, title): """ Set the title text of the window containing the figure. Note that this has no effect for non-GUI backends (e.g., a PS backend). """ pass class Cursors: # this class is only used as a simple namespace HAND, POINTER, SELECT_REGION, MOVE = list(range(4)) cursors = Cursors() class NavigationToolbar2(object): """ Base class for the navigation cursor, version 2 backends must implement a canvas that handles connections for 'button_press_event' and 'button_release_event'. See :meth:`FigureCanvasBase.mpl_connect` for more information They must also define :meth:`save_figure` save the current figure :meth:`set_cursor` if you want the pointer icon to change :meth:`_init_toolbar` create your toolbar widget :meth:`draw_rubberband` (optional) draw the zoom to rect "rubberband" rectangle :meth:`press` (optional) whenever a mouse button is pressed, you'll be notified with the event :meth:`release` (optional) whenever a mouse button is released, you'll be notified with the event :meth:`dynamic_update` (optional) dynamically update the window while navigating :meth:`set_message` (optional) display message :meth:`set_history_buttons` (optional) you can change the history back / forward buttons to indicate disabled / enabled state. That's it, we'll do the rest! """ # list of toolitems to add to the toolbar, format is: # ( # text, # the text of the button (often not visible to users) # tooltip_text, # the tooltip shown on hover (where possible) # image_file, # name of the image for the button (without the extension) # name_of_method, # name of the method in NavigationToolbar2 to call # ) toolitems = ( ('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous view', 'back', 'back'), ('Forward', 'Forward to next view', 'forward', 'forward'), (None, None, None, None), ('Pan', 'Pan axes with left mouse, zoom with right', 'move', 'pan'), ('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'), (None, None, None, None), ('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'), ('Save', 'Save the figure', 'filesave', 'save_figure'), ) def __init__(self, canvas): self.canvas = canvas canvas.toolbar = self # a dict from axes index to a list of view limits self._views = cbook.Stack() self._positions = cbook.Stack() # stack of subplot positions self._xypress = None # the location and axis info at the time # of the press self._idPress = None self._idRelease = None self._active = None self._lastCursor = None self._init_toolbar() self._idDrag = self.canvas.mpl_connect( 'motion_notify_event', self.mouse_move) self._ids_zoom = [] self._zoom_mode = None self._button_pressed = None # determined by the button pressed # at start self.mode = '' # a mode string for the status bar self.set_history_buttons() def set_message(self, s): """Display a message on toolbar or in status bar""" pass def back(self, *args): """move back up the view lim stack""" self._views.back() self._positions.back() self.set_history_buttons() self._update_view() def dynamic_update(self): pass def draw_rubberband(self, event, x0, y0, x1, y1): """Draw a rectangle rubberband to indicate zoom limits""" pass def forward(self, *args): """Move forward in the view lim stack""" self._views.forward() self._positions.forward() self.set_history_buttons() self._update_view() def home(self, *args): """Restore the original view""" self._views.home() self._positions.home() self.set_history_buttons() self._update_view() def _init_toolbar(self): """ This is where you actually build the GUI widgets (called by __init__). The icons ``home.xpm``, ``back.xpm``, ``forward.xpm``, ``hand.xpm``, ``zoom_to_rect.xpm`` and ``filesave.xpm`` are standard across backends (there are ppm versions in CVS also). You just need to set the callbacks home : self.home back : self.back forward : self.forward hand : self.pan zoom_to_rect : self.zoom filesave : self.save_figure You only need to define the last one - the others are in the base class implementation. """ raise NotImplementedError def _set_cursor(self, event): if not event.inaxes or not self._active: if self._lastCursor != cursors.POINTER: self.set_cursor(cursors.POINTER) self._lastCursor = cursors.POINTER else: if self._active == 'ZOOM': if self._lastCursor != cursors.SELECT_REGION: self.set_cursor(cursors.SELECT_REGION) self._lastCursor = cursors.SELECT_REGION elif (self._active == 'PAN' and self._lastCursor != cursors.MOVE): self.set_cursor(cursors.MOVE) self._lastCursor = cursors.MOVE def mouse_move(self, event): self._set_cursor(event) if event.inaxes and event.inaxes.get_navigate(): try: s = event.inaxes.format_coord(event.xdata, event.ydata) except (ValueError, OverflowError): pass else: if len(self.mode): self.set_message('%s, %s' % (self.mode, s)) else: self.set_message(s) else: self.set_message(self.mode) def pan(self, *args): """Activate the pan/zoom tool. pan with left button, zoom with right""" # set the pointer icon and button press funcs to the # appropriate callbacks if self._active == 'PAN': self._active = None else: self._active = 'PAN' if self._idPress is not None: self._idPress = self.canvas.mpl_disconnect(self._idPress) self.mode = '' if self._idRelease is not None: self._idRelease = self.canvas.mpl_disconnect(self._idRelease) self.mode = '' if self._active: self._idPress = self.canvas.mpl_connect( 'button_press_event', self.press_pan) self._idRelease = self.canvas.mpl_connect( 'button_release_event', self.release_pan) self.mode = 'pan/zoom' self.canvas.widgetlock(self) else: self.canvas.widgetlock.release(self) for a in self.canvas.figure.get_axes(): a.set_navigate_mode(self._active) self.set_message(self.mode) def press(self, event): """Called whenver a mouse button is pressed.""" pass def press_pan(self, event): """the press mouse button in pan/zoom mode callback""" if event.button == 1: self._button_pressed = 1 elif event.button == 3: self._button_pressed = 3 else: self._button_pressed = None return x, y = event.x, event.y # push the current view to define home if stack is empty if self._views.empty(): self.push_current() self._xypress = [] for i, a in enumerate(self.canvas.figure.get_axes()): if (x is not None and y is not None and a.in_axes(event) and a.get_navigate() and a.can_pan()): a.start_pan(x, y, event.button) self._xypress.append((a, i)) self.canvas.mpl_disconnect(self._idDrag) self._idDrag = self.canvas.mpl_connect('motion_notify_event', self.drag_pan) self.press(event) def press_zoom(self, event): """the press mouse button in zoom to rect mode callback""" # If we're already in the middle of a zoom, pressing another # button works to "cancel" if self._ids_zoom != []: for zoom_id in self._ids_zoom: self.canvas.mpl_disconnect(zoom_id) self.release(event) self.draw() self._xypress = None self._button_pressed = None self._ids_zoom = [] return if event.button == 1: self._button_pressed = 1 elif event.button == 3: self._button_pressed = 3 else: self._button_pressed = None return x, y = event.x, event.y # push the current view to define home if stack is empty if self._views.empty(): self.push_current() self._xypress = [] for i, a in enumerate(self.canvas.figure.get_axes()): if (x is not None and y is not None and a.in_axes(event) and a.get_navigate() and a.can_zoom()): self._xypress.append((x, y, a, i, a.viewLim.frozen(), a.transData.frozen())) id1 = self.canvas.mpl_connect('motion_notify_event', self.drag_zoom) id2 = self.canvas.mpl_connect('key_press_event', self._switch_on_zoom_mode) id3 = self.canvas.mpl_connect('key_release_event', self._switch_off_zoom_mode) self._ids_zoom = id1, id2, id3 self._zoom_mode = event.key self.press(event) def _switch_on_zoom_mode(self, event): self._zoom_mode = event.key self.mouse_move(event) def _switch_off_zoom_mode(self, event): self._zoom_mode = None self.mouse_move(event) def push_current(self): """push the current view limits and position onto the stack""" lims = [] pos = [] for a in self.canvas.figure.get_axes(): xmin, xmax = a.get_xlim() ymin, ymax = a.get_ylim() lims.append((xmin, xmax, ymin, ymax)) # Store both the original and modified positions pos.append(( a.get_position(True).frozen(), a.get_position().frozen())) self._views.push(lims) self._positions.push(pos) self.set_history_buttons() def release(self, event): """this will be called whenever mouse button is released""" pass def release_pan(self, event): """the release mouse button callback in pan/zoom mode""" if self._button_pressed is None: return self.canvas.mpl_disconnect(self._idDrag) self._idDrag = self.canvas.mpl_connect( 'motion_notify_event', self.mouse_move) for a, ind in self._xypress: a.end_pan() if not self._xypress: return self._xypress = [] self._button_pressed = None self.push_current() self.release(event) self.draw() def drag_pan(self, event): """the drag callback in pan/zoom mode""" for a, ind in self._xypress: #safer to use the recorded button at the press than current button: #multiple button can get pressed during motion... a.drag_pan(self._button_pressed, event.key, event.x, event.y) self.dynamic_update() def drag_zoom(self, event): """the drag callback in zoom mode""" if self._xypress: x, y = event.x, event.y lastx, lasty, a, ind, lim, trans = self._xypress[0] # adjust x, last, y, last x1, y1, x2, y2 = a.bbox.extents x, lastx = max(min(x, lastx), x1), min(max(x, lastx), x2) y, lasty = max(min(y, lasty), y1), min(max(y, lasty), y2) if self._zoom_mode == "x": x1, y1, x2, y2 = a.bbox.extents y, lasty = y1, y2 elif self._zoom_mode == "y": x1, y1, x2, y2 = a.bbox.extents x, lastx = x1, x2 self.draw_rubberband(event, x, y, lastx, lasty) def release_zoom(self, event): """the release mouse button callback in zoom to rect mode""" for zoom_id in self._ids_zoom: self.canvas.mpl_disconnect(zoom_id) self._ids_zoom = [] if not self._xypress: return last_a = [] for cur_xypress in self._xypress: x, y = event.x, event.y lastx, lasty, a, ind, lim, trans = cur_xypress # ignore singular clicks - 5 pixels is a threshold if abs(x - lastx) < 5 or abs(y - lasty) < 5: self._xypress = None self.release(event) self.draw() return x0, y0, x1, y1 = lim.extents # zoom to rect inverse = a.transData.inverted() lastx, lasty = inverse.transform_point((lastx, lasty)) x, y = inverse.transform_point((x, y)) Xmin, Xmax = a.get_xlim() Ymin, Ymax = a.get_ylim() # detect twinx,y axes and avoid double zooming twinx, twiny = False, False if last_a: for la in last_a: if a.get_shared_x_axes().joined(a, la): twinx = True if a.get_shared_y_axes().joined(a, la): twiny = True last_a.append(a) if twinx: x0, x1 = Xmin, Xmax else: if Xmin < Xmax: if x < lastx: x0, x1 = x, lastx else: x0, x1 = lastx, x if x0 < Xmin: x0 = Xmin if x1 > Xmax: x1 = Xmax else: if x > lastx: x0, x1 = x, lastx else: x0, x1 = lastx, x if x0 > Xmin: x0 = Xmin if x1 < Xmax: x1 = Xmax if twiny: y0, y1 = Ymin, Ymax else: if Ymin < Ymax: if y < lasty: y0, y1 = y, lasty else: y0, y1 = lasty, y if y0 < Ymin: y0 = Ymin if y1 > Ymax: y1 = Ymax else: if y > lasty: y0, y1 = y, lasty else: y0, y1 = lasty, y if y0 > Ymin: y0 = Ymin if y1 < Ymax: y1 = Ymax if self._button_pressed == 1: if self._zoom_mode == "x": a.set_xlim((x0, x1)) elif self._zoom_mode == "y": a.set_ylim((y0, y1)) else: a.set_xlim((x0, x1)) a.set_ylim((y0, y1)) elif self._button_pressed == 3: if a.get_xscale() == 'log': alpha = np.log(Xmax / Xmin) / np.log(x1 / x0) rx1 = pow(Xmin / x0, alpha) * Xmin rx2 = pow(Xmax / x0, alpha) * Xmin else: alpha = (Xmax - Xmin) / (x1 - x0) rx1 = alpha * (Xmin - x0) + Xmin rx2 = alpha * (Xmax - x0) + Xmin if a.get_yscale() == 'log': alpha = np.log(Ymax / Ymin) / np.log(y1 / y0) ry1 = pow(Ymin / y0, alpha) * Ymin ry2 = pow(Ymax / y0, alpha) * Ymin else: alpha = (Ymax - Ymin) / (y1 - y0) ry1 = alpha * (Ymin - y0) + Ymin ry2 = alpha * (Ymax - y0) + Ymin if self._zoom_mode == "x": a.set_xlim((rx1, rx2)) elif self._zoom_mode == "y": a.set_ylim((ry1, ry2)) else: a.set_xlim((rx1, rx2)) a.set_ylim((ry1, ry2)) self.draw() self._xypress = None self._button_pressed = None self._zoom_mode = None self.push_current() self.release(event) def draw(self): """Redraw the canvases, update the locators""" for a in self.canvas.figure.get_axes(): xaxis = getattr(a, 'xaxis', None) yaxis = getattr(a, 'yaxis', None) locators = [] if xaxis is not None: locators.append(xaxis.get_major_locator()) locators.append(xaxis.get_minor_locator()) if yaxis is not None: locators.append(yaxis.get_major_locator()) locators.append(yaxis.get_minor_locator()) for loc in locators: loc.refresh() self.canvas.draw_idle() def _update_view(self): """Update the viewlim and position from the view and position stack for each axes """ lims = self._views() if lims is None: return pos = self._positions() if pos is None: return for i, a in enumerate(self.canvas.figure.get_axes()): xmin, xmax, ymin, ymax = lims[i] a.set_xlim((xmin, xmax)) a.set_ylim((ymin, ymax)) # Restore both the original and modified positions a.set_position(pos[i][0], 'original') a.set_position(pos[i][1], 'active') self.canvas.draw_idle() def save_figure(self, *args): """Save the current figure""" raise NotImplementedError def set_cursor(self, cursor): """ Set the current cursor to one of the :class:`Cursors` enums values """ pass def update(self): """Reset the axes stack""" self._views.clear() self._positions.clear() self.set_history_buttons() def zoom(self, *args): """Activate zoom to rect mode""" if self._active == 'ZOOM': self._active = None else: self._active = 'ZOOM' if self._idPress is not None: self._idPress = self.canvas.mpl_disconnect(self._idPress) self.mode = '' if self._idRelease is not None: self._idRelease = self.canvas.mpl_disconnect(self._idRelease) self.mode = '' if self._active: self._idPress = self.canvas.mpl_connect('button_press_event', self.press_zoom) self._idRelease = self.canvas.mpl_connect('button_release_event', self.release_zoom) self.mode = 'zoom rect' self.canvas.widgetlock(self) else: self.canvas.widgetlock.release(self) for a in self.canvas.figure.get_axes(): a.set_navigate_mode(self._active) self.set_message(self.mode) def set_history_buttons(self): """Enable or disable back/forward button""" pass
mit
costypetrisor/scikit-learn
examples/mixture/plot_gmm_sin.py
248
2747
""" ================================= Gaussian Mixture Model Sine Curve ================================= This example highlights the advantages of the Dirichlet Process: complexity control and dealing with sparse data. The dataset is formed by 100 points loosely spaced following a noisy sine curve. The fit by the GMM class, using the expectation-maximization algorithm to fit a mixture of 10 Gaussian components, finds too-small components and very little structure. The fits by the Dirichlet process, however, show that the model can either learn a global structure for the data (small alpha) or easily interpolate to finding relevant local structure (large alpha), never falling into the problems shown by the GMM class. """ import itertools import numpy as np from scipy import linalg import matplotlib.pyplot as plt import matplotlib as mpl from sklearn import mixture from sklearn.externals.six.moves import xrange # Number of samples per component n_samples = 100 # Generate random sample following a sine curve np.random.seed(0) X = np.zeros((n_samples, 2)) step = 4 * np.pi / n_samples for i in xrange(X.shape[0]): x = i * step - 6 X[i, 0] = x + np.random.normal(0, 0.1) X[i, 1] = 3 * (np.sin(x) + np.random.normal(0, .2)) color_iter = itertools.cycle(['r', 'g', 'b', 'c', 'm']) for i, (clf, title) in enumerate([ (mixture.GMM(n_components=10, covariance_type='full', n_iter=100), "Expectation-maximization"), (mixture.DPGMM(n_components=10, covariance_type='full', alpha=0.01, n_iter=100), "Dirichlet Process,alpha=0.01"), (mixture.DPGMM(n_components=10, covariance_type='diag', alpha=100., n_iter=100), "Dirichlet Process,alpha=100.")]): clf.fit(X) splot = plt.subplot(3, 1, 1 + i) Y_ = clf.predict(X) for i, (mean, covar, color) in enumerate(zip( clf.means_, clf._get_covars(), color_iter)): v, w = linalg.eigh(covar) u = w[0] / linalg.norm(w[0]) # as the DP will not use every component it has access to # unless it needs it, we shouldn't plot the redundant # components. if not np.any(Y_ == i): continue plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color) # Plot an ellipse to show the Gaussian component angle = np.arctan(u[1] / u[0]) angle = 180 * angle / np.pi # convert to degrees ell = mpl.patches.Ellipse(mean, v[0], v[1], 180 + angle, color=color) ell.set_clip_box(splot.bbox) ell.set_alpha(0.5) splot.add_artist(ell) plt.xlim(-6, 4 * np.pi - 6) plt.ylim(-5, 5) plt.title(title) plt.xticks(()) plt.yticks(()) plt.show()
bsd-3-clause
cpcloud/ibis
ibis/expr/window.py
1
15482
"""Encapsulation of SQL window clauses.""" import functools from typing import NamedTuple, Union import numpy as np import pandas as pd import ibis.common.exceptions as com import ibis.expr.operations as ops import ibis.expr.types as ir import ibis.util as util def _sequence_to_tuple(x): return tuple(x) if util.is_iterable(x) else x RowsWithMaxLookback = NamedTuple('RowsWithMaxLookback', [('rows', Union[int, np.integer]), ('max_lookback', ir.IntervalValue)] ) def _choose_non_empty_val(first, second): if isinstance(first, (int, np.integer)) and first: non_empty_value = first elif not isinstance(first, (int, np.integer)) and first is not None: non_empty_value = first else: non_empty_value = second return non_empty_value def _determine_how(preceding): offset_type = type(_get_preceding_value(preceding)) if issubclass(offset_type, (int, np.integer)): how = 'rows' elif issubclass(offset_type, ir.IntervalScalar): how = 'range' else: raise TypeError( 'Type {} is not supported for row- or range- based trailing ' 'window operations'.format(offset_type) ) return how @functools.singledispatch def _get_preceding_value(preceding): raise TypeError( "Type {} is not a valid type for 'preceding' " "parameter".format(type(preceding)) ) @_get_preceding_value.register(tuple) def _get_preceding_value_tuple(preceding): start, end = preceding if start is None: preceding_value = end else: preceding_value = start return preceding_value @_get_preceding_value.register(int) @_get_preceding_value.register(np.integer) @_get_preceding_value.register(ir.IntervalScalar) def _get_preceding_value_simple(preceding): return preceding @_get_preceding_value.register(RowsWithMaxLookback) def _get_preceding_value_mlb(preceding): preceding_value = preceding.rows if not isinstance(preceding_value, (int, np.integer)): raise TypeError("'Rows with max look-back' only supports integer " "row-based indexing.") return preceding_value class Window: """Class to encapsulate the details of a window frame. Notes ----- This class is patterned after SQL window clauses. Using None for preceding or following currently indicates unbounded. Use 0 for ``CURRENT ROW``. """ def __init__( self, group_by=None, order_by=None, preceding=None, following=None, max_lookback=None, how='rows', ): if group_by is None: group_by = [] if order_by is None: order_by = [] self._group_by = util.promote_list(group_by) self._order_by = [] for x in util.promote_list(order_by): if isinstance(x, ir.SortExpr): pass elif isinstance(x, ir.Expr): x = ops.SortKey(x).to_expr() self._order_by.append(x) if isinstance(preceding, RowsWithMaxLookback): # the offset interval is used as the 'preceding' value of a window # while 'rows' is used to adjust the window created using offset self.preceding = preceding.max_lookback self.max_lookback = preceding.rows else: self.preceding = _sequence_to_tuple(preceding) self.max_lookback = max_lookback self.following = _sequence_to_tuple(following) self.how = how self._validate_frame() def __hash__(self) -> int: return hash( ( tuple(gb.op() for gb in self._group_by), tuple(ob.op() for ob in self._order_by), self.preceding, self.following, self.how, ) ) def _validate_frame(self): preceding_tuple = has_preceding = False following_tuple = has_following = False if self.preceding is not None: preceding_tuple = isinstance(self.preceding, tuple) has_preceding = True if self.following is not None: following_tuple = isinstance(self.following, tuple) has_following = True if (preceding_tuple and has_following) or ( following_tuple and has_preceding ): raise com.IbisInputError( 'Can only specify one window side when you want an ' 'off-center window' ) elif preceding_tuple: start, end = self.preceding if end is None: raise com.IbisInputError("preceding end point cannot be None") if end < 0: raise com.IbisInputError( "preceding end point must be non-negative" ) if start is not None: if start < 0: raise com.IbisInputError( "preceding start point must be non-negative" ) if start <= end: raise com.IbisInputError( "preceding start must be greater than preceding end" ) elif following_tuple: start, end = self.following if start is None: raise com.IbisInputError( "following start point cannot be None" ) if start < 0: raise com.IbisInputError( "following start point must be non-negative" ) if end is not None: if end < 0: raise com.IbisInputError( "following end point must be non-negative" ) if start >= end: raise com.IbisInputError( "following start must be less than following end" ) else: if not isinstance(self.preceding, ir.Expr): if has_preceding and self.preceding < 0: raise com.IbisInputError( "'preceding' must be positive, got {}".format( self.preceding ) ) if not isinstance(self.following, ir.Expr): if has_following and self.following < 0: raise com.IbisInputError( "'following' must be positive, got {}".format( self.following ) ) if self.how not in {'rows', 'range'}: raise com.IbisInputError( "'how' must be 'rows' or 'range', got {}".format(self.how) ) if self.max_lookback is not None: if not isinstance( self.preceding, (ir.IntervalValue, pd.Timedelta)): raise com.IbisInputError( "'max_lookback' must be specified as an interval " "or pandas.Timedelta object" ) def bind(self, table): # Internal API, ensure that any unresolved expr references (as strings, # say) are bound to the table being windowed groups = table._resolve(self._group_by) sorts = [ops.to_sort_key(table, k) for k in self._order_by] return self._replace(group_by=groups, order_by=sorts) def combine(self, window): if self.how != window.how: raise com.IbisInputError( ( "Window types must match. " "Expecting '{}' Window, got '{}'" ).format(self.how.upper(), window.how.upper()) ) kwds = dict( preceding=_choose_non_empty_val(self.preceding, window.preceding), following=_choose_non_empty_val(self.following, window.following), max_lookback=self.max_lookback or window.max_lookback, group_by=self._group_by + window._group_by, order_by=self._order_by + window._order_by, ) return Window(**kwds) def group_by(self, expr): new_groups = self._group_by + util.promote_list(expr) return self._replace(group_by=new_groups) def _replace(self, **kwds): new_kwds = dict( group_by=kwds.get('group_by', self._group_by), order_by=kwds.get('order_by', self._order_by), preceding=kwds.get('preceding', self.preceding), following=kwds.get('following', self.following), max_lookback=kwds.get('max_lookback', self.max_lookback), how=kwds.get('how', self.how), ) return Window(**new_kwds) def order_by(self, expr): new_sorts = self._order_by + util.promote_list(expr) return self._replace(order_by=new_sorts) def equals(self, other, cache=None): if cache is None: cache = {} if self is other: cache[self, other] = True return True if not isinstance(other, Window): cache[self, other] = False return False try: return cache[self, other] except KeyError: pass if len(self._group_by) != len(other._group_by) or not ops.all_equal( self._group_by, other._group_by, cache=cache ): cache[self, other] = False return False if len(self._order_by) != len(other._order_by) or not ops.all_equal( self._order_by, other._order_by, cache=cache ): cache[self, other] = False return False equal = ops.all_equal( self.preceding, other.preceding, cache=cache ) and ops.all_equal( self.following, other.following, cache=cache ) and ops.all_equal( self.max_lookback, other.max_lookback, cache=cache ) cache[self, other] = equal return equal def rows_with_max_lookback(rows, max_lookback): """Create a bound preceding value for use with trailing window functions""" return RowsWithMaxLookback(rows, max_lookback) def window(preceding=None, following=None, group_by=None, order_by=None): """Create a window clause for use with window functions. This ROW window clause aggregates adjacent rows based on differences in row number. All window frames / ranges are inclusive. Parameters ---------- preceding : int, tuple, or None, default None Specify None for unbounded, 0 to include current row tuple for off-center window following : int, tuple, or None, default None Specify None for unbounded, 0 to include current row tuple for off-center window group_by : expressions, default None Either specify here or with TableExpr.group_by order_by : expressions, default None For analytic functions requiring an ordering, specify here, or let Ibis determine the default ordering (for functions like rank) Returns ------- Window """ return Window( preceding=preceding, following=following, group_by=group_by, order_by=order_by, how='rows', ) def range_window(preceding=None, following=None, group_by=None, order_by=None): """Create a range-based window clause for use with window functions. This RANGE window clause aggregates rows based upon differences in the value of the order-by expression. All window frames / ranges are inclusive. Parameters ---------- preceding : int, tuple, or None, default None Specify None for unbounded, 0 to include current row tuple for off-center window following : int, tuple, or None, default None Specify None for unbounded, 0 to include current row tuple for off-center window group_by : expressions, default None Either specify here or with TableExpr.group_by order_by : expressions, default None For analytic functions requiring an ordering, specify here, or let Ibis determine the default ordering (for functions like rank) Returns ------- Window """ return Window( preceding=preceding, following=following, group_by=group_by, order_by=order_by, how='range', ) def cumulative_window(group_by=None, order_by=None): """Create a cumulative window for use with aggregate window functions. All window frames / ranges are inclusive. Parameters ---------- group_by : expressions, default None Either specify here or with TableExpr.group_by order_by : expressions, default None For analytic functions requiring an ordering, specify here, or let Ibis determine the default ordering (for functions like rank) Returns ------- Window """ return Window( preceding=None, following=0, group_by=group_by, order_by=order_by ) def trailing_window(preceding, group_by=None, order_by=None): """Create a trailing window for use with aggregate window functions. Parameters ---------- preceding : int, float or expression of intervals, i.e. ibis.interval(days=1) + ibis.interval(hours=5) Int indicates number of trailing rows to include; 0 includes only the current row. Interval indicates a trailing range window. group_by : expressions, default None Either specify here or with TableExpr.group_by order_by : expressions, default None For analytic functions requiring an ordering, specify here, or let Ibis determine the default ordering (for functions like rank) Returns ------- Window """ how = _determine_how(preceding) return Window( preceding=preceding, following=0, group_by=group_by, order_by=order_by, how=how ) def trailing_range_window(preceding, order_by, group_by=None): """Create a trailing time window for use with aggregate window functions. Parameters ---------- preceding : float or expression of intervals, i.e. ibis.interval(days=1) + ibis.interval(hours=5) order_by : expressions, default None For analytic functions requiring an ordering, specify here, or let Ibis determine the default ordering (for functions like rank) group_by : expressions, default None Either specify here or with TableExpr.group_by Returns ------- Window """ return Window( preceding=preceding, following=0, group_by=group_by, order_by=order_by, how='range', ) def propagate_down_window(expr, window): op = expr.op() clean_args = [] unchanged = True for arg in op.args: if isinstance(arg, ir.Expr) and not isinstance(op, ops.WindowOp): new_arg = propagate_down_window(arg, window) if isinstance(new_arg.op(), ops.AnalyticOp): new_arg = ops.WindowOp(new_arg, window).to_expr() if arg is not new_arg: unchanged = False arg = new_arg clean_args.append(arg) if unchanged: return expr else: return type(op)(*clean_args).to_expr()
apache-2.0
econpy/google-ngrams
getngrams.py
2
6725
#!/usr/bin/env python # -*- coding: utf-8 -* from ast import literal_eval from pandas import DataFrame # http://github.com/pydata/pandas import re import requests # http://github.com/kennethreitz/requests import subprocess import sys corpora = dict(eng_us_2012=17, eng_us_2009=5, eng_gb_2012=18, eng_gb_2009=6, chi_sim_2012=23, chi_sim_2009=11, eng_2012=15, eng_2009=0, eng_fiction_2012=16, eng_fiction_2009=4, eng_1m_2009=1, fre_2012=19, fre_2009=7, ger_2012=20, ger_2009=8, heb_2012=24, heb_2009=9, spa_2012=21, spa_2009=10, rus_2012=25, rus_2009=12, ita_2012=22) def getNgrams(query, corpus, startYear, endYear, smoothing, caseInsensitive): params = dict(content=query, year_start=startYear, year_end=endYear, corpus=corpora[corpus], smoothing=smoothing, case_insensitive=caseInsensitive) if params['case_insensitive'] is False: params.pop('case_insensitive') if '?' in params['content']: params['content'] = params['content'].replace('?', '*') if '@' in params['content']: params['content'] = params['content'].replace('@', '=>') req = requests.get('http://books.google.com/ngrams/graph', params=params) res = re.findall('var data = (.*?);\\n', req.text) if res: data = {qry['ngram']: qry['timeseries'] for qry in literal_eval(res[0])} df = DataFrame(data) df.insert(0, 'year', list(range(startYear, endYear + 1))) else: df = DataFrame() return req.url, params['content'], df def runQuery(argumentString): arguments = argumentString.split() query = ' '.join([arg for arg in arguments if not arg.startswith('-')]) if '?' in query: query = query.replace('?', '*') if '@' in query: query = query.replace('@', '=>') params = [arg for arg in arguments if arg.startswith('-')] corpus, startYear, endYear, smoothing = 'eng_2012', 1800, 2000, 3 printHelp, caseInsensitive, allData = False, False, False toSave, toPrint, toPlot = True, True, False # parsing the query parameters for param in params: if '-nosave' in param: toSave = False elif '-noprint' in param: toPrint = False elif '-plot' in param: toPlot = True elif '-corpus' in param: corpus = param.split('=')[1].strip() elif '-startYear' in param: startYear = int(param.split('=')[1]) elif '-endYear' in param: endYear = int(param.split('=')[1]) elif '-smoothing' in param: smoothing = int(param.split('=')[1]) elif '-caseInsensitive' in param: caseInsensitive = True elif '-alldata' in param: allData = True elif '-help' in param: printHelp = True else: print(('Did not recognize the following argument: %s' % param)) if printHelp: print('See README file.') else: if '*' in query and caseInsensitive is True: caseInsensitive = False notifyUser = True warningMessage = "*NOTE: Wildcard and case-insensitive " + \ "searches can't be combined, so the " + \ "case-insensitive option was ignored." elif '_INF' in query and caseInsensitive is True: caseInsensitive = False notifyUser = True warningMessage = "*NOTE: Inflected form and case-insensitive " + \ "searches can't be combined, so the " + \ "case-insensitive option was ignored." else: notifyUser = False url, urlquery, df = getNgrams(query, corpus, startYear, endYear, smoothing, caseInsensitive) if not allData: if caseInsensitive is True: for col in df.columns: if col.count('(All)') == 1: df[col.replace(' (All)', '')] = df.pop(col) elif col.count(':chi_') == 1 or corpus.startswith('chi_'): pass elif col.count(':ger_') == 1 or corpus.startswith('ger_'): pass elif col.count(':heb_') == 1 or corpus.startswith('heb_'): pass elif col.count('(All)') == 0 and col != 'year': if col not in urlquery.split(','): df.pop(col) if '_INF' in query: for col in df.columns: if '_INF' in col: df.pop(col) if '*' in query: for col in df.columns: if '*' in col: df.pop(col) if toPrint: print((','.join(df.columns.tolist()))) for row in df.iterrows(): try: print(('%d,' % int(row[1].values[0]) + ','.join(['%.12f' % s for s in row[1].values[1:]]))) except: print((','.join([str(s) for s in row[1].values]))) queries = ''.join(urlquery.replace(',', '_').split()) if '*' in queries: queries = queries.replace('*', 'WILDCARD') if caseInsensitive is True: word_case = 'caseInsensitive' else: word_case = 'caseSensitive' filename = '%s-%s-%d-%d-%d-%s.csv' % (queries, corpus, startYear, endYear, smoothing, word_case) if toSave: for col in df.columns: if '&gt;' in col: df[col.replace('&gt;', '>')] = df.pop(col) df.to_csv(filename, index=False) print(('Data saved to %s' % filename)) if toPlot: try: subprocess.call(['python', 'xkcd.py', filename]) except: if not toSave: print(('Currently, if you want to create a plot you ' + 'must also save the data. Rerun your query, ' + 'removing the -nosave option.')) else: print(('Plotting Failed: %s' % filename)) if notifyUser: print(warningMessage) if __name__ == '__main__': argumentString = ' '.join(sys.argv[1:]) if argumentString == '': argumentString = eval(input('Enter query (or -help):')) else: try: runQuery(argumentString) except: print('An error occurred.')
mit
gregreen/legacypipe
py/legacypipe/write_initial_catalog.py
1
3639
from __future__ import print_function if __name__ == '__main__': import matplotlib matplotlib.use('Agg') import numpy as np from common import * from tractor import * if __name__ == '__main__': import optparse parser = optparse.OptionParser() parser.add_option('-b', '--brick', type=int, help='Brick ID to run: default %default', default=377306) parser.add_option('-s', '--sed-matched', action='store_true', default=False, help='Run SED-matched filter?') parser.add_option('--bands', default='grz', help='Bands to retrieve') parser.add_option('-o', '--output', help='Output filename for catalog', default='initial-cat.fits') parser.add_option('--threads', type=int, help='Run multi-threaded') parser.add_option('-W', type=int, default=3600, help='Target image width (default %default)') parser.add_option('-H', type=int, default=3600, help='Target image height (default %default)') if not (('BOSS_PHOTOOBJ' in os.environ) and ('PHOTO_RESOLVE' in os.environ)): print('''$BOSS_PHOTOOBJ and $PHOTO_RESOLVE not set -- on NERSC, you can do: export BOSS_PHOTOOBJ=/project/projectdirs/cosmo/data/sdss/pre13/eboss/photoObj.v5b export PHOTO_RESOLVE=/project/projectdirs/cosmo/data/sdss/pre13/eboss/resolve/2013-07-29 To read SDSS files from the local filesystem rather than downloading them. ''') opt,args = parser.parse_args() brickid = opt.brick bands = opt.bands if opt.threads and opt.threads > 1: from astrometry.util.multiproc import multiproc mp = multiproc(opt.threads) else: mp = multiproc() ps = None plots = False decals = Decals() brick = decals.get_brick(brickid) print('Chosen brick:') brick.about() targetwcs = wcs_for_brick(brick, W=opt.W, H=opt.H) W,H = targetwcs.get_width(), targetwcs.get_height() # Read SDSS sources cat,T = get_sdss_sources(bands, targetwcs) if opt.sed_matched: # Read images tims = decals.tims_touching_wcs(targetwcs, mp, mock_psf=True, bands=bands) print('Rendering detection maps...') detmaps, detivs = detection_maps(tims, targetwcs, bands, mp) SEDs = sed_matched_filters(bands) Tnew,newcat,nil = run_sed_matched_filters(SEDs, bands, detmaps, detivs, (T.itx,T.ity), targetwcs) T = merge_tables([T,Tnew], columns='fillzero') cat.extend(newcat) from desi_common import prepare_fits_catalog TT = T.copy() for k in ['itx','ity','index']: TT.delete_column(k) for col in TT.get_columns(): if not col in ['tx', 'ty', 'blob']: TT.rename(col, 'sdss_%s' % col) TT.brickid = np.zeros(len(TT), np.int32) + brickid TT.objid = np.arange(len(TT)).astype(np.int32) invvars = None hdr = None fs = None cat.thawAllRecursive() T2,hdr = prepare_fits_catalog(cat, invvars, TT, hdr, bands, fs) # Unpack shape columns T2.shapeExp_r = T2.shapeExp[:,0] T2.shapeExp_e1 = T2.shapeExp[:,1] T2.shapeExp_e2 = T2.shapeExp[:,2] T2.shapeDev_r = T2.shapeExp[:,0] T2.shapeDev_e1 = T2.shapeExp[:,1] T2.shapeDev_e2 = T2.shapeExp[:,2] T2.shapeExp_r_ivar = T2.shapeExp_ivar[:,0] T2.shapeExp_e1_ivar = T2.shapeExp_ivar[:,1] T2.shapeExp_e2_ivar = T2.shapeExp_ivar[:,2] T2.shapeDev_r_ivar = T2.shapeExp_ivar[:,0] T2.shapeDev_e1_ivar = T2.shapeExp_ivar[:,1] T2.shapeDev_e2_ivar = T2.shapeExp_ivar[:,2] T2.writeto(opt.output) print('Wrote', opt.output)
gpl-2.0
SuLab/scheduled-bots
scheduled_bots/phenotypes/mitodb_bot.py
1
6364
import argparse import json import os from datetime import datetime from itertools import groupby from time import gmtime, strftime, strptime import pandas as pd from tqdm import tqdm from scheduled_bots import PROPS, ITEMS from wikidataintegrator import wdi_core, wdi_helpers, wdi_login from wikidataintegrator.ref_handlers import update_retrieved_if_new_multiple_refs from wikidataintegrator.wdi_helpers import PublicationHelper from wikidataintegrator.wdi_helpers import try_write __metadata__ = { 'name': 'MitoBot', 'maintainer': 'GSS', 'tags': ['disease', 'phenotype'], 'properties': [PROPS['symptoms']] } try: from scheduled_bots.local import WDUSER, WDPASS except ImportError: if "WDUSER" in os.environ and "WDPASS" in os.environ: WDUSER = os.environ['WDUSER'] WDPASS = os.environ['WDPASS'] else: raise ValueError("WDUSER and WDPASS must be specified in local.py or as environment variables") class MitoBot: def __init__(self, records, login, write=True, run_one=False): """ # records is a list of dicts that look like: {'Added on(yyyy-mm-dd)': '2011-10-27', 'Organ system': 'nervous', 'Percent affected': '100 %', 'Pubmed id': 19696032, 'Symptom/sign': 'ataxia', 'disease': 606002, 'hpo': 'HP:0001251'} """ self.records = records self.login = login self.write = write self.run_one = run_one self.core_props = set() self.append_props = [PROPS['symptoms']] self.item_engine = self.make_item_engine() def make_item_engine(self): append_props = self.append_props core_props = self.core_props class SubCls(wdi_core.WDItemEngine): def __init__(self, *args, **kwargs): kwargs['fast_run'] = False kwargs['ref_handler'] = update_retrieved_if_new_multiple_refs kwargs['core_props'] = core_props kwargs['append_value'] = append_props super(SubCls, self).__init__(*args, **kwargs) return SubCls @staticmethod def create_reference(omim, pmid, login=None): """ Reference is: retrieved: date stated in: links to pmid items optional reference URL """ # ref = [wdi_core.WDItemID(ITEMS['MitoDB'], PROPS['curator'], is_reference=True)] t = strftime("+%Y-%m-%dT00:00:00Z", gmtime()) ref.append(wdi_core.WDTime(t, prop_nr=PROPS['retrieved'], is_reference=True)) pmid_qid, _, success = PublicationHelper(ext_id=pmid, id_type='pmid', source="europepmc").get_or_create(login) if success is True: ref.append(wdi_core.WDItemID(pmid_qid, PROPS['stated in'], is_reference=True)) ref_url = "http://mitodb.com/symptoms.php?oid={}&symptoms=Show" ref.append(wdi_core.WDUrl(ref_url.format(omim), PROPS['reference URL'], is_reference=True)) return ref @staticmethod def create_qualifier(incidence): q = [] if incidence: q.append(wdi_core.WDQuantity(incidence, PROPS['incidence'], is_qualifier=True, unit="http://www.wikidata.org/entity/" + ITEMS['percentage'])) pass return q def run_one_disease(self, disease_qid, records): ss = [] for record in records: incidence = float(record['Percent affected'][:-2]) pmid = record['Pubmed id'] phenotype_qid = record['phenotype_qid'] omim_id = record['disease'] refs = [self.create_reference(omim_id, pmid=pmid, login=self.login)] qual = self.create_qualifier(incidence) s = wdi_core.WDItemID(phenotype_qid, PROPS['symptoms'], references=refs, qualifiers=qual) ss.append(s) item = self.item_engine(wd_item_id=disease_qid, data=ss) assert not item.create_new_item try_write(item, record_id=disease_qid, record_prop=PROPS['symptoms'], edit_summary="Add phenotype from mitodb", login=self.login, write=self.write) def run(self): if self.run_one: d = [x for x in self.records if x['disease_qid'] == self.run_one] if d: print(d[0]) self.run_one_disease(d[0]['disease_qid'], d) else: raise ValueError("{} not found".format(self.run_one)) return None self.records = sorted(self.records, key=lambda x: x['disease_qid']) record_group = groupby(self.records, key=lambda x: x['disease_qid']) for disease_qid, sub_records in tqdm(record_group): self.run_one_disease(disease_qid, sub_records) def main(write=True, run_one=None): omim_qid = wdi_helpers.id_mapper(PROPS['OMIM ID'], prefer_exact_match=True, return_as_set=True) omim_qid = {k: list(v)[0] for k, v in omim_qid.items() if len(v) == 1} hpo_qid = wdi_helpers.id_mapper(PROPS['Human Phenotype Ontology ID'], prefer_exact_match=True, return_as_set=True) hpo_qid = {k: list(v)[0] for k, v in hpo_qid.items() if len(v) == 1} df = pd.read_csv("mitodb.csv", dtype=str) df['disease_qid'] = df.disease.map(omim_qid.get) df['phenotype_qid'] = df.hpo.map(hpo_qid.get) df.dropna(subset=['disease_qid', 'phenotype_qid'], inplace=True) records = df.to_dict("records") login = wdi_login.WDLogin(user=WDUSER, pwd=WDPASS) bot = MitoBot(records, login, write=write, run_one=run_one) bot.run() if __name__ == "__main__": parser = argparse.ArgumentParser(description='run mitodb phenotype bot') parser.add_argument('--dummy', help='do not actually do write', action='store_true') parser.add_argument('--run-one', help='run one disease, by qid') args = parser.parse_args() log_dir = "./logs" run_id = datetime.now().strftime('%Y%m%d_%H:%M') __metadata__['run_id'] = run_id log_name = '{}-{}.log'.format(__metadata__['name'], run_id) if wdi_core.WDItemEngine.logger is not None: wdi_core.WDItemEngine.logger.handles = [] wdi_core.WDItemEngine.setup_logging(log_dir=log_dir, log_name=log_name, header=json.dumps(__metadata__), logger_name='mitodb') main(write=not args.dummy, run_one=args.run_one)
mit
pbreach/pysd
tests/unit_test_utils.py
2
7923
from unittest import TestCase import xarray as xr import pandas as pd from . import test_utils import doctest class TestUtils(TestCase): def test_get_return_elements_subscirpts(self): from pysd.utils import get_return_elements self.assertEqual( get_return_elements(["Inflow A[Entry 1,Column 1]", "Inflow A[Entry 1,Column 2]"], {'Inflow A': 'inflow_a'}, {'Dim1': ['Entry 1', 'Entry 2'], 'Dim2': ['Column 1', 'Column 2']}), (['inflow_a'], {'Inflow A[Entry 1,Column 1]': ('inflow_a', {'Dim1': ['Entry 1'], 'Dim2': ['Column 1']}), 'Inflow A[Entry 1,Column 2]': ('inflow_a', {'Dim1': ['Entry 1'], 'Dim2': ['Column 2']})} ) ) def test_get_return_elements_realnames(self): from pysd.utils import get_return_elements self.assertEqual( get_return_elements(["Inflow A", "Inflow B"], subscript_dict={'Dim1': ['Entry 1', 'Entry 2'], 'Dim2': ['Column 1', 'Column 2']}, namespace={'Inflow A': 'inflow_a', 'Inflow B': 'inflow_b'}), (['inflow_a', 'inflow_b'], {'Inflow A': ('inflow_a', {}), 'Inflow B': ('inflow_b', {})} ) ) def test_get_return_elements_pysafe_names(self): from pysd.utils import get_return_elements self.assertEqual( get_return_elements(["inflow_a", "inflow_b"], subscript_dict={'Dim1': ['Entry 1', 'Entry 2'], 'Dim2': ['Column 1', 'Column 2']}, namespace={'Inflow A': 'inflow_a', 'Inflow B': 'inflow_b'}), (['inflow_a', 'inflow_b'], {'inflow_a': ('inflow_a', {}), 'inflow_b': ('inflow_b', {})} ) ) def test_make_flat_df(self): from pysd.utils import make_flat_df frames = [{'elem1': xr.DataArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}, dims=['Dim1', 'Dim2']), 'elem2': xr.DataArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}, dims=['Dim1', 'Dim2'])}, {'elem1': xr.DataArray([[2, 4, 6], [8, 10, 12], [14, 16, 19]], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}, dims=['Dim1', 'Dim2']), 'elem2': xr.DataArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}, dims=['Dim1', 'Dim2'])}] return_addresses = {'Elem1[B,F]': ('elem1', {'Dim1': ['B'], 'Dim2': ['F']})} df = pd.DataFrame([{'Elem1[B,F]': 6}, {'Elem1[B,F]': 12}]) resultdf = make_flat_df(frames, return_addresses) test_utils.assert_frames_close(resultdf, df, rtol=.01) def test_visit_addresses(self): from pysd.utils import visit_addresses frame = {'elem1': xr.DataArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}, dims=['Dim1', 'Dim2']), 'elem2': xr.DataArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}, dims=['Dim1', 'Dim2'])} return_addresses = {'Elem1[B,F]': ('elem1', {'Dim1': ['B'], 'Dim2': ['F']})} self.assertEqual(visit_addresses(frame, return_addresses), {'Elem1[B,F]': 6}) def test_visit_addresses_nosubs(self): from pysd.utils import visit_addresses frame = {'elem1': 25, 'elem2': 13} return_addresses = {'Elem1': ('elem1', {}), 'Elem2': ('elem2', {})} self.assertEqual(visit_addresses(frame, return_addresses), {'Elem1': 25, 'Elem2': 13}) def test_visit_addresses_return_array(self): """ There could be cases where we want to return a whole section of an array - ie, by passing in only part of the simulation dictionary. in this case, we can't force to float...""" from pysd.utils import visit_addresses frame = {'elem1': xr.DataArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}, dims=['Dim1', 'Dim2']), 'elem2': xr.DataArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}, dims=['Dim1', 'Dim2'])} return_addresses = {'Elem1[A, Dim2]': ('elem1', {'Dim1': ['A'], 'Dim2': ['D', 'E', 'F']})} actual = visit_addresses(frame, return_addresses) expected = {'Elem1[A, Dim2]': xr.DataArray([[1, 2, 3]], {'Dim1': ['A'], 'Dim2': ['D', 'E', 'F']}, dims=['Dim1', 'Dim2']), } self.assertIsInstance(list(actual.values())[0], xr.DataArray) self.assertEqual(actual['Elem1[A, Dim2]'].shape, expected['Elem1[A, Dim2]'].shape) # Todo: test that the values are equal def test_make_coord_dict(self): from pysd.utils import make_coord_dict self.assertEqual(make_coord_dict(['Dim1', 'D'], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}, terse=True), {'Dim2': ['D']}) self.assertEqual(make_coord_dict(['Dim1', 'D'], {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D', 'E', 'F']}, terse=False), {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D']}) def test_find_subscript_name(self): from pysd.utils import find_subscript_name self.assertEqual(find_subscript_name({'Dim1': ['A', 'B'], 'Dim2': ['C', 'D', 'E'], 'Dim3': ['F', 'G', 'H', 'I']}, 'D'), 'Dim2') self.assertEqual(find_subscript_name({'Dim1': ['A', 'B'], 'Dim2': ['C', 'D', 'E'], 'Dim3': ['F', 'G', 'H', 'I']}, 'Dim3'), 'Dim3') def test_doctests(self): import pysd.utils doctest.DocTestSuite(pysd.utils)
mit
mayblue9/scikit-learn
sklearn/datasets/mlcomp.py
289
3855
# Copyright (c) 2010 Olivier Grisel <olivier.grisel@ensta.org> # License: BSD 3 clause """Glue code to load http://mlcomp.org data as a scikit.learn dataset""" import os import numbers from sklearn.datasets.base import load_files def _load_document_classification(dataset_path, metadata, set_=None, **kwargs): if set_ is not None: dataset_path = os.path.join(dataset_path, set_) return load_files(dataset_path, metadata.get('description'), **kwargs) LOADERS = { 'DocumentClassification': _load_document_classification, # TODO: implement the remaining domain formats } def load_mlcomp(name_or_id, set_="raw", mlcomp_root=None, **kwargs): """Load a datasets as downloaded from http://mlcomp.org Parameters ---------- name_or_id : the integer id or the string name metadata of the MLComp dataset to load set_ : select the portion to load: 'train', 'test' or 'raw' mlcomp_root : the filesystem path to the root folder where MLComp datasets are stored, if mlcomp_root is None, the MLCOMP_DATASETS_HOME environment variable is looked up instead. **kwargs : domain specific kwargs to be passed to the dataset loader. Read more in the :ref:`User Guide <datasets>`. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'filenames', the files holding the raw to learn, 'target', the classification labels (integer index), 'target_names', the meaning of the labels, and 'DESCR', the full description of the dataset. Note on the lookup process: depending on the type of name_or_id, will choose between integer id lookup or metadata name lookup by looking at the unzipped archives and metadata file. TODO: implement zip dataset loading too """ if mlcomp_root is None: try: mlcomp_root = os.environ['MLCOMP_DATASETS_HOME'] except KeyError: raise ValueError("MLCOMP_DATASETS_HOME env variable is undefined") mlcomp_root = os.path.expanduser(mlcomp_root) mlcomp_root = os.path.abspath(mlcomp_root) mlcomp_root = os.path.normpath(mlcomp_root) if not os.path.exists(mlcomp_root): raise ValueError("Could not find folder: " + mlcomp_root) # dataset lookup if isinstance(name_or_id, numbers.Integral): # id lookup dataset_path = os.path.join(mlcomp_root, str(name_or_id)) else: # assume name based lookup dataset_path = None expected_name_line = "name: " + name_or_id for dataset in os.listdir(mlcomp_root): metadata_file = os.path.join(mlcomp_root, dataset, 'metadata') if not os.path.exists(metadata_file): continue with open(metadata_file) as f: for line in f: if line.strip() == expected_name_line: dataset_path = os.path.join(mlcomp_root, dataset) break if dataset_path is None: raise ValueError("Could not find dataset with metadata line: " + expected_name_line) # loading the dataset metadata metadata = dict() metadata_file = os.path.join(dataset_path, 'metadata') if not os.path.exists(metadata_file): raise ValueError(dataset_path + ' is not a valid MLComp dataset') with open(metadata_file) as f: for line in f: if ":" in line: key, value = line.split(":", 1) metadata[key.strip()] = value.strip() format = metadata.get('format', 'unknow') loader = LOADERS.get(format) if loader is None: raise ValueError("No loader implemented for format: " + format) return loader(dataset_path, metadata, set_=set_, **kwargs)
bsd-3-clause
dpshelio/sunpy
examples/plotting/simple_differential_rotation.py
1
3061
""" ============================ Simple Differential Rotation ============================ The Sun is known to rotate differentially, meaning that the rotation rate near the poles (rotation period of approximately 35 days) is not the same as the rotation rate near the equator (rotation period of approximately 25 days). This is possible because the Sun is not a solid body. Though it is still poorly understood, it is fairly well measured and must be taken into account when comparing observations of features on the Sun over time. A good review can be found in Beck 1999 Solar Physics 191, 47–70. This example illustrates solar differential rotation. """ # sphinx_gallery_thumbnail_number = 2 import numpy as np import matplotlib.pyplot as plt import astropy.units as u from astropy.coordinates import SkyCoord from astropy.time import TimeDelta import sunpy.map import sunpy.data.sample from sunpy.physics.differential_rotation import diff_rot, solar_rotate_coordinate ############################################################################## # Next lets explore solar differential rotation by replicating Figure 1 # in Beck 1999 latitudes = u.Quantity(np.arange(0, 90, 1), 'deg') dt = 1 * u.day rotation_rate = [diff_rot(dt, this_lat) / dt for this_lat in latitudes] rotation_period = [360 * u.deg / this_rate for this_rate in rotation_rate] fig = plt.figure() plt.plot(np.sin(latitudes), [this_period.value for this_period in rotation_period]) plt.ylim(38, 24) plt.ylabel('Rotation Period [{0}]'.format(rotation_period[0].unit)) plt.xlabel('Sin(Latitude)') plt.title('Solar Differential Rotation Rate') ############################################################################## # Next let's show how to this looks like on the Sun. # Load in an AIA map: aia_map = sunpy.map.Map(sunpy.data.sample.AIA_171_IMAGE) ############################################################################## # Let's define our starting coordinates hpc_y = u.Quantity(np.arange(-700, 800, 100), u.arcsec) hpc_x = np.zeros_like(hpc_y) ############################################################################## # Let's define how many days in the future we want to rotate to dt = TimeDelta(4*u.day) future_date = aia_map.date + dt ############################################################################## # Now let's plot the original and rotated positions on the AIA map. fig = plt.figure() ax = plt.subplot(projection=aia_map) aia_map.plot() ax.set_title('The effect of {0} days of differential rotation'.format(dt.to(u.day).value)) aia_map.draw_grid() for this_hpc_x, this_hpc_y in zip(hpc_x, hpc_y): start_coord = SkyCoord(this_hpc_x, this_hpc_y, frame=aia_map.coordinate_frame) rotated_coord = solar_rotate_coordinate(start_coord, time=future_date) coord = SkyCoord([start_coord.Tx, rotated_coord.Tx], [start_coord.Ty, rotated_coord.Ty], frame=aia_map.coordinate_frame) ax.plot_coord(coord, 'o-') plt.ylim(0, aia_map.data.shape[1]) plt.xlim(0, aia_map.data.shape[0]) plt.show()
bsd-2-clause
karstenw/nodebox-pyobjc
examples/Extended Application/matplotlib/examples/api/histogram_path.py
1
2441
""" ======================================================== Building histograms using Rectangles and PolyCollections ======================================================== This example shows how to use a path patch to draw a bunch of rectangles. The technique of using lots of Rectangle instances, or the faster method of using PolyCollections, were implemented before we had proper paths with moveto/lineto, closepoly etc in mpl. Now that we have them, we can draw collections of regularly shaped objects with homogeneous properties more efficiently with a PathCollection. This example makes a histogram -- its more work to set up the vertex arrays at the outset, but it should be much faster for large numbers of objects """ import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.path as path # nodebox section if __name__ == '__builtin__': # were in nodebox import os import tempfile W = 800 inset = 20 size(W, 600) plt.cla() plt.clf() plt.close('all') def tempimage(): fob = tempfile.NamedTemporaryFile(mode='w+b', suffix='.png', delete=False) fname = fob.name fob.close() return fname imgx = 20 imgy = 0 def pltshow(plt, dpi=150): global imgx, imgy temppath = tempimage() plt.savefig(temppath, dpi=dpi) dx,dy = imagesize(temppath) w = min(W,dx) image(temppath,imgx,imgy,width=w) imgy = imgy + dy + 20 os.remove(temppath) size(W, HEIGHT+dy+40) else: def pltshow(mplpyplot): mplpyplot.show() # nodebox section end fig, ax = plt.subplots() # Fixing random state for reproducibility np.random.seed(19680801) # histogram our data with numpy data = np.random.randn(1000) n, bins = np.histogram(data, 50) # get the corners of the rectangles for the histogram left = np.array(bins[:-1]) right = np.array(bins[1:]) bottom = np.zeros(len(left)) top = bottom + n # we need a (numrects x numsides x 2) numpy array for the path helper # function to build a compound path XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T # get the Path object barpath = path.Path.make_compound_path_from_polys(XY) # make a patch out of it patch = patches.PathPatch(barpath) ax.add_patch(patch) # update the view limits ax.set_xlim(left[0], right[-1]) ax.set_ylim(bottom.min(), top.max()) pltshow(plt)
mit
eustislab/horton
scripts/horton-entanglement.py
1
7461
#!/usr/bin/env python # -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2015 The HORTON Development Team # # This file is part of HORTON. # # HORTON 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. # # HORTON 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 numpy as np, argparse from horton import __version__ def plot(i12ind1, i12ind2, i12val, orbinit, orbfinal, thresh, s1index, s1value): try: import matplotlib.pyplot as plt import matplotlib.lines as mlines from matplotlib.ticker import NullFormatter except ImportError: if log.do_warning: log.warn('Skipping plots because matplotlib was not found.') return norb = orbfinal-orbinit orbitals = np.arange(orbinit, orbfinal) theta = 2 * np.pi * (orbitals-orbinit)/(norb) r = 22*np.ones(norb,int)-3.00*((orbitals-orbinit)%3) plt.figure(figsize=(10,5)) ax = plt.subplot(121, polar=True) ax.grid(False) ax.set_theta_zero_location("N") ax.set_theta_direction(-1) plt.plot(theta, r, 'o', markersize=12, alpha=0.2) for i in range(len(orbitals)): plt.annotate( i+1+orbinit, xy = (theta[i], r[i]), xytext = (0, 0), textcoords = 'offset points', ha = 'center', va = 'bottom', fontsize=8, fontweight='bold', ) ax.yaxis.set_data_interval(0,22.5) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) legend = [] for ind in range(len(i12val)): if i12val[ind] >= thresh: if i12val[ind] >= 0.0001 and i12val[ind] < 0.001: plt.plot([theta[i12ind1[ind]-orbinit], theta[i12ind2[ind]-orbinit]], [r[i12ind1[ind]-orbinit], r[i12ind2[ind]-orbinit]], ':', lw=2, color='orange') if i12val[ind] >= 0.001 and i12val[ind] < 0.01: plt.plot([theta[i12ind1[ind]-orbinit], theta[i12ind2[ind]-orbinit]], [r[i12ind1[ind]-orbinit], r[i12ind2[ind]-orbinit]], '-.', lw=2, color='g') if i12val[ind] >= 0.01 and i12val[ind] < 0.1: plt.plot([theta[i12ind1[ind]-orbinit], theta[i12ind2[ind]-orbinit]], [r[i12ind1[ind]-orbinit], r[i12ind2[ind]-orbinit]], '--', lw=2, color='r') if i12val[ind] >= 0.1: plt.plot([theta[i12ind1[ind]-orbinit], theta[i12ind2[ind]-orbinit]], [r[i12ind1[ind]-orbinit], r[i12ind2[ind]-orbinit]], '-', lw=3, color='b') blue_line = mlines.Line2D([], [], color='blue', marker='', lw=3, ls='-', label='0.1') red_line = mlines.Line2D([], [], color='red', marker='', lw=2, ls='--', label='0.01') green_line = mlines.Line2D([], [], color='green', marker='', ls='-.', lw=2, label='0.001') orange_line = mlines.Line2D([], [], color='orange', marker='', ls=':', lw=2, label='0.0001') if thresh >= 0.0001 and thresh < 0.001: legend.append(blue_line) legend.append(red_line) legend.append(green_line) legend.append(orange_line) if thresh >= 0.001 and thresh < 0.01: legend.append(blue_line) legend.append(red_line) legend.append(green_line) if thresh >= 0.01 and thresh < 0.1: legend.append(blue_line) legend.append(red_line) if thresh >= 0.1: legend.append(blue_line) plt.legend(handles=legend, loc='center', fancybox=True, fontsize=10) plt.title('Mutual information') ax2 = plt.subplot(122) ax2.axis([orbinit, orbfinal, 0, 0.71]) ax2.vlines(s1index, [0], s1value, color='r', linewidth=2, linestyle='-') plt.ylabel('single-orbital entropy') plt.xlabel('Orbital index') plt.plot(s1index, s1value, 'ro', markersize=8) plt.savefig('orbital_entanglement.png', dpi=300) def read_i12_data(orbinit, orbfinal, thresh): index1 = np.array([]) index2 = np.array([]) value = np.array([]) with open("i12.dat") as f: counter = 1 for line in f: words = line.split() if len(words) != 3: raise IOError('Expecting 3 fields on each data line in i12.dat') if float(words[2]) >= thresh and int(words[0]) >= orbinit and \ int(words[1]) >= orbinit and int(words[0]) <= orbfinal and \ int(words[1]) <= orbfinal: index1 = np.append(index1, int(words[0])-1) index2 = np.append(index2, int(words[1])-1) value = np.append(value, float(words[2])) return index1, index2, value def read_s1_data(orbinit, orbfinal): index = np.array([]) value = np.array([]) with open("s1.dat") as f: for line in f: words = line.split() if len(words) != 2: raise IOError('Expecting 2 fields on each data line in s1.dat') index = np.append(index, int(words[0])) value = np.append(value, float(words[1])) if orbfinal: newind = np.where(index>=(orbinit+1)) index = index[newind] value = value[newind] newind2 = np.where(index<=orbfinal) index = index[newind2] value = value[newind2] return index, value def parse_args(): parser = argparse.ArgumentParser(prog='horton-entanglement.py', description='This script makes an orbital entanglement plot. It ' 'assumes that the files s1.dat and i12.dat are present in ' 'the current directory. These two files will be used to ' 'create the figure orbital_entanglement.png.') parser.add_argument('-V', '--version', action='version', version="%%(prog)s (HORTON version %s)" % __version__) parser.add_argument('threshold', type=float, help='Orbitals with a mutual information below this threshold will not ' 'be connected by a line.') parser.add_argument('init_index', default=1, type=int, nargs='?', help='The first orbital to be used for the plot. [default=%(default)s]') parser.add_argument('final_index', default=None, type=int, nargs='?', help='The last orbital to be used for the plot (inclusive). ' '[default=last orbital]') return parser.parse_args() def main(): args = parse_args() orbinit = args.init_index - 1 orbfinal = args.final_index # Read s1.dat and store data s1index, s1value = read_s1_data(orbinit, orbfinal) if orbfinal is None: orbfinal = len(s1index) # Read i12.dat and store data i12index1, i12index2, i12value = read_i12_data(orbinit, orbfinal, args.threshold) # Plot i12 graph plt1 = plot(i12index1, i12index2, i12value, orbinit, orbfinal, args.threshold, s1index, s1value) if __name__ == '__main__': main()
gpl-3.0

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
1
Add dataset card