repo_name
stringlengths
6
67
path
stringlengths
5
185
copies
stringlengths
1
3
size
stringlengths
4
6
content
stringlengths
1.02k
962k
license
stringclasses
15 values
iLampard/alphaware
alphaware/selector.py
1
6672
# -*- coding: utf-8 -*- import pandas as pd import numpy as np import copy from sklearn.base import (BaseEstimator, TransformerMixin) from sklearn_pandas import DataFrameMapper from xutils import py_assert from argcheck import preprocess from itertools import chain from alphaware.base import (ensure_factor_container, FactorEstimator) from alphaware.enums import (FactorType, SelectionMethod) from alphaware.const import (INDEX_SELECTOR, INDEX_FACTOR, INDEX_INDUSTRY_WEIGHT) from alphaware.utils import ensure_pd_series, top class IndustryNeutralSelector(BaseEstimator, TransformerMixin): @preprocess(industry_weight=ensure_pd_series) def __init__(self, industry_weight, prop_select=0.1, min_select_per_industry=2, reset_index=False): self.industry_weight = industry_weight self.prop_select = prop_select self.min_select_per_industry = min_select_per_industry self.score = None self.industry_code = None self.reset_index = reset_index def fit(self, X, **kwargs): try: col_score = kwargs.get('col_score', 'score') col_industry_code = kwargs.get('col_score', 'industry_code') self.score = X[col_score] self.industry_code = X[col_industry_code] except KeyError: raise KeyError('Fail to retrieve data: please either use default col names or reset them') return self def transform(self, X): """ :param X: pd.DataFrame :return: """ ret = pd.DataFrame() for name, group in X.groupby(self.industry_code.name): try: weight = self.industry_weight[name] except KeyError: continue if weight == 0: continue nb_select = int(max(len(group) * self.prop_select, min(self.min_select_per_industry, len(group)))) largest_score = top(group, n=nb_select, column=self.score.name) weight_append = pd.DataFrame({INDEX_SELECTOR.col_name: [weight / nb_select] * nb_select, self.industry_code.name: [name] * nb_select}, index=largest_score.index) ret = pd.concat([ret, pd.concat([largest_score[self.score.name], weight_append], axis=1)], axis=0) return ret.reset_index() if self.reset_index else ret class BrutalSelector(BaseEstimator, TransformerMixin): def __init__(self, nb_select=10, prop_select=0.1, reset_index=False): self.nb_select = nb_select self.prop_select = prop_select self.reset_index = reset_index def fit(self, X): return self @preprocess(X=ensure_pd_series) def transform(self, X): """ :param X: pd.Series :return: """ ret = pd.DataFrame() nb_select = self.nb_select if self.nb_select is not None else int(len(X) * self.prop_select) largest_score = top(X, n=nb_select) weight = [100.0 / nb_select] * nb_select weight_append = pd.DataFrame({INDEX_SELECTOR.col_name: weight}, index=largest_score.index) weight_append = pd.concat([largest_score, weight_append], axis=1) ret = pd.concat([ret, weight_append], axis=0) ret = pd.DataFrame(ret) return ret.reset_index() if self.reset_index else ret class Selector(FactorEstimator): def __init__(self, industry_weight=None, method=SelectionMethod.INDUSTRY_NEUTRAL, nb_select=10, prop_select=0.1, copy=True, **kwargs): super(Selector, self).__init__() self.method = method self.nb_select = nb_select self.prop_select = prop_select self.industry_weight = industry_weight self.min_select_per_industry = kwargs.get('min_select_per_industry', 2) self.copy = copy self.df_mapper = None def _build_mapper(self, factor_container): data_mapper_by_date = pd.Series() industry_code = factor_container.industry_code score = factor_container.score for date in factor_container.tiaocang_date: if self.method == SelectionMethod.INDUSTRY_NEUTRAL: py_assert(self.industry_weight is not None, ValueError, 'industry weight has not been given') industry_weight = self.industry_weight.loc[date] data_mapper = [([score.name, industry_code.name], IndustryNeutralSelector(industry_weight=industry_weight, prop_select=self.prop_select, min_select_per_industry=self.min_select_per_industry, reset_index=True))] else: data_mapper = [(score.name, BrutalSelector(nb_select=self.nb_select, prop_select=self.prop_select, reset_index=True))] data_mapper_by_date[date] = DataFrameMapper(data_mapper, input_df=True, df_out=True) return data_mapper_by_date def fit(self, factor_container, **kwargs): self.df_mapper = self._build_mapper(factor_container) return self @preprocess(factor_container=ensure_factor_container) def predict(self, factor_container): if self.copy: factor_container = copy.deepcopy(factor_container) tiaocang_date = factor_container.tiaocang_date selector_data = [self.df_mapper[date_].fit_transform(factor_container.data.loc[date_]) for date_ in tiaocang_date] date_list = [[tiaocang_date[i]] * len(selector_data[i]) for i in range(len(selector_data))] date_agg = list(chain.from_iterable(date_list)) selector_data_ = np.vstack(selector_data) selector_data_agg = np.column_stack((date_agg, selector_data_)) data_df = pd.DataFrame(selector_data_agg) data_df.columns = [INDEX_FACTOR.date_index, INDEX_FACTOR.sec_index, INDEX_FACTOR.col_score, INDEX_INDUSTRY_WEIGHT.industry_index, INDEX_SELECTOR.col_name] data_df.set_index([data_df.columns[0], data_df.columns[1]], inplace=True) return data_df
apache-2.0
ssaeger/scikit-learn
sklearn/model_selection/tests/test_validation.py
18
28537
"""Test the validation module""" from __future__ import division import sys import warnings import numpy as np from scipy.sparse import coo_matrix, csr_matrix from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raise_message from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_warns from sklearn.utils.mocking import CheckingClassifier, MockDataFrame from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.model_selection import permutation_test_score from sklearn.model_selection import KFold from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import LeaveOneOut from sklearn.model_selection import LeaveOneLabelOut from sklearn.model_selection import LeavePLabelOut from sklearn.model_selection import LabelKFold from sklearn.model_selection import LabelShuffleSplit from sklearn.model_selection import learning_curve from sklearn.model_selection import validation_curve from sklearn.model_selection._validation import _check_is_permutation from sklearn.datasets import make_regression from sklearn.datasets import load_boston from sklearn.datasets import load_iris from sklearn.metrics import explained_variance_score from sklearn.metrics import make_scorer from sklearn.metrics import precision_score from sklearn.linear_model import Ridge from sklearn.linear_model import PassiveAggressiveClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.cluster import KMeans from sklearn.preprocessing import Imputer from sklearn.pipeline import Pipeline from sklearn.externals.six.moves import cStringIO as StringIO from sklearn.base import BaseEstimator from sklearn.multiclass import OneVsRestClassifier from sklearn.datasets import make_classification from sklearn.datasets import make_multilabel_classification from test_split import MockClassifier class MockImprovingEstimator(BaseEstimator): """Dummy classifier to test the learning curve""" def __init__(self, n_max_train_sizes): self.n_max_train_sizes = n_max_train_sizes self.train_sizes = 0 self.X_subset = None def fit(self, X_subset, y_subset=None): self.X_subset = X_subset self.train_sizes = X_subset.shape[0] return self def predict(self, X): raise NotImplementedError def score(self, X=None, Y=None): # training score becomes worse (2 -> 1), test error better (0 -> 1) if self._is_training_data(X): return 2. - float(self.train_sizes) / self.n_max_train_sizes else: return float(self.train_sizes) / self.n_max_train_sizes def _is_training_data(self, X): return X is self.X_subset class MockIncrementalImprovingEstimator(MockImprovingEstimator): """Dummy classifier that provides partial_fit""" def __init__(self, n_max_train_sizes): super(MockIncrementalImprovingEstimator, self).__init__(n_max_train_sizes) self.x = None def _is_training_data(self, X): return self.x in X def partial_fit(self, X, y=None, **params): self.train_sizes += X.shape[0] self.x = X[0] class MockEstimatorWithParameter(BaseEstimator): """Dummy classifier to test the validation curve""" def __init__(self, param=0.5): self.X_subset = None self.param = param def fit(self, X_subset, y_subset): self.X_subset = X_subset self.train_sizes = X_subset.shape[0] return self def predict(self, X): raise NotImplementedError def score(self, X=None, y=None): return self.param if self._is_training_data(X) else 1 - self.param def _is_training_data(self, X): return X is self.X_subset # XXX: use 2D array, since 1D X is being detected as a single sample in # check_consistent_length X = np.ones((10, 2)) X_sparse = coo_matrix(X) y = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4]) # The number of samples per class needs to be > n_folds, for StratifiedKFold(3) y2 = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 3]) def test_cross_val_score(): clf = MockClassifier() for a in range(-10, 10): clf.a = a # Smoke test scores = cross_val_score(clf, X, y2) assert_array_equal(scores, clf.score(X, y2)) # test with multioutput y multioutput_y = np.column_stack([y2, y2[::-1]]) scores = cross_val_score(clf, X_sparse, multioutput_y) assert_array_equal(scores, clf.score(X_sparse, multioutput_y)) scores = cross_val_score(clf, X_sparse, y2) assert_array_equal(scores, clf.score(X_sparse, y2)) # test with multioutput y scores = cross_val_score(clf, X_sparse, multioutput_y) assert_array_equal(scores, clf.score(X_sparse, multioutput_y)) # test with X and y as list list_check = lambda x: isinstance(x, list) clf = CheckingClassifier(check_X=list_check) scores = cross_val_score(clf, X.tolist(), y2.tolist()) clf = CheckingClassifier(check_y=list_check) scores = cross_val_score(clf, X, y2.tolist()) assert_raises(ValueError, cross_val_score, clf, X, y2, scoring="sklearn") # test with 3d X and X_3d = X[:, :, np.newaxis] clf = MockClassifier(allow_nd=True) scores = cross_val_score(clf, X_3d, y2) clf = MockClassifier(allow_nd=False) assert_raises(ValueError, cross_val_score, clf, X_3d, y2) def test_cross_val_score_predict_labels(): # Check if ValueError (when labels is None) propagates to cross_val_score # and cross_val_predict # And also check if labels is correctly passed to the cv object X, y = make_classification(n_samples=20, n_classes=2, random_state=0) clf = SVC(kernel="linear") label_cvs = [LeaveOneLabelOut(), LeavePLabelOut(2), LabelKFold(), LabelShuffleSplit()] for cv in label_cvs: assert_raise_message(ValueError, "The labels parameter should not be None", cross_val_score, estimator=clf, X=X, y=y, cv=cv) assert_raise_message(ValueError, "The labels parameter should not be None", cross_val_predict, estimator=clf, X=X, y=y, cv=cv) def test_cross_val_score_pandas(): # check cross_val_score doesn't destroy pandas dataframe types = [(MockDataFrame, MockDataFrame)] try: from pandas import Series, DataFrame types.append((Series, DataFrame)) except ImportError: pass for TargetType, InputFeatureType in types: # X dataframe, y series # 3 fold cross val is used so we need atleast 3 samples per class X_df, y_ser = InputFeatureType(X), TargetType(y2) check_df = lambda x: isinstance(x, InputFeatureType) check_series = lambda x: isinstance(x, TargetType) clf = CheckingClassifier(check_X=check_df, check_y=check_series) cross_val_score(clf, X_df, y_ser) def test_cross_val_score_mask(): # test that cross_val_score works with boolean masks svm = SVC(kernel="linear") iris = load_iris() X, y = iris.data, iris.target kfold = KFold(5) scores_indices = cross_val_score(svm, X, y, cv=kfold) kfold = KFold(5) cv_masks = [] for train, test in kfold.split(X, y): mask_train = np.zeros(len(y), dtype=np.bool) mask_test = np.zeros(len(y), dtype=np.bool) mask_train[train] = 1 mask_test[test] = 1 cv_masks.append((train, test)) scores_masks = cross_val_score(svm, X, y, cv=cv_masks) assert_array_equal(scores_indices, scores_masks) def test_cross_val_score_precomputed(): # test for svm with precomputed kernel svm = SVC(kernel="precomputed") iris = load_iris() X, y = iris.data, iris.target linear_kernel = np.dot(X, X.T) score_precomputed = cross_val_score(svm, linear_kernel, y) svm = SVC(kernel="linear") score_linear = cross_val_score(svm, X, y) assert_array_equal(score_precomputed, score_linear) # Error raised for non-square X svm = SVC(kernel="precomputed") assert_raises(ValueError, cross_val_score, svm, X, y) # test error is raised when the precomputed kernel is not array-like # or sparse assert_raises(ValueError, cross_val_score, svm, linear_kernel.tolist(), y) def test_cross_val_score_fit_params(): clf = MockClassifier() n_samples = X.shape[0] n_classes = len(np.unique(y)) W_sparse = coo_matrix((np.array([1]), (np.array([1]), np.array([0]))), shape=(10, 1)) P_sparse = coo_matrix(np.eye(5)) DUMMY_INT = 42 DUMMY_STR = '42' DUMMY_OBJ = object() def assert_fit_params(clf): # Function to test that the values are passed correctly to the # classifier arguments for non-array type assert_equal(clf.dummy_int, DUMMY_INT) assert_equal(clf.dummy_str, DUMMY_STR) assert_equal(clf.dummy_obj, DUMMY_OBJ) fit_params = {'sample_weight': np.ones(n_samples), 'class_prior': np.ones(n_classes) / n_classes, 'sparse_sample_weight': W_sparse, 'sparse_param': P_sparse, 'dummy_int': DUMMY_INT, 'dummy_str': DUMMY_STR, 'dummy_obj': DUMMY_OBJ, 'callback': assert_fit_params} cross_val_score(clf, X, y, fit_params=fit_params) def test_cross_val_score_score_func(): clf = MockClassifier() _score_func_args = [] def score_func(y_test, y_predict): _score_func_args.append((y_test, y_predict)) return 1.0 with warnings.catch_warnings(record=True): scoring = make_scorer(score_func) score = cross_val_score(clf, X, y, scoring=scoring) assert_array_equal(score, [1.0, 1.0, 1.0]) assert len(_score_func_args) == 3 def test_cross_val_score_errors(): class BrokenEstimator: pass assert_raises(TypeError, cross_val_score, BrokenEstimator(), X) def test_cross_val_score_with_score_func_classification(): iris = load_iris() clf = SVC(kernel='linear') # Default score (should be the accuracy score) scores = cross_val_score(clf, iris.data, iris.target, cv=5) assert_array_almost_equal(scores, [0.97, 1., 0.97, 0.97, 1.], 2) # Correct classification score (aka. zero / one score) - should be the # same as the default estimator score zo_scores = cross_val_score(clf, iris.data, iris.target, scoring="accuracy", cv=5) assert_array_almost_equal(zo_scores, [0.97, 1., 0.97, 0.97, 1.], 2) # F1 score (class are balanced so f1_score should be equal to zero/one # score f1_scores = cross_val_score(clf, iris.data, iris.target, scoring="f1_weighted", cv=5) assert_array_almost_equal(f1_scores, [0.97, 1., 0.97, 0.97, 1.], 2) def test_cross_val_score_with_score_func_regression(): X, y = make_regression(n_samples=30, n_features=20, n_informative=5, random_state=0) reg = Ridge() # Default score of the Ridge regression estimator scores = cross_val_score(reg, X, y, cv=5) assert_array_almost_equal(scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2) # R2 score (aka. determination coefficient) - should be the # same as the default estimator score r2_scores = cross_val_score(reg, X, y, scoring="r2", cv=5) assert_array_almost_equal(r2_scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2) # Mean squared error; this is a loss function, so "scores" are negative mse_scores = cross_val_score(reg, X, y, cv=5, scoring="mean_squared_error") expected_mse = np.array([-763.07, -553.16, -274.38, -273.26, -1681.99]) assert_array_almost_equal(mse_scores, expected_mse, 2) # Explained variance scoring = make_scorer(explained_variance_score) ev_scores = cross_val_score(reg, X, y, cv=5, scoring=scoring) assert_array_almost_equal(ev_scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2) def test_permutation_score(): iris = load_iris() X = iris.data X_sparse = coo_matrix(X) y = iris.target svm = SVC(kernel='linear') cv = StratifiedKFold(2) score, scores, pvalue = permutation_test_score( svm, X, y, n_permutations=30, cv=cv, scoring="accuracy") assert_greater(score, 0.9) assert_almost_equal(pvalue, 0.0, 1) score_label, _, pvalue_label = permutation_test_score( svm, X, y, n_permutations=30, cv=cv, scoring="accuracy", labels=np.ones(y.size), random_state=0) assert_true(score_label == score) assert_true(pvalue_label == pvalue) # check that we obtain the same results with a sparse representation svm_sparse = SVC(kernel='linear') cv_sparse = StratifiedKFold(2) score_label, _, pvalue_label = permutation_test_score( svm_sparse, X_sparse, y, n_permutations=30, cv=cv_sparse, scoring="accuracy", labels=np.ones(y.size), random_state=0) assert_true(score_label == score) assert_true(pvalue_label == pvalue) # test with custom scoring object def custom_score(y_true, y_pred): return (((y_true == y_pred).sum() - (y_true != y_pred).sum()) / y_true.shape[0]) scorer = make_scorer(custom_score) score, _, pvalue = permutation_test_score( svm, X, y, n_permutations=100, scoring=scorer, cv=cv, random_state=0) assert_almost_equal(score, .93, 2) assert_almost_equal(pvalue, 0.01, 3) # set random y y = np.mod(np.arange(len(y)), 3) score, scores, pvalue = permutation_test_score( svm, X, y, n_permutations=30, cv=cv, scoring="accuracy") assert_less(score, 0.5) assert_greater(pvalue, 0.2) def test_permutation_test_score_allow_nans(): # Check that permutation_test_score allows input data with NaNs X = np.arange(200, dtype=np.float64).reshape(10, -1) X[2, :] = np.nan y = np.repeat([0, 1], X.shape[0] / 2) p = Pipeline([ ('imputer', Imputer(strategy='mean', missing_values='NaN')), ('classifier', MockClassifier()), ]) permutation_test_score(p, X, y, cv=5) def test_cross_val_score_allow_nans(): # Check that cross_val_score allows input data with NaNs X = np.arange(200, dtype=np.float64).reshape(10, -1) X[2, :] = np.nan y = np.repeat([0, 1], X.shape[0] / 2) p = Pipeline([ ('imputer', Imputer(strategy='mean', missing_values='NaN')), ('classifier', MockClassifier()), ]) cross_val_score(p, X, y, cv=5) def test_cross_val_score_multilabel(): X = np.array([[-3, 4], [2, 4], [3, 3], [0, 2], [-3, 1], [-2, 1], [0, 0], [-2, -1], [-1, -2], [1, -2]]) y = np.array([[1, 1], [0, 1], [0, 1], [0, 1], [1, 1], [0, 1], [1, 0], [1, 1], [1, 0], [0, 0]]) clf = KNeighborsClassifier(n_neighbors=1) scoring_micro = make_scorer(precision_score, average='micro') scoring_macro = make_scorer(precision_score, average='macro') scoring_samples = make_scorer(precision_score, average='samples') score_micro = cross_val_score(clf, X, y, scoring=scoring_micro, cv=5) score_macro = cross_val_score(clf, X, y, scoring=scoring_macro, cv=5) score_samples = cross_val_score(clf, X, y, scoring=scoring_samples, cv=5) assert_almost_equal(score_micro, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 3]) assert_almost_equal(score_macro, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 4]) assert_almost_equal(score_samples, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 4]) def test_cross_val_predict(): boston = load_boston() X, y = boston.data, boston.target cv = KFold() est = Ridge() # Naive loop (should be same as cross_val_predict): preds2 = np.zeros_like(y) for train, test in cv.split(X, y): est.fit(X[train], y[train]) preds2[test] = est.predict(X[test]) preds = cross_val_predict(est, X, y, cv=cv) assert_array_almost_equal(preds, preds2) preds = cross_val_predict(est, X, y) assert_equal(len(preds), len(y)) cv = LeaveOneOut() preds = cross_val_predict(est, X, y, cv=cv) assert_equal(len(preds), len(y)) Xsp = X.copy() Xsp *= (Xsp > np.median(Xsp)) Xsp = coo_matrix(Xsp) preds = cross_val_predict(est, Xsp, y) assert_array_almost_equal(len(preds), len(y)) preds = cross_val_predict(KMeans(), X) assert_equal(len(preds), len(y)) class BadCV(): def split(self, X, y=None, labels=None): for i in range(4): yield np.array([0, 1, 2, 3]), np.array([4, 5, 6, 7, 8]) assert_raises(ValueError, cross_val_predict, est, X, y, cv=BadCV()) def test_cross_val_predict_input_types(): iris = load_iris() X, y = iris.data, iris.target X_sparse = coo_matrix(X) multioutput_y = np.column_stack([y, y[::-1]]) clf = Ridge(fit_intercept=False, random_state=0) # 3 fold cv is used --> atleast 3 samples per class # Smoke test predictions = cross_val_predict(clf, X, y) assert_equal(predictions.shape, (150,)) # test with multioutput y predictions = cross_val_predict(clf, X_sparse, multioutput_y) assert_equal(predictions.shape, (150, 2)) predictions = cross_val_predict(clf, X_sparse, y) assert_array_equal(predictions.shape, (150,)) # test with multioutput y predictions = cross_val_predict(clf, X_sparse, multioutput_y) assert_array_equal(predictions.shape, (150, 2)) # test with X and y as list list_check = lambda x: isinstance(x, list) clf = CheckingClassifier(check_X=list_check) predictions = cross_val_predict(clf, X.tolist(), y.tolist()) clf = CheckingClassifier(check_y=list_check) predictions = cross_val_predict(clf, X, y.tolist()) # test with 3d X and X_3d = X[:, :, np.newaxis] check_3d = lambda x: x.ndim == 3 clf = CheckingClassifier(check_X=check_3d) predictions = cross_val_predict(clf, X_3d, y) assert_array_equal(predictions.shape, (150,)) def test_cross_val_predict_pandas(): # check cross_val_score doesn't destroy pandas dataframe types = [(MockDataFrame, MockDataFrame)] try: from pandas import Series, DataFrame types.append((Series, DataFrame)) except ImportError: pass for TargetType, InputFeatureType in types: # X dataframe, y series X_df, y_ser = InputFeatureType(X), TargetType(y2) check_df = lambda x: isinstance(x, InputFeatureType) check_series = lambda x: isinstance(x, TargetType) clf = CheckingClassifier(check_X=check_df, check_y=check_series) cross_val_predict(clf, X_df, y_ser) def test_cross_val_score_sparse_fit_params(): iris = load_iris() X, y = iris.data, iris.target clf = MockClassifier() fit_params = {'sparse_sample_weight': coo_matrix(np.eye(X.shape[0]))} a = cross_val_score(clf, X, y, fit_params=fit_params) assert_array_equal(a, np.ones(3)) def test_learning_curve(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(20) with warnings.catch_warnings(record=True) as w: train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=3, train_sizes=np.linspace(0.1, 1.0, 10)) if len(w) > 0: raise RuntimeError("Unexpected warning: %r" % w[0].message) assert_equal(train_scores.shape, (10, 3)) assert_equal(test_scores.shape, (10, 3)) assert_array_equal(train_sizes, np.linspace(2, 20, 10)) assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) def test_learning_curve_unsupervised(): X, _ = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(20) train_sizes, train_scores, test_scores = learning_curve( estimator, X, y=None, cv=3, train_sizes=np.linspace(0.1, 1.0, 10)) assert_array_equal(train_sizes, np.linspace(2, 20, 10)) assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) def test_learning_curve_verbose(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(20) old_stdout = sys.stdout sys.stdout = StringIO() try: train_sizes, train_scores, test_scores = \ learning_curve(estimator, X, y, cv=3, verbose=1) finally: out = sys.stdout.getvalue() sys.stdout.close() sys.stdout = old_stdout assert("[learning_curve]" in out) def test_learning_curve_incremental_learning_not_possible(): X, y = make_classification(n_samples=2, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) # The mockup does not have partial_fit() estimator = MockImprovingEstimator(1) assert_raises(ValueError, learning_curve, estimator, X, y, exploit_incremental_learning=True) def test_learning_curve_incremental_learning(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockIncrementalImprovingEstimator(20) train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=3, exploit_incremental_learning=True, train_sizes=np.linspace(0.1, 1.0, 10)) assert_array_equal(train_sizes, np.linspace(2, 20, 10)) assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) def test_learning_curve_incremental_learning_unsupervised(): X, _ = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockIncrementalImprovingEstimator(20) train_sizes, train_scores, test_scores = learning_curve( estimator, X, y=None, cv=3, exploit_incremental_learning=True, train_sizes=np.linspace(0.1, 1.0, 10)) assert_array_equal(train_sizes, np.linspace(2, 20, 10)) assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) def test_learning_curve_batch_and_incremental_learning_are_equal(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) train_sizes = np.linspace(0.2, 1.0, 5) estimator = PassiveAggressiveClassifier(n_iter=1, shuffle=False) train_sizes_inc, train_scores_inc, test_scores_inc = \ learning_curve( estimator, X, y, train_sizes=train_sizes, cv=3, exploit_incremental_learning=True) train_sizes_batch, train_scores_batch, test_scores_batch = \ learning_curve( estimator, X, y, cv=3, train_sizes=train_sizes, exploit_incremental_learning=False) assert_array_equal(train_sizes_inc, train_sizes_batch) assert_array_almost_equal(train_scores_inc.mean(axis=1), train_scores_batch.mean(axis=1)) assert_array_almost_equal(test_scores_inc.mean(axis=1), test_scores_batch.mean(axis=1)) def test_learning_curve_n_sample_range_out_of_bounds(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(20) assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, train_sizes=[0, 1]) assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, train_sizes=[0.0, 1.0]) assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, train_sizes=[0.1, 1.1]) assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, train_sizes=[0, 20]) assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, train_sizes=[1, 21]) def test_learning_curve_remove_duplicate_sample_sizes(): X, y = make_classification(n_samples=3, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(2) train_sizes, _, _ = assert_warns( RuntimeWarning, learning_curve, estimator, X, y, cv=3, train_sizes=np.linspace(0.33, 1.0, 3)) assert_array_equal(train_sizes, [1, 2]) def test_learning_curve_with_boolean_indices(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(20) cv = KFold(n_folds=3) train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=cv, train_sizes=np.linspace(0.1, 1.0, 10)) assert_array_equal(train_sizes, np.linspace(2, 20, 10)) assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) def test_validation_curve(): X, y = make_classification(n_samples=2, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) param_range = np.linspace(0, 1, 10) with warnings.catch_warnings(record=True) as w: train_scores, test_scores = validation_curve( MockEstimatorWithParameter(), X, y, param_name="param", param_range=param_range, cv=2 ) if len(w) > 0: raise RuntimeError("Unexpected warning: %r" % w[0].message) assert_array_almost_equal(train_scores.mean(axis=1), param_range) assert_array_almost_equal(test_scores.mean(axis=1), 1 - param_range) def test_check_is_permutation(): p = np.arange(100) assert_true(_check_is_permutation(p, 100)) assert_false(_check_is_permutation(np.delete(p, 23), 100)) p[0] = 23 assert_false(_check_is_permutation(p, 100)) def test_cross_val_predict_sparse_prediction(): # check that cross_val_predict gives same result for sparse and dense input X, y = make_multilabel_classification(n_classes=2, n_labels=1, allow_unlabeled=False, return_indicator=True, random_state=1) X_sparse = csr_matrix(X) y_sparse = csr_matrix(y) classif = OneVsRestClassifier(SVC(kernel='linear')) preds = cross_val_predict(classif, X, y, cv=10) preds_sparse = cross_val_predict(classif, X_sparse, y_sparse, cv=10) preds_sparse = preds_sparse.toarray() assert_array_almost_equal(preds_sparse, preds)
bsd-3-clause
xgrg/alfa
roistats/plotting.py
1
5563
def _prefit_data(y, data, covariates): adj_model = 'roi ~ %s + 1'%' + '.join(covariates) ycorr = pd.DataFrame(correct(data, adj_model), columns=[y]) del data[y] data = data.join(ycorr) log.info('Fit model used for correction: %s'%adj_model) return data def _plot_significance(data_dummies, x1, x2, groups, by, dummy_columns, covariates): import logging as log from matplotlib import pyplot as plt from statsmodels.formula.api import ols formula = 'roi ~ %s%s + 1'%(' + '.join(dummy_columns), {False:'', True: ' + %s'%' + '.join(covariates)}[len(covariates)!=0]) log.info('Used model for significance estimation: %s'%formula) fitted_model = ols(formula, data_dummies).fit() s1 = ['%s * %s_%s'%(1.0/len(groups[x1]), by, each) for each in groups[x1]] s2 = ['%s * %s_%s'%(1.0/len(groups[x2]), by, each) for each in groups[x2]] c = '%s - %s'%(' + '.join(s1), ' + '.join(s2)) log.info('Used contrast: %s'%c) T = fitted_model.t_test(c) log.info('p-value: %s'%T.pvalue) y, h, col = data_dummies['roi'].mean() + data_dummies['roi'].std() + 1e-4, 1e-5, 'k' i1 = groups.keys().index(x1) i2 = groups.keys().index(x2) plt.plot([i1, i1, i2, i2], [y, y+h, y+h, y], lw=1.5, c=col) opt = {'ha':'center', 'va':'bottom', 'color':col} if T.pvalue<0.05: opt['weight'] = 'bold' plt.text((i1+i2)*.5, y+h, '%.3f'%T.pvalue, **opt) return T.pvalue import seaborn as sns import pandas as pd import logging as log from __init__ import correct def boxplot_region(y, data, groups, by='apoe', covariates=[]): '''`y` should be a variable name, `data` is the data, `covariates` lists the various nuisance factors, `by` is the variable setting the different groups and `groups` is a dictionary that sets the various groups (i.e. boxplots). ex: {'not HO': ['NC', 'HT'], 'HO': ['HO']} NB: the group splitting must be complete (all subjects from the given dataset must be covered, otherwise drop the non-desired groups first)''' # Create a column with a group index based on `groups` col = [] for i, row in data.iterrows(): for k, group in groups.items(): if row[by] in group: col.append(k) data['_group'] = col # Build a new table `df` with only needed variables # y is renamed to roi to avoid potential issues with strange characters roi_name = y variables = {'_group', y, by} for c in covariates: variables.add(c) df = pd.DataFrame(data, columns=list(variables)).rename(columns={y:'roi'}) df = df.dropna() y = 'roi' log.info('Dependent variable: %s'%roi_name) # Create dummy variables which will be used to estimate p-values data_dummies = pd.get_dummies(df, columns=[by]) del data_dummies['_group'] dummy_columns = set(data_dummies.columns).difference(df.columns) # Correct depending variable for covariates (if any) (df is modified) if len(covariates) != 0: df = _prefit_data(y, df, covariates) # Plot for good palette = {'HO':'#ff9999', 'HT':'#ffd699','NC':'#99ccff', 'not HO':'#99ccff', 'f':'#ff9999', 'm':'#99ccff', 'apoe44':'#ff9999', 'apoe34':'#ffd699', 'apoe33':'#99ccff'}#, ax=ax) box = sns.boxplot(x='_group', y='roi', data=df, showfliers=False, palette=palette) #box = sns.violinplot(x='_group', y='roi', data=df, palette=palette) box.axes.set_yticklabels(['%.2e'%x for x in box.axes.get_yticks()]) xlabel = 'groups%s'\ %{False:'', True:' (corrected for %s)'\ %(' and '.join(covariates))}[len(covariates)!=0] box.axes.set_xlabel(xlabel, fontsize=15, weight='bold') box.axes.set_ylabel('') box.set_title(roi_name) # Estimate p-values and add them to the figure import itertools pvals, hdr = [], [] for i1, i2 in itertools.combinations(groups.keys(), 2): pval = plot_significance(data_dummies, i1, i2, groups, by, dummy_columns, covariates) pvals.append(pval) hdr.append((i1, i2)) return pvals, hdr def lm_plot(y, x, data, covariates=['gender', 'age'], hue='apoe', ylim=None, savefig=None, facecolor='white'): # Build a new table with only needed variables # y is renamed to roi to avoid potential issues with strange characters roi_name = y log.info('Dependent variable: %s'%y) variables = {x, y} if not hue is None: variables.add(hue) for c in covariates: variables.add(c) df = pd.DataFrame(data, columns=list(variables)).rename(columns={y:'roi'}) df = df.dropna() y = 'roi' if len(covariates) != 0: df = _prefit_data(y, df, covariates) # Plotting for good lm = sns.lmplot(x=x, y=y, data=df, size=6.2, hue=hue, aspect=1.35, ci=90, truncate=True, sharex=False,sharey=False) ax = lm.axes if ylim is None: ax[0,0].set_ylim([df[y].min(), df[y].max()]) else: ax[0,0].set_ylim(ylim) ax[0,0].set_xlim([df[x].min(), df[x].max()]) ax[0,0].set_yticklabels(['%.2e'%i for i in ax[0,0].get_yticks()]) ax[0,0].tick_params(labelsize=12) ax[0,0].set_ylabel('') xlabel = 'groups%s'%{False:'', True:' (corrected for %s)'\ %(' and '.join(covariates))}[len(covariates)!=0] ax[0,0].set_xlabel(xlabel, fontsize=15, weight='bold') lm.fig.suptitle(roi_name) if not savefig is None: lm.savefig(savefig, facecolor=facecolor) return df
mit
beepee14/scikit-learn
sklearn/datasets/species_distributions.py
198
7923
""" ============================= Species distribution dataset ============================= This dataset represents the geographic distribution of species. The dataset is provided by Phillips et. al. (2006). The two species are: - `"Bradypus variegatus" <http://www.iucnredlist.org/apps/redlist/details/3038/0>`_ , the Brown-throated Sloth. - `"Microryzomys minutus" <http://www.iucnredlist.org/apps/redlist/details/13408/0>`_ , also known as the Forest Small Rice Rat, a rodent that lives in Peru, Colombia, Ecuador, Peru, and Venezuela. References: * `"Maximum entropy modeling of species geographic distributions" <http://www.cs.princeton.edu/~schapire/papers/ecolmod.pdf>`_ S. J. Phillips, R. P. Anderson, R. E. Schapire - Ecological Modelling, 190:231-259, 2006. Notes: * See examples/applications/plot_species_distribution_modeling.py for an example of using this dataset """ # Authors: Peter Prettenhofer <peter.prettenhofer@gmail.com> # Jake Vanderplas <vanderplas@astro.washington.edu> # # License: BSD 3 clause from io import BytesIO from os import makedirs from os.path import join from os.path import exists try: # Python 2 from urllib2 import urlopen PY2 = True except ImportError: # Python 3 from urllib.request import urlopen PY2 = False import numpy as np from sklearn.datasets.base import get_data_home, Bunch from sklearn.externals import joblib DIRECTORY_URL = "http://www.cs.princeton.edu/~schapire/maxent/datasets/" SAMPLES_URL = join(DIRECTORY_URL, "samples.zip") COVERAGES_URL = join(DIRECTORY_URL, "coverages.zip") DATA_ARCHIVE_NAME = "species_coverage.pkz" def _load_coverage(F, header_length=6, dtype=np.int16): """Load a coverage file from an open file object. This will return a numpy array of the given dtype """ header = [F.readline() for i in range(header_length)] make_tuple = lambda t: (t.split()[0], float(t.split()[1])) header = dict([make_tuple(line) for line in header]) M = np.loadtxt(F, dtype=dtype) nodata = header[b'NODATA_value'] if nodata != -9999: print(nodata) M[nodata] = -9999 return M def _load_csv(F): """Load csv file. Parameters ---------- F : file object CSV file open in byte mode. Returns ------- rec : np.ndarray record array representing the data """ if PY2: # Numpy recarray wants Python 2 str but not unicode names = F.readline().strip().split(',') else: # Numpy recarray wants Python 3 str but not bytes... names = F.readline().decode('ascii').strip().split(',') rec = np.loadtxt(F, skiprows=0, delimiter=',', dtype='a22,f4,f4') rec.dtype.names = names return rec def construct_grids(batch): """Construct the map grid from the batch object Parameters ---------- batch : Batch object The object returned by :func:`fetch_species_distributions` Returns ------- (xgrid, ygrid) : 1-D arrays The grid corresponding to the values in batch.coverages """ # x,y coordinates for corner cells xmin = batch.x_left_lower_corner + batch.grid_size xmax = xmin + (batch.Nx * batch.grid_size) ymin = batch.y_left_lower_corner + batch.grid_size ymax = ymin + (batch.Ny * batch.grid_size) # x coordinates of the grid cells xgrid = np.arange(xmin, xmax, batch.grid_size) # y coordinates of the grid cells ygrid = np.arange(ymin, ymax, batch.grid_size) return (xgrid, ygrid) def fetch_species_distributions(data_home=None, download_if_missing=True): """Loader for species distribution dataset from Phillips et. al. (2006) Read more in the :ref:`User Guide <datasets>`. Parameters ---------- data_home : optional, default: None Specify another download and cache folder for the datasets. By default all scikit learn data is stored in '~/scikit_learn_data' subfolders. download_if_missing: optional, True by default If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. Returns -------- The data is returned as a Bunch object with the following attributes: coverages : array, shape = [14, 1592, 1212] These represent the 14 features measured at each point of the map grid. The latitude/longitude values for the grid are discussed below. Missing data is represented by the value -9999. train : record array, shape = (1623,) The training points for the data. Each point has three fields: - train['species'] is the species name - train['dd long'] is the longitude, in degrees - train['dd lat'] is the latitude, in degrees test : record array, shape = (619,) The test points for the data. Same format as the training data. Nx, Ny : integers The number of longitudes (x) and latitudes (y) in the grid x_left_lower_corner, y_left_lower_corner : floats The (x,y) position of the lower-left corner, in degrees grid_size : float The spacing between points of the grid, in degrees Notes ------ This dataset represents the geographic distribution of species. The dataset is provided by Phillips et. al. (2006). The two species are: - `"Bradypus variegatus" <http://www.iucnredlist.org/apps/redlist/details/3038/0>`_ , the Brown-throated Sloth. - `"Microryzomys minutus" <http://www.iucnredlist.org/apps/redlist/details/13408/0>`_ , also known as the Forest Small Rice Rat, a rodent that lives in Peru, Colombia, Ecuador, Peru, and Venezuela. References ---------- * `"Maximum entropy modeling of species geographic distributions" <http://www.cs.princeton.edu/~schapire/papers/ecolmod.pdf>`_ S. J. Phillips, R. P. Anderson, R. E. Schapire - Ecological Modelling, 190:231-259, 2006. Notes ----- * See examples/applications/plot_species_distribution_modeling.py for an example of using this dataset with scikit-learn """ data_home = get_data_home(data_home) if not exists(data_home): makedirs(data_home) # Define parameters for the data files. These should not be changed # unless the data model changes. They will be saved in the npz file # with the downloaded data. extra_params = dict(x_left_lower_corner=-94.8, Nx=1212, y_left_lower_corner=-56.05, Ny=1592, grid_size=0.05) dtype = np.int16 if not exists(join(data_home, DATA_ARCHIVE_NAME)): print('Downloading species data from %s to %s' % (SAMPLES_URL, data_home)) X = np.load(BytesIO(urlopen(SAMPLES_URL).read())) for f in X.files: fhandle = BytesIO(X[f]) if 'train' in f: train = _load_csv(fhandle) if 'test' in f: test = _load_csv(fhandle) print('Downloading coverage data from %s to %s' % (COVERAGES_URL, data_home)) X = np.load(BytesIO(urlopen(COVERAGES_URL).read())) coverages = [] for f in X.files: fhandle = BytesIO(X[f]) print(' - converting', f) coverages.append(_load_coverage(fhandle)) coverages = np.asarray(coverages, dtype=dtype) bunch = Bunch(coverages=coverages, test=test, train=train, **extra_params) joblib.dump(bunch, join(data_home, DATA_ARCHIVE_NAME), compress=9) else: bunch = joblib.load(join(data_home, DATA_ARCHIVE_NAME)) return bunch
bsd-3-clause
nilbody/h2o-3
py/h2o_gbm.py
30
16328
import re, random, math import h2o_args import h2o_nodes import h2o_cmd from h2o_test import verboseprint, dump_json, check_sandbox_for_errors def plotLists(xList, xLabel=None, eListTitle=None, eList=None, eLabel=None, fListTitle=None, fList=None, fLabel=None, server=False): if h2o_args.python_username!='kevin': return # Force matplotlib to not use any Xwindows backend. if server: import matplotlib matplotlib.use('Agg') import pylab as plt print "xList", xList print "eList", eList print "fList", fList font = {'family' : 'normal', 'weight' : 'normal', 'size' : 26} ### plt.rc('font', **font) plt.rcdefaults() if eList: if eListTitle: plt.title(eListTitle) plt.figure() plt.plot (xList, eList) plt.xlabel(xLabel) plt.ylabel(eLabel) plt.draw() plt.savefig('eplot.jpg',format='jpg') # Image.open('testplot.jpg').save('eplot.jpg','JPEG') if fList: if fListTitle: plt.title(fListTitle) plt.figure() plt.plot (xList, fList) plt.xlabel(xLabel) plt.ylabel(fLabel) plt.draw() plt.savefig('fplot.jpg',format='jpg') # Image.open('fplot.jpg').save('fplot.jpg','JPEG') if eList or fList: plt.show() # pretty print a cm that the C def pp_cm(jcm, header=None): # header = jcm['header'] # hack col index header for now..where do we get it? header = ['"%s"'%i for i in range(len(jcm[0]))] # cm = ' '.join(header) cm = '{0:<8}'.format('') for h in header: cm = '{0}|{1:<8}'.format(cm, h) cm = '{0}|{1:<8}'.format(cm, 'error') c = 0 for line in jcm: lineSum = sum(line) if c < 0 or c >= len(line): raise Exception("Error in h2o_gbm.pp_cm. c: %s line: %s len(line): %s jcm: %s" % (c, line, len(line), dump_json(jcm))) print "c:", c, "line:", line errorSum = lineSum - line[c] if (lineSum>0): err = float(errorSum) / lineSum else: err = 0.0 fl = '{0:<8}'.format(header[c]) for num in line: fl = '{0}|{1:<8}'.format(fl, num) fl = '{0}|{1:<8.2f}'.format(fl, err) cm = "{0}\n{1}".format(cm, fl) c += 1 return cm def pp_cm_summary(cm): # hack cut and past for now (should be in h2o_gbm.py? scoresList = cm totalScores = 0 totalRight = 0 # individual scores can be all 0 if nothing for that output class # due to sampling classErrorPctList = [] predictedClassDict = {} # may be missing some? so need a dict? for classIndex,s in enumerate(scoresList): classSum = sum(s) if classSum == 0 : # why would the number of scores for a class be 0? # in any case, tolerate. (it shows up in test.py on poker100) print "classIndex:", classIndex, "classSum", classSum, "<- why 0?" else: if classIndex >= len(s): print "Why is classindex:", classIndex, 'for s:"', s else: # H2O should really give me this since it's in the browser, but it doesn't classRightPct = ((s[classIndex] + 0.0)/classSum) * 100 totalRight += s[classIndex] classErrorPct = 100 - classRightPct classErrorPctList.append(classErrorPct) ### print "s:", s, "classIndex:", classIndex print "class:", classIndex, "classSum", classSum, "classErrorPct:", "%4.2f" % classErrorPct # gather info for prediction summary for pIndex,p in enumerate(s): if pIndex not in predictedClassDict: predictedClassDict[pIndex] = p else: predictedClassDict[pIndex] += p totalScores += classSum print "Predicted summary:" # FIX! Not sure why we weren't working with a list..hack with dict for now for predictedClass,p in predictedClassDict.items(): print str(predictedClass)+":", p # this should equal the num rows in the dataset if full scoring? (minus any NAs) print "totalScores:", totalScores print "totalRight:", totalRight if totalScores != 0: pctRight = 100.0 * totalRight/totalScores else: pctRight = 0.0 print "pctRight:", "%5.2f" % pctRight pctWrong = 100 - pctRight print "pctWrong:", "%5.2f" % pctWrong return pctWrong # I just copied and changed GBM to GBM. Have to update to match GBM params and responses def pickRandGbmParams(paramDict, params): colX = 0 randomGroupSize = random.randint(1,len(paramDict)) for i in range(randomGroupSize): randomKey = random.choice(paramDict.keys()) randomV = paramDict[randomKey] randomValue = random.choice(randomV) params[randomKey] = randomValue # compare this glm to last one. since the files are concatenations, # the results should be similar? 10% of first is allowed delta def compareToFirstGbm(self, key, glm, firstglm): # if isinstance(firstglm[key], list): # in case it's not a list allready (err is a list) verboseprint("compareToFirstGbm key:", key) verboseprint("compareToFirstGbm glm[key]:", glm[key]) # key could be a list or not. if a list, don't want to create list of that list # so use extend on an empty list. covers all cases? if type(glm[key]) is list: kList = glm[key] firstkList = firstglm[key] elif type(glm[key]) is dict: raise Exception("compareToFirstGLm: Not expecting dict for " + key) else: kList = [glm[key]] firstkList = [firstglm[key]] for k, firstk in zip(kList, firstkList): # delta must be a positive number ? delta = .1 * abs(float(firstk)) msg = "Too large a delta (" + str(delta) + ") comparing current and first for: " + key self.assertAlmostEqual(float(k), float(firstk), delta=delta, msg=msg) self.assertGreaterEqual(abs(float(k)), 0.0, str(k) + " abs not >= 0.0 in current") def goodXFromColumnInfo(y, num_cols=None, missingValuesDict=None, constantValuesDict=None, enumSizeDict=None, colTypeDict=None, colNameDict=None, keepPattern=None, key=None, timeoutSecs=120, forRF=False, noPrint=False): y = str(y) # if we pass a key, means we want to get the info ourselves here if key is not None: (missingValuesDict, constantValuesDict, enumSizeDict, colTypeDict, colNameDict) = \ h2o_cmd.columnInfoFromInspect(key, exceptionOnMissingValues=False, max_column_display=99999999, timeoutSecs=timeoutSecs) num_cols = len(colNameDict) # now remove any whose names don't match the required keepPattern if keepPattern is not None: keepX = re.compile(keepPattern) else: keepX = None x = range(num_cols) # need to walk over a copy, cause we change x xOrig = x[:] ignore_x = [] # for use by RF for k in xOrig: name = colNameDict[k] # remove it if it has the same name as the y output if str(k)== y: # if they pass the col index as y if not noPrint: print "Removing %d because name: %s matches output %s" % (k, str(k), y) x.remove(k) # rf doesn't want it in ignore list # ignore_x.append(k) elif name == y: # if they pass the name as y if not noPrint: print "Removing %d because name: %s matches output %s" % (k, name, y) x.remove(k) # rf doesn't want it in ignore list # ignore_x.append(k) elif keepX is not None and not keepX.match(name): if not noPrint: print "Removing %d because name: %s doesn't match desired keepPattern %s" % (k, name, keepPattern) x.remove(k) ignore_x.append(k) # missing values reports as constant also. so do missing first. # remove all cols with missing values # could change it against num_rows for a ratio elif k in missingValuesDict: value = missingValuesDict[k] if not noPrint: print "Removing %d with name: %s because it has %d missing values" % (k, name, value) x.remove(k) ignore_x.append(k) elif k in constantValuesDict: value = constantValuesDict[k] if not noPrint: print "Removing %d with name: %s because it has constant value: %s " % (k, name, str(value)) x.remove(k) ignore_x.append(k) # this is extra pruning.. # remove all cols with enums, if not already removed elif k in enumSizeDict: value = enumSizeDict[k] if not noPrint: print "Removing %d %s because it has enums of size: %d" % (k, name, value) x.remove(k) ignore_x.append(k) if not noPrint: print "x has", len(x), "cols" print "ignore_x has", len(ignore_x), "cols" x = ",".join(map(str,x)) ignore_x = ",".join(map(str,ignore_x)) if not noPrint: print "\nx:", x print "\nignore_x:", ignore_x if forRF: return ignore_x else: return x def showGBMGridResults(GBMResult, expectedErrorMax, classification=True): # print "GBMResult:", dump_json(GBMResult) jobs = GBMResult['jobs'] print "GBM jobs:", jobs for jobnum, j in enumerate(jobs): _distribution = j['_distribution'] model_key = j['destination_key'] job_key = j['job_key'] # inspect = h2o_cmd.runInspect(key=model_key) # print "jobnum:", jobnum, dump_json(inspect) gbmTrainView = h2o_cmd.runGBMView(model_key=model_key) print "jobnum:", jobnum, dump_json(gbmTrainView) if classification: cms = gbmTrainView['gbm_model']['cms'] cm = cms[-1]['_arr'] # take the last one print "GBM cms[-1]['_predErr']:", cms[-1]['_predErr'] print "GBM cms[-1]['_classErr']:", cms[-1]['_classErr'] pctWrongTrain = pp_cm_summary(cm); if pctWrongTrain > expectedErrorMax: raise Exception("Should have < %s error here. pctWrongTrain: %s" % (expectedErrorMax, pctWrongTrain)) errsLast = gbmTrainView['gbm_model']['errs'][-1] print "\nTrain", jobnum, job_key, "\n==========\n", "pctWrongTrain:", pctWrongTrain, "errsLast:", errsLast print "GBM 'errsLast'", errsLast print pp_cm(cm) else: print "\nTrain", jobnum, job_key, "\n==========\n", "errsLast:", errsLast print "GBMTrainView errs:", gbmTrainView['gbm_model']['errs'] def simpleCheckGBMView(node=None, gbmv=None, noPrint=False, **kwargs): if not node: node = h2o_nodes.nodes[0] if 'warnings' in gbmv: warnings = gbmv['warnings'] # catch the 'Failed to converge" for now for w in warnings: if not noPrint: print "\nwarning:", w if ('Failed' in w) or ('failed' in w): raise Exception(w) if 'cm' in gbmv: cm = gbmv['cm'] # only one else: if 'gbm_model' in gbmv: gbm_model = gbmv['gbm_model'] else: raise Exception("no gbm_model in gbmv? %s" % dump_json(gbmv)) cms = gbm_model['cms'] print "number of cms:", len(cms) print "FIX! need to add reporting of h2o's _perr per class error" # FIX! what if regression. is rf only classification? print "cms[-1]['_arr']:", cms[-1]['_arr'] print "cms[-1]['_predErr']:", cms[-1]['_predErr'] print "cms[-1]['_classErr']:", cms[-1]['_classErr'] ## print "cms[-1]:", dump_json(cms[-1]) ## for i,c in enumerate(cms): ## print "cm %s: %s" % (i, c['_arr']) cm = cms[-1]['_arr'] # take the last one scoresList = cm used_trees = gbm_model['N'] errs = gbm_model['errs'] print "errs[0]:", errs[0] print "errs[-1]:", errs[-1] print "errs:", errs # if we got the ntree for comparison. Not always there in kwargs though! param_ntrees = kwargs.get('ntrees',None) if (param_ntrees is not None and used_trees != param_ntrees): raise Exception("used_trees should == param_ntree. used_trees: %s" % used_trees) if (used_trees+1)!=len(cms) or (used_trees+1)!=len(errs): raise Exception("len(cms): %s and len(errs): %s should be one more than N %s trees" % (len(cms), len(errs), used_trees)) totalScores = 0 totalRight = 0 # individual scores can be all 0 if nothing for that output class # due to sampling classErrorPctList = [] predictedClassDict = {} # may be missing some? so need a dict? for classIndex,s in enumerate(scoresList): classSum = sum(s) if classSum == 0 : # why would the number of scores for a class be 0? does GBM CM have entries for non-existent classes # in a range??..in any case, tolerate. (it shows up in test.py on poker100) if not noPrint: print "class:", classIndex, "classSum", classSum, "<- why 0?" else: # H2O should really give me this since it's in the browser, but it doesn't classRightPct = ((s[classIndex] + 0.0)/classSum) * 100 totalRight += s[classIndex] classErrorPct = round(100 - classRightPct, 2) classErrorPctList.append(classErrorPct) ### print "s:", s, "classIndex:", classIndex if not noPrint: print "class:", classIndex, "classSum", classSum, "classErrorPct:", "%4.2f" % classErrorPct # gather info for prediction summary for pIndex,p in enumerate(s): if pIndex not in predictedClassDict: predictedClassDict[pIndex] = p else: predictedClassDict[pIndex] += p totalScores += classSum #**************************** if not noPrint: print "Predicted summary:" # FIX! Not sure why we weren't working with a list..hack with dict for now for predictedClass,p in predictedClassDict.items(): print str(predictedClass)+":", p # this should equal the num rows in the dataset if full scoring? (minus any NAs) print "totalScores:", totalScores print "totalRight:", totalRight if totalScores != 0: pctRight = 100.0 * totalRight/totalScores else: pctRight = 0.0 pctWrong = 100 - pctRight print "pctRight:", "%5.2f" % pctRight print "pctWrong:", "%5.2f" % pctWrong #**************************** # more testing for GBMView # it's legal to get 0's for oobe error # if sample_rate = 1 sample_rate = kwargs.get('sample_rate', None) validation = kwargs.get('validation', None) if (sample_rate==1 and not validation): pass elif (totalScores<=0 or totalScores>5e9): raise Exception("scores in GBMView seems wrong. scores:", scoresList) varimp = gbm_model['varimp'] treeStats = gbm_model['treeStats'] if not treeStats: raise Exception("treeStats not right?: %s" % dump_json(treeStats)) # print "json:", dump_json(gbmv) data_key = gbm_model['_dataKey'] model_key = gbm_model['_key'] classification_error = pctWrong if not noPrint: if 'minLeaves' not in treeStats or not treeStats['minLeaves']: raise Exception("treeStats seems to be missing minLeaves %s" % dump_json(treeStats)) print """ Leaves: {0} / {1} / {2} Depth: {3} / {4} / {5} Err: {6:0.2f} % """.format( treeStats['minLeaves'], treeStats['meanLeaves'], treeStats['maxLeaves'], treeStats['minDepth'], treeStats['meanDepth'], treeStats['maxDepth'], classification_error, ) ### modelInspect = node.inspect(model_key) dataInspect = h2o_cmd.runInspect(key=data_key) check_sandbox_for_errors() return (round(classification_error,2), classErrorPctList, totalScores)
apache-2.0
Paul-St-Young/QMC
from_density.py
1
3864
#!/usr/bin/env python import h5py from lxml import etree import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter # helper functions # ==================== def grab_density_parameters(qmc_input_xml): root = etree.parse(qmc_input_xml) dens_est_list = root.xpath('//estimator[@type="density"]') if len(dens_est_list) != 1: print "expected 1 density estimator, found: ", len(dens_est_list) raise InputError() # end if dens_est = dens_est_list[0] nx,ny,nz = [int(1./float(x)) for x in dens_est.attrib["delta"].split()] x = np.linspace( float(dens_est.attrib["x_min"]), float(dens_est.attrib["x_max"]),nx) y = np.linspace( float(dens_est.attrib["y_min"]), float(dens_est.attrib["y_max"]),ny) z = np.linspace( float(dens_est.attrib["z_min"]), float(dens_est.attrib["z_max"]),nz) return x,y,z # end def grab_density_parameters def grab_density(h5file): # get density f = h5py.File(h5file) for name,quantity in f.items(): if name.startswith('density'): density = quantity.get("value")[:] # end if name.startswith # end for name,quantity f.close() return density # end def grab_density def a2w(alpha): return 1./np.sqrt(2.*alpha) def w2a(sigma): return 1./(4.*sigma**2.) # fitting procedure # ==================== def gauss_1d(x,A,xo,alpha): return A*np.exp(-alpha*(x-xo)**2.) # end def gauss_1d def fit_1d_gaussian(x,y,z,density,ro,plot=True): # find density maximum max_density = max( density[density.nonzero()] ) max_idx = np.where(density==max_density) max_idx = [item[0] for item in max_idx] max_idx[2] += 1 max_xyz = x[max_idx[0]],y[max_idx[1]],z[max_idx[2]] # x slice xslice = density[:,max_idx[1],max_idx[2]] xcoeff,var = curve_fit(gauss_1d,x,xslice,p0=(max(xslice),ro[0],10)) alphax = xcoeff[-1] # y slice yslice = density[max_idx[0],:,max_idx[2]] ycoeff,var = curve_fit(gauss_1d,y,yslice,p0=(max(yslice),ro[1],10)) alphay = ycoeff[-1] # z slice zslice = density[max_idx[0],max_idx[1],:] zcoeff,var = curve_fit(gauss_1d,z,zslice,p0=(max(zslice),ro[2],10)) alphaz = zcoeff[-1] if plot: fig = plt.figure() # x slice ax = fig.add_subplot(131) ax.set_xlabel("x (bohr)",fontsize=14) ax.set_ylabel("density slice (arb. u.)",fontsize=14) ax.plot(x,xslice,".") ax.plot(x,gauss_1d(x,*xcoeff),lw=2,color="black") ax.set_xticks( np.linspace(min(x),max(x),4) ) ax.get_xaxis().set_major_formatter( FormatStrFormatter("%1.2f") ) # y slice ax = fig.add_subplot(132) ax.set_xlabel("y (bohr)",fontsize=14) ax.plot(y,yslice,".") ax.plot(y,gauss_1d(y,*ycoeff),lw=2,color="black") ax.set_xticks( np.linspace(min(y),max(y),4) ) ax.get_xaxis().set_major_formatter( FormatStrFormatter("%1.2f") ) # z slice ax = fig.add_subplot(133) ax.set_xlabel("z (bohr)",fontsize=14) ax.plot(z,zslice,".") ax.plot(z,gauss_1d(z,*zcoeff),lw=2,color="black") ax.set_xticks( np.linspace(min(z),max(z),4) ) ax.get_xaxis().set_major_formatter( FormatStrFormatter("%1.2f") ) fig.tight_layout() # end if plot return alphax,alphay,alphaz # end def fit_1d_gaussian def density_from_1d_fit(qmc_input_xml,qmc_stat_h5,nequil,ro,plot=True): # load data,extract equilibrated piece x,y,z = grab_density_parameters(qmc_input_xml) density = grabDensity(qmc_stat_h5) equil = density[nequil:].sum(axis=0) alphas = fit_1d_gaussian(x,y,z,equil,ro,plot) return np.array(alphas) # end def
mit
kashif/scikit-learn
examples/linear_model/plot_ridge_path.py
55
2138
""" =========================================================== Plot Ridge coefficients as a function of the regularization =========================================================== Shows the effect of collinearity in the coefficients of an estimator. .. currentmodule:: sklearn.linear_model :class:`Ridge` Regression is the estimator used in this example. Each color represents a different feature of the coefficient vector, and this is displayed as a function of the regularization parameter. This example also shows the usefulness of applying Ridge regression to highly ill-conditioned matrices. For such matrices, a slight change in the target variable can cause huge variances in the calculated weights. In such cases, it is useful to set a certain regularization (alpha) to reduce this variation (noise). When alpha is very large, the regularization effect dominates the squared loss function and the coefficients tend to zero. At the end of the path, as alpha tends toward zero and the solution tends towards the ordinary least squares, coefficients exhibit big oscillations. In practise it is necessary to tune alpha in such a way that a balance is maintained between both. """ # Author: Fabian Pedregosa -- <fabian.pedregosa@inria.fr> # License: BSD 3 clause print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model # X is the 10x10 Hilbert matrix X = 1. / (np.arange(1, 11) + np.arange(0, 10)[:, np.newaxis]) y = np.ones(10) ############################################################################### # Compute paths n_alphas = 200 alphas = np.logspace(-10, -2, n_alphas) clf = linear_model.Ridge(fit_intercept=False) coefs = [] for a in alphas: clf.set_params(alpha=a) clf.fit(X, y) coefs.append(clf.coef_) ############################################################################### # Display results ax = plt.gca() ax.plot(alphas, coefs) ax.set_xscale('log') ax.set_xlim(ax.get_xlim()[::-1]) # reverse axis plt.xlabel('alpha') plt.ylabel('weights') plt.title('Ridge coefficients as a function of the regularization') plt.axis('tight') plt.show()
bsd-3-clause
dallascard/guac
core/export/convert_to_ARKcat_format.py
1
1824
import os import sys from optparse import OptionParser import pandas as pd from ..util import dirs from ..util import file_handling as fh from ..preprocessing import data_splitting as ds def main(): usage = "%prog project label_file splits_file output_dir" parser = OptionParser(usage=usage) parser.add_option('-t', dest='test_fold', default=0, help='Test fold: default=%default') #parser.add_option('--keyword', dest='key', default=None, # help='Keyword argument: default=%default') #parser.add_option('--boolarg', action="store_true", dest="boolarg", default=False, # help='Keyword argument: default=%default') (options, args) = parser.parse_args() if len(args) < 3: sys.exit("Please specify the project name and output directory") project = args[0] label_file = args[1] splits_file = args[2] output_dir = args[3] dirs.make_base_dir(project, splits_file) test_fold = int(options.test_fold) text = fh.read_json(dirs.data_raw_text_file) labels = pd.read_csv(label_file, index_col=0, header=0) test_items = list(ds.get_test_documents(test_fold)) nontest_items = list(ds.get_nontest_documents(test_fold)) train_text = {k: text[k] for k in nontest_items} test_text = {k: text[k] for k in test_items} train_labels = labels.loc[nontest_items] test_labels = labels.loc[test_items] if not os.path.exists(output_dir): os.makedirs(output_dir) fh.write_to_json(train_text, os.path.join(output_dir, 'train.json')) fh.write_to_json(test_text, os.path.join(output_dir, 'test.json')) train_labels.to_csv(os.path.join(output_dir, 'train.csv')) test_labels.to_csv(os.path.join(output_dir, 'test.csv')) if __name__ == '__main__': main()
apache-2.0
airanmehr/bio
Scripts/TimeSeriesPaper/Simulation/createPool.py
1
5695
''' Copyleft Dec 4, 2015 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: airanmehr@gmail.com ''' import numpy as np; np.set_printoptions(linewidth=200, precision=5, suppress=True) import pandas as pd; pd.options.display.max_rows=30;pd.options.display.expand_frame_repr=False import os; home=os.path.expanduser('~') +'/' import sys;sys.path.insert(1,'/home/arya/workspace/bio/') import subprocess from Utils import Simulation from multiprocessing import Pool import Utils.Util as utl import CLEAR.Libs.Markov as mkv import optparse, socket, datetime parser = optparse.OptionParser() parser.add_option('-n', '--name', action="store", dest="name", help="method can be [TimeSeries,Chrom]") parser.add_option('-o', '--shutstd', action="store", dest="shutstd", help="takes 0,1", default=0, type='int') options, args = parser.parse_args() options.runname = 'SimulationPool.{}.'.format(options.name) + str(datetime.datetime.now()).split('.')[0] print 'Running {}.'.format(options.runname) if options.shutstd:sys.stderr = sys.stdout = open(utl.stdoutpath + options.runname + '.out', 'w') print 'Running on', socket.gethostname(), str(datetime.datetime.now()), options sys.stdout.flush() def computeEmissions(mypath=utl.simoutpath + 'TimeSeries/simpop/'): print "computing emissions..." E = [] depths = [30, 100, 300] for depth in depths: cd = [] for f in [f for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]: sim = pd.read_pickle(mypath + f) print f cd += [pd.concat([pd.Series(sim.C.loc[depth].reshape(-1)), pd.Series(sim.D.loc[depth].reshape(-1))], axis=1).drop_duplicates()] cd = pd.concat(cd).drop_duplicates() cd = cd.apply(lambda x: (x[0], x[1]), axis=1) cd.index = index = pd.MultiIndex.from_tuples(cd.values, names=['c', 'd']) nu = pd.Series(np.arange(0, 1.0000001, 1. / (2. * sim.N)), index=np.arange(0, 1.0000001, 1. / (2. * sim.N))) a = cd.apply(lambda x: mkv.getStateLikelihoods(x, nu)).sort_index() E += [a] pd.Series(E, index=depths).to_pickle(utl.outpath + 'markov/Emissions.df') def generateSimulation(param): print param if 'generationStep'not in param.keys(): param['generationStep']=10 if 'maxGeneration' not in param.keys(): param['maxGeneration']=50 if 'save' not in param.keys(): param['save']=True for s in param['S']: try: filename = '{}{}/msms/L{:E}.{:E}.msms'.format(utl.simoutpath, param['ModelName'], param['L'], param['i']) Simulation.Simulation(s=s, experimentID=param['i'], msmsFile=filename, L=param['L'], numReplicates=3, initialCarrierFreq=param['nu'], save=param['save'], maxGeneration=param['maxGeneration'], ExperimentName=param['ModelName'], generationStep=param['generationStep']) print 'L,nu,s,i:', param['L'],param['nu'],s, param['i'] sys.stdout.flush() except: import traceback print 'Error************: L,nu,s,i:', param['L'],param['nu'],s, param['i'] traceback.print_exc() def createOneMSMS(param,forceToHaveSoftFreq ): theta=2*param['Ne']*param['mu']*param['L']; rho=2*param['Ne']*param['r']*param['L'] path = '{}{}/msms/'.format(utl.simoutpath, param['ModelName']) utl.mkdir(path) if isinstance(param['i'],(int,float,long)): filename = '{}L{:E}.{:E}.msms'.format(path, param['L'], param['i']) else: filename = '{}L{:E}.{}.msms'.format(path, param['L'], param['i']) cmd = "java -jar -Xmx2g ~/bin/msms/lib/msms.jar -ms {} 1 -t {:.0f} -r {:.0f} {:.0f} -oFP 0.000000000000E00 > {}".\ format(param['n'], theta, rho, param['L'], filename) subprocess.call(cmd,shell=True) if forceToHaveSoftFreq and not (Simulation.MSMS.load(filename)[0].mean(0) == 0.1).sum(): # make sure inital freq 0.1 exist createOneMSMS(param) def getModelParam(name): if name=='TimeSeries': param={'L':int(5e4), 'ModelName':'TimeSeries','numProc': 1,'S' : [0.1, 0.075, 0.05, 0.025], 'numExp' : 1000,\ 'n':200, 'mu':2*1e-9, 'Ne':1e6, 'r':4*1e-9} elif name=='Chrom': param={'L':int(1e7), 'ModelName':'Chrom','numProc': 4,'S' : [0.1, 0.075, 0.05, 0.025], 'numExp' : 100,\ 'n':200, 'mu':2*1e-9, 'Ne':1e6, 'r':4*1e-9} elif name=='Null': param={'L':int(5e6), 'ModelName':'Null','numProc': 4,'S' : [0], 'numExp' : 1,'nu':0.005, 'n':200, 'mu':2*1e-9, 'Ne':1e6, 'r':4*1e-9, 'maxGeneration':59, 'generationStep':1, 'save':False} else: print 'Invalid Model Name' exit() return param def createSimulations(name): param=getModelParam(name) print pd.Series(param) params=[param.copy()for _ in range(param['numExp'])] for i,p in enumerate(params): p.update({'i':i}) #Pool(param['numProc']).map(createOneMSMS, params) for p in params: p.update({'nu':0.1}) Pool(param['numProc']).map(generateSimulation, params) for p in params: p.update({'nu':0.005}) Pool(param['numProc']).map(generateSimulation, params) for p in params: p.update({'S':[0]}) Pool(param['numProc']).map(generateSimulation, params) # computeEmissions() # computeLinkage(0) # Pool(4).map(computeLinkage,range(100)) if __name__ == '__main__': if options.name is None: options.name='Chrom' #scan(300) # SimulationsToDF() # createSimulations(options.name) # param=getModelParam('Null') # print pd.Series(param) # sampleReads(getGens(,d),d) # CD = pd.read_pickle(utl.outpath + 'real/CDEidx.df') # # reload(Simulation)
mit
jblackburne/scikit-learn
sklearn/ensemble/__init__.py
153
1382
""" The :mod:`sklearn.ensemble` module includes ensemble-based methods for classification, regression and anomaly detection. """ from .base import BaseEnsemble from .forest import RandomForestClassifier from .forest import RandomForestRegressor from .forest import RandomTreesEmbedding from .forest import ExtraTreesClassifier from .forest import ExtraTreesRegressor from .bagging import BaggingClassifier from .bagging import BaggingRegressor from .iforest import IsolationForest from .weight_boosting import AdaBoostClassifier from .weight_boosting import AdaBoostRegressor from .gradient_boosting import GradientBoostingClassifier from .gradient_boosting import GradientBoostingRegressor from .voting_classifier import VotingClassifier from . import bagging from . import forest from . import weight_boosting from . import gradient_boosting from . import partial_dependence __all__ = ["BaseEnsemble", "RandomForestClassifier", "RandomForestRegressor", "RandomTreesEmbedding", "ExtraTreesClassifier", "ExtraTreesRegressor", "BaggingClassifier", "BaggingRegressor", "IsolationForest", "GradientBoostingClassifier", "GradientBoostingRegressor", "AdaBoostClassifier", "AdaBoostRegressor", "VotingClassifier", "bagging", "forest", "gradient_boosting", "partial_dependence", "weight_boosting"]
bsd-3-clause
clemkoa/scikit-learn
examples/ensemble/plot_voting_probas.py
29
2932
""" =========================================================== Plot class probabilities calculated by the VotingClassifier =========================================================== Plot the class probabilities of the first sample in a toy dataset predicted by three different classifiers and averaged by the `VotingClassifier`. First, three examplary classifiers are initialized (`LogisticRegression`, `GaussianNB`, and `RandomForestClassifier`) and used to initialize a soft-voting `VotingClassifier` with weights `[1, 1, 5]`, which means that the predicted probabilities of the `RandomForestClassifier` count 5 times as much as the weights of the other classifiers when the averaged probability is calculated. To visualize the probability weighting, we fit each classifier on the training set and plot the predicted class probabilities for the first sample in this example dataset. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import VotingClassifier clf1 = LogisticRegression(random_state=123) clf2 = RandomForestClassifier(random_state=123) clf3 = GaussianNB() X = np.array([[-1.0, -1.0], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2]]) y = np.array([1, 1, 2, 2]) eclf = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='soft', weights=[1, 1, 5]) # predict class probabilities for all classifiers probas = [c.fit(X, y).predict_proba(X) for c in (clf1, clf2, clf3, eclf)] # get class probabilities for the first sample in the dataset class1_1 = [pr[0, 0] for pr in probas] class2_1 = [pr[0, 1] for pr in probas] # plotting N = 4 # number of groups ind = np.arange(N) # group positions width = 0.35 # bar width fig, ax = plt.subplots() # bars for classifier 1-3 p1 = ax.bar(ind, np.hstack(([class1_1[:-1], [0]])), width, color='green', edgecolor='k') p2 = ax.bar(ind + width, np.hstack(([class2_1[:-1], [0]])), width, color='lightgreen', edgecolor='k') # bars for VotingClassifier p3 = ax.bar(ind, [0, 0, 0, class1_1[-1]], width, color='blue', edgecolor='k') p4 = ax.bar(ind + width, [0, 0, 0, class2_1[-1]], width, color='steelblue', edgecolor='k') # plot annotations plt.axvline(2.8, color='k', linestyle='dashed') ax.set_xticks(ind + width) ax.set_xticklabels(['LogisticRegression\nweight 1', 'GaussianNB\nweight 1', 'RandomForestClassifier\nweight 5', 'VotingClassifier\n(average probabilities)'], rotation=40, ha='right') plt.ylim([0, 1]) plt.title('Class probabilities for sample 1 by different classifiers') plt.legend([p1[0], p2[0]], ['class 1', 'class 2'], loc='upper left') plt.show()
bsd-3-clause
sauloal/cnidaria
scripts/venv/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axis3d.py
9
17055
#!/usr/bin/python # axis3d.py, original mplot3d version by John Porter # Created: 23 Sep 2005 # Parts rewritten by Reinier Heeres <reinier@heeres.eu> from __future__ import (absolute_import, division, print_function, unicode_literals) import six import math import copy from matplotlib import lines as mlines, axis as maxis, \ patches as mpatches from . import art3d from . import proj3d import numpy as np def get_flip_min_max(coord, index, mins, maxs): if coord[index] == mins[index]: return maxs[index] else: return mins[index] def move_from_center(coord, centers, deltas, axmask=(True, True, True)): '''Return a coordinate that is moved by "deltas" away from the center.''' coord = copy.copy(coord) #print coord, centers, deltas, axmask for i in range(3): if not axmask[i]: continue if coord[i] < centers[i]: coord[i] -= deltas[i] else: coord[i] += deltas[i] return coord def tick_update_position(tick, tickxs, tickys, labelpos): '''Update tick line and label position and style.''' for (label, on) in ((tick.label1, tick.label1On), \ (tick.label2, tick.label2On)): if on: label.set_position(labelpos) tick.tick1On, tick.tick2On = True, False tick.tick1line.set_linestyle('-') tick.tick1line.set_marker('') tick.tick1line.set_data(tickxs, tickys) tick.gridline.set_data(0, 0) class Axis(maxis.XAxis): # These points from the unit cube make up the x, y and z-planes _PLANES = ( (0, 3, 7, 4), (1, 2, 6, 5), # yz planes (0, 1, 5, 4), (3, 2, 6, 7), # xz planes (0, 1, 2, 3), (4, 5, 6, 7), # xy planes ) # Some properties for the axes _AXINFO = { 'x': {'i': 0, 'tickdir': 1, 'juggled': (1, 0, 2), 'color': (0.95, 0.95, 0.95, 0.5)}, 'y': {'i': 1, 'tickdir': 0, 'juggled': (0, 1, 2), 'color': (0.90, 0.90, 0.90, 0.5)}, 'z': {'i': 2, 'tickdir': 0, 'juggled': (0, 2, 1), 'color': (0.925, 0.925, 0.925, 0.5)}, } def __init__(self, adir, v_intervalx, d_intervalx, axes, *args, **kwargs): # adir identifies which axes this is self.adir = adir # data and viewing intervals for this direction self.d_interval = d_intervalx self.v_interval = v_intervalx # This is a temporary member variable. # Do not depend on this existing in future releases! self._axinfo = self._AXINFO[adir].copy() self._axinfo.update({'label' : {'space_factor': 1.6, 'va': 'center', 'ha': 'center'}, 'tick' : {'inward_factor': 0.2, 'outward_factor': 0.1}, 'ticklabel': {'space_factor': 0.7}, 'axisline': {'linewidth': 0.75, 'color': (0, 0, 0, 1)}, 'grid' : {'color': (0.9, 0.9, 0.9, 1), 'linewidth': 1.0}, }) maxis.XAxis.__init__(self, axes, *args, **kwargs) self.set_rotate_label(kwargs.get('rotate_label', None)) def init3d(self): self.line = mlines.Line2D(xdata=(0, 0), ydata=(0, 0), linewidth=self._axinfo['axisline']['linewidth'], color=self._axinfo['axisline']['color'], antialiased=True, ) # Store dummy data in Polygon object self.pane = mpatches.Polygon(np.array([[0,0], [0,1], [1,0], [0,0]]), closed=False, alpha=0.8, facecolor=(1,1,1,0), edgecolor=(1,1,1,0)) self.set_pane_color(self._axinfo['color']) self.axes._set_artist_props(self.line) self.axes._set_artist_props(self.pane) self.gridlines = art3d.Line3DCollection([], ) self.axes._set_artist_props(self.gridlines) self.axes._set_artist_props(self.label) self.axes._set_artist_props(self.offsetText) # Need to be able to place the label at the correct location self.label._transform = self.axes.transData self.offsetText._transform = self.axes.transData def get_tick_positions(self): majorLocs = self.major.locator() self.major.formatter.set_locs(majorLocs) majorLabels = [self.major.formatter(val, i) for i, val in enumerate(majorLocs)] return majorLabels, majorLocs def get_major_ticks(self, numticks=None): ticks = maxis.XAxis.get_major_ticks(self, numticks) for t in ticks: t.tick1line.set_transform(self.axes.transData) t.tick2line.set_transform(self.axes.transData) t.gridline.set_transform(self.axes.transData) t.label1.set_transform(self.axes.transData) t.label2.set_transform(self.axes.transData) return ticks def set_pane_pos(self, xys): xys = np.asarray(xys) xys = xys[:,:2] self.pane.xy = xys def set_pane_color(self, color): '''Set pane color to a RGBA tuple''' self._axinfo['color'] = color self.pane.set_edgecolor(color) self.pane.set_facecolor(color) self.pane.set_alpha(color[-1]) def set_rotate_label(self, val): ''' Whether to rotate the axis label: True, False or None. If set to None the label will be rotated if longer than 4 chars. ''' self._rotate_label = val def get_rotate_label(self, text): if self._rotate_label is not None: return self._rotate_label else: return len(text) > 4 def _get_coord_info(self, renderer): minx, maxx, miny, maxy, minz, maxz = self.axes.get_w_lims() if minx > maxx: minx, maxx = maxx, minx if miny > maxy: miny, maxy = maxy, miny if minz > maxz: minz, maxz = maxz, minz mins = np.array((minx, miny, minz)) maxs = np.array((maxx, maxy, maxz)) centers = (maxs + mins) / 2. deltas = (maxs - mins) / 12. mins = mins - deltas / 4. maxs = maxs + deltas / 4. vals = mins[0], maxs[0], mins[1], maxs[1], mins[2], maxs[2] tc = self.axes.tunit_cube(vals, renderer.M) avgz = [tc[p1][2] + tc[p2][2] + tc[p3][2] + tc[p4][2] for \ p1, p2, p3, p4 in self._PLANES] highs = np.array([avgz[2*i] < avgz[2*i+1] for i in range(3)]) return mins, maxs, centers, deltas, tc, highs def draw_pane(self, renderer): renderer.open_group('pane3d') mins, maxs, centers, deltas, tc, highs = self._get_coord_info(renderer) info = self._axinfo index = info['i'] if not highs[index]: plane = self._PLANES[2 * index] else: plane = self._PLANES[2 * index + 1] xys = [tc[p] for p in plane] self.set_pane_pos(xys) self.pane.draw(renderer) renderer.close_group('pane3d') def draw(self, renderer): self.label._transform = self.axes.transData renderer.open_group('axis3d') # code from XAxis majorTicks = self.get_major_ticks() majorLocs = self.major.locator() info = self._axinfo index = info['i'] # filter locations here so that no extra grid lines are drawn locmin, locmax = self.get_view_interval() if locmin > locmax: locmin, locmax = locmax, locmin # Rudimentary clipping majorLocs = [loc for loc in majorLocs if locmin <= loc <= locmax] self.major.formatter.set_locs(majorLocs) majorLabels = [self.major.formatter(val, i) for i, val in enumerate(majorLocs)] mins, maxs, centers, deltas, tc, highs = self._get_coord_info(renderer) # Determine grid lines minmax = np.where(highs, maxs, mins) # Draw main axis line juggled = info['juggled'] edgep1 = minmax.copy() edgep1[juggled[0]] = get_flip_min_max(edgep1, juggled[0], mins, maxs) edgep2 = edgep1.copy() edgep2[juggled[1]] = get_flip_min_max(edgep2, juggled[1], mins, maxs) pep = proj3d.proj_trans_points([edgep1, edgep2], renderer.M) centpt = proj3d.proj_transform(centers[0], centers[1], centers[2], renderer.M) self.line.set_data((pep[0][0], pep[0][1]), (pep[1][0], pep[1][1])) self.line.draw(renderer) # Grid points where the planes meet xyz0 = [] for val in majorLocs: coord = minmax.copy() coord[index] = val xyz0.append(coord) # Draw labels peparray = np.asanyarray(pep) # The transAxes transform is used because the Text object # rotates the text relative to the display coordinate system. # Therefore, if we want the labels to remain parallel to the # axis regardless of the aspect ratio, we need to convert the # edge points of the plane to display coordinates and calculate # an angle from that. # TODO: Maybe Text objects should handle this themselves? dx, dy = (self.axes.transAxes.transform(peparray[0:2, 1]) - self.axes.transAxes.transform(peparray[0:2, 0])) lxyz = 0.5*(edgep1 + edgep2) labeldeltas = info['label']['space_factor'] * deltas axmask = [True, True, True] axmask[index] = False lxyz = move_from_center(lxyz, centers, labeldeltas, axmask) tlx, tly, tlz = proj3d.proj_transform(lxyz[0], lxyz[1], lxyz[2], \ renderer.M) self.label.set_position((tlx, tly)) if self.get_rotate_label(self.label.get_text()): angle = art3d.norm_text_angle(math.degrees(math.atan2(dy, dx))) self.label.set_rotation(angle) self.label.set_va(info['label']['va']) self.label.set_ha(info['label']['ha']) self.label.draw(renderer) # Draw Offset text # Which of the two edge points do we want to # use for locating the offset text? if juggled[2] == 2 : outeredgep = edgep1 outerindex = 0 else : outeredgep = edgep2 outerindex = 1 pos = copy.copy(outeredgep) pos = move_from_center(pos, centers, labeldeltas, axmask) olx, oly, olz = proj3d.proj_transform(pos[0], pos[1], pos[2], renderer.M) self.offsetText.set_text( self.major.formatter.get_offset() ) self.offsetText.set_position( (olx, oly) ) angle = art3d.norm_text_angle(math.degrees(math.atan2(dy, dx))) self.offsetText.set_rotation(angle) # Must set rotation mode to "anchor" so that # the alignment point is used as the "fulcrum" for rotation. self.offsetText.set_rotation_mode('anchor') #----------------------------------------------------------------------- # Note: the following statement for determining the proper alignment of # the offset text. This was determined entirely by trial-and-error # and should not be in any way considered as "the way". There are # still some edge cases where alignment is not quite right, but # this seems to be more of a geometry issue (in other words, I # might be using the wrong reference points). # # (TT, FF, TF, FT) are the shorthand for the tuple of # (centpt[info['tickdir']] <= peparray[info['tickdir'], outerindex], # centpt[index] <= peparray[index, outerindex]) # # Three-letters (e.g., TFT, FTT) are short-hand for the array # of bools from the variable 'highs'. # --------------------------------------------------------------------- if centpt[info['tickdir']] > peparray[info['tickdir'], outerindex] : # if FT and if highs has an even number of Trues if (centpt[index] <= peparray[index, outerindex] and ((len(highs.nonzero()[0]) % 2) == 0)) : # Usually, this means align right, except for the FTT case, # in which offset for axis 1 and 2 are aligned left. if highs.tolist() == [False, True, True] and index in (1, 2) : align = 'left' else : align = 'right' else : # The FF case align = 'left' else : # if TF and if highs has an even number of Trues if (centpt[index] > peparray[index, outerindex] and ((len(highs.nonzero()[0]) % 2) == 0)) : # Usually mean align left, except if it is axis 2 if index == 2 : align = 'right' else : align = 'left' else : # The TT case align = 'right' self.offsetText.set_va('center') self.offsetText.set_ha(align) self.offsetText.draw(renderer) # Draw grid lines if len(xyz0) > 0: # Grid points at end of one plane xyz1 = copy.deepcopy(xyz0) newindex = (index + 1) % 3 newval = get_flip_min_max(xyz1[0], newindex, mins, maxs) for i in range(len(majorLocs)): xyz1[i][newindex] = newval # Grid points at end of the other plane xyz2 = copy.deepcopy(xyz0) newindex = (index + 2) % 3 newval = get_flip_min_max(xyz2[0], newindex, mins, maxs) for i in range(len(majorLocs)): xyz2[i][newindex] = newval lines = list(zip(xyz1, xyz0, xyz2)) if self.axes._draw_grid: self.gridlines.set_segments(lines) self.gridlines.set_color([info['grid']['color']] * len(lines)) self.gridlines.draw(renderer, project=True) # Draw ticks tickdir = info['tickdir'] tickdelta = deltas[tickdir] if highs[tickdir]: ticksign = 1 else: ticksign = -1 for tick, loc, label in zip(majorTicks, majorLocs, majorLabels): if tick is None: continue # Get tick line positions pos = copy.copy(edgep1) pos[index] = loc pos[tickdir] = edgep1[tickdir] + info['tick']['outward_factor'] * \ ticksign * tickdelta x1, y1, z1 = proj3d.proj_transform(pos[0], pos[1], pos[2], \ renderer.M) pos[tickdir] = edgep1[tickdir] - info['tick']['inward_factor'] * \ ticksign * tickdelta x2, y2, z2 = proj3d.proj_transform(pos[0], pos[1], pos[2], \ renderer.M) # Get position of label labeldeltas = [info['ticklabel']['space_factor'] * x for x in deltas] axmask = [True, True, True] axmask[index] = False pos[tickdir] = edgep1[tickdir] pos = move_from_center(pos, centers, labeldeltas, axmask) lx, ly, lz = proj3d.proj_transform(pos[0], pos[1], pos[2], \ renderer.M) tick_update_position(tick, (x1, x2), (y1, y2), (lx, ly)) tick.set_label1(label) tick.set_label2(label) tick.draw(renderer) renderer.close_group('axis3d') def get_view_interval(self): """return the Interval instance for this 3d axis view limits""" return self.v_interval def set_view_interval(self, vmin, vmax, ignore=False): if ignore: self.v_interval = vmin, vmax else: Vmin, Vmax = self.get_view_interval() self.v_interval = min(vmin, Vmin), max(vmax, Vmax) # TODO: Get this to work properly when mplot3d supports # the transforms framework. def get_tightbbox(self, renderer) : # Currently returns None so that Axis.get_tightbbox # doesn't return junk info. return None # Use classes to look at different data limits class XAxis(Axis): def get_data_interval(self): 'return the Interval instance for this axis data limits' return self.axes.xy_dataLim.intervalx class YAxis(Axis): def get_data_interval(self): 'return the Interval instance for this axis data limits' return self.axes.xy_dataLim.intervaly class ZAxis(Axis): def get_data_interval(self): 'return the Interval instance for this axis data limits' return self.axes.zz_dataLim.intervalx
mit
MoonRaker/pvlib-python
pvlib/forecast.py
1
26344
''' The 'forecast' module contains class definitions for retreiving forecasted data from UNIDATA Thredd servers. ''' import datetime from netCDF4 import num2date import numpy as np import pandas as pd from requests.exceptions import HTTPError from xml.etree.ElementTree import ParseError from pvlib.location import Location from pvlib.tools import localize_to_utc from pvlib.solarposition import get_solarposition from pvlib.irradiance import liujordan from siphon.catalog import TDSCatalog from siphon.ncss import NCSS class ForecastModel(object): ''' An object for holding forecast model information for use within the pvlib library. Simplifies use of siphon library on a THREDDS server. Parameters ---------- model_type: string UNIDATA category in which the model is located. model_name: string Name of the UNIDATA forecast model. set_type: string Model dataset type. Attributes ---------- access_url: string URL specifying the dataset from data will be retrieved. base_tds_url : string The top level server address catalog_url : string The url path of the catalog to parse. columns: list List of headers used to create the data DataFrame. data: pd.DataFrame Data returned from the query. data_format: string Format of the forecast data being requested from UNIDATA. dataset: Dataset Object containing information used to access forecast data. dataframe_variables: list Model variables that are present in the data. datasets_list: list List of all available datasets. fm_models: Dataset Object containing all available foreast models. fm_models_list: list List of all available forecast models from UNIDATA. latitude: list A list of floats containing latitude values. location: Location A pvlib Location object containing geographic quantities. longitude: list A list of floats containing longitude values. lbox: boolean Indicates the use of a location bounding box. ncss: NCSS object NCSS model_name: string Name of the UNIDATA forecast model. model: Dataset A dictionary of Dataset object, whose keys are the name of the dataset's name. model_url: string The url path of the dataset to parse. modelvariables: list Common variable names that correspond to queryvariables. query: NCSS query object NCSS object used to complete the forecast data retrival. queryvariables: list Variables that are used to query the THREDDS Data Server. rad_type: dictionary Dictionary labeling the method used for calculating radiation values. time: datetime Time range specified for the NCSS query. utctime: DatetimeIndex Time range in UTC. var_stdnames: dictionary Dictionary containing the standard names of the variables in the query, where the keys are the common names. var_units: dictionary Dictionary containing the unites of the variables in the query, where the keys are the common names. variables: dictionary Dictionary that translates model specific variables to common named variables. vert_level: float or integer Vertical altitude for query data. wind_type: string Quantity that was used to calculate wind_speed. zenith: numpy.array Solar zenith angles for the given time range. ''' access_url_key = 'NetcdfSubset' catalog_url = 'http://thredds.ucar.edu/thredds/catalog.xml' base_tds_url = catalog_url.split('/thredds/')[0] data_format = 'netcdf' vert_level = 100000 columns = np.array(['temperature', 'wind_speed', 'total_clouds', 'low_clouds', 'mid_clouds', 'high_clouds', 'dni', 'dhi', 'ghi', ]) def __init__(self, model_type, model_name, set_type): self.model_type = model_type self.model_name = model_name self.set_type = set_type self.catalog = TDSCatalog(self.catalog_url) self.fm_models = TDSCatalog(self.catalog.catalog_refs[model_type].href) self.fm_models_list = sorted(list(self.fm_models.catalog_refs.keys())) try: model_url = self.fm_models.catalog_refs[model_name].href except ParseError: raise ParseError(self.model_name + ' model may be unavailable.') try: self.model = TDSCatalog(model_url) except HTTPError: raise HTTPError(self.model_name + ' model may be unavailable.') self.datasets_list = list(self.model.datasets.keys()) self.set_dataset() def set_dataset(self): ''' Retreives the designated dataset, creates NCSS object, and initiates a NCSS query. ''' keys = list(self.model.datasets.keys()) labels = [item.split()[0].lower() for item in keys] if self.set_type == 'best': self.dataset = self.model.datasets[keys[labels.index('best')]] elif self.set_type == 'latest': self.dataset = self.model.datasets[keys[labels.index('latest')]] elif self.set_type == 'full': self.dataset = self.model.datasets[keys[labels.index('full')]] self.access_url = self.dataset.access_urls[self.access_url_key] self.ncss = NCSS(self.access_url) self.query = self.ncss.query() def set_query_latlon(self): ''' Sets the NCSS query location latitude and longitude. ''' if isinstance(self.longitude, list): self.lbox = True # west, east, south, north self.query.lonlat_box(self.latitude[0], self.latitude[1], self.longitude[0], self.longitude[1]) else: self.lbox = False self.query.lonlat_point(self.longitude, self.latitude) def set_query_time(self): ''' Sets the NCSS query time range. as: single or range ''' if len(self.utctime) == 1: self.query.time(pd.to_datetime(self.utctime)[0]) else: self.query.time_range(pd.to_datetime(self.utctime)[0], pd.to_datetime(self.utctime)[-1]) def set_location(self, time): ''' Sets the location for Parameters ---------- time: datetime or DatetimeIndex Time range of the query. ''' if isinstance(time, datetime.datetime): tzinfo = time.tzinfo else: tzinfo = time.tz if tzinfo is None: self.location = Location(self.latitude, self.longitude) else: self.location = Location(self.latitude, self.longitude, tz=tzinfo) def get_query_data(self, latitude, longitude, time, vert_level=None, variables=None): ''' Submits a query to the UNIDATA servers using siphon NCSS and converts the netcdf data to a pandas DataFrame. Parameters ---------- latitude: list A list of floats containing latitude values. longitude: list A list of floats containing longitude values. time: pd.datetimeindex Time range of interest. vert_level: float or integer Vertical altitude of interest. variables: dictionary Variables and common names being queried. Returns ------- pd.DataFrame ''' if vert_level is not None: self.vert_level = vert_level if variables is not None: self.variables = variables self.modelvariables = list(self.variables.keys()) self.queryvariables = [self.variables[key] for key in \ self.modelvariables] self.columns = self.modelvariables self.dataframe_variables = self.modelvariables self.latitude = latitude self.longitude = longitude self.set_query_latlon() self.set_location(time) self.utctime = localize_to_utc(time, self.location) self.set_query_time() self.query.vertical_level(self.vert_level) self.query.variables(*self.queryvariables) self.query.accept(self.data_format) netcdf_data = self.ncss.get_data(self.query) try: time_var = 'time' self.set_time(netcdf_data.variables[time_var]) except KeyError: time_var = 'time1' self.set_time(netcdf_data.variables[time_var]) self.data = self.netcdf2pandas(netcdf_data) self.set_variable_units(netcdf_data) self.set_variable_stdnames(netcdf_data) if self.__class__.__name__ is 'HRRR': self.calc_temperature(netcdf_data) self.convert_temperature() self.calc_wind(netcdf_data) self.calc_radiation(netcdf_data) self.data = self.data.tz_convert(self.location.tz) netcdf_data.close() return self.data def netcdf2pandas(self, data): ''' Transforms data from netcdf to pandas DataFrame. Currently only supports one-dimensional netcdf data. Parameters ---------- data: netcdf Data returned from UNIDATA NCSS query. Returns ------- pd.DataFrame ''' if not self.lbox: ''' one-dimensional data ''' data_dict = {} for var in self.dataframe_variables: data_dict[var] = pd.Series( data[self.variables[var]][:].squeeze(), index=self.utctime) return pd.DataFrame(data_dict, columns=self.columns) else: return pd.DataFrame(columns=self.columns, index=self.utctime) def set_time(self, time): ''' Converts time data into a pandas date object. Parameters ---------- time: netcdf Contains time information. Returns ------- pandas.DatetimeIndex ''' times = num2date(time[:].squeeze(), time.units) self.time = pd.DatetimeIndex(pd.Series(times), tz='UTC') self.time = self.time.tz_convert(self.location.tz) self.utctime = localize_to_utc(self.time, self.location.tz) def set_variable_units(self, data): ''' Extracts variable unit information from netcdf data. Parameters ---------- data: netcdf Contains queried variable information. ''' self.var_units = {} for var in self.variables: self.var_units[var] = data[self.variables[var]].units def set_variable_stdnames(self, data): ''' Extracts standard names from netcdf data. Parameters ---------- data: netcdf Contains queried variable information. ''' self.var_stdnames = {} for var in self.variables: try: self.var_stdnames[var] = \ data[self.variables[var]].standard_name except AttributeError: self.var_stdnames[var] = var def calc_radiation(self, data, cloud_type='total_clouds'): ''' Determines shortwave radiation values if they are missing from the model data. Parameters ---------- data: netcdf Query data formatted in netcdf format. cloud_type: string Type of cloud cover to use for calculating radiation values. ''' self.rad_type = {} if not self.lbox and cloud_type in self.modelvariables: cloud_prct = self.data[cloud_type] solpos = get_solarposition(self.time, self.location) self.zenith = np.array(solpos.zenith.tz_convert('UTC')) for rad in ['dni','dhi','ghi']: if self.model_name is 'HRRR_ESRL': # HRRR_ESRL is the only model with the # correct equation of time. if rad in self.modelvariables: self.data[rad] = pd.Series( data[self.variables[rad]][:].squeeze(), index=self.time) self.rad_type[rad] = 'forecast' self.data[rad].fillna(0, inplace=True) else: for rad in ['dni','dhi','ghi']: self.rad_type[rad] = 'liujordan' self.data[rad] = liujordan(self.zenith, cloud_prct)[rad] self.data[rad].fillna(0, inplace=True) for var in ['dni', 'dhi', 'ghi']: self.data[var].fillna(0, inplace=True) self.var_units[var] = '$W m^{-2}$' def convert_temperature(self): ''' Converts Kelvin to celsius. ''' if 'Temperature_surface' in self.queryvariables or 'Temperature_isobaric' in self.queryvariables: self.data['temperature'] -= 273.15 self.var_units['temperature'] = 'C' def calc_temperature(self, data): ''' Calculates temperature (in degrees C) from isobaric temperature. Parameters ---------- data: netcdf Query data in netcdf format. ''' P = data['Pressure_surface'][:].squeeze() / 100.0 Tiso = data['Temperature_isobaric'][:].squeeze() Td = data['Dewpoint_temperature_isobaric'][:].squeeze() - 273.15 e = 6.11 * 10**((7.5 * Td) / (Td + 273.3)) w = 0.622 * (e / (P - e)) T = Tiso - ((2.501 * 10.**6) / 1005.7) * w self.data['temperature'] = T def calc_wind(self, data): ''' Computes wind speed. In some cases only gust wind speed is available. The wind_type attribute will indicate the type of wind speed that is present. Parameters ---------- data: netcdf Query data in netcdf format. ''' if not self.lbox: if 'u-component_of_wind_isobaric' in self.queryvariables and \ 'v-component_of_wind_isobaric' in self.queryvariables: wind_data = np.sqrt(\ data['u-component_of_wind_isobaric'][:].squeeze()**2 + data['v-component_of_wind_isobaric'][:].squeeze()**2) self.wind_type = 'component' elif 'Wind_speed_gust_surface' in self.queryvariables: wind_data = data['Wind_speed_gust_surface'][:].squeeze() self.wind_type = 'gust' if 'wind_speed' in self.data: self.data['wind_speed'] = pd.Series(wind_data, index=self.time) self.var_units['wind_speed'] = 'm/s' class GFS(ForecastModel): ''' Subclass of the ForecastModel class representing GFS forecast model. Model data corresponds to 0.25 degree resolution forecasts. Parameters ---------- res: string Resolution of the model. set_type: string Type of model to pull data from. Attributes ---------- dataframe_variables: list Common variables present in the final set of data. model: string Name of the UNIDATA forecast model. model_type: string UNIDATA category in which the model is located. modelvariables: list Common variable names. queryvariables: list Names of default variables specific to the model. variables: dictionary Dictionary of common variables that reference the model specific variables. ''' def __init__(self, res='half', set_type='best'): model_type = 'Forecast Model Data' if res == 'half': model = 'GFS Half Degree Forecast' elif res == 'quarter': model = 'GFS Quarter Degree Forecast' self.variables = { 'temperature':'Temperature_surface', 'wind_speed_gust':'Wind_speed_gust_surface', 'wind_speed_u':'u-component_of_wind_isobaric', 'wind_speed_v':'v-component_of_wind_isobaric', 'total_clouds': 'Total_cloud_cover_entire_atmosphere_Mixed_intervals_Average', 'low_clouds': 'Total_cloud_cover_low_cloud_Mixed_intervals_Average', 'mid_clouds': 'Total_cloud_cover_middle_cloud_Mixed_intervals_Average', 'high_clouds': 'Total_cloud_cover_high_cloud_Mixed_intervals_Average', 'boundary_clouds': 'Total_cloud_cover_boundary_layer_cloud_Mixed_intervals_Average', 'convect_clouds':'Total_cloud_cover_convective_cloud', 'ghi': 'Downward_Short-Wave_Radiation_Flux_surface_Mixed_intervals_Average', } self.modelvariables = self.variables.keys() self.queryvariables = [self.variables[key] for key in \ self.modelvariables] self.dataframe_variables = [ 'temperature', 'total_clouds', 'low_clouds', 'mid_clouds', 'high_clouds', 'boundary_clouds', 'convect_clouds', 'ghi', ] super(GFS, self).__init__(model_type, model, set_type) class HRRR_ESRL(ForecastModel): ''' Subclass of the ForecastModel class representing NOAA/GSD/ESRL's HRRR forecast model. This is not an operational product. Model data corresponds to NOAA/GSD/ESRL HRRR CONUS 3km resolution surface forecasts. Parameters ---------- set_type: string Type of model to pull data from. Attributes ---------- dataframe_variables: list Common variables present in the final set of data. model: string Name of the UNIDATA forecast model. model_type: string UNIDATA category in which the model is located. modelvariables: list Common variable names. queryvariables: list Names of default variables specific to the model. variables: dictionary Dictionary of common variables that reference the model specific variables. ''' def __init__(self, set_type='best'): import warnings warnings.warn('HRRR_ESRL is an experimental model and is not always ' + 'available.') model_type = 'Forecast Model Data' model = 'GSD HRRR CONUS 3km surface' self.variables = { 'temperature':'Temperature_surface', 'wind_speed_gust':'Wind_speed_gust_surface', 'total_clouds':'Total_cloud_cover_entire_atmosphere', 'low_clouds':'Low_cloud_cover_UnknownLevelType-214', 'mid_clouds':'Medium_cloud_cover_UnknownLevelType-224', 'high_clouds':'High_cloud_cover_UnknownLevelType-234', 'ghi':'Downward_short-wave_radiation_flux_surface', } self.modelvariables = self.variables.keys() self.queryvariables = [self.variables[key] for key in \ self.modelvariables] self.dataframe_variables = [ 'temperature', 'total_clouds', 'low_clouds', 'mid_clouds', 'high_clouds', 'ghi', ] super(HRRR_ESRL, self).__init__(model_type, model, set_type) class NAM(ForecastModel): ''' Subclass of the ForecastModel class representing NAM forecast model. Model data corresponds to NAM CONUS 12km resolution forecasts from CONDUIT. Parameters ---------- set_type: string Type of model to pull data from. Attributes ---------- dataframe_variables: list Common variables present in the final set of data. model: string Name of the UNIDATA forecast model. model_type: string UNIDATA category in which the model is located. modelvariables: list Common variable names. queryvariables: list Names of default variables specific to the model. variables: dictionary Dictionary of common variables that reference the model specific variables. ''' def __init__(self,set_type='best'): model_type = 'Forecast Model Data' model = 'NAM CONUS 12km from CONDUIT' self.variables = { 'temperature':'Temperature_surface', 'wind_speed_gust':'Wind_speed_gust_surface', 'total_clouds':'Total_cloud_cover_entire_atmosphere_single_layer', 'low_clouds':'Low_cloud_cover_low_cloud', 'mid_clouds':'Medium_cloud_cover_middle_cloud', 'high_clouds':'High_cloud_cover_high_cloud', 'ghi':'Downward_Short-Wave_Radiation_Flux_surface', } self.modelvariables = self.variables.keys() self.queryvariables = [self.variables[key] for key in \ self.modelvariables] self.dataframe_variables = [ 'temperature', 'total_clouds', 'low_clouds', 'mid_clouds', 'high_clouds', 'ghi', ] super(NAM, self).__init__(model_type, model, set_type) class HRRR(ForecastModel): ''' Subclass of the ForecastModel class representing HRRR forecast model. Model data corresponds to NCEP HRRR CONUS 2.5km resolution forecasts. Parameters ---------- set_type: string Type of model to pull data from. Attributes ---------- dataframe_variables: list Common variables present in the final set of data. model: string Name of the UNIDATA forecast model. model_type: string UNIDATA category in which the model is located. modelvariables: list Common variable names. queryvariables: list Names of default variables specific to the model. variables: dictionary Dictionary of common variables that reference the model specific variables. ''' def __init__(self, set_type='best'): model_type = 'Forecast Model Data' model = 'NCEP HRRR CONUS 2.5km' self.variables = { 'temperature_iso':'Dewpoint_temperature_isobaric', 'temperature_dew_iso':'Temperature_isobaric', 'pressure':'Pressure_surface', 'wind_speed_gust':'Wind_speed_gust_surface', 'total_clouds':'Total_cloud_cover_entire_atmosphere', 'low_clouds':'Low_cloud_cover_low_cloud', 'mid_clouds':'Medium_cloud_cover_middle_cloud', 'high_clouds':'High_cloud_cover_high_cloud', 'condensation_height':'Geopotential_height_adiabatic_condensation_lifted'} self.modelvariables = self.variables.keys() self.queryvariables = [self.variables[key] for key in \ self.modelvariables] self.dataframe_variables = [ 'total_clouds', 'low_clouds', 'mid_clouds', 'high_clouds', ] super(HRRR, self).__init__(model_type, model, set_type) class NDFD(ForecastModel): ''' Subclass of the ForecastModel class representing NDFD forecast model. Model data corresponds to NWS CONUS CONDUIT forecasts. Parameters ---------- set_type: string Type of model to pull data from. Attributes ---------- dataframe_variables: list Common variables present in the final set of data. model: string Name of the UNIDATA forecast model. model_type: string UNIDATA category in which the model is located. modelvariables: list Common variable names. queryvariables: list Names of default variables specific to the model. variables: dictionary Dictionary of common variables that reference the model specific variables. ''' def __init__(self, set_type='best'): model_type = 'Forecast Products and Analyses' model = 'National Weather Service CONUS Forecast Grids (CONDUIT)' self.variables = { 'temperature':'Temperature_surface', 'wind_speed':'Wind_speed_surface', 'wind_speed_gust':'Wind_speed_gust_surface', 'total_clouds':'Total_cloud_cover_surface', } self.modelvariables = self.variables.keys() self.queryvariables = [self.variables[key] for key in \ self.modelvariables] self.dataframe_variables = [ 'temperature', 'total_clouds', ] super(NDFD, self).__init__(model_type, model, set_type) class RAP(ForecastModel): ''' Subclass of the ForecastModel class representing RAP forecast model. Model data corresponds to Rapid Refresh CONUS 20km resolution forecasts. Parameters ---------- set_type: string Type of model to pull data from. Attributes ---------- dataframe_variables: list Common variables present in the final set of data. model: string Name of the UNIDATA forecast model. model_type: string UNIDATA category in which the model is located. modelvariables: list Common variable names. queryvariables: list Names of default variables specific to the model. variables: dictionary Dictionary of common variables that reference the model specific variables. ''' def __init__(self, set_type='best'): model_type = 'Forecast Model Data' model = 'Rapid Refresh CONUS 20km' self.variables = { 'temperature':'Temperature_surface', 'wind_speed_gust':'Wind_speed_gust_surface', 'total_clouds':'Total_cloud_cover_entire_atmosphere_single_layer', 'low_clouds':'Low_cloud_cover_low_cloud', 'mid_clouds':'Medium_cloud_cover_middle_cloud', 'high_clouds':'High_cloud_cover_high_cloud', } self.modelvariables = self.variables.keys() self.queryvariables = [self.variables[key] for key in \ self.modelvariables] self.dataframe_variables = [ 'temperature', 'total_clouds', 'low_clouds', 'mid_clouds', 'high_clouds', ] super(RAP, self).__init__(model_type, model, set_type)
bsd-3-clause
wangsharp/trading-with-python
cookbook/workingWithDatesAndTime.py
77
1551
# -*- coding: utf-8 -*- """ Created on Sun Oct 16 17:45:02 2011 @author: jev """ import time import datetime as dt from pandas import * from pandas.core import datetools # basic functions print 'Epoch start: %s' % time.asctime(time.gmtime(0)) print 'Seconds from epoch: %.2f' % time.time() today = dt.date.today() print type(today) print 'Today is %s' % today.strftime('%Y.%m.%d') # parse datetime d = dt.datetime.strptime('20120803 21:59:59',"%Y%m%d %H:%M:%S") # time deltas someDate = dt.date(2011,8,1) delta = today - someDate print 'Delta :', delta # calculate difference in dates delta = dt.timedelta(days=20) print 'Today-delta=', today-delta t = dt.datetime(*time.strptime('3/30/2004',"%m/%d/%Y")[0:5]) # the '*' operator unpacks the tuple, producing the argument list. print t # print every 3d wednesday of the month for month in xrange(1,13): t = dt.date(2013,month,1)+datetools.relativedelta(months=1) offset = datetools.Week(weekday=4) if t.weekday()<>4: t_new = t+3*offset else: t_new = t+2*offset t_new = t_new-datetools.relativedelta(days=30) print t_new.strftime("%B, %d %Y (%A)") #rng = DateRange(t, t+datetools.YearEnd()) #print rng # create a range of times start = dt.datetime(2012,8,1)+datetools.relativedelta(hours=9,minutes=30) end = dt.datetime(2012,8,1)+datetools.relativedelta(hours=22) rng = date_range(start,end,freq='30min') for r in rng: print r.strftime("%Y%m%d %H:%M:%S")
bsd-3-clause
FRidh/scipy
scipy/spatial/_plotutils.py
53
4034
from __future__ import division, print_function, absolute_import import numpy as np from scipy._lib.decorator import decorator as _decorator __all__ = ['delaunay_plot_2d', 'convex_hull_plot_2d', 'voronoi_plot_2d'] @_decorator def _held_figure(func, obj, ax=None, **kw): import matplotlib.pyplot as plt if ax is None: fig = plt.figure() ax = fig.gca() was_held = ax.ishold() try: ax.hold(True) return func(obj, ax=ax, **kw) finally: ax.hold(was_held) def _adjust_bounds(ax, points): ptp_bound = points.ptp(axis=0) ax.set_xlim(points[:,0].min() - 0.1*ptp_bound[0], points[:,0].max() + 0.1*ptp_bound[0]) ax.set_ylim(points[:,1].min() - 0.1*ptp_bound[1], points[:,1].max() + 0.1*ptp_bound[1]) @_held_figure def delaunay_plot_2d(tri, ax=None): """ Plot the given Delaunay triangulation in 2-D Parameters ---------- tri : scipy.spatial.Delaunay instance Triangulation to plot ax : matplotlib.axes.Axes instance, optional Axes to plot on Returns ------- fig : matplotlib.figure.Figure instance Figure for the plot See Also -------- Delaunay matplotlib.pyplot.triplot Notes ----- Requires Matplotlib. """ if tri.points.shape[1] != 2: raise ValueError("Delaunay triangulation is not 2-D") ax.plot(tri.points[:,0], tri.points[:,1], 'o') ax.triplot(tri.points[:,0], tri.points[:,1], tri.simplices.copy()) _adjust_bounds(ax, tri.points) return ax.figure @_held_figure def convex_hull_plot_2d(hull, ax=None): """ Plot the given convex hull diagram in 2-D Parameters ---------- hull : scipy.spatial.ConvexHull instance Convex hull to plot ax : matplotlib.axes.Axes instance, optional Axes to plot on Returns ------- fig : matplotlib.figure.Figure instance Figure for the plot See Also -------- ConvexHull Notes ----- Requires Matplotlib. """ if hull.points.shape[1] != 2: raise ValueError("Convex hull is not 2-D") ax.plot(hull.points[:,0], hull.points[:,1], 'o') for simplex in hull.simplices: ax.plot(hull.points[simplex,0], hull.points[simplex,1], 'k-') _adjust_bounds(ax, hull.points) return ax.figure @_held_figure def voronoi_plot_2d(vor, ax=None): """ Plot the given Voronoi diagram in 2-D Parameters ---------- vor : scipy.spatial.Voronoi instance Diagram to plot ax : matplotlib.axes.Axes instance, optional Axes to plot on Returns ------- fig : matplotlib.figure.Figure instance Figure for the plot See Also -------- Voronoi Notes ----- Requires Matplotlib. """ if vor.points.shape[1] != 2: raise ValueError("Voronoi diagram is not 2-D") ax.plot(vor.points[:,0], vor.points[:,1], '.') ax.plot(vor.vertices[:,0], vor.vertices[:,1], 'o') for simplex in vor.ridge_vertices: simplex = np.asarray(simplex) if np.all(simplex >= 0): ax.plot(vor.vertices[simplex,0], vor.vertices[simplex,1], 'k-') ptp_bound = vor.points.ptp(axis=0) center = vor.points.mean(axis=0) for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices): simplex = np.asarray(simplex) if np.any(simplex < 0): i = simplex[simplex >= 0][0] # finite end Voronoi vertex t = vor.points[pointidx[1]] - vor.points[pointidx[0]] # tangent t /= np.linalg.norm(t) n = np.array([-t[1], t[0]]) # normal midpoint = vor.points[pointidx].mean(axis=0) direction = np.sign(np.dot(midpoint - center, n)) * n far_point = vor.vertices[i] + direction * ptp_bound.max() ax.plot([vor.vertices[i,0], far_point[0]], [vor.vertices[i,1], far_point[1]], 'k--') _adjust_bounds(ax, vor.points) return ax.figure
bsd-3-clause
dch312/scipy
scipy/signal/spectral.py
3
13830
"""Tools for spectral analysis. """ from __future__ import division, print_function, absolute_import import numpy as np from scipy import fftpack from . import signaltools from .windows import get_window from ._spectral import lombscargle import warnings from scipy._lib.six import string_types __all__ = ['periodogram', 'welch', 'lombscargle'] def periodogram(x, fs=1.0, window=None, nfft=None, detrend='constant', return_onesided=True, scaling='density', axis=-1): """ Estimate power spectral density using a periodogram. Parameters ---------- x : array_like Time series of measurement values fs : float, optional Sampling frequency of the `x` time series in units of Hz. Defaults to 1.0. window : str or tuple or array_like, optional Desired window to use. See `get_window` for a list of windows and required parameters. If `window` is an array it will be used directly as the window. Defaults to None; equivalent to 'boxcar'. nfft : int, optional Length of the FFT used. If None the length of `x` will be used. detrend : str or function or False, optional Specifies how to detrend `x` prior to computing the spectrum. If `detrend` is a string, it is passed as the ``type`` argument to `detrend`. If it is a function, it should return a detrended array. If `detrend` is False, no detrending is done. Defaults to 'constant'. return_onesided : bool, optional If True, return a one-sided spectrum for real data. If False return a two-sided spectrum. Note that for complex data, a two-sided spectrum is always returned. scaling : { 'density', 'spectrum' }, optional Selects between computing the power spectral density ('density') where `Pxx` has units of V**2/Hz if `x` is measured in V and computing the power spectrum ('spectrum') where `Pxx` has units of V**2 if `x` is measured in V. Defaults to 'density' axis : int, optional Axis along which the periodogram is computed; the default is over the last axis (i.e. ``axis=-1``). Returns ------- f : ndarray Array of sample frequencies. Pxx : ndarray Power spectral density or power spectrum of `x`. Notes ----- .. versionadded:: 0.12.0 See Also -------- welch: Estimate power spectral density using Welch's method lombscargle: Lomb-Scargle periodogram for unevenly sampled data Examples -------- >>> from scipy import signal >>> import matplotlib.pyplot as plt Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by 0.001 V**2/Hz of white noise sampled at 10 kHz. >>> fs = 10e3 >>> N = 1e5 >>> amp = 2*np.sqrt(2) >>> freq = 1234.0 >>> noise_power = 0.001 * fs / 2 >>> time = np.arange(N) / fs >>> x = amp*np.sin(2*np.pi*freq*time) >>> x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape) Compute and plot the power spectral density. >>> f, Pxx_den = signal.periodogram(x, fs) >>> plt.semilogy(f, Pxx_den) >>> plt.ylim([1e-7, 1e2]) >>> plt.xlabel('frequency [Hz]') >>> plt.ylabel('PSD [V**2/Hz]') >>> plt.show() If we average the last half of the spectral density, to exclude the peak, we can recover the noise power on the signal. >>> np.mean(Pxx_den[256:]) 0.0009924865443739191 Now compute and plot the power spectrum. >>> f, Pxx_spec = signal.periodogram(x, fs, 'flattop', scaling='spectrum') >>> plt.figure() >>> plt.semilogy(f, np.sqrt(Pxx_spec)) >>> plt.ylim([1e-4, 1e1]) >>> plt.xlabel('frequency [Hz]') >>> plt.ylabel('Linear spectrum [V RMS]') >>> plt.show() The peak height in the power spectrum is an estimate of the RMS amplitude. >>> np.sqrt(Pxx_spec.max()) 2.0077340678640727 """ x = np.asarray(x) if x.size == 0: return np.empty(x.shape), np.empty(x.shape) if window is None: window = 'boxcar' if nfft is None: nperseg = x.shape[axis] elif nfft == x.shape[axis]: nperseg = nfft elif nfft > x.shape[axis]: nperseg = x.shape[axis] elif nfft < x.shape[axis]: s = [np.s_[:]]*len(x.shape) s[axis] = np.s_[:nfft] x = x[s] nperseg = nfft nfft = None return welch(x, fs, window, nperseg, 0, nfft, detrend, return_onesided, scaling, axis) def welch(x, fs=1.0, window='hanning', nperseg=256, noverlap=None, nfft=None, detrend='constant', return_onesided=True, scaling='density', axis=-1): """ Estimate power spectral density using Welch's method. Welch's method [1]_ computes an estimate of the power spectral density by dividing the data into overlapping segments, computing a modified periodogram for each segment and averaging the periodograms. Parameters ---------- x : array_like Time series of measurement values fs : float, optional Sampling frequency of the `x` time series in units of Hz. Defaults to 1.0. window : str or tuple or array_like, optional Desired window to use. See `get_window` for a list of windows and required parameters. If `window` is array_like it will be used directly as the window and its length will be used for nperseg. Defaults to 'hanning'. nperseg : int, optional Length of each segment. Defaults to 256. noverlap: int, optional Number of points to overlap between segments. If None, ``noverlap = nperseg / 2``. Defaults to None. nfft : int, optional Length of the FFT used, if a zero padded FFT is desired. If None, the FFT length is `nperseg`. Defaults to None. detrend : str or function or False, optional Specifies how to detrend each segment. If `detrend` is a string, it is passed as the ``type`` argument to `detrend`. If it is a function, it takes a segment and returns a detrended segment. If `detrend` is False, no detrending is done. Defaults to 'constant'. return_onesided : bool, optional If True, return a one-sided spectrum for real data. If False return a two-sided spectrum. Note that for complex data, a two-sided spectrum is always returned. scaling : { 'density', 'spectrum' }, optional Selects between computing the power spectral density ('density') where Pxx has units of V**2/Hz if x is measured in V and computing the power spectrum ('spectrum') where Pxx has units of V**2 if x is measured in V. Defaults to 'density'. axis : int, optional Axis along which the periodogram is computed; the default is over the last axis (i.e. ``axis=-1``). Returns ------- f : ndarray Array of sample frequencies. Pxx : ndarray Power spectral density or power spectrum of x. See Also -------- periodogram: Simple, optionally modified periodogram lombscargle: Lomb-Scargle periodogram for unevenly sampled data Notes ----- An appropriate amount of overlap will depend on the choice of window and on your requirements. For the default 'hanning' window an overlap of 50% is a reasonable trade off between accurately estimating the signal power, while not over counting any of the data. Narrower windows may require a larger overlap. If `noverlap` is 0, this method is equivalent to Bartlett's method [2]_. .. versionadded:: 0.12.0 References ---------- .. [1] P. Welch, "The use of the fast Fourier transform for the estimation of power spectra: A method based on time averaging over short, modified periodograms", IEEE Trans. Audio Electroacoust. vol. 15, pp. 70-73, 1967. .. [2] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra", Biometrika, vol. 37, pp. 1-16, 1950. Examples -------- >>> from scipy import signal >>> import matplotlib.pyplot as plt Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by 0.001 V**2/Hz of white noise sampled at 10 kHz. >>> fs = 10e3 >>> N = 1e5 >>> amp = 2*np.sqrt(2) >>> freq = 1234.0 >>> noise_power = 0.001 * fs / 2 >>> time = np.arange(N) / fs >>> x = amp*np.sin(2*np.pi*freq*time) >>> x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape) Compute and plot the power spectral density. >>> f, Pxx_den = signal.welch(x, fs, nperseg=1024) >>> plt.semilogy(f, Pxx_den) >>> plt.ylim([0.5e-3, 1]) >>> plt.xlabel('frequency [Hz]') >>> plt.ylabel('PSD [V**2/Hz]') >>> plt.show() If we average the last half of the spectral density, to exclude the peak, we can recover the noise power on the signal. >>> np.mean(Pxx_den[256:]) 0.0009924865443739191 Now compute and plot the power spectrum. >>> f, Pxx_spec = signal.welch(x, fs, 'flattop', 1024, scaling='spectrum') >>> plt.figure() >>> plt.semilogy(f, np.sqrt(Pxx_spec)) >>> plt.xlabel('frequency [Hz]') >>> plt.ylabel('Linear spectrum [V RMS]') >>> plt.show() The peak height in the power spectrum is an estimate of the RMS amplitude. >>> np.sqrt(Pxx_spec.max()) 2.0077340678640727 """ x = np.asarray(x) if x.size == 0: return np.empty(x.shape), np.empty(x.shape) if axis != -1: x = np.rollaxis(x, axis, len(x.shape)) if x.shape[-1] < nperseg: warnings.warn('nperseg = %d, is greater than x.shape[%d] = %d, using ' 'nperseg = x.shape[%d]' % (nperseg, axis, x.shape[axis], axis)) nperseg = x.shape[-1] if isinstance(window, string_types) or type(window) is tuple: win = get_window(window, nperseg) else: win = np.asarray(window) if len(win.shape) != 1: raise ValueError('window must be 1-D') if win.shape[0] > x.shape[-1]: raise ValueError('window is longer than x.') nperseg = win.shape[0] # numpy 1.5.1 doesn't have result_type. outdtype = (np.array([x[0]]) * np.array([1], 'f')).dtype.char.lower() if win.dtype != outdtype: win = win.astype(outdtype) if scaling == 'density': scale = 1.0 / (fs * (win*win).sum()) elif scaling == 'spectrum': scale = 1.0 / win.sum()**2 else: raise ValueError('Unknown scaling: %r' % scaling) if noverlap is None: noverlap = nperseg // 2 elif noverlap >= nperseg: raise ValueError('noverlap must be less than nperseg.') if nfft is None: nfft = nperseg elif nfft < nperseg: raise ValueError('nfft must be greater than or equal to nperseg.') if not detrend: detrend_func = lambda seg: seg elif not hasattr(detrend, '__call__'): detrend_func = lambda seg: signaltools.detrend(seg, type=detrend) elif axis != -1: # Wrap this function so that it receives a shape that it could # reasonably expect to receive. def detrend_func(seg): seg = np.rollaxis(seg, -1, axis) seg = detrend(seg) return np.rollaxis(seg, axis, len(seg.shape)) else: detrend_func = detrend step = nperseg - noverlap indices = np.arange(0, x.shape[-1]-nperseg+1, step) if np.isrealobj(x) and return_onesided: outshape = list(x.shape) if nfft % 2 == 0: # even outshape[-1] = nfft // 2 + 1 Pxx = np.empty(outshape, outdtype) for k, ind in enumerate(indices): x_dt = detrend_func(x[..., ind:ind+nperseg]) xft = fftpack.rfft(x_dt*win, nfft) # fftpack.rfft returns the positive frequency part of the fft # as real values, packed r r i r i r i ... # this indexing is to extract the matching real and imaginary # parts, while also handling the pure real zero and nyquist # frequencies. if k == 0: Pxx[..., (0,-1)] = xft[..., (0,-1)]**2 Pxx[..., 1:-1] = xft[..., 1:-1:2]**2 + xft[..., 2::2]**2 else: Pxx *= k/(k+1.0) Pxx[..., (0,-1)] += xft[..., (0,-1)]**2 / (k+1.0) Pxx[..., 1:-1] += (xft[..., 1:-1:2]**2 + xft[..., 2::2]**2) \ / (k+1.0) else: # odd outshape[-1] = (nfft+1) // 2 Pxx = np.empty(outshape, outdtype) for k, ind in enumerate(indices): x_dt = detrend_func(x[..., ind:ind+nperseg]) xft = fftpack.rfft(x_dt*win, nfft) if k == 0: Pxx[..., 0] = xft[..., 0]**2 Pxx[..., 1:] = xft[..., 1::2]**2 + xft[..., 2::2]**2 else: Pxx *= k/(k+1.0) Pxx[..., 0] += xft[..., 0]**2 / (k+1) Pxx[..., 1:] += (xft[..., 1::2]**2 + xft[..., 2::2]**2) \ / (k+1.0) Pxx[..., 1:-1] *= 2*scale Pxx[..., (0,-1)] *= scale f = np.arange(Pxx.shape[-1]) * (fs/nfft) else: for k, ind in enumerate(indices): x_dt = detrend_func(x[..., ind:ind+nperseg]) xft = fftpack.fft(x_dt*win, nfft) if k == 0: Pxx = (xft * xft.conj()).real else: Pxx *= k/(k+1.0) Pxx += (xft * xft.conj()).real / (k+1.0) Pxx *= scale f = fftpack.fftfreq(nfft, 1.0/fs) if axis != -1: Pxx = np.rollaxis(Pxx, -1, axis) return f, Pxx
bsd-3-clause
ebothmann/seaborn
seaborn/linearmodels.py
5
43689
"""Plotting functions for linear models (broadly construed).""" from __future__ import division import copy import itertools import numpy as np import pandas as pd from scipy.spatial import distance import matplotlib as mpl import matplotlib.pyplot as plt try: import statsmodels assert statsmodels _has_statsmodels = True except ImportError: _has_statsmodels = False from .external.six import string_types from .external.six.moves import range from . import utils from . import algorithms as algo from .palettes import color_palette from .axisgrid import FacetGrid, PairGrid from .distributions import kdeplot class _LinearPlotter(object): """Base class for plotting relational data in tidy format. To get anything useful done you'll have to inherit from this, but setup code that can be abstracted out should be put here. """ def establish_variables(self, data, **kws): """Extract variables from data or use directly.""" self.data = data # Validate the inputs any_strings = any([isinstance(v, string_types) for v in kws.values()]) if any_strings and data is None: raise ValueError("Must pass `data` if using named variables.") # Set the variables for var, val in kws.items(): if isinstance(val, string_types): setattr(self, var, data[val]) else: setattr(self, var, val) def dropna(self, *vars): """Remove observations with missing data.""" vals = [getattr(self, var) for var in vars] vals = [v for v in vals if v is not None] not_na = np.all(np.column_stack([pd.notnull(v) for v in vals]), axis=1) for var in vars: val = getattr(self, var) if val is not None: setattr(self, var, val[not_na]) def plot(self, ax): raise NotImplementedError class _RegressionPlotter(_LinearPlotter): """Plotter for numeric independent variables with regression model. This does the computations and drawing for the `regplot` function, and is thus also used indirectly by `lmplot`. It is generally similar to the `_DiscretePlotter`, but it's intended for use when the independent variable is numeric (continuous or discrete), and its primary advantage is that a regression model can be fit to the data and visualized, allowing extrapolations beyond the observed datapoints. """ def __init__(self, x, y, data=None, x_estimator=None, x_bins=None, x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=False, dropna=True, x_jitter=None, y_jitter=None, color=None, label=None): # Set member attributes self.x_estimator = x_estimator self.ci = ci self.x_ci = ci if x_ci == "ci" else x_ci self.n_boot = n_boot self.scatter = scatter self.fit_reg = fit_reg self.order = order self.logistic = logistic self.lowess = lowess self.robust = robust self.logx = logx self.truncate = truncate self.x_jitter = x_jitter self.y_jitter = y_jitter self.color = color self.label = label # Validate the regression options: if sum((order > 1, logistic, robust, lowess, logx)) > 1: raise ValueError("Mutually exclusive regression options.") # Extract the data vals from the arguments or passed dataframe self.establish_variables(data, x=x, y=y, units=units, x_partial=x_partial, y_partial=y_partial) # Drop null observations if dropna: self.dropna("x", "y", "units", "x_partial", "y_partial") # Regress nuisance variables out of the data if self.x_partial is not None: self.x = self.regress_out(self.x, self.x_partial) if self.y_partial is not None: self.y = self.regress_out(self.y, self.y_partial) # Possibly bin the predictor variable, which implies a point estimate if x_bins is not None: self.x_estimator = np.mean if x_estimator is None else x_estimator x_discrete, x_bins = self.bin_predictor(x_bins) self.x_discrete = x_discrete else: self.x_discrete = self.x # Save the range of the x variable for the grid later self.x_range = self.x.min(), self.x.max() @property def scatter_data(self): """Data where each observation is a point.""" x_j = self.x_jitter if x_j is None: x = self.x else: x = self.x + np.random.uniform(-x_j, x_j, len(self.x)) y_j = self.y_jitter if y_j is None: y = self.y else: y = self.y + np.random.uniform(-y_j, y_j, len(self.y)) return x, y @property def estimate_data(self): """Data with a point estimate and CI for each discrete x value.""" x, y = self.x_discrete, self.y vals = sorted(np.unique(x)) points, cis = [], [] for val in vals: # Get the point estimate of the y variable _y = y[x == val] est = self.x_estimator(_y) points.append(est) # Compute the confidence interval for this estimate if self.x_ci is None: cis.append(None) else: units = None if self.units is not None: units = self.units[x == val] boots = algo.bootstrap(_y, func=self.x_estimator, n_boot=self.n_boot, units=units) _ci = utils.ci(boots, self.x_ci) cis.append(_ci) return vals, points, cis def fit_regression(self, ax=None, x_range=None, grid=None): """Fit the regression model.""" # Create the grid for the regression if grid is None: if self.truncate: x_min, x_max = self.x_range else: if ax is None: x_min, x_max = x_range else: x_min, x_max = ax.get_xlim() grid = np.linspace(x_min, x_max, 100) ci = self.ci # Fit the regression if self.order > 1: yhat, yhat_boots = self.fit_poly(grid, self.order) elif self.logistic: from statsmodels.genmod.generalized_linear_model import GLM from statsmodels.genmod.families import Binomial yhat, yhat_boots = self.fit_statsmodels(grid, GLM, family=Binomial()) elif self.lowess: ci = None grid, yhat = self.fit_lowess() elif self.robust: from statsmodels.robust.robust_linear_model import RLM yhat, yhat_boots = self.fit_statsmodels(grid, RLM) elif self.logx: yhat, yhat_boots = self.fit_logx(grid) else: yhat, yhat_boots = self.fit_fast(grid) # Compute the confidence interval at each grid point if ci is None: err_bands = None else: err_bands = utils.ci(yhat_boots, ci, axis=0) return grid, yhat, err_bands def fit_fast(self, grid): """Low-level regression and prediction using linear algebra.""" X, y = np.c_[np.ones(len(self.x)), self.x], self.y grid = np.c_[np.ones(len(grid)), grid] reg_func = lambda _x, _y: np.linalg.pinv(_x).dot(_y) yhat = grid.dot(reg_func(X, y)) if self.ci is None: return yhat, None beta_boots = algo.bootstrap(X, y, func=reg_func, n_boot=self.n_boot, units=self.units).T yhat_boots = grid.dot(beta_boots).T return yhat, yhat_boots def fit_poly(self, grid, order): """Regression using numpy polyfit for higher-order trends.""" x, y = self.x, self.y reg_func = lambda _x, _y: np.polyval(np.polyfit(_x, _y, order), grid) yhat = reg_func(x, y) if self.ci is None: return yhat, None yhat_boots = algo.bootstrap(x, y, func=reg_func, n_boot=self.n_boot, units=self.units) return yhat, yhat_boots def fit_statsmodels(self, grid, model, **kwargs): """More general regression function using statsmodels objects.""" X, y = np.c_[np.ones(len(self.x)), self.x], self.y grid = np.c_[np.ones(len(grid)), grid] reg_func = lambda _x, _y: model(_y, _x, **kwargs).fit().predict(grid) yhat = reg_func(X, y) if self.ci is None: return yhat, None yhat_boots = algo.bootstrap(X, y, func=reg_func, n_boot=self.n_boot, units=self.units) return yhat, yhat_boots def fit_lowess(self): """Fit a locally-weighted regression, which returns its own grid.""" from statsmodels.nonparametric.smoothers_lowess import lowess grid, yhat = lowess(self.y, self.x).T return grid, yhat def fit_logx(self, grid): """Fit the model in log-space.""" X, y = np.c_[np.ones(len(self.x)), self.x], self.y grid = np.c_[np.ones(len(grid)), np.log(grid)] def reg_func(_x, _y): _x = np.c_[_x[:, 0], np.log(_x[:, 1])] return np.linalg.pinv(_x).dot(_y) yhat = grid.dot(reg_func(X, y)) if self.ci is None: return yhat, None beta_boots = algo.bootstrap(X, y, func=reg_func, n_boot=self.n_boot, units=self.units).T yhat_boots = grid.dot(beta_boots).T return yhat, yhat_boots def bin_predictor(self, bins): """Discretize a predictor by assigning value to closest bin.""" x = self.x if np.isscalar(bins): percentiles = np.linspace(0, 100, bins + 2)[1:-1] bins = np.c_[utils.percentiles(x, percentiles)] else: bins = np.c_[np.ravel(bins)] dist = distance.cdist(np.c_[x], bins) x_binned = bins[np.argmin(dist, axis=1)].ravel() return x_binned, bins.ravel() def regress_out(self, a, b): """Regress b from a keeping a's original mean.""" a_mean = a.mean() a = a - a_mean b = b - b.mean() b = np.c_[b] a_prime = a - b.dot(np.linalg.pinv(b).dot(a)) return (a_prime + a_mean).reshape(a.shape) def plot(self, ax, scatter_kws, line_kws): """Draw the full plot.""" # Insert the plot label into the correct set of keyword arguments if self.scatter: scatter_kws["label"] = self.label else: line_kws["label"] = self.label # Use the current color cycle state as a default if self.color is None: lines, = plt.plot(self.x.mean(), self.y.mean()) color = lines.get_color() lines.remove() else: color = self.color # Let color in keyword arguments override overall plot color scatter_kws.setdefault("color", color) line_kws.setdefault("color", color) # Draw the constituent plots if self.scatter: self.scatterplot(ax, scatter_kws) if self.fit_reg: self.lineplot(ax, line_kws) # Label the axes if hasattr(self.x, "name"): ax.set_xlabel(self.x.name) if hasattr(self.y, "name"): ax.set_ylabel(self.y.name) def scatterplot(self, ax, kws): """Draw the data.""" # Treat the line-based markers specially, explicitly setting larger # linewidth than is provided by the seaborn style defaults. # This would ideally be handled better in matplotlib (i.e., distinguish # between edgewidth for solid glyphs and linewidth for line glyphs # but this should do for now. line_markers = ["1", "2", "3", "4", "+", "x", "|", "_"] if self.x_estimator is None: if "marker" in kws and kws["marker"] in line_markers: lw = mpl.rcParams["lines.linewidth"] else: lw = mpl.rcParams["lines.markeredgewidth"] kws.setdefault("linewidths", lw) if not hasattr(kws['color'], 'shape') or kws['color'].shape[1] < 4: kws.setdefault("alpha", .8) x, y = self.scatter_data ax.scatter(x, y, **kws) else: # TODO abstraction ci_kws = {"color": kws["color"]} ci_kws["linewidth"] = mpl.rcParams["lines.linewidth"] * 1.75 kws.setdefault("s", 50) xs, ys, cis = self.estimate_data if [ci for ci in cis if ci is not None]: for x, ci in zip(xs, cis): ax.plot([x, x], ci, **ci_kws) ax.scatter(xs, ys, **kws) def lineplot(self, ax, kws): """Draw the model.""" xlim = ax.get_xlim() # Fit the regression model grid, yhat, err_bands = self.fit_regression(ax) # Get set default aesthetics fill_color = kws["color"] lw = kws.pop("lw", mpl.rcParams["lines.linewidth"] * 1.5) kws.setdefault("linewidth", lw) # Draw the regression line and confidence interval ax.plot(grid, yhat, **kws) if err_bands is not None: ax.fill_between(grid, *err_bands, color=fill_color, alpha=.15) ax.set_xlim(*xlim) def lmplot(x, y, data, hue=None, col=None, row=None, palette=None, col_wrap=None, size=5, aspect=1, markers="o", sharex=True, sharey=True, hue_order=None, col_order=None, row_order=None, dropna=True, legend=True, legend_out=True, **kwargs): """Plot a data and a regression model fit onto a FacetGrid. Parameters ---------- x, y : strings Column names in ``data``. data : DataFrame Long-form (tidy) dataframe with variables in columns and observations in rows. hue, col, row : strings, optional Variable names to facet on the hue, col, or row dimensions (see :class:`FacetGrid` docs for more information). palette : seaborn palette or dict, optional Color palette if using a `hue` facet. Should be something that seaborn.color_palette can read, or a dictionary mapping values of the hue variable to matplotlib colors. col_wrap : int, optional Wrap the column variable at this width. Incompatible with `row`. size : scalar, optional Height (in inches) of each facet. aspect : scalar, optional Aspect * size gives the width (in inches) of each facet. markers : single matplotlib marker code or list, optional Either the marker to use for all datapoints or a list of markers with a length the same as the number of levels in the hue variable so that differently colored points will also have different scatterplot markers. share{x, y}: booleans, optional Lock the limits of the vertical and horizontal axes across the facets. {hue, col, row}_order: sequence of strings, optional Order to plot the values in the faceting variables in, otherwise sorts the unique values. dropna : boolean, optional Drop missing values from the data before plotting. legend : boolean, optional Draw a legend for the data when using a `hue` variable. legend_out: boolean, optional Draw the legend outside the grid of plots. kwargs : key, value pairs Other keyword arguments are pasted to :func:`regplot` Returns ------- facets : FacetGrid Returns the :class:`FacetGrid` instance with the plot on it for further tweaking. See Also -------- regplot : Axes-level function for plotting linear regressions. """ # Reduce the dataframe to only needed columns # Otherwise when dropna is True we could lose data because it is missing # in a column that isn't relevant to this plot units = kwargs.get("units", None) x_partial = kwargs.get("x_partial", None) y_partial = kwargs.get("y_partial", None) need_cols = [x, y, hue, col, row, units, x_partial, y_partial] cols = np.unique([a for a in need_cols if a is not None]).tolist() data = data[cols] # Initialize the grid facets = FacetGrid(data, row, col, hue, palette=palette, row_order=row_order, col_order=col_order, hue_order=hue_order, dropna=dropna, size=size, aspect=aspect, col_wrap=col_wrap, sharex=sharex, sharey=sharey, legend_out=legend_out) # Add the markers here as FacetGrid has figured out how many levels of the # hue variable are needed and we don't want to duplicate that process if facets.hue_names is None: n_markers = 1 else: n_markers = len(facets.hue_names) if not isinstance(markers, list): markers = [markers] * n_markers if len(markers) != n_markers: raise ValueError(("markers must be a singeton or a list of markers " "for each level of the hue variable")) facets.hue_kws = {"marker": markers} # Hack to set the x limits properly, which needs to happen here # because the extent of the regression estimate is determined # by the limits of the plot if sharex: for ax in facets.axes.flat: scatter = ax.scatter(data[x], np.ones(len(data)) * data[y].mean()) scatter.remove() # Draw the regression plot on each facet facets.map_dataframe(regplot, x, y, **kwargs) # Add a legend if legend and (hue is not None) and (hue not in [col, row]): facets.add_legend() return facets def regplot(x, y, data=None, x_estimator=None, x_bins=None, x_ci=95, scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=False, dropna=True, x_jitter=None, y_jitter=None, xlabel=None, ylabel=None, label=None, color=None, marker="o", scatter_kws=None, line_kws=None, ax=None): """Draw a scatter plot between x and y with a regression line. Parameters ---------- x : vector or string Data or column name in `data` for the predictor variable. y : vector or string Data or column name in `data` for the response variable. data : DataFrame, optional DataFrame to use if `x` and `y` are column names. x_estimator : function that aggregates a vector into one value, optional When `x` is a discrete variable, apply this estimator to the data at each value and plot the data as a series of point estimates and confidence intervals rather than a scatter plot. x_bins : int or vector, optional When `x` is a continuous variable, use the values in this vector (or a vector of evenly spaced values with this length) to discretize the data by assigning each point to the closest bin value. This applies only to the plot; the regression is fit to the original data. This implies that `x_estimator` is numpy.mean if not otherwise provided. x_ci: int between 0 and 100, optional Confidence interval to compute and draw around the point estimates when `x` is treated as a discrete variable. scatter : boolean, optional Draw the scatter plot or point estimates with CIs representing the observed data. fit_reg : boolean, optional If False, don't fit a regression; just draw the scatterplot. ci : int between 0 and 100 or None, optional Confidence interval to compute for regression estimate, which is drawn as translucent bands around the regression line. n_boot : int, optional Number of bootstrap resamples used to compute the confidence intervals. units : vector or string Data or column name in `data` with ids for sampling units, so that the bootstrap is performed by resampling units and then observations within units for more accurate confidence intervals when data have repeated measures. order : int, optional Order of the polynomial to fit. Use order > 1 to explore higher-order trends in the relationship. logistic : boolean, optional Fit a logistic regression model. This requires `y` to be dichotomous with values of either 0 or 1. lowess : boolean, optional Plot a lowess model (locally weighted nonparametric regression). robust : boolean, optional Fit a robust linear regression, which may be useful when the data appear to have outliers. logx : boolean, optional Fit the regression in log(x) space. {x, y}_partial : matrix or string(s) , optional Matrix with same first dimension as `x`, or column name(s) in `data`. These variables are treated as confounding and are removed from the `x` or `y` variables before plotting. truncate : boolean, optional If True, truncate the regression estimate at the minimum and maximum values of the `x` variable. dropna : boolean, optional Remove observations that are NA in at least one of the variables. {x, y}_jitter : floats, optional Add uniform random noise from within this range (in data coordinates) to each datapoint in the x and/or y direction. This can be helpful when plotting discrete values. label : string, optional Label to use for the regression line, or for the scatterplot if not fitting a regression. color : matplotlib color, optional Color to use for all elements of the plot. Can set the scatter and regression colors separately using the `kws` dictionaries. If not provided, the current color in the axis cycle is used. marker : matplotlib marker code, optional Marker to use for the scatterplot points. {scatter, line}_kws : dictionaries, optional Additional keyword arguments passed to scatter() and plot() for drawing the components of the plot. ax : matplotlib axis, optional Plot into this axis, otherwise grab the current axis or make a new one if not existing. Returns ------- ax: matplotlib axes Axes with the regression plot. See Also -------- lmplot : Combine regplot and a FacetGrid. residplot : Calculate and plot the residuals of a linear model. jointplot (with kind="reg"): Draw a regplot with univariate marginal distrbutions. """ plotter = _RegressionPlotter(x, y, data, x_estimator, x_bins, x_ci, scatter, fit_reg, ci, n_boot, units, order, logistic, lowess, robust, logx, x_partial, y_partial, truncate, dropna, x_jitter, y_jitter, color, label) if ax is None: ax = plt.gca() scatter_kws = {} if scatter_kws is None else copy.copy(scatter_kws) scatter_kws["marker"] = marker line_kws = {} if line_kws is None else copy.copy(line_kws) plotter.plot(ax, scatter_kws, line_kws) return ax def residplot(x, y, data=None, lowess=False, x_partial=None, y_partial=None, order=1, robust=False, dropna=True, label=None, color=None, scatter_kws=None, line_kws=None, ax=None): """Plot the residuals of a linear regression. This function will regress y on x (possibly as a robust or polynomial regression) and then draw a scatterplot of the residuals. You can optionally fit a lowess smoother to the residual plot, which can help in determining if there is structure to the residuals. Parameters ---------- x : vector or string Data or column name in `data` for the predictor variable. y : vector or string Data or column name in `data` for the response variable. data : DataFrame, optional DataFrame to use if `x` and `y` are column names. lowess : boolean, optional Fit a lowess smoother to the residual scatterplot. {x, y}_partial : matrix or string(s) , optional Matrix with same first dimension as `x`, or column name(s) in `data`. These variables are treated as confounding and are removed from the `x` or `y` variables before plotting. order : int, optional Order of the polynomial to fit when calculating the residuals. robust : boolean, optional Fit a robust linear regression when calculating the residuals. dropna : boolean, optional If True, ignore observations with missing data when fitting and plotting. label : string, optional Label that will be used in any plot legends. color : matplotlib color, optional Color to use for all elements of the plot. {scatter, line}_kws : dictionaries, optional Additional keyword arguments passed to scatter() and plot() for drawing the components of the plot. ax : matplotlib axis, optional Plot into this axis, otherwise grab the current axis or make a new one if not existing. Returns ------- ax: matplotlib axes Axes with the regression plot. See Also -------- regplot : Plot a simple linear regression model. jointplot (with kind="resid"): Draw a residplot with univariate marginal distrbutions. """ plotter = _RegressionPlotter(x, y, data, ci=None, order=order, robust=robust, x_partial=x_partial, y_partial=y_partial, dropna=dropna, color=color, label=label) if ax is None: ax = plt.gca() # Calculate the residual from a linear regression _, yhat, _ = plotter.fit_regression(grid=plotter.x) plotter.y = plotter.y - yhat # Set the regression option on the plotter if lowess: plotter.lowess = True else: plotter.fit_reg = False # Plot a horizontal line at 0 ax.axhline(0, ls=":", c=".2") # Draw the scatterplot scatter_kws = {} if scatter_kws is None else scatter_kws line_kws = {} if line_kws is None else line_kws plotter.plot(ax, scatter_kws, line_kws) return ax def coefplot(formula, data, groupby=None, intercept=False, ci=95, palette="husl"): """Plot the coefficients from a linear model. Parameters ---------- formula : string patsy formula for ols model data : dataframe data for the plot; formula terms must appear in columns groupby : grouping object, optional object to group data with to fit conditional models intercept : bool, optional if False, strips the intercept term before plotting ci : float, optional size of confidence intervals palette : seaborn color palette, optional palette for the horizonal plots """ if not _has_statsmodels: raise ImportError("The `coefplot` function requires statsmodels") import statsmodels.formula.api as sf alpha = 1 - ci / 100 if groupby is None: coefs = sf.ols(formula, data).fit().params cis = sf.ols(formula, data).fit().conf_int(alpha) else: grouped = data.groupby(groupby) coefs = grouped.apply(lambda d: sf.ols(formula, d).fit().params).T cis = grouped.apply(lambda d: sf.ols(formula, d).fit().conf_int(alpha)) # Possibly ignore the intercept if not intercept: coefs = coefs.ix[1:] n_terms = len(coefs) # Plot seperately depending on groupby w, h = mpl.rcParams["figure.figsize"] hsize = lambda n: n * (h / 2) wsize = lambda n: n * (w / (4 * (n / 5))) if groupby is None: colors = itertools.cycle(color_palette(palette, n_terms)) f, ax = plt.subplots(1, 1, figsize=(wsize(n_terms), hsize(1))) for i, term in enumerate(coefs.index): color = next(colors) low, high = cis.ix[term] ax.plot([i, i], [low, high], c=color, solid_capstyle="round", lw=2.5) ax.plot(i, coefs.ix[term], "o", c=color, ms=8) ax.set_xlim(-.5, n_terms - .5) ax.axhline(0, ls="--", c="dimgray") ax.set_xticks(range(n_terms)) ax.set_xticklabels(coefs.index) else: n_groups = len(coefs.columns) f, axes = plt.subplots(n_terms, 1, sharex=True, figsize=(wsize(n_groups), hsize(n_terms))) if n_terms == 1: axes = [axes] colors = itertools.cycle(color_palette(palette, n_groups)) for ax, term in zip(axes, coefs.index): for i, group in enumerate(coefs.columns): color = next(colors) low, high = cis.ix[(group, term)] ax.plot([i, i], [low, high], c=color, solid_capstyle="round", lw=2.5) ax.plot(i, coefs.loc[term, group], "o", c=color, ms=8) ax.set_xlim(-.5, n_groups - .5) ax.axhline(0, ls="--", c="dimgray") ax.set_title(term) ax.set_xlabel(groupby) ax.set_xticks(range(n_groups)) ax.set_xticklabels(coefs.columns) def interactplot(x1, x2, y, data=None, filled=False, cmap="RdBu_r", colorbar=True, levels=30, logistic=False, contour_kws=None, scatter_kws=None, ax=None, **kwargs): """Visualize a continuous two-way interaction with a contour plot. Parameters ---------- x1, x2, y, strings or array-like Either the two independent variables and the dependent variable, or keys to extract them from `data` data : DataFrame Pandas DataFrame with the data in the columns. filled : bool Whether to plot with filled or unfilled contours cmap : matplotlib colormap Colormap to represent yhat in the countour plot. colorbar : bool Whether to draw the colorbar for interpreting the color values. levels : int or sequence Number or position of contour plot levels. logistic : bool Fit a logistic regression model instead of linear regression. contour_kws : dictionary Keyword arguments for contour[f](). scatter_kws : dictionary Keyword arguments for plot(). ax : matplotlib axis Axis to draw plot in. Returns ------- ax : Matplotlib axis Axis with the contour plot. """ if not _has_statsmodels: raise ImportError("The `interactplot` function requires statsmodels") from statsmodels.regression.linear_model import OLS from statsmodels.genmod.generalized_linear_model import GLM from statsmodels.genmod.families import Binomial # Handle the form of the data if data is not None: x1 = data[x1] x2 = data[x2] y = data[y] if hasattr(x1, "name"): xlabel = x1.name else: xlabel = None if hasattr(x2, "name"): ylabel = x2.name else: ylabel = None if hasattr(y, "name"): clabel = y.name else: clabel = None x1 = np.asarray(x1) x2 = np.asarray(x2) y = np.asarray(y) # Initialize the scatter keyword dictionary if scatter_kws is None: scatter_kws = {} if not ("color" in scatter_kws or "c" in scatter_kws): scatter_kws["color"] = "#222222" if "alpha" not in scatter_kws: scatter_kws["alpha"] = 0.75 # Intialize the contour keyword dictionary if contour_kws is None: contour_kws = {} # Initialize the axis if ax is None: ax = plt.gca() # Plot once to let matplotlib sort out the axis limits ax.plot(x1, x2, "o", **scatter_kws) # Find the plot limits x1min, x1max = ax.get_xlim() x2min, x2max = ax.get_ylim() # Make the grid for the contour plot x1_points = np.linspace(x1min, x1max, 100) x2_points = np.linspace(x2min, x2max, 100) xx1, xx2 = np.meshgrid(x1_points, x2_points) # Fit the model with an interaction X = np.c_[np.ones(x1.size), x1, x2, x1 * x2] if logistic: lm = GLM(y, X, family=Binomial()).fit() else: lm = OLS(y, X).fit() # Evaluate the model on the grid eval = np.vectorize(lambda x1_, x2_: lm.predict([1, x1_, x2_, x1_ * x2_])) yhat = eval(xx1, xx2) # Default color limits put the midpoint at mean(y) y_bar = y.mean() c_min = min(np.percentile(y, 2), yhat.min()) c_max = max(np.percentile(y, 98), yhat.max()) delta = max(c_max - y_bar, y_bar - c_min) c_min, cmax = y_bar - delta, y_bar + delta contour_kws.setdefault("vmin", c_min) contour_kws.setdefault("vmax", c_max) # Draw the contour plot func_name = "contourf" if filled else "contour" contour = getattr(ax, func_name) c = contour(xx1, xx2, yhat, levels, cmap=cmap, **contour_kws) # Draw the scatter again so it's visible ax.plot(x1, x2, "o", **scatter_kws) # Draw a colorbar, maybe if colorbar: bar = plt.colorbar(c) # Label the axes if xlabel is not None: ax.set_xlabel(xlabel) if ylabel is not None: ax.set_ylabel(ylabel) if clabel is not None and colorbar: clabel = "P(%s)" % clabel if logistic else clabel bar.set_label(clabel, labelpad=15, rotation=270) return ax def corrplot(data, names=None, annot=True, sig_stars=True, sig_tail="both", sig_corr=True, cmap=None, cmap_range=None, cbar=True, diag_names=True, method=None, ax=None, **kwargs): """Plot a correlation matrix with colormap and r values. Parameters ---------- data : Dataframe or nobs x nvars array Rectangular input data with variabes in the columns. names : sequence of strings Names to associate with variables if `data` is not a DataFrame. annot : bool Whether to annotate the upper triangle with correlation coefficients. sig_stars : bool If True, get significance with permutation test and denote with stars. sig_tail : both | upper | lower Direction for significance test. Also controls the default colorbar. sig_corr : bool If True, use FWE-corrected p values for the sig stars. cmap : colormap Colormap name as string or colormap object. cmap_range : None, "full", (low, high) Either truncate colormap at (-max(abs(r)), max(abs(r))), use the full range (-1, 1), or specify (min, max) values for the colormap. cbar : bool If true, plot the colorbar legend. method: None (pearson) | kendall | spearman Correlation method to compute pairwise correlations. Methods other than the default pearson correlation will not have a significance computed. ax : matplotlib axis Axis to draw plot in. kwargs : other keyword arguments Passed to ax.matshow() Returns ------- ax : matplotlib axis Axis object with plot. """ if not isinstance(data, pd.DataFrame): if names is None: names = ["var_%d" % i for i in range(data.shape[1])] data = pd.DataFrame(data, columns=names, dtype=np.float) # Calculate the correlation matrix of the dataframe if method is None: corrmat = data.corr() else: corrmat = data.corr(method=method) # Pandas will drop non-numeric columns; let's keep track of that operation names = corrmat.columns data = data[names] # Get p values with a permutation test if annot and sig_stars and method is None: p_mat = algo.randomize_corrmat(data.values.T, sig_tail, sig_corr) else: p_mat = None # Sort out the color range if cmap_range is None: triu = np.triu_indices(len(corrmat), 1) vmax = min(1, np.max(np.abs(corrmat.values[triu])) * 1.15) vmin = -vmax if sig_tail == "both": cmap_range = vmin, vmax elif sig_tail == "upper": cmap_range = 0, vmax elif sig_tail == "lower": cmap_range = vmin, 0 elif cmap_range == "full": cmap_range = (-1, 1) # Find a colormapping, somewhat intelligently if cmap is None: if min(cmap_range) >= 0: cmap = "OrRd" elif max(cmap_range) <= 0: cmap = "PuBu_r" else: cmap = "coolwarm" if cmap == "jet": # Paternalism raise ValueError("Never use the 'jet' colormap!") # Plot using the more general symmatplot function ax = symmatplot(corrmat, p_mat, names, cmap, cmap_range, cbar, annot, diag_names, ax, **kwargs) return ax def symmatplot(mat, p_mat=None, names=None, cmap="Greys", cmap_range=None, cbar=True, annot=True, diag_names=True, ax=None, **kwargs): """Plot a symmetric matrix with colormap and statistic values.""" if ax is None: ax = plt.gca() nvars = len(mat) if isinstance(mat, pd.DataFrame): plotmat = mat.values.copy() mat = mat.values else: plotmat = mat.copy() plotmat[np.triu_indices(nvars)] = np.nan if cmap_range is None: vmax = np.nanmax(plotmat) * 1.15 vmin = np.nanmin(plotmat) * 1.15 elif len(cmap_range) == 2: vmin, vmax = cmap_range else: raise ValueError("cmap_range argument not understood") mat_img = ax.matshow(plotmat, cmap=cmap, vmin=vmin, vmax=vmax, **kwargs) if cbar: plt.colorbar(mat_img, shrink=.75) if p_mat is None: p_mat = np.ones((nvars, nvars)) if annot: for i, j in zip(*np.triu_indices(nvars, 1)): val = mat[i, j] stars = utils.sig_stars(p_mat[i, j]) ax.text(j, i, "\n%.2g\n%s" % (val, stars), fontdict=dict(ha="center", va="center")) else: fill = np.ones_like(plotmat) fill[np.tril_indices_from(fill, -1)] = np.nan ax.matshow(fill, cmap="Greys", vmin=0, vmax=0, zorder=2) if names is None: names = ["var%d" % i for i in range(nvars)] if diag_names: for i, name in enumerate(names): ax.text(i, i, name, fontdict=dict(ha="center", va="center", weight="bold", rotation=45)) ax.set_xticklabels(()) ax.set_yticklabels(()) else: ax.xaxis.set_ticks_position("bottom") xnames = names if annot else names[:-1] ax.set_xticklabels(xnames, rotation=90) ynames = names if annot else names[1:] ax.set_yticklabels(ynames) minor_ticks = np.linspace(-.5, nvars - 1.5, nvars) ax.set_xticks(minor_ticks, True) ax.set_yticks(minor_ticks, True) major_ticks = np.linspace(0, nvars - 1, nvars) xticks = major_ticks if annot else major_ticks[:-1] ax.set_xticks(xticks) yticks = major_ticks if annot else major_ticks[1:] ax.set_yticks(yticks) ax.grid(False, which="major") ax.grid(True, which="minor", linestyle="-") return ax def pairplot(data, hue=None, hue_order=None, palette=None, vars=None, x_vars=None, y_vars=None, kind="scatter", diag_kind="hist", markers=None, size=3, aspect=1, dropna=True, plot_kws=None, diag_kws=None, grid_kws=None): """Plot pairwise relationships in a dataset. Parameters ---------- data : DataFrame Tidy (long-form) dataframe where each column is a variable and each row is an observation. hue : string (variable name), optional Variable in ``data`` to map plot aspects to different colors. hue_order : list of strings Order for the levels of the hue variable in the palette palette : dict or seaborn color palette Set of colors for mapping the ``hue`` variable. If a dict, keys should be values in the ``hue`` variable. vars : list of variable names, optional Variables within ``data`` to use, otherwise use every column with a numeric datatype. {x, y}_vars : lists of variable names, optional Variables within ``data`` to use separately for the rows and columns of the figure; i.e. to make a non-square plot. kind : {'scatter', 'reg'}, optional Kind of plot for the non-identity relationships. diag_kind : {'hist', 'kde'}, optional Kind of plot for the diagonal subplots. markers : single matplotlib marker code or list, optional Either the marker to use for all datapoints or a list of markers with a length the same as the number of levels in the hue variable so that differently colored points will also have different scatterplot markers. size : scalar, optional Height (in inches) of each facet. aspect : scalar, optional Aspect * size gives the width (in inches) of each facet. dropna : boolean, optional Drop missing values from the data before plotting. {plot, diag, grid}_kws : dicts, optional Dictionaries of keyword arguments. Returns ------- grid : PairGrid Returns the underlying ``PairGrid`` instance for further tweaking. See Also -------- PairGrid : Subplot grid for more flexible plotting of pairwise relationships. """ if plot_kws is None: plot_kws = {} if diag_kws is None: diag_kws = {} if grid_kws is None: grid_kws = {} # Set up the PairGrid diag_sharey = diag_kind == "hist" grid = PairGrid(data, vars=vars, x_vars=x_vars, y_vars=y_vars, hue=hue, hue_order=hue_order, palette=palette, diag_sharey=diag_sharey, size=size, aspect=aspect, dropna=dropna, **grid_kws) # Add the markers here as PairGrid has figured out how many levels of the # hue variable are needed and we don't want to duplicate that process if markers is not None: if grid.hue_names is None: n_markers = 1 else: n_markers = len(grid.hue_names) if not isinstance(markers, list): markers = [markers] * n_markers if len(markers) != n_markers: raise ValueError(("markers must be a singeton or a list of markers" " for each level of the hue variable")) grid.hue_kws = {"marker": markers} # Maybe plot on the diagonal if grid.square_grid: if diag_kind == "hist": grid.map_diag(plt.hist, **diag_kws) elif diag_kind == "kde": diag_kws["legend"] = False grid.map_diag(kdeplot, **diag_kws) # Maybe plot on the off-diagonals if grid.square_grid and diag_kind is not None: plotter = grid.map_offdiag else: plotter = grid.map if kind == "scatter": plot_kws.setdefault("edgecolor", "white") plotter(plt.scatter, **plot_kws) elif kind == "reg": plotter(regplot, **plot_kws) # Add a legend if hue is not None: grid.add_legend() return grid
bsd-3-clause
yosssi/scipy_2015_sklearn_tutorial
notebooks/solutions/06B_learning_curves.py
21
1448
from sklearn.metrics import explained_variance_score, mean_squared_error from sklearn.cross_validation import train_test_split def plot_learning_curve(model, err_func=explained_variance_score, N=300, n_runs=10, n_sizes=50, ylim=None): sizes = np.linspace(5, N, n_sizes).astype(int) train_err = np.zeros((n_runs, n_sizes)) validation_err = np.zeros((n_runs, n_sizes)) for i in range(n_runs): for j, size in enumerate(sizes): xtrain, xtest, ytrain, ytest = train_test_split( X, y, train_size=size, random_state=i) # Train on only the first `size` points model.fit(xtrain, ytrain) validation_err[i, j] = err_func(ytest, model.predict(xtest)) train_err[i, j] = err_func(ytrain, model.predict(xtrain)) plt.plot(sizes, validation_err.mean(axis=0), lw=2, label='validation') plt.plot(sizes, train_err.mean(axis=0), lw=2, label='training') plt.xlabel('traning set size') plt.ylabel(err_func.__name__.replace('_', ' ')) plt.grid(True) plt.legend(loc=0) plt.xlim(0, N-1) if ylim: plt.ylim(ylim) plt.figure(figsize=(10, 8)) for i, model in enumerate([Lasso(0.01), Ridge(0.06)]): plt.subplot(221 + i) plot_learning_curve(model, ylim=(0, 1)) plt.title(model.__class__.__name__) plt.subplot(223 + i) plot_learning_curve(model, err_func=mean_squared_error, ylim=(0, 8000))
cc0-1.0
sandeepkrjha/pgmpy
pgmpy/estimators/ExhaustiveSearch.py
5
8140
#!/usr/bin/env python from warnings import warn from itertools import combinations import networkx as nx from pgmpy.estimators import StructureEstimator from pgmpy.estimators import K2Score from pgmpy.utils.mathext import powerset from pgmpy.models import BayesianModel class ExhaustiveSearch(StructureEstimator): def __init__(self, data, scoring_method=None, **kwargs): """ Search class for exhaustive searches over all BayesianModels with a given set of variables. Takes a `StructureScore`-Instance as parameter; `estimate` finds the model with maximal score. Parameters ---------- data: pandas DataFrame object datafame object where each column represents one variable. (If some values in the data are missing the data cells should be set to `numpy.NaN`. Note that pandas converts each column containing `numpy.NaN`s to dtype `float`.) scoring_method: Instance of a `StructureScore`-subclass (`K2Score` is used as default) An instance of `K2Score`, `BdeuScore`, or `BicScore`. This score is optimized during structure estimation by the `estimate`-method. state_names: dict (optional) A dict indicating, for each variable, the discrete set of states (or values) that the variable can take. If unspecified, the observed values in the data set are taken to be the only possible states. complete_samples_only: bool (optional, default `True`) Specifies how to deal with missing data, if present. If set to `True` all rows that contain `np.Nan` somewhere are ignored. If `False` then, for each variable, every row where neither the variable nor its parents are `np.NaN` is used. This sets the behavior of the `state_count`-method. """ if scoring_method is not None: self.scoring_method = scoring_method else: self.scoring_method = K2Score(data, **kwargs) super(ExhaustiveSearch, self).__init__(data, **kwargs) def all_dags(self, nodes=None): """ Computes all possible directed acyclic graphs with a given set of nodes, sparse ones first. `2**(n*(n-1))` graphs need to be searched, given `n` nodes, so this is likely not feasible for n>6. This is a generator. Parameters ---------- nodes: list of nodes for the DAGs (optional) A list of the node names that the generated DAGs should have. If not provided, nodes are taken from data. Returns ------- dags: Generator object for nx.DiGraphs Generator that yields all acyclic nx.DiGraphs, ordered by number of edges. Empty DAG first. Examples -------- >>> import pandas as pd >>> from pgmpy.estimators import ExhaustiveSearch >>> s = ExhaustiveSearch(pd.DataFrame(data={'Temperature': [23, 19], 'Weather': ['sunny', 'cloudy'], 'Humidity': [65, 75]})) >>> list(s.all_dags()) [<networkx.classes.digraph.DiGraph object at 0x7f6955216438>, <networkx.classes.digraph.DiGraph object at 0x7f6955216518>, .... >>> [dag.edges() for dag in s.all_dags()] [[], [('Humidity', 'Temperature')], [('Humidity', 'Weather')], [('Temperature', 'Weather')], [('Temperature', 'Humidity')], .... [('Weather', 'Humidity'), ('Weather', 'Temperature'), ('Temperature', 'Humidity')]] """ if nodes is None: nodes = sorted(self.state_names.keys()) if len(nodes) > 6: warn("Generating all DAGs of n nodes likely not feasible for n>6!") warn("Attempting to search through {0} graphs".format(2**(len(nodes)*(len(nodes)-1)))) edges = list(combinations(nodes, 2)) # n*(n-1) possible directed edges edges.extend([(y, x) for x, y in edges]) all_graphs = powerset(edges) # 2^(n*(n-1)) graphs for graph_edges in all_graphs: graph = nx.DiGraph() graph.add_nodes_from(nodes) graph.add_edges_from(graph_edges) if nx.is_directed_acyclic_graph(graph): yield graph def all_scores(self): """ Computes a list of DAGs and their structure scores, ordered by score. Returns ------- list: a list of (score, dag) pairs A list of (score, dag)-tuples, where score is a float and model a acyclic nx.DiGraph. The list is ordered by score values. Examples -------- >>> import pandas as pd >>> import numpy as np >>> from pgmpy.estimators import ExhaustiveSearch, K2Score >>> # create random data sample with 3 variables, where B and C are identical: >>> data = pd.DataFrame(np.random.randint(0, 5, size=(5000, 2)), columns=list('AB')) >>> data['C'] = data['B'] >>> searcher = ExhaustiveSearch(data, scoring_method=K2Score(data)) >>> for score, model in searcher.all_scores(): ... print("{0}\t{1}".format(score, model.edges())) -24234.44977974726 [('A', 'B'), ('A', 'C')] -24234.449760691063 [('A', 'B'), ('C', 'A')] -24234.449760691063 [('A', 'C'), ('B', 'A')] -24203.700955937973 [('A', 'B')] -24203.700955937973 [('A', 'C')] -24203.700936881774 [('B', 'A')] -24203.700936881774 [('C', 'A')] -24203.700936881774 [('B', 'A'), ('C', 'A')] -24172.952132128685 [] -16597.30920265254 [('A', 'B'), ('A', 'C'), ('B', 'C')] -16597.30920265254 [('A', 'B'), ('A', 'C'), ('C', 'B')] -16597.309183596342 [('A', 'B'), ('C', 'A'), ('C', 'B')] -16597.309183596342 [('A', 'C'), ('B', 'A'), ('B', 'C')] -16566.560378843253 [('A', 'B'), ('C', 'B')] -16566.560378843253 [('A', 'C'), ('B', 'C')] -16268.324549347722 [('A', 'B'), ('B', 'C')] -16268.324549347722 [('A', 'C'), ('C', 'B')] -16268.324530291524 [('B', 'A'), ('B', 'C')] -16268.324530291524 [('B', 'C'), ('C', 'A')] -16268.324530291524 [('B', 'A'), ('C', 'B')] -16268.324530291524 [('C', 'A'), ('C', 'B')] -16268.324530291524 [('B', 'A'), ('B', 'C'), ('C', 'A')] -16268.324530291524 [('B', 'A'), ('C', 'A'), ('C', 'B')] -16237.575725538434 [('B', 'C')] -16237.575725538434 [('C', 'B')] """ scored_dags = sorted([(self.scoring_method.score(dag), dag) for dag in self.all_dags()], key=lambda x: x[0]) return scored_dags def estimate(self): """ Estimates the `BayesianModel` structure that fits best to the given data set, according to the scoring method supplied in the constructor. Exhaustively searches through all models. Only estimates network structure, no parametrization. Returns ------- model: `BayesianModel` instance A `BayesianModel` with maximal score. Examples -------- >>> import pandas as pd >>> import numpy as np >>> from pgmpy.estimators import ExhaustiveSearch >>> # create random data sample with 3 variables, where B and C are identical: >>> data = pd.DataFrame(np.random.randint(0, 5, size=(5000, 2)), columns=list('AB')) >>> data['C'] = data['B'] >>> est = ExhaustiveSearch(data) >>> best_model = est.estimate() >>> best_model <pgmpy.models.BayesianModel.BayesianModel object at 0x7f695c535470> >>> best_model.edges() [('B', 'C')] """ best_dag = max(self.all_dags(), key=self.scoring_method.score) best_model = BayesianModel() best_model.add_nodes_from(sorted(best_dag.nodes())) best_model.add_edges_from(sorted(best_dag.edges())) return best_model
mit
ArnaudBelcour/Workflow_GeneList_Analysis
pathway_extraction/database_mapping_from_gos.py
1
2431
#!/usr/bin/env python3 import csv import pandas as pa from tqdm import tqdm from . import * def request_gene_ontology(url, file_name): """ Requests the Gene Ontology server to obtain mapping file between GO and Interpro, KEGG, Enzyme Code, MetaCyc. Rewrites each file into a correct tsv file. """ if file_name == 'metacyc_go_mapping': id_name = 'metacyc_pathway' id_prefix = 'MetaCyc:' elif file_name == 'reactome_go_mapping': id_name = 'reactome_pathway' id_prefix = 'Reactome:' elif file_name == 'kegg_go_mapping': id_name = 'kegg_pathway' id_prefix = 'KEGG:' elif file_name == 'interpro_go_mapping': id_name = 'interpro' id_prefix = 'InterPro:' elif file_name == 'eccode_go_mapping': id_name = 'ec_code' id_prefix = 'EC:' if file_name in ['metacyc_go_mapping', 'reactome_go_mapping', 'kegg_go_mapping', 'eccode_go_mapping']: df = pa.read_csv(url, sep=' > | ; ', skiprows=2, header=None, engine='python') elif file_name == 'interpro_go_mapping': df = pa.read_csv(url, sep=' > | ; ', skiprows=6, header=None, engine='python') df.columns = [[id_name, 'go_label', 'GOs']] df[id_name] = df[id_name].str.replace(id_prefix, "") df[id_name] = df[id_name].str.strip(to_strip='+-') if id_name == "interpro": df[id_name] = [interpro[:9] for interpro in df[id_name]] if id_name == "ec_code": df[id_name] = ['ec:'+ec for ec in df[id_name]] df['go_label'] = df['go_label'].str.replace("GO:", "") df['go_label'] = df['go_label'].str.strip(to_strip='+-') df.to_csv(temporary_directory_database + file_name + ".tsv", sep='\t', index=False, header=True, quoting=csv.QUOTE_NONE) def main(): databases_gos_mapping = {'metacyc_go_mapping': 'http://geneontology.org/external2go/metacyc2go', 'reactome_go_mapping': 'http://geneontology.org/external2go/reactome2go', 'kegg_go_mapping': 'http://geneontology.org/external2go/kegg2go', 'interpro_go_mapping': 'http://geneontology.org/external2go/interpro2go', 'eccode_go_mapping': 'http://geneontology.org/external2go/ec2go', } for database in tqdm(databases_gos_mapping): request_gene_ontology(databases_gos_mapping[database], database)
agpl-3.0
pschella/scipy
doc/source/tutorial/stats/plots/kde_plot3.py
132
1229
import numpy as np import matplotlib.pyplot as plt from scipy import stats np.random.seed(12456) x1 = np.random.normal(size=200) # random data, normal distribution xs = np.linspace(x1.min()-1, x1.max()+1, 200) kde1 = stats.gaussian_kde(x1) kde2 = stats.gaussian_kde(x1, bw_method='silverman') fig = plt.figure(figsize=(8, 6)) ax1 = fig.add_subplot(211) ax1.plot(x1, np.zeros(x1.shape), 'b+', ms=12) # rug plot ax1.plot(xs, kde1(xs), 'k-', label="Scott's Rule") ax1.plot(xs, kde2(xs), 'b-', label="Silverman's Rule") ax1.plot(xs, stats.norm.pdf(xs), 'r--', label="True PDF") ax1.set_xlabel('x') ax1.set_ylabel('Density') ax1.set_title("Normal (top) and Student's T$_{df=5}$ (bottom) distributions") ax1.legend(loc=1) x2 = stats.t.rvs(5, size=200) # random data, T distribution xs = np.linspace(x2.min() - 1, x2.max() + 1, 200) kde3 = stats.gaussian_kde(x2) kde4 = stats.gaussian_kde(x2, bw_method='silverman') ax2 = fig.add_subplot(212) ax2.plot(x2, np.zeros(x2.shape), 'b+', ms=12) # rug plot ax2.plot(xs, kde3(xs), 'k-', label="Scott's Rule") ax2.plot(xs, kde4(xs), 'b-', label="Silverman's Rule") ax2.plot(xs, stats.t.pdf(xs, 5), 'r--', label="True PDF") ax2.set_xlabel('x') ax2.set_ylabel('Density') plt.show()
bsd-3-clause
Bitl/RBXLegacy-src
Cut/RBXLegacyDiscordBot/lib/youtube_dl/extractor/wsj.py
19
4502
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( int_or_none, float_or_none, unified_strdate, ) class WSJIE(InfoExtractor): _VALID_URL = r'''(?x) (?: https?://video-api\.wsj\.com/api-video/player/iframe\.html\?.*?\bguid=| https?://(?:www\.)?(?:wsj|barrons)\.com/video/[^/]+/| wsj: ) (?P<id>[a-fA-F0-9-]{36}) ''' IE_DESC = 'Wall Street Journal' _TESTS = [{ 'url': 'http://video-api.wsj.com/api-video/player/iframe.html?guid=1BD01A4C-BFE8-40A5-A42F-8A8AF9898B1A', 'md5': 'e230a5bb249075e40793b655a54a02e4', 'info_dict': { 'id': '1BD01A4C-BFE8-40A5-A42F-8A8AF9898B1A', 'ext': 'mp4', 'upload_date': '20150202', 'uploader_id': 'jdesai', 'creator': 'jdesai', 'categories': list, # a long list 'duration': 90, 'title': 'Bills Coach Rex Ryan Updates His Old Jets Tattoo', }, }, { 'url': 'http://www.wsj.com/video/can-alphabet-build-a-smarter-city/359DDAA8-9AC1-489C-82E6-0429C1E430E0.html', 'only_matching': True, }, { 'url': 'http://www.barrons.com/video/capitalism-deserves-more-respect-from-millennials/F301217E-6F46-43AE-B8D2-B7180D642EE9.html', 'only_matching': True, }] def _real_extract(self, url): video_id = self._match_id(url) info = self._download_json( 'http://video-api.wsj.com/api-video/find_all_videos.asp', video_id, query={ 'type': 'guid', 'count': 1, 'query': video_id, 'fields': ','.join(( 'type', 'hls', 'videoMP4List', 'thumbnailList', 'author', 'description', 'name', 'duration', 'videoURL', 'titletag', 'formattedCreationDate', 'keywords', 'editor')), })['items'][0] title = info.get('name', info.get('titletag')) formats = [] f4m_url = info.get('videoURL') if f4m_url: formats.extend(self._extract_f4m_formats( f4m_url, video_id, f4m_id='hds', fatal=False)) m3u8_url = info.get('hls') if m3u8_url: formats.extend(self._extract_m3u8_formats( info['hls'], video_id, ext='mp4', entry_protocol='m3u8_native', m3u8_id='hls', fatal=False)) for v in info.get('videoMP4List', []): mp4_url = v.get('url') if not mp4_url: continue tbr = int_or_none(v.get('bitrate')) formats.append({ 'url': mp4_url, 'format_id': 'http' + ('-%d' % tbr if tbr else ''), 'tbr': tbr, 'width': int_or_none(v.get('width')), 'height': int_or_none(v.get('height')), 'fps': float_or_none(v.get('fps')), }) self._sort_formats(formats) return { 'id': video_id, 'formats': formats, # Thumbnails are conveniently in the correct format already 'thumbnails': info.get('thumbnailList'), 'creator': info.get('author'), 'uploader_id': info.get('editor'), 'duration': int_or_none(info.get('duration')), 'upload_date': unified_strdate(info.get( 'formattedCreationDate'), day_first=False), 'title': title, 'categories': info.get('keywords'), } class WSJArticleIE(InfoExtractor): _VALID_URL = r'(?i)https?://(?:www\.)?wsj\.com/articles/(?P<id>[^/?#&]+)' _TEST = { 'url': 'https://www.wsj.com/articles/dont-like-china-no-pandas-for-you-1490366939?', 'info_dict': { 'id': '4B13FA62-1D8C-45DB-8EA1-4105CB20B362', 'ext': 'mp4', 'upload_date': '20170221', 'uploader_id': 'ralcaraz', 'title': 'Bao Bao the Panda Leaves for China', } } def _real_extract(self, url): article_id = self._match_id(url) webpage = self._download_webpage(url, article_id) video_id = self._search_regex( r'data-src=["\']([a-fA-F0-9-]{36})', webpage, 'video id') return self.url_result('wsj:%s' % video_id, WSJIE.ie_key(), video_id)
gpl-3.0
mromanello/CitationExtractor
citation_extractor/ned/candidates.py
1
9851
# -*- coding: utf-8 -*- # author: Matteo Filipponi """Candidates Generation code related to the NED step.""" from __future__ import print_function import logging from citation_extractor.Utils.strmatching import StringSimilarity, StringUtils from citation_extractor.ned import AUTHOR_TYPE, WORK_TYPE, REFAUWORK_TYPE import pandas as pd LOGGER = logging.getLogger(__name__) try: # import dask from dask import delayed, compute from dask.multiprocessing import get as mp_get from dask.diagnostics import ProgressBar except ImportError: LOGGER.warning('Dask not installed') # TODO: we should define precise data-structures, # if we use pandas dataframes we should also enforce a schema and also define # column names as variables class CandidatesGenerator(object): """Generate entity candidates for a given mention.""" def __init__( self, kb, mention_surface_is_normalized=True, fuzzy_threshold=0.7, **kwargs ): """Initialize an instance of CandidatesGenerator. :param kb: an instance of HuCit KnowledgeBase :type kb: knowledge_base.KnowledgeBase :param mention_surface_is_normalized: specify whether mention surfaces are already normalized (default is True) :type mention_surface_is_normalized: bool :param fuzzy_threshold: specify the threshold to be used in fuzzy string matching (default is 0.7) :type fuzzy_threshold: float """ if 'kb_norm_authors' in kwargs and 'kb_norm_works' in kwargs: self._kb_norm_authors = kwargs['kb_norm_authors'] self._kb_norm_works = kwargs['kb_norm_works'] else: # TODO: make static the normalization methods of FeatureExtractor raise Exception self._surf_is_norm = mention_surface_is_normalized self._fuzzy_threshold = fuzzy_threshold self._authors_dict_names = None self._authors_dict_abbr = None self._works_dict_names = None self._works_dict_abbr = None self._build_name_abbr_dict() def _build_name_abbr_dict(self): """Map names/abbrev. to sets of entity URNs with those names/abbrev. This function initializes (in-place) the dictionaries that map author names to their URNs, author abbreviations to their URN, work names to their URNs and work abbreviations to their URNs. For example if two author entities share the same abbreviation. then the URNs of the two entities will be both present in the set mapped by that abbreviation key. """ LOGGER.info("Starting to build name/abbreviation indexes...") # Helper function: update a dataframe entry set with a new value def update_df_list(df, row, col, value): if row not in df.index: df.loc[row, col] = set() df.loc[row, col].add(value) authors_dict_names = pd.DataFrame( dtype='object', columns=['urns', 'len'] ) authors_dict_abbr = pd.DataFrame( dtype='object', columns=['urns', 'len'] ) # first, process all authors for aid, arow in self._kb_norm_authors.iterrows(): for n in arow.norm_names_clean: if n == u'': continue update_df_list(authors_dict_names, n, 'urns', aid) for a in arow.norm_abbr: if a == u'': continue update_df_list(authors_dict_abbr, a, 'urns', aid) for aid, arow in authors_dict_names.iterrows(): arow.len = len(arow.urns) for aid, arow in authors_dict_abbr.iterrows(): arow.len = len(arow.urns) authors_dict_names.sort_values('len', ascending=False, inplace=True) authors_dict_abbr.sort_values('len', ascending=False, inplace=True) works_dict_names = pd.DataFrame( dtype='object', columns=['urns', 'len'] ) works_dict_abbr = pd.DataFrame( dtype='object', columns=['urns', 'len'] ) # second, process all works for aid, arow in self._kb_norm_works.iterrows(): for n in arow.norm_titles_clean: if n == u'': continue update_df_list(works_dict_names, n, 'urns', aid) for a in arow.norm_abbr: if a == u'': continue update_df_list(works_dict_abbr, a, 'urns', aid) for aid, arow in works_dict_names.iterrows(): arow.len = len(arow.urns) for aid, arow in works_dict_abbr.iterrows(): arow.len = len(arow.urns) works_dict_names.sort_values('len', ascending=False, inplace=True) works_dict_abbr.sort_values('len', ascending=False, inplace=True) self._authors_dict_names = authors_dict_names self._authors_dict_abbr = authors_dict_abbr self._works_dict_names = works_dict_names self._works_dict_abbr = works_dict_abbr LOGGER.info("Done with creating name/abbreviation indexes.") def generate_candidates(self, mention_surface, mention_type, mention_scope): """Generate a set of entity candidates for a given mention. :param mention_surface: surface form of the mention :type mention_surface: unicode :param mention_type: type of the mention (AAUTHOR, AWORK, REFAUWORK) :type mention_type: str :param mention_scope: the scope of the mention (could be None) :type mention_scope: unicode :return: the URNs of the candidate entities :rtype: list of str """ def many_to_many_exact_match(surf, name): return len(set(surf.split()) & set(name.split())) > 0 def many_to_many_startswith(surf, name): for s in surf.split(): for n in name.split(): if n.startswith(s): return True return False def is_exact_acronym(acronym, name): return acronym == u''.join(map(lambda w: w[0], name.split())) def search_names(names_dict, surf): results = set() for n, row in names_dict.iterrows(): if n == surf: results.update(row.urns) elif StringSimilarity.levenshtein_distance_norm(n, surf) >= 0.7: results.update(row.urns) elif many_to_many_exact_match(surf, n): results.update(row.urns) elif many_to_many_startswith(surf, n): results.update(row.urns) elif is_exact_acronym(surf, n): results.update(row.urns) return results def search_abbr(abbr_dict, surf): results = set() for n, row in abbr_dict.iterrows(): if n == surf: results.update(row.urns) elif many_to_many_exact_match(surf, n): results.update(row.urns) return results candidates = set() norm_surface = mention_surface if not self._surf_is_norm: norm_surface = StringUtils.normalize(mention_surface) if mention_type == AUTHOR_TYPE and mention_scope: for aurn in search_names(self._authors_dict_names, norm_surface): candidates.update(self._kb_norm_authors.loc[aurn, 'works']) for aurn in search_abbr(self._authors_dict_abbr, norm_surface): candidates.update(self._kb_norm_authors.loc[aurn, 'works']) if mention_type == AUTHOR_TYPE and not mention_scope: candidates.update( search_names(self._authors_dict_names, norm_surface) ) candidates.update( search_abbr(self._authors_dict_abbr, norm_surface) ) if mention_type == WORK_TYPE: candidates.update( search_names(self._works_dict_names, norm_surface) ) candidates.update(search_abbr(self._works_dict_abbr, norm_surface)) if mention_type == REFAUWORK_TYPE: for aurn in search_names(self._authors_dict_names, norm_surface): candidates.update(self._kb_norm_authors.loc[aurn, 'works']) for aurn in search_abbr(self._authors_dict_abbr, norm_surface): candidates.update(self._kb_norm_authors.loc[aurn, 'works']) candidates.update( search_names(self._works_dict_names, norm_surface) ) candidates.update(search_abbr(self._works_dict_abbr, norm_surface)) return list(candidates) def generate_candidates_parallel(self, mentions): """Generate the entity candidates for a mention in parallel. :param mentions: a pandas Dataframe containing the mentions (min columns required: surface_norm, type, scope) :type mentions: pandas.DataFrame :return: the URNs of the candidate entities for each mention [(mention_id, set_of_candidates), ...] :rtype: list of tuples (str, list of str) """ tasks = [ ( m_id, delayed(self.generate_candidates)( row['surface_norm'], row['type'], row['scope'] ), ) for m_id, row in mentions.iterrows() ] print("Generating candidates in parallel") with ProgressBar(): result = compute(*tasks, scheduler='processes') candidates = { mention_id: candidate_set for mention_id, candidate_set in result } return candidates
gpl-3.0
yonglehou/scikit-learn
sklearn/cluster/bicluster.py
211
19443
"""Spectral biclustering algorithms. Authors : Kemal Eren License: BSD 3 clause """ from abc import ABCMeta, abstractmethod import numpy as np from scipy.sparse import dia_matrix from scipy.sparse import issparse from . import KMeans, MiniBatchKMeans from ..base import BaseEstimator, BiclusterMixin from ..externals import six from ..utils.arpack import eigsh, svds from ..utils.extmath import (make_nonnegative, norm, randomized_svd, safe_sparse_dot) from ..utils.validation import assert_all_finite, check_array __all__ = ['SpectralCoclustering', 'SpectralBiclustering'] def _scale_normalize(X): """Normalize ``X`` by scaling rows and columns independently. Returns the normalized matrix and the row and column scaling factors. """ X = make_nonnegative(X) row_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=1))).squeeze() col_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=0))).squeeze() row_diag = np.where(np.isnan(row_diag), 0, row_diag) col_diag = np.where(np.isnan(col_diag), 0, col_diag) if issparse(X): n_rows, n_cols = X.shape r = dia_matrix((row_diag, [0]), shape=(n_rows, n_rows)) c = dia_matrix((col_diag, [0]), shape=(n_cols, n_cols)) an = r * X * c else: an = row_diag[:, np.newaxis] * X * col_diag return an, row_diag, col_diag def _bistochastic_normalize(X, max_iter=1000, tol=1e-5): """Normalize rows and columns of ``X`` simultaneously so that all rows sum to one constant and all columns sum to a different constant. """ # According to paper, this can also be done more efficiently with # deviation reduction and balancing algorithms. X = make_nonnegative(X) X_scaled = X dist = None for _ in range(max_iter): X_new, _, _ = _scale_normalize(X_scaled) if issparse(X): dist = norm(X_scaled.data - X.data) else: dist = norm(X_scaled - X_new) X_scaled = X_new if dist is not None and dist < tol: break return X_scaled def _log_normalize(X): """Normalize ``X`` according to Kluger's log-interactions scheme.""" X = make_nonnegative(X, min_value=1) if issparse(X): raise ValueError("Cannot compute log of a sparse matrix," " because log(x) diverges to -infinity as x" " goes to 0.") L = np.log(X) row_avg = L.mean(axis=1)[:, np.newaxis] col_avg = L.mean(axis=0) avg = L.mean() return L - row_avg - col_avg + avg class BaseSpectral(six.with_metaclass(ABCMeta, BaseEstimator, BiclusterMixin)): """Base class for spectral biclustering.""" @abstractmethod def __init__(self, n_clusters=3, svd_method="randomized", n_svd_vecs=None, mini_batch=False, init="k-means++", n_init=10, n_jobs=1, random_state=None): self.n_clusters = n_clusters self.svd_method = svd_method self.n_svd_vecs = n_svd_vecs self.mini_batch = mini_batch self.init = init self.n_init = n_init self.n_jobs = n_jobs self.random_state = random_state def _check_parameters(self): legal_svd_methods = ('randomized', 'arpack') if self.svd_method not in legal_svd_methods: raise ValueError("Unknown SVD method: '{0}'. svd_method must be" " one of {1}.".format(self.svd_method, legal_svd_methods)) def fit(self, X): """Creates a biclustering for X. Parameters ---------- X : array-like, shape (n_samples, n_features) """ X = check_array(X, accept_sparse='csr', dtype=np.float64) self._check_parameters() self._fit(X) def _svd(self, array, n_components, n_discard): """Returns first `n_components` left and right singular vectors u and v, discarding the first `n_discard`. """ if self.svd_method == 'randomized': kwargs = {} if self.n_svd_vecs is not None: kwargs['n_oversamples'] = self.n_svd_vecs u, _, vt = randomized_svd(array, n_components, random_state=self.random_state, **kwargs) elif self.svd_method == 'arpack': u, _, vt = svds(array, k=n_components, ncv=self.n_svd_vecs) if np.any(np.isnan(vt)): # some eigenvalues of A * A.T are negative, causing # sqrt() to be np.nan. This causes some vectors in vt # to be np.nan. _, v = eigsh(safe_sparse_dot(array.T, array), ncv=self.n_svd_vecs) vt = v.T if np.any(np.isnan(u)): _, u = eigsh(safe_sparse_dot(array, array.T), ncv=self.n_svd_vecs) assert_all_finite(u) assert_all_finite(vt) u = u[:, n_discard:] vt = vt[n_discard:] return u, vt.T def _k_means(self, data, n_clusters): if self.mini_batch: model = MiniBatchKMeans(n_clusters, init=self.init, n_init=self.n_init, random_state=self.random_state) else: model = KMeans(n_clusters, init=self.init, n_init=self.n_init, n_jobs=self.n_jobs, random_state=self.random_state) model.fit(data) centroid = model.cluster_centers_ labels = model.labels_ return centroid, labels class SpectralCoclustering(BaseSpectral): """Spectral Co-Clustering algorithm (Dhillon, 2001). Clusters rows and columns of an array `X` to solve the relaxed normalized cut of the bipartite graph created from `X` as follows: the edge between row vertex `i` and column vertex `j` has weight `X[i, j]`. The resulting bicluster structure is block-diagonal, since each row and each column belongs to exactly one bicluster. Supports sparse matrices, as long as they are nonnegative. Read more in the :ref:`User Guide <spectral_coclustering>`. Parameters ---------- n_clusters : integer, optional, default: 3 The number of biclusters to find. svd_method : string, optional, default: 'randomized' Selects the algorithm for finding singular vectors. May be 'randomized' or 'arpack'. If 'randomized', use :func:`sklearn.utils.extmath.randomized_svd`, which may be faster for large matrices. If 'arpack', use :func:`sklearn.utils.arpack.svds`, which is more accurate, but possibly slower in some cases. n_svd_vecs : int, optional, default: None Number of vectors to use in calculating the SVD. Corresponds to `ncv` when `svd_method=arpack` and `n_oversamples` when `svd_method` is 'randomized`. mini_batch : bool, optional, default: False Whether to use mini-batch k-means, which is faster but may get different results. init : {'k-means++', 'random' or an ndarray} Method for initialization of k-means algorithm; defaults to 'k-means++'. n_init : int, optional, default: 10 Number of random initializations that are tried with the k-means algorithm. If mini-batch k-means is used, the best initialization is chosen and the algorithm runs once. Otherwise, the algorithm is run for each initialization and the best solution chosen. n_jobs : int, optional, default: 1 The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. random_state : int seed, RandomState instance, or None (default) A pseudo random number generator used by the K-Means initialization. Attributes ---------- rows_ : array-like, shape (n_row_clusters, n_rows) Results of the clustering. `rows[i, r]` is True if cluster `i` contains row `r`. Available only after calling ``fit``. columns_ : array-like, shape (n_column_clusters, n_columns) Results of the clustering, like `rows`. row_labels_ : array-like, shape (n_rows,) The bicluster label of each row. column_labels_ : array-like, shape (n_cols,) The bicluster label of each column. References ---------- * Dhillon, Inderjit S, 2001. `Co-clustering documents and words using bipartite spectral graph partitioning <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.140.3011>`__. """ def __init__(self, n_clusters=3, svd_method='randomized', n_svd_vecs=None, mini_batch=False, init='k-means++', n_init=10, n_jobs=1, random_state=None): super(SpectralCoclustering, self).__init__(n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, n_jobs, random_state) def _fit(self, X): normalized_data, row_diag, col_diag = _scale_normalize(X) n_sv = 1 + int(np.ceil(np.log2(self.n_clusters))) u, v = self._svd(normalized_data, n_sv, n_discard=1) z = np.vstack((row_diag[:, np.newaxis] * u, col_diag[:, np.newaxis] * v)) _, labels = self._k_means(z, self.n_clusters) n_rows = X.shape[0] self.row_labels_ = labels[:n_rows] self.column_labels_ = labels[n_rows:] self.rows_ = np.vstack(self.row_labels_ == c for c in range(self.n_clusters)) self.columns_ = np.vstack(self.column_labels_ == c for c in range(self.n_clusters)) class SpectralBiclustering(BaseSpectral): """Spectral biclustering (Kluger, 2003). Partitions rows and columns under the assumption that the data has an underlying checkerboard structure. For instance, if there are two row partitions and three column partitions, each row will belong to three biclusters, and each column will belong to two biclusters. The outer product of the corresponding row and column label vectors gives this checkerboard structure. Read more in the :ref:`User Guide <spectral_biclustering>`. Parameters ---------- n_clusters : integer or tuple (n_row_clusters, n_column_clusters) The number of row and column clusters in the checkerboard structure. method : string, optional, default: 'bistochastic' Method of normalizing and converting singular vectors into biclusters. May be one of 'scale', 'bistochastic', or 'log'. The authors recommend using 'log'. If the data is sparse, however, log normalization will not work, which is why the default is 'bistochastic'. CAUTION: if `method='log'`, the data must not be sparse. n_components : integer, optional, default: 6 Number of singular vectors to check. n_best : integer, optional, default: 3 Number of best singular vectors to which to project the data for clustering. svd_method : string, optional, default: 'randomized' Selects the algorithm for finding singular vectors. May be 'randomized' or 'arpack'. If 'randomized', uses `sklearn.utils.extmath.randomized_svd`, which may be faster for large matrices. If 'arpack', uses `sklearn.utils.arpack.svds`, which is more accurate, but possibly slower in some cases. n_svd_vecs : int, optional, default: None Number of vectors to use in calculating the SVD. Corresponds to `ncv` when `svd_method=arpack` and `n_oversamples` when `svd_method` is 'randomized`. mini_batch : bool, optional, default: False Whether to use mini-batch k-means, which is faster but may get different results. init : {'k-means++', 'random' or an ndarray} Method for initialization of k-means algorithm; defaults to 'k-means++'. n_init : int, optional, default: 10 Number of random initializations that are tried with the k-means algorithm. If mini-batch k-means is used, the best initialization is chosen and the algorithm runs once. Otherwise, the algorithm is run for each initialization and the best solution chosen. n_jobs : int, optional, default: 1 The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. random_state : int seed, RandomState instance, or None (default) A pseudo random number generator used by the K-Means initialization. Attributes ---------- rows_ : array-like, shape (n_row_clusters, n_rows) Results of the clustering. `rows[i, r]` is True if cluster `i` contains row `r`. Available only after calling ``fit``. columns_ : array-like, shape (n_column_clusters, n_columns) Results of the clustering, like `rows`. row_labels_ : array-like, shape (n_rows,) Row partition labels. column_labels_ : array-like, shape (n_cols,) Column partition labels. References ---------- * Kluger, Yuval, et. al., 2003. `Spectral biclustering of microarray data: coclustering genes and conditions <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.135.1608>`__. """ def __init__(self, n_clusters=3, method='bistochastic', n_components=6, n_best=3, svd_method='randomized', n_svd_vecs=None, mini_batch=False, init='k-means++', n_init=10, n_jobs=1, random_state=None): super(SpectralBiclustering, self).__init__(n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, n_jobs, random_state) self.method = method self.n_components = n_components self.n_best = n_best def _check_parameters(self): super(SpectralBiclustering, self)._check_parameters() legal_methods = ('bistochastic', 'scale', 'log') if self.method not in legal_methods: raise ValueError("Unknown method: '{0}'. method must be" " one of {1}.".format(self.method, legal_methods)) try: int(self.n_clusters) except TypeError: try: r, c = self.n_clusters int(r) int(c) except (ValueError, TypeError): raise ValueError("Incorrect parameter n_clusters has value:" " {}. It should either be a single integer" " or an iterable with two integers:" " (n_row_clusters, n_column_clusters)") if self.n_components < 1: raise ValueError("Parameter n_components must be greater than 0," " but its value is {}".format(self.n_components)) if self.n_best < 1: raise ValueError("Parameter n_best must be greater than 0," " but its value is {}".format(self.n_best)) if self.n_best > self.n_components: raise ValueError("n_best cannot be larger than" " n_components, but {} > {}" "".format(self.n_best, self.n_components)) def _fit(self, X): n_sv = self.n_components if self.method == 'bistochastic': normalized_data = _bistochastic_normalize(X) n_sv += 1 elif self.method == 'scale': normalized_data, _, _ = _scale_normalize(X) n_sv += 1 elif self.method == 'log': normalized_data = _log_normalize(X) n_discard = 0 if self.method == 'log' else 1 u, v = self._svd(normalized_data, n_sv, n_discard) ut = u.T vt = v.T try: n_row_clusters, n_col_clusters = self.n_clusters except TypeError: n_row_clusters = n_col_clusters = self.n_clusters best_ut = self._fit_best_piecewise(ut, self.n_best, n_row_clusters) best_vt = self._fit_best_piecewise(vt, self.n_best, n_col_clusters) self.row_labels_ = self._project_and_cluster(X, best_vt.T, n_row_clusters) self.column_labels_ = self._project_and_cluster(X.T, best_ut.T, n_col_clusters) self.rows_ = np.vstack(self.row_labels_ == label for label in range(n_row_clusters) for _ in range(n_col_clusters)) self.columns_ = np.vstack(self.column_labels_ == label for _ in range(n_row_clusters) for label in range(n_col_clusters)) def _fit_best_piecewise(self, vectors, n_best, n_clusters): """Find the ``n_best`` vectors that are best approximated by piecewise constant vectors. The piecewise vectors are found by k-means; the best is chosen according to Euclidean distance. """ def make_piecewise(v): centroid, labels = self._k_means(v.reshape(-1, 1), n_clusters) return centroid[labels].ravel() piecewise_vectors = np.apply_along_axis(make_piecewise, axis=1, arr=vectors) dists = np.apply_along_axis(norm, axis=1, arr=(vectors - piecewise_vectors)) result = vectors[np.argsort(dists)[:n_best]] return result def _project_and_cluster(self, data, vectors, n_clusters): """Project ``data`` to ``vectors`` and cluster the result.""" projected = safe_sparse_dot(data, vectors) _, labels = self._k_means(projected, n_clusters) return labels
bsd-3-clause
bombehub/FrequentCheckpointing
zigzag.py
1
1335
__author__ = 'mk' import matplotlib.pyplot as plt unitSize = 8192 unitNum = 25600 uf = 32 threadID = 0 dataDir = "./log/latency/" resultDir = "./diagrams/experimental_result/" algLabel = ['naive', 'cou', 'zigzag', 'pingpong', 'MK', 'LL'] fig = plt.figure(figsize=(8, 4)) def init(): plt.xlabel("time(ns)") plt.ylabel("Latency") plt.title("Latency Test") def gen(xmin, xmax, ymin, ymax): plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) #fig.yscale('log') fig.canvas.draw() # plt.savefig(resultDir + "Latency" + str(uf) + "k.pdf") def loadlog(): for i in range(0 , 3, 2): logPath = dataDir + str(i) + "_latency_" + str(uf) + "k_" + str(unitNum) + "_" + str(unitSize) + "_" + str(threadID) + ".log" logFile = open(logPath) tick = [] latency = [] count = 0 for eachLine in logFile.readlines(): timeNsStr, latencyNsStr = eachLine.split(",") latencyNs = int(latencyNsStr) count = count + 1 tick.append(count) #latency.append(latencyNs / 1000000000.0) #1 ms normalization latency.append(latencyNs / 1000000.0) #latency.append(latencyNs / 1000) plt.plot(tick, latency, label=algLabel[i], linewidth=1) logFile.close() plt.legend() init() loadlog() fig.show()
gpl-3.0
tgsmith61591/skutil
skutil/h2o/balance.py
1
11679
from __future__ import absolute_import, division, print_function import pandas as pd from abc import ABCMeta import warnings from sklearn.externals import six from skutil.base import overrides from .transform import _flatten_one from .util import reorder_h2o_frame, _gen_optimized_chunks, h2o_col_to_numpy from .base import check_frame, BaseH2OFunctionWrapper from ..preprocessing.balance import (_validate_ratio, _validate_target, _validate_num_classes, _OversamplingBalancePartitioner, _UndersamplingBalancePartitioner, BalancerMixin) __all__ = [ 'H2OOversamplingClassBalancer', 'H2OUndersamplingClassBalancer' ] def _validate_x_y_ratio(X, y, ratio): """Validates the following, given that X is already a validated pandas DataFrame: 1. That y is a string 2. That the number of classes does not exceed _max_classes as defined by the BalancerMixin class 3. That the number of classes is at least 2 4. That ratio is a float that falls between 0.0 (exclusive) and 1.0 (inclusive) Parameters ---------- X : ``H2OFrame``, shape=(n_samples, n_features) The frame from which to sample y : str The name of the column that is the response class. This is the column on which ``value_counts`` will be executed to determine imbalance. ratio : float The ratio at which the balancing operation will be performed. Used to determine whether balancing is required. Returns ------- out_tup : tuple, shape=(3,) a length-3 tuple with the following args: [0] - cts (pd.Series), the ascending sorted ``value_counts`` of the class, where the index is the class label. [1] - n_classes (int), the number of unique classes [2] - needs_balancing (bool), whether the least populated class is represented at a rate lower than the demanded ratio. """ # validate ratio, if the current ratio is >= the ratio, it's "balanced enough" ratio = _validate_ratio(ratio) y = _validate_target(y) # cast to string type is_factor = _flatten_one(X[y].isfactor()) # is the target a factor? # if the target is a factor, we might have an issue here... """ if is_factor: warnings.warn('Balancing with the target as a factor can cause unpredictable ' 'sampling behavior (H2O makes it difficult to assess equality ' 'between two factors). Balancing works best when the target ' 'is an int. If possible, consider using `asnumeric`.', UserWarning) """ # generate cts. Have to get kludgier in h2o... then validate is < max classes # we have to do it this way, because H2O might treat the vals as enum, and we cannot # slice based on equality (dernit, H2O). target_col = pd.Series(h2o_col_to_numpy(X[y])) cts = target_col.value_counts().sort_values(ascending=True) n_classes = _validate_num_classes(cts) needs_balancing = (cts.values[0] / cts.values[-1]) < ratio index = cts.index if not is_factor else cts.index.astype('str') out_tup = (dict(zip(index, cts.values)), # cts index, # labels sorted ascending by commonality target_col.values if not is_factor else target_col.astype('str').values, # the target n_classes, needs_balancing) return out_tup class _BaseH2OBalancer(six.with_metaclass(ABCMeta, BaseH2OFunctionWrapper, BalancerMixin)): """Base class for all H2O balancers. Provides _min_version and _max_version for BaseH2OFunctionWrapper constructor. """ def __init__(self, target_feature, ratio=BalancerMixin._def_ratio, min_version='any', max_version=None, shuffle=True): super(_BaseH2OBalancer, self).__init__(target_feature=target_feature, min_version=min_version, max_version=max_version) self.ratio = ratio self.shuffle = shuffle # this is a new warning if shuffle: warnings.warn('Setting shuffle=True will eventually be deprecated, as H2O ' 'does not allow re-ordering of frames by row. The current work-around ' '(rbinding the rows) is known to cause issues in the H2O ExprNode ' 'cache for very large frames.', DeprecationWarning) class H2OOversamplingClassBalancer(_BaseH2OBalancer): """Oversample the minority classes until they are represented at the target proportion to the majority class. Parameters ---------- target_feature : str The name of the response column. The response column must be more than a single class and less than ``skutil.preprocessing.balance.BalancerMixin._max_classes`` ratio : float, optional (default=0.2) The target ratio of the minority records to the majority records. If the existing ratio is >= the provided ratio, the return value will merely be a copy of the input frame shuffle : bool, optional (default=True) Whether or not to shuffle rows on return Examples -------- Consider the following example: with a ``ratio`` of 0.5, the minority classes (1, 2) will be oversampled until they are represented at a ratio of at least 0.5 * the prevalence of the majority class (0) >>> def example(): ... import h2o ... import pandas as pd ... import numpy as np ... from skutil.h2o.frame import value_counts ... from skutil.h2o import from_pandas ... ... # initialize h2o ... h2o.init() ... ... # read into pandas ... x = pd.DataFrame(np.concatenate([np.zeros(100), np.ones(30), np.ones(25)*2]), columns=['A']) ... ... # load into h2o ... X = from_pandas(x) ... ... # initialize sampler ... sampler = H2OOversamplingClassBalancer(target_feature="A", ratio=0.5) ... ... # do balancing ... X_balanced = sampler.balance(X) ... value_counts(X_balanced) >>> >>> example() # doctest: +SKIP 0 100 1 50 2 50 Name A, dtype: int64 .. versionadded:: 0.1.0 """ def __init__(self, target_feature, ratio=BalancerMixin._def_ratio, shuffle=True): # as of now, no min/max version; it's simply compatible with all... super(H2OOversamplingClassBalancer, self).__init__( target_feature=target_feature, ratio=ratio, shuffle=shuffle) @overrides(BalancerMixin) def balance(self, X): """Apply the oversampling balance operation. Oversamples the minority class to the provided ratio of minority class(es) : majority class. Parameters ---------- X : ``H2OFrame``, shape=(n_samples, n_features) The imbalanced dataset. Returns ------- Xb : ``H2OFrame``, shape=(n_samples, n_features) The balanced H2OFrame """ # check on state of X frame = check_frame(X, copy=False) # get the partitioner partitioner = _OversamplingBalancePartitioner( X=frame, y_name=self.target_feature, ratio=self.ratio, validation_function=_validate_x_y_ratio) sample_idcs = partitioner.get_indices(self.shuffle) # since H2O won't allow us to resample (it's considered rearranging) # we need to rbind at each point of duplication... this can be pretty # inefficient, so we might need to get clever about this... Xb = reorder_h2o_frame(frame, _gen_optimized_chunks(sample_idcs), from_chunks=True) return Xb class H2OUndersamplingClassBalancer(_BaseH2OBalancer): """Undersample the majority class until it is represented at the target proportion to the most-represented minority class. Parameters ---------- target_feature : str The name of the response column. The response column must be more than a single class and less than ``skutil.preprocessing.balance.BalancerMixin._max_classes`` ratio : float, optional (default=0.2) The target ratio of the minority records to the majority records. If the existing ratio is >= the provided ratio, the return value will merely be a copy of the input frame shuffle : bool, optional (default=True) Whether or not to shuffle rows on return Examples -------- Consider the following example: with a ``ratio`` of 0.5, the majority class (0) will be undersampled until the second most-populous class (1) is represented at a ratio of 0.5. >>> def example(): ... import h2o ... import pandas as pd ... import numpy as np ... from skutil.h2o.frame import value_counts ... from skutil.h2o import from_pandas ... ... # initialize h2o ... h2o.init() ... ... # read into pandas ... x = pd.DataFrame(np.concatenate([np.zeros(100), np.ones(30), np.ones(25)*2]), columns=['A']) ... ... # load into h2o ... X = from_pandas(x) # doctest:+ELLIPSIS ... ... # initialize sampler ... sampler = H2OUndersamplingClassBalancer(target_feature="A", ratio=0.5) ... ... X_balanced = sampler.balance(X) ... value_counts(X_balanced) ... >>> example() # doctest: +SKIP 0 60 1 30 2 10 Name A, dtype: int64 .. versionadded:: 0.1.0 """ _min_version = '3.8.2.9' _max_version = None def __init__(self, target_feature, ratio=BalancerMixin._def_ratio, shuffle=True): super(H2OUndersamplingClassBalancer, self).__init__( target_feature=target_feature, ratio=ratio, min_version=self._min_version, max_version=self._max_version, shuffle=shuffle) @overrides(BalancerMixin) def balance(self, X): """Apply the undersampling balance operation. Undersamples the majority class to the provided ratio of minority class(es) : majority class Parameters ---------- X : ``H2OFrame``, shape=(n_samples, n_features) The imbalanced dataset. Returns ------- Xb : ``H2OFrame``, shape=(n_samples, n_features) The balanced H2OFrame """ # check on state of X frame = check_frame(X, copy=False) # get the partitioner partitioner = _UndersamplingBalancePartitioner( X=frame, y_name=self.target_feature, ratio=self.ratio, validation_function=_validate_x_y_ratio) # since there are no feature_names, we can just slice # the h2o frame as is, given the indices: idcs = partitioner.get_indices(self.shuffle) Xb = frame[idcs, :] if not self.shuffle else reorder_h2o_frame(frame, _gen_optimized_chunks(idcs), from_chunks=True) return Xb
bsd-3-clause
toobaz/pandas
pandas/tests/arrays/categorical/test_dtypes.py
2
7118
import numpy as np import pytest from pandas.core.dtypes.dtypes import CategoricalDtype from pandas import Categorical, CategoricalIndex, Index, Series, Timestamp import pandas.util.testing as tm class TestCategoricalDtypes: def test_is_equal_dtype(self): # test dtype comparisons between cats c1 = Categorical(list("aabca"), categories=list("abc"), ordered=False) c2 = Categorical(list("aabca"), categories=list("cab"), ordered=False) c3 = Categorical(list("aabca"), categories=list("cab"), ordered=True) assert c1.is_dtype_equal(c1) assert c2.is_dtype_equal(c2) assert c3.is_dtype_equal(c3) assert c1.is_dtype_equal(c2) assert not c1.is_dtype_equal(c3) assert not c1.is_dtype_equal(Index(list("aabca"))) assert not c1.is_dtype_equal(c1.astype(object)) assert c1.is_dtype_equal(CategoricalIndex(c1)) assert c1.is_dtype_equal(CategoricalIndex(c1, categories=list("cab"))) assert not c1.is_dtype_equal(CategoricalIndex(c1, ordered=True)) # GH 16659 s1 = Series(c1) s2 = Series(c2) s3 = Series(c3) assert c1.is_dtype_equal(s1) assert c2.is_dtype_equal(s2) assert c3.is_dtype_equal(s3) assert c1.is_dtype_equal(s2) assert not c1.is_dtype_equal(s3) assert not c1.is_dtype_equal(s1.astype(object)) def test_set_dtype_same(self): c = Categorical(["a", "b", "c"]) result = c._set_dtype(CategoricalDtype(["a", "b", "c"])) tm.assert_categorical_equal(result, c) def test_set_dtype_new_categories(self): c = Categorical(["a", "b", "c"]) result = c._set_dtype(CategoricalDtype(list("abcd"))) tm.assert_numpy_array_equal(result.codes, c.codes) tm.assert_index_equal(result.dtype.categories, Index(list("abcd"))) @pytest.mark.parametrize( "values, categories, new_categories", [ # No NaNs, same cats, same order (["a", "b", "a"], ["a", "b"], ["a", "b"]), # No NaNs, same cats, different order (["a", "b", "a"], ["a", "b"], ["b", "a"]), # Same, unsorted (["b", "a", "a"], ["a", "b"], ["a", "b"]), # No NaNs, same cats, different order (["b", "a", "a"], ["a", "b"], ["b", "a"]), # NaNs (["a", "b", "c"], ["a", "b"], ["a", "b"]), (["a", "b", "c"], ["a", "b"], ["b", "a"]), (["b", "a", "c"], ["a", "b"], ["a", "b"]), (["b", "a", "c"], ["a", "b"], ["a", "b"]), # Introduce NaNs (["a", "b", "c"], ["a", "b"], ["a"]), (["a", "b", "c"], ["a", "b"], ["b"]), (["b", "a", "c"], ["a", "b"], ["a"]), (["b", "a", "c"], ["a", "b"], ["a"]), # No overlap (["a", "b", "c"], ["a", "b"], ["d", "e"]), ], ) @pytest.mark.parametrize("ordered", [True, False]) def test_set_dtype_many(self, values, categories, new_categories, ordered): c = Categorical(values, categories) expected = Categorical(values, new_categories, ordered) result = c._set_dtype(expected.dtype) tm.assert_categorical_equal(result, expected) def test_set_dtype_no_overlap(self): c = Categorical(["a", "b", "c"], ["d", "e"]) result = c._set_dtype(CategoricalDtype(["a", "b"])) expected = Categorical([None, None, None], categories=["a", "b"]) tm.assert_categorical_equal(result, expected) def test_codes_dtypes(self): # GH 8453 result = Categorical(["foo", "bar", "baz"]) assert result.codes.dtype == "int8" result = Categorical(["foo{i:05d}".format(i=i) for i in range(400)]) assert result.codes.dtype == "int16" result = Categorical(["foo{i:05d}".format(i=i) for i in range(40000)]) assert result.codes.dtype == "int32" # adding cats result = Categorical(["foo", "bar", "baz"]) assert result.codes.dtype == "int8" result = result.add_categories(["foo{i:05d}".format(i=i) for i in range(400)]) assert result.codes.dtype == "int16" # removing cats result = result.remove_categories( ["foo{i:05d}".format(i=i) for i in range(300)] ) assert result.codes.dtype == "int8" @pytest.mark.parametrize("ordered", [True, False]) def test_astype(self, ordered): # string cat = Categorical(list("abbaaccc"), ordered=ordered) result = cat.astype(object) expected = np.array(cat) tm.assert_numpy_array_equal(result, expected) msg = "could not convert string to float" with pytest.raises(ValueError, match=msg): cat.astype(float) # numeric cat = Categorical([0, 1, 2, 2, 1, 0, 1, 0, 2], ordered=ordered) result = cat.astype(object) expected = np.array(cat, dtype=object) tm.assert_numpy_array_equal(result, expected) result = cat.astype(int) expected = np.array(cat, dtype=np.int) tm.assert_numpy_array_equal(result, expected) result = cat.astype(float) expected = np.array(cat, dtype=np.float) tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize("dtype_ordered", [True, False]) @pytest.mark.parametrize("cat_ordered", [True, False]) def test_astype_category(self, dtype_ordered, cat_ordered): # GH 10696/18593 data = list("abcaacbab") cat = Categorical(data, categories=list("bac"), ordered=cat_ordered) # standard categories dtype = CategoricalDtype(ordered=dtype_ordered) result = cat.astype(dtype) expected = Categorical(data, categories=cat.categories, ordered=dtype_ordered) tm.assert_categorical_equal(result, expected) # non-standard categories dtype = CategoricalDtype(list("adc"), dtype_ordered) result = cat.astype(dtype) expected = Categorical(data, dtype=dtype) tm.assert_categorical_equal(result, expected) if dtype_ordered is False: # dtype='category' can't specify ordered, so only test once result = cat.astype("category") expected = cat tm.assert_categorical_equal(result, expected) def test_astype_category_ordered_none_deprecated(self): # GH 26336 cdt1 = CategoricalDtype(categories=list("cdab"), ordered=True) cdt2 = CategoricalDtype(categories=list("cedafb")) cat = Categorical(list("abcdaba"), dtype=cdt1) with tm.assert_produces_warning(FutureWarning): cat.astype(cdt2) def test_iter_python_types(self): # GH-19909 cat = Categorical([1, 2]) assert isinstance(list(cat)[0], int) assert isinstance(cat.tolist()[0], int) def test_iter_python_types_datetime(self): cat = Categorical([Timestamp("2017-01-01"), Timestamp("2017-01-02")]) assert isinstance(list(cat)[0], Timestamp) assert isinstance(cat.tolist()[0], Timestamp)
bsd-3-clause
CompPhysics/ThesisProjects
doc/MSc/msc_students/former/AudunHansen/Audun/Pythonscripts/CCAlgebra.py
1
37355
# <!-- collapse=True --> from IPython.display import display, Math, Latex #from sympy.interactive import printing #printing.init_printing() from numpy import * from itertools import * from matplotlib.pyplot import * class Operator(): #Normal ordered operator for cluster algebra (diagrammatic) def __init__(self, q_create, q_annihilate): self.q_c = q_create self.q_a = q_annihilate self.diagrams = [] self.contracted = [] self.I = [] self.T_operator = [] self.T_vertices = [] self.vertexform = [] self.vertexform_locked = [] self.labels_p = ['h','g','f','e','d','c','b','a'] self.labels_h = ['p','o','n','m','l','k','j','i'] self.enable_printing = False self.assess_excitation() def combine(self, ops, excitation = None): #Assosciate a list of T-operators (ops) to the current operator instance #Find all possible ways to combine the operators using self.distinct_combinations() T = [] for i in ops: T.append(i.q_c) self.T_vertices.append(i.vertexform) self.T_operator = T #Finding acceptable combinations of internal contractions between the operators self.I = self.distinct_combinations(self.q_a, T) #Find excitation level of combination self.assess_excitation() def assess_excitation(self): #Assess current excitation level (also if combined operator) self.E = self.q_c.count(-1) + self.q_c.count(1) - (self.q_a.count(1) + self.q_a.count(-1)) for i in range(len(self.T_operator)): self.E += self.T_operator[i].count(1) + self.T_operator[i].count(-1) #fill in contracted elements self.E/= 2.0 def scan_extract(L, e): #Exctract element e from list L ret = None for i in range(len(L)): if L[i] == e: L = delete(L, i) ret = e def nloops(self,x,y): #returns number of loops in budget return (x+y - abs(x-y))//2 def assess_contributions(self, excitation_level = None): #self.label_vertices() #returns the contribution to the CC-energy or amplitude eq. in symbolic form enable_printing = self.enable_printing #True #self.enable_printing self.loops = [] self.holes = [] self.equivalents = [] self.stringforms = [] for i in self.I: #for each distinct diagram, generate the expression for the contribution """ Following S-B, ch. 10, this section evaluates the contribution to the CC-eqs. using the diagrammatic rules: (1) Label internal and external lines with particle and hole labels (2) Assosciate f(i,a) with every 1-p operator vertex (3) Assosciate <lout rout!!lin rin> with every 2-p operator vertex (4) Assosciate t(ab,ij) for every amplitude (5) Sum over all internal lines (6) Multiply by 1/2 for each pair of equivalent internal lines (7) Multiply by 1/2 for each pair of equivalent T-vertices (8) Include a phase factor (-)**(holes-loops) (9) Not yet implemented (10) Not yet implemented """ H_labels = [] H_ins = [] H_outs = [] T_labels = [] prefactor = 1.0 #this factor is multiplied to the sum and adjusted according to the rules laid out above #Comparing distribution of lines i_budget = self.itemcount(i) #internal distribution t_budget = self.itemcount(self.T_operator) #all lines from T t_budget_external = self.itemcount(self.T_operator) #distribution of external lines in T for e in range(len(t_budget_external)): #Subtracting internal lines t_budget_external[e][0] -= i_budget[e][0] t_budget_external[e][1] -= i_budget[e][1] t_external_equiv = self.find_identical(t_budget_external) #len of this list yields number of identical external distribution in the Ts t_equiv = self.find_identical(i_budget) #len of this line yields the number of identical internal distributions in the Ts n_equivalent_t = 0 for e in range(len(t_external_equiv)): if t_external_equiv[e] == t_equiv[e]: n_equivalent_t += 1 #Counting number of equivalent lines, holes and loops n_equi_lines = 0 n_loops = 0 n_loops_external = 0 n_holes = 0 #Counting equivalent lines for e in i_budget: n_equi_lines += e[0]//2 n_equi_lines += e[1]//2 #Counting loops for e in range(len(i_budget)): n_loops += self.nloops(i_budget[e][0], i_budget[e][1]) n_loops_external += self.nloops(t_budget_external[e][0], t_budget_external[e][1]) #So-called quasi-loops (S-B, ch. 10) #Counting holes for e in range(len(i_budget)): n_holes += i_budget[e][1] + t_budget_external[e][1] n_holes += self.q_c.count(-1) #labelling all lines #Setting up a mapping to keep track of connected lines in T t_mapping = [] for e in range(len(self.T_operator)): t_mapping.append([]) for u in range(len(self.T_operator[e])): t_mapping[e].append(0) #a 0 implies an external line for e in range(len(i)): for u in range(len(i[e])): linetype = i[e][u] #+1 = particle / -1 = hole for l in range(len(self.T_operator[e])): if self.T_operator[e][l] == linetype: if t_mapping[e][l] == 0: #Connect and label line t_mapping[e][l] = 1 #1 implies a connected line break #Labeling all looped lines: plabels = ['h','g','f','e','d','c','b','a'] hlabels = ['p','o','n','m','l','k','j','i'] i_connections = [] i_labels = [] for e in range(len(i)): i_connections.append([]) i_labels.append([]) for u in range(len(i[e])): i_connections[e].append(0) i_labels[e].append(0) h_vertices = [] #list containing pairs of operators t_vertices = [] for e in range(len(self.T_operator)): t_vertices.append([]) #Connect all loops connecting at the hamiltonian for e in range(len(i)): for u in range(len(i[e])): if i_connections[e][u] == 0: linetype = i[e][u] found = False for ee in range(len(i)): for uu in range(len(i[ee])): if i_connections[e][u] == 0 and i_connections[ee][uu] == 0 and i[ee][uu] == -linetype: #Connect i_connections[e][u] = 2 i_connections[ee][uu] = 2 #2 denotes a looped connection vertex if linetype == -1: i_labels[e][u] = hlabels.pop() i_labels[ee][uu] = plabels.pop() if e == ee: t_vertices[e].append([i_labels[e][u], i_labels[ee][uu]]) if e != ee: t_vertices[e].append([i_labels[e][u], -1]) t_vertices[ee].append([1,i_labels[ee][uu]]) if linetype == 1: i_labels[e][u] = plabels.pop() i_labels[ee][uu] = hlabels.pop() if e == ee: t_vertices[e].append([i_labels[e][u], i_labels[ee][uu]]) if e != ee: t_vertices[e].append([i_labels[e][u], -1]) t_vertices[ee].append([1,i_labels[ee][uu]]) #set in/out in vertex n h_vertices.append([i_labels[e][u],i_labels[ee][uu]]) found = True break if found: break #Connect all lines passing through the hamiltonian for e in range(len(i)): for u in range(len(i[e])): if i_connections[e][u] == 0: linetype = i[e][u] found = False for ee in range(len(self.q_c)): if self.q_c[ee] == linetype: #add vertex, connect i_connections[e][u] = 1 if linetype == 1: i_labels[e][u] = plabels.pop() t_vertices[e].append([i_labels[e][u], -1]) if linetype == -1: i_labels[e][u] = hlabels.pop() t_vertices[e].append([1, i_labels[e][u]]) h_vertices.append([i_labels[e][u], i_labels[e][u]]) found = True if found: break #Label remaining lines in the T_operator for e in range(len(t_vertices)): for u in range(len(t_vertices[e])): if t_vertices[e][u][0] == 1: t_vertices[e][u][0] = plabels.pop() if t_vertices[e][u][1] == -1: t_vertices[e][u][1] = hlabels.pop() #Add unconnected vertices to T_operator for e in range(len(self.T_operator)): while len(self.T_operator[e])/2 > len(t_vertices[e]): t_vertices[e].append([plabels.pop(), hlabels.pop()]) stringform = '' #The stringform will contain the CC contribution in latex format if enable_printing: print "=== Distinct contribution with excitation %i ===" % self.E print "Connection pattern:", i prefactor = ((-1)**(n_holes - (n_loops+n_loops_external))) predivisor = (2**n_equi_lines)*(2**n_equivalent_t) if enable_printing: print "Multiplier:", prefactor, "/", predivisor stringform+=' \\frac{%i}{%i} ' % (prefactor, predivisor) summingover = '' summation_indices = [] for e in range(len(h_vertices)): summation_indices.append(h_vertices[e][0]) summation_indices.append(h_vertices[e][1]) summation_indices2 = set(summation_indices) #only unique values #print summation_indices for e in summation_indices2: summingover+= e stringform+= '\sum_{%s} ' % summingover if enable_printing: print "Sum over :", summation_indices H_tensor = ['',''] for e in range(len(h_vertices)): H_tensor[1]+=h_vertices[e][0] H_tensor[0]+=h_vertices[e][1] if enable_printing: print "H-tensor : <%s||%s> " % (H_tensor[0], H_tensor[1]) stringform += '[%s|H|%s]' % (H_tensor[0], H_tensor[1]) T_tensor = [] for e in range(len(t_vertices)): T_tensor.append(['', '']) for u in range(len(t_vertices[e])): T_tensor[e][1]+=t_vertices[e][u][0] T_tensor[e][0]+=t_vertices[e][u][1] if enable_printing: print "T-tensor(s):" for e in T_tensor: if enable_printing: print " T(%s,%s)" % (e[0], e[1]) stringform += 't_{%s}^{%s} ' % (e[0], e[1]) stringform += " (excitation:%i) " % self.E if excitation_level == None: self.stringforms.append(stringform) else: if excitation_level == self.E: self.stringforms.append(stringform) if enable_printing: print " " if len(self.I) == 0: #self.stringforms.append('No contributions found.') if enable_printing: print "=== No distinct contribution found ===" print " " #print self.I for e in range(len(self.I)): hh,tt = self.visualize(self.q_a, self.q_c, [0,e*2.6], self.I[e], T = self.T_operator, t = 0) self.diagrams.append([hh,tt]) #self.hhvis, self.tvis = self.visualize(self.q_a, self.q_c, [0,0], self.I[0], T = None, t = 0) return 0 def nozeroedges(self,i): #Assert that there are no borders in the endpoints of the connection pattern i ret = True try: if i[0] == 0 or i[-1] == 0: ret = False except: ret = False return ret def nozerocontact(self,i): #Assert that there are no neighbouring borders in the connection pattern i ret = True for e in range(len(i) - 1): if i[e+1] == 0 and i[e] == 0: ret = False return ret def splitlist(self,L, d): #Returns a split list HL from a list L into constituents, d denotes barrier HL = [[]] n = 0 for i in range(len(L)): if L[i] != d: HL[n].append(L[i]) if L[i] == d: HL.append([]) n += 1 return HL def itemcount(self,T): #Count number of particle- and hole lines in each constituent part of T #Returns a list object of the form [[#particles, #holes], ...] itemnumber = [] for i in range(len(T)): itemnumber.append([]) itemnumber[i].append(T[i].count(1)) #number of q-particles itemnumber[i].append(T[i].count(-1)) #number of q-holes return itemnumber def contractable(self,L,T): #Asserts that the number of contractions in each p- and hline of L does not superseed # of p-h in T #input two itemcount items lists, returns bool ret = True for i in range(len(T)): for e in range(len(T[i])): if T[i][e]<L[i][e]: #print T[i][e],L[i][e] ret = False return ret def find_identical(self,T): #Find identical operators in the list of operators T #returns a list of pairs of indices that denotes permutations that does not alter the T operator identicals = [] for i in range(len(T)): for e in range(i,len(T)): if T[i] == T[e] and i!=e: identicals.append([i,e]) return identicals def permute_elements(self,e1,e2,L): #Returns a list where elements at indices e1,e2 in L is permuted L_ret = [] for i in L: L_ret.append(i) L_ret[e1] = L[e2] L_ret[e2] = L[e1] return L_ret def acceptable(self,i, T, excluded, excluded_budgets): #Test if a potential connection pattern is distinct #Returns bool ret = False identicals = self.find_identical(T) T_budget = self.itemcount(T) if self.nozeroedges(i) and self.nozerocontact(i): I = self.splitlist(i, 0) I_budget = self.itemcount(I) if I_budget not in excluded_budgets: excluded_budgets.append(I_budget) for e in identicals: excluded_budgets.append(self.permute_elements(e[0], e[1], I_budget)) if self.contractable(I_budget,T_budget): if I not in excluded: excluded.append(I) for e in identicals: excluded.append(self.permute_elements(e[0], e[1], I)) ret = True return ret def distinct_combinations(self,H,T): #Returns all possible combinations of H and T #I - all q-particle annihilation operators #T list of list with T operators. ex. [[-1,1],[-1,1]] = T_1 T_1 lenH = len(H) lenT = len(T) lenTi = [] for i in range(lenT): lenTi.append(len(T[i])) H+=[0 for i in range(lenT-1)] #adding zeros to denote separations in the cluster-operators #Creating countlist for T-operator to keep track of q-operators in each clusteroperator T_budget = self.itemcount(T) #Create all permutations H_permuted = permutations(H) #Sort out indistinct diagrams and cancelling terms excluded = [] excluded_budgets = [] accepted = [] for i in H_permuted: if self.acceptable(i, T, excluded, excluded_budgets): #print "Accepted" accepted.append(self.splitlist(i,0)) self.combined = accepted return accepted def printout(self): for i in self.stringforms: display(Math(r'%s' % i)) def plot_diagrams(self): figure(figsize = (2, len(self.diagrams)+1), dpi = 80, edgecolor = 'k',facecolor='white') p2 =0.0 for i in self.diagrams: pos2 = [0,p2] for e in i[0]: e.draw() for e in i[1]: for u in e: u.draw() p2 += 1.8 #axisbg='red' #set_cmap('hot') axis('off') axes().set_aspect('equal', 'datalim') show() def visualize(self,h_below, h_above, pos, I, T = None, t = 0): #create operator vxnode objects from Ob-object #NV = len(O.L)/2 NV = (len(h_below) + len(h_above))/2 Nbelow = len(h_below) Nabove = len(h_above) c_below = [] for i in range(Nbelow): c_below.append(0) #A zero implies a "free" line below the interaction line c_above = [] for i in range(Nabove): c_above.append(0) #A zero implies a "free" line above the interaction line ncount = NV #(1) Identify lines passing through the interaction line vnodes = [] for i in range(Nabove): for e in range(Nbelow): if c_below[e] == 0 and c_above[i] == 0: if h_above[i]== h_below[e]: #Append the operator to vnodes #print "Found a line passing through the interaction." c_above[i] = 1 c_below[e] = 1 ncount -= 1 if h_above[i] == 1: c1,c2,c3,c4 = [0,None],[1,None],[0,None],[1,None] nd = vxnode([pos[0] + i, pos[1]+1.5], [c1,c2,c3,c4]) vnodes.append(nd) if h_above[i] == -1: c1,c2,c3,c4 = [1,None],[0,None],[1,None],[0,None] nd = vxnode([pos[0] + i, pos[1]+1.5], [c1,c2,c3,c4]) vnodes.append(nd) #(2) Identify lines annihilating at the interaction for i in range(Nbelow): for e in range(Nbelow): if c_below[e] == 0 and c_below[i] == 0 and i!= e: if h_below[i]== -1*h_below[e]: #Append the operator to vnodes #print "Found a line annihilating at the interaction." c_below[i] = 1 c_below[e] = 1 ncount -= 1 c1,c2,c3,c4 = [0,None],[0,None],[1,None],[1,None] nd = vxnode([pos[0] + i, pos[1]+1.5], [c1,c2,c3,c4]) vnodes.append(nd) #(3) Identify lines created at the interaction for i in range(Nabove): for e in range(Nabove): if c_above[e] == 0 and c_above[i] == 0 and i!= e: if h_above[i]== -1*h_above[e]: #Append the operator to vnodes #print "Found a line creating at the interaction" c_above[i] = 1 c_above[e] = 1 ncount -= 1 c1,c2,c3,c4 = [1,None],[1,None],[0,None],[0,None] nd = vxnode([pos[0] + i, pos[1]+1.5], [c1,c2,c3,c4]) vnodes.append(nd) #print "C_above:", c_above #print "C_below:", c_below if NV%2 != 0: print "Warning: non-binary operator." for i in range(len(vnodes)-1): if t == 0: vnodes[i].opconnect(vnodes[i+1].pos) if t == 1: vnodes[i].tconnect(vnodes[i+1].pos) tnodes = [] #print "lenT:", len(T), T if T != None: for t in range(len(T)): tnodes.append([]) for i in range(len(T[t])/2): c1,c2,c3,c4 = [1,None],[1,None],[0,None],[0,None] #nd = vxnode([pos[0] + i, pos[1]], [c1,c2,c3,c4]) tnodes[t].append(vxnode([pos[0] + i, pos[1]], [c1,c2,c3,c4])) for i in range(len(tnodes[t])-1): tnodes[t][i].tconnect(tnodes[t][i+1].pos) p = 0 for i in range(len(tnodes)): #print "Tlen:", len(tnodes[i]) for e in range(len(tnodes[i])): tnodes[i][e].pos[0] = pos[0] + p p += 1 for i in range(len((vnodes))): vnodes[i].pos[0] += .5 #Contract T #I contains a recipe for the contractions in the diagram. #Iterate over each element in I and match up the contractions #For every element in I, match up corresponding elements in H and T for i in range(len(tnodes)): for e in range(len(I[i])): cn = I[i][e] self.m = 0 nn = 0 cond = True while cond: cond = self.probe(tnodes[i],vnodes,cn) #probe and perform a possible connection nn += 1 if self.m != 0: break if nn>10: break for i in range(len(tnodes)): pass return [vnodes, tnodes] def probe(self,T,H,cn): cond = True if cn == -1: #hole line for i in range(len(T)): for e in range(len(H)): if T[i].config[0][0] == 1 and T[i].config[0][1] == None: if H[e].config[2][0] == 1 and H[e].config[2][1] == None: #perform connection H[e].config[2][1] = T[i].pos T[i].config[0][0] = 0 self.m = 1 cn = 0 break if self.m == 1: break if cn == 1: #particle line for i in range(len(T)): for e in range(len(H)): if T[i].config[1][0] == 1 and T[i].config[1][1] == None: if H[e].config[3][0] == 1 and H[e].config[3][1] == None: #perform connection H[e].config[3][1] = T[i].pos T[i].config[1][0] = 0 self.m = 1 cn = 0 break if self.m == 1: break if self.m == 1: cond = False return cond def nconnect(self,n1,n2,S,order="l0", p_h = None): N = 60 if n1.x==n2.x and n1.y == n2.y: Cx = n1.x + S Cy = n1.y X = Cx + S*cos(linspace(0,2*pi,N)) Y = Cy + S*sin(linspace(0,2*pi,N)) #S = -1 else: Phx = (n1.x+n2.x)/2.0 Phy = (n1.y+n2.y)/2.0 lP = sqrt((n2.x-n1.x)**2 + (n2.y-n1.y)**2) dPx = (n2.x-n1.x)/lP dPy = (n2.y-n1.y)/lP Cx = Phx - S*dPy Cy = Phy + S*dPx lC = sqrt((S*dPy)**2 + (S*dPx)**2) #node(Phx,Phy, c="blue") #node(Cx,Cy, c="red") R = sqrt((Cx-n1.x)**2 + (Cy-n1.y)**2) lPC0 = sqrt(((Cx+R)-n1.x)**2 + (Cy - n1.y)**2) lPC1 = sqrt(((Cx+R)-n2.x)**2 + (Cy - n2.y)**2) dalpha = arccos((2*R**2 - lP**2)/(2.0*R**2)) CPx = n1.x - Cx CPy = n1.y - Cy X,Y = 0,0 if order == "0": X = [n1.x, n2.x] Y = [n1.y, n2.y] if order == "l0": if S<0: dalpha = 2*pi - dalpha A = linspace(0,dalpha, N) X,Y = rotate_v(CPx,CPy,A) X+=Cx Y+=Cy if order == "r0": if S>0: dalpha = 2*pi - dalpha A = linspace(0,-dalpha, N) X,Y = rotate_v(CPx,CPy,A) X+=Cx Y+=Cy msize = 10 if p_h == 1: draw_arrow([X[len(X)/2],Y[len(X)/2]], [-dPx,-dPy]) #X[len(X)/2],Y[len(X)/2] #plot(X[len(X)/2],Y[len(X)/2], "^", color = "black", markersize = msize) if p_h == -1: draw_arrow([X[len(X)/2],Y[len(X)/2]], [-dPx,-dPy]) #plot(X[len(X)/2],Y[len(X)/2], "v", color = "black", markersize = msize) plot(X,Y, color = "black") def ncon(self,n1,n2,order = 0, p_h = None): if order == 0: nconnect(n1,n2,1,"0", p_h) if order > 0: nconnect(n1,n2,(-2+order),"l0", p_h) if order < 0: nconnect(n1,n2,(-2-order),"r0", p_h) def rotate_v(x,y,alpha): ca = cos(alpha) sa = sin(alpha) return ca*x - sa*y, sa*x + ca*y class vxnode(): def __init__(self, pos, config): #config = [[1,None],[1,None],[1,None],[1,None]] self.pos = pos self.hole_up = 0 #config[0] #Outgoing Q-particle creation operators self.part_up = 0 #config[1] #Outgoing Q-particle creation operators self.hole_down = 0#config[2] #Outgoing Q-particle creation operators self.part_down = 0#config[3] #Outgoing Q-particle creation operators self.config = config self.subline = False self.Opconnect = [] self.Tconnect = [] self.vconnect_h = [] self.c = "black" def opconnect(self, pos): #connect horizontal to another vxnode self.Opconnect.append(pos) def tconnect(self, pos): #connect horizontal to another vxnode self.Tconnect.append(pos) def ttype(self): #Draw a solid, horizontal line through the operator self.subline = True def draw(self, pos2 = None): if pos2 != None: self.pos[0] += pos2[0] self.pos[1] += pos2[1] msize = 10 c= self.c hold('on') sx = .4 sy = 2.0 #if len(self.Tconnect) != 0: #sy *= 1.5 #sx *= 1.3 config = self.config plot(self.pos[0],self.pos[1], ".", color = c,markersize = 10) if config[0][0] == 1: if config[0][1] == None: #Draw straight line hole up plot([self.pos[0], self.pos[0]-sx],[self.pos[1], self.pos[1]+sy],color = c) #print "DRAWING ARROW" draw_arrow([(self.pos[0] + self.pos[0]-sx)/2.0,(self.pos[1] + self.pos[1]+sy)/2.0], [sx,-sy]) #plot((self.pos[0] + self.pos[0]-sx)/2.0,(self.pos[1] + self.pos[1]+sy)/2.0,"v", color = c, markersize = msize) if config[0][1] != None: #connect to node config[0][1] in hole up manner order = -1 #if config[1][1] != None: # order = 0 self.ncon(node(self.pos),node(config[0][1]), order, -1) if config[1][0] == 1: if config[1][1] == None: #Draw straight line particle up plot([self.pos[0], self.pos[0]+sx],[self.pos[1], self.pos[1]+sy],color = c) #print "DRAWING ARROW" draw_arrow([(self.pos[0] + self.pos[0]+sx)/2.0,(self.pos[1] + self.pos[1]+sy)/2.0], [sx,sy]) #plot((self.pos[0] + self.pos[0]+sx)/2.0,(self.pos[1] + self.pos[1]+sy)/2.0,"^", color = c, markersize = msize) if config[1][1] != None: #connect to node config[0][1] in particle up manner order = -1 #if config[0][1] != None: # order = 0 self.ncon(node(config[1][1]),node(self.pos),order,1) if config[2][0] == 1: if config[2][1] == None: #Draw straight line hole down plot([self.pos[0], self.pos[0]-sx],[self.pos[1], self.pos[1]-sy],color = c) #print "DRAWING ARROW" draw_arrow([(self.pos[0] + self.pos[0]-sx)/2.0,(self.pos[1] + self.pos[1]-sy)/2.0], [-sx,-sy]) #plot((self.pos[0] + self.pos[0]-sx)/2.0,(self.pos[1] + self.pos[1]-sy)/2.0,"v", color = c, markersize = msize) if config[2][1] != None: #connect to node config[0][1] in hole down manner #print "Active" order = -1 #if config[3][1] != None: # order = 0 self.ncon(node(config[2][1]), node(self.pos),order, -1) if config[3][0] == 1: if config[3][1] == None: plot([self.pos[0], self.pos[0]+sx],[self.pos[1], self.pos[1]-sy],color = c) #print "DRAWING ARROW" draw_arrow([(self.pos[0] + self.pos[0]+sx)/2.0,(self.pos[1] + self.pos[1]-sy)/2.0], [-sx,sy]) #plot((self.pos[0] + self.pos[0]+sx)/2.0,(self.pos[1] + self.pos[1]-sy)/2.0,"^", color = c, markersize = msize) #Draw straight line particle down if config[3][1] != None: #connect to node config[0][1] in particle down manner order = -1 #if config[2][1] != None: # order = 0 self.ncon(node(self.pos), node(config[3][1]), order, 1) for i in range(len(self.Opconnect)): plot([self.pos[0],self.Opconnect[i][0]],[self.pos[1],self.Opconnect[i][1]], ls = "dotted", color = c) for i in range(len(self.Tconnect)): plot([self.pos[0],self.Tconnect[i][0]],[self.pos[1],self.Tconnect[i][1]], color = c) if self.subline: plot([self.pos[0]-sx, self.pos[0]+sx], [self.pos[1], self.pos[1]], color = c) def ncon(self,n1,n2,order = 0, p_h = None): if order == 0: self.nconnect(n1,n2,1,"0", p_h) if order > 0: self.nconnect(n1,n2,(-2+order),"l0", p_h) if order < 0: self.nconnect(n1,n2,(-2-order),"r0", p_h) def nconnect(self,n1,n2,S,order="l0", p_h = None): N = 60 if n1.x==n2.x and n1.y == n2.y: Cx = n1.x + S Cy = n1.y X = Cx + S*cos(linspace(0,2*pi,N)) Y = Cy + S*sin(linspace(0,2*pi,N)) #S = -1 else: Phx = (n1.x+n2.x)/2.0 Phy = (n1.y+n2.y)/2.0 lP = sqrt((n2.x-n1.x)**2 + (n2.y-n1.y)**2) dPx = (n2.x-n1.x)/lP dPy = (n2.y-n1.y)/lP Cx = Phx - S*dPy Cy = Phy + S*dPx lC = sqrt((S*dPy)**2 + (S*dPx)**2) #node(Phx,Phy, c="blue") #node(Cx,Cy, c="red") R = sqrt((Cx-n1.x)**2 + (Cy-n1.y)**2) lPC0 = sqrt(((Cx+R)-n1.x)**2 + (Cy - n1.y)**2) lPC1 = sqrt(((Cx+R)-n2.x)**2 + (Cy - n2.y)**2) dalpha = arccos((2*R**2 - lP**2)/(2.0*R**2)) CPx = n1.x - Cx CPy = n1.y - Cy X,Y = 0,0 if order == "0": X = [n1.x, n2.x] Y = [n1.y, n2.y] if order == "l0": if S<0: dalpha = 2*pi - dalpha A = linspace(0,dalpha, N) X,Y = rotate_v(CPx,CPy,A) X+=Cx Y+=Cy if order == "r0": if S>0: dalpha = 2*pi - dalpha A = linspace(0,-dalpha, N) X,Y = rotate_v(CPx,CPy,A) X+=Cx Y+=Cy msize = 10 if p_h == 1: draw_arrow([X[len(X)/2],Y[len(X)/2]], [-dPx,-dPy]) #X[len(X)/2],Y[len(X)/2] #plot(X[len(X)/2],Y[len(X)/2], "^", color = "black", markersize = msize) if p_h == -1: draw_arrow([X[len(X)/2],Y[len(X)/2]], [-dPx,-dPy]) #plot(X[len(X)/2],Y[len(X)/2], "v", color = "black", markersize = msize) plot(X,Y, color = "black") def draw_arrow(pos, point, s = .2, h = .1): #normalize direction p2 = sqrt(point[0]**2 + point[1]**2) point[0] /= p2 point[1] /= p2 #pi/2 degree rotation p_rotx, p_roty = point[1], -point[0] x0, y0 = pos[0], pos[1] x1, y1 = pos[0] - s*point[0], pos[1] - s*point[1] #plot the arrow plot([x0, x1+h*p_rotx],[y0, y1+h*p_roty], color = "black") plot([x0, x1-h*p_rotx],[y0, y1-h*p_roty], color = "black") class node(): def __init__(self, V, c= "black"): self.x = V[0] self.y = V[1] #plot(x,y,".", color = c,markersize = 15) def normal_ordered_hamiltonian(): F1 = Operator([1],[1]) F2 = Operator([-1],[-1]) F3 = Operator([1,-1],[]) F4 = Operator([],[1,-1]) V1 = Operator([1,1],[1,1]) V2 = Operator([-1,-1],[-1,-1]) V3 = Operator([1,-1],[1,-1]) V4 = Operator([1,1,-1],[1]) V5 = Operator([1],[1,1,-1]) V6 = Operator([1,-1,-1],[-1]) V7 = Operator([-1],[1,-1,-1]) V8 = Operator([1,1,-1,-1],[]) V9 = Operator([],[1,1,-1,-1]) return [F1,F2,F3,F4,V1,V2,V3,V4,V5,V6,V7,V8,V9] def cluster_operator(configuration): #configuration =[] T1= Operator([1,-1],[]) T2= Operator([1,1,-1,-1],[]) T3= Operator([1,1,1,-1,-1,-1],[]) T4= Operator([1,1,1,1,-1,-1,-1,-1],[]) T5= Operator([1,1,1,1,1,-1,-1,-1,-1,-1],[]) T_list = [T1, T2, T3, T4, T5] ret = [] for i in configuration: ret.append(T_list[i-1]) return ret def generate_all_combinations(H,T, excitation_level = None, printing = 0): for i in H: i.combine(T) i.assess_contributions(excitation_level) i.printout() T = cluster_operator([2,1]) H = normal_ordered_hamiltonian() generate_all_combinations(H,T,0)
cc0-1.0
Koheron/laser-development-kit
examples/spectrum_analyzer.py
2
1482
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time import numpy as np import matplotlib matplotlib.use('GTKAgg') from matplotlib import pyplot as plt from koheron import connect from drivers import Spectrum from drivers import Laser host = os.getenv('HOST','192.168.1.100') client = connect(host, name='spectrum') driver = Spectrum(client) laser = Laser(client) laser.start() current = 30 # mA laser.set_current(current) # driver.reset_acquisition() wfm_size = 4096 decimation_factor = 1 index_low = 0 index_high = wfm_size / 2 signal = driver.get_decimated_data(decimation_factor, index_low, index_high) print('Signal') print(signal) mhz = 1e6 sampling_rate = 125e6 freq_min = 0 freq_max = sampling_rate / mhz / 2 # Plot parameters fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(freq_min, freq_max, (wfm_size / 2)) print('X') print(len(x)) y = 10*np.log10(signal) print('Y') print(len(y)) li, = ax.plot(x, y) fig.canvas.draw() ax.set_xlim((x[0],x[-1])) ax.set_ylim((0,200)) ax.set_xlabel('Frequency (MHz)') ax.set_ylabel('Power spectral density (dB)') while True: try: signal = driver.get_decimated_data(decimation_factor, index_low, index_high) li.set_ydata(10*np.log10(signal)) fig.canvas.draw() plt.pause(0.001) except KeyboardInterrupt: # Save last spectrum in a csv file np.savetxt("psd.csv", signal, delimiter=",") laser.stop() driver.close() break
mit
icdishb/scikit-learn
examples/decomposition/plot_incremental_pca.py
244
1878
""" =============== Incremental PCA =============== Incremental principal component analysis (IPCA) is typically used as a replacement for principal component analysis (PCA) when the dataset to be decomposed is too large to fit in memory. IPCA builds a low-rank approximation for the input data using an amount of memory which is independent of the number of input data samples. It is still dependent on the input data features, but changing the batch size allows for control of memory usage. This example serves as a visual check that IPCA is able to find a similar projection of the data to PCA (to a sign flip), while only processing a few samples at a time. This can be considered a "toy example", as IPCA is intended for large datasets which do not fit in main memory, requiring incremental approaches. """ print(__doc__) # Authors: Kyle Kastner # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.decomposition import PCA, IncrementalPCA iris = load_iris() X = iris.data y = iris.target n_components = 2 ipca = IncrementalPCA(n_components=n_components, batch_size=10) X_ipca = ipca.fit_transform(X) pca = PCA(n_components=n_components) X_pca = pca.fit_transform(X) for X_transformed, title in [(X_ipca, "Incremental PCA"), (X_pca, "PCA")]: plt.figure(figsize=(8, 8)) for c, i, target_name in zip("rgb", [0, 1, 2], iris.target_names): plt.scatter(X_transformed[y == i, 0], X_transformed[y == i, 1], c=c, label=target_name) if "Incremental" in title: err = np.abs(np.abs(X_pca) - np.abs(X_ipca)).mean() plt.title(title + " of iris dataset\nMean absolute unsigned error " "%.6f" % err) else: plt.title(title + " of iris dataset") plt.legend(loc="best") plt.axis([-4, 4, -1.5, 1.5]) plt.show()
bsd-3-clause
iLeoDo/SAExtractor
SAEFun/tester/LearnerTester.py
1
5133
from util import config from sklearn import cross_validation from sklearn import tree import DTreeLearner from sklearn.externals.six import StringIO import pydot import dot_parser # DTreeLearner.feature_extraction( # config.path_data+'/raw_data/data.csv', # config.path_data+'/raw_data/raw', # config.path_data+'/results2.csv', # config.path_knowledge+'/fe/featurespace2.xml') X, Y = DTreeLearner.get_data_set(config.path_data + "/results2.csv") skf = cross_validation.StratifiedKFold(Y, n_folds=10) thetas = [ { "criterion": "entropy", #"gini" "splitter": "best", #"best" "max_features": None, #None "max_depth": 6, #None "min_samples_split": 20, #2 "min_samples_leaf": 1, #1 "min_weight_fraction_leaf": 0., #0. "max_leaf_nodes": None, #None "class_weight": None, #None "random_state": None #None }, { "criterion": "gini", #"gini" "splitter": "best", #"best" "max_features": None, #None "max_depth": 6, #None "min_samples_split": 20, #2 "min_samples_leaf": 1, #1 "min_weight_fraction_leaf": 0., #0. "max_leaf_nodes": None, #None "class_weight": None, #None "random_state": None #None }, { "criterion": "gini", #"gini" "splitter": "best", #"best" "max_features": None, #None "max_depth": 12, #None "min_samples_split": 20, #2 "min_samples_leaf": 1, #1 "min_weight_fraction_leaf": 0., #0. "max_leaf_nodes": None, #None "class_weight": None, #None "random_state": None #None }, { "criterion": "gini", #"gini" "splitter": "best", #"best" "max_features": None, #None "max_depth": 4, #None "min_samples_split": 20, #2 "min_samples_leaf": 1, #1 "min_weight_fraction_leaf": 0., #0. "max_leaf_nodes": None, #None "class_weight": None, #None "random_state": None #None }, { "criterion": "gini", #"gini" "splitter": "best", #"best" "max_features": None, #None "max_depth": 8, #None "min_samples_split": 10, #2 "min_samples_leaf": 1, #1 "min_weight_fraction_leaf": 0., #0. "max_leaf_nodes": None, #None "class_weight": None, #None "random_state": None #None }, ] case_i = 0 result = [[],[],[],[],[]] for train_index, test_index in skf: X_train, X_test = [X[i] for i in train_index ], [X[i] for i in test_index] Y_train, Y_test = [Y[i] for i in train_index ], [Y[i] for i in test_index] for t in xrange(0,len(thetas)): clf = tree.DecisionTreeClassifier(**thetas[t]) clf = clf.fit(X_train, Y_train) count_false_neg = 0 count_true_pos = 0 count_false_pos = 0 count_true_neg = 0 for i in xrange(0,len(X_test)): fv = X_test[i] judge = clf.predict(fv)[0] prob = max(clf.predict_proba(fv)[0]) if int(Y_test[i]) in [1, 2]: if int(judge) in [1, 2]: count_true_pos += 1 else: count_false_neg += 1 else: if int(judge) in [1, 2]: count_false_pos += 1 else: count_true_neg += 1 recall = float(count_true_pos) / (count_true_pos + count_false_neg) precision = float(count_true_pos) / (count_true_pos + count_false_pos) fmeasure = 2*precision*recall / (precision + recall) result[t].insert(case_i,{ "recall":recall, "precision" : precision, "f-measure" : fmeasure }) if t==len(thetas)-1 and case_i==0: dot_data = StringIO() tree.export_graphviz(clf, out_file=dot_data) graph = pydot.graph_from_dot_data(dot_data.getvalue()) graph.write_pdf(config.path_data+'/dtree' + ".pdf") case_i+=1 for t in xrange(0,len(thetas)): print "\nWith theta %d:" %t print "-\t"+"\t".join(["folder %d"% c for c in xrange(0,len(result[t]))])+"\taverage" precision = [c['precision'] for c in result[t]] print "precision\t"+"\t".join([format(c, '.2%') for c in precision]) + "\t"+ format(sum(precision)/len(precision), '.2%') recall = [c['recall'] for c in result[t]] print "recall\t"+"\t".join([format(c, '.2%') for c in recall]) + "\t"+format(sum(recall)/len(recall), '.2%') fmeasure = [c['f-measure'] for c in result[t]] print "f-measure\t"+"\t".join([format(c, '.2%') for c in fmeasure]) + "\t"+format(sum(fmeasure)/len(fmeasure), '.2%') # cross_validation. # # for x in xrange(1,20): # param = config.dtree_param.copy() # # param['min_samples_leaf']=x # # print "===== x:%d =====" %x # DTreeLearner.learn_dtree( # config.path_root + "/data/dataset2/train.csv", # config.path_judge_dtree, # param # ) # # DTreeLearner.test_data( # config.path_judge_dtree, # config.path_root + "/data/dataset2/test.csv", # config.path_root + "/data/result.csv", # )
apache-2.0
ebrahimraeyat/civilTools
applications/records/MainWindow.py
1
20043
import sys import os abs_path = os.path.dirname(__file__) sys.path.insert(0, abs_path) from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5 import uic # import pandas as pd import pickle import numpy as np #from pandas.tools.plotting import table ##matplotlib.use("Agg") # from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas # import matplotlib.pyplot as plt from earthquake import addearthquake, earthquake from process import addprocess, process import pyqtgraph as pg ## Switch to using white background and black foreground pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') main_window = uic.loadUiType(os.path.join(abs_path, 'widgets', 'mainwindow.ui'))[0] class Record(QMainWindow, main_window): def __init__(self, parent=None): super(Record, self).__init__(parent) self.setupUi(self) self.dirty = False self.lastDirectory = '' self.filename = None self.create_connections() self.load_settings() self.earthquakes = {} self.min_earthquakes_dt = 1.0 self.max_eff_duration = 1.0 self.__set_labels() def create_connections(self): self.add_earth_button.clicked.connect(self.add_earthquake) self.x_radioButton.clicked.connect(self.__plot_accelerated) self.y_radioButton.clicked.connect(self.__plot_accelerated) self.z_radioButton.clicked.connect(self.__plot_accelerated) self.x_radioButton.clicked.connect(self._display_earthquake_prop) self.y_radioButton.clicked.connect(self._display_earthquake_prop) self.z_radioButton.clicked.connect(self._display_earthquake_prop) self.save_earthquakes_button.clicked.connect(self.save_earthquakes) self.load_earthquakes_button.clicked.connect(self.load_earthquakes) self.earthquake_list.currentItemChanged.connect(self.__plot_accelerated) self.earthquake_list.currentItemChanged.connect(self._display_earthquake_prop) self.clear_earths_button.clicked.connect(self.clear_earthquakes) self.interpolate_earths_button.clicked.connect(self.interpolate_earthquakes) self.scale_earths_button.clicked.connect(self.scale_earthquakes) self.unify_earth_durations_button.clicked.connect(self.unify_duration_of_earthquakes) self.action_Report.triggered.connect(self.create_report) self.s0_SpinBox.valueChanged.connect(self.draw_canai_tajimi) self.w0_SpinBox.valueChanged.connect(self.draw_canai_tajimi) self.xi0_SpinBox.valueChanged.connect(self.draw_canai_tajimi) self.start_process_button.clicked.connect(self.start_process) self.process_dir_list.currentItemChanged.connect(self.__plot_process) self.s0_process_SpinBox.valueChanged.connect(self.draw_process_canai_tajimi) self.w0_process_SpinBox.valueChanged.connect(self.draw_process_canai_tajimi) self.xi0_process_SpinBox.valueChanged.connect(self.draw_process_canai_tajimi) def load_settings(self): qsettings = QSettings("civiltools", "records") self.restoreGeometry(qsettings.value( "geometry", self.saveGeometry())) self.restoreState(qsettings.value( "saveState", self.saveState())) self.move(qsettings.value( "pos", self.pos())) self.resize(qsettings.value( "size", self.size())) self.splitter.restoreState(qsettings.value("splitter", self.splitter.saveState())) self.splitter1.restoreState(qsettings.value("splitter1", self.splitter1.saveState())) def closeEvent(self, event): if (self.dirty and QMessageBox.question(self, "earthquakes - Save?", "Save unsaved changes?", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) == QMessageBox.Yes): self.save_earthquakes() qsettings = QSettings("civiltools", "records") qsettings.setValue( "geometry", self.saveGeometry() ) qsettings.setValue( "saveState", self.saveState() ) qsettings.setValue( "pos", self.pos() ) qsettings.setValue( "size", self.size() ) qsettings.setValue("splitter", self.splitter.saveState()) qsettings.setValue("splitter1", self.splitter1.saveState()) event.accept() def save_earthquakes(self): filename, _ = QFileDialog.getSaveFileName(self, 'save earthquakes', self.lastDirectory) if not filename: return l = {'min_dt':self.min_earthquakes_dt, 'max_eff_duration': self.max_eff_duration, 'earthquakes': self.earthquakes} pickle.dump(l, open(filename, "wb")) self.dirty = False def load_earthquakes(self): filename, _ = QFileDialog.getOpenFileName(self, 'open earthquakes', self.lastDirectory) if not filename: return l = pickle.load(open(filename, "rb")) self.min_earthquakes_dt = l['min_dt'] self.max_eff_duration = l['max_eff_duration'] self.earthquakes = l['earthquakes'] self.earthquake_list.clear() self.earthquake_list.addItems(self.earthquakes.keys()) # for earthquake in self.earthquakes.values(): # for acc in earthquake.accelerations.values(): # acc.reset_prop() if self.earthquake_list.count() > 0: self.earthquake_list.setCurrentRow(0) self.min_dt_label.setText(f"min = {self.min_earthquakes_dt}") def add_earthquake(self): win = addearthquake.AddEarthquakeWin(self) if win.exec_(): new_earthquake = earthquake.Earthquake(win.accelerated['x'], win.accelerated['y'], win.accelerated['z']) if new_earthquake.dt < self.min_earthquakes_dt: self.min_earthquakes_dt = new_earthquake.dt if new_earthquake.eff_duration > self.max_eff_duration: self.max_eff_duration = new_earthquake.eff_duration name = '{}_{}'.format(new_earthquake.name, new_earthquake.station) self.earthquakes[name] = new_earthquake self.earthquake_list.addItem(name) if self.earthquake_list.count() == 1: self.earthquake_list.setCurrentRow(0) self.min_dt_label.setText(f"min = {self.min_earthquakes_dt}") self.dirty = True def __plot_accelerated(self): if not self.earthquake_list.count(): return if self.earthquake_list.currentRow() == -1: return self.__clear_accelerated_plot() direction = self.__direction() earthquake_name = self.earthquake_list.currentItem().text() earthquake = self.earthquakes[earthquake_name] accelerated = earthquake.accelerations[direction] self.accelerated_time_history.plot(accelerated.time, accelerated.acc) self.accelerated_density_func.plot(accelerated.x[:-1], accelerated.density_func.values) self.accelerated_distributed_func.plot(accelerated.x[:-1], accelerated.distribute_func.values) self.accelerated_r_tow.plot(accelerated.tow, accelerated.r_tow) self.accelerated_s_w.plot(accelerated.ws, accelerated.s_w) self.fourier_amplitude.plot(accelerated.freq, accelerated.fourier_amplitude) # print(dir(self.accelerated_time_history)) # self.accelerated_s_w.plot(accelerated.ws_canai, accelerated.s_w_canai) def __set_labels(self): self.accelerated_time_history.setLabel('bottom', text='Time [sec]') self.accelerated_time_history.setLabel('left', text="Acc [g]") self.accelerated_density_func.setLabel('bottom', text='Acc [g]') self.accelerated_density_func.setLabel('left', text='%') self.accelerated_density_func.setTitle('Probability Density Function (PDF)') self.accelerated_distributed_func.setLabel('bottom', text='Acc [g]') self.accelerated_distributed_func.setLabel('left', text="%") self.accelerated_distributed_func.setTitle('Cumulative Distribution Function (CDF)') self.accelerated_r_tow.setLabel('bottom', text='<font>&tau;</font> [Sec]') self.accelerated_r_tow.setLabel('left', text='[g] ^ 2') self.accelerated_r_tow.setTitle('Auto Correlation Function') self.accelerated_s_w.setLabel('bottom', text='<font>&omega;</font> [Hz]') self.accelerated_s_w.setLabel('left', text='[g] ^ 2 - rad - Sec') self.accelerated_s_w.setTitle('Density Function') self.fourier_amplitude.setLabel('bottom', text='<font>&omega;</font> [Hz]') self.fourier_amplitude.setLabel('left', text="Fourier Amplitude") self.fourier_amplitude.setTitle('Frequency content') # process labels # self.process_expexted_pow1.setLabel('bottom', text='Time [sec]') self.process_expexted_pow1.setLabel('left', text="Acc [g]") self.process_expexted_pow1.setTitle('E[X]') # self.process_expexted_pow2.setLabel('bottom', text='Time [sec]') self.process_expexted_pow2.setLabel('left', text="Acc [g]") self.process_expexted_pow2.setTitle('E[X<sup>2</sup>]') self.process_expexted_pow3.setLabel('bottom', text='Time [sec]') self.process_expexted_pow3.setLabel('left', text="Acc [g]") self.process_expexted_pow3.setTitle('E[X<sup>3</sup>]') self.process_r_tow.setLabel('bottom', text='<font>&tau;</font> [Sec]') self.process_r_tow.setLabel('left', text='[g] ^ 2') self.process_r_tow.setTitle('Auto Correlation Function') self.process_s_w.setLabel('bottom', text='<font>&omega;</font> [Hz]') self.process_s_w.setLabel('left', text='[g] ^ 2 - rad - Sec') self.process_s_w.setTitle('Density Function') def interpolate_earthquakes(self): dt = self.dt_SpinBox.value() if dt == 0: dt = self.min_earthquakes_dt if (self.earthquake_list.count() and QMessageBox.question(self, "interpolate - earthquakes?", f"interpolate all earthquakes with dt = {dt}?", QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes): for i, earthquake in enumerate(self.earthquakes.values()): earthquake.interpolate_earthquake(dt) self.update_progressBar(i) self.__plot_accelerated() self.dt_SpinBox.setValue(dt) QMessageBox.information(self, "Successful !", f"All earthquakes Interpolated to dt = {dt}") self.update_progressBar(-1) self.min_dt_label.setText(f"min = {self.min_earthquakes_dt}") self.dirty = True def scale_earthquakes(self): sf = self.scale_SpinBox.value() if sf == 0: sf = 1 if (self.earthquake_list.count() and QMessageBox.question(self, "scale - earthquakes?", f"scale all earthquakes to {sf} g?", QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes): for i, earthquake in enumerate(self.earthquakes.values()): earthquake.scale(sf) self.update_progressBar(i) self.__plot_accelerated() QMessageBox.information(self, "Successful !", f"All earthquakes Scaled to Acceleration = {sf} g") self.update_progressBar(-1) self.dirty = True def unify_duration_of_earthquakes(self): duration = self.unify_duration_SpinBox.value() if duration == 0: duration = self.max_eff_duration if (self.earthquake_list.count() and QMessageBox.question(self, "unify duration - earthquakes?", f"unify duration of all earthquakes to {duration} sec?", QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes): for i, earthquake in enumerate(self.earthquakes.values()): earthquake.cut(duration) print(earthquake.name, earthquake.number_of_points) self.update_progressBar(i) self.__plot_accelerated() QMessageBox.information(self, "Successful !", f"All earthquakes unified to duration = {duration} Sec") self.update_progressBar(-1) self.dirty = True def update_progressBar(self, i): self.progressBar.setValue(100 * (i + 1) / len(self.earthquakes)) def __clear_accelerated_plot(self): self.accelerated_time_history.clear() self.accelerated_density_func.clear() self.accelerated_distributed_func.clear() self.accelerated_r_tow.clear() self.accelerated_s_w.clear() self.fourier_amplitude.clear() def draw_canai_tajimi(self): if not self.earthquake_list.count(): return if self.earthquake_list.currentRow() == -1: return s0 = self.s0_SpinBox.value() w0 = self.w0_SpinBox.value() xi0 = self.xi0_SpinBox.value() direction = self.__direction() earthquake_name = self.earthquake_list.currentItem().text() earthquake = self.earthquakes[earthquake_name] accelerated = earthquake.accelerations[direction] ws_canai, s_w_canai = accelerated.canai_tajimis(s0, w0, xi0) pen = pg.mkPen('b', width=1) try: self.accelerated_s_w.removeItem(self.canai_item) except: pass self.canai_item = pg.PlotDataItem(ws_canai, s_w_canai, connect="finite", pen=pen) self.accelerated_s_w.addItem(self.canai_item) def clear_earthquakes(self): if (self.earthquake_list.count() and QMessageBox.question(self, "clear - earthquakes?", "clear all earthquakes?", QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes): self.__clear_accelerated_plot() self.earthquake_list.clear() self.earthquakes = {} def _display_earthquake_prop(self): if self.earthquake_list.currentItem() is None: return earthquake_name = self.earthquake_list.currentItem().text() earthquake = self.earthquakes[earthquake_name] direction = self.__direction() accelerated = earthquake.accelerations[direction] s = earthquake.__str__() + accelerated.__str__() self.earth_prop_textEdit.setText(s) def create_report(self): pass # exporter = pg.exporters.ImageExporter(self.accelerated_time_history.plotItem) # # save to file # exporter.export('fileName.png') def __direction(self): ''' return direction that selected in earthquake direction groupbox ''' if self.x_radioButton.isChecked(): return 'x' if self.y_radioButton.isChecked(): return 'y' return 'z' # ax = self.figure.add_subplot(311) # plotWidget = Work_on_record_file(self.filename, .005) # plotWidget.acc.plot(title='Acceleration', ax=ax, legend=None) # ax = self.figure.add_subplot(312) # plotWidget.density_function.plot(title='density function', ax=ax, kind='bar', legend=None) # ax = self.figure.add_subplot(313) # #table(ax, sr_info, loc='center right', fontsize=30, colWidths=[0.1]) # plotWidget.distribute_function.plot(title='distribute function', ax=ax, legend=None) # self.canvas.draw() # sr_info = pd.Series(plotWidget.return_dict) # html = '' # for key, value in sr_info.iteritems(): # html += '<p>{}: {}</p>\n'.format(key, value) # self.info_text_browser.setHtml(html) def start_process(self): win = addprocess.ProcessWin(self.earthquakes, self) if win.exec_(): self.process = {} for direction, e in win.process.items(): pro = process.Process(e) pro.set_properties() pro.reset_prop() self.process[direction] = pro self.process_list.clear() self.process_list.addItems([*pro.accelerations.keys()]) self.__plot_process() def __plot_process(self): if self.process_dir_list.currentItem() is None: return self.__clear_process_plot() direction = self.process_dir_list.currentItem().text() pro = self.process[direction] self.process_r_tow.plot(pro.tow, pro.r_tow) self.process_s_w.plot(pro.ws, pro.s_w) self.process_expexted_pow1.plot(pro.time, pro.ex) self.process_expexted_pow2.plot(pro.time, pro.ex2) self.process_expexted_pow3.plot(pro.time, pro.ex3) # self.process_density_func.plot(pro.x[:-1], pro.density_func) # print(self.process) def __clear_process_plot(self): self.process_r_tow.clear() self.process_s_w.clear() self.process_expexted_pow1.clear() self.process_expexted_pow2.clear() self.process_expexted_pow3.clear() # self.process_density_func.clear() def draw_process_canai_tajimi(self): if not self.process_list.count(): return if self.process_dir_list.currentRow() == -1: return s0 = self.s0_process_SpinBox.value() w0 = self.w0_process_SpinBox.value() xi0 = self.xi0_process_SpinBox.value() process = self.process['X'] ws_canai, s_w_canai = process.canai_tajimis(s0, w0, xi0) pen = pg.mkPen('b', width=1) try: self.process_s_w.removeItem(self.canai_process_item) except: pass self.canai_process_item = pg.PlotDataItem(ws_canai, s_w_canai, connect="finite", pen=pen) self.process_s_w.addItem(self.canai_process_item) # for e in selected_earthquakes: # x_process = # new_earthquake = earthquake.Earthquake(win.accelerated['x'], win.accelerated['y'], win.accelerated['z']) # if new_earthquake.dt < self.min_earthquakes_dt: # self.min_earthquakes_dt = new_earthquake.dt # if new_earthquake.eff_duration > self.max_eff_duration: # self.max_eff_duration = new_earthquake.eff_duration # name = '{}_{}'.format(new_earthquake.name, new_earthquake.station) # self.earthquakes[name] = new_earthquake # self.earthquake_list.addItem(name) # if self.earthquake_list.count() == 1: # self.earthquake_list.setCurrentRow(0) # self.min_dt_label.setText(f"min = {self.min_earthquakes_dt}") self.dirty = True def getLastSaveDirectory(self, f): return os.sep.join(f.split(os.sep)[:-1]) def getFilename(self, prefixes): filters = '' for prefix in prefixes: filters += "{}(*.{})".format(prefix, prefix) filename = QFileDialog.getSaveFileName(self, ' خروجی ', self.lastDirectory, filters) if filename == '': return self.lastDirectory = self.getLastSaveDirectory(filename) return filename if __name__ == "__main__": app = QApplication(sys.argv) # pixmap = QPixmap("./images/run.png") # splash = QSplashScreen(pixmap) # splash.show() # app.processEvents() global defaultPointsize font = QFont() font.setFamily("Tahoma") if sys.platform.startswith('linux'): defaultPointsize = 10 font.setPointSize(defaultPointsize) else: defaultPointsize = 9 font.setPointSize(defaultPointsize) app.setFont(font) app.setOrganizationName("Ebrahim Raeyat") app.setOrganizationDomain("ebrahimraeyat.blog.ir") app.setApplicationName("section prop") #app.setWindowIcon(QIcon(":/icon.png")) window = Record() window.show() app.exec_()
gpl-3.0
bhatiaharsh/naturalHHD
pynhhd-v1.1/examples/utils/drawing.py
1
3712
''' Copyright (c) 2015, Harsh Bhatia (bhatia4@llnl.gov) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # discretize a colormap into n levels def discretize_colormap(cmap, n): # extract all colors from the cmap cmaplist = [cmap(i) for i in range(cmap.N)] for i in range(n): oidx = i * float(cmap.N)/float(n) cmaplist[i] = cmap( int(oidx) ) # create the new map return cmap.from_list('Custom cmap', cmaplist, n) # draw streamlines on a regular grid def draw_slines(X, Y, u, v, vrng): mgn = np.sqrt(u*u + v*v) strm = plt.streamplot(X, Y, u, v, color=mgn, linewidth=2, cmap=plt.cm.autumn) plt.clim(vmin=vrng[0], vmax=vrng[1]) frame = plt.gca() frame.axes.get_xaxis().set_visible(False) frame.axes.get_yaxis().set_visible(False) frame.axes.set_aspect('equal') #, 'datalim') plt.colorbar(strm.lines) # draw streamlines on a triangulation def draw_quivers(points, vfield, vrng, n=20): s = 350 X = points[::n,0] Y = points[::n,1] u = vfield[::n,0] v = vfield[::n,1] mgn = np.linalg.norm(vfield, axis=1) strm = plt.quiver(X,Y,u,v,mgn,pivot='tail',cmap=plt.cm.autumn,scale=s,scale_units='width',width=0.005) plt.clim(vmin=vrng[0], vmax=vrng[1]) #frame = plt.gca() #frame.axes.get_xaxis().set_visible(False) #frame.axes.get_yaxis().set_visible(False) #frame.axes.set_aspect('equal') #, 'datalim')) plt.colorbar() # ------------------------------------------------------------------------------ def draw_scatter3D(positions, normals=None, color=None, alpha=1, ax=None): if ax == None: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_aspect('equal', 'datalim') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') if color == None: color = 'r' ax.scatter(positions[:,0], positions[:,1], positions[:,2], c=color, marker='.', alpha=alpha) if (normals != None): ax.quiver( positions[:,0], positions[:,1], positions[:,2], normals[:,0], normals[:,1], normals[:,2], length=10,pivot='tail',color='cyan') # ------------------------------------------------------------------------------
bsd-2-clause
JonasWallin/BayesFlow
src/tests/pipeline.py
1
13575
from __future__ import division import os import time import tempfile import imp import shutil from mpi4py import MPI import numpy as np import matplotlib.pyplot as plt from .. import setup_sim, hierarical_mixture_mpi, HMlogB, HMElog, HMres from ..exceptions import BadQualityError from ..utils import load_fcdata from ..utils.initialization.EM import (EMD_to_generated_from_model, data_log_likelihood) from ..utils.initialization.PSO import HGMM_pre_burnin from ..utils.initialization.distributed_data import DataMPI from ..PurePython.GMM import mixture from ..exceptions import NoOtherClusterError from ..PurePython.distribution.wishart import invwishartrand def some_small_clusters_some_empty(K, q): p = np.ones(K) p[np.random.randint(K, size=int(K*q))] = 0.05 p[np.random.randint(K, size=int(K*q))] = 0 return p/np.sum(p) def one_small_rare_cluster(K): p = np.ones(K) if np.random.rand() < 1: # 0.2: p[0] = 0.002 else: p[0] = 0 return p/np.sum(p) p_fun_dict = { 'A': lambda K: np.ones(K)/K, 'B': lambda K: some_small_clusters_some_empty(K, 0.25), 'C': lambda K: one_small_rare_cluster(K) } class SynSamp(object): def __init__(self, j, n_obs, d, C, ver='A'): self.d = d self.C = C # Number of clusters. self.n_obs = n_obs self.name = str(j) self.ver = ver def generate_data(self, savedir): ''' Generate data and save ''' #Y = mixture.simulate_mixture(self.mu, self.sigma, self.p, self.n_obs) np.savetxt(os.path.join(savedir, self.name+'.txt'), self.data) @property def data(self): return mixture.simulate_mixture(self.mu, self.sigma, self.p, self.n_obs) @property def p(self): return p_fun_dict[self.ver](self.C) class SynSample(SynSamp): def __init__(self, j, n_obs, d=3, C=4, ver='A'): super(SynSample, self).__init__(j, n_obs, d, C, ver) self.mu = [np.repeat(k+0.1*(j % 5), self.d) for k in range(self.C)] self.sigma = [invwishartrand(self.d+1+5*(k+1)**2, np.eye(self.d)*0.01*5*(k+1)**2) for k in range(self.C)] class SynSample2(SynSamp): def __init__(self, j, n_obs, d=2, C=None, ver='A'): super(SynSample2, self).__init__(j, n_obs, d, C, ver) self.mu = [tuple(int(i) for i in "{0:0{width}b}".format(k, width=d)) for k in range(2**d)] # all corners of d-dimensional cube self.mu = [np.array(mu)+0.1*(j % 3) for mu in self.mu] self.C = len(self.mu) # Number of clusters. self.sigma = [np.eye(self.d)*0.05 for k in range(self.C)] class Pipeline(object): def __init__(self, J, K, N, d, C=None, data_class=SynSample, ver='A', par_file='src/tests/param/0.py', run=None, copy_data=False, comm=MPI.COMM_WORLD): self.comm = comm self.rank = comm.Get_rank() self.J = J self.K = K # Number of components. self.N = N self.savedir = 'blah' # tempfile.mkdtemp() print("savedir = {}".format(self.savedir)) self.datadir = os.path.join(self.savedir, 'data') if self.rank == 0: js = np.array_split(np.arange(J), comm.Get_size()) else: js = None js = self.comm.scatter(js) self.synsamples = [data_class(j, N, d, C, ver=ver) for j in js] self.d = self.synsamples[0].d self.parfile = par_file self.data_kws = {'scale': 'percentilescale', 'loadfilef': lambda filename: np.loadtxt(filename), 'ext': '.txt', 'datadir': self.datadir, 'overwrite_eventind': True} self.metadata = {'marker_lab': [str(i+1) for i in range(self.d)]} self.logdata = {} if not run is None: self.run_nbr = run self.rundir = os.path.join(self.savedir, 'run'+str(self.run_nbr)) self.copy_data = copy_data def generate_data(self): if self.rank == 0: if not os.path.exists(self.datadir): os.mkdir(self.datadir) self.comm.Barrier() self.names = [] for synsamp in self.synsamples: synsamp.generate_data(self.datadir) self.names.append(synsamp.name) def setup_run(self): if not hasattr(self, 'run_nbr'): self.rundir, self.run_nbr = setup_sim(self.savedir, setupfile=self.parfile, comm=self.comm) if self.copy_data: datadir = self.data_kws['datadir'] run_datadir = os.path.join(self.rundir, 'data') if self.rank == 0: if not os.path.exists(run_datadir): os.mkdir(run_datadir) self.comm.Barrier() for name in self.names: shutil.copy(os.path.join(datadir, name+self.data_kws['ext']), run_datadir) if self.rank == 0: eventind_dir = os.path.join(datadir, 'eventinds') shutil.copytree(eventind_dir, os.path.join(run_datadir, 'eventinds')) try: self.bf_setup = imp.load_source('src.tests.param.setup', self.parfile).setup except IOError as e: print("Setupfile {} does not exist".format(self.parfile)) print("Setupdir has files: {}".format(os.listdir(os.path.split(self.parfile)[0]))) raise e self.Nevent = np.mean([synsamp.n_obs for synsamp in self.synsamples]) self.prior, self.simpar, self.postpar = self.bf_setup( self.comm, self.J, self.Nevent, self.d, K=self.K) def init_hGMM(self, method='EM_pooled', WIS=False, rho=2, n_iter=20, n_init=10, plotting=False, selection='likelihood', gamma=2): ''' Load prior, initialize hGMM, load data ''' self.hGMM = hierarical_mixture_mpi(K=self.prior.K, AMCMC=self.simpar.AMCMC, comm=self.comm) #sampnames = sampnames_scattered(self.comm, self.datadir, self.data_kws['ext']) #print("sampnames before load: {}".format(sampnames)) self.hGMM.load_data(self.names, **self.data_kws) print("after load data") self.hGMM.set_prior(prior=self.prior, init=False) t0 = time.time() self.hGMM.set_init(self.prior, method=method, WIS=WIS, N=int(self.Nevent*self.J/100), rho=rho, n_iter=n_iter, n_init=n_init, plotting=plotting, selection=selection, gamma=gamma) t1 = time.time() self.logdata['t_init'] = t1-t0 self.hGMM.toggle_timing() def pre_burnin(self): t0 = time.time() HGMM_pre_burnin(self.hGMM) t1 = time.time() print("pre burnin: {} s".format(t1 - t0)) def MCMC(self, plot_sim=False, save_hGMM=False): ''' Burn-in iterations ''' printfrq = 100 sim_settings = {'printfrq': printfrq, 'stop_if_cl_off': False, 'plotting': plot_sim, 'plotdim': [[0, 1]]} t0 = time.time() self.hGMM.resize_var_priors(self.simpar.tightinitfac) self.hGMM.simulate(self.simpar.phases['B1a'], 'Burnin phase 1a', **sim_settings) self.hGMM.resize_var_priors(1./self.simpar.tightinitfac) self.hGMM.simulate(self.simpar.phases['B1b'], 'Burnin phase 1b', **sim_settings) self.hGMM.set_theta_to_median() #print("any deactivated at rank {}: {}".format(self.comm.Get_rank(), self.hGMM.deactivate_outlying_components())) self.hGMM.set_GMMs_mu_Sigma_from_prior() self.comm.Barrier() self.hGMM.simulate(self.simpar.phases['B2a'], 'Burnin phase 2a', **sim_settings) self.hGMM.simulate(self.simpar.phases['B2b'], 'Burnin phase 2b', **sim_settings) self.hGMM.simulate(self.simpar.phases['B3'], 'Burnin phase 3', **sim_settings) self.hGMM.save_burnlog(self.rundir) t1 = time.time() ''' Production iterations ''' self.hGMM.simulate(self.simpar.phases['P'], 'Production phase', **sim_settings) self.hGMM.save_log(self.rundir) t2 = time.time() print('burnin iterations ({}) and postproc: {} s'.format( self.simpar.nbriter*self.simpar.qburn, t1-t0)) print('production iterations ({}) and postproc: {} s'.format( self.simpar.nbriter*self.simpar.qprod, t2-t1)) if save_hGMM: self.hGMM.save(self.rundir) del self.hGMM def load_res(self, comm=MPI.COMM_SELF): blog = HMlogB.load(self.rundir, comm=comm) self.logdata['lab_sw'] = blog.lab_sw log = HMElog.load(self.rundir, comm=comm) if self.copy_data: data_kws = self.data_kws.copy() data_kws['datadir'] = os.path.join(self.rundir, 'data') else: data_kws = self.data_kws data = load_fcdata(log.names, comm=comm, **data_kws) self.metadata['samp'] = {'names': log.names} self.res = HMres(log, blog, data, self.metadata, comm=comm) def postproc(self, comm=MPI.COMM_SELF): self.load_res(comm) self.res.merge(self.postpar.mergemeth, **self.postpar.mergekws) @property def number_label_switches(self): return len(self.logdata['lab_sw']) def quality_check(self): print("self.res.active_komp = {}".format(self.res.active_komp)) self.res.traces.plot.all(figsize=(18, 4), yscale=True) self.res.traces.plot.nu() self.res.traces.plot.nu_sigma() plt.show() print("Are trace plots ok? (y/n)") while 1: ans = raw_input() if ans.lower() == 'y': break if ans.lower() == 'n': raise BadQualityError('Trace plots not ok') print("Bad answer. Are trace plots ok? (y/n)") fig, axs = plt.subplots(self.res.K, 2, figsize=(9, 4)) try: self.res.components.plot.center_distance_quotient(axs=axs[:, 0]) self.res.components.plot.bhattacharyya_overlap_quotient(axs=axs[:, 1]) except NoOtherClusterError: print("Only one super component, cannot plot center distance \ and bhattacharyya overlap quotients.") pass self.res.components.plot.cov_dist(figsize=(4, 4)) plt.show() print("Are distances to latent components ok? (y/n)") while 1: ans = raw_input() if ans.lower() == 'y': break if ans.lower() == 'n': raise BadQualityError('Distance to latent components not ok') print("Bad answer. Are distance to latent components ok? (y/n)") emds, e_dim = self.res.earth_movers_distance_to_generated() log_lik = np.empty(self.J) data_mpi = [DataMPI(MPI.COMM_SELF, [dat]) for dat in self.res.data] for j, dat_mpi in enumerate(data_mpi): mus, Sigmas, pis = self.res.get_mix(j) log_lik[j] = data_log_likelihood(dat_mpi, mus, Sigmas, pis) return emds, log_lik def plot(self): plotdim = [[i, j] for i in range(self.d) for j in range(i+1, self.d)] fig_m, axs = plt.subplots(len(self.res.mergeind), 3, figsize=(9, 6)) self.res.components.plot.center(yscale=False, alpha=0.3, axs=axs[:, 0]) self.res.plot.box(axs=axs[:, 1]) self.res.plot.prob(axs=axs[:, 2]) fig, axs = plt.subplots(self.res.K, 3, figsize=(9, 6)) self.res.components.plot.center(suco=False, yscale=False, axs=axs[:, 0]) self.res.plot.box(suco=False, axs=axs[:, 1]) self.res.plot.prob(suco=False, axs=axs[:, 2]) mimicnames = self.res.mimics.keys() self.res.plot.component_fit(plotdim, name=mimicnames[-1], figsize=(18, 25)) self.res.plot.component_fit(plotdim, name='pooled', figsize=(18, 25)) def clean_up(self): print("removing savedir {} ...".format(self.savedir)) try: pass #shutil.rmtree(self.savedir) except Exception as e: print("Could not remove savedir {}: {}".format(self.savedir, e)) else: print("removing savedir {} done".format(self.savedir)) def run(self, init_method='EM_pooled', WIS=False, rho=2, init_n_iter=20, n_init=10, init_plotting=False, init_selection='likelihood', gamma=2, plot_sim=False, pre_burnin=True, save_hGMM=False): if 1: self.generate_data() self.setup_run() self.init_hGMM(method=init_method, WIS=WIS, rho=rho, n_iter=init_n_iter, n_init=n_init, plotting=init_plotting, selection=init_selection, gamma=gamma) print("prior vals: {}".format(self.hGMM.prior.__dict__)) if pre_burnin: self.pre_burnin() self.MCMC(plot_sim, save_hGMM=save_hGMM) if self.rank == 0: self.postproc(MPI.COMM_SELF) # except Exception as e: # self.clean_up() # raise e # else: # self.clean_up() if __name__ == '__main__': pipeline = Pipeline(J=6, K=8, N=1000, d=3, C=4, data_class=SynSample, ver='A', par_file='src/tests/param/0.py') pipeline.run(plot_sim=True) if pipeline.rank == 0: pipeline.quality_check() pipeline.plot() plt.show()
gpl-2.0
shahankhatch/scikit-learn
examples/linear_model/plot_sgd_loss_functions.py
249
1095
""" ========================== SGD: convex loss functions ========================== A plot that compares the various convex loss functions supported by :class:`sklearn.linear_model.SGDClassifier` . """ print(__doc__) import numpy as np import matplotlib.pyplot as plt def modified_huber_loss(y_true, y_pred): z = y_pred * y_true loss = -4 * z loss[z >= -1] = (1 - z[z >= -1]) ** 2 loss[z >= 1.] = 0 return loss xmin, xmax = -4, 4 xx = np.linspace(xmin, xmax, 100) plt.plot([xmin, 0, 0, xmax], [1, 1, 0, 0], 'k-', label="Zero-one loss") plt.plot(xx, np.where(xx < 1, 1 - xx, 0), 'g-', label="Hinge loss") plt.plot(xx, -np.minimum(xx, 0), 'm-', label="Perceptron loss") plt.plot(xx, np.log2(1 + np.exp(-xx)), 'r-', label="Log loss") plt.plot(xx, np.where(xx < 1, 1 - xx, 0) ** 2, 'b-', label="Squared hinge loss") plt.plot(xx, modified_huber_loss(xx, 1), 'y--', label="Modified Huber loss") plt.ylim((0, 8)) plt.legend(loc="upper right") plt.xlabel(r"Decision function $f(x)$") plt.ylabel("$L(y, f(x))$") plt.show()
bsd-3-clause
strint/tensorflow
tensorflow/contrib/learn/python/learn/grid_search_test.py
137
2035
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Grid search tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import random from tensorflow.contrib.learn.python import learn from tensorflow.python.platform import test HAS_SKLEARN = os.environ.get('TENSORFLOW_SKLEARN', False) if HAS_SKLEARN: try: # pylint: disable=g-import-not-at-top from sklearn import datasets from sklearn.grid_search import GridSearchCV from sklearn.metrics import accuracy_score except ImportError: HAS_SKLEARN = False class GridSearchTest(test.TestCase): """Grid search tests.""" def testIrisDNN(self): if HAS_SKLEARN: random.seed(42) iris = datasets.load_iris() feature_columns = learn.infer_real_valued_columns_from_input(iris.data) classifier = learn.DNNClassifier( feature_columns=feature_columns, hidden_units=[10, 20, 10], n_classes=3) grid_search = GridSearchCV( classifier, {'hidden_units': [[5, 5], [10, 10]]}, scoring='accuracy', fit_params={'steps': [50]}) grid_search.fit(iris.data, iris.target) score = accuracy_score(iris.target, grid_search.predict(iris.data)) self.assertGreater(score, 0.5, 'Failed with score = {0}'.format(score)) if __name__ == '__main__': test.main()
apache-2.0
scienceopen/hist-feasibility
Plots/EMCCD_fiducial.py
2
1130
#!/usr/bin/env python """ creates EMCCD fiducials for TGARS 2015 Reconstruction of fine scale auroral Dyanmics paper figure """ from numpy import array,rot90 import imageio from matplotlib.pyplot import show # from pathlib import Path from histfeas.fiducial import fiducial #%% EMCCD Figure path = '~/data/2007-03/optical' ccdflist = ('1132.png','1147.png','1162.png','1177.png') ccdcal= '~/data/CMOS/X1387_03_23_2007_031836.mat' xycrop=(0,0) # ccdfid(path/ccdflist[0],ccdcal) oxyfull = [222,190] wh0 = (140,140) pstr=('0s','0.5s','1.0s','1.5s') lblring = array((89,87,85)) ringmult=90-lblring rings=(True,False,False,False) rays=(False,False,False,False) # set first True, and oxyfull to geographic zenith to plot ray pointing to magnetic zentih path = Path(path).expanduser() for f,ring,ray,p in zip(ccdflist,rings,rays,pstr): imgfn = path/f outfn = path/('anno_' + f) try: img = imageio.imread(str(imgfn)) img = rot90(img,-1) except FileNotFoundError: continue fiducial(img, xycrop[0], xycrop[1], outfn, ring, ray, p, oxyfull,wh0,lblring,ringmult,wh0) show()
gpl-3.0
iandriver/RNA-sequence-tools
test_count_matrix.py
2
1472
import os import pandas as pd import cPickle as pickle import subprocess import csv def make_count_matrix(dirs_in): count_dict = {} single_file_stop = True rows =[] headers = ['Gene_ID'] for p in dirs_in: head_stop = True for root, dirnames, filenames in os.walk(p): cname = root.split('/')[-1] hts_out = os.path.join(root,cname+'_htseqcount.txt') for f in filenames: if cname+'_htseqcount.txt' == f: with open(hts_out, mode='r') as infile: hts_tab = csv.reader(infile, delimiter = '\t') for i, l in enumerate(hts_tab): if head_stop == 1: headers.append(cname) if single_file_stop: rows.append({'Gene_ID':l[0], cname:l[1]}) else: rows[i][cname] = l[1] single_file_stop = False head_stop = False with open(os.path.join('/Volumes/Seq_data', 'spc2_counts.txt'), "wb") as outfile: writer = csv.DictWriter(outfile, headers, delimiter = "\t") writer.writeheader() writer.writerows(rows) pats = ['/Volumes/Seq_data/results_Lane1_data', '/Volumes/Seq_data/results_Lane2_data', '/Volumes/Seq_data/results_Lane3_data', '/Volumes/Seq_data/results_Lane4_data'] make_count_matrix(pats)
mit
KaelChen/numpy
numpy/core/code_generators/ufunc_docstrings.py
51
90047
""" Docstrings for generated ufuncs The syntax is designed to look like the function add_newdoc is being called from numpy.lib, but in this file add_newdoc puts the docstrings in a dictionary. This dictionary is used in numpy/core/code_generators/generate_umath.py to generate the docstrings for the ufuncs in numpy.core at the C level when the ufuncs are created at compile time. """ from __future__ import division, absolute_import, print_function docdict = {} def get(name): return docdict.get(name) def add_newdoc(place, name, doc): docdict['.'.join((place, name))] = doc add_newdoc('numpy.core.umath', 'absolute', """ Calculate the absolute value element-wise. Parameters ---------- x : array_like Input array. Returns ------- absolute : ndarray An ndarray containing the absolute value of each element in `x`. For complex input, ``a + ib``, the absolute value is :math:`\\sqrt{ a^2 + b^2 }`. Examples -------- >>> x = np.array([-1.2, 1.2]) >>> np.absolute(x) array([ 1.2, 1.2]) >>> np.absolute(1.2 + 1j) 1.5620499351813308 Plot the function over ``[-10, 10]``: >>> import matplotlib.pyplot as plt >>> x = np.linspace(start=-10, stop=10, num=101) >>> plt.plot(x, np.absolute(x)) >>> plt.show() Plot the function over the complex plane: >>> xx = x + 1j * x[:, np.newaxis] >>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10]) >>> plt.show() """) add_newdoc('numpy.core.umath', 'add', """ Add arguments element-wise. Parameters ---------- x1, x2 : array_like The arrays to be added. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which may be the shape of one or the other). Returns ------- add : ndarray or scalar The sum of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. Notes ----- Equivalent to `x1` + `x2` in terms of array broadcasting. Examples -------- >>> np.add(1.0, 4.0) 5.0 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.add(x1, x2) array([[ 0., 2., 4.], [ 3., 5., 7.], [ 6., 8., 10.]]) """) add_newdoc('numpy.core.umath', 'arccos', """ Trigonometric inverse cosine, element-wise. The inverse of `cos` so that, if ``y = cos(x)``, then ``x = arccos(y)``. Parameters ---------- x : array_like `x`-coordinate on the unit circle. For real arguments, the domain is [-1, 1]. out : ndarray, optional Array of the same shape as `a`, to store results in. See `doc.ufuncs` (Section "Output arguments") for more details. Returns ------- angle : ndarray The angle of the ray intersecting the unit circle at the given `x`-coordinate in radians [0, pi]. If `x` is a scalar then a scalar is returned, otherwise an array of the same shape as `x` is returned. See Also -------- cos, arctan, arcsin, emath.arccos Notes ----- `arccos` is a multivalued function: for each `x` there are infinitely many numbers `z` such that `cos(z) = x`. The convention is to return the angle `z` whose real part lies in `[0, pi]`. For real-valued input data types, `arccos` always returns real output. For each value that cannot be expressed as a real number or infinity, it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `arccos` is a complex analytic function that has branch cuts `[-inf, -1]` and `[1, inf]` and is continuous from above on the former and from below on the latter. The inverse `cos` is also known as `acos` or cos^-1. References ---------- M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/ Examples -------- We expect the arccos of 1 to be 0, and of -1 to be pi: >>> np.arccos([1, -1]) array([ 0. , 3.14159265]) Plot arccos: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-1, 1, num=100) >>> plt.plot(x, np.arccos(x)) >>> plt.axis('tight') >>> plt.show() """) add_newdoc('numpy.core.umath', 'arccosh', """ Inverse hyperbolic cosine, element-wise. Parameters ---------- x : array_like Input array. out : ndarray, optional Array of the same shape as `x`, to store results in. See `doc.ufuncs` (Section "Output arguments") for details. Returns ------- arccosh : ndarray Array of the same shape as `x`. See Also -------- cosh, arcsinh, sinh, arctanh, tanh Notes ----- `arccosh` is a multivalued function: for each `x` there are infinitely many numbers `z` such that `cosh(z) = x`. The convention is to return the `z` whose imaginary part lies in `[-pi, pi]` and the real part in ``[0, inf]``. For real-valued input data types, `arccosh` always returns real output. For each value that cannot be expressed as a real number or infinity, it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `arccosh` is a complex analytical function that has a branch cut `[-inf, 1]` and is continuous from above on it. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Inverse hyperbolic function", http://en.wikipedia.org/wiki/Arccosh Examples -------- >>> np.arccosh([np.e, 10.0]) array([ 1.65745445, 2.99322285]) >>> np.arccosh(1) 0.0 """) add_newdoc('numpy.core.umath', 'arcsin', """ Inverse sine, element-wise. Parameters ---------- x : array_like `y`-coordinate on the unit circle. out : ndarray, optional Array of the same shape as `x`, in which to store the results. See `doc.ufuncs` (Section "Output arguments") for more details. Returns ------- angle : ndarray The inverse sine of each element in `x`, in radians and in the closed interval ``[-pi/2, pi/2]``. If `x` is a scalar, a scalar is returned, otherwise an array. See Also -------- sin, cos, arccos, tan, arctan, arctan2, emath.arcsin Notes ----- `arcsin` is a multivalued function: for each `x` there are infinitely many numbers `z` such that :math:`sin(z) = x`. The convention is to return the angle `z` whose real part lies in [-pi/2, pi/2]. For real-valued input data types, *arcsin* always returns real output. For each value that cannot be expressed as a real number or infinity, it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `arcsin` is a complex analytic function that has, by convention, the branch cuts [-inf, -1] and [1, inf] and is continuous from above on the former and from below on the latter. The inverse sine is also known as `asin` or sin^{-1}. References ---------- Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*, 10th printing, New York: Dover, 1964, pp. 79ff. http://www.math.sfu.ca/~cbm/aands/ Examples -------- >>> np.arcsin(1) # pi/2 1.5707963267948966 >>> np.arcsin(-1) # -pi/2 -1.5707963267948966 >>> np.arcsin(0) 0.0 """) add_newdoc('numpy.core.umath', 'arcsinh', """ Inverse hyperbolic sine element-wise. Parameters ---------- x : array_like Input array. out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See `doc.ufuncs`. Returns ------- out : ndarray Array of of the same shape as `x`. Notes ----- `arcsinh` is a multivalued function: for each `x` there are infinitely many numbers `z` such that `sinh(z) = x`. The convention is to return the `z` whose imaginary part lies in `[-pi/2, pi/2]`. For real-valued input data types, `arcsinh` always returns real output. For each value that cannot be expressed as a real number or infinity, it returns ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `arccos` is a complex analytical function that has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from the right on the former and from the left on the latter. The inverse hyperbolic sine is also known as `asinh` or ``sinh^-1``. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Inverse hyperbolic function", http://en.wikipedia.org/wiki/Arcsinh Examples -------- >>> np.arcsinh(np.array([np.e, 10.0])) array([ 1.72538256, 2.99822295]) """) add_newdoc('numpy.core.umath', 'arctan', """ Trigonometric inverse tangent, element-wise. The inverse of tan, so that if ``y = tan(x)`` then ``x = arctan(y)``. Parameters ---------- x : array_like Input values. `arctan` is applied to each element of `x`. Returns ------- out : ndarray Out has the same shape as `x`. Its real part is in ``[-pi/2, pi/2]`` (``arctan(+/-inf)`` returns ``+/-pi/2``). It is a scalar if `x` is a scalar. See Also -------- arctan2 : The "four quadrant" arctan of the angle formed by (`x`, `y`) and the positive `x`-axis. angle : Argument of complex values. Notes ----- `arctan` is a multi-valued function: for each `x` there are infinitely many numbers `z` such that tan(`z`) = `x`. The convention is to return the angle `z` whose real part lies in [-pi/2, pi/2]. For real-valued input data types, `arctan` always returns real output. For each value that cannot be expressed as a real number or infinity, it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `arctan` is a complex analytic function that has [`1j, infj`] and [`-1j, -infj`] as branch cuts, and is continuous from the left on the former and from the right on the latter. The inverse tangent is also known as `atan` or tan^{-1}. References ---------- Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*, 10th printing, New York: Dover, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/ Examples -------- We expect the arctan of 0 to be 0, and of 1 to be pi/4: >>> np.arctan([0, 1]) array([ 0. , 0.78539816]) >>> np.pi/4 0.78539816339744828 Plot arctan: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-10, 10) >>> plt.plot(x, np.arctan(x)) >>> plt.axis('tight') >>> plt.show() """) add_newdoc('numpy.core.umath', 'arctan2', """ Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly. The quadrant (i.e., branch) is chosen so that ``arctan2(x1, x2)`` is the signed angle in radians between the ray ending at the origin and passing through the point (1,0), and the ray ending at the origin and passing through the point (`x2`, `x1`). (Note the role reversal: the "`y`-coordinate" is the first function parameter, the "`x`-coordinate" is the second.) By IEEE convention, this function is defined for `x2` = +/-0 and for either or both of `x1` and `x2` = +/-inf (see Notes for specific values). This function is not defined for complex-valued arguments; for the so-called argument of complex values, use `angle`. Parameters ---------- x1 : array_like, real-valued `y`-coordinates. x2 : array_like, real-valued `x`-coordinates. `x2` must be broadcastable to match the shape of `x1` or vice versa. Returns ------- angle : ndarray Array of angles in radians, in the range ``[-pi, pi]``. See Also -------- arctan, tan, angle Notes ----- *arctan2* is identical to the `atan2` function of the underlying C library. The following special values are defined in the C standard: [1]_ ====== ====== ================ `x1` `x2` `arctan2(x1,x2)` ====== ====== ================ +/- 0 +0 +/- 0 +/- 0 -0 +/- pi > 0 +/-inf +0 / +pi < 0 +/-inf -0 / -pi +/-inf +inf +/- (pi/4) +/-inf -inf +/- (3*pi/4) ====== ====== ================ Note that +0 and -0 are distinct floating point numbers, as are +inf and -inf. References ---------- .. [1] ISO/IEC standard 9899:1999, "Programming language C." Examples -------- Consider four points in different quadrants: >>> x = np.array([-1, +1, +1, -1]) >>> y = np.array([-1, -1, +1, +1]) >>> np.arctan2(y, x) * 180 / np.pi array([-135., -45., 45., 135.]) Note the order of the parameters. `arctan2` is defined also when `x2` = 0 and at several other special points, obtaining values in the range ``[-pi, pi]``: >>> np.arctan2([1., -1.], [0., 0.]) array([ 1.57079633, -1.57079633]) >>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf]) array([ 0. , 3.14159265, 0.78539816]) """) add_newdoc('numpy.core.umath', '_arg', """ DO NOT USE, ONLY FOR TESTING """) add_newdoc('numpy.core.umath', 'arctanh', """ Inverse hyperbolic tangent element-wise. Parameters ---------- x : array_like Input array. Returns ------- out : ndarray Array of the same shape as `x`. See Also -------- emath.arctanh Notes ----- `arctanh` is a multivalued function: for each `x` there are infinitely many numbers `z` such that `tanh(z) = x`. The convention is to return the `z` whose imaginary part lies in `[-pi/2, pi/2]`. For real-valued input data types, `arctanh` always returns real output. For each value that cannot be expressed as a real number or infinity, it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `arctanh` is a complex analytical function that has branch cuts `[-1, -inf]` and `[1, inf]` and is continuous from above on the former and from below on the latter. The inverse hyperbolic tangent is also known as `atanh` or ``tanh^-1``. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Inverse hyperbolic function", http://en.wikipedia.org/wiki/Arctanh Examples -------- >>> np.arctanh([0, -0.5]) array([ 0. , -0.54930614]) """) add_newdoc('numpy.core.umath', 'bitwise_and', """ Compute the bit-wise AND of two arrays element-wise. Computes the bit-wise AND of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ``&``. Parameters ---------- x1, x2 : array_like Only integer and boolean types are handled. Returns ------- out : array_like Result. See Also -------- logical_and bitwise_or bitwise_xor binary_repr : Return the binary representation of the input number as a string. Examples -------- The number 13 is represented by ``00001101``. Likewise, 17 is represented by ``00010001``. The bit-wise AND of 13 and 17 is therefore ``000000001``, or 1: >>> np.bitwise_and(13, 17) 1 >>> np.bitwise_and(14, 13) 12 >>> np.binary_repr(12) '1100' >>> np.bitwise_and([14,3], 13) array([12, 1]) >>> np.bitwise_and([11,7], [4,25]) array([0, 1]) >>> np.bitwise_and(np.array([2,5,255]), np.array([3,14,16])) array([ 2, 4, 16]) >>> np.bitwise_and([True, True], [False, True]) array([False, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'bitwise_or', """ Compute the bit-wise OR of two arrays element-wise. Computes the bit-wise OR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ``|``. Parameters ---------- x1, x2 : array_like Only integer and boolean types are handled. out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See doc.ufuncs. Returns ------- out : array_like Result. See Also -------- logical_or bitwise_and bitwise_xor binary_repr : Return the binary representation of the input number as a string. Examples -------- The number 13 has the binaray representation ``00001101``. Likewise, 16 is represented by ``00010000``. The bit-wise OR of 13 and 16 is then ``000111011``, or 29: >>> np.bitwise_or(13, 16) 29 >>> np.binary_repr(29) '11101' >>> np.bitwise_or(32, 2) 34 >>> np.bitwise_or([33, 4], 1) array([33, 5]) >>> np.bitwise_or([33, 4], [1, 2]) array([33, 6]) >>> np.bitwise_or(np.array([2, 5, 255]), np.array([4, 4, 4])) array([ 6, 5, 255]) >>> np.array([2, 5, 255]) | np.array([4, 4, 4]) array([ 6, 5, 255]) >>> np.bitwise_or(np.array([2, 5, 255, 2147483647L], dtype=np.int32), ... np.array([4, 4, 4, 2147483647L], dtype=np.int32)) array([ 6, 5, 255, 2147483647]) >>> np.bitwise_or([True, True], [False, True]) array([ True, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'bitwise_xor', """ Compute the bit-wise XOR of two arrays element-wise. Computes the bit-wise XOR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ``^``. Parameters ---------- x1, x2 : array_like Only integer and boolean types are handled. Returns ------- out : array_like Result. See Also -------- logical_xor bitwise_and bitwise_or binary_repr : Return the binary representation of the input number as a string. Examples -------- The number 13 is represented by ``00001101``. Likewise, 17 is represented by ``00010001``. The bit-wise XOR of 13 and 17 is therefore ``00011100``, or 28: >>> np.bitwise_xor(13, 17) 28 >>> np.binary_repr(28) '11100' >>> np.bitwise_xor(31, 5) 26 >>> np.bitwise_xor([31,3], 5) array([26, 6]) >>> np.bitwise_xor([31,3], [5,6]) array([26, 5]) >>> np.bitwise_xor([True, True], [False, True]) array([ True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'ceil', """ Return the ceiling of the input, element-wise. The ceil of the scalar `x` is the smallest integer `i`, such that `i >= x`. It is often denoted as :math:`\\lceil x \\rceil`. Parameters ---------- x : array_like Input data. Returns ------- y : ndarray or scalar The ceiling of each element in `x`, with `float` dtype. See Also -------- floor, trunc, rint Examples -------- >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.ceil(a) array([-1., -1., -0., 1., 2., 2., 2.]) """) add_newdoc('numpy.core.umath', 'trunc', """ Return the truncated value of the input, element-wise. The truncated value of the scalar `x` is the nearest integer `i` which is closer to zero than `x` is. In short, the fractional part of the signed number `x` is discarded. Parameters ---------- x : array_like Input data. Returns ------- y : ndarray or scalar The truncated value of each element in `x`. See Also -------- ceil, floor, rint Notes ----- .. versionadded:: 1.3.0 Examples -------- >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.trunc(a) array([-1., -1., -0., 0., 1., 1., 2.]) """) add_newdoc('numpy.core.umath', 'conjugate', """ Return the complex conjugate, element-wise. The complex conjugate of a complex number is obtained by changing the sign of its imaginary part. Parameters ---------- x : array_like Input value. Returns ------- y : ndarray The complex conjugate of `x`, with same dtype as `y`. Examples -------- >>> np.conjugate(1+2j) (1-2j) >>> x = np.eye(2) + 1j * np.eye(2) >>> np.conjugate(x) array([[ 1.-1.j, 0.-0.j], [ 0.-0.j, 1.-1.j]]) """) add_newdoc('numpy.core.umath', 'cos', """ Cosine element-wise. Parameters ---------- x : array_like Input array in radians. out : ndarray, optional Output array of same shape as `x`. Returns ------- y : ndarray The corresponding cosine values. Raises ------ ValueError: invalid return array shape if `out` is provided and `out.shape` != `x.shape` (See Examples) Notes ----- If `out` is provided, the function writes the result into it, and returns a reference to `out`. (See Examples) References ---------- M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972. Examples -------- >>> np.cos(np.array([0, np.pi/2, np.pi])) array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00]) >>> >>> # Example of providing the optional output parameter >>> out2 = np.cos([0.1], out1) >>> out2 is out1 True >>> >>> # Example of ValueError due to provision of shape mis-matched `out` >>> np.cos(np.zeros((3,3)),np.zeros((2,2))) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid return array shape """) add_newdoc('numpy.core.umath', 'cosh', """ Hyperbolic cosine, element-wise. Equivalent to ``1/2 * (np.exp(x) + np.exp(-x))`` and ``np.cos(1j*x)``. Parameters ---------- x : array_like Input array. Returns ------- out : ndarray Output array of same shape as `x`. Examples -------- >>> np.cosh(0) 1.0 The hyperbolic cosine describes the shape of a hanging cable: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-4, 4, 1000) >>> plt.plot(x, np.cosh(x)) >>> plt.show() """) add_newdoc('numpy.core.umath', 'degrees', """ Convert angles from radians to degrees. Parameters ---------- x : array_like Input array in radians. out : ndarray, optional Output array of same shape as x. Returns ------- y : ndarray of floats The corresponding degree values; if `out` was supplied this is a reference to it. See Also -------- rad2deg : equivalent function Examples -------- Convert a radian array to degrees >>> rad = np.arange(12.)*np.pi/6 >>> np.degrees(rad) array([ 0., 30., 60., 90., 120., 150., 180., 210., 240., 270., 300., 330.]) >>> out = np.zeros((rad.shape)) >>> r = degrees(rad, out) >>> np.all(r == out) True """) add_newdoc('numpy.core.umath', 'rad2deg', """ Convert angles from radians to degrees. Parameters ---------- x : array_like Angle in radians. out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See doc.ufuncs. Returns ------- y : ndarray The corresponding angle in degrees. See Also -------- deg2rad : Convert angles from degrees to radians. unwrap : Remove large jumps in angle by wrapping. Notes ----- .. versionadded:: 1.3.0 rad2deg(x) is ``180 * x / pi``. Examples -------- >>> np.rad2deg(np.pi/2) 90.0 """) add_newdoc('numpy.core.umath', 'divide', """ Divide arguments element-wise. Parameters ---------- x1 : array_like Dividend array. x2 : array_like Divisor array. out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See doc.ufuncs. Returns ------- y : ndarray or scalar The quotient ``x1/x2``, element-wise. Returns a scalar if both ``x1`` and ``x2`` are scalars. See Also -------- seterr : Set whether to raise or warn on overflow, underflow and division by zero. Notes ----- Equivalent to ``x1`` / ``x2`` in terms of array-broadcasting. Behavior on division by zero can be changed using ``seterr``. In Python 2, when both ``x1`` and ``x2`` are of an integer type, ``divide`` will behave like ``floor_divide``. In Python 3, it behaves like ``true_divide``. Examples -------- >>> np.divide(2.0, 4.0) 0.5 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.divide(x1, x2) array([[ NaN, 1. , 1. ], [ Inf, 4. , 2.5], [ Inf, 7. , 4. ]]) Note the behavior with integer types (Python 2 only): >>> np.divide(2, 4) 0 >>> np.divide(2, 4.) 0.5 Division by zero always yields zero in integer arithmetic (again, Python 2 only), and does not raise an exception or a warning: >>> np.divide(np.array([0, 1], dtype=int), np.array([0, 0], dtype=int)) array([0, 0]) Division by zero can, however, be caught using ``seterr``: >>> old_err_state = np.seterr(divide='raise') >>> np.divide(1, 0) Traceback (most recent call last): File "<stdin>", line 1, in <module> FloatingPointError: divide by zero encountered in divide >>> ignored_states = np.seterr(**old_err_state) >>> np.divide(1, 0) 0 """) add_newdoc('numpy.core.umath', 'equal', """ Return (x1 == x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays of the same shape. Returns ------- out : ndarray or bool Output array of bools, or a single bool if x1 and x2 are scalars. See Also -------- not_equal, greater_equal, less_equal, greater, less Examples -------- >>> np.equal([0, 1, 3], np.arange(3)) array([ True, True, False], dtype=bool) What is compared are values, not types. So an int (1) and an array of length one can evaluate as True: >>> np.equal(1, np.ones(1)) array([ True], dtype=bool) """) add_newdoc('numpy.core.umath', 'exp', """ Calculate the exponential of all elements in the input array. Parameters ---------- x : array_like Input values. Returns ------- out : ndarray Output array, element-wise exponential of `x`. See Also -------- expm1 : Calculate ``exp(x) - 1`` for all elements in the array. exp2 : Calculate ``2**x`` for all elements in the array. Notes ----- The irrational number ``e`` is also known as Euler's number. It is approximately 2.718281, and is the base of the natural logarithm, ``ln`` (this means that, if :math:`x = \\ln y = \\log_e y`, then :math:`e^x = y`. For real input, ``exp(x)`` is always positive. For complex arguments, ``x = a + ib``, we can write :math:`e^x = e^a e^{ib}`. The first term, :math:`e^a`, is already known (it is the real argument, described above). The second term, :math:`e^{ib}`, is :math:`\\cos b + i \\sin b`, a function with magnitude 1 and a periodic phase. References ---------- .. [1] Wikipedia, "Exponential function", http://en.wikipedia.org/wiki/Exponential_function .. [2] M. Abramovitz and I. A. Stegun, "Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables," Dover, 1964, p. 69, http://www.math.sfu.ca/~cbm/aands/page_69.htm Examples -------- Plot the magnitude and phase of ``exp(x)`` in the complex plane: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-2*np.pi, 2*np.pi, 100) >>> xx = x + 1j * x[:, np.newaxis] # a + ib over complex plane >>> out = np.exp(xx) >>> plt.subplot(121) >>> plt.imshow(np.abs(out), ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi]) >>> plt.title('Magnitude of exp(x)') >>> plt.subplot(122) >>> plt.imshow(np.angle(out), ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi]) >>> plt.title('Phase (angle) of exp(x)') >>> plt.show() """) add_newdoc('numpy.core.umath', 'exp2', """ Calculate `2**p` for all `p` in the input array. Parameters ---------- x : array_like Input values. out : ndarray, optional Array to insert results into. Returns ------- out : ndarray Element-wise 2 to the power `x`. See Also -------- power Notes ----- .. versionadded:: 1.3.0 Examples -------- >>> np.exp2([2, 3]) array([ 4., 8.]) """) add_newdoc('numpy.core.umath', 'expm1', """ Calculate ``exp(x) - 1`` for all elements in the array. Parameters ---------- x : array_like Input values. Returns ------- out : ndarray Element-wise exponential minus one: ``out = exp(x) - 1``. See Also -------- log1p : ``log(1 + x)``, the inverse of expm1. Notes ----- This function provides greater precision than ``exp(x) - 1`` for small values of ``x``. Examples -------- The true value of ``exp(1e-10) - 1`` is ``1.00000000005e-10`` to about 32 significant digits. This example shows the superiority of expm1 in this case. >>> np.expm1(1e-10) 1.00000000005e-10 >>> np.exp(1e-10) - 1 1.000000082740371e-10 """) add_newdoc('numpy.core.umath', 'fabs', """ Compute the absolute values element-wise. This function returns the absolute values (positive magnitude) of the data in `x`. Complex values are not handled, use `absolute` to find the absolute values of complex data. Parameters ---------- x : array_like The array of numbers for which the absolute values are required. If `x` is a scalar, the result `y` will also be a scalar. out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See doc.ufuncs. Returns ------- y : ndarray or scalar The absolute values of `x`, the returned values are always floats. See Also -------- absolute : Absolute values including `complex` types. Examples -------- >>> np.fabs(-1) 1.0 >>> np.fabs([-1.2, 1.2]) array([ 1.2, 1.2]) """) add_newdoc('numpy.core.umath', 'floor', """ Return the floor of the input, element-wise. The floor of the scalar `x` is the largest integer `i`, such that `i <= x`. It is often denoted as :math:`\\lfloor x \\rfloor`. Parameters ---------- x : array_like Input data. Returns ------- y : ndarray or scalar The floor of each element in `x`. See Also -------- ceil, trunc, rint Notes ----- Some spreadsheet programs calculate the "floor-towards-zero", in other words ``floor(-2.5) == -2``. NumPy instead uses the definition of `floor` where `floor(-2.5) == -3`. Examples -------- >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.floor(a) array([-2., -2., -1., 0., 1., 1., 2.]) """) add_newdoc('numpy.core.umath', 'floor_divide', """ Return the largest integer smaller or equal to the division of the inputs. Parameters ---------- x1 : array_like Numerator. x2 : array_like Denominator. Returns ------- y : ndarray y = floor(`x1`/`x2`) See Also -------- divide : Standard division. floor : Round a number to the nearest integer toward minus infinity. ceil : Round a number to the nearest integer toward infinity. Examples -------- >>> np.floor_divide(7,3) 2 >>> np.floor_divide([1., 2., 3., 4.], 2.5) array([ 0., 0., 1., 1.]) """) add_newdoc('numpy.core.umath', 'fmod', """ Return the element-wise remainder of division. This is the NumPy implementation of the C library function fmod, the remainder has the same sign as the dividend `x1`. It is equivalent to the Matlab(TM) ``rem`` function and should not be confused with the Python modulus operator ``x1 % x2``. Parameters ---------- x1 : array_like Dividend. x2 : array_like Divisor. Returns ------- y : array_like The remainder of the division of `x1` by `x2`. See Also -------- remainder : Equivalent to the Python ``%`` operator. divide Notes ----- The result of the modulo operation for negative dividend and divisors is bound by conventions. For `fmod`, the sign of result is the sign of the dividend, while for `remainder` the sign of the result is the sign of the divisor. The `fmod` function is equivalent to the Matlab(TM) ``rem`` function. Examples -------- >>> np.fmod([-3, -2, -1, 1, 2, 3], 2) array([-1, 0, -1, 1, 0, 1]) >>> np.remainder([-3, -2, -1, 1, 2, 3], 2) array([1, 0, 1, 1, 0, 1]) >>> np.fmod([5, 3], [2, 2.]) array([ 1., 1.]) >>> a = np.arange(-3, 3).reshape(3, 2) >>> a array([[-3, -2], [-1, 0], [ 1, 2]]) >>> np.fmod(a, [2,2]) array([[-1, 0], [-1, 0], [ 1, 0]]) """) add_newdoc('numpy.core.umath', 'greater', """ Return the truth value of (x1 > x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which may be the shape of one or the other). Returns ------- out : bool or ndarray of bool Array of bools, or a single bool if `x1` and `x2` are scalars. See Also -------- greater_equal, less, less_equal, equal, not_equal Examples -------- >>> np.greater([4,2],[2,2]) array([ True, False], dtype=bool) If the inputs are ndarrays, then np.greater is equivalent to '>'. >>> a = np.array([4,2]) >>> b = np.array([2,2]) >>> a > b array([ True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'greater_equal', """ Return the truth value of (x1 >= x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which may be the shape of one or the other). Returns ------- out : bool or ndarray of bool Array of bools, or a single bool if `x1` and `x2` are scalars. See Also -------- greater, less, less_equal, equal, not_equal Examples -------- >>> np.greater_equal([4, 2, 1], [2, 2, 2]) array([ True, True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'hypot', """ Given the "legs" of a right triangle, return its hypotenuse. Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or `x2` is scalar_like (i.e., unambiguously cast-able to a scalar type), it is broadcast for use with each element of the other argument. (See Examples) Parameters ---------- x1, x2 : array_like Leg of the triangle(s). out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See doc.ufuncs. Returns ------- z : ndarray The hypotenuse of the triangle(s). Examples -------- >>> np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3))) array([[ 5., 5., 5.], [ 5., 5., 5.], [ 5., 5., 5.]]) Example showing broadcast of scalar_like argument: >>> np.hypot(3*np.ones((3, 3)), [4]) array([[ 5., 5., 5.], [ 5., 5., 5.], [ 5., 5., 5.]]) """) add_newdoc('numpy.core.umath', 'invert', """ Compute bit-wise inversion, or bit-wise NOT, element-wise. Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ``~``. For signed integer inputs, the two's complement is returned. In a two's-complement system negative numbers are represented by the two's complement of the absolute value. This is the most common method of representing signed integers on computers [1]_. A N-bit two's-complement system can represent every integer in the range :math:`-2^{N-1}` to :math:`+2^{N-1}-1`. Parameters ---------- x1 : array_like Only integer and boolean types are handled. Returns ------- out : array_like Result. See Also -------- bitwise_and, bitwise_or, bitwise_xor logical_not binary_repr : Return the binary representation of the input number as a string. Notes ----- `bitwise_not` is an alias for `invert`: >>> np.bitwise_not is np.invert True References ---------- .. [1] Wikipedia, "Two's complement", http://en.wikipedia.org/wiki/Two's_complement Examples -------- We've seen that 13 is represented by ``00001101``. The invert or bit-wise NOT of 13 is then: >>> np.invert(np.array([13], dtype=uint8)) array([242], dtype=uint8) >>> np.binary_repr(x, width=8) '00001101' >>> np.binary_repr(242, width=8) '11110010' The result depends on the bit-width: >>> np.invert(np.array([13], dtype=uint16)) array([65522], dtype=uint16) >>> np.binary_repr(x, width=16) '0000000000001101' >>> np.binary_repr(65522, width=16) '1111111111110010' When using signed integer types the result is the two's complement of the result for the unsigned type: >>> np.invert(np.array([13], dtype=int8)) array([-14], dtype=int8) >>> np.binary_repr(-14, width=8) '11110010' Booleans are accepted as well: >>> np.invert(array([True, False])) array([False, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'isfinite', """ Test element-wise for finiteness (not infinity or not Not a Number). The result is returned as a boolean array. Parameters ---------- x : array_like Input values. out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See `doc.ufuncs`. Returns ------- y : ndarray, bool For scalar input, the result is a new boolean with value True if the input is finite; otherwise the value is False (input is either positive infinity, negative infinity or Not a Number). For array input, the result is a boolean array with the same dimensions as the input and the values are True if the corresponding element of the input is finite; otherwise the values are False (element is either positive infinity, negative infinity or Not a Number). See Also -------- isinf, isneginf, isposinf, isnan Notes ----- Not a Number, positive infinity and negative infinity are considered to be non-finite. Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Also that positive infinity is not equivalent to negative infinity. But infinity is equivalent to positive infinity. Errors result if the second argument is also supplied when `x` is a scalar input, or if first and second arguments have different shapes. Examples -------- >>> np.isfinite(1) True >>> np.isfinite(0) True >>> np.isfinite(np.nan) False >>> np.isfinite(np.inf) False >>> np.isfinite(np.NINF) False >>> np.isfinite([np.log(-1.),1.,np.log(0)]) array([False, True, False], dtype=bool) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isfinite(x, y) array([0, 1, 0]) >>> y array([0, 1, 0]) """) add_newdoc('numpy.core.umath', 'isinf', """ Test element-wise for positive or negative infinity. Returns a boolean array of the same shape as `x`, True where ``x == +/-inf``, otherwise False. Parameters ---------- x : array_like Input values out : array_like, optional An array with the same shape as `x` to store the result. Returns ------- y : bool (scalar) or boolean ndarray For scalar input, the result is a new boolean with value True if the input is positive or negative infinity; otherwise the value is False. For array input, the result is a boolean array with the same shape as the input and the values are True where the corresponding element of the input is positive or negative infinity; elsewhere the values are False. If a second argument was supplied the result is stored there. If the type of that array is a numeric type the result is represented as zeros and ones, if the type is boolean then as False and True, respectively. The return value `y` is then a reference to that array. See Also -------- isneginf, isposinf, isnan, isfinite Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Errors result if the second argument is supplied when the first argument is a scalar, or if the first and second arguments have different shapes. Examples -------- >>> np.isinf(np.inf) True >>> np.isinf(np.nan) False >>> np.isinf(np.NINF) True >>> np.isinf([np.inf, -np.inf, 1.0, np.nan]) array([ True, True, False, False], dtype=bool) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isinf(x, y) array([1, 0, 1]) >>> y array([1, 0, 1]) """) add_newdoc('numpy.core.umath', 'isnan', """ Test element-wise for NaN and return result as a boolean array. Parameters ---------- x : array_like Input array. Returns ------- y : ndarray or bool For scalar input, the result is a new boolean with value True if the input is NaN; otherwise the value is False. For array input, the result is a boolean array of the same dimensions as the input and the values are True if the corresponding element of the input is NaN; otherwise the values are False. See Also -------- isinf, isneginf, isposinf, isfinite Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Examples -------- >>> np.isnan(np.nan) True >>> np.isnan(np.inf) False >>> np.isnan([np.log(-1.),1.,np.log(0)]) array([ True, False, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'left_shift', """ Shift the bits of an integer to the left. Bits are shifted to the left by appending `x2` 0s at the right of `x1`. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying `x1` by ``2**x2``. Parameters ---------- x1 : array_like of integer type Input values. x2 : array_like of integer type Number of zeros to append to `x1`. Has to be non-negative. Returns ------- out : array of integer type Return `x1` with bits shifted `x2` times to the left. See Also -------- right_shift : Shift the bits of an integer to the right. binary_repr : Return the binary representation of the input number as a string. Examples -------- >>> np.binary_repr(5) '101' >>> np.left_shift(5, 2) 20 >>> np.binary_repr(20) '10100' >>> np.left_shift(5, [1,2,3]) array([10, 20, 40]) """) add_newdoc('numpy.core.umath', 'less', """ Return the truth value of (x1 < x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which may be the shape of one or the other). Returns ------- out : bool or ndarray of bool Array of bools, or a single bool if `x1` and `x2` are scalars. See Also -------- greater, less_equal, greater_equal, equal, not_equal Examples -------- >>> np.less([1, 2], [2, 2]) array([ True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'less_equal', """ Return the truth value of (x1 =< x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which may be the shape of one or the other). Returns ------- out : bool or ndarray of bool Array of bools, or a single bool if `x1` and `x2` are scalars. See Also -------- greater, less, greater_equal, equal, not_equal Examples -------- >>> np.less_equal([4, 2, 1], [2, 2, 2]) array([False, True, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'log', """ Natural logarithm, element-wise. The natural logarithm `log` is the inverse of the exponential function, so that `log(exp(x)) = x`. The natural logarithm is logarithm in base `e`. Parameters ---------- x : array_like Input value. Returns ------- y : ndarray The natural logarithm of `x`, element-wise. See Also -------- log10, log2, log1p, emath.log Notes ----- Logarithm is a multivalued function: for each `x` there is an infinite number of `z` such that `exp(z) = x`. The convention is to return the `z` whose imaginary part lies in `[-pi, pi]`. For real-valued input data types, `log` always returns real output. For each value that cannot be expressed as a real number or infinity, it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `log` is a complex analytical function that has a branch cut `[-inf, 0]` and is continuous from above on it. `log` handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 67. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Logarithm". http://en.wikipedia.org/wiki/Logarithm Examples -------- >>> np.log([1, np.e, np.e**2, 0]) array([ 0., 1., 2., -Inf]) """) add_newdoc('numpy.core.umath', 'log10', """ Return the base 10 logarithm of the input array, element-wise. Parameters ---------- x : array_like Input values. Returns ------- y : ndarray The logarithm to the base 10 of `x`, element-wise. NaNs are returned where x is negative. See Also -------- emath.log10 Notes ----- Logarithm is a multivalued function: for each `x` there is an infinite number of `z` such that `10**z = x`. The convention is to return the `z` whose imaginary part lies in `[-pi, pi]`. For real-valued input data types, `log10` always returns real output. For each value that cannot be expressed as a real number or infinity, it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `log10` is a complex analytical function that has a branch cut `[-inf, 0]` and is continuous from above on it. `log10` handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 67. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Logarithm". http://en.wikipedia.org/wiki/Logarithm Examples -------- >>> np.log10([1e-15, -3.]) array([-15., NaN]) """) add_newdoc('numpy.core.umath', 'log2', """ Base-2 logarithm of `x`. Parameters ---------- x : array_like Input values. Returns ------- y : ndarray Base-2 logarithm of `x`. See Also -------- log, log10, log1p, emath.log2 Notes ----- .. versionadded:: 1.3.0 Logarithm is a multivalued function: for each `x` there is an infinite number of `z` such that `2**z = x`. The convention is to return the `z` whose imaginary part lies in `[-pi, pi]`. For real-valued input data types, `log2` always returns real output. For each value that cannot be expressed as a real number or infinity, it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `log2` is a complex analytical function that has a branch cut `[-inf, 0]` and is continuous from above on it. `log2` handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard. Examples -------- >>> x = np.array([0, 1, 2, 2**4]) >>> np.log2(x) array([-Inf, 0., 1., 4.]) >>> xi = np.array([0+1.j, 1, 2+0.j, 4.j]) >>> np.log2(xi) array([ 0.+2.26618007j, 0.+0.j , 1.+0.j , 2.+2.26618007j]) """) add_newdoc('numpy.core.umath', 'logaddexp', """ Logarithm of the sum of exponentiations of the inputs. Calculates ``log(exp(x1) + exp(x2))``. This function is useful in statistics where the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the logarithm of the calculated probability is stored. This function allows adding probabilities stored in such a fashion. Parameters ---------- x1, x2 : array_like Input values. Returns ------- result : ndarray Logarithm of ``exp(x1) + exp(x2)``. See Also -------- logaddexp2: Logarithm of the sum of exponentiations of inputs in base 2. Notes ----- .. versionadded:: 1.3.0 Examples -------- >>> prob1 = np.log(1e-50) >>> prob2 = np.log(2.5e-50) >>> prob12 = np.logaddexp(prob1, prob2) >>> prob12 -113.87649168120691 >>> np.exp(prob12) 3.5000000000000057e-50 """) add_newdoc('numpy.core.umath', 'logaddexp2', """ Logarithm of the sum of exponentiations of the inputs in base-2. Calculates ``log2(2**x1 + 2**x2)``. This function is useful in machine learning when the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the base-2 logarithm of the calculated probability can be used instead. This function allows adding probabilities stored in such a fashion. Parameters ---------- x1, x2 : array_like Input values. out : ndarray, optional Array to store results in. Returns ------- result : ndarray Base-2 logarithm of ``2**x1 + 2**x2``. See Also -------- logaddexp: Logarithm of the sum of exponentiations of the inputs. Notes ----- .. versionadded:: 1.3.0 Examples -------- >>> prob1 = np.log2(1e-50) >>> prob2 = np.log2(2.5e-50) >>> prob12 = np.logaddexp2(prob1, prob2) >>> prob1, prob2, prob12 (-166.09640474436813, -164.77447664948076, -164.28904982231052) >>> 2**prob12 3.4999999999999914e-50 """) add_newdoc('numpy.core.umath', 'log1p', """ Return the natural logarithm of one plus the input array, element-wise. Calculates ``log(1 + x)``. Parameters ---------- x : array_like Input values. Returns ------- y : ndarray Natural logarithm of `1 + x`, element-wise. See Also -------- expm1 : ``exp(x) - 1``, the inverse of `log1p`. Notes ----- For real-valued input, `log1p` is accurate also for `x` so small that `1 + x == 1` in floating-point accuracy. Logarithm is a multivalued function: for each `x` there is an infinite number of `z` such that `exp(z) = 1 + x`. The convention is to return the `z` whose imaginary part lies in `[-pi, pi]`. For real-valued input data types, `log1p` always returns real output. For each value that cannot be expressed as a real number or infinity, it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `log1p` is a complex analytical function that has a branch cut `[-inf, -1]` and is continuous from above on it. `log1p` handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 67. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Logarithm". http://en.wikipedia.org/wiki/Logarithm Examples -------- >>> np.log1p(1e-99) 1e-99 >>> np.log(1 + 1e-99) 0.0 """) add_newdoc('numpy.core.umath', 'logical_and', """ Compute the truth value of x1 AND x2 element-wise. Parameters ---------- x1, x2 : array_like Input arrays. `x1` and `x2` must be of the same shape. Returns ------- y : ndarray or bool Boolean result with the same shape as `x1` and `x2` of the logical AND operation on corresponding elements of `x1` and `x2`. See Also -------- logical_or, logical_not, logical_xor bitwise_and Examples -------- >>> np.logical_and(True, False) False >>> np.logical_and([True, False], [False, False]) array([False, False], dtype=bool) >>> x = np.arange(5) >>> np.logical_and(x>1, x<4) array([False, False, True, True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'logical_not', """ Compute the truth value of NOT x element-wise. Parameters ---------- x : array_like Logical NOT is applied to the elements of `x`. Returns ------- y : bool or ndarray of bool Boolean result with the same shape as `x` of the NOT operation on elements of `x`. See Also -------- logical_and, logical_or, logical_xor Examples -------- >>> np.logical_not(3) False >>> np.logical_not([True, False, 0, 1]) array([False, True, True, False], dtype=bool) >>> x = np.arange(5) >>> np.logical_not(x<3) array([False, False, False, True, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'logical_or', """ Compute the truth value of x1 OR x2 element-wise. Parameters ---------- x1, x2 : array_like Logical OR is applied to the elements of `x1` and `x2`. They have to be of the same shape. Returns ------- y : ndarray or bool Boolean result with the same shape as `x1` and `x2` of the logical OR operation on elements of `x1` and `x2`. See Also -------- logical_and, logical_not, logical_xor bitwise_or Examples -------- >>> np.logical_or(True, False) True >>> np.logical_or([True, False], [False, False]) array([ True, False], dtype=bool) >>> x = np.arange(5) >>> np.logical_or(x < 1, x > 3) array([ True, False, False, False, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'logical_xor', """ Compute the truth value of x1 XOR x2, element-wise. Parameters ---------- x1, x2 : array_like Logical XOR is applied to the elements of `x1` and `x2`. They must be broadcastable to the same shape. Returns ------- y : bool or ndarray of bool Boolean result of the logical XOR operation applied to the elements of `x1` and `x2`; the shape is determined by whether or not broadcasting of one or both arrays was required. See Also -------- logical_and, logical_or, logical_not, bitwise_xor Examples -------- >>> np.logical_xor(True, False) True >>> np.logical_xor([True, True, False, False], [True, False, True, False]) array([False, True, True, False], dtype=bool) >>> x = np.arange(5) >>> np.logical_xor(x < 1, x > 3) array([ True, False, False, False, True], dtype=bool) Simple example showing support of broadcasting >>> np.logical_xor(0, np.eye(2)) array([[ True, False], [False, True]], dtype=bool) """) add_newdoc('numpy.core.umath', 'maximum', """ Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. Parameters ---------- x1, x2 : array_like The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape. Returns ------- y : ndarray or scalar The maximum of `x1` and `x2`, element-wise. Returns scalar if both `x1` and `x2` are scalars. See Also -------- minimum : Element-wise minimum of two arrays, propagates NaNs. fmax : Element-wise maximum of two arrays, ignores NaNs. amax : The maximum value of an array along a given axis, propagates NaNs. nanmax : The maximum value of an array along a given axis, ignores NaNs. fmin, amin, nanmin Notes ----- The maximum is equivalent to ``np.where(x1 >= x2, x1, x2)`` when neither x1 nor x2 are nans, but it is faster and does proper broadcasting. Examples -------- >>> np.maximum([2, 3, 4], [1, 5, 2]) array([2, 5, 4]) >>> np.maximum(np.eye(2), [0.5, 2]) # broadcasting array([[ 1. , 2. ], [ 0.5, 2. ]]) >>> np.maximum([np.nan, 0, np.nan], [0, np.nan, np.nan]) array([ NaN, NaN, NaN]) >>> np.maximum(np.Inf, 1) inf """) add_newdoc('numpy.core.umath', 'minimum', """ Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. Parameters ---------- x1, x2 : array_like The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape. Returns ------- y : ndarray or scalar The minimum of `x1` and `x2`, element-wise. Returns scalar if both `x1` and `x2` are scalars. See Also -------- maximum : Element-wise maximum of two arrays, propagates NaNs. fmin : Element-wise minimum of two arrays, ignores NaNs. amin : The minimum value of an array along a given axis, propagates NaNs. nanmin : The minimum value of an array along a given axis, ignores NaNs. fmax, amax, nanmax Notes ----- The minimum is equivalent to ``np.where(x1 <= x2, x1, x2)`` when neither x1 nor x2 are NaNs, but it is faster and does proper broadcasting. Examples -------- >>> np.minimum([2, 3, 4], [1, 5, 2]) array([1, 3, 2]) >>> np.minimum(np.eye(2), [0.5, 2]) # broadcasting array([[ 0.5, 0. ], [ 0. , 1. ]]) >>> np.minimum([np.nan, 0, np.nan],[0, np.nan, np.nan]) array([ NaN, NaN, NaN]) >>> np.minimum(-np.Inf, 1) -inf """) add_newdoc('numpy.core.umath', 'fmax', """ Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible. Parameters ---------- x1, x2 : array_like The arrays holding the elements to be compared. They must have the same shape. Returns ------- y : ndarray or scalar The maximum of `x1` and `x2`, element-wise. Returns scalar if both `x1` and `x2` are scalars. See Also -------- fmin : Element-wise minimum of two arrays, ignores NaNs. maximum : Element-wise maximum of two arrays, propagates NaNs. amax : The maximum value of an array along a given axis, propagates NaNs. nanmax : The maximum value of an array along a given axis, ignores NaNs. minimum, amin, nanmin Notes ----- .. versionadded:: 1.3.0 The fmax is equivalent to ``np.where(x1 >= x2, x1, x2)`` when neither x1 nor x2 are NaNs, but it is faster and does proper broadcasting. Examples -------- >>> np.fmax([2, 3, 4], [1, 5, 2]) array([ 2., 5., 4.]) >>> np.fmax(np.eye(2), [0.5, 2]) array([[ 1. , 2. ], [ 0.5, 2. ]]) >>> np.fmax([np.nan, 0, np.nan],[0, np.nan, np.nan]) array([ 0., 0., NaN]) """) add_newdoc('numpy.core.umath', 'fmin', """ Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible. Parameters ---------- x1, x2 : array_like The arrays holding the elements to be compared. They must have the same shape. Returns ------- y : ndarray or scalar The minimum of `x1` and `x2`, element-wise. Returns scalar if both `x1` and `x2` are scalars. See Also -------- fmax : Element-wise maximum of two arrays, ignores NaNs. minimum : Element-wise minimum of two arrays, propagates NaNs. amin : The minimum value of an array along a given axis, propagates NaNs. nanmin : The minimum value of an array along a given axis, ignores NaNs. maximum, amax, nanmax Notes ----- .. versionadded:: 1.3.0 The fmin is equivalent to ``np.where(x1 <= x2, x1, x2)`` when neither x1 nor x2 are NaNs, but it is faster and does proper broadcasting. Examples -------- >>> np.fmin([2, 3, 4], [1, 5, 2]) array([2, 5, 4]) >>> np.fmin(np.eye(2), [0.5, 2]) array([[ 1. , 2. ], [ 0.5, 2. ]]) >>> np.fmin([np.nan, 0, np.nan],[0, np.nan, np.nan]) array([ 0., 0., NaN]) """) add_newdoc('numpy.core.umath', 'modf', """ Return the fractional and integral parts of an array, element-wise. The fractional and integral parts are negative if the given number is negative. Parameters ---------- x : array_like Input array. Returns ------- y1 : ndarray Fractional part of `x`. y2 : ndarray Integral part of `x`. Notes ----- For integer input the return values are floats. Examples -------- >>> np.modf([0, 3.5]) (array([ 0. , 0.5]), array([ 0., 3.])) >>> np.modf(-0.5) (-0.5, -0) """) add_newdoc('numpy.core.umath', 'multiply', """ Multiply arguments element-wise. Parameters ---------- x1, x2 : array_like Input arrays to be multiplied. Returns ------- y : ndarray The product of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. Notes ----- Equivalent to `x1` * `x2` in terms of array broadcasting. Examples -------- >>> np.multiply(2.0, 4.0) 8.0 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.multiply(x1, x2) array([[ 0., 1., 4.], [ 0., 4., 10.], [ 0., 7., 16.]]) """) add_newdoc('numpy.core.umath', 'negative', """ Numerical negative, element-wise. Parameters ---------- x : array_like or scalar Input array. Returns ------- y : ndarray or scalar Returned array or scalar: `y = -x`. Examples -------- >>> np.negative([1.,-1.]) array([-1., 1.]) """) add_newdoc('numpy.core.umath', 'not_equal', """ Return (x1 != x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays. out : ndarray, optional A placeholder the same shape as `x1` to store the result. See `doc.ufuncs` (Section "Output arguments") for more details. Returns ------- not_equal : ndarray bool, scalar bool For each element in `x1, x2`, return True if `x1` is not equal to `x2` and False otherwise. See Also -------- equal, greater, greater_equal, less, less_equal Examples -------- >>> np.not_equal([1.,2.], [1., 3.]) array([False, True], dtype=bool) >>> np.not_equal([1, 2], [[1, 3],[1, 4]]) array([[False, True], [False, True]], dtype=bool) """) add_newdoc('numpy.core.umath', '_ones_like', """ This function used to be the numpy.ones_like, but now a specific function for that has been written for consistency with the other *_like functions. It is only used internally in a limited fashion now. See Also -------- ones_like """) add_newdoc('numpy.core.umath', 'power', """ First array elements raised to powers from second array, element-wise. Raise each base in `x1` to the positionally-corresponding power in `x2`. `x1` and `x2` must be broadcastable to the same shape. Parameters ---------- x1 : array_like The bases. x2 : array_like The exponents. Returns ------- y : ndarray The bases in `x1` raised to the exponents in `x2`. Examples -------- Cube each element in a list. >>> x1 = range(6) >>> x1 [0, 1, 2, 3, 4, 5] >>> np.power(x1, 3) array([ 0, 1, 8, 27, 64, 125]) Raise the bases to different exponents. >>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0] >>> np.power(x1, x2) array([ 0., 1., 8., 27., 16., 5.]) The effect of broadcasting. >>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]]) >>> x2 array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]]) >>> np.power(x1, x2) array([[ 0, 1, 8, 27, 16, 5], [ 0, 1, 8, 27, 16, 5]]) """) add_newdoc('numpy.core.umath', 'radians', """ Convert angles from degrees to radians. Parameters ---------- x : array_like Input array in degrees. out : ndarray, optional Output array of same shape as `x`. Returns ------- y : ndarray The corresponding radian values. See Also -------- deg2rad : equivalent function Examples -------- Convert a degree array to radians >>> deg = np.arange(12.) * 30. >>> np.radians(deg) array([ 0. , 0.52359878, 1.04719755, 1.57079633, 2.0943951 , 2.61799388, 3.14159265, 3.66519143, 4.1887902 , 4.71238898, 5.23598776, 5.75958653]) >>> out = np.zeros((deg.shape)) >>> ret = np.radians(deg, out) >>> ret is out True """) add_newdoc('numpy.core.umath', 'deg2rad', """ Convert angles from degrees to radians. Parameters ---------- x : array_like Angles in degrees. Returns ------- y : ndarray The corresponding angle in radians. See Also -------- rad2deg : Convert angles from radians to degrees. unwrap : Remove large jumps in angle by wrapping. Notes ----- .. versionadded:: 1.3.0 ``deg2rad(x)`` is ``x * pi / 180``. Examples -------- >>> np.deg2rad(180) 3.1415926535897931 """) add_newdoc('numpy.core.umath', 'reciprocal', """ Return the reciprocal of the argument, element-wise. Calculates ``1/x``. Parameters ---------- x : array_like Input array. Returns ------- y : ndarray Return array. Notes ----- .. note:: This function is not designed to work with integers. For integer arguments with absolute value larger than 1 the result is always zero because of the way Python handles integer division. For integer zero the result is an overflow. Examples -------- >>> np.reciprocal(2.) 0.5 >>> np.reciprocal([1, 2., 3.33]) array([ 1. , 0.5 , 0.3003003]) """) add_newdoc('numpy.core.umath', 'remainder', """ Return element-wise remainder of division. Computes ``x1 - floor(x1 / x2) * x2``, the result has the same sign as the divisor `x2`. It is equivalent to the Python modulus operator ``x1 % x2`` and should not be confused with the Matlab(TM) ``rem`` function. Parameters ---------- x1 : array_like Dividend array. x2 : array_like Divisor array. out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See doc.ufuncs. Returns ------- y : ndarray The remainder of the quotient ``x1/x2``, element-wise. Returns a scalar if both `x1` and `x2` are scalars. See Also -------- fmod : Equivalent of the Matlab(TM) ``rem`` function. divide, floor Notes ----- Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of) integers. Examples -------- >>> np.remainder([4, 7], [2, 3]) array([0, 1]) >>> np.remainder(np.arange(7), 5) array([0, 1, 2, 3, 4, 0, 1]) """) add_newdoc('numpy.core.umath', 'right_shift', """ Shift the bits of an integer to the right. Bits are shifted to the right `x2`. Because the internal representation of numbers is in binary format, this operation is equivalent to dividing `x1` by ``2**x2``. Parameters ---------- x1 : array_like, int Input values. x2 : array_like, int Number of bits to remove at the right of `x1`. Returns ------- out : ndarray, int Return `x1` with bits shifted `x2` times to the right. See Also -------- left_shift : Shift the bits of an integer to the left. binary_repr : Return the binary representation of the input number as a string. Examples -------- >>> np.binary_repr(10) '1010' >>> np.right_shift(10, 1) 5 >>> np.binary_repr(5) '101' >>> np.right_shift(10, [1,2,3]) array([5, 2, 1]) """) add_newdoc('numpy.core.umath', 'rint', """ Round elements of the array to the nearest integer. Parameters ---------- x : array_like Input array. Returns ------- out : ndarray or scalar Output array is same shape and type as `x`. See Also -------- ceil, floor, trunc Examples -------- >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.rint(a) array([-2., -2., -0., 0., 2., 2., 2.]) """) add_newdoc('numpy.core.umath', 'sign', """ Returns an element-wise indication of the sign of a number. The `sign` function returns ``-1 if x < 0, 0 if x==0, 1 if x > 0``. Parameters ---------- x : array_like Input values. Returns ------- y : ndarray The sign of `x`. Examples -------- >>> np.sign([-5., 4.5]) array([-1., 1.]) >>> np.sign(0) 0 """) add_newdoc('numpy.core.umath', 'signbit', """ Returns element-wise True where signbit is set (less than zero). Parameters ---------- x : array_like The input value(s). out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See `doc.ufuncs`. Returns ------- result : ndarray of bool Output array, or reference to `out` if that was supplied. Examples -------- >>> np.signbit(-1.2) True >>> np.signbit(np.array([1, -2.3, 2.1])) array([False, True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'copysign', """ Change the sign of x1 to that of x2, element-wise. If both arguments are arrays or sequences, they have to be of the same length. If `x2` is a scalar, its sign will be copied to all elements of `x1`. Parameters ---------- x1 : array_like Values to change the sign of. x2 : array_like The sign of `x2` is copied to `x1`. out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See doc.ufuncs. Returns ------- out : array_like The values of `x1` with the sign of `x2`. Examples -------- >>> np.copysign(1.3, -1) -1.3 >>> 1/np.copysign(0, 1) inf >>> 1/np.copysign(0, -1) -inf >>> np.copysign([-1, 0, 1], -1.1) array([-1., -0., -1.]) >>> np.copysign([-1, 0, 1], np.arange(3)-1) array([-1., 0., 1.]) """) add_newdoc('numpy.core.umath', 'nextafter', """ Return the next floating-point value after x1 towards x2, element-wise. Parameters ---------- x1 : array_like Values to find the next representable value of. x2 : array_like The direction where to look for the next representable value of `x1`. out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See `doc.ufuncs`. Returns ------- out : array_like The next representable values of `x1` in the direction of `x2`. Examples -------- >>> eps = np.finfo(np.float64).eps >>> np.nextafter(1, 2) == eps + 1 True >>> np.nextafter([1, 2], [2, 1]) == [eps + 1, 2 - eps] array([ True, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'spacing', """ Return the distance between x and the nearest adjacent number. Parameters ---------- x1 : array_like Values to find the spacing of. Returns ------- out : array_like The spacing of values of `x1`. Notes ----- It can be considered as a generalization of EPS: ``spacing(np.float64(1)) == np.finfo(np.float64).eps``, and there should not be any representable number between ``x + spacing(x)`` and x for any finite x. Spacing of +- inf and NaN is NaN. Examples -------- >>> np.spacing(1) == np.finfo(np.float64).eps True """) add_newdoc('numpy.core.umath', 'sin', """ Trigonometric sine, element-wise. Parameters ---------- x : array_like Angle, in radians (:math:`2 \\pi` rad equals 360 degrees). Returns ------- y : array_like The sine of each element of x. See Also -------- arcsin, sinh, cos Notes ----- The sine is one of the fundamental functions of trigonometry (the mathematical study of triangles). Consider a circle of radius 1 centered on the origin. A ray comes in from the :math:`+x` axis, makes an angle at the origin (measured counter-clockwise from that axis), and departs from the origin. The :math:`y` coordinate of the outgoing ray's intersection with the unit circle is the sine of that angle. It ranges from -1 for :math:`x=3\\pi / 2` to +1 for :math:`\\pi / 2.` The function has zeroes where the angle is a multiple of :math:`\\pi`. Sines of angles between :math:`\\pi` and :math:`2\\pi` are negative. The numerous properties of the sine and related functions are included in any standard trigonometry text. Examples -------- Print sine of one angle: >>> np.sin(np.pi/2.) 1.0 Print sines of an array of angles given in degrees: >>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. ) array([ 0. , 0.5 , 0.70710678, 0.8660254 , 1. ]) Plot the sine function: >>> import matplotlib.pylab as plt >>> x = np.linspace(-np.pi, np.pi, 201) >>> plt.plot(x, np.sin(x)) >>> plt.xlabel('Angle [rad]') >>> plt.ylabel('sin(x)') >>> plt.axis('tight') >>> plt.show() """) add_newdoc('numpy.core.umath', 'sinh', """ Hyperbolic sine, element-wise. Equivalent to ``1/2 * (np.exp(x) - np.exp(-x))`` or ``-1j * np.sin(1j*x)``. Parameters ---------- x : array_like Input array. out : ndarray, optional Output array of same shape as `x`. Returns ------- y : ndarray The corresponding hyperbolic sine values. Raises ------ ValueError: invalid return array shape if `out` is provided and `out.shape` != `x.shape` (See Examples) Notes ----- If `out` is provided, the function writes the result into it, and returns a reference to `out`. (See Examples) References ---------- M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972, pg. 83. Examples -------- >>> np.sinh(0) 0.0 >>> np.sinh(np.pi*1j/2) 1j >>> np.sinh(np.pi*1j) # (exact value is 0) 1.2246063538223773e-016j >>> # Discrepancy due to vagaries of floating point arithmetic. >>> # Example of providing the optional output parameter >>> out2 = np.sinh([0.1], out1) >>> out2 is out1 True >>> # Example of ValueError due to provision of shape mis-matched `out` >>> np.sinh(np.zeros((3,3)),np.zeros((2,2))) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid return array shape """) add_newdoc('numpy.core.umath', 'sqrt', """ Return the positive square-root of an array, element-wise. Parameters ---------- x : array_like The values whose square-roots are required. out : ndarray, optional Alternate array object in which to put the result; if provided, it must have the same shape as `x` Returns ------- y : ndarray An array of the same shape as `x`, containing the positive square-root of each element in `x`. If any element in `x` is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in `x` are real, so is `y`, with negative elements returning ``nan``. If `out` was provided, `y` is a reference to it. See Also -------- lib.scimath.sqrt A version which returns complex numbers when given negative reals. Notes ----- *sqrt* has--consistent with common convention--as its branch cut the real "interval" [`-inf`, 0), and is continuous from above on it. A branch cut is a curve in the complex plane across which a given complex function fails to be continuous. Examples -------- >>> np.sqrt([1,4,9]) array([ 1., 2., 3.]) >>> np.sqrt([4, -1, -3+4J]) array([ 2.+0.j, 0.+1.j, 1.+2.j]) >>> np.sqrt([4, -1, numpy.inf]) array([ 2., NaN, Inf]) """) add_newdoc('numpy.core.umath', 'cbrt', """ Return the cube-root of an array, element-wise. .. versionadded:: 1.10.0 Parameters ---------- x : array_like The values whose cube-roots are required. out : ndarray, optional Alternate array object in which to put the result; if provided, it must have the same shape as `x` Returns ------- y : ndarray An array of the same shape as `x`, containing the cube cube-root of each element in `x`. If `out` was provided, `y` is a reference to it. Examples -------- >>> np.cbrt([1,8,27]) array([ 1., 2., 3.]) """) add_newdoc('numpy.core.umath', 'square', """ Return the element-wise square of the input. Parameters ---------- x : array_like Input data. Returns ------- out : ndarray Element-wise `x*x`, of the same shape and dtype as `x`. Returns scalar if `x` is a scalar. See Also -------- numpy.linalg.matrix_power sqrt power Examples -------- >>> np.square([-1j, 1]) array([-1.-0.j, 1.+0.j]) """) add_newdoc('numpy.core.umath', 'subtract', """ Subtract arguments, element-wise. Parameters ---------- x1, x2 : array_like The arrays to be subtracted from each other. Returns ------- y : ndarray The difference of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. Notes ----- Equivalent to ``x1 - x2`` in terms of array broadcasting. Examples -------- >>> np.subtract(1.0, 4.0) -3.0 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.subtract(x1, x2) array([[ 0., 0., 0.], [ 3., 3., 3.], [ 6., 6., 6.]]) """) add_newdoc('numpy.core.umath', 'tan', """ Compute tangent element-wise. Equivalent to ``np.sin(x)/np.cos(x)`` element-wise. Parameters ---------- x : array_like Input array. out : ndarray, optional Output array of same shape as `x`. Returns ------- y : ndarray The corresponding tangent values. Raises ------ ValueError: invalid return array shape if `out` is provided and `out.shape` != `x.shape` (See Examples) Notes ----- If `out` is provided, the function writes the result into it, and returns a reference to `out`. (See Examples) References ---------- M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972. Examples -------- >>> from math import pi >>> np.tan(np.array([-pi,pi/2,pi])) array([ 1.22460635e-16, 1.63317787e+16, -1.22460635e-16]) >>> >>> # Example of providing the optional output parameter illustrating >>> # that what is returned is a reference to said parameter >>> out2 = np.cos([0.1], out1) >>> out2 is out1 True >>> >>> # Example of ValueError due to provision of shape mis-matched `out` >>> np.cos(np.zeros((3,3)),np.zeros((2,2))) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid return array shape """) add_newdoc('numpy.core.umath', 'tanh', """ Compute hyperbolic tangent element-wise. Equivalent to ``np.sinh(x)/np.cosh(x)`` or ``-1j * np.tan(1j*x)``. Parameters ---------- x : array_like Input array. out : ndarray, optional Output array of same shape as `x`. Returns ------- y : ndarray The corresponding hyperbolic tangent values. Raises ------ ValueError: invalid return array shape if `out` is provided and `out.shape` != `x.shape` (See Examples) Notes ----- If `out` is provided, the function writes the result into it, and returns a reference to `out`. (See Examples) References ---------- .. [1] M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972, pg. 83. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Hyperbolic function", http://en.wikipedia.org/wiki/Hyperbolic_function Examples -------- >>> np.tanh((0, np.pi*1j, np.pi*1j/2)) array([ 0. +0.00000000e+00j, 0. -1.22460635e-16j, 0. +1.63317787e+16j]) >>> # Example of providing the optional output parameter illustrating >>> # that what is returned is a reference to said parameter >>> out2 = np.tanh([0.1], out1) >>> out2 is out1 True >>> # Example of ValueError due to provision of shape mis-matched `out` >>> np.tanh(np.zeros((3,3)),np.zeros((2,2))) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid return array shape """) add_newdoc('numpy.core.umath', 'true_divide', """ Returns a true division of the inputs, element-wise. Instead of the Python traditional 'floor division', this returns a true division. True division adjusts the output type to present the best answer, regardless of input types. Parameters ---------- x1 : array_like Dividend array. x2 : array_like Divisor array. Returns ------- out : ndarray Result is scalar if both inputs are scalar, ndarray otherwise. Notes ----- The floor division operator ``//`` was added in Python 2.2 making ``//`` and ``/`` equivalent operators. The default floor division operation of ``/`` can be replaced by true division with ``from __future__ import division``. In Python 3.0, ``//`` is the floor division operator and ``/`` the true division operator. The ``true_divide(x1, x2)`` function is equivalent to true division in Python. Examples -------- >>> x = np.arange(5) >>> np.true_divide(x, 4) array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x/4 array([0, 0, 0, 0, 1]) >>> x//4 array([0, 0, 0, 0, 1]) >>> from __future__ import division >>> x/4 array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x//4 array([0, 0, 0, 0, 1]) """) add_newdoc('numpy.core.umath', 'frexp', """ Decompose the elements of x into mantissa and twos exponent. Returns (`mantissa`, `exponent`), where `x = mantissa * 2**exponent``. The mantissa is lies in the open interval(-1, 1), while the twos exponent is a signed integer. Parameters ---------- x : array_like Array of numbers to be decomposed. out1 : ndarray, optional Output array for the mantissa. Must have the same shape as `x`. out2 : ndarray, optional Output array for the exponent. Must have the same shape as `x`. Returns ------- (mantissa, exponent) : tuple of ndarrays, (float, int) `mantissa` is a float array with values between -1 and 1. `exponent` is an int array which represents the exponent of 2. See Also -------- ldexp : Compute ``y = x1 * 2**x2``, the inverse of `frexp`. Notes ----- Complex dtypes are not supported, they will raise a TypeError. Examples -------- >>> x = np.arange(9) >>> y1, y2 = np.frexp(x) >>> y1 array([ 0. , 0.5 , 0.5 , 0.75 , 0.5 , 0.625, 0.75 , 0.875, 0.5 ]) >>> y2 array([0, 1, 2, 2, 3, 3, 3, 3, 4]) >>> y1 * 2**y2 array([ 0., 1., 2., 3., 4., 5., 6., 7., 8.]) """) add_newdoc('numpy.core.umath', 'ldexp', """ Returns x1 * 2**x2, element-wise. The mantissas `x1` and twos exponents `x2` are used to construct floating point numbers ``x1 * 2**x2``. Parameters ---------- x1 : array_like Array of multipliers. x2 : array_like, int Array of twos exponents. out : ndarray, optional Output array for the result. Returns ------- y : ndarray or scalar The result of ``x1 * 2**x2``. See Also -------- frexp : Return (y1, y2) from ``x = y1 * 2**y2``, inverse to `ldexp`. Notes ----- Complex dtypes are not supported, they will raise a TypeError. `ldexp` is useful as the inverse of `frexp`, if used by itself it is more clear to simply use the expression ``x1 * 2**x2``. Examples -------- >>> np.ldexp(5, np.arange(4)) array([ 5., 10., 20., 40.], dtype=float32) >>> x = np.arange(6) >>> np.ldexp(*np.frexp(x)) array([ 0., 1., 2., 3., 4., 5.]) """)
bsd-3-clause
danielvdende/incubator-airflow
airflow/www/views.py
1
111409
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import ast import codecs import copy import datetime as dt import inspect import itertools import json import logging import math import os import traceback from collections import defaultdict from datetime import timedelta from functools import wraps from textwrap import dedent import bleach import markdown import nvd3 import pendulum import pkg_resources import sqlalchemy as sqla from flask import ( abort, jsonify, redirect, url_for, request, Markup, Response, current_app, render_template, make_response) from flask import flash from flask._compat import PY2 from flask_admin import BaseView, expose, AdminIndexView from flask_admin.actions import action from flask_admin.babel import lazy_gettext from flask_admin.contrib.sqla import ModelView from flask_admin.form.fields import DateTimeField from flask_admin.tools import iterdecode from jinja2 import escape from jinja2.sandbox import ImmutableSandboxedEnvironment from past.builtins import basestring, unicode from pygments import highlight, lexers from pygments.formatters import HtmlFormatter from sqlalchemy import or_, desc, and_, union_all from wtforms import ( Form, SelectField, TextAreaField, PasswordField, StringField, validators) import airflow from airflow import configuration as conf from airflow import models from airflow import settings from airflow.api.common.experimental.mark_tasks import (set_dag_run_state_to_running, set_dag_run_state_to_success, set_dag_run_state_to_failed) from airflow.exceptions import AirflowException from airflow.models import BaseOperator from airflow.models import XCom, DagRun from airflow.operators.subdag_operator import SubDagOperator from airflow.ti_deps.dep_context import DepContext, QUEUE_DEPS, SCHEDULER_DEPS from airflow.utils import timezone from airflow.utils.dates import infer_time_unit, scale_time_units, parse_execution_date from airflow.utils.db import create_session, provide_session from airflow.utils.helpers import alchemy_to_dict from airflow.utils.json import json_ser from airflow.utils.net import get_hostname from airflow.utils.state import State from airflow.utils.timezone import datetime from airflow.www import utils as wwwutils from airflow.www.forms import (DateTimeForm, DateTimeWithNumRunsForm, DateTimeWithNumRunsWithDagRunsForm) from airflow.www.validators import GreaterEqualThan QUERY_LIMIT = 100000 CHART_LIMIT = 200000 UTF8_READER = codecs.getreader('utf-8') dagbag = models.DagBag(settings.DAGS_FOLDER) login_required = airflow.login.login_required current_user = airflow.login.current_user logout_user = airflow.login.logout_user FILTER_BY_OWNER = False PAGE_SIZE = conf.getint('webserver', 'page_size') if conf.getboolean('webserver', 'FILTER_BY_OWNER'): # filter_by_owner if authentication is enabled and filter_by_owner is true FILTER_BY_OWNER = not current_app.config['LOGIN_DISABLED'] def dag_link(v, c, m, p): if m.dag_id is None: return Markup() dag_id = bleach.clean(m.dag_id) url = url_for( 'airflow.graph', dag_id=dag_id, execution_date=m.execution_date) return Markup( '<a href="{}">{}</a>'.format(url, dag_id)) def log_url_formatter(v, c, m, p): return Markup( '<a href="{m.log_url}">' ' <span class="glyphicon glyphicon-book" aria-hidden="true">' '</span></a>').format(**locals()) def dag_run_link(v, c, m, p): dag_id = bleach.clean(m.dag_id) url = url_for( 'airflow.graph', dag_id=m.dag_id, run_id=m.run_id, execution_date=m.execution_date) return Markup('<a href="{url}">{m.run_id}</a>'.format(**locals())) def task_instance_link(v, c, m, p): dag_id = bleach.clean(m.dag_id) task_id = bleach.clean(m.task_id) url = url_for( 'airflow.task', dag_id=dag_id, task_id=task_id, execution_date=m.execution_date.isoformat()) url_root = url_for( 'airflow.graph', dag_id=dag_id, root=task_id, execution_date=m.execution_date.isoformat()) return Markup( """ <span style="white-space: nowrap;"> <a href="{url}">{task_id}</a> <a href="{url_root}" title="Filter on this task and upstream"> <span class="glyphicon glyphicon-filter" style="margin-left: 0px;" aria-hidden="true"></span> </a> </span> """.format(**locals())) def state_token(state): color = State.color(state) return Markup( '<span class="label" style="background-color:{color};">' '{state}</span>'.format(**locals())) def parse_datetime_f(value): if not isinstance(value, dt.datetime): return value return timezone.make_aware(value) def state_f(v, c, m, p): return state_token(m.state) def duration_f(v, c, m, p): if m.end_date and m.duration: return timedelta(seconds=m.duration) def datetime_f(v, c, m, p): attr = getattr(m, p) dttm = attr.isoformat() if attr else '' if timezone.utcnow().isoformat()[:4] == dttm[:4]: dttm = dttm[5:] return Markup("<nobr>{}</nobr>".format(dttm)) def nobr_f(v, c, m, p): return Markup("<nobr>{}</nobr>".format(getattr(m, p))) def label_link(v, c, m, p): try: default_params = ast.literal_eval(m.default_params) except Exception: default_params = {} url = url_for( 'airflow.chart', chart_id=m.id, iteration_no=m.iteration_no, **default_params) return Markup("<a href='{url}'>{m.label}</a>".format(**locals())) def pool_link(v, c, m, p): url = '/admin/taskinstance/?flt1_pool_equals=' + m.pool return Markup("<a href='{url}'>{m.pool}</a>".format(**locals())) def pygment_html_render(s, lexer=lexers.TextLexer): return highlight( s, lexer(), HtmlFormatter(linenos=True), ) def render(obj, lexer): out = "" if isinstance(obj, basestring): out += pygment_html_render(obj, lexer) elif isinstance(obj, (tuple, list)): for i, s in enumerate(obj): out += "<div>List item #{}</div>".format(i) out += "<div>" + pygment_html_render(s, lexer) + "</div>" elif isinstance(obj, dict): for k, v in obj.items(): out += '<div>Dict item "{}"</div>'.format(k) out += "<div>" + pygment_html_render(v, lexer) + "</div>" return out def wrapped_markdown(s): return '<div class="rich_doc">' + markdown.markdown(s) + "</div>" attr_renderer = { 'bash_command': lambda x: render(x, lexers.BashLexer), 'hql': lambda x: render(x, lexers.SqlLexer), 'sql': lambda x: render(x, lexers.SqlLexer), 'doc': lambda x: render(x, lexers.TextLexer), 'doc_json': lambda x: render(x, lexers.JsonLexer), 'doc_rst': lambda x: render(x, lexers.RstLexer), 'doc_yaml': lambda x: render(x, lexers.YamlLexer), 'doc_md': wrapped_markdown, 'python_callable': lambda x: render( wwwutils.get_python_source(x), lexers.PythonLexer, ), } def data_profiling_required(f): """Decorator for views requiring data profiling access""" @wraps(f) def decorated_function(*args, **kwargs): if ( current_app.config['LOGIN_DISABLED'] or (not current_user.is_anonymous() and current_user.data_profiling()) ): return f(*args, **kwargs) else: flash("This page requires data profiling privileges", "error") return redirect(url_for('admin.index')) return decorated_function def fused_slots(v, c, m, p): url = ( '/admin/taskinstance/' + '?flt1_pool_equals=' + m.pool + '&flt2_state_equals=running') return Markup("<a href='{0}'>{1}</a>".format(url, m.used_slots())) def fqueued_slots(v, c, m, p): url = ( '/admin/taskinstance/' + '?flt1_pool_equals=' + m.pool + '&flt2_state_equals=queued&sort=10&desc=1') return Markup("<a href='{0}'>{1}</a>".format(url, m.queued_slots())) def recurse_tasks(tasks, task_ids, dag_ids, task_id_to_dag): if isinstance(tasks, list): for task in tasks: recurse_tasks(task, task_ids, dag_ids, task_id_to_dag) return if isinstance(tasks, SubDagOperator): subtasks = tasks.subdag.tasks dag_ids.append(tasks.subdag.dag_id) for subtask in subtasks: if subtask.task_id not in task_ids: task_ids.append(subtask.task_id) task_id_to_dag[subtask.task_id] = tasks.subdag recurse_tasks(subtasks, task_ids, dag_ids, task_id_to_dag) if isinstance(tasks, BaseOperator): task_id_to_dag[tasks.task_id] = tasks.dag def get_chart_height(dag): """ TODO(aoen): See [AIRFLOW-1263] We use the number of tasks in the DAG as a heuristic to approximate the size of generated chart (otherwise the charts are tiny and unreadable when DAGs have a large number of tasks). Ideally nvd3 should allow for dynamic-height charts, that is charts that take up space based on the size of the components within. """ return 600 + len(dag.tasks) * 10 def get_date_time_num_runs_dag_runs_form_data(request, session, dag): dttm = request.args.get('execution_date') if dttm: dttm = pendulum.parse(dttm) else: dttm = dag.latest_execution_date or timezone.utcnow() base_date = request.args.get('base_date') if base_date: base_date = timezone.parse(base_date) else: # The DateTimeField widget truncates milliseconds and would loose # the first dag run. Round to next second. base_date = (dttm + timedelta(seconds=1)).replace(microsecond=0) default_dag_run = conf.getint('webserver', 'default_dag_run_display_number') num_runs = request.args.get('num_runs') num_runs = int(num_runs) if num_runs else default_dag_run DR = models.DagRun drs = ( session.query(DR) .filter( DR.dag_id == dag.dag_id, DR.execution_date <= base_date) .order_by(desc(DR.execution_date)) .limit(num_runs) .all() ) dr_choices = [] dr_state = None for dr in drs: dr_choices.append((dr.execution_date.isoformat(), dr.run_id)) if dttm == dr.execution_date: dr_state = dr.state # Happens if base_date was changed and the selected dag run is not in result if not dr_state and drs: dr = drs[0] dttm = dr.execution_date dr_state = dr.state return { 'dttm': dttm, 'base_date': base_date, 'num_runs': num_runs, 'execution_date': dttm.isoformat(), 'dr_choices': dr_choices, 'dr_state': dr_state, } class Airflow(BaseView): def is_visible(self): return False @expose('/') @login_required def index(self): return self.render('airflow/dags.html') @expose('/chart_data') @data_profiling_required @wwwutils.gzipped # @cache.cached(timeout=3600, key_prefix=wwwutils.make_cache_key) def chart_data(self): from airflow import macros import pandas as pd if conf.getboolean('core', 'secure_mode'): abort(404) with create_session() as session: chart_id = request.args.get('chart_id') csv = request.args.get('csv') == "true" chart = session.query(models.Chart).filter_by(id=chart_id).first() db = session.query( models.Connection).filter_by(conn_id=chart.conn_id).first() payload = { "state": "ERROR", "error": "" } # Processing templated fields try: args = ast.literal_eval(chart.default_params) if not isinstance(args, dict): raise AirflowException('Not a dict') except Exception: args = {} payload['error'] += ( "Default params is not valid, string has to evaluate as " "a Python dictionary. ") request_dict = {k: request.args.get(k) for k in request.args} args.update(request_dict) args['macros'] = macros sandbox = ImmutableSandboxedEnvironment() sql = sandbox.from_string(chart.sql).render(**args) label = sandbox.from_string(chart.label).render(**args) payload['sql_html'] = Markup(highlight( sql, lexers.SqlLexer(), # Lexer call HtmlFormatter(noclasses=True)) ) payload['label'] = label pd.set_option('display.max_colwidth', 100) hook = db.get_hook() try: df = hook.get_pandas_df( wwwutils.limit_sql(sql, CHART_LIMIT, conn_type=db.conn_type)) df = df.fillna(0) except Exception as e: payload['error'] += "SQL execution failed. Details: " + str(e) if csv: return Response( response=df.to_csv(index=False), status=200, mimetype="application/text") if not payload['error'] and len(df) == CHART_LIMIT: payload['warning'] = ( "Data has been truncated to {0}" " rows. Expect incomplete results.").format(CHART_LIMIT) if not payload['error'] and len(df) == 0: payload['error'] += "Empty result set. " elif ( not payload['error'] and chart.sql_layout == 'series' and chart.chart_type != "datatable" and len(df.columns) < 3): payload['error'] += "SQL needs to return at least 3 columns. " elif ( not payload['error'] and chart.sql_layout == 'columns' and len(df.columns) < 2): payload['error'] += "SQL needs to return at least 2 columns. " elif not payload['error']: import numpy as np chart_type = chart.chart_type data = None if chart.show_datatable or chart_type == "datatable": data = df.to_dict(orient="split") data['columns'] = [{'title': c} for c in data['columns']] payload['data'] = data # Trying to convert time to something Highcharts likes x_col = 1 if chart.sql_layout == 'series' else 0 if chart.x_is_date: try: # From string to datetime df[df.columns[x_col]] = pd.to_datetime( df[df.columns[x_col]]) df[df.columns[x_col]] = df[df.columns[x_col]].apply( lambda x: int(x.strftime("%s")) * 1000) except Exception as e: payload['error'] = "Time conversion failed" if chart_type == 'datatable': payload['state'] = 'SUCCESS' return wwwutils.json_response(payload) else: if chart.sql_layout == 'series': # User provides columns (series, x, y) xaxis_label = df.columns[1] yaxis_label = df.columns[2] df[df.columns[2]] = df[df.columns[2]].astype(np.float) df = df.pivot_table( index=df.columns[1], columns=df.columns[0], values=df.columns[2], aggfunc=np.sum) else: # User provides columns (x, y, metric1, metric2, ...) xaxis_label = df.columns[0] yaxis_label = 'y' df.index = df[df.columns[0]] df = df.sort(df.columns[0]) del df[df.columns[0]] for col in df.columns: df[col] = df[col].astype(np.float) df = df.fillna(0) NVd3ChartClass = chart_mapping.get(chart.chart_type) NVd3ChartClass = getattr(nvd3, NVd3ChartClass) nvd3_chart = NVd3ChartClass(x_is_date=chart.x_is_date) for col in df.columns: nvd3_chart.add_serie(name=col, y=df[col].tolist(), x=df[col].index.tolist()) try: nvd3_chart.buildcontent() payload['chart_type'] = nvd3_chart.__class__.__name__ payload['htmlcontent'] = nvd3_chart.htmlcontent except Exception as e: payload['error'] = str(e) payload['state'] = 'SUCCESS' payload['request_dict'] = request_dict return wwwutils.json_response(payload) @expose('/chart') @data_profiling_required def chart(self): if conf.getboolean('core', 'secure_mode'): abort(404) with create_session() as session: chart_id = request.args.get('chart_id') embed = request.args.get('embed') chart = session.query(models.Chart).filter_by(id=chart_id).first() NVd3ChartClass = chart_mapping.get(chart.chart_type) if not NVd3ChartClass: flash( "Not supported anymore as the license was incompatible, " "sorry", "danger") redirect('/admin/chart/') sql = "" if chart.show_sql: sql = Markup(highlight( chart.sql, lexers.SqlLexer(), # Lexer call HtmlFormatter(noclasses=True)) ) return self.render( 'airflow/nvd3.html', chart=chart, title="Airflow - Chart", sql=sql, label=chart.label, embed=embed) @expose('/dag_stats') @login_required @provide_session def dag_stats(self, session=None): ds = models.DagStat ds.update( dag_ids=[dag.dag_id for dag in dagbag.dags.values() if not dag.is_subdag] ) qry = ( session.query(ds.dag_id, ds.state, ds.count) ) data = {} for dag_id, state, count in qry: if dag_id not in data: data[dag_id] = {} data[dag_id][state] = count payload = {} for dag in dagbag.dags.values(): payload[dag.safe_dag_id] = [] for state in State.dag_states: try: count = data[dag.dag_id][state] except Exception: count = 0 d = { 'state': state, 'count': count, 'dag_id': dag.dag_id, 'color': State.color(state) } payload[dag.safe_dag_id].append(d) return wwwutils.json_response(payload) @expose('/task_stats') @login_required @provide_session def task_stats(self, session=None): TI = models.TaskInstance DagRun = models.DagRun Dag = models.DagModel LastDagRun = ( session.query(DagRun.dag_id, sqla.func.max(DagRun.execution_date).label('execution_date')) .join(Dag, Dag.dag_id == DagRun.dag_id) .filter(DagRun.state != State.RUNNING) .filter(Dag.is_active == True) .filter(Dag.is_subdag == False) .group_by(DagRun.dag_id) .subquery('last_dag_run') ) RunningDagRun = ( session.query(DagRun.dag_id, DagRun.execution_date) .join(Dag, Dag.dag_id == DagRun.dag_id) .filter(DagRun.state == State.RUNNING) .filter(Dag.is_active == True) .filter(Dag.is_subdag == False) .subquery('running_dag_run') ) # Select all task_instances from active dag_runs. # If no dag_run is active, return task instances from most recent dag_run. LastTI = ( session.query(TI.dag_id.label('dag_id'), TI.state.label('state')) .join(LastDagRun, and_( LastDagRun.c.dag_id == TI.dag_id, LastDagRun.c.execution_date == TI.execution_date)) ) RunningTI = ( session.query(TI.dag_id.label('dag_id'), TI.state.label('state')) .join(RunningDagRun, and_( RunningDagRun.c.dag_id == TI.dag_id, RunningDagRun.c.execution_date == TI.execution_date)) ) UnionTI = union_all(LastTI, RunningTI).alias('union_ti') qry = ( session.query(UnionTI.c.dag_id, UnionTI.c.state, sqla.func.count()) .group_by(UnionTI.c.dag_id, UnionTI.c.state) ) data = {} for dag_id, state, count in qry: if dag_id not in data: data[dag_id] = {} data[dag_id][state] = count session.commit() payload = {} for dag in dagbag.dags.values(): payload[dag.safe_dag_id] = [] for state in State.task_states: try: count = data[dag.dag_id][state] except Exception: count = 0 d = { 'state': state, 'count': count, 'dag_id': dag.dag_id, 'color': State.color(state) } payload[dag.safe_dag_id].append(d) return wwwutils.json_response(payload) @expose('/code') @login_required def code(self): dag_id = request.args.get('dag_id') dag = dagbag.get_dag(dag_id) title = dag_id try: with open(dag.fileloc, 'r') as f: code = f.read() html_code = highlight( code, lexers.PythonLexer(), HtmlFormatter(linenos=True)) except IOError as e: html_code = str(e) return self.render( 'airflow/dag_code.html', html_code=html_code, dag=dag, title=title, root=request.args.get('root'), demo_mode=conf.getboolean('webserver', 'demo_mode')) @expose('/dag_details') @login_required @provide_session def dag_details(self, session=None): dag_id = request.args.get('dag_id') dag = dagbag.get_dag(dag_id) title = "DAG details" TI = models.TaskInstance states = ( session.query(TI.state, sqla.func.count(TI.dag_id)) .filter(TI.dag_id == dag_id) .group_by(TI.state) .all() ) return self.render( 'airflow/dag_details.html', dag=dag, title=title, states=states, State=State) @current_app.errorhandler(404) def circles(self): return render_template( 'airflow/circles.html', hostname=get_hostname()), 404 @current_app.errorhandler(500) def show_traceback(self): from airflow.utils import asciiart as ascii_ return render_template( 'airflow/traceback.html', hostname=get_hostname(), nukular=ascii_.nukular, info=traceback.format_exc()), 500 @expose('/noaccess') def noaccess(self): return self.render('airflow/noaccess.html') @expose('/pickle_info') @login_required def pickle_info(self): d = {} dag_id = request.args.get('dag_id') dags = [dagbag.dags.get(dag_id)] if dag_id else dagbag.dags.values() for dag in dags: if not dag.is_subdag: d[dag.dag_id] = dag.pickle_info() return wwwutils.json_response(d) @expose('/login', methods=['GET', 'POST']) def login(self): return airflow.login.login(self, request) @expose('/logout') def logout(self): logout_user() flash('You have been logged out.') return redirect(url_for('admin.index')) @expose('/rendered') @login_required @wwwutils.action_logging def rendered(self): dag_id = request.args.get('dag_id') task_id = request.args.get('task_id') execution_date = request.args.get('execution_date') dttm = pendulum.parse(execution_date) form = DateTimeForm(data={'execution_date': dttm}) dag = dagbag.get_dag(dag_id) task = copy.copy(dag.get_task(task_id)) ti = models.TaskInstance(task=task, execution_date=dttm) try: ti.render_templates() except Exception as e: flash("Error rendering template: " + str(e), "error") title = "Rendered Template" html_dict = {} for template_field in task.__class__.template_fields: content = getattr(task, template_field) if template_field in attr_renderer: html_dict[template_field] = attr_renderer[template_field](content) else: html_dict[template_field] = ( "<pre><code>" + str(content) + "</pre></code>") return self.render( 'airflow/ti_code.html', html_dict=html_dict, dag=dag, task_id=task_id, execution_date=execution_date, form=form, title=title, ) @expose('/get_logs_with_metadata') @login_required @wwwutils.action_logging @provide_session def get_logs_with_metadata(self, session=None): dag_id = request.args.get('dag_id') task_id = request.args.get('task_id') execution_date = request.args.get('execution_date') dttm = pendulum.parse(execution_date) try_number = int(request.args.get('try_number')) metadata = request.args.get('metadata') metadata = json.loads(metadata) # metadata may be null if not metadata: metadata = {} # Convert string datetime into actual datetime try: execution_date = timezone.parse(execution_date) except ValueError: error_message = ( 'Given execution date, {}, could not be identified ' 'as a date. Example date format: 2015-11-16T14:34:15+00:00'.format( execution_date)) response = jsonify({'error': error_message}) response.status_code = 400 return response logger = logging.getLogger('airflow.task') task_log_reader = conf.get('core', 'task_log_reader') handler = next((handler for handler in logger.handlers if handler.name == task_log_reader), None) ti = session.query(models.TaskInstance).filter( models.TaskInstance.dag_id == dag_id, models.TaskInstance.task_id == task_id, models.TaskInstance.execution_date == dttm).first() try: if ti is None: logs = ["*** Task instance did not exist in the DB\n"] metadata['end_of_log'] = True else: dag = dagbag.get_dag(dag_id) ti.task = dag.get_task(ti.task_id) logs, metadatas = handler.read(ti, try_number, metadata=metadata) metadata = metadatas[0] for i, log in enumerate(logs): if PY2 and not isinstance(log, unicode): logs[i] = log.decode('utf-8') message = logs[0] return jsonify(message=message, metadata=metadata) except AttributeError as e: error_message = ["Task log handler {} does not support read logs.\n{}\n" .format(task_log_reader, str(e))] metadata['end_of_log'] = True return jsonify(message=error_message, error=True, metadata=metadata) @expose('/log') @login_required @wwwutils.action_logging @provide_session def log(self, session=None): dag_id = request.args.get('dag_id') task_id = request.args.get('task_id') execution_date = request.args.get('execution_date') dttm = pendulum.parse(execution_date) form = DateTimeForm(data={'execution_date': dttm}) dag = dagbag.get_dag(dag_id) ti = session.query(models.TaskInstance).filter( models.TaskInstance.dag_id == dag_id, models.TaskInstance.task_id == task_id, models.TaskInstance.execution_date == dttm).first() logs = [''] * (ti.next_try_number - 1 if ti is not None else 0) return self.render( 'airflow/ti_log.html', logs=logs, dag=dag, title="Log by attempts", dag_id=dag.dag_id, task_id=task_id, execution_date=execution_date, form=form) @expose('/task') @login_required @wwwutils.action_logging def task(self): TI = models.TaskInstance dag_id = request.args.get('dag_id') task_id = request.args.get('task_id') # Carrying execution_date through, even though it's irrelevant for # this context execution_date = request.args.get('execution_date') dttm = pendulum.parse(execution_date) form = DateTimeForm(data={'execution_date': dttm}) dag = dagbag.get_dag(dag_id) if not dag or task_id not in dag.task_ids: flash( "Task [{}.{}] doesn't seem to exist" " at the moment".format(dag_id, task_id), "error") return redirect('/admin/') task = copy.copy(dag.get_task(task_id)) task.resolve_template_files() ti = TI(task=task, execution_date=dttm) ti.refresh_from_db() ti_attrs = [] for attr_name in dir(ti): if not attr_name.startswith('_'): attr = getattr(ti, attr_name) if type(attr) != type(self.task): ti_attrs.append((attr_name, str(attr))) task_attrs = [] for attr_name in dir(task): if not attr_name.startswith('_'): attr = getattr(task, attr_name) if type(attr) != type(self.task) and \ attr_name not in attr_renderer: task_attrs.append((attr_name, str(attr))) # Color coding the special attributes that are code special_attrs_rendered = {} for attr_name in attr_renderer: if hasattr(task, attr_name): source = getattr(task, attr_name) special_attrs_rendered[attr_name] = attr_renderer[attr_name](source) no_failed_deps_result = [( "Unknown", dedent("""\ All dependencies are met but the task instance is not running. In most cases this just means that the task will probably be scheduled soon unless:<br/> - The scheduler is down or under heavy load<br/> - The following configuration values may be limiting the number of queueable processes: <code>parallelism</code>, <code>dag_concurrency</code>, <code>max_active_dag_runs_per_dag</code>, <code>non_pooled_task_slot_count</code><br/> {} <br/> If this task instance does not start soon please contact your Airflow """ """administrator for assistance.""" .format( "- This task instance already ran and had its state changed " "manually (e.g. cleared in the UI)<br/>" if ti.state == State.NONE else "")))] # Use the scheduler's context to figure out which dependencies are not met dep_context = DepContext(SCHEDULER_DEPS) failed_dep_reasons = [(dep.dep_name, dep.reason) for dep in ti.get_failed_dep_statuses( dep_context=dep_context)] title = "Task Instance Details" return self.render( 'airflow/task.html', task_attrs=task_attrs, ti_attrs=ti_attrs, failed_dep_reasons=failed_dep_reasons or no_failed_deps_result, task_id=task_id, execution_date=execution_date, special_attrs_rendered=special_attrs_rendered, form=form, dag=dag, title=title) @expose('/xcom') @login_required @wwwutils.action_logging @provide_session def xcom(self, session=None): dag_id = request.args.get('dag_id') task_id = request.args.get('task_id') # Carrying execution_date through, even though it's irrelevant for # this context execution_date = request.args.get('execution_date') dttm = pendulum.parse(execution_date) form = DateTimeForm(data={'execution_date': dttm}) dag = dagbag.get_dag(dag_id) if not dag or task_id not in dag.task_ids: flash( "Task [{}.{}] doesn't seem to exist" " at the moment".format(dag_id, task_id), "error") return redirect('/admin/') xcomlist = session.query(XCom).filter( XCom.dag_id == dag_id, XCom.task_id == task_id, XCom.execution_date == dttm).all() attributes = [] for xcom in xcomlist: if not xcom.key.startswith('_'): attributes.append((xcom.key, xcom.value)) title = "XCom" return self.render( 'airflow/xcom.html', attributes=attributes, task_id=task_id, execution_date=execution_date, form=form, dag=dag, title=title) @expose('/run') @login_required @wwwutils.action_logging @wwwutils.notify_owner def run(self): dag_id = request.args.get('dag_id') task_id = request.args.get('task_id') origin = request.args.get('origin') dag = dagbag.get_dag(dag_id) task = dag.get_task(task_id) execution_date = request.args.get('execution_date') execution_date = pendulum.parse(execution_date) ignore_all_deps = request.args.get('ignore_all_deps') == "true" ignore_task_deps = request.args.get('ignore_task_deps') == "true" ignore_ti_state = request.args.get('ignore_ti_state') == "true" try: from airflow.executors import GetDefaultExecutor from airflow.executors.celery_executor import CeleryExecutor executor = GetDefaultExecutor() if not isinstance(executor, CeleryExecutor): flash("Only works with the CeleryExecutor, sorry", "error") return redirect(origin) except ImportError: # in case CeleryExecutor cannot be imported it is not active either flash("Only works with the CeleryExecutor, sorry", "error") return redirect(origin) ti = models.TaskInstance(task=task, execution_date=execution_date) ti.refresh_from_db() # Make sure the task instance can be queued dep_context = DepContext( deps=QUEUE_DEPS, ignore_all_deps=ignore_all_deps, ignore_task_deps=ignore_task_deps, ignore_ti_state=ignore_ti_state) failed_deps = list(ti.get_failed_dep_statuses(dep_context=dep_context)) if failed_deps: failed_deps_str = ", ".join( ["{}: {}".format(dep.dep_name, dep.reason) for dep in failed_deps]) flash("Could not queue task instance for execution, dependencies not met: " "{}".format(failed_deps_str), "error") return redirect(origin) executor.start() executor.queue_task_instance( ti, ignore_all_deps=ignore_all_deps, ignore_task_deps=ignore_task_deps, ignore_ti_state=ignore_ti_state) executor.heartbeat() flash( "Sent {} to the message queue, " "it should start any moment now.".format(ti)) return redirect(origin) @expose('/delete') @login_required @wwwutils.action_logging @wwwutils.notify_owner def delete(self): from airflow.api.common.experimental import delete_dag from airflow.exceptions import DagNotFound, DagFileExists dag_id = request.args.get('dag_id') origin = request.args.get('origin') or "/admin/" try: delete_dag.delete_dag(dag_id) except DagNotFound: flash("DAG with id {} not found. Cannot delete".format(dag_id)) return redirect(request.referrer) except DagFileExists: flash("Dag id {} is still in DagBag. " "Remove the DAG file first.".format(dag_id)) return redirect(request.referrer) flash("Deleting DAG with id {}. May take a couple minutes to fully" " disappear.".format(dag_id)) # Upon successful delete return to origin return redirect(origin) @expose('/trigger') @login_required @wwwutils.action_logging @wwwutils.notify_owner def trigger(self): dag_id = request.args.get('dag_id') origin = request.args.get('origin') or "/admin/" dag = dagbag.get_dag(dag_id) if not dag: flash("Cannot find dag {}".format(dag_id)) return redirect(origin) execution_date = timezone.utcnow() run_id = "manual__{0}".format(execution_date.isoformat()) dr = DagRun.find(dag_id=dag_id, run_id=run_id) if dr: flash("This run_id {} already exists".format(run_id)) return redirect(origin) run_conf = {} dag.create_dagrun( run_id=run_id, execution_date=execution_date, state=State.RUNNING, conf=run_conf, external_trigger=True ) flash( "Triggered {}, " "it should start any moment now.".format(dag_id)) return redirect(origin) def _clear_dag_tis(self, dag, start_date, end_date, origin, recursive=False, confirmed=False): if confirmed: count = dag.clear( start_date=start_date, end_date=end_date, include_subdags=recursive) flash("{0} task instances have been cleared".format(count)) return redirect(origin) tis = dag.clear( start_date=start_date, end_date=end_date, include_subdags=recursive, dry_run=True) if not tis: flash("No task instances to clear", 'error') response = redirect(origin) else: details = "\n".join([str(t) for t in tis]) response = self.render( 'airflow/confirm.html', message=("Here's the list of task instances you are about " "to clear:"), details=details) return response @expose('/clear') @login_required @wwwutils.action_logging @wwwutils.notify_owner def clear(self): dag_id = request.args.get('dag_id') task_id = request.args.get('task_id') origin = request.args.get('origin') dag = dagbag.get_dag(dag_id) execution_date = request.args.get('execution_date') execution_date = pendulum.parse(execution_date) confirmed = request.args.get('confirmed') == "true" upstream = request.args.get('upstream') == "true" downstream = request.args.get('downstream') == "true" future = request.args.get('future') == "true" past = request.args.get('past') == "true" recursive = request.args.get('recursive') == "true" dag = dag.sub_dag( task_regex=r"^{0}$".format(task_id), include_downstream=downstream, include_upstream=upstream) end_date = execution_date if not future else None start_date = execution_date if not past else None return self._clear_dag_tis(dag, start_date, end_date, origin, recursive=recursive, confirmed=confirmed) @expose('/dagrun_clear') @login_required @wwwutils.action_logging @wwwutils.notify_owner def dagrun_clear(self): dag_id = request.args.get('dag_id') task_id = request.args.get('task_id') origin = request.args.get('origin') execution_date = request.args.get('execution_date') confirmed = request.args.get('confirmed') == "true" dag = dagbag.get_dag(dag_id) execution_date = pendulum.parse(execution_date) start_date = execution_date end_date = execution_date return self._clear_dag_tis(dag, start_date, end_date, origin, recursive=True, confirmed=confirmed) @expose('/blocked') @login_required @provide_session def blocked(self, session=None): DR = models.DagRun dags = ( session.query(DR.dag_id, sqla.func.count(DR.id)) .filter(DR.state == State.RUNNING) .group_by(DR.dag_id) .all() ) payload = [] for dag_id, active_dag_runs in dags: max_active_runs = 0 if dag_id in dagbag.dags: max_active_runs = dagbag.dags[dag_id].max_active_runs payload.append({ 'dag_id': dag_id, 'active_dag_run': active_dag_runs, 'max_active_runs': max_active_runs, }) return wwwutils.json_response(payload) def _mark_dagrun_state_as_failed(self, dag_id, execution_date, confirmed, origin): if not execution_date: flash('Invalid execution date', 'error') return redirect(origin) execution_date = pendulum.parse(execution_date) dag = dagbag.get_dag(dag_id) if not dag: flash('Cannot find DAG: {}'.format(dag_id), 'error') return redirect(origin) new_dag_state = set_dag_run_state_to_failed(dag, execution_date, commit=confirmed) if confirmed: flash('Marked failed on {} task instances'.format(len(new_dag_state))) return redirect(origin) else: details = '\n'.join([str(t) for t in new_dag_state]) response = self.render('airflow/confirm.html', message=("Here's the list of task instances you are " "about to mark as failed"), details=details) return response def _mark_dagrun_state_as_success(self, dag_id, execution_date, confirmed, origin): if not execution_date: flash('Invalid execution date', 'error') return redirect(origin) execution_date = pendulum.parse(execution_date) dag = dagbag.get_dag(dag_id) if not dag: flash('Cannot find DAG: {}'.format(dag_id), 'error') return redirect(origin) new_dag_state = set_dag_run_state_to_success(dag, execution_date, commit=confirmed) if confirmed: flash('Marked success on {} task instances'.format(len(new_dag_state))) return redirect(origin) else: details = '\n'.join([str(t) for t in new_dag_state]) response = self.render('airflow/confirm.html', message=("Here's the list of task instances you are " "about to mark as success"), details=details) return response @expose('/dagrun_failed') @login_required @wwwutils.action_logging @wwwutils.notify_owner def dagrun_failed(self): dag_id = request.args.get('dag_id') execution_date = request.args.get('execution_date') confirmed = request.args.get('confirmed') == 'true' origin = request.args.get('origin') return self._mark_dagrun_state_as_failed(dag_id, execution_date, confirmed, origin) @expose('/dagrun_success') @login_required @wwwutils.action_logging @wwwutils.notify_owner def dagrun_success(self): dag_id = request.args.get('dag_id') execution_date = request.args.get('execution_date') confirmed = request.args.get('confirmed') == 'true' origin = request.args.get('origin') return self._mark_dagrun_state_as_success(dag_id, execution_date, confirmed, origin) def _mark_task_instance_state(self, dag_id, task_id, origin, execution_date, confirmed, upstream, downstream, future, past, state): dag = dagbag.get_dag(dag_id) task = dag.get_task(task_id) task.dag = dag execution_date = pendulum.parse(execution_date) if not dag: flash("Cannot find DAG: {}".format(dag_id)) return redirect(origin) if not task: flash("Cannot find task {} in DAG {}".format(task_id, dag.dag_id)) return redirect(origin) from airflow.api.common.experimental.mark_tasks import set_state if confirmed: altered = set_state(task=task, execution_date=execution_date, upstream=upstream, downstream=downstream, future=future, past=past, state=state, commit=True) flash("Marked {} on {} task instances".format(state, len(altered))) return redirect(origin) to_be_altered = set_state(task=task, execution_date=execution_date, upstream=upstream, downstream=downstream, future=future, past=past, state=state, commit=False) details = "\n".join([str(t) for t in to_be_altered]) response = self.render("airflow/confirm.html", message=("Here's the list of task instances you are " "about to mark as {}:".format(state)), details=details) return response @expose('/failed') @login_required @wwwutils.action_logging @wwwutils.notify_owner def failed(self): dag_id = request.args.get('dag_id') task_id = request.args.get('task_id') origin = request.args.get('origin') execution_date = request.args.get('execution_date') confirmed = request.args.get('confirmed') == "true" upstream = request.args.get('upstream') == "true" downstream = request.args.get('downstream') == "true" future = request.args.get('future') == "true" past = request.args.get('past') == "true" return self._mark_task_instance_state(dag_id, task_id, origin, execution_date, confirmed, upstream, downstream, future, past, State.FAILED) @expose('/success') @login_required @wwwutils.action_logging @wwwutils.notify_owner def success(self): dag_id = request.args.get('dag_id') task_id = request.args.get('task_id') origin = request.args.get('origin') execution_date = request.args.get('execution_date') confirmed = request.args.get('confirmed') == "true" upstream = request.args.get('upstream') == "true" downstream = request.args.get('downstream') == "true" future = request.args.get('future') == "true" past = request.args.get('past') == "true" return self._mark_task_instance_state(dag_id, task_id, origin, execution_date, confirmed, upstream, downstream, future, past, State.SUCCESS) @expose('/tree') @login_required @wwwutils.gzipped @wwwutils.action_logging @provide_session def tree(self, session=None): default_dag_run = conf.getint('webserver', 'default_dag_run_display_number') dag_id = request.args.get('dag_id') blur = conf.getboolean('webserver', 'demo_mode') dag = dagbag.get_dag(dag_id) if dag_id not in dagbag.dags: flash('DAG "{0}" seems to be missing.'.format(dag_id), "error") return redirect('/admin/') root = request.args.get('root') if root: dag = dag.sub_dag( task_regex=root, include_downstream=False, include_upstream=True) base_date = request.args.get('base_date') num_runs = request.args.get('num_runs') num_runs = int(num_runs) if num_runs else default_dag_run if base_date: base_date = timezone.parse(base_date) else: base_date = dag.latest_execution_date or timezone.utcnow() DR = models.DagRun dag_runs = ( session.query(DR) .filter( DR.dag_id == dag.dag_id, DR.execution_date <= base_date) .order_by(DR.execution_date.desc()) .limit(num_runs) .all() ) dag_runs = { dr.execution_date: alchemy_to_dict(dr) for dr in dag_runs} dates = sorted(list(dag_runs.keys())) max_date = max(dates) if dates else None min_date = min(dates) if dates else None tis = dag.get_task_instances( session, start_date=min_date, end_date=base_date) task_instances = {} for ti in tis: tid = alchemy_to_dict(ti) dr = dag_runs.get(ti.execution_date) tid['external_trigger'] = dr['external_trigger'] if dr else False task_instances[(ti.task_id, ti.execution_date)] = tid expanded = [] # The default recursion traces every path so that tree view has full # expand/collapse functionality. After 5,000 nodes we stop and fall # back on a quick DFS search for performance. See PR #320. node_count = [0] node_limit = 5000 / max(1, len(dag.roots)) def recurse_nodes(task, visited): visited.add(task) node_count[0] += 1 children = [ recurse_nodes(t, visited) for t in task.upstream_list if node_count[0] < node_limit or t not in visited] # D3 tree uses children vs _children to define what is # expanded or not. The following block makes it such that # repeated nodes are collapsed by default. children_key = 'children' if task.task_id not in expanded: expanded.append(task.task_id) elif children: children_key = "_children" def set_duration(tid): if (isinstance(tid, dict) and tid.get("state") == State.RUNNING and tid["start_date"] is not None): d = timezone.utcnow() - pendulum.parse(tid["start_date"]) tid["duration"] = d.total_seconds() return tid return { 'name': task.task_id, 'instances': [ set_duration(task_instances.get((task.task_id, d))) or { 'execution_date': d.isoformat(), 'task_id': task.task_id } for d in dates], children_key: children, 'num_dep': len(task.upstream_list), 'operator': task.task_type, 'retries': task.retries, 'owner': task.owner, 'start_date': task.start_date, 'end_date': task.end_date, 'depends_on_past': task.depends_on_past, 'ui_color': task.ui_color, } data = { 'name': '[DAG]', 'children': [recurse_nodes(t, set()) for t in dag.roots], 'instances': [ dag_runs.get(d) or {'execution_date': d.isoformat()} for d in dates], } # minimize whitespace as this can be huge for bigger dags data = json.dumps(data, default=json_ser, separators=(',', ':')) session.commit() form = DateTimeWithNumRunsForm(data={'base_date': max_date, 'num_runs': num_runs}) return self.render( 'airflow/tree.html', operators=sorted( list(set([op.__class__ for op in dag.tasks])), key=lambda x: x.__name__ ), root=root, form=form, dag=dag, data=data, blur=blur, num_runs=num_runs) @expose('/graph') @login_required @wwwutils.gzipped @wwwutils.action_logging @provide_session def graph(self, session=None): dag_id = request.args.get('dag_id') blur = conf.getboolean('webserver', 'demo_mode') dag = dagbag.get_dag(dag_id) if dag_id not in dagbag.dags: flash('DAG "{0}" seems to be missing.'.format(dag_id), "error") return redirect('/admin/') root = request.args.get('root') if root: dag = dag.sub_dag( task_regex=root, include_upstream=True, include_downstream=False) arrange = request.args.get('arrange', dag.orientation) nodes = [] edges = [] for task in dag.tasks: nodes.append({ 'id': task.task_id, 'value': { 'label': task.task_id, 'labelStyle': "fill:{0};".format(task.ui_fgcolor), 'style': "fill:{0};".format(task.ui_color), } }) def get_upstream(task): for t in task.upstream_list: edge = { 'u': t.task_id, 'v': task.task_id, } if edge not in edges: edges.append(edge) get_upstream(t) for t in dag.roots: get_upstream(t) dt_nr_dr_data = get_date_time_num_runs_dag_runs_form_data(request, session, dag) dt_nr_dr_data['arrange'] = arrange dttm = dt_nr_dr_data['dttm'] class GraphForm(DateTimeWithNumRunsWithDagRunsForm): arrange = SelectField("Layout", choices=( ('LR', "Left->Right"), ('RL', "Right->Left"), ('TB', "Top->Bottom"), ('BT', "Bottom->Top"), )) form = GraphForm(data=dt_nr_dr_data) form.execution_date.choices = dt_nr_dr_data['dr_choices'] task_instances = { ti.task_id: alchemy_to_dict(ti) for ti in dag.get_task_instances(session, dttm, dttm)} tasks = { t.task_id: { 'dag_id': t.dag_id, 'task_type': t.task_type, } for t in dag.tasks} if not tasks: flash("No tasks found", "error") session.commit() doc_md = markdown.markdown(dag.doc_md) if hasattr(dag, 'doc_md') and dag.doc_md else '' return self.render( 'airflow/graph.html', dag=dag, form=form, width=request.args.get('width', "100%"), height=request.args.get('height', "800"), execution_date=dttm.isoformat(), state_token=state_token(dt_nr_dr_data['dr_state']), doc_md=doc_md, arrange=arrange, operators=sorted( list(set([op.__class__ for op in dag.tasks])), key=lambda x: x.__name__ ), blur=blur, root=root or '', task_instances=json.dumps(task_instances, indent=2), tasks=json.dumps(tasks, indent=2), nodes=json.dumps(nodes, indent=2), edges=json.dumps(edges, indent=2), ) @expose('/duration') @login_required @wwwutils.action_logging @provide_session def duration(self, session=None): default_dag_run = conf.getint('webserver', 'default_dag_run_display_number') dag_id = request.args.get('dag_id') dag = dagbag.get_dag(dag_id) base_date = request.args.get('base_date') num_runs = request.args.get('num_runs') num_runs = int(num_runs) if num_runs else default_dag_run if base_date: base_date = pendulum.parse(base_date) else: base_date = dag.latest_execution_date or timezone.utcnow() dates = dag.date_range(base_date, num=-abs(num_runs)) min_date = dates[0] if dates else datetime(2000, 1, 1) root = request.args.get('root') if root: dag = dag.sub_dag( task_regex=root, include_upstream=True, include_downstream=False) chart_height = get_chart_height(dag) chart = nvd3.lineChart( name="lineChart", x_is_date=True, height=chart_height, width="1200") cum_chart = nvd3.lineChart( name="cumLineChart", x_is_date=True, height=chart_height, width="1200") y = defaultdict(list) x = defaultdict(list) cum_y = defaultdict(list) tis = dag.get_task_instances( session, start_date=min_date, end_date=base_date) TF = models.TaskFail ti_fails = ( session .query(TF) .filter( TF.dag_id == dag.dag_id, TF.execution_date >= min_date, TF.execution_date <= base_date, TF.task_id.in_([t.task_id for t in dag.tasks])) .all() ) fails_totals = defaultdict(int) for tf in ti_fails: dict_key = (tf.dag_id, tf.task_id, tf.execution_date) fails_totals[dict_key] += tf.duration for ti in tis: if ti.duration: dttm = wwwutils.epoch(ti.execution_date) x[ti.task_id].append(dttm) y[ti.task_id].append(float(ti.duration)) fails_dict_key = (ti.dag_id, ti.task_id, ti.execution_date) fails_total = fails_totals[fails_dict_key] cum_y[ti.task_id].append(float(ti.duration + fails_total)) # determine the most relevant time unit for the set of task instance # durations for the DAG y_unit = infer_time_unit([d for t in y.values() for d in t]) cum_y_unit = infer_time_unit([d for t in cum_y.values() for d in t]) # update the y Axis on both charts to have the correct time units chart.create_y_axis('yAxis', format='.02f', custom_format=False, label='Duration ({})'.format(y_unit)) chart.axislist['yAxis']['axisLabelDistance'] = '40' cum_chart.create_y_axis('yAxis', format='.02f', custom_format=False, label='Duration ({})'.format(cum_y_unit)) cum_chart.axislist['yAxis']['axisLabelDistance'] = '40' for task in dag.tasks: if x[task.task_id]: chart.add_serie(name=task.task_id, x=x[task.task_id], y=scale_time_units(y[task.task_id], y_unit)) cum_chart.add_serie(name=task.task_id, x=x[task.task_id], y=scale_time_units(cum_y[task.task_id], cum_y_unit)) dates = sorted(list({ti.execution_date for ti in tis})) max_date = max([ti.execution_date for ti in tis]) if dates else None session.commit() form = DateTimeWithNumRunsForm(data={'base_date': max_date, 'num_runs': num_runs}) chart.buildcontent() cum_chart.buildcontent() s_index = cum_chart.htmlcontent.rfind('});') cum_chart.htmlcontent = (cum_chart.htmlcontent[:s_index] + "$(function() {$( document ).trigger('chartload') })" + cum_chart.htmlcontent[s_index:]) return self.render( 'airflow/duration_chart.html', dag=dag, demo_mode=conf.getboolean('webserver', 'demo_mode'), root=root, form=form, chart=chart.htmlcontent, cum_chart=cum_chart.htmlcontent ) @expose('/tries') @login_required @wwwutils.action_logging @provide_session def tries(self, session=None): default_dag_run = conf.getint('webserver', 'default_dag_run_display_number') dag_id = request.args.get('dag_id') dag = dagbag.get_dag(dag_id) base_date = request.args.get('base_date') num_runs = request.args.get('num_runs') num_runs = int(num_runs) if num_runs else default_dag_run if base_date: base_date = pendulum.parse(base_date) else: base_date = dag.latest_execution_date or timezone.utcnow() dates = dag.date_range(base_date, num=-abs(num_runs)) min_date = dates[0] if dates else datetime(2000, 1, 1) root = request.args.get('root') if root: dag = dag.sub_dag( task_regex=root, include_upstream=True, include_downstream=False) chart_height = get_chart_height(dag) chart = nvd3.lineChart( name="lineChart", x_is_date=True, y_axis_format='d', height=chart_height, width="1200") for task in dag.tasks: y = [] x = [] for ti in task.get_task_instances(session, start_date=min_date, end_date=base_date): dttm = wwwutils.epoch(ti.execution_date) x.append(dttm) y.append(ti.try_number) if x: chart.add_serie(name=task.task_id, x=x, y=y) tis = dag.get_task_instances( session, start_date=min_date, end_date=base_date) tries = sorted(list({ti.try_number for ti in tis})) max_date = max([ti.execution_date for ti in tis]) if tries else None session.commit() form = DateTimeWithNumRunsForm(data={'base_date': max_date, 'num_runs': num_runs}) chart.buildcontent() return self.render( 'airflow/chart.html', dag=dag, demo_mode=conf.getboolean('webserver', 'demo_mode'), root=root, form=form, chart=chart.htmlcontent ) @expose('/landing_times') @login_required @wwwutils.action_logging @provide_session def landing_times(self, session=None): default_dag_run = conf.getint('webserver', 'default_dag_run_display_number') dag_id = request.args.get('dag_id') dag = dagbag.get_dag(dag_id) base_date = request.args.get('base_date') num_runs = request.args.get('num_runs') num_runs = int(num_runs) if num_runs else default_dag_run if base_date: base_date = pendulum.parse(base_date) else: base_date = dag.latest_execution_date or timezone.utcnow() dates = dag.date_range(base_date, num=-abs(num_runs)) min_date = dates[0] if dates else datetime(2000, 1, 1) root = request.args.get('root') if root: dag = dag.sub_dag( task_regex=root, include_upstream=True, include_downstream=False) chart_height = get_chart_height(dag) chart = nvd3.lineChart( name="lineChart", x_is_date=True, height=chart_height, width="1200") y = {} x = {} for task in dag.tasks: y[task.task_id] = [] x[task.task_id] = [] for ti in task.get_task_instances(session, start_date=min_date, end_date=base_date): if ti.end_date: ts = ti.execution_date following_schedule = dag.following_schedule(ts) if dag.schedule_interval and following_schedule: ts = following_schedule dttm = wwwutils.epoch(ti.execution_date) secs = (ti.end_date - ts).total_seconds() x[ti.task_id].append(dttm) y[ti.task_id].append(secs) # determine the most relevant time unit for the set of landing times # for the DAG y_unit = infer_time_unit([d for t in y.values() for d in t]) # update the y Axis to have the correct time units chart.create_y_axis('yAxis', format='.02f', custom_format=False, label='Landing Time ({})'.format(y_unit)) chart.axislist['yAxis']['axisLabelDistance'] = '40' for task in dag.tasks: if x[task.task_id]: chart.add_serie(name=task.task_id, x=x[task.task_id], y=scale_time_units(y[task.task_id], y_unit)) tis = dag.get_task_instances( session, start_date=min_date, end_date=base_date) dates = sorted(list({ti.execution_date for ti in tis})) max_date = max([ti.execution_date for ti in tis]) if dates else None form = DateTimeWithNumRunsForm(data={'base_date': max_date, 'num_runs': num_runs}) chart.buildcontent() return self.render( 'airflow/chart.html', dag=dag, chart=chart.htmlcontent, height=str(chart_height + 100) + "px", demo_mode=conf.getboolean('webserver', 'demo_mode'), root=root, form=form, ) @expose('/paused', methods=['POST']) @login_required @wwwutils.action_logging @provide_session def paused(self, session=None): DagModel = models.DagModel dag_id = request.args.get('dag_id') orm_dag = session.query( DagModel).filter(DagModel.dag_id == dag_id).first() if request.args.get('is_paused') == 'false': orm_dag.is_paused = True else: orm_dag.is_paused = False session.merge(orm_dag) session.commit() dagbag.get_dag(dag_id) return "OK" @expose('/refresh') @login_required @wwwutils.action_logging @provide_session def refresh(self, session=None): DagModel = models.DagModel dag_id = request.args.get('dag_id') orm_dag = session.query( DagModel).filter(DagModel.dag_id == dag_id).first() if orm_dag: orm_dag.last_expired = timezone.utcnow() session.merge(orm_dag) session.commit() dagbag.get_dag(dag_id) flash("DAG [{}] is now fresh as a daisy".format(dag_id)) return redirect(request.referrer) @expose('/refresh_all') @login_required @wwwutils.action_logging def refresh_all(self): dagbag.collect_dags(only_if_updated=False) flash("All DAGs are now up to date") return redirect('/') @expose('/gantt') @login_required @wwwutils.action_logging @provide_session def gantt(self, session=None): dag_id = request.args.get('dag_id') dag = dagbag.get_dag(dag_id) demo_mode = conf.getboolean('webserver', 'demo_mode') root = request.args.get('root') if root: dag = dag.sub_dag( task_regex=root, include_upstream=True, include_downstream=False) dt_nr_dr_data = get_date_time_num_runs_dag_runs_form_data(request, session, dag) dttm = dt_nr_dr_data['dttm'] form = DateTimeWithNumRunsWithDagRunsForm(data=dt_nr_dr_data) form.execution_date.choices = dt_nr_dr_data['dr_choices'] tis = [ ti for ti in dag.get_task_instances(session, dttm, dttm) if ti.start_date] tis = sorted(tis, key=lambda ti: ti.start_date) TF = models.TaskFail ti_fails = list(itertools.chain(*[( session .query(TF) .filter(TF.dag_id == ti.dag_id, TF.task_id == ti.task_id, TF.execution_date == ti.execution_date) .all() ) for ti in tis])) tis_with_fails = sorted(tis + ti_fails, key=lambda ti: ti.start_date) tasks = [] for ti in tis_with_fails: end_date = ti.end_date if ti.end_date else timezone.utcnow() state = ti.state if type(ti) == models.TaskInstance else State.FAILED tasks.append({ 'startDate': wwwutils.epoch(ti.start_date), 'endDate': wwwutils.epoch(end_date), 'isoStart': ti.start_date.isoformat()[:-4], 'isoEnd': end_date.isoformat()[:-4], 'taskName': ti.task_id, 'duration': "{}".format(end_date - ti.start_date)[:-4], 'status': state, 'executionDate': ti.execution_date.isoformat(), }) states = {task['status']: task['status'] for task in tasks} data = { 'taskNames': [ti.task_id for ti in tis], 'tasks': tasks, 'taskStatus': states, 'height': len(tis) * 25 + 25, } session.commit() return self.render( 'airflow/gantt.html', dag=dag, execution_date=dttm.isoformat(), form=form, data=json.dumps(data, indent=2), base_date='', demo_mode=demo_mode, root=root, ) @expose('/object/task_instances') @login_required @wwwutils.action_logging @provide_session def task_instances(self, session=None): dag_id = request.args.get('dag_id') dag = dagbag.get_dag(dag_id) dttm = request.args.get('execution_date') if dttm: dttm = pendulum.parse(dttm) else: return ("Error: Invalid execution_date") task_instances = { ti.task_id: alchemy_to_dict(ti) for ti in dag.get_task_instances(session, dttm, dttm)} return json.dumps(task_instances) @expose('/variables/<form>', methods=["GET", "POST"]) @login_required @wwwutils.action_logging def variables(self, form): try: if request.method == 'POST': data = request.json if data: with create_session() as session: var = models.Variable(key=form, val=json.dumps(data)) session.add(var) session.commit() return "" else: return self.render( 'airflow/variables/{}.html'.format(form) ) except Exception: # prevent XSS form = escape(form) return ("Error: form airflow/variables/{}.html " "not found.").format(form), 404 @expose('/varimport', methods=["GET", "POST"]) @login_required @wwwutils.action_logging def varimport(self): try: d = json.load(UTF8_READER(request.files['file'])) except Exception as e: flash("Missing file or syntax error: {}.".format(e)) else: for k, v in d.items(): models.Variable.set(k, v, serialize_json=isinstance(v, dict)) flash("{} variable(s) successfully updated.".format(len(d))) return redirect('/admin/variable') class HomeView(AdminIndexView): @expose("/") @login_required @provide_session def index(self, session=None): DM = models.DagModel # restrict the dags shown if filter_by_owner and current user is not superuser do_filter = FILTER_BY_OWNER and (not current_user.is_superuser()) owner_mode = conf.get('webserver', 'OWNER_MODE').strip().lower() hide_paused_dags_by_default = conf.getboolean('webserver', 'hide_paused_dags_by_default') show_paused_arg = request.args.get('showPaused', 'None') def get_int_arg(value, default=0): try: return int(value) except ValueError: return default arg_current_page = request.args.get('page', '0') arg_search_query = request.args.get('search', None) dags_per_page = PAGE_SIZE current_page = get_int_arg(arg_current_page, default=0) if show_paused_arg.strip().lower() == 'false': hide_paused = True elif show_paused_arg.strip().lower() == 'true': hide_paused = False else: hide_paused = hide_paused_dags_by_default # read orm_dags from the db sql_query = session.query(DM) if do_filter and owner_mode == 'ldapgroup': sql_query = sql_query.filter( ~DM.is_subdag, DM.is_active, DM.owners.in_(current_user.ldap_groups) ) elif do_filter and owner_mode == 'user': sql_query = sql_query.filter( ~DM.is_subdag, DM.is_active, DM.owners == current_user.user.username ) else: sql_query = sql_query.filter( ~DM.is_subdag, DM.is_active ) # optionally filter out "paused" dags if hide_paused: sql_query = sql_query.filter(~DM.is_paused) orm_dags = {dag.dag_id: dag for dag in sql_query .all()} import_errors = session.query(models.ImportError).all() for ie in import_errors: flash( "Broken DAG: [{ie.filename}] {ie.stacktrace}".format(ie=ie), "error") # get a list of all non-subdag dags visible to everyone # optionally filter out "paused" dags if hide_paused: unfiltered_webserver_dags = [dag for dag in dagbag.dags.values() if not dag.parent_dag and not dag.is_paused] else: unfiltered_webserver_dags = [dag for dag in dagbag.dags.values() if not dag.parent_dag] # optionally filter to get only dags that the user should see if do_filter and owner_mode == 'ldapgroup': # only show dags owned by someone in @current_user.ldap_groups webserver_dags = { dag.dag_id: dag for dag in unfiltered_webserver_dags if dag.owner in current_user.ldap_groups } elif do_filter and owner_mode == 'user': # only show dags owned by @current_user.user.username webserver_dags = { dag.dag_id: dag for dag in unfiltered_webserver_dags if dag.owner == current_user.user.username } else: webserver_dags = { dag.dag_id: dag for dag in unfiltered_webserver_dags } if arg_search_query: lower_search_query = arg_search_query.lower() # filter by dag_id webserver_dags_filtered = { dag_id: dag for dag_id, dag in webserver_dags.items() if (lower_search_query in dag_id.lower() or lower_search_query in dag.owner.lower()) } all_dag_ids = (set([dag.dag_id for dag in orm_dags.values() if lower_search_query in dag.dag_id.lower() or lower_search_query in dag.owners.lower()]) | set(webserver_dags_filtered.keys())) sorted_dag_ids = sorted(all_dag_ids) else: webserver_dags_filtered = webserver_dags sorted_dag_ids = sorted(set(orm_dags.keys()) | set(webserver_dags.keys())) start = current_page * dags_per_page end = start + dags_per_page num_of_all_dags = len(sorted_dag_ids) page_dag_ids = sorted_dag_ids[start:end] num_of_pages = int(math.ceil(num_of_all_dags / float(dags_per_page))) auto_complete_data = set() for dag in webserver_dags_filtered.values(): auto_complete_data.add(dag.dag_id) auto_complete_data.add(dag.owner) for dag in orm_dags.values(): auto_complete_data.add(dag.dag_id) auto_complete_data.add(dag.owners) return self.render( 'airflow/dags.html', webserver_dags=webserver_dags_filtered, orm_dags=orm_dags, hide_paused=hide_paused, current_page=current_page, search_query=arg_search_query if arg_search_query else '', page_size=dags_per_page, num_of_pages=num_of_pages, num_dag_from=start + 1, num_dag_to=min(end, num_of_all_dags), num_of_all_dags=num_of_all_dags, paging=wwwutils.generate_pages(current_page, num_of_pages, search=arg_search_query, showPaused=not hide_paused), dag_ids_in_page=page_dag_ids, auto_complete_data=auto_complete_data) class QueryView(wwwutils.DataProfilingMixin, BaseView): @expose('/', methods=['POST', 'GET']) @wwwutils.gzipped @provide_session def query(self, session=None): dbs = session.query(models.Connection).order_by( models.Connection.conn_id).all() session.expunge_all() db_choices = list( ((db.conn_id, db.conn_id) for db in dbs if db.get_hook())) conn_id_str = request.form.get('conn_id') csv = request.form.get('csv') == "true" sql = request.form.get('sql') class QueryForm(Form): conn_id = SelectField("Layout", choices=db_choices) sql = TextAreaField("SQL", widget=wwwutils.AceEditorWidget()) data = { 'conn_id': conn_id_str, 'sql': sql, } results = None has_data = False error = False if conn_id_str: db = [db for db in dbs if db.conn_id == conn_id_str][0] hook = db.get_hook() try: df = hook.get_pandas_df(wwwutils.limit_sql(sql, QUERY_LIMIT, conn_type=db.conn_type)) # df = hook.get_pandas_df(sql) has_data = len(df) > 0 df = df.fillna('') results = df.to_html( classes=[ 'table', 'table-bordered', 'table-striped', 'no-wrap'], index=False, na_rep='', ) if has_data else '' except Exception as e: flash(str(e), 'error') error = True if has_data and len(df) == QUERY_LIMIT: flash( "Query output truncated at " + str(QUERY_LIMIT) + " rows", 'info') if not has_data and error: flash('No data', 'error') if csv: return Response( response=df.to_csv(index=False), status=200, mimetype="application/text") form = QueryForm(request.form, data=data) session.commit() return self.render( 'airflow/query.html', form=form, title="Ad Hoc Query", results=results or '', has_data=has_data) class AirflowModelView(ModelView): list_template = 'airflow/model_list.html' edit_template = 'airflow/model_edit.html' create_template = 'airflow/model_create.html' column_display_actions = True page_size = PAGE_SIZE class ModelViewOnly(wwwutils.LoginMixin, AirflowModelView): """ Modifying the base ModelView class for non edit, browse only operations """ named_filter_urls = True can_create = False can_edit = False can_delete = False column_display_pk = True class PoolModelView(wwwutils.SuperUserMixin, AirflowModelView): column_list = ('pool', 'slots', 'used_slots', 'queued_slots') column_formatters = dict( pool=pool_link, used_slots=fused_slots, queued_slots=fqueued_slots) named_filter_urls = True form_args = { 'pool': { 'validators': [ validators.DataRequired(), ] } } class SlaMissModelView(wwwutils.SuperUserMixin, ModelViewOnly): verbose_name_plural = "SLA misses" verbose_name = "SLA miss" column_list = ( 'dag_id', 'task_id', 'execution_date', 'email_sent', 'timestamp') column_formatters = dict( task_id=task_instance_link, execution_date=datetime_f, timestamp=datetime_f, dag_id=dag_link) named_filter_urls = True column_searchable_list = ('dag_id', 'task_id',) column_filters = ( 'dag_id', 'task_id', 'email_sent', 'timestamp', 'execution_date') filter_converter = wwwutils.UtcFilterConverter() form_widget_args = { 'email_sent': {'disabled': True}, 'timestamp': {'disabled': True}, } @provide_session def _connection_ids(session=None): return [ (c.conn_id, c.conn_id) for c in ( session.query(models.Connection.conn_id) .group_by(models.Connection.conn_id) ) ] class ChartModelView(wwwutils.DataProfilingMixin, AirflowModelView): verbose_name = "chart" verbose_name_plural = "charts" form_columns = ( 'label', 'owner', 'conn_id', 'chart_type', 'show_datatable', 'x_is_date', 'y_log_scale', 'show_sql', 'height', 'sql_layout', 'sql', 'default_params', ) column_list = ( 'label', 'conn_id', 'chart_type', 'owner', 'last_modified', ) column_sortable_list = ( 'label', 'conn_id', 'chart_type', ('owner', 'owner.username'), 'last_modified', ) column_formatters = dict(label=label_link, last_modified=datetime_f) column_default_sort = ('last_modified', True) create_template = 'airflow/chart/create.html' edit_template = 'airflow/chart/edit.html' column_filters = ('label', 'owner.username', 'conn_id') column_searchable_list = ('owner.username', 'label', 'sql') column_descriptions = { 'label': "Can include {{ templated_fields }} and {{ macros }}", 'chart_type': "The type of chart to be displayed", 'sql': "Can include {{ templated_fields }} and {{ macros }}.", 'height': "Height of the chart, in pixels.", 'conn_id': "Source database to run the query against", 'x_is_date': ( "Whether the X axis should be casted as a date field. Expect most " "intelligible date formats to get casted properly." ), 'owner': ( "The chart's owner, mostly used for reference and filtering in " "the list view." ), 'show_datatable': "Whether to display an interactive data table under the chart.", 'default_params': ( 'A dictionary of {"key": "values",} that define what the ' 'templated fields (parameters) values should be by default. ' 'To be valid, it needs to "eval" as a Python dict. ' 'The key values will show up in the url\'s querystring ' 'and can be altered there.' ), 'show_sql': "Whether to display the SQL statement as a collapsible " "section in the chart page.", 'y_log_scale': "Whether to use a log scale for the Y axis.", 'sql_layout': ( "Defines the layout of the SQL that the application should " "expect. Depending on the tables you are sourcing from, it may " "make more sense to pivot / unpivot the metrics." ), } column_labels = { 'sql': "SQL", 'height': "Chart Height", 'sql_layout': "SQL Layout", 'show_sql': "Display the SQL Statement", 'default_params': "Default Parameters", } form_choices = { 'chart_type': [ ('line', 'Line Chart'), ('spline', 'Spline Chart'), ('bar', 'Bar Chart'), ('column', 'Column Chart'), ('area', 'Overlapping Area Chart'), ('stacked_area', 'Stacked Area Chart'), ('percent_area', 'Percent Area Chart'), ('datatable', 'No chart, data table only'), ], 'sql_layout': [ ('series', 'SELECT series, x, y FROM ...'), ('columns', 'SELECT x, y (series 1), y (series 2), ... FROM ...'), ], 'conn_id': _connection_ids() } def on_model_change(self, form, model, is_created=True): if model.iteration_no is None: model.iteration_no = 0 else: model.iteration_no += 1 if not model.user_id and current_user and hasattr(current_user, 'id'): model.user_id = current_user.id model.last_modified = timezone.utcnow() chart_mapping = ( ('line', 'lineChart'), ('spline', 'lineChart'), ('bar', 'multiBarChart'), ('column', 'multiBarChart'), ('area', 'stackedAreaChart'), ('stacked_area', 'stackedAreaChart'), ('percent_area', 'stackedAreaChart'), ('datatable', 'datatable'), ) chart_mapping = dict(chart_mapping) class KnownEventView(wwwutils.DataProfilingMixin, AirflowModelView): verbose_name = "known event" verbose_name_plural = "known events" form_columns = ( 'label', 'event_type', 'start_date', 'end_date', 'reported_by', 'description', ) form_args = { 'label': { 'validators': [ validators.DataRequired(), ], }, 'event_type': { 'validators': [ validators.DataRequired(), ], }, 'start_date': { 'validators': [ validators.DataRequired(), ], 'filters': [ parse_datetime_f, ], }, 'end_date': { 'validators': [ validators.DataRequired(), GreaterEqualThan(fieldname='start_date'), ], 'filters': [ parse_datetime_f, ] }, 'reported_by': { 'validators': [ validators.DataRequired(), ], } } column_list = ( 'label', 'event_type', 'start_date', 'end_date', 'reported_by', ) column_default_sort = ("start_date", True) column_sortable_list = ( 'label', # todo: yes this has a spelling error ('event_type', 'event_type.know_event_type'), 'start_date', 'end_date', ('reported_by', 'reported_by.username'), ) filter_converter = wwwutils.UtcFilterConverter() form_overrides = dict(start_date=DateTimeField, end_date=DateTimeField) class KnownEventTypeView(wwwutils.DataProfilingMixin, AirflowModelView): pass # NOTE: For debugging / troubleshooting # mv = KnowEventTypeView( # models.KnownEventType, # Session, name="Known Event Types", category="Manage") # admin.add_view(mv) # class DagPickleView(SuperUserMixin, ModelView): # pass # mv = DagPickleView( # models.DagPickle, # Session, name="Pickles", category="Manage") # admin.add_view(mv) class VariableView(wwwutils.DataProfilingMixin, AirflowModelView): verbose_name = "Variable" verbose_name_plural = "Variables" list_template = 'airflow/variable_list.html' def hidden_field_formatter(view, context, model, name): if wwwutils.should_hide_value_for_key(model.key): return Markup('*' * 8) val = getattr(model, name) if val: return val else: return Markup('<span class="label label-danger">Invalid</span>') form_columns = ( 'key', 'val', ) column_list = ('key', 'val', 'is_encrypted',) column_filters = ('key', 'val') column_searchable_list = ('key', 'val', 'is_encrypted',) column_default_sort = ('key', False) form_widget_args = { 'is_encrypted': {'disabled': True}, 'val': { 'rows': 20, } } form_args = { 'key': { 'validators': { validators.DataRequired(), }, }, } column_sortable_list = ( 'key', 'val', 'is_encrypted', ) column_formatters = { 'val': hidden_field_formatter, } # Default flask-admin export functionality doesn't handle serialized json @action('varexport', 'Export', None) @provide_session def action_varexport(self, ids, session=None): V = models.Variable qry = session.query(V).filter(V.id.in_(ids)).all() var_dict = {} d = json.JSONDecoder() for var in qry: val = None try: val = d.decode(var.val) except Exception: val = var.val var_dict[var.key] = val response = make_response(json.dumps(var_dict, sort_keys=True, indent=4)) response.headers["Content-Disposition"] = "attachment; filename=variables.json" return response def on_form_prefill(self, form, id): if wwwutils.should_hide_value_for_key(form.key.data): form.val.data = '*' * 8 class XComView(wwwutils.SuperUserMixin, AirflowModelView): verbose_name = "XCom" verbose_name_plural = "XComs" form_columns = ( 'key', 'value', 'execution_date', 'task_id', 'dag_id', ) form_extra_fields = { 'value': StringField('Value'), } form_args = { 'execution_date': { 'filters': [ parse_datetime_f, ] } } column_filters = ('key', 'timestamp', 'execution_date', 'task_id', 'dag_id') column_searchable_list = ('key', 'timestamp', 'execution_date', 'task_id', 'dag_id') filter_converter = wwwutils.UtcFilterConverter() form_overrides = dict(execution_date=DateTimeField) class JobModelView(ModelViewOnly): verbose_name_plural = "jobs" verbose_name = "job" column_display_actions = False column_default_sort = ('start_date', True) column_filters = ( 'job_type', 'dag_id', 'state', 'unixname', 'hostname', 'start_date', 'end_date', 'latest_heartbeat') column_formatters = dict( start_date=datetime_f, end_date=datetime_f, hostname=nobr_f, state=state_f, latest_heartbeat=datetime_f) filter_converter = wwwutils.UtcFilterConverter() class DagRunModelView(ModelViewOnly): verbose_name_plural = "DAG Runs" can_edit = True can_create = True column_editable_list = ('state',) verbose_name = "dag run" column_default_sort = ('execution_date', True) form_choices = { 'state': [ ('success', 'success'), ('running', 'running'), ('failed', 'failed'), ], } form_args = dict( dag_id=dict(validators=[validators.DataRequired()]) ) column_list = ( 'state', 'dag_id', 'execution_date', 'run_id', 'external_trigger') column_filters = column_list filter_converter = wwwutils.UtcFilterConverter() column_searchable_list = ('dag_id', 'state', 'run_id') column_formatters = dict( execution_date=datetime_f, state=state_f, start_date=datetime_f, dag_id=dag_link, run_id=dag_run_link ) @action('new_delete', "Delete", "Are you sure you want to delete selected records?") @provide_session def action_new_delete(self, ids, session=None): deleted = set(session.query(models.DagRun) .filter(models.DagRun.id.in_(ids)) .all()) session.query(models.DagRun) \ .filter(models.DagRun.id.in_(ids)) \ .delete(synchronize_session='fetch') session.commit() dirty_ids = [] for row in deleted: dirty_ids.append(row.dag_id) models.DagStat.update(dirty_ids, dirty_only=False, session=session) @action('set_running', "Set state to 'running'", None) @provide_session def action_set_running(self, ids, session=None): try: DR = models.DagRun count = 0 dirty_ids = [] for dr in session.query(DR).filter(DR.id.in_(ids)).all(): dirty_ids.append(dr.dag_id) count += 1 dr.state = State.RUNNING dr.start_date = timezone.utcnow() models.DagStat.update(dirty_ids, session=session) flash( "{count} dag runs were set to running".format(**locals())) except Exception as ex: if not self.handle_view_exception(ex): raise Exception("Ooops") flash('Failed to set state', 'error') @action('set_failed', "Set state to 'failed'", "All running task instances would also be marked as failed, are you sure?") @provide_session def action_set_failed(self, ids, session=None): try: DR = models.DagRun count = 0 dirty_ids = [] altered_tis = [] for dr in session.query(DR).filter(DR.id.in_(ids)).all(): dirty_ids.append(dr.dag_id) count += 1 altered_tis += \ set_dag_run_state_to_failed(dagbag.get_dag(dr.dag_id), dr.execution_date, commit=True, session=session) models.DagStat.update(dirty_ids, session=session) altered_ti_count = len(altered_tis) flash( "{count} dag runs and {altered_ti_count} task instances " "were set to failed".format(**locals())) except Exception as ex: if not self.handle_view_exception(ex): raise Exception("Ooops") flash('Failed to set state', 'error') @action('set_success', "Set state to 'success'", "All task instances would also be marked as success, are you sure?") @provide_session def action_set_success(self, ids, session=None): try: DR = models.DagRun count = 0 dirty_ids = [] altered_tis = [] for dr in session.query(DR).filter(DR.id.in_(ids)).all(): dirty_ids.append(dr.dag_id) count += 1 altered_tis += \ set_dag_run_state_to_success(dagbag.get_dag(dr.dag_id), dr.execution_date, commit=True, session=session) models.DagStat.update(dirty_ids, session=session) altered_ti_count = len(altered_tis) flash( "{count} dag runs and {altered_ti_count} task instances " "were set to success".format(**locals())) except Exception as ex: if not self.handle_view_exception(ex): raise Exception("Ooops") flash('Failed to set state', 'error') # Called after editing DagRun model in the UI. @provide_session def after_model_change(self, form, dagrun, is_created, session=None): altered_tis = [] if dagrun.state == State.SUCCESS: altered_tis = set_dag_run_state_to_success( dagbag.get_dag(dagrun.dag_id), dagrun.execution_date, commit=True, session=session) elif dagrun.state == State.FAILED: altered_tis = set_dag_run_state_to_failed( dagbag.get_dag(dagrun.dag_id), dagrun.execution_date, commit=True, session=session) elif dagrun.state == State.RUNNING: altered_tis = set_dag_run_state_to_running( dagbag.get_dag(dagrun.dag_id), dagrun.execution_date, commit=True, session=session) altered_ti_count = len(altered_tis) models.DagStat.update([dagrun.dag_id], session=session) flash( "1 dag run and {altered_ti_count} task instances " "were set to '{dagrun.state}'".format(**locals())) class LogModelView(ModelViewOnly): verbose_name_plural = "logs" verbose_name = "log" column_display_actions = False column_default_sort = ('dttm', True) column_filters = ('dag_id', 'task_id', 'execution_date', 'extra') filter_converter = wwwutils.UtcFilterConverter() column_formatters = dict( dttm=datetime_f, execution_date=datetime_f, dag_id=dag_link) class TaskInstanceModelView(ModelViewOnly): verbose_name_plural = "task instances" verbose_name = "task instance" column_filters = ( 'state', 'dag_id', 'task_id', 'execution_date', 'hostname', 'queue', 'pool', 'operator', 'start_date', 'end_date') filter_converter = wwwutils.UtcFilterConverter() named_filter_urls = True column_formatters = dict( log_url=log_url_formatter, task_id=task_instance_link, hostname=nobr_f, state=state_f, execution_date=datetime_f, start_date=datetime_f, end_date=datetime_f, queued_dttm=datetime_f, dag_id=dag_link, run_id=dag_run_link, duration=duration_f) column_searchable_list = ('dag_id', 'task_id', 'state') column_default_sort = ('job_id', True) form_choices = { 'state': [ ('success', 'success'), ('running', 'running'), ('failed', 'failed'), ], } column_list = ( 'state', 'dag_id', 'task_id', 'execution_date', 'operator', 'start_date', 'end_date', 'duration', 'job_id', 'hostname', 'unixname', 'priority_weight', 'queue', 'queued_dttm', 'try_number', 'pool', 'log_url') page_size = PAGE_SIZE @action('set_running', "Set state to 'running'", None) def action_set_running(self, ids): self.set_task_instance_state(ids, State.RUNNING) @action('set_failed', "Set state to 'failed'", None) def action_set_failed(self, ids): self.set_task_instance_state(ids, State.FAILED) @action('set_success', "Set state to 'success'", None) def action_set_success(self, ids): self.set_task_instance_state(ids, State.SUCCESS) @action('set_retry', "Set state to 'up_for_retry'", None) def action_set_retry(self, ids): self.set_task_instance_state(ids, State.UP_FOR_RETRY) @provide_session @action('clear', lazy_gettext('Clear'), lazy_gettext( 'Are you sure you want to clear the state of the selected task instance(s)' ' and set their dagruns to the running state?')) def action_clear(self, ids, session=None): try: TI = models.TaskInstance dag_to_task_details = {} dag_to_tis = {} # Collect dags upfront as dagbag.get_dag() will reset the session for id_str in ids: task_id, dag_id, execution_date = iterdecode(id_str) dag = dagbag.get_dag(dag_id) task_details = dag_to_task_details.setdefault(dag, []) task_details.append((task_id, execution_date)) for dag, task_details in dag_to_task_details.items(): for task_id, execution_date in task_details: execution_date = parse_execution_date(execution_date) ti = session.query(TI).filter(TI.task_id == task_id, TI.dag_id == dag.dag_id, TI.execution_date == execution_date).one() tis = dag_to_tis.setdefault(dag, []) tis.append(ti) for dag, tis in dag_to_tis.items(): models.clear_task_instances(tis, session, dag=dag) session.commit() flash("{0} task instances have been cleared".format(len(ids))) except Exception as ex: if not self.handle_view_exception(ex): raise Exception("Ooops") flash('Failed to clear task instances', 'error') @provide_session def set_task_instance_state(self, ids, target_state, session=None): try: TI = models.TaskInstance count = len(ids) for id in ids: task_id, dag_id, execution_date = iterdecode(id) execution_date = parse_execution_date(execution_date) ti = session.query(TI).filter(TI.task_id == task_id, TI.dag_id == dag_id, TI.execution_date == execution_date).one() ti.state = target_state session.commit() flash( "{count} task instances were set to '{target_state}'".format(**locals())) except Exception as ex: if not self.handle_view_exception(ex): raise Exception("Ooops") flash('Failed to set state', 'error') def get_one(self, id): """ As a workaround for AIRFLOW-252, this method overrides Flask-Admin's ModelView.get_one(). TODO: this method should be removed once the below bug is fixed on Flask-Admin side. https://github.com/flask-admin/flask-admin/issues/1226 """ task_id, dag_id, execution_date = iterdecode(id) execution_date = pendulum.parse(execution_date) return self.session.query(self.model).get((task_id, dag_id, execution_date)) class ConnectionModelView(wwwutils.SuperUserMixin, AirflowModelView): create_template = 'airflow/conn_create.html' edit_template = 'airflow/conn_edit.html' list_template = 'airflow/conn_list.html' form_columns = ( 'conn_id', 'conn_type', 'host', 'schema', 'login', 'password', 'port', 'extra', 'extra__jdbc__drv_path', 'extra__jdbc__drv_clsname', 'extra__google_cloud_platform__project', 'extra__google_cloud_platform__key_path', 'extra__google_cloud_platform__keyfile_dict', 'extra__google_cloud_platform__scope', ) verbose_name = "Connection" verbose_name_plural = "Connections" column_default_sort = ('conn_id', False) column_list = ('conn_id', 'conn_type', 'host', 'port', 'is_encrypted', 'is_extra_encrypted',) form_overrides = dict(_password=PasswordField, _extra=TextAreaField) form_widget_args = { 'is_extra_encrypted': {'disabled': True}, 'is_encrypted': {'disabled': True}, } # Used to customized the form, the forms elements get rendered # and results are stored in the extra field as json. All of these # need to be prefixed with extra__ and then the conn_type ___ as in # extra__{conn_type}__name. You can also hide form elements and rename # others from the connection_form.js file form_extra_fields = { 'extra__jdbc__drv_path': StringField('Driver Path'), 'extra__jdbc__drv_clsname': StringField('Driver Class'), 'extra__google_cloud_platform__project': StringField('Project Id'), 'extra__google_cloud_platform__key_path': StringField('Keyfile Path'), 'extra__google_cloud_platform__keyfile_dict': PasswordField('Keyfile JSON'), 'extra__google_cloud_platform__scope': StringField('Scopes (comma separated)'), } form_choices = { 'conn_type': models.Connection._types } def on_model_change(self, form, model, is_created): formdata = form.data if formdata['conn_type'] in ['jdbc', 'google_cloud_platform']: extra = { key: formdata[key] for key in self.form_extra_fields.keys() if key in formdata} model.extra = json.dumps(extra) @classmethod def alert_fernet_key(cls): fk = None try: fk = conf.get('core', 'fernet_key') except Exception: pass return fk is None @classmethod def is_secure(cls): """ Used to display a message in the Connection list view making it clear that the passwords and `extra` field can't be encrypted. """ is_secure = False try: import cryptography # noqa F401 conf.get('core', 'fernet_key') is_secure = True except Exception: pass return is_secure def on_form_prefill(self, form, id): try: d = json.loads(form.data.get('extra', '{}')) except Exception: d = {} for field in list(self.form_extra_fields.keys()): value = d.get(field, '') if value: field = getattr(form, field) field.data = value class UserModelView(wwwutils.SuperUserMixin, AirflowModelView): verbose_name = "User" verbose_name_plural = "Users" column_default_sort = 'username' class VersionView(wwwutils.SuperUserMixin, BaseView): @expose('/') def version(self): # Look at the version from setup.py try: airflow_version = pkg_resources.require("apache-airflow")[0].version except Exception as e: airflow_version = None logging.error(e) # Get the Git repo and git hash git_version = None try: with open(os.path.join(*[settings.AIRFLOW_HOME, 'airflow', 'git_version'])) as f: git_version = f.readline() except Exception as e: logging.error(e) # Render information title = "Version Info" return self.render('airflow/version.html', title=title, airflow_version=airflow_version, git_version=git_version) class ConfigurationView(wwwutils.SuperUserMixin, BaseView): @expose('/') def conf(self): raw = request.args.get('raw') == "true" title = "Airflow Configuration" subtitle = conf.AIRFLOW_CONFIG if conf.getboolean("webserver", "expose_config"): with open(conf.AIRFLOW_CONFIG, 'r') as f: config = f.read() table = [(section, key, value, source) for section, parameters in conf.as_dict(True, True).items() for key, (value, source) in parameters.items()] else: config = ( "# Your Airflow administrator chose not to expose the " "configuration, most likely for security reasons.") table = None if raw: return Response( response=config, status=200, mimetype="application/text") else: code_html = Markup(highlight( config, lexers.IniLexer(), # Lexer call HtmlFormatter(noclasses=True)) ) return self.render( 'airflow/config.html', pre_subtitle=settings.HEADER + " v" + airflow.__version__, code_html=code_html, title=title, subtitle=subtitle, table=table) class DagModelView(wwwutils.SuperUserMixin, ModelView): column_list = ('dag_id', 'owners') column_editable_list = ('is_paused',) form_excluded_columns = ('is_subdag', 'is_active') column_searchable_list = ('dag_id',) column_filters = ( 'dag_id', 'owners', 'is_paused', 'is_active', 'is_subdag', 'last_scheduler_run', 'last_expired') filter_converter = wwwutils.UtcFilterConverter() form_widget_args = { 'last_scheduler_run': {'disabled': True}, 'fileloc': {'disabled': True}, 'is_paused': {'disabled': True}, 'last_pickled': {'disabled': True}, 'pickle_id': {'disabled': True}, 'last_loaded': {'disabled': True}, 'last_expired': {'disabled': True}, 'pickle_size': {'disabled': True}, 'scheduler_lock': {'disabled': True}, 'owners': {'disabled': True}, } column_formatters = dict( dag_id=dag_link, ) can_delete = False can_create = False page_size = PAGE_SIZE list_template = 'airflow/list_dags.html' named_filter_urls = True def get_query(self): """ Default filters for model """ return ( super(DagModelView, self) .get_query() .filter(or_(models.DagModel.is_active, models.DagModel.is_paused)) .filter(~models.DagModel.is_subdag) ) def get_count_query(self): """ Default filters for model """ return ( super(DagModelView, self) .get_count_query() .filter(models.DagModel.is_active) .filter(~models.DagModel.is_subdag) )
apache-2.0
aemerick/galaxy_analysis
grackle/cooling_cell_plot.py
1
3215
from galaxy_analysis.plot.plot_styles import * import matplotlib.pyplot as plt import os, sys import numpy as np from mpl_toolkits.axes_grid1 import make_axes_locatable def bins_from_centers(x): xnew = np.zeros(len(x) + 1) dx = np.zeros(len(x) + 1) dx[1:-1] = x[1:] - x[:-1] dx[0] = dx[1] dx[-1] = dx[-2] xnew[:-1] = x - 0.5*dx[:-1] xnew[-1] = x[-1] + 0.5*dx[-1] return xnew def plot_2d_histogram(datafile = 'all_runs_d_12.20.dat'): ylabel = r'log(H$^{-}$ Photodetachment Scale Factor)' xlabel = "log(LW Scale Factor)" data = np.genfromtxt(datafile) # names = True) k27 = data[:,0] LW = data[:,1] k27_centers = np.linspace(np.log10(np.min(k27)), np.log10(np.max(k27)), int(np.sqrt(np.size(k27) ))) k27_vals = bins_from_centers(k27_centers) LW_centers = np.linspace(np.log10(np.min(LW)), np.log10(np.max(LW)), int(np.sqrt(np.size(LW)))) LW_vals = bins_from_centers(LW_centers) k27_mesh, LW_mesh = np.meshgrid(LW_vals, k27_vals) k27_center_mesh, LW_center_mesh = np.meshgrid(LW_centers, k27_centers) #f_H2[data['k27'] == 1.58489319] = 100.0 # flag to figure out orientation f_H2 = data[:,2] z_mesh = f_H2.reshape( int(np.sqrt(np.size(k27))), int(np.sqrt(np.size(LW)))) #z_mesh = z[:-1,:-1] fig, ax = plt.subplots() fig.set_size_inches(8,8) img1 = ax.pcolormesh(10.0**(LW_mesh), 10.0**(k27_mesh), np.log10(z_mesh.T), cmap = 'magma', vmin = -9, vmax = -2.8) ax.semilogx() ax.semilogy() ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) divider = make_axes_locatable(ax) cax1 = divider.append_axes('right', size = '5%', pad = 0.05) fig.colorbar(img1, cax=cax1, label = r'log(f$_{\rm H_2}$)') ax.contour( 10.**(LW_center_mesh), 10.0**(k27_center_mesh), np.log10(z_mesh.T), levels = [-8,-7,-6,-5,-4,-3], colors = 'black', linewidths = 3, linestyles = '-.') ax.scatter( [1,1,100,100], [1,100,1,100], s = 250, marker = "*", color = "white") plt.minorticks_on() plt.tight_layout(h_pad = 0, w_pad = 0.05) fig.savefig("fH2.png") plt.close() f_H2 = data[:,3] z_mesh= f_H2.reshape( int(np.sqrt(np.size(k27))), int(np.sqrt(np.size(LW)))) #z_mesh = z[:-1,:-1] fig, ax = plt.subplots() fig.set_size_inches(8,8) img1 = ax.pcolormesh(10.0**(LW_mesh), 10.0**(k27_mesh), np.log10(z_mesh.T), cmap = 'RdYlBu_r', vmin = np.min(np.log10(z_mesh)), vmax = np.max(np.log10(z_mesh))) ax.semilogx() ax.semilogy() ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) divider = make_axes_locatable(ax) cax1 = divider.append_axes('right', size = '5%', pad = 0.05) fig.colorbar(img1, cax=cax1, label = r'log(Temperature [K])') plt.minorticks_on() plt.tight_layout(h_pad = 0, w_pad = 0.05) fig.savefig("T.png") plt.close() return if __name__ == "__main__": plot_2d_histogram( datafile = str(sys.argv[1]))
mit
bruino/pulppy
mplCanvas.py
1
5364
#!/usr/bin/env python # Pulppy Software - Linear Programming software for optimizing various practical problems of Operations Research. # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import sys import random import matplotlib import numpy as np matplotlib.use("Qt5Agg") from PyQt5 import QtCore from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure # #Pulppy Software: Graphic linear programming model # class MplCanvas(FigureCanvas): """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).""" def __init__(self, parent=None, width=5, height=8, dpi=100, matrixModel=[], title='', point=[]): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) self.title = title self.Plot(matrixModel, title, point) FigureCanvas.__init__(self, fig) self.mpl_toolbar = NavigationToolbar(self, parent) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def Plot(self, matrix, title, optime): s = 0 t = 0 for i in range(len(matrix)): if i != 0: if matrix[i][0] != 0: r = matrix[i][3] / matrix[i][0] if r > s: s = r if matrix[i][1] != 0: u = matrix[i][3] / matrix[i][1] if u > t: t = u if s != 0: x = np.linspace(0, s) else: x = np.linspace(0, t) listFmenor = [] listFmayor= [] for i in range(len(matrix)): if i == 0: y = -(matrix[i][0] / matrix[i][1])*(x-float(optime[0])) + float(optime[1]) self.axes.plot(x, y, 'k--',linewidth=1) else: y = (matrix[i][3] - matrix[i][0]*x) / matrix[i][1] if matrix[i][2] == u'>=': listFmayor.append(y) self.axes.plot(x, y, linewidth=1.5, label='C'+str(i)) self.axes.fill_between(x, y, t, alpha=0.2) elif matrix[i][2] == u'>': listFmayor.append(y) self.axes.plot(x, y, '--', linewidth=1.5, label='C'+str(i)) self.axes.fill_between(x, y, t, alpha=0.2) elif matrix[i][2] == u'<=': listFmenor.append(y) self.axes.plot(x, y, linewidth=1.5, label='C'+str(i)) self.axes.fill_between(x, 0, y, alpha=0.2) elif matrix[i][2] == u'<': listFmenor.append(y) self.axes.plot(x, y, '--', linewidth=1.5, label='C'+str(i)) self.axes.fill_between(x, 0, y, alpha=0.2) else: self.axes.plot(x, y, linewidth=1.5, label='C'+str(i)) #Functions <=, < j = len(listFmenor) if j > 1: ySup = np.minimum(listFmenor[0], listFmenor[1]) for i in range(j-2): ySup = np.minimum(listFmenor[i+2], ySup) elif j == 1: ySup = listFmenor[0] else: ySup = t #Functions >=, > j = len(listFmayor) if j > 1: yInf = np.maximum(listFmayor[0], listFmayor[1]) for i in range(j-2): yInf = np.maximum(listFmayor[i+2], yInf) elif j == 1: yInf = listFmayor[0] else: yInf = 0 self.axes.fill_between(x, ySup, yInf, where=ySup>yInf, color='blue', alpha=0.8) self.axes.set_xlim(0, s) self.axes.set_ylim(0, t) self.axes.set_xlabel('x') self.axes.set_ylabel('y') self.axes.plot(optime[0], optime[1], 'go', label="%.2f" % optime[0]+", "+"%.2f" % optime[1]) self.axes.set_title(title) self.axes.legend(fontsize=10) self.axes.grid(True)
mit
waterponey/scikit-learn
examples/cluster/plot_face_ward_segmentation.py
71
2460
""" ========================================================================= A demo of structured Ward hierarchical clustering on a raccoon face image ========================================================================= Compute the segmentation of a 2D image with Ward hierarchical clustering. The clustering is spatially constrained in order for each segmented region to be in one piece. """ # Author : Vincent Michel, 2010 # Alexandre Gramfort, 2011 # License: BSD 3 clause print(__doc__) import time as time import numpy as np import scipy as sp import matplotlib.pyplot as plt from sklearn.feature_extraction.image import grid_to_graph from sklearn.cluster import AgglomerativeClustering from sklearn.utils.testing import SkipTest from sklearn.utils.fixes import sp_version if sp_version < (0, 12): raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and " "thus does not include the scipy.misc.face() image.") ############################################################################### # Generate data try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) # Resize it to 10% of the original size to speed up the processing face = sp.misc.imresize(face, 0.10) / 255. X = np.reshape(face, (-1, 1)) ############################################################################### # Define the structure A of the data. Pixels connected to their neighbors. connectivity = grid_to_graph(*face.shape) ############################################################################### # Compute clustering print("Compute structured hierarchical clustering...") st = time.time() n_clusters = 15 # number of regions ward = AgglomerativeClustering(n_clusters=n_clusters, linkage='ward', connectivity=connectivity) ward.fit(X) label = np.reshape(ward.labels_, face.shape) print("Elapsed time: ", time.time() - st) print("Number of pixels: ", label.size) print("Number of clusters: ", np.unique(label).size) ############################################################################### # Plot the results on an image plt.figure(figsize=(5, 5)) plt.imshow(face, cmap=plt.cm.gray) for l in range(n_clusters): plt.contour(label == l, contours=1, colors=[plt.cm.spectral(l / float(n_clusters)), ]) plt.xticks(()) plt.yticks(()) plt.show()
bsd-3-clause
sijiangdu/Tensorflow
mnist_rnn/mnist_cnn_kaggles_cmpt.py
1
18345
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # Modifications copyright (C) 2017 Sijiang Du # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # Author: Sijiang Du, May, 2017 # This program runs on MAC OS. It is for Kaggle Digit Recognizer competition. # # Input: train.csv, test.csv. # # Output: "submission_sijiangdu.csv" in folder /tmp/tensorflow/mnist_rnn/input_data/ # Generated temparary files are at /tmp/tensorflow/mnist_rnn/ # # Kaggle.com provides its own MNIST "train.csv" and "test.csv". # The program here uses tensorflow input pipe line to stream line the training and testing data from the cvs files. # There are two flags in the program "train_by_mnist_lib" and "test_by_mnist_lib" set those to "True" to use moist_data as inputs. # Otherwise, user need to download the cvs file from Kaggle website for Digit Recognizer: https://www.kaggle.com/c/digit-recognizer/data # # A 2-D convolution network is implemented. # The variable "n_conv" defines the number of convolution layer being added. The 2-D pooling is applied after 2-D covn. # However, there is no pooling if the image width is too mall (width is less than 10). # # The program provided an emxaple how to construct a CNN with a sigle parameter and add multiple conv layers accordingly in the while loop. # Two-layer "n_conv = 2" is the default value. The vaiable value can be changed to larger number to construct a much deeper network in the # CNN_Wrapper function. # import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt import matplotlib.cm as cm import argparse import sys import numpy as np import os.path import csv import random csv_file_name = "train.csv" test_csv_file_name = "test.csv" train_file_name = "mnist_rnn_train.csv" test_file_name = "mnist_rnn_test.csv" submit_test_file_name = "test_28000.csv" submit_result_file_name = "submission_sijiangdu.csv" # set random seed for comparing the two result calculations tf.set_random_seed(1) ## this is data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) # hyperparameters csv_size = 42000 train_size = 40000 test_size = 2000 epochs = 5 training_iters = train_size * epochs batch_size = 100 img_width = 28 img_height = 28 sample_size = img_width*img_height n_conv = 6 n_classes = 10 # MNIST classes (0-9 digits) # partition: randomly partion the input file to two files. E.g. partition = 0.8: 80% for training 20% for testing. def csv_partition_train_test(input_file, partition=0.98): global csv_size, train_size, test_size,training_iters csv_size = 0 train_size = 0 test_size = 0 with open(input_file) as data: with open(FLAGS.data_dir+test_file_name, 'w+') as test: with open(FLAGS.data_dir+train_file_name, 'w+') as train: header = next(data) test.write(header) train.write(header) csv_r = csv.reader(data) csv_w_train = csv.writer(train) csv_w_test = csv.writer(test) for line in csv_r: csv_size += 1 if(len(line)!=785): print("Invalid CSV format. Discard record #%s"%(csv_size)) continue if random.random() < partition: csv_w_train.writerow(line) train_size += 1 else: csv_w_test.writerow(line) test_size += 1 training_iters = train_size * epochs print("CSV input size = %s, train set size = %s, validation set size = %s, training samples = %s"%(csv_size , train_size,test_size, training_iters)) #add a dummy column to the test.csv def csv_test_csv_file_change(input_file, output_file): with open(input_file) as data: with open(FLAGS.data_dir+output_file, 'w+') as out_file: header = next(data) out_file.write("label,"+header) csv_r = csv.reader(data) csv_w = csv.writer(out_file) size = 0 for line in csv_r: size += 1 line = [-1] + line if(len(line)!=785): print("Invalid test.csv. Discard record #%s"%(size)) continue csv_w.writerow(line) print("test.csv input size = %s"%(size)) def read_mnist_csv(filename_queue): reader = tf.TextLineReader(skip_header_lines=1) key, value = reader.read(filename_queue) record_defaults = [[0]for row in range(785)] cols = tf.decode_csv( value, record_defaults=record_defaults) features = tf.stack(cols[1:]) label = tf.stack([cols[0]]) return features, label def input_pipeline(filenames, batch_size, num_epochs=None, shuffle=True): filename_queue = tf.train.string_input_producer( filenames, num_epochs=num_epochs, shuffle=shuffle) features, label = read_mnist_csv(filename_queue) # min_after_dequeue defines how big a buffer we will randomly sample # from -- bigger means better shuffling but slower start up and more # memory used. # capacity must be larger than min_after_dequeue and the amount larger # determines the maximum we will prefetch. Recommendation: # min_after_dequeue + (num_threads + a small safety margin) * batch_size min_after_dequeue = 10000 capacity = min_after_dequeue + 3 * batch_size if shuffle == True: feature_batch, label_batch = tf.train.shuffle_batch( [features, label], batch_size=batch_size, capacity=capacity, min_after_dequeue=min_after_dequeue) else: feature_batch, label_batch = tf.train.batch( [features, label], batch_size=batch_size, capacity=capacity ) return feature_batch, label_batch # display image show_num = 5 fig_mnist, ax_array = plt.subplots(show_num,show_num) def show_mnist(images,labels,title = "Digits"): global fig_mnist, ax_array plt.figure(fig_mnist.number) fig_mnist.suptitle(title) n = len(images) z = np.zeros((28,28)) t = [[i] for i in range(10)] for i in range(show_num*show_num): row = int(i/show_num) col = int(i%show_num) if i<n: img = images[i].reshape(28,28) ax_array[row,col].imshow(img, cmap=cm.binary) ax_array[row, col].set_title(int(labels[i])) ax_array[row, col].axis('off') else: ax_array[row, col].imshow(z, cmap=cm.binary) ax_array[row, col].set_title('') ax_array[row, col].axis('off') plt.draw() plt.pause(0.3) plt.savefig(FLAGS.result_dir+'/'+ title +'.png') # tf Graph input x = tf.placeholder(tf.float32, [None, 28*28]) y = tf.placeholder(tf.float32, [None, n_classes]) def weight_variable(shape): """Create a weight variable with appropriate initialization.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): """Create a bias variable with appropriate initialization.""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def variable_summaries(var): """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary.scalar('stddev', stddev) tf.summary.scalar('max', tf.reduce_max(var)) tf.summary.scalar('min', tf.reduce_min(var)) tf.summary.histogram('histogram', var) def conv2d(x, W): # stride [1, x_movement, y_movement, 1] # Must have strides[0] = strides[3] = 1 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): # stride [1, x_movement, y_movement, 1] return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') def CNN_Wrapper(X, num_classes, n_hidden_layers, init_size=32, drop_out = 0.9, name='Conv_2D'): with tf.name_scope(name): x = tf.reshape(X, [-1, 28, 28, 1]) print( "CNN input:"+str(x) ) width = 28; #Add layer_num layers of hidden layer W = weight_variable([5,5, 1,init_size]) b = bias_variable([init_size]) cur_layer = conv2d(x, W) + b cur_layer = tf.nn.relu(cur_layer) cur_layer = max_pool_2x2(cur_layer) width /= 2; size = init_size print("CNN layer 1: " + str(cur_layer) ) for i in range(1,n_hidden_layers): W = weight_variable([5,5,size,size*2]) b = bias_variable([size*2]) cur_layer = conv2d(cur_layer, W) + b cur_layer = tf.nn.relu(cur_layer) if width > 7: #not doing pooling when the width is small cur_layer = max_pool_2x2(cur_layer) width = (int)(width/2); size = size*2 print('CNN layer %s: '%(i+1) + str(cur_layer) ) height = width W = weight_variable([width*height*size, 1024]) b = bias_variable([1024]) #flat the layer: [n_samples, 7, 7, size] ->> [n_samples, 7*7*size] cur_layer = tf.reshape(cur_layer, [-1, width*height*size]) cur_layer = tf.nn.relu(tf.matmul(cur_layer, W) + b) cur_layer = tf.nn.dropout(cur_layer, drop_out) print('CNN output flat layer:'+str(cur_layer)) # output results# W = weight_variable([1024, num_classes]) b = bias_variable([num_classes]) results = tf.matmul(cur_layer, W) + b results = tf.nn.l2_normalize(results,0) return results def train(): if not os.path.exists(FLAGS.data_dir+train_file_name)\ or not os.path.exists(FLAGS.data_dir+test_file_name): csv_partition_train_test(csv_file_name) if not os.path.exists(FLAGS.data_dir+submit_test_file_name): csv_test_csv_file_change(test_csv_file_name, submit_test_file_name) pred = CNN_Wrapper(x, n_classes, n_conv, init_size=32, drop_out = FLAGS.dropout, name='Conv_2_layer'); with tf.name_scope('Train'): cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) train_op = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(cost) with tf.name_scope('Classify'): classification = tf.argmax(pred, 1) with tf.name_scope('accuracy'): with tf.name_scope('correct_prediction'): correct_pred = tf.equal(classification, tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) tf.summary.scalar('accuracy', accuracy) with tf.name_scope('Input_Batch'): example_batch_train, label_batch_train = input_pipeline(tf.constant([FLAGS.data_dir+train_file_name]), batch_size) example_batch_test, label_batch_test = input_pipeline(tf.constant([FLAGS.data_dir+test_file_name]), batch_size) example_batch_submit, label_batch_submit = input_pipeline(tf.constant([FLAGS.data_dir+submit_test_file_name]), batch_size,num_epochs=1,shuffle=False) train_by_mnist_lib = False test_by_mnist_lib = True def feed_dict(train, submit=False): """Make a TensorFlow feed_dict: maps data onto Tensor placeholders.""" if train: if train_by_mnist_lib == True: xs, ys = mnist.train.next_batch(batch_size) return {x: xs, y: ys} xs, ys_label = sess.run([example_batch_train, label_batch_train]) else: if submit: xs, ys_label = sess.run([example_batch_submit, label_batch_submit]) else: if test_by_mnist_lib == True: xs, ys = mnist.test.next_batch(batch_size) return {x: xs, y: ys} xs, ys_label = sess.run([example_batch_test, label_batch_test]) n = ys_label.shape[0] ys = np.zeros((n,10)) if not submit: for i in range(n): ys[i][int(ys_label[i])] = 1 xs = xs/255 return {x: xs, y: ys} sess = tf.InteractiveSession() with tf.name_scope('training_epoch'): # Merge all the summaries and write them out to /tmp/tensorflow/mnist/logs/mnist_with_summaries (by default) merged = tf.summary.merge_all() train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph) init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) sess.run(init_op) # Start input enqueue threads. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) step = 0 acc = 0 # plotting fig1, ax = plt.subplots(1,1) plt.ylim((0.94, 1.03)) plt.ylabel('Accuracy') plt.xlabel('Training Step ( bactch size:' + str(int(batch_size)) + ')') ax.text(0.05, 0.90,'Number of Conv layers: ' + str(n_conv), ha='left', va='center', color='blue', transform=ax.transAxes) text_acc = ax.text(0.05, 0.85,'Accuracy: ' + str(acc), ha='left', va='center', color='green', transform=ax.transAxes) fig1.suptitle('Tensorflow CNN - MNIST Digit Recognizer') acc_all = [0.0,0.0,0.0] plt.draw() plt.pause(0.3) try: submit_file = open(FLAGS.data_dir+submit_result_file_name, 'w+') submit_file.write("ImageId,Label\r\n") csv_w_submit = csv.writer(submit_file) submit_size = 0 while not coord.should_stop(): #generate output submission file if step * batch_size > training_iters: feed_d = feed_dict(False,True) [digits] = sess.run([classification], feed_d) for i in digits: submit_size += 1 line = [str(submit_size),str(i)] csv_w_submit.writerow(line) if(submit_size%1000 == 0): print("Outputs to submission file: "+str(submit_size)) continue #training sess.run([train_op], feed_dict=feed_dict(True)) step += 1 #testing and plotting training progress test_at = 100 if step % test_at == 0: tmp = acc #Init images those are incorrectly classified s = np.zeros((1,28*28)) d = np.zeros(1) test_loop = 100 acc_l = [0.0]*test_loop for i in range(test_loop): feed_d=feed_dict(False) acc_l[i],summary,digits = sess.run([accuracy,merged,classification], feed_dict=feed_d) train_writer.add_summary(summary, step) #show the images those are incorrectly classified if len(s) > show_num*show_num: continue correct = np.argmax(feed_d[y],1) for i in range(batch_size): if correct[i] != digits[i]: s = np.append(s,np.array([feed_d[x][i].flatten()]),0) d = np.append(d,np.array([digits[i]]),0) acc = np.mean(acc_l) show_mnist(s[1:],d[1:],"Incorect Classifications") print(acc) plt.figure(fig1.number) plt.plot([step-test_at,step], [tmp, acc],'g') acc_all.append(acc) acc_all.pop(0) text_acc.set_text('Accuracy: ..., [%s], [%s], [%s]'%(acc_all[-3], acc_all[-2],acc_all[-1]) ) plt.draw() plt.savefig(FLAGS.result_dir+'/mnist_cnn'+'.png') plt.pause(0.3) except tf.errors.OutOfRangeError: print('Done training and testing -- epoch limit reached') finally: # When done, ask the threads to stop. coord.request_stop() submit_file.close() if not coord.should_stop(): coord.request_stop() # Wait for threads to finish. coord.join(threads) sess.close() result_str = str(round(int(acc*1000)))+'_layer_'+str(n_conv) plt.figure(fig1.number) plt.savefig(FLAGS.result_dir+'/mnist_cnn_'+result_str+'.png') train_writer.close() def main(_): if tf.gfile.Exists(FLAGS.log_dir): tf.gfile.DeleteRecursively(FLAGS.log_dir) tf.gfile.MakeDirs(FLAGS.log_dir) if tf.gfile.Exists(FLAGS.data_dir): tf.gfile.DeleteRecursively(FLAGS.data_dir) if not tf.gfile.Exists(FLAGS.data_dir): tf.gfile.MakeDirs(FLAGS.data_dir) if not tf.gfile.Exists(FLAGS.result_dir): tf.gfile.MakeDirs(FLAGS.result_dir) #enter the training and testing loop train() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--learning_rate', type=float, default=0.001, help='Initial learning rate') parser.add_argument('--dropout', type=float, default= 0.95, help='Keep probability for training dropout.') parser.add_argument('--forget_bias', type=float, default= 0.9, help='forget bias for training') parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist_rnn/input_data/', help='Directory for storing input data') parser.add_argument('--log_dir', type=str, default='/tmp/tensorflow/mnist_rnn/logs/mnist_rnn_with_summaries', help='Summaries log directory') parser.add_argument('--result_dir', type=str, default='/tmp/tensorflow/mnist_rnn/result', help='result plotting PNG files directory') FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
apache-2.0
MJuddBooth/pandas
pandas/tests/io/sas/test_xport.py
2
4895
import os import numpy as np import pytest import pandas as pd import pandas.util.testing as tm from pandas.io.sas.sasreader import read_sas # CSV versions of test xpt files were obtained using the R foreign library # Numbers in a SAS xport file are always float64, so need to convert # before making comparisons. def numeric_as_float(data): for v in data.columns: if data[v].dtype is np.dtype('int64'): data[v] = data[v].astype(np.float64) class TestXport(object): @pytest.fixture(autouse=True) def setup_method(self, datapath): self.dirpath = datapath("io", "sas", "data") self.file01 = os.path.join(self.dirpath, "DEMO_G.xpt") self.file02 = os.path.join(self.dirpath, "SSHSV1_A.xpt") self.file03 = os.path.join(self.dirpath, "DRXFCD_G.xpt") self.file04 = os.path.join(self.dirpath, "paxraw_d_short.xpt") def test1_basic(self): # Tests with DEMO_G.xpt (all numeric file) # Compare to this data_csv = pd.read_csv(self.file01.replace(".xpt", ".csv")) numeric_as_float(data_csv) # Read full file data = read_sas(self.file01, format="xport") tm.assert_frame_equal(data, data_csv) num_rows = data.shape[0] # Test reading beyond end of file reader = read_sas(self.file01, format="xport", iterator=True) data = reader.read(num_rows + 100) assert data.shape[0] == num_rows reader.close() # Test incremental read with `read` method. reader = read_sas(self.file01, format="xport", iterator=True) data = reader.read(10) reader.close() tm.assert_frame_equal(data, data_csv.iloc[0:10, :]) # Test incremental read with `get_chunk` method. reader = read_sas(self.file01, format="xport", chunksize=10) data = reader.get_chunk() reader.close() tm.assert_frame_equal(data, data_csv.iloc[0:10, :]) # Test read in loop m = 0 reader = read_sas(self.file01, format="xport", chunksize=100) for x in reader: m += x.shape[0] reader.close() assert m == num_rows # Read full file with `read_sas` method data = read_sas(self.file01) tm.assert_frame_equal(data, data_csv) def test1_index(self): # Tests with DEMO_G.xpt using index (all numeric file) # Compare to this data_csv = pd.read_csv(self.file01.replace(".xpt", ".csv")) data_csv = data_csv.set_index("SEQN") numeric_as_float(data_csv) # Read full file data = read_sas(self.file01, index="SEQN", format="xport") tm.assert_frame_equal(data, data_csv, check_index_type=False) # Test incremental read with `read` method. reader = read_sas(self.file01, index="SEQN", format="xport", iterator=True) data = reader.read(10) reader.close() tm.assert_frame_equal(data, data_csv.iloc[0:10, :], check_index_type=False) # Test incremental read with `get_chunk` method. reader = read_sas(self.file01, index="SEQN", format="xport", chunksize=10) data = reader.get_chunk() reader.close() tm.assert_frame_equal(data, data_csv.iloc[0:10, :], check_index_type=False) def test1_incremental(self): # Test with DEMO_G.xpt, reading full file incrementally data_csv = pd.read_csv(self.file01.replace(".xpt", ".csv")) data_csv = data_csv.set_index("SEQN") numeric_as_float(data_csv) reader = read_sas(self.file01, index="SEQN", chunksize=1000) all_data = [x for x in reader] data = pd.concat(all_data, axis=0) tm.assert_frame_equal(data, data_csv, check_index_type=False) def test2(self): # Test with SSHSV1_A.xpt # Compare to this data_csv = pd.read_csv(self.file02.replace(".xpt", ".csv")) numeric_as_float(data_csv) data = read_sas(self.file02) tm.assert_frame_equal(data, data_csv) def test_multiple_types(self): # Test with DRXFCD_G.xpt (contains text and numeric variables) # Compare to this data_csv = pd.read_csv(self.file03.replace(".xpt", ".csv")) data = read_sas(self.file03, encoding="utf-8") tm.assert_frame_equal(data, data_csv) def test_truncated_float_support(self): # Test with paxraw_d_short.xpt, a shortened version of: # http://wwwn.cdc.gov/Nchs/Nhanes/2005-2006/PAXRAW_D.ZIP # This file has truncated floats (5 bytes in this case). # GH 11713 data_csv = pd.read_csv(self.file04.replace(".xpt", ".csv")) data = read_sas(self.file04, format="xport") tm.assert_frame_equal(data.astype('int64'), data_csv)
bsd-3-clause
UltronAI/Deep-Learning
Pattern-Recognition/hw2-Feature-Selection/main.py
1
2886
import numpy as np from skfeature.function.similarity_based import trace_ratio from FeatureSelector.FisherSelector import FisherSelector from sklearn import svm from FisherClassifier import FisherClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier train_dir = "data/traindata.txt" test_dir = "data/testdata.txt" x_train = np.loadtxt(train_dir)[:, 0:10] y_train = np.loadtxt(train_dir)[:, 10] x_test = np.loadtxt(test_dir)[:, 0:10] y_test = np.loadtxt(test_dir)[:, 10] for n_select in range(2, 5): n_neighbors = 5 # Trace Ratio, Fisher for feature_select in ["Trace Ratio", "Fisher"]: # SVM, Fisher LDA, KNN, RandomForest, AdaBoost for classifier in ["SVM", "Fisher LDA", "KNN", "RandomForest", "AdaBoost"]: selected = [] if classifier == "KNN": print("[ feature select method:", feature_select, "] [ classifier:", classifier, "] [k:", n_neighbors, "]") else: print("[ feature select method:", feature_select, "] [ classifier:", classifier, "]") if feature_select == "Trace Ratio": idx, feature_score, subset_score = trace_ratio.trace_ratio(x_train, y_train, n_select, style='laplacian') selected = list(idx[:n_select]) elif feature_select == "Fisher": selected = list(FisherSelector(x_train, y_train, n_select)) # elif feature_select == "GA": # selected = GA(x_train, y_train) x_train_selected = x_train[:, selected] x_test_selected = x_test[:, selected] if classifier == "SVM": clf = svm.SVC(kernel='linear', C=3) clf.fit(x_train_selected, y_train) y_pred = clf.predict(x_test_selected) elif classifier == "Fisher LDA": y_pred = FisherClassifier(x_train_selected, y_train, x_test_selected) elif classifier == "KNN": knn = KNeighborsClassifier(n_neighbors=n_neighbors) knn.fit(x_train_selected, y_train) y_pred = knn.predict(x_test_selected) elif classifier == "RandomForest": rf = RandomForestClassifier(max_depth=2, random_state=0) rf.fit(x_train_selected, y_train) y_pred = rf.predict(x_test_selected) elif classifier == "AdaBoost": ada = AdaBoostClassifier() ada.fit(x_train_selected, y_train) y_pred = ada.predict(x_test_selected) err = np.sum(np.abs(y_pred - y_test)) / y_test.shape[0] print("feature_num:", n_select, ", feature_id:", selected, ", err: %.4f" % err)
mit
krez13/scikit-learn
sklearn/utils/arpack.py
265
64837
""" This contains a copy of the future version of scipy.sparse.linalg.eigen.arpack.eigsh It's an upgraded wrapper of the ARPACK library which allows the use of shift-invert mode for symmetric matrices. Find a few eigenvectors and eigenvalues of a matrix. Uses ARPACK: http://www.caam.rice.edu/software/ARPACK/ """ # Wrapper implementation notes # # ARPACK Entry Points # ------------------- # The entry points to ARPACK are # - (s,d)seupd : single and double precision symmetric matrix # - (s,d,c,z)neupd: single,double,complex,double complex general matrix # This wrapper puts the *neupd (general matrix) interfaces in eigs() # and the *seupd (symmetric matrix) in eigsh(). # There is no Hermetian complex/double complex interface. # To find eigenvalues of a Hermetian matrix you # must use eigs() and not eigsh() # It might be desirable to handle the Hermetian case differently # and, for example, return real eigenvalues. # Number of eigenvalues returned and complex eigenvalues # ------------------------------------------------------ # The ARPACK nonsymmetric real and double interface (s,d)naupd return # eigenvalues and eigenvectors in real (float,double) arrays. # Since the eigenvalues and eigenvectors are, in general, complex # ARPACK puts the real and imaginary parts in consecutive entries # in real-valued arrays. This wrapper puts the real entries # into complex data types and attempts to return the requested eigenvalues # and eigenvectors. # Solver modes # ------------ # ARPACK and handle shifted and shift-inverse computations # for eigenvalues by providing a shift (sigma) and a solver. __docformat__ = "restructuredtext en" __all__ = ['eigs', 'eigsh', 'svds', 'ArpackError', 'ArpackNoConvergence'] import warnings from scipy.sparse.linalg.eigen.arpack import _arpack import numpy as np from scipy.sparse.linalg.interface import aslinearoperator, LinearOperator from scipy.sparse import identity, isspmatrix, isspmatrix_csr from scipy.linalg import lu_factor, lu_solve from scipy.sparse.sputils import isdense from scipy.sparse.linalg import gmres, splu import scipy from distutils.version import LooseVersion _type_conv = {'f': 's', 'd': 'd', 'F': 'c', 'D': 'z'} _ndigits = {'f': 5, 'd': 12, 'F': 5, 'D': 12} DNAUPD_ERRORS = { 0: "Normal exit.", 1: "Maximum number of iterations taken. " "All possible eigenvalues of OP has been found. IPARAM(5) " "returns the number of wanted converged Ritz values.", 2: "No longer an informational error. Deprecated starting " "with release 2 of ARPACK.", 3: "No shifts could be applied during a cycle of the " "Implicitly restarted Arnoldi iteration. One possibility " "is to increase the size of NCV relative to NEV. ", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 2 and less than or equal to N.", -4: "The maximum number of Arnoldi update iterations allowed " "must be greater than zero.", -5: " WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work array WORKL is not sufficient.", -8: "Error return from LAPACK eigenvalue calculation;", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", -13: "NEV and WHICH = 'BE' are incompatible.", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " "enough workspace and array storage has been allocated." } SNAUPD_ERRORS = DNAUPD_ERRORS ZNAUPD_ERRORS = DNAUPD_ERRORS.copy() ZNAUPD_ERRORS[-10] = "IPARAM(7) must be 1,2,3." CNAUPD_ERRORS = ZNAUPD_ERRORS DSAUPD_ERRORS = { 0: "Normal exit.", 1: "Maximum number of iterations taken. " "All possible eigenvalues of OP has been found.", 2: "No longer an informational error. Deprecated starting with " "release 2 of ARPACK.", 3: "No shifts could be applied during a cycle of the Implicitly " "restarted Arnoldi iteration. One possibility is to increase " "the size of NCV relative to NEV. ", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV must be greater than NEV and less than or equal to N.", -4: "The maximum number of Arnoldi update iterations allowed " "must be greater than zero.", -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work array WORKL is not sufficient.", -8: "Error return from trid. eigenvalue calculation; " "Informational error from LAPACK routine dsteqr .", -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4,5.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "IPARAM(1) must be equal to 0 or 1.", -13: "NEV and WHICH = 'BE' are incompatible. ", -9999: "Could not build an Arnoldi factorization. " "IPARAM(5) returns the size of the current Arnoldi " "factorization. The user is advised to check that " "enough workspace and array storage has been allocated.", } SSAUPD_ERRORS = DSAUPD_ERRORS DNEUPD_ERRORS = { 0: "Normal exit.", 1: "The Schur form computed by LAPACK routine dlahqr " "could not be reordered by LAPACK routine dtrsen. " "Re-enter subroutine dneupd with IPARAM(5)NCV and " "increase the size of the arrays DR and DI to have " "dimension at least dimension NCV and allocate at least NCV " "columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 2 and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: "Error return from calculation of a real Schur form. " "Informational error from LAPACK routine dlahqr .", -9: "Error return from calculation of eigenvectors. " "Informational error from LAPACK routine dtrevc.", -10: "IPARAM(7) must be 1,2,3,4.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "HOWMNY = 'S' not yet implemented", -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.", -14: "DNAUPD did not find any eigenvalues to sufficient " "accuracy.", -15: "DNEUPD got a different count of the number of converged " "Ritz values than DNAUPD got. This indicates the user " "probably made an error in passing data from DNAUPD to " "DNEUPD or that the data was modified before entering " "DNEUPD", } SNEUPD_ERRORS = DNEUPD_ERRORS.copy() SNEUPD_ERRORS[1] = ("The Schur form computed by LAPACK routine slahqr " "could not be reordered by LAPACK routine strsen . " "Re-enter subroutine dneupd with IPARAM(5)=NCV and " "increase the size of the arrays DR and DI to have " "dimension at least dimension NCV and allocate at least " "NCV columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.") SNEUPD_ERRORS[-14] = ("SNAUPD did not find any eigenvalues to sufficient " "accuracy.") SNEUPD_ERRORS[-15] = ("SNEUPD got a different count of the number of " "converged Ritz values than SNAUPD got. This indicates " "the user probably made an error in passing data from " "SNAUPD to SNEUPD or that the data was modified before " "entering SNEUPD") ZNEUPD_ERRORS = {0: "Normal exit.", 1: "The Schur form computed by LAPACK routine csheqr " "could not be reordered by LAPACK routine ztrsen. " "Re-enter subroutine zneupd with IPARAM(5)=NCV and " "increase the size of the array D to have " "dimension at least dimension NCV and allocate at least " "NCV columns for Z. NOTE: Not necessary if Z and V share " "the same space. Please notify the authors if this error " "occurs.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV-NEV >= 1 and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: "Error return from LAPACK eigenvalue calculation. " "This should never happened.", -9: "Error return from calculation of eigenvectors. " "Informational error from LAPACK routine ztrevc.", -10: "IPARAM(7) must be 1,2,3", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "HOWMNY = 'S' not yet implemented", -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.", -14: "ZNAUPD did not find any eigenvalues to sufficient " "accuracy.", -15: "ZNEUPD got a different count of the number of " "converged Ritz values than ZNAUPD got. This " "indicates the user probably made an error in passing " "data from ZNAUPD to ZNEUPD or that the data was " "modified before entering ZNEUPD"} CNEUPD_ERRORS = ZNEUPD_ERRORS.copy() CNEUPD_ERRORS[-14] = ("CNAUPD did not find any eigenvalues to sufficient " "accuracy.") CNEUPD_ERRORS[-15] = ("CNEUPD got a different count of the number of " "converged Ritz values than CNAUPD got. This indicates " "the user probably made an error in passing data from " "CNAUPD to CNEUPD or that the data was modified before " "entering CNEUPD") DSEUPD_ERRORS = { 0: "Normal exit.", -1: "N must be positive.", -2: "NEV must be positive.", -3: "NCV must be greater than NEV and less than or equal to N.", -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.", -6: "BMAT must be one of 'I' or 'G'.", -7: "Length of private work WORKL array is not sufficient.", -8: ("Error return from trid. eigenvalue calculation; " "Information error from LAPACK routine dsteqr."), -9: "Starting vector is zero.", -10: "IPARAM(7) must be 1,2,3,4,5.", -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.", -12: "NEV and WHICH = 'BE' are incompatible.", -14: "DSAUPD did not find any eigenvalues to sufficient accuracy.", -15: "HOWMNY must be one of 'A' or 'S' if RVEC = .true.", -16: "HOWMNY = 'S' not yet implemented", -17: ("DSEUPD got a different count of the number of converged " "Ritz values than DSAUPD got. This indicates the user " "probably made an error in passing data from DSAUPD to " "DSEUPD or that the data was modified before entering " "DSEUPD.") } SSEUPD_ERRORS = DSEUPD_ERRORS.copy() SSEUPD_ERRORS[-14] = ("SSAUPD did not find any eigenvalues " "to sufficient accuracy.") SSEUPD_ERRORS[-17] = ("SSEUPD got a different count of the number of " "converged " "Ritz values than SSAUPD got. This indicates the user " "probably made an error in passing data from SSAUPD to " "SSEUPD or that the data was modified before entering " "SSEUPD.") _SAUPD_ERRORS = {'d': DSAUPD_ERRORS, 's': SSAUPD_ERRORS} _NAUPD_ERRORS = {'d': DNAUPD_ERRORS, 's': SNAUPD_ERRORS, 'z': ZNAUPD_ERRORS, 'c': CNAUPD_ERRORS} _SEUPD_ERRORS = {'d': DSEUPD_ERRORS, 's': SSEUPD_ERRORS} _NEUPD_ERRORS = {'d': DNEUPD_ERRORS, 's': SNEUPD_ERRORS, 'z': ZNEUPD_ERRORS, 'c': CNEUPD_ERRORS} # accepted values of parameter WHICH in _SEUPD _SEUPD_WHICH = ['LM', 'SM', 'LA', 'SA', 'BE'] # accepted values of parameter WHICH in _NAUPD _NEUPD_WHICH = ['LM', 'SM', 'LR', 'SR', 'LI', 'SI'] class ArpackError(RuntimeError): """ ARPACK error """ def __init__(self, info, infodict=_NAUPD_ERRORS): msg = infodict.get(info, "Unknown error") RuntimeError.__init__(self, "ARPACK error %d: %s" % (info, msg)) class ArpackNoConvergence(ArpackError): """ ARPACK iteration did not converge Attributes ---------- eigenvalues : ndarray Partial result. Converged eigenvalues. eigenvectors : ndarray Partial result. Converged eigenvectors. """ def __init__(self, msg, eigenvalues, eigenvectors): ArpackError.__init__(self, -1, {-1: msg}) self.eigenvalues = eigenvalues self.eigenvectors = eigenvectors class _ArpackParams(object): def __init__(self, n, k, tp, mode=1, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): if k <= 0: raise ValueError("k must be positive, k=%d" % k) if maxiter is None: maxiter = n * 10 if maxiter <= 0: raise ValueError("maxiter must be positive, maxiter=%d" % maxiter) if tp not in 'fdFD': raise ValueError("matrix type must be 'f', 'd', 'F', or 'D'") if v0 is not None: # ARPACK overwrites its initial resid, make a copy self.resid = np.array(v0, copy=True) info = 1 else: self.resid = np.zeros(n, tp) info = 0 if sigma is None: #sigma not used self.sigma = 0 else: self.sigma = sigma if ncv is None: ncv = 2 * k + 1 ncv = min(ncv, n) self.v = np.zeros((n, ncv), tp) # holds Ritz vectors self.iparam = np.zeros(11, "int") # set solver mode and parameters ishfts = 1 self.mode = mode self.iparam[0] = ishfts self.iparam[2] = maxiter self.iparam[3] = 1 self.iparam[6] = mode self.n = n self.tol = tol self.k = k self.maxiter = maxiter self.ncv = ncv self.which = which self.tp = tp self.info = info self.converged = False self.ido = 0 def _raise_no_convergence(self): msg = "No convergence (%d iterations, %d/%d eigenvectors converged)" k_ok = self.iparam[4] num_iter = self.iparam[2] try: ev, vec = self.extract(True) except ArpackError as err: msg = "%s [%s]" % (msg, err) ev = np.zeros((0,)) vec = np.zeros((self.n, 0)) k_ok = 0 raise ArpackNoConvergence(msg % (num_iter, k_ok, self.k), ev, vec) class _SymmetricArpackParams(_ArpackParams): def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None, Minv_matvec=None, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): # The following modes are supported: # mode = 1: # Solve the standard eigenvalue problem: # A*x = lambda*x : # A - symmetric # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = None [not used] # # mode = 2: # Solve the general eigenvalue problem: # A*x = lambda*M*x # A - symmetric # M - symmetric positive definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # Minv_matvec = left multiplication by M^-1 # # mode = 3: # Solve the general eigenvalue problem in shift-invert mode: # A*x = lambda*M*x # A - symmetric # M - symmetric positive semi-definite # Arguments should be # matvec = None [not used] # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 # # mode = 4: # Solve the general eigenvalue problem in Buckling mode: # A*x = lambda*AG*x # A - symmetric positive semi-definite # AG - symmetric indefinite # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = left multiplication by [A-sigma*AG]^-1 # # mode = 5: # Solve the general eigenvalue problem in Cayley-transformed mode: # A*x = lambda*M*x # A - symmetric # M - symmetric positive semi-definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 if mode == 1: if matvec is None: raise ValueError("matvec must be specified for mode=1") if M_matvec is not None: raise ValueError("M_matvec cannot be specified for mode=1") if Minv_matvec is not None: raise ValueError("Minv_matvec cannot be specified for mode=1") self.OP = matvec self.B = lambda x: x self.bmat = 'I' elif mode == 2: if matvec is None: raise ValueError("matvec must be specified for mode=2") if M_matvec is None: raise ValueError("M_matvec must be specified for mode=2") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=2") self.OP = lambda x: Minv_matvec(matvec(x)) self.OPa = Minv_matvec self.OPb = matvec self.B = M_matvec self.bmat = 'G' elif mode == 3: if matvec is not None: raise ValueError("matvec must not be specified for mode=3") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=3") if M_matvec is None: self.OP = Minv_matvec self.OPa = Minv_matvec self.B = lambda x: x self.bmat = 'I' else: self.OP = lambda x: Minv_matvec(M_matvec(x)) self.OPa = Minv_matvec self.B = M_matvec self.bmat = 'G' elif mode == 4: if matvec is None: raise ValueError("matvec must be specified for mode=4") if M_matvec is not None: raise ValueError("M_matvec must not be specified for mode=4") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=4") self.OPa = Minv_matvec self.OP = lambda x: self.OPa(matvec(x)) self.B = matvec self.bmat = 'G' elif mode == 5: if matvec is None: raise ValueError("matvec must be specified for mode=5") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=5") self.OPa = Minv_matvec self.A_matvec = matvec if M_matvec is None: self.OP = lambda x: Minv_matvec(matvec(x) + sigma * x) self.B = lambda x: x self.bmat = 'I' else: self.OP = lambda x: Minv_matvec(matvec(x) + sigma * M_matvec(x)) self.B = M_matvec self.bmat = 'G' else: raise ValueError("mode=%i not implemented" % mode) if which not in _SEUPD_WHICH: raise ValueError("which must be one of %s" % ' '.join(_SEUPD_WHICH)) if k >= n: raise ValueError("k must be less than rank(A), k=%d" % k) _ArpackParams.__init__(self, n, k, tp, mode, sigma, ncv, v0, maxiter, which, tol) if self.ncv > n or self.ncv <= k: raise ValueError("ncv must be k<ncv<=n, ncv=%s" % self.ncv) self.workd = np.zeros(3 * n, self.tp) self.workl = np.zeros(self.ncv * (self.ncv + 8), self.tp) ltr = _type_conv[self.tp] if ltr not in ["s", "d"]: raise ValueError("Input matrix is not real-valued.") self._arpack_solver = _arpack.__dict__[ltr + 'saupd'] self._arpack_extract = _arpack.__dict__[ltr + 'seupd'] self.iterate_infodict = _SAUPD_ERRORS[ltr] self.extract_infodict = _SEUPD_ERRORS[ltr] self.ipntr = np.zeros(11, "int") def iterate(self): self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info = \ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n) yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n) if self.ido == -1: # initialization self.workd[yslice] = self.OP(self.workd[xslice]) elif self.ido == 1: # compute y = Op*x if self.mode == 1: self.workd[yslice] = self.OP(self.workd[xslice]) elif self.mode == 2: self.workd[xslice] = self.OPb(self.workd[xslice]) self.workd[yslice] = self.OPa(self.workd[xslice]) elif self.mode == 5: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) Ax = self.A_matvec(self.workd[xslice]) self.workd[yslice] = self.OPa(Ax + (self.sigma * self.workd[Bxslice])) else: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) self.workd[yslice] = self.OPa(self.workd[Bxslice]) elif self.ido == 2: self.workd[yslice] = self.B(self.workd[xslice]) elif self.ido == 3: raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0") else: self.converged = True if self.info == 0: pass elif self.info == 1: self._raise_no_convergence() else: raise ArpackError(self.info, infodict=self.iterate_infodict) def extract(self, return_eigenvectors): rvec = return_eigenvectors ierr = 0 howmny = 'A' # return all eigenvectors sselect = np.zeros(self.ncv, 'int') # unused d, z, ierr = self._arpack_extract(rvec, howmny, sselect, self.sigma, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam[0:7], self.ipntr, self.workd[0:2 * self.n], self.workl, ierr) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) k_ok = self.iparam[4] d = d[:k_ok] z = z[:, :k_ok] if return_eigenvectors: return d, z else: return d class _UnsymmetricArpackParams(_ArpackParams): def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None, Minv_matvec=None, sigma=None, ncv=None, v0=None, maxiter=None, which="LM", tol=0): # The following modes are supported: # mode = 1: # Solve the standard eigenvalue problem: # A*x = lambda*x # A - square matrix # Arguments should be # matvec = left multiplication by A # M_matvec = None [not used] # Minv_matvec = None [not used] # # mode = 2: # Solve the generalized eigenvalue problem: # A*x = lambda*M*x # A - square matrix # M - symmetric, positive semi-definite # Arguments should be # matvec = left multiplication by A # M_matvec = left multiplication by M # Minv_matvec = left multiplication by M^-1 # # mode = 3,4: # Solve the general eigenvalue problem in shift-invert mode: # A*x = lambda*M*x # A - square matrix # M - symmetric, positive semi-definite # Arguments should be # matvec = None [not used] # M_matvec = left multiplication by M # or None, if M is the identity # Minv_matvec = left multiplication by [A-sigma*M]^-1 # if A is real and mode==3, use the real part of Minv_matvec # if A is real and mode==4, use the imag part of Minv_matvec # if A is complex and mode==3, # use real and imag parts of Minv_matvec if mode == 1: if matvec is None: raise ValueError("matvec must be specified for mode=1") if M_matvec is not None: raise ValueError("M_matvec cannot be specified for mode=1") if Minv_matvec is not None: raise ValueError("Minv_matvec cannot be specified for mode=1") self.OP = matvec self.B = lambda x: x self.bmat = 'I' elif mode == 2: if matvec is None: raise ValueError("matvec must be specified for mode=2") if M_matvec is None: raise ValueError("M_matvec must be specified for mode=2") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified for mode=2") self.OP = lambda x: Minv_matvec(matvec(x)) self.OPa = Minv_matvec self.OPb = matvec self.B = M_matvec self.bmat = 'G' elif mode in (3, 4): if matvec is None: raise ValueError("matvec must be specified " "for mode in (3,4)") if Minv_matvec is None: raise ValueError("Minv_matvec must be specified " "for mode in (3,4)") self.matvec = matvec if tp in 'DF': # complex type if mode == 3: self.OPa = Minv_matvec else: raise ValueError("mode=4 invalid for complex A") else: # real type if mode == 3: self.OPa = lambda x: np.real(Minv_matvec(x)) else: self.OPa = lambda x: np.imag(Minv_matvec(x)) if M_matvec is None: self.B = lambda x: x self.bmat = 'I' self.OP = self.OPa else: self.B = M_matvec self.bmat = 'G' self.OP = lambda x: self.OPa(M_matvec(x)) else: raise ValueError("mode=%i not implemented" % mode) if which not in _NEUPD_WHICH: raise ValueError("Parameter which must be one of %s" % ' '.join(_NEUPD_WHICH)) if k >= n - 1: raise ValueError("k must be less than rank(A)-1, k=%d" % k) _ArpackParams.__init__(self, n, k, tp, mode, sigma, ncv, v0, maxiter, which, tol) if self.ncv > n or self.ncv <= k + 1: raise ValueError("ncv must be k+1<ncv<=n, ncv=%s" % self.ncv) self.workd = np.zeros(3 * n, self.tp) self.workl = np.zeros(3 * self.ncv * (self.ncv + 2), self.tp) ltr = _type_conv[self.tp] self._arpack_solver = _arpack.__dict__[ltr + 'naupd'] self._arpack_extract = _arpack.__dict__[ltr + 'neupd'] self.iterate_infodict = _NAUPD_ERRORS[ltr] self.extract_infodict = _NEUPD_ERRORS[ltr] self.ipntr = np.zeros(14, "int") if self.tp in 'FD': self.rwork = np.zeros(self.ncv, self.tp.lower()) else: self.rwork = None def iterate(self): if self.tp in 'fd': self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info =\ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) else: self.ido, self.resid, self.v, self.iparam, self.ipntr, self.info =\ self._arpack_solver(self.ido, self.bmat, self.which, self.k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.rwork, self.info) xslice = slice(self.ipntr[0] - 1, self.ipntr[0] - 1 + self.n) yslice = slice(self.ipntr[1] - 1, self.ipntr[1] - 1 + self.n) if self.ido == -1: # initialization self.workd[yslice] = self.OP(self.workd[xslice]) elif self.ido == 1: # compute y = Op*x if self.mode in (1, 2): self.workd[yslice] = self.OP(self.workd[xslice]) else: Bxslice = slice(self.ipntr[2] - 1, self.ipntr[2] - 1 + self.n) self.workd[yslice] = self.OPa(self.workd[Bxslice]) elif self.ido == 2: self.workd[yslice] = self.B(self.workd[xslice]) elif self.ido == 3: raise ValueError("ARPACK requested user shifts. Assure ISHIFT==0") else: self.converged = True if self.info == 0: pass elif self.info == 1: self._raise_no_convergence() else: raise ArpackError(self.info, infodict=self.iterate_infodict) def extract(self, return_eigenvectors): k, n = self.k, self.n ierr = 0 howmny = 'A' # return all eigenvectors sselect = np.zeros(self.ncv, 'int') # unused sigmar = np.real(self.sigma) sigmai = np.imag(self.sigma) workev = np.zeros(3 * self.ncv, self.tp) if self.tp in 'fd': dr = np.zeros(k + 1, self.tp) di = np.zeros(k + 1, self.tp) zr = np.zeros((n, k + 1), self.tp) dr, di, zr, ierr = \ self._arpack_extract( return_eigenvectors, howmny, sselect, sigmar, sigmai, workev, self.bmat, self.which, k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.info) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) nreturned = self.iparam[4] # number of good eigenvalues returned # Build complex eigenvalues from real and imaginary parts d = dr + 1.0j * di # Arrange the eigenvectors: complex eigenvectors are stored as # real,imaginary in consecutive columns z = zr.astype(self.tp.upper()) # The ARPACK nonsymmetric real and double interface (s,d)naupd # return eigenvalues and eigenvectors in real (float,double) # arrays. # Efficiency: this should check that return_eigenvectors == True # before going through this construction. if sigmai == 0: i = 0 while i <= k: # check if complex if abs(d[i].imag) != 0: # this is a complex conjugate pair with eigenvalues # in consecutive columns if i < k: z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1] z[:, i + 1] = z[:, i].conjugate() i += 1 else: #last eigenvalue is complex: the imaginary part of # the eigenvector has not been returned #this can only happen if nreturned > k, so we'll # throw out this case. nreturned -= 1 i += 1 else: # real matrix, mode 3 or 4, imag(sigma) is nonzero: # see remark 3 in <s,d>neupd.f # Build complex eigenvalues from real and imaginary parts i = 0 while i <= k: if abs(d[i].imag) == 0: d[i] = np.dot(zr[:, i], self.matvec(zr[:, i])) else: if i < k: z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1] z[:, i + 1] = z[:, i].conjugate() d[i] = ((np.dot(zr[:, i], self.matvec(zr[:, i])) + np.dot(zr[:, i + 1], self.matvec(zr[:, i + 1]))) + 1j * (np.dot(zr[:, i], self.matvec(zr[:, i + 1])) - np.dot(zr[:, i + 1], self.matvec(zr[:, i])))) d[i + 1] = d[i].conj() i += 1 else: #last eigenvalue is complex: the imaginary part of # the eigenvector has not been returned #this can only happen if nreturned > k, so we'll # throw out this case. nreturned -= 1 i += 1 # Now we have k+1 possible eigenvalues and eigenvectors # Return the ones specified by the keyword "which" if nreturned <= k: # we got less or equal as many eigenvalues we wanted d = d[:nreturned] z = z[:, :nreturned] else: # we got one extra eigenvalue (likely a cc pair, but which?) # cut at approx precision for sorting rd = np.round(d, decimals=_ndigits[self.tp]) if self.which in ['LR', 'SR']: ind = np.argsort(rd.real) elif self.which in ['LI', 'SI']: # for LI,SI ARPACK returns largest,smallest # abs(imaginary) why? ind = np.argsort(abs(rd.imag)) else: ind = np.argsort(abs(rd)) if self.which in ['LR', 'LM', 'LI']: d = d[ind[-k:]] z = z[:, ind[-k:]] if self.which in ['SR', 'SM', 'SI']: d = d[ind[:k]] z = z[:, ind[:k]] else: # complex is so much simpler... d, z, ierr =\ self._arpack_extract( return_eigenvectors, howmny, sselect, self.sigma, workev, self.bmat, self.which, k, self.tol, self.resid, self.v, self.iparam, self.ipntr, self.workd, self.workl, self.rwork, ierr) if ierr != 0: raise ArpackError(ierr, infodict=self.extract_infodict) k_ok = self.iparam[4] d = d[:k_ok] z = z[:, :k_ok] if return_eigenvectors: return d, z else: return d def _aslinearoperator_with_dtype(m): m = aslinearoperator(m) if not hasattr(m, 'dtype'): x = np.zeros(m.shape[1]) m.dtype = (m * x).dtype return m class SpLuInv(LinearOperator): """ SpLuInv: helper class to repeatedly solve M*x=b using a sparse LU-decopposition of M """ def __init__(self, M): self.M_lu = splu(M) LinearOperator.__init__(self, M.shape, self._matvec, dtype=M.dtype) self.isreal = not np.issubdtype(self.dtype, np.complexfloating) def _matvec(self, x): # careful here: splu.solve will throw away imaginary # part of x if M is real if self.isreal and np.issubdtype(x.dtype, np.complexfloating): return (self.M_lu.solve(np.real(x)) + 1j * self.M_lu.solve(np.imag(x))) else: return self.M_lu.solve(x) class LuInv(LinearOperator): """ LuInv: helper class to repeatedly solve M*x=b using an LU-decomposition of M """ def __init__(self, M): self.M_lu = lu_factor(M) LinearOperator.__init__(self, M.shape, self._matvec, dtype=M.dtype) def _matvec(self, x): return lu_solve(self.M_lu, x) class IterInv(LinearOperator): """ IterInv: helper class to repeatedly solve M*x=b using an iterative method. """ def __init__(self, M, ifunc=gmres, tol=0): if tol <= 0: # when tol=0, ARPACK uses machine tolerance as calculated # by LAPACK's _LAMCH function. We should match this tol = np.finfo(M.dtype).eps self.M = M self.ifunc = ifunc self.tol = tol if hasattr(M, 'dtype'): dtype = M.dtype else: x = np.zeros(M.shape[1]) dtype = (M * x).dtype LinearOperator.__init__(self, M.shape, self._matvec, dtype=dtype) def _matvec(self, x): b, info = self.ifunc(self.M, x, tol=self.tol) if info != 0: raise ValueError("Error in inverting M: function " "%s did not converge (info = %i)." % (self.ifunc.__name__, info)) return b class IterOpInv(LinearOperator): """ IterOpInv: helper class to repeatedly solve [A-sigma*M]*x = b using an iterative method """ def __init__(self, A, M, sigma, ifunc=gmres, tol=0): if tol <= 0: # when tol=0, ARPACK uses machine tolerance as calculated # by LAPACK's _LAMCH function. We should match this tol = np.finfo(A.dtype).eps self.A = A self.M = M self.sigma = sigma self.ifunc = ifunc self.tol = tol x = np.zeros(A.shape[1]) if M is None: dtype = self.mult_func_M_None(x).dtype self.OP = LinearOperator(self.A.shape, self.mult_func_M_None, dtype=dtype) else: dtype = self.mult_func(x).dtype self.OP = LinearOperator(self.A.shape, self.mult_func, dtype=dtype) LinearOperator.__init__(self, A.shape, self._matvec, dtype=dtype) def mult_func(self, x): return self.A.matvec(x) - self.sigma * self.M.matvec(x) def mult_func_M_None(self, x): return self.A.matvec(x) - self.sigma * x def _matvec(self, x): b, info = self.ifunc(self.OP, x, tol=self.tol) if info != 0: raise ValueError("Error in inverting [A-sigma*M]: function " "%s did not converge (info = %i)." % (self.ifunc.__name__, info)) return b def get_inv_matvec(M, symmetric=False, tol=0): if isdense(M): return LuInv(M).matvec elif isspmatrix(M): if isspmatrix_csr(M) and symmetric: M = M.T return SpLuInv(M).matvec else: return IterInv(M, tol=tol).matvec def get_OPinv_matvec(A, M, sigma, symmetric=False, tol=0): if sigma == 0: return get_inv_matvec(A, symmetric=symmetric, tol=tol) if M is None: #M is the identity matrix if isdense(A): if (np.issubdtype(A.dtype, np.complexfloating) or np.imag(sigma) == 0): A = np.copy(A) else: A = A + 0j A.flat[::A.shape[1] + 1] -= sigma return LuInv(A).matvec elif isspmatrix(A): A = A - sigma * identity(A.shape[0]) if symmetric and isspmatrix_csr(A): A = A.T return SpLuInv(A.tocsc()).matvec else: return IterOpInv(_aslinearoperator_with_dtype(A), M, sigma, tol=tol).matvec else: if ((not isdense(A) and not isspmatrix(A)) or (not isdense(M) and not isspmatrix(M))): return IterOpInv(_aslinearoperator_with_dtype(A), _aslinearoperator_with_dtype(M), sigma, tol=tol).matvec elif isdense(A) or isdense(M): return LuInv(A - sigma * M).matvec else: OP = A - sigma * M if symmetric and isspmatrix_csr(OP): OP = OP.T return SpLuInv(OP.tocsc()).matvec def _eigs(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, maxiter=None, tol=0, return_eigenvectors=True, Minv=None, OPinv=None, OPpart=None): """ Find k eigenvalues and eigenvectors of the square matrix A. Solves ``A * x[i] = w[i] * x[i]``, the standard eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i]. If M is specified, solves ``A * x[i] = w[i] * M * x[i]``, the generalized eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i] Parameters ---------- A : An N x N matrix, array, sparse matrix, or LinearOperator representing \ the operation A * x, where A is a real or complex square matrix. k : int, default 6 The number of eigenvalues and eigenvectors desired. `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. return_eigenvectors : boolean, default True Whether to return the eigenvectors along with the eigenvalues. M : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation M*x for the generalized eigenvalue problem ``A * x = w * M * x`` M must represent a real symmetric matrix. For best results, M should be of the same type as A. Additionally: * If sigma==None, M is positive definite * If sigma is specified, M is positive semi-definite If sigma==None, eigs requires an operator to compute the solution of the linear equation `M * x = b`. This is done internally via a (sparse) LU decomposition for an explicit matrix M, or via an iterative solver for a general linear operator. Alternatively, the user can supply the matrix or operator Minv, which gives x = Minv * b = M^-1 * b sigma : real or complex Find eigenvalues near sigma using shift-invert mode. This requires an operator to compute the solution of the linear system `[A - sigma * M] * x = b`, where M is the identity matrix if unspecified. This is computed internally via a (sparse) LU decomposition for explicit matrices A & M, or via an iterative solver if either A or M is a general linear operator. Alternatively, the user can supply the matrix or operator OPinv, which gives x = OPinv * b = [A - sigma * M]^-1 * b. For a real matrix A, shift-invert can either be done in imaginary mode or real mode, specified by the parameter OPpart ('r' or 'i'). Note that when sigma is specified, the keyword 'which' (below) refers to the shifted eigenvalues w'[i] where: * If A is real and OPpart == 'r' (default), w'[i] = 1/2 * [ 1/(w[i]-sigma) + 1/(w[i]-conj(sigma)) ] * If A is real and OPpart == 'i', w'[i] = 1/2i * [ 1/(w[i]-sigma) - 1/(w[i]-conj(sigma)) ] * If A is complex, w'[i] = 1/(w[i]-sigma) v0 : array Starting vector for iteration. ncv : integer The number of Lanczos vectors generated `ncv` must be greater than `k`; it is recommended that ``ncv > 2*k``. which : string ['LM' | 'SM' | 'LR' | 'SR' | 'LI' | 'SI'] Which `k` eigenvectors and eigenvalues to find: - 'LM' : largest magnitude - 'SM' : smallest magnitude - 'LR' : largest real part - 'SR' : smallest real part - 'LI' : largest imaginary part - 'SI' : smallest imaginary part When sigma != None, 'which' refers to the shifted eigenvalues w'[i] (see discussion in 'sigma', above). ARPACK is generally better at finding large values than small values. If small eigenvalues are desired, consider using shift-invert mode for better performance. maxiter : integer Maximum number of Arnoldi update iterations allowed tol : float Relative accuracy for eigenvalues (stopping criterion) The default value of 0 implies machine precision. return_eigenvectors : boolean Return eigenvectors (True) in addition to eigenvalues Minv : N x N matrix, array, sparse matrix, or linear operator See notes in M, above. OPinv : N x N matrix, array, sparse matrix, or linear operator See notes in sigma, above. OPpart : 'r' or 'i'. See notes in sigma, above Returns ------- w : array Array of k eigenvalues. v : array An array of `k` eigenvectors. ``v[:, i]`` is the eigenvector corresponding to the eigenvalue w[i]. Raises ------ ArpackNoConvergence When the requested convergence is not obtained. The currently converged eigenvalues and eigenvectors can be found as ``eigenvalues`` and ``eigenvectors`` attributes of the exception object. See Also -------- eigsh : eigenvalues and eigenvectors for symmetric matrix A svds : singular value decomposition for a matrix A Examples -------- Find 6 eigenvectors of the identity matrix: >>> from sklearn.utils.arpack import eigs >>> id = np.identity(13) >>> vals, vecs = eigs(id, k=6) >>> vals array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]) >>> vecs.shape (13, 6) Notes ----- This function is a wrapper to the ARPACK [1]_ SNEUPD, DNEUPD, CNEUPD, ZNEUPD, functions which use the Implicitly Restarted Arnoldi Method to find the eigenvalues and eigenvectors [2]_. References ---------- .. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE: Solution of Large Scale Eigenvalue Problems by Implicitly Restarted Arnoldi Methods. SIAM, Philadelphia, PA, 1998. """ if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix (shape=%s)' % (A.shape,)) if M is not None: if M.shape != A.shape: raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] if k <= 0 or k >= n: raise ValueError("k must be between 1 and rank(A)-1") if sigma is None: matvec = _aslinearoperator_with_dtype(A).matvec if OPinv is not None: raise ValueError("OPinv should not be specified " "with sigma = None.") if OPpart is not None: raise ValueError("OPpart should not be specified with " "sigma = None or complex A") if M is None: #standard eigenvalue problem mode = 1 M_matvec = None Minv_matvec = None if Minv is not None: raise ValueError("Minv should not be " "specified with M = None.") else: #general eigenvalue problem mode = 2 if Minv is None: Minv_matvec = get_inv_matvec(M, symmetric=True, tol=tol) else: Minv = _aslinearoperator_with_dtype(Minv) Minv_matvec = Minv.matvec M_matvec = _aslinearoperator_with_dtype(M).matvec else: #sigma is not None: shift-invert mode if np.issubdtype(A.dtype, np.complexfloating): if OPpart is not None: raise ValueError("OPpart should not be specified " "with sigma=None or complex A") mode = 3 elif OPpart is None or OPpart.lower() == 'r': mode = 3 elif OPpart.lower() == 'i': if np.imag(sigma) == 0: raise ValueError("OPpart cannot be 'i' if sigma is real") mode = 4 else: raise ValueError("OPpart must be one of ('r','i')") matvec = _aslinearoperator_with_dtype(A).matvec if Minv is not None: raise ValueError("Minv should not be specified when sigma is") if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=False, tol=tol) else: OPinv = _aslinearoperator_with_dtype(OPinv) Minv_matvec = OPinv.matvec if M is None: M_matvec = None else: M_matvec = _aslinearoperator_with_dtype(M).matvec params = _UnsymmetricArpackParams(n, k, A.dtype.char, matvec, mode, M_matvec, Minv_matvec, sigma, ncv, v0, maxiter, which, tol) while not params.converged: params.iterate() return params.extract(return_eigenvectors) def _eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, maxiter=None, tol=0, return_eigenvectors=True, Minv=None, OPinv=None, mode='normal'): """ Find k eigenvalues and eigenvectors of the real symmetric square matrix or complex hermitian matrix A. Solves ``A * x[i] = w[i] * x[i]``, the standard eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i]. If M is specified, solves ``A * x[i] = w[i] * M * x[i]``, the generalized eigenvalue problem for w[i] eigenvalues with corresponding eigenvectors x[i] Parameters ---------- A : An N x N matrix, array, sparse matrix, or LinearOperator representing the operation A * x, where A is a real symmetric matrix For buckling mode (see below) A must additionally be positive-definite k : integer The number of eigenvalues and eigenvectors desired. `k` must be smaller than N. It is not possible to compute all eigenvectors of a matrix. M : An N x N matrix, array, sparse matrix, or linear operator representing the operation M * x for the generalized eigenvalue problem ``A * x = w * M * x``. M must represent a real, symmetric matrix. For best results, M should be of the same type as A. Additionally: * If sigma == None, M is symmetric positive definite * If sigma is specified, M is symmetric positive semi-definite * In buckling mode, M is symmetric indefinite. If sigma == None, eigsh requires an operator to compute the solution of the linear equation `M * x = b`. This is done internally via a (sparse) LU decomposition for an explicit matrix M, or via an iterative solver for a general linear operator. Alternatively, the user can supply the matrix or operator Minv, which gives x = Minv * b = M^-1 * b sigma : real Find eigenvalues near sigma using shift-invert mode. This requires an operator to compute the solution of the linear system `[A - sigma * M] x = b`, where M is the identity matrix if unspecified. This is computed internally via a (sparse) LU decomposition for explicit matrices A & M, or via an iterative solver if either A or M is a general linear operator. Alternatively, the user can supply the matrix or operator OPinv, which gives x = OPinv * b = [A - sigma * M]^-1 * b. Note that when sigma is specified, the keyword 'which' refers to the shifted eigenvalues w'[i] where: - if mode == 'normal', w'[i] = 1 / (w[i] - sigma) - if mode == 'cayley', w'[i] = (w[i] + sigma) / (w[i] - sigma) - if mode == 'buckling', w'[i] = w[i] / (w[i] - sigma) (see further discussion in 'mode' below) v0 : array Starting vector for iteration. ncv : integer The number of Lanczos vectors generated ncv must be greater than k and smaller than n; it is recommended that ncv > 2*k which : string ['LM' | 'SM' | 'LA' | 'SA' | 'BE'] If A is a complex hermitian matrix, 'BE' is invalid. Which `k` eigenvectors and eigenvalues to find - 'LM' : Largest (in magnitude) eigenvalues - 'SM' : Smallest (in magnitude) eigenvalues - 'LA' : Largest (algebraic) eigenvalues - 'SA' : Smallest (algebraic) eigenvalues - 'BE' : Half (k/2) from each end of the spectrum When k is odd, return one more (k/2+1) from the high end When sigma != None, 'which' refers to the shifted eigenvalues w'[i] (see discussion in 'sigma', above). ARPACK is generally better at finding large values than small values. If small eigenvalues are desired, consider using shift-invert mode for better performance. maxiter : integer Maximum number of Arnoldi update iterations allowed tol : float Relative accuracy for eigenvalues (stopping criterion). The default value of 0 implies machine precision. Minv : N x N matrix, array, sparse matrix, or LinearOperator See notes in M, above OPinv : N x N matrix, array, sparse matrix, or LinearOperator See notes in sigma, above. return_eigenvectors : boolean Return eigenvectors (True) in addition to eigenvalues mode : string ['normal' | 'buckling' | 'cayley'] Specify strategy to use for shift-invert mode. This argument applies only for real-valued A and sigma != None. For shift-invert mode, ARPACK internally solves the eigenvalue problem ``OP * x'[i] = w'[i] * B * x'[i]`` and transforms the resulting Ritz vectors x'[i] and Ritz values w'[i] into the desired eigenvectors and eigenvalues of the problem ``A * x[i] = w[i] * M * x[i]``. The modes are as follows: - 'normal' : OP = [A - sigma * M]^-1 * M B = M w'[i] = 1 / (w[i] - sigma) - 'buckling' : OP = [A - sigma * M]^-1 * A B = A w'[i] = w[i] / (w[i] - sigma) - 'cayley' : OP = [A - sigma * M]^-1 * [A + sigma * M] B = M w'[i] = (w[i] + sigma) / (w[i] - sigma) The choice of mode will affect which eigenvalues are selected by the keyword 'which', and can also impact the stability of convergence (see [2] for a discussion) Returns ------- w : array Array of k eigenvalues v : array An array of k eigenvectors The v[i] is the eigenvector corresponding to the eigenvector w[i] Raises ------ ArpackNoConvergence When the requested convergence is not obtained. The currently converged eigenvalues and eigenvectors can be found as ``eigenvalues`` and ``eigenvectors`` attributes of the exception object. See Also -------- eigs : eigenvalues and eigenvectors for a general (nonsymmetric) matrix A svds : singular value decomposition for a matrix A Notes ----- This function is a wrapper to the ARPACK [1]_ SSEUPD and DSEUPD functions which use the Implicitly Restarted Lanczos Method to find the eigenvalues and eigenvectors [2]_. Examples -------- >>> from sklearn.utils.arpack import eigsh >>> id = np.identity(13) >>> vals, vecs = eigsh(id, k=6) >>> vals # doctest: +SKIP array([ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]) >>> print(vecs.shape) (13, 6) References ---------- .. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/ .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang, ARPACK USERS GUIDE: Solution of Large Scale Eigenvalue Problems by Implicitly Restarted Arnoldi Methods. SIAM, Philadelphia, PA, 1998. """ # complex hermitian matrices should be solved with eigs if np.issubdtype(A.dtype, np.complexfloating): if mode != 'normal': raise ValueError("mode=%s cannot be used with " "complex matrix A" % mode) if which == 'BE': raise ValueError("which='BE' cannot be used with complex matrix A") elif which == 'LA': which = 'LR' elif which == 'SA': which = 'SR' ret = eigs(A, k, M=M, sigma=sigma, which=which, v0=v0, ncv=ncv, maxiter=maxiter, tol=tol, return_eigenvectors=return_eigenvectors, Minv=Minv, OPinv=OPinv) if return_eigenvectors: return ret[0].real, ret[1] else: return ret.real if A.shape[0] != A.shape[1]: raise ValueError('expected square matrix (shape=%s)' % (A.shape,)) if M is not None: if M.shape != A.shape: raise ValueError('wrong M dimensions %s, should be %s' % (M.shape, A.shape)) if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower(): warnings.warn('M does not have the same type precision as A. ' 'This may adversely affect ARPACK convergence') n = A.shape[0] if k <= 0 or k >= n: raise ValueError("k must be between 1 and rank(A)-1") if sigma is None: A = _aslinearoperator_with_dtype(A) matvec = A.matvec if OPinv is not None: raise ValueError("OPinv should not be specified " "with sigma = None.") if M is None: #standard eigenvalue problem mode = 1 M_matvec = None Minv_matvec = None if Minv is not None: raise ValueError("Minv should not be " "specified with M = None.") else: #general eigenvalue problem mode = 2 if Minv is None: Minv_matvec = get_inv_matvec(M, symmetric=True, tol=tol) else: Minv = _aslinearoperator_with_dtype(Minv) Minv_matvec = Minv.matvec M_matvec = _aslinearoperator_with_dtype(M).matvec else: # sigma is not None: shift-invert mode if Minv is not None: raise ValueError("Minv should not be specified when sigma is") # normal mode if mode == 'normal': mode = 3 matvec = None if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: OPinv = _aslinearoperator_with_dtype(OPinv) Minv_matvec = OPinv.matvec if M is None: M_matvec = None else: M = _aslinearoperator_with_dtype(M) M_matvec = M.matvec # buckling mode elif mode == 'buckling': mode = 4 if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: Minv_matvec = _aslinearoperator_with_dtype(OPinv).matvec matvec = _aslinearoperator_with_dtype(A).matvec M_matvec = None # cayley-transform mode elif mode == 'cayley': mode = 5 matvec = _aslinearoperator_with_dtype(A).matvec if OPinv is None: Minv_matvec = get_OPinv_matvec(A, M, sigma, symmetric=True, tol=tol) else: Minv_matvec = _aslinearoperator_with_dtype(OPinv).matvec if M is None: M_matvec = None else: M_matvec = _aslinearoperator_with_dtype(M).matvec # unrecognized mode else: raise ValueError("unrecognized mode '%s'" % mode) params = _SymmetricArpackParams(n, k, A.dtype.char, matvec, mode, M_matvec, Minv_matvec, sigma, ncv, v0, maxiter, which, tol) while not params.converged: params.iterate() return params.extract(return_eigenvectors) def _svds(A, k=6, ncv=None, tol=0): """Compute k singular values/vectors for a sparse matrix using ARPACK. Parameters ---------- A : sparse matrix Array to compute the SVD on k : int, optional Number of singular values and vectors to compute. ncv : integer The number of Lanczos vectors generated ncv must be greater than k+1 and smaller than n; it is recommended that ncv > 2*k tol : float, optional Tolerance for singular values. Zero (default) means machine precision. Notes ----- This is a naive implementation using an eigensolver on A.H * A or A * A.H, depending on which one is more efficient. """ if not (isinstance(A, np.ndarray) or isspmatrix(A)): A = np.asarray(A) n, m = A.shape if np.issubdtype(A.dtype, np.complexfloating): herm = lambda x: x.T.conjugate() eigensolver = eigs else: herm = lambda x: x.T eigensolver = eigsh if n > m: X = A XH = herm(A) else: XH = A X = herm(A) if hasattr(XH, 'dot'): def matvec_XH_X(x): return XH.dot(X.dot(x)) else: def matvec_XH_X(x): return np.dot(XH, np.dot(X, x)) XH_X = LinearOperator(matvec=matvec_XH_X, dtype=X.dtype, shape=(X.shape[1], X.shape[1])) # Ignore deprecation warnings here: dot on matrices is deprecated, # but this code is a backport anyhow with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) eigvals, eigvec = eigensolver(XH_X, k=k, tol=tol ** 2) s = np.sqrt(eigvals) if n > m: v = eigvec if hasattr(X, 'dot'): u = X.dot(v) / s else: u = np.dot(X, v) / s vh = herm(v) else: u = eigvec if hasattr(X, 'dot'): vh = herm(X.dot(u) / s) else: vh = herm(np.dot(X, u) / s) return u, s, vh # check if backport is actually needed: if scipy.version.version >= LooseVersion('0.10'): from scipy.sparse.linalg import eigs, eigsh, svds else: eigs, eigsh, svds = _eigs, _eigsh, _svds
bsd-3-clause
jjx02230808/project0223
examples/decomposition/plot_pca_3d.py
354
2432
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= Principal components analysis (PCA) ========================================================= These figures aid in illustrating how a point cloud can be very flat in one direction--which is where PCA comes in to choose a direction that is not flat. """ print(__doc__) # Authors: Gael Varoquaux # Jaques Grobler # Kevin Hughes # License: BSD 3 clause from sklearn.decomposition import PCA from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt from scipy import stats ############################################################################### # Create the data e = np.exp(1) np.random.seed(4) def pdf(x): return 0.5 * (stats.norm(scale=0.25 / e).pdf(x) + stats.norm(scale=4 / e).pdf(x)) y = np.random.normal(scale=0.5, size=(30000)) x = np.random.normal(scale=0.5, size=(30000)) z = np.random.normal(scale=0.1, size=len(x)) density = pdf(x) * pdf(y) pdf_z = pdf(5 * z) density *= pdf_z a = x + y b = 2 * y c = a - b + z norm = np.sqrt(a.var() + b.var()) a /= norm b /= norm ############################################################################### # Plot the figures def plot_figs(fig_num, elev, azim): fig = plt.figure(fig_num, figsize=(4, 3)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=elev, azim=azim) ax.scatter(a[::10], b[::10], c[::10], c=density[::10], marker='+', alpha=.4) Y = np.c_[a, b, c] # Using SciPy's SVD, this would be: # _, pca_score, V = scipy.linalg.svd(Y, full_matrices=False) pca = PCA(n_components=3) pca.fit(Y) pca_score = pca.explained_variance_ratio_ V = pca.components_ x_pca_axis, y_pca_axis, z_pca_axis = V.T * pca_score / pca_score.min() x_pca_axis, y_pca_axis, z_pca_axis = 3 * V.T x_pca_plane = np.r_[x_pca_axis[:2], - x_pca_axis[1::-1]] y_pca_plane = np.r_[y_pca_axis[:2], - y_pca_axis[1::-1]] z_pca_plane = np.r_[z_pca_axis[:2], - z_pca_axis[1::-1]] x_pca_plane.shape = (2, 2) y_pca_plane.shape = (2, 2) z_pca_plane.shape = (2, 2) ax.plot_surface(x_pca_plane, y_pca_plane, z_pca_plane) ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) elev = -40 azim = -80 plot_figs(1, elev, azim) elev = 30 azim = 20 plot_figs(2, elev, azim) plt.show()
bsd-3-clause
kyoheiotsuka/LDA
lda.py
2
7617
# -*- coding: utf-8 -*- import numpy as np import scipy.special import time, cPickle import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable class LDA: # variational implimentation of smoothed LDA def __init__(self): # do nothing particularly pass def setData(self,data): # data is required to be given in a two dimensional numpy array (nDocuments,nVocabulary) # with each element representing the number of times observed # set parameters self.data = data self.nDocuments = data.shape[0] self.nVocabulary = data.shape[1] def solve(self,nTopics,epsilon=1e-3,alpha=1.0,beta=0.01): # set additional parameters self.nTopics = nTopics self.epsilon = epsilon # prior distribution for alpha and beta self.alpha = np.full(self.nTopics,alpha,dtype=np.float64) self.beta = np.full(self.nVocabulary,beta,dtype=np.float64) # define q(theta) self.qTheta = np.empty((self.nDocuments,self.nTopics),dtype=np.float64) self.qThetaNew = np.empty((self.nDocuments,self.nTopics),dtype=np.float64) # define q(phi) self.qPhi = np.empty((self.nTopics,self.nVocabulary),dtype=np.float64) # define and initialize q(z) self.qZ = np.random.rand(self.nDocuments,self.nVocabulary,self.nTopics) for i in range(self.qZ.shape[0]): self.qZ[i] /= self.qZ[i].sum(axis=1).reshape((self.qZ[i].shape[0],1)) # start solving using variational Bayes nIteration = 0 while(1): deltaMax = 0.0 tic = time.clock() # update qPhi qPhi = self.qPhi[:,:] qPhi[:] = np.tile(self.beta.reshape((1,self.nVocabulary)),(self.nTopics,1)) for d in range(self.nDocuments): doc = self.data[d,:] qZ = self.qZ[d,:,:] qPhi += (qZ[:,:] * doc.reshape((doc.shape[0],1))).T phiExpLog = scipy.special.psi(self.qPhi[:,:]) phiExpLog -= np.tile(scipy.special.psi((self.qPhi[:,:]).sum(axis=1)).reshape((self.nTopics,1)),(1,self.nVocabulary)) # iterate throught all documents for d in range(self.nDocuments): doc = self.data[d,:] qZ = self.qZ[d,:,:] qTheta = self.qTheta[d,:] qThetaNew = self.qThetaNew[d,:] # update qTheta if nIteration == 0: qTheta[:] = self.alpha qTheta += (qZ * doc.reshape((qZ.shape[0],1))).sum(axis=0) else: qTheta[:] = qThetaNew thetaExpLog = scipy.special.psi(qTheta) thetaExpLog -= scipy.special.psi((qTheta).sum()) # update qZ qZ[:,:] = np.exp(phiExpLog.T+np.tile(thetaExpLog.reshape((1,self.nTopics)),(self.nVocabulary,1))) qZ /= qZ.sum(axis=1).reshape((self.nVocabulary,1)) # measure amount of change qThetaNew[:] = self.alpha qThetaNew += (qZ * doc.reshape((qZ.shape[0],1))).sum(axis=0) delta = np.abs(qTheta-qThetaNew).sum()/doc.sum() deltaMax = max(deltaMax,delta) # break if converged if deltaMax<self.epsilon: break # display information toc = time.clock() self.heatmap(nIteration) print "nIteration=%d, delta=%f, time=%.5f"%(nIteration,deltaMax,toc-tic) nIteration += 1 def predict(self,dataPredict): # dataPredict is required to be given in a two dimensional numpy array (nDocuments,nVocabulary) # with each element representing the number of times observed # set additional parameters nDataPredict = dataPredict.shape[0] # utilize topic information with training data phiExpLog = scipy.special.psi(self.qPhi[:,:]) phiExpLog -= np.tile(scipy.special.psi((self.qPhi[:,:]).sum(axis=1)).reshape((self.nTopics,1)),(1,self.nVocabulary)) # define q(theta) for unseen data qThetaPredict = np.empty((nDataPredict,self.nTopics),dtype=np.float32) qThetaPredictNew = np.empty((nDataPredict,self.nTopics),dtype=np.float32) # define and initialize q(z) for unseen data qZPredict = np.random.rand(nDataPredict,self.nVocabulary,self.nTopics) for i in range(qZPredict.shape[0]): qZPredict[i] /= qZPredict[i].sum(axis=1).reshape((qZPredict[i].shape[0],1)) # start prediction nIteration = 0 while(1): deltaMax = 0.0 tic = time.clock() # iterate over all documents for d in range(nDataPredict): doc = dataPredict[d,:] qZ = qZPredict[d,:,:] qTheta = qThetaPredict[d,:] qThetaNew = qThetaPredictNew[d,:] # update qTheta for unseen data if nIteration == 0: qTheta[:] = self.alpha qTheta += (qZ * doc.reshape((qZ.shape[0],1))).sum(axis=0) else: qTheta[:] = qThetaNew thetaExpLog = scipy.special.psi(qTheta) thetaExpLog -= scipy.special.psi((qTheta).sum()) # update qZ for unseen data qZ[:,:] = np.exp(phiExpLog.T+np.tile(thetaExpLog.reshape((1,self.nTopics)),(self.nVocabulary,1))) qZ /= qZ.sum(axis=1).reshape((self.nVocabulary,1)) # measure amount of change qThetaNew[:] = self.alpha qThetaNew += (qZ * doc.reshape((qZ.shape[0],1))).sum(axis=0) delta = np.abs(qTheta-qThetaNew).sum()/doc.sum() deltaMax = max(deltaMax,delta) # break if converged if deltaMax<self.epsilon: break # display information toc = time.clock() print (nIteration,deltaMax,toc-tic) nIteration += 1 return qThetaPredict def heatmap(self,nIteration): # save heatmap image of topic-word distribution topicWordDistribution = self.qPhi/self.qPhi.sum(axis=1).reshape((self.nTopics,1)) plt.clf() fig,ax = plt.subplots() # visualize topic-word distribution X,Y = np.meshgrid(np.arange(topicWordDistribution.shape[1]+1),np.arange(topicWordDistribution.shape[0]+1)) image = ax.pcolormesh(X,Y,topicWordDistribution) plt.xlim(0,topicWordDistribution.shape[1]) plt.xlabel("Vocabulary ID") plt.ylabel("Topic ID") # show colorbar divider = make_axes_locatable(ax) ax_cb = divider.new_horizontal(size="2%",pad=0.05) fig.add_axes(ax_cb) plt.colorbar(image,cax=ax_cb) figure = plt.gcf() figure.set_size_inches(16,12) plt.tight_layout() # save image as a file plt.savefig("visualization/nIteration_%d.jpg"%nIteration,dpi=100) plt.close() def save(self,name): # save object as a file with open(name,"wb") as output: cPickle.dump(self.__dict__,output,protocol=cPickle.HIGHEST_PROTOCOL) def load(self,name): # load object from a file with open(name,"rb") as input: self.__dict__.update(cPickle.load(input))
mit
bzero/statsmodels
examples/python/quantile_regression.py
30
3970
## Quantile regression # # This example page shows how to use ``statsmodels``' ``QuantReg`` class to replicate parts of the analysis published in # # * Koenker, Roger and Kevin F. Hallock. "Quantile Regressioin". Journal of Economic Perspectives, Volume 15, Number 4, Fall 2001, Pages 143–156 # # We are interested in the relationship between income and expenditures on food for a sample of working class Belgian households in 1857 (the Engel data). # # ## Setup # # We first need to load some modules and to retrieve the data. Conveniently, the Engel dataset is shipped with ``statsmodels``. from __future__ import print_function import patsy import numpy as np import pandas as pd import statsmodels.api as sm import statsmodels.formula.api as smf import matplotlib.pyplot as plt from statsmodels.regression.quantile_regression import QuantReg data = sm.datasets.engel.load_pandas().data data.head() # ## Least Absolute Deviation # # The LAD model is a special case of quantile regression where q=0.5 mod = smf.quantreg('foodexp ~ income', data) res = mod.fit(q=.5) print(res.summary()) # ## Visualizing the results # # We estimate the quantile regression model for many quantiles between .05 and .95, and compare best fit line from each of these models to Ordinary Least Squares results. # ### Prepare data for plotting # # For convenience, we place the quantile regression results in a Pandas DataFrame, and the OLS results in a dictionary. quantiles = np.arange(.05, .96, .1) def fit_model(q): res = mod.fit(q=q) return [q, res.params['Intercept'], res.params['income']] + res.conf_int().ix['income'].tolist() models = [fit_model(x) for x in quantiles] models = pd.DataFrame(models, columns=['q', 'a', 'b','lb','ub']) ols = smf.ols('foodexp ~ income', data).fit() ols_ci = ols.conf_int().ix['income'].tolist() ols = dict(a = ols.params['Intercept'], b = ols.params['income'], lb = ols_ci[0], ub = ols_ci[1]) print(models) print(ols) # ### First plot # # This plot compares best fit lines for 10 quantile regression models to the least squares fit. As Koenker and Hallock (2001) point out, we see that: # # 1. Food expenditure increases with income # 2. The *dispersion* of food expenditure increases with income # 3. The least squares estimates fit low income observations quite poorly (i.e. the OLS line passes over most low income households) x = np.arange(data.income.min(), data.income.max(), 50) get_y = lambda a, b: a + b * x for i in range(models.shape[0]): y = get_y(models.a[i], models.b[i]) plt.plot(x, y, linestyle='dotted', color='grey') y = get_y(ols['a'], ols['b']) plt.plot(x, y, color='red', label='OLS') plt.scatter(data.income, data.foodexp, alpha=.2) plt.xlim((240, 3000)) plt.ylim((240, 2000)) plt.legend() plt.xlabel('Income') plt.ylabel('Food expenditure') plt.show() # ### Second plot # # The dotted black lines form 95% point-wise confidence band around 10 quantile regression estimates (solid black line). The red lines represent OLS regression results along with their 95% confindence interval. # # In most cases, the quantile regression point estimates lie outside the OLS confidence interval, which suggests that the effect of income on food expenditure may not be constant across the distribution. from matplotlib import rc rc('text', usetex=True) n = models.shape[0] p1 = plt.plot(models.q, models.b, color='black', label='Quantile Reg.') p2 = plt.plot(models.q, models.ub, linestyle='dotted', color='black') p3 = plt.plot(models.q, models.lb, linestyle='dotted', color='black') p4 = plt.plot(models.q, [ols['b']] * n, color='red', label='OLS') p5 = plt.plot(models.q, [ols['lb']] * n, linestyle='dotted', color='red') p6 = plt.plot(models.q, [ols['ub']] * n, linestyle='dotted', color='red') plt.ylabel(r'\beta_\mbox{income}') plt.xlabel('Quantiles of the conditional food expenditure distribution') plt.legend() plt.show()
bsd-3-clause
lucabaldini/pyxpe
pyxpe/recon/event.py
1
8144
#!/usr/bin/env python # Copyright (C) 2007--2016 the X-ray Polarimetry Explorer (XPE) team. # # For the license terms see the file LICENSE, distributed along with this # software. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 2 of the License, or (at your # option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from pyxpe.utils.logging_ import logger import struct import numpy import matplotlib import matplotlib.pyplot as plt from pyxpe.recon.xpol import xpeHexagonalMatrix, pixel2world # python2/3 compatibility fix try: xrange except NameError: xrange = range class xpeAnsiColors: HEADER = '\033[95m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class xpeEventBase: """ """ pass class xpeEventFullFrame(xpeEventBase): """Basic class representing an event aquired in full-frame mode. """ def __init__(self, adc_values): """Constructor. """ self.adc_values = adc_values def size(self): """Return the total number of bytes in the event. """ return 2*self.num_pixels() def num_columns(self): """Return the number of columns. """ return 300 def num_rows(self): """Return the number of rows. """ return 352 def num_pixels(self): """Return the total number of pixels in the window. """ return self.num_rows()*self.num_columns() def adc_value(self, col, row): """Return the pulse height for a given pixel in the window. """ return self.adc_values[col, row] def highest_pixel(self): """Return the coordinats of the pixel with the maximum value of ADC counts. """ return numpy.unravel_index(numpy.argmax(self.adc_values), self.adc_values.shape) def highest_adc_value(self): """Return the maximum value of ADC counts for the pixels in the event. """ return self.adc_values.max() def draw(self, show = True): """ """ im = plt.imshow(self.adc_values.T, cmap='hot', interpolation='none') plt.colorbar(im, orientation='horizontal') if show: plt.show() class xpeEventWindowed(xpeEventBase): """Basic class representing an event aquired in windowed mode. """ HEADER_MARKER = 65535 HEADER_LENGTH = 20 def __init__(self, xmin, xmax, ymin, ymax, buffer_id, t1, t2, s1, s2, adc_values): """Constructor. """ self.xmin = xmin self.xmax = xmax self.ymin = ymin self.ymax = ymax self.buffer_id = buffer_id self.microseconds = (t1 + t2*65534)*0.8 self.adc_values = adc_values def size(self): """Return the total number of bytes in the event. """ return self.HEADER_LENGTH + 2*self.num_pixels() def num_columns(self): """Return the number of columns. """ return (self.xmax - self.xmin + 1) def num_rows(self): """Return the number of rows. """ return (self.ymax - self.ymin + 1) def num_pixels(self): """Return the total number of pixels in the window. """ return self.num_rows()*self.num_columns() def adc_value(self, col, row): """Return the pulse height for a given pixel in the window. """ return self.adc_values[col, row] def highest_pixel(self): """Return the coordinats of the pixel with the maximum value of ADC counts. """ return numpy.unravel_index(numpy.argmax(self.adc_values), self.adc_values.shape) def highest_adc_value(self): """Return the maximum value of ADC counts for the pixels in the event. """ return self.adc_values.max() def pulse_height(self, zero_suppression): """Return the total pulse height for the event, i.e., the raw sum of all the ADC values above the zero-suppression threshold. Args ---- zero_suppression : int The zero-suppression threshold. """ return self.adc_values[self.adc_values > zero_suppression].sum() def hit_data(self, zero_suppression, coordinate_system): """Return three arrays (of the same length) containing the x and y coordinates and the charge in ADC counts for all the pixels in the event above the zero-suppression threshold. Args ---- zero_suppression : int The zero-suppression threshold. coordinate_system : str The coordinate system to be used. """ _mask = self.adc_values > zero_suppression adc_values = self.adc_values[_mask] col, row = numpy.where(_mask) x, y = pixel2world(self.xmin + col, self.ymin + row, coordinate_system) return x, y, adc_values def ascii(self, zero_suppression=9, max_threshold=0.75, width=4, color=True): """Return a pretty-printed ASCII representation of the event. """ _fmt = '%%%dd' % width _max = self.highest_adc_value() text = '' text += ' '*(2*width + 2) for col in xrange(self.num_columns()): text += _fmt % (col + self.xmin) text += '\n' text += ' '*(2*width + 2) for col in xrange(self.num_columns()): text += _fmt % col text += '\n' text += ' '*(2*width + 1) + '+' + '-'*(width*self.num_columns()) + '\n' for row in xrange(self.num_rows()): text += (_fmt % (row + self.ymin)) + ' ' + (_fmt % row) + '|' for col in xrange(self.num_columns()): adc = self.adc_value(col, row) pix = _fmt % adc if color and adc == _max: pix = '%s%s%s' %\ (xpeAnsiColors.RED, pix, xpeAnsiColors.ENDC) elif color and adc >= max_threshold*_max: pix = '%s%s%s' %\ (xpeAnsiColors.YELLOW, pix, xpeAnsiColors.ENDC) elif color and adc > zero_suppression: pix = '%s%s%s' %\ (xpeAnsiColors.GREEN, pix, xpeAnsiColors.ENDC) text += pix text += '\n%s|\n' % (' '*(2*width + 1)) return text def draw_ascii(self, zero_suppression=9): """Print the ASCII representation of the event. """ print(self.ascii(zero_suppression)) def window_matrix(self): """Return an xpeHexagonalMatrix object corresponding to the readout window. """ return xpeHexagonalMatrix(self.num_columns(), self.num_rows(), self.xmin, self.ymin) def draw(self, zero_suppression=9, grids=True, show=True): """ """ matrix = self.window_matrix() matrix.draw(self.adc_values, zero_suppression, grids=grids, show=False) if show: plt.show() def __str__(self): """String representation. """ text = 'buffer %5d, w(%3d, %3d)--(%3d, %3d), %d px, t = %d us' %\ (self.buffer_id, self.xmin, self.ymin, self.xmax, self.ymax, self.num_pixels(), self.microseconds) return text
gpl-3.0
Clyde-fare/scikit-learn
examples/semi_supervised/plot_label_propagation_digits_active_learning.py
294
3417
""" ======================================== Label Propagation digits active learning ======================================== Demonstrates an active learning technique to learn handwritten digits using label propagation. We start by training a label propagation model with only 10 labeled points, then we select the top five most uncertain points to label. Next, we train with 15 labeled points (original 10 + 5 new ones). We repeat this process four times to have a model trained with 30 labeled examples. A plot will appear showing the top 5 most uncertain digits for each iteration of training. These may or may not contain mistakes, but we will train the next model with their true labels. """ print(__doc__) # Authors: Clay Woolam <clay@woolam.org> # Licence: BSD import numpy as np import matplotlib.pyplot as plt from scipy import stats from sklearn import datasets from sklearn.semi_supervised import label_propagation from sklearn.metrics import classification_report, confusion_matrix digits = datasets.load_digits() rng = np.random.RandomState(0) indices = np.arange(len(digits.data)) rng.shuffle(indices) X = digits.data[indices[:330]] y = digits.target[indices[:330]] images = digits.images[indices[:330]] n_total_samples = len(y) n_labeled_points = 10 unlabeled_indices = np.arange(n_total_samples)[n_labeled_points:] f = plt.figure() for i in range(5): y_train = np.copy(y) y_train[unlabeled_indices] = -1 lp_model = label_propagation.LabelSpreading(gamma=0.25, max_iter=5) lp_model.fit(X, y_train) predicted_labels = lp_model.transduction_[unlabeled_indices] true_labels = y[unlabeled_indices] cm = confusion_matrix(true_labels, predicted_labels, labels=lp_model.classes_) print('Iteration %i %s' % (i, 70 * '_')) print("Label Spreading model: %d labeled & %d unlabeled (%d total)" % (n_labeled_points, n_total_samples - n_labeled_points, n_total_samples)) print(classification_report(true_labels, predicted_labels)) print("Confusion matrix") print(cm) # compute the entropies of transduced label distributions pred_entropies = stats.distributions.entropy( lp_model.label_distributions_.T) # select five digit examples that the classifier is most uncertain about uncertainty_index = uncertainty_index = np.argsort(pred_entropies)[-5:] # keep track of indices that we get labels for delete_indices = np.array([]) f.text(.05, (1 - (i + 1) * .183), "model %d\n\nfit with\n%d labels" % ((i + 1), i * 5 + 10), size=10) for index, image_index in enumerate(uncertainty_index): image = images[image_index] sub = f.add_subplot(5, 5, index + 1 + (5 * i)) sub.imshow(image, cmap=plt.cm.gray_r) sub.set_title('predict: %i\ntrue: %i' % ( lp_model.transduction_[image_index], y[image_index]), size=10) sub.axis('off') # labeling 5 points, remote from labeled set delete_index, = np.where(unlabeled_indices == image_index) delete_indices = np.concatenate((delete_indices, delete_index)) unlabeled_indices = np.delete(unlabeled_indices, delete_indices) n_labeled_points += 5 f.suptitle("Active learning with Label Propagation.\nRows show 5 most " "uncertain labels to learn with the next model.") plt.subplots_adjust(0.12, 0.03, 0.9, 0.8, 0.2, 0.45) plt.show()
bsd-3-clause
EarToEarOak/RTLSDR-Scanner
rtlsdr_scanner/dialogs_help.py
1
5039
# # rtlsdr_scan # # http://eartoearoak.com/software/rtlsdr-scanner # # Copyright 2012 - 2015 Al Brown # # A frequency scanning GUI for the OsmoSDR rtl-sdr library at # http://sdr.osmocom.org/trac/wiki/rtl-sdr # # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import multiprocessing import platform import sys from PIL import Image import matplotlib import numpy import serial import wx from rtlsdr_scanner.utils_wx import load_bitmap from rtlsdr_scanner.version import VERSION class DialogSysInfo(wx.Dialog): def __init__(self, parent): wx.Dialog.__init__(self, parent=parent, title="System Information") textVersions = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_DONTWRAP | wx.TE_NO_VSCROLL) buttonOk = wx.Button(self, wx.ID_OK) self.__populate_versions(textVersions) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(textVersions, 1, flag=wx.ALL, border=10) sizer.Add(buttonOk, 0, flag=wx.ALL | wx.ALIGN_RIGHT, border=10) self.SetSizerAndFit(sizer) self.Centre() def __populate_versions(self, control): imageType = 'Pillow' try: imageVer = Image.PILLOW_VERSION except AttributeError: imageType = 'PIL' imageVer = Image.VERSION visvisVer = 'Not installed' if not hasattr(sys, 'frozen'): try: import visvis as vv visvisVer = vv.__version__ except ImportError: pass versions = ('Hardware:\n' '\tProcessor: {}, {} cores\n\n' 'Software:\n' '\tOS: {}, {}\n' '\tPython: {}\n' '\tmatplotlib: {}\n' '\tNumPy: {}\n' '\t{}: {}\n' '\tpySerial: {}\n' '\tvisvis: {}\n' '\twxPython: {}\n' ).format(platform.processor(), multiprocessing.cpu_count(), platform.platform(), platform.machine(), platform.python_version(), matplotlib.__version__, numpy.version.version, imageType, imageVer, serial.VERSION, visvisVer, wx.version()) control.SetValue(versions) dc = wx.WindowDC(control) extent = list(dc.GetMultiLineTextExtent(versions, control.GetFont())) extent[0] += wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X) * 2 extent[1] += wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y) * 2 control.SetMinSize((extent[0], extent[1])) self.Layout() class DialogAbout(wx.Dialog): def __init__(self, parent): wx.Dialog.__init__(self, parent=parent, title="About") bitmapIcon = wx.StaticBitmap(self, bitmap=load_bitmap('icon')) textAbout = wx.StaticText(self, label="A simple spectrum analyser for " "scanning\n with a RTL-SDR compatible USB " "device", style=wx.ALIGN_CENTRE) textLink = wx.HyperlinkCtrl(self, wx.ID_ANY, label="http://eartoearoak.com/software/rtlsdr-scanner", url="http://eartoearoak.com/software/rtlsdr-scanner") textVersion = wx.StaticText(self, label='v' + '.'.join([str(x) for x in VERSION])) buttonOk = wx.Button(self, wx.ID_OK) grid = wx.GridBagSizer(10, 10) grid.Add(bitmapIcon, pos=(0, 0), span=(3, 1), flag=wx.ALIGN_LEFT | wx.ALL, border=10) grid.Add(textAbout, pos=(0, 1), span=(1, 2), flag=wx.ALIGN_CENTRE | wx.ALL, border=10) grid.Add(textLink, pos=(1, 1), span=(1, 2), flag=wx.ALIGN_CENTRE | wx.ALL, border=10) grid.Add(textVersion, pos=(2, 1), span=(1, 2), flag=wx.ALIGN_CENTRE | wx.ALL, border=10) grid.Add(buttonOk, pos=(3, 2), flag=wx.ALIGN_RIGHT | wx.ALL, border=10) self.SetSizerAndFit(grid) self.Centre() if __name__ == '__main__': print 'Please run rtlsdr_scan.py' exit(1)
gpl-3.0
dhruv13J/scikit-learn
sklearn/svm/tests/test_sparse.py
95
12156
from nose.tools import assert_raises, assert_true, assert_false import numpy as np from scipy import sparse from numpy.testing import (assert_array_almost_equal, assert_array_equal, assert_equal) from sklearn import datasets, svm, linear_model, base from sklearn.datasets import make_classification, load_digits, make_blobs from sklearn.svm.tests import test_svm from sklearn.utils import ConvergenceWarning from sklearn.utils.extmath import safe_sparse_dot from sklearn.utils.testing import assert_warns, assert_raise_message # test sample 1 X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]) X_sp = sparse.lil_matrix(X) Y = [1, 1, 1, 2, 2, 2] T = np.array([[-1, -1], [2, 2], [3, 2]]) true_result = [1, 2, 2] # test sample 2 X2 = np.array([[0, 0, 0], [1, 1, 1], [2, 0, 0, ], [0, 0, 2], [3, 3, 3]]) X2_sp = sparse.dok_matrix(X2) Y2 = [1, 2, 2, 2, 3] T2 = np.array([[-1, -1, -1], [1, 1, 1], [2, 2, 2]]) true_result2 = [1, 2, 3] iris = datasets.load_iris() # permute rng = np.random.RandomState(0) perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] # sparsify iris.data = sparse.csr_matrix(iris.data) def check_svm_model_equal(dense_svm, sparse_svm, X_train, y_train, X_test): dense_svm.fit(X_train.toarray(), y_train) if sparse.isspmatrix(X_test): X_test_dense = X_test.toarray() else: X_test_dense = X_test sparse_svm.fit(X_train, y_train) assert_true(sparse.issparse(sparse_svm.support_vectors_)) assert_true(sparse.issparse(sparse_svm.dual_coef_)) assert_array_almost_equal(dense_svm.support_vectors_, sparse_svm.support_vectors_.toarray()) assert_array_almost_equal(dense_svm.dual_coef_, sparse_svm.dual_coef_.toarray()) if dense_svm.kernel == "linear": assert_true(sparse.issparse(sparse_svm.coef_)) assert_array_almost_equal(dense_svm.coef_, sparse_svm.coef_.toarray()) assert_array_almost_equal(dense_svm.support_, sparse_svm.support_) assert_array_almost_equal(dense_svm.predict(X_test_dense), sparse_svm.predict(X_test)) assert_array_almost_equal(dense_svm.decision_function(X_test_dense), sparse_svm.decision_function(X_test)) assert_array_almost_equal(dense_svm.decision_function(X_test_dense), sparse_svm.decision_function(X_test_dense)) assert_array_almost_equal(dense_svm.predict_proba(X_test_dense), sparse_svm.predict_proba(X_test), 4) msg = "cannot use sparse input in 'SVC' trained on dense data" if sparse.isspmatrix(X_test): assert_raise_message(ValueError, msg, dense_svm.predict, X_test) def test_svc(): """Check that sparse SVC gives the same result as SVC""" # many class dataset: X_blobs, y_blobs = make_blobs(n_samples=100, centers=10, random_state=0) X_blobs = sparse.csr_matrix(X_blobs) datasets = [[X_sp, Y, T], [X2_sp, Y2, T2], [X_blobs[:80], y_blobs[:80], X_blobs[80:]], [iris.data, iris.target, iris.data]] kernels = ["linear", "poly", "rbf", "sigmoid"] for dataset in datasets: for kernel in kernels: clf = svm.SVC(kernel=kernel, probability=True, random_state=0) sp_clf = svm.SVC(kernel=kernel, probability=True, random_state=0) check_svm_model_equal(clf, sp_clf, *dataset) def test_unsorted_indices(): # test that the result with sorted and unsorted indices in csr is the same # we use a subset of digits as iris, blobs or make_classification didn't # show the problem digits = load_digits() X, y = digits.data[:50], digits.target[:50] X_test = sparse.csr_matrix(digits.data[50:100]) X_sparse = sparse.csr_matrix(X) coef_dense = svm.SVC(kernel='linear', probability=True, random_state=0).fit(X, y).coef_ sparse_svc = svm.SVC(kernel='linear', probability=True, random_state=0).fit(X_sparse, y) coef_sorted = sparse_svc.coef_ # make sure dense and sparse SVM give the same result assert_array_almost_equal(coef_dense, coef_sorted.toarray()) X_sparse_unsorted = X_sparse[np.arange(X.shape[0])] X_test_unsorted = X_test[np.arange(X_test.shape[0])] # make sure we scramble the indices assert_false(X_sparse_unsorted.has_sorted_indices) assert_false(X_test_unsorted.has_sorted_indices) unsorted_svc = svm.SVC(kernel='linear', probability=True, random_state=0).fit(X_sparse_unsorted, y) coef_unsorted = unsorted_svc.coef_ # make sure unsorted indices give same result assert_array_almost_equal(coef_unsorted.toarray(), coef_sorted.toarray()) assert_array_almost_equal(sparse_svc.predict_proba(X_test_unsorted), sparse_svc.predict_proba(X_test)) def test_svc_with_custom_kernel(): kfunc = lambda x, y: safe_sparse_dot(x, y.T) clf_lin = svm.SVC(kernel='linear').fit(X_sp, Y) clf_mylin = svm.SVC(kernel=kfunc).fit(X_sp, Y) assert_array_equal(clf_lin.predict(X_sp), clf_mylin.predict(X_sp)) def test_svc_iris(): # Test the sparse SVC with the iris dataset for k in ('linear', 'poly', 'rbf'): sp_clf = svm.SVC(kernel=k).fit(iris.data, iris.target) clf = svm.SVC(kernel=k).fit(iris.data.toarray(), iris.target) assert_array_almost_equal(clf.support_vectors_, sp_clf.support_vectors_.toarray()) assert_array_almost_equal(clf.dual_coef_, sp_clf.dual_coef_.toarray()) assert_array_almost_equal( clf.predict(iris.data.toarray()), sp_clf.predict(iris.data)) if k == 'linear': assert_array_almost_equal(clf.coef_, sp_clf.coef_.toarray()) def test_sparse_decision_function(): #Test decision_function #Sanity check, test that decision_function implemented in python #returns the same as the one in libsvm # multi class: clf = svm.SVC(kernel='linear', C=0.1).fit(iris.data, iris.target) dec = safe_sparse_dot(iris.data, clf.coef_.T) + clf.intercept_ assert_array_almost_equal(dec, clf.decision_function(iris.data)) # binary: clf.fit(X, Y) dec = np.dot(X, clf.coef_.T) + clf.intercept_ prediction = clf.predict(X) assert_array_almost_equal(dec.ravel(), clf.decision_function(X)) assert_array_almost_equal( prediction, clf.classes_[(clf.decision_function(X) > 0).astype(np.int).ravel()]) expected = np.array([-1., -0.66, -1., 0.66, 1., 1.]) assert_array_almost_equal(clf.decision_function(X), expected, 2) def test_error(): # Test that it gives proper exception on deficient input # impossible value of C assert_raises(ValueError, svm.SVC(C=-1).fit, X, Y) # impossible value of nu clf = svm.NuSVC(nu=0.0) assert_raises(ValueError, clf.fit, X_sp, Y) Y2 = Y[:-1] # wrong dimensions for labels assert_raises(ValueError, clf.fit, X_sp, Y2) clf = svm.SVC() clf.fit(X_sp, Y) assert_array_equal(clf.predict(T), true_result) def test_linearsvc(): # Similar to test_SVC clf = svm.LinearSVC(random_state=0).fit(X, Y) sp_clf = svm.LinearSVC(random_state=0).fit(X_sp, Y) assert_true(sp_clf.fit_intercept) assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=4) assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=4) assert_array_almost_equal(clf.predict(X), sp_clf.predict(X_sp)) clf.fit(X2, Y2) sp_clf.fit(X2_sp, Y2) assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=4) assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=4) def test_linearsvc_iris(): # Test the sparse LinearSVC with the iris dataset sp_clf = svm.LinearSVC(random_state=0).fit(iris.data, iris.target) clf = svm.LinearSVC(random_state=0).fit(iris.data.toarray(), iris.target) assert_equal(clf.fit_intercept, sp_clf.fit_intercept) assert_array_almost_equal(clf.coef_, sp_clf.coef_, decimal=1) assert_array_almost_equal(clf.intercept_, sp_clf.intercept_, decimal=1) assert_array_almost_equal( clf.predict(iris.data.toarray()), sp_clf.predict(iris.data)) # check decision_function pred = np.argmax(sp_clf.decision_function(iris.data), 1) assert_array_almost_equal(pred, clf.predict(iris.data.toarray())) # sparsify the coefficients on both models and check that they still # produce the same results clf.sparsify() assert_array_equal(pred, clf.predict(iris.data)) sp_clf.sparsify() assert_array_equal(pred, sp_clf.predict(iris.data)) def test_weight(): # Test class weights X_, y_ = make_classification(n_samples=200, n_features=100, weights=[0.833, 0.167], random_state=0) X_ = sparse.csr_matrix(X_) for clf in (linear_model.LogisticRegression(), svm.LinearSVC(random_state=0), svm.SVC()): clf.set_params(class_weight={0: 5}) clf.fit(X_[:180], y_[:180]) y_pred = clf.predict(X_[180:]) assert_true(np.sum(y_pred == y_[180:]) >= 11) def test_sample_weights(): # Test weights on individual samples clf = svm.SVC() clf.fit(X_sp, Y) assert_array_equal(clf.predict(X[2]), [1.]) sample_weight = [.1] * 3 + [10] * 3 clf.fit(X_sp, Y, sample_weight=sample_weight) assert_array_equal(clf.predict(X[2]), [2.]) def test_sparse_liblinear_intercept_handling(): # Test that sparse liblinear honours intercept_scaling param test_svm.test_dense_liblinear_intercept_handling(svm.LinearSVC) def test_sparse_realdata(): # Test on a subset from the 20newsgroups dataset. # This catchs some bugs if input is not correctly converted into # sparse format or weights are not correctly initialized. data = np.array([0.03771744, 0.1003567, 0.01174647, 0.027069]) indices = np.array([6, 5, 35, 31]) indptr = np.array( [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4]) X = sparse.csr_matrix((data, indices, indptr)) y = np.array( [1., 0., 2., 2., 1., 1., 1., 2., 2., 0., 1., 2., 2., 0., 2., 0., 3., 0., 3., 0., 1., 1., 3., 2., 3., 2., 0., 3., 1., 0., 2., 1., 2., 0., 1., 0., 2., 3., 1., 3., 0., 1., 0., 0., 2., 0., 1., 2., 2., 2., 3., 2., 0., 3., 2., 1., 2., 3., 2., 2., 0., 1., 0., 1., 2., 3., 0., 0., 2., 2., 1., 3., 1., 1., 0., 1., 2., 1., 1., 3.]) clf = svm.SVC(kernel='linear').fit(X.toarray(), y) sp_clf = svm.SVC(kernel='linear').fit(sparse.coo_matrix(X), y) assert_array_equal(clf.support_vectors_, sp_clf.support_vectors_.toarray()) assert_array_equal(clf.dual_coef_, sp_clf.dual_coef_.toarray()) def test_sparse_svc_clone_with_callable_kernel(): # Test that the "dense_fit" is called even though we use sparse input # meaning that everything works fine. a = svm.SVC(C=1, kernel=lambda x, y: x * y.T, probability=True, random_state=0) b = base.clone(a) b.fit(X_sp, Y) pred = b.predict(X_sp) b.predict_proba(X_sp) dense_svm = svm.SVC(C=1, kernel=lambda x, y: np.dot(x, y.T), probability=True, random_state=0) pred_dense = dense_svm.fit(X, Y).predict(X) assert_array_equal(pred_dense, pred) # b.decision_function(X_sp) # XXX : should be supported def test_timeout(): sp = svm.SVC(C=1, kernel=lambda x, y: x * y.T, probability=True, random_state=0, max_iter=1) assert_warns(ConvergenceWarning, sp.fit, X_sp, Y) def test_consistent_proba(): a = svm.SVC(probability=True, max_iter=1, random_state=0) proba_1 = a.fit(X, Y).predict_proba(X) a = svm.SVC(probability=True, max_iter=1, random_state=0) proba_2 = a.fit(X, Y).predict_proba(X) assert_array_almost_equal(proba_1, proba_2)
bsd-3-clause
bnaul/scikit-learn
benchmarks/bench_sample_without_replacement.py
14
7745
""" Benchmarks for sampling without replacement of integer. """ import gc import sys import optparse from datetime import datetime import operator import matplotlib.pyplot as plt import numpy as np import random from sklearn.utils.random import sample_without_replacement def compute_time(t_start, delta): mu_second = 0.0 + 10 ** 6 # number of microseconds in a second return delta.seconds + delta.microseconds / mu_second def bench_sample(sampling, n_population, n_samples): gc.collect() # start time t_start = datetime.now() sampling(n_population, n_samples) delta = (datetime.now() - t_start) # stop time time = compute_time(t_start, delta) return time if __name__ == "__main__": ########################################################################### # Option parser ########################################################################### op = optparse.OptionParser() op.add_option("--n-times", dest="n_times", default=5, type=int, help="Benchmark results are average over n_times experiments") op.add_option("--n-population", dest="n_population", default=100000, type=int, help="Size of the population to sample from.") op.add_option("--n-step", dest="n_steps", default=5, type=int, help="Number of step interval between 0 and n_population.") default_algorithms = "custom-tracking-selection,custom-auto," \ "custom-reservoir-sampling,custom-pool,"\ "python-core-sample,numpy-permutation" op.add_option("--algorithm", dest="selected_algorithm", default=default_algorithms, type=str, help="Comma-separated list of transformer to benchmark. " "Default: %default. \nAvailable: %default") # op.add_option("--random-seed", # dest="random_seed", default=13, type=int, # help="Seed used by the random number generators.") (opts, args) = op.parse_args() if len(args) > 0: op.error("this script takes no arguments.") sys.exit(1) selected_algorithm = opts.selected_algorithm.split(',') for key in selected_algorithm: if key not in default_algorithms.split(','): raise ValueError("Unknown sampling algorithm \"%s\" not in (%s)." % (key, default_algorithms)) ########################################################################### # List sampling algorithm ########################################################################### # We assume that sampling algorithm has the following signature: # sample(n_population, n_sample) # sampling_algorithm = {} ########################################################################### # Set Python core input sampling_algorithm["python-core-sample"] = \ lambda n_population, n_sample: \ random.sample(range(n_population), n_sample) ########################################################################### # Set custom automatic method selection sampling_algorithm["custom-auto"] = \ lambda n_population, n_samples, random_state=None: \ sample_without_replacement(n_population, n_samples, method="auto", random_state=random_state) ########################################################################### # Set custom tracking based method sampling_algorithm["custom-tracking-selection"] = \ lambda n_population, n_samples, random_state=None: \ sample_without_replacement(n_population, n_samples, method="tracking_selection", random_state=random_state) ########################################################################### # Set custom reservoir based method sampling_algorithm["custom-reservoir-sampling"] = \ lambda n_population, n_samples, random_state=None: \ sample_without_replacement(n_population, n_samples, method="reservoir_sampling", random_state=random_state) ########################################################################### # Set custom reservoir based method sampling_algorithm["custom-pool"] = \ lambda n_population, n_samples, random_state=None: \ sample_without_replacement(n_population, n_samples, method="pool", random_state=random_state) ########################################################################### # Numpy permutation based sampling_algorithm["numpy-permutation"] = \ lambda n_population, n_sample: \ np.random.permutation(n_population)[:n_sample] ########################################################################### # Remove unspecified algorithm sampling_algorithm = {key: value for key, value in sampling_algorithm.items() if key in selected_algorithm} ########################################################################### # Perform benchmark ########################################################################### time = {} n_samples = np.linspace(start=0, stop=opts.n_population, num=opts.n_steps).astype(int) ratio = n_samples / opts.n_population print('Benchmarks') print("===========================") for name in sorted(sampling_algorithm): print("Perform benchmarks for %s..." % name, end="") time[name] = np.zeros(shape=(opts.n_steps, opts.n_times)) for step in range(opts.n_steps): for it in range(opts.n_times): time[name][step, it] = bench_sample(sampling_algorithm[name], opts.n_population, n_samples[step]) print("done") print("Averaging results...", end="") for name in sampling_algorithm: time[name] = np.mean(time[name], axis=1) print("done\n") # Print results ########################################################################### print("Script arguments") print("===========================") arguments = vars(opts) print("%s \t | %s " % ("Arguments".ljust(16), "Value".center(12),)) print(25 * "-" + ("|" + "-" * 14) * 1) for key, value in arguments.items(): print("%s \t | %s " % (str(key).ljust(16), str(value).strip().center(12))) print("") print("Sampling algorithm performance:") print("===============================") print("Results are averaged over %s repetition(s)." % opts.n_times) print("") fig = plt.figure('scikit-learn sample w/o replacement benchmark results') plt.title("n_population = %s, n_times = %s" % (opts.n_population, opts.n_times)) ax = fig.add_subplot(111) for name in sampling_algorithm: ax.plot(ratio, time[name], label=name) ax.set_xlabel('ratio of n_sample / n_population') ax.set_ylabel('Time (s)') ax.legend() # Sort legend labels handles, labels = ax.get_legend_handles_labels() hl = sorted(zip(handles, labels), key=operator.itemgetter(1)) handles2, labels2 = zip(*hl) ax.legend(handles2, labels2, loc=0) plt.show()
bsd-3-clause
mcanthony/nupic
external/linux32/lib/python2.6/site-packages/matplotlib/_cm.py
70
375423
""" Color data and pre-defined cmap objects. This is a helper for cm.py, originally part of that file. Separating the data (this file) from cm.py makes both easier to deal with. Objects visible in cm.py are the individual cmap objects ('autumn', etc.) and a dictionary, 'datad', including all of these objects. """ import matplotlib as mpl import matplotlib.colors as colors LUTSIZE = mpl.rcParams['image.lut'] _binary_data = { 'red' : ((0., 1., 1.), (1., 0., 0.)), 'green': ((0., 1., 1.), (1., 0., 0.)), 'blue' : ((0., 1., 1.), (1., 0., 0.)) } _bone_data = {'red': ((0., 0., 0.),(1.0, 1.0, 1.0)), 'green': ((0., 0., 0.),(1.0, 1.0, 1.0)), 'blue': ((0., 0., 0.),(1.0, 1.0, 1.0))} _autumn_data = {'red': ((0., 1.0, 1.0),(1.0, 1.0, 1.0)), 'green': ((0., 0., 0.),(1.0, 1.0, 1.0)), 'blue': ((0., 0., 0.),(1.0, 0., 0.))} _bone_data = {'red': ((0., 0., 0.),(0.746032, 0.652778, 0.652778),(1.0, 1.0, 1.0)), 'green': ((0., 0., 0.),(0.365079, 0.319444, 0.319444), (0.746032, 0.777778, 0.777778),(1.0, 1.0, 1.0)), 'blue': ((0., 0., 0.),(0.365079, 0.444444, 0.444444),(1.0, 1.0, 1.0))} _cool_data = {'red': ((0., 0., 0.), (1.0, 1.0, 1.0)), 'green': ((0., 1., 1.), (1.0, 0., 0.)), 'blue': ((0., 1., 1.), (1.0, 1., 1.))} _copper_data = {'red': ((0., 0., 0.),(0.809524, 1.000000, 1.000000),(1.0, 1.0, 1.0)), 'green': ((0., 0., 0.),(1.0, 0.7812, 0.7812)), 'blue': ((0., 0., 0.),(1.0, 0.4975, 0.4975))} _flag_data = {'red': ((0., 1., 1.),(0.015873, 1.000000, 1.000000), (0.031746, 0.000000, 0.000000),(0.047619, 0.000000, 0.000000), (0.063492, 1.000000, 1.000000),(0.079365, 1.000000, 1.000000), (0.095238, 0.000000, 0.000000),(0.111111, 0.000000, 0.000000), (0.126984, 1.000000, 1.000000),(0.142857, 1.000000, 1.000000), (0.158730, 0.000000, 0.000000),(0.174603, 0.000000, 0.000000), (0.190476, 1.000000, 1.000000),(0.206349, 1.000000, 1.000000), (0.222222, 0.000000, 0.000000),(0.238095, 0.000000, 0.000000), (0.253968, 1.000000, 1.000000),(0.269841, 1.000000, 1.000000), (0.285714, 0.000000, 0.000000),(0.301587, 0.000000, 0.000000), (0.317460, 1.000000, 1.000000),(0.333333, 1.000000, 1.000000), (0.349206, 0.000000, 0.000000),(0.365079, 0.000000, 0.000000), (0.380952, 1.000000, 1.000000),(0.396825, 1.000000, 1.000000), (0.412698, 0.000000, 0.000000),(0.428571, 0.000000, 0.000000), (0.444444, 1.000000, 1.000000),(0.460317, 1.000000, 1.000000), (0.476190, 0.000000, 0.000000),(0.492063, 0.000000, 0.000000), (0.507937, 1.000000, 1.000000),(0.523810, 1.000000, 1.000000), (0.539683, 0.000000, 0.000000),(0.555556, 0.000000, 0.000000), (0.571429, 1.000000, 1.000000),(0.587302, 1.000000, 1.000000), (0.603175, 0.000000, 0.000000),(0.619048, 0.000000, 0.000000), (0.634921, 1.000000, 1.000000),(0.650794, 1.000000, 1.000000), (0.666667, 0.000000, 0.000000),(0.682540, 0.000000, 0.000000), (0.698413, 1.000000, 1.000000),(0.714286, 1.000000, 1.000000), (0.730159, 0.000000, 0.000000),(0.746032, 0.000000, 0.000000), (0.761905, 1.000000, 1.000000),(0.777778, 1.000000, 1.000000), (0.793651, 0.000000, 0.000000),(0.809524, 0.000000, 0.000000), (0.825397, 1.000000, 1.000000),(0.841270, 1.000000, 1.000000), (0.857143, 0.000000, 0.000000),(0.873016, 0.000000, 0.000000), (0.888889, 1.000000, 1.000000),(0.904762, 1.000000, 1.000000), (0.920635, 0.000000, 0.000000),(0.936508, 0.000000, 0.000000), (0.952381, 1.000000, 1.000000),(0.968254, 1.000000, 1.000000), (0.984127, 0.000000, 0.000000),(1.0, 0., 0.)), 'green': ((0., 0., 0.),(0.015873, 1.000000, 1.000000), (0.031746, 0.000000, 0.000000),(0.063492, 0.000000, 0.000000), (0.079365, 1.000000, 1.000000),(0.095238, 0.000000, 0.000000), (0.126984, 0.000000, 0.000000),(0.142857, 1.000000, 1.000000), (0.158730, 0.000000, 0.000000),(0.190476, 0.000000, 0.000000), (0.206349, 1.000000, 1.000000),(0.222222, 0.000000, 0.000000), (0.253968, 0.000000, 0.000000),(0.269841, 1.000000, 1.000000), (0.285714, 0.000000, 0.000000),(0.317460, 0.000000, 0.000000), (0.333333, 1.000000, 1.000000),(0.349206, 0.000000, 0.000000), (0.380952, 0.000000, 0.000000),(0.396825, 1.000000, 1.000000), (0.412698, 0.000000, 0.000000),(0.444444, 0.000000, 0.000000), (0.460317, 1.000000, 1.000000),(0.476190, 0.000000, 0.000000), (0.507937, 0.000000, 0.000000),(0.523810, 1.000000, 1.000000), (0.539683, 0.000000, 0.000000),(0.571429, 0.000000, 0.000000), (0.587302, 1.000000, 1.000000),(0.603175, 0.000000, 0.000000), (0.634921, 0.000000, 0.000000),(0.650794, 1.000000, 1.000000), (0.666667, 0.000000, 0.000000),(0.698413, 0.000000, 0.000000), (0.714286, 1.000000, 1.000000),(0.730159, 0.000000, 0.000000), (0.761905, 0.000000, 0.000000),(0.777778, 1.000000, 1.000000), (0.793651, 0.000000, 0.000000),(0.825397, 0.000000, 0.000000), (0.841270, 1.000000, 1.000000),(0.857143, 0.000000, 0.000000), (0.888889, 0.000000, 0.000000),(0.904762, 1.000000, 1.000000), (0.920635, 0.000000, 0.000000),(0.952381, 0.000000, 0.000000), (0.968254, 1.000000, 1.000000),(0.984127, 0.000000, 0.000000), (1.0, 0., 0.)), 'blue': ((0., 0., 0.),(0.015873, 1.000000, 1.000000), (0.031746, 1.000000, 1.000000),(0.047619, 0.000000, 0.000000), (0.063492, 0.000000, 0.000000),(0.079365, 1.000000, 1.000000), (0.095238, 1.000000, 1.000000),(0.111111, 0.000000, 0.000000), (0.126984, 0.000000, 0.000000),(0.142857, 1.000000, 1.000000), (0.158730, 1.000000, 1.000000),(0.174603, 0.000000, 0.000000), (0.190476, 0.000000, 0.000000),(0.206349, 1.000000, 1.000000), (0.222222, 1.000000, 1.000000),(0.238095, 0.000000, 0.000000), (0.253968, 0.000000, 0.000000),(0.269841, 1.000000, 1.000000), (0.285714, 1.000000, 1.000000),(0.301587, 0.000000, 0.000000), (0.317460, 0.000000, 0.000000),(0.333333, 1.000000, 1.000000), (0.349206, 1.000000, 1.000000),(0.365079, 0.000000, 0.000000), (0.380952, 0.000000, 0.000000),(0.396825, 1.000000, 1.000000), (0.412698, 1.000000, 1.000000),(0.428571, 0.000000, 0.000000), (0.444444, 0.000000, 0.000000),(0.460317, 1.000000, 1.000000), (0.476190, 1.000000, 1.000000),(0.492063, 0.000000, 0.000000), (0.507937, 0.000000, 0.000000),(0.523810, 1.000000, 1.000000), (0.539683, 1.000000, 1.000000),(0.555556, 0.000000, 0.000000), (0.571429, 0.000000, 0.000000),(0.587302, 1.000000, 1.000000), (0.603175, 1.000000, 1.000000),(0.619048, 0.000000, 0.000000), (0.634921, 0.000000, 0.000000),(0.650794, 1.000000, 1.000000), (0.666667, 1.000000, 1.000000),(0.682540, 0.000000, 0.000000), (0.698413, 0.000000, 0.000000),(0.714286, 1.000000, 1.000000), (0.730159, 1.000000, 1.000000),(0.746032, 0.000000, 0.000000), (0.761905, 0.000000, 0.000000),(0.777778, 1.000000, 1.000000), (0.793651, 1.000000, 1.000000),(0.809524, 0.000000, 0.000000), (0.825397, 0.000000, 0.000000),(0.841270, 1.000000, 1.000000), (0.857143, 1.000000, 1.000000),(0.873016, 0.000000, 0.000000), (0.888889, 0.000000, 0.000000),(0.904762, 1.000000, 1.000000), (0.920635, 1.000000, 1.000000),(0.936508, 0.000000, 0.000000), (0.952381, 0.000000, 0.000000),(0.968254, 1.000000, 1.000000), (0.984127, 1.000000, 1.000000),(1.0, 0., 0.))} _gray_data = {'red': ((0., 0, 0), (1., 1, 1)), 'green': ((0., 0, 0), (1., 1, 1)), 'blue': ((0., 0, 0), (1., 1, 1))} _hot_data = {'red': ((0., 0.0416, 0.0416),(0.365079, 1.000000, 1.000000),(1.0, 1.0, 1.0)), 'green': ((0., 0., 0.),(0.365079, 0.000000, 0.000000), (0.746032, 1.000000, 1.000000),(1.0, 1.0, 1.0)), 'blue': ((0., 0., 0.),(0.746032, 0.000000, 0.000000),(1.0, 1.0, 1.0))} _hsv_data = {'red': ((0., 1., 1.),(0.158730, 1.000000, 1.000000), (0.174603, 0.968750, 0.968750),(0.333333, 0.031250, 0.031250), (0.349206, 0.000000, 0.000000),(0.666667, 0.000000, 0.000000), (0.682540, 0.031250, 0.031250),(0.841270, 0.968750, 0.968750), (0.857143, 1.000000, 1.000000),(1.0, 1.0, 1.0)), 'green': ((0., 0., 0.),(0.158730, 0.937500, 0.937500), (0.174603, 1.000000, 1.000000),(0.507937, 1.000000, 1.000000), (0.666667, 0.062500, 0.062500),(0.682540, 0.000000, 0.000000), (1.0, 0., 0.)), 'blue': ((0., 0., 0.),(0.333333, 0.000000, 0.000000), (0.349206, 0.062500, 0.062500),(0.507937, 1.000000, 1.000000), (0.841270, 1.000000, 1.000000),(0.857143, 0.937500, 0.937500), (1.0, 0.09375, 0.09375))} _jet_data = {'red': ((0., 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89,1, 1), (1, 0.5, 0.5)), 'green': ((0., 0, 0), (0.125,0, 0), (0.375,1, 1), (0.64,1, 1), (0.91,0,0), (1, 0, 0)), 'blue': ((0., 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65,0, 0), (1, 0, 0))} _pink_data = {'red': ((0., 0.1178, 0.1178),(0.015873, 0.195857, 0.195857), (0.031746, 0.250661, 0.250661),(0.047619, 0.295468, 0.295468), (0.063492, 0.334324, 0.334324),(0.079365, 0.369112, 0.369112), (0.095238, 0.400892, 0.400892),(0.111111, 0.430331, 0.430331), (0.126984, 0.457882, 0.457882),(0.142857, 0.483867, 0.483867), (0.158730, 0.508525, 0.508525),(0.174603, 0.532042, 0.532042), (0.190476, 0.554563, 0.554563),(0.206349, 0.576204, 0.576204), (0.222222, 0.597061, 0.597061),(0.238095, 0.617213, 0.617213), (0.253968, 0.636729, 0.636729),(0.269841, 0.655663, 0.655663), (0.285714, 0.674066, 0.674066),(0.301587, 0.691980, 0.691980), (0.317460, 0.709441, 0.709441),(0.333333, 0.726483, 0.726483), (0.349206, 0.743134, 0.743134),(0.365079, 0.759421, 0.759421), (0.380952, 0.766356, 0.766356),(0.396825, 0.773229, 0.773229), (0.412698, 0.780042, 0.780042),(0.428571, 0.786796, 0.786796), (0.444444, 0.793492, 0.793492),(0.460317, 0.800132, 0.800132), (0.476190, 0.806718, 0.806718),(0.492063, 0.813250, 0.813250), (0.507937, 0.819730, 0.819730),(0.523810, 0.826160, 0.826160), (0.539683, 0.832539, 0.832539),(0.555556, 0.838870, 0.838870), (0.571429, 0.845154, 0.845154),(0.587302, 0.851392, 0.851392), (0.603175, 0.857584, 0.857584),(0.619048, 0.863731, 0.863731), (0.634921, 0.869835, 0.869835),(0.650794, 0.875897, 0.875897), (0.666667, 0.881917, 0.881917),(0.682540, 0.887896, 0.887896), (0.698413, 0.893835, 0.893835),(0.714286, 0.899735, 0.899735), (0.730159, 0.905597, 0.905597),(0.746032, 0.911421, 0.911421), (0.761905, 0.917208, 0.917208),(0.777778, 0.922958, 0.922958), (0.793651, 0.928673, 0.928673),(0.809524, 0.934353, 0.934353), (0.825397, 0.939999, 0.939999),(0.841270, 0.945611, 0.945611), (0.857143, 0.951190, 0.951190),(0.873016, 0.956736, 0.956736), (0.888889, 0.962250, 0.962250),(0.904762, 0.967733, 0.967733), (0.920635, 0.973185, 0.973185),(0.936508, 0.978607, 0.978607), (0.952381, 0.983999, 0.983999),(0.968254, 0.989361, 0.989361), (0.984127, 0.994695, 0.994695),(1.0, 1.0, 1.0)), 'green': ((0., 0., 0.),(0.015873, 0.102869, 0.102869), (0.031746, 0.145479, 0.145479),(0.047619, 0.178174, 0.178174), (0.063492, 0.205738, 0.205738),(0.079365, 0.230022, 0.230022), (0.095238, 0.251976, 0.251976),(0.111111, 0.272166, 0.272166), (0.126984, 0.290957, 0.290957),(0.142857, 0.308607, 0.308607), (0.158730, 0.325300, 0.325300),(0.174603, 0.341178, 0.341178), (0.190476, 0.356348, 0.356348),(0.206349, 0.370899, 0.370899), (0.222222, 0.384900, 0.384900),(0.238095, 0.398410, 0.398410), (0.253968, 0.411476, 0.411476),(0.269841, 0.424139, 0.424139), (0.285714, 0.436436, 0.436436),(0.301587, 0.448395, 0.448395), (0.317460, 0.460044, 0.460044),(0.333333, 0.471405, 0.471405), (0.349206, 0.482498, 0.482498),(0.365079, 0.493342, 0.493342), (0.380952, 0.517549, 0.517549),(0.396825, 0.540674, 0.540674), (0.412698, 0.562849, 0.562849),(0.428571, 0.584183, 0.584183), (0.444444, 0.604765, 0.604765),(0.460317, 0.624669, 0.624669), (0.476190, 0.643958, 0.643958),(0.492063, 0.662687, 0.662687), (0.507937, 0.680900, 0.680900),(0.523810, 0.698638, 0.698638), (0.539683, 0.715937, 0.715937),(0.555556, 0.732828, 0.732828), (0.571429, 0.749338, 0.749338),(0.587302, 0.765493, 0.765493), (0.603175, 0.781313, 0.781313),(0.619048, 0.796819, 0.796819), (0.634921, 0.812029, 0.812029),(0.650794, 0.826960, 0.826960), (0.666667, 0.841625, 0.841625),(0.682540, 0.856040, 0.856040), (0.698413, 0.870216, 0.870216),(0.714286, 0.884164, 0.884164), (0.730159, 0.897896, 0.897896),(0.746032, 0.911421, 0.911421), (0.761905, 0.917208, 0.917208),(0.777778, 0.922958, 0.922958), (0.793651, 0.928673, 0.928673),(0.809524, 0.934353, 0.934353), (0.825397, 0.939999, 0.939999),(0.841270, 0.945611, 0.945611), (0.857143, 0.951190, 0.951190),(0.873016, 0.956736, 0.956736), (0.888889, 0.962250, 0.962250),(0.904762, 0.967733, 0.967733), (0.920635, 0.973185, 0.973185),(0.936508, 0.978607, 0.978607), (0.952381, 0.983999, 0.983999),(0.968254, 0.989361, 0.989361), (0.984127, 0.994695, 0.994695),(1.0, 1.0, 1.0)), 'blue': ((0., 0., 0.),(0.015873, 0.102869, 0.102869), (0.031746, 0.145479, 0.145479),(0.047619, 0.178174, 0.178174), (0.063492, 0.205738, 0.205738),(0.079365, 0.230022, 0.230022), (0.095238, 0.251976, 0.251976),(0.111111, 0.272166, 0.272166), (0.126984, 0.290957, 0.290957),(0.142857, 0.308607, 0.308607), (0.158730, 0.325300, 0.325300),(0.174603, 0.341178, 0.341178), (0.190476, 0.356348, 0.356348),(0.206349, 0.370899, 0.370899), (0.222222, 0.384900, 0.384900),(0.238095, 0.398410, 0.398410), (0.253968, 0.411476, 0.411476),(0.269841, 0.424139, 0.424139), (0.285714, 0.436436, 0.436436),(0.301587, 0.448395, 0.448395), (0.317460, 0.460044, 0.460044),(0.333333, 0.471405, 0.471405), (0.349206, 0.482498, 0.482498),(0.365079, 0.493342, 0.493342), (0.380952, 0.503953, 0.503953),(0.396825, 0.514344, 0.514344), (0.412698, 0.524531, 0.524531),(0.428571, 0.534522, 0.534522), (0.444444, 0.544331, 0.544331),(0.460317, 0.553966, 0.553966), (0.476190, 0.563436, 0.563436),(0.492063, 0.572750, 0.572750), (0.507937, 0.581914, 0.581914),(0.523810, 0.590937, 0.590937), (0.539683, 0.599824, 0.599824),(0.555556, 0.608581, 0.608581), (0.571429, 0.617213, 0.617213),(0.587302, 0.625727, 0.625727), (0.603175, 0.634126, 0.634126),(0.619048, 0.642416, 0.642416), (0.634921, 0.650600, 0.650600),(0.650794, 0.658682, 0.658682), (0.666667, 0.666667, 0.666667),(0.682540, 0.674556, 0.674556), (0.698413, 0.682355, 0.682355),(0.714286, 0.690066, 0.690066), (0.730159, 0.697691, 0.697691),(0.746032, 0.705234, 0.705234), (0.761905, 0.727166, 0.727166),(0.777778, 0.748455, 0.748455), (0.793651, 0.769156, 0.769156),(0.809524, 0.789314, 0.789314), (0.825397, 0.808969, 0.808969),(0.841270, 0.828159, 0.828159), (0.857143, 0.846913, 0.846913),(0.873016, 0.865261, 0.865261), (0.888889, 0.883229, 0.883229),(0.904762, 0.900837, 0.900837), (0.920635, 0.918109, 0.918109),(0.936508, 0.935061, 0.935061), (0.952381, 0.951711, 0.951711),(0.968254, 0.968075, 0.968075), (0.984127, 0.984167, 0.984167),(1.0, 1.0, 1.0))} _prism_data = {'red': ((0., 1., 1.),(0.031746, 1.000000, 1.000000), (0.047619, 0.000000, 0.000000),(0.063492, 0.000000, 0.000000), (0.079365, 0.666667, 0.666667),(0.095238, 1.000000, 1.000000), (0.126984, 1.000000, 1.000000),(0.142857, 0.000000, 0.000000), (0.158730, 0.000000, 0.000000),(0.174603, 0.666667, 0.666667), (0.190476, 1.000000, 1.000000),(0.222222, 1.000000, 1.000000), (0.238095, 0.000000, 0.000000),(0.253968, 0.000000, 0.000000), (0.269841, 0.666667, 0.666667),(0.285714, 1.000000, 1.000000), (0.317460, 1.000000, 1.000000),(0.333333, 0.000000, 0.000000), (0.349206, 0.000000, 0.000000),(0.365079, 0.666667, 0.666667), (0.380952, 1.000000, 1.000000),(0.412698, 1.000000, 1.000000), (0.428571, 0.000000, 0.000000),(0.444444, 0.000000, 0.000000), (0.460317, 0.666667, 0.666667),(0.476190, 1.000000, 1.000000), (0.507937, 1.000000, 1.000000),(0.523810, 0.000000, 0.000000), (0.539683, 0.000000, 0.000000),(0.555556, 0.666667, 0.666667), (0.571429, 1.000000, 1.000000),(0.603175, 1.000000, 1.000000), (0.619048, 0.000000, 0.000000),(0.634921, 0.000000, 0.000000), (0.650794, 0.666667, 0.666667),(0.666667, 1.000000, 1.000000), (0.698413, 1.000000, 1.000000),(0.714286, 0.000000, 0.000000), (0.730159, 0.000000, 0.000000),(0.746032, 0.666667, 0.666667), (0.761905, 1.000000, 1.000000),(0.793651, 1.000000, 1.000000), (0.809524, 0.000000, 0.000000),(0.825397, 0.000000, 0.000000), (0.841270, 0.666667, 0.666667),(0.857143, 1.000000, 1.000000), (0.888889, 1.000000, 1.000000),(0.904762, 0.000000, 0.000000), (0.920635, 0.000000, 0.000000),(0.936508, 0.666667, 0.666667), (0.952381, 1.000000, 1.000000),(0.984127, 1.000000, 1.000000), (1.0, 0.0, 0.0)), 'green': ((0., 0., 0.),(0.031746, 1.000000, 1.000000), (0.047619, 1.000000, 1.000000),(0.063492, 0.000000, 0.000000), (0.095238, 0.000000, 0.000000),(0.126984, 1.000000, 1.000000), (0.142857, 1.000000, 1.000000),(0.158730, 0.000000, 0.000000), (0.190476, 0.000000, 0.000000),(0.222222, 1.000000, 1.000000), (0.238095, 1.000000, 1.000000),(0.253968, 0.000000, 0.000000), (0.285714, 0.000000, 0.000000),(0.317460, 1.000000, 1.000000), (0.333333, 1.000000, 1.000000),(0.349206, 0.000000, 0.000000), (0.380952, 0.000000, 0.000000),(0.412698, 1.000000, 1.000000), (0.428571, 1.000000, 1.000000),(0.444444, 0.000000, 0.000000), (0.476190, 0.000000, 0.000000),(0.507937, 1.000000, 1.000000), (0.523810, 1.000000, 1.000000),(0.539683, 0.000000, 0.000000), (0.571429, 0.000000, 0.000000),(0.603175, 1.000000, 1.000000), (0.619048, 1.000000, 1.000000),(0.634921, 0.000000, 0.000000), (0.666667, 0.000000, 0.000000),(0.698413, 1.000000, 1.000000), (0.714286, 1.000000, 1.000000),(0.730159, 0.000000, 0.000000), (0.761905, 0.000000, 0.000000),(0.793651, 1.000000, 1.000000), (0.809524, 1.000000, 1.000000),(0.825397, 0.000000, 0.000000), (0.857143, 0.000000, 0.000000),(0.888889, 1.000000, 1.000000), (0.904762, 1.000000, 1.000000),(0.920635, 0.000000, 0.000000), (0.952381, 0.000000, 0.000000),(0.984127, 1.000000, 1.000000), (1.0, 1.0, 1.0)), 'blue': ((0., 0., 0.),(0.047619, 0.000000, 0.000000), (0.063492, 1.000000, 1.000000),(0.079365, 1.000000, 1.000000), (0.095238, 0.000000, 0.000000),(0.142857, 0.000000, 0.000000), (0.158730, 1.000000, 1.000000),(0.174603, 1.000000, 1.000000), (0.190476, 0.000000, 0.000000),(0.238095, 0.000000, 0.000000), (0.253968, 1.000000, 1.000000),(0.269841, 1.000000, 1.000000), (0.285714, 0.000000, 0.000000),(0.333333, 0.000000, 0.000000), (0.349206, 1.000000, 1.000000),(0.365079, 1.000000, 1.000000), (0.380952, 0.000000, 0.000000),(0.428571, 0.000000, 0.000000), (0.444444, 1.000000, 1.000000),(0.460317, 1.000000, 1.000000), (0.476190, 0.000000, 0.000000),(0.523810, 0.000000, 0.000000), (0.539683, 1.000000, 1.000000),(0.555556, 1.000000, 1.000000), (0.571429, 0.000000, 0.000000),(0.619048, 0.000000, 0.000000), (0.634921, 1.000000, 1.000000),(0.650794, 1.000000, 1.000000), (0.666667, 0.000000, 0.000000),(0.714286, 0.000000, 0.000000), (0.730159, 1.000000, 1.000000),(0.746032, 1.000000, 1.000000), (0.761905, 0.000000, 0.000000),(0.809524, 0.000000, 0.000000), (0.825397, 1.000000, 1.000000),(0.841270, 1.000000, 1.000000), (0.857143, 0.000000, 0.000000),(0.904762, 0.000000, 0.000000), (0.920635, 1.000000, 1.000000),(0.936508, 1.000000, 1.000000), (0.952381, 0.000000, 0.000000),(1.0, 0.0, 0.0))} _spring_data = {'red': ((0., 1., 1.),(1.0, 1.0, 1.0)), 'green': ((0., 0., 0.),(1.0, 1.0, 1.0)), 'blue': ((0., 1., 1.),(1.0, 0.0, 0.0))} _summer_data = {'red': ((0., 0., 0.),(1.0, 1.0, 1.0)), 'green': ((0., 0.5, 0.5),(1.0, 1.0, 1.0)), 'blue': ((0., 0.4, 0.4),(1.0, 0.4, 0.4))} _winter_data = {'red': ((0., 0., 0.),(1.0, 0.0, 0.0)), 'green': ((0., 0., 0.),(1.0, 1.0, 1.0)), 'blue': ((0., 1., 1.),(1.0, 0.5, 0.5))} _spectral_data = {'red': [(0.0, 0.0, 0.0), (0.05, 0.4667, 0.4667), (0.10, 0.5333, 0.5333), (0.15, 0.0, 0.0), (0.20, 0.0, 0.0), (0.25, 0.0, 0.0), (0.30, 0.0, 0.0), (0.35, 0.0, 0.0), (0.40, 0.0, 0.0), (0.45, 0.0, 0.0), (0.50, 0.0, 0.0), (0.55, 0.0, 0.0), (0.60, 0.0, 0.0), (0.65, 0.7333, 0.7333), (0.70, 0.9333, 0.9333), (0.75, 1.0, 1.0), (0.80, 1.0, 1.0), (0.85, 1.0, 1.0), (0.90, 0.8667, 0.8667), (0.95, 0.80, 0.80), (1.0, 0.80, 0.80)], 'green': [(0.0, 0.0, 0.0), (0.05, 0.0, 0.0), (0.10, 0.0, 0.0), (0.15, 0.0, 0.0), (0.20, 0.0, 0.0), (0.25, 0.4667, 0.4667), (0.30, 0.6000, 0.6000), (0.35, 0.6667, 0.6667), (0.40, 0.6667, 0.6667), (0.45, 0.6000, 0.6000), (0.50, 0.7333, 0.7333), (0.55, 0.8667, 0.8667), (0.60, 1.0, 1.0), (0.65, 1.0, 1.0), (0.70, 0.9333, 0.9333), (0.75, 0.8000, 0.8000), (0.80, 0.6000, 0.6000), (0.85, 0.0, 0.0), (0.90, 0.0, 0.0), (0.95, 0.0, 0.0), (1.0, 0.80, 0.80)], 'blue': [(0.0, 0.0, 0.0), (0.05, 0.5333, 0.5333), (0.10, 0.6000, 0.6000), (0.15, 0.6667, 0.6667), (0.20, 0.8667, 0.8667), (0.25, 0.8667, 0.8667), (0.30, 0.8667, 0.8667), (0.35, 0.6667, 0.6667), (0.40, 0.5333, 0.5333), (0.45, 0.0, 0.0), (0.5, 0.0, 0.0), (0.55, 0.0, 0.0), (0.60, 0.0, 0.0), (0.65, 0.0, 0.0), (0.70, 0.0, 0.0), (0.75, 0.0, 0.0), (0.80, 0.0, 0.0), (0.85, 0.0, 0.0), (0.90, 0.0, 0.0), (0.95, 0.0, 0.0), (1.0, 0.80, 0.80)]} autumn = colors.LinearSegmentedColormap('autumn', _autumn_data, LUTSIZE) bone = colors.LinearSegmentedColormap('bone ', _bone_data, LUTSIZE) binary = colors.LinearSegmentedColormap('binary ', _binary_data, LUTSIZE) cool = colors.LinearSegmentedColormap('cool', _cool_data, LUTSIZE) copper = colors.LinearSegmentedColormap('copper', _copper_data, LUTSIZE) flag = colors.LinearSegmentedColormap('flag', _flag_data, LUTSIZE) gray = colors.LinearSegmentedColormap('gray', _gray_data, LUTSIZE) hot = colors.LinearSegmentedColormap('hot', _hot_data, LUTSIZE) hsv = colors.LinearSegmentedColormap('hsv', _hsv_data, LUTSIZE) jet = colors.LinearSegmentedColormap('jet', _jet_data, LUTSIZE) pink = colors.LinearSegmentedColormap('pink', _pink_data, LUTSIZE) prism = colors.LinearSegmentedColormap('prism', _prism_data, LUTSIZE) spring = colors.LinearSegmentedColormap('spring', _spring_data, LUTSIZE) summer = colors.LinearSegmentedColormap('summer', _summer_data, LUTSIZE) winter = colors.LinearSegmentedColormap('winter', _winter_data, LUTSIZE) spectral = colors.LinearSegmentedColormap('spectral', _spectral_data, LUTSIZE) datad = { 'autumn': _autumn_data, 'bone': _bone_data, 'binary': _binary_data, 'cool': _cool_data, 'copper': _copper_data, 'flag': _flag_data, 'gray' : _gray_data, 'hot': _hot_data, 'hsv': _hsv_data, 'jet' : _jet_data, 'pink': _pink_data, 'prism': _prism_data, 'spring': _spring_data, 'summer': _summer_data, 'winter': _winter_data, 'spectral': _spectral_data } # 34 colormaps based on color specifications and designs # developed by Cynthia Brewer (http://colorbrewer.org). # The ColorBrewer palettes have been included under the terms # of an Apache-stype license (for details, see the file # LICENSE_COLORBREWER in the license directory of the matplotlib # source distribution). _Accent_data = {'blue': [(0.0, 0.49803921580314636, 0.49803921580314636), (0.14285714285714285, 0.83137255907058716, 0.83137255907058716), (0.2857142857142857, 0.52549022436141968, 0.52549022436141968), (0.42857142857142855, 0.60000002384185791, 0.60000002384185791), (0.5714285714285714, 0.69019609689712524, 0.69019609689712524), (0.7142857142857143, 0.49803921580314636, 0.49803921580314636), (0.8571428571428571, 0.090196080505847931, 0.090196080505847931), (1.0, 0.40000000596046448, 0.40000000596046448)], 'green': [(0.0, 0.78823530673980713, 0.78823530673980713), (0.14285714285714285, 0.68235296010971069, 0.68235296010971069), (0.2857142857142857, 0.75294119119644165, 0.75294119119644165), (0.42857142857142855, 1.0, 1.0), (0.5714285714285714, 0.42352941632270813, 0.42352941632270813), (0.7142857142857143, 0.0078431377187371254, 0.0078431377187371254), (0.8571428571428571, 0.35686275362968445, 0.35686275362968445), (1.0, 0.40000000596046448, 0.40000000596046448)], 'red': [(0.0, 0.49803921580314636, 0.49803921580314636), (0.14285714285714285, 0.7450980544090271, 0.7450980544090271), (0.2857142857142857, 0.99215686321258545, 0.99215686321258545), (0.42857142857142855, 1.0, 1.0), (0.5714285714285714, 0.21960784494876862, 0.21960784494876862), (0.7142857142857143, 0.94117647409439087, 0.94117647409439087), (0.8571428571428571, 0.74901962280273438, 0.74901962280273438), (1.0, 0.40000000596046448, 0.40000000596046448)]} _Blues_data = {'blue': [(0.0, 1.0, 1.0), (0.125, 0.9686274528503418, 0.9686274528503418), (0.25, 0.93725490570068359, 0.93725490570068359), (0.375, 0.88235294818878174, 0.88235294818878174), (0.5, 0.83921569585800171, 0.83921569585800171), (0.625, 0.7764706015586853, 0.7764706015586853), (0.75, 0.70980393886566162, 0.70980393886566162), (0.875, 0.61176472902297974, 0.61176472902297974), (1.0, 0.41960784792900085, 0.41960784792900085)], 'green': [(0.0, 0.9843137264251709, 0.9843137264251709), (0.125, 0.92156863212585449, 0.92156863212585449), (0.25, 0.85882353782653809, 0.85882353782653809), (0.375, 0.7921568751335144, 0.7921568751335144), (0.5, 0.68235296010971069, 0.68235296010971069), (0.625, 0.57254904508590698, 0.57254904508590698), (0.75, 0.44313725829124451, 0.44313725829124451), (0.875, 0.31764706969261169, 0.31764706969261169), (1.0, 0.18823529779911041, 0.18823529779911041)], 'red': [(0.0, 0.9686274528503418, 0.9686274528503418), (0.125, 0.87058824300765991, 0.87058824300765991), (0.25, 0.7764706015586853, 0.7764706015586853), (0.375, 0.61960786581039429, 0.61960786581039429), (0.5, 0.41960784792900085, 0.41960784792900085), (0.625, 0.25882354378700256, 0.25882354378700256), (0.75, 0.12941177189350128, 0.12941177189350128), (0.875, 0.031372550874948502, 0.031372550874948502), (1.0, 0.031372550874948502, 0.031372550874948502)]} _BrBG_data = {'blue': [(0.0, 0.019607843831181526, 0.019607843831181526), (0.10000000000000001, 0.039215687662363052, 0.039215687662363052), (0.20000000000000001, 0.17647059261798859, 0.17647059261798859), (0.29999999999999999, 0.49019607901573181, 0.49019607901573181), (0.40000000000000002, 0.76470589637756348, 0.76470589637756348), (0.5, 0.96078431606292725, 0.96078431606292725), (0.59999999999999998, 0.89803922176361084, 0.89803922176361084), (0.69999999999999996, 0.75686275959014893, 0.75686275959014893), (0.80000000000000004, 0.56078433990478516, 0.56078433990478516), (0.90000000000000002, 0.36862745881080627, 0.36862745881080627), (1.0, 0.18823529779911041, 0.18823529779911041)], 'green': [(0.0, 0.18823529779911041, 0.18823529779911041), (0.10000000000000001, 0.31764706969261169, 0.31764706969261169), (0.20000000000000001, 0.5058823823928833, 0.5058823823928833), (0.29999999999999999, 0.7607843279838562, 0.7607843279838562), (0.40000000000000002, 0.90980392694473267, 0.90980392694473267), (0.5, 0.96078431606292725, 0.96078431606292725), (0.59999999999999998, 0.91764706373214722, 0.91764706373214722), (0.69999999999999996, 0.80392158031463623, 0.80392158031463623), (0.80000000000000004, 0.59215688705444336, 0.59215688705444336), (0.90000000000000002, 0.40000000596046448, 0.40000000596046448), (1.0, 0.23529411852359772, 0.23529411852359772)], 'red': [(0.0, 0.32941177487373352, 0.32941177487373352), (0.10000000000000001, 0.54901963472366333, 0.54901963472366333), (0.20000000000000001, 0.74901962280273438, 0.74901962280273438), (0.29999999999999999, 0.87450981140136719, 0.87450981140136719), (0.40000000000000002, 0.96470588445663452, 0.96470588445663452), (0.5, 0.96078431606292725, 0.96078431606292725), (0.59999999999999998, 0.78039216995239258, 0.78039216995239258), (0.69999999999999996, 0.50196081399917603, 0.50196081399917603), (0.80000000000000004, 0.20784313976764679, 0.20784313976764679), (0.90000000000000002, 0.0039215688593685627, 0.0039215688593685627), (1.0, 0.0, 0.0)]} _BuGn_data = {'blue': [(0.0, 0.99215686321258545, 0.99215686321258545), (0.125, 0.97647058963775635, 0.97647058963775635), (0.25, 0.90196079015731812, 0.90196079015731812), (0.375, 0.78823530673980713, 0.78823530673980713), (0.5, 0.64313727617263794, 0.64313727617263794), (0.625, 0.46274510025978088, 0.46274510025978088), (0.75, 0.27058824896812439, 0.27058824896812439), (0.875, 0.17254902422428131, 0.17254902422428131), (1.0, 0.10588235408067703, 0.10588235408067703)], 'green': [(0.0, 0.98823529481887817, 0.98823529481887817), (0.125, 0.96078431606292725, 0.96078431606292725), (0.25, 0.92549020051956177, 0.92549020051956177), (0.375, 0.84705883264541626, 0.84705883264541626), (0.5, 0.7607843279838562, 0.7607843279838562), (0.625, 0.68235296010971069, 0.68235296010971069), (0.75, 0.54509806632995605, 0.54509806632995605), (0.875, 0.42745098471641541, 0.42745098471641541), (1.0, 0.26666668057441711, 0.26666668057441711)], 'red': [(0.0, 0.9686274528503418, 0.9686274528503418), (0.125, 0.89803922176361084, 0.89803922176361084), (0.25, 0.80000001192092896, 0.80000001192092896), (0.375, 0.60000002384185791, 0.60000002384185791), (0.5, 0.40000000596046448, 0.40000000596046448), (0.625, 0.25490197539329529, 0.25490197539329529), (0.75, 0.13725490868091583, 0.13725490868091583), (0.875, 0.0, 0.0), (1.0, 0.0, 0.0)]} _BuPu_data = {'blue': [(0.0, 0.99215686321258545, 0.99215686321258545), (0.125, 0.95686274766921997, 0.95686274766921997), (0.25, 0.90196079015731812, 0.90196079015731812), (0.375, 0.85490196943283081, 0.85490196943283081), (0.5, 0.7764706015586853, 0.7764706015586853), (0.625, 0.69411766529083252, 0.69411766529083252), (0.75, 0.61568629741668701, 0.61568629741668701), (0.875, 0.48627451062202454, 0.48627451062202454), (1.0, 0.29411765933036804, 0.29411765933036804)], 'green': [(0.0, 0.98823529481887817, 0.98823529481887817), (0.125, 0.92549020051956177, 0.92549020051956177), (0.25, 0.82745099067687988, 0.82745099067687988), (0.375, 0.73725491762161255, 0.73725491762161255), (0.5, 0.58823531866073608, 0.58823531866073608), (0.625, 0.41960784792900085, 0.41960784792900085), (0.75, 0.25490197539329529, 0.25490197539329529), (0.875, 0.058823529630899429, 0.058823529630899429), (1.0, 0.0, 0.0)], 'red': [(0.0, 0.9686274528503418, 0.9686274528503418), (0.125, 0.87843137979507446, 0.87843137979507446), (0.25, 0.74901962280273438, 0.74901962280273438), (0.375, 0.61960786581039429, 0.61960786581039429), (0.5, 0.54901963472366333, 0.54901963472366333), (0.625, 0.54901963472366333, 0.54901963472366333), (0.75, 0.53333336114883423, 0.53333336114883423), (0.875, 0.5058823823928833, 0.5058823823928833), (1.0, 0.30196079611778259, 0.30196079611778259)]} _Dark2_data = {'blue': [(0.0, 0.46666666865348816, 0.46666666865348816), (0.14285714285714285, 0.0078431377187371254, 0.0078431377187371254), (0.2857142857142857, 0.70196080207824707, 0.70196080207824707), (0.42857142857142855, 0.54117649793624878, 0.54117649793624878), (0.5714285714285714, 0.11764705926179886, 0.11764705926179886), (0.7142857142857143, 0.0078431377187371254, 0.0078431377187371254), (0.8571428571428571, 0.11372549086809158, 0.11372549086809158), (1.0, 0.40000000596046448, 0.40000000596046448)], 'green': [(0.0, 0.61960786581039429, 0.61960786581039429), (0.14285714285714285, 0.37254902720451355, 0.37254902720451355), (0.2857142857142857, 0.43921568989753723, 0.43921568989753723), (0.42857142857142855, 0.16078431904315948, 0.16078431904315948), (0.5714285714285714, 0.65098041296005249, 0.65098041296005249), (0.7142857142857143, 0.67058825492858887, 0.67058825492858887), (0.8571428571428571, 0.46274510025978088, 0.46274510025978088), (1.0, 0.40000000596046448, 0.40000000596046448)], 'red': [(0.0, 0.10588235408067703, 0.10588235408067703), (0.14285714285714285, 0.85098040103912354, 0.85098040103912354), (0.2857142857142857, 0.45882353186607361, 0.45882353186607361), (0.42857142857142855, 0.90588235855102539, 0.90588235855102539), (0.5714285714285714, 0.40000000596046448, 0.40000000596046448), (0.7142857142857143, 0.90196079015731812, 0.90196079015731812), (0.8571428571428571, 0.65098041296005249, 0.65098041296005249), (1.0, 0.40000000596046448, 0.40000000596046448)]} _GnBu_data = {'blue': [(0.0, 0.94117647409439087, 0.94117647409439087), (0.125, 0.85882353782653809, 0.85882353782653809), (0.25, 0.77254903316497803, 0.77254903316497803), (0.375, 0.70980393886566162, 0.70980393886566162), (0.5, 0.76862746477127075, 0.76862746477127075), (0.625, 0.82745099067687988, 0.82745099067687988), (0.75, 0.7450980544090271, 0.7450980544090271), (0.875, 0.67450982332229614, 0.67450982332229614), (1.0, 0.5058823823928833, 0.5058823823928833)], 'green': [(0.0, 0.98823529481887817, 0.98823529481887817), (0.125, 0.9529411792755127, 0.9529411792755127), (0.25, 0.92156863212585449, 0.92156863212585449), (0.375, 0.86666667461395264, 0.86666667461395264), (0.5, 0.80000001192092896, 0.80000001192092896), (0.625, 0.70196080207824707, 0.70196080207824707), (0.75, 0.54901963472366333, 0.54901963472366333), (0.875, 0.40784314274787903, 0.40784314274787903), (1.0, 0.25098040699958801, 0.25098040699958801)], 'red': [(0.0, 0.9686274528503418, 0.9686274528503418), (0.125, 0.87843137979507446, 0.87843137979507446), (0.25, 0.80000001192092896, 0.80000001192092896), (0.375, 0.65882354974746704, 0.65882354974746704), (0.5, 0.48235294222831726, 0.48235294222831726), (0.625, 0.30588236451148987, 0.30588236451148987), (0.75, 0.16862745583057404, 0.16862745583057404), (0.875, 0.031372550874948502, 0.031372550874948502), (1.0, 0.031372550874948502, 0.031372550874948502)]} _Greens_data = {'blue': [(0.0, 0.96078431606292725, 0.96078431606292725), (0.125, 0.87843137979507446, 0.87843137979507446), (0.25, 0.75294119119644165, 0.75294119119644165), (0.375, 0.60784316062927246, 0.60784316062927246), (0.5, 0.46274510025978088, 0.46274510025978088), (0.625, 0.364705890417099, 0.364705890417099), (0.75, 0.27058824896812439, 0.27058824896812439), (0.875, 0.17254902422428131, 0.17254902422428131), (1.0, 0.10588235408067703, 0.10588235408067703)], 'green': [(0.0, 0.98823529481887817, 0.98823529481887817), (0.125, 0.96078431606292725, 0.96078431606292725), (0.25, 0.91372549533843994, 0.91372549533843994), (0.375, 0.85098040103912354, 0.85098040103912354), (0.5, 0.76862746477127075, 0.76862746477127075), (0.625, 0.67058825492858887, 0.67058825492858887), (0.75, 0.54509806632995605, 0.54509806632995605), (0.875, 0.42745098471641541, 0.42745098471641541), (1.0, 0.26666668057441711, 0.26666668057441711)], 'red': [(0.0, 0.9686274528503418, 0.9686274528503418), (0.125, 0.89803922176361084, 0.89803922176361084), (0.25, 0.78039216995239258, 0.78039216995239258), (0.375, 0.63137257099151611, 0.63137257099151611), (0.5, 0.45490196347236633, 0.45490196347236633), (0.625, 0.25490197539329529, 0.25490197539329529), (0.75, 0.13725490868091583, 0.13725490868091583), (0.875, 0.0, 0.0), (1.0, 0.0, 0.0)]} _Greys_data = {'blue': [(0.0, 1.0, 1.0), (0.125, 0.94117647409439087, 0.94117647409439087), (0.25, 0.85098040103912354, 0.85098040103912354), (0.375, 0.74117648601531982, 0.74117648601531982), (0.5, 0.58823531866073608, 0.58823531866073608), (0.625, 0.45098039507865906, 0.45098039507865906), (0.75, 0.32156863808631897, 0.32156863808631897), (0.875, 0.14509804546833038, 0.14509804546833038), (1.0, 0.0, 0.0)], 'green': [(0.0, 1.0, 1.0), (0.125, 0.94117647409439087, 0.94117647409439087), (0.25, 0.85098040103912354, 0.85098040103912354), (0.375, 0.74117648601531982, 0.74117648601531982), (0.5, 0.58823531866073608, 0.58823531866073608), (0.625, 0.45098039507865906, 0.45098039507865906), (0.75, 0.32156863808631897, 0.32156863808631897), (0.875, 0.14509804546833038, 0.14509804546833038), (1.0, 0.0, 0.0)], 'red': [(0.0, 1.0, 1.0), (0.125, 0.94117647409439087, 0.94117647409439087), (0.25, 0.85098040103912354, 0.85098040103912354), (0.375, 0.74117648601531982, 0.74117648601531982), (0.5, 0.58823531866073608, 0.58823531866073608), (0.625, 0.45098039507865906, 0.45098039507865906), (0.75, 0.32156863808631897, 0.32156863808631897), (0.875, 0.14509804546833038, 0.14509804546833038), (1.0, 0.0, 0.0)]} _Oranges_data = {'blue': [(0.0, 0.92156863212585449, 0.92156863212585449), (0.125, 0.80784314870834351, 0.80784314870834351), (0.25, 0.63529413938522339, 0.63529413938522339), (0.375, 0.41960784792900085, 0.41960784792900085), (0.5, 0.23529411852359772, 0.23529411852359772), (0.625, 0.074509806931018829, 0.074509806931018829), (0.75, 0.0039215688593685627, 0.0039215688593685627), (0.875, 0.011764706112444401, 0.011764706112444401), (1.0, 0.015686275437474251, 0.015686275437474251)], 'green': [(0.0, 0.96078431606292725, 0.96078431606292725), (0.125, 0.90196079015731812, 0.90196079015731812), (0.25, 0.81568628549575806, 0.81568628549575806), (0.375, 0.68235296010971069, 0.68235296010971069), (0.5, 0.55294120311737061, 0.55294120311737061), (0.625, 0.4117647111415863, 0.4117647111415863), (0.75, 0.28235295414924622, 0.28235295414924622), (0.875, 0.21176470816135406, 0.21176470816135406), (1.0, 0.15294118225574493, 0.15294118225574493)], 'red': [(0.0, 1.0, 1.0), (0.125, 0.99607843160629272, 0.99607843160629272), (0.25, 0.99215686321258545, 0.99215686321258545), (0.375, 0.99215686321258545, 0.99215686321258545), (0.5, 0.99215686321258545, 0.99215686321258545), (0.625, 0.94509804248809814, 0.94509804248809814), (0.75, 0.85098040103912354, 0.85098040103912354), (0.875, 0.65098041296005249, 0.65098041296005249), (1.0, 0.49803921580314636, 0.49803921580314636)]} _OrRd_data = {'blue': [(0.0, 0.92549020051956177, 0.92549020051956177), (0.125, 0.78431373834609985, 0.78431373834609985), (0.25, 0.61960786581039429, 0.61960786581039429), (0.375, 0.51764708757400513, 0.51764708757400513), (0.5, 0.3490196168422699, 0.3490196168422699), (0.625, 0.28235295414924622, 0.28235295414924622), (0.75, 0.12156862765550613, 0.12156862765550613), (0.875, 0.0, 0.0), (1.0, 0.0, 0.0)], 'green': [(0.0, 0.9686274528503418, 0.9686274528503418), (0.125, 0.90980392694473267, 0.90980392694473267), (0.25, 0.83137255907058716, 0.83137255907058716), (0.375, 0.73333334922790527, 0.73333334922790527), (0.5, 0.55294120311737061, 0.55294120311737061), (0.625, 0.3960784375667572, 0.3960784375667572), (0.75, 0.18823529779911041, 0.18823529779911041), (0.875, 0.0, 0.0), (1.0, 0.0, 0.0)], 'red': [(0.0, 1.0, 1.0), (0.125, 0.99607843160629272, 0.99607843160629272), (0.25, 0.99215686321258545, 0.99215686321258545), (0.375, 0.99215686321258545, 0.99215686321258545), (0.5, 0.98823529481887817, 0.98823529481887817), (0.625, 0.93725490570068359, 0.93725490570068359), (0.75, 0.84313726425170898, 0.84313726425170898), (0.875, 0.70196080207824707, 0.70196080207824707), (1.0, 0.49803921580314636, 0.49803921580314636)]} _Paired_data = {'blue': [(0.0, 0.89019608497619629, 0.89019608497619629), (0.090909090909090912, 0.70588237047195435, 0.70588237047195435), (0.18181818181818182, 0.54117649793624878, 0.54117649793624878), (0.27272727272727271, 0.17254902422428131, 0.17254902422428131), (0.36363636363636365, 0.60000002384185791, 0.60000002384185791), (0.45454545454545453, 0.10980392247438431, 0.10980392247438431), (0.54545454545454541, 0.43529412150382996, 0.43529412150382996), (0.63636363636363635, 0.0, 0.0), (0.72727272727272729, 0.83921569585800171, 0.83921569585800171), (0.81818181818181823, 0.60392159223556519, 0.60392159223556519), (0.90909090909090906, 0.60000002384185791, 0.60000002384185791), (1.0, 0.15686275064945221, 0.15686275064945221)], 'green': [(0.0, 0.80784314870834351, 0.80784314870834351), (0.090909090909090912, 0.47058823704719543, 0.47058823704719543), (0.18181818181818182, 0.87450981140136719, 0.87450981140136719), (0.27272727272727271, 0.62745100259780884, 0.62745100259780884), (0.36363636363636365, 0.60392159223556519, 0.60392159223556519), (0.45454545454545453, 0.10196078568696976, 0.10196078568696976), (0.54545454545454541, 0.74901962280273438, 0.74901962280273438), (0.63636363636363635, 0.49803921580314636, 0.49803921580314636), (0.72727272727272729, 0.69803923368453979, 0.69803923368453979), (0.81818181818181823, 0.23921568691730499, 0.23921568691730499), (0.90909090909090906, 1.0, 1.0), (1.0, 0.3490196168422699, 0.3490196168422699)], 'red': [(0.0, 0.65098041296005249, 0.65098041296005249), (0.090909090909090912, 0.12156862765550613, 0.12156862765550613), (0.18181818181818182, 0.69803923368453979, 0.69803923368453979), (0.27272727272727271, 0.20000000298023224, 0.20000000298023224), (0.36363636363636365, 0.9843137264251709, 0.9843137264251709), (0.45454545454545453, 0.89019608497619629, 0.89019608497619629), (0.54545454545454541, 0.99215686321258545, 0.99215686321258545), (0.63636363636363635, 1.0, 1.0), (0.72727272727272729, 0.7921568751335144, 0.7921568751335144), (0.81818181818181823, 0.41568627953529358, 0.41568627953529358), (0.90909090909090906, 1.0, 1.0), (1.0, 0.69411766529083252, 0.69411766529083252)]} _Pastel1_data = {'blue': [(0.0, 0.68235296010971069, 0.68235296010971069), (0.125, 0.89019608497619629, 0.89019608497619629), (0.25, 0.77254903316497803, 0.77254903316497803), (0.375, 0.89411765336990356, 0.89411765336990356), (0.5, 0.65098041296005249, 0.65098041296005249), (0.625, 0.80000001192092896, 0.80000001192092896), (0.75, 0.74117648601531982, 0.74117648601531982), (0.875, 0.92549020051956177, 0.92549020051956177), (1.0, 0.94901961088180542, 0.94901961088180542)], 'green': [(0.0, 0.70588237047195435, 0.70588237047195435), (0.125, 0.80392158031463623, 0.80392158031463623), (0.25, 0.92156863212585449, 0.92156863212585449), (0.375, 0.79607844352722168, 0.79607844352722168), (0.5, 0.85098040103912354, 0.85098040103912354), (0.625, 1.0, 1.0), (0.75, 0.84705883264541626, 0.84705883264541626), (0.875, 0.85490196943283081, 0.85490196943283081), (1.0, 0.94901961088180542, 0.94901961088180542)], 'red': [(0.0, 0.9843137264251709, 0.9843137264251709), (0.125, 0.70196080207824707, 0.70196080207824707), (0.25, 0.80000001192092896, 0.80000001192092896), (0.375, 0.87058824300765991, 0.87058824300765991), (0.5, 0.99607843160629272, 0.99607843160629272), (0.625, 1.0, 1.0), (0.75, 0.89803922176361084, 0.89803922176361084), (0.875, 0.99215686321258545, 0.99215686321258545), (1.0, 0.94901961088180542, 0.94901961088180542)]} _Pastel2_data = {'blue': [(0.0, 0.80392158031463623, 0.80392158031463623), (0.14285714285714285, 0.67450982332229614, 0.67450982332229614), (0.2857142857142857, 0.90980392694473267, 0.90980392694473267), (0.42857142857142855, 0.89411765336990356, 0.89411765336990356), (0.5714285714285714, 0.78823530673980713, 0.78823530673980713), (0.7142857142857143, 0.68235296010971069, 0.68235296010971069), (0.8571428571428571, 0.80000001192092896, 0.80000001192092896), (1.0, 0.80000001192092896, 0.80000001192092896)], 'green': [(0.0, 0.88627451658248901, 0.88627451658248901), (0.14285714285714285, 0.80392158031463623, 0.80392158031463623), (0.2857142857142857, 0.83529412746429443, 0.83529412746429443), (0.42857142857142855, 0.7921568751335144, 0.7921568751335144), (0.5714285714285714, 0.96078431606292725, 0.96078431606292725), (0.7142857142857143, 0.94901961088180542, 0.94901961088180542), (0.8571428571428571, 0.88627451658248901, 0.88627451658248901), (1.0, 0.80000001192092896, 0.80000001192092896)], 'red': [(0.0, 0.70196080207824707, 0.70196080207824707), (0.14285714285714285, 0.99215686321258545, 0.99215686321258545), (0.2857142857142857, 0.79607844352722168, 0.79607844352722168), (0.42857142857142855, 0.95686274766921997, 0.95686274766921997), (0.5714285714285714, 0.90196079015731812, 0.90196079015731812), (0.7142857142857143, 1.0, 1.0), (0.8571428571428571, 0.94509804248809814, 0.94509804248809814), (1.0, 0.80000001192092896, 0.80000001192092896)]} _PiYG_data = {'blue': [(0.0, 0.32156863808631897, 0.32156863808631897), (0.10000000000000001, 0.49019607901573181, 0.49019607901573181), (0.20000000000000001, 0.68235296010971069, 0.68235296010971069), (0.29999999999999999, 0.85490196943283081, 0.85490196943283081), (0.40000000000000002, 0.93725490570068359, 0.93725490570068359), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.81568628549575806, 0.81568628549575806), (0.69999999999999996, 0.52549022436141968, 0.52549022436141968), (0.80000000000000004, 0.25490197539329529, 0.25490197539329529), (0.90000000000000002, 0.12941177189350128, 0.12941177189350128), (1.0, 0.098039217293262482, 0.098039217293262482)], 'green': [(0.0, 0.0039215688593685627, 0.0039215688593685627), (0.10000000000000001, 0.10588235408067703, 0.10588235408067703), (0.20000000000000001, 0.46666666865348816, 0.46666666865348816), (0.29999999999999999, 0.7137255072593689, 0.7137255072593689), (0.40000000000000002, 0.87843137979507446, 0.87843137979507446), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.96078431606292725, 0.96078431606292725), (0.69999999999999996, 0.88235294818878174, 0.88235294818878174), (0.80000000000000004, 0.73725491762161255, 0.73725491762161255), (0.90000000000000002, 0.57254904508590698, 0.57254904508590698), (1.0, 0.39215686917304993, 0.39215686917304993)], 'red': [(0.0, 0.55686277151107788, 0.55686277151107788), (0.10000000000000001, 0.77254903316497803, 0.77254903316497803), (0.20000000000000001, 0.87058824300765991, 0.87058824300765991), (0.29999999999999999, 0.94509804248809814, 0.94509804248809814), (0.40000000000000002, 0.99215686321258545, 0.99215686321258545), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.90196079015731812, 0.90196079015731812), (0.69999999999999996, 0.72156864404678345, 0.72156864404678345), (0.80000000000000004, 0.49803921580314636, 0.49803921580314636), (0.90000000000000002, 0.30196079611778259, 0.30196079611778259), (1.0, 0.15294118225574493, 0.15294118225574493)]} _PRGn_data = {'blue': [(0.0, 0.29411765933036804, 0.29411765933036804), (0.10000000000000001, 0.51372551918029785, 0.51372551918029785), (0.20000000000000001, 0.67058825492858887, 0.67058825492858887), (0.29999999999999999, 0.81176471710205078, 0.81176471710205078), (0.40000000000000002, 0.90980392694473267, 0.90980392694473267), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.82745099067687988, 0.82745099067687988), (0.69999999999999996, 0.62745100259780884, 0.62745100259780884), (0.80000000000000004, 0.3803921639919281, 0.3803921639919281), (0.90000000000000002, 0.21568627655506134, 0.21568627655506134), (1.0, 0.10588235408067703, 0.10588235408067703)], 'green': [(0.0, 0.0, 0.0), (0.10000000000000001, 0.16470588743686676, 0.16470588743686676), (0.20000000000000001, 0.43921568989753723, 0.43921568989753723), (0.29999999999999999, 0.64705884456634521, 0.64705884456634521), (0.40000000000000002, 0.83137255907058716, 0.83137255907058716), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.94117647409439087, 0.94117647409439087), (0.69999999999999996, 0.85882353782653809, 0.85882353782653809), (0.80000000000000004, 0.68235296010971069, 0.68235296010971069), (0.90000000000000002, 0.47058823704719543, 0.47058823704719543), (1.0, 0.26666668057441711, 0.26666668057441711)], 'red': [(0.0, 0.25098040699958801, 0.25098040699958801), (0.10000000000000001, 0.46274510025978088, 0.46274510025978088), (0.20000000000000001, 0.60000002384185791, 0.60000002384185791), (0.29999999999999999, 0.7607843279838562, 0.7607843279838562), (0.40000000000000002, 0.90588235855102539, 0.90588235855102539), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.85098040103912354, 0.85098040103912354), (0.69999999999999996, 0.65098041296005249, 0.65098041296005249), (0.80000000000000004, 0.35294118523597717, 0.35294118523597717), (0.90000000000000002, 0.10588235408067703, 0.10588235408067703), (1.0, 0.0, 0.0)]} _PuBu_data = {'blue': [(0.0, 0.9843137264251709, 0.9843137264251709), (0.125, 0.94901961088180542, 0.94901961088180542), (0.25, 0.90196079015731812, 0.90196079015731812), (0.375, 0.85882353782653809, 0.85882353782653809), (0.5, 0.81176471710205078, 0.81176471710205078), (0.625, 0.75294119119644165, 0.75294119119644165), (0.75, 0.69019609689712524, 0.69019609689712524), (0.875, 0.55294120311737061, 0.55294120311737061), (1.0, 0.34509804844856262, 0.34509804844856262)], 'green': [(0.0, 0.9686274528503418, 0.9686274528503418), (0.125, 0.90588235855102539, 0.90588235855102539), (0.25, 0.81960785388946533, 0.81960785388946533), (0.375, 0.74117648601531982, 0.74117648601531982), (0.5, 0.66274511814117432, 0.66274511814117432), (0.625, 0.56470590829849243, 0.56470590829849243), (0.75, 0.43921568989753723, 0.43921568989753723), (0.875, 0.35294118523597717, 0.35294118523597717), (1.0, 0.21960784494876862, 0.21960784494876862)], 'red': [(0.0, 1.0, 1.0), (0.125, 0.92549020051956177, 0.92549020051956177), (0.25, 0.81568628549575806, 0.81568628549575806), (0.375, 0.65098041296005249, 0.65098041296005249), (0.5, 0.45490196347236633, 0.45490196347236633), (0.625, 0.21176470816135406, 0.21176470816135406), (0.75, 0.019607843831181526, 0.019607843831181526), (0.875, 0.015686275437474251, 0.015686275437474251), (1.0, 0.0078431377187371254, 0.0078431377187371254)]} _PuBuGn_data = {'blue': [(0.0, 0.9843137264251709, 0.9843137264251709), (0.125, 0.94117647409439087, 0.94117647409439087), (0.25, 0.90196079015731812, 0.90196079015731812), (0.375, 0.85882353782653809, 0.85882353782653809), (0.5, 0.81176471710205078, 0.81176471710205078), (0.625, 0.75294119119644165, 0.75294119119644165), (0.75, 0.54117649793624878, 0.54117649793624878), (0.875, 0.3490196168422699, 0.3490196168422699), (1.0, 0.21176470816135406, 0.21176470816135406)], 'green': [(0.0, 0.9686274528503418, 0.9686274528503418), (0.125, 0.88627451658248901, 0.88627451658248901), (0.25, 0.81960785388946533, 0.81960785388946533), (0.375, 0.74117648601531982, 0.74117648601531982), (0.5, 0.66274511814117432, 0.66274511814117432), (0.625, 0.56470590829849243, 0.56470590829849243), (0.75, 0.5058823823928833, 0.5058823823928833), (0.875, 0.42352941632270813, 0.42352941632270813), (1.0, 0.27450981736183167, 0.27450981736183167)], 'red': [(0.0, 1.0, 1.0), (0.125, 0.92549020051956177, 0.92549020051956177), (0.25, 0.81568628549575806, 0.81568628549575806), (0.375, 0.65098041296005249, 0.65098041296005249), (0.5, 0.40392157435417175, 0.40392157435417175), (0.625, 0.21176470816135406, 0.21176470816135406), (0.75, 0.0078431377187371254, 0.0078431377187371254), (0.875, 0.0039215688593685627, 0.0039215688593685627), (1.0, 0.0039215688593685627, 0.0039215688593685627)]} _PuOr_data = {'blue': [(0.0, 0.031372550874948502, 0.031372550874948502), (0.10000000000000001, 0.023529412224888802, 0.023529412224888802), (0.20000000000000001, 0.078431375324726105, 0.078431375324726105), (0.29999999999999999, 0.38823530077934265, 0.38823530077934265), (0.40000000000000002, 0.7137255072593689, 0.7137255072593689), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.92156863212585449, 0.92156863212585449), (0.69999999999999996, 0.82352942228317261, 0.82352942228317261), (0.80000000000000004, 0.67450982332229614, 0.67450982332229614), (0.90000000000000002, 0.53333336114883423, 0.53333336114883423), (1.0, 0.29411765933036804, 0.29411765933036804)], 'green': [(0.0, 0.23137255012989044, 0.23137255012989044), (0.10000000000000001, 0.34509804844856262, 0.34509804844856262), (0.20000000000000001, 0.50980395078659058, 0.50980395078659058), (0.29999999999999999, 0.72156864404678345, 0.72156864404678345), (0.40000000000000002, 0.87843137979507446, 0.87843137979507446), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.85490196943283081, 0.85490196943283081), (0.69999999999999996, 0.67058825492858887, 0.67058825492858887), (0.80000000000000004, 0.45098039507865906, 0.45098039507865906), (0.90000000000000002, 0.15294118225574493, 0.15294118225574493), (1.0, 0.0, 0.0)], 'red': [(0.0, 0.49803921580314636, 0.49803921580314636), (0.10000000000000001, 0.70196080207824707, 0.70196080207824707), (0.20000000000000001, 0.87843137979507446, 0.87843137979507446), (0.29999999999999999, 0.99215686321258545, 0.99215686321258545), (0.40000000000000002, 0.99607843160629272, 0.99607843160629272), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.84705883264541626, 0.84705883264541626), (0.69999999999999996, 0.69803923368453979, 0.69803923368453979), (0.80000000000000004, 0.50196081399917603, 0.50196081399917603), (0.90000000000000002, 0.32941177487373352, 0.32941177487373352), (1.0, 0.17647059261798859, 0.17647059261798859)]} _PuRd_data = {'blue': [(0.0, 0.97647058963775635, 0.97647058963775635), (0.125, 0.93725490570068359, 0.93725490570068359), (0.25, 0.85490196943283081, 0.85490196943283081), (0.375, 0.78039216995239258, 0.78039216995239258), (0.5, 0.69019609689712524, 0.69019609689712524), (0.625, 0.54117649793624878, 0.54117649793624878), (0.75, 0.33725491166114807, 0.33725491166114807), (0.875, 0.26274511218070984, 0.26274511218070984), (1.0, 0.12156862765550613, 0.12156862765550613)], 'green': [(0.0, 0.95686274766921997, 0.95686274766921997), (0.125, 0.88235294818878174, 0.88235294818878174), (0.25, 0.72549021244049072, 0.72549021244049072), (0.375, 0.58039218187332153, 0.58039218187332153), (0.5, 0.3960784375667572, 0.3960784375667572), (0.625, 0.16078431904315948, 0.16078431904315948), (0.75, 0.070588238537311554, 0.070588238537311554), (0.875, 0.0, 0.0), (1.0, 0.0, 0.0)], 'red': [(0.0, 0.9686274528503418, 0.9686274528503418), (0.125, 0.90588235855102539, 0.90588235855102539), (0.25, 0.83137255907058716, 0.83137255907058716), (0.375, 0.78823530673980713, 0.78823530673980713), (0.5, 0.87450981140136719, 0.87450981140136719), (0.625, 0.90588235855102539, 0.90588235855102539), (0.75, 0.80784314870834351, 0.80784314870834351), (0.875, 0.59607845544815063, 0.59607845544815063), (1.0, 0.40392157435417175, 0.40392157435417175)]} _Purples_data = {'blue': [(0.0, 0.99215686321258545, 0.99215686321258545), (0.125, 0.96078431606292725, 0.96078431606292725), (0.25, 0.92156863212585449, 0.92156863212585449), (0.375, 0.86274510622024536, 0.86274510622024536), (0.5, 0.78431373834609985, 0.78431373834609985), (0.625, 0.729411780834198, 0.729411780834198), (0.75, 0.63921570777893066, 0.63921570777893066), (0.875, 0.56078433990478516, 0.56078433990478516), (1.0, 0.49019607901573181, 0.49019607901573181)], 'green': [(0.0, 0.9843137264251709, 0.9843137264251709), (0.125, 0.92941176891326904, 0.92941176891326904), (0.25, 0.85490196943283081, 0.85490196943283081), (0.375, 0.74117648601531982, 0.74117648601531982), (0.5, 0.60392159223556519, 0.60392159223556519), (0.625, 0.49019607901573181, 0.49019607901573181), (0.75, 0.31764706969261169, 0.31764706969261169), (0.875, 0.15294118225574493, 0.15294118225574493), (1.0, 0.0, 0.0)], 'red': [(0.0, 0.98823529481887817, 0.98823529481887817), (0.125, 0.93725490570068359, 0.93725490570068359), (0.25, 0.85490196943283081, 0.85490196943283081), (0.375, 0.73725491762161255, 0.73725491762161255), (0.5, 0.61960786581039429, 0.61960786581039429), (0.625, 0.50196081399917603, 0.50196081399917603), (0.75, 0.41568627953529358, 0.41568627953529358), (0.875, 0.32941177487373352, 0.32941177487373352), (1.0, 0.24705882370471954, 0.24705882370471954)]} _RdBu_data = {'blue': [(0.0, 0.12156862765550613, 0.12156862765550613), (0.10000000000000001, 0.16862745583057404, 0.16862745583057404), (0.20000000000000001, 0.30196079611778259, 0.30196079611778259), (0.29999999999999999, 0.50980395078659058, 0.50980395078659058), (0.40000000000000002, 0.78039216995239258, 0.78039216995239258), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.94117647409439087, 0.94117647409439087), (0.69999999999999996, 0.87058824300765991, 0.87058824300765991), (0.80000000000000004, 0.76470589637756348, 0.76470589637756348), (0.90000000000000002, 0.67450982332229614, 0.67450982332229614), (1.0, 0.3803921639919281, 0.3803921639919281)], 'green': [(0.0, 0.0, 0.0), (0.10000000000000001, 0.094117648899555206, 0.094117648899555206), (0.20000000000000001, 0.37647059559822083, 0.37647059559822083), (0.29999999999999999, 0.64705884456634521, 0.64705884456634521), (0.40000000000000002, 0.85882353782653809, 0.85882353782653809), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.89803922176361084, 0.89803922176361084), (0.69999999999999996, 0.77254903316497803, 0.77254903316497803), (0.80000000000000004, 0.57647061347961426, 0.57647061347961426), (0.90000000000000002, 0.40000000596046448, 0.40000000596046448), (1.0, 0.18823529779911041, 0.18823529779911041)], 'red': [(0.0, 0.40392157435417175, 0.40392157435417175), (0.10000000000000001, 0.69803923368453979, 0.69803923368453979), (0.20000000000000001, 0.83921569585800171, 0.83921569585800171), (0.29999999999999999, 0.95686274766921997, 0.95686274766921997), (0.40000000000000002, 0.99215686321258545, 0.99215686321258545), (0.5, 0.9686274528503418, 0.9686274528503418), (0.59999999999999998, 0.81960785388946533, 0.81960785388946533), (0.69999999999999996, 0.57254904508590698, 0.57254904508590698), (0.80000000000000004, 0.26274511218070984, 0.26274511218070984), (0.90000000000000002, 0.12941177189350128, 0.12941177189350128), (1.0, 0.019607843831181526, 0.019607843831181526)]} _RdGy_data = {'blue': [(0.0, 0.12156862765550613, 0.12156862765550613), (0.10000000000000001, 0.16862745583057404, 0.16862745583057404), (0.20000000000000001, 0.30196079611778259, 0.30196079611778259), (0.29999999999999999, 0.50980395078659058, 0.50980395078659058), (0.40000000000000002, 0.78039216995239258, 0.78039216995239258), (0.5, 1.0, 1.0), (0.59999999999999998, 0.87843137979507446, 0.87843137979507446), (0.69999999999999996, 0.729411780834198, 0.729411780834198), (0.80000000000000004, 0.52941179275512695, 0.52941179275512695), (0.90000000000000002, 0.30196079611778259, 0.30196079611778259), (1.0, 0.10196078568696976, 0.10196078568696976)], 'green': [(0.0, 0.0, 0.0), (0.10000000000000001, 0.094117648899555206, 0.094117648899555206), (0.20000000000000001, 0.37647059559822083, 0.37647059559822083), (0.29999999999999999, 0.64705884456634521, 0.64705884456634521), (0.40000000000000002, 0.85882353782653809, 0.85882353782653809), (0.5, 1.0, 1.0), (0.59999999999999998, 0.87843137979507446, 0.87843137979507446), (0.69999999999999996, 0.729411780834198, 0.729411780834198), (0.80000000000000004, 0.52941179275512695, 0.52941179275512695), (0.90000000000000002, 0.30196079611778259, 0.30196079611778259), (1.0, 0.10196078568696976, 0.10196078568696976)], 'red': [(0.0, 0.40392157435417175, 0.40392157435417175), (0.10000000000000001, 0.69803923368453979, 0.69803923368453979), (0.20000000000000001, 0.83921569585800171, 0.83921569585800171), (0.29999999999999999, 0.95686274766921997, 0.95686274766921997), (0.40000000000000002, 0.99215686321258545, 0.99215686321258545), (0.5, 1.0, 1.0), (0.59999999999999998, 0.87843137979507446, 0.87843137979507446), (0.69999999999999996, 0.729411780834198, 0.729411780834198), (0.80000000000000004, 0.52941179275512695, 0.52941179275512695), (0.90000000000000002, 0.30196079611778259, 0.30196079611778259), (1.0, 0.10196078568696976, 0.10196078568696976)]} _RdPu_data = {'blue': [(0.0, 0.9529411792755127, 0.9529411792755127), (0.125, 0.86666667461395264, 0.86666667461395264), (0.25, 0.75294119119644165, 0.75294119119644165), (0.375, 0.70980393886566162, 0.70980393886566162), (0.5, 0.63137257099151611, 0.63137257099151611), (0.625, 0.59215688705444336, 0.59215688705444336), (0.75, 0.49411764740943909, 0.49411764740943909), (0.875, 0.46666666865348816, 0.46666666865348816), (1.0, 0.41568627953529358, 0.41568627953529358)], 'green': [(0.0, 0.9686274528503418, 0.9686274528503418), (0.125, 0.87843137979507446, 0.87843137979507446), (0.25, 0.77254903316497803, 0.77254903316497803), (0.375, 0.62352943420410156, 0.62352943420410156), (0.5, 0.40784314274787903, 0.40784314274787903), (0.625, 0.20392157137393951, 0.20392157137393951), (0.75, 0.0039215688593685627, 0.0039215688593685627), (0.875, 0.0039215688593685627, 0.0039215688593685627), (1.0, 0.0, 0.0)], 'red': [(0.0, 1.0, 1.0), (0.125, 0.99215686321258545, 0.99215686321258545), (0.25, 0.98823529481887817, 0.98823529481887817), (0.375, 0.98039215803146362, 0.98039215803146362), (0.5, 0.9686274528503418, 0.9686274528503418), (0.625, 0.86666667461395264, 0.86666667461395264), (0.75, 0.68235296010971069, 0.68235296010971069), (0.875, 0.47843137383460999, 0.47843137383460999), (1.0, 0.28627452254295349, 0.28627452254295349)]} _RdYlBu_data = {'blue': [(0.0, 0.14901961386203766, 0.14901961386203766), (0.10000000149011612, 0.15294118225574493, 0.15294118225574493), (0.20000000298023224, 0.26274511218070984, 0.26274511218070984), (0.30000001192092896, 0.3803921639919281, 0.3803921639919281), (0.40000000596046448, 0.56470590829849243, 0.56470590829849243), (0.5, 0.74901962280273438, 0.74901962280273438), (0.60000002384185791, 0.97254902124404907, 0.97254902124404907), (0.69999998807907104, 0.91372549533843994, 0.91372549533843994), (0.80000001192092896, 0.81960785388946533, 0.81960785388946533), (0.89999997615814209, 0.70588237047195435, 0.70588237047195435), (1.0, 0.58431375026702881, 0.58431375026702881)], 'green': [(0.0, 0.0, 0.0), (0.10000000149011612, 0.18823529779911041, 0.18823529779911041), (0.20000000298023224, 0.42745098471641541, 0.42745098471641541), (0.30000001192092896, 0.68235296010971069, 0.68235296010971069), (0.40000000596046448, 0.87843137979507446, 0.87843137979507446), (0.5, 1.0, 1.0), (0.60000002384185791, 0.9529411792755127, 0.9529411792755127), (0.69999998807907104, 0.85098040103912354, 0.85098040103912354), (0.80000001192092896, 0.67843139171600342, 0.67843139171600342), (0.89999997615814209, 0.45882353186607361, 0.45882353186607361), (1.0, 0.21176470816135406, 0.21176470816135406)], 'red': [(0.0, 0.64705884456634521, 0.64705884456634521), (0.10000000149011612, 0.84313726425170898, 0.84313726425170898), (0.20000000298023224, 0.95686274766921997, 0.95686274766921997), (0.30000001192092896, 0.99215686321258545, 0.99215686321258545), (0.40000000596046448, 0.99607843160629272, 0.99607843160629272), (0.5, 1.0, 1.0), (0.60000002384185791, 0.87843137979507446, 0.87843137979507446), (0.69999998807907104, 0.67058825492858887, 0.67058825492858887), (0.80000001192092896, 0.45490196347236633, 0.45490196347236633), (0.89999997615814209, 0.27058824896812439, 0.27058824896812439), (1.0, 0.19215686619281769, 0.19215686619281769)]} _RdYlGn_data = {'blue': [(0.0, 0.14901961386203766, 0.14901961386203766), (0.10000000000000001, 0.15294118225574493, 0.15294118225574493), (0.20000000000000001, 0.26274511218070984, 0.26274511218070984), (0.29999999999999999, 0.3803921639919281, 0.3803921639919281), (0.40000000000000002, 0.54509806632995605, 0.54509806632995605), (0.5, 0.74901962280273438, 0.74901962280273438), (0.59999999999999998, 0.54509806632995605, 0.54509806632995605), (0.69999999999999996, 0.41568627953529358, 0.41568627953529358), (0.80000000000000004, 0.38823530077934265, 0.38823530077934265), (0.90000000000000002, 0.31372550129890442, 0.31372550129890442), (1.0, 0.21568627655506134, 0.21568627655506134)], 'green': [(0.0, 0.0, 0.0), (0.10000000000000001, 0.18823529779911041, 0.18823529779911041), (0.20000000000000001, 0.42745098471641541, 0.42745098471641541), (0.29999999999999999, 0.68235296010971069, 0.68235296010971069), (0.40000000000000002, 0.87843137979507446, 0.87843137979507446), (0.5, 1.0, 1.0), (0.59999999999999998, 0.93725490570068359, 0.93725490570068359), (0.69999999999999996, 0.85098040103912354, 0.85098040103912354), (0.80000000000000004, 0.74117648601531982, 0.74117648601531982), (0.90000000000000002, 0.59607845544815063, 0.59607845544815063), (1.0, 0.40784314274787903, 0.40784314274787903)], 'red': [(0.0, 0.64705884456634521, 0.64705884456634521), (0.10000000000000001, 0.84313726425170898, 0.84313726425170898), (0.20000000000000001, 0.95686274766921997, 0.95686274766921997), (0.29999999999999999, 0.99215686321258545, 0.99215686321258545), (0.40000000000000002, 0.99607843160629272, 0.99607843160629272), (0.5, 1.0, 1.0), (0.59999999999999998, 0.85098040103912354, 0.85098040103912354), (0.69999999999999996, 0.65098041296005249, 0.65098041296005249), (0.80000000000000004, 0.40000000596046448, 0.40000000596046448), (0.90000000000000002, 0.10196078568696976, 0.10196078568696976), (1.0, 0.0, 0.0)]} _Reds_data = {'blue': [(0.0, 0.94117647409439087, 0.94117647409439087), (0.125, 0.82352942228317261, 0.82352942228317261), (0.25, 0.63137257099151611, 0.63137257099151611), (0.375, 0.44705882668495178, 0.44705882668495178), (0.5, 0.29019609093666077, 0.29019609093666077), (0.625, 0.17254902422428131, 0.17254902422428131), (0.75, 0.11372549086809158, 0.11372549086809158), (0.875, 0.08235294371843338, 0.08235294371843338), (1.0, 0.050980392843484879, 0.050980392843484879)], 'green': [(0.0, 0.96078431606292725, 0.96078431606292725), (0.125, 0.87843137979507446, 0.87843137979507446), (0.25, 0.73333334922790527, 0.73333334922790527), (0.375, 0.57254904508590698, 0.57254904508590698), (0.5, 0.41568627953529358, 0.41568627953529358), (0.625, 0.23137255012989044, 0.23137255012989044), (0.75, 0.094117648899555206, 0.094117648899555206), (0.875, 0.058823529630899429, 0.058823529630899429), (1.0, 0.0, 0.0)], 'red': [(0.0, 1.0, 1.0), (0.125, 0.99607843160629272, 0.99607843160629272), (0.25, 0.98823529481887817, 0.98823529481887817), (0.375, 0.98823529481887817, 0.98823529481887817), (0.5, 0.9843137264251709, 0.9843137264251709), (0.625, 0.93725490570068359, 0.93725490570068359), (0.75, 0.79607844352722168, 0.79607844352722168), (0.875, 0.64705884456634521, 0.64705884456634521), (1.0, 0.40392157435417175, 0.40392157435417175)]} _Set1_data = {'blue': [(0.0, 0.10980392247438431, 0.10980392247438431), (0.125, 0.72156864404678345, 0.72156864404678345), (0.25, 0.29019609093666077, 0.29019609093666077), (0.375, 0.63921570777893066, 0.63921570777893066), (0.5, 0.0, 0.0), (0.625, 0.20000000298023224, 0.20000000298023224), (0.75, 0.15686275064945221, 0.15686275064945221), (0.875, 0.74901962280273438, 0.74901962280273438), (1.0, 0.60000002384185791, 0.60000002384185791)], 'green': [(0.0, 0.10196078568696976, 0.10196078568696976), (0.125, 0.49411764740943909, 0.49411764740943909), (0.25, 0.68627452850341797, 0.68627452850341797), (0.375, 0.30588236451148987, 0.30588236451148987), (0.5, 0.49803921580314636, 0.49803921580314636), (0.625, 1.0, 1.0), (0.75, 0.33725491166114807, 0.33725491166114807), (0.875, 0.5058823823928833, 0.5058823823928833), (1.0, 0.60000002384185791, 0.60000002384185791)], 'red': [(0.0, 0.89411765336990356, 0.89411765336990356), (0.125, 0.21568627655506134, 0.21568627655506134), (0.25, 0.30196079611778259, 0.30196079611778259), (0.375, 0.59607845544815063, 0.59607845544815063), (0.5, 1.0, 1.0), (0.625, 1.0, 1.0), (0.75, 0.65098041296005249, 0.65098041296005249), (0.875, 0.9686274528503418, 0.9686274528503418), (1.0, 0.60000002384185791, 0.60000002384185791)]} _Set2_data = {'blue': [(0.0, 0.64705884456634521, 0.64705884456634521), (0.14285714285714285, 0.38431373238563538, 0.38431373238563538), (0.2857142857142857, 0.79607844352722168, 0.79607844352722168), (0.42857142857142855, 0.76470589637756348, 0.76470589637756348), (0.5714285714285714, 0.32941177487373352, 0.32941177487373352), (0.7142857142857143, 0.18431372940540314, 0.18431372940540314), (0.8571428571428571, 0.58039218187332153, 0.58039218187332153), (1.0, 0.70196080207824707, 0.70196080207824707)], 'green': [(0.0, 0.7607843279838562, 0.7607843279838562), (0.14285714285714285, 0.55294120311737061, 0.55294120311737061), (0.2857142857142857, 0.62745100259780884, 0.62745100259780884), (0.42857142857142855, 0.54117649793624878, 0.54117649793624878), (0.5714285714285714, 0.84705883264541626, 0.84705883264541626), (0.7142857142857143, 0.85098040103912354, 0.85098040103912354), (0.8571428571428571, 0.76862746477127075, 0.76862746477127075), (1.0, 0.70196080207824707, 0.70196080207824707)], 'red': [(0.0, 0.40000000596046448, 0.40000000596046448), (0.14285714285714285, 0.98823529481887817, 0.98823529481887817), (0.2857142857142857, 0.55294120311737061, 0.55294120311737061), (0.42857142857142855, 0.90588235855102539, 0.90588235855102539), (0.5714285714285714, 0.65098041296005249, 0.65098041296005249), (0.7142857142857143, 1.0, 1.0), (0.8571428571428571, 0.89803922176361084, 0.89803922176361084), (1.0, 0.70196080207824707, 0.70196080207824707)]} _Set3_data = {'blue': [(0.0, 0.78039216995239258, 0.78039216995239258), (0.090909090909090912, 0.70196080207824707, 0.70196080207824707), (0.18181818181818182, 0.85490196943283081, 0.85490196943283081), (0.27272727272727271, 0.44705882668495178, 0.44705882668495178), (0.36363636363636365, 0.82745099067687988, 0.82745099067687988), (0.45454545454545453, 0.38431373238563538, 0.38431373238563538), (0.54545454545454541, 0.4117647111415863, 0.4117647111415863), (0.63636363636363635, 0.89803922176361084, 0.89803922176361084), (0.72727272727272729, 0.85098040103912354, 0.85098040103912354), (0.81818181818181823, 0.74117648601531982, 0.74117648601531982), (0.90909090909090906, 0.77254903316497803, 0.77254903316497803), (1.0, 0.43529412150382996, 0.43529412150382996)], 'green': [(0.0, 0.82745099067687988, 0.82745099067687988), (0.090909090909090912, 1.0, 1.0), (0.18181818181818182, 0.729411780834198, 0.729411780834198), (0.27272727272727271, 0.50196081399917603, 0.50196081399917603), (0.36363636363636365, 0.69411766529083252, 0.69411766529083252), (0.45454545454545453, 0.70588237047195435, 0.70588237047195435), (0.54545454545454541, 0.87058824300765991, 0.87058824300765991), (0.63636363636363635, 0.80392158031463623, 0.80392158031463623), (0.72727272727272729, 0.85098040103912354, 0.85098040103912354), (0.81818181818181823, 0.50196081399917603, 0.50196081399917603), (0.90909090909090906, 0.92156863212585449, 0.92156863212585449), (1.0, 0.92941176891326904, 0.92941176891326904)], 'red': [(0.0, 0.55294120311737061, 0.55294120311737061), (0.090909090909090912, 1.0, 1.0), (0.18181818181818182, 0.7450980544090271, 0.7450980544090271), (0.27272727272727271, 0.9843137264251709, 0.9843137264251709), (0.36363636363636365, 0.50196081399917603, 0.50196081399917603), (0.45454545454545453, 0.99215686321258545, 0.99215686321258545), (0.54545454545454541, 0.70196080207824707, 0.70196080207824707), (0.63636363636363635, 0.98823529481887817, 0.98823529481887817), (0.72727272727272729, 0.85098040103912354, 0.85098040103912354), (0.81818181818181823, 0.73725491762161255, 0.73725491762161255), (0.90909090909090906, 0.80000001192092896, 0.80000001192092896), (1.0, 1.0, 1.0)]} _Spectral_data = {'blue': [(0.0, 0.25882354378700256, 0.25882354378700256), (0.10000000000000001, 0.30980393290519714, 0.30980393290519714), (0.20000000000000001, 0.26274511218070984, 0.26274511218070984), (0.29999999999999999, 0.3803921639919281, 0.3803921639919281), (0.40000000000000002, 0.54509806632995605, 0.54509806632995605), (0.5, 0.74901962280273438, 0.74901962280273438), (0.59999999999999998, 0.59607845544815063, 0.59607845544815063), (0.69999999999999996, 0.64313727617263794, 0.64313727617263794), (0.80000000000000004, 0.64705884456634521, 0.64705884456634521), (0.90000000000000002, 0.74117648601531982, 0.74117648601531982), (1.0, 0.63529413938522339, 0.63529413938522339)], 'green': [(0.0, 0.0039215688593685627, 0.0039215688593685627), (0.10000000000000001, 0.24313725531101227, 0.24313725531101227), (0.20000000000000001, 0.42745098471641541, 0.42745098471641541), (0.29999999999999999, 0.68235296010971069, 0.68235296010971069), (0.40000000000000002, 0.87843137979507446, 0.87843137979507446), (0.5, 1.0, 1.0), (0.59999999999999998, 0.96078431606292725, 0.96078431606292725), (0.69999999999999996, 0.86666667461395264, 0.86666667461395264), (0.80000000000000004, 0.7607843279838562, 0.7607843279838562), (0.90000000000000002, 0.53333336114883423, 0.53333336114883423), (1.0, 0.30980393290519714, 0.30980393290519714)], 'red': [(0.0, 0.61960786581039429, 0.61960786581039429), (0.10000000000000001, 0.83529412746429443, 0.83529412746429443), (0.20000000000000001, 0.95686274766921997, 0.95686274766921997), (0.29999999999999999, 0.99215686321258545, 0.99215686321258545), (0.40000000000000002, 0.99607843160629272, 0.99607843160629272), (0.5, 1.0, 1.0), (0.59999999999999998, 0.90196079015731812, 0.90196079015731812), (0.69999999999999996, 0.67058825492858887, 0.67058825492858887), (0.80000000000000004, 0.40000000596046448, 0.40000000596046448), (0.90000000000000002, 0.19607843458652496, 0.19607843458652496), (1.0, 0.36862745881080627, 0.36862745881080627)]} _YlGn_data = {'blue': [(0.0, 0.89803922176361084, 0.89803922176361084), (0.125, 0.72549021244049072, 0.72549021244049072), (0.25, 0.63921570777893066, 0.63921570777893066), (0.375, 0.55686277151107788, 0.55686277151107788), (0.5, 0.47450980544090271, 0.47450980544090271), (0.625, 0.364705890417099, 0.364705890417099), (0.75, 0.26274511218070984, 0.26274511218070984), (0.875, 0.21568627655506134, 0.21568627655506134), (1.0, 0.16078431904315948, 0.16078431904315948)], 'green': [(0.0, 1.0, 1.0), (0.125, 0.98823529481887817, 0.98823529481887817), (0.25, 0.94117647409439087, 0.94117647409439087), (0.375, 0.86666667461395264, 0.86666667461395264), (0.5, 0.7764706015586853, 0.7764706015586853), (0.625, 0.67058825492858887, 0.67058825492858887), (0.75, 0.51764708757400513, 0.51764708757400513), (0.875, 0.40784314274787903, 0.40784314274787903), (1.0, 0.27058824896812439, 0.27058824896812439)], 'red': [(0.0, 1.0, 1.0), (0.125, 0.9686274528503418, 0.9686274528503418), (0.25, 0.85098040103912354, 0.85098040103912354), (0.375, 0.67843139171600342, 0.67843139171600342), (0.5, 0.47058823704719543, 0.47058823704719543), (0.625, 0.25490197539329529, 0.25490197539329529), (0.75, 0.13725490868091583, 0.13725490868091583), (0.875, 0.0, 0.0), (1.0, 0.0, 0.0)]} _YlGnBu_data = {'blue': [(0.0, 0.85098040103912354, 0.85098040103912354), (0.125, 0.69411766529083252, 0.69411766529083252), (0.25, 0.70588237047195435, 0.70588237047195435), (0.375, 0.73333334922790527, 0.73333334922790527), (0.5, 0.76862746477127075, 0.76862746477127075), (0.625, 0.75294119119644165, 0.75294119119644165), (0.75, 0.65882354974746704, 0.65882354974746704), (0.875, 0.58039218187332153, 0.58039218187332153), (1.0, 0.34509804844856262, 0.34509804844856262)], 'green': [(0.0, 1.0, 1.0), (0.125, 0.97254902124404907, 0.97254902124404907), (0.25, 0.91372549533843994, 0.91372549533843994), (0.375, 0.80392158031463623, 0.80392158031463623), (0.5, 0.7137255072593689, 0.7137255072593689), (0.625, 0.56862747669219971, 0.56862747669219971), (0.75, 0.36862745881080627, 0.36862745881080627), (0.875, 0.20392157137393951, 0.20392157137393951), (1.0, 0.11372549086809158, 0.11372549086809158)], 'red': [(0.0, 1.0, 1.0), (0.125, 0.92941176891326904, 0.92941176891326904), (0.25, 0.78039216995239258, 0.78039216995239258), (0.375, 0.49803921580314636, 0.49803921580314636), (0.5, 0.25490197539329529, 0.25490197539329529), (0.625, 0.11372549086809158, 0.11372549086809158), (0.75, 0.13333334028720856, 0.13333334028720856), (0.875, 0.14509804546833038, 0.14509804546833038), (1.0, 0.031372550874948502, 0.031372550874948502)]} _YlOrBr_data = {'blue': [(0.0, 0.89803922176361084, 0.89803922176361084), (0.125, 0.73725491762161255, 0.73725491762161255), (0.25, 0.56862747669219971, 0.56862747669219971), (0.375, 0.30980393290519714, 0.30980393290519714), (0.5, 0.16078431904315948, 0.16078431904315948), (0.625, 0.078431375324726105, 0.078431375324726105), (0.75, 0.0078431377187371254, 0.0078431377187371254), (0.875, 0.015686275437474251, 0.015686275437474251), (1.0, 0.023529412224888802, 0.023529412224888802)], 'green': [(0.0, 1.0, 1.0), (0.125, 0.9686274528503418, 0.9686274528503418), (0.25, 0.89019608497619629, 0.89019608497619629), (0.375, 0.76862746477127075, 0.76862746477127075), (0.5, 0.60000002384185791, 0.60000002384185791), (0.625, 0.43921568989753723, 0.43921568989753723), (0.75, 0.29803922772407532, 0.29803922772407532), (0.875, 0.20392157137393951, 0.20392157137393951), (1.0, 0.14509804546833038, 0.14509804546833038)], 'red': [(0.0, 1.0, 1.0), (0.125, 1.0, 1.0), (0.25, 0.99607843160629272, 0.99607843160629272), (0.375, 0.99607843160629272, 0.99607843160629272), (0.5, 0.99607843160629272, 0.99607843160629272), (0.625, 0.92549020051956177, 0.92549020051956177), (0.75, 0.80000001192092896, 0.80000001192092896), (0.875, 0.60000002384185791, 0.60000002384185791), (1.0, 0.40000000596046448, 0.40000000596046448)]} _YlOrRd_data = {'blue': [(0.0, 0.80000001192092896, 0.80000001192092896), (0.125, 0.62745100259780884, 0.62745100259780884), (0.25, 0.46274510025978088, 0.46274510025978088), (0.375, 0.29803922772407532, 0.29803922772407532), (0.5, 0.23529411852359772, 0.23529411852359772), (0.625, 0.16470588743686676, 0.16470588743686676), (0.75, 0.10980392247438431, 0.10980392247438431), (0.875, 0.14901961386203766, 0.14901961386203766), (1.0, 0.14901961386203766, 0.14901961386203766)], 'green': [(0.0, 1.0, 1.0), (0.125, 0.92941176891326904, 0.92941176891326904), (0.25, 0.85098040103912354, 0.85098040103912354), (0.375, 0.69803923368453979, 0.69803923368453979), (0.5, 0.55294120311737061, 0.55294120311737061), (0.625, 0.30588236451148987, 0.30588236451148987), (0.75, 0.10196078568696976, 0.10196078568696976), (0.875, 0.0, 0.0), (1.0, 0.0, 0.0)], 'red': [(0.0, 1.0, 1.0), (0.125, 1.0, 1.0), (0.25, 0.99607843160629272, 0.99607843160629272), (0.375, 0.99607843160629272, 0.99607843160629272), (0.5, 0.99215686321258545, 0.99215686321258545), (0.625, 0.98823529481887817, 0.98823529481887817), (0.75, 0.89019608497619629, 0.89019608497619629), (0.875, 0.74117648601531982, 0.74117648601531982), (1.0, 0.50196081399917603, 0.50196081399917603)]} # The next 7 palettes are from the Yorick scientific visalisation package, # an evolution of the GIST package, both by David H. Munro. # They are released under a BSD-like license (see LICENSE_YORICK in # the license directory of the matplotlib source distribution). _gist_earth_data = {'blue': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.18039216101169586, 0.18039216101169586), (0.0084033617749810219, 0.22745098173618317, 0.22745098173618317), (0.012605042196810246, 0.27058824896812439, 0.27058824896812439), (0.016806723549962044, 0.31764706969261169, 0.31764706969261169), (0.021008403971791267, 0.36078432202339172, 0.36078432202339172), (0.025210084393620491, 0.40784314274787903, 0.40784314274787903), (0.029411764815449715, 0.45490196347236633, 0.45490196347236633), (0.033613447099924088, 0.45490196347236633, 0.45490196347236633), (0.037815127521753311, 0.45490196347236633, 0.45490196347236633), (0.042016807943582535, 0.45490196347236633, 0.45490196347236633), (0.046218488365411758, 0.45490196347236633, 0.45490196347236633), (0.050420168787240982, 0.45882353186607361, 0.45882353186607361), (0.054621849209070206, 0.45882353186607361, 0.45882353186607361), (0.058823529630899429, 0.45882353186607361, 0.45882353186607361), (0.063025213778018951, 0.45882353186607361, 0.45882353186607361), (0.067226894199848175, 0.45882353186607361, 0.45882353186607361), (0.071428574621677399, 0.46274510025978088, 0.46274510025978088), (0.075630255043506622, 0.46274510025978088, 0.46274510025978088), (0.079831935465335846, 0.46274510025978088, 0.46274510025978088), (0.08403361588716507, 0.46274510025978088, 0.46274510025978088), (0.088235296308994293, 0.46274510025978088, 0.46274510025978088), (0.092436976730823517, 0.46666666865348816, 0.46666666865348816), (0.09663865715265274, 0.46666666865348816, 0.46666666865348816), (0.10084033757448196, 0.46666666865348816, 0.46666666865348816), (0.10504201799631119, 0.46666666865348816, 0.46666666865348816), (0.10924369841814041, 0.46666666865348816, 0.46666666865348816), (0.11344537883996964, 0.47058823704719543, 0.47058823704719543), (0.11764705926179886, 0.47058823704719543, 0.47058823704719543), (0.12184873968362808, 0.47058823704719543, 0.47058823704719543), (0.1260504275560379, 0.47058823704719543, 0.47058823704719543), (0.13025210797786713, 0.47058823704719543, 0.47058823704719543), (0.13445378839969635, 0.47450980544090271, 0.47450980544090271), (0.13865546882152557, 0.47450980544090271, 0.47450980544090271), (0.1428571492433548, 0.47450980544090271, 0.47450980544090271), (0.14705882966518402, 0.47450980544090271, 0.47450980544090271), (0.15126051008701324, 0.47450980544090271, 0.47450980544090271), (0.15546219050884247, 0.47843137383460999, 0.47843137383460999), (0.15966387093067169, 0.47843137383460999, 0.47843137383460999), (0.16386555135250092, 0.47843137383460999, 0.47843137383460999), (0.16806723177433014, 0.47843137383460999, 0.47843137383460999), (0.17226891219615936, 0.47843137383460999, 0.47843137383460999), (0.17647059261798859, 0.48235294222831726, 0.48235294222831726), (0.18067227303981781, 0.48235294222831726, 0.48235294222831726), (0.18487395346164703, 0.48235294222831726, 0.48235294222831726), (0.18907563388347626, 0.48235294222831726, 0.48235294222831726), (0.19327731430530548, 0.48235294222831726, 0.48235294222831726), (0.1974789947271347, 0.48627451062202454, 0.48627451062202454), (0.20168067514896393, 0.48627451062202454, 0.48627451062202454), (0.20588235557079315, 0.48627451062202454, 0.48627451062202454), (0.21008403599262238, 0.48627451062202454, 0.48627451062202454), (0.2142857164144516, 0.48627451062202454, 0.48627451062202454), (0.21848739683628082, 0.49019607901573181, 0.49019607901573181), (0.22268907725811005, 0.49019607901573181, 0.49019607901573181), (0.22689075767993927, 0.49019607901573181, 0.49019607901573181), (0.23109243810176849, 0.49019607901573181, 0.49019607901573181), (0.23529411852359772, 0.49019607901573181, 0.49019607901573181), (0.23949579894542694, 0.49411764740943909, 0.49411764740943909), (0.24369747936725616, 0.49411764740943909, 0.49411764740943909), (0.24789915978908539, 0.49411764740943909, 0.49411764740943909), (0.25210085511207581, 0.49411764740943909, 0.49411764740943909), (0.25630253553390503, 0.49411764740943909, 0.49411764740943909), (0.26050421595573425, 0.49803921580314636, 0.49803921580314636), (0.26470589637756348, 0.49803921580314636, 0.49803921580314636), (0.2689075767993927, 0.49803921580314636, 0.49803921580314636), (0.27310925722122192, 0.49803921580314636, 0.49803921580314636), (0.27731093764305115, 0.49803921580314636, 0.49803921580314636), (0.28151261806488037, 0.50196081399917603, 0.50196081399917603), (0.28571429848670959, 0.49411764740943909, 0.49411764740943909), (0.28991597890853882, 0.49019607901573181, 0.49019607901573181), (0.29411765933036804, 0.48627451062202454, 0.48627451062202454), (0.29831933975219727, 0.48235294222831726, 0.48235294222831726), (0.30252102017402649, 0.47843137383460999, 0.47843137383460999), (0.30672270059585571, 0.47058823704719543, 0.47058823704719543), (0.31092438101768494, 0.46666666865348816, 0.46666666865348816), (0.31512606143951416, 0.46274510025978088, 0.46274510025978088), (0.31932774186134338, 0.45882353186607361, 0.45882353186607361), (0.32352942228317261, 0.45098039507865906, 0.45098039507865906), (0.32773110270500183, 0.44705882668495178, 0.44705882668495178), (0.33193278312683105, 0.44313725829124451, 0.44313725829124451), (0.33613446354866028, 0.43529412150382996, 0.43529412150382996), (0.3403361439704895, 0.43137255311012268, 0.43137255311012268), (0.34453782439231873, 0.42745098471641541, 0.42745098471641541), (0.34873950481414795, 0.42352941632270813, 0.42352941632270813), (0.35294118523597717, 0.41568627953529358, 0.41568627953529358), (0.3571428656578064, 0.4117647111415863, 0.4117647111415863), (0.36134454607963562, 0.40784314274787903, 0.40784314274787903), (0.36554622650146484, 0.40000000596046448, 0.40000000596046448), (0.36974790692329407, 0.3960784375667572, 0.3960784375667572), (0.37394958734512329, 0.39215686917304993, 0.39215686917304993), (0.37815126776695251, 0.38431373238563538, 0.38431373238563538), (0.38235294818878174, 0.3803921639919281, 0.3803921639919281), (0.38655462861061096, 0.37647059559822083, 0.37647059559822083), (0.39075630903244019, 0.36862745881080627, 0.36862745881080627), (0.39495798945426941, 0.364705890417099, 0.364705890417099), (0.39915966987609863, 0.36078432202339172, 0.36078432202339172), (0.40336135029792786, 0.35294118523597717, 0.35294118523597717), (0.40756303071975708, 0.3490196168422699, 0.3490196168422699), (0.4117647111415863, 0.34509804844856262, 0.34509804844856262), (0.41596639156341553, 0.33725491166114807, 0.33725491166114807), (0.42016807198524475, 0.3333333432674408, 0.3333333432674408), (0.42436975240707397, 0.32941177487373352, 0.32941177487373352), (0.4285714328289032, 0.32156863808631897, 0.32156863808631897), (0.43277311325073242, 0.31764706969261169, 0.31764706969261169), (0.43697479367256165, 0.31372550129890442, 0.31372550129890442), (0.44117647409439087, 0.30588236451148987, 0.30588236451148987), (0.44537815451622009, 0.30196079611778259, 0.30196079611778259), (0.44957983493804932, 0.29803922772407532, 0.29803922772407532), (0.45378151535987854, 0.29019609093666077, 0.29019609093666077), (0.45798319578170776, 0.28627452254295349, 0.28627452254295349), (0.46218487620353699, 0.27843138575553894, 0.27843138575553894), (0.46638655662536621, 0.27450981736183167, 0.27450981736183167), (0.47058823704719543, 0.27843138575553894, 0.27843138575553894), (0.47478991746902466, 0.28235295414924622, 0.28235295414924622), (0.47899159789085388, 0.28235295414924622, 0.28235295414924622), (0.48319327831268311, 0.28627452254295349, 0.28627452254295349), (0.48739495873451233, 0.28627452254295349, 0.28627452254295349), (0.49159663915634155, 0.29019609093666077, 0.29019609093666077), (0.49579831957817078, 0.29411765933036804, 0.29411765933036804), (0.5, 0.29411765933036804, 0.29411765933036804), (0.50420171022415161, 0.29803922772407532, 0.29803922772407532), (0.50840336084365845, 0.29803922772407532, 0.29803922772407532), (0.51260507106781006, 0.30196079611778259, 0.30196079611778259), (0.51680672168731689, 0.30196079611778259, 0.30196079611778259), (0.52100843191146851, 0.30588236451148987, 0.30588236451148987), (0.52521008253097534, 0.30980393290519714, 0.30980393290519714), (0.52941179275512695, 0.30980393290519714, 0.30980393290519714), (0.53361344337463379, 0.31372550129890442, 0.31372550129890442), (0.5378151535987854, 0.31372550129890442, 0.31372550129890442), (0.54201680421829224, 0.31764706969261169, 0.31764706969261169), (0.54621851444244385, 0.32156863808631897, 0.32156863808631897), (0.55042016506195068, 0.32156863808631897, 0.32156863808631897), (0.55462187528610229, 0.32156863808631897, 0.32156863808631897), (0.55882352590560913, 0.32549020648002625, 0.32549020648002625), (0.56302523612976074, 0.32549020648002625, 0.32549020648002625), (0.56722688674926758, 0.32549020648002625, 0.32549020648002625), (0.57142859697341919, 0.32941177487373352, 0.32941177487373352), (0.57563024759292603, 0.32941177487373352, 0.32941177487373352), (0.57983195781707764, 0.32941177487373352, 0.32941177487373352), (0.58403360843658447, 0.3333333432674408, 0.3333333432674408), (0.58823531866073608, 0.3333333432674408, 0.3333333432674408), (0.59243696928024292, 0.3333333432674408, 0.3333333432674408), (0.59663867950439453, 0.33725491166114807, 0.33725491166114807), (0.60084033012390137, 0.33725491166114807, 0.33725491166114807), (0.60504204034805298, 0.33725491166114807, 0.33725491166114807), (0.60924369096755981, 0.34117648005485535, 0.34117648005485535), (0.61344540119171143, 0.34117648005485535, 0.34117648005485535), (0.61764705181121826, 0.34117648005485535, 0.34117648005485535), (0.62184876203536987, 0.34509804844856262, 0.34509804844856262), (0.62605041265487671, 0.34509804844856262, 0.34509804844856262), (0.63025212287902832, 0.34509804844856262, 0.34509804844856262), (0.63445377349853516, 0.3490196168422699, 0.3490196168422699), (0.63865548372268677, 0.3490196168422699, 0.3490196168422699), (0.6428571343421936, 0.3490196168422699, 0.3490196168422699), (0.64705884456634521, 0.35294118523597717, 0.35294118523597717), (0.65126049518585205, 0.35294118523597717, 0.35294118523597717), (0.65546220541000366, 0.35294118523597717, 0.35294118523597717), (0.6596638560295105, 0.35686275362968445, 0.35686275362968445), (0.66386556625366211, 0.35686275362968445, 0.35686275362968445), (0.66806721687316895, 0.35686275362968445, 0.35686275362968445), (0.67226892709732056, 0.36078432202339172, 0.36078432202339172), (0.67647057771682739, 0.36078432202339172, 0.36078432202339172), (0.680672287940979, 0.36078432202339172, 0.36078432202339172), (0.68487393856048584, 0.364705890417099, 0.364705890417099), (0.68907564878463745, 0.364705890417099, 0.364705890417099), (0.69327729940414429, 0.364705890417099, 0.364705890417099), (0.6974790096282959, 0.36862745881080627, 0.36862745881080627), (0.70168066024780273, 0.36862745881080627, 0.36862745881080627), (0.70588237047195435, 0.36862745881080627, 0.36862745881080627), (0.71008402109146118, 0.37254902720451355, 0.37254902720451355), (0.71428573131561279, 0.37254902720451355, 0.37254902720451355), (0.71848738193511963, 0.37254902720451355, 0.37254902720451355), (0.72268909215927124, 0.37647059559822083, 0.37647059559822083), (0.72689074277877808, 0.37647059559822083, 0.37647059559822083), (0.73109245300292969, 0.3803921639919281, 0.3803921639919281), (0.73529410362243652, 0.3803921639919281, 0.3803921639919281), (0.73949581384658813, 0.3803921639919281, 0.3803921639919281), (0.74369746446609497, 0.38431373238563538, 0.38431373238563538), (0.74789917469024658, 0.38431373238563538, 0.38431373238563538), (0.75210082530975342, 0.38431373238563538, 0.38431373238563538), (0.75630253553390503, 0.38823530077934265, 0.38823530077934265), (0.76050418615341187, 0.38823530077934265, 0.38823530077934265), (0.76470589637756348, 0.38823530077934265, 0.38823530077934265), (0.76890754699707031, 0.39215686917304993, 0.39215686917304993), (0.77310925722122192, 0.39215686917304993, 0.39215686917304993), (0.77731090784072876, 0.39215686917304993, 0.39215686917304993), (0.78151261806488037, 0.3960784375667572, 0.3960784375667572), (0.78571426868438721, 0.3960784375667572, 0.3960784375667572), (0.78991597890853882, 0.40784314274787903, 0.40784314274787903), (0.79411762952804565, 0.41568627953529358, 0.41568627953529358), (0.79831933975219727, 0.42352941632270813, 0.42352941632270813), (0.8025209903717041, 0.43529412150382996, 0.43529412150382996), (0.80672270059585571, 0.44313725829124451, 0.44313725829124451), (0.81092435121536255, 0.45490196347236633, 0.45490196347236633), (0.81512606143951416, 0.46274510025978088, 0.46274510025978088), (0.819327712059021, 0.47450980544090271, 0.47450980544090271), (0.82352942228317261, 0.48235294222831726, 0.48235294222831726), (0.82773107290267944, 0.49411764740943909, 0.49411764740943909), (0.83193278312683105, 0.5058823823928833, 0.5058823823928833), (0.83613443374633789, 0.51372551918029785, 0.51372551918029785), (0.8403361439704895, 0.52549022436141968, 0.52549022436141968), (0.84453779458999634, 0.5372549295425415, 0.5372549295425415), (0.84873950481414795, 0.54509806632995605, 0.54509806632995605), (0.85294115543365479, 0.55686277151107788, 0.55686277151107788), (0.8571428656578064, 0.56862747669219971, 0.56862747669219971), (0.86134451627731323, 0.58039218187332153, 0.58039218187332153), (0.86554622650146484, 0.58823531866073608, 0.58823531866073608), (0.86974787712097168, 0.60000002384185791, 0.60000002384185791), (0.87394958734512329, 0.61176472902297974, 0.61176472902297974), (0.87815123796463013, 0.62352943420410156, 0.62352943420410156), (0.88235294818878174, 0.63529413938522339, 0.63529413938522339), (0.88655459880828857, 0.64705884456634521, 0.64705884456634521), (0.89075630903244019, 0.65882354974746704, 0.65882354974746704), (0.89495795965194702, 0.66666668653488159, 0.66666668653488159), (0.89915966987609863, 0.67843139171600342, 0.67843139171600342), (0.90336132049560547, 0.69019609689712524, 0.69019609689712524), (0.90756303071975708, 0.70196080207824707, 0.70196080207824707), (0.91176468133926392, 0.7137255072593689, 0.7137255072593689), (0.91596639156341553, 0.72549021244049072, 0.72549021244049072), (0.92016804218292236, 0.74117648601531982, 0.74117648601531982), (0.92436975240707397, 0.75294119119644165, 0.75294119119644165), (0.92857140302658081, 0.76470589637756348, 0.76470589637756348), (0.93277311325073242, 0.7764706015586853, 0.7764706015586853), (0.93697476387023926, 0.78823530673980713, 0.78823530673980713), (0.94117647409439087, 0.80000001192092896, 0.80000001192092896), (0.94537812471389771, 0.81176471710205078, 0.81176471710205078), (0.94957983493804932, 0.82745099067687988, 0.82745099067687988), (0.95378148555755615, 0.83921569585800171, 0.83921569585800171), (0.95798319578170776, 0.85098040103912354, 0.85098040103912354), (0.9621848464012146, 0.86274510622024536, 0.86274510622024536), (0.96638655662536621, 0.87843137979507446, 0.87843137979507446), (0.97058820724487305, 0.89019608497619629, 0.89019608497619629), (0.97478991746902466, 0.90196079015731812, 0.90196079015731812), (0.97899156808853149, 0.91764706373214722, 0.91764706373214722), (0.98319327831268311, 0.92941176891326904, 0.92941176891326904), (0.98739492893218994, 0.94509804248809814, 0.94509804248809814), (0.99159663915634155, 0.95686274766921997, 0.95686274766921997), (0.99579828977584839, 0.97254902124404907, 0.97254902124404907), (1.0, 0.9843137264251709, 0.9843137264251709)], 'green': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0, 0.0), (0.0084033617749810219, 0.0, 0.0), (0.012605042196810246, 0.0, 0.0), (0.016806723549962044, 0.0, 0.0), (0.021008403971791267, 0.0, 0.0), (0.025210084393620491, 0.0, 0.0), (0.029411764815449715, 0.0, 0.0), (0.033613447099924088, 0.011764706112444401, 0.011764706112444401), (0.037815127521753311, 0.023529412224888802, 0.023529412224888802), (0.042016807943582535, 0.031372550874948502, 0.031372550874948502), (0.046218488365411758, 0.043137256056070328, 0.043137256056070328), (0.050420168787240982, 0.050980392843484879, 0.050980392843484879), (0.054621849209070206, 0.062745101749897003, 0.062745101749897003), (0.058823529630899429, 0.070588238537311554, 0.070588238537311554), (0.063025213778018951, 0.08235294371843338, 0.08235294371843338), (0.067226894199848175, 0.090196080505847931, 0.090196080505847931), (0.071428574621677399, 0.10196078568696976, 0.10196078568696976), (0.075630255043506622, 0.10980392247438431, 0.10980392247438431), (0.079831935465335846, 0.12156862765550613, 0.12156862765550613), (0.08403361588716507, 0.12941177189350128, 0.12941177189350128), (0.088235296308994293, 0.14117647707462311, 0.14117647707462311), (0.092436976730823517, 0.14901961386203766, 0.14901961386203766), (0.09663865715265274, 0.16078431904315948, 0.16078431904315948), (0.10084033757448196, 0.16862745583057404, 0.16862745583057404), (0.10504201799631119, 0.17647059261798859, 0.17647059261798859), (0.10924369841814041, 0.18823529779911041, 0.18823529779911041), (0.11344537883996964, 0.19607843458652496, 0.19607843458652496), (0.11764705926179886, 0.20392157137393951, 0.20392157137393951), (0.12184873968362808, 0.21568627655506134, 0.21568627655506134), (0.1260504275560379, 0.22352941334247589, 0.22352941334247589), (0.13025210797786713, 0.23137255012989044, 0.23137255012989044), (0.13445378839969635, 0.23921568691730499, 0.23921568691730499), (0.13865546882152557, 0.25098040699958801, 0.25098040699958801), (0.1428571492433548, 0.25882354378700256, 0.25882354378700256), (0.14705882966518402, 0.26666668057441711, 0.26666668057441711), (0.15126051008701324, 0.27450981736183167, 0.27450981736183167), (0.15546219050884247, 0.28235295414924622, 0.28235295414924622), (0.15966387093067169, 0.29019609093666077, 0.29019609093666077), (0.16386555135250092, 0.30196079611778259, 0.30196079611778259), (0.16806723177433014, 0.30980393290519714, 0.30980393290519714), (0.17226891219615936, 0.31764706969261169, 0.31764706969261169), (0.17647059261798859, 0.32549020648002625, 0.32549020648002625), (0.18067227303981781, 0.3333333432674408, 0.3333333432674408), (0.18487395346164703, 0.34117648005485535, 0.34117648005485535), (0.18907563388347626, 0.3490196168422699, 0.3490196168422699), (0.19327731430530548, 0.35686275362968445, 0.35686275362968445), (0.1974789947271347, 0.364705890417099, 0.364705890417099), (0.20168067514896393, 0.37254902720451355, 0.37254902720451355), (0.20588235557079315, 0.3803921639919281, 0.3803921639919281), (0.21008403599262238, 0.38823530077934265, 0.38823530077934265), (0.2142857164144516, 0.39215686917304993, 0.39215686917304993), (0.21848739683628082, 0.40000000596046448, 0.40000000596046448), (0.22268907725811005, 0.40784314274787903, 0.40784314274787903), (0.22689075767993927, 0.41568627953529358, 0.41568627953529358), (0.23109243810176849, 0.42352941632270813, 0.42352941632270813), (0.23529411852359772, 0.42745098471641541, 0.42745098471641541), (0.23949579894542694, 0.43529412150382996, 0.43529412150382996), (0.24369747936725616, 0.44313725829124451, 0.44313725829124451), (0.24789915978908539, 0.45098039507865906, 0.45098039507865906), (0.25210085511207581, 0.45490196347236633, 0.45490196347236633), (0.25630253553390503, 0.46274510025978088, 0.46274510025978088), (0.26050421595573425, 0.47058823704719543, 0.47058823704719543), (0.26470589637756348, 0.47450980544090271, 0.47450980544090271), (0.2689075767993927, 0.48235294222831726, 0.48235294222831726), (0.27310925722122192, 0.49019607901573181, 0.49019607901573181), (0.27731093764305115, 0.49411764740943909, 0.49411764740943909), (0.28151261806488037, 0.50196081399917603, 0.50196081399917603), (0.28571429848670959, 0.50196081399917603, 0.50196081399917603), (0.28991597890853882, 0.5058823823928833, 0.5058823823928833), (0.29411765933036804, 0.5058823823928833, 0.5058823823928833), (0.29831933975219727, 0.50980395078659058, 0.50980395078659058), (0.30252102017402649, 0.51372551918029785, 0.51372551918029785), (0.30672270059585571, 0.51372551918029785, 0.51372551918029785), (0.31092438101768494, 0.51764708757400513, 0.51764708757400513), (0.31512606143951416, 0.5215686559677124, 0.5215686559677124), (0.31932774186134338, 0.5215686559677124, 0.5215686559677124), (0.32352942228317261, 0.52549022436141968, 0.52549022436141968), (0.32773110270500183, 0.52549022436141968, 0.52549022436141968), (0.33193278312683105, 0.52941179275512695, 0.52941179275512695), (0.33613446354866028, 0.53333336114883423, 0.53333336114883423), (0.3403361439704895, 0.53333336114883423, 0.53333336114883423), (0.34453782439231873, 0.5372549295425415, 0.5372549295425415), (0.34873950481414795, 0.54117649793624878, 0.54117649793624878), (0.35294118523597717, 0.54117649793624878, 0.54117649793624878), (0.3571428656578064, 0.54509806632995605, 0.54509806632995605), (0.36134454607963562, 0.54901963472366333, 0.54901963472366333), (0.36554622650146484, 0.54901963472366333, 0.54901963472366333), (0.36974790692329407, 0.55294120311737061, 0.55294120311737061), (0.37394958734512329, 0.55294120311737061, 0.55294120311737061), (0.37815126776695251, 0.55686277151107788, 0.55686277151107788), (0.38235294818878174, 0.56078433990478516, 0.56078433990478516), (0.38655462861061096, 0.56078433990478516, 0.56078433990478516), (0.39075630903244019, 0.56470590829849243, 0.56470590829849243), (0.39495798945426941, 0.56862747669219971, 0.56862747669219971), (0.39915966987609863, 0.56862747669219971, 0.56862747669219971), (0.40336135029792786, 0.57254904508590698, 0.57254904508590698), (0.40756303071975708, 0.57254904508590698, 0.57254904508590698), (0.4117647111415863, 0.57647061347961426, 0.57647061347961426), (0.41596639156341553, 0.58039218187332153, 0.58039218187332153), (0.42016807198524475, 0.58039218187332153, 0.58039218187332153), (0.42436975240707397, 0.58431375026702881, 0.58431375026702881), (0.4285714328289032, 0.58823531866073608, 0.58823531866073608), (0.43277311325073242, 0.58823531866073608, 0.58823531866073608), (0.43697479367256165, 0.59215688705444336, 0.59215688705444336), (0.44117647409439087, 0.59215688705444336, 0.59215688705444336), (0.44537815451622009, 0.59607845544815063, 0.59607845544815063), (0.44957983493804932, 0.60000002384185791, 0.60000002384185791), (0.45378151535987854, 0.60000002384185791, 0.60000002384185791), (0.45798319578170776, 0.60392159223556519, 0.60392159223556519), (0.46218487620353699, 0.60784316062927246, 0.60784316062927246), (0.46638655662536621, 0.60784316062927246, 0.60784316062927246), (0.47058823704719543, 0.61176472902297974, 0.61176472902297974), (0.47478991746902466, 0.61176472902297974, 0.61176472902297974), (0.47899159789085388, 0.61568629741668701, 0.61568629741668701), (0.48319327831268311, 0.61960786581039429, 0.61960786581039429), (0.48739495873451233, 0.61960786581039429, 0.61960786581039429), (0.49159663915634155, 0.62352943420410156, 0.62352943420410156), (0.49579831957817078, 0.62745100259780884, 0.62745100259780884), (0.5, 0.62745100259780884, 0.62745100259780884), (0.50420171022415161, 0.63137257099151611, 0.63137257099151611), (0.50840336084365845, 0.63137257099151611, 0.63137257099151611), (0.51260507106781006, 0.63529413938522339, 0.63529413938522339), (0.51680672168731689, 0.63921570777893066, 0.63921570777893066), (0.52100843191146851, 0.63921570777893066, 0.63921570777893066), (0.52521008253097534, 0.64313727617263794, 0.64313727617263794), (0.52941179275512695, 0.64705884456634521, 0.64705884456634521), (0.53361344337463379, 0.64705884456634521, 0.64705884456634521), (0.5378151535987854, 0.65098041296005249, 0.65098041296005249), (0.54201680421829224, 0.65098041296005249, 0.65098041296005249), (0.54621851444244385, 0.65490198135375977, 0.65490198135375977), (0.55042016506195068, 0.65882354974746704, 0.65882354974746704), (0.55462187528610229, 0.65882354974746704, 0.65882354974746704), (0.55882352590560913, 0.65882354974746704, 0.65882354974746704), (0.56302523612976074, 0.66274511814117432, 0.66274511814117432), (0.56722688674926758, 0.66274511814117432, 0.66274511814117432), (0.57142859697341919, 0.66666668653488159, 0.66666668653488159), (0.57563024759292603, 0.66666668653488159, 0.66666668653488159), (0.57983195781707764, 0.67058825492858887, 0.67058825492858887), (0.58403360843658447, 0.67058825492858887, 0.67058825492858887), (0.58823531866073608, 0.67450982332229614, 0.67450982332229614), (0.59243696928024292, 0.67450982332229614, 0.67450982332229614), (0.59663867950439453, 0.67450982332229614, 0.67450982332229614), (0.60084033012390137, 0.67843139171600342, 0.67843139171600342), (0.60504204034805298, 0.67843139171600342, 0.67843139171600342), (0.60924369096755981, 0.68235296010971069, 0.68235296010971069), (0.61344540119171143, 0.68235296010971069, 0.68235296010971069), (0.61764705181121826, 0.68627452850341797, 0.68627452850341797), (0.62184876203536987, 0.68627452850341797, 0.68627452850341797), (0.62605041265487671, 0.68627452850341797, 0.68627452850341797), (0.63025212287902832, 0.69019609689712524, 0.69019609689712524), (0.63445377349853516, 0.69019609689712524, 0.69019609689712524), (0.63865548372268677, 0.69411766529083252, 0.69411766529083252), (0.6428571343421936, 0.69411766529083252, 0.69411766529083252), (0.64705884456634521, 0.69803923368453979, 0.69803923368453979), (0.65126049518585205, 0.69803923368453979, 0.69803923368453979), (0.65546220541000366, 0.70196080207824707, 0.70196080207824707), (0.6596638560295105, 0.70196080207824707, 0.70196080207824707), (0.66386556625366211, 0.70196080207824707, 0.70196080207824707), (0.66806721687316895, 0.70588237047195435, 0.70588237047195435), (0.67226892709732056, 0.70588237047195435, 0.70588237047195435), (0.67647057771682739, 0.70980393886566162, 0.70980393886566162), (0.680672287940979, 0.70980393886566162, 0.70980393886566162), (0.68487393856048584, 0.7137255072593689, 0.7137255072593689), (0.68907564878463745, 0.7137255072593689, 0.7137255072593689), (0.69327729940414429, 0.71764707565307617, 0.71764707565307617), (0.6974790096282959, 0.71764707565307617, 0.71764707565307617), (0.70168066024780273, 0.7137255072593689, 0.7137255072593689), (0.70588237047195435, 0.70980393886566162, 0.70980393886566162), (0.71008402109146118, 0.70980393886566162, 0.70980393886566162), (0.71428573131561279, 0.70588237047195435, 0.70588237047195435), (0.71848738193511963, 0.70196080207824707, 0.70196080207824707), (0.72268909215927124, 0.69803923368453979, 0.69803923368453979), (0.72689074277877808, 0.69411766529083252, 0.69411766529083252), (0.73109245300292969, 0.69019609689712524, 0.69019609689712524), (0.73529410362243652, 0.68627452850341797, 0.68627452850341797), (0.73949581384658813, 0.68235296010971069, 0.68235296010971069), (0.74369746446609497, 0.67843139171600342, 0.67843139171600342), (0.74789917469024658, 0.67450982332229614, 0.67450982332229614), (0.75210082530975342, 0.67058825492858887, 0.67058825492858887), (0.75630253553390503, 0.66666668653488159, 0.66666668653488159), (0.76050418615341187, 0.66274511814117432, 0.66274511814117432), (0.76470589637756348, 0.65882354974746704, 0.65882354974746704), (0.76890754699707031, 0.65490198135375977, 0.65490198135375977), (0.77310925722122192, 0.65098041296005249, 0.65098041296005249), (0.77731090784072876, 0.64705884456634521, 0.64705884456634521), (0.78151261806488037, 0.64313727617263794, 0.64313727617263794), (0.78571426868438721, 0.63921570777893066, 0.63921570777893066), (0.78991597890853882, 0.63921570777893066, 0.63921570777893066), (0.79411762952804565, 0.64313727617263794, 0.64313727617263794), (0.79831933975219727, 0.64313727617263794, 0.64313727617263794), (0.8025209903717041, 0.64705884456634521, 0.64705884456634521), (0.80672270059585571, 0.64705884456634521, 0.64705884456634521), (0.81092435121536255, 0.65098041296005249, 0.65098041296005249), (0.81512606143951416, 0.65490198135375977, 0.65490198135375977), (0.819327712059021, 0.65490198135375977, 0.65490198135375977), (0.82352942228317261, 0.65882354974746704, 0.65882354974746704), (0.82773107290267944, 0.66274511814117432, 0.66274511814117432), (0.83193278312683105, 0.66666668653488159, 0.66666668653488159), (0.83613443374633789, 0.67058825492858887, 0.67058825492858887), (0.8403361439704895, 0.67450982332229614, 0.67450982332229614), (0.84453779458999634, 0.67843139171600342, 0.67843139171600342), (0.84873950481414795, 0.68235296010971069, 0.68235296010971069), (0.85294115543365479, 0.68627452850341797, 0.68627452850341797), (0.8571428656578064, 0.69019609689712524, 0.69019609689712524), (0.86134451627731323, 0.69411766529083252, 0.69411766529083252), (0.86554622650146484, 0.69803923368453979, 0.69803923368453979), (0.86974787712097168, 0.70196080207824707, 0.70196080207824707), (0.87394958734512329, 0.70980393886566162, 0.70980393886566162), (0.87815123796463013, 0.7137255072593689, 0.7137255072593689), (0.88235294818878174, 0.72156864404678345, 0.72156864404678345), (0.88655459880828857, 0.72549021244049072, 0.72549021244049072), (0.89075630903244019, 0.73333334922790527, 0.73333334922790527), (0.89495795965194702, 0.73725491762161255, 0.73725491762161255), (0.89915966987609863, 0.7450980544090271, 0.7450980544090271), (0.90336132049560547, 0.75294119119644165, 0.75294119119644165), (0.90756303071975708, 0.7607843279838562, 0.7607843279838562), (0.91176468133926392, 0.76862746477127075, 0.76862746477127075), (0.91596639156341553, 0.7764706015586853, 0.7764706015586853), (0.92016804218292236, 0.78431373834609985, 0.78431373834609985), (0.92436975240707397, 0.7921568751335144, 0.7921568751335144), (0.92857140302658081, 0.80000001192092896, 0.80000001192092896), (0.93277311325073242, 0.80784314870834351, 0.80784314870834351), (0.93697476387023926, 0.81568628549575806, 0.81568628549575806), (0.94117647409439087, 0.82745099067687988, 0.82745099067687988), (0.94537812471389771, 0.83529412746429443, 0.83529412746429443), (0.94957983493804932, 0.84313726425170898, 0.84313726425170898), (0.95378148555755615, 0.85490196943283081, 0.85490196943283081), (0.95798319578170776, 0.86666667461395264, 0.86666667461395264), (0.9621848464012146, 0.87450981140136719, 0.87450981140136719), (0.96638655662536621, 0.88627451658248901, 0.88627451658248901), (0.97058820724487305, 0.89803922176361084, 0.89803922176361084), (0.97478991746902466, 0.90980392694473267, 0.90980392694473267), (0.97899156808853149, 0.92156863212585449, 0.92156863212585449), (0.98319327831268311, 0.93333333730697632, 0.93333333730697632), (0.98739492893218994, 0.94509804248809814, 0.94509804248809814), (0.99159663915634155, 0.95686274766921997, 0.95686274766921997), (0.99579828977584839, 0.97254902124404907, 0.97254902124404907), (1.0, 0.9843137264251709, 0.9843137264251709)], 'red': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0, 0.0), (0.0084033617749810219, 0.0, 0.0), (0.012605042196810246, 0.0, 0.0), (0.016806723549962044, 0.0, 0.0), (0.021008403971791267, 0.0, 0.0), (0.025210084393620491, 0.0, 0.0), (0.029411764815449715, 0.0, 0.0), (0.033613447099924088, 0.0, 0.0), (0.037815127521753311, 0.0039215688593685627, 0.0039215688593685627), (0.042016807943582535, 0.0078431377187371254, 0.0078431377187371254), (0.046218488365411758, 0.0078431377187371254, 0.0078431377187371254), (0.050420168787240982, 0.011764706112444401, 0.011764706112444401), (0.054621849209070206, 0.015686275437474251, 0.015686275437474251), (0.058823529630899429, 0.019607843831181526, 0.019607843831181526), (0.063025213778018951, 0.019607843831181526, 0.019607843831181526), (0.067226894199848175, 0.023529412224888802, 0.023529412224888802), (0.071428574621677399, 0.027450980618596077, 0.027450980618596077), (0.075630255043506622, 0.031372550874948502, 0.031372550874948502), (0.079831935465335846, 0.031372550874948502, 0.031372550874948502), (0.08403361588716507, 0.035294119268655777, 0.035294119268655777), (0.088235296308994293, 0.039215687662363052, 0.039215687662363052), (0.092436976730823517, 0.043137256056070328, 0.043137256056070328), (0.09663865715265274, 0.043137256056070328, 0.043137256056070328), (0.10084033757448196, 0.047058824449777603, 0.047058824449777603), (0.10504201799631119, 0.050980392843484879, 0.050980392843484879), (0.10924369841814041, 0.054901961237192154, 0.054901961237192154), (0.11344537883996964, 0.058823529630899429, 0.058823529630899429), (0.11764705926179886, 0.058823529630899429, 0.058823529630899429), (0.12184873968362808, 0.062745101749897003, 0.062745101749897003), (0.1260504275560379, 0.066666670143604279, 0.066666670143604279), (0.13025210797786713, 0.070588238537311554, 0.070588238537311554), (0.13445378839969635, 0.070588238537311554, 0.070588238537311554), (0.13865546882152557, 0.074509806931018829, 0.074509806931018829), (0.1428571492433548, 0.078431375324726105, 0.078431375324726105), (0.14705882966518402, 0.08235294371843338, 0.08235294371843338), (0.15126051008701324, 0.086274512112140656, 0.086274512112140656), (0.15546219050884247, 0.086274512112140656, 0.086274512112140656), (0.15966387093067169, 0.090196080505847931, 0.090196080505847931), (0.16386555135250092, 0.094117648899555206, 0.094117648899555206), (0.16806723177433014, 0.098039217293262482, 0.098039217293262482), (0.17226891219615936, 0.10196078568696976, 0.10196078568696976), (0.17647059261798859, 0.10196078568696976, 0.10196078568696976), (0.18067227303981781, 0.10588235408067703, 0.10588235408067703), (0.18487395346164703, 0.10980392247438431, 0.10980392247438431), (0.18907563388347626, 0.11372549086809158, 0.11372549086809158), (0.19327731430530548, 0.11764705926179886, 0.11764705926179886), (0.1974789947271347, 0.12156862765550613, 0.12156862765550613), (0.20168067514896393, 0.12156862765550613, 0.12156862765550613), (0.20588235557079315, 0.12549020349979401, 0.12549020349979401), (0.21008403599262238, 0.12941177189350128, 0.12941177189350128), (0.2142857164144516, 0.13333334028720856, 0.13333334028720856), (0.21848739683628082, 0.13725490868091583, 0.13725490868091583), (0.22268907725811005, 0.14117647707462311, 0.14117647707462311), (0.22689075767993927, 0.14117647707462311, 0.14117647707462311), (0.23109243810176849, 0.14509804546833038, 0.14509804546833038), (0.23529411852359772, 0.14901961386203766, 0.14901961386203766), (0.23949579894542694, 0.15294118225574493, 0.15294118225574493), (0.24369747936725616, 0.15686275064945221, 0.15686275064945221), (0.24789915978908539, 0.16078431904315948, 0.16078431904315948), (0.25210085511207581, 0.16078431904315948, 0.16078431904315948), (0.25630253553390503, 0.16470588743686676, 0.16470588743686676), (0.26050421595573425, 0.16862745583057404, 0.16862745583057404), (0.26470589637756348, 0.17254902422428131, 0.17254902422428131), (0.2689075767993927, 0.17647059261798859, 0.17647059261798859), (0.27310925722122192, 0.18039216101169586, 0.18039216101169586), (0.27731093764305115, 0.18431372940540314, 0.18431372940540314), (0.28151261806488037, 0.18823529779911041, 0.18823529779911041), (0.28571429848670959, 0.18823529779911041, 0.18823529779911041), (0.28991597890853882, 0.18823529779911041, 0.18823529779911041), (0.29411765933036804, 0.19215686619281769, 0.19215686619281769), (0.29831933975219727, 0.19215686619281769, 0.19215686619281769), (0.30252102017402649, 0.19607843458652496, 0.19607843458652496), (0.30672270059585571, 0.19607843458652496, 0.19607843458652496), (0.31092438101768494, 0.20000000298023224, 0.20000000298023224), (0.31512606143951416, 0.20000000298023224, 0.20000000298023224), (0.31932774186134338, 0.20392157137393951, 0.20392157137393951), (0.32352942228317261, 0.20392157137393951, 0.20392157137393951), (0.32773110270500183, 0.20784313976764679, 0.20784313976764679), (0.33193278312683105, 0.20784313976764679, 0.20784313976764679), (0.33613446354866028, 0.21176470816135406, 0.21176470816135406), (0.3403361439704895, 0.21176470816135406, 0.21176470816135406), (0.34453782439231873, 0.21568627655506134, 0.21568627655506134), (0.34873950481414795, 0.21568627655506134, 0.21568627655506134), (0.35294118523597717, 0.21960784494876862, 0.21960784494876862), (0.3571428656578064, 0.21960784494876862, 0.21960784494876862), (0.36134454607963562, 0.22352941334247589, 0.22352941334247589), (0.36554622650146484, 0.22352941334247589, 0.22352941334247589), (0.36974790692329407, 0.22745098173618317, 0.22745098173618317), (0.37394958734512329, 0.22745098173618317, 0.22745098173618317), (0.37815126776695251, 0.23137255012989044, 0.23137255012989044), (0.38235294818878174, 0.23137255012989044, 0.23137255012989044), (0.38655462861061096, 0.23529411852359772, 0.23529411852359772), (0.39075630903244019, 0.23921568691730499, 0.23921568691730499), (0.39495798945426941, 0.23921568691730499, 0.23921568691730499), (0.39915966987609863, 0.24313725531101227, 0.24313725531101227), (0.40336135029792786, 0.24313725531101227, 0.24313725531101227), (0.40756303071975708, 0.24705882370471954, 0.24705882370471954), (0.4117647111415863, 0.24705882370471954, 0.24705882370471954), (0.41596639156341553, 0.25098040699958801, 0.25098040699958801), (0.42016807198524475, 0.25098040699958801, 0.25098040699958801), (0.42436975240707397, 0.25490197539329529, 0.25490197539329529), (0.4285714328289032, 0.25490197539329529, 0.25490197539329529), (0.43277311325073242, 0.25882354378700256, 0.25882354378700256), (0.43697479367256165, 0.26274511218070984, 0.26274511218070984), (0.44117647409439087, 0.26274511218070984, 0.26274511218070984), (0.44537815451622009, 0.26666668057441711, 0.26666668057441711), (0.44957983493804932, 0.26666668057441711, 0.26666668057441711), (0.45378151535987854, 0.27058824896812439, 0.27058824896812439), (0.45798319578170776, 0.27058824896812439, 0.27058824896812439), (0.46218487620353699, 0.27450981736183167, 0.27450981736183167), (0.46638655662536621, 0.27843138575553894, 0.27843138575553894), (0.47058823704719543, 0.28627452254295349, 0.28627452254295349), (0.47478991746902466, 0.29803922772407532, 0.29803922772407532), (0.47899159789085388, 0.30588236451148987, 0.30588236451148987), (0.48319327831268311, 0.31764706969261169, 0.31764706969261169), (0.48739495873451233, 0.32549020648002625, 0.32549020648002625), (0.49159663915634155, 0.33725491166114807, 0.33725491166114807), (0.49579831957817078, 0.34509804844856262, 0.34509804844856262), (0.5, 0.35686275362968445, 0.35686275362968445), (0.50420171022415161, 0.36862745881080627, 0.36862745881080627), (0.50840336084365845, 0.37647059559822083, 0.37647059559822083), (0.51260507106781006, 0.38823530077934265, 0.38823530077934265), (0.51680672168731689, 0.3960784375667572, 0.3960784375667572), (0.52100843191146851, 0.40784314274787903, 0.40784314274787903), (0.52521008253097534, 0.41568627953529358, 0.41568627953529358), (0.52941179275512695, 0.42745098471641541, 0.42745098471641541), (0.53361344337463379, 0.43529412150382996, 0.43529412150382996), (0.5378151535987854, 0.44705882668495178, 0.44705882668495178), (0.54201680421829224, 0.45882353186607361, 0.45882353186607361), (0.54621851444244385, 0.46666666865348816, 0.46666666865348816), (0.55042016506195068, 0.47450980544090271, 0.47450980544090271), (0.55462187528610229, 0.47843137383460999, 0.47843137383460999), (0.55882352590560913, 0.48627451062202454, 0.48627451062202454), (0.56302523612976074, 0.49411764740943909, 0.49411764740943909), (0.56722688674926758, 0.50196081399917603, 0.50196081399917603), (0.57142859697341919, 0.5058823823928833, 0.5058823823928833), (0.57563024759292603, 0.51372551918029785, 0.51372551918029785), (0.57983195781707764, 0.5215686559677124, 0.5215686559677124), (0.58403360843658447, 0.52941179275512695, 0.52941179275512695), (0.58823531866073608, 0.53333336114883423, 0.53333336114883423), (0.59243696928024292, 0.54117649793624878, 0.54117649793624878), (0.59663867950439453, 0.54901963472366333, 0.54901963472366333), (0.60084033012390137, 0.55294120311737061, 0.55294120311737061), (0.60504204034805298, 0.56078433990478516, 0.56078433990478516), (0.60924369096755981, 0.56862747669219971, 0.56862747669219971), (0.61344540119171143, 0.57647061347961426, 0.57647061347961426), (0.61764705181121826, 0.58431375026702881, 0.58431375026702881), (0.62184876203536987, 0.58823531866073608, 0.58823531866073608), (0.62605041265487671, 0.59607845544815063, 0.59607845544815063), (0.63025212287902832, 0.60392159223556519, 0.60392159223556519), (0.63445377349853516, 0.61176472902297974, 0.61176472902297974), (0.63865548372268677, 0.61568629741668701, 0.61568629741668701), (0.6428571343421936, 0.62352943420410156, 0.62352943420410156), (0.64705884456634521, 0.63137257099151611, 0.63137257099151611), (0.65126049518585205, 0.63921570777893066, 0.63921570777893066), (0.65546220541000366, 0.64705884456634521, 0.64705884456634521), (0.6596638560295105, 0.65098041296005249, 0.65098041296005249), (0.66386556625366211, 0.65882354974746704, 0.65882354974746704), (0.66806721687316895, 0.66666668653488159, 0.66666668653488159), (0.67226892709732056, 0.67450982332229614, 0.67450982332229614), (0.67647057771682739, 0.68235296010971069, 0.68235296010971069), (0.680672287940979, 0.68627452850341797, 0.68627452850341797), (0.68487393856048584, 0.69411766529083252, 0.69411766529083252), (0.68907564878463745, 0.70196080207824707, 0.70196080207824707), (0.69327729940414429, 0.70980393886566162, 0.70980393886566162), (0.6974790096282959, 0.71764707565307617, 0.71764707565307617), (0.70168066024780273, 0.71764707565307617, 0.71764707565307617), (0.70588237047195435, 0.72156864404678345, 0.72156864404678345), (0.71008402109146118, 0.72156864404678345, 0.72156864404678345), (0.71428573131561279, 0.72549021244049072, 0.72549021244049072), (0.71848738193511963, 0.72549021244049072, 0.72549021244049072), (0.72268909215927124, 0.729411780834198, 0.729411780834198), (0.72689074277877808, 0.729411780834198, 0.729411780834198), (0.73109245300292969, 0.73333334922790527, 0.73333334922790527), (0.73529410362243652, 0.73333334922790527, 0.73333334922790527), (0.73949581384658813, 0.73333334922790527, 0.73333334922790527), (0.74369746446609497, 0.73725491762161255, 0.73725491762161255), (0.74789917469024658, 0.73725491762161255, 0.73725491762161255), (0.75210082530975342, 0.74117648601531982, 0.74117648601531982), (0.75630253553390503, 0.74117648601531982, 0.74117648601531982), (0.76050418615341187, 0.7450980544090271, 0.7450980544090271), (0.76470589637756348, 0.7450980544090271, 0.7450980544090271), (0.76890754699707031, 0.7450980544090271, 0.7450980544090271), (0.77310925722122192, 0.74901962280273438, 0.74901962280273438), (0.77731090784072876, 0.74901962280273438, 0.74901962280273438), (0.78151261806488037, 0.75294119119644165, 0.75294119119644165), (0.78571426868438721, 0.75294119119644165, 0.75294119119644165), (0.78991597890853882, 0.75686275959014893, 0.75686275959014893), (0.79411762952804565, 0.76470589637756348, 0.76470589637756348), (0.79831933975219727, 0.76862746477127075, 0.76862746477127075), (0.8025209903717041, 0.77254903316497803, 0.77254903316497803), (0.80672270059585571, 0.7764706015586853, 0.7764706015586853), (0.81092435121536255, 0.78039216995239258, 0.78039216995239258), (0.81512606143951416, 0.78823530673980713, 0.78823530673980713), (0.819327712059021, 0.7921568751335144, 0.7921568751335144), (0.82352942228317261, 0.79607844352722168, 0.79607844352722168), (0.82773107290267944, 0.80000001192092896, 0.80000001192092896), (0.83193278312683105, 0.80392158031463623, 0.80392158031463623), (0.83613443374633789, 0.81176471710205078, 0.81176471710205078), (0.8403361439704895, 0.81568628549575806, 0.81568628549575806), (0.84453779458999634, 0.81960785388946533, 0.81960785388946533), (0.84873950481414795, 0.82352942228317261, 0.82352942228317261), (0.85294115543365479, 0.82745099067687988, 0.82745099067687988), (0.8571428656578064, 0.83529412746429443, 0.83529412746429443), (0.86134451627731323, 0.83921569585800171, 0.83921569585800171), (0.86554622650146484, 0.84313726425170898, 0.84313726425170898), (0.86974787712097168, 0.84705883264541626, 0.84705883264541626), (0.87394958734512329, 0.85098040103912354, 0.85098040103912354), (0.87815123796463013, 0.85882353782653809, 0.85882353782653809), (0.88235294818878174, 0.86274510622024536, 0.86274510622024536), (0.88655459880828857, 0.86666667461395264, 0.86666667461395264), (0.89075630903244019, 0.87058824300765991, 0.87058824300765991), (0.89495795965194702, 0.87450981140136719, 0.87450981140136719), (0.89915966987609863, 0.88235294818878174, 0.88235294818878174), (0.90336132049560547, 0.88627451658248901, 0.88627451658248901), (0.90756303071975708, 0.89019608497619629, 0.89019608497619629), (0.91176468133926392, 0.89411765336990356, 0.89411765336990356), (0.91596639156341553, 0.89803922176361084, 0.89803922176361084), (0.92016804218292236, 0.90588235855102539, 0.90588235855102539), (0.92436975240707397, 0.90980392694473267, 0.90980392694473267), (0.92857140302658081, 0.91372549533843994, 0.91372549533843994), (0.93277311325073242, 0.91764706373214722, 0.91764706373214722), (0.93697476387023926, 0.92156863212585449, 0.92156863212585449), (0.94117647409439087, 0.92941176891326904, 0.92941176891326904), (0.94537812471389771, 0.93333333730697632, 0.93333333730697632), (0.94957983493804932, 0.93725490570068359, 0.93725490570068359), (0.95378148555755615, 0.94117647409439087, 0.94117647409439087), (0.95798319578170776, 0.94509804248809814, 0.94509804248809814), (0.9621848464012146, 0.9529411792755127, 0.9529411792755127), (0.96638655662536621, 0.95686274766921997, 0.95686274766921997), (0.97058820724487305, 0.96078431606292725, 0.96078431606292725), (0.97478991746902466, 0.96470588445663452, 0.96470588445663452), (0.97899156808853149, 0.9686274528503418, 0.9686274528503418), (0.98319327831268311, 0.97647058963775635, 0.97647058963775635), (0.98739492893218994, 0.98039215803146362, 0.98039215803146362), (0.99159663915634155, 0.9843137264251709, 0.9843137264251709), (0.99579828977584839, 0.98823529481887817, 0.98823529481887817), (1.0, 0.99215686321258545, 0.99215686321258545)]} _gist_gray_data = {'blue': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0039215688593685627, 0.0039215688593685627), (0.0084033617749810219, 0.0078431377187371254, 0.0078431377187371254), (0.012605042196810246, 0.011764706112444401, 0.011764706112444401), (0.016806723549962044, 0.015686275437474251, 0.015686275437474251), (0.021008403971791267, 0.019607843831181526, 0.019607843831181526), (0.025210084393620491, 0.023529412224888802, 0.023529412224888802), (0.029411764815449715, 0.027450980618596077, 0.027450980618596077), (0.033613447099924088, 0.035294119268655777, 0.035294119268655777), (0.037815127521753311, 0.039215687662363052, 0.039215687662363052), (0.042016807943582535, 0.043137256056070328, 0.043137256056070328), (0.046218488365411758, 0.047058824449777603, 0.047058824449777603), (0.050420168787240982, 0.050980392843484879, 0.050980392843484879), (0.054621849209070206, 0.054901961237192154, 0.054901961237192154), (0.058823529630899429, 0.058823529630899429, 0.058823529630899429), (0.063025213778018951, 0.062745101749897003, 0.062745101749897003), (0.067226894199848175, 0.066666670143604279, 0.066666670143604279), (0.071428574621677399, 0.070588238537311554, 0.070588238537311554), (0.075630255043506622, 0.074509806931018829, 0.074509806931018829), (0.079831935465335846, 0.078431375324726105, 0.078431375324726105), (0.08403361588716507, 0.08235294371843338, 0.08235294371843338), (0.088235296308994293, 0.086274512112140656, 0.086274512112140656), (0.092436976730823517, 0.090196080505847931, 0.090196080505847931), (0.09663865715265274, 0.098039217293262482, 0.098039217293262482), (0.10084033757448196, 0.10196078568696976, 0.10196078568696976), (0.10504201799631119, 0.10588235408067703, 0.10588235408067703), (0.10924369841814041, 0.10980392247438431, 0.10980392247438431), (0.11344537883996964, 0.11372549086809158, 0.11372549086809158), (0.11764705926179886, 0.11764705926179886, 0.11764705926179886), (0.12184873968362808, 0.12156862765550613, 0.12156862765550613), (0.1260504275560379, 0.12549020349979401, 0.12549020349979401), (0.13025210797786713, 0.12941177189350128, 0.12941177189350128), (0.13445378839969635, 0.13333334028720856, 0.13333334028720856), (0.13865546882152557, 0.13725490868091583, 0.13725490868091583), (0.1428571492433548, 0.14117647707462311, 0.14117647707462311), (0.14705882966518402, 0.14509804546833038, 0.14509804546833038), (0.15126051008701324, 0.14901961386203766, 0.14901961386203766), (0.15546219050884247, 0.15294118225574493, 0.15294118225574493), (0.15966387093067169, 0.16078431904315948, 0.16078431904315948), (0.16386555135250092, 0.16470588743686676, 0.16470588743686676), (0.16806723177433014, 0.16862745583057404, 0.16862745583057404), (0.17226891219615936, 0.17254902422428131, 0.17254902422428131), (0.17647059261798859, 0.17647059261798859, 0.17647059261798859), (0.18067227303981781, 0.18039216101169586, 0.18039216101169586), (0.18487395346164703, 0.18431372940540314, 0.18431372940540314), (0.18907563388347626, 0.18823529779911041, 0.18823529779911041), (0.19327731430530548, 0.19215686619281769, 0.19215686619281769), (0.1974789947271347, 0.19607843458652496, 0.19607843458652496), (0.20168067514896393, 0.20000000298023224, 0.20000000298023224), (0.20588235557079315, 0.20392157137393951, 0.20392157137393951), (0.21008403599262238, 0.20784313976764679, 0.20784313976764679), (0.2142857164144516, 0.21176470816135406, 0.21176470816135406), (0.21848739683628082, 0.21568627655506134, 0.21568627655506134), (0.22268907725811005, 0.22352941334247589, 0.22352941334247589), (0.22689075767993927, 0.22745098173618317, 0.22745098173618317), (0.23109243810176849, 0.23137255012989044, 0.23137255012989044), (0.23529411852359772, 0.23529411852359772, 0.23529411852359772), (0.23949579894542694, 0.23921568691730499, 0.23921568691730499), (0.24369747936725616, 0.24313725531101227, 0.24313725531101227), (0.24789915978908539, 0.24705882370471954, 0.24705882370471954), (0.25210085511207581, 0.25098040699958801, 0.25098040699958801), (0.25630253553390503, 0.25490197539329529, 0.25490197539329529), (0.26050421595573425, 0.25882354378700256, 0.25882354378700256), (0.26470589637756348, 0.26274511218070984, 0.26274511218070984), (0.2689075767993927, 0.26666668057441711, 0.26666668057441711), (0.27310925722122192, 0.27058824896812439, 0.27058824896812439), (0.27731093764305115, 0.27450981736183167, 0.27450981736183167), (0.28151261806488037, 0.27843138575553894, 0.27843138575553894), (0.28571429848670959, 0.28627452254295349, 0.28627452254295349), (0.28991597890853882, 0.29019609093666077, 0.29019609093666077), (0.29411765933036804, 0.29411765933036804, 0.29411765933036804), (0.29831933975219727, 0.29803922772407532, 0.29803922772407532), (0.30252102017402649, 0.30196079611778259, 0.30196079611778259), (0.30672270059585571, 0.30588236451148987, 0.30588236451148987), (0.31092438101768494, 0.30980393290519714, 0.30980393290519714), (0.31512606143951416, 0.31372550129890442, 0.31372550129890442), (0.31932774186134338, 0.31764706969261169, 0.31764706969261169), (0.32352942228317261, 0.32156863808631897, 0.32156863808631897), (0.32773110270500183, 0.32549020648002625, 0.32549020648002625), (0.33193278312683105, 0.32941177487373352, 0.32941177487373352), (0.33613446354866028, 0.3333333432674408, 0.3333333432674408), (0.3403361439704895, 0.33725491166114807, 0.33725491166114807), (0.34453782439231873, 0.34117648005485535, 0.34117648005485535), (0.34873950481414795, 0.3490196168422699, 0.3490196168422699), (0.35294118523597717, 0.35294118523597717, 0.35294118523597717), (0.3571428656578064, 0.35686275362968445, 0.35686275362968445), (0.36134454607963562, 0.36078432202339172, 0.36078432202339172), (0.36554622650146484, 0.364705890417099, 0.364705890417099), (0.36974790692329407, 0.36862745881080627, 0.36862745881080627), (0.37394958734512329, 0.37254902720451355, 0.37254902720451355), (0.37815126776695251, 0.37647059559822083, 0.37647059559822083), (0.38235294818878174, 0.3803921639919281, 0.3803921639919281), (0.38655462861061096, 0.38431373238563538, 0.38431373238563538), (0.39075630903244019, 0.38823530077934265, 0.38823530077934265), (0.39495798945426941, 0.39215686917304993, 0.39215686917304993), (0.39915966987609863, 0.3960784375667572, 0.3960784375667572), (0.40336135029792786, 0.40000000596046448, 0.40000000596046448), (0.40756303071975708, 0.40392157435417175, 0.40392157435417175), (0.4117647111415863, 0.4117647111415863, 0.4117647111415863), (0.41596639156341553, 0.41568627953529358, 0.41568627953529358), (0.42016807198524475, 0.41960784792900085, 0.41960784792900085), (0.42436975240707397, 0.42352941632270813, 0.42352941632270813), (0.4285714328289032, 0.42745098471641541, 0.42745098471641541), (0.43277311325073242, 0.43137255311012268, 0.43137255311012268), (0.43697479367256165, 0.43529412150382996, 0.43529412150382996), (0.44117647409439087, 0.43921568989753723, 0.43921568989753723), (0.44537815451622009, 0.44313725829124451, 0.44313725829124451), (0.44957983493804932, 0.44705882668495178, 0.44705882668495178), (0.45378151535987854, 0.45098039507865906, 0.45098039507865906), (0.45798319578170776, 0.45490196347236633, 0.45490196347236633), (0.46218487620353699, 0.45882353186607361, 0.45882353186607361), (0.46638655662536621, 0.46274510025978088, 0.46274510025978088), (0.47058823704719543, 0.46666666865348816, 0.46666666865348816), (0.47478991746902466, 0.47450980544090271, 0.47450980544090271), (0.47899159789085388, 0.47843137383460999, 0.47843137383460999), (0.48319327831268311, 0.48235294222831726, 0.48235294222831726), (0.48739495873451233, 0.48627451062202454, 0.48627451062202454), (0.49159663915634155, 0.49019607901573181, 0.49019607901573181), (0.49579831957817078, 0.49411764740943909, 0.49411764740943909), (0.5, 0.49803921580314636, 0.49803921580314636), (0.50420171022415161, 0.50196081399917603, 0.50196081399917603), (0.50840336084365845, 0.5058823823928833, 0.5058823823928833), (0.51260507106781006, 0.50980395078659058, 0.50980395078659058), (0.51680672168731689, 0.51372551918029785, 0.51372551918029785), (0.52100843191146851, 0.51764708757400513, 0.51764708757400513), (0.52521008253097534, 0.5215686559677124, 0.5215686559677124), (0.52941179275512695, 0.52549022436141968, 0.52549022436141968), (0.53361344337463379, 0.52941179275512695, 0.52941179275512695), (0.5378151535987854, 0.5372549295425415, 0.5372549295425415), (0.54201680421829224, 0.54117649793624878, 0.54117649793624878), (0.54621851444244385, 0.54509806632995605, 0.54509806632995605), (0.55042016506195068, 0.54901963472366333, 0.54901963472366333), (0.55462187528610229, 0.55294120311737061, 0.55294120311737061), (0.55882352590560913, 0.55686277151107788, 0.55686277151107788), (0.56302523612976074, 0.56078433990478516, 0.56078433990478516), (0.56722688674926758, 0.56470590829849243, 0.56470590829849243), (0.57142859697341919, 0.56862747669219971, 0.56862747669219971), (0.57563024759292603, 0.57254904508590698, 0.57254904508590698), (0.57983195781707764, 0.57647061347961426, 0.57647061347961426), (0.58403360843658447, 0.58039218187332153, 0.58039218187332153), (0.58823531866073608, 0.58431375026702881, 0.58431375026702881), (0.59243696928024292, 0.58823531866073608, 0.58823531866073608), (0.59663867950439453, 0.59215688705444336, 0.59215688705444336), (0.60084033012390137, 0.60000002384185791, 0.60000002384185791), (0.60504204034805298, 0.60392159223556519, 0.60392159223556519), (0.60924369096755981, 0.60784316062927246, 0.60784316062927246), (0.61344540119171143, 0.61176472902297974, 0.61176472902297974), (0.61764705181121826, 0.61568629741668701, 0.61568629741668701), (0.62184876203536987, 0.61960786581039429, 0.61960786581039429), (0.62605041265487671, 0.62352943420410156, 0.62352943420410156), (0.63025212287902832, 0.62745100259780884, 0.62745100259780884), (0.63445377349853516, 0.63137257099151611, 0.63137257099151611), (0.63865548372268677, 0.63529413938522339, 0.63529413938522339), (0.6428571343421936, 0.63921570777893066, 0.63921570777893066), (0.64705884456634521, 0.64313727617263794, 0.64313727617263794), (0.65126049518585205, 0.64705884456634521, 0.64705884456634521), (0.65546220541000366, 0.65098041296005249, 0.65098041296005249), (0.6596638560295105, 0.65490198135375977, 0.65490198135375977), (0.66386556625366211, 0.66274511814117432, 0.66274511814117432), (0.66806721687316895, 0.66666668653488159, 0.66666668653488159), (0.67226892709732056, 0.67058825492858887, 0.67058825492858887), (0.67647057771682739, 0.67450982332229614, 0.67450982332229614), (0.680672287940979, 0.67843139171600342, 0.67843139171600342), (0.68487393856048584, 0.68235296010971069, 0.68235296010971069), (0.68907564878463745, 0.68627452850341797, 0.68627452850341797), (0.69327729940414429, 0.69019609689712524, 0.69019609689712524), (0.6974790096282959, 0.69411766529083252, 0.69411766529083252), (0.70168066024780273, 0.69803923368453979, 0.69803923368453979), (0.70588237047195435, 0.70196080207824707, 0.70196080207824707), (0.71008402109146118, 0.70588237047195435, 0.70588237047195435), (0.71428573131561279, 0.70980393886566162, 0.70980393886566162), (0.71848738193511963, 0.7137255072593689, 0.7137255072593689), (0.72268909215927124, 0.71764707565307617, 0.71764707565307617), (0.72689074277877808, 0.72549021244049072, 0.72549021244049072), (0.73109245300292969, 0.729411780834198, 0.729411780834198), (0.73529410362243652, 0.73333334922790527, 0.73333334922790527), (0.73949581384658813, 0.73725491762161255, 0.73725491762161255), (0.74369746446609497, 0.74117648601531982, 0.74117648601531982), (0.74789917469024658, 0.7450980544090271, 0.7450980544090271), (0.75210082530975342, 0.74901962280273438, 0.74901962280273438), (0.75630253553390503, 0.75294119119644165, 0.75294119119644165), (0.76050418615341187, 0.75686275959014893, 0.75686275959014893), (0.76470589637756348, 0.7607843279838562, 0.7607843279838562), (0.76890754699707031, 0.76470589637756348, 0.76470589637756348), (0.77310925722122192, 0.76862746477127075, 0.76862746477127075), (0.77731090784072876, 0.77254903316497803, 0.77254903316497803), (0.78151261806488037, 0.7764706015586853, 0.7764706015586853), (0.78571426868438721, 0.78039216995239258, 0.78039216995239258), (0.78991597890853882, 0.78823530673980713, 0.78823530673980713), (0.79411762952804565, 0.7921568751335144, 0.7921568751335144), (0.79831933975219727, 0.79607844352722168, 0.79607844352722168), (0.8025209903717041, 0.80000001192092896, 0.80000001192092896), (0.80672270059585571, 0.80392158031463623, 0.80392158031463623), (0.81092435121536255, 0.80784314870834351, 0.80784314870834351), (0.81512606143951416, 0.81176471710205078, 0.81176471710205078), (0.819327712059021, 0.81568628549575806, 0.81568628549575806), (0.82352942228317261, 0.81960785388946533, 0.81960785388946533), (0.82773107290267944, 0.82352942228317261, 0.82352942228317261), (0.83193278312683105, 0.82745099067687988, 0.82745099067687988), (0.83613443374633789, 0.83137255907058716, 0.83137255907058716), (0.8403361439704895, 0.83529412746429443, 0.83529412746429443), (0.84453779458999634, 0.83921569585800171, 0.83921569585800171), (0.84873950481414795, 0.84313726425170898, 0.84313726425170898), (0.85294115543365479, 0.85098040103912354, 0.85098040103912354), (0.8571428656578064, 0.85490196943283081, 0.85490196943283081), (0.86134451627731323, 0.85882353782653809, 0.85882353782653809), (0.86554622650146484, 0.86274510622024536, 0.86274510622024536), (0.86974787712097168, 0.86666667461395264, 0.86666667461395264), (0.87394958734512329, 0.87058824300765991, 0.87058824300765991), (0.87815123796463013, 0.87450981140136719, 0.87450981140136719), (0.88235294818878174, 0.87843137979507446, 0.87843137979507446), (0.88655459880828857, 0.88235294818878174, 0.88235294818878174), (0.89075630903244019, 0.88627451658248901, 0.88627451658248901), (0.89495795965194702, 0.89019608497619629, 0.89019608497619629), (0.89915966987609863, 0.89411765336990356, 0.89411765336990356), (0.90336132049560547, 0.89803922176361084, 0.89803922176361084), (0.90756303071975708, 0.90196079015731812, 0.90196079015731812), (0.91176468133926392, 0.90588235855102539, 0.90588235855102539), (0.91596639156341553, 0.91372549533843994, 0.91372549533843994), (0.92016804218292236, 0.91764706373214722, 0.91764706373214722), (0.92436975240707397, 0.92156863212585449, 0.92156863212585449), (0.92857140302658081, 0.92549020051956177, 0.92549020051956177), (0.93277311325073242, 0.92941176891326904, 0.92941176891326904), (0.93697476387023926, 0.93333333730697632, 0.93333333730697632), (0.94117647409439087, 0.93725490570068359, 0.93725490570068359), (0.94537812471389771, 0.94117647409439087, 0.94117647409439087), (0.94957983493804932, 0.94509804248809814, 0.94509804248809814), (0.95378148555755615, 0.94901961088180542, 0.94901961088180542), (0.95798319578170776, 0.9529411792755127, 0.9529411792755127), (0.9621848464012146, 0.95686274766921997, 0.95686274766921997), (0.96638655662536621, 0.96078431606292725, 0.96078431606292725), (0.97058820724487305, 0.96470588445663452, 0.96470588445663452), (0.97478991746902466, 0.9686274528503418, 0.9686274528503418), (0.97899156808853149, 0.97647058963775635, 0.97647058963775635), (0.98319327831268311, 0.98039215803146362, 0.98039215803146362), (0.98739492893218994, 0.9843137264251709, 0.9843137264251709), (0.99159663915634155, 0.98823529481887817, 0.98823529481887817), (0.99579828977584839, 0.99215686321258545, 0.99215686321258545), (1.0, 0.99607843160629272, 0.99607843160629272)], 'green': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0039215688593685627, 0.0039215688593685627), (0.0084033617749810219, 0.0078431377187371254, 0.0078431377187371254), (0.012605042196810246, 0.011764706112444401, 0.011764706112444401), (0.016806723549962044, 0.015686275437474251, 0.015686275437474251), (0.021008403971791267, 0.019607843831181526, 0.019607843831181526), (0.025210084393620491, 0.023529412224888802, 0.023529412224888802), (0.029411764815449715, 0.027450980618596077, 0.027450980618596077), (0.033613447099924088, 0.035294119268655777, 0.035294119268655777), (0.037815127521753311, 0.039215687662363052, 0.039215687662363052), (0.042016807943582535, 0.043137256056070328, 0.043137256056070328), (0.046218488365411758, 0.047058824449777603, 0.047058824449777603), (0.050420168787240982, 0.050980392843484879, 0.050980392843484879), (0.054621849209070206, 0.054901961237192154, 0.054901961237192154), (0.058823529630899429, 0.058823529630899429, 0.058823529630899429), (0.063025213778018951, 0.062745101749897003, 0.062745101749897003), (0.067226894199848175, 0.066666670143604279, 0.066666670143604279), (0.071428574621677399, 0.070588238537311554, 0.070588238537311554), (0.075630255043506622, 0.074509806931018829, 0.074509806931018829), (0.079831935465335846, 0.078431375324726105, 0.078431375324726105), (0.08403361588716507, 0.08235294371843338, 0.08235294371843338), (0.088235296308994293, 0.086274512112140656, 0.086274512112140656), (0.092436976730823517, 0.090196080505847931, 0.090196080505847931), (0.09663865715265274, 0.098039217293262482, 0.098039217293262482), (0.10084033757448196, 0.10196078568696976, 0.10196078568696976), (0.10504201799631119, 0.10588235408067703, 0.10588235408067703), (0.10924369841814041, 0.10980392247438431, 0.10980392247438431), (0.11344537883996964, 0.11372549086809158, 0.11372549086809158), (0.11764705926179886, 0.11764705926179886, 0.11764705926179886), (0.12184873968362808, 0.12156862765550613, 0.12156862765550613), (0.1260504275560379, 0.12549020349979401, 0.12549020349979401), (0.13025210797786713, 0.12941177189350128, 0.12941177189350128), (0.13445378839969635, 0.13333334028720856, 0.13333334028720856), (0.13865546882152557, 0.13725490868091583, 0.13725490868091583), (0.1428571492433548, 0.14117647707462311, 0.14117647707462311), (0.14705882966518402, 0.14509804546833038, 0.14509804546833038), (0.15126051008701324, 0.14901961386203766, 0.14901961386203766), (0.15546219050884247, 0.15294118225574493, 0.15294118225574493), (0.15966387093067169, 0.16078431904315948, 0.16078431904315948), (0.16386555135250092, 0.16470588743686676, 0.16470588743686676), (0.16806723177433014, 0.16862745583057404, 0.16862745583057404), (0.17226891219615936, 0.17254902422428131, 0.17254902422428131), (0.17647059261798859, 0.17647059261798859, 0.17647059261798859), (0.18067227303981781, 0.18039216101169586, 0.18039216101169586), (0.18487395346164703, 0.18431372940540314, 0.18431372940540314), (0.18907563388347626, 0.18823529779911041, 0.18823529779911041), (0.19327731430530548, 0.19215686619281769, 0.19215686619281769), (0.1974789947271347, 0.19607843458652496, 0.19607843458652496), (0.20168067514896393, 0.20000000298023224, 0.20000000298023224), (0.20588235557079315, 0.20392157137393951, 0.20392157137393951), (0.21008403599262238, 0.20784313976764679, 0.20784313976764679), (0.2142857164144516, 0.21176470816135406, 0.21176470816135406), (0.21848739683628082, 0.21568627655506134, 0.21568627655506134), (0.22268907725811005, 0.22352941334247589, 0.22352941334247589), (0.22689075767993927, 0.22745098173618317, 0.22745098173618317), (0.23109243810176849, 0.23137255012989044, 0.23137255012989044), (0.23529411852359772, 0.23529411852359772, 0.23529411852359772), (0.23949579894542694, 0.23921568691730499, 0.23921568691730499), (0.24369747936725616, 0.24313725531101227, 0.24313725531101227), (0.24789915978908539, 0.24705882370471954, 0.24705882370471954), (0.25210085511207581, 0.25098040699958801, 0.25098040699958801), (0.25630253553390503, 0.25490197539329529, 0.25490197539329529), (0.26050421595573425, 0.25882354378700256, 0.25882354378700256), (0.26470589637756348, 0.26274511218070984, 0.26274511218070984), (0.2689075767993927, 0.26666668057441711, 0.26666668057441711), (0.27310925722122192, 0.27058824896812439, 0.27058824896812439), (0.27731093764305115, 0.27450981736183167, 0.27450981736183167), (0.28151261806488037, 0.27843138575553894, 0.27843138575553894), (0.28571429848670959, 0.28627452254295349, 0.28627452254295349), (0.28991597890853882, 0.29019609093666077, 0.29019609093666077), (0.29411765933036804, 0.29411765933036804, 0.29411765933036804), (0.29831933975219727, 0.29803922772407532, 0.29803922772407532), (0.30252102017402649, 0.30196079611778259, 0.30196079611778259), (0.30672270059585571, 0.30588236451148987, 0.30588236451148987), (0.31092438101768494, 0.30980393290519714, 0.30980393290519714), (0.31512606143951416, 0.31372550129890442, 0.31372550129890442), (0.31932774186134338, 0.31764706969261169, 0.31764706969261169), (0.32352942228317261, 0.32156863808631897, 0.32156863808631897), (0.32773110270500183, 0.32549020648002625, 0.32549020648002625), (0.33193278312683105, 0.32941177487373352, 0.32941177487373352), (0.33613446354866028, 0.3333333432674408, 0.3333333432674408), (0.3403361439704895, 0.33725491166114807, 0.33725491166114807), (0.34453782439231873, 0.34117648005485535, 0.34117648005485535), (0.34873950481414795, 0.3490196168422699, 0.3490196168422699), (0.35294118523597717, 0.35294118523597717, 0.35294118523597717), (0.3571428656578064, 0.35686275362968445, 0.35686275362968445), (0.36134454607963562, 0.36078432202339172, 0.36078432202339172), (0.36554622650146484, 0.364705890417099, 0.364705890417099), (0.36974790692329407, 0.36862745881080627, 0.36862745881080627), (0.37394958734512329, 0.37254902720451355, 0.37254902720451355), (0.37815126776695251, 0.37647059559822083, 0.37647059559822083), (0.38235294818878174, 0.3803921639919281, 0.3803921639919281), (0.38655462861061096, 0.38431373238563538, 0.38431373238563538), (0.39075630903244019, 0.38823530077934265, 0.38823530077934265), (0.39495798945426941, 0.39215686917304993, 0.39215686917304993), (0.39915966987609863, 0.3960784375667572, 0.3960784375667572), (0.40336135029792786, 0.40000000596046448, 0.40000000596046448), (0.40756303071975708, 0.40392157435417175, 0.40392157435417175), (0.4117647111415863, 0.4117647111415863, 0.4117647111415863), (0.41596639156341553, 0.41568627953529358, 0.41568627953529358), (0.42016807198524475, 0.41960784792900085, 0.41960784792900085), (0.42436975240707397, 0.42352941632270813, 0.42352941632270813), (0.4285714328289032, 0.42745098471641541, 0.42745098471641541), (0.43277311325073242, 0.43137255311012268, 0.43137255311012268), (0.43697479367256165, 0.43529412150382996, 0.43529412150382996), (0.44117647409439087, 0.43921568989753723, 0.43921568989753723), (0.44537815451622009, 0.44313725829124451, 0.44313725829124451), (0.44957983493804932, 0.44705882668495178, 0.44705882668495178), (0.45378151535987854, 0.45098039507865906, 0.45098039507865906), (0.45798319578170776, 0.45490196347236633, 0.45490196347236633), (0.46218487620353699, 0.45882353186607361, 0.45882353186607361), (0.46638655662536621, 0.46274510025978088, 0.46274510025978088), (0.47058823704719543, 0.46666666865348816, 0.46666666865348816), (0.47478991746902466, 0.47450980544090271, 0.47450980544090271), (0.47899159789085388, 0.47843137383460999, 0.47843137383460999), (0.48319327831268311, 0.48235294222831726, 0.48235294222831726), (0.48739495873451233, 0.48627451062202454, 0.48627451062202454), (0.49159663915634155, 0.49019607901573181, 0.49019607901573181), (0.49579831957817078, 0.49411764740943909, 0.49411764740943909), (0.5, 0.49803921580314636, 0.49803921580314636), (0.50420171022415161, 0.50196081399917603, 0.50196081399917603), (0.50840336084365845, 0.5058823823928833, 0.5058823823928833), (0.51260507106781006, 0.50980395078659058, 0.50980395078659058), (0.51680672168731689, 0.51372551918029785, 0.51372551918029785), (0.52100843191146851, 0.51764708757400513, 0.51764708757400513), (0.52521008253097534, 0.5215686559677124, 0.5215686559677124), (0.52941179275512695, 0.52549022436141968, 0.52549022436141968), (0.53361344337463379, 0.52941179275512695, 0.52941179275512695), (0.5378151535987854, 0.5372549295425415, 0.5372549295425415), (0.54201680421829224, 0.54117649793624878, 0.54117649793624878), (0.54621851444244385, 0.54509806632995605, 0.54509806632995605), (0.55042016506195068, 0.54901963472366333, 0.54901963472366333), (0.55462187528610229, 0.55294120311737061, 0.55294120311737061), (0.55882352590560913, 0.55686277151107788, 0.55686277151107788), (0.56302523612976074, 0.56078433990478516, 0.56078433990478516), (0.56722688674926758, 0.56470590829849243, 0.56470590829849243), (0.57142859697341919, 0.56862747669219971, 0.56862747669219971), (0.57563024759292603, 0.57254904508590698, 0.57254904508590698), (0.57983195781707764, 0.57647061347961426, 0.57647061347961426), (0.58403360843658447, 0.58039218187332153, 0.58039218187332153), (0.58823531866073608, 0.58431375026702881, 0.58431375026702881), (0.59243696928024292, 0.58823531866073608, 0.58823531866073608), (0.59663867950439453, 0.59215688705444336, 0.59215688705444336), (0.60084033012390137, 0.60000002384185791, 0.60000002384185791), (0.60504204034805298, 0.60392159223556519, 0.60392159223556519), (0.60924369096755981, 0.60784316062927246, 0.60784316062927246), (0.61344540119171143, 0.61176472902297974, 0.61176472902297974), (0.61764705181121826, 0.61568629741668701, 0.61568629741668701), (0.62184876203536987, 0.61960786581039429, 0.61960786581039429), (0.62605041265487671, 0.62352943420410156, 0.62352943420410156), (0.63025212287902832, 0.62745100259780884, 0.62745100259780884), (0.63445377349853516, 0.63137257099151611, 0.63137257099151611), (0.63865548372268677, 0.63529413938522339, 0.63529413938522339), (0.6428571343421936, 0.63921570777893066, 0.63921570777893066), (0.64705884456634521, 0.64313727617263794, 0.64313727617263794), (0.65126049518585205, 0.64705884456634521, 0.64705884456634521), (0.65546220541000366, 0.65098041296005249, 0.65098041296005249), (0.6596638560295105, 0.65490198135375977, 0.65490198135375977), (0.66386556625366211, 0.66274511814117432, 0.66274511814117432), (0.66806721687316895, 0.66666668653488159, 0.66666668653488159), (0.67226892709732056, 0.67058825492858887, 0.67058825492858887), (0.67647057771682739, 0.67450982332229614, 0.67450982332229614), (0.680672287940979, 0.67843139171600342, 0.67843139171600342), (0.68487393856048584, 0.68235296010971069, 0.68235296010971069), (0.68907564878463745, 0.68627452850341797, 0.68627452850341797), (0.69327729940414429, 0.69019609689712524, 0.69019609689712524), (0.6974790096282959, 0.69411766529083252, 0.69411766529083252), (0.70168066024780273, 0.69803923368453979, 0.69803923368453979), (0.70588237047195435, 0.70196080207824707, 0.70196080207824707), (0.71008402109146118, 0.70588237047195435, 0.70588237047195435), (0.71428573131561279, 0.70980393886566162, 0.70980393886566162), (0.71848738193511963, 0.7137255072593689, 0.7137255072593689), (0.72268909215927124, 0.71764707565307617, 0.71764707565307617), (0.72689074277877808, 0.72549021244049072, 0.72549021244049072), (0.73109245300292969, 0.729411780834198, 0.729411780834198), (0.73529410362243652, 0.73333334922790527, 0.73333334922790527), (0.73949581384658813, 0.73725491762161255, 0.73725491762161255), (0.74369746446609497, 0.74117648601531982, 0.74117648601531982), (0.74789917469024658, 0.7450980544090271, 0.7450980544090271), (0.75210082530975342, 0.74901962280273438, 0.74901962280273438), (0.75630253553390503, 0.75294119119644165, 0.75294119119644165), (0.76050418615341187, 0.75686275959014893, 0.75686275959014893), (0.76470589637756348, 0.7607843279838562, 0.7607843279838562), (0.76890754699707031, 0.76470589637756348, 0.76470589637756348), (0.77310925722122192, 0.76862746477127075, 0.76862746477127075), (0.77731090784072876, 0.77254903316497803, 0.77254903316497803), (0.78151261806488037, 0.7764706015586853, 0.7764706015586853), (0.78571426868438721, 0.78039216995239258, 0.78039216995239258), (0.78991597890853882, 0.78823530673980713, 0.78823530673980713), (0.79411762952804565, 0.7921568751335144, 0.7921568751335144), (0.79831933975219727, 0.79607844352722168, 0.79607844352722168), (0.8025209903717041, 0.80000001192092896, 0.80000001192092896), (0.80672270059585571, 0.80392158031463623, 0.80392158031463623), (0.81092435121536255, 0.80784314870834351, 0.80784314870834351), (0.81512606143951416, 0.81176471710205078, 0.81176471710205078), (0.819327712059021, 0.81568628549575806, 0.81568628549575806), (0.82352942228317261, 0.81960785388946533, 0.81960785388946533), (0.82773107290267944, 0.82352942228317261, 0.82352942228317261), (0.83193278312683105, 0.82745099067687988, 0.82745099067687988), (0.83613443374633789, 0.83137255907058716, 0.83137255907058716), (0.8403361439704895, 0.83529412746429443, 0.83529412746429443), (0.84453779458999634, 0.83921569585800171, 0.83921569585800171), (0.84873950481414795, 0.84313726425170898, 0.84313726425170898), (0.85294115543365479, 0.85098040103912354, 0.85098040103912354), (0.8571428656578064, 0.85490196943283081, 0.85490196943283081), (0.86134451627731323, 0.85882353782653809, 0.85882353782653809), (0.86554622650146484, 0.86274510622024536, 0.86274510622024536), (0.86974787712097168, 0.86666667461395264, 0.86666667461395264), (0.87394958734512329, 0.87058824300765991, 0.87058824300765991), (0.87815123796463013, 0.87450981140136719, 0.87450981140136719), (0.88235294818878174, 0.87843137979507446, 0.87843137979507446), (0.88655459880828857, 0.88235294818878174, 0.88235294818878174), (0.89075630903244019, 0.88627451658248901, 0.88627451658248901), (0.89495795965194702, 0.89019608497619629, 0.89019608497619629), (0.89915966987609863, 0.89411765336990356, 0.89411765336990356), (0.90336132049560547, 0.89803922176361084, 0.89803922176361084), (0.90756303071975708, 0.90196079015731812, 0.90196079015731812), (0.91176468133926392, 0.90588235855102539, 0.90588235855102539), (0.91596639156341553, 0.91372549533843994, 0.91372549533843994), (0.92016804218292236, 0.91764706373214722, 0.91764706373214722), (0.92436975240707397, 0.92156863212585449, 0.92156863212585449), (0.92857140302658081, 0.92549020051956177, 0.92549020051956177), (0.93277311325073242, 0.92941176891326904, 0.92941176891326904), (0.93697476387023926, 0.93333333730697632, 0.93333333730697632), (0.94117647409439087, 0.93725490570068359, 0.93725490570068359), (0.94537812471389771, 0.94117647409439087, 0.94117647409439087), (0.94957983493804932, 0.94509804248809814, 0.94509804248809814), (0.95378148555755615, 0.94901961088180542, 0.94901961088180542), (0.95798319578170776, 0.9529411792755127, 0.9529411792755127), (0.9621848464012146, 0.95686274766921997, 0.95686274766921997), (0.96638655662536621, 0.96078431606292725, 0.96078431606292725), (0.97058820724487305, 0.96470588445663452, 0.96470588445663452), (0.97478991746902466, 0.9686274528503418, 0.9686274528503418), (0.97899156808853149, 0.97647058963775635, 0.97647058963775635), (0.98319327831268311, 0.98039215803146362, 0.98039215803146362), (0.98739492893218994, 0.9843137264251709, 0.9843137264251709), (0.99159663915634155, 0.98823529481887817, 0.98823529481887817), (0.99579828977584839, 0.99215686321258545, 0.99215686321258545), (1.0, 0.99607843160629272, 0.99607843160629272)], 'red': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0039215688593685627, 0.0039215688593685627), (0.0084033617749810219, 0.0078431377187371254, 0.0078431377187371254), (0.012605042196810246, 0.011764706112444401, 0.011764706112444401), (0.016806723549962044, 0.015686275437474251, 0.015686275437474251), (0.021008403971791267, 0.019607843831181526, 0.019607843831181526), (0.025210084393620491, 0.023529412224888802, 0.023529412224888802), (0.029411764815449715, 0.027450980618596077, 0.027450980618596077), (0.033613447099924088, 0.035294119268655777, 0.035294119268655777), (0.037815127521753311, 0.039215687662363052, 0.039215687662363052), (0.042016807943582535, 0.043137256056070328, 0.043137256056070328), (0.046218488365411758, 0.047058824449777603, 0.047058824449777603), (0.050420168787240982, 0.050980392843484879, 0.050980392843484879), (0.054621849209070206, 0.054901961237192154, 0.054901961237192154), (0.058823529630899429, 0.058823529630899429, 0.058823529630899429), (0.063025213778018951, 0.062745101749897003, 0.062745101749897003), (0.067226894199848175, 0.066666670143604279, 0.066666670143604279), (0.071428574621677399, 0.070588238537311554, 0.070588238537311554), (0.075630255043506622, 0.074509806931018829, 0.074509806931018829), (0.079831935465335846, 0.078431375324726105, 0.078431375324726105), (0.08403361588716507, 0.08235294371843338, 0.08235294371843338), (0.088235296308994293, 0.086274512112140656, 0.086274512112140656), (0.092436976730823517, 0.090196080505847931, 0.090196080505847931), (0.09663865715265274, 0.098039217293262482, 0.098039217293262482), (0.10084033757448196, 0.10196078568696976, 0.10196078568696976), (0.10504201799631119, 0.10588235408067703, 0.10588235408067703), (0.10924369841814041, 0.10980392247438431, 0.10980392247438431), (0.11344537883996964, 0.11372549086809158, 0.11372549086809158), (0.11764705926179886, 0.11764705926179886, 0.11764705926179886), (0.12184873968362808, 0.12156862765550613, 0.12156862765550613), (0.1260504275560379, 0.12549020349979401, 0.12549020349979401), (0.13025210797786713, 0.12941177189350128, 0.12941177189350128), (0.13445378839969635, 0.13333334028720856, 0.13333334028720856), (0.13865546882152557, 0.13725490868091583, 0.13725490868091583), (0.1428571492433548, 0.14117647707462311, 0.14117647707462311), (0.14705882966518402, 0.14509804546833038, 0.14509804546833038), (0.15126051008701324, 0.14901961386203766, 0.14901961386203766), (0.15546219050884247, 0.15294118225574493, 0.15294118225574493), (0.15966387093067169, 0.16078431904315948, 0.16078431904315948), (0.16386555135250092, 0.16470588743686676, 0.16470588743686676), (0.16806723177433014, 0.16862745583057404, 0.16862745583057404), (0.17226891219615936, 0.17254902422428131, 0.17254902422428131), (0.17647059261798859, 0.17647059261798859, 0.17647059261798859), (0.18067227303981781, 0.18039216101169586, 0.18039216101169586), (0.18487395346164703, 0.18431372940540314, 0.18431372940540314), (0.18907563388347626, 0.18823529779911041, 0.18823529779911041), (0.19327731430530548, 0.19215686619281769, 0.19215686619281769), (0.1974789947271347, 0.19607843458652496, 0.19607843458652496), (0.20168067514896393, 0.20000000298023224, 0.20000000298023224), (0.20588235557079315, 0.20392157137393951, 0.20392157137393951), (0.21008403599262238, 0.20784313976764679, 0.20784313976764679), (0.2142857164144516, 0.21176470816135406, 0.21176470816135406), (0.21848739683628082, 0.21568627655506134, 0.21568627655506134), (0.22268907725811005, 0.22352941334247589, 0.22352941334247589), (0.22689075767993927, 0.22745098173618317, 0.22745098173618317), (0.23109243810176849, 0.23137255012989044, 0.23137255012989044), (0.23529411852359772, 0.23529411852359772, 0.23529411852359772), (0.23949579894542694, 0.23921568691730499, 0.23921568691730499), (0.24369747936725616, 0.24313725531101227, 0.24313725531101227), (0.24789915978908539, 0.24705882370471954, 0.24705882370471954), (0.25210085511207581, 0.25098040699958801, 0.25098040699958801), (0.25630253553390503, 0.25490197539329529, 0.25490197539329529), (0.26050421595573425, 0.25882354378700256, 0.25882354378700256), (0.26470589637756348, 0.26274511218070984, 0.26274511218070984), (0.2689075767993927, 0.26666668057441711, 0.26666668057441711), (0.27310925722122192, 0.27058824896812439, 0.27058824896812439), (0.27731093764305115, 0.27450981736183167, 0.27450981736183167), (0.28151261806488037, 0.27843138575553894, 0.27843138575553894), (0.28571429848670959, 0.28627452254295349, 0.28627452254295349), (0.28991597890853882, 0.29019609093666077, 0.29019609093666077), (0.29411765933036804, 0.29411765933036804, 0.29411765933036804), (0.29831933975219727, 0.29803922772407532, 0.29803922772407532), (0.30252102017402649, 0.30196079611778259, 0.30196079611778259), (0.30672270059585571, 0.30588236451148987, 0.30588236451148987), (0.31092438101768494, 0.30980393290519714, 0.30980393290519714), (0.31512606143951416, 0.31372550129890442, 0.31372550129890442), (0.31932774186134338, 0.31764706969261169, 0.31764706969261169), (0.32352942228317261, 0.32156863808631897, 0.32156863808631897), (0.32773110270500183, 0.32549020648002625, 0.32549020648002625), (0.33193278312683105, 0.32941177487373352, 0.32941177487373352), (0.33613446354866028, 0.3333333432674408, 0.3333333432674408), (0.3403361439704895, 0.33725491166114807, 0.33725491166114807), (0.34453782439231873, 0.34117648005485535, 0.34117648005485535), (0.34873950481414795, 0.3490196168422699, 0.3490196168422699), (0.35294118523597717, 0.35294118523597717, 0.35294118523597717), (0.3571428656578064, 0.35686275362968445, 0.35686275362968445), (0.36134454607963562, 0.36078432202339172, 0.36078432202339172), (0.36554622650146484, 0.364705890417099, 0.364705890417099), (0.36974790692329407, 0.36862745881080627, 0.36862745881080627), (0.37394958734512329, 0.37254902720451355, 0.37254902720451355), (0.37815126776695251, 0.37647059559822083, 0.37647059559822083), (0.38235294818878174, 0.3803921639919281, 0.3803921639919281), (0.38655462861061096, 0.38431373238563538, 0.38431373238563538), (0.39075630903244019, 0.38823530077934265, 0.38823530077934265), (0.39495798945426941, 0.39215686917304993, 0.39215686917304993), (0.39915966987609863, 0.3960784375667572, 0.3960784375667572), (0.40336135029792786, 0.40000000596046448, 0.40000000596046448), (0.40756303071975708, 0.40392157435417175, 0.40392157435417175), (0.4117647111415863, 0.4117647111415863, 0.4117647111415863), (0.41596639156341553, 0.41568627953529358, 0.41568627953529358), (0.42016807198524475, 0.41960784792900085, 0.41960784792900085), (0.42436975240707397, 0.42352941632270813, 0.42352941632270813), (0.4285714328289032, 0.42745098471641541, 0.42745098471641541), (0.43277311325073242, 0.43137255311012268, 0.43137255311012268), (0.43697479367256165, 0.43529412150382996, 0.43529412150382996), (0.44117647409439087, 0.43921568989753723, 0.43921568989753723), (0.44537815451622009, 0.44313725829124451, 0.44313725829124451), (0.44957983493804932, 0.44705882668495178, 0.44705882668495178), (0.45378151535987854, 0.45098039507865906, 0.45098039507865906), (0.45798319578170776, 0.45490196347236633, 0.45490196347236633), (0.46218487620353699, 0.45882353186607361, 0.45882353186607361), (0.46638655662536621, 0.46274510025978088, 0.46274510025978088), (0.47058823704719543, 0.46666666865348816, 0.46666666865348816), (0.47478991746902466, 0.47450980544090271, 0.47450980544090271), (0.47899159789085388, 0.47843137383460999, 0.47843137383460999), (0.48319327831268311, 0.48235294222831726, 0.48235294222831726), (0.48739495873451233, 0.48627451062202454, 0.48627451062202454), (0.49159663915634155, 0.49019607901573181, 0.49019607901573181), (0.49579831957817078, 0.49411764740943909, 0.49411764740943909), (0.5, 0.49803921580314636, 0.49803921580314636), (0.50420171022415161, 0.50196081399917603, 0.50196081399917603), (0.50840336084365845, 0.5058823823928833, 0.5058823823928833), (0.51260507106781006, 0.50980395078659058, 0.50980395078659058), (0.51680672168731689, 0.51372551918029785, 0.51372551918029785), (0.52100843191146851, 0.51764708757400513, 0.51764708757400513), (0.52521008253097534, 0.5215686559677124, 0.5215686559677124), (0.52941179275512695, 0.52549022436141968, 0.52549022436141968), (0.53361344337463379, 0.52941179275512695, 0.52941179275512695), (0.5378151535987854, 0.5372549295425415, 0.5372549295425415), (0.54201680421829224, 0.54117649793624878, 0.54117649793624878), (0.54621851444244385, 0.54509806632995605, 0.54509806632995605), (0.55042016506195068, 0.54901963472366333, 0.54901963472366333), (0.55462187528610229, 0.55294120311737061, 0.55294120311737061), (0.55882352590560913, 0.55686277151107788, 0.55686277151107788), (0.56302523612976074, 0.56078433990478516, 0.56078433990478516), (0.56722688674926758, 0.56470590829849243, 0.56470590829849243), (0.57142859697341919, 0.56862747669219971, 0.56862747669219971), (0.57563024759292603, 0.57254904508590698, 0.57254904508590698), (0.57983195781707764, 0.57647061347961426, 0.57647061347961426), (0.58403360843658447, 0.58039218187332153, 0.58039218187332153), (0.58823531866073608, 0.58431375026702881, 0.58431375026702881), (0.59243696928024292, 0.58823531866073608, 0.58823531866073608), (0.59663867950439453, 0.59215688705444336, 0.59215688705444336), (0.60084033012390137, 0.60000002384185791, 0.60000002384185791), (0.60504204034805298, 0.60392159223556519, 0.60392159223556519), (0.60924369096755981, 0.60784316062927246, 0.60784316062927246), (0.61344540119171143, 0.61176472902297974, 0.61176472902297974), (0.61764705181121826, 0.61568629741668701, 0.61568629741668701), (0.62184876203536987, 0.61960786581039429, 0.61960786581039429), (0.62605041265487671, 0.62352943420410156, 0.62352943420410156), (0.63025212287902832, 0.62745100259780884, 0.62745100259780884), (0.63445377349853516, 0.63137257099151611, 0.63137257099151611), (0.63865548372268677, 0.63529413938522339, 0.63529413938522339), (0.6428571343421936, 0.63921570777893066, 0.63921570777893066), (0.64705884456634521, 0.64313727617263794, 0.64313727617263794), (0.65126049518585205, 0.64705884456634521, 0.64705884456634521), (0.65546220541000366, 0.65098041296005249, 0.65098041296005249), (0.6596638560295105, 0.65490198135375977, 0.65490198135375977), (0.66386556625366211, 0.66274511814117432, 0.66274511814117432), (0.66806721687316895, 0.66666668653488159, 0.66666668653488159), (0.67226892709732056, 0.67058825492858887, 0.67058825492858887), (0.67647057771682739, 0.67450982332229614, 0.67450982332229614), (0.680672287940979, 0.67843139171600342, 0.67843139171600342), (0.68487393856048584, 0.68235296010971069, 0.68235296010971069), (0.68907564878463745, 0.68627452850341797, 0.68627452850341797), (0.69327729940414429, 0.69019609689712524, 0.69019609689712524), (0.6974790096282959, 0.69411766529083252, 0.69411766529083252), (0.70168066024780273, 0.69803923368453979, 0.69803923368453979), (0.70588237047195435, 0.70196080207824707, 0.70196080207824707), (0.71008402109146118, 0.70588237047195435, 0.70588237047195435), (0.71428573131561279, 0.70980393886566162, 0.70980393886566162), (0.71848738193511963, 0.7137255072593689, 0.7137255072593689), (0.72268909215927124, 0.71764707565307617, 0.71764707565307617), (0.72689074277877808, 0.72549021244049072, 0.72549021244049072), (0.73109245300292969, 0.729411780834198, 0.729411780834198), (0.73529410362243652, 0.73333334922790527, 0.73333334922790527), (0.73949581384658813, 0.73725491762161255, 0.73725491762161255), (0.74369746446609497, 0.74117648601531982, 0.74117648601531982), (0.74789917469024658, 0.7450980544090271, 0.7450980544090271), (0.75210082530975342, 0.74901962280273438, 0.74901962280273438), (0.75630253553390503, 0.75294119119644165, 0.75294119119644165), (0.76050418615341187, 0.75686275959014893, 0.75686275959014893), (0.76470589637756348, 0.7607843279838562, 0.7607843279838562), (0.76890754699707031, 0.76470589637756348, 0.76470589637756348), (0.77310925722122192, 0.76862746477127075, 0.76862746477127075), (0.77731090784072876, 0.77254903316497803, 0.77254903316497803), (0.78151261806488037, 0.7764706015586853, 0.7764706015586853), (0.78571426868438721, 0.78039216995239258, 0.78039216995239258), (0.78991597890853882, 0.78823530673980713, 0.78823530673980713), (0.79411762952804565, 0.7921568751335144, 0.7921568751335144), (0.79831933975219727, 0.79607844352722168, 0.79607844352722168), (0.8025209903717041, 0.80000001192092896, 0.80000001192092896), (0.80672270059585571, 0.80392158031463623, 0.80392158031463623), (0.81092435121536255, 0.80784314870834351, 0.80784314870834351), (0.81512606143951416, 0.81176471710205078, 0.81176471710205078), (0.819327712059021, 0.81568628549575806, 0.81568628549575806), (0.82352942228317261, 0.81960785388946533, 0.81960785388946533), (0.82773107290267944, 0.82352942228317261, 0.82352942228317261), (0.83193278312683105, 0.82745099067687988, 0.82745099067687988), (0.83613443374633789, 0.83137255907058716, 0.83137255907058716), (0.8403361439704895, 0.83529412746429443, 0.83529412746429443), (0.84453779458999634, 0.83921569585800171, 0.83921569585800171), (0.84873950481414795, 0.84313726425170898, 0.84313726425170898), (0.85294115543365479, 0.85098040103912354, 0.85098040103912354), (0.8571428656578064, 0.85490196943283081, 0.85490196943283081), (0.86134451627731323, 0.85882353782653809, 0.85882353782653809), (0.86554622650146484, 0.86274510622024536, 0.86274510622024536), (0.86974787712097168, 0.86666667461395264, 0.86666667461395264), (0.87394958734512329, 0.87058824300765991, 0.87058824300765991), (0.87815123796463013, 0.87450981140136719, 0.87450981140136719), (0.88235294818878174, 0.87843137979507446, 0.87843137979507446), (0.88655459880828857, 0.88235294818878174, 0.88235294818878174), (0.89075630903244019, 0.88627451658248901, 0.88627451658248901), (0.89495795965194702, 0.89019608497619629, 0.89019608497619629), (0.89915966987609863, 0.89411765336990356, 0.89411765336990356), (0.90336132049560547, 0.89803922176361084, 0.89803922176361084), (0.90756303071975708, 0.90196079015731812, 0.90196079015731812), (0.91176468133926392, 0.90588235855102539, 0.90588235855102539), (0.91596639156341553, 0.91372549533843994, 0.91372549533843994), (0.92016804218292236, 0.91764706373214722, 0.91764706373214722), (0.92436975240707397, 0.92156863212585449, 0.92156863212585449), (0.92857140302658081, 0.92549020051956177, 0.92549020051956177), (0.93277311325073242, 0.92941176891326904, 0.92941176891326904), (0.93697476387023926, 0.93333333730697632, 0.93333333730697632), (0.94117647409439087, 0.93725490570068359, 0.93725490570068359), (0.94537812471389771, 0.94117647409439087, 0.94117647409439087), (0.94957983493804932, 0.94509804248809814, 0.94509804248809814), (0.95378148555755615, 0.94901961088180542, 0.94901961088180542), (0.95798319578170776, 0.9529411792755127, 0.9529411792755127), (0.9621848464012146, 0.95686274766921997, 0.95686274766921997), (0.96638655662536621, 0.96078431606292725, 0.96078431606292725), (0.97058820724487305, 0.96470588445663452, 0.96470588445663452), (0.97478991746902466, 0.9686274528503418, 0.9686274528503418), (0.97899156808853149, 0.97647058963775635, 0.97647058963775635), (0.98319327831268311, 0.98039215803146362, 0.98039215803146362), (0.98739492893218994, 0.9843137264251709, 0.9843137264251709), (0.99159663915634155, 0.98823529481887817, 0.98823529481887817), (0.99579828977584839, 0.99215686321258545, 0.99215686321258545), (1.0, 0.99607843160629272, 0.99607843160629272)]} _gist_heat_data = {'blue': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0, 0.0), (0.0084033617749810219, 0.0, 0.0), (0.012605042196810246, 0.0, 0.0), (0.016806723549962044, 0.0, 0.0), (0.021008403971791267, 0.0, 0.0), (0.025210084393620491, 0.0, 0.0), (0.029411764815449715, 0.0, 0.0), (0.033613447099924088, 0.0, 0.0), (0.037815127521753311, 0.0, 0.0), (0.042016807943582535, 0.0, 0.0), (0.046218488365411758, 0.0, 0.0), (0.050420168787240982, 0.0, 0.0), (0.054621849209070206, 0.0, 0.0), (0.058823529630899429, 0.0, 0.0), (0.063025213778018951, 0.0, 0.0), (0.067226894199848175, 0.0, 0.0), (0.071428574621677399, 0.0, 0.0), (0.075630255043506622, 0.0, 0.0), (0.079831935465335846, 0.0, 0.0), (0.08403361588716507, 0.0, 0.0), (0.088235296308994293, 0.0, 0.0), (0.092436976730823517, 0.0, 0.0), (0.09663865715265274, 0.0, 0.0), (0.10084033757448196, 0.0, 0.0), (0.10504201799631119, 0.0, 0.0), (0.10924369841814041, 0.0, 0.0), (0.11344537883996964, 0.0, 0.0), (0.11764705926179886, 0.0, 0.0), (0.12184873968362808, 0.0, 0.0), (0.1260504275560379, 0.0, 0.0), (0.13025210797786713, 0.0, 0.0), (0.13445378839969635, 0.0, 0.0), (0.13865546882152557, 0.0, 0.0), (0.1428571492433548, 0.0, 0.0), (0.14705882966518402, 0.0, 0.0), (0.15126051008701324, 0.0, 0.0), (0.15546219050884247, 0.0, 0.0), (0.15966387093067169, 0.0, 0.0), (0.16386555135250092, 0.0, 0.0), (0.16806723177433014, 0.0, 0.0), (0.17226891219615936, 0.0, 0.0), (0.17647059261798859, 0.0, 0.0), (0.18067227303981781, 0.0, 0.0), (0.18487395346164703, 0.0, 0.0), (0.18907563388347626, 0.0, 0.0), (0.19327731430530548, 0.0, 0.0), (0.1974789947271347, 0.0, 0.0), (0.20168067514896393, 0.0, 0.0), (0.20588235557079315, 0.0, 0.0), (0.21008403599262238, 0.0, 0.0), (0.2142857164144516, 0.0, 0.0), (0.21848739683628082, 0.0, 0.0), (0.22268907725811005, 0.0, 0.0), (0.22689075767993927, 0.0, 0.0), (0.23109243810176849, 0.0, 0.0), (0.23529411852359772, 0.0, 0.0), (0.23949579894542694, 0.0, 0.0), (0.24369747936725616, 0.0, 0.0), (0.24789915978908539, 0.0, 0.0), (0.25210085511207581, 0.0, 0.0), (0.25630253553390503, 0.0, 0.0), (0.26050421595573425, 0.0, 0.0), (0.26470589637756348, 0.0, 0.0), (0.2689075767993927, 0.0, 0.0), (0.27310925722122192, 0.0, 0.0), (0.27731093764305115, 0.0, 0.0), (0.28151261806488037, 0.0, 0.0), (0.28571429848670959, 0.0, 0.0), (0.28991597890853882, 0.0, 0.0), (0.29411765933036804, 0.0, 0.0), (0.29831933975219727, 0.0, 0.0), (0.30252102017402649, 0.0, 0.0), (0.30672270059585571, 0.0, 0.0), (0.31092438101768494, 0.0, 0.0), (0.31512606143951416, 0.0, 0.0), (0.31932774186134338, 0.0, 0.0), (0.32352942228317261, 0.0, 0.0), (0.32773110270500183, 0.0, 0.0), (0.33193278312683105, 0.0, 0.0), (0.33613446354866028, 0.0, 0.0), (0.3403361439704895, 0.0, 0.0), (0.34453782439231873, 0.0, 0.0), (0.34873950481414795, 0.0, 0.0), (0.35294118523597717, 0.0, 0.0), (0.3571428656578064, 0.0, 0.0), (0.36134454607963562, 0.0, 0.0), (0.36554622650146484, 0.0, 0.0), (0.36974790692329407, 0.0, 0.0), (0.37394958734512329, 0.0, 0.0), (0.37815126776695251, 0.0, 0.0), (0.38235294818878174, 0.0, 0.0), (0.38655462861061096, 0.0, 0.0), (0.39075630903244019, 0.0, 0.0), (0.39495798945426941, 0.0, 0.0), (0.39915966987609863, 0.0, 0.0), (0.40336135029792786, 0.0, 0.0), (0.40756303071975708, 0.0, 0.0), (0.4117647111415863, 0.0, 0.0), (0.41596639156341553, 0.0, 0.0), (0.42016807198524475, 0.0, 0.0), (0.42436975240707397, 0.0, 0.0), (0.4285714328289032, 0.0, 0.0), (0.43277311325073242, 0.0, 0.0), (0.43697479367256165, 0.0, 0.0), (0.44117647409439087, 0.0, 0.0), (0.44537815451622009, 0.0, 0.0), (0.44957983493804932, 0.0, 0.0), (0.45378151535987854, 0.0, 0.0), (0.45798319578170776, 0.0, 0.0), (0.46218487620353699, 0.0, 0.0), (0.46638655662536621, 0.0, 0.0), (0.47058823704719543, 0.0, 0.0), (0.47478991746902466, 0.0, 0.0), (0.47899159789085388, 0.0, 0.0), (0.48319327831268311, 0.0, 0.0), (0.48739495873451233, 0.0, 0.0), (0.49159663915634155, 0.0, 0.0), (0.49579831957817078, 0.0, 0.0), (0.5, 0.0, 0.0), (0.50420171022415161, 0.0, 0.0), (0.50840336084365845, 0.0, 0.0), (0.51260507106781006, 0.0, 0.0), (0.51680672168731689, 0.0, 0.0), (0.52100843191146851, 0.0, 0.0), (0.52521008253097534, 0.0, 0.0), (0.52941179275512695, 0.0, 0.0), (0.53361344337463379, 0.0, 0.0), (0.5378151535987854, 0.0, 0.0), (0.54201680421829224, 0.0, 0.0), (0.54621851444244385, 0.0, 0.0), (0.55042016506195068, 0.0, 0.0), (0.55462187528610229, 0.0, 0.0), (0.55882352590560913, 0.0, 0.0), (0.56302523612976074, 0.0, 0.0), (0.56722688674926758, 0.0, 0.0), (0.57142859697341919, 0.0, 0.0), (0.57563024759292603, 0.0, 0.0), (0.57983195781707764, 0.0, 0.0), (0.58403360843658447, 0.0, 0.0), (0.58823531866073608, 0.0, 0.0), (0.59243696928024292, 0.0, 0.0), (0.59663867950439453, 0.0, 0.0), (0.60084033012390137, 0.0, 0.0), (0.60504204034805298, 0.0, 0.0), (0.60924369096755981, 0.0, 0.0), (0.61344540119171143, 0.0, 0.0), (0.61764705181121826, 0.0, 0.0), (0.62184876203536987, 0.0, 0.0), (0.62605041265487671, 0.0, 0.0), (0.63025212287902832, 0.0, 0.0), (0.63445377349853516, 0.0, 0.0), (0.63865548372268677, 0.0, 0.0), (0.6428571343421936, 0.0, 0.0), (0.64705884456634521, 0.0, 0.0), (0.65126049518585205, 0.0, 0.0), (0.65546220541000366, 0.0, 0.0), (0.6596638560295105, 0.0, 0.0), (0.66386556625366211, 0.0, 0.0), (0.66806721687316895, 0.0, 0.0), (0.67226892709732056, 0.0, 0.0), (0.67647057771682739, 0.0, 0.0), (0.680672287940979, 0.0, 0.0), (0.68487393856048584, 0.0, 0.0), (0.68907564878463745, 0.0, 0.0), (0.69327729940414429, 0.0, 0.0), (0.6974790096282959, 0.0, 0.0), (0.70168066024780273, 0.0, 0.0), (0.70588237047195435, 0.0, 0.0), (0.71008402109146118, 0.0, 0.0), (0.71428573131561279, 0.0, 0.0), (0.71848738193511963, 0.0, 0.0), (0.72268909215927124, 0.0, 0.0), (0.72689074277877808, 0.0, 0.0), (0.73109245300292969, 0.0, 0.0), (0.73529410362243652, 0.0, 0.0), (0.73949581384658813, 0.0, 0.0), (0.74369746446609497, 0.0, 0.0), (0.74789917469024658, 0.0, 0.0), (0.75210082530975342, 0.0, 0.0), (0.75630253553390503, 0.027450980618596077, 0.027450980618596077), (0.76050418615341187, 0.043137256056070328, 0.043137256056070328), (0.76470589637756348, 0.058823529630899429, 0.058823529630899429), (0.76890754699707031, 0.074509806931018829, 0.074509806931018829), (0.77310925722122192, 0.090196080505847931, 0.090196080505847931), (0.77731090784072876, 0.10588235408067703, 0.10588235408067703), (0.78151261806488037, 0.12156862765550613, 0.12156862765550613), (0.78571426868438721, 0.13725490868091583, 0.13725490868091583), (0.78991597890853882, 0.15294118225574493, 0.15294118225574493), (0.79411762952804565, 0.16862745583057404, 0.16862745583057404), (0.79831933975219727, 0.20000000298023224, 0.20000000298023224), (0.8025209903717041, 0.21176470816135406, 0.21176470816135406), (0.80672270059585571, 0.22745098173618317, 0.22745098173618317), (0.81092435121536255, 0.24313725531101227, 0.24313725531101227), (0.81512606143951416, 0.25882354378700256, 0.25882354378700256), (0.819327712059021, 0.27450981736183167, 0.27450981736183167), (0.82352942228317261, 0.29019609093666077, 0.29019609093666077), (0.82773107290267944, 0.30588236451148987, 0.30588236451148987), (0.83193278312683105, 0.32156863808631897, 0.32156863808631897), (0.83613443374633789, 0.33725491166114807, 0.33725491166114807), (0.8403361439704895, 0.35294118523597717, 0.35294118523597717), (0.84453779458999634, 0.36862745881080627, 0.36862745881080627), (0.84873950481414795, 0.38431373238563538, 0.38431373238563538), (0.85294115543365479, 0.40000000596046448, 0.40000000596046448), (0.8571428656578064, 0.4117647111415863, 0.4117647111415863), (0.86134451627731323, 0.42745098471641541, 0.42745098471641541), (0.86554622650146484, 0.44313725829124451, 0.44313725829124451), (0.86974787712097168, 0.45882353186607361, 0.45882353186607361), (0.87394958734512329, 0.47450980544090271, 0.47450980544090271), (0.87815123796463013, 0.49019607901573181, 0.49019607901573181), (0.88235294818878174, 0.5215686559677124, 0.5215686559677124), (0.88655459880828857, 0.5372549295425415, 0.5372549295425415), (0.89075630903244019, 0.55294120311737061, 0.55294120311737061), (0.89495795965194702, 0.56862747669219971, 0.56862747669219971), (0.89915966987609863, 0.58431375026702881, 0.58431375026702881), (0.90336132049560547, 0.60000002384185791, 0.60000002384185791), (0.90756303071975708, 0.61176472902297974, 0.61176472902297974), (0.91176468133926392, 0.62745100259780884, 0.62745100259780884), (0.91596639156341553, 0.64313727617263794, 0.64313727617263794), (0.92016804218292236, 0.65882354974746704, 0.65882354974746704), (0.92436975240707397, 0.67450982332229614, 0.67450982332229614), (0.92857140302658081, 0.69019609689712524, 0.69019609689712524), (0.93277311325073242, 0.70588237047195435, 0.70588237047195435), (0.93697476387023926, 0.72156864404678345, 0.72156864404678345), (0.94117647409439087, 0.73725491762161255, 0.73725491762161255), (0.94537812471389771, 0.75294119119644165, 0.75294119119644165), (0.94957983493804932, 0.76862746477127075, 0.76862746477127075), (0.95378148555755615, 0.78431373834609985, 0.78431373834609985), (0.95798319578170776, 0.80000001192092896, 0.80000001192092896), (0.9621848464012146, 0.81176471710205078, 0.81176471710205078), (0.96638655662536621, 0.84313726425170898, 0.84313726425170898), (0.97058820724487305, 0.85882353782653809, 0.85882353782653809), (0.97478991746902466, 0.87450981140136719, 0.87450981140136719), (0.97899156808853149, 0.89019608497619629, 0.89019608497619629), (0.98319327831268311, 0.90588235855102539, 0.90588235855102539), (0.98739492893218994, 0.92156863212585449, 0.92156863212585449), (0.99159663915634155, 0.93725490570068359, 0.93725490570068359), (0.99579828977584839, 0.9529411792755127, 0.9529411792755127), (1.0, 0.9686274528503418, 0.9686274528503418)], 'green': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0, 0.0), (0.0084033617749810219, 0.0, 0.0), (0.012605042196810246, 0.0, 0.0), (0.016806723549962044, 0.0, 0.0), (0.021008403971791267, 0.0, 0.0), (0.025210084393620491, 0.0, 0.0), (0.029411764815449715, 0.0, 0.0), (0.033613447099924088, 0.0, 0.0), (0.037815127521753311, 0.0, 0.0), (0.042016807943582535, 0.0, 0.0), (0.046218488365411758, 0.0, 0.0), (0.050420168787240982, 0.0, 0.0), (0.054621849209070206, 0.0, 0.0), (0.058823529630899429, 0.0, 0.0), (0.063025213778018951, 0.0, 0.0), (0.067226894199848175, 0.0, 0.0), (0.071428574621677399, 0.0, 0.0), (0.075630255043506622, 0.0, 0.0), (0.079831935465335846, 0.0, 0.0), (0.08403361588716507, 0.0, 0.0), (0.088235296308994293, 0.0, 0.0), (0.092436976730823517, 0.0, 0.0), (0.09663865715265274, 0.0, 0.0), (0.10084033757448196, 0.0, 0.0), (0.10504201799631119, 0.0, 0.0), (0.10924369841814041, 0.0, 0.0), (0.11344537883996964, 0.0, 0.0), (0.11764705926179886, 0.0, 0.0), (0.12184873968362808, 0.0, 0.0), (0.1260504275560379, 0.0, 0.0), (0.13025210797786713, 0.0, 0.0), (0.13445378839969635, 0.0, 0.0), (0.13865546882152557, 0.0, 0.0), (0.1428571492433548, 0.0, 0.0), (0.14705882966518402, 0.0, 0.0), (0.15126051008701324, 0.0, 0.0), (0.15546219050884247, 0.0, 0.0), (0.15966387093067169, 0.0, 0.0), (0.16386555135250092, 0.0, 0.0), (0.16806723177433014, 0.0, 0.0), (0.17226891219615936, 0.0, 0.0), (0.17647059261798859, 0.0, 0.0), (0.18067227303981781, 0.0, 0.0), (0.18487395346164703, 0.0, 0.0), (0.18907563388347626, 0.0, 0.0), (0.19327731430530548, 0.0, 0.0), (0.1974789947271347, 0.0, 0.0), (0.20168067514896393, 0.0, 0.0), (0.20588235557079315, 0.0, 0.0), (0.21008403599262238, 0.0, 0.0), (0.2142857164144516, 0.0, 0.0), (0.21848739683628082, 0.0, 0.0), (0.22268907725811005, 0.0, 0.0), (0.22689075767993927, 0.0, 0.0), (0.23109243810176849, 0.0, 0.0), (0.23529411852359772, 0.0, 0.0), (0.23949579894542694, 0.0, 0.0), (0.24369747936725616, 0.0, 0.0), (0.24789915978908539, 0.0, 0.0), (0.25210085511207581, 0.0, 0.0), (0.25630253553390503, 0.0, 0.0), (0.26050421595573425, 0.0, 0.0), (0.26470589637756348, 0.0, 0.0), (0.2689075767993927, 0.0, 0.0), (0.27310925722122192, 0.0, 0.0), (0.27731093764305115, 0.0, 0.0), (0.28151261806488037, 0.0, 0.0), (0.28571429848670959, 0.0, 0.0), (0.28991597890853882, 0.0, 0.0), (0.29411765933036804, 0.0, 0.0), (0.29831933975219727, 0.0, 0.0), (0.30252102017402649, 0.0, 0.0), (0.30672270059585571, 0.0, 0.0), (0.31092438101768494, 0.0, 0.0), (0.31512606143951416, 0.0, 0.0), (0.31932774186134338, 0.0, 0.0), (0.32352942228317261, 0.0, 0.0), (0.32773110270500183, 0.0, 0.0), (0.33193278312683105, 0.0, 0.0), (0.33613446354866028, 0.0, 0.0), (0.3403361439704895, 0.0, 0.0), (0.34453782439231873, 0.0, 0.0), (0.34873950481414795, 0.0, 0.0), (0.35294118523597717, 0.0, 0.0), (0.3571428656578064, 0.0, 0.0), (0.36134454607963562, 0.0, 0.0), (0.36554622650146484, 0.0, 0.0), (0.36974790692329407, 0.0, 0.0), (0.37394958734512329, 0.0, 0.0), (0.37815126776695251, 0.0, 0.0), (0.38235294818878174, 0.0, 0.0), (0.38655462861061096, 0.0, 0.0), (0.39075630903244019, 0.0, 0.0), (0.39495798945426941, 0.0, 0.0), (0.39915966987609863, 0.0, 0.0), (0.40336135029792786, 0.0, 0.0), (0.40756303071975708, 0.0, 0.0), (0.4117647111415863, 0.0, 0.0), (0.41596639156341553, 0.0, 0.0), (0.42016807198524475, 0.0, 0.0), (0.42436975240707397, 0.0, 0.0), (0.4285714328289032, 0.0, 0.0), (0.43277311325073242, 0.0, 0.0), (0.43697479367256165, 0.0, 0.0), (0.44117647409439087, 0.0, 0.0), (0.44537815451622009, 0.0, 0.0), (0.44957983493804932, 0.0, 0.0), (0.45378151535987854, 0.0, 0.0), (0.45798319578170776, 0.0, 0.0), (0.46218487620353699, 0.0, 0.0), (0.46638655662536621, 0.0, 0.0), (0.47058823704719543, 0.0, 0.0), (0.47478991746902466, 0.0, 0.0), (0.47899159789085388, 0.0039215688593685627, 0.0039215688593685627), (0.48319327831268311, 0.011764706112444401, 0.011764706112444401), (0.48739495873451233, 0.019607843831181526, 0.019607843831181526), (0.49159663915634155, 0.027450980618596077, 0.027450980618596077), (0.49579831957817078, 0.035294119268655777, 0.035294119268655777), (0.5, 0.043137256056070328, 0.043137256056070328), (0.50420171022415161, 0.058823529630899429, 0.058823529630899429), (0.50840336084365845, 0.066666670143604279, 0.066666670143604279), (0.51260507106781006, 0.070588238537311554, 0.070588238537311554), (0.51680672168731689, 0.078431375324726105, 0.078431375324726105), (0.52100843191146851, 0.086274512112140656, 0.086274512112140656), (0.52521008253097534, 0.094117648899555206, 0.094117648899555206), (0.52941179275512695, 0.10196078568696976, 0.10196078568696976), (0.53361344337463379, 0.10980392247438431, 0.10980392247438431), (0.5378151535987854, 0.11764705926179886, 0.11764705926179886), (0.54201680421829224, 0.12549020349979401, 0.12549020349979401), (0.54621851444244385, 0.13725490868091583, 0.13725490868091583), (0.55042016506195068, 0.14509804546833038, 0.14509804546833038), (0.55462187528610229, 0.15294118225574493, 0.15294118225574493), (0.55882352590560913, 0.16078431904315948, 0.16078431904315948), (0.56302523612976074, 0.16862745583057404, 0.16862745583057404), (0.56722688674926758, 0.17647059261798859, 0.17647059261798859), (0.57142859697341919, 0.18431372940540314, 0.18431372940540314), (0.57563024759292603, 0.19215686619281769, 0.19215686619281769), (0.57983195781707764, 0.20000000298023224, 0.20000000298023224), (0.58403360843658447, 0.20392157137393951, 0.20392157137393951), (0.58823531866073608, 0.21176470816135406, 0.21176470816135406), (0.59243696928024292, 0.21960784494876862, 0.21960784494876862), (0.59663867950439453, 0.22745098173618317, 0.22745098173618317), (0.60084033012390137, 0.23529411852359772, 0.23529411852359772), (0.60504204034805298, 0.24313725531101227, 0.24313725531101227), (0.60924369096755981, 0.25098040699958801, 0.25098040699958801), (0.61344540119171143, 0.25882354378700256, 0.25882354378700256), (0.61764705181121826, 0.26666668057441711, 0.26666668057441711), (0.62184876203536987, 0.27058824896812439, 0.27058824896812439), (0.62605041265487671, 0.27843138575553894, 0.27843138575553894), (0.63025212287902832, 0.29411765933036804, 0.29411765933036804), (0.63445377349853516, 0.30196079611778259, 0.30196079611778259), (0.63865548372268677, 0.30980393290519714, 0.30980393290519714), (0.6428571343421936, 0.31764706969261169, 0.31764706969261169), (0.64705884456634521, 0.32549020648002625, 0.32549020648002625), (0.65126049518585205, 0.3333333432674408, 0.3333333432674408), (0.65546220541000366, 0.33725491166114807, 0.33725491166114807), (0.6596638560295105, 0.34509804844856262, 0.34509804844856262), (0.66386556625366211, 0.35294118523597717, 0.35294118523597717), (0.66806721687316895, 0.36078432202339172, 0.36078432202339172), (0.67226892709732056, 0.36862745881080627, 0.36862745881080627), (0.67647057771682739, 0.37647059559822083, 0.37647059559822083), (0.680672287940979, 0.38431373238563538, 0.38431373238563538), (0.68487393856048584, 0.39215686917304993, 0.39215686917304993), (0.68907564878463745, 0.40000000596046448, 0.40000000596046448), (0.69327729940414429, 0.40392157435417175, 0.40392157435417175), (0.6974790096282959, 0.4117647111415863, 0.4117647111415863), (0.70168066024780273, 0.41960784792900085, 0.41960784792900085), (0.70588237047195435, 0.42745098471641541, 0.42745098471641541), (0.71008402109146118, 0.43529412150382996, 0.43529412150382996), (0.71428573131561279, 0.45098039507865906, 0.45098039507865906), (0.71848738193511963, 0.45882353186607361, 0.45882353186607361), (0.72268909215927124, 0.46666666865348816, 0.46666666865348816), (0.72689074277877808, 0.47058823704719543, 0.47058823704719543), (0.73109245300292969, 0.47843137383460999, 0.47843137383460999), (0.73529410362243652, 0.48627451062202454, 0.48627451062202454), (0.73949581384658813, 0.49411764740943909, 0.49411764740943909), (0.74369746446609497, 0.50196081399917603, 0.50196081399917603), (0.74789917469024658, 0.50980395078659058, 0.50980395078659058), (0.75210082530975342, 0.51764708757400513, 0.51764708757400513), (0.75630253553390503, 0.53333336114883423, 0.53333336114883423), (0.76050418615341187, 0.5372549295425415, 0.5372549295425415), (0.76470589637756348, 0.54509806632995605, 0.54509806632995605), (0.76890754699707031, 0.55294120311737061, 0.55294120311737061), (0.77310925722122192, 0.56078433990478516, 0.56078433990478516), (0.77731090784072876, 0.56862747669219971, 0.56862747669219971), (0.78151261806488037, 0.57647061347961426, 0.57647061347961426), (0.78571426868438721, 0.58431375026702881, 0.58431375026702881), (0.78991597890853882, 0.59215688705444336, 0.59215688705444336), (0.79411762952804565, 0.60000002384185791, 0.60000002384185791), (0.79831933975219727, 0.61176472902297974, 0.61176472902297974), (0.8025209903717041, 0.61960786581039429, 0.61960786581039429), (0.80672270059585571, 0.62745100259780884, 0.62745100259780884), (0.81092435121536255, 0.63529413938522339, 0.63529413938522339), (0.81512606143951416, 0.64313727617263794, 0.64313727617263794), (0.819327712059021, 0.65098041296005249, 0.65098041296005249), (0.82352942228317261, 0.65882354974746704, 0.65882354974746704), (0.82773107290267944, 0.66666668653488159, 0.66666668653488159), (0.83193278312683105, 0.67058825492858887, 0.67058825492858887), (0.83613443374633789, 0.67843139171600342, 0.67843139171600342), (0.8403361439704895, 0.68627452850341797, 0.68627452850341797), (0.84453779458999634, 0.69411766529083252, 0.69411766529083252), (0.84873950481414795, 0.70196080207824707, 0.70196080207824707), (0.85294115543365479, 0.70980393886566162, 0.70980393886566162), (0.8571428656578064, 0.71764707565307617, 0.71764707565307617), (0.86134451627731323, 0.72549021244049072, 0.72549021244049072), (0.86554622650146484, 0.73333334922790527, 0.73333334922790527), (0.86974787712097168, 0.73725491762161255, 0.73725491762161255), (0.87394958734512329, 0.7450980544090271, 0.7450980544090271), (0.87815123796463013, 0.75294119119644165, 0.75294119119644165), (0.88235294818878174, 0.76862746477127075, 0.76862746477127075), (0.88655459880828857, 0.7764706015586853, 0.7764706015586853), (0.89075630903244019, 0.78431373834609985, 0.78431373834609985), (0.89495795965194702, 0.7921568751335144, 0.7921568751335144), (0.89915966987609863, 0.80000001192092896, 0.80000001192092896), (0.90336132049560547, 0.80392158031463623, 0.80392158031463623), (0.90756303071975708, 0.81176471710205078, 0.81176471710205078), (0.91176468133926392, 0.81960785388946533, 0.81960785388946533), (0.91596639156341553, 0.82745099067687988, 0.82745099067687988), (0.92016804218292236, 0.83529412746429443, 0.83529412746429443), (0.92436975240707397, 0.84313726425170898, 0.84313726425170898), (0.92857140302658081, 0.85098040103912354, 0.85098040103912354), (0.93277311325073242, 0.85882353782653809, 0.85882353782653809), (0.93697476387023926, 0.86666667461395264, 0.86666667461395264), (0.94117647409439087, 0.87058824300765991, 0.87058824300765991), (0.94537812471389771, 0.87843137979507446, 0.87843137979507446), (0.94957983493804932, 0.88627451658248901, 0.88627451658248901), (0.95378148555755615, 0.89411765336990356, 0.89411765336990356), (0.95798319578170776, 0.90196079015731812, 0.90196079015731812), (0.9621848464012146, 0.90980392694473267, 0.90980392694473267), (0.96638655662536621, 0.92549020051956177, 0.92549020051956177), (0.97058820724487305, 0.93333333730697632, 0.93333333730697632), (0.97478991746902466, 0.93725490570068359, 0.93725490570068359), (0.97899156808853149, 0.94509804248809814, 0.94509804248809814), (0.98319327831268311, 0.9529411792755127, 0.9529411792755127), (0.98739492893218994, 0.96078431606292725, 0.96078431606292725), (0.99159663915634155, 0.9686274528503418, 0.9686274528503418), (0.99579828977584839, 0.97647058963775635, 0.97647058963775635), (1.0, 0.9843137264251709, 0.9843137264251709)], 'red': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0039215688593685627, 0.0039215688593685627), (0.0084033617749810219, 0.0078431377187371254, 0.0078431377187371254), (0.012605042196810246, 0.015686275437474251, 0.015686275437474251), (0.016806723549962044, 0.019607843831181526, 0.019607843831181526), (0.021008403971791267, 0.027450980618596077, 0.027450980618596077), (0.025210084393620491, 0.031372550874948502, 0.031372550874948502), (0.029411764815449715, 0.039215687662363052, 0.039215687662363052), (0.033613447099924088, 0.043137256056070328, 0.043137256056070328), (0.037815127521753311, 0.050980392843484879, 0.050980392843484879), (0.042016807943582535, 0.058823529630899429, 0.058823529630899429), (0.046218488365411758, 0.066666670143604279, 0.066666670143604279), (0.050420168787240982, 0.070588238537311554, 0.070588238537311554), (0.054621849209070206, 0.078431375324726105, 0.078431375324726105), (0.058823529630899429, 0.08235294371843338, 0.08235294371843338), (0.063025213778018951, 0.090196080505847931, 0.090196080505847931), (0.067226894199848175, 0.094117648899555206, 0.094117648899555206), (0.071428574621677399, 0.10196078568696976, 0.10196078568696976), (0.075630255043506622, 0.10588235408067703, 0.10588235408067703), (0.079831935465335846, 0.10980392247438431, 0.10980392247438431), (0.08403361588716507, 0.11764705926179886, 0.11764705926179886), (0.088235296308994293, 0.12156862765550613, 0.12156862765550613), (0.092436976730823517, 0.12941177189350128, 0.12941177189350128), (0.09663865715265274, 0.13333334028720856, 0.13333334028720856), (0.10084033757448196, 0.14117647707462311, 0.14117647707462311), (0.10504201799631119, 0.14509804546833038, 0.14509804546833038), (0.10924369841814041, 0.15294118225574493, 0.15294118225574493), (0.11344537883996964, 0.15686275064945221, 0.15686275064945221), (0.11764705926179886, 0.16470588743686676, 0.16470588743686676), (0.12184873968362808, 0.16862745583057404, 0.16862745583057404), (0.1260504275560379, 0.18039216101169586, 0.18039216101169586), (0.13025210797786713, 0.18431372940540314, 0.18431372940540314), (0.13445378839969635, 0.19215686619281769, 0.19215686619281769), (0.13865546882152557, 0.19607843458652496, 0.19607843458652496), (0.1428571492433548, 0.20392157137393951, 0.20392157137393951), (0.14705882966518402, 0.20784313976764679, 0.20784313976764679), (0.15126051008701324, 0.21568627655506134, 0.21568627655506134), (0.15546219050884247, 0.21960784494876862, 0.21960784494876862), (0.15966387093067169, 0.22352941334247589, 0.22352941334247589), (0.16386555135250092, 0.23137255012989044, 0.23137255012989044), (0.16806723177433014, 0.23529411852359772, 0.23529411852359772), (0.17226891219615936, 0.24313725531101227, 0.24313725531101227), (0.17647059261798859, 0.24705882370471954, 0.24705882370471954), (0.18067227303981781, 0.25490197539329529, 0.25490197539329529), (0.18487395346164703, 0.25882354378700256, 0.25882354378700256), (0.18907563388347626, 0.26666668057441711, 0.26666668057441711), (0.19327731430530548, 0.27058824896812439, 0.27058824896812439), (0.1974789947271347, 0.27450981736183167, 0.27450981736183167), (0.20168067514896393, 0.28235295414924622, 0.28235295414924622), (0.20588235557079315, 0.28627452254295349, 0.28627452254295349), (0.21008403599262238, 0.29803922772407532, 0.29803922772407532), (0.2142857164144516, 0.30588236451148987, 0.30588236451148987), (0.21848739683628082, 0.30980393290519714, 0.30980393290519714), (0.22268907725811005, 0.31764706969261169, 0.31764706969261169), (0.22689075767993927, 0.32156863808631897, 0.32156863808631897), (0.23109243810176849, 0.32941177487373352, 0.32941177487373352), (0.23529411852359772, 0.3333333432674408, 0.3333333432674408), (0.23949579894542694, 0.33725491166114807, 0.33725491166114807), (0.24369747936725616, 0.34509804844856262, 0.34509804844856262), (0.24789915978908539, 0.3490196168422699, 0.3490196168422699), (0.25210085511207581, 0.36078432202339172, 0.36078432202339172), (0.25630253553390503, 0.36862745881080627, 0.36862745881080627), (0.26050421595573425, 0.37254902720451355, 0.37254902720451355), (0.26470589637756348, 0.3803921639919281, 0.3803921639919281), (0.2689075767993927, 0.38431373238563538, 0.38431373238563538), (0.27310925722122192, 0.38823530077934265, 0.38823530077934265), (0.27731093764305115, 0.3960784375667572, 0.3960784375667572), (0.28151261806488037, 0.40000000596046448, 0.40000000596046448), (0.28571429848670959, 0.40784314274787903, 0.40784314274787903), (0.28991597890853882, 0.4117647111415863, 0.4117647111415863), (0.29411765933036804, 0.42352941632270813, 0.42352941632270813), (0.29831933975219727, 0.43137255311012268, 0.43137255311012268), (0.30252102017402649, 0.43529412150382996, 0.43529412150382996), (0.30672270059585571, 0.44313725829124451, 0.44313725829124451), (0.31092438101768494, 0.44705882668495178, 0.44705882668495178), (0.31512606143951416, 0.45098039507865906, 0.45098039507865906), (0.31932774186134338, 0.45882353186607361, 0.45882353186607361), (0.32352942228317261, 0.46274510025978088, 0.46274510025978088), (0.32773110270500183, 0.47058823704719543, 0.47058823704719543), (0.33193278312683105, 0.47450980544090271, 0.47450980544090271), (0.33613446354866028, 0.48235294222831726, 0.48235294222831726), (0.3403361439704895, 0.48627451062202454, 0.48627451062202454), (0.34453782439231873, 0.49411764740943909, 0.49411764740943909), (0.34873950481414795, 0.49803921580314636, 0.49803921580314636), (0.35294118523597717, 0.50196081399917603, 0.50196081399917603), (0.3571428656578064, 0.50980395078659058, 0.50980395078659058), (0.36134454607963562, 0.51372551918029785, 0.51372551918029785), (0.36554622650146484, 0.5215686559677124, 0.5215686559677124), (0.36974790692329407, 0.52549022436141968, 0.52549022436141968), (0.37394958734512329, 0.53333336114883423, 0.53333336114883423), (0.37815126776695251, 0.54509806632995605, 0.54509806632995605), (0.38235294818878174, 0.54901963472366333, 0.54901963472366333), (0.38655462861061096, 0.55294120311737061, 0.55294120311737061), (0.39075630903244019, 0.56078433990478516, 0.56078433990478516), (0.39495798945426941, 0.56470590829849243, 0.56470590829849243), (0.39915966987609863, 0.57254904508590698, 0.57254904508590698), (0.40336135029792786, 0.57647061347961426, 0.57647061347961426), (0.40756303071975708, 0.58431375026702881, 0.58431375026702881), (0.4117647111415863, 0.58823531866073608, 0.58823531866073608), (0.41596639156341553, 0.59607845544815063, 0.59607845544815063), (0.42016807198524475, 0.60000002384185791, 0.60000002384185791), (0.42436975240707397, 0.60784316062927246, 0.60784316062927246), (0.4285714328289032, 0.61176472902297974, 0.61176472902297974), (0.43277311325073242, 0.61568629741668701, 0.61568629741668701), (0.43697479367256165, 0.62352943420410156, 0.62352943420410156), (0.44117647409439087, 0.62745100259780884, 0.62745100259780884), (0.44537815451622009, 0.63529413938522339, 0.63529413938522339), (0.44957983493804932, 0.63921570777893066, 0.63921570777893066), (0.45378151535987854, 0.64705884456634521, 0.64705884456634521), (0.45798319578170776, 0.65098041296005249, 0.65098041296005249), (0.46218487620353699, 0.66274511814117432, 0.66274511814117432), (0.46638655662536621, 0.66666668653488159, 0.66666668653488159), (0.47058823704719543, 0.67450982332229614, 0.67450982332229614), (0.47478991746902466, 0.67843139171600342, 0.67843139171600342), (0.47899159789085388, 0.68627452850341797, 0.68627452850341797), (0.48319327831268311, 0.69019609689712524, 0.69019609689712524), (0.48739495873451233, 0.69803923368453979, 0.69803923368453979), (0.49159663915634155, 0.70196080207824707, 0.70196080207824707), (0.49579831957817078, 0.70980393886566162, 0.70980393886566162), (0.5, 0.7137255072593689, 0.7137255072593689), (0.50420171022415161, 0.72549021244049072, 0.72549021244049072), (0.50840336084365845, 0.729411780834198, 0.729411780834198), (0.51260507106781006, 0.73725491762161255, 0.73725491762161255), (0.51680672168731689, 0.74117648601531982, 0.74117648601531982), (0.52100843191146851, 0.74901962280273438, 0.74901962280273438), (0.52521008253097534, 0.75294119119644165, 0.75294119119644165), (0.52941179275512695, 0.7607843279838562, 0.7607843279838562), (0.53361344337463379, 0.76470589637756348, 0.76470589637756348), (0.5378151535987854, 0.77254903316497803, 0.77254903316497803), (0.54201680421829224, 0.7764706015586853, 0.7764706015586853), (0.54621851444244385, 0.78823530673980713, 0.78823530673980713), (0.55042016506195068, 0.7921568751335144, 0.7921568751335144), (0.55462187528610229, 0.80000001192092896, 0.80000001192092896), (0.55882352590560913, 0.80392158031463623, 0.80392158031463623), (0.56302523612976074, 0.81176471710205078, 0.81176471710205078), (0.56722688674926758, 0.81568628549575806, 0.81568628549575806), (0.57142859697341919, 0.82352942228317261, 0.82352942228317261), (0.57563024759292603, 0.82745099067687988, 0.82745099067687988), (0.57983195781707764, 0.83137255907058716, 0.83137255907058716), (0.58403360843658447, 0.83921569585800171, 0.83921569585800171), (0.58823531866073608, 0.84313726425170898, 0.84313726425170898), (0.59243696928024292, 0.85098040103912354, 0.85098040103912354), (0.59663867950439453, 0.85490196943283081, 0.85490196943283081), (0.60084033012390137, 0.86274510622024536, 0.86274510622024536), (0.60504204034805298, 0.86666667461395264, 0.86666667461395264), (0.60924369096755981, 0.87450981140136719, 0.87450981140136719), (0.61344540119171143, 0.87843137979507446, 0.87843137979507446), (0.61764705181121826, 0.88627451658248901, 0.88627451658248901), (0.62184876203536987, 0.89019608497619629, 0.89019608497619629), (0.62605041265487671, 0.89411765336990356, 0.89411765336990356), (0.63025212287902832, 0.90588235855102539, 0.90588235855102539), (0.63445377349853516, 0.91372549533843994, 0.91372549533843994), (0.63865548372268677, 0.91764706373214722, 0.91764706373214722), (0.6428571343421936, 0.92549020051956177, 0.92549020051956177), (0.64705884456634521, 0.92941176891326904, 0.92941176891326904), (0.65126049518585205, 0.93725490570068359, 0.93725490570068359), (0.65546220541000366, 0.94117647409439087, 0.94117647409439087), (0.6596638560295105, 0.94509804248809814, 0.94509804248809814), (0.66386556625366211, 0.9529411792755127, 0.9529411792755127), (0.66806721687316895, 0.95686274766921997, 0.95686274766921997), (0.67226892709732056, 0.96470588445663452, 0.96470588445663452), (0.67647057771682739, 0.9686274528503418, 0.9686274528503418), (0.680672287940979, 0.97647058963775635, 0.97647058963775635), (0.68487393856048584, 0.98039215803146362, 0.98039215803146362), (0.68907564878463745, 0.98823529481887817, 0.98823529481887817), (0.69327729940414429, 0.99215686321258545, 0.99215686321258545), (0.6974790096282959, 1.0, 1.0), (0.70168066024780273, 1.0, 1.0), (0.70588237047195435, 1.0, 1.0), (0.71008402109146118, 1.0, 1.0), (0.71428573131561279, 1.0, 1.0), (0.71848738193511963, 1.0, 1.0), (0.72268909215927124, 1.0, 1.0), (0.72689074277877808, 1.0, 1.0), (0.73109245300292969, 1.0, 1.0), (0.73529410362243652, 1.0, 1.0), (0.73949581384658813, 1.0, 1.0), (0.74369746446609497, 1.0, 1.0), (0.74789917469024658, 1.0, 1.0), (0.75210082530975342, 1.0, 1.0), (0.75630253553390503, 1.0, 1.0), (0.76050418615341187, 1.0, 1.0), (0.76470589637756348, 1.0, 1.0), (0.76890754699707031, 1.0, 1.0), (0.77310925722122192, 1.0, 1.0), (0.77731090784072876, 1.0, 1.0), (0.78151261806488037, 1.0, 1.0), (0.78571426868438721, 1.0, 1.0), (0.78991597890853882, 1.0, 1.0), (0.79411762952804565, 1.0, 1.0), (0.79831933975219727, 1.0, 1.0), (0.8025209903717041, 1.0, 1.0), (0.80672270059585571, 1.0, 1.0), (0.81092435121536255, 1.0, 1.0), (0.81512606143951416, 1.0, 1.0), (0.819327712059021, 1.0, 1.0), (0.82352942228317261, 1.0, 1.0), (0.82773107290267944, 1.0, 1.0), (0.83193278312683105, 1.0, 1.0), (0.83613443374633789, 1.0, 1.0), (0.8403361439704895, 1.0, 1.0), (0.84453779458999634, 1.0, 1.0), (0.84873950481414795, 1.0, 1.0), (0.85294115543365479, 1.0, 1.0), (0.8571428656578064, 1.0, 1.0), (0.86134451627731323, 1.0, 1.0), (0.86554622650146484, 1.0, 1.0), (0.86974787712097168, 1.0, 1.0), (0.87394958734512329, 1.0, 1.0), (0.87815123796463013, 1.0, 1.0), (0.88235294818878174, 1.0, 1.0), (0.88655459880828857, 1.0, 1.0), (0.89075630903244019, 1.0, 1.0), (0.89495795965194702, 1.0, 1.0), (0.89915966987609863, 1.0, 1.0), (0.90336132049560547, 1.0, 1.0), (0.90756303071975708, 1.0, 1.0), (0.91176468133926392, 1.0, 1.0), (0.91596639156341553, 1.0, 1.0), (0.92016804218292236, 1.0, 1.0), (0.92436975240707397, 1.0, 1.0), (0.92857140302658081, 1.0, 1.0), (0.93277311325073242, 1.0, 1.0), (0.93697476387023926, 1.0, 1.0), (0.94117647409439087, 1.0, 1.0), (0.94537812471389771, 1.0, 1.0), (0.94957983493804932, 1.0, 1.0), (0.95378148555755615, 1.0, 1.0), (0.95798319578170776, 1.0, 1.0), (0.9621848464012146, 1.0, 1.0), (0.96638655662536621, 1.0, 1.0), (0.97058820724487305, 1.0, 1.0), (0.97478991746902466, 1.0, 1.0), (0.97899156808853149, 1.0, 1.0), (0.98319327831268311, 1.0, 1.0), (0.98739492893218994, 1.0, 1.0), (0.99159663915634155, 1.0, 1.0), (0.99579828977584839, 1.0, 1.0), (1.0, 1.0, 1.0)]} _gist_ncar_data = {'blue': [(0.0, 0.50196081399917603, 0.50196081399917603), (0.0050505050458014011, 0.45098039507865906, 0.45098039507865906), (0.010101010091602802, 0.40392157435417175, 0.40392157435417175), (0.015151515603065491, 0.35686275362968445, 0.35686275362968445), (0.020202020183205605, 0.30980393290519714, 0.30980393290519714), (0.025252524763345718, 0.25882354378700256, 0.25882354378700256), (0.030303031206130981, 0.21176470816135406, 0.21176470816135406), (0.035353533923625946, 0.16470588743686676, 0.16470588743686676), (0.040404040366411209, 0.11764705926179886, 0.11764705926179886), (0.045454546809196472, 0.070588238537311554, 0.070588238537311554), (0.050505049526691437, 0.019607843831181526, 0.019607843831181526), (0.0555555559694767, 0.047058824449777603, 0.047058824449777603), (0.060606062412261963, 0.14509804546833038, 0.14509804546833038), (0.065656565129756927, 0.23921568691730499, 0.23921568691730499), (0.070707067847251892, 0.3333333432674408, 0.3333333432674408), (0.075757578015327454, 0.43137255311012268, 0.43137255311012268), (0.080808080732822418, 0.52549022436141968, 0.52549022436141968), (0.085858583450317383, 0.61960786581039429, 0.61960786581039429), (0.090909093618392944, 0.71764707565307617, 0.71764707565307617), (0.095959596335887909, 0.81176471710205078, 0.81176471710205078), (0.10101009905338287, 0.90588235855102539, 0.90588235855102539), (0.10606060922145844, 1.0, 1.0), (0.1111111119389534, 1.0, 1.0), (0.11616161465644836, 1.0, 1.0), (0.12121212482452393, 1.0, 1.0), (0.12626262009143829, 1.0, 1.0), (0.13131313025951385, 1.0, 1.0), (0.13636364042758942, 1.0, 1.0), (0.14141413569450378, 1.0, 1.0), (0.14646464586257935, 1.0, 1.0), (0.15151515603065491, 1.0, 1.0), (0.15656565129756927, 1.0, 1.0), (0.16161616146564484, 1.0, 1.0), (0.1666666716337204, 1.0, 1.0), (0.17171716690063477, 1.0, 1.0), (0.17676767706871033, 1.0, 1.0), (0.18181818723678589, 1.0, 1.0), (0.18686868250370026, 1.0, 1.0), (0.19191919267177582, 1.0, 1.0), (0.19696970283985138, 1.0, 1.0), (0.20202019810676575, 1.0, 1.0), (0.20707070827484131, 1.0, 1.0), (0.21212121844291687, 0.99215686321258545, 0.99215686321258545), (0.21717171370983124, 0.95686274766921997, 0.95686274766921997), (0.2222222238779068, 0.91764706373214722, 0.91764706373214722), (0.22727273404598236, 0.88235294818878174, 0.88235294818878174), (0.23232322931289673, 0.84313726425170898, 0.84313726425170898), (0.23737373948097229, 0.80392158031463623, 0.80392158031463623), (0.24242424964904785, 0.76862746477127075, 0.76862746477127075), (0.24747474491596222, 0.729411780834198, 0.729411780834198), (0.25252524018287659, 0.69019609689712524, 0.69019609689712524), (0.25757575035095215, 0.65490198135375977, 0.65490198135375977), (0.26262626051902771, 0.61568629741668701, 0.61568629741668701), (0.26767677068710327, 0.56470590829849243, 0.56470590829849243), (0.27272728085517883, 0.50980395078659058, 0.50980395078659058), (0.27777779102325439, 0.45098039507865906, 0.45098039507865906), (0.28282827138900757, 0.39215686917304993, 0.39215686917304993), (0.28787878155708313, 0.3333333432674408, 0.3333333432674408), (0.29292929172515869, 0.27843138575553894, 0.27843138575553894), (0.29797980189323425, 0.21960784494876862, 0.21960784494876862), (0.30303031206130981, 0.16078431904315948, 0.16078431904315948), (0.30808082222938538, 0.10588235408067703, 0.10588235408067703), (0.31313130259513855, 0.047058824449777603, 0.047058824449777603), (0.31818181276321411, 0.0, 0.0), (0.32323232293128967, 0.0, 0.0), (0.32828283309936523, 0.0, 0.0), (0.3333333432674408, 0.0, 0.0), (0.33838382363319397, 0.0, 0.0), (0.34343433380126953, 0.0, 0.0), (0.34848484396934509, 0.0, 0.0), (0.35353535413742065, 0.0, 0.0), (0.35858586430549622, 0.0, 0.0), (0.36363637447357178, 0.0, 0.0), (0.36868685483932495, 0.0, 0.0), (0.37373736500740051, 0.0, 0.0), (0.37878787517547607, 0.0, 0.0), (0.38383838534355164, 0.0, 0.0), (0.3888888955116272, 0.0, 0.0), (0.39393940567970276, 0.0, 0.0), (0.39898988604545593, 0.0, 0.0), (0.40404039621353149, 0.0, 0.0), (0.40909090638160706, 0.0, 0.0), (0.41414141654968262, 0.0, 0.0), (0.41919192671775818, 0.0, 0.0), (0.42424243688583374, 0.0039215688593685627, 0.0039215688593685627), (0.42929291725158691, 0.027450980618596077, 0.027450980618596077), (0.43434342741966248, 0.050980392843484879, 0.050980392843484879), (0.43939393758773804, 0.074509806931018829, 0.074509806931018829), (0.4444444477558136, 0.094117648899555206, 0.094117648899555206), (0.44949495792388916, 0.11764705926179886, 0.11764705926179886), (0.45454546809196472, 0.14117647707462311, 0.14117647707462311), (0.4595959484577179, 0.16470588743686676, 0.16470588743686676), (0.46464645862579346, 0.18823529779911041, 0.18823529779911041), (0.46969696879386902, 0.21176470816135406, 0.21176470816135406), (0.47474747896194458, 0.23529411852359772, 0.23529411852359772), (0.47979798913002014, 0.22352941334247589, 0.22352941334247589), (0.4848484992980957, 0.20000000298023224, 0.20000000298023224), (0.48989897966384888, 0.17647059261798859, 0.17647059261798859), (0.49494948983192444, 0.15294118225574493, 0.15294118225574493), (0.5, 0.12941177189350128, 0.12941177189350128), (0.50505048036575317, 0.10980392247438431, 0.10980392247438431), (0.51010102033615112, 0.086274512112140656, 0.086274512112140656), (0.5151515007019043, 0.062745101749897003, 0.062745101749897003), (0.52020204067230225, 0.039215687662363052, 0.039215687662363052), (0.52525252103805542, 0.015686275437474251, 0.015686275437474251), (0.53030300140380859, 0.0, 0.0), (0.53535354137420654, 0.0, 0.0), (0.54040402173995972, 0.0, 0.0), (0.54545456171035767, 0.0, 0.0), (0.55050504207611084, 0.0, 0.0), (0.55555558204650879, 0.0, 0.0), (0.56060606241226196, 0.0, 0.0), (0.56565654277801514, 0.0, 0.0), (0.57070708274841309, 0.0, 0.0), (0.57575756311416626, 0.0, 0.0), (0.58080810308456421, 0.0, 0.0), (0.58585858345031738, 0.0039215688593685627, 0.0039215688593685627), (0.59090906381607056, 0.0078431377187371254, 0.0078431377187371254), (0.59595960378646851, 0.011764706112444401, 0.011764706112444401), (0.60101008415222168, 0.019607843831181526, 0.019607843831181526), (0.60606062412261963, 0.023529412224888802, 0.023529412224888802), (0.6111111044883728, 0.031372550874948502, 0.031372550874948502), (0.61616164445877075, 0.035294119268655777, 0.035294119268655777), (0.62121212482452393, 0.043137256056070328, 0.043137256056070328), (0.6262626051902771, 0.047058824449777603, 0.047058824449777603), (0.63131314516067505, 0.054901961237192154, 0.054901961237192154), (0.63636362552642822, 0.054901961237192154, 0.054901961237192154), (0.64141416549682617, 0.050980392843484879, 0.050980392843484879), (0.64646464586257935, 0.043137256056070328, 0.043137256056070328), (0.65151512622833252, 0.039215687662363052, 0.039215687662363052), (0.65656566619873047, 0.031372550874948502, 0.031372550874948502), (0.66161614656448364, 0.027450980618596077, 0.027450980618596077), (0.66666668653488159, 0.019607843831181526, 0.019607843831181526), (0.67171716690063477, 0.015686275437474251, 0.015686275437474251), (0.67676764726638794, 0.011764706112444401, 0.011764706112444401), (0.68181818723678589, 0.0039215688593685627, 0.0039215688593685627), (0.68686866760253906, 0.0, 0.0), (0.69191920757293701, 0.0, 0.0), (0.69696968793869019, 0.0, 0.0), (0.70202022790908813, 0.0, 0.0), (0.70707070827484131, 0.0, 0.0), (0.71212118864059448, 0.0, 0.0), (0.71717172861099243, 0.0, 0.0), (0.72222220897674561, 0.0, 0.0), (0.72727274894714355, 0.0, 0.0), (0.73232322931289673, 0.0, 0.0), (0.7373737096786499, 0.0, 0.0), (0.74242424964904785, 0.031372550874948502, 0.031372550874948502), (0.74747473001480103, 0.12941177189350128, 0.12941177189350128), (0.75252526998519897, 0.22352941334247589, 0.22352941334247589), (0.75757575035095215, 0.32156863808631897, 0.32156863808631897), (0.7626262903213501, 0.41568627953529358, 0.41568627953529358), (0.76767677068710327, 0.50980395078659058, 0.50980395078659058), (0.77272725105285645, 0.60784316062927246, 0.60784316062927246), (0.77777779102325439, 0.70196080207824707, 0.70196080207824707), (0.78282827138900757, 0.79607844352722168, 0.79607844352722168), (0.78787881135940552, 0.89411765336990356, 0.89411765336990356), (0.79292929172515869, 0.98823529481887817, 0.98823529481887817), (0.79797977209091187, 1.0, 1.0), (0.80303031206130981, 1.0, 1.0), (0.80808079242706299, 1.0, 1.0), (0.81313133239746094, 1.0, 1.0), (0.81818181276321411, 1.0, 1.0), (0.82323235273361206, 1.0, 1.0), (0.82828283309936523, 1.0, 1.0), (0.83333331346511841, 1.0, 1.0), (0.83838385343551636, 1.0, 1.0), (0.84343433380126953, 1.0, 1.0), (0.84848487377166748, 0.99607843160629272, 0.99607843160629272), (0.85353535413742065, 0.98823529481887817, 0.98823529481887817), (0.85858583450317383, 0.9843137264251709, 0.9843137264251709), (0.86363637447357178, 0.97647058963775635, 0.97647058963775635), (0.86868685483932495, 0.9686274528503418, 0.9686274528503418), (0.8737373948097229, 0.96470588445663452, 0.96470588445663452), (0.87878787517547607, 0.95686274766921997, 0.95686274766921997), (0.88383835554122925, 0.94901961088180542, 0.94901961088180542), (0.8888888955116272, 0.94509804248809814, 0.94509804248809814), (0.89393937587738037, 0.93725490570068359, 0.93725490570068359), (0.89898991584777832, 0.93333333730697632, 0.93333333730697632), (0.90404039621353149, 0.93333333730697632, 0.93333333730697632), (0.90909093618392944, 0.93725490570068359, 0.93725490570068359), (0.91414141654968262, 0.93725490570068359, 0.93725490570068359), (0.91919189691543579, 0.94117647409439087, 0.94117647409439087), (0.92424243688583374, 0.94509804248809814, 0.94509804248809814), (0.92929291725158691, 0.94509804248809814, 0.94509804248809814), (0.93434345722198486, 0.94901961088180542, 0.94901961088180542), (0.93939393758773804, 0.9529411792755127, 0.9529411792755127), (0.94444441795349121, 0.9529411792755127, 0.9529411792755127), (0.94949495792388916, 0.95686274766921997, 0.95686274766921997), (0.95454543828964233, 0.96078431606292725, 0.96078431606292725), (0.95959597826004028, 0.96470588445663452, 0.96470588445663452), (0.96464645862579346, 0.9686274528503418, 0.9686274528503418), (0.96969699859619141, 0.97254902124404907, 0.97254902124404907), (0.97474747896194458, 0.97647058963775635, 0.97647058963775635), (0.97979795932769775, 0.98039215803146362, 0.98039215803146362), (0.9848484992980957, 0.9843137264251709, 0.9843137264251709), (0.98989897966384888, 0.98823529481887817, 0.98823529481887817), (0.99494951963424683, 0.99215686321258545, 0.99215686321258545), (1.0, 0.99607843160629272, 0.99607843160629272)], 'green': [(0.0, 0.0, 0.0), (0.0050505050458014011, 0.035294119268655777, 0.035294119268655777), (0.010101010091602802, 0.074509806931018829, 0.074509806931018829), (0.015151515603065491, 0.10980392247438431, 0.10980392247438431), (0.020202020183205605, 0.14901961386203766, 0.14901961386203766), (0.025252524763345718, 0.18431372940540314, 0.18431372940540314), (0.030303031206130981, 0.22352941334247589, 0.22352941334247589), (0.035353533923625946, 0.25882354378700256, 0.25882354378700256), (0.040404040366411209, 0.29803922772407532, 0.29803922772407532), (0.045454546809196472, 0.3333333432674408, 0.3333333432674408), (0.050505049526691437, 0.37254902720451355, 0.37254902720451355), (0.0555555559694767, 0.36862745881080627, 0.36862745881080627), (0.060606062412261963, 0.3333333432674408, 0.3333333432674408), (0.065656565129756927, 0.29411765933036804, 0.29411765933036804), (0.070707067847251892, 0.25882354378700256, 0.25882354378700256), (0.075757578015327454, 0.21960784494876862, 0.21960784494876862), (0.080808080732822418, 0.18431372940540314, 0.18431372940540314), (0.085858583450317383, 0.14509804546833038, 0.14509804546833038), (0.090909093618392944, 0.10980392247438431, 0.10980392247438431), (0.095959596335887909, 0.070588238537311554, 0.070588238537311554), (0.10101009905338287, 0.035294119268655777, 0.035294119268655777), (0.10606060922145844, 0.0, 0.0), (0.1111111119389534, 0.074509806931018829, 0.074509806931018829), (0.11616161465644836, 0.14509804546833038, 0.14509804546833038), (0.12121212482452393, 0.21568627655506134, 0.21568627655506134), (0.12626262009143829, 0.28627452254295349, 0.28627452254295349), (0.13131313025951385, 0.36078432202339172, 0.36078432202339172), (0.13636364042758942, 0.43137255311012268, 0.43137255311012268), (0.14141413569450378, 0.50196081399917603, 0.50196081399917603), (0.14646464586257935, 0.57254904508590698, 0.57254904508590698), (0.15151515603065491, 0.64705884456634521, 0.64705884456634521), (0.15656565129756927, 0.71764707565307617, 0.71764707565307617), (0.16161616146564484, 0.7607843279838562, 0.7607843279838562), (0.1666666716337204, 0.78431373834609985, 0.78431373834609985), (0.17171716690063477, 0.80784314870834351, 0.80784314870834351), (0.17676767706871033, 0.83137255907058716, 0.83137255907058716), (0.18181818723678589, 0.85490196943283081, 0.85490196943283081), (0.18686868250370026, 0.88235294818878174, 0.88235294818878174), (0.19191919267177582, 0.90588235855102539, 0.90588235855102539), (0.19696970283985138, 0.92941176891326904, 0.92941176891326904), (0.20202019810676575, 0.9529411792755127, 0.9529411792755127), (0.20707070827484131, 0.97647058963775635, 0.97647058963775635), (0.21212121844291687, 0.99607843160629272, 0.99607843160629272), (0.21717171370983124, 0.99607843160629272, 0.99607843160629272), (0.2222222238779068, 0.99215686321258545, 0.99215686321258545), (0.22727273404598236, 0.99215686321258545, 0.99215686321258545), (0.23232322931289673, 0.99215686321258545, 0.99215686321258545), (0.23737373948097229, 0.98823529481887817, 0.98823529481887817), (0.24242424964904785, 0.98823529481887817, 0.98823529481887817), (0.24747474491596222, 0.9843137264251709, 0.9843137264251709), (0.25252524018287659, 0.9843137264251709, 0.9843137264251709), (0.25757575035095215, 0.98039215803146362, 0.98039215803146362), (0.26262626051902771, 0.98039215803146362, 0.98039215803146362), (0.26767677068710327, 0.98039215803146362, 0.98039215803146362), (0.27272728085517883, 0.98039215803146362, 0.98039215803146362), (0.27777779102325439, 0.9843137264251709, 0.9843137264251709), (0.28282827138900757, 0.9843137264251709, 0.9843137264251709), (0.28787878155708313, 0.98823529481887817, 0.98823529481887817), (0.29292929172515869, 0.98823529481887817, 0.98823529481887817), (0.29797980189323425, 0.99215686321258545, 0.99215686321258545), (0.30303031206130981, 0.99215686321258545, 0.99215686321258545), (0.30808082222938538, 0.99607843160629272, 0.99607843160629272), (0.31313130259513855, 0.99607843160629272, 0.99607843160629272), (0.31818181276321411, 0.99607843160629272, 0.99607843160629272), (0.32323232293128967, 0.97647058963775635, 0.97647058963775635), (0.32828283309936523, 0.95686274766921997, 0.95686274766921997), (0.3333333432674408, 0.93725490570068359, 0.93725490570068359), (0.33838382363319397, 0.92156863212585449, 0.92156863212585449), (0.34343433380126953, 0.90196079015731812, 0.90196079015731812), (0.34848484396934509, 0.88235294818878174, 0.88235294818878174), (0.35353535413742065, 0.86274510622024536, 0.86274510622024536), (0.35858586430549622, 0.84705883264541626, 0.84705883264541626), (0.36363637447357178, 0.82745099067687988, 0.82745099067687988), (0.36868685483932495, 0.80784314870834351, 0.80784314870834351), (0.37373736500740051, 0.81568628549575806, 0.81568628549575806), (0.37878787517547607, 0.83529412746429443, 0.83529412746429443), (0.38383838534355164, 0.85098040103912354, 0.85098040103912354), (0.3888888955116272, 0.87058824300765991, 0.87058824300765991), (0.39393940567970276, 0.89019608497619629, 0.89019608497619629), (0.39898988604545593, 0.90980392694473267, 0.90980392694473267), (0.40404039621353149, 0.92549020051956177, 0.92549020051956177), (0.40909090638160706, 0.94509804248809814, 0.94509804248809814), (0.41414141654968262, 0.96470588445663452, 0.96470588445663452), (0.41919192671775818, 0.9843137264251709, 0.9843137264251709), (0.42424243688583374, 1.0, 1.0), (0.42929291725158691, 1.0, 1.0), (0.43434342741966248, 1.0, 1.0), (0.43939393758773804, 1.0, 1.0), (0.4444444477558136, 1.0, 1.0), (0.44949495792388916, 1.0, 1.0), (0.45454546809196472, 1.0, 1.0), (0.4595959484577179, 1.0, 1.0), (0.46464645862579346, 1.0, 1.0), (0.46969696879386902, 1.0, 1.0), (0.47474747896194458, 1.0, 1.0), (0.47979798913002014, 1.0, 1.0), (0.4848484992980957, 1.0, 1.0), (0.48989897966384888, 1.0, 1.0), (0.49494948983192444, 1.0, 1.0), (0.5, 1.0, 1.0), (0.50505048036575317, 1.0, 1.0), (0.51010102033615112, 1.0, 1.0), (0.5151515007019043, 1.0, 1.0), (0.52020204067230225, 1.0, 1.0), (0.52525252103805542, 1.0, 1.0), (0.53030300140380859, 0.99215686321258545, 0.99215686321258545), (0.53535354137420654, 0.98039215803146362, 0.98039215803146362), (0.54040402173995972, 0.96470588445663452, 0.96470588445663452), (0.54545456171035767, 0.94901961088180542, 0.94901961088180542), (0.55050504207611084, 0.93333333730697632, 0.93333333730697632), (0.55555558204650879, 0.91764706373214722, 0.91764706373214722), (0.56060606241226196, 0.90588235855102539, 0.90588235855102539), (0.56565654277801514, 0.89019608497619629, 0.89019608497619629), (0.57070708274841309, 0.87450981140136719, 0.87450981140136719), (0.57575756311416626, 0.85882353782653809, 0.85882353782653809), (0.58080810308456421, 0.84313726425170898, 0.84313726425170898), (0.58585858345031738, 0.83137255907058716, 0.83137255907058716), (0.59090906381607056, 0.81960785388946533, 0.81960785388946533), (0.59595960378646851, 0.81176471710205078, 0.81176471710205078), (0.60101008415222168, 0.80000001192092896, 0.80000001192092896), (0.60606062412261963, 0.78823530673980713, 0.78823530673980713), (0.6111111044883728, 0.7764706015586853, 0.7764706015586853), (0.61616164445877075, 0.76470589637756348, 0.76470589637756348), (0.62121212482452393, 0.75294119119644165, 0.75294119119644165), (0.6262626051902771, 0.74117648601531982, 0.74117648601531982), (0.63131314516067505, 0.729411780834198, 0.729411780834198), (0.63636362552642822, 0.70980393886566162, 0.70980393886566162), (0.64141416549682617, 0.66666668653488159, 0.66666668653488159), (0.64646464586257935, 0.62352943420410156, 0.62352943420410156), (0.65151512622833252, 0.58039218187332153, 0.58039218187332153), (0.65656566619873047, 0.5372549295425415, 0.5372549295425415), (0.66161614656448364, 0.49411764740943909, 0.49411764740943909), (0.66666668653488159, 0.45098039507865906, 0.45098039507865906), (0.67171716690063477, 0.40392157435417175, 0.40392157435417175), (0.67676764726638794, 0.36078432202339172, 0.36078432202339172), (0.68181818723678589, 0.31764706969261169, 0.31764706969261169), (0.68686866760253906, 0.27450981736183167, 0.27450981736183167), (0.69191920757293701, 0.24705882370471954, 0.24705882370471954), (0.69696968793869019, 0.21960784494876862, 0.21960784494876862), (0.70202022790908813, 0.19607843458652496, 0.19607843458652496), (0.70707070827484131, 0.16862745583057404, 0.16862745583057404), (0.71212118864059448, 0.14509804546833038, 0.14509804546833038), (0.71717172861099243, 0.11764705926179886, 0.11764705926179886), (0.72222220897674561, 0.090196080505847931, 0.090196080505847931), (0.72727274894714355, 0.066666670143604279, 0.066666670143604279), (0.73232322931289673, 0.039215687662363052, 0.039215687662363052), (0.7373737096786499, 0.015686275437474251, 0.015686275437474251), (0.74242424964904785, 0.0, 0.0), (0.74747473001480103, 0.0, 0.0), (0.75252526998519897, 0.0, 0.0), (0.75757575035095215, 0.0, 0.0), (0.7626262903213501, 0.0, 0.0), (0.76767677068710327, 0.0, 0.0), (0.77272725105285645, 0.0, 0.0), (0.77777779102325439, 0.0, 0.0), (0.78282827138900757, 0.0, 0.0), (0.78787881135940552, 0.0, 0.0), (0.79292929172515869, 0.0, 0.0), (0.79797977209091187, 0.015686275437474251, 0.015686275437474251), (0.80303031206130981, 0.031372550874948502, 0.031372550874948502), (0.80808079242706299, 0.050980392843484879, 0.050980392843484879), (0.81313133239746094, 0.066666670143604279, 0.066666670143604279), (0.81818181276321411, 0.086274512112140656, 0.086274512112140656), (0.82323235273361206, 0.10588235408067703, 0.10588235408067703), (0.82828283309936523, 0.12156862765550613, 0.12156862765550613), (0.83333331346511841, 0.14117647707462311, 0.14117647707462311), (0.83838385343551636, 0.15686275064945221, 0.15686275064945221), (0.84343433380126953, 0.17647059261798859, 0.17647059261798859), (0.84848487377166748, 0.20000000298023224, 0.20000000298023224), (0.85353535413742065, 0.23137255012989044, 0.23137255012989044), (0.85858583450317383, 0.25882354378700256, 0.25882354378700256), (0.86363637447357178, 0.29019609093666077, 0.29019609093666077), (0.86868685483932495, 0.32156863808631897, 0.32156863808631897), (0.8737373948097229, 0.35294118523597717, 0.35294118523597717), (0.87878787517547607, 0.38431373238563538, 0.38431373238563538), (0.88383835554122925, 0.41568627953529358, 0.41568627953529358), (0.8888888955116272, 0.44313725829124451, 0.44313725829124451), (0.89393937587738037, 0.47450980544090271, 0.47450980544090271), (0.89898991584777832, 0.5058823823928833, 0.5058823823928833), (0.90404039621353149, 0.52941179275512695, 0.52941179275512695), (0.90909093618392944, 0.55294120311737061, 0.55294120311737061), (0.91414141654968262, 0.57254904508590698, 0.57254904508590698), (0.91919189691543579, 0.59607845544815063, 0.59607845544815063), (0.92424243688583374, 0.61960786581039429, 0.61960786581039429), (0.92929291725158691, 0.64313727617263794, 0.64313727617263794), (0.93434345722198486, 0.66274511814117432, 0.66274511814117432), (0.93939393758773804, 0.68627452850341797, 0.68627452850341797), (0.94444441795349121, 0.70980393886566162, 0.70980393886566162), (0.94949495792388916, 0.729411780834198, 0.729411780834198), (0.95454543828964233, 0.75294119119644165, 0.75294119119644165), (0.95959597826004028, 0.78039216995239258, 0.78039216995239258), (0.96464645862579346, 0.80392158031463623, 0.80392158031463623), (0.96969699859619141, 0.82745099067687988, 0.82745099067687988), (0.97474747896194458, 0.85098040103912354, 0.85098040103912354), (0.97979795932769775, 0.87450981140136719, 0.87450981140136719), (0.9848484992980957, 0.90196079015731812, 0.90196079015731812), (0.98989897966384888, 0.92549020051956177, 0.92549020051956177), (0.99494951963424683, 0.94901961088180542, 0.94901961088180542), (1.0, 0.97254902124404907, 0.97254902124404907)], 'red': [(0.0, 0.0, 0.0), (0.0050505050458014011, 0.0, 0.0), (0.010101010091602802, 0.0, 0.0), (0.015151515603065491, 0.0, 0.0), (0.020202020183205605, 0.0, 0.0), (0.025252524763345718, 0.0, 0.0), (0.030303031206130981, 0.0, 0.0), (0.035353533923625946, 0.0, 0.0), (0.040404040366411209, 0.0, 0.0), (0.045454546809196472, 0.0, 0.0), (0.050505049526691437, 0.0, 0.0), (0.0555555559694767, 0.0, 0.0), (0.060606062412261963, 0.0, 0.0), (0.065656565129756927, 0.0, 0.0), (0.070707067847251892, 0.0, 0.0), (0.075757578015327454, 0.0, 0.0), (0.080808080732822418, 0.0, 0.0), (0.085858583450317383, 0.0, 0.0), (0.090909093618392944, 0.0, 0.0), (0.095959596335887909, 0.0, 0.0), (0.10101009905338287, 0.0, 0.0), (0.10606060922145844, 0.0, 0.0), (0.1111111119389534, 0.0, 0.0), (0.11616161465644836, 0.0, 0.0), (0.12121212482452393, 0.0, 0.0), (0.12626262009143829, 0.0, 0.0), (0.13131313025951385, 0.0, 0.0), (0.13636364042758942, 0.0, 0.0), (0.14141413569450378, 0.0, 0.0), (0.14646464586257935, 0.0, 0.0), (0.15151515603065491, 0.0, 0.0), (0.15656565129756927, 0.0, 0.0), (0.16161616146564484, 0.0, 0.0), (0.1666666716337204, 0.0, 0.0), (0.17171716690063477, 0.0, 0.0), (0.17676767706871033, 0.0, 0.0), (0.18181818723678589, 0.0, 0.0), (0.18686868250370026, 0.0, 0.0), (0.19191919267177582, 0.0, 0.0), (0.19696970283985138, 0.0, 0.0), (0.20202019810676575, 0.0, 0.0), (0.20707070827484131, 0.0, 0.0), (0.21212121844291687, 0.0, 0.0), (0.21717171370983124, 0.0, 0.0), (0.2222222238779068, 0.0, 0.0), (0.22727273404598236, 0.0, 0.0), (0.23232322931289673, 0.0, 0.0), (0.23737373948097229, 0.0, 0.0), (0.24242424964904785, 0.0, 0.0), (0.24747474491596222, 0.0, 0.0), (0.25252524018287659, 0.0, 0.0), (0.25757575035095215, 0.0, 0.0), (0.26262626051902771, 0.0, 0.0), (0.26767677068710327, 0.0, 0.0), (0.27272728085517883, 0.0, 0.0), (0.27777779102325439, 0.0, 0.0), (0.28282827138900757, 0.0, 0.0), (0.28787878155708313, 0.0, 0.0), (0.29292929172515869, 0.0, 0.0), (0.29797980189323425, 0.0, 0.0), (0.30303031206130981, 0.0, 0.0), (0.30808082222938538, 0.0, 0.0), (0.31313130259513855, 0.0, 0.0), (0.31818181276321411, 0.0039215688593685627, 0.0039215688593685627), (0.32323232293128967, 0.043137256056070328, 0.043137256056070328), (0.32828283309936523, 0.08235294371843338, 0.08235294371843338), (0.3333333432674408, 0.11764705926179886, 0.11764705926179886), (0.33838382363319397, 0.15686275064945221, 0.15686275064945221), (0.34343433380126953, 0.19607843458652496, 0.19607843458652496), (0.34848484396934509, 0.23137255012989044, 0.23137255012989044), (0.35353535413742065, 0.27058824896812439, 0.27058824896812439), (0.35858586430549622, 0.30980393290519714, 0.30980393290519714), (0.36363637447357178, 0.3490196168422699, 0.3490196168422699), (0.36868685483932495, 0.38431373238563538, 0.38431373238563538), (0.37373736500740051, 0.40392157435417175, 0.40392157435417175), (0.37878787517547607, 0.41568627953529358, 0.41568627953529358), (0.38383838534355164, 0.42352941632270813, 0.42352941632270813), (0.3888888955116272, 0.43137255311012268, 0.43137255311012268), (0.39393940567970276, 0.44313725829124451, 0.44313725829124451), (0.39898988604545593, 0.45098039507865906, 0.45098039507865906), (0.40404039621353149, 0.45882353186607361, 0.45882353186607361), (0.40909090638160706, 0.47058823704719543, 0.47058823704719543), (0.41414141654968262, 0.47843137383460999, 0.47843137383460999), (0.41919192671775818, 0.49019607901573181, 0.49019607901573181), (0.42424243688583374, 0.50196081399917603, 0.50196081399917603), (0.42929291725158691, 0.52549022436141968, 0.52549022436141968), (0.43434342741966248, 0.54901963472366333, 0.54901963472366333), (0.43939393758773804, 0.57254904508590698, 0.57254904508590698), (0.4444444477558136, 0.60000002384185791, 0.60000002384185791), (0.44949495792388916, 0.62352943420410156, 0.62352943420410156), (0.45454546809196472, 0.64705884456634521, 0.64705884456634521), (0.4595959484577179, 0.67058825492858887, 0.67058825492858887), (0.46464645862579346, 0.69411766529083252, 0.69411766529083252), (0.46969696879386902, 0.72156864404678345, 0.72156864404678345), (0.47474747896194458, 0.7450980544090271, 0.7450980544090271), (0.47979798913002014, 0.76862746477127075, 0.76862746477127075), (0.4848484992980957, 0.7921568751335144, 0.7921568751335144), (0.48989897966384888, 0.81568628549575806, 0.81568628549575806), (0.49494948983192444, 0.83921569585800171, 0.83921569585800171), (0.5, 0.86274510622024536, 0.86274510622024536), (0.50505048036575317, 0.88627451658248901, 0.88627451658248901), (0.51010102033615112, 0.90980392694473267, 0.90980392694473267), (0.5151515007019043, 0.93333333730697632, 0.93333333730697632), (0.52020204067230225, 0.95686274766921997, 0.95686274766921997), (0.52525252103805542, 0.98039215803146362, 0.98039215803146362), (0.53030300140380859, 1.0, 1.0), (0.53535354137420654, 1.0, 1.0), (0.54040402173995972, 1.0, 1.0), (0.54545456171035767, 1.0, 1.0), (0.55050504207611084, 1.0, 1.0), (0.55555558204650879, 1.0, 1.0), (0.56060606241226196, 1.0, 1.0), (0.56565654277801514, 1.0, 1.0), (0.57070708274841309, 1.0, 1.0), (0.57575756311416626, 1.0, 1.0), (0.58080810308456421, 1.0, 1.0), (0.58585858345031738, 1.0, 1.0), (0.59090906381607056, 1.0, 1.0), (0.59595960378646851, 1.0, 1.0), (0.60101008415222168, 1.0, 1.0), (0.60606062412261963, 1.0, 1.0), (0.6111111044883728, 1.0, 1.0), (0.61616164445877075, 1.0, 1.0), (0.62121212482452393, 1.0, 1.0), (0.6262626051902771, 1.0, 1.0), (0.63131314516067505, 1.0, 1.0), (0.63636362552642822, 1.0, 1.0), (0.64141416549682617, 1.0, 1.0), (0.64646464586257935, 1.0, 1.0), (0.65151512622833252, 1.0, 1.0), (0.65656566619873047, 1.0, 1.0), (0.66161614656448364, 1.0, 1.0), (0.66666668653488159, 1.0, 1.0), (0.67171716690063477, 1.0, 1.0), (0.67676764726638794, 1.0, 1.0), (0.68181818723678589, 1.0, 1.0), (0.68686866760253906, 1.0, 1.0), (0.69191920757293701, 1.0, 1.0), (0.69696968793869019, 1.0, 1.0), (0.70202022790908813, 1.0, 1.0), (0.70707070827484131, 1.0, 1.0), (0.71212118864059448, 1.0, 1.0), (0.71717172861099243, 1.0, 1.0), (0.72222220897674561, 1.0, 1.0), (0.72727274894714355, 1.0, 1.0), (0.73232322931289673, 1.0, 1.0), (0.7373737096786499, 1.0, 1.0), (0.74242424964904785, 1.0, 1.0), (0.74747473001480103, 1.0, 1.0), (0.75252526998519897, 1.0, 1.0), (0.75757575035095215, 1.0, 1.0), (0.7626262903213501, 1.0, 1.0), (0.76767677068710327, 1.0, 1.0), (0.77272725105285645, 1.0, 1.0), (0.77777779102325439, 1.0, 1.0), (0.78282827138900757, 1.0, 1.0), (0.78787881135940552, 1.0, 1.0), (0.79292929172515869, 1.0, 1.0), (0.79797977209091187, 0.96470588445663452, 0.96470588445663452), (0.80303031206130981, 0.92549020051956177, 0.92549020051956177), (0.80808079242706299, 0.89019608497619629, 0.89019608497619629), (0.81313133239746094, 0.85098040103912354, 0.85098040103912354), (0.81818181276321411, 0.81568628549575806, 0.81568628549575806), (0.82323235273361206, 0.7764706015586853, 0.7764706015586853), (0.82828283309936523, 0.74117648601531982, 0.74117648601531982), (0.83333331346511841, 0.70196080207824707, 0.70196080207824707), (0.83838385343551636, 0.66666668653488159, 0.66666668653488159), (0.84343433380126953, 0.62745100259780884, 0.62745100259780884), (0.84848487377166748, 0.61960786581039429, 0.61960786581039429), (0.85353535413742065, 0.65098041296005249, 0.65098041296005249), (0.85858583450317383, 0.68235296010971069, 0.68235296010971069), (0.86363637447357178, 0.7137255072593689, 0.7137255072593689), (0.86868685483932495, 0.7450980544090271, 0.7450980544090271), (0.8737373948097229, 0.77254903316497803, 0.77254903316497803), (0.87878787517547607, 0.80392158031463623, 0.80392158031463623), (0.88383835554122925, 0.83529412746429443, 0.83529412746429443), (0.8888888955116272, 0.86666667461395264, 0.86666667461395264), (0.89393937587738037, 0.89803922176361084, 0.89803922176361084), (0.89898991584777832, 0.92941176891326904, 0.92941176891326904), (0.90404039621353149, 0.93333333730697632, 0.93333333730697632), (0.90909093618392944, 0.93725490570068359, 0.93725490570068359), (0.91414141654968262, 0.93725490570068359, 0.93725490570068359), (0.91919189691543579, 0.94117647409439087, 0.94117647409439087), (0.92424243688583374, 0.94509804248809814, 0.94509804248809814), (0.92929291725158691, 0.94509804248809814, 0.94509804248809814), (0.93434345722198486, 0.94901961088180542, 0.94901961088180542), (0.93939393758773804, 0.9529411792755127, 0.9529411792755127), (0.94444441795349121, 0.9529411792755127, 0.9529411792755127), (0.94949495792388916, 0.95686274766921997, 0.95686274766921997), (0.95454543828964233, 0.96078431606292725, 0.96078431606292725), (0.95959597826004028, 0.96470588445663452, 0.96470588445663452), (0.96464645862579346, 0.9686274528503418, 0.9686274528503418), (0.96969699859619141, 0.97254902124404907, 0.97254902124404907), (0.97474747896194458, 0.97647058963775635, 0.97647058963775635), (0.97979795932769775, 0.98039215803146362, 0.98039215803146362), (0.9848484992980957, 0.9843137264251709, 0.9843137264251709), (0.98989897966384888, 0.98823529481887817, 0.98823529481887817), (0.99494951963424683, 0.99215686321258545, 0.99215686321258545), (1.0, 0.99607843160629272, 0.99607843160629272)]} _gist_rainbow_data = {'blue': [(0.0, 0.16470588743686676, 0.16470588743686676), (0.0042016808874905109, 0.14117647707462311, 0.14117647707462311), (0.0084033617749810219, 0.12156862765550613, 0.12156862765550613), (0.012605042196810246, 0.10196078568696976, 0.10196078568696976), (0.016806723549962044, 0.078431375324726105, 0.078431375324726105), (0.021008403971791267, 0.058823529630899429, 0.058823529630899429), (0.025210084393620491, 0.039215687662363052, 0.039215687662363052), (0.029411764815449715, 0.015686275437474251, 0.015686275437474251), (0.033613447099924088, 0.0, 0.0), (0.037815127521753311, 0.0, 0.0), (0.042016807943582535, 0.0, 0.0), (0.046218488365411758, 0.0, 0.0), (0.050420168787240982, 0.0, 0.0), (0.054621849209070206, 0.0, 0.0), (0.058823529630899429, 0.0, 0.0), (0.063025213778018951, 0.0, 0.0), (0.067226894199848175, 0.0, 0.0), (0.071428574621677399, 0.0, 0.0), (0.075630255043506622, 0.0, 0.0), (0.079831935465335846, 0.0, 0.0), (0.08403361588716507, 0.0, 0.0), (0.088235296308994293, 0.0, 0.0), (0.092436976730823517, 0.0, 0.0), (0.09663865715265274, 0.0, 0.0), (0.10084033757448196, 0.0, 0.0), (0.10504201799631119, 0.0, 0.0), (0.10924369841814041, 0.0, 0.0), (0.11344537883996964, 0.0, 0.0), (0.11764705926179886, 0.0, 0.0), (0.12184873968362808, 0.0, 0.0), (0.1260504275560379, 0.0, 0.0), (0.13025210797786713, 0.0, 0.0), (0.13445378839969635, 0.0, 0.0), (0.13865546882152557, 0.0, 0.0), (0.1428571492433548, 0.0, 0.0), (0.14705882966518402, 0.0, 0.0), (0.15126051008701324, 0.0, 0.0), (0.15546219050884247, 0.0, 0.0), (0.15966387093067169, 0.0, 0.0), (0.16386555135250092, 0.0, 0.0), (0.16806723177433014, 0.0, 0.0), (0.17226891219615936, 0.0, 0.0), (0.17647059261798859, 0.0, 0.0), (0.18067227303981781, 0.0, 0.0), (0.18487395346164703, 0.0, 0.0), (0.18907563388347626, 0.0, 0.0), (0.19327731430530548, 0.0, 0.0), (0.1974789947271347, 0.0, 0.0), (0.20168067514896393, 0.0, 0.0), (0.20588235557079315, 0.0, 0.0), (0.21008403599262238, 0.0, 0.0), (0.2142857164144516, 0.0, 0.0), (0.21848739683628082, 0.0, 0.0), (0.22268907725811005, 0.0, 0.0), (0.22689075767993927, 0.0, 0.0), (0.23109243810176849, 0.0, 0.0), (0.23529411852359772, 0.0, 0.0), (0.23949579894542694, 0.0, 0.0), (0.24369747936725616, 0.0, 0.0), (0.24789915978908539, 0.0, 0.0), (0.25210085511207581, 0.0, 0.0), (0.25630253553390503, 0.0, 0.0), (0.26050421595573425, 0.0, 0.0), (0.26470589637756348, 0.0, 0.0), (0.2689075767993927, 0.0, 0.0), (0.27310925722122192, 0.0, 0.0), (0.27731093764305115, 0.0, 0.0), (0.28151261806488037, 0.0, 0.0), (0.28571429848670959, 0.0, 0.0), (0.28991597890853882, 0.0, 0.0), (0.29411765933036804, 0.0, 0.0), (0.29831933975219727, 0.0, 0.0), (0.30252102017402649, 0.0, 0.0), (0.30672270059585571, 0.0, 0.0), (0.31092438101768494, 0.0, 0.0), (0.31512606143951416, 0.0, 0.0), (0.31932774186134338, 0.0, 0.0), (0.32352942228317261, 0.0, 0.0), (0.32773110270500183, 0.0, 0.0), (0.33193278312683105, 0.0, 0.0), (0.33613446354866028, 0.0, 0.0), (0.3403361439704895, 0.0, 0.0), (0.34453782439231873, 0.0, 0.0), (0.34873950481414795, 0.0, 0.0), (0.35294118523597717, 0.0, 0.0), (0.3571428656578064, 0.0, 0.0), (0.36134454607963562, 0.0, 0.0), (0.36554622650146484, 0.0, 0.0), (0.36974790692329407, 0.0, 0.0), (0.37394958734512329, 0.0, 0.0), (0.37815126776695251, 0.0, 0.0), (0.38235294818878174, 0.0, 0.0), (0.38655462861061096, 0.0, 0.0), (0.39075630903244019, 0.0, 0.0), (0.39495798945426941, 0.0, 0.0), (0.39915966987609863, 0.0, 0.0), (0.40336135029792786, 0.0, 0.0), (0.40756303071975708, 0.0039215688593685627, 0.0039215688593685627), (0.4117647111415863, 0.047058824449777603, 0.047058824449777603), (0.41596639156341553, 0.066666670143604279, 0.066666670143604279), (0.42016807198524475, 0.090196080505847931, 0.090196080505847931), (0.42436975240707397, 0.10980392247438431, 0.10980392247438431), (0.4285714328289032, 0.12941177189350128, 0.12941177189350128), (0.43277311325073242, 0.15294118225574493, 0.15294118225574493), (0.43697479367256165, 0.17254902422428131, 0.17254902422428131), (0.44117647409439087, 0.19215686619281769, 0.19215686619281769), (0.44537815451622009, 0.21568627655506134, 0.21568627655506134), (0.44957983493804932, 0.23529411852359772, 0.23529411852359772), (0.45378151535987854, 0.25882354378700256, 0.25882354378700256), (0.45798319578170776, 0.27843138575553894, 0.27843138575553894), (0.46218487620353699, 0.29803922772407532, 0.29803922772407532), (0.46638655662536621, 0.32156863808631897, 0.32156863808631897), (0.47058823704719543, 0.34117648005485535, 0.34117648005485535), (0.47478991746902466, 0.38431373238563538, 0.38431373238563538), (0.47899159789085388, 0.40392157435417175, 0.40392157435417175), (0.48319327831268311, 0.42745098471641541, 0.42745098471641541), (0.48739495873451233, 0.44705882668495178, 0.44705882668495178), (0.49159663915634155, 0.46666666865348816, 0.46666666865348816), (0.49579831957817078, 0.49019607901573181, 0.49019607901573181), (0.5, 0.50980395078659058, 0.50980395078659058), (0.50420171022415161, 0.52941179275512695, 0.52941179275512695), (0.50840336084365845, 0.55294120311737061, 0.55294120311737061), (0.51260507106781006, 0.57254904508590698, 0.57254904508590698), (0.51680672168731689, 0.59607845544815063, 0.59607845544815063), (0.52100843191146851, 0.61568629741668701, 0.61568629741668701), (0.52521008253097534, 0.63529413938522339, 0.63529413938522339), (0.52941179275512695, 0.65882354974746704, 0.65882354974746704), (0.53361344337463379, 0.67843139171600342, 0.67843139171600342), (0.5378151535987854, 0.72156864404678345, 0.72156864404678345), (0.54201680421829224, 0.74117648601531982, 0.74117648601531982), (0.54621851444244385, 0.76470589637756348, 0.76470589637756348), (0.55042016506195068, 0.78431373834609985, 0.78431373834609985), (0.55462187528610229, 0.80392158031463623, 0.80392158031463623), (0.55882352590560913, 0.82745099067687988, 0.82745099067687988), (0.56302523612976074, 0.84705883264541626, 0.84705883264541626), (0.56722688674926758, 0.87058824300765991, 0.87058824300765991), (0.57142859697341919, 0.89019608497619629, 0.89019608497619629), (0.57563024759292603, 0.90980392694473267, 0.90980392694473267), (0.57983195781707764, 0.93333333730697632, 0.93333333730697632), (0.58403360843658447, 0.9529411792755127, 0.9529411792755127), (0.58823531866073608, 0.97254902124404907, 0.97254902124404907), (0.59243696928024292, 0.99607843160629272, 0.99607843160629272), (0.59663867950439453, 1.0, 1.0), (0.60084033012390137, 1.0, 1.0), (0.60504204034805298, 1.0, 1.0), (0.60924369096755981, 1.0, 1.0), (0.61344540119171143, 1.0, 1.0), (0.61764705181121826, 1.0, 1.0), (0.62184876203536987, 1.0, 1.0), (0.62605041265487671, 1.0, 1.0), (0.63025212287902832, 1.0, 1.0), (0.63445377349853516, 1.0, 1.0), (0.63865548372268677, 1.0, 1.0), (0.6428571343421936, 1.0, 1.0), (0.64705884456634521, 1.0, 1.0), (0.65126049518585205, 1.0, 1.0), (0.65546220541000366, 1.0, 1.0), (0.6596638560295105, 1.0, 1.0), (0.66386556625366211, 1.0, 1.0), (0.66806721687316895, 1.0, 1.0), (0.67226892709732056, 1.0, 1.0), (0.67647057771682739, 1.0, 1.0), (0.680672287940979, 1.0, 1.0), (0.68487393856048584, 1.0, 1.0), (0.68907564878463745, 1.0, 1.0), (0.69327729940414429, 1.0, 1.0), (0.6974790096282959, 1.0, 1.0), (0.70168066024780273, 1.0, 1.0), (0.70588237047195435, 1.0, 1.0), (0.71008402109146118, 1.0, 1.0), (0.71428573131561279, 1.0, 1.0), (0.71848738193511963, 1.0, 1.0), (0.72268909215927124, 1.0, 1.0), (0.72689074277877808, 1.0, 1.0), (0.73109245300292969, 1.0, 1.0), (0.73529410362243652, 1.0, 1.0), (0.73949581384658813, 1.0, 1.0), (0.74369746446609497, 1.0, 1.0), (0.74789917469024658, 1.0, 1.0), (0.75210082530975342, 1.0, 1.0), (0.75630253553390503, 1.0, 1.0), (0.76050418615341187, 1.0, 1.0), (0.76470589637756348, 1.0, 1.0), (0.76890754699707031, 1.0, 1.0), (0.77310925722122192, 1.0, 1.0), (0.77731090784072876, 1.0, 1.0), (0.78151261806488037, 1.0, 1.0), (0.78571426868438721, 1.0, 1.0), (0.78991597890853882, 1.0, 1.0), (0.79411762952804565, 1.0, 1.0), (0.79831933975219727, 1.0, 1.0), (0.8025209903717041, 1.0, 1.0), (0.80672270059585571, 1.0, 1.0), (0.81092435121536255, 1.0, 1.0), (0.81512606143951416, 1.0, 1.0), (0.819327712059021, 1.0, 1.0), (0.82352942228317261, 1.0, 1.0), (0.82773107290267944, 1.0, 1.0), (0.83193278312683105, 1.0, 1.0), (0.83613443374633789, 1.0, 1.0), (0.8403361439704895, 1.0, 1.0), (0.84453779458999634, 1.0, 1.0), (0.84873950481414795, 1.0, 1.0), (0.85294115543365479, 1.0, 1.0), (0.8571428656578064, 1.0, 1.0), (0.86134451627731323, 1.0, 1.0), (0.86554622650146484, 1.0, 1.0), (0.86974787712097168, 1.0, 1.0), (0.87394958734512329, 1.0, 1.0), (0.87815123796463013, 1.0, 1.0), (0.88235294818878174, 1.0, 1.0), (0.88655459880828857, 1.0, 1.0), (0.89075630903244019, 1.0, 1.0), (0.89495795965194702, 1.0, 1.0), (0.89915966987609863, 1.0, 1.0), (0.90336132049560547, 1.0, 1.0), (0.90756303071975708, 1.0, 1.0), (0.91176468133926392, 1.0, 1.0), (0.91596639156341553, 1.0, 1.0), (0.92016804218292236, 1.0, 1.0), (0.92436975240707397, 1.0, 1.0), (0.92857140302658081, 1.0, 1.0), (0.93277311325073242, 1.0, 1.0), (0.93697476387023926, 1.0, 1.0), (0.94117647409439087, 1.0, 1.0), (0.94537812471389771, 1.0, 1.0), (0.94957983493804932, 1.0, 1.0), (0.95378148555755615, 1.0, 1.0), (0.95798319578170776, 1.0, 1.0), (0.9621848464012146, 1.0, 1.0), (0.96638655662536621, 0.99607843160629272, 0.99607843160629272), (0.97058820724487305, 0.97647058963775635, 0.97647058963775635), (0.97478991746902466, 0.9529411792755127, 0.9529411792755127), (0.97899156808853149, 0.91372549533843994, 0.91372549533843994), (0.98319327831268311, 0.89019608497619629, 0.89019608497619629), (0.98739492893218994, 0.87058824300765991, 0.87058824300765991), (0.99159663915634155, 0.85098040103912354, 0.85098040103912354), (0.99579828977584839, 0.82745099067687988, 0.82745099067687988), (1.0, 0.80784314870834351, 0.80784314870834351)], 'green': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0, 0.0), (0.0084033617749810219, 0.0, 0.0), (0.012605042196810246, 0.0, 0.0), (0.016806723549962044, 0.0, 0.0), (0.021008403971791267, 0.0, 0.0), (0.025210084393620491, 0.0, 0.0), (0.029411764815449715, 0.0, 0.0), (0.033613447099924088, 0.019607843831181526, 0.019607843831181526), (0.037815127521753311, 0.043137256056070328, 0.043137256056070328), (0.042016807943582535, 0.062745101749897003, 0.062745101749897003), (0.046218488365411758, 0.086274512112140656, 0.086274512112140656), (0.050420168787240982, 0.10588235408067703, 0.10588235408067703), (0.054621849209070206, 0.12549020349979401, 0.12549020349979401), (0.058823529630899429, 0.14901961386203766, 0.14901961386203766), (0.063025213778018951, 0.16862745583057404, 0.16862745583057404), (0.067226894199848175, 0.18823529779911041, 0.18823529779911041), (0.071428574621677399, 0.21176470816135406, 0.21176470816135406), (0.075630255043506622, 0.23137255012989044, 0.23137255012989044), (0.079831935465335846, 0.25490197539329529, 0.25490197539329529), (0.08403361588716507, 0.27450981736183167, 0.27450981736183167), (0.088235296308994293, 0.29411765933036804, 0.29411765933036804), (0.092436976730823517, 0.31764706969261169, 0.31764706969261169), (0.09663865715265274, 0.35686275362968445, 0.35686275362968445), (0.10084033757448196, 0.3803921639919281, 0.3803921639919281), (0.10504201799631119, 0.40000000596046448, 0.40000000596046448), (0.10924369841814041, 0.42352941632270813, 0.42352941632270813), (0.11344537883996964, 0.44313725829124451, 0.44313725829124451), (0.11764705926179886, 0.46274510025978088, 0.46274510025978088), (0.12184873968362808, 0.48627451062202454, 0.48627451062202454), (0.1260504275560379, 0.5058823823928833, 0.5058823823928833), (0.13025210797786713, 0.52941179275512695, 0.52941179275512695), (0.13445378839969635, 0.54901963472366333, 0.54901963472366333), (0.13865546882152557, 0.56862747669219971, 0.56862747669219971), (0.1428571492433548, 0.59215688705444336, 0.59215688705444336), (0.14705882966518402, 0.61176472902297974, 0.61176472902297974), (0.15126051008701324, 0.63137257099151611, 0.63137257099151611), (0.15546219050884247, 0.65490198135375977, 0.65490198135375977), (0.15966387093067169, 0.69803923368453979, 0.69803923368453979), (0.16386555135250092, 0.71764707565307617, 0.71764707565307617), (0.16806723177433014, 0.73725491762161255, 0.73725491762161255), (0.17226891219615936, 0.7607843279838562, 0.7607843279838562), (0.17647059261798859, 0.78039216995239258, 0.78039216995239258), (0.18067227303981781, 0.80000001192092896, 0.80000001192092896), (0.18487395346164703, 0.82352942228317261, 0.82352942228317261), (0.18907563388347626, 0.84313726425170898, 0.84313726425170898), (0.19327731430530548, 0.86666667461395264, 0.86666667461395264), (0.1974789947271347, 0.88627451658248901, 0.88627451658248901), (0.20168067514896393, 0.90588235855102539, 0.90588235855102539), (0.20588235557079315, 0.92941176891326904, 0.92941176891326904), (0.21008403599262238, 0.94901961088180542, 0.94901961088180542), (0.2142857164144516, 0.9686274528503418, 0.9686274528503418), (0.21848739683628082, 0.99215686321258545, 0.99215686321258545), (0.22268907725811005, 1.0, 1.0), (0.22689075767993927, 1.0, 1.0), (0.23109243810176849, 1.0, 1.0), (0.23529411852359772, 1.0, 1.0), (0.23949579894542694, 1.0, 1.0), (0.24369747936725616, 1.0, 1.0), (0.24789915978908539, 1.0, 1.0), (0.25210085511207581, 1.0, 1.0), (0.25630253553390503, 1.0, 1.0), (0.26050421595573425, 1.0, 1.0), (0.26470589637756348, 1.0, 1.0), (0.2689075767993927, 1.0, 1.0), (0.27310925722122192, 1.0, 1.0), (0.27731093764305115, 1.0, 1.0), (0.28151261806488037, 1.0, 1.0), (0.28571429848670959, 1.0, 1.0), (0.28991597890853882, 1.0, 1.0), (0.29411765933036804, 1.0, 1.0), (0.29831933975219727, 1.0, 1.0), (0.30252102017402649, 1.0, 1.0), (0.30672270059585571, 1.0, 1.0), (0.31092438101768494, 1.0, 1.0), (0.31512606143951416, 1.0, 1.0), (0.31932774186134338, 1.0, 1.0), (0.32352942228317261, 1.0, 1.0), (0.32773110270500183, 1.0, 1.0), (0.33193278312683105, 1.0, 1.0), (0.33613446354866028, 1.0, 1.0), (0.3403361439704895, 1.0, 1.0), (0.34453782439231873, 1.0, 1.0), (0.34873950481414795, 1.0, 1.0), (0.35294118523597717, 1.0, 1.0), (0.3571428656578064, 1.0, 1.0), (0.36134454607963562, 1.0, 1.0), (0.36554622650146484, 1.0, 1.0), (0.36974790692329407, 1.0, 1.0), (0.37394958734512329, 1.0, 1.0), (0.37815126776695251, 1.0, 1.0), (0.38235294818878174, 1.0, 1.0), (0.38655462861061096, 1.0, 1.0), (0.39075630903244019, 1.0, 1.0), (0.39495798945426941, 1.0, 1.0), (0.39915966987609863, 1.0, 1.0), (0.40336135029792786, 1.0, 1.0), (0.40756303071975708, 1.0, 1.0), (0.4117647111415863, 1.0, 1.0), (0.41596639156341553, 1.0, 1.0), (0.42016807198524475, 1.0, 1.0), (0.42436975240707397, 1.0, 1.0), (0.4285714328289032, 1.0, 1.0), (0.43277311325073242, 1.0, 1.0), (0.43697479367256165, 1.0, 1.0), (0.44117647409439087, 1.0, 1.0), (0.44537815451622009, 1.0, 1.0), (0.44957983493804932, 1.0, 1.0), (0.45378151535987854, 1.0, 1.0), (0.45798319578170776, 1.0, 1.0), (0.46218487620353699, 1.0, 1.0), (0.46638655662536621, 1.0, 1.0), (0.47058823704719543, 1.0, 1.0), (0.47478991746902466, 1.0, 1.0), (0.47899159789085388, 1.0, 1.0), (0.48319327831268311, 1.0, 1.0), (0.48739495873451233, 1.0, 1.0), (0.49159663915634155, 1.0, 1.0), (0.49579831957817078, 1.0, 1.0), (0.5, 1.0, 1.0), (0.50420171022415161, 1.0, 1.0), (0.50840336084365845, 1.0, 1.0), (0.51260507106781006, 1.0, 1.0), (0.51680672168731689, 1.0, 1.0), (0.52100843191146851, 1.0, 1.0), (0.52521008253097534, 1.0, 1.0), (0.52941179275512695, 1.0, 1.0), (0.53361344337463379, 1.0, 1.0), (0.5378151535987854, 1.0, 1.0), (0.54201680421829224, 1.0, 1.0), (0.54621851444244385, 1.0, 1.0), (0.55042016506195068, 1.0, 1.0), (0.55462187528610229, 1.0, 1.0), (0.55882352590560913, 1.0, 1.0), (0.56302523612976074, 1.0, 1.0), (0.56722688674926758, 1.0, 1.0), (0.57142859697341919, 1.0, 1.0), (0.57563024759292603, 1.0, 1.0), (0.57983195781707764, 1.0, 1.0), (0.58403360843658447, 1.0, 1.0), (0.58823531866073608, 1.0, 1.0), (0.59243696928024292, 1.0, 1.0), (0.59663867950439453, 0.98039215803146362, 0.98039215803146362), (0.60084033012390137, 0.93725490570068359, 0.93725490570068359), (0.60504204034805298, 0.91764706373214722, 0.91764706373214722), (0.60924369096755981, 0.89411765336990356, 0.89411765336990356), (0.61344540119171143, 0.87450981140136719, 0.87450981140136719), (0.61764705181121826, 0.85490196943283081, 0.85490196943283081), (0.62184876203536987, 0.83137255907058716, 0.83137255907058716), (0.62605041265487671, 0.81176471710205078, 0.81176471710205078), (0.63025212287902832, 0.78823530673980713, 0.78823530673980713), (0.63445377349853516, 0.76862746477127075, 0.76862746477127075), (0.63865548372268677, 0.74901962280273438, 0.74901962280273438), (0.6428571343421936, 0.72549021244049072, 0.72549021244049072), (0.64705884456634521, 0.70588237047195435, 0.70588237047195435), (0.65126049518585205, 0.68235296010971069, 0.68235296010971069), (0.65546220541000366, 0.66274511814117432, 0.66274511814117432), (0.6596638560295105, 0.64313727617263794, 0.64313727617263794), (0.66386556625366211, 0.60000002384185791, 0.60000002384185791), (0.66806721687316895, 0.58039218187332153, 0.58039218187332153), (0.67226892709732056, 0.55686277151107788, 0.55686277151107788), (0.67647057771682739, 0.5372549295425415, 0.5372549295425415), (0.680672287940979, 0.51372551918029785, 0.51372551918029785), (0.68487393856048584, 0.49411764740943909, 0.49411764740943909), (0.68907564878463745, 0.47450980544090271, 0.47450980544090271), (0.69327729940414429, 0.45098039507865906, 0.45098039507865906), (0.6974790096282959, 0.43137255311012268, 0.43137255311012268), (0.70168066024780273, 0.4117647111415863, 0.4117647111415863), (0.70588237047195435, 0.38823530077934265, 0.38823530077934265), (0.71008402109146118, 0.36862745881080627, 0.36862745881080627), (0.71428573131561279, 0.34509804844856262, 0.34509804844856262), (0.71848738193511963, 0.32549020648002625, 0.32549020648002625), (0.72268909215927124, 0.30588236451148987, 0.30588236451148987), (0.72689074277877808, 0.26274511218070984, 0.26274511218070984), (0.73109245300292969, 0.24313725531101227, 0.24313725531101227), (0.73529410362243652, 0.21960784494876862, 0.21960784494876862), (0.73949581384658813, 0.20000000298023224, 0.20000000298023224), (0.74369746446609497, 0.17647059261798859, 0.17647059261798859), (0.74789917469024658, 0.15686275064945221, 0.15686275064945221), (0.75210082530975342, 0.13725490868091583, 0.13725490868091583), (0.75630253553390503, 0.11372549086809158, 0.11372549086809158), (0.76050418615341187, 0.094117648899555206, 0.094117648899555206), (0.76470589637756348, 0.070588238537311554, 0.070588238537311554), (0.76890754699707031, 0.050980392843484879, 0.050980392843484879), (0.77310925722122192, 0.031372550874948502, 0.031372550874948502), (0.77731090784072876, 0.0078431377187371254, 0.0078431377187371254), (0.78151261806488037, 0.0, 0.0), (0.78571426868438721, 0.0, 0.0), (0.78991597890853882, 0.0, 0.0), (0.79411762952804565, 0.0, 0.0), (0.79831933975219727, 0.0, 0.0), (0.8025209903717041, 0.0, 0.0), (0.80672270059585571, 0.0, 0.0), (0.81092435121536255, 0.0, 0.0), (0.81512606143951416, 0.0, 0.0), (0.819327712059021, 0.0, 0.0), (0.82352942228317261, 0.0, 0.0), (0.82773107290267944, 0.0, 0.0), (0.83193278312683105, 0.0, 0.0), (0.83613443374633789, 0.0, 0.0), (0.8403361439704895, 0.0, 0.0), (0.84453779458999634, 0.0, 0.0), (0.84873950481414795, 0.0, 0.0), (0.85294115543365479, 0.0, 0.0), (0.8571428656578064, 0.0, 0.0), (0.86134451627731323, 0.0, 0.0), (0.86554622650146484, 0.0, 0.0), (0.86974787712097168, 0.0, 0.0), (0.87394958734512329, 0.0, 0.0), (0.87815123796463013, 0.0, 0.0), (0.88235294818878174, 0.0, 0.0), (0.88655459880828857, 0.0, 0.0), (0.89075630903244019, 0.0, 0.0), (0.89495795965194702, 0.0, 0.0), (0.89915966987609863, 0.0, 0.0), (0.90336132049560547, 0.0, 0.0), (0.90756303071975708, 0.0, 0.0), (0.91176468133926392, 0.0, 0.0), (0.91596639156341553, 0.0, 0.0), (0.92016804218292236, 0.0, 0.0), (0.92436975240707397, 0.0, 0.0), (0.92857140302658081, 0.0, 0.0), (0.93277311325073242, 0.0, 0.0), (0.93697476387023926, 0.0, 0.0), (0.94117647409439087, 0.0, 0.0), (0.94537812471389771, 0.0, 0.0), (0.94957983493804932, 0.0, 0.0), (0.95378148555755615, 0.0, 0.0), (0.95798319578170776, 0.0, 0.0), (0.9621848464012146, 0.0, 0.0), (0.96638655662536621, 0.0, 0.0), (0.97058820724487305, 0.0, 0.0), (0.97478991746902466, 0.0, 0.0), (0.97899156808853149, 0.0, 0.0), (0.98319327831268311, 0.0, 0.0), (0.98739492893218994, 0.0, 0.0), (0.99159663915634155, 0.0, 0.0), (0.99579828977584839, 0.0, 0.0), (1.0, 0.0, 0.0)], 'red': [(0.0, 1.0, 1.0), (0.0042016808874905109, 1.0, 1.0), (0.0084033617749810219, 1.0, 1.0), (0.012605042196810246, 1.0, 1.0), (0.016806723549962044, 1.0, 1.0), (0.021008403971791267, 1.0, 1.0), (0.025210084393620491, 1.0, 1.0), (0.029411764815449715, 1.0, 1.0), (0.033613447099924088, 1.0, 1.0), (0.037815127521753311, 1.0, 1.0), (0.042016807943582535, 1.0, 1.0), (0.046218488365411758, 1.0, 1.0), (0.050420168787240982, 1.0, 1.0), (0.054621849209070206, 1.0, 1.0), (0.058823529630899429, 1.0, 1.0), (0.063025213778018951, 1.0, 1.0), (0.067226894199848175, 1.0, 1.0), (0.071428574621677399, 1.0, 1.0), (0.075630255043506622, 1.0, 1.0), (0.079831935465335846, 1.0, 1.0), (0.08403361588716507, 1.0, 1.0), (0.088235296308994293, 1.0, 1.0), (0.092436976730823517, 1.0, 1.0), (0.09663865715265274, 1.0, 1.0), (0.10084033757448196, 1.0, 1.0), (0.10504201799631119, 1.0, 1.0), (0.10924369841814041, 1.0, 1.0), (0.11344537883996964, 1.0, 1.0), (0.11764705926179886, 1.0, 1.0), (0.12184873968362808, 1.0, 1.0), (0.1260504275560379, 1.0, 1.0), (0.13025210797786713, 1.0, 1.0), (0.13445378839969635, 1.0, 1.0), (0.13865546882152557, 1.0, 1.0), (0.1428571492433548, 1.0, 1.0), (0.14705882966518402, 1.0, 1.0), (0.15126051008701324, 1.0, 1.0), (0.15546219050884247, 1.0, 1.0), (0.15966387093067169, 1.0, 1.0), (0.16386555135250092, 1.0, 1.0), (0.16806723177433014, 1.0, 1.0), (0.17226891219615936, 1.0, 1.0), (0.17647059261798859, 1.0, 1.0), (0.18067227303981781, 1.0, 1.0), (0.18487395346164703, 1.0, 1.0), (0.18907563388347626, 1.0, 1.0), (0.19327731430530548, 1.0, 1.0), (0.1974789947271347, 1.0, 1.0), (0.20168067514896393, 1.0, 1.0), (0.20588235557079315, 1.0, 1.0), (0.21008403599262238, 1.0, 1.0), (0.2142857164144516, 1.0, 1.0), (0.21848739683628082, 1.0, 1.0), (0.22268907725811005, 0.96078431606292725, 0.96078431606292725), (0.22689075767993927, 0.94117647409439087, 0.94117647409439087), (0.23109243810176849, 0.92156863212585449, 0.92156863212585449), (0.23529411852359772, 0.89803922176361084, 0.89803922176361084), (0.23949579894542694, 0.87843137979507446, 0.87843137979507446), (0.24369747936725616, 0.85882353782653809, 0.85882353782653809), (0.24789915978908539, 0.83529412746429443, 0.83529412746429443), (0.25210085511207581, 0.81568628549575806, 0.81568628549575806), (0.25630253553390503, 0.7921568751335144, 0.7921568751335144), (0.26050421595573425, 0.77254903316497803, 0.77254903316497803), (0.26470589637756348, 0.75294119119644165, 0.75294119119644165), (0.2689075767993927, 0.729411780834198, 0.729411780834198), (0.27310925722122192, 0.70980393886566162, 0.70980393886566162), (0.27731093764305115, 0.68627452850341797, 0.68627452850341797), (0.28151261806488037, 0.66666668653488159, 0.66666668653488159), (0.28571429848670959, 0.62352943420410156, 0.62352943420410156), (0.28991597890853882, 0.60392159223556519, 0.60392159223556519), (0.29411765933036804, 0.58431375026702881, 0.58431375026702881), (0.29831933975219727, 0.56078433990478516, 0.56078433990478516), (0.30252102017402649, 0.54117649793624878, 0.54117649793624878), (0.30672270059585571, 0.51764708757400513, 0.51764708757400513), (0.31092438101768494, 0.49803921580314636, 0.49803921580314636), (0.31512606143951416, 0.47843137383460999, 0.47843137383460999), (0.31932774186134338, 0.45490196347236633, 0.45490196347236633), (0.32352942228317261, 0.43529412150382996, 0.43529412150382996), (0.32773110270500183, 0.41568627953529358, 0.41568627953529358), (0.33193278312683105, 0.39215686917304993, 0.39215686917304993), (0.33613446354866028, 0.37254902720451355, 0.37254902720451355), (0.3403361439704895, 0.3490196168422699, 0.3490196168422699), (0.34453782439231873, 0.32941177487373352, 0.32941177487373352), (0.34873950481414795, 0.28627452254295349, 0.28627452254295349), (0.35294118523597717, 0.26666668057441711, 0.26666668057441711), (0.3571428656578064, 0.24705882370471954, 0.24705882370471954), (0.36134454607963562, 0.22352941334247589, 0.22352941334247589), (0.36554622650146484, 0.20392157137393951, 0.20392157137393951), (0.36974790692329407, 0.18039216101169586, 0.18039216101169586), (0.37394958734512329, 0.16078431904315948, 0.16078431904315948), (0.37815126776695251, 0.14117647707462311, 0.14117647707462311), (0.38235294818878174, 0.11764705926179886, 0.11764705926179886), (0.38655462861061096, 0.098039217293262482, 0.098039217293262482), (0.39075630903244019, 0.074509806931018829, 0.074509806931018829), (0.39495798945426941, 0.054901961237192154, 0.054901961237192154), (0.39915966987609863, 0.035294119268655777, 0.035294119268655777), (0.40336135029792786, 0.011764706112444401, 0.011764706112444401), (0.40756303071975708, 0.0, 0.0), (0.4117647111415863, 0.0, 0.0), (0.41596639156341553, 0.0, 0.0), (0.42016807198524475, 0.0, 0.0), (0.42436975240707397, 0.0, 0.0), (0.4285714328289032, 0.0, 0.0), (0.43277311325073242, 0.0, 0.0), (0.43697479367256165, 0.0, 0.0), (0.44117647409439087, 0.0, 0.0), (0.44537815451622009, 0.0, 0.0), (0.44957983493804932, 0.0, 0.0), (0.45378151535987854, 0.0, 0.0), (0.45798319578170776, 0.0, 0.0), (0.46218487620353699, 0.0, 0.0), (0.46638655662536621, 0.0, 0.0), (0.47058823704719543, 0.0, 0.0), (0.47478991746902466, 0.0, 0.0), (0.47899159789085388, 0.0, 0.0), (0.48319327831268311, 0.0, 0.0), (0.48739495873451233, 0.0, 0.0), (0.49159663915634155, 0.0, 0.0), (0.49579831957817078, 0.0, 0.0), (0.5, 0.0, 0.0), (0.50420171022415161, 0.0, 0.0), (0.50840336084365845, 0.0, 0.0), (0.51260507106781006, 0.0, 0.0), (0.51680672168731689, 0.0, 0.0), (0.52100843191146851, 0.0, 0.0), (0.52521008253097534, 0.0, 0.0), (0.52941179275512695, 0.0, 0.0), (0.53361344337463379, 0.0, 0.0), (0.5378151535987854, 0.0, 0.0), (0.54201680421829224, 0.0, 0.0), (0.54621851444244385, 0.0, 0.0), (0.55042016506195068, 0.0, 0.0), (0.55462187528610229, 0.0, 0.0), (0.55882352590560913, 0.0, 0.0), (0.56302523612976074, 0.0, 0.0), (0.56722688674926758, 0.0, 0.0), (0.57142859697341919, 0.0, 0.0), (0.57563024759292603, 0.0, 0.0), (0.57983195781707764, 0.0, 0.0), (0.58403360843658447, 0.0, 0.0), (0.58823531866073608, 0.0, 0.0), (0.59243696928024292, 0.0, 0.0), (0.59663867950439453, 0.0, 0.0), (0.60084033012390137, 0.0, 0.0), (0.60504204034805298, 0.0, 0.0), (0.60924369096755981, 0.0, 0.0), (0.61344540119171143, 0.0, 0.0), (0.61764705181121826, 0.0, 0.0), (0.62184876203536987, 0.0, 0.0), (0.62605041265487671, 0.0, 0.0), (0.63025212287902832, 0.0, 0.0), (0.63445377349853516, 0.0, 0.0), (0.63865548372268677, 0.0, 0.0), (0.6428571343421936, 0.0, 0.0), (0.64705884456634521, 0.0, 0.0), (0.65126049518585205, 0.0, 0.0), (0.65546220541000366, 0.0, 0.0), (0.6596638560295105, 0.0, 0.0), (0.66386556625366211, 0.0, 0.0), (0.66806721687316895, 0.0, 0.0), (0.67226892709732056, 0.0, 0.0), (0.67647057771682739, 0.0, 0.0), (0.680672287940979, 0.0, 0.0), (0.68487393856048584, 0.0, 0.0), (0.68907564878463745, 0.0, 0.0), (0.69327729940414429, 0.0, 0.0), (0.6974790096282959, 0.0, 0.0), (0.70168066024780273, 0.0, 0.0), (0.70588237047195435, 0.0, 0.0), (0.71008402109146118, 0.0, 0.0), (0.71428573131561279, 0.0, 0.0), (0.71848738193511963, 0.0, 0.0), (0.72268909215927124, 0.0, 0.0), (0.72689074277877808, 0.0, 0.0), (0.73109245300292969, 0.0, 0.0), (0.73529410362243652, 0.0, 0.0), (0.73949581384658813, 0.0, 0.0), (0.74369746446609497, 0.0, 0.0), (0.74789917469024658, 0.0, 0.0), (0.75210082530975342, 0.0, 0.0), (0.75630253553390503, 0.0, 0.0), (0.76050418615341187, 0.0, 0.0), (0.76470589637756348, 0.0, 0.0), (0.76890754699707031, 0.0, 0.0), (0.77310925722122192, 0.0, 0.0), (0.77731090784072876, 0.0, 0.0), (0.78151261806488037, 0.0078431377187371254, 0.0078431377187371254), (0.78571426868438721, 0.027450980618596077, 0.027450980618596077), (0.78991597890853882, 0.070588238537311554, 0.070588238537311554), (0.79411762952804565, 0.094117648899555206, 0.094117648899555206), (0.79831933975219727, 0.11372549086809158, 0.11372549086809158), (0.8025209903717041, 0.13333334028720856, 0.13333334028720856), (0.80672270059585571, 0.15686275064945221, 0.15686275064945221), (0.81092435121536255, 0.17647059261798859, 0.17647059261798859), (0.81512606143951416, 0.19607843458652496, 0.19607843458652496), (0.819327712059021, 0.21960784494876862, 0.21960784494876862), (0.82352942228317261, 0.23921568691730499, 0.23921568691730499), (0.82773107290267944, 0.26274511218070984, 0.26274511218070984), (0.83193278312683105, 0.28235295414924622, 0.28235295414924622), (0.83613443374633789, 0.30196079611778259, 0.30196079611778259), (0.8403361439704895, 0.32549020648002625, 0.32549020648002625), (0.84453779458999634, 0.34509804844856262, 0.34509804844856262), (0.84873950481414795, 0.364705890417099, 0.364705890417099), (0.85294115543365479, 0.40784314274787903, 0.40784314274787903), (0.8571428656578064, 0.43137255311012268, 0.43137255311012268), (0.86134451627731323, 0.45098039507865906, 0.45098039507865906), (0.86554622650146484, 0.47058823704719543, 0.47058823704719543), (0.86974787712097168, 0.49411764740943909, 0.49411764740943909), (0.87394958734512329, 0.51372551918029785, 0.51372551918029785), (0.87815123796463013, 0.53333336114883423, 0.53333336114883423), (0.88235294818878174, 0.55686277151107788, 0.55686277151107788), (0.88655459880828857, 0.57647061347961426, 0.57647061347961426), (0.89075630903244019, 0.60000002384185791, 0.60000002384185791), (0.89495795965194702, 0.61960786581039429, 0.61960786581039429), (0.89915966987609863, 0.63921570777893066, 0.63921570777893066), (0.90336132049560547, 0.66274511814117432, 0.66274511814117432), (0.90756303071975708, 0.68235296010971069, 0.68235296010971069), (0.91176468133926392, 0.70588237047195435, 0.70588237047195435), (0.91596639156341553, 0.7450980544090271, 0.7450980544090271), (0.92016804218292236, 0.76862746477127075, 0.76862746477127075), (0.92436975240707397, 0.78823530673980713, 0.78823530673980713), (0.92857140302658081, 0.80784314870834351, 0.80784314870834351), (0.93277311325073242, 0.83137255907058716, 0.83137255907058716), (0.93697476387023926, 0.85098040103912354, 0.85098040103912354), (0.94117647409439087, 0.87450981140136719, 0.87450981140136719), (0.94537812471389771, 0.89411765336990356, 0.89411765336990356), (0.94957983493804932, 0.91372549533843994, 0.91372549533843994), (0.95378148555755615, 0.93725490570068359, 0.93725490570068359), (0.95798319578170776, 0.95686274766921997, 0.95686274766921997), (0.9621848464012146, 0.97647058963775635, 0.97647058963775635), (0.96638655662536621, 1.0, 1.0), (0.97058820724487305, 1.0, 1.0), (0.97478991746902466, 1.0, 1.0), (0.97899156808853149, 1.0, 1.0), (0.98319327831268311, 1.0, 1.0), (0.98739492893218994, 1.0, 1.0), (0.99159663915634155, 1.0, 1.0), (0.99579828977584839, 1.0, 1.0), (1.0, 1.0, 1.0)]} _gist_stern_data = {'blue': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0039215688593685627, 0.0039215688593685627), (0.0084033617749810219, 0.011764706112444401, 0.011764706112444401), (0.012605042196810246, 0.019607843831181526, 0.019607843831181526), (0.016806723549962044, 0.027450980618596077, 0.027450980618596077), (0.021008403971791267, 0.035294119268655777, 0.035294119268655777), (0.025210084393620491, 0.043137256056070328, 0.043137256056070328), (0.029411764815449715, 0.050980392843484879, 0.050980392843484879), (0.033613447099924088, 0.058823529630899429, 0.058823529630899429), (0.037815127521753311, 0.066666670143604279, 0.066666670143604279), (0.042016807943582535, 0.08235294371843338, 0.08235294371843338), (0.046218488365411758, 0.090196080505847931, 0.090196080505847931), (0.050420168787240982, 0.098039217293262482, 0.098039217293262482), (0.054621849209070206, 0.10588235408067703, 0.10588235408067703), (0.058823529630899429, 0.11372549086809158, 0.11372549086809158), (0.063025213778018951, 0.12156862765550613, 0.12156862765550613), (0.067226894199848175, 0.12941177189350128, 0.12941177189350128), (0.071428574621677399, 0.13725490868091583, 0.13725490868091583), (0.075630255043506622, 0.14509804546833038, 0.14509804546833038), (0.079831935465335846, 0.15294118225574493, 0.15294118225574493), (0.08403361588716507, 0.16078431904315948, 0.16078431904315948), (0.088235296308994293, 0.16862745583057404, 0.16862745583057404), (0.092436976730823517, 0.17647059261798859, 0.17647059261798859), (0.09663865715265274, 0.18431372940540314, 0.18431372940540314), (0.10084033757448196, 0.19215686619281769, 0.19215686619281769), (0.10504201799631119, 0.20000000298023224, 0.20000000298023224), (0.10924369841814041, 0.20784313976764679, 0.20784313976764679), (0.11344537883996964, 0.21568627655506134, 0.21568627655506134), (0.11764705926179886, 0.22352941334247589, 0.22352941334247589), (0.12184873968362808, 0.23137255012989044, 0.23137255012989044), (0.1260504275560379, 0.24705882370471954, 0.24705882370471954), (0.13025210797786713, 0.25490197539329529, 0.25490197539329529), (0.13445378839969635, 0.26274511218070984, 0.26274511218070984), (0.13865546882152557, 0.27058824896812439, 0.27058824896812439), (0.1428571492433548, 0.27843138575553894, 0.27843138575553894), (0.14705882966518402, 0.28627452254295349, 0.28627452254295349), (0.15126051008701324, 0.29411765933036804, 0.29411765933036804), (0.15546219050884247, 0.30196079611778259, 0.30196079611778259), (0.15966387093067169, 0.30980393290519714, 0.30980393290519714), (0.16386555135250092, 0.31764706969261169, 0.31764706969261169), (0.16806723177433014, 0.32549020648002625, 0.32549020648002625), (0.17226891219615936, 0.3333333432674408, 0.3333333432674408), (0.17647059261798859, 0.34117648005485535, 0.34117648005485535), (0.18067227303981781, 0.3490196168422699, 0.3490196168422699), (0.18487395346164703, 0.35686275362968445, 0.35686275362968445), (0.18907563388347626, 0.364705890417099, 0.364705890417099), (0.19327731430530548, 0.37254902720451355, 0.37254902720451355), (0.1974789947271347, 0.3803921639919281, 0.3803921639919281), (0.20168067514896393, 0.38823530077934265, 0.38823530077934265), (0.20588235557079315, 0.3960784375667572, 0.3960784375667572), (0.21008403599262238, 0.4117647111415863, 0.4117647111415863), (0.2142857164144516, 0.41960784792900085, 0.41960784792900085), (0.21848739683628082, 0.42745098471641541, 0.42745098471641541), (0.22268907725811005, 0.43529412150382996, 0.43529412150382996), (0.22689075767993927, 0.44313725829124451, 0.44313725829124451), (0.23109243810176849, 0.45098039507865906, 0.45098039507865906), (0.23529411852359772, 0.45882353186607361, 0.45882353186607361), (0.23949579894542694, 0.46666666865348816, 0.46666666865348816), (0.24369747936725616, 0.47450980544090271, 0.47450980544090271), (0.24789915978908539, 0.48235294222831726, 0.48235294222831726), (0.25210085511207581, 0.49803921580314636, 0.49803921580314636), (0.25630253553390503, 0.5058823823928833, 0.5058823823928833), (0.26050421595573425, 0.51372551918029785, 0.51372551918029785), (0.26470589637756348, 0.5215686559677124, 0.5215686559677124), (0.2689075767993927, 0.52941179275512695, 0.52941179275512695), (0.27310925722122192, 0.5372549295425415, 0.5372549295425415), (0.27731093764305115, 0.54509806632995605, 0.54509806632995605), (0.28151261806488037, 0.55294120311737061, 0.55294120311737061), (0.28571429848670959, 0.56078433990478516, 0.56078433990478516), (0.28991597890853882, 0.56862747669219971, 0.56862747669219971), (0.29411765933036804, 0.58431375026702881, 0.58431375026702881), (0.29831933975219727, 0.59215688705444336, 0.59215688705444336), (0.30252102017402649, 0.60000002384185791, 0.60000002384185791), (0.30672270059585571, 0.60784316062927246, 0.60784316062927246), (0.31092438101768494, 0.61568629741668701, 0.61568629741668701), (0.31512606143951416, 0.62352943420410156, 0.62352943420410156), (0.31932774186134338, 0.63137257099151611, 0.63137257099151611), (0.32352942228317261, 0.63921570777893066, 0.63921570777893066), (0.32773110270500183, 0.64705884456634521, 0.64705884456634521), (0.33193278312683105, 0.65490198135375977, 0.65490198135375977), (0.33613446354866028, 0.66274511814117432, 0.66274511814117432), (0.3403361439704895, 0.67058825492858887, 0.67058825492858887), (0.34453782439231873, 0.67843139171600342, 0.67843139171600342), (0.34873950481414795, 0.68627452850341797, 0.68627452850341797), (0.35294118523597717, 0.69411766529083252, 0.69411766529083252), (0.3571428656578064, 0.70196080207824707, 0.70196080207824707), (0.36134454607963562, 0.70980393886566162, 0.70980393886566162), (0.36554622650146484, 0.71764707565307617, 0.71764707565307617), (0.36974790692329407, 0.72549021244049072, 0.72549021244049072), (0.37394958734512329, 0.73333334922790527, 0.73333334922790527), (0.37815126776695251, 0.74901962280273438, 0.74901962280273438), (0.38235294818878174, 0.75686275959014893, 0.75686275959014893), (0.38655462861061096, 0.76470589637756348, 0.76470589637756348), (0.39075630903244019, 0.77254903316497803, 0.77254903316497803), (0.39495798945426941, 0.78039216995239258, 0.78039216995239258), (0.39915966987609863, 0.78823530673980713, 0.78823530673980713), (0.40336135029792786, 0.79607844352722168, 0.79607844352722168), (0.40756303071975708, 0.80392158031463623, 0.80392158031463623), (0.4117647111415863, 0.81176471710205078, 0.81176471710205078), (0.41596639156341553, 0.81960785388946533, 0.81960785388946533), (0.42016807198524475, 0.82745099067687988, 0.82745099067687988), (0.42436975240707397, 0.83529412746429443, 0.83529412746429443), (0.4285714328289032, 0.84313726425170898, 0.84313726425170898), (0.43277311325073242, 0.85098040103912354, 0.85098040103912354), (0.43697479367256165, 0.85882353782653809, 0.85882353782653809), (0.44117647409439087, 0.86666667461395264, 0.86666667461395264), (0.44537815451622009, 0.87450981140136719, 0.87450981140136719), (0.44957983493804932, 0.88235294818878174, 0.88235294818878174), (0.45378151535987854, 0.89019608497619629, 0.89019608497619629), (0.45798319578170776, 0.89803922176361084, 0.89803922176361084), (0.46218487620353699, 0.91372549533843994, 0.91372549533843994), (0.46638655662536621, 0.92156863212585449, 0.92156863212585449), (0.47058823704719543, 0.92941176891326904, 0.92941176891326904), (0.47478991746902466, 0.93725490570068359, 0.93725490570068359), (0.47899159789085388, 0.94509804248809814, 0.94509804248809814), (0.48319327831268311, 0.9529411792755127, 0.9529411792755127), (0.48739495873451233, 0.96078431606292725, 0.96078431606292725), (0.49159663915634155, 0.9686274528503418, 0.9686274528503418), (0.49579831957817078, 0.97647058963775635, 0.97647058963775635), (0.5, 0.9843137264251709, 0.9843137264251709), (0.50420171022415161, 1.0, 1.0), (0.50840336084365845, 0.9843137264251709, 0.9843137264251709), (0.51260507106781006, 0.9686274528503418, 0.9686274528503418), (0.51680672168731689, 0.9529411792755127, 0.9529411792755127), (0.52100843191146851, 0.93333333730697632, 0.93333333730697632), (0.52521008253097534, 0.91764706373214722, 0.91764706373214722), (0.52941179275512695, 0.90196079015731812, 0.90196079015731812), (0.53361344337463379, 0.88627451658248901, 0.88627451658248901), (0.5378151535987854, 0.86666667461395264, 0.86666667461395264), (0.54201680421829224, 0.85098040103912354, 0.85098040103912354), (0.54621851444244385, 0.81960785388946533, 0.81960785388946533), (0.55042016506195068, 0.80000001192092896, 0.80000001192092896), (0.55462187528610229, 0.78431373834609985, 0.78431373834609985), (0.55882352590560913, 0.76862746477127075, 0.76862746477127075), (0.56302523612976074, 0.75294119119644165, 0.75294119119644165), (0.56722688674926758, 0.73333334922790527, 0.73333334922790527), (0.57142859697341919, 0.71764707565307617, 0.71764707565307617), (0.57563024759292603, 0.70196080207824707, 0.70196080207824707), (0.57983195781707764, 0.68627452850341797, 0.68627452850341797), (0.58403360843658447, 0.66666668653488159, 0.66666668653488159), (0.58823531866073608, 0.65098041296005249, 0.65098041296005249), (0.59243696928024292, 0.63529413938522339, 0.63529413938522339), (0.59663867950439453, 0.61960786581039429, 0.61960786581039429), (0.60084033012390137, 0.60000002384185791, 0.60000002384185791), (0.60504204034805298, 0.58431375026702881, 0.58431375026702881), (0.60924369096755981, 0.56862747669219971, 0.56862747669219971), (0.61344540119171143, 0.55294120311737061, 0.55294120311737061), (0.61764705181121826, 0.53333336114883423, 0.53333336114883423), (0.62184876203536987, 0.51764708757400513, 0.51764708757400513), (0.62605041265487671, 0.50196081399917603, 0.50196081399917603), (0.63025212287902832, 0.46666666865348816, 0.46666666865348816), (0.63445377349853516, 0.45098039507865906, 0.45098039507865906), (0.63865548372268677, 0.43529412150382996, 0.43529412150382996), (0.6428571343421936, 0.41960784792900085, 0.41960784792900085), (0.64705884456634521, 0.40000000596046448, 0.40000000596046448), (0.65126049518585205, 0.38431373238563538, 0.38431373238563538), (0.65546220541000366, 0.36862745881080627, 0.36862745881080627), (0.6596638560295105, 0.35294118523597717, 0.35294118523597717), (0.66386556625366211, 0.3333333432674408, 0.3333333432674408), (0.66806721687316895, 0.31764706969261169, 0.31764706969261169), (0.67226892709732056, 0.30196079611778259, 0.30196079611778259), (0.67647057771682739, 0.28627452254295349, 0.28627452254295349), (0.680672287940979, 0.26666668057441711, 0.26666668057441711), (0.68487393856048584, 0.25098040699958801, 0.25098040699958801), (0.68907564878463745, 0.23529411852359772, 0.23529411852359772), (0.69327729940414429, 0.21960784494876862, 0.21960784494876862), (0.6974790096282959, 0.20000000298023224, 0.20000000298023224), (0.70168066024780273, 0.18431372940540314, 0.18431372940540314), (0.70588237047195435, 0.16862745583057404, 0.16862745583057404), (0.71008402109146118, 0.15294118225574493, 0.15294118225574493), (0.71428573131561279, 0.11764705926179886, 0.11764705926179886), (0.71848738193511963, 0.10196078568696976, 0.10196078568696976), (0.72268909215927124, 0.086274512112140656, 0.086274512112140656), (0.72689074277877808, 0.066666670143604279, 0.066666670143604279), (0.73109245300292969, 0.050980392843484879, 0.050980392843484879), (0.73529410362243652, 0.035294119268655777, 0.035294119268655777), (0.73949581384658813, 0.019607843831181526, 0.019607843831181526), (0.74369746446609497, 0.0, 0.0), (0.74789917469024658, 0.011764706112444401, 0.011764706112444401), (0.75210082530975342, 0.027450980618596077, 0.027450980618596077), (0.75630253553390503, 0.058823529630899429, 0.058823529630899429), (0.76050418615341187, 0.074509806931018829, 0.074509806931018829), (0.76470589637756348, 0.086274512112140656, 0.086274512112140656), (0.76890754699707031, 0.10196078568696976, 0.10196078568696976), (0.77310925722122192, 0.11764705926179886, 0.11764705926179886), (0.77731090784072876, 0.13333334028720856, 0.13333334028720856), (0.78151261806488037, 0.14901961386203766, 0.14901961386203766), (0.78571426868438721, 0.16078431904315948, 0.16078431904315948), (0.78991597890853882, 0.17647059261798859, 0.17647059261798859), (0.79411762952804565, 0.19215686619281769, 0.19215686619281769), (0.79831933975219727, 0.22352941334247589, 0.22352941334247589), (0.8025209903717041, 0.23529411852359772, 0.23529411852359772), (0.80672270059585571, 0.25098040699958801, 0.25098040699958801), (0.81092435121536255, 0.26666668057441711, 0.26666668057441711), (0.81512606143951416, 0.28235295414924622, 0.28235295414924622), (0.819327712059021, 0.29803922772407532, 0.29803922772407532), (0.82352942228317261, 0.30980393290519714, 0.30980393290519714), (0.82773107290267944, 0.32549020648002625, 0.32549020648002625), (0.83193278312683105, 0.34117648005485535, 0.34117648005485535), (0.83613443374633789, 0.35686275362968445, 0.35686275362968445), (0.8403361439704895, 0.37254902720451355, 0.37254902720451355), (0.84453779458999634, 0.38431373238563538, 0.38431373238563538), (0.84873950481414795, 0.40000000596046448, 0.40000000596046448), (0.85294115543365479, 0.41568627953529358, 0.41568627953529358), (0.8571428656578064, 0.43137255311012268, 0.43137255311012268), (0.86134451627731323, 0.44705882668495178, 0.44705882668495178), (0.86554622650146484, 0.45882353186607361, 0.45882353186607361), (0.86974787712097168, 0.47450980544090271, 0.47450980544090271), (0.87394958734512329, 0.49019607901573181, 0.49019607901573181), (0.87815123796463013, 0.5058823823928833, 0.5058823823928833), (0.88235294818878174, 0.5372549295425415, 0.5372549295425415), (0.88655459880828857, 0.54901963472366333, 0.54901963472366333), (0.89075630903244019, 0.56470590829849243, 0.56470590829849243), (0.89495795965194702, 0.58039218187332153, 0.58039218187332153), (0.89915966987609863, 0.59607845544815063, 0.59607845544815063), (0.90336132049560547, 0.61176472902297974, 0.61176472902297974), (0.90756303071975708, 0.62352943420410156, 0.62352943420410156), (0.91176468133926392, 0.63921570777893066, 0.63921570777893066), (0.91596639156341553, 0.65490198135375977, 0.65490198135375977), (0.92016804218292236, 0.67058825492858887, 0.67058825492858887), (0.92436975240707397, 0.68627452850341797, 0.68627452850341797), (0.92857140302658081, 0.69803923368453979, 0.69803923368453979), (0.93277311325073242, 0.7137255072593689, 0.7137255072593689), (0.93697476387023926, 0.729411780834198, 0.729411780834198), (0.94117647409439087, 0.7450980544090271, 0.7450980544090271), (0.94537812471389771, 0.7607843279838562, 0.7607843279838562), (0.94957983493804932, 0.77254903316497803, 0.77254903316497803), (0.95378148555755615, 0.78823530673980713, 0.78823530673980713), (0.95798319578170776, 0.80392158031463623, 0.80392158031463623), (0.9621848464012146, 0.81960785388946533, 0.81960785388946533), (0.96638655662536621, 0.84705883264541626, 0.84705883264541626), (0.97058820724487305, 0.86274510622024536, 0.86274510622024536), (0.97478991746902466, 0.87843137979507446, 0.87843137979507446), (0.97899156808853149, 0.89411765336990356, 0.89411765336990356), (0.98319327831268311, 0.90980392694473267, 0.90980392694473267), (0.98739492893218994, 0.92156863212585449, 0.92156863212585449), (0.99159663915634155, 0.93725490570068359, 0.93725490570068359), (0.99579828977584839, 0.9529411792755127, 0.9529411792755127), (1.0, 0.9686274528503418, 0.9686274528503418)], 'green': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.0039215688593685627, 0.0039215688593685627), (0.0084033617749810219, 0.0078431377187371254, 0.0078431377187371254), (0.012605042196810246, 0.011764706112444401, 0.011764706112444401), (0.016806723549962044, 0.015686275437474251, 0.015686275437474251), (0.021008403971791267, 0.019607843831181526, 0.019607843831181526), (0.025210084393620491, 0.023529412224888802, 0.023529412224888802), (0.029411764815449715, 0.027450980618596077, 0.027450980618596077), (0.033613447099924088, 0.031372550874948502, 0.031372550874948502), (0.037815127521753311, 0.035294119268655777, 0.035294119268655777), (0.042016807943582535, 0.043137256056070328, 0.043137256056070328), (0.046218488365411758, 0.047058824449777603, 0.047058824449777603), (0.050420168787240982, 0.050980392843484879, 0.050980392843484879), (0.054621849209070206, 0.054901961237192154, 0.054901961237192154), (0.058823529630899429, 0.058823529630899429, 0.058823529630899429), (0.063025213778018951, 0.062745101749897003, 0.062745101749897003), (0.067226894199848175, 0.066666670143604279, 0.066666670143604279), (0.071428574621677399, 0.070588238537311554, 0.070588238537311554), (0.075630255043506622, 0.074509806931018829, 0.074509806931018829), (0.079831935465335846, 0.078431375324726105, 0.078431375324726105), (0.08403361588716507, 0.08235294371843338, 0.08235294371843338), (0.088235296308994293, 0.086274512112140656, 0.086274512112140656), (0.092436976730823517, 0.090196080505847931, 0.090196080505847931), (0.09663865715265274, 0.094117648899555206, 0.094117648899555206), (0.10084033757448196, 0.098039217293262482, 0.098039217293262482), (0.10504201799631119, 0.10196078568696976, 0.10196078568696976), (0.10924369841814041, 0.10588235408067703, 0.10588235408067703), (0.11344537883996964, 0.10980392247438431, 0.10980392247438431), (0.11764705926179886, 0.11372549086809158, 0.11372549086809158), (0.12184873968362808, 0.11764705926179886, 0.11764705926179886), (0.1260504275560379, 0.12549020349979401, 0.12549020349979401), (0.13025210797786713, 0.12941177189350128, 0.12941177189350128), (0.13445378839969635, 0.13333334028720856, 0.13333334028720856), (0.13865546882152557, 0.13725490868091583, 0.13725490868091583), (0.1428571492433548, 0.14117647707462311, 0.14117647707462311), (0.14705882966518402, 0.14509804546833038, 0.14509804546833038), (0.15126051008701324, 0.14901961386203766, 0.14901961386203766), (0.15546219050884247, 0.15294118225574493, 0.15294118225574493), (0.15966387093067169, 0.15686275064945221, 0.15686275064945221), (0.16386555135250092, 0.16078431904315948, 0.16078431904315948), (0.16806723177433014, 0.16470588743686676, 0.16470588743686676), (0.17226891219615936, 0.16862745583057404, 0.16862745583057404), (0.17647059261798859, 0.17254902422428131, 0.17254902422428131), (0.18067227303981781, 0.17647059261798859, 0.17647059261798859), (0.18487395346164703, 0.18039216101169586, 0.18039216101169586), (0.18907563388347626, 0.18431372940540314, 0.18431372940540314), (0.19327731430530548, 0.18823529779911041, 0.18823529779911041), (0.1974789947271347, 0.19215686619281769, 0.19215686619281769), (0.20168067514896393, 0.19607843458652496, 0.19607843458652496), (0.20588235557079315, 0.20000000298023224, 0.20000000298023224), (0.21008403599262238, 0.20784313976764679, 0.20784313976764679), (0.2142857164144516, 0.21176470816135406, 0.21176470816135406), (0.21848739683628082, 0.21568627655506134, 0.21568627655506134), (0.22268907725811005, 0.21960784494876862, 0.21960784494876862), (0.22689075767993927, 0.22352941334247589, 0.22352941334247589), (0.23109243810176849, 0.22745098173618317, 0.22745098173618317), (0.23529411852359772, 0.23137255012989044, 0.23137255012989044), (0.23949579894542694, 0.23529411852359772, 0.23529411852359772), (0.24369747936725616, 0.23921568691730499, 0.23921568691730499), (0.24789915978908539, 0.24313725531101227, 0.24313725531101227), (0.25210085511207581, 0.25098040699958801, 0.25098040699958801), (0.25630253553390503, 0.25490197539329529, 0.25490197539329529), (0.26050421595573425, 0.25882354378700256, 0.25882354378700256), (0.26470589637756348, 0.26274511218070984, 0.26274511218070984), (0.2689075767993927, 0.26666668057441711, 0.26666668057441711), (0.27310925722122192, 0.27058824896812439, 0.27058824896812439), (0.27731093764305115, 0.27450981736183167, 0.27450981736183167), (0.28151261806488037, 0.27843138575553894, 0.27843138575553894), (0.28571429848670959, 0.28235295414924622, 0.28235295414924622), (0.28991597890853882, 0.28627452254295349, 0.28627452254295349), (0.29411765933036804, 0.29411765933036804, 0.29411765933036804), (0.29831933975219727, 0.29803922772407532, 0.29803922772407532), (0.30252102017402649, 0.30196079611778259, 0.30196079611778259), (0.30672270059585571, 0.30588236451148987, 0.30588236451148987), (0.31092438101768494, 0.30980393290519714, 0.30980393290519714), (0.31512606143951416, 0.31372550129890442, 0.31372550129890442), (0.31932774186134338, 0.31764706969261169, 0.31764706969261169), (0.32352942228317261, 0.32156863808631897, 0.32156863808631897), (0.32773110270500183, 0.32549020648002625, 0.32549020648002625), (0.33193278312683105, 0.32941177487373352, 0.32941177487373352), (0.33613446354866028, 0.3333333432674408, 0.3333333432674408), (0.3403361439704895, 0.33725491166114807, 0.33725491166114807), (0.34453782439231873, 0.34117648005485535, 0.34117648005485535), (0.34873950481414795, 0.34509804844856262, 0.34509804844856262), (0.35294118523597717, 0.3490196168422699, 0.3490196168422699), (0.3571428656578064, 0.35294118523597717, 0.35294118523597717), (0.36134454607963562, 0.35686275362968445, 0.35686275362968445), (0.36554622650146484, 0.36078432202339172, 0.36078432202339172), (0.36974790692329407, 0.364705890417099, 0.364705890417099), (0.37394958734512329, 0.36862745881080627, 0.36862745881080627), (0.37815126776695251, 0.37647059559822083, 0.37647059559822083), (0.38235294818878174, 0.3803921639919281, 0.3803921639919281), (0.38655462861061096, 0.38431373238563538, 0.38431373238563538), (0.39075630903244019, 0.38823530077934265, 0.38823530077934265), (0.39495798945426941, 0.39215686917304993, 0.39215686917304993), (0.39915966987609863, 0.3960784375667572, 0.3960784375667572), (0.40336135029792786, 0.40000000596046448, 0.40000000596046448), (0.40756303071975708, 0.40392157435417175, 0.40392157435417175), (0.4117647111415863, 0.40784314274787903, 0.40784314274787903), (0.41596639156341553, 0.4117647111415863, 0.4117647111415863), (0.42016807198524475, 0.41568627953529358, 0.41568627953529358), (0.42436975240707397, 0.41960784792900085, 0.41960784792900085), (0.4285714328289032, 0.42352941632270813, 0.42352941632270813), (0.43277311325073242, 0.42745098471641541, 0.42745098471641541), (0.43697479367256165, 0.43137255311012268, 0.43137255311012268), (0.44117647409439087, 0.43529412150382996, 0.43529412150382996), (0.44537815451622009, 0.43921568989753723, 0.43921568989753723), (0.44957983493804932, 0.44313725829124451, 0.44313725829124451), (0.45378151535987854, 0.44705882668495178, 0.44705882668495178), (0.45798319578170776, 0.45098039507865906, 0.45098039507865906), (0.46218487620353699, 0.45882353186607361, 0.45882353186607361), (0.46638655662536621, 0.46274510025978088, 0.46274510025978088), (0.47058823704719543, 0.46666666865348816, 0.46666666865348816), (0.47478991746902466, 0.47058823704719543, 0.47058823704719543), (0.47899159789085388, 0.47450980544090271, 0.47450980544090271), (0.48319327831268311, 0.47843137383460999, 0.47843137383460999), (0.48739495873451233, 0.48235294222831726, 0.48235294222831726), (0.49159663915634155, 0.48627451062202454, 0.48627451062202454), (0.49579831957817078, 0.49019607901573181, 0.49019607901573181), (0.5, 0.49411764740943909, 0.49411764740943909), (0.50420171022415161, 0.50196081399917603, 0.50196081399917603), (0.50840336084365845, 0.5058823823928833, 0.5058823823928833), (0.51260507106781006, 0.50980395078659058, 0.50980395078659058), (0.51680672168731689, 0.51372551918029785, 0.51372551918029785), (0.52100843191146851, 0.51764708757400513, 0.51764708757400513), (0.52521008253097534, 0.5215686559677124, 0.5215686559677124), (0.52941179275512695, 0.52549022436141968, 0.52549022436141968), (0.53361344337463379, 0.52941179275512695, 0.52941179275512695), (0.5378151535987854, 0.53333336114883423, 0.53333336114883423), (0.54201680421829224, 0.5372549295425415, 0.5372549295425415), (0.54621851444244385, 0.54509806632995605, 0.54509806632995605), (0.55042016506195068, 0.54901963472366333, 0.54901963472366333), (0.55462187528610229, 0.55294120311737061, 0.55294120311737061), (0.55882352590560913, 0.55686277151107788, 0.55686277151107788), (0.56302523612976074, 0.56078433990478516, 0.56078433990478516), (0.56722688674926758, 0.56470590829849243, 0.56470590829849243), (0.57142859697341919, 0.56862747669219971, 0.56862747669219971), (0.57563024759292603, 0.57254904508590698, 0.57254904508590698), (0.57983195781707764, 0.57647061347961426, 0.57647061347961426), (0.58403360843658447, 0.58039218187332153, 0.58039218187332153), (0.58823531866073608, 0.58431375026702881, 0.58431375026702881), (0.59243696928024292, 0.58823531866073608, 0.58823531866073608), (0.59663867950439453, 0.59215688705444336, 0.59215688705444336), (0.60084033012390137, 0.59607845544815063, 0.59607845544815063), (0.60504204034805298, 0.60000002384185791, 0.60000002384185791), (0.60924369096755981, 0.60392159223556519, 0.60392159223556519), (0.61344540119171143, 0.60784316062927246, 0.60784316062927246), (0.61764705181121826, 0.61176472902297974, 0.61176472902297974), (0.62184876203536987, 0.61568629741668701, 0.61568629741668701), (0.62605041265487671, 0.61960786581039429, 0.61960786581039429), (0.63025212287902832, 0.62745100259780884, 0.62745100259780884), (0.63445377349853516, 0.63137257099151611, 0.63137257099151611), (0.63865548372268677, 0.63529413938522339, 0.63529413938522339), (0.6428571343421936, 0.63921570777893066, 0.63921570777893066), (0.64705884456634521, 0.64313727617263794, 0.64313727617263794), (0.65126049518585205, 0.64705884456634521, 0.64705884456634521), (0.65546220541000366, 0.65098041296005249, 0.65098041296005249), (0.6596638560295105, 0.65490198135375977, 0.65490198135375977), (0.66386556625366211, 0.65882354974746704, 0.65882354974746704), (0.66806721687316895, 0.66274511814117432, 0.66274511814117432), (0.67226892709732056, 0.66666668653488159, 0.66666668653488159), (0.67647057771682739, 0.67058825492858887, 0.67058825492858887), (0.680672287940979, 0.67450982332229614, 0.67450982332229614), (0.68487393856048584, 0.67843139171600342, 0.67843139171600342), (0.68907564878463745, 0.68235296010971069, 0.68235296010971069), (0.69327729940414429, 0.68627452850341797, 0.68627452850341797), (0.6974790096282959, 0.69019609689712524, 0.69019609689712524), (0.70168066024780273, 0.69411766529083252, 0.69411766529083252), (0.70588237047195435, 0.69803923368453979, 0.69803923368453979), (0.71008402109146118, 0.70196080207824707, 0.70196080207824707), (0.71428573131561279, 0.70980393886566162, 0.70980393886566162), (0.71848738193511963, 0.7137255072593689, 0.7137255072593689), (0.72268909215927124, 0.71764707565307617, 0.71764707565307617), (0.72689074277877808, 0.72156864404678345, 0.72156864404678345), (0.73109245300292969, 0.72549021244049072, 0.72549021244049072), (0.73529410362243652, 0.729411780834198, 0.729411780834198), (0.73949581384658813, 0.73333334922790527, 0.73333334922790527), (0.74369746446609497, 0.73725491762161255, 0.73725491762161255), (0.74789917469024658, 0.74117648601531982, 0.74117648601531982), (0.75210082530975342, 0.7450980544090271, 0.7450980544090271), (0.75630253553390503, 0.75294119119644165, 0.75294119119644165), (0.76050418615341187, 0.75686275959014893, 0.75686275959014893), (0.76470589637756348, 0.7607843279838562, 0.7607843279838562), (0.76890754699707031, 0.76470589637756348, 0.76470589637756348), (0.77310925722122192, 0.76862746477127075, 0.76862746477127075), (0.77731090784072876, 0.77254903316497803, 0.77254903316497803), (0.78151261806488037, 0.7764706015586853, 0.7764706015586853), (0.78571426868438721, 0.78039216995239258, 0.78039216995239258), (0.78991597890853882, 0.78431373834609985, 0.78431373834609985), (0.79411762952804565, 0.78823530673980713, 0.78823530673980713), (0.79831933975219727, 0.79607844352722168, 0.79607844352722168), (0.8025209903717041, 0.80000001192092896, 0.80000001192092896), (0.80672270059585571, 0.80392158031463623, 0.80392158031463623), (0.81092435121536255, 0.80784314870834351, 0.80784314870834351), (0.81512606143951416, 0.81176471710205078, 0.81176471710205078), (0.819327712059021, 0.81568628549575806, 0.81568628549575806), (0.82352942228317261, 0.81960785388946533, 0.81960785388946533), (0.82773107290267944, 0.82352942228317261, 0.82352942228317261), (0.83193278312683105, 0.82745099067687988, 0.82745099067687988), (0.83613443374633789, 0.83137255907058716, 0.83137255907058716), (0.8403361439704895, 0.83529412746429443, 0.83529412746429443), (0.84453779458999634, 0.83921569585800171, 0.83921569585800171), (0.84873950481414795, 0.84313726425170898, 0.84313726425170898), (0.85294115543365479, 0.84705883264541626, 0.84705883264541626), (0.8571428656578064, 0.85098040103912354, 0.85098040103912354), (0.86134451627731323, 0.85490196943283081, 0.85490196943283081), (0.86554622650146484, 0.85882353782653809, 0.85882353782653809), (0.86974787712097168, 0.86274510622024536, 0.86274510622024536), (0.87394958734512329, 0.86666667461395264, 0.86666667461395264), (0.87815123796463013, 0.87058824300765991, 0.87058824300765991), (0.88235294818878174, 0.87843137979507446, 0.87843137979507446), (0.88655459880828857, 0.88235294818878174, 0.88235294818878174), (0.89075630903244019, 0.88627451658248901, 0.88627451658248901), (0.89495795965194702, 0.89019608497619629, 0.89019608497619629), (0.89915966987609863, 0.89411765336990356, 0.89411765336990356), (0.90336132049560547, 0.89803922176361084, 0.89803922176361084), (0.90756303071975708, 0.90196079015731812, 0.90196079015731812), (0.91176468133926392, 0.90588235855102539, 0.90588235855102539), (0.91596639156341553, 0.90980392694473267, 0.90980392694473267), (0.92016804218292236, 0.91372549533843994, 0.91372549533843994), (0.92436975240707397, 0.91764706373214722, 0.91764706373214722), (0.92857140302658081, 0.92156863212585449, 0.92156863212585449), (0.93277311325073242, 0.92549020051956177, 0.92549020051956177), (0.93697476387023926, 0.92941176891326904, 0.92941176891326904), (0.94117647409439087, 0.93333333730697632, 0.93333333730697632), (0.94537812471389771, 0.93725490570068359, 0.93725490570068359), (0.94957983493804932, 0.94117647409439087, 0.94117647409439087), (0.95378148555755615, 0.94509804248809814, 0.94509804248809814), (0.95798319578170776, 0.94901961088180542, 0.94901961088180542), (0.9621848464012146, 0.9529411792755127, 0.9529411792755127), (0.96638655662536621, 0.96078431606292725, 0.96078431606292725), (0.97058820724487305, 0.96470588445663452, 0.96470588445663452), (0.97478991746902466, 0.9686274528503418, 0.9686274528503418), (0.97899156808853149, 0.97254902124404907, 0.97254902124404907), (0.98319327831268311, 0.97647058963775635, 0.97647058963775635), (0.98739492893218994, 0.98039215803146362, 0.98039215803146362), (0.99159663915634155, 0.9843137264251709, 0.9843137264251709), (0.99579828977584839, 0.98823529481887817, 0.98823529481887817), (1.0, 0.99215686321258545, 0.99215686321258545)], 'red': [(0.0, 0.0, 0.0), (0.0042016808874905109, 0.070588238537311554, 0.070588238537311554), (0.0084033617749810219, 0.14117647707462311, 0.14117647707462311), (0.012605042196810246, 0.21176470816135406, 0.21176470816135406), (0.016806723549962044, 0.28235295414924622, 0.28235295414924622), (0.021008403971791267, 0.35294118523597717, 0.35294118523597717), (0.025210084393620491, 0.42352941632270813, 0.42352941632270813), (0.029411764815449715, 0.49803921580314636, 0.49803921580314636), (0.033613447099924088, 0.56862747669219971, 0.56862747669219971), (0.037815127521753311, 0.63921570777893066, 0.63921570777893066), (0.042016807943582535, 0.78039216995239258, 0.78039216995239258), (0.046218488365411758, 0.85098040103912354, 0.85098040103912354), (0.050420168787240982, 0.92156863212585449, 0.92156863212585449), (0.054621849209070206, 0.99607843160629272, 0.99607843160629272), (0.058823529630899429, 0.97647058963775635, 0.97647058963775635), (0.063025213778018951, 0.95686274766921997, 0.95686274766921997), (0.067226894199848175, 0.93725490570068359, 0.93725490570068359), (0.071428574621677399, 0.91764706373214722, 0.91764706373214722), (0.075630255043506622, 0.89803922176361084, 0.89803922176361084), (0.079831935465335846, 0.87450981140136719, 0.87450981140136719), (0.08403361588716507, 0.85490196943283081, 0.85490196943283081), (0.088235296308994293, 0.83529412746429443, 0.83529412746429443), (0.092436976730823517, 0.81568628549575806, 0.81568628549575806), (0.09663865715265274, 0.79607844352722168, 0.79607844352722168), (0.10084033757448196, 0.77254903316497803, 0.77254903316497803), (0.10504201799631119, 0.75294119119644165, 0.75294119119644165), (0.10924369841814041, 0.73333334922790527, 0.73333334922790527), (0.11344537883996964, 0.7137255072593689, 0.7137255072593689), (0.11764705926179886, 0.69411766529083252, 0.69411766529083252), (0.12184873968362808, 0.67450982332229614, 0.67450982332229614), (0.1260504275560379, 0.63137257099151611, 0.63137257099151611), (0.13025210797786713, 0.61176472902297974, 0.61176472902297974), (0.13445378839969635, 0.59215688705444336, 0.59215688705444336), (0.13865546882152557, 0.57254904508590698, 0.57254904508590698), (0.1428571492433548, 0.54901963472366333, 0.54901963472366333), (0.14705882966518402, 0.52941179275512695, 0.52941179275512695), (0.15126051008701324, 0.50980395078659058, 0.50980395078659058), (0.15546219050884247, 0.49019607901573181, 0.49019607901573181), (0.15966387093067169, 0.47058823704719543, 0.47058823704719543), (0.16386555135250092, 0.45098039507865906, 0.45098039507865906), (0.16806723177433014, 0.42745098471641541, 0.42745098471641541), (0.17226891219615936, 0.40784314274787903, 0.40784314274787903), (0.17647059261798859, 0.38823530077934265, 0.38823530077934265), (0.18067227303981781, 0.36862745881080627, 0.36862745881080627), (0.18487395346164703, 0.3490196168422699, 0.3490196168422699), (0.18907563388347626, 0.32549020648002625, 0.32549020648002625), (0.19327731430530548, 0.30588236451148987, 0.30588236451148987), (0.1974789947271347, 0.28627452254295349, 0.28627452254295349), (0.20168067514896393, 0.26666668057441711, 0.26666668057441711), (0.20588235557079315, 0.24705882370471954, 0.24705882370471954), (0.21008403599262238, 0.20392157137393951, 0.20392157137393951), (0.2142857164144516, 0.18431372940540314, 0.18431372940540314), (0.21848739683628082, 0.16470588743686676, 0.16470588743686676), (0.22268907725811005, 0.14509804546833038, 0.14509804546833038), (0.22689075767993927, 0.12549020349979401, 0.12549020349979401), (0.23109243810176849, 0.10196078568696976, 0.10196078568696976), (0.23529411852359772, 0.08235294371843338, 0.08235294371843338), (0.23949579894542694, 0.062745101749897003, 0.062745101749897003), (0.24369747936725616, 0.043137256056070328, 0.043137256056070328), (0.24789915978908539, 0.023529412224888802, 0.023529412224888802), (0.25210085511207581, 0.25098040699958801, 0.25098040699958801), (0.25630253553390503, 0.25490197539329529, 0.25490197539329529), (0.26050421595573425, 0.25882354378700256, 0.25882354378700256), (0.26470589637756348, 0.26274511218070984, 0.26274511218070984), (0.2689075767993927, 0.26666668057441711, 0.26666668057441711), (0.27310925722122192, 0.27058824896812439, 0.27058824896812439), (0.27731093764305115, 0.27450981736183167, 0.27450981736183167), (0.28151261806488037, 0.27843138575553894, 0.27843138575553894), (0.28571429848670959, 0.28235295414924622, 0.28235295414924622), (0.28991597890853882, 0.28627452254295349, 0.28627452254295349), (0.29411765933036804, 0.29411765933036804, 0.29411765933036804), (0.29831933975219727, 0.29803922772407532, 0.29803922772407532), (0.30252102017402649, 0.30196079611778259, 0.30196079611778259), (0.30672270059585571, 0.30588236451148987, 0.30588236451148987), (0.31092438101768494, 0.30980393290519714, 0.30980393290519714), (0.31512606143951416, 0.31372550129890442, 0.31372550129890442), (0.31932774186134338, 0.31764706969261169, 0.31764706969261169), (0.32352942228317261, 0.32156863808631897, 0.32156863808631897), (0.32773110270500183, 0.32549020648002625, 0.32549020648002625), (0.33193278312683105, 0.32941177487373352, 0.32941177487373352), (0.33613446354866028, 0.3333333432674408, 0.3333333432674408), (0.3403361439704895, 0.33725491166114807, 0.33725491166114807), (0.34453782439231873, 0.34117648005485535, 0.34117648005485535), (0.34873950481414795, 0.34509804844856262, 0.34509804844856262), (0.35294118523597717, 0.3490196168422699, 0.3490196168422699), (0.3571428656578064, 0.35294118523597717, 0.35294118523597717), (0.36134454607963562, 0.35686275362968445, 0.35686275362968445), (0.36554622650146484, 0.36078432202339172, 0.36078432202339172), (0.36974790692329407, 0.364705890417099, 0.364705890417099), (0.37394958734512329, 0.36862745881080627, 0.36862745881080627), (0.37815126776695251, 0.37647059559822083, 0.37647059559822083), (0.38235294818878174, 0.3803921639919281, 0.3803921639919281), (0.38655462861061096, 0.38431373238563538, 0.38431373238563538), (0.39075630903244019, 0.38823530077934265, 0.38823530077934265), (0.39495798945426941, 0.39215686917304993, 0.39215686917304993), (0.39915966987609863, 0.3960784375667572, 0.3960784375667572), (0.40336135029792786, 0.40000000596046448, 0.40000000596046448), (0.40756303071975708, 0.40392157435417175, 0.40392157435417175), (0.4117647111415863, 0.40784314274787903, 0.40784314274787903), (0.41596639156341553, 0.4117647111415863, 0.4117647111415863), (0.42016807198524475, 0.41568627953529358, 0.41568627953529358), (0.42436975240707397, 0.41960784792900085, 0.41960784792900085), (0.4285714328289032, 0.42352941632270813, 0.42352941632270813), (0.43277311325073242, 0.42745098471641541, 0.42745098471641541), (0.43697479367256165, 0.43137255311012268, 0.43137255311012268), (0.44117647409439087, 0.43529412150382996, 0.43529412150382996), (0.44537815451622009, 0.43921568989753723, 0.43921568989753723), (0.44957983493804932, 0.44313725829124451, 0.44313725829124451), (0.45378151535987854, 0.44705882668495178, 0.44705882668495178), (0.45798319578170776, 0.45098039507865906, 0.45098039507865906), (0.46218487620353699, 0.45882353186607361, 0.45882353186607361), (0.46638655662536621, 0.46274510025978088, 0.46274510025978088), (0.47058823704719543, 0.46666666865348816, 0.46666666865348816), (0.47478991746902466, 0.47058823704719543, 0.47058823704719543), (0.47899159789085388, 0.47450980544090271, 0.47450980544090271), (0.48319327831268311, 0.47843137383460999, 0.47843137383460999), (0.48739495873451233, 0.48235294222831726, 0.48235294222831726), (0.49159663915634155, 0.48627451062202454, 0.48627451062202454), (0.49579831957817078, 0.49019607901573181, 0.49019607901573181), (0.5, 0.49411764740943909, 0.49411764740943909), (0.50420171022415161, 0.50196081399917603, 0.50196081399917603), (0.50840336084365845, 0.5058823823928833, 0.5058823823928833), (0.51260507106781006, 0.50980395078659058, 0.50980395078659058), (0.51680672168731689, 0.51372551918029785, 0.51372551918029785), (0.52100843191146851, 0.51764708757400513, 0.51764708757400513), (0.52521008253097534, 0.5215686559677124, 0.5215686559677124), (0.52941179275512695, 0.52549022436141968, 0.52549022436141968), (0.53361344337463379, 0.52941179275512695, 0.52941179275512695), (0.5378151535987854, 0.53333336114883423, 0.53333336114883423), (0.54201680421829224, 0.5372549295425415, 0.5372549295425415), (0.54621851444244385, 0.54509806632995605, 0.54509806632995605), (0.55042016506195068, 0.54901963472366333, 0.54901963472366333), (0.55462187528610229, 0.55294120311737061, 0.55294120311737061), (0.55882352590560913, 0.55686277151107788, 0.55686277151107788), (0.56302523612976074, 0.56078433990478516, 0.56078433990478516), (0.56722688674926758, 0.56470590829849243, 0.56470590829849243), (0.57142859697341919, 0.56862747669219971, 0.56862747669219971), (0.57563024759292603, 0.57254904508590698, 0.57254904508590698), (0.57983195781707764, 0.57647061347961426, 0.57647061347961426), (0.58403360843658447, 0.58039218187332153, 0.58039218187332153), (0.58823531866073608, 0.58431375026702881, 0.58431375026702881), (0.59243696928024292, 0.58823531866073608, 0.58823531866073608), (0.59663867950439453, 0.59215688705444336, 0.59215688705444336), (0.60084033012390137, 0.59607845544815063, 0.59607845544815063), (0.60504204034805298, 0.60000002384185791, 0.60000002384185791), (0.60924369096755981, 0.60392159223556519, 0.60392159223556519), (0.61344540119171143, 0.60784316062927246, 0.60784316062927246), (0.61764705181121826, 0.61176472902297974, 0.61176472902297974), (0.62184876203536987, 0.61568629741668701, 0.61568629741668701), (0.62605041265487671, 0.61960786581039429, 0.61960786581039429), (0.63025212287902832, 0.62745100259780884, 0.62745100259780884), (0.63445377349853516, 0.63137257099151611, 0.63137257099151611), (0.63865548372268677, 0.63529413938522339, 0.63529413938522339), (0.6428571343421936, 0.63921570777893066, 0.63921570777893066), (0.64705884456634521, 0.64313727617263794, 0.64313727617263794), (0.65126049518585205, 0.64705884456634521, 0.64705884456634521), (0.65546220541000366, 0.65098041296005249, 0.65098041296005249), (0.6596638560295105, 0.65490198135375977, 0.65490198135375977), (0.66386556625366211, 0.65882354974746704, 0.65882354974746704), (0.66806721687316895, 0.66274511814117432, 0.66274511814117432), (0.67226892709732056, 0.66666668653488159, 0.66666668653488159), (0.67647057771682739, 0.67058825492858887, 0.67058825492858887), (0.680672287940979, 0.67450982332229614, 0.67450982332229614), (0.68487393856048584, 0.67843139171600342, 0.67843139171600342), (0.68907564878463745, 0.68235296010971069, 0.68235296010971069), (0.69327729940414429, 0.68627452850341797, 0.68627452850341797), (0.6974790096282959, 0.69019609689712524, 0.69019609689712524), (0.70168066024780273, 0.69411766529083252, 0.69411766529083252), (0.70588237047195435, 0.69803923368453979, 0.69803923368453979), (0.71008402109146118, 0.70196080207824707, 0.70196080207824707), (0.71428573131561279, 0.70980393886566162, 0.70980393886566162), (0.71848738193511963, 0.7137255072593689, 0.7137255072593689), (0.72268909215927124, 0.71764707565307617, 0.71764707565307617), (0.72689074277877808, 0.72156864404678345, 0.72156864404678345), (0.73109245300292969, 0.72549021244049072, 0.72549021244049072), (0.73529410362243652, 0.729411780834198, 0.729411780834198), (0.73949581384658813, 0.73333334922790527, 0.73333334922790527), (0.74369746446609497, 0.73725491762161255, 0.73725491762161255), (0.74789917469024658, 0.74117648601531982, 0.74117648601531982), (0.75210082530975342, 0.7450980544090271, 0.7450980544090271), (0.75630253553390503, 0.75294119119644165, 0.75294119119644165), (0.76050418615341187, 0.75686275959014893, 0.75686275959014893), (0.76470589637756348, 0.7607843279838562, 0.7607843279838562), (0.76890754699707031, 0.76470589637756348, 0.76470589637756348), (0.77310925722122192, 0.76862746477127075, 0.76862746477127075), (0.77731090784072876, 0.77254903316497803, 0.77254903316497803), (0.78151261806488037, 0.7764706015586853, 0.7764706015586853), (0.78571426868438721, 0.78039216995239258, 0.78039216995239258), (0.78991597890853882, 0.78431373834609985, 0.78431373834609985), (0.79411762952804565, 0.78823530673980713, 0.78823530673980713), (0.79831933975219727, 0.79607844352722168, 0.79607844352722168), (0.8025209903717041, 0.80000001192092896, 0.80000001192092896), (0.80672270059585571, 0.80392158031463623, 0.80392158031463623), (0.81092435121536255, 0.80784314870834351, 0.80784314870834351), (0.81512606143951416, 0.81176471710205078, 0.81176471710205078), (0.819327712059021, 0.81568628549575806, 0.81568628549575806), (0.82352942228317261, 0.81960785388946533, 0.81960785388946533), (0.82773107290267944, 0.82352942228317261, 0.82352942228317261), (0.83193278312683105, 0.82745099067687988, 0.82745099067687988), (0.83613443374633789, 0.83137255907058716, 0.83137255907058716), (0.8403361439704895, 0.83529412746429443, 0.83529412746429443), (0.84453779458999634, 0.83921569585800171, 0.83921569585800171), (0.84873950481414795, 0.84313726425170898, 0.84313726425170898), (0.85294115543365479, 0.84705883264541626, 0.84705883264541626), (0.8571428656578064, 0.85098040103912354, 0.85098040103912354), (0.86134451627731323, 0.85490196943283081, 0.85490196943283081), (0.86554622650146484, 0.85882353782653809, 0.85882353782653809), (0.86974787712097168, 0.86274510622024536, 0.86274510622024536), (0.87394958734512329, 0.86666667461395264, 0.86666667461395264), (0.87815123796463013, 0.87058824300765991, 0.87058824300765991), (0.88235294818878174, 0.87843137979507446, 0.87843137979507446), (0.88655459880828857, 0.88235294818878174, 0.88235294818878174), (0.89075630903244019, 0.88627451658248901, 0.88627451658248901), (0.89495795965194702, 0.89019608497619629, 0.89019608497619629), (0.89915966987609863, 0.89411765336990356, 0.89411765336990356), (0.90336132049560547, 0.89803922176361084, 0.89803922176361084), (0.90756303071975708, 0.90196079015731812, 0.90196079015731812), (0.91176468133926392, 0.90588235855102539, 0.90588235855102539), (0.91596639156341553, 0.90980392694473267, 0.90980392694473267), (0.92016804218292236, 0.91372549533843994, 0.91372549533843994), (0.92436975240707397, 0.91764706373214722, 0.91764706373214722), (0.92857140302658081, 0.92156863212585449, 0.92156863212585449), (0.93277311325073242, 0.92549020051956177, 0.92549020051956177), (0.93697476387023926, 0.92941176891326904, 0.92941176891326904), (0.94117647409439087, 0.93333333730697632, 0.93333333730697632), (0.94537812471389771, 0.93725490570068359, 0.93725490570068359), (0.94957983493804932, 0.94117647409439087, 0.94117647409439087), (0.95378148555755615, 0.94509804248809814, 0.94509804248809814), (0.95798319578170776, 0.94901961088180542, 0.94901961088180542), (0.9621848464012146, 0.9529411792755127, 0.9529411792755127), (0.96638655662536621, 0.96078431606292725, 0.96078431606292725), (0.97058820724487305, 0.96470588445663452, 0.96470588445663452), (0.97478991746902466, 0.9686274528503418, 0.9686274528503418), (0.97899156808853149, 0.97254902124404907, 0.97254902124404907), (0.98319327831268311, 0.97647058963775635, 0.97647058963775635), (0.98739492893218994, 0.98039215803146362, 0.98039215803146362), (0.99159663915634155, 0.9843137264251709, 0.9843137264251709), (0.99579828977584839, 0.98823529481887817, 0.98823529481887817), (1.0, 0.99215686321258545, 0.99215686321258545)]} _gist_yarg_data = {'blue': [(0.0, 1.0, 1.0), (0.0042016808874905109, 0.99607843160629272, 0.99607843160629272), (0.0084033617749810219, 0.99215686321258545, 0.99215686321258545), (0.012605042196810246, 0.98823529481887817, 0.98823529481887817), (0.016806723549962044, 0.9843137264251709, 0.9843137264251709), (0.021008403971791267, 0.98039215803146362, 0.98039215803146362), (0.025210084393620491, 0.97647058963775635, 0.97647058963775635), (0.029411764815449715, 0.97254902124404907, 0.97254902124404907), (0.033613447099924088, 0.96470588445663452, 0.96470588445663452), (0.037815127521753311, 0.96078431606292725, 0.96078431606292725), (0.042016807943582535, 0.95686274766921997, 0.95686274766921997), (0.046218488365411758, 0.9529411792755127, 0.9529411792755127), (0.050420168787240982, 0.94901961088180542, 0.94901961088180542), (0.054621849209070206, 0.94509804248809814, 0.94509804248809814), (0.058823529630899429, 0.94117647409439087, 0.94117647409439087), (0.063025213778018951, 0.93725490570068359, 0.93725490570068359), (0.067226894199848175, 0.93333333730697632, 0.93333333730697632), (0.071428574621677399, 0.92941176891326904, 0.92941176891326904), (0.075630255043506622, 0.92549020051956177, 0.92549020051956177), (0.079831935465335846, 0.92156863212585449, 0.92156863212585449), (0.08403361588716507, 0.91764706373214722, 0.91764706373214722), (0.088235296308994293, 0.91372549533843994, 0.91372549533843994), (0.092436976730823517, 0.90980392694473267, 0.90980392694473267), (0.09663865715265274, 0.90196079015731812, 0.90196079015731812), (0.10084033757448196, 0.89803922176361084, 0.89803922176361084), (0.10504201799631119, 0.89411765336990356, 0.89411765336990356), (0.10924369841814041, 0.89019608497619629, 0.89019608497619629), (0.11344537883996964, 0.88627451658248901, 0.88627451658248901), (0.11764705926179886, 0.88235294818878174, 0.88235294818878174), (0.12184873968362808, 0.87843137979507446, 0.87843137979507446), (0.1260504275560379, 0.87450981140136719, 0.87450981140136719), (0.13025210797786713, 0.87058824300765991, 0.87058824300765991), (0.13445378839969635, 0.86666667461395264, 0.86666667461395264), (0.13865546882152557, 0.86274510622024536, 0.86274510622024536), (0.1428571492433548, 0.85882353782653809, 0.85882353782653809), (0.14705882966518402, 0.85490196943283081, 0.85490196943283081), (0.15126051008701324, 0.85098040103912354, 0.85098040103912354), (0.15546219050884247, 0.84705883264541626, 0.84705883264541626), (0.15966387093067169, 0.83921569585800171, 0.83921569585800171), (0.16386555135250092, 0.83529412746429443, 0.83529412746429443), (0.16806723177433014, 0.83137255907058716, 0.83137255907058716), (0.17226891219615936, 0.82745099067687988, 0.82745099067687988), (0.17647059261798859, 0.82352942228317261, 0.82352942228317261), (0.18067227303981781, 0.81960785388946533, 0.81960785388946533), (0.18487395346164703, 0.81568628549575806, 0.81568628549575806), (0.18907563388347626, 0.81176471710205078, 0.81176471710205078), (0.19327731430530548, 0.80784314870834351, 0.80784314870834351), (0.1974789947271347, 0.80392158031463623, 0.80392158031463623), (0.20168067514896393, 0.80000001192092896, 0.80000001192092896), (0.20588235557079315, 0.79607844352722168, 0.79607844352722168), (0.21008403599262238, 0.7921568751335144, 0.7921568751335144), (0.2142857164144516, 0.78823530673980713, 0.78823530673980713), (0.21848739683628082, 0.78431373834609985, 0.78431373834609985), (0.22268907725811005, 0.7764706015586853, 0.7764706015586853), (0.22689075767993927, 0.77254903316497803, 0.77254903316497803), (0.23109243810176849, 0.76862746477127075, 0.76862746477127075), (0.23529411852359772, 0.76470589637756348, 0.76470589637756348), (0.23949579894542694, 0.7607843279838562, 0.7607843279838562), (0.24369747936725616, 0.75686275959014893, 0.75686275959014893), (0.24789915978908539, 0.75294119119644165, 0.75294119119644165), (0.25210085511207581, 0.74901962280273438, 0.74901962280273438), (0.25630253553390503, 0.7450980544090271, 0.7450980544090271), (0.26050421595573425, 0.74117648601531982, 0.74117648601531982), (0.26470589637756348, 0.73725491762161255, 0.73725491762161255), (0.2689075767993927, 0.73333334922790527, 0.73333334922790527), (0.27310925722122192, 0.729411780834198, 0.729411780834198), (0.27731093764305115, 0.72549021244049072, 0.72549021244049072), (0.28151261806488037, 0.72156864404678345, 0.72156864404678345), (0.28571429848670959, 0.7137255072593689, 0.7137255072593689), (0.28991597890853882, 0.70980393886566162, 0.70980393886566162), (0.29411765933036804, 0.70588237047195435, 0.70588237047195435), (0.29831933975219727, 0.70196080207824707, 0.70196080207824707), (0.30252102017402649, 0.69803923368453979, 0.69803923368453979), (0.30672270059585571, 0.69411766529083252, 0.69411766529083252), (0.31092438101768494, 0.69019609689712524, 0.69019609689712524), (0.31512606143951416, 0.68627452850341797, 0.68627452850341797), (0.31932774186134338, 0.68235296010971069, 0.68235296010971069), (0.32352942228317261, 0.67843139171600342, 0.67843139171600342), (0.32773110270500183, 0.67450982332229614, 0.67450982332229614), (0.33193278312683105, 0.67058825492858887, 0.67058825492858887), (0.33613446354866028, 0.66666668653488159, 0.66666668653488159), (0.3403361439704895, 0.66274511814117432, 0.66274511814117432), (0.34453782439231873, 0.65882354974746704, 0.65882354974746704), (0.34873950481414795, 0.65098041296005249, 0.65098041296005249), (0.35294118523597717, 0.64705884456634521, 0.64705884456634521), (0.3571428656578064, 0.64313727617263794, 0.64313727617263794), (0.36134454607963562, 0.63921570777893066, 0.63921570777893066), (0.36554622650146484, 0.63529413938522339, 0.63529413938522339), (0.36974790692329407, 0.63137257099151611, 0.63137257099151611), (0.37394958734512329, 0.62745100259780884, 0.62745100259780884), (0.37815126776695251, 0.62352943420410156, 0.62352943420410156), (0.38235294818878174, 0.61960786581039429, 0.61960786581039429), (0.38655462861061096, 0.61568629741668701, 0.61568629741668701), (0.39075630903244019, 0.61176472902297974, 0.61176472902297974), (0.39495798945426941, 0.60784316062927246, 0.60784316062927246), (0.39915966987609863, 0.60392159223556519, 0.60392159223556519), (0.40336135029792786, 0.60000002384185791, 0.60000002384185791), (0.40756303071975708, 0.59607845544815063, 0.59607845544815063), (0.4117647111415863, 0.58823531866073608, 0.58823531866073608), (0.41596639156341553, 0.58431375026702881, 0.58431375026702881), (0.42016807198524475, 0.58039218187332153, 0.58039218187332153), (0.42436975240707397, 0.57647061347961426, 0.57647061347961426), (0.4285714328289032, 0.57254904508590698, 0.57254904508590698), (0.43277311325073242, 0.56862747669219971, 0.56862747669219971), (0.43697479367256165, 0.56470590829849243, 0.56470590829849243), (0.44117647409439087, 0.56078433990478516, 0.56078433990478516), (0.44537815451622009, 0.55686277151107788, 0.55686277151107788), (0.44957983493804932, 0.55294120311737061, 0.55294120311737061), (0.45378151535987854, 0.54901963472366333, 0.54901963472366333), (0.45798319578170776, 0.54509806632995605, 0.54509806632995605), (0.46218487620353699, 0.54117649793624878, 0.54117649793624878), (0.46638655662536621, 0.5372549295425415, 0.5372549295425415), (0.47058823704719543, 0.53333336114883423, 0.53333336114883423), (0.47478991746902466, 0.52549022436141968, 0.52549022436141968), (0.47899159789085388, 0.5215686559677124, 0.5215686559677124), (0.48319327831268311, 0.51764708757400513, 0.51764708757400513), (0.48739495873451233, 0.51372551918029785, 0.51372551918029785), (0.49159663915634155, 0.50980395078659058, 0.50980395078659058), (0.49579831957817078, 0.5058823823928833, 0.5058823823928833), (0.5, 0.50196081399917603, 0.50196081399917603), (0.50420171022415161, 0.49803921580314636, 0.49803921580314636), (0.50840336084365845, 0.49411764740943909, 0.49411764740943909), (0.51260507106781006, 0.49019607901573181, 0.49019607901573181), (0.51680672168731689, 0.48627451062202454, 0.48627451062202454), (0.52100843191146851, 0.48235294222831726, 0.48235294222831726), (0.52521008253097534, 0.47843137383460999, 0.47843137383460999), (0.52941179275512695, 0.47450980544090271, 0.47450980544090271), (0.53361344337463379, 0.47058823704719543, 0.47058823704719543), (0.5378151535987854, 0.46274510025978088, 0.46274510025978088), (0.54201680421829224, 0.45882353186607361, 0.45882353186607361), (0.54621851444244385, 0.45490196347236633, 0.45490196347236633), (0.55042016506195068, 0.45098039507865906, 0.45098039507865906), (0.55462187528610229, 0.44705882668495178, 0.44705882668495178), (0.55882352590560913, 0.44313725829124451, 0.44313725829124451), (0.56302523612976074, 0.43921568989753723, 0.43921568989753723), (0.56722688674926758, 0.43529412150382996, 0.43529412150382996), (0.57142859697341919, 0.43137255311012268, 0.43137255311012268), (0.57563024759292603, 0.42745098471641541, 0.42745098471641541), (0.57983195781707764, 0.42352941632270813, 0.42352941632270813), (0.58403360843658447, 0.41960784792900085, 0.41960784792900085), (0.58823531866073608, 0.41568627953529358, 0.41568627953529358), (0.59243696928024292, 0.4117647111415863, 0.4117647111415863), (0.59663867950439453, 0.40784314274787903, 0.40784314274787903), (0.60084033012390137, 0.40000000596046448, 0.40000000596046448), (0.60504204034805298, 0.3960784375667572, 0.3960784375667572), (0.60924369096755981, 0.39215686917304993, 0.39215686917304993), (0.61344540119171143, 0.38823530077934265, 0.38823530077934265), (0.61764705181121826, 0.38431373238563538, 0.38431373238563538), (0.62184876203536987, 0.3803921639919281, 0.3803921639919281), (0.62605041265487671, 0.37647059559822083, 0.37647059559822083), (0.63025212287902832, 0.37254902720451355, 0.37254902720451355), (0.63445377349853516, 0.36862745881080627, 0.36862745881080627), (0.63865548372268677, 0.364705890417099, 0.364705890417099), (0.6428571343421936, 0.36078432202339172, 0.36078432202339172), (0.64705884456634521, 0.35686275362968445, 0.35686275362968445), (0.65126049518585205, 0.35294118523597717, 0.35294118523597717), (0.65546220541000366, 0.3490196168422699, 0.3490196168422699), (0.6596638560295105, 0.34509804844856262, 0.34509804844856262), (0.66386556625366211, 0.33725491166114807, 0.33725491166114807), (0.66806721687316895, 0.3333333432674408, 0.3333333432674408), (0.67226892709732056, 0.32941177487373352, 0.32941177487373352), (0.67647057771682739, 0.32549020648002625, 0.32549020648002625), (0.680672287940979, 0.32156863808631897, 0.32156863808631897), (0.68487393856048584, 0.31764706969261169, 0.31764706969261169), (0.68907564878463745, 0.31372550129890442, 0.31372550129890442), (0.69327729940414429, 0.30980393290519714, 0.30980393290519714), (0.6974790096282959, 0.30588236451148987, 0.30588236451148987), (0.70168066024780273, 0.30196079611778259, 0.30196079611778259), (0.70588237047195435, 0.29803922772407532, 0.29803922772407532), (0.71008402109146118, 0.29411765933036804, 0.29411765933036804), (0.71428573131561279, 0.29019609093666077, 0.29019609093666077), (0.71848738193511963, 0.28627452254295349, 0.28627452254295349), (0.72268909215927124, 0.28235295414924622, 0.28235295414924622), (0.72689074277877808, 0.27450981736183167, 0.27450981736183167), (0.73109245300292969, 0.27058824896812439, 0.27058824896812439), (0.73529410362243652, 0.26666668057441711, 0.26666668057441711), (0.73949581384658813, 0.26274511218070984, 0.26274511218070984), (0.74369746446609497, 0.25882354378700256, 0.25882354378700256), (0.74789917469024658, 0.25490197539329529, 0.25490197539329529), (0.75210082530975342, 0.25098040699958801, 0.25098040699958801), (0.75630253553390503, 0.24705882370471954, 0.24705882370471954), (0.76050418615341187, 0.24313725531101227, 0.24313725531101227), (0.76470589637756348, 0.23921568691730499, 0.23921568691730499), (0.76890754699707031, 0.23529411852359772, 0.23529411852359772), (0.77310925722122192, 0.23137255012989044, 0.23137255012989044), (0.77731090784072876, 0.22745098173618317, 0.22745098173618317), (0.78151261806488037, 0.22352941334247589, 0.22352941334247589), (0.78571426868438721, 0.21960784494876862, 0.21960784494876862), (0.78991597890853882, 0.21176470816135406, 0.21176470816135406), (0.79411762952804565, 0.20784313976764679, 0.20784313976764679), (0.79831933975219727, 0.20392157137393951, 0.20392157137393951), (0.8025209903717041, 0.20000000298023224, 0.20000000298023224), (0.80672270059585571, 0.19607843458652496, 0.19607843458652496), (0.81092435121536255, 0.19215686619281769, 0.19215686619281769), (0.81512606143951416, 0.18823529779911041, 0.18823529779911041), (0.819327712059021, 0.18431372940540314, 0.18431372940540314), (0.82352942228317261, 0.18039216101169586, 0.18039216101169586), (0.82773107290267944, 0.17647059261798859, 0.17647059261798859), (0.83193278312683105, 0.17254902422428131, 0.17254902422428131), (0.83613443374633789, 0.16862745583057404, 0.16862745583057404), (0.8403361439704895, 0.16470588743686676, 0.16470588743686676), (0.84453779458999634, 0.16078431904315948, 0.16078431904315948), (0.84873950481414795, 0.15686275064945221, 0.15686275064945221), (0.85294115543365479, 0.14901961386203766, 0.14901961386203766), (0.8571428656578064, 0.14509804546833038, 0.14509804546833038), (0.86134451627731323, 0.14117647707462311, 0.14117647707462311), (0.86554622650146484, 0.13725490868091583, 0.13725490868091583), (0.86974787712097168, 0.13333334028720856, 0.13333334028720856), (0.87394958734512329, 0.12941177189350128, 0.12941177189350128), (0.87815123796463013, 0.12549020349979401, 0.12549020349979401), (0.88235294818878174, 0.12156862765550613, 0.12156862765550613), (0.88655459880828857, 0.11764705926179886, 0.11764705926179886), (0.89075630903244019, 0.11372549086809158, 0.11372549086809158), (0.89495795965194702, 0.10980392247438431, 0.10980392247438431), (0.89915966987609863, 0.10588235408067703, 0.10588235408067703), (0.90336132049560547, 0.10196078568696976, 0.10196078568696976), (0.90756303071975708, 0.098039217293262482, 0.098039217293262482), (0.91176468133926392, 0.094117648899555206, 0.094117648899555206), (0.91596639156341553, 0.086274512112140656, 0.086274512112140656), (0.92016804218292236, 0.08235294371843338, 0.08235294371843338), (0.92436975240707397, 0.078431375324726105, 0.078431375324726105), (0.92857140302658081, 0.074509806931018829, 0.074509806931018829), (0.93277311325073242, 0.070588238537311554, 0.070588238537311554), (0.93697476387023926, 0.066666670143604279, 0.066666670143604279), (0.94117647409439087, 0.062745101749897003, 0.062745101749897003), (0.94537812471389771, 0.058823529630899429, 0.058823529630899429), (0.94957983493804932, 0.054901961237192154, 0.054901961237192154), (0.95378148555755615, 0.050980392843484879, 0.050980392843484879), (0.95798319578170776, 0.047058824449777603, 0.047058824449777603), (0.9621848464012146, 0.043137256056070328, 0.043137256056070328), (0.96638655662536621, 0.039215687662363052, 0.039215687662363052), (0.97058820724487305, 0.035294119268655777, 0.035294119268655777), (0.97478991746902466, 0.031372550874948502, 0.031372550874948502), (0.97899156808853149, 0.023529412224888802, 0.023529412224888802), (0.98319327831268311, 0.019607843831181526, 0.019607843831181526), (0.98739492893218994, 0.015686275437474251, 0.015686275437474251), (0.99159663915634155, 0.011764706112444401, 0.011764706112444401), (0.99579828977584839, 0.0078431377187371254, 0.0078431377187371254), (1.0, 0.0039215688593685627, 0.0039215688593685627)], 'green': [(0.0, 1.0, 1.0), (0.0042016808874905109, 0.99607843160629272, 0.99607843160629272), (0.0084033617749810219, 0.99215686321258545, 0.99215686321258545), (0.012605042196810246, 0.98823529481887817, 0.98823529481887817), (0.016806723549962044, 0.9843137264251709, 0.9843137264251709), (0.021008403971791267, 0.98039215803146362, 0.98039215803146362), (0.025210084393620491, 0.97647058963775635, 0.97647058963775635), (0.029411764815449715, 0.97254902124404907, 0.97254902124404907), (0.033613447099924088, 0.96470588445663452, 0.96470588445663452), (0.037815127521753311, 0.96078431606292725, 0.96078431606292725), (0.042016807943582535, 0.95686274766921997, 0.95686274766921997), (0.046218488365411758, 0.9529411792755127, 0.9529411792755127), (0.050420168787240982, 0.94901961088180542, 0.94901961088180542), (0.054621849209070206, 0.94509804248809814, 0.94509804248809814), (0.058823529630899429, 0.94117647409439087, 0.94117647409439087), (0.063025213778018951, 0.93725490570068359, 0.93725490570068359), (0.067226894199848175, 0.93333333730697632, 0.93333333730697632), (0.071428574621677399, 0.92941176891326904, 0.92941176891326904), (0.075630255043506622, 0.92549020051956177, 0.92549020051956177), (0.079831935465335846, 0.92156863212585449, 0.92156863212585449), (0.08403361588716507, 0.91764706373214722, 0.91764706373214722), (0.088235296308994293, 0.91372549533843994, 0.91372549533843994), (0.092436976730823517, 0.90980392694473267, 0.90980392694473267), (0.09663865715265274, 0.90196079015731812, 0.90196079015731812), (0.10084033757448196, 0.89803922176361084, 0.89803922176361084), (0.10504201799631119, 0.89411765336990356, 0.89411765336990356), (0.10924369841814041, 0.89019608497619629, 0.89019608497619629), (0.11344537883996964, 0.88627451658248901, 0.88627451658248901), (0.11764705926179886, 0.88235294818878174, 0.88235294818878174), (0.12184873968362808, 0.87843137979507446, 0.87843137979507446), (0.1260504275560379, 0.87450981140136719, 0.87450981140136719), (0.13025210797786713, 0.87058824300765991, 0.87058824300765991), (0.13445378839969635, 0.86666667461395264, 0.86666667461395264), (0.13865546882152557, 0.86274510622024536, 0.86274510622024536), (0.1428571492433548, 0.85882353782653809, 0.85882353782653809), (0.14705882966518402, 0.85490196943283081, 0.85490196943283081), (0.15126051008701324, 0.85098040103912354, 0.85098040103912354), (0.15546219050884247, 0.84705883264541626, 0.84705883264541626), (0.15966387093067169, 0.83921569585800171, 0.83921569585800171), (0.16386555135250092, 0.83529412746429443, 0.83529412746429443), (0.16806723177433014, 0.83137255907058716, 0.83137255907058716), (0.17226891219615936, 0.82745099067687988, 0.82745099067687988), (0.17647059261798859, 0.82352942228317261, 0.82352942228317261), (0.18067227303981781, 0.81960785388946533, 0.81960785388946533), (0.18487395346164703, 0.81568628549575806, 0.81568628549575806), (0.18907563388347626, 0.81176471710205078, 0.81176471710205078), (0.19327731430530548, 0.80784314870834351, 0.80784314870834351), (0.1974789947271347, 0.80392158031463623, 0.80392158031463623), (0.20168067514896393, 0.80000001192092896, 0.80000001192092896), (0.20588235557079315, 0.79607844352722168, 0.79607844352722168), (0.21008403599262238, 0.7921568751335144, 0.7921568751335144), (0.2142857164144516, 0.78823530673980713, 0.78823530673980713), (0.21848739683628082, 0.78431373834609985, 0.78431373834609985), (0.22268907725811005, 0.7764706015586853, 0.7764706015586853), (0.22689075767993927, 0.77254903316497803, 0.77254903316497803), (0.23109243810176849, 0.76862746477127075, 0.76862746477127075), (0.23529411852359772, 0.76470589637756348, 0.76470589637756348), (0.23949579894542694, 0.7607843279838562, 0.7607843279838562), (0.24369747936725616, 0.75686275959014893, 0.75686275959014893), (0.24789915978908539, 0.75294119119644165, 0.75294119119644165), (0.25210085511207581, 0.74901962280273438, 0.74901962280273438), (0.25630253553390503, 0.7450980544090271, 0.7450980544090271), (0.26050421595573425, 0.74117648601531982, 0.74117648601531982), (0.26470589637756348, 0.73725491762161255, 0.73725491762161255), (0.2689075767993927, 0.73333334922790527, 0.73333334922790527), (0.27310925722122192, 0.729411780834198, 0.729411780834198), (0.27731093764305115, 0.72549021244049072, 0.72549021244049072), (0.28151261806488037, 0.72156864404678345, 0.72156864404678345), (0.28571429848670959, 0.7137255072593689, 0.7137255072593689), (0.28991597890853882, 0.70980393886566162, 0.70980393886566162), (0.29411765933036804, 0.70588237047195435, 0.70588237047195435), (0.29831933975219727, 0.70196080207824707, 0.70196080207824707), (0.30252102017402649, 0.69803923368453979, 0.69803923368453979), (0.30672270059585571, 0.69411766529083252, 0.69411766529083252), (0.31092438101768494, 0.69019609689712524, 0.69019609689712524), (0.31512606143951416, 0.68627452850341797, 0.68627452850341797), (0.31932774186134338, 0.68235296010971069, 0.68235296010971069), (0.32352942228317261, 0.67843139171600342, 0.67843139171600342), (0.32773110270500183, 0.67450982332229614, 0.67450982332229614), (0.33193278312683105, 0.67058825492858887, 0.67058825492858887), (0.33613446354866028, 0.66666668653488159, 0.66666668653488159), (0.3403361439704895, 0.66274511814117432, 0.66274511814117432), (0.34453782439231873, 0.65882354974746704, 0.65882354974746704), (0.34873950481414795, 0.65098041296005249, 0.65098041296005249), (0.35294118523597717, 0.64705884456634521, 0.64705884456634521), (0.3571428656578064, 0.64313727617263794, 0.64313727617263794), (0.36134454607963562, 0.63921570777893066, 0.63921570777893066), (0.36554622650146484, 0.63529413938522339, 0.63529413938522339), (0.36974790692329407, 0.63137257099151611, 0.63137257099151611), (0.37394958734512329, 0.62745100259780884, 0.62745100259780884), (0.37815126776695251, 0.62352943420410156, 0.62352943420410156), (0.38235294818878174, 0.61960786581039429, 0.61960786581039429), (0.38655462861061096, 0.61568629741668701, 0.61568629741668701), (0.39075630903244019, 0.61176472902297974, 0.61176472902297974), (0.39495798945426941, 0.60784316062927246, 0.60784316062927246), (0.39915966987609863, 0.60392159223556519, 0.60392159223556519), (0.40336135029792786, 0.60000002384185791, 0.60000002384185791), (0.40756303071975708, 0.59607845544815063, 0.59607845544815063), (0.4117647111415863, 0.58823531866073608, 0.58823531866073608), (0.41596639156341553, 0.58431375026702881, 0.58431375026702881), (0.42016807198524475, 0.58039218187332153, 0.58039218187332153), (0.42436975240707397, 0.57647061347961426, 0.57647061347961426), (0.4285714328289032, 0.57254904508590698, 0.57254904508590698), (0.43277311325073242, 0.56862747669219971, 0.56862747669219971), (0.43697479367256165, 0.56470590829849243, 0.56470590829849243), (0.44117647409439087, 0.56078433990478516, 0.56078433990478516), (0.44537815451622009, 0.55686277151107788, 0.55686277151107788), (0.44957983493804932, 0.55294120311737061, 0.55294120311737061), (0.45378151535987854, 0.54901963472366333, 0.54901963472366333), (0.45798319578170776, 0.54509806632995605, 0.54509806632995605), (0.46218487620353699, 0.54117649793624878, 0.54117649793624878), (0.46638655662536621, 0.5372549295425415, 0.5372549295425415), (0.47058823704719543, 0.53333336114883423, 0.53333336114883423), (0.47478991746902466, 0.52549022436141968, 0.52549022436141968), (0.47899159789085388, 0.5215686559677124, 0.5215686559677124), (0.48319327831268311, 0.51764708757400513, 0.51764708757400513), (0.48739495873451233, 0.51372551918029785, 0.51372551918029785), (0.49159663915634155, 0.50980395078659058, 0.50980395078659058), (0.49579831957817078, 0.5058823823928833, 0.5058823823928833), (0.5, 0.50196081399917603, 0.50196081399917603), (0.50420171022415161, 0.49803921580314636, 0.49803921580314636), (0.50840336084365845, 0.49411764740943909, 0.49411764740943909), (0.51260507106781006, 0.49019607901573181, 0.49019607901573181), (0.51680672168731689, 0.48627451062202454, 0.48627451062202454), (0.52100843191146851, 0.48235294222831726, 0.48235294222831726), (0.52521008253097534, 0.47843137383460999, 0.47843137383460999), (0.52941179275512695, 0.47450980544090271, 0.47450980544090271), (0.53361344337463379, 0.47058823704719543, 0.47058823704719543), (0.5378151535987854, 0.46274510025978088, 0.46274510025978088), (0.54201680421829224, 0.45882353186607361, 0.45882353186607361), (0.54621851444244385, 0.45490196347236633, 0.45490196347236633), (0.55042016506195068, 0.45098039507865906, 0.45098039507865906), (0.55462187528610229, 0.44705882668495178, 0.44705882668495178), (0.55882352590560913, 0.44313725829124451, 0.44313725829124451), (0.56302523612976074, 0.43921568989753723, 0.43921568989753723), (0.56722688674926758, 0.43529412150382996, 0.43529412150382996), (0.57142859697341919, 0.43137255311012268, 0.43137255311012268), (0.57563024759292603, 0.42745098471641541, 0.42745098471641541), (0.57983195781707764, 0.42352941632270813, 0.42352941632270813), (0.58403360843658447, 0.41960784792900085, 0.41960784792900085), (0.58823531866073608, 0.41568627953529358, 0.41568627953529358), (0.59243696928024292, 0.4117647111415863, 0.4117647111415863), (0.59663867950439453, 0.40784314274787903, 0.40784314274787903), (0.60084033012390137, 0.40000000596046448, 0.40000000596046448), (0.60504204034805298, 0.3960784375667572, 0.3960784375667572), (0.60924369096755981, 0.39215686917304993, 0.39215686917304993), (0.61344540119171143, 0.38823530077934265, 0.38823530077934265), (0.61764705181121826, 0.38431373238563538, 0.38431373238563538), (0.62184876203536987, 0.3803921639919281, 0.3803921639919281), (0.62605041265487671, 0.37647059559822083, 0.37647059559822083), (0.63025212287902832, 0.37254902720451355, 0.37254902720451355), (0.63445377349853516, 0.36862745881080627, 0.36862745881080627), (0.63865548372268677, 0.364705890417099, 0.364705890417099), (0.6428571343421936, 0.36078432202339172, 0.36078432202339172), (0.64705884456634521, 0.35686275362968445, 0.35686275362968445), (0.65126049518585205, 0.35294118523597717, 0.35294118523597717), (0.65546220541000366, 0.3490196168422699, 0.3490196168422699), (0.6596638560295105, 0.34509804844856262, 0.34509804844856262), (0.66386556625366211, 0.33725491166114807, 0.33725491166114807), (0.66806721687316895, 0.3333333432674408, 0.3333333432674408), (0.67226892709732056, 0.32941177487373352, 0.32941177487373352), (0.67647057771682739, 0.32549020648002625, 0.32549020648002625), (0.680672287940979, 0.32156863808631897, 0.32156863808631897), (0.68487393856048584, 0.31764706969261169, 0.31764706969261169), (0.68907564878463745, 0.31372550129890442, 0.31372550129890442), (0.69327729940414429, 0.30980393290519714, 0.30980393290519714), (0.6974790096282959, 0.30588236451148987, 0.30588236451148987), (0.70168066024780273, 0.30196079611778259, 0.30196079611778259), (0.70588237047195435, 0.29803922772407532, 0.29803922772407532), (0.71008402109146118, 0.29411765933036804, 0.29411765933036804), (0.71428573131561279, 0.29019609093666077, 0.29019609093666077), (0.71848738193511963, 0.28627452254295349, 0.28627452254295349), (0.72268909215927124, 0.28235295414924622, 0.28235295414924622), (0.72689074277877808, 0.27450981736183167, 0.27450981736183167), (0.73109245300292969, 0.27058824896812439, 0.27058824896812439), (0.73529410362243652, 0.26666668057441711, 0.26666668057441711), (0.73949581384658813, 0.26274511218070984, 0.26274511218070984), (0.74369746446609497, 0.25882354378700256, 0.25882354378700256), (0.74789917469024658, 0.25490197539329529, 0.25490197539329529), (0.75210082530975342, 0.25098040699958801, 0.25098040699958801), (0.75630253553390503, 0.24705882370471954, 0.24705882370471954), (0.76050418615341187, 0.24313725531101227, 0.24313725531101227), (0.76470589637756348, 0.23921568691730499, 0.23921568691730499), (0.76890754699707031, 0.23529411852359772, 0.23529411852359772), (0.77310925722122192, 0.23137255012989044, 0.23137255012989044), (0.77731090784072876, 0.22745098173618317, 0.22745098173618317), (0.78151261806488037, 0.22352941334247589, 0.22352941334247589), (0.78571426868438721, 0.21960784494876862, 0.21960784494876862), (0.78991597890853882, 0.21176470816135406, 0.21176470816135406), (0.79411762952804565, 0.20784313976764679, 0.20784313976764679), (0.79831933975219727, 0.20392157137393951, 0.20392157137393951), (0.8025209903717041, 0.20000000298023224, 0.20000000298023224), (0.80672270059585571, 0.19607843458652496, 0.19607843458652496), (0.81092435121536255, 0.19215686619281769, 0.19215686619281769), (0.81512606143951416, 0.18823529779911041, 0.18823529779911041), (0.819327712059021, 0.18431372940540314, 0.18431372940540314), (0.82352942228317261, 0.18039216101169586, 0.18039216101169586), (0.82773107290267944, 0.17647059261798859, 0.17647059261798859), (0.83193278312683105, 0.17254902422428131, 0.17254902422428131), (0.83613443374633789, 0.16862745583057404, 0.16862745583057404), (0.8403361439704895, 0.16470588743686676, 0.16470588743686676), (0.84453779458999634, 0.16078431904315948, 0.16078431904315948), (0.84873950481414795, 0.15686275064945221, 0.15686275064945221), (0.85294115543365479, 0.14901961386203766, 0.14901961386203766), (0.8571428656578064, 0.14509804546833038, 0.14509804546833038), (0.86134451627731323, 0.14117647707462311, 0.14117647707462311), (0.86554622650146484, 0.13725490868091583, 0.13725490868091583), (0.86974787712097168, 0.13333334028720856, 0.13333334028720856), (0.87394958734512329, 0.12941177189350128, 0.12941177189350128), (0.87815123796463013, 0.12549020349979401, 0.12549020349979401), (0.88235294818878174, 0.12156862765550613, 0.12156862765550613), (0.88655459880828857, 0.11764705926179886, 0.11764705926179886), (0.89075630903244019, 0.11372549086809158, 0.11372549086809158), (0.89495795965194702, 0.10980392247438431, 0.10980392247438431), (0.89915966987609863, 0.10588235408067703, 0.10588235408067703), (0.90336132049560547, 0.10196078568696976, 0.10196078568696976), (0.90756303071975708, 0.098039217293262482, 0.098039217293262482), (0.91176468133926392, 0.094117648899555206, 0.094117648899555206), (0.91596639156341553, 0.086274512112140656, 0.086274512112140656), (0.92016804218292236, 0.08235294371843338, 0.08235294371843338), (0.92436975240707397, 0.078431375324726105, 0.078431375324726105), (0.92857140302658081, 0.074509806931018829, 0.074509806931018829), (0.93277311325073242, 0.070588238537311554, 0.070588238537311554), (0.93697476387023926, 0.066666670143604279, 0.066666670143604279), (0.94117647409439087, 0.062745101749897003, 0.062745101749897003), (0.94537812471389771, 0.058823529630899429, 0.058823529630899429), (0.94957983493804932, 0.054901961237192154, 0.054901961237192154), (0.95378148555755615, 0.050980392843484879, 0.050980392843484879), (0.95798319578170776, 0.047058824449777603, 0.047058824449777603), (0.9621848464012146, 0.043137256056070328, 0.043137256056070328), (0.96638655662536621, 0.039215687662363052, 0.039215687662363052), (0.97058820724487305, 0.035294119268655777, 0.035294119268655777), (0.97478991746902466, 0.031372550874948502, 0.031372550874948502), (0.97899156808853149, 0.023529412224888802, 0.023529412224888802), (0.98319327831268311, 0.019607843831181526, 0.019607843831181526), (0.98739492893218994, 0.015686275437474251, 0.015686275437474251), (0.99159663915634155, 0.011764706112444401, 0.011764706112444401), (0.99579828977584839, 0.0078431377187371254, 0.0078431377187371254), (1.0, 0.0039215688593685627, 0.0039215688593685627)], 'red': [(0.0, 1.0, 1.0), (0.0042016808874905109, 0.99607843160629272, 0.99607843160629272), (0.0084033617749810219, 0.99215686321258545, 0.99215686321258545), (0.012605042196810246, 0.98823529481887817, 0.98823529481887817), (0.016806723549962044, 0.9843137264251709, 0.9843137264251709), (0.021008403971791267, 0.98039215803146362, 0.98039215803146362), (0.025210084393620491, 0.97647058963775635, 0.97647058963775635), (0.029411764815449715, 0.97254902124404907, 0.97254902124404907), (0.033613447099924088, 0.96470588445663452, 0.96470588445663452), (0.037815127521753311, 0.96078431606292725, 0.96078431606292725), (0.042016807943582535, 0.95686274766921997, 0.95686274766921997), (0.046218488365411758, 0.9529411792755127, 0.9529411792755127), (0.050420168787240982, 0.94901961088180542, 0.94901961088180542), (0.054621849209070206, 0.94509804248809814, 0.94509804248809814), (0.058823529630899429, 0.94117647409439087, 0.94117647409439087), (0.063025213778018951, 0.93725490570068359, 0.93725490570068359), (0.067226894199848175, 0.93333333730697632, 0.93333333730697632), (0.071428574621677399, 0.92941176891326904, 0.92941176891326904), (0.075630255043506622, 0.92549020051956177, 0.92549020051956177), (0.079831935465335846, 0.92156863212585449, 0.92156863212585449), (0.08403361588716507, 0.91764706373214722, 0.91764706373214722), (0.088235296308994293, 0.91372549533843994, 0.91372549533843994), (0.092436976730823517, 0.90980392694473267, 0.90980392694473267), (0.09663865715265274, 0.90196079015731812, 0.90196079015731812), (0.10084033757448196, 0.89803922176361084, 0.89803922176361084), (0.10504201799631119, 0.89411765336990356, 0.89411765336990356), (0.10924369841814041, 0.89019608497619629, 0.89019608497619629), (0.11344537883996964, 0.88627451658248901, 0.88627451658248901), (0.11764705926179886, 0.88235294818878174, 0.88235294818878174), (0.12184873968362808, 0.87843137979507446, 0.87843137979507446), (0.1260504275560379, 0.87450981140136719, 0.87450981140136719), (0.13025210797786713, 0.87058824300765991, 0.87058824300765991), (0.13445378839969635, 0.86666667461395264, 0.86666667461395264), (0.13865546882152557, 0.86274510622024536, 0.86274510622024536), (0.1428571492433548, 0.85882353782653809, 0.85882353782653809), (0.14705882966518402, 0.85490196943283081, 0.85490196943283081), (0.15126051008701324, 0.85098040103912354, 0.85098040103912354), (0.15546219050884247, 0.84705883264541626, 0.84705883264541626), (0.15966387093067169, 0.83921569585800171, 0.83921569585800171), (0.16386555135250092, 0.83529412746429443, 0.83529412746429443), (0.16806723177433014, 0.83137255907058716, 0.83137255907058716), (0.17226891219615936, 0.82745099067687988, 0.82745099067687988), (0.17647059261798859, 0.82352942228317261, 0.82352942228317261), (0.18067227303981781, 0.81960785388946533, 0.81960785388946533), (0.18487395346164703, 0.81568628549575806, 0.81568628549575806), (0.18907563388347626, 0.81176471710205078, 0.81176471710205078), (0.19327731430530548, 0.80784314870834351, 0.80784314870834351), (0.1974789947271347, 0.80392158031463623, 0.80392158031463623), (0.20168067514896393, 0.80000001192092896, 0.80000001192092896), (0.20588235557079315, 0.79607844352722168, 0.79607844352722168), (0.21008403599262238, 0.7921568751335144, 0.7921568751335144), (0.2142857164144516, 0.78823530673980713, 0.78823530673980713), (0.21848739683628082, 0.78431373834609985, 0.78431373834609985), (0.22268907725811005, 0.7764706015586853, 0.7764706015586853), (0.22689075767993927, 0.77254903316497803, 0.77254903316497803), (0.23109243810176849, 0.76862746477127075, 0.76862746477127075), (0.23529411852359772, 0.76470589637756348, 0.76470589637756348), (0.23949579894542694, 0.7607843279838562, 0.7607843279838562), (0.24369747936725616, 0.75686275959014893, 0.75686275959014893), (0.24789915978908539, 0.75294119119644165, 0.75294119119644165), (0.25210085511207581, 0.74901962280273438, 0.74901962280273438), (0.25630253553390503, 0.7450980544090271, 0.7450980544090271), (0.26050421595573425, 0.74117648601531982, 0.74117648601531982), (0.26470589637756348, 0.73725491762161255, 0.73725491762161255), (0.2689075767993927, 0.73333334922790527, 0.73333334922790527), (0.27310925722122192, 0.729411780834198, 0.729411780834198), (0.27731093764305115, 0.72549021244049072, 0.72549021244049072), (0.28151261806488037, 0.72156864404678345, 0.72156864404678345), (0.28571429848670959, 0.7137255072593689, 0.7137255072593689), (0.28991597890853882, 0.70980393886566162, 0.70980393886566162), (0.29411765933036804, 0.70588237047195435, 0.70588237047195435), (0.29831933975219727, 0.70196080207824707, 0.70196080207824707), (0.30252102017402649, 0.69803923368453979, 0.69803923368453979), (0.30672270059585571, 0.69411766529083252, 0.69411766529083252), (0.31092438101768494, 0.69019609689712524, 0.69019609689712524), (0.31512606143951416, 0.68627452850341797, 0.68627452850341797), (0.31932774186134338, 0.68235296010971069, 0.68235296010971069), (0.32352942228317261, 0.67843139171600342, 0.67843139171600342), (0.32773110270500183, 0.67450982332229614, 0.67450982332229614), (0.33193278312683105, 0.67058825492858887, 0.67058825492858887), (0.33613446354866028, 0.66666668653488159, 0.66666668653488159), (0.3403361439704895, 0.66274511814117432, 0.66274511814117432), (0.34453782439231873, 0.65882354974746704, 0.65882354974746704), (0.34873950481414795, 0.65098041296005249, 0.65098041296005249), (0.35294118523597717, 0.64705884456634521, 0.64705884456634521), (0.3571428656578064, 0.64313727617263794, 0.64313727617263794), (0.36134454607963562, 0.63921570777893066, 0.63921570777893066), (0.36554622650146484, 0.63529413938522339, 0.63529413938522339), (0.36974790692329407, 0.63137257099151611, 0.63137257099151611), (0.37394958734512329, 0.62745100259780884, 0.62745100259780884), (0.37815126776695251, 0.62352943420410156, 0.62352943420410156), (0.38235294818878174, 0.61960786581039429, 0.61960786581039429), (0.38655462861061096, 0.61568629741668701, 0.61568629741668701), (0.39075630903244019, 0.61176472902297974, 0.61176472902297974), (0.39495798945426941, 0.60784316062927246, 0.60784316062927246), (0.39915966987609863, 0.60392159223556519, 0.60392159223556519), (0.40336135029792786, 0.60000002384185791, 0.60000002384185791), (0.40756303071975708, 0.59607845544815063, 0.59607845544815063), (0.4117647111415863, 0.58823531866073608, 0.58823531866073608), (0.41596639156341553, 0.58431375026702881, 0.58431375026702881), (0.42016807198524475, 0.58039218187332153, 0.58039218187332153), (0.42436975240707397, 0.57647061347961426, 0.57647061347961426), (0.4285714328289032, 0.57254904508590698, 0.57254904508590698), (0.43277311325073242, 0.56862747669219971, 0.56862747669219971), (0.43697479367256165, 0.56470590829849243, 0.56470590829849243), (0.44117647409439087, 0.56078433990478516, 0.56078433990478516), (0.44537815451622009, 0.55686277151107788, 0.55686277151107788), (0.44957983493804932, 0.55294120311737061, 0.55294120311737061), (0.45378151535987854, 0.54901963472366333, 0.54901963472366333), (0.45798319578170776, 0.54509806632995605, 0.54509806632995605), (0.46218487620353699, 0.54117649793624878, 0.54117649793624878), (0.46638655662536621, 0.5372549295425415, 0.5372549295425415), (0.47058823704719543, 0.53333336114883423, 0.53333336114883423), (0.47478991746902466, 0.52549022436141968, 0.52549022436141968), (0.47899159789085388, 0.5215686559677124, 0.5215686559677124), (0.48319327831268311, 0.51764708757400513, 0.51764708757400513), (0.48739495873451233, 0.51372551918029785, 0.51372551918029785), (0.49159663915634155, 0.50980395078659058, 0.50980395078659058), (0.49579831957817078, 0.5058823823928833, 0.5058823823928833), (0.5, 0.50196081399917603, 0.50196081399917603), (0.50420171022415161, 0.49803921580314636, 0.49803921580314636), (0.50840336084365845, 0.49411764740943909, 0.49411764740943909), (0.51260507106781006, 0.49019607901573181, 0.49019607901573181), (0.51680672168731689, 0.48627451062202454, 0.48627451062202454), (0.52100843191146851, 0.48235294222831726, 0.48235294222831726), (0.52521008253097534, 0.47843137383460999, 0.47843137383460999), (0.52941179275512695, 0.47450980544090271, 0.47450980544090271), (0.53361344337463379, 0.47058823704719543, 0.47058823704719543), (0.5378151535987854, 0.46274510025978088, 0.46274510025978088), (0.54201680421829224, 0.45882353186607361, 0.45882353186607361), (0.54621851444244385, 0.45490196347236633, 0.45490196347236633), (0.55042016506195068, 0.45098039507865906, 0.45098039507865906), (0.55462187528610229, 0.44705882668495178, 0.44705882668495178), (0.55882352590560913, 0.44313725829124451, 0.44313725829124451), (0.56302523612976074, 0.43921568989753723, 0.43921568989753723), (0.56722688674926758, 0.43529412150382996, 0.43529412150382996), (0.57142859697341919, 0.43137255311012268, 0.43137255311012268), (0.57563024759292603, 0.42745098471641541, 0.42745098471641541), (0.57983195781707764, 0.42352941632270813, 0.42352941632270813), (0.58403360843658447, 0.41960784792900085, 0.41960784792900085), (0.58823531866073608, 0.41568627953529358, 0.41568627953529358), (0.59243696928024292, 0.4117647111415863, 0.4117647111415863), (0.59663867950439453, 0.40784314274787903, 0.40784314274787903), (0.60084033012390137, 0.40000000596046448, 0.40000000596046448), (0.60504204034805298, 0.3960784375667572, 0.3960784375667572), (0.60924369096755981, 0.39215686917304993, 0.39215686917304993), (0.61344540119171143, 0.38823530077934265, 0.38823530077934265), (0.61764705181121826, 0.38431373238563538, 0.38431373238563538), (0.62184876203536987, 0.3803921639919281, 0.3803921639919281), (0.62605041265487671, 0.37647059559822083, 0.37647059559822083), (0.63025212287902832, 0.37254902720451355, 0.37254902720451355), (0.63445377349853516, 0.36862745881080627, 0.36862745881080627), (0.63865548372268677, 0.364705890417099, 0.364705890417099), (0.6428571343421936, 0.36078432202339172, 0.36078432202339172), (0.64705884456634521, 0.35686275362968445, 0.35686275362968445), (0.65126049518585205, 0.35294118523597717, 0.35294118523597717), (0.65546220541000366, 0.3490196168422699, 0.3490196168422699), (0.6596638560295105, 0.34509804844856262, 0.34509804844856262), (0.66386556625366211, 0.33725491166114807, 0.33725491166114807), (0.66806721687316895, 0.3333333432674408, 0.3333333432674408), (0.67226892709732056, 0.32941177487373352, 0.32941177487373352), (0.67647057771682739, 0.32549020648002625, 0.32549020648002625), (0.680672287940979, 0.32156863808631897, 0.32156863808631897), (0.68487393856048584, 0.31764706969261169, 0.31764706969261169), (0.68907564878463745, 0.31372550129890442, 0.31372550129890442), (0.69327729940414429, 0.30980393290519714, 0.30980393290519714), (0.6974790096282959, 0.30588236451148987, 0.30588236451148987), (0.70168066024780273, 0.30196079611778259, 0.30196079611778259), (0.70588237047195435, 0.29803922772407532, 0.29803922772407532), (0.71008402109146118, 0.29411765933036804, 0.29411765933036804), (0.71428573131561279, 0.29019609093666077, 0.29019609093666077), (0.71848738193511963, 0.28627452254295349, 0.28627452254295349), (0.72268909215927124, 0.28235295414924622, 0.28235295414924622), (0.72689074277877808, 0.27450981736183167, 0.27450981736183167), (0.73109245300292969, 0.27058824896812439, 0.27058824896812439), (0.73529410362243652, 0.26666668057441711, 0.26666668057441711), (0.73949581384658813, 0.26274511218070984, 0.26274511218070984), (0.74369746446609497, 0.25882354378700256, 0.25882354378700256), (0.74789917469024658, 0.25490197539329529, 0.25490197539329529), (0.75210082530975342, 0.25098040699958801, 0.25098040699958801), (0.75630253553390503, 0.24705882370471954, 0.24705882370471954), (0.76050418615341187, 0.24313725531101227, 0.24313725531101227), (0.76470589637756348, 0.23921568691730499, 0.23921568691730499), (0.76890754699707031, 0.23529411852359772, 0.23529411852359772), (0.77310925722122192, 0.23137255012989044, 0.23137255012989044), (0.77731090784072876, 0.22745098173618317, 0.22745098173618317), (0.78151261806488037, 0.22352941334247589, 0.22352941334247589), (0.78571426868438721, 0.21960784494876862, 0.21960784494876862), (0.78991597890853882, 0.21176470816135406, 0.21176470816135406), (0.79411762952804565, 0.20784313976764679, 0.20784313976764679), (0.79831933975219727, 0.20392157137393951, 0.20392157137393951), (0.8025209903717041, 0.20000000298023224, 0.20000000298023224), (0.80672270059585571, 0.19607843458652496, 0.19607843458652496), (0.81092435121536255, 0.19215686619281769, 0.19215686619281769), (0.81512606143951416, 0.18823529779911041, 0.18823529779911041), (0.819327712059021, 0.18431372940540314, 0.18431372940540314), (0.82352942228317261, 0.18039216101169586, 0.18039216101169586), (0.82773107290267944, 0.17647059261798859, 0.17647059261798859), (0.83193278312683105, 0.17254902422428131, 0.17254902422428131), (0.83613443374633789, 0.16862745583057404, 0.16862745583057404), (0.8403361439704895, 0.16470588743686676, 0.16470588743686676), (0.84453779458999634, 0.16078431904315948, 0.16078431904315948), (0.84873950481414795, 0.15686275064945221, 0.15686275064945221), (0.85294115543365479, 0.14901961386203766, 0.14901961386203766), (0.8571428656578064, 0.14509804546833038, 0.14509804546833038), (0.86134451627731323, 0.14117647707462311, 0.14117647707462311), (0.86554622650146484, 0.13725490868091583, 0.13725490868091583), (0.86974787712097168, 0.13333334028720856, 0.13333334028720856), (0.87394958734512329, 0.12941177189350128, 0.12941177189350128), (0.87815123796463013, 0.12549020349979401, 0.12549020349979401), (0.88235294818878174, 0.12156862765550613, 0.12156862765550613), (0.88655459880828857, 0.11764705926179886, 0.11764705926179886), (0.89075630903244019, 0.11372549086809158, 0.11372549086809158), (0.89495795965194702, 0.10980392247438431, 0.10980392247438431), (0.89915966987609863, 0.10588235408067703, 0.10588235408067703), (0.90336132049560547, 0.10196078568696976, 0.10196078568696976), (0.90756303071975708, 0.098039217293262482, 0.098039217293262482), (0.91176468133926392, 0.094117648899555206, 0.094117648899555206), (0.91596639156341553, 0.086274512112140656, 0.086274512112140656), (0.92016804218292236, 0.08235294371843338, 0.08235294371843338), (0.92436975240707397, 0.078431375324726105, 0.078431375324726105), (0.92857140302658081, 0.074509806931018829, 0.074509806931018829), (0.93277311325073242, 0.070588238537311554, 0.070588238537311554), (0.93697476387023926, 0.066666670143604279, 0.066666670143604279), (0.94117647409439087, 0.062745101749897003, 0.062745101749897003), (0.94537812471389771, 0.058823529630899429, 0.058823529630899429), (0.94957983493804932, 0.054901961237192154, 0.054901961237192154), (0.95378148555755615, 0.050980392843484879, 0.050980392843484879), (0.95798319578170776, 0.047058824449777603, 0.047058824449777603), (0.9621848464012146, 0.043137256056070328, 0.043137256056070328), (0.96638655662536621, 0.039215687662363052, 0.039215687662363052), (0.97058820724487305, 0.035294119268655777, 0.035294119268655777), (0.97478991746902466, 0.031372550874948502, 0.031372550874948502), (0.97899156808853149, 0.023529412224888802, 0.023529412224888802), (0.98319327831268311, 0.019607843831181526, 0.019607843831181526), (0.98739492893218994, 0.015686275437474251, 0.015686275437474251), (0.99159663915634155, 0.011764706112444401, 0.011764706112444401), (0.99579828977584839, 0.0078431377187371254, 0.0078431377187371254), (1.0, 0.0039215688593685627, 0.0039215688593685627)]} Accent = colors.LinearSegmentedColormap('Accent', _Accent_data, LUTSIZE) Blues = colors.LinearSegmentedColormap('Blues', _Blues_data, LUTSIZE) BrBG = colors.LinearSegmentedColormap('BrBG', _BrBG_data, LUTSIZE) BuGn = colors.LinearSegmentedColormap('BuGn', _BuGn_data, LUTSIZE) BuPu = colors.LinearSegmentedColormap('BuPu', _BuPu_data, LUTSIZE) Dark2 = colors.LinearSegmentedColormap('Dark2', _Dark2_data, LUTSIZE) GnBu = colors.LinearSegmentedColormap('GnBu', _GnBu_data, LUTSIZE) Greens = colors.LinearSegmentedColormap('Greens', _Greens_data, LUTSIZE) Greys = colors.LinearSegmentedColormap('Greys', _Greys_data, LUTSIZE) Oranges = colors.LinearSegmentedColormap('Oranges', _Oranges_data, LUTSIZE) OrRd = colors.LinearSegmentedColormap('OrRd', _OrRd_data, LUTSIZE) Paired = colors.LinearSegmentedColormap('Paired', _Paired_data, LUTSIZE) Pastel1 = colors.LinearSegmentedColormap('Pastel1', _Pastel1_data, LUTSIZE) Pastel2 = colors.LinearSegmentedColormap('Pastel2', _Pastel2_data, LUTSIZE) PiYG = colors.LinearSegmentedColormap('PiYG', _PiYG_data, LUTSIZE) PRGn = colors.LinearSegmentedColormap('PRGn', _PRGn_data, LUTSIZE) PuBu = colors.LinearSegmentedColormap('PuBu', _PuBu_data, LUTSIZE) PuBuGn = colors.LinearSegmentedColormap('PuBuGn', _PuBuGn_data, LUTSIZE) PuOr = colors.LinearSegmentedColormap('PuOr', _PuOr_data, LUTSIZE) PuRd = colors.LinearSegmentedColormap('PuRd', _PuRd_data, LUTSIZE) Purples = colors.LinearSegmentedColormap('Purples', _Purples_data, LUTSIZE) RdBu = colors.LinearSegmentedColormap('RdBu', _RdBu_data, LUTSIZE) RdGy = colors.LinearSegmentedColormap('RdGy', _RdGy_data, LUTSIZE) RdPu = colors.LinearSegmentedColormap('RdPu', _RdPu_data, LUTSIZE) RdYlBu = colors.LinearSegmentedColormap('RdYlBu', _RdYlBu_data, LUTSIZE) RdYlGn = colors.LinearSegmentedColormap('RdYlGn', _RdYlGn_data, LUTSIZE) Reds = colors.LinearSegmentedColormap('Reds', _Reds_data, LUTSIZE) Set1 = colors.LinearSegmentedColormap('Set1', _Set1_data, LUTSIZE) Set2 = colors.LinearSegmentedColormap('Set2', _Set2_data, LUTSIZE) Set3 = colors.LinearSegmentedColormap('Set3', _Set3_data, LUTSIZE) Spectral = colors.LinearSegmentedColormap('Spectral', _Spectral_data, LUTSIZE) YlGn = colors.LinearSegmentedColormap('YlGn', _YlGn_data, LUTSIZE) YlGnBu = colors.LinearSegmentedColormap('YlGnBu', _YlGnBu_data, LUTSIZE) YlOrBr = colors.LinearSegmentedColormap('YlOrBr', _YlOrBr_data, LUTSIZE) YlOrRd = colors.LinearSegmentedColormap('YlOrRd', _YlOrRd_data, LUTSIZE) gist_earth = colors.LinearSegmentedColormap('gist_earth', _gist_earth_data, LUTSIZE) gist_gray = colors.LinearSegmentedColormap('gist_gray', _gist_gray_data, LUTSIZE) gist_heat = colors.LinearSegmentedColormap('gist_heat', _gist_heat_data, LUTSIZE) gist_ncar = colors.LinearSegmentedColormap('gist_ncar', _gist_ncar_data, LUTSIZE) gist_rainbow = colors.LinearSegmentedColormap('gist_rainbow', _gist_rainbow_data, LUTSIZE) gist_stern = colors.LinearSegmentedColormap('gist_stern', _gist_stern_data, LUTSIZE) gist_yarg = colors.LinearSegmentedColormap('gist_yarg', _gist_yarg_data, LUTSIZE) datad['Accent']=_Accent_data datad['Blues']=_Blues_data datad['BrBG']=_BrBG_data datad['BuGn']=_BuGn_data datad['BuPu']=_BuPu_data datad['Dark2']=_Dark2_data datad['GnBu']=_GnBu_data datad['Greens']=_Greens_data datad['Greys']=_Greys_data datad['Oranges']=_Oranges_data datad['OrRd']=_OrRd_data datad['Paired']=_Paired_data datad['Pastel1']=_Pastel1_data datad['Pastel2']=_Pastel2_data datad['PiYG']=_PiYG_data datad['PRGn']=_PRGn_data datad['PuBu']=_PuBu_data datad['PuBuGn']=_PuBuGn_data datad['PuOr']=_PuOr_data datad['PuRd']=_PuRd_data datad['Purples']=_Purples_data datad['RdBu']=_RdBu_data datad['RdGy']=_RdGy_data datad['RdPu']=_RdPu_data datad['RdYlBu']=_RdYlBu_data datad['RdYlGn']=_RdYlGn_data datad['Reds']=_Reds_data datad['Set1']=_Set1_data datad['Set2']=_Set2_data datad['Set3']=_Set3_data datad['Spectral']=_Spectral_data datad['YlGn']=_YlGn_data datad['YlGnBu']=_YlGnBu_data datad['YlOrBr']=_YlOrBr_data datad['YlOrRd']=_YlOrRd_data datad['gist_earth']=_gist_earth_data datad['gist_gray']=_gist_gray_data datad['gist_heat']=_gist_heat_data datad['gist_ncar']=_gist_ncar_data datad['gist_rainbow']=_gist_rainbow_data datad['gist_stern']=_gist_stern_data datad['gist_yarg']=_gist_yarg_data # reverse all the colormaps. # reversed colormaps have '_r' appended to the name. def revcmap(data): data_r = {} for key, val in data.iteritems(): valnew = [(1.-a, b, c) for a, b, c in reversed(val)] data_r[key] = valnew return data_r cmapnames = datad.keys() for cmapname in cmapnames: cmapname_r = cmapname+'_r' cmapdat_r = revcmap(datad[cmapname]) datad[cmapname_r] = cmapdat_r locals()[cmapname_r] = colors.LinearSegmentedColormap(cmapname_r, cmapdat_r, LUTSIZE)
agpl-3.0
ray-project/ray
python/ray/experimental/data/impl/arrow_block.py
1
5133
import collections from typing import Iterator, List, Union, Tuple, Any, TypeVar, TYPE_CHECKING try: import pyarrow except ImportError: pyarrow = None from ray.experimental.data.impl.block import Block, BlockBuilder, \ SimpleBlockBuilder if TYPE_CHECKING: import pandas T = TypeVar("T") class ArrowRow: def __init__(self, row: "pyarrow.Table"): self._row = row def as_pydict(self) -> dict: return {k: v[0] for k, v in self._row.to_pydict().items()} def keys(self) -> Iterator[str]: return self.as_pydict().keys() def values(self) -> Iterator[Any]: return self.as_pydict().values() def items(self) -> Iterator[Tuple[str, Any]]: return self.as_pydict().items() def __getitem__(self, key: str) -> Any: return self._row[key][0].as_py() def __eq__(self, other: Any) -> bool: return self.as_pydict() == other def __str__(self): return "ArrowRow({})".format(self.as_pydict()) def __repr__(self): return str(self) class DelegatingArrowBlockBuilder(BlockBuilder[T]): def __init__(self): self._builder = None def add(self, item: Any) -> None: if self._builder is None: if isinstance(item, dict): try: check = ArrowBlockBuilder() check.add(item) check.build() self._builder = ArrowBlockBuilder() except (TypeError, pyarrow.lib.ArrowInvalid): self._builder = SimpleBlockBuilder() else: self._builder = SimpleBlockBuilder() self._builder.add(item) def add_block(self, block: Block[T]) -> None: if self._builder is None: self._builder = block.builder() self._builder.add_block(block) def build(self) -> Block[T]: if self._builder is None: self._builder = ArrowBlockBuilder() return self._builder.build() def num_rows(self) -> int: return self._builder.num_rows() if self._builder is not None else 0 class ArrowBlockBuilder(BlockBuilder[T]): def __init__(self): if pyarrow is None: raise ImportError("Run `pip install pyarrow` for Arrow support") self._columns = collections.defaultdict(list) self._tables: List["pyarrow.Table"] = [] self._num_rows = 0 def add(self, item: Union[dict, ArrowRow]) -> None: if isinstance(item, ArrowRow): item = item.as_pydict() if not isinstance(item, dict): raise ValueError( "Returned elements of an ArrowBlock must be of type `dict`, " "got {} (type {}).".format(item, type(item))) for key, value in item.items(): self._columns[key].append(value) self._num_rows += 1 def add_block(self, block: "ArrowBlock[T]") -> None: self._tables.append(block._table) self._num_rows += block.num_rows() def build(self) -> "ArrowBlock[T]": if self._columns: tables = [pyarrow.Table.from_pydict(self._columns)] else: tables = [] tables.extend(self._tables) if len(tables) > 1: return ArrowBlock(pyarrow.concat_tables(tables)) elif len(tables) > 0: return ArrowBlock(tables[0]) else: return ArrowBlock(pyarrow.Table.from_pydict({})) def num_rows(self) -> int: return self._num_rows class ArrowBlock(Block): def __init__(self, table: "pyarrow.Table"): if pyarrow is None: raise ImportError("Run `pip install pyarrow` for Arrow support") self._table = table def iter_rows(self) -> Iterator[ArrowRow]: outer = self class Iter: def __init__(self): self._cur = -1 def __iter__(self): return self def __next__(self): self._cur += 1 if self._cur < outer._table.num_rows: row = ArrowRow(outer._table.slice(self._cur, 1)) return row raise StopIteration return Iter() def slice(self, start: int, end: int, copy: bool) -> "ArrowBlock[T]": view = self._table.slice(start, end - start) if copy: # TODO(ekl) there must be a cleaner way to force a copy of a table. copy = [c.to_pandas() for c in view.itercolumns()] return ArrowBlock( pyarrow.Table.from_arrays(copy, schema=self._table.schema)) else: return ArrowBlock(view) def schema(self) -> "pyarrow.lib.Schema": return self._table.schema def to_pandas(self) -> "pandas.DataFrame": return self._table.to_pandas() def to_arrow_table(self) -> "pyarrow.Table": return self._table def num_rows(self) -> int: return self._table.num_rows def size_bytes(self) -> int: return self._table.nbytes @staticmethod def builder() -> ArrowBlockBuilder[T]: return ArrowBlockBuilder()
apache-2.0
cdeboever3/cdpybio
cdpybio/analysis.py
1
43419
import pandas as pd chrom_sizes = pd.Series( {1: 249250621, 10: 135534747, 11: 135006516, 12: 133851895, 13: 115169878, 14: 107349540, 15: 102531392, 16: 90354753, 17: 81195210, 18: 78077248, 19: 59128983, 2: 243199373, 20: 63025520, 21: 48129895, 22: 51304566, 3: 198022430, 4: 191154276, 5: 180915260, 6: 171115067, 7: 159138663, 8: 146364022, 9: 141213431, } ) chrom_sizes_norm = chrom_sizes / chrom_sizes.max() def _make_tableau20(): # tableau20 from # http://www.randalolson.com/2014/06/28/how-to-make-beautiful-data-visualizations-in-python-with-matplotlib/ tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] # Scale the RGB values to the [0, 1] range, which is the format matplotlib # accepts. for i in range(len(tableau20)): r, g, b = tableau20[i] tableau20[i] = (r / 255., g / 255., b / 255.) return tableau20 tableau20 = _make_tableau20() def generate_null_snvs(df, snvs, num_null_sets=5): """ Generate a set of null SNVs based on an input list of SNVs and categorical annotations. Parameters ---------- df : pandas.DataFrame Pandas dataframe where each column is a categorization of SNPs. The index should be SNPs of the form chrom:pos. snvs : list List of input SNVs in the format chrom:pos. Entries that aren't in the index of df will be dropped. num_null_sets : int Number of sets of null SNVs to generate. Returns ------- null_sets : pandas.Dataframe Pandas dataframe with input SNVs as first column and null SNVs as following columns. """ import numpy as np import random random.seed(20151007) input_snvs = list(set(df.index) & set(snvs)) sig = df.ix[input_snvs] not_sig = df.ix[set(df.index) - set(snvs)] sig['group'] = sig.apply(lambda x: '::'.join(x), axis=1) not_sig['group'] = not_sig.apply(lambda x: '::'.join(x), axis=1) null_sets = [] vc = sig.group.value_counts() bins = {c:sorted(list(df[c].value_counts().index)) for c in df.columns} ordered_inputs = [] for i in vc.index: ordered_inputs += list(sig[sig.group == i].index) tdf = not_sig[not_sig.group == i] count = vc[i] for n in xrange(num_null_sets): if tdf.shape[0] == 0: groups = [i] while tdf.shape[0] == 0: # If there are no potential null SNVs in this group, we'll # expand the group randomly. g = groups[-1] # Choose random bin. cols = list(not_sig.columns) cols.remove('group') b = random.choice(cols) # Get possibilities for that bin. t = bins[b] # Get last set of bin values and the value for the bin we # want to change. d = dict(zip(not_sig.columns, g.split('::'))) cat = d[b] # Randomly walk away from bin value. ind = t.index(cat) if ind == 0: ind += 1 elif ind == len(t) - 1: ind -= 1 else: ind += random.choice([-1, 1]) d[b] = t[ind] groups.append('::'.join(pd.Series(d)[not_sig.columns].astype(str))) tdf = not_sig[not_sig.group.apply(lambda x: x in groups)] if count <= tdf.shape[0]: ind = random.sample(tdf.index, count) else: ind = list(np.random.choice(tdf.index, size=count, replace=True)) if i == vc.index[0]: null_sets.append(ind) else: null_sets[n] += ind null_sets = pd.DataFrame(null_sets).T null_sets.columns = ['null_{}'.format(x) for x in null_sets.columns] cs = list(null_sets.columns) null_sets['input'] = ordered_inputs null_sets = null_sets[['input'] + cs] return null_sets def make_grasp_phenotype_file(fn, pheno, out): """ Subset the GRASP database on a specific phenotype. Parameters ---------- fn : str Path to GRASP database file. pheno : str Phenotype to extract from database. out : sttr Path to output file for subset of GRASP database. """ import subprocess c = 'awk -F "\\t" \'NR == 1 || $12 == "{}" \' {} > {}'.format( pheno.replace("'", '\\x27'), fn, out) subprocess.check_call(c, shell=True) def parse_grasp_gwas(fn): """ Read GRASP database and filter for unique hits. Parameters ---------- fn : str Path to (subset of) GRASP database. Returns ------- df : pandas.DataFrame Pandas dataframe with de-duplicated, significant SNPs. The index is of the form chrom:pos where pos is the one-based position of the SNP. The columns are chrom, start, end, rsid, and pvalue. rsid may be empty or not actually an RSID. chrom, start, end make a zero-based bed file with the SNP coordinates. """ df = pd.read_table(fn, low_memory=False) df = df[df.Pvalue < 1e-5] df = df.sort(columns=['chr(hg19)', 'pos(hg19)', 'Pvalue']) df = df.drop_duplicates(subset=['chr(hg19)', 'pos(hg19)']) df = df[df.Pvalue < 1e-5] df['chrom'] = 'chr' + df['chr(hg19)'].astype(str) df['end'] = df['pos(hg19)'] df['start'] = df.end - 1 df['rsid'] = df['SNPid(in paper)'] df['pvalue'] = df['Pvalue'] df = df[['chrom', 'start', 'end', 'rsid', 'pvalue']] df.index = df['chrom'].astype(str) + ':' + df['end'].astype(str) return df def parse_roadmap_gwas(fn): """ Read Roadmap GWAS file and filter for unique, significant (p < 1e-5) SNPs. Parameters ---------- fn : str Path to (subset of) GRASP database. Returns ------- df : pandas.DataFrame Pandas dataframe with de-duplicated, significant SNPs. The index is of the form chrom:pos where pos is the one-based position of the SNP. The columns are chrom, start, end, rsid, and pvalue. rsid may be empty or not actually an RSID. chrom, start, end make a zero-based bed file with the SNP coordinates. """ df = pd.read_table(fn, low_memory=False, names=['chrom', 'start', 'end', 'rsid', 'pvalue']) df = df[df.pvalue < 1e-5] df = df.sort(columns=['chrom', 'start', 'pvalue']) df = df.drop_duplicates(subset=['chrom', 'start']) df = df[df['chrom'] != 'chrY'] df.index = df['chrom'].astype(str) + ':' + df['end'].astype(str) return df def ld_prune(df, ld_beds, snvs=None): """ Prune set of GWAS based on LD and significance. A graph of all SNVs is constructed with edges for LD >= 0.8 and the most significant SNV per connected component is kept. Parameters ---------- df : pandas.DataFrame Pandas dataframe with unique SNVs. The index is of the form chrom:pos where pos is the one-based position of the SNV. The columns must include chrom, start, end, and pvalue. chrom, start, end make a zero-based bed file with the SNV coordinates. ld_beds : dict Dict whose keys are chromosomes and whose values are filenames of tabixed LD bed files. An LD bed file looks like "chr1 11007 11008 11008:11012:1" where the first three columns are the zero-based half-open coordinate of the SNV and the fourth column has the one-based coordinate followed of the SNV followed by the one-based coordinate of a different SNV and the LD between them. In this example, the variants are in perfect LD. The bed file should also contain the reciprocal line for this LD relationship: "chr1 11011 11012 11012:11008:1". snvs : list List of SNVs to filter against. If a SNV is not in this list, it will not be included. If you are working with GWAS SNPs, this is useful for filtering out SNVs that aren't in the SNPsnap database for instance. Returns ------- out : pandas.DataFrame Pandas dataframe in the same format as the input dataframe but with only independent SNVs. """ import networkx as nx import tabix if snvs: df = df.ix[set(df.index) & set(snvs)] keep = set() for chrom in ld_beds.keys(): tdf = df[df['chrom'].astype(str) == chrom] if tdf.shape[0] > 0: f = tabix.open(ld_beds[chrom]) # Make a dict where each key is a SNP and the values are all of the # other SNPs in LD with the key. ld_d = {} for j in tdf.index: p = tdf.ix[j, 'end'] ld_d[p] = [] try: r = f.query(chrom, p - 1, p) while True: try: n = r.next() p1, p2, r2 = n[-1].split(':') if float(r2) >= 0.8: ld_d[p].append(int(p2)) except StopIteration: break except TabixError: continue # Make adjacency matrix for LD. cols = sorted(list(set( [item for sublist in ld_d.values() for item in sublist]))) t = pd.DataFrame(0, index=ld_d.keys(), columns=cols) for k in ld_d.keys(): t.ix[k, ld_d[k]] = 1 t.index = ['{}:{}'.format(chrom, x) for x in t.index] t.columns = ['{}:{}'.format(chrom, x) for x in t.columns] # Keep all SNPs not in LD with any others. These will be in the index # but not in the columns. keep |= set(t.index) - set(t.columns) # Filter so we only have SNPs that are in LD with at least one other # SNP. ind = list(set(t.columns) & set(t.index)) # Keep one most sig. SNP per connected subgraph. t = t.ix[ind, ind] g = nx.Graph(t.values) c = nx.connected_components(g) while True: try: sg = c.next() s = tdf.ix[t.index[list(sg)]] keep.add(s[s.pvalue == s.pvalue.min()].index[0]) except StopIteration: break out = df.ix[keep] return out def ld_expand(df, ld_beds): """ Expand a set of SNVs into all SNVs with LD >= 0.8 and return a BedTool of the expanded SNPs. Parameters ---------- df : pandas.DataFrame Pandas dataframe with SNVs. The index is of the form chrom:pos where pos is the one-based position of the SNV. The columns are chrom, start, end. chrom, start, end make a zero-based bed file with the SNV coordinates. ld_beds : dict Dict whose keys are chromosomes and whose values are filenames of tabixed LD bed files. The LD bed files should be formatted like this: chr1 14463 14464 14464:51479:0.254183 where the the first three columns indicate the zero-based coordinates of a SNV and the the fourth column has the one-based coordinate of that SNV, the one-based coordinate of another SNV on the same chromosome, and the LD between these SNVs (all separated by colons). Returns ------- bt : pybedtools.BedTool BedTool with input SNVs and SNVs they are in LD with. indepdent SNVs. """ import pybedtools as pbt import tabix out_snps = [] for chrom in ld_beds.keys(): t = tabix.open(ld_beds[chrom]) tdf = df[df['chrom'].astype(str) == chrom] for ind in tdf.index: p = tdf.ix[ind, 'end'] out_snps.append('{}\t{}\t{}\t{}\n'.format(chrom, p - 1, p, ind)) try: r = t.query('{}'.format(chrom), p - 1, p) while True: try: n = r.next() p1, p2, r2 = n[-1].split(':') if float(r2) >= 0.8: out_snps.append('{}\t{}\t{}\t{}\n'.format( n[0], int(p2) - 1, int(p2), ind)) except StopIteration: break except tabix.TabixError: continue bt = pbt.BedTool(''.join(out_snps), from_string=True) bt = bt.sort() return bt def liftover_bed( bed, chain, mapped=None, unmapped=None, liftOver_path='liftOver', ): """ Lift over a bed file using a given chain file. Parameters ---------- bed : str or pybedtools.BedTool Coordinates to lift over. chain : str Path to chain file to use for lift over. mapped : str Path for bed file with coordinates that are lifted over correctly. unmapped : str Path for text file to store coordinates that did not lift over correctly. If this is not provided, these are discarded. liftOver_path : str Path to liftOver executable if not in path. Returns ------- new_coords : pandas.DataFrame Pandas data frame with lift over results. Index is old coordinates in the form chrom:start-end and columns are chrom, start, end and loc (chrom:start-end) in new coordinate system. """ import subprocess import pybedtools as pbt if mapped == None: import tempfile mapped = tempfile.NamedTemporaryFile() mname = mapped.name else: mname = mapped if unmapped == None: import tempfile unmapped = tempfile.NamedTemporaryFile() uname = unmapped.name else: uname = unmapped if type(bed) == str: bt = pbt.BedTool(bed) elif type(bed) == pbt.bedtool.BedTool: bt = bed else: sys.exit(1) bt = bt.sort() c = '{} {} {} {} {}'.format(liftOver_path, bt.fn, chain, mname, uname) subprocess.check_call(c, shell=True) with open(uname) as f: missing = pbt.BedTool(''.join([x for x in f.readlines()[1::2]]), from_string=True) bt = bt.subtract(missing) bt_mapped = pbt.BedTool(mname) old_loc = [] for r in bt: old_loc.append('{}:{}-{}'.format(r.chrom, r.start, r.end)) new_loc = [] new_chrom = [] new_start = [] new_end = [] for r in bt_mapped: new_loc.append('{}:{}-{}'.format(r.chrom, r.start, r.end)) new_chrom.append(r.chrom) new_start.append(r.start) new_end.append(r.end) new_coords = pd.DataFrame({'loc':new_loc, 'chrom': new_chrom, 'start': new_start, 'end': new_end}, index=old_loc) for f in [mapped, unmapped]: try: f.close() except AttributeError: continue return new_coords def deseq2_size_factors(counts, meta, design): """ Get size factors for counts using DESeq2. Parameters ---------- counts : pandas.DataFrame Counts to pass to DESeq2. meta : pandas.DataFrame Pandas dataframe whose index matches the columns of counts. This is passed to DESeq2's colData. design : str Design like ~subject_id that will be passed to DESeq2. The design variables should match columns in meta. Returns ------- sf : pandas.Series Series whose index matches the columns of counts and whose values are the size factors from DESeq2. Divide each column by its size factor to obtain normalized counts. """ import rpy2.robjects as r from rpy2.robjects import pandas2ri pandas2ri.activate() r.r('suppressMessages(library(DESeq2))') r.globalenv['counts'] = counts r.globalenv['meta'] = meta r.r('dds = DESeqDataSetFromMatrix(countData=counts, colData=meta, ' 'design={})'.format(design)) r.r('dds = estimateSizeFactors(dds)') r.r('sf = sizeFactors(dds)') sf = r.globalenv['sf'] return pd.Series(sf, index=counts.columns) def goseq_gene_enrichment(genes, sig, plot_fn=None, length_correct=True): """ Perform goseq enrichment for an Ensembl gene set. Parameters ---------- genes : list List of all genes as Ensembl IDs. sig : list List of boolean values indicating whether each gene is significant or not. plot_fn : str Path to save length bias plot to. If not provided, the plot is deleted. length_correct : bool Correct for length bias. Returns ------- go_results : pandas.DataFrame Dataframe with goseq results as well as Benjamini-Hochberg correct p-values. """ import os import readline import statsmodels.stats.multitest as smm import rpy2.robjects as r genes = list(genes) sig = [bool(x) for x in sig] r.r('suppressMessages(library(goseq))') r.globalenv['genes'] = list(genes) r.globalenv['group'] = list(sig) r.r('group = as.logical(group)') r.r('names(group) = genes') r.r('pwf = nullp(group, "hg19", "ensGene")') if length_correct: r.r('wall = goseq(pwf, "hg19", "ensGene")') else: r.r('wall = goseq(pwf, "hg19", "ensGene", method="Hypergeometric")') r.r('t = as.data.frame(wall)') t = r.globalenv['t'] go_results = pd.DataFrame(columns=list(t.colnames)) for i, c in enumerate(go_results.columns): go_results[c] = list(t[i]) r, c, ask, abf = smm.multipletests( go_results.over_represented_pvalue, alpha=0.05, method='fdr_i') go_results['over_represented_pvalue_bh'] = c r, c, ask, abf = smm.multipletests( go_results.under_represented_pvalue, alpha=0.05, method='fdr_i') go_results['under_represented_pvalue_bh'] = c go_results.index = go_results.category go_results = go_results.drop('category', axis=1) if plot_fn and os.path.exists('Rplots.pdf'): from os import rename rename('Rplots.pdf', plot_fn) elif os.path.exists('Rplots.pdf'): from os import remove remove('Rplots.pdf') return go_results def categories_to_colors(cats, colormap=None): """ Map categorical data to colors. Parameters ---------- cats : pandas.Series or list Categorical data as a list or in a Series. colormap : list List of RGB triples. If not provided, the tableau20 colormap defined in this module will be used. Returns ------- legend : pd.Series Series whose values are colors and whose index are the original categories that correspond to those colors. """ if colormap is None: colormap = tableau20 if type(cats) != pd.Series: cats = pd.Series(cats) legend = pd.Series(dict(zip(set(cats), colormap))) # colors = pd.Series([legend[x] for x in cats.values], index=cats.index) # I've removed this output: # colors : pd.Series # Series whose values are the colors for each category. If cats was a # Series, then out will have the same index as cats. return(legend) def plot_color_legend(legend, horizontal=False, ax=None): """ Plot a pandas Series with labels and colors. Parameters ---------- legend : pandas.Series Pandas Series whose values are RGB triples and whose index contains categorical labels. horizontal : bool If True, plot horizontally. ax : matplotlib.axis Axis to plot on. Returns ------- ax : matplotlib.axis Plot axis. """ import matplotlib.pyplot as plt import numpy as np t = np.array([np.array([x for x in legend])]) if ax is None: fig, ax = plt.subplots(1, 1) if horizontal: ax.imshow(t, interpolation='none') ax.set_yticks([]) ax.set_xticks(np.arange(0, legend.shape[0])) t = ax.set_xticklabels(legend.index) else: t = t.reshape([legend.shape[0], 1, 3]) ax.imshow(t, interpolation='none') ax.set_xticks([]) ax.set_yticks(np.arange(0, legend.shape[0])) t = ax.set_yticklabels(legend.index) return ax def make_color_legend_rects(colors, labels=None): """ Make list of rectangles and labels for making legends. Parameters ---------- colors : pandas.Series or list Pandas series whose values are colors and index is labels. Alternatively, you can provide a list with colors and provide the labels as a list. labels : list If colors is a list, this should be the list of corresponding labels. Returns ------- out : pd.Series Pandas series whose values are matplotlib rectangles and whose index are the legend labels for those rectangles. You can add each of these rectangles to your axis using ax.add_patch(r) for r in out then create a legend whose labels are out.values and whose labels are legend_rects.index: for r in legend_rects: ax.add_patch(r) lgd = ax.legend(legend_rects.values, labels=legend_rects.index) """ from matplotlib.pyplot import Rectangle if labels: d = dict(zip(labels, colors)) se = pd.Series(d) else: se = colors rects = [] for i in se.index: r = Rectangle((0, 0), 0, 0, fc=se[i]) rects.append(r) out = pd.Series(rects, index=se.index) return out class SVD: def __init__(self, df, mean_center=True, scale_variance=False, full_matrices=False): """ Perform SVD for data matrix using scipy.linalg.svd. Note that this is currently inefficient for large matrices due to some of the pandas operations. Parameters ---------- df : pandas.DataFrame Pandas data frame with data. mean_center : bool If True, mean center the rows. This should be done if not already done. scale_variance : bool If True, scale the variance of each row to be one. Combined with mean centering, this will transform your data into z-scores. full_matrices : bool Passed to scipy.linalg.svd. If True, U and Vh are of shape (M, M), (N, N). If False, the shapes are (M, K) and (K, N), where K = min(M, N). """ import copy self.data_orig = copy.deepcopy(df) self.data = copy.deepcopy(df) if mean_center: self.data = (self.data.T - self.data.mean(axis=1)).T if scale_variance: self.data = (self.data.T / self.data.std(axis=1)).T self._perform_svd(full_matrices) def _perform_svd(self, full_matrices): from scipy.linalg import svd u, s, vh = svd(self.data, full_matrices=full_matrices) self.u_orig = u self.s_orig = s self.vh_orig = vh self.u = pd.DataFrame( u, index=self.data.index, columns=['PC{}'.format(x) for x in range(1, u.shape[1] + 1)], ) self.v = pd.DataFrame( vh.T, index=self.data.columns, columns=['PC{}'.format(x) for x in range(1, vh.shape[0] + 1)], ) index = ['PC{}'.format(x) for x in range(1, len(s) + 1)] self.s_norm = pd.Series(s / s.sum(), index=index) def plot_variance_explained(self, cumulative=False, xtick_start=1, xtick_spacing=1, num_pc=None): """ Plot amount of variance explained by each principal component. Parameters ---------- num_pc : int Number of principal components to plot. If None, plot all. cumulative : bool If True, include cumulative variance. xtick_start : int The first principal component to label on the x-axis. xtick_spacing : int The spacing between labels on the x-axis. """ import matplotlib.pyplot as plt from numpy import arange if num_pc: s_norm = self.s_norm[0:num_pc] else: s_norm = self.s_norm if cumulative: s_cumsum = s_norm.cumsum() plt.bar(range(s_cumsum.shape[0]), s_cumsum.values, label='Cumulative', color=(0.17254901960784313, 0.6274509803921569, 0.17254901960784313)) plt.bar(range(s_norm.shape[0]), s_norm.values, label='Per PC', color=(0.12156862745098039, 0.4666666666666667, 0.7058823529411765)) plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.ylabel('Variance') else: plt.bar(range(s_norm.shape[0]), s_norm.values, color=(0.12156862745098039, 0.4666666666666667, 0.7058823529411765)) plt.ylabel('Proportion variance explained') plt.xlabel('PC') plt.xlim(0, s_norm.shape[0]) tick_locs = arange(xtick_start - 1, s_norm.shape[0], step=xtick_spacing) # 0.8 is the width of the bars. tick_locs = tick_locs + 0.4 plt.xticks(tick_locs, arange(xtick_start, s_norm.shape[0] + 1, xtick_spacing)) def plot_pc_scatter(self, pc1, pc2, v=True, subset=None, ax=None, color=None, s=None, marker=None, color_name=None, s_name=None, marker_name=None): """ Make a scatter plot of two principal components. You can create differently colored, sized, or marked scatter points. Parameters ---------- pc1 : str String of form PCX where X is the number of the principal component you want to plot on the x-axis. pc2 : str String of form PCX where X is the number of the principal component you want to plot on the y-axis. v : bool If True, use the v matrix for plotting the principal components (typical if input data was genes as rows and samples as columns). If False, use the u matrix. subset : list Make the scatter plot using only a subset of the rows of u or v. ax : matplotlib.axes Plot the scatter plot on this axis. color : pandas.Series Pandas series containing a categorical variable to color the scatter points. s : pandas.Series Pandas series containing a categorical variable to size the scatter points. Currently limited to 7 distinct values (sizes). marker : pandas.Series Pandas series containing a categorical variable to choose the marker type for the scatter points. Currently limited to 21 distinct values (marker styles). color_name : str Name for the color legend if a categorical variable for color is provided. s_name : str Name for the size legend if a categorical variable for size is provided. marker_name : str Name for the marker legend if a categorical variable for marker type is provided. Returns ------- ax : matplotlib.axes._subplots.AxesSubplot Scatter plot axis. TODO: Add ability to label points. """ import matplotlib.pyplot as plt import seaborn as sns assert s <= 7, 'Error: too many values for "s"' if v: df = self.v else: df = self.u if color is not None: if color.unique().shape[0] <= 10: colormap = pd.Series(dict(zip(set(color.values), tableau20[0:2 * len(set(color)):2]))) else: colormap = pd.Series(dict(zip(set(color.values), sns.color_palette('husl', len(set(color)))))) color = pd.Series([colormap[x] for x in color.values], index=color.index) color_legend = True if not color_name: color_name = color.index.name else: color = pd.Series([tableau20[0]] * df.shape[0], index=df.index) color_legend = False if s is not None: smap = pd.Series(dict(zip( set(s.values), range(30, 351)[0::50][0:len(set(s)) + 1]))) s = pd.Series([smap[x] for x in s.values], index=s.index) s_legend = True if not s_name: s_name = s.index.name else: s = pd.Series(30, index=df.index) s_legend = False markers = ['o', '*', 's', 'v', '+', 'x', 'd', 'p', '2', '<', '|', '>', '_', 'h', '1', '2', '3', '4', '8', '^', 'D'] if marker is not None: markermap = pd.Series(dict(zip(set(marker.values), markers))) marker = pd.Series([markermap[x] for x in marker.values], index=marker.index) marker_legend = True if not marker_name: marker_name = marker.index.name else: marker = pd.Series('o', index=df.index) marker_legend = False if ax is None: fig, ax = plt.subplots(1, 1) for m in set(marker.values): mse = marker[marker == m] cse = color[mse.index] sse = s[mse.index] ax.scatter(df.ix[mse.index, pc1], df.ix[mse.index, pc2], s=sse.values, color=list(cse.values), marker=m, alpha=0.8) ax.set_title('{} vs. {}'.format(pc1, pc2)) ax.set_xlabel(pc1) ax.set_ylabel(pc2) if color_legend: legend_rects = make_color_legend_rects(colormap) for r in legend_rects: ax.add_patch(r) lgd = ax.legend(legend_rects.values, labels=legend_rects.index, title=color_name, loc='upper left', bbox_to_anchor=(1, 1)) if s_legend: if lgd: lgd = ax.add_artist(lgd) xa, xb = ax.get_xlim() ya, yb = ax.get_ylim() for i in smap.index: ax.scatter([xb + 1], [yb + 1], marker='o', s=smap[i], color='black', label=i) lgd = ax.legend(title=s_name, loc='center left', bbox_to_anchor=(1, 0.5)) ax.set_xlim(xa, xb) ax.set_ylim(ya, yb) if marker_legend: if lgd: lgd = ax.add_artist(lgd) xa, xb = ax.get_xlim() ya, yb = ax.get_ylim() for i in markermap.index: t = ax.scatter([xb + 1], [yb + 1], marker=markermap[i], s=sse.min(), color='black', label=i) handles, labels = ax.get_legend_handles_labels() if s_legend: handles = handles[len(smap):] labels = labels[len(smap):] lgd = ax.legend(handles, labels, title=marker_name, loc='lower left', bbox_to_anchor=(1, 0)) ax.set_xlim(xa, xb) ax.set_ylim(ya, yb) # fig.tight_layout() return fig, ax def pc_correlation(self, covariates, num_pc=5): """ Calculate the correlation between the first num_pc prinicipal components and known covariates. The size and index of covariates determines whether u or v is used. Parameters ---------- covariates : pandas.DataFrame Dataframe of covariates whose index corresponds to the index of either u or v. num_pc : int Number of principal components to correlate with. Returns ------- corr : pandas.Panel Panel with correlation values and p-values. """ from scipy.stats import spearmanr if (covariates.shape[0] == self.u.shape[0] and len(set(covariates.index) & set(self.u.index)) == self.u.shape[0]): mat = self.u elif (covariates.shape[0] == self.v.shape[0] and len(set(covariates.index) & set(self.v.index)) == self.v.shape[0]): mat = self.v else: import sys sys.stderr.write('Covariates differ in size from input data.\n') sys.exit(1) corr = pd.Panel(items=['rho', 'pvalue'], major_axis=covariates.columns, minor_axis=mat.columns[0:num_pc]) for i in corr.major_axis: for j in corr.minor_axis: rho, p = spearmanr(covariates[i], mat[j]) corr.ix['rho', i, j] = rho corr.ix['pvalue', i, j] = p return corr def pc_anova(self, covariates, num_pc=5): """ Calculate one-way ANOVA between the first num_pc prinicipal components and known covariates. The size and index of covariates determines whether u or v is used. Parameters ---------- covariates : pandas.DataFrame Dataframe of covariates whose index corresponds to the index of either u or v. num_pc : int Number of principal components to correlate with. Returns ------- anova : pandas.Panel Panel with F-values and p-values. """ from scipy.stats import f_oneway if (covariates.shape[0] == self.u.shape[0] and len(set(covariates.index) & set(self.u.index)) == self.u.shape[0]): mat = self.u elif (covariates.shape[0] == self.v.shape[0] and len(set(covariates.index) & set(self.v.index)) == self.v.shape[0]): mat = self.v anova = pd.Panel(items=['fvalue', 'pvalue'], major_axis=covariates.columns, minor_axis=mat.columns[0:num_pc]) for i in anova.major_axis: for j in anova.minor_axis: t = [mat[j][covariates[i] == x] for x in set(covariates[i])] f, p = f_oneway(*t) anova.ix['fvalue', i, j] = f anova.ix['pvalue', i, j] = p return anova def manhattan_plot( res, ax, p_filter=1, p_cutoff=None, marker_size=10, font_size=8, chrom_labels=range(1, 23)[0::2], label_column=None, category_order=None, legend=True, ): """ Make Manhattan plot for GWAS results. Currently only support autosomes. Parameters ---------- res : pandas.DataFrame GWAS results. The following columns are required - chrom (chromsome, int), pos (genomic position, int), P (GWAS p-value, float). ax : matplotlib.axis Matplotlib axis to make Manhattan plot on. p_filter : float Only plot p-values smaller than this cutoff. This is useful for testing because filtering on p-values speeds up the plotting. p_cutoff : float Plot horizontal line at this p-value. marker_size : int Size of Manhattan markers. font_size : int Font size for plots. chrom_labels : list List of ints indicating which chromsomes to label. You may want to modulate this based on the size of the plot. Currently only integers 1-22 are supported. label_column : str String with column name from res. This column should contain a categorical annotation for each variant. These will be indicated by colors. category_order : list If label_column is not None, you can provide a list of the categories that are contained in the label_column. This will be used to assign the color palette and will specify the z-order of the categories. legend : boolean If True and label_column is not None, plot a legend. Returns ------- res : pandas.Dataframe GWAS results. The results will have additional columns that were used for plotting. ax : matplotlib.axis Axis with the Manhattan plot. colors : pd.Series or None If label_column is None, this will be None. Otherwise, if a label_column is specified, this will be a series with a mapping between the labels and the colors for each label. """ # TODO: It might make sense to allow a variable that specifies the z-order # of labels in label_column. If there are many labels and points in the same # place, certain annotations will be preferentially shown. import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import seaborn as sns # Filter results based on p-value. if p_filter < 1: res = res[res['P'] < p_filter] # Assign x coordinates for each association. res['xpos'] = np.nan chrom_vc = res['chrom'].value_counts() # total_length is arbitrary, but it's a little easier than working with the # normalized chromosome sizes to avoid small numbers. total_length = 1000 right = chrom_sizes_norm.cumsum() right = right / right[22] * total_length left = chrom_sizes_norm.cumsum() - chrom_sizes_norm[1] left = pd.Series(0, range(1, 23)) left[1:23] = right[0:21].values for chrom in range(1, 23): if chrom in res['chrom'].values: res.loc[res['chrom'] == chrom, 'xpos'] = np.linspace( left[chrom], right[chrom], chrom_vc[chrom]) # Assign colors. grey = mpl.colors.to_rgb('grey') light_grey = (0.9, 0.9, 0.9) middle_grey = (0.8, 0.8, 0.8) # I first set everything to black, but in the end everything should be # changed to one of the greys (or other colors if there is an annotation # column). If there are black points on the plot, that indicates a problem. res['color'] = 'black' for chrom in range(1, 23)[0::2]: if chrom in res['chrom'].values: ind = res[res.chrom == chrom].index res.loc[ind, 'color'] = pd.Series([grey for x in ind], index=ind) for chrom in range(1, 23)[1::2]: if chrom in res['chrom'].values: ind = res[res.chrom == chrom].index res.loc[ind, 'color'] = pd.Series([middle_grey for x in ind], index=ind) if label_column is not None: if category_order is not None: assert set(category_order) == set(res[label_column].dropna()) categories = category_order else: categories = list(set(res[label_column].dropna())) colors = categories_to_colors( categories, colormap=sns.color_palette('colorblind'), ) for cat in categories: ind = res[res[label_column] == cat].index res.loc[ind, 'color'] = pd.Series([colors[cat] for x in ind], index=ind) # Plot if label_column is not None: ind = res[res[label_column].isnull()].index ax.scatter( res.loc[ind, 'xpos'], -np.log10(res.loc[ind, 'P']), color=res.loc[ind, 'color'], s=marker_size, alpha=0.75, rasterized=True, label=None, ) for cat in reversed(categories): ind = res[res[label_column] == cat].index ax.scatter( res.loc[ind, 'xpos'], -np.log10(res.loc[ind, 'P']), color=res.loc[ind, 'color'], s=marker_size, alpha=0.75, rasterized=True, label=None, ) else: ax.scatter( res['xpos'], -np.log10(res['P']), color=res['color'], s=marker_size, alpha=0.75, rasterized=True, label=None, ) xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() ax.grid(axis='x') ax.grid(axis='y') ax.grid(axis='y', alpha=0.5, ls='-', lw=0.6) if p_cutoff is not None: ax.hlines( -np.log10(p_cutoff), -5, total_length + 5, color='red', linestyles='--', lw=0.8, alpha=0.5, ) # These next two lines add background shading. I may add back in as option. # for chrom in range(1, 23)[0::2]: # ax.axvspan(left[chrom], right[chrom], facecolor=(0.4, 0.4, 0.4), alpha=0.2, lw=0) ax.set_xlim(-5, total_length + 5) ax.set_ylim(0, ymax) # Set chromosome labels # ind = range(1, 23)[0::2] # if skip19: # ind = [x for x in ind if x != 19] ind = [x for x in chrom_labels if x in range(1, 23)] ax.set_xticks(left[ind] + (right[ind] - left[ind]) / 2) ax.set_xticklabels(ind, fontsize=font_size) ax.set_ylabel('$-\log_{10} p$ value', fontsize=font_size) for t in ax.get_xticklabels() + ax.get_yticklabels(): t.set_fontsize(font_size) if label_column is not None and legend: for cat in categories: ax.scatter( -100, -100, s=marker_size, color=colors[cat], label=cat, ) if legend: ax.legend( fontsize=font_size- 1, framealpha=0.5, frameon=True, facecolor='white', ) # TODO: eventually, it would be better to be smarter about the x-axis # limits. Depending on the size of the markers and plot, some of the markers # might be cut off. ax.set_xlim(-5, total_length + 5) # TODO: eventually, it would be better to be smarter about the y-axis # limits. Depending on the size of the markers and plot, some of the markers # might be cut off. Matplotlib doesn't know anything about the size of the # markers, so it might set the y-limit too low. ax.set_ylim(-1 * np.log10(p_filter), ymax) if label_column is None: colors = None return(res, ax, colors)
mit
russel1237/scikit-learn
sklearn/tests/test_multiclass.py
136
23649
import numpy as np import scipy.sparse as sp from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_warns from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_greater from sklearn.multiclass import OneVsRestClassifier from sklearn.multiclass import OneVsOneClassifier from sklearn.multiclass import OutputCodeClassifier from sklearn.multiclass import fit_ovr from sklearn.multiclass import fit_ovo from sklearn.multiclass import fit_ecoc from sklearn.multiclass import predict_ovr from sklearn.multiclass import predict_ovo from sklearn.multiclass import predict_ecoc from sklearn.multiclass import predict_proba_ovr from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.preprocessing import LabelBinarizer from sklearn.svm import LinearSVC, SVC from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import (LinearRegression, Lasso, ElasticNet, Ridge, Perceptron, LogisticRegression) from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.grid_search import GridSearchCV from sklearn.pipeline import Pipeline from sklearn import svm from sklearn import datasets from sklearn.externals.six.moves import zip iris = datasets.load_iris() rng = np.random.RandomState(0) perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] n_classes = 3 def test_ovr_exceptions(): ovr = OneVsRestClassifier(LinearSVC(random_state=0)) assert_raises(ValueError, ovr.predict, []) with ignore_warnings(): assert_raises(ValueError, predict_ovr, [LinearSVC(), MultinomialNB()], LabelBinarizer(), []) # Fail on multioutput data assert_raises(ValueError, OneVsRestClassifier(MultinomialNB()).fit, np.array([[1, 0], [0, 1]]), np.array([[1, 2], [3, 1]])) assert_raises(ValueError, OneVsRestClassifier(MultinomialNB()).fit, np.array([[1, 0], [0, 1]]), np.array([[1.5, 2.4], [3.1, 0.8]])) def test_ovr_fit_predict(): # A classifier which implements decision_function. ovr = OneVsRestClassifier(LinearSVC(random_state=0)) pred = ovr.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovr.estimators_), n_classes) clf = LinearSVC(random_state=0) pred2 = clf.fit(iris.data, iris.target).predict(iris.data) assert_equal(np.mean(iris.target == pred), np.mean(iris.target == pred2)) # A classifier which implements predict_proba. ovr = OneVsRestClassifier(MultinomialNB()) pred = ovr.fit(iris.data, iris.target).predict(iris.data) assert_greater(np.mean(iris.target == pred), 0.65) def test_ovr_ovo_regressor(): # test that ovr and ovo work on regressors which don't have a decision_function ovr = OneVsRestClassifier(DecisionTreeRegressor()) pred = ovr.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovr.estimators_), n_classes) assert_array_equal(np.unique(pred), [0, 1, 2]) # we are doing something sensible assert_greater(np.mean(pred == iris.target), .9) ovr = OneVsOneClassifier(DecisionTreeRegressor()) pred = ovr.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovr.estimators_), n_classes * (n_classes - 1) / 2) assert_array_equal(np.unique(pred), [0, 1, 2]) # we are doing something sensible assert_greater(np.mean(pred == iris.target), .9) def test_ovr_fit_predict_sparse(): for sparse in [sp.csr_matrix, sp.csc_matrix, sp.coo_matrix, sp.dok_matrix, sp.lil_matrix]: base_clf = MultinomialNB(alpha=1) X, Y = datasets.make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, n_labels=3, length=50, allow_unlabeled=True, random_state=0) X_train, Y_train = X[:80], Y[:80] X_test = X[80:] clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) Y_pred = clf.predict(X_test) clf_sprs = OneVsRestClassifier(base_clf).fit(X_train, sparse(Y_train)) Y_pred_sprs = clf_sprs.predict(X_test) assert_true(clf.multilabel_) assert_true(sp.issparse(Y_pred_sprs)) assert_array_equal(Y_pred_sprs.toarray(), Y_pred) # Test predict_proba Y_proba = clf_sprs.predict_proba(X_test) # predict assigns a label if the probability that the # sample has the label is greater than 0.5. pred = Y_proba > .5 assert_array_equal(pred, Y_pred_sprs.toarray()) # Test decision_function clf_sprs = OneVsRestClassifier(svm.SVC()).fit(X_train, sparse(Y_train)) dec_pred = (clf_sprs.decision_function(X_test) > 0).astype(int) assert_array_equal(dec_pred, clf_sprs.predict(X_test).toarray()) def test_ovr_always_present(): # Test that ovr works with classes that are always present or absent. # Note: tests is the case where _ConstantPredictor is utilised X = np.ones((10, 2)) X[:5, :] = 0 # Build an indicator matrix where two features are always on. # As list of lists, it would be: [[int(i >= 5), 2, 3] for i in range(10)] y = np.zeros((10, 3)) y[5:, 0] = 1 y[:, 1] = 1 y[:, 2] = 1 ovr = OneVsRestClassifier(LogisticRegression()) assert_warns(UserWarning, ovr.fit, X, y) y_pred = ovr.predict(X) assert_array_equal(np.array(y_pred), np.array(y)) y_pred = ovr.decision_function(X) assert_equal(np.unique(y_pred[:, -2:]), 1) y_pred = ovr.predict_proba(X) assert_array_equal(y_pred[:, -1], np.ones(X.shape[0])) # y has a constantly absent label y = np.zeros((10, 2)) y[5:, 0] = 1 # variable label ovr = OneVsRestClassifier(LogisticRegression()) assert_warns(UserWarning, ovr.fit, X, y) y_pred = ovr.predict_proba(X) assert_array_equal(y_pred[:, -1], np.zeros(X.shape[0])) def test_ovr_multiclass(): # Toy dataset where features correspond directly to labels. X = np.array([[0, 0, 5], [0, 5, 0], [3, 0, 0], [0, 0, 6], [6, 0, 0]]) y = ["eggs", "spam", "ham", "eggs", "ham"] Y = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, 1], [1, 0, 0]]) classes = set("ham eggs spam".split()) for base_clf in (MultinomialNB(), LinearSVC(random_state=0), LinearRegression(), Ridge(), ElasticNet()): clf = OneVsRestClassifier(base_clf).fit(X, y) assert_equal(set(clf.classes_), classes) y_pred = clf.predict(np.array([[0, 0, 4]]))[0] assert_equal(set(y_pred), set("eggs")) # test input as label indicator matrix clf = OneVsRestClassifier(base_clf).fit(X, Y) y_pred = clf.predict([[0, 0, 4]])[0] assert_array_equal(y_pred, [0, 0, 1]) def test_ovr_binary(): # Toy dataset where features correspond directly to labels. X = np.array([[0, 0, 5], [0, 5, 0], [3, 0, 0], [0, 0, 6], [6, 0, 0]]) y = ["eggs", "spam", "spam", "eggs", "spam"] Y = np.array([[0, 1, 1, 0, 1]]).T classes = set("eggs spam".split()) def conduct_test(base_clf, test_predict_proba=False): clf = OneVsRestClassifier(base_clf).fit(X, y) assert_equal(set(clf.classes_), classes) y_pred = clf.predict(np.array([[0, 0, 4]]))[0] assert_equal(set(y_pred), set("eggs")) if test_predict_proba: X_test = np.array([[0, 0, 4]]) probabilities = clf.predict_proba(X_test) assert_equal(2, len(probabilities[0])) assert_equal(clf.classes_[np.argmax(probabilities, axis=1)], clf.predict(X_test)) # test input as label indicator matrix clf = OneVsRestClassifier(base_clf).fit(X, Y) y_pred = clf.predict([[3, 0, 0]])[0] assert_equal(y_pred, 1) for base_clf in (LinearSVC(random_state=0), LinearRegression(), Ridge(), ElasticNet()): conduct_test(base_clf) for base_clf in (MultinomialNB(), SVC(probability=True), LogisticRegression()): conduct_test(base_clf, test_predict_proba=True) def test_ovr_multilabel(): # Toy dataset where features correspond directly to labels. X = np.array([[0, 4, 5], [0, 5, 0], [3, 3, 3], [4, 0, 6], [6, 0, 0]]) y = np.array([[0, 1, 1], [0, 1, 0], [1, 1, 1], [1, 0, 1], [1, 0, 0]]) for base_clf in (MultinomialNB(), LinearSVC(random_state=0), LinearRegression(), Ridge(), ElasticNet(), Lasso(alpha=0.5)): clf = OneVsRestClassifier(base_clf).fit(X, y) y_pred = clf.predict([[0, 4, 4]])[0] assert_array_equal(y_pred, [0, 1, 1]) assert_true(clf.multilabel_) def test_ovr_fit_predict_svc(): ovr = OneVsRestClassifier(svm.SVC()) ovr.fit(iris.data, iris.target) assert_equal(len(ovr.estimators_), 3) assert_greater(ovr.score(iris.data, iris.target), .9) def test_ovr_multilabel_dataset(): base_clf = MultinomialNB(alpha=1) for au, prec, recall in zip((True, False), (0.51, 0.66), (0.51, 0.80)): X, Y = datasets.make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, n_labels=2, length=50, allow_unlabeled=au, random_state=0) X_train, Y_train = X[:80], Y[:80] X_test, Y_test = X[80:], Y[80:] clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) Y_pred = clf.predict(X_test) assert_true(clf.multilabel_) assert_almost_equal(precision_score(Y_test, Y_pred, average="micro"), prec, decimal=2) assert_almost_equal(recall_score(Y_test, Y_pred, average="micro"), recall, decimal=2) def test_ovr_multilabel_predict_proba(): base_clf = MultinomialNB(alpha=1) for au in (False, True): X, Y = datasets.make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, n_labels=3, length=50, allow_unlabeled=au, random_state=0) X_train, Y_train = X[:80], Y[:80] X_test = X[80:] clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) # decision function only estimator. Fails in current implementation. decision_only = OneVsRestClassifier(svm.SVR()).fit(X_train, Y_train) assert_raises(AttributeError, decision_only.predict_proba, X_test) # Estimator with predict_proba disabled, depending on parameters. decision_only = OneVsRestClassifier(svm.SVC(probability=False)) decision_only.fit(X_train, Y_train) assert_raises(AttributeError, decision_only.predict_proba, X_test) Y_pred = clf.predict(X_test) Y_proba = clf.predict_proba(X_test) # predict assigns a label if the probability that the # sample has the label is greater than 0.5. pred = Y_proba > .5 assert_array_equal(pred, Y_pred) def test_ovr_single_label_predict_proba(): base_clf = MultinomialNB(alpha=1) X, Y = iris.data, iris.target X_train, Y_train = X[:80], Y[:80] X_test = X[80:] clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train) # decision function only estimator. Fails in current implementation. decision_only = OneVsRestClassifier(svm.SVR()).fit(X_train, Y_train) assert_raises(AttributeError, decision_only.predict_proba, X_test) Y_pred = clf.predict(X_test) Y_proba = clf.predict_proba(X_test) assert_almost_equal(Y_proba.sum(axis=1), 1.0) # predict assigns a label if the probability that the # sample has the label is greater than 0.5. pred = np.array([l.argmax() for l in Y_proba]) assert_false((pred - Y_pred).any()) def test_ovr_multilabel_decision_function(): X, Y = datasets.make_multilabel_classification(n_samples=100, n_features=20, n_classes=5, n_labels=3, length=50, allow_unlabeled=True, random_state=0) X_train, Y_train = X[:80], Y[:80] X_test = X[80:] clf = OneVsRestClassifier(svm.SVC()).fit(X_train, Y_train) assert_array_equal((clf.decision_function(X_test) > 0).astype(int), clf.predict(X_test)) def test_ovr_single_label_decision_function(): X, Y = datasets.make_classification(n_samples=100, n_features=20, random_state=0) X_train, Y_train = X[:80], Y[:80] X_test = X[80:] clf = OneVsRestClassifier(svm.SVC()).fit(X_train, Y_train) assert_array_equal(clf.decision_function(X_test).ravel() > 0, clf.predict(X_test)) def test_ovr_gridsearch(): ovr = OneVsRestClassifier(LinearSVC(random_state=0)) Cs = [0.1, 0.5, 0.8] cv = GridSearchCV(ovr, {'estimator__C': Cs}) cv.fit(iris.data, iris.target) best_C = cv.best_estimator_.estimators_[0].C assert_true(best_C in Cs) def test_ovr_pipeline(): # Test with pipeline of length one # This test is needed because the multiclass estimators may fail to detect # the presence of predict_proba or decision_function. clf = Pipeline([("tree", DecisionTreeClassifier())]) ovr_pipe = OneVsRestClassifier(clf) ovr_pipe.fit(iris.data, iris.target) ovr = OneVsRestClassifier(DecisionTreeClassifier()) ovr.fit(iris.data, iris.target) assert_array_equal(ovr.predict(iris.data), ovr_pipe.predict(iris.data)) def test_ovr_coef_(): for base_classifier in [SVC(kernel='linear', random_state=0), LinearSVC(random_state=0)]: # SVC has sparse coef with sparse input data ovr = OneVsRestClassifier(base_classifier) for X in [iris.data, sp.csr_matrix(iris.data)]: # test with dense and sparse coef ovr.fit(X, iris.target) shape = ovr.coef_.shape assert_equal(shape[0], n_classes) assert_equal(shape[1], iris.data.shape[1]) # don't densify sparse coefficients assert_equal(sp.issparse(ovr.estimators_[0].coef_), sp.issparse(ovr.coef_)) def test_ovr_coef_exceptions(): # Not fitted exception! ovr = OneVsRestClassifier(LinearSVC(random_state=0)) # lambda is needed because we don't want coef_ to be evaluated right away assert_raises(ValueError, lambda x: ovr.coef_, None) # Doesn't have coef_ exception! ovr = OneVsRestClassifier(DecisionTreeClassifier()) ovr.fit(iris.data, iris.target) assert_raises(AttributeError, lambda x: ovr.coef_, None) def test_ovo_exceptions(): ovo = OneVsOneClassifier(LinearSVC(random_state=0)) assert_raises(ValueError, ovo.predict, []) def test_ovo_fit_on_list(): # Test that OneVsOne fitting works with a list of targets and yields the # same output as predict from an array ovo = OneVsOneClassifier(LinearSVC(random_state=0)) prediction_from_array = ovo.fit(iris.data, iris.target).predict(iris.data) prediction_from_list = ovo.fit(iris.data, list(iris.target)).predict(iris.data) assert_array_equal(prediction_from_array, prediction_from_list) def test_ovo_fit_predict(): # A classifier which implements decision_function. ovo = OneVsOneClassifier(LinearSVC(random_state=0)) ovo.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovo.estimators_), n_classes * (n_classes - 1) / 2) # A classifier which implements predict_proba. ovo = OneVsOneClassifier(MultinomialNB()) ovo.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ovo.estimators_), n_classes * (n_classes - 1) / 2) def test_ovo_decision_function(): n_samples = iris.data.shape[0] ovo_clf = OneVsOneClassifier(LinearSVC(random_state=0)) ovo_clf.fit(iris.data, iris.target) decisions = ovo_clf.decision_function(iris.data) assert_equal(decisions.shape, (n_samples, n_classes)) assert_array_equal(decisions.argmax(axis=1), ovo_clf.predict(iris.data)) # Compute the votes votes = np.zeros((n_samples, n_classes)) k = 0 for i in range(n_classes): for j in range(i + 1, n_classes): pred = ovo_clf.estimators_[k].predict(iris.data) votes[pred == 0, i] += 1 votes[pred == 1, j] += 1 k += 1 # Extract votes and verify assert_array_equal(votes, np.round(decisions)) for class_idx in range(n_classes): # For each sample and each class, there only 3 possible vote levels # because they are only 3 distinct class pairs thus 3 distinct # binary classifiers. # Therefore, sorting predictions based on votes would yield # mostly tied predictions: assert_true(set(votes[:, class_idx]).issubset(set([0., 1., 2.]))) # The OVO decision function on the other hand is able to resolve # most of the ties on this data as it combines both the vote counts # and the aggregated confidence levels of the binary classifiers # to compute the aggregate decision function. The iris dataset # has 150 samples with a couple of duplicates. The OvO decisions # can resolve most of the ties: assert_greater(len(np.unique(decisions[:, class_idx])), 146) def test_ovo_gridsearch(): ovo = OneVsOneClassifier(LinearSVC(random_state=0)) Cs = [0.1, 0.5, 0.8] cv = GridSearchCV(ovo, {'estimator__C': Cs}) cv.fit(iris.data, iris.target) best_C = cv.best_estimator_.estimators_[0].C assert_true(best_C in Cs) def test_ovo_ties(): # Test that ties are broken using the decision function, # not defaulting to the smallest label X = np.array([[1, 2], [2, 1], [-2, 1], [-2, -1]]) y = np.array([2, 0, 1, 2]) multi_clf = OneVsOneClassifier(Perceptron(shuffle=False)) ovo_prediction = multi_clf.fit(X, y).predict(X) ovo_decision = multi_clf.decision_function(X) # Classifiers are in order 0-1, 0-2, 1-2 # Use decision_function to compute the votes and the normalized # sum_of_confidences, which is used to disambiguate when there is a tie in # votes. votes = np.round(ovo_decision) normalized_confidences = ovo_decision - votes # For the first point, there is one vote per class assert_array_equal(votes[0, :], 1) # For the rest, there is no tie and the prediction is the argmax assert_array_equal(np.argmax(votes[1:], axis=1), ovo_prediction[1:]) # For the tie, the prediction is the class with the highest score assert_equal(ovo_prediction[0], normalized_confidences[0].argmax()) def test_ovo_ties2(): # test that ties can not only be won by the first two labels X = np.array([[1, 2], [2, 1], [-2, 1], [-2, -1]]) y_ref = np.array([2, 0, 1, 2]) # cycle through labels so that each label wins once for i in range(3): y = (y_ref + i) % 3 multi_clf = OneVsOneClassifier(Perceptron(shuffle=False)) ovo_prediction = multi_clf.fit(X, y).predict(X) assert_equal(ovo_prediction[0], i % 3) def test_ovo_string_y(): # Test that the OvO doesn't mess up the encoding of string labels X = np.eye(4) y = np.array(['a', 'b', 'c', 'd']) ovo = OneVsOneClassifier(LinearSVC()) ovo.fit(X, y) assert_array_equal(y, ovo.predict(X)) def test_ecoc_exceptions(): ecoc = OutputCodeClassifier(LinearSVC(random_state=0)) assert_raises(ValueError, ecoc.predict, []) def test_ecoc_fit_predict(): # A classifier which implements decision_function. ecoc = OutputCodeClassifier(LinearSVC(random_state=0), code_size=2, random_state=0) ecoc.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ecoc.estimators_), n_classes * 2) # A classifier which implements predict_proba. ecoc = OutputCodeClassifier(MultinomialNB(), code_size=2, random_state=0) ecoc.fit(iris.data, iris.target).predict(iris.data) assert_equal(len(ecoc.estimators_), n_classes * 2) def test_ecoc_gridsearch(): ecoc = OutputCodeClassifier(LinearSVC(random_state=0), random_state=0) Cs = [0.1, 0.5, 0.8] cv = GridSearchCV(ecoc, {'estimator__C': Cs}) cv.fit(iris.data, iris.target) best_C = cv.best_estimator_.estimators_[0].C assert_true(best_C in Cs) @ignore_warnings def test_deprecated(): base_estimator = DecisionTreeClassifier(random_state=0) X, Y = iris.data, iris.target X_train, Y_train = X[:80], Y[:80] X_test = X[80:] all_metas = [ (OneVsRestClassifier, fit_ovr, predict_ovr, predict_proba_ovr), (OneVsOneClassifier, fit_ovo, predict_ovo, None), (OutputCodeClassifier, fit_ecoc, predict_ecoc, None), ] for MetaEst, fit_func, predict_func, proba_func in all_metas: try: meta_est = MetaEst(base_estimator, random_state=0).fit(X_train, Y_train) fitted_return = fit_func(base_estimator, X_train, Y_train, random_state=0) except TypeError: meta_est = MetaEst(base_estimator).fit(X_train, Y_train) fitted_return = fit_func(base_estimator, X_train, Y_train) if len(fitted_return) == 2: estimators_, classes_or_lb = fitted_return assert_almost_equal(predict_func(estimators_, classes_or_lb, X_test), meta_est.predict(X_test)) if proba_func is not None: assert_almost_equal(proba_func(estimators_, X_test, is_multilabel=False), meta_est.predict_proba(X_test)) else: estimators_, classes_or_lb, codebook = fitted_return assert_almost_equal(predict_func(estimators_, classes_or_lb, codebook, X_test), meta_est.predict(X_test))
bsd-3-clause
anirudhjayaraman/scikit-learn
benchmarks/bench_random_projections.py
397
8900
""" =========================== Random projection benchmark =========================== Benchmarks for random projections. """ from __future__ import division from __future__ import print_function import gc import sys import optparse from datetime import datetime import collections import numpy as np import scipy.sparse as sp from sklearn import clone from sklearn.externals.six.moves import xrange from sklearn.random_projection import (SparseRandomProjection, GaussianRandomProjection, johnson_lindenstrauss_min_dim) def type_auto_or_float(val): if val == "auto": return "auto" else: return float(val) def type_auto_or_int(val): if val == "auto": return "auto" else: return int(val) def compute_time(t_start, delta): mu_second = 0.0 + 10 ** 6 # number of microseconds in a second return delta.seconds + delta.microseconds / mu_second def bench_scikit_transformer(X, transfomer): gc.collect() clf = clone(transfomer) # start time t_start = datetime.now() clf.fit(X) delta = (datetime.now() - t_start) # stop time time_to_fit = compute_time(t_start, delta) # start time t_start = datetime.now() clf.transform(X) delta = (datetime.now() - t_start) # stop time time_to_transform = compute_time(t_start, delta) return time_to_fit, time_to_transform # Make some random data with uniformly located non zero entries with # Gaussian distributed values def make_sparse_random_data(n_samples, n_features, n_nonzeros, random_state=None): rng = np.random.RandomState(random_state) data_coo = sp.coo_matrix( (rng.randn(n_nonzeros), (rng.randint(n_samples, size=n_nonzeros), rng.randint(n_features, size=n_nonzeros))), shape=(n_samples, n_features)) return data_coo.toarray(), data_coo.tocsr() def print_row(clf_type, time_fit, time_transform): print("%s | %s | %s" % (clf_type.ljust(30), ("%.4fs" % time_fit).center(12), ("%.4fs" % time_transform).center(12))) if __name__ == "__main__": ########################################################################### # Option parser ########################################################################### op = optparse.OptionParser() op.add_option("--n-times", dest="n_times", default=5, type=int, help="Benchmark results are average over n_times experiments") op.add_option("--n-features", dest="n_features", default=10 ** 4, type=int, help="Number of features in the benchmarks") op.add_option("--n-components", dest="n_components", default="auto", help="Size of the random subspace." " ('auto' or int > 0)") op.add_option("--ratio-nonzeros", dest="ratio_nonzeros", default=10 ** -3, type=float, help="Number of features in the benchmarks") op.add_option("--n-samples", dest="n_samples", default=500, type=int, help="Number of samples in the benchmarks") op.add_option("--random-seed", dest="random_seed", default=13, type=int, help="Seed used by the random number generators.") op.add_option("--density", dest="density", default=1 / 3, help="Density used by the sparse random projection." " ('auto' or float (0.0, 1.0]") op.add_option("--eps", dest="eps", default=0.5, type=float, help="See the documentation of the underlying transformers.") op.add_option("--transformers", dest="selected_transformers", default='GaussianRandomProjection,SparseRandomProjection', type=str, help="Comma-separated list of transformer to benchmark. " "Default: %default. Available: " "GaussianRandomProjection,SparseRandomProjection") op.add_option("--dense", dest="dense", default=False, action="store_true", help="Set input space as a dense matrix.") (opts, args) = op.parse_args() if len(args) > 0: op.error("this script takes no arguments.") sys.exit(1) opts.n_components = type_auto_or_int(opts.n_components) opts.density = type_auto_or_float(opts.density) selected_transformers = opts.selected_transformers.split(',') ########################################################################### # Generate dataset ########################################################################### n_nonzeros = int(opts.ratio_nonzeros * opts.n_features) print('Dataset statics') print("===========================") print('n_samples \t= %s' % opts.n_samples) print('n_features \t= %s' % opts.n_features) if opts.n_components == "auto": print('n_components \t= %s (auto)' % johnson_lindenstrauss_min_dim(n_samples=opts.n_samples, eps=opts.eps)) else: print('n_components \t= %s' % opts.n_components) print('n_elements \t= %s' % (opts.n_features * opts.n_samples)) print('n_nonzeros \t= %s per feature' % n_nonzeros) print('ratio_nonzeros \t= %s' % opts.ratio_nonzeros) print('') ########################################################################### # Set transformer input ########################################################################### transformers = {} ########################################################################### # Set GaussianRandomProjection input gaussian_matrix_params = { "n_components": opts.n_components, "random_state": opts.random_seed } transformers["GaussianRandomProjection"] = \ GaussianRandomProjection(**gaussian_matrix_params) ########################################################################### # Set SparseRandomProjection input sparse_matrix_params = { "n_components": opts.n_components, "random_state": opts.random_seed, "density": opts.density, "eps": opts.eps, } transformers["SparseRandomProjection"] = \ SparseRandomProjection(**sparse_matrix_params) ########################################################################### # Perform benchmark ########################################################################### time_fit = collections.defaultdict(list) time_transform = collections.defaultdict(list) print('Benchmarks') print("===========================") print("Generate dataset benchmarks... ", end="") X_dense, X_sparse = make_sparse_random_data(opts.n_samples, opts.n_features, n_nonzeros, random_state=opts.random_seed) X = X_dense if opts.dense else X_sparse print("done") for name in selected_transformers: print("Perform benchmarks for %s..." % name) for iteration in xrange(opts.n_times): print("\titer %s..." % iteration, end="") time_to_fit, time_to_transform = bench_scikit_transformer(X_dense, transformers[name]) time_fit[name].append(time_to_fit) time_transform[name].append(time_to_transform) print("done") print("") ########################################################################### # Print results ########################################################################### print("Script arguments") print("===========================") arguments = vars(opts) print("%s \t | %s " % ("Arguments".ljust(16), "Value".center(12),)) print(25 * "-" + ("|" + "-" * 14) * 1) for key, value in arguments.items(): print("%s \t | %s " % (str(key).ljust(16), str(value).strip().center(12))) print("") print("Transformer performance:") print("===========================") print("Results are averaged over %s repetition(s)." % opts.n_times) print("") print("%s | %s | %s" % ("Transformer".ljust(30), "fit".center(12), "transform".center(12))) print(31 * "-" + ("|" + "-" * 14) * 2) for name in sorted(selected_transformers): print_row(name, np.mean(time_fit[name]), np.mean(time_transform[name])) print("") print("")
bsd-3-clause
gietal/Stocker
sandbox/sentdex/3.py
1
1034
import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as mticker import matplotlib.dates as mdates import numpy as np def graphRaw(): date, bid, ask = np.loadtxt( 'Data/GBPUSD1d.txt', # 'Data/GBPUSD10s.txt', delimiter=',', unpack=True, converters={0:mdates.strpdate2num('%Y%m%d%H%M%S')}) fig = plt.figure(figsize=(10,7)) ax1 = plt.subplot2grid((40, 40), (0, 0), rowspan=40, colspan=40) # chart the bid and ask as line graph ax1.plot(date, bid) ax1.plot(date, ask) plt.gca().get_yaxis().get_major_formatter().set_useOffset(False) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S')) # rotate the date label 45 degree for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) # make the spread bar chart ax1_2 = ax1.twinx() ax1_2.fill_between(date, 0, (ask - bid), facecolor='g', alpha = 0.3) plt.subplots_adjust(bottom=0.23) plt.grid() plt.show() graphRaw()
mit
JohnCEarls/DataDirac
test/test_hddata_process.py
1
9435
import sys sys.path.append('/home/sgeadmin/DataDirac') from datadirac import data from datadirac.utils import hddata_process import boto import os import os.path import random def test_metadata( meta_file): header = [] meta_base = [] with open(meta_file, 'r') as meta: for line in meta: a = line.strip().split('\t') if header: meta_base.append( dict( ((k,v) for k,v in zip( header, a))) ) else: header = a meta_base metainfo_obj = data.MetaInfo( meta_file ) #test strains strains = metainfo_obj.get_strains() for x in meta_base: assert x['strain'] in strains, "%s not in mi strains" % x['strain'] for strain in strains: assert strain in (x['strain'] for x in meta_base), ( "%s in MetaInfo but not in file" % strain) #test alleles for strain in strains: alleles = metainfo_obj.get_nominal_alleles( strain=strain ) for x in meta_base: if x['strain'] == strain: assert x['allele_nominal'] in alleles, ( "Strain %s and Allele %s not in metainfo" % (x['strain'], x['allele_nominal']) ) #test samples for strain in strains: samples = metainfo_obj.get_sample_ids( strain ) s = [x['sample_id'] for x in meta_base if x['strain'] == strain] assert len(s) == len(samples), "Mismatched sizes in sample strains" for sample in samples: assert sample in s, "%s not in %s " %( sample, strain ) alleles = metainfo_obj.get_nominal_alleles( strain=strain ) for allele in alleles: s = [x['sample_id'] for x in meta_base if x['strain'] == strain and x['allele_nominal'] == allele] samples = metainfo_obj.get_sample_ids( strain, allele) assert len(samples) == len(s), "Mismatched sizes in sample alleles" for sample in samples: assert sample in s, "%s not in %s " %( sample, strain ) #test age for x in meta_base: assert metainfo_obj.get_age( x['sample_id'] ) == float(x['age']), ( "age for %s does not match %d" % (x['sample_id'] , float(x['age']))) print "MetaInfo passed...." """ def test_sourcedata( local_meta, local_dataframe ): source_bucket = 'hd_source_data' d = 'norm.mean.proc.txt' md = 'metadata.txt' ad = 'annodata.txt' agilent_file = 'HDLux_agilent_gene_list.txt' syn_file = 'Mus_homo.gene_info' network_table = 'net_info_table' data_dir='/scratch/sgeadmin/test/' main_data, meta_data, anno_data,syn_file,agilent_file = hddata_process.getFromS3( source_bucket,d,md,ad, syn_file, agilent_file, data_dir) print main_data print meta_data, anno_data, syn_file, agilent_file ctr = 0 header = [] data_dict = {} with open(main_data,'r') as df: for line in df: if header: parsed = line.strip().split('\t') assert len(header) == len(parsed), "Header does not match line" for k, v in zip( header, parsed ): data_dict[k].append(float(v)) else: header = line.strip().split('\t') for sn in header: data_dict[sn] = [] header = [] annotations = [] with open(anno_data, 'r') as anno: for line in anno: if header: parsed = line.strip().split('\t') annotations.append( (int(parsed[0]),parsed[1]) ) else: header = line.strip().split('\t') for k,v in data_dict.iteritems(): assert len(v) == len(annotations), "annotations does not match input data" probe_to_row_map = {} for i,a in enumerate(annotations): if a[1] not in probe_to_row_map: probe_to_row_map[a[1]] = [] probe_to_row_map[a[1]].append(i) agilent_dict = {} #probe id -> ['ProbeID', 'TargetID', 'GeneSymbol', 'GeneName', # 'Accessions', 'Description'] with open(agilent_file, 'r') as ag: ctr = 0 header = [] for line in ag: parsed = line.strip().split('\t') if not header: header = parsed else: agilent_dict[parsed[0]] = dict( ( ((k,v) for k,v in zip(header, parsed)) ) ) syn_set_list = [] with open(syn_file, 'r') as syn: ctr = 0 for line in syn: syn_set = set() a = line.strip().split() for p in a[:5]: tt = p.split('|') for t in tt: if len(t) > 2: syn_set.add(t) syn_set_list.append(syn_set) probelist = [] gene_set = [] for probe_id, v in agilent_dict.iteritems(): my_geneset = set() for myset in syn_set_list: if v['GeneSymbol'] in myset: my_geneset |= myset if my_geneset: probelist.append(probe_id) gene_set.append(my_geneset) print probelist[:5] print gene_set[:5] sd = data.SourceData() sd.load_dataframe( local_dataframe ) gene_to_row = [] for gene in sd.genes: gene_to_probeset.append([]) for i, v in enumerate( gene_set ): if gene in v: if probe_list[i] in probe_to_row_map: for row in probe_to_row_map: gene_to_row[-1].append(row) """ def test__HDDataGen__get_network_genes( ): working_dir = '/scratch/sgeadmin/test' hddg = hddata_process.HDDataGen( working_dir ) ng = hddg._get_network_genes( 'net_info_table', 'c2.cp.biocarta.v4.0.symbols.gmt') s3 = boto.connect_s3() b = s3.get_bucket('hd_source_data') k = b.get_key('c2.cp.biocarta.v4.0.symbols.gmt') with open('tmp.tmp', 'r+') as tmp: k.get_contents_to_file(tmp) tmp.seek(0) for line in tmp: for g in line.strip().split()[2:]: if g not in ng: print line assert g in ng, "%s is missing" % g print 'test__HDDataGen__get_network_genes ... PASSED' def test__HDDataGen_get_data(): working_dir = '/scratch/sgeadmin/test' hddg = hddata_process.HDDataGen( working_dir ) data = hddg._get_data( 'norm.mean.proc.txt', 'annodata.txt') agi = hddg._get_probe_mapping( 'HDLux_agilent_gene_list.txt' ) anno = hddg._get_annotations( 'annodata.txt' ) nd_set = set(data.index.tolist()) for ind in data.index: message = "%s is in new data and has a ct of %i" assert anno['ControlType'][anno['ProbeName'] == ind] == 0,( message % (ind, anno['ControlType'][anno['ProbeName'] == ind])) print "test__HDDataGen_get_data ... PASSED" def test__HDDataGen_get_synonyms(): working_dir = '/scratch/sgeadmin/test' hddg = hddata_process.HDDataGen( working_dir ) probe_mapping = hddg._get_probe_mapping( 'HDLux_agilent_gene_list.txt' ) network_genes = hddg._get_network_genes( 'net_info_table', 'c2.cp.biocarta.v4.0.symbols.gmt') hddg._get_synonyms( probe_mapping, network_genes, 'Mus_homo.gene_info') print "test__HDDataGen_get_synonyms ... Passed" def test__HDDataGen_get_probe_to_gene_map(): working_dir = '/scratch/sgeadmin/test' hddg = hddata_process.HDDataGen( working_dir ) probe_mapping = hddg._get_probe_mapping( 'HDLux_agilent_gene_list.txt' ) network_genes = hddg._get_network_genes( 'net_info_table', 'c2.cp.biocarta.v4.0.symbols.gmt') syn_map = hddg._get_synonyms( probe_mapping, network_genes, 'Mus_homo.gene_info') ng2pm = hddg._get_probe_to_gene_map( probe_mapping, syn_map ) print "test__HDDataGen_get_probe_to_gene_map ... passes" def test__HDData_generate_dataframe(): working_dir = '/scratch/sgeadmin/test' hddg = hddata_process.HDDataGen( working_dir ) data_file = 'norm.mean.proc.txt' annotations_file = 'annodata.txt' agilent_file = 'HDLux_agilent_gene_list.txt' synonym_file = 'Mus_homo.gene_info' network_table = 'net_info_table' source_id = 'c2.cp.biocarta.v4.0.symbols.gmt' data_orig = hddg._get_data( 'norm.mean.proc.txt', 'annodata.txt') df = hddg.generate_dataframe( data_file, annotations_file, agilent_file, synonym_file, network_table, source_id ) assert all(data_orig.columns == df.columns), "Columns are fubared" desc = df.describe() for c in df.columns: if random.random() > .05: print desc[c] print "test__HDData_generate_dataframe ... Passed" if __name__ == "__main__": if not os.path.exists('/scratch/sgeadmin/test'): os.makedirs('/scratch/sgeadmin/test') s3 = boto.connect_s3() b = s3.get_bucket('hd_working_0') k = b.get_key('metadata.txt') local_meta = '/scratch/sgeadmin/test/metadata.txt' k.get_contents_to_filename(local_meta) k = b.get_key('trimmed_dataframe.pandas') local_dataframe = '/scratch/sgeadmin/test/trimmed_dataframe.pandas' k.get_contents_to_filename( local_dataframe ) test_metadata(local_meta) test__HDDataGen__get_network_genes() test__HDDataGen_get_data() test__HDDataGen_get_synonyms() test__HDDataGen_get_probe_to_gene_map() test__HDData_generate_dataframe()
gpl-3.0
kdz/test
Spec.py
1
6467
__author__ = 'kdsouza' from functools import reduce import pandas as pd from MPL_pyqt_mergewidget import * from MPL_style_formatting import * from VEdit import * from MPL_dicts import * import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.figure import Figure as MPLFigure from canopy_data_import.commands.command import Command def get_x_y(receiver): """ (receiver: Receiver) -> (Column, Column) Returns x column and y column tuple. Assumes Receiver has at least two columns, takes first two. """ selection = receiver.selection return selection[1][0], selection[1][1] def tap(x, label): print("%s: %s" % (label, x)) return x def get_editor(val): """ Any -> EditorFactory, {Str: Any} Returns customized Editor, kwargs for given attribute value. Customizing editor style done in self-defined VEdits. dict -> InstanceEditor list(str) -> CheckListEditor, {'values: val} list(other) -> EnumEditor, {'values': val} bool -> BooleanEditor rest -> TextEditor, {'auto_set': False, 'enter_set': True} """ if isinstance(val, dict): return InstanceEditor, {} if isinstance(val, list): if isinstance(val[0], str): return CheckListEditor, {'values': val} else: return EnumEditor, {'values': val} if isinstance(val, bool): return BooleanEditor, {} else: return TextEditor, {'auto_set': False, 'enter_set': True} ##### Container classes ######## class Spec(tr.HasTraits): # <- just inherit from Dict? """Container class for mpl plot keys and values.""" _dict = tr.Dict(key_trait=tr.Str, value_trait=VEdit) def __init__(self, d): """ dict{Str: builtin, Dict, or VEdit} -> dict{Str: VEdit} Digests given dict into Spec instance of nested VEdits, nested dictionaries digested into nested VEdits with Spec values. """ self._dict = {key: (val if isinstance(val, VEdit) else VEdit(Spec(val) if isinstance(val, dict) else val, *get_editor(val))) for key, val in d.items()} def __getattr__(self, attr): """ Returns value of corresponding key in _dict. """ if attr == '_dict': return self._dict elif attr in self._dict: return self._dict[attr].value def __setattr__(self, attr, new_value): """ Sets value of VEdit at specified attribute key in _dict. """ if attr == '_dict': super(Spec, self).__setattr__(attr, new_value) elif attr in self._dict: self._dict[attr].value = new_value def convert_to_items(self): """ Returns list of TraitsUI Items with corresponding editors for each key in _dict. Editors are either specified in original dictionary or computed through get_editor. """ items = [] for key, vedit in self._dict.items(): val, editor, kwargs = vedit.value, vedit.editor, vedit.kwargs if isinstance(val, Spec): items.append(trui.Item(key, editor=editor(**kwargs), style='custom')) else: items.append(trui.Item(key, editor=editor(**kwargs))) return items def default_traits_view(self): items = self.convert_to_items() return trui.View(trui.Group(*items), resizable=True) def _anytrait_changed(self, attr_name, old_val, new_val): print("%s: %s -> %s" % (attr_name, old_val, new_val)) class PlotLayout(tr.HasTraits): """Mutable container for all plots, axes, and plot specs""" spec_nodes = tr.Instance(Spec) figure = tr.Instance(MPLFigure, ()) def default_traits_view(self): # later perhaps switch to TreeEditor for collapsing return trui.View(trui.HSplit(trui.Item('figure', editor=MPLFigureEditor(), show_label=False), trui.Item('spec_nodes', editor=InstanceEditor(), style='custom')), resizable=True) ##### Pure Functions def complete(spec, receiver): """ (spec: AType, receiver: Receiver) -> AType Returns same input spec type with computed values in place of receiver functions. """ if isinstance(spec, dict): return {key: complete(val, receiver) for key, val in spec.items()} if isinstance(spec, list): return [complete(val, receiver) for val in spec] if callable(spec): return spec(receiver) if isinstance(spec, Spec): d = spec.__dict__ return Spec(complete(d, receiver)) else: return spec def merge_spec(c1, c2): """ (c1: Spec, c2: Spec) -> Spec Merges Spec (Dict {Str: Spec}, builtin, VEdit), defaulting to c1 in cases of conflict. Returns collection of same type. """ if c1 is None: return c2 if c2 is None: return c1 if isinstance(c1, list) and isinstance(c2, list): return [merge_spec(x, y) for x, y in map(None, c1, c2)] if isinstance(c1, tuple) and isinstance(c2, tuple): return tuple(merge_spec(x, y) for x, y in map(None, c1, c2)) if isinstance(c1, VEdit) and isinstance(c2, VEdit): # uses c1 editor return VEdit(merge_spec(c1.value, c2.value), c1.editor, c1.kwargs) if isinstance(c1, dict) and isinstance(c2, dict): all_keys = set(c1.iterkeys()) | set(c2.iterkeys()) return {key: merge_spec(c1.get(key), c2.get(key)) for key in all_keys} if callable(c1) or callable(c2): return lambda receiver: merge_spec(complete(c1, receiver), complete(c2, receiver)) if isinstance(c1, Spec) and isinstance(c2, Spec): d1 = c1._dict d2 = c2._dict return Spec(merge_spec(d1, d2)) return c1 ##### Command classes ##### import pandas as pd class Plot(Command): """Displays a plot on the layout""" default_spec = tr.Instance(Spec) edited_spec = tr.Instance(Spec) x = tr.Any y = tr.List() def apply(self, receiver): out_spec = merge_spec(self.edited_spec, self.default_spec) filled_out_spec = complete(out_spec, receiver) def undo(self): pass class UpdatePlot(Plot): """apply() updates given plot figure using the difference between new and old dicts""" def apply(self, receiver): pass def undo(self): pass
mit
hainm/scikit-learn
examples/cluster/plot_adjusted_for_chance_measures.py
286
4353
""" ========================================================== Adjustment for chance in clustering performance evaluation ========================================================== The following plots demonstrate the impact of the number of clusters and number of samples on various clustering performance evaluation metrics. Non-adjusted measures such as the V-Measure show a dependency between the number of clusters and the number of samples: the mean V-Measure of random labeling increases significantly as the number of clusters is closer to the total number of samples used to compute the measure. Adjusted for chance measure such as ARI display some random variations centered around a mean score of 0.0 for any number of samples and clusters. Only adjusted measures can hence safely be used as a consensus index to evaluate the average stability of clustering algorithms for a given value of k on various overlapping sub-samples of the dataset. """ print(__doc__) # Author: Olivier Grisel <olivier.grisel@ensta.org> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from time import time from sklearn import metrics def uniform_labelings_scores(score_func, n_samples, n_clusters_range, fixed_n_classes=None, n_runs=5, seed=42): """Compute score for 2 random uniform cluster labelings. Both random labelings have the same number of clusters for each value possible value in ``n_clusters_range``. When fixed_n_classes is not None the first labeling is considered a ground truth class assignment with fixed number of classes. """ random_labels = np.random.RandomState(seed).random_integers scores = np.zeros((len(n_clusters_range), n_runs)) if fixed_n_classes is not None: labels_a = random_labels(low=0, high=fixed_n_classes - 1, size=n_samples) for i, k in enumerate(n_clusters_range): for j in range(n_runs): if fixed_n_classes is None: labels_a = random_labels(low=0, high=k - 1, size=n_samples) labels_b = random_labels(low=0, high=k - 1, size=n_samples) scores[i, j] = score_func(labels_a, labels_b) return scores score_funcs = [ metrics.adjusted_rand_score, metrics.v_measure_score, metrics.adjusted_mutual_info_score, metrics.mutual_info_score, ] # 2 independent random clusterings with equal cluster number n_samples = 100 n_clusters_range = np.linspace(2, n_samples, 10).astype(np.int) plt.figure(1) plots = [] names = [] for score_func in score_funcs: print("Computing %s for %d values of n_clusters and n_samples=%d" % (score_func.__name__, len(n_clusters_range), n_samples)) t0 = time() scores = uniform_labelings_scores(score_func, n_samples, n_clusters_range) print("done in %0.3fs" % (time() - t0)) plots.append(plt.errorbar( n_clusters_range, np.median(scores, axis=1), scores.std(axis=1))[0]) names.append(score_func.__name__) plt.title("Clustering measures for 2 random uniform labelings\n" "with equal number of clusters") plt.xlabel('Number of clusters (Number of samples is fixed to %d)' % n_samples) plt.ylabel('Score value') plt.legend(plots, names) plt.ylim(ymin=-0.05, ymax=1.05) # Random labeling with varying n_clusters against ground class labels # with fixed number of clusters n_samples = 1000 n_clusters_range = np.linspace(2, 100, 10).astype(np.int) n_classes = 10 plt.figure(2) plots = [] names = [] for score_func in score_funcs: print("Computing %s for %d values of n_clusters and n_samples=%d" % (score_func.__name__, len(n_clusters_range), n_samples)) t0 = time() scores = uniform_labelings_scores(score_func, n_samples, n_clusters_range, fixed_n_classes=n_classes) print("done in %0.3fs" % (time() - t0)) plots.append(plt.errorbar( n_clusters_range, scores.mean(axis=1), scores.std(axis=1))[0]) names.append(score_func.__name__) plt.title("Clustering measures for random uniform labeling\n" "against reference assignment with %d classes" % n_classes) plt.xlabel('Number of clusters (Number of samples is fixed to %d)' % n_samples) plt.ylabel('Score value') plt.ylim(ymin=-0.05, ymax=1.05) plt.legend(plots, names) plt.show()
bsd-3-clause
IDEALLab/design_embeddings_jmd_2016
util.py
1
17261
########################################## # File: util.py # # Copyright Richard Stebbing 2014. # # Distributed under the MIT License. # # (See accompany file LICENSE or copy at # # http://opensource.org/licenses/MIT) # ########################################## # Imports import re # raise_if_not_shape def raise_if_not_shape(name, A, shape): """Raise a `ValueError` if the np.ndarray `A` does not have dimensions `shape`.""" if A.shape != shape: raise ValueError('{}.shape != {}'.format(name, shape)) # previous_float PARSE_FLOAT_RE = re.compile(r'([+-]*)0x1\.([\da-f]{13})p(.*)') def previous_float(x): """Return the next closest float (towards zero).""" s, f, e = PARSE_FLOAT_RE.match(float(x).hex().lower()).groups() f, e = int(f, 16), int(e) if f > 0: f -= 1 else: f = int('f' * 13, 16) e -= 1 return float.fromhex('{}0x1.{:013x}p{:d}'.format(s, f, e)) ############################################################################## """ Author(s): Wei Chen (wchen459@umd.edu) """ import os import sys import numpy as np from matplotlib import pyplot as plt from sklearn.decomposition import PCA from sklearn.utils.graph import graph_shortest_path from sklearn.neighbors import kneighbors_graph from scipy.sparse.csgraph import connected_components from sklearn.manifold import Isomap from sklearn.preprocessing import scale from sklearn.metrics import pairwise_distances from sklearn.neighbors import NearestNeighbors from scipy.stats import pearsonr from sklearn.externals import joblib import ConfigParser def create_dir(path): if os.path.isdir(path): pass else: os.mkdir(path) def reduce_dim(data_h, plot=False, save=False, c=None): if plot: # Scree plot plt.rc("font", size=12) pca = PCA() pca.fit(data_h) plt.plot(range(1,data_h.shape[1]+1), pca.explained_variance_ratio_) plt.xlabel('Dimensionality') plt.ylabel('Explained variance ratio') plt.title('Scree Plot') plt.show() plt.close() # Dimensionality reduction pca = PCA(n_components=.995) # 99.5% variance attained data_l = pca.fit_transform(data_h) print 'Reduced dimensionality: %d' % data_l.shape[1] if save: save_model(pca, 'xpca', c) return data_l, pca.inverse_transform def sort_eigen(M): ''' Sort the eigenvalues and eigenvectors in DESCENT order ''' w, v = np.linalg.eigh(M) idx = w.argsort()[::-1] w = w[idx] v = v[:,idx] return w, v def find_gap(metrics, threshold=.99, method='difference', multiple=False, verbose=0): ''' Find the largest gap of any NONNEGATIVE metrics (which is in DESCENT order) The returned index is before the gap threshold: needs to be specified only if method is 'percentage' multiple: whether to find multiple gaps ''' if method == 'percentage': s = np.sum(metrics) for i in range(len(metrics)): if np.sum(metrics[:i+1])/s > threshold: break if verbose == 2: plt.figure() plt.plot(metrics, 'o-') plt.title('metrics') plt.show() return i else: if method == 'difference': m0 = np.array(metrics[:-1]) m1 = np.array(metrics[1:]) d = m0-m1 elif method == 'divide': metrics = np.clip(metrics, np.finfo(float).eps, np.inf) m0 = np.array(metrics[:-1]) m1 = np.array(metrics[1:]) d = m0/m1 else: print 'No method called %s!' % method sys.exit(0) if multiple: # dmin = np.min(d) # dmax = np.max(d) # t = dmin + (dmax-dmin)/10 # set a threshold # n_gap = sum(d > t) # idx = d.argsort()[::-1][:n_gap] # arggap = idx tol = 1e-4 arggap = [] if d[0] > tol: arggap.append(0) for i in range(len(d)-1): if d[i+1] > d[i]: arggap.append(i+1) arggap = np.array(arggap) else: arggap = np.argmax(d) if verbose == 2: plt.figure() plt.subplot(211) plt.plot(metrics, 'o') plt.title('metrics') plt.subplot(212) plt.plot(d, 'o') # plt.plot([0, len(d)], [t, t], 'g--') plt.title('gaps') plt.show() gap = d[arggap] return arggap, gap def create_graph(X, n_neighbors, include_self=False, verbose=0): kng = kneighbors_graph(X, n_neighbors, mode='distance', include_self=include_self) nb_graph = graph_shortest_path(kng, directed=False) if verbose: # Visualize nearest neighbor graph neigh = NearestNeighbors().fit(X) nbrs = neigh.kneighbors(n_neighbors=n_neighbors, return_distance=False) visualize_graph(X, nbrs) return nb_graph def get_geo_dist(X, K='auto', verbose=0): m = X.shape[0] if K == 'auto': # Choose the smallest k that gives a fully connected graph for k in range(2, m): G = create_graph(X, k, verbose=verbose) if connected_components(G, directed=False, return_labels=False) == 1: break; return G, k else: return create_graph(X, K, verbose=verbose) def get_k_range(X, verbose=0): N = X.shape[0] # Select k_min for k in range(1, N): G = create_graph(X, k, include_self=False, verbose=verbose) if connected_components(G,directed=False,return_labels=False) == 1: break; k_min = k # Select k_max for k in range(k_min, N): kng = kneighbors_graph(X, k, include_self=False).toarray() A = np.logical_or(kng, kng.T) # convert to undirrected graph P = np.sum(A)/2 if 2*P/float(N) > k+2: break; k_max = k-1#min(k_min+10, N) if verbose == 2: print 'k_range: [%d, %d]' % (k_min, k_max) if k_max < k_min: print 'No suitable neighborhood size!' return k_min, k_max def get_candidate(X, dim, k_min, k_max, verbose=0): errs = [] k_candidates = [] for k in range(k_min, k_max+1): isomap = Isomap(n_neighbors=k, n_components=dim).fit(X) rec_err = isomap.reconstruction_error() errs.append(rec_err) i = k - k_min if i > 1 and errs[i-1] < errs[i-2] and errs[i-1] < errs[i]: k_candidates.append(k-1) if len(k_candidates) == 0: k_candidates.append(k) if verbose == 2: print 'k_candidates: ', k_candidates plt.figure() plt.rc("font", size=12) plt.plot(range(k_min, k_max+1), errs, '-o') plt.xlabel('Neighborhood size') plt.ylabel('Reconstruction error') plt.title('Select candidates of neighborhood size') plt.show() return k_candidates def pick_k(X, dim, k_min=None, k_max=None, verbose=0): ''' Pick optimal neighborhood size for isomap algothm Reference: Samko, O., Marshall, A. D., & Rosin, P. L. (2006). Selection of the optimal parameter value for the Isomap algorithm. Pattern Recognition Letters, 27(9), 968-979. ''' if k_min is None or k_max is None: k_min, k_max = get_k_range(X, verbose=verbose) ccs = [] k_candidates = range(k_min, k_max+1)#get_candidate(X, dim, k_min, k_max, verbose=verbose) for k in k_candidates: isomap = Isomap(n_neighbors=k, n_components=dim).fit(X) F = isomap.fit_transform(X) distF = pairwise_distances(F) distX = create_graph(X, k, verbose=verbose) cc = 1-pearsonr(distX.flatten(), distF.flatten())[0]**2 ccs.append(cc) k_opt = k_candidates[np.argmin(ccs)] if verbose == 2: print 'k_opt: ', k_opt plt.figure() plt.rc("font", size=12) plt.plot(k_candidates, ccs, '-o') plt.xlabel('Neighborhood size') plt.ylabel('Residual variance') plt.title('Select optimal neighborhood size') plt.show() return k_opt def estimate_dim(data, verbose=0): ''' Estimate intrinsic dimensionality of data data: input data Reference: "Samko, O., Marshall, A. D., & Rosin, P. L. (2006). Selection of the optimal parameter value for the Isomap algorithm. Pattern Recognition Letters, 27(9), 968-979." ''' # Standardize by center to the mean and component wise scale to unit variance data = scale(data) # The reconstruction error will decrease as n_components is increased until n_components == intr_dim errs = [] found = False k_min, k_max = get_k_range(data, verbose=verbose) for dim in range(1, data.shape[1]+1): k_opt = pick_k(data, dim, k_min, k_max, verbose=verbose) isomap = Isomap(n_neighbors=k_opt, n_components=dim).fit(data) err = isomap.reconstruction_error() #print(err) errs.append(err) if dim > 2 and errs[dim-2]-errs[dim-1] < .5 * (errs[dim-3]-errs[dim-2]): intr_dim = dim-1 found = True break if not found: intr_dim = 1 # intr_dim = find_gap(errs, method='difference', verbose=verbose)[0] + 1 # intr_dim = find_gap(errs, method='percentage', threshold=.9, verbose=verbose) + 1 if verbose == 2: plt.figure() plt.rc("font", size=12) plt.plot(range(1,dim+1), errs, '-o') plt.xlabel('Dimensionality') plt.ylabel('Reconstruction error') plt.title('Select intrinsic dimension') plt.show() return intr_dim def get_singular_ratio(X_nbr, d): x_mean = np.mean(X_nbr, axis=1).reshape(-1,1) s = np.linalg.svd(X_nbr-x_mean, compute_uv=0) r = (np.sum(s[d:]**2.)/np.sum(s[:d]**2.))**.5 return r def select_neighborhood(X, dims, k_range=None, get_full_ind=False, verbose=0): ''' Inspired by the Neighborhood Contraction and Neighborhood Expansion algorithms The selected neighbors for each sample point should reflect the local geometric structure of the manifold Reference: "Zhang, Z., Wang, J., & Zha, H. (2012). Adaptive manifold learning. IEEE Transactions on Pattern Analysis and Machine Intelligence, 34(2), 253-265." ''' print 'Selecting neighborhood ... ' m = X.shape[0] if type(dims) == int: dims = [dims] * m if k_range is None: k_min, k_max = get_k_range(X) else: k_min, k_max = k_range # G = get_geo_dist(X, verbose=verbose)[0] # geodesic distances # ind = np.argsort(G)[:,:k_max+1] neigh = NearestNeighbors().fit(X) ind = neigh.kneighbors(n_neighbors=k_max, return_distance=False) ind = np.concatenate((np.arange(m).reshape(-1,1), ind), axis=1) nbrs = [] # Choose eta k0 = k_max r0s =[] for j in range(m): X_nbr0 = X[ind[j,:k0]].T r0 = get_singular_ratio(X_nbr0, dims[j]) r0s.append(r0) r0s.sort(reverse=True) j0 = find_gap(r0s, method='divide')[0] eta = (r0s[j0]+r0s[j0+1])/2 # eta = 0.02 if verbose: print 'eta = %f' % eta for i in range(m): ''' Neighborhood Contraction ''' rs = [] for k in range(k_max, k_min-1, -1): X_nbr = X[ind[i,:k]].T r = get_singular_ratio(X_nbr, dims[i]) rs.append(r) if r < eta: ki = k break if k == k_min: ki = k_max-np.argmin(rs) nbrs.append(ind[i,:ki]) ''' Neighborhood Expansion ''' pca = PCA(n_components=dims[i]).fit(X[nbrs[i]]) nbr_out = ind[i, ki:] # neighbors of x_i outside the neighborhood set by Neighborhood Contraction for j in nbr_out: theta = pca.transform(X[j].reshape(1,-1)) err = np.linalg.norm(pca.inverse_transform(theta) - X[j]) # reconstruction error if err < eta * np.linalg.norm(theta): nbrs[i] = np.append(nbrs[i], [j]) # print ki, len(nbrs[i]) # print max([len(nbrs[i]) for i in range(m)]) if verbose: # Visualize nearest neighbor graph visualize_graph(X, nbrs) # Visualize neighborhood selection if X.shape[1] > 3: pca = PCA(n_components=3) F = pca.fit_transform(X) else: F = np.zeros((X.shape[0], 3)) F[:,:X.shape[1]] = X fig3d = plt.figure() ax3d = fig3d.add_subplot(111, projection = '3d') # Create cubic bounding box to simulate equal aspect ratio max_range = np.array([F[:,0].max()-F[:,0].min(), F[:,1].max()-F[:,1].min(), F[:,2].max()-F[:,2].min()]).max() Xb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][0].flatten() + 0.5*(F[:,0].max()+F[:,0].min()) Yb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][1].flatten() + 0.5*(F[:,1].max()+F[:,1].min()) Zb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][2].flatten() + 0.5*(F[:,2].max()+F[:,2].min()) ax3d.scatter(Xb, Yb, Zb, c='white', alpha=0) # Plot point sets in 3D plot_samples = [0, 1] nbr_indices = [] for i in plot_samples: nbr_indices = list(set(nbr_indices) | set(nbrs[i])) F_ = np.delete(F, nbr_indices, axis=0) ax3d.scatter(F_[:,0], F_[:,1], F_[:,2], c='white') colors = ['b', 'g', 'y', 'r', 'c', 'm', 'y', 'k'] from itertools import cycle colorcycler = cycle(colors) for i in plot_samples: color = next(colorcycler) ax3d.scatter(F[nbrs[i][1:],0], F[nbrs[i][1:],1], F[nbrs[i][1:],2], marker='*', c=color, s=100) ax3d.scatter(F[i,0], F[i,1], F[i,2], marker='x', c=color, s=100) plt.show() if get_full_ind: return nbrs, ind else: return nbrs def visualize_graph(X, nbrs): # Reduce dimensionality if X.shape[1] > 3: pca = PCA(n_components=3) F = pca.fit_transform(X) else: F = np.zeros((X.shape[0], 3)) F[:,:X.shape[1]] = X m = F.shape[0] fig3d = plt.figure() ax3d = fig3d.add_subplot(111, projection = '3d') # Create cubic bounding box to simulate equal aspect ratio max_range = np.array([F[:,0].max()-F[:,0].min(), F[:,1].max()-F[:,1].min(), F[:,2].max()-F[:,2].min()]).max() Xb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][0].flatten() + 0.5*(F[:,0].max()+F[:,0].min()) Yb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][1].flatten() + 0.5*(F[:,1].max()+F[:,1].min()) Zb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][2].flatten() + 0.5*(F[:,2].max()+F[:,2].min()) ax3d.scatter(Xb, Yb, Zb, c='white', alpha=0) # Plot point sets in 3D ax3d.scatter(F[:,0], F[:,1], F[:,2], c='blue') # Plot edges # for i in range(m-1): # for j in range(i+1, m): # if j in nbrs[i]: # line = np.vstack((F[i], F[j])) # ax3d.plot(line[:,0], line[:,1], line[:,2], c='green') for i in [3]: for j in range(i+1, m): if j in nbrs[i]: line = np.vstack((F[i], F[j])) ax3d.plot(line[:,0], line[:,1], line[:,2], c='green') plt.show() def get_fname(mname, c, directory='./trained_models/', extension='pkl'): config = ConfigParser.ConfigParser() config.read('config.ini') source = config.get('Global', 'source') noise_scale = config.getfloat('Global', 'noise_scale') if source == 'sf': alpha = config.getfloat('Superformula', 'nonlinearity') beta = config.getint('Superformula', 'n_clusters') sname = source + '-' + str(beta) + '-' + str(alpha) elif source == 'glass' or source[:3] == 'sf-': sname = source if c is None: fname = '%s/%s_%.4f_%s.%s' % (directory, sname, noise_scale, mname, extension) else: fname = '%s/%s_%.4f_%s_%d.%s' % (directory, sname, noise_scale, mname, c, extension) return fname def save_model(model, mname, c=None): # Get the file name fname = get_fname(mname, c) # Save the model joblib.dump(model, fname, compress=9) print 'Model ' + mname + ' saved!' def load_model(mname, c=None): # Get the file name fname = get_fname(mname, c) # Load the model model = joblib.load(fname) return model def save_array(array, dname, c=None): # Get the file name fname = get_fname(dname, c, extension='npy') # Save the model np.save(fname, array) print 'Model ' + dname + ' saved!' def load_array(dname, c=None): # Get the file name fname = get_fname(dname, c, extension='npy') # Load the model array = np.load(fname) return array
mit
jskDr/jamespy_py3
medic/dl.py
1
12919
from sklearn import model_selection, metrics from sklearn.preprocessing import MinMaxScaler import numpy as np import matplotlib.pyplot as plt import os import keras from keras import backend as K from keras.utils import np_utils from keras.models import Model from keras.layers import Input, Conv2D, BatchNormalization, \ Activation, MaxPooling2D, Flatten, Dense, Dropout from keras.preprocessing.image import ImageDataGenerator import kkeras from keraspp import sfile def rgb_to_gray(X): return 0.2989 * X[..., 0] + 0.5870 * X[..., 1] + 0.1140 * X[..., 2] class CNN(Model): def __init__(model, nb_classes, in_shape=None): model.nb_classes = nb_classes model.in_shape = in_shape model.build_model() super().__init__(model.x, model.y) model.compile() def build_model(model): nb_classes = model.nb_classes in_shape = model.in_shape # number of convolutional filters to use nb_filters = 8 # size of pooling area for max pooling pool_size = (50, 50) # convolution kernel size kernel_size = (20, 20) # super(CNN, model).__init__() x = Input(in_shape) h = Conv2D(nb_filters, kernel_size, input_shape=in_shape)(x) h = BatchNormalization()(h) h = Activation('tanh')(h) h = Dropout(0.05)(h) h = MaxPooling2D(pool_size=pool_size)(h) h = Flatten()(h) z_cl = h h = Dense(4)(h) h = BatchNormalization()(h) h = Activation('tanh')(h) h = Dropout(0.05)(h) z_fl = h y = Dense(nb_classes, activation='softmax')(h) model.cl_part = Model(x, z_cl) model.fl_part = Model(x, z_fl) model.x, model.y = x, y def compile(model): Model.compile(model, loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy']) class CNN_LENET(CNN): def __init__(model, nb_classes, in_shape): super().__init__(nb_classes, in_shape=in_shape) def build_model(model): """ Tip --- Make a callable object using class - https://stackoverflow.com/questions/15719172/overload-operator-in-python -- def __call__(self, ...) """ nb_classes = model.nb_classes in_shape = model.in_shape # super().__init__() x = Input(in_shape) h = Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=in_shape)(x) h = Conv2D(64, (3, 3), activation='relu')(h) h = MaxPooling2D(pool_size=(2, 2))(h) h = Dropout(0.25)(h) h = Flatten()(h) h = Dense(128, activation='relu')(h) h = Dropout(0.5)(h) y = Dense(nb_classes, activation='softmax', name='preds')(h) model.x, model.y = x, y def compile(model): Model.compile(model, loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) def cnn_lenet_org(nb_classes, in_shape): x = Input(in_shape) h = Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=in_shape)(x) h = Conv2D(64, (3, 3), activation='relu')(h) h = MaxPooling2D(pool_size=(2, 2))(h) h = Dropout(0.25)(h) h = Flatten()(h) h = Dense(128, activation='relu')(h) h = Dropout(0.5)(h) y = Dense(nb_classes, activation='softmax', name='preds')(h) model = Model(x, y) model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy']) return model cnn_lenet = cnn_lenet_org def cnn_lenet_32(nb_classes, in_shape): x = Input(in_shape) h = Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=in_shape)(x) h = Conv2D(64, (3, 3), activation='relu')(h) h = MaxPooling2D(pool_size=(2, 2))(h) h = Dropout(0.25)(h) h = Flatten()(h) h = Dense(32, activation='relu')(h) h = Dropout(0.5)(h) y = Dense(nb_classes, activation='softmax', name='preds')(h) model = Model(x, y) model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy']) return model class Data(): def __init__(self, X, y, img_rows, img_cols, nb_classes): """ X is originally vector. Hence, it will be transformed to 2D images with a channel (i.e, 3D). """ if K.image_dim_ordering() == 'th': X = X.reshape(X.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: X = X.reshape(X.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) # the data, shuffled and split between train and test sets X_train, X_test, y_train, y_test = model_selection.train_test_split( X, y, test_size=0.2, random_state=0) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 print('X_train shape:', X_train.shape) print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) self.X_train, self.X_test = X_train, X_test self.Y_train, self.Y_test = Y_train, Y_test self.y_train, self.y_test = y_train, y_test self.input_shape = input_shape class DataSet(): def __init__(self, X, y, nb_classes, scaling=True, test_size=0.2, random_state=0): """ X is originally vector. Hence, it will be transformed to 2D images with a channel (i.e, 3D). Preprocessing: 0 ~ 255 --> around -128 ~ 128 Pretrained networks: ~128 ~ 128 """ self.X = X self.y = y self.nb_classes = nb_classes self.add_channels() X = self.X # the data, shuffled and split between train and test sets X_train, X_test, y_train, y_test = model_selection.train_test_split( X, y, test_size=0.2, random_state=random_state) print(X_train.shape, y_train.shape) X_train = X_train.astype('float32') X_test = X_test.astype('float32') if scaling: # scaling to have (0, 1) for each feature (each pixel) scaler = MinMaxScaler() n = X_train.shape[0] X_train = scaler.fit_transform(X_train.reshape(n, -1)).reshape(X_train.shape) n = X_test.shape[0] X_test = scaler.transform(X_test.reshape(n, -1)).reshape(X_test.shape) self.scaler = scaler print('X_train shape:', X_train.shape) print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) self.X_train, self.X_test = X_train, X_test self.Y_train, self.Y_test = Y_train, Y_test self.y_train, self.y_test = y_train, y_test # self.input_shape = input_shape # KFold is not stated yet # self.kfold_state = 'Lock' def add_channels(self): X = self.X if len(X.shape) == 3: N, img_rows, img_cols = X.shape if K.image_dim_ordering() == 'th': X = X.reshape(X.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: X = X.reshape(X.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) else: input_shape = X.shape[1:] # channel is already included. self.X = X self.input_shape = input_shape def init_kfold(self, cv=5): self.kfold_kf = model_selection.KFold(n_splits=cv, shuffle=True) def iter_kfold(self): kf = self.kfold_kf X = self.X y = self.y nb_classes = self.nb_classes for cv_i, (train_index, test_index) in enumerate(kf.split(X)): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) self.X_train, self.X_test = X_train, X_test self.Y_train, self.Y_test = Y_train, Y_test self.y_train, self.y_test = y_train, y_test print('Effective #Classes for train, test', set(y_train), set(y_test)) yield cv_i class Machine(): def __init__(self, X, y, Lx, Ly, nb_classes=2, fig=True): data = Data(X, y, Lx, Ly, nb_classes) print('data.input_shape', data.input_shape) model = CNN(nb_classes, data.input_shape) self.data = data self.model = model self.fig = fig def fit(self, nb_epoch=10, batch_size=128, verbose=1): data = self.data model = self.model history = model.fit(data.X_train, data.Y_train, batch_size=batch_size, epochs=nb_epoch, verbose=verbose, validation_data=(data.X_test, data.Y_test)) return history def run(self, nb_epoch=10, batch_size=128, verbose=1): data = self.data model = self.model fig = self.fig history = self.fit(nb_epoch=nb_epoch, batch_size=batch_size, verbose=verbose) score = model.evaluate(data.X_test, data.Y_test, verbose=0) print('Confusion matrix') Y_test_pred = model.predict(data.X_test, verbose=0) y_test_pred = np.argmax(Y_test_pred, axis=1) print(metrics.confusion_matrix(data.y_test, y_test_pred)) print('Test score:', score[0]) print('Test accuracy:', score[1]) # Save results foldname = sfile.makenewfold(prefix='output_', type='datetime') kkeras.save_history_history('history_history.npy', history.history, fold=foldname) model.save_weights(os.path.join(foldname, 'dl_model.h5')) print('Output results are saved in', foldname) if fig: plt.figure(figsize=(12, 4)) plt.subplot(1, 2, 1) kkeras.plot_acc(history) plt.subplot(1, 2, 2) kkeras.plot_loss(history) plt.show() self.history = history return foldname class Machine_cnn_lenet(Machine): def __init__(self, X, y, nb_classes=2, fig=True): data = DataSet(X, y, nb_classes) self.nb_classes = nb_classes self.data = data self.fig = fig self.set_model() def set_model(self): nb_classes = self.nb_classes data = self.data self.model = cnn_lenet(nb_classes=nb_classes, in_shape=data.input_shape) def run_cv(self, nb_epoch=10, batch_size=128, verbose=1, cv=5): """ cv is K of KFold crossvalidation """ self.data.init_kfold(cv=cv) for cv_i in self.data.iter_kfold(): print('CV#', cv_i) self.set_model() self.run(nb_epoch=nb_epoch, batch_size=batch_size, verbose=verbose) class Machine_Generator(Machine_cnn_lenet): def __init__(self, X, y, nb_classes=2, steps_per_epoch=10, fig=True, gen_param_dict=None): super().__init__(X, y, nb_classes=nb_classes, fig=fig) self.set_generator(steps_per_epoch=steps_per_epoch, gen_param_dict=gen_param_dict) def set_generator(self, steps_per_epoch=10, gen_param_dict=None): if gen_param_dict is not None: self.generator = ImageDataGenerator(**gen_param_dict) else: self.generator = ImageDataGenerator() print(self.data.X_train.shape) self.generator.fit(self.data.X_train, seed=0) self.steps_per_epoch = steps_per_epoch def fit(self, nb_epoch=10, batch_size=64, verbose=1): model = self.model data = self.data generator = self.generator steps_per_epoch = self.steps_per_epoch history = model.fit_generator(generator.flow(data.X_train, data.Y_train, batch_size=batch_size), epochs=nb_epoch, steps_per_epoch=steps_per_epoch, validation_data=(data.X_test, data.Y_test)) return history def fit_scaling(scaler, x_train): s1 = x_train.shape[0] return scaler.fit_transform(x_train.reshape(s1, -1)).reshape(x_train.shape) def scaling(scaler, x_train): s1 = x_train.shape[0] return scaler.transform(x_train.reshape(s1, -1)).reshape(x_train.shape) def rescaling(scaler, x_train): s1 = x_train.shape[0] return scaler.inverse_transform(x_train.reshape(s1, -1)).reshape(x_train.shape)
mit
djgagne/scikit-learn
sklearn/feature_selection/tests/test_from_model.py
244
1593
import numpy as np import scipy.sparse as sp from nose.tools import assert_raises, assert_true from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_greater from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from sklearn.linear_model import SGDClassifier from sklearn.svm import LinearSVC iris = load_iris() def test_transform_linear_model(): for clf in (LogisticRegression(C=0.1), LinearSVC(C=0.01, dual=False), SGDClassifier(alpha=0.001, n_iter=50, shuffle=True, random_state=0)): for thresh in (None, ".09*mean", "1e-5 * median"): for func in (np.array, sp.csr_matrix): X = func(iris.data) clf.set_params(penalty="l1") clf.fit(X, iris.target) X_new = clf.transform(X, thresh) if isinstance(clf, SGDClassifier): assert_true(X_new.shape[1] <= X.shape[1]) else: assert_less(X_new.shape[1], X.shape[1]) clf.set_params(penalty="l2") clf.fit(X_new, iris.target) pred = clf.predict(X_new) assert_greater(np.mean(pred == iris.target), 0.7) def test_invalid_input(): clf = SGDClassifier(alpha=0.1, n_iter=10, shuffle=True, random_state=None) clf.fit(iris.data, iris.target) assert_raises(ValueError, clf.transform, iris.data, "gobbledigook") assert_raises(ValueError, clf.transform, iris.data, ".5 * gobbledigook")
bsd-3-clause
ibmsoe/tensorflow
tensorflow/contrib/learn/python/learn/dataframe/tensorflow_dataframe.py
75
29377
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """TensorFlowDataFrame implements convenience functions using TensorFlow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import csv import numpy as np from tensorflow.contrib.learn.python.learn.dataframe import dataframe as df from tensorflow.contrib.learn.python.learn.dataframe.transforms import batch from tensorflow.contrib.learn.python.learn.dataframe.transforms import csv_parser from tensorflow.contrib.learn.python.learn.dataframe.transforms import example_parser from tensorflow.contrib.learn.python.learn.dataframe.transforms import in_memory_source from tensorflow.contrib.learn.python.learn.dataframe.transforms import reader_source from tensorflow.contrib.learn.python.learn.dataframe.transforms import sparsify from tensorflow.contrib.learn.python.learn.dataframe.transforms import split_mask from tensorflow.python.client import session as sess from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.ops import io_ops from tensorflow.python.ops import parsing_ops from tensorflow.python.ops import variables from tensorflow.python.platform import gfile from tensorflow.python.training import coordinator from tensorflow.python.training import queue_runner as qr def _expand_file_names(filepatterns): """Takes a list of file patterns and returns a list of resolved file names.""" if not isinstance(filepatterns, (list, tuple, set)): filepatterns = [filepatterns] filenames = set() for filepattern in filepatterns: names = set(gfile.Glob(filepattern)) filenames |= names return list(filenames) def _dtype_to_nan(dtype): if dtype is dtypes.string: return b"" elif dtype.is_integer: return np.nan elif dtype.is_floating: return np.nan elif dtype is dtypes.bool: return np.nan else: raise ValueError("Can't parse type without NaN into sparse tensor: %s" % dtype) def _get_default_value(feature_spec): if isinstance(feature_spec, parsing_ops.FixedLenFeature): return feature_spec.default_value else: return _dtype_to_nan(feature_spec.dtype) class TensorFlowDataFrame(df.DataFrame): """TensorFlowDataFrame implements convenience functions using TensorFlow.""" def run(self, num_batches=None, graph=None, session=None, start_queues=True, initialize_variables=True, **kwargs): """Builds and runs the columns of the `DataFrame` and yields batches. This is a generator that yields a dictionary mapping column names to evaluated columns. Args: num_batches: the maximum number of batches to produce. If none specified, the returned value will iterate through infinite batches. graph: the `Graph` in which the `DataFrame` should be built. session: the `Session` in which to run the columns of the `DataFrame`. start_queues: if true, queues will be started before running and halted after producting `n` batches. initialize_variables: if true, variables will be initialized. **kwargs: Additional keyword arguments e.g. `num_epochs`. Yields: A dictionary, mapping column names to the values resulting from running each column for a single batch. """ if graph is None: graph = ops.get_default_graph() with graph.as_default(): if session is None: session = sess.Session() self_built = self.build(**kwargs) keys = list(self_built.keys()) cols = list(self_built.values()) if initialize_variables: if variables.local_variables(): session.run(variables.local_variables_initializer()) if variables.global_variables(): session.run(variables.global_variables_initializer()) if start_queues: coord = coordinator.Coordinator() threads = qr.start_queue_runners(sess=session, coord=coord) i = 0 while num_batches is None or i < num_batches: i += 1 try: values = session.run(cols) yield collections.OrderedDict(zip(keys, values)) except errors.OutOfRangeError: break if start_queues: coord.request_stop() coord.join(threads) def select_rows(self, boolean_series): """Returns a `DataFrame` with only the rows indicated by `boolean_series`. Note that batches may no longer have consistent size after calling `select_rows`, so the new `DataFrame` may need to be rebatched. For example: ''' filtered_df = df.select_rows(df["country"] == "jp").batch(64) ''' Args: boolean_series: a `Series` that evaluates to a boolean `Tensor`. Returns: A new `DataFrame` with the same columns as `self`, but selecting only the rows where `boolean_series` evaluated to `True`. """ result = type(self)() for key, col in self._columns.items(): try: result[key] = col.select_rows(boolean_series) except AttributeError as e: raise NotImplementedError(( "The select_rows method is not implemented for Series type {}. " "Original error: {}").format(type(col), e)) return result def split(self, index_series, proportion, batch_size=None): """Deterministically split a `DataFrame` into two `DataFrame`s. Note this split is only as deterministic as the underlying hash function; see `tf.string_to_hash_bucket_fast`. The hash function is deterministic for a given binary, but may change occasionally. The only way to achieve an absolute guarantee that the split `DataFrame`s do not change across runs is to materialize them. Note too that the allocation of a row to one partition or the other is evaluated independently for each row, so the exact number of rows in each partition is binomially distributed. Args: index_series: a `Series` of unique strings, whose hash will determine the partitioning; or the name in this `DataFrame` of such a `Series`. (This `Series` must contain strings because TensorFlow provides hash ops only for strings, and there are no number-to-string converter ops.) proportion: The proportion of the rows to select for the 'left' partition; the remaining (1 - proportion) rows form the 'right' partition. batch_size: the batch size to use when rebatching the left and right `DataFrame`s. If None (default), the `DataFrame`s are not rebatched; thus their batches will have variable sizes, according to which rows are selected from each batch of the original `DataFrame`. Returns: Two `DataFrame`s containing the partitioned rows. """ if isinstance(index_series, str): index_series = self[index_series] left_mask, = split_mask.SplitMask(proportion)(index_series) right_mask = ~left_mask left_rows = self.select_rows(left_mask) right_rows = self.select_rows(right_mask) if batch_size: left_rows = left_rows.batch(batch_size=batch_size, shuffle=False) right_rows = right_rows.batch(batch_size=batch_size, shuffle=False) return left_rows, right_rows def split_fast(self, index_series, proportion, batch_size, base_batch_size=1000): """Deterministically split a `DataFrame` into two `DataFrame`s. Note this split is only as deterministic as the underlying hash function; see `tf.string_to_hash_bucket_fast`. The hash function is deterministic for a given binary, but may change occasionally. The only way to achieve an absolute guarantee that the split `DataFrame`s do not change across runs is to materialize them. Note too that the allocation of a row to one partition or the other is evaluated independently for each row, so the exact number of rows in each partition is binomially distributed. Args: index_series: a `Series` of unique strings, whose hash will determine the partitioning; or the name in this `DataFrame` of such a `Series`. (This `Series` must contain strings because TensorFlow provides hash ops only for strings, and there are no number-to-string converter ops.) proportion: The proportion of the rows to select for the 'left' partition; the remaining (1 - proportion) rows form the 'right' partition. batch_size: the batch size to use when rebatching the left and right `DataFrame`s. If None (default), the `DataFrame`s are not rebatched; thus their batches will have variable sizes, according to which rows are selected from each batch of the original `DataFrame`. base_batch_size: the batch size to use for materialized data, prior to the split. Returns: Two `DataFrame`s containing the partitioned rows. """ if isinstance(index_series, str): index_series = self[index_series] left_mask, = split_mask.SplitMask(proportion)(index_series) right_mask = ~left_mask self["left_mask__"] = left_mask self["right_mask__"] = right_mask # TODO(soergel): instead of base_batch_size can we just do one big batch? # avoid computing the hashes twice m = self.materialize_to_memory(batch_size=base_batch_size) left_rows_df = m.select_rows(m["left_mask__"]) right_rows_df = m.select_rows(m["right_mask__"]) del left_rows_df[["left_mask__", "right_mask__"]] del right_rows_df[["left_mask__", "right_mask__"]] # avoid recomputing the split repeatedly left_rows_df = left_rows_df.materialize_to_memory(batch_size=batch_size) right_rows_df = right_rows_df.materialize_to_memory(batch_size=batch_size) return left_rows_df, right_rows_df def run_one_batch(self): """Creates a new 'Graph` and `Session` and runs a single batch. Returns: A dictionary mapping column names to numpy arrays that contain a single batch of the `DataFrame`. """ return list(self.run(num_batches=1))[0] def run_one_epoch(self): """Creates a new 'Graph` and `Session` and runs a single epoch. Naturally this makes sense only for DataFrames that fit in memory. Returns: A dictionary mapping column names to numpy arrays that contain a single epoch of the `DataFrame`. """ # batches is a list of dicts of numpy arrays batches = [b for b in self.run(num_epochs=1)] # first invert that to make a dict of lists of numpy arrays pivoted_batches = {} for k in batches[0].keys(): pivoted_batches[k] = [] for b in batches: for k, v in b.items(): pivoted_batches[k].append(v) # then concat the arrays in each column result = {k: np.concatenate(column_batches) for k, column_batches in pivoted_batches.items()} return result def materialize_to_memory(self, batch_size): unordered_dict_of_arrays = self.run_one_epoch() # there may already be an 'index' column, in which case from_ordereddict) # below will complain because it wants to generate a new one. # for now, just remove it. # TODO(soergel): preserve index history, potentially many levels deep del unordered_dict_of_arrays["index"] # the order of the columns in this dict is arbitrary; we just need it to # remain consistent. ordered_dict_of_arrays = collections.OrderedDict(unordered_dict_of_arrays) return TensorFlowDataFrame.from_ordereddict(ordered_dict_of_arrays, batch_size=batch_size) def batch(self, batch_size, shuffle=False, num_threads=1, queue_capacity=None, min_after_dequeue=None, seed=None): """Resize the batches in the `DataFrame` to the given `batch_size`. Args: batch_size: desired batch size. shuffle: whether records should be shuffled. Defaults to true. num_threads: the number of enqueueing threads. queue_capacity: capacity of the queue that will hold new batches. min_after_dequeue: minimum number of elements that can be left by a dequeue operation. Only used if `shuffle` is true. seed: passed to random shuffle operations. Only used if `shuffle` is true. Returns: A `DataFrame` with `batch_size` rows. """ column_names = list(self._columns.keys()) if shuffle: batcher = batch.ShuffleBatch(batch_size, output_names=column_names, num_threads=num_threads, queue_capacity=queue_capacity, min_after_dequeue=min_after_dequeue, seed=seed) else: batcher = batch.Batch(batch_size, output_names=column_names, num_threads=num_threads, queue_capacity=queue_capacity) batched_series = batcher(list(self._columns.values())) dataframe = type(self)() dataframe.assign(**(dict(zip(column_names, batched_series)))) return dataframe @classmethod def _from_csv_base(cls, filepatterns, get_default_values, has_header, column_names, num_threads, enqueue_size, batch_size, queue_capacity, min_after_dequeue, shuffle, seed): """Create a `DataFrame` from CSV files. If `has_header` is false, then `column_names` must be specified. If `has_header` is true and `column_names` are specified, then `column_names` overrides the names in the header. Args: filepatterns: a list of file patterns that resolve to CSV files. get_default_values: a function that produces a list of default values for each column, given the column names. has_header: whether or not the CSV files have headers. column_names: a list of names for the columns in the CSV files. num_threads: the number of readers that will work in parallel. enqueue_size: block size for each read operation. batch_size: desired batch size. queue_capacity: capacity of the queue that will store parsed lines. min_after_dequeue: minimum number of elements that can be left by a dequeue operation. Only used if `shuffle` is true. shuffle: whether records should be shuffled. Defaults to true. seed: passed to random shuffle operations. Only used if `shuffle` is true. Returns: A `DataFrame` that has columns corresponding to `features` and is filled with examples from `filepatterns`. Raises: ValueError: no files match `filepatterns`. ValueError: `features` contains the reserved name 'index'. """ filenames = _expand_file_names(filepatterns) if not filenames: raise ValueError("No matching file names.") if column_names is None: if not has_header: raise ValueError("If column_names is None, has_header must be true.") with gfile.GFile(filenames[0]) as f: column_names = csv.DictReader(f).fieldnames if "index" in column_names: raise ValueError( "'index' is reserved and can not be used for a column name.") default_values = get_default_values(column_names) reader_kwargs = {"skip_header_lines": (1 if has_header else 0)} index, value = reader_source.TextFileSource( filenames, reader_kwargs=reader_kwargs, enqueue_size=enqueue_size, batch_size=batch_size, queue_capacity=queue_capacity, shuffle=shuffle, min_after_dequeue=min_after_dequeue, num_threads=num_threads, seed=seed)() parser = csv_parser.CSVParser(column_names, default_values) parsed = parser(value) column_dict = parsed._asdict() column_dict["index"] = index dataframe = cls() dataframe.assign(**column_dict) return dataframe @classmethod def from_csv(cls, filepatterns, default_values, has_header=True, column_names=None, num_threads=1, enqueue_size=None, batch_size=32, queue_capacity=None, min_after_dequeue=None, shuffle=True, seed=None): """Create a `DataFrame` from CSV files. If `has_header` is false, then `column_names` must be specified. If `has_header` is true and `column_names` are specified, then `column_names` overrides the names in the header. Args: filepatterns: a list of file patterns that resolve to CSV files. default_values: a list of default values for each column. has_header: whether or not the CSV files have headers. column_names: a list of names for the columns in the CSV files. num_threads: the number of readers that will work in parallel. enqueue_size: block size for each read operation. batch_size: desired batch size. queue_capacity: capacity of the queue that will store parsed lines. min_after_dequeue: minimum number of elements that can be left by a dequeue operation. Only used if `shuffle` is true. shuffle: whether records should be shuffled. Defaults to true. seed: passed to random shuffle operations. Only used if `shuffle` is true. Returns: A `DataFrame` that has columns corresponding to `features` and is filled with examples from `filepatterns`. Raises: ValueError: no files match `filepatterns`. ValueError: `features` contains the reserved name 'index'. """ def get_default_values(column_names): # pylint: disable=unused-argument return default_values return cls._from_csv_base(filepatterns, get_default_values, has_header, column_names, num_threads, enqueue_size, batch_size, queue_capacity, min_after_dequeue, shuffle, seed) @classmethod def from_csv_with_feature_spec(cls, filepatterns, feature_spec, has_header=True, column_names=None, num_threads=1, enqueue_size=None, batch_size=32, queue_capacity=None, min_after_dequeue=None, shuffle=True, seed=None): """Create a `DataFrame` from CSV files, given a feature_spec. If `has_header` is false, then `column_names` must be specified. If `has_header` is true and `column_names` are specified, then `column_names` overrides the names in the header. Args: filepatterns: a list of file patterns that resolve to CSV files. feature_spec: a dict mapping column names to `FixedLenFeature` or `VarLenFeature`. has_header: whether or not the CSV files have headers. column_names: a list of names for the columns in the CSV files. num_threads: the number of readers that will work in parallel. enqueue_size: block size for each read operation. batch_size: desired batch size. queue_capacity: capacity of the queue that will store parsed lines. min_after_dequeue: minimum number of elements that can be left by a dequeue operation. Only used if `shuffle` is true. shuffle: whether records should be shuffled. Defaults to true. seed: passed to random shuffle operations. Only used if `shuffle` is true. Returns: A `DataFrame` that has columns corresponding to `features` and is filled with examples from `filepatterns`. Raises: ValueError: no files match `filepatterns`. ValueError: `features` contains the reserved name 'index'. """ def get_default_values(column_names): return [_get_default_value(feature_spec[name]) for name in column_names] dataframe = cls._from_csv_base(filepatterns, get_default_values, has_header, column_names, num_threads, enqueue_size, batch_size, queue_capacity, min_after_dequeue, shuffle, seed) # replace the dense columns with sparse ones in place in the dataframe for name in dataframe.columns(): if name != "index" and isinstance(feature_spec[name], parsing_ops.VarLenFeature): strip_value = _get_default_value(feature_spec[name]) (dataframe[name],) = sparsify.Sparsify(strip_value)(dataframe[name]) return dataframe @classmethod def from_examples(cls, filepatterns, features, reader_cls=io_ops.TFRecordReader, num_threads=1, enqueue_size=None, batch_size=32, queue_capacity=None, min_after_dequeue=None, shuffle=True, seed=None): """Create a `DataFrame` from `tensorflow.Example`s. Args: filepatterns: a list of file patterns containing `tensorflow.Example`s. features: a dict mapping feature names to `VarLenFeature` or `FixedLenFeature`. reader_cls: a subclass of `tensorflow.ReaderBase` that will be used to read the `Example`s. num_threads: the number of readers that will work in parallel. enqueue_size: block size for each read operation. batch_size: desired batch size. queue_capacity: capacity of the queue that will store parsed `Example`s min_after_dequeue: minimum number of elements that can be left by a dequeue operation. Only used if `shuffle` is true. shuffle: whether records should be shuffled. Defaults to true. seed: passed to random shuffle operations. Only used if `shuffle` is true. Returns: A `DataFrame` that has columns corresponding to `features` and is filled with `Example`s from `filepatterns`. Raises: ValueError: no files match `filepatterns`. ValueError: `features` contains the reserved name 'index'. """ filenames = _expand_file_names(filepatterns) if not filenames: raise ValueError("No matching file names.") if "index" in features: raise ValueError( "'index' is reserved and can not be used for a feature name.") index, record = reader_source.ReaderSource( reader_cls, filenames, enqueue_size=enqueue_size, batch_size=batch_size, queue_capacity=queue_capacity, shuffle=shuffle, min_after_dequeue=min_after_dequeue, num_threads=num_threads, seed=seed)() parser = example_parser.ExampleParser(features) parsed = parser(record) column_dict = parsed._asdict() column_dict["index"] = index dataframe = cls() dataframe.assign(**column_dict) return dataframe @classmethod def from_pandas(cls, pandas_dataframe, num_threads=None, enqueue_size=None, batch_size=None, queue_capacity=None, min_after_dequeue=None, shuffle=True, seed=None, data_name="pandas_data"): """Create a `tf.learn.DataFrame` from a `pandas.DataFrame`. Args: pandas_dataframe: `pandas.DataFrame` that serves as a data source. num_threads: the number of threads to use for enqueueing. enqueue_size: the number of rows to enqueue per step. batch_size: desired batch size. queue_capacity: capacity of the queue that will store parsed `Example`s min_after_dequeue: minimum number of elements that can be left by a dequeue operation. Only used if `shuffle` is true. shuffle: whether records should be shuffled. Defaults to true. seed: passed to random shuffle operations. Only used if `shuffle` is true. data_name: a scope name identifying the data. Returns: A `tf.learn.DataFrame` that contains batches drawn from the given `pandas_dataframe`. """ pandas_source = in_memory_source.PandasSource( pandas_dataframe, num_threads=num_threads, enqueue_size=enqueue_size, batch_size=batch_size, queue_capacity=queue_capacity, shuffle=shuffle, min_after_dequeue=min_after_dequeue, seed=seed, data_name=data_name) dataframe = cls() dataframe.assign(**(pandas_source()._asdict())) return dataframe @classmethod def from_numpy(cls, numpy_array, num_threads=None, enqueue_size=None, batch_size=None, queue_capacity=None, min_after_dequeue=None, shuffle=True, seed=None, data_name="numpy_data"): """Creates a `tf.learn.DataFrame` from a `numpy.ndarray`. The returned `DataFrame` contains two columns: 'index' and 'value'. The 'value' column contains a row from the array. The 'index' column contains the corresponding row number. Args: numpy_array: `numpy.ndarray` that serves as a data source. num_threads: the number of threads to use for enqueueing. enqueue_size: the number of rows to enqueue per step. batch_size: desired batch size. queue_capacity: capacity of the queue that will store parsed `Example`s min_after_dequeue: minimum number of elements that can be left by a dequeue operation. Only used if `shuffle` is true. shuffle: whether records should be shuffled. Defaults to true. seed: passed to random shuffle operations. Only used if `shuffle` is true. data_name: a scope name identifying the data. Returns: A `tf.learn.DataFrame` that contains batches drawn from the given array. """ numpy_source = in_memory_source.NumpySource( numpy_array, num_threads=num_threads, enqueue_size=enqueue_size, batch_size=batch_size, queue_capacity=queue_capacity, shuffle=shuffle, min_after_dequeue=min_after_dequeue, seed=seed, data_name=data_name) dataframe = cls() dataframe.assign(**(numpy_source()._asdict())) return dataframe @classmethod def from_ordereddict(cls, ordered_dict_of_arrays, num_threads=None, enqueue_size=None, batch_size=None, queue_capacity=None, min_after_dequeue=None, shuffle=True, seed=None, data_name="numpy_data"): """Creates a `tf.learn.DataFrame` from an `OrderedDict` of `numpy.ndarray`. The returned `DataFrame` contains a column for each key of the dict plus an extra 'index' column. The 'index' column contains the row number. Each of the other columns contains a row from the corresponding array. Args: ordered_dict_of_arrays: `OrderedDict` of `numpy.ndarray` that serves as a data source. num_threads: the number of threads to use for enqueueing. enqueue_size: the number of rows to enqueue per step. batch_size: desired batch size. queue_capacity: capacity of the queue that will store parsed `Example`s min_after_dequeue: minimum number of elements that can be left by a dequeue operation. Only used if `shuffle` is true. shuffle: whether records should be shuffled. Defaults to true. seed: passed to random shuffle operations. Only used if `shuffle` is true. data_name: a scope name identifying the data. Returns: A `tf.learn.DataFrame` that contains batches drawn from the given arrays. Raises: ValueError: `ordered_dict_of_arrays` contains the reserved name 'index'. """ numpy_source = in_memory_source.OrderedDictNumpySource( ordered_dict_of_arrays, num_threads=num_threads, enqueue_size=enqueue_size, batch_size=batch_size, queue_capacity=queue_capacity, shuffle=shuffle, min_after_dequeue=min_after_dequeue, seed=seed, data_name=data_name) dataframe = cls() dataframe.assign(**(numpy_source()._asdict())) return dataframe
apache-2.0
yaukwankiu/armor
tests/modifiedMexicanHatTest15_march2014_sigmaPreprocessing20.py
1
7833
# modified mexican hat wavelet test.py # spectral analysis for RADAR and WRF patterns # NO plotting - just saving the results: LOG-response spectra for each sigma and max-LOG response numerical spectra # pre-convolved with a gaussian filter of sigma=10 import os, shutil import time, datetime import pickle import numpy as np from scipy import signal, ndimage import matplotlib.pyplot as plt from armor import defaultParameters as dp from armor import pattern from armor import objects4 as ob #from armor import misc as ms dbz = pattern.DBZ kongreywrf = ob.kongreywrf kongreywrf.fix() kongrey = ob.kongrey monsoon = ob.monsoon monsoon.list= [v for v in monsoon.list if '20120612' in v.dataTime] #fix march2014 = ob.march2014 march2014wrf11 = ob.march2014wrf11 march2014wrf12 = ob.march2014wrf12 march2014wrf = ob.march2014wrf march2014wrf.fix() ################################################################################ # hack #kongrey.list = [v for v in kongrey.list if v.dataTime>="20130828.2320"] ################################################################################ # parameters sigmaPreprocessing = 20 # sigma for preprocessing, 2014-05-15 testName = "modifiedMexicanHatTest15_march2014_sigmaPreprocessing" + str(sigmaPreprocessing) sigmas = [1, 2, 4, 5, 8 ,10 ,16, 20, 32, 40, 64, 80, 128, 160, 256,] dbzstreams = [march2014] sigmaPower=0 scaleSpacePower=0 #2014-05-14 testScriptsFolder = dp.root + 'python/armor/tests/' timeString = str(int(time.time())) outputFolder = dp.root + 'labLogs/%d-%d-%d-%s/' % \ (time.localtime().tm_year, time.localtime().tm_mon, time.localtime().tm_mday, testName) if not os.path.exists(outputFolder): os.makedirs(outputFolder) shutil.copyfile(testScriptsFolder+testName+".py", outputFolder+ timeString + testName+".py") # end parameters ################################################################################ summaryFile = open(outputFolder + timeString + "summary.txt", 'a') for ds in dbzstreams: summaryFile.write("\n===============================================================\n\n\n") streamMean = 0. dbzCount = 0 #hack #streamMean = np.array([135992.57472004235, 47133.59049120619, 16685.039217734946, 11814.043851969862, 5621.567482638702, 3943.2774923729303, 1920.246102887001, 1399.7855335686243, 760.055614122099, 575.3654495432361, 322.26668666562375, 243.49842951291757, 120.54647935045809, 79.05741086463254, 26.38971066782135]) #dbzCount = 140 for a in ds: print "-------------------------------------------------" print testName print print a.name a.load() a.setThreshold(0) a.saveImage(imagePath=outputFolder+a.name+".png") L = [] a.responseImages = [] #2014-05-02 #for sigma in [1, 2, 4, 8 ,16, 32, 64, 128, 256, 512]: for sigma in sigmas: print "sigma:", sigma a.load() a.setThreshold(0) arr0 = a.matrix ##################################################################### arr0 = ndimage.filters.gaussian_filter(arr0, sigma=sigmaPreprocessing) # <-- 2014-05-15 ##################################################################### #arr1 = signal.convolve2d(arr0, mask_i, mode='same', boundary='fill') #arr1 = ndimage.filters.gaussian_laplace(arr0, sigma=sigma, mode="constant", cval=0.0) #2014-05-07 #arr1 = ndimage.filters.gaussian_laplace(arr0, sigma=sigma, mode="constant", cval=0.0) * sigma**2 #2014-04-29 arr1 = ndimage.filters.gaussian_laplace(arr0, sigma=sigma, mode="constant", cval=0.0) * sigma**scaleSpacePower #2014-05-14 a1 = dbz(matrix=arr1.real, name=a.name + "_" + testName + "_sigma" + str(sigma)) L.append({ 'sigma' : sigma, 'a1' : a1, 'abssum1': abs(a1.matrix).sum(), 'sum1' : a1.matrix.sum(), }) print "abs sum", abs(a1.matrix.sum()) #a1.show() #a2.show() plt.close() #a1.histogram(display=False, outputPath=outputFolder+a1.name+"_histogram.png") ############################################################################### # computing the spectrum, i.e. sigma for which the LOG has max response # 2014-05-02 a.responseImages.append({'sigma' : sigma, 'matrix' : arr1 * sigma**2, }) pickle.dump(a.responseImages, open(outputFolder+a.name+"responseImagesList.pydump",'w')) a_LOGspec = dbz(name= a.name + "Laplacian-of-Gaussian_numerical_spectrum", imagePath=outputFolder+a1.name+"_LOGspec.png", outputPath = outputFolder+a1.name+"_LOGspec.dat", cmap = 'jet', ) a.responseImages = np.dstack([v['matrix'] for v in a.responseImages]) #print 'shape:', a.responseImages.shape #debug a.responseMax = a.responseImages.max(axis=2) # the deepest dimension a_LOGspec.matrix = np.zeros(a.matrix.shape) for count, sigma in enumerate(sigmas): a_LOGspec.matrix += sigma * (a.responseMax == a.responseImages[:,:,count]) a_LOGspec.vmin = a_LOGspec.matrix.min() a_LOGspec.vmax = a_LOGspec.matrix.max() print "saving to:", a_LOGspec.imagePath #a_LOGspec.saveImage() print a_LOGspec.outputPath #a_LOGspec.saveMatrix() #a_LOGspec.histogram(display=False, outputPath=outputFolder+a1.name+"_LOGspec_histogram.png") pickle.dump(a_LOGspec, open(outputFolder+ a_LOGspec.name + ".pydump","w")) # end computing the sigma for which the LOG has max response # 2014-05-02 ############################################################################## #pickle.dump(L, open(outputFolder+ a.name +'_test_results.pydump','w')) # no need to dump if test is easy sigmas = np.array([v['sigma'] for v in L]) y1 = [v['abssum1'] for v in L] plt.close() plt.plot(sigmas,y1) plt.title(a1.name+ '\n absolute values against sigma') plt.savefig(outputFolder+a1.name+"-spectrum-histogram.png") plt.close() # now update the mean streamMeanUpdate = np.array([v['abssum1'] for v in L]) dbzCount += 1 streamMean = 1.* ((streamMean*(dbzCount -1)) + streamMeanUpdate ) / dbzCount print "Stream Count and Mean so far:", dbzCount, streamMean # now save the mean and the plot summaryText = '\n---------------------------------------\n' summaryText += str(int(time.time())) + '\n' summaryText += "dbzStream Name: " + ds.name + '\n' summaryText += "dbzCount:\t" + str(dbzCount) + '\n' summaryText +="sigma=\t\t" + str(sigmas.tolist()) + '\n' summaryText += "streamMean=\t" + str(streamMean.tolist()) +'\n' print summaryText print "saving..." # release the memory a.matrix = np.array([0]) summaryFile.write(summaryText) plt.close() plt.plot(sigmas, streamMean* (sigmas**sigmaPower)) plt.title(ds.name + '- average laplacian-of-gaussian numerical spectrum\n' +\ 'for ' +str(dbzCount) + ' DBZ patterns\n' +\ 'suppressed by a factor of sigma^' + str(sigmaPower) ) plt.savefig(outputFolder + ds.name + "_average_LoG_numerical_spectrum.png") plt.close() summaryFile.close()
cc0-1.0
bsipocz/statsmodels
statsmodels/graphics/tsaplots.py
16
10392
"""Correlation plot functions.""" import numpy as np from statsmodels.graphics import utils from statsmodels.tsa.stattools import acf, pacf def plot_acf(x, ax=None, lags=None, alpha=.05, use_vlines=True, unbiased=False, fft=False, **kwargs): """Plot the autocorrelation function Plots lags on the horizontal and the correlations on vertical axis. Parameters ---------- x : array_like Array of time-series values ax : Matplotlib AxesSubplot instance, optional If given, this subplot is used to plot in instead of a new figure being created. lags : array_like, optional Array of lag values, used on horizontal axis. If not given, ``lags=np.arange(len(corr))`` is used. alpha : scalar, optional If a number is given, the confidence intervals for the given level are returned. For instance if alpha=.05, 95 % confidence intervals are returned where the standard deviation is computed according to Bartlett's formula. If None, no confidence intervals are plotted. use_vlines : bool, optional If True, vertical lines and markers are plotted. If False, only markers are plotted. The default marker is 'o'; it can be overridden with a ``marker`` kwarg. unbiased : bool If True, then denominators for autocovariance are n-k, otherwise n fft : bool, optional If True, computes the ACF via FFT. **kwargs : kwargs, optional Optional keyword arguments that are directly passed on to the Matplotlib ``plot`` and ``axhline`` functions. Returns ------- fig : Matplotlib figure instance If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. See Also -------- matplotlib.pyplot.xcorr matplotlib.pyplot.acorr mpl_examples/pylab_examples/xcorr_demo.py Notes ----- Adapted from matplotlib's `xcorr`. Data are plotted as ``plot(lags, corr, **kwargs)`` """ fig, ax = utils.create_mpl_ax(ax) if lags is None: lags = np.arange(len(x)) nlags = len(lags) - 1 else: nlags = lags lags = np.arange(lags + 1) # +1 for zero lag confint = None # acf has different return type based on alpha if alpha is None: acf_x = acf(x, nlags=nlags, alpha=alpha, fft=fft, unbiased=unbiased) else: acf_x, confint = acf(x, nlags=nlags, alpha=alpha, fft=fft, unbiased=unbiased) if use_vlines: ax.vlines(lags, [0], acf_x, **kwargs) ax.axhline(**kwargs) kwargs.setdefault('marker', 'o') kwargs.setdefault('markersize', 5) kwargs.setdefault('linestyle', 'None') ax.margins(.05) ax.plot(lags, acf_x, **kwargs) ax.set_title("Autocorrelation") if confint is not None: # center the confidence interval TODO: do in acf? ax.fill_between(lags, confint[:,0] - acf_x, confint[:,1] - acf_x, alpha=.25) return fig def plot_pacf(x, ax=None, lags=None, alpha=.05, method='ywm', use_vlines=True, **kwargs): """Plot the partial autocorrelation function Plots lags on the horizontal and the correlations on vertical axis. Parameters ---------- x : array_like Array of time-series values ax : Matplotlib AxesSubplot instance, optional If given, this subplot is used to plot in instead of a new figure being created. lags : array_like, optional Array of lag values, used on horizontal axis. If not given, ``lags=np.arange(len(corr))`` is used. alpha : scalar, optional If a number is given, the confidence intervals for the given level are returned. For instance if alpha=.05, 95 % confidence intervals are returned where the standard deviation is computed according to 1/sqrt(len(x)) method : 'ywunbiased' (default) or 'ywmle' or 'ols' specifies which method for the calculations to use: - yw or ywunbiased : yule walker with bias correction in denominator for acovf - ywm or ywmle : yule walker without bias correction - ols - regression of time series on lags of it and on constant - ld or ldunbiased : Levinson-Durbin recursion with bias correction - ldb or ldbiased : Levinson-Durbin recursion without bias correction use_vlines : bool, optional If True, vertical lines and markers are plotted. If False, only markers are plotted. The default marker is 'o'; it can be overridden with a ``marker`` kwarg. **kwargs : kwargs, optional Optional keyword arguments that are directly passed on to the Matplotlib ``plot`` and ``axhline`` functions. Returns ------- fig : Matplotlib figure instance If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. See Also -------- matplotlib.pyplot.xcorr matplotlib.pyplot.acorr mpl_examples/pylab_examples/xcorr_demo.py Notes ----- Adapted from matplotlib's `xcorr`. Data are plotted as ``plot(lags, corr, **kwargs)`` """ fig, ax = utils.create_mpl_ax(ax) if lags is None: lags = np.arange(len(x)) nlags = len(lags) - 1 else: nlags = lags lags = np.arange(lags + 1) # +1 for zero lag confint = None if alpha is None: acf_x = pacf(x, nlags=nlags, alpha=alpha, method=method) else: acf_x, confint = pacf(x, nlags=nlags, alpha=alpha, method=method) if use_vlines: ax.vlines(lags, [0], acf_x, **kwargs) ax.axhline(**kwargs) # center the confidence interval TODO: do in acf? kwargs.setdefault('marker', 'o') kwargs.setdefault('markersize', 5) kwargs.setdefault('linestyle', 'None') ax.margins(.05) ax.plot(lags, acf_x, **kwargs) ax.set_title("Partial Autocorrelation") if confint is not None: # center the confidence interval TODO: do in acf? ax.fill_between(lags, confint[:,0] - acf_x, confint[:,1] - acf_x, alpha=.25) return fig def seasonal_plot(grouped_x, xticklabels, ylabel=None, ax=None): """ Consider using one of month_plot or quarter_plot unless you need irregular plotting. Parameters ---------- grouped_x : iterable of DataFrames Should be a GroupBy object (or similar pair of group_names and groups as DataFrames) with a DatetimeIndex or PeriodIndex """ fig, ax = utils.create_mpl_ax(ax) start = 0 ticks = [] for season, df in grouped_x: df = df.copy() # or sort balks for series. may be better way df.sort() nobs = len(df) x_plot = np.arange(start, start + nobs) ticks.append(x_plot.mean()) ax.plot(x_plot, df.values, 'k') ax.hlines(df.values.mean(), x_plot[0], x_plot[-1], colors='k') start += nobs ax.set_xticks(ticks) ax.set_xticklabels(xticklabels) ax.set_ylabel(ylabel) ax.margins(.1, .05) return fig def month_plot(x, dates=None, ylabel=None, ax=None): """ Seasonal plot of monthly data Parameters ---------- x : array-like Seasonal data to plot. If dates is None, x must be a pandas object with a PeriodIndex or DatetimeIndex with a monthly frequency. dates : array-like, optional If `x` is not a pandas object, then dates must be supplied. ylabel : str, optional The label for the y-axis. Will attempt to use the `name` attribute of the Series. ax : matplotlib.axes, optional Existing axes instance. Returns ------- matplotlib.Figure Examples -------- >>> import statsmodels.api as sm >>> import pandas as pd >>> dta = sm.datasets.elnino.load_pandas().data >>> dta['YEAR'] = dta.YEAR.astype(int).astype(str) >>> dta = dta.set_index('YEAR').T.unstack() >>> dates = map(lambda x : pd.datetools.parse('1 '+' '.join(x)), ... dta.index.values) >>> dta.index = pd.DatetimeIndex(dates, freq='M') >>> fig = sm.graphics.tsa.month_plot(dta) .. plot:: plots/graphics_month_plot.py """ from pandas import DataFrame if dates is None: from statsmodels.tools.data import _check_period_index _check_period_index(x, freq="M") else: from pandas import Series, PeriodIndex x = Series(x, index=PeriodIndex(dates, freq="M")) xticklabels = ['j','f','m','a','m','j','j','a','s','o','n','d'] return seasonal_plot(x.groupby(lambda y : y.month), xticklabels, ylabel=ylabel, ax=ax) def quarter_plot(x, dates=None, ylabel=None, ax=None): """ Seasonal plot of quarterly data Parameters ---------- x : array-like Seasonal data to plot. If dates is None, x must be a pandas object with a PeriodIndex or DatetimeIndex with a monthly frequency. dates : array-like, optional If `x` is not a pandas object, then dates must be supplied. ylabel : str, optional The label for the y-axis. Will attempt to use the `name` attribute of the Series. ax : matplotlib.axes, optional Existing axes instance. Returns ------- matplotlib.Figure """ from pandas import DataFrame if dates is None: from statsmodels.tools.data import _check_period_index _check_period_index(x, freq="Q") else: from pandas import Series, PeriodIndex x = Series(x, index=PeriodIndex(dates, freq="Q")) xticklabels = ['q1', 'q2', 'q3', 'q4'] return seasonal_plot(x.groupby(lambda y : y.quarter), xticklabels, ylabel=ylabel, ax=ax) if __name__ == "__main__": import pandas as pd #R code to run to load that dataset in this directory #data(co2) #library(zoo) #write.csv(as.data.frame(list(date=as.Date(co2), co2=coredata(co2))), "co2.csv", row.names=FALSE) co2 = pd.read_csv("co2.csv", index_col=0, parse_dates=True) month_plot(co2.co2) #will work when dates are sorted #co2 = sm.datasets.get_rdataset("co2", cache=True) x = pd.Series(np.arange(20), index=pd.PeriodIndex(start='1/1/1990', periods=20, freq='Q')) quarter_plot(x)
bsd-3-clause
scholer/na_strand_model
nascent/graph_visualization/live_visualizer_base.py
2
9342
# -*- coding: utf-8 -*- ## Copyright 2015 Rasmus Scholer Sorensen, rasmusscholer@gmail.com ## ## This file is part of Nascent. ## ## Nascent is free software: you can redistribute it and/or modify ## it under the terms of the GNU Affero General Public License as ## published by the Free Software Foundation, either version 3 of the ## License, or (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU Affero General Public License for more details. ## ## You should have received a copy of the GNU Affero General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. # pylint: disable=C0103 """ Module with live visualizer base class. """ import logging logger = logging.getLogger(__name__) class LiveVisualizerBase(): """ Base class for all live/online graph visualizer classes. """ def __init__(self, config): self.config = config # Graph visualization adaptors should be model agnostic # self.graph_type = config.get('visualization_graph_type', '5p3p') ## TODO: Consolidate visualization_* vs livestreamer_* config keys self.directed_graph = config.get('visualization_graph_directed', False) self.default_layout = config.get('livestreamer_graph_layout_method', 'force-directed') self.is_multigraph = config.get('livestreamer_graph_is_multigraph', True) # Note: For purely visualization, it doesn't matter if the graph is directed or not; # we are not using the visualized graph for any analysis or calculation. self.network = None self.node_name_to_suid = {} self.node_suid_to_name = {} # frozenset(source, target) for undirected graphs, (source, target) for directed. # If multigraph, this should be a dict of lists: self.edge_names_to_suid = {} self.edge_suid_to_names = {} self.deleted_name_to_suid = [] self.deleted_suid_to_name = [] self.id_key = 'SUID' def initialize_graph(self, graph, reset=True): """ Initialize the visualization based on graph. If reset=True, the current graph visualization will be reset before adding graph. """ raise NotImplementedError("Must be defined by subclass.") def apply_layout(self, layout): """ Change in subclass if it should automatically apply layout. """ pass # #def propagate_change(self, change): # """ # Propagate a single state change. # """ # raise NotImplementedError("Must be defined by subclass.") # #def propagate_changes(self, changes): # """ # Propagate a list of state changes. # """ # raise NotImplementedError("Must be defined by subclass.") def register_new_nodes(self, new_node_ids): """ Register new nodes. :param new_edge_ids: Should be a list of dicts, e.g. [{'SUID': 5455, 'name': 'a', ...], OR a dict with {'name': SUID, ...} """ if isinstance(new_node_ids, dict): # Assume this is a SUID: name map. node_suid_to_name = new_node_ids node_name_to_suid = {v: k for k, v in node_suid_to_name.items()} else: node_suid_to_name = {row[self.id_key]: row['name'] for row in new_node_ids} node_name_to_suid = {v: k for k, v in node_suid_to_name.items()} self.node_suid_to_name.update(node_suid_to_name) self.node_name_to_suid.update(node_name_to_suid) def register_new_edges(self, new_edge_ids, directed=None): """ Register new edges. :param new_edge_ids: Should be a list of dicts, e.g. [{'SUID': 5455, 'source': 4875, 'target': 4876}, ...], or a pandas dataframe. """ if directed is None: directed = self.directed_graph #if isinstance(new_edge_ids, DataFrame): # edge_suid_to_names = edge_suid_to_names_mapper(new_edge_ids, directed=self.directed_graph) #else: if self.is_multigraph: if directed is True: edge_suid_to_names = {d[self.id_key]: (d['source'], d['target'], d.get('key')) for d in new_edge_ids} elif directed is False: edge_suid_to_names = {d[self.id_key]: (frozenset((d['source'], d['target'])), d.get('key')) for d in new_edge_ids} else: # directed might be a list of different directed values, one for each node edge_suid_to_names = {d[self.id_key]: (d['source'], d['target'], d.get('key')) if node_directed else (frozenset((d['source'], d['target'])), d.get('key')) for d, node_directed in zip(new_edge_ids, directed)} else: # regular graph (not multi-graph): if directed is True: edge_suid_to_names = {d[self.id_key]: (d['source'], d['target']) for d in new_edge_ids} elif directed is False: edge_suid_to_names = {d[self.id_key]: frozenset((d['source'], d['target'])) for d in new_edge_ids} else: # directed might be a list of different directed values, one for each node edge_suid_to_names = {d[self.id_key]: (d['source'], d['target']) if node_directed else frozenset((d['source'], d['target'])) for d, node_directed in zip(new_edge_ids, directed)} edge_names_to_suid = {v: k for k, v in edge_suid_to_names.items()} self.edge_suid_to_names.update(edge_suid_to_names) self.edge_names_to_suid.update(edge_names_to_suid) def add_node(self, node_name, attributes=None): """ Add a single node. """ raise NotImplementedError("Override in sub-class.") def add_nodes(self, node_names_list, attributes=None): """ Add all nodes in node_names_list. """ raise NotImplementedError("Override in sub-class.") def add_edge(self, source, target, directed=True, key=None, interaction=None, bidirectional=None, attributes=None): """ Add a single edge. Id is auto-generated as source-target""" raise NotImplementedError("Override in sub-class.") def add_edges(self, edges, directed, keys=None, attributes=None): """ Takes a list of edges dicts with the form of [{'source': <name>, 'target': <name>, 'interaction': <str>, 'directed': <bool>}, ...] """ raise NotImplementedError("Override in sub-class.") def delete_edge(self, source, target, directed=None, key=None, interaction=None): """ Delete a single node from the graph. Key vs id: - Key is used *in conjunction with source and target* to identify an edge. E.g. (source, target, key=1). Key can be the same for edges connecting different source, target: (source1, target1, key='h') and (source2, target2, key='h') are valid. - ID is unique within the entire graph. No two edges or nodes have the same id. """ if directed is None: directed = self.directed_graph if key is None: key = interaction if self.is_multigraph: # key_directed, key_undirected = (source, target, key), (frozenset((source, target)), key) edge_lookup = (source, target, key) if directed else (frozenset((source, target)), key) else: # key_directed, key_undirected = (source, target), frozenset((source, target)) edge_lookup = (source, target) if directed else frozenset((source, target)) # key, fallback = (key_directed, key_undirected) (key_undirected, key_directed) # try: edge_id = self.edge_names_to_suid.pop(edge_lookup) # except KeyError: # print("Unable to find expected edge key %s in node_name_to_suid map." % key) # try: # edge_id = self.edge_names_to_suid.pop(fallback) # key = fallback # except KeyError as e: # print("- Also unable to find fallback key %s in node_name_to_suid map." % (fallback,)) # raise e try: print("Deleting edge %s" % edge_id) self.network.delete_edge(edge_id) except Exception as e: # pylint: disable=W0703 print("Error deleting node %s: %s" % (edge_id, e)) # Re-insert node_name => node_id entry self.edge_names_to_suid[edge_lookup] = edge_id else: lookup_test = self.edge_suid_to_names.pop(edge_id) self.deleted_name_to_suid.append({lookup_test: edge_id}) self.deleted_suid_to_name.append({edge_id: lookup_test}) if lookup_test != edge_lookup: print("WARNING: Mapping issue: node_suid_to_name[node_id] %s != node_name %s" % (lookup_test, edge_lookup))
gpl-3.0
ryanfobel/dmf_control_board
dmf_control_board_firmware/calibrate/impedance_benchmarks.py
3
9822
# coding: utf-8 import pandas as pd import matplotlib.mlab as mlab import matplotlib.pyplot as plt from matplotlib.colors import Colormap from matplotlib.gridspec import GridSpec import numpy as np pd.set_option('display.width', 300) def plot_capacitance_vs_frequency(df, **kwargs): cleaned_df = df.dropna().copy() fb_resistor_df = cleaned_df.set_index(cleaned_df.fb_resistor) axis = kwargs.pop('axis', None) s = kwargs.pop('s', 50) facecolor = kwargs.pop('facecolor', 'none') if axis is None: fig = plt.figure() axis = fig.add_subplot(111) stats = fb_resistor_df[['frequency', 'C']].describe() axis.set_xlim(0.8 * stats.frequency['min'], 1.2 * stats.frequency['max']) axis.set_ylim(0.8 * stats.C['min'], 1.2 * stats.C['max']) frequencies = fb_resistor_df.frequency.unique() # Plot nominal test capacitance lines. for C in fb_resistor_df.test_capacitor.unique(): axis.plot(frequencies, [C] * len(frequencies), '--', alpha=0.7, color='0.5', linewidth=1) # Plot scatter of _measured_ capacitance vs. frequency. for k, v in fb_resistor_df[['frequency', 'C']].groupby(level=0): try: color = axis._get_lines.color_cycle.next() except: # make compatible with matplotlib v1.5 color = axis._get_lines.prop_cycler.next()['color'] v.plot(kind='scatter', x='frequency', y='C', loglog=True, label='R$_{fb,%d}$' % k, ax=axis, color=color, s=s, facecolor=facecolor, **kwargs) axis.legend(loc='upper right') axis.set_xlabel('Frequency (Hz)') axis.set_ylabel('C$_{device}$ (F)') axis.set_title('C$_{device}$') plt.tight_layout() return axis def estimate_relative_error_in_nominal_capacitance(df): # Calculate the relative percentage difference in the mean capacitance # values measured relative to the nominal values. cleaned_df = df.dropna().copy() C_relative_error = (cleaned_df.groupby('test_capacitor') .apply(lambda x: ((x['C'] - x['test_capacitor']) / x['test_capacitor']).describe())) pd.set_eng_float_format(accuracy=1, use_eng_prefix=True) print ('Estimated relative error in nominal capacitance values = %.1f%% ' ' +/-%.1f%%' % (C_relative_error['mean'].mean() * 100, C_relative_error['mean'].std() * 100)) print C_relative_error[['mean', 'std']] * 100 print return C_relative_error def plot_impedance_vs_frequency(data): test_loads = data['test_loads'] frequencies = data['frequencies'] C = data['C'] fb_resistor = data['fb_resistor'] calibration = data['calibration'] # create a masked array version of the capacitance matrix C = np.ma.masked_invalid(C) # create frequency matrix to match shape of C f = np.tile(np.reshape(frequencies, [len(frequencies)] + [1]*(len(C.shape) - 1)), [1] + list(C.shape[1:])) # Plot the impedance of each experiment vs frequency (with the data points # color-coded according to the feedback resistor). # Note that impedance, $Z$, can be computed as: # # 1 # Z = ────────── # 2⋅π⋅freq⋅C # plt.figure(figsize=figsize) legend = [] for i in range(len(calibration.R_fb)): legend.append("R$_{fb,%d}$" % i) ind = mlab.find(fb_resistor == i) plt.loglog(f.flatten()[ind], 1.0 / (2 * np.pi * f.flatten()[ind] * C.flatten()[ind]), 'o') plt.xlim(0.8 * np.min(frequencies), 1.2 * np.max(frequencies)) for C_device in test_loads: # TODO: What is the reason for the `np.ones` below? plt.plot(frequencies, 1.0 / (2 * np.pi * C_device * np.ones(len(frequencies)) * frequencies), '--', color='0.5') plt.legend(legend) plt.xlabel('Frequency (Hz)') plt.ylabel('Z$_{device}$ ($\Omega$)') plt.title('Z$_{device}$') plt.tight_layout() def calculate_stats(df, groupby='test_capacitor'): cleaned_df = df.dropna().copy() stats = cleaned_df.groupby(groupby)['C'].agg(['mean', 'std', 'median']) stats['bias %'] = (cleaned_df.groupby(groupby) .apply(lambda x: ((x['C'] - x['test_capacitor'])).mean() / x['C'].mean())) * 100 stats['RMSE %'] = 100 * (cleaned_df.groupby(groupby) .apply(lambda x: np.sqrt(((x['C'] - x['test_capacitor']) ** 2).mean()) / x['C'].mean())) stats['cv %'] = stats['std'] / stats['mean'] * 100 return stats def print_detailed_stats_by_condition(data, stats): test_loads = data['test_loads'] frequencies = data['frequencies'] mean = stats['mean'] CV = stats['CV'] bias = stats['bias'] RMSE = stats['RMSE'] # print the RMSE, CV, and bias for each test capacitor and frequency combination for i, (channel, C_device) in enumerate(test_loads): print "\n%.2f pF" % (C_device*1e12) for j in range(len(frequencies)): print "%.1fkHz: mean(C)=%.2f pF, RMSE=%.1f%%, CV=%.1f%%, bias=%.1f%%" % (frequencies[j]/1e3, 1e12*mean[j,i], RMSE[j,i], CV[j,i], bias[j,i]) print def plot_measured_vs_nominal_capacitance_for_each_frequency(data, stats): # plot the measured vs nominal capacitance for each frequency frequencies = data['frequencies'] test_loads = data['test_loads'] mean_C = stats['mean'] std_C = stats['std'] for i in range(len(frequencies)): plt.figure() plt.title('(frequency=%.2fkHz)' % (frequencies[i]/1e3)) for j, (channel, C_device) in enumerate(test_loads): plt.errorbar(C_device, mean_C[i,j], std_C[i,j], fmt='k') C_device = np.array([x for channel, x in test_loads]) plt.loglog(C_device, C_device, 'k:') plt.xlim(min(C_device)*.9, max(C_device)*1.1) plt.ylim(min(C_device)*.9, max(C_device)*1.1) plt.xlabel('C$_{nom}$ (F)') plt.ylabel('C$_{measured}$ (F)') def plot_colormap(stats, column, axis=None, fig=None): freq_vs_C_rmse = stats.reindex_axis( pd.Index([(i, j) for i in stats.index.levels[0] for j in stats.index.levels[1]], name=['test_capacitor', 'frequency'])).reset_index().pivot(index='frequency', columns= 'test_capacitor', values=column) if axis is None: fig = plt.figure() axis = fig.add_subplot(111) frequencies = stats.index.levels[1] axis.set_xlabel('Capacitance') axis.set_ylabel('Frequency') vmin = freq_vs_C_rmse.fillna(0).values.min() vmax = freq_vs_C_rmse.fillna(0).values.max() if vmin < 0: vmax = np.abs([vmin, vmax]).max() vmin = -vmax cmap=plt.cm.coolwarm else: vmin = 0 cmap=plt.cm.Reds mesh = axis.pcolormesh(freq_vs_C_rmse.fillna(0).values, vmin=vmin, vmax=vmax, cmap=cmap) if fig is not None: fig.colorbar(mesh) else: plt.colorbar() axis.set_xticks(np.arange(freq_vs_C_rmse.shape[1]) + 0.5) axis.set_xticklabels(["%.1fpF" % (c*1e12) for c in freq_vs_C_rmse.columns], rotation=90) axis.set_yticks(np.arange(len(frequencies)) + 0.5) axis.set_yticklabels(["%.2fkHz" % (f / 1e3) for f in frequencies]) axis.set_xlim(0, freq_vs_C_rmse.shape[1]) axis.set_ylim(0, freq_vs_C_rmse.shape[0]) return axis def plot_stat_summary(df, fig=None): ''' Plot stats grouped by test capacitor load _and_ frequency. In other words, we calculate the mean of all samples in the data frame for each test capacitance and frequency pairing, plotting the following stats: - Root mean squared error - Coefficient of variation - Bias ## [Coefficient of variation][1] ## > In probability theory and statistics, the coefficient of > variation (CV) is a normalized measure of dispersion of a > probability distribution or frequency distribution. It is defined > as the ratio of the standard deviation to the mean. [1]: http://en.wikipedia.org/wiki/Coefficient_of_variation ''' if fig is None: fig = plt.figure(figsize=(8, 8)) # Define a subplot layout, 3 rows, 2 columns grid = GridSpec(3, 2) stats = calculate_stats(df, groupby=['test_capacitor', 'frequency']).dropna() for i, stat in enumerate(['RMSE %', 'cv %', 'bias %']): axis = fig.add_subplot(grid[i, 0]) axis.set_title(stat) # Plot a colormap to show how the statistical value changes # according to frequency/capacitance pairs. plot_colormap(stats, stat, axis=axis, fig=fig) axis = fig.add_subplot(grid[i, 1]) axis.set_title(stat) # Plot a histogram to show the distribution of statistical # values across all frequency/capacitance pairs. try: axis.hist(stats[stat].values, bins=50) except AttributeError: print stats[stat].describe() fig.tight_layout()
gpl-3.0
sumspr/scikit-learn
examples/feature_selection/plot_rfe_with_cross_validation.py
226
1384
""" =================================================== Recursive feature elimination with cross-validation =================================================== A recursive feature elimination example with automatic tuning of the number of features selected with cross-validation. """ print(__doc__) import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.cross_validation import StratifiedKFold from sklearn.feature_selection import RFECV from sklearn.datasets import make_classification # Build a classification task using 3 informative features X, y = make_classification(n_samples=1000, n_features=25, n_informative=3, n_redundant=2, n_repeated=0, n_classes=8, n_clusters_per_class=1, random_state=0) # Create the RFE object and compute a cross-validated score. svc = SVC(kernel="linear") # The "accuracy" scoring is proportional to the number of correct # classifications rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(y, 2), scoring='accuracy') rfecv.fit(X, y) print("Optimal number of features : %d" % rfecv.n_features_) # Plot number of features VS. cross-validation scores plt.figure() plt.xlabel("Number of features selected") plt.ylabel("Cross validation score (nb of correct classifications)") plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_) plt.show()
bsd-3-clause
numpy/datetime
numpy/core/function_base.py
82
5474
__all__ = ['logspace', 'linspace'] import numeric as _nx from numeric import array def linspace(start, stop, num=50, endpoint=True, retstep=False): """ Return evenly spaced numbers over a specified interval. Returns `num` evenly spaced samples, calculated over the interval [`start`, `stop` ]. The endpoint of the interval can optionally be excluded. Parameters ---------- start : scalar The starting value of the sequence. stop : scalar The end value of the sequence, unless `endpoint` is set to False. In that case, the sequence consists of all but the last of ``num + 1`` evenly spaced samples, so that `stop` is excluded. Note that the step size changes when `endpoint` is False. num : int, optional Number of samples to generate. Default is 50. endpoint : bool, optional If True, `stop` is the last sample. Otherwise, it is not included. Default is True. retstep : bool, optional If True, return (`samples`, `step`), where `step` is the spacing between samples. Returns ------- samples : ndarray There are `num` equally spaced samples in the closed interval ``[start, stop]`` or the half-open interval ``[start, stop)`` (depending on whether `endpoint` is True or False). step : float (only if `retstep` is True) Size of spacing between samples. See Also -------- arange : Similiar to `linspace`, but uses a step size (instead of the number of samples). logspace : Samples uniformly distributed in log space. Examples -------- >>> np.linspace(2.0, 3.0, num=5) array([ 2. , 2.25, 2.5 , 2.75, 3. ]) >>> np.linspace(2.0, 3.0, num=5, endpoint=False) array([ 2. , 2.2, 2.4, 2.6, 2.8]) >>> np.linspace(2.0, 3.0, num=5, retstep=True) (array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25) Graphical illustration: >>> import matplotlib.pyplot as plt >>> N = 8 >>> y = np.zeros(N) >>> x1 = np.linspace(0, 10, N, endpoint=True) >>> x2 = np.linspace(0, 10, N, endpoint=False) >>> plt.plot(x1, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(x2, y + 0.5, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.ylim([-0.5, 1]) (-0.5, 1) >>> plt.show() """ num = int(num) if num <= 0: return array([], float) if endpoint: if num == 1: return array([float(start)]) step = (stop-start)/float((num-1)) y = _nx.arange(0, num) * step + start y[-1] = stop else: step = (stop-start)/float(num) y = _nx.arange(0, num) * step + start if retstep: return y, step else: return y def logspace(start,stop,num=50,endpoint=True,base=10.0): """ Return numbers spaced evenly on a log scale. In linear space, the sequence starts at ``base ** start`` (`base` to the power of `start`) and ends with ``base ** stop`` (see `endpoint` below). Parameters ---------- start : float ``base ** start`` is the starting value of the sequence. stop : float ``base ** stop`` is the final value of the sequence, unless `endpoint` is False. In that case, ``num + 1`` values are spaced over the interval in log-space, of which all but the last (a sequence of length ``num``) are returned. num : integer, optional Number of samples to generate. Default is 50. endpoint : boolean, optional If true, `stop` is the last sample. Otherwise, it is not included. Default is True. base : float, optional The base of the log space. The step size between the elements in ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform. Default is 10.0. Returns ------- samples : ndarray `num` samples, equally spaced on a log scale. See Also -------- arange : Similiar to linspace, with the step size specified instead of the number of samples. Note that, when used with a float endpoint, the endpoint may or may not be included. linspace : Similar to logspace, but with the samples uniformly distributed in linear space, instead of log space. Notes ----- Logspace is equivalent to the code >>> y = np.linspace(start, stop, num=num, endpoint=endpoint) ... # doctest: +SKIP >>> power(base, y) ... # doctest: +SKIP Examples -------- >>> np.logspace(2.0, 3.0, num=4) array([ 100. , 215.443469 , 464.15888336, 1000. ]) >>> np.logspace(2.0, 3.0, num=4, endpoint=False) array([ 100. , 177.827941 , 316.22776602, 562.34132519]) >>> np.logspace(2.0, 3.0, num=4, base=2.0) array([ 4. , 5.0396842 , 6.34960421, 8. ]) Graphical illustration: >>> import matplotlib.pyplot as plt >>> N = 10 >>> x1 = np.logspace(0.1, 1, N, endpoint=True) >>> x2 = np.logspace(0.1, 1, N, endpoint=False) >>> y = np.zeros(N) >>> plt.plot(x1, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(x2, y + 0.5, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.ylim([-0.5, 1]) (-0.5, 1) >>> plt.show() """ y = linspace(start,stop,num=num,endpoint=endpoint) return _nx.power(base,y)
bsd-3-clause
great-expectations/great_expectations
great_expectations/expectations/metrics/column_map_metrics/column_values_in_type_list.py
1
1603
import numpy as np import pandas as pd from great_expectations.execution_engine import PandasExecutionEngine from great_expectations.expectations.core.expect_column_values_to_be_of_type import ( _native_type_type_map, ) from great_expectations.expectations.metrics.map_metric import ( ColumnMapMetricProvider, column_condition_partial, ) class ColumnValuesInTypeList(ColumnMapMetricProvider): condition_metric_name = "column_values.in_type_list" condition_value_keys = ("type_list",) @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, type_list, **kwargs): comp_types = [] for type_ in type_list: try: comp_types.append(np.dtype(type_).type) except TypeError: try: pd_type = getattr(pd, type_) if isinstance(pd_type, type): comp_types.append(pd_type) except AttributeError: pass try: pd_type = getattr(pd.core.dtypes.dtypes, type_) if isinstance(pd_type, type): comp_types.append(pd_type) except AttributeError: pass native_type = _native_type_type_map(type_) if native_type is not None: comp_types.extend(native_type) if len(comp_types) < 1: raise ValueError("No recognized numpy/python type in list: %s" % type_list) return column.map(lambda x: isinstance(x, tuple(comp_types)))
apache-2.0
cloud-fan/spark
python/pyspark/pandas/tests/plot/test_series_plot.py
15
4133
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import unittest import pandas as pd import numpy as np from pyspark import pandas as ps from pyspark.pandas.plot import PandasOnSparkPlotAccessor, BoxPlotBase from pyspark.testing.pandasutils import have_plotly, plotly_requirement_message class SeriesPlotTest(unittest.TestCase): @property def pdf1(self): return pd.DataFrame( {"a": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 50]}, index=[0, 1, 3, 5, 6, 8, 9, 9, 9, 10, 10] ) @property def psdf1(self): return ps.from_pandas(self.pdf1) @unittest.skipIf(not have_plotly, plotly_requirement_message) def test_plot_backends(self): plot_backend = "plotly" with ps.option_context("plotting.backend", plot_backend): self.assertEqual(ps.options.plotting.backend, plot_backend) module = PandasOnSparkPlotAccessor._get_plot_backend(plot_backend) self.assertEqual(module.__name__, "pyspark.pandas.plot.plotly") def test_plot_backends_incorrect(self): fake_plot_backend = "none_plotting_module" with ps.option_context("plotting.backend", fake_plot_backend): self.assertEqual(ps.options.plotting.backend, fake_plot_backend) with self.assertRaises(ValueError): PandasOnSparkPlotAccessor._get_plot_backend(fake_plot_backend) def test_box_summary(self): def check_box_summary(psdf, pdf): k = 1.5 stats, fences = BoxPlotBase.compute_stats(psdf["a"], "a", whis=k, precision=0.01) outliers = BoxPlotBase.outliers(psdf["a"], "a", *fences) whiskers = BoxPlotBase.calc_whiskers("a", outliers) fliers = BoxPlotBase.get_fliers("a", outliers, whiskers[0]) expected_mean = pdf["a"].mean() expected_median = pdf["a"].median() expected_q1 = np.percentile(pdf["a"], 25) expected_q3 = np.percentile(pdf["a"], 75) iqr = expected_q3 - expected_q1 expected_fences = (expected_q1 - k * iqr, expected_q3 + k * iqr) pdf["outlier"] = ~pdf["a"].between(fences[0], fences[1]) expected_whiskers = ( pdf.query("not outlier")["a"].min(), pdf.query("not outlier")["a"].max(), ) expected_fliers = pdf.query("outlier")["a"].values self.assertEqual(expected_mean, stats["mean"]) self.assertEqual(expected_median, stats["med"]) self.assertEqual(expected_q1, stats["q1"] + 0.5) self.assertEqual(expected_q3, stats["q3"] - 0.5) self.assertEqual(expected_fences[0], fences[0] + 2.0) self.assertEqual(expected_fences[1], fences[1] - 2.0) self.assertEqual(expected_whiskers[0], whiskers[0]) self.assertEqual(expected_whiskers[1], whiskers[1]) self.assertEqual(expected_fliers, fliers) check_box_summary(self.psdf1, self.pdf1) check_box_summary(-self.psdf1, -self.pdf1) if __name__ == "__main__": from pyspark.pandas.tests.plot.test_series_plot import * # noqa: F401 try: import xmlrunner # type: ignore[import] testRunner = xmlrunner.XMLTestRunner(output="target/test-reports", verbosity=2) except ImportError: testRunner = None unittest.main(testRunner=testRunner, verbosity=2)
apache-2.0
NMTHydro/Recharge
utils/zonal_stats_shapefile_class_raster.py
1
13084
# =============================================================================== # Copyright 2018 gabe-parrish # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =============================================================================== # ============= standard library imports ======================== import os import ogr, gdal, osr import numpy as np import pandas as pd import glob # ============= local library imports =========================== def raster_sieve(masking_arr, target_masked_arr, iterator): masking_arr[masking_arr != iterator] = 0 masking_arr[masking_arr == 1] = 1 objective_arr = target_masked_arr * masking_arr print "good values", objective_arr print "mean of sieved values", objective_arr.mean() print "new mean of the changed masking_arr", masking_arr.mean() return objective_arr def main(): """""" # === Paths to shapefile, classified raster and target raster data set === # todo - Get this all as form-based application root = '/Users/Gabe/Desktop/wrri_stuff/NM_raster_zonal_stats' shapefile_path = os.path.join(root, 'test_polygon_file/test_polygon.shp') shapefile_name = 'test_polygon' class_raster = os.path.join(root, 'classified_raster/1985_mc_uniquevals_colors_final_9_nad83_13n.tif') rasters_path = os.path.join(root, 'rasters') output_path = os.path.join(root, 'output_tables') # what string do all the raster files have in common? search_string = 'water_fraction' # TODO - take this main() function and divvy it up so that tasks are compartmentalized.... # reading in the geotransform should be a separate function... # getting offsets should be a separate function. # need to rename the 'data' rasters and distinguish better from the class rasters... # mainly, add a feature where you can just do a shapefile, just do a class raster or both. But this is a good start. # === First let's just read in the class raster based on the path... # the raster ras_datasource = gdal.Open(class_raster) # the vector shape_datasource = ogr.Open(shapefile_path) layer_obj = shape_datasource.GetLayer() # get number of features in the layer num_features = layer_obj.GetFeatureCount() # ====== iterate through features ========= for i in range(num_features): feature = layer_obj.GetFeature(i) print "feature id {}".format(feature.GetField('id')) # this name is used for the naming convention of the output tables... feature_name = 'polygonid{}'.format(feature.GetField('id')) # take the feature and read in it's extent geom = feature.GetGeometryRef() # get the ring, which contains the nodes... ring = geom.GetGeometryRef(0) # how many points in the ring? number_points = ring.GetPointCount() x_points = [] y_points = [] for i in range(number_points): x, y, z = ring.GetPoint(i) x_points.append(x) y_points.append(y) # now you have the x's and y's of the nodes, you'll need the max and min extents of each xmin = min(x_points) xmax = max(x_points) ymin = min(y_points) ymax = max(y_points) # get the pixel widths from the raster (and other shape info) geotrans = ras_datasource.GetGeoTransform() # This pattern makes no sense by the way but it seems to be correct. xorigin = geotrans[0] yorigin = geotrans[3] pix_w = geotrans[1] pix_h = geotrans[5] print 'pix_h', pix_h # get the offsets -> you should figure out what the offset is and why it's calculated this way... x_off = int((xmin - xorigin)/pix_w) y_off = int((yorigin - ymax)/pix_w) # get the counts x_count = int((xmax - xmin) / pix_w) + 1 # add 1 bc index starts at zero, perhaps? y_count = int((ymax - ymin) / pix_w) + 1 # create memory target raster -> What's a memory raster? # The target dataset is an empty shell that we burn the vector onto when we rasterize print "test xcxc", x_count, y_count target_ds = gdal.GetDriverByName('MEM').Create('', x_count, y_count, 1, gdal.GDT_Byte) # why not float 32? print 'target_ds', target_ds target_ds.SetGeoTransform((xmin, pix_w, 0, ymax, 0, pix_h, )) # why the blank space?!?!?!? # the target raster needs the same projection as the original raster raster_srs = osr.SpatialReference() raster_srs.ImportFromWkt(ras_datasource.GetProjectionRef()) target_ds.SetProjection(raster_srs.ExportToWkt()) # Rasterize the polygon to a raster gdal.RasterizeLayer(target_ds, [1], layer_obj, burn_values=[1]) # read raster as arrays bandraster = ras_datasource.GetRasterBand(1) # when you read it as an array, you read it in starting with the offests from your shapefile data_raster = bandraster.ReadAsArray(x_off, y_off, x_count, y_count).astype(np.float) bandmask = target_ds.GetRasterBand(1) # For the mask, since we made it with the counts, we use those for reading, and we have zero x and y offset. data_mask = bandmask.ReadAsArray(0, 0, x_count, y_count).astype(np.float) # mask the raster with numpy masked_raster_arr = np.ma.masked_array(data_raster, np.logical_not(data_mask)) # print "first masked arr", masked_raster_arr print "mean same ol", np.mean(masked_raster_arr) # make this batch-file capable for a rasters path with many rasters.... # try to use glob to get the job done here.... for raster_path_string in glob.glob('{}/*{}.img'.format(rasters_path, search_string)): print 'raster path string', raster_path_string filename = raster_path_string.split('/')[-1] raster_name = filename.split('_')[0] # now you've clipped the class raster, do the same with the primary dataset! ras_datasource_primary = gdal.Open(raster_path_string) # get the geotransform geo_prime = ras_datasource_primary.GetGeoTransform() x_origin_prime = geo_prime[0] y_origin_prime = geo_prime[3] pix_w_prime = geo_prime[1] pix_h_prime = geo_prime[5] # new offsets x_off_prime = int((xmin - x_origin_prime) / pix_w_prime) y_off_prime = int((y_origin_prime - ymax) / pix_w_prime) # # get the counts # x_count = int((xmax - xmin) / pix_w_prime) + 1 # add 1 bc index starts at zero, perhaps? # y_count = int((ymax - ymin) / pix_w_prime) + 1 # read in prime raster with the correct offsets bandrasterprime = ras_datasource_primary.GetRasterBand(1) data_raster_prime = bandrasterprime.ReadAsArray(x_off_prime, y_off_prime, x_count, y_count).astype(np.float) # print "raster array", data_raster_prime # print "the regular raster mean", np.mean(data_raster_prime) masked_raster_arr_prime = np.ma.masked_array(data_raster_prime, np.logical_not(data_mask)) # print 'masked arr raster', masked_raster_arr_prime print "mean", np.mean(masked_raster_arr_prime) # you've got two masked arrays, time to iterate through the class one # need to ravel(), set to list, take the set of the list, and iterate through set. rav_arr = masked_raster_arr.ravel() list_arr = rav_arr.tolist() set_arr = set(list_arr) print "set, finally -> {}".format(set_arr) print "how does this look \n {}".format(masked_raster_arr) print "same ol mean?", masked_raster_arr.mean() # so we don't mess up our good array as we iterate and change values in-place masked_raster_arr # so to output the stats to a table, a good way to do it would be a dictionary ids = [] headers = ['mean', 'standard_deviation', 'minimum', 'maximum', 'range', 'variance'] shape_class_stats = {} for i in set_arr: class_stats = {'mean': [], 'standard_deviation': [], 'minimum': [], 'maximum': [], 'range': [], 'variance': []} if i != None: print "now we'll take care of this class {}".format(i) # keep track of the order you process the classes. ids.append(i) # do this to not mess up the masked_raster_arr by modifying it in-place in the function. mra = np.copy(masked_raster_arr) class_filtered_array = raster_sieve(mra, masked_raster_arr_prime, iterator=i) # use the class filtered array to add statistics do the dictionary # class_stats['mean'] = class_filtered_array.mean() # class_stats['standard deviation'] = class_filtered_array.std() # maximum = class_filtered_array.max() # minimum = class_filtered_array.min() # class_stats['minimum'] = class_filtered_array.min() # class_stats['maximum'] = class_filtered_array.max() # class_stats['range'] = maximum - minimum # class_stats['variance'] = class_filtered_array.var() class_stats['mean'].append(class_filtered_array.mean()) class_stats['standard_deviation'].append(class_filtered_array.std()) maximum = class_filtered_array.max() minimum = class_filtered_array.min() class_stats['minimum'].append(class_filtered_array.min()) class_stats['maximum'].append(class_filtered_array.max()) class_stats['range'].append(maximum-minimum) class_stats['variance'].append(class_filtered_array.var()) # mean = class_filtered_array.mean() # std_dev = class_filtered_array.std() # minimum = class_filtered_array.min() # maximum = class_filtered_array.max() # range = maximum - minimum # # median = class_filtered_array # variance = class_filtered_array.var() # make a dictionary with the statistics. # #todo - re evaluate this later... # class_stats = {'class label': 'class_{}'.format(i), 'mean': mean, # 'standard deviation': std_dev, 'minimum': minimum, 'maximum': maximum, # 'range': range, 'variance': variance} else: pass if i != None: shape_class_stats['{}'.format(i)] = class_stats # todo - let's try some test outputs to figure out how to format the table that will be output for each feature print shape_class_stats # cols = pd.MultiIndex.from_product([headers, ids]) # # cols = headers + ids # print 'cols', cols # pandas wants (inner key, outer key) : [data] in order to format the dataframe correctly. #shape_class_stats_format = {('{}'.format(outer_key), inner_key) : lst for outer_key, nested_dictionary in shape_class_stats.iteritems() for inner_key, lst in nested_dictionary.iteritems() } shape_class_stats_format = {} for key in ids: nested_dict = shape_class_stats['{}'.format(key)] for nest_key in headers: lst = nested_dict['{}'.format(nest_key)] shape_class_stats_format[('{}'.format(key), '{}'.format(nest_key))] = lst print "reformatted nested dictionary \n {}".format(shape_class_stats_format) df = pd.DataFrame(shape_class_stats_format) # tODO - see the stack overflow article on how to solve this one... table_output = os.path.join(output_path, 'shape_{}_{}_imageidentifier_{}.csv'.format(shapefile_name, feature_name, raster_name)) df.to_csv(table_output) print "let's see that df!\n ", df if __name__ == "__main__": main() # ======== EOF ==============\n
apache-2.0
sugartom/tensorflow-alien
tensorflow/examples/learn/iris_with_pipeline.py
62
1824
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Example of DNNClassifier for Iris plant dataset, with pipeline.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from sklearn import cross_validation from sklearn.datasets import load_iris from sklearn.metrics import accuracy_score from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler import tensorflow as tf learn = tf.contrib.learn def main(unused_argv): iris = load_iris() x_train, x_test, y_train, y_test = cross_validation.train_test_split( iris.data, iris.target, test_size=0.2, random_state=42) # It's useful to scale to ensure Stochastic Gradient Descent # will do the right thing. scaler = StandardScaler() # DNN classifier. classifier = learn.DNNClassifier( feature_columns=learn.infer_real_valued_columns_from_input(x_train), hidden_units=[10, 20, 10], n_classes=3) pipeline = Pipeline([('scaler', scaler), ('DNNclassifier', classifier)]) pipeline.fit(x_train, y_train, DNNclassifier__steps=200) score = accuracy_score(y_test, list(pipeline.predict(x_test))) print('Accuracy: {0:f}'.format(score)) if __name__ == '__main__': tf.app.run()
apache-2.0
victorbergelin/scikit-learn
sklearn/covariance/tests/test_graph_lasso.py
272
5245
""" Test the graph_lasso module. """ import sys import numpy as np from scipy import linalg from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_array_less from sklearn.covariance import (graph_lasso, GraphLasso, GraphLassoCV, empirical_covariance) from sklearn.datasets.samples_generator import make_sparse_spd_matrix from sklearn.externals.six.moves import StringIO from sklearn.utils import check_random_state from sklearn import datasets def test_graph_lasso(random_state=0): # Sample data from a sparse multivariate normal dim = 20 n_samples = 100 random_state = check_random_state(random_state) prec = make_sparse_spd_matrix(dim, alpha=.95, random_state=random_state) cov = linalg.inv(prec) X = random_state.multivariate_normal(np.zeros(dim), cov, size=n_samples) emp_cov = empirical_covariance(X) for alpha in (0., .1, .25): covs = dict() icovs = dict() for method in ('cd', 'lars'): cov_, icov_, costs = graph_lasso(emp_cov, alpha=alpha, mode=method, return_costs=True) covs[method] = cov_ icovs[method] = icov_ costs, dual_gap = np.array(costs).T # Check that the costs always decrease (doesn't hold if alpha == 0) if not alpha == 0: assert_array_less(np.diff(costs), 0) # Check that the 2 approaches give similar results assert_array_almost_equal(covs['cd'], covs['lars'], decimal=4) assert_array_almost_equal(icovs['cd'], icovs['lars'], decimal=4) # Smoke test the estimator model = GraphLasso(alpha=.25).fit(X) model.score(X) assert_array_almost_equal(model.covariance_, covs['cd'], decimal=4) assert_array_almost_equal(model.covariance_, covs['lars'], decimal=4) # For a centered matrix, assume_centered could be chosen True or False # Check that this returns indeed the same result for centered data Z = X - X.mean(0) precs = list() for assume_centered in (False, True): prec_ = GraphLasso(assume_centered=assume_centered).fit(Z).precision_ precs.append(prec_) assert_array_almost_equal(precs[0], precs[1]) def test_graph_lasso_iris(): # Hard-coded solution from R glasso package for alpha=1.0 # The iris datasets in R and sklearn do not match in a few places, these # values are for the sklearn version cov_R = np.array([ [0.68112222, 0.0, 0.2651911, 0.02467558], [0.00, 0.1867507, 0.0, 0.00], [0.26519111, 0.0, 3.0924249, 0.28774489], [0.02467558, 0.0, 0.2877449, 0.57853156] ]) icov_R = np.array([ [1.5188780, 0.0, -0.1302515, 0.0], [0.0, 5.354733, 0.0, 0.0], [-0.1302515, 0.0, 0.3502322, -0.1686399], [0.0, 0.0, -0.1686399, 1.8123908] ]) X = datasets.load_iris().data emp_cov = empirical_covariance(X) for method in ('cd', 'lars'): cov, icov = graph_lasso(emp_cov, alpha=1.0, return_costs=False, mode=method) assert_array_almost_equal(cov, cov_R) assert_array_almost_equal(icov, icov_R) def test_graph_lasso_iris_singular(): # Small subset of rows to test the rank-deficient case # Need to choose samples such that none of the variances are zero indices = np.arange(10, 13) # Hard-coded solution from R glasso package for alpha=0.01 cov_R = np.array([ [0.08, 0.056666662595, 0.00229729713223, 0.00153153142149], [0.056666662595, 0.082222222222, 0.00333333333333, 0.00222222222222], [0.002297297132, 0.003333333333, 0.00666666666667, 0.00009009009009], [0.001531531421, 0.002222222222, 0.00009009009009, 0.00222222222222] ]) icov_R = np.array([ [24.42244057, -16.831679593, 0.0, 0.0], [-16.83168201, 24.351841681, -6.206896552, -12.5], [0.0, -6.206896171, 153.103448276, 0.0], [0.0, -12.499999143, 0.0, 462.5] ]) X = datasets.load_iris().data[indices, :] emp_cov = empirical_covariance(X) for method in ('cd', 'lars'): cov, icov = graph_lasso(emp_cov, alpha=0.01, return_costs=False, mode=method) assert_array_almost_equal(cov, cov_R, decimal=5) assert_array_almost_equal(icov, icov_R, decimal=5) def test_graph_lasso_cv(random_state=1): # Sample data from a sparse multivariate normal dim = 5 n_samples = 6 random_state = check_random_state(random_state) prec = make_sparse_spd_matrix(dim, alpha=.96, random_state=random_state) cov = linalg.inv(prec) X = random_state.multivariate_normal(np.zeros(dim), cov, size=n_samples) # Capture stdout, to smoke test the verbose mode orig_stdout = sys.stdout try: sys.stdout = StringIO() # We need verbose very high so that Parallel prints on stdout GraphLassoCV(verbose=100, alphas=5, tol=1e-1).fit(X) finally: sys.stdout = orig_stdout # Smoke test with specified alphas GraphLassoCV(alphas=[0.8, 0.5], tol=1e-1, n_jobs=1).fit(X)
bsd-3-clause
sonapraneeth-a/object-classification
library/tf/models/MLPClassifier_old.py
1
30651
import tensorflow as tf from sklearn.metrics import confusion_matrix, classification_report, accuracy_score from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import numpy as np from library.utils import file_utils from sklearn.preprocessing import StandardScaler, MinMaxScaler import math import os, glob, time from os.path import basename from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file from library.preprocessing import ZCA # Resources # https://www.youtube.com/watch?v=3VEXX73tnw4 class TFMLPClassifier: def __init__(self, logs=True, log_dir='./logs/', learning_rate=0.01, activation_fn='softmax', restore=True, num_iterations=100, device='cpu', session_type='default', descent_method='adam', init_weights='random', display_step=10, reg_const=0.01, regularize=False, learning_rate_type='constant', model_name='./model/mlp_classifier_model.ckpt', save_model=False, transform=True, test_log=True, transform_method='StandardScaler', tolerance=1e-7, train_validate_split=None, separate_writer=False, batch_size=100, nodes_in_layers=[5, 5], activation_req=False, verbose=False): # Docs self.tensorboard_logs = logs self.verbose = verbose self.tensorboard_log_dir = log_dir self.merged_summary_op = None self.summary_writer = None self.train_writer = None self.validate_writer = None self.test_writer = None self.model = None self.model_name = model_name self.save_model = save_model self.train_loss_summary = None self.train_acc_summary = None self.validate_acc_summary = None self.test_acc_summary = None self.w_hist = None self.w_im = None self.b_hist = None self.restore = restore self.separate_writer = separate_writer # self.session = None self.device = device self.session_type = session_type # Parameters self.learning_rate = learning_rate self.max_iterations = num_iterations self.display_step = display_step self.tolerance = tolerance self.descent_method = descent_method self.init_weights = init_weights self.reg_const = reg_const self.regularize = regularize self.activation = activation_fn self.learning_rate_type = learning_rate_type self.batch_size = batch_size self.hidden_layers = nodes_in_layers # Data transform methods self.transform = transform self.transform_method = transform_method # Graph inputs self.x = None self.y_true = None self.y_true_cls = None self.num_features = None self.num_classes = None # Validation and testing self.y_pred = None self.y_pred_cls = None # self.init_var = None self.last_epoch = 0 self.global_step = 0 self.optimizer = None self.train_accuracy = None self.validate_accuracy = None self.test_log = test_log self.test_accuracy = None self.activation_req = activation_req self.weights = {} self.biases = {} self.layers = {} self.output_layer = None self.loss = None self.correct_prediction = None self.cross_entropy = None # self.train_validate_split = train_validate_split def print_parameters(self): print('Linear Classifier') def make_placeholders_for_inputs(self, num_features, num_classes): with tf.device('/cpu:0'): with tf.name_scope('Inputs'): with tf.name_scope('Data'): self.x = tf.placeholder(tf.float32, [None, num_features], name='X') with tf.name_scope('Train_Labels'): self.y_true = tf.placeholder(tf.float32, [None, num_classes], name='y_label') self.y_true_cls = tf.placeholder(tf.int64, [None], name='y_class') with tf.name_scope('Input_Image'): image_shaped_input = tf.reshape(self.x, [-1, 32, 32, 3]) tf.summary.image('Training_Images', image_shaped_input, 1) def make_weights(self, num_features, num_classes, number_of_layers=1): prev_layer_weights = num_features for layer_no in range(number_of_layers): weight = None weight_key = 'weight_' + str(layer_no) if self.init_weights == 'zeros': weight = tf.Variable(tf.zeros([prev_layer_weights, self.hidden_layers[layer_no]]), name='W_'+str(layer_no)+'_zeros') elif self.init_weights == 'random': weight = tf.Variable(tf.random_normal([prev_layer_weights, self.hidden_layers[layer_no]]), name='W_'+str(layer_no)+'_random_normal') else: weight = tf.Variable(tf.random_normal([prev_layer_weights, self.hidden_layers[layer_no]]), name='W_'+str(layer_no)+'_random_normal') self.weights[weight_key] = weight prev_layer_weights = self.hidden_layers[layer_no] def make_bias(self, num_features, num_classes, number_of_layers=1): for layer_no in range(number_of_layers): bias = None bias_key = 'bias_' + str(layer_no) bias = tf.Variable(tf.random_normal([self.hidden_layers[layer_no]]), name='b_'+str(layer_no)) self.biases[bias_key] = bias def make_layers(self, number_of_layers): prev_layer = self.x for layer_no in range(number_of_layers): layer = None weight_key = 'weight_' + str(layer_no) bias_key = 'bias_' + str(layer_no) layer_key = 'layer_' + str(layer_no) if self.activation == 'sigmoid': layer = tf.nn.sigmoid(tf.add(tf.matmul(prev_layer, self.weights[weight_key]), self.biases[bias_key]), name='Layer_'+str(layer_no)+'_sigmoid') elif self.activation == 'softmax': layer = tf.nn.softmax(tf.add(tf.matmul(prev_layer, self.weights[weight_key]), self.biases[bias_key]), name='Layer_' + str(layer_no)+'_softmax') elif self.activation == 'relu': layer = tf.nn.relu(tf.add(tf.matmul(prev_layer, self.weights[weight_key]), self.biases[bias_key]), name='Layer_' + str(layer_no)+'_relu') else: layer = tf.nn.relu(tf.add(tf.matmul(prev_layer, self.weights[weight_key]), self.biases[bias_key]), name='Layer_' + str(layer_no)+'_relu') self.layers[layer_key] = layer prev_layer = self.layers[layer_key] def make_output_layer(self): layer_key = layer_key = 'layer_' + str(len(self.hidden_layers)-1) print(len(self.hidden_layers)) print(layer_key) print(self.weights.keys()) print(self.biases.keys()) print('output') output = tf.Variable( tf.random_normal([self.hidden_layers[-1], self.num_classes])) print('bias') bias_output = tf.Variable(tf.random_normal([self.num_classes])) print('layer') self.output_layer = tf.add(tf.matmul(self.layers[layer_key], output), bias_output, name='out_layer') def make_parameters(self, num_features, num_classes): with tf.device('/cpu:0'): number_of_layers = len(self.hidden_layers) with tf.name_scope('Parameters'): with tf.name_scope('Weights'): self.make_weights(num_features, num_classes, number_of_layers) with tf.name_scope('Bias'): self.make_bias(num_features, num_classes, number_of_layers) with tf.name_scope('Hidden_Layers'): self.make_layers(number_of_layers) with tf.name_scope('Output_Layer'): self.make_output_layer() def make_predictions(self): with tf.device('/cpu:0'): with tf.name_scope('Predictions'): if self.activation_req is True: if self.activation == 'softmax': self.y_pred = tf.nn.softmax(self.output_layer) elif self.activation == 'relu': self.y_pred = tf.nn.relu(self.output_layer) elif self.activation == 'sigmoid': self.y_pred = tf.nn.sigmoid(self.output_layer) else: self.y_pred = self.output_layer self.y_pred_cls = tf.argmax(self.y_pred, dimension=1) def make_optimization(self): with tf.device('/cpu:0'): with tf.name_scope('Cross_Entropy'): self.cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.output_layer, labels=self.y_true) with tf.name_scope('Loss_Function'): if self.regularize is True: ridge_param = tf.cast(tf.constant(self.reg_const), dtype=tf.float32) ridge_loss = tf.reduce_mean(tf.square(self.weights)) self.loss = tf.add(tf.reduce_mean(self.cross_entropy), tf.multiply(ridge_param, ridge_loss)) else: self.loss = tf.reduce_mean(self.cross_entropy) self.train_loss_summary = tf.summary.scalar('Training_Error', self.loss) with tf.name_scope('Optimizer'): if self.learning_rate_type == 'exponential': learning_rate = tf.train.exponential_decay(self.learning_rate, self.global_step, self.display_step, 0.96, staircase=True) else: learning_rate = self.learning_rate if self.descent_method == 'gradient': self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\ .minimize(self.loss) elif self.descent_method == 'adam': self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\ .minimize(self.loss) else: self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\ .minimize(self.loss) self.correct_prediction = tf.equal(self.y_pred_cls, self.y_true_cls) def make_accuracy(self): with tf.device('/cpu:0'): with tf.name_scope('Train_Accuracy'): self.train_accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32)) if self.separate_writer is True: self.train_acc_summary = tf.summary.scalar('Train_Accuracy', self.train_accuracy) else: self.train_acc_summary = tf.summary.scalar('Train_Accuracy', self.train_accuracy) if self.train_validate_split is not None: with tf.name_scope('Validate_Accuracy'): self.validate_accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32)) if self.separate_writer is True: self.validate_acc_summary = tf.summary.scalar('Validate_Accuracy', self.validate_accuracy) else: self.validate_acc_summary = tf.summary.scalar('Validation_Accuracy', self.validate_accuracy) if self.test_log is True: with tf.name_scope('Test_Accuracy'): self.test_accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32)) if self.separate_writer is True: self.test_acc_summary = tf.summary.scalar('Test_Accuracy', self.test_accuracy) else: self.test_acc_summary = tf.summary.scalar('Test_Accuracy', self.test_accuracy) def create_graph(self, num_features, num_classes): self.num_features = num_features self.num_classes = num_classes self.global_step = tf.Variable(0, name='last_successful_epoch', trainable=False, dtype=tf.int32) self.last_epoch = tf.assign(self.global_step, self.global_step + 1, name='assign_updated_epoch') # Step 1: Creating placeholders for inputs self.make_placeholders_for_inputs(num_features, num_classes) # Step 2: Creating initial parameters for the variables self.make_parameters(num_features, num_classes) # Step 3: Make predictions for the data self.make_predictions() # Step 4: Perform optimization operation self.make_optimization() # Step 5: Calculate accuracies self.make_accuracy() # Step 6: Initialize all the required variables with tf.device('/cpu:0'): self.init_var = tf.global_variables_initializer() if self.verbose is True: print('X : ' + str(self.x)) print('Y_true : ' + str(self.y_true)) print('Y_true_cls : ' + str(self.y_true_cls)) print('W : ' + str(self.weights)) for i in range(len(self.hidden_layers)): weight_key = 'weight_' + str(i) print(' weight_%d : %s' % (i,str(self.weights[weight_key]))) print('b : ' + str(self.biases)) for i in range(len(self.hidden_layers)): bias_key = 'bias_' + str(i) print(' bias_%d : %s' % (i,str(self.biases[bias_key]))) print('Layers : ' + str(self.layers)) for i in range(len(self.hidden_layers)): layer_key = 'layer_' + str(i) print(' layer_%d : %s' % (i,str(self.layers[layer_key]))) print('Output layer : ' + str(self.output_layer)) print('Y_pred : ' + str(self.y_pred)) print('Y_pred_cls : ' + str(self.y_pred_cls)) print('cross_entropy : ' + str(self.cross_entropy)) print('train_loss : ' + str(self.loss)) print('optimizer : ' + str(self.optimizer)) print('correct_prediction : ' + str(self.correct_prediction)) print('Train Accuracy : ' + str(self.train_accuracy)) print('Validate Accuracy : ' + str(self.validate_accuracy)) print('Test Accuracy : ' + str(self.test_accuracy)) return True def fit(self, data, labels, classes, test_data=None, test_labels=None, test_classes=None): if self.device == 'cpu': print('Using CPU') config = tf.ConfigProto( log_device_placement=True, allow_soft_placement=True, #allow_growth=True, #device_count={'CPU': 0} ) else: print('Using GPU') config = tf.ConfigProto( log_device_placement=True, allow_soft_placement=True, #allow_growth=True, #device_count={'GPU': 0} ) if self.session_type == 'default': self.session = tf.Session(config=config) if self.session_type == 'interactive': self.session = tf.InteractiveSession(config=config) print('Session: ' + str(self.session)) self.session.run(self.init_var) if self.tensorboard_logs is True: file_utils.mkdir_p(self.tensorboard_log_dir) self.merged_summary_op = tf.summary.merge_all() if self.restore is False: file_utils.delete_all_files_in_dir(self.tensorboard_log_dir) if self.separate_writer is False: self.summary_writer = tf.summary.FileWriter(self.tensorboard_log_dir, graph=self.session.graph) else: self.train_writer = tf.summary.FileWriter(self.tensorboard_log_dir + 'train', graph=self.session.graph) if self.train_validate_split is not None: self.validate_writer = tf.summary.FileWriter(self.tensorboard_log_dir + 'validate', graph=self.session.graph) if self.test_log is True: self.test_writer = tf.summary.FileWriter(self.tensorboard_log_dir + 'test', graph=self.session.graph) if self.save_model is True: self.model = tf.train.Saver(max_to_keep=5) if self.train_validate_split is not None: train_data, validate_data, train_labels, validate_labels, train_classes, validate_classes = \ train_test_split(data, labels, classes, train_size=self.train_validate_split) if self.verbose is True: print('Data shape: ' + str(data.shape)) print('Labels shape: ' + str(labels.shape)) print('Classes shape: ' + str(classes.shape)) print('Train Data shape: ' + str(train_data.shape)) print('Train Labels shape: ' + str(train_labels.shape)) print('Train Classes shape: ' + str(train_classes.shape)) print('Validate Data shape: ' + str(validate_data.shape)) print('Validate Labels shape: ' + str(validate_labels.shape)) print('Validate Classes shape: ' + str(validate_classes.shape)) if self.test_log is False: self.optimize(train_data, train_labels, train_classes, validate_data=validate_data, validate_labels=validate_labels, validate_classes=validate_classes) else: self.optimize(train_data, train_labels, train_classes, validate_data=validate_data, validate_labels=validate_labels, validate_classes=validate_classes, test_data=test_data, test_labels=test_labels, test_classes=test_classes) else: if self.test_log is False: self.optimize(data, labels, classes) else: self.optimize(data, labels, classes, test_data=test_data, test_labels=test_labels, test_classes=test_classes) def optimize(self, train_data, train_labels, train_classes, validate_data=None, validate_labels=None, validate_classes=None, test_data = None, test_labels = None, test_classes = None): if self.transform is True: if self.transform_method == 'StandardScaler': ss = StandardScaler() train_data = ss.fit_transform(train_data) if self.train_validate_split is not None: validate_data = ss.fit_transform(validate_data) if self.test_log is True: test_data = ss.fit_transform(test_data) if self.transform_method == 'MinMaxScaler': ss = MinMaxScaler() train_data = ss.fit_transform(train_data) if self.train_validate_split is not None: validate_data = ss.fit_transform(validate_data) if self.test_log is True: test_data = ss.fit_transform(test_data) file_name = os.path.splitext(os.path.abspath(self.model_name))[0] num_files = len(sorted(glob.glob(os.path.abspath(file_name + '*.meta')))) if num_files > 0: checkpoint_file = os.path.abspath(sorted(glob.glob(file_name + '*.data-00000-of-00001'), reverse=True)[0]) if os.path.exists(checkpoint_file): print('Restoring model from %s' % checkpoint_file) meta_file = os.path.abspath(sorted(glob.glob(file_name + '*.meta'), reverse=True)[0]) print('Loading: %s' %meta_file) saver = tf.train.import_meta_graph(meta_file) print('Loading: %s' %os.path.abspath(checkpoint_file)) cpk = tf.train.latest_checkpoint(os.path.dirname(meta_file)) print('Checkpoint: ' + str(cpk)) print('Tensors') print(print_tensors_in_checkpoint_file(file_name=cpk, all_tensors='', tensor_name='')) saver.restore(self.session, tf.train.latest_checkpoint(os.path.dirname(meta_file))) print('Last epoch to restore: ' + str(self.session.run(self.global_step))) if self.train_validate_split is not None: if self.test_log is False: self.run(train_data, train_labels, train_classes, validate_data=validate_data, validate_labels=validate_labels, validate_classes=validate_classes) else: self.run(train_data, train_labels, train_classes, validate_data=validate_data, validate_labels=validate_labels, validate_classes=validate_classes, test_data=test_data, test_labels=test_labels, test_classes=test_classes) else: if self.test_log is False: self.run(train_data, train_labels, train_classes) else: self.run(train_data, train_labels, train_classes, test_data=test_data, test_labels=test_labels, test_classes=test_classes) def run(self, train_data, train_labels, train_classes, validate_data=None, validate_labels=None, validate_classes=None, test_data=None, test_labels=None, test_classes=None): if self.train_validate_split is not None: feed_dict_validate = {self.x: validate_data, self.y_true: validate_labels, self.y_true_cls: validate_classes} if self.test_log is True: feed_dict_test = {self.x: test_data, self.y_true: test_labels, self.y_true_cls: test_classes} epoch = self.session.run(self.global_step) print('Last successful epoch: ' + str(epoch)) converged = False prev_cost = 0 start = time.time() end_batch_index = 0 num_batches = int(train_data.shape[0] / self.batch_size) while (epoch != self.max_iterations) and converged is False: start_batch_index = 0 for batch in range(num_batches): # print('Training on batch %d' %batch) end_batch_index = start_batch_index + self.batch_size if end_batch_index < train_data.shape[0]: train_batch_data = train_data[start_batch_index:end_batch_index, :] train_batch_labels = train_labels[start_batch_index:end_batch_index, :] train_batch_classes = train_classes[start_batch_index:end_batch_index] else: train_batch_data = train_data[start_batch_index:, :] train_batch_labels = train_labels[start_batch_index:, :] train_batch_classes = train_classes[start_batch_index:] feed_dict_train = {self.x: train_batch_data, self.y_true: train_batch_labels, self.y_true_cls: train_batch_classes} _, cost, train_acc, curr_epoch = self.session.run([self.optimizer, self.loss, self.train_accuracy, self.last_epoch], feed_dict=feed_dict_train) train_loss_summary = self.session.run(self.train_loss_summary, feed_dict=feed_dict_train) train_acc_summary = self.session.run(self.train_acc_summary, feed_dict=feed_dict_train) start_batch_index += self.batch_size if self.train_validate_split is not None: validate_acc, validate_summary = \ self.session.run([self.validate_accuracy, self.validate_acc_summary], feed_dict=feed_dict_validate) if self.test_log is True: test_acc, test_summary = \ self.session.run([self.test_accuracy, self.test_acc_summary], feed_dict=feed_dict_test) if self.separate_writer is False: self.summary_writer.add_summary(train_loss_summary, epoch) self.summary_writer.add_summary(train_acc_summary, epoch) self.summary_writer.add_summary(validate_summary, epoch) self.summary_writer.add_summary(test_summary, epoch) else: self.train_writer.add_summary(train_loss_summary, epoch) self.train_writer.add_summary(train_acc_summary, epoch) if self.train_validate_split is not None: self.validate_writer.add_summary(validate_summary, epoch) if self.test_log is True: self.test_writer.add_summary(test_summary, epoch) if epoch % self.display_step == 0: duration = time.time() - start if self.train_validate_split is not None and self.test_log is False: print('>>> Epoch [%*d/%*d] | Error: %.4f | Train Acc.: %.4f | Validate Acc.: %.4f | ' 'Duration: %.4f seconds' %(int(len(str(self.max_iterations))), epoch, int(len(str(self.max_iterations))), self.max_iterations, cost, train_acc, validate_acc, duration)) elif self.train_validate_split is not None and self.test_log is True: print('>>> Epoch [%*d/%*d] | Error: %.4f | Train Acc.: %.4f | Validate Acc.: %.4f | ' 'Test Acc.: %.4f | Duration: %.4f seconds' %(int(len(str(self.max_iterations))), epoch, int(len(str(self.max_iterations))), self.max_iterations, cost, train_acc, validate_acc, test_acc, duration)) elif self.train_validate_split is None and self.test_log is True: print('>>> Epoch [%*d/%*d] | Error: %.4f | Train Acc.: %.4f | ' 'Test Acc.: %.4f | Duration: %.4f seconds' %(int(len(str(self.max_iterations))), epoch, int(len(str(self.max_iterations))), self.max_iterations, cost, train_acc, test_acc, duration)) else: print('>>> Epoch [%*d/%*d] | Error: %.4f | Train Acc.: %.4f | Duration of run: %.4f seconds' % (int(len(str(self.max_iterations))), epoch, int(len(str(self.max_iterations))), self.max_iterations, cost, train_acc)) start = time.time() if self.save_model is True: model_directory = os.path.dirname(self.model_name) file_utils.mkdir_p(model_directory) self.model.save(self.session, self.model_name, global_step=epoch) if epoch == 0: prev_cost = cost else: if math.fabs(cost-prev_cost) < self.tolerance: converged = False epoch += 1 # print('Current success step: ' + str(self.session.run(self.global_step))) def fit_and_test(self, data, labels, classes, test_data, test_labels, test_classes): self.fit(data, labels, classes) def predict(self, data): if self.transform is True: if self.transform_method == 'StandardScaler': ss = StandardScaler() data = ss.fit_transform(data) if self.transform_method == 'MinMaxScaler': ss = MinMaxScaler() data = ss.fit_transform(data) feed_dict_data = {self.x: data} predictions = self.session.run(self.y_pred_cls, feed_dict=feed_dict_data) predictions = np.array(predictions) return predictions def load_model(self, model_name): self.model.restore(self.session, model_name) def close(self): self.session.close() def print_accuracy(self, test_data, test_labels, test_classes): predict_classes = self.predict(test_data) return accuracy_score(test_classes, predict_classes, normalize=True) def print_classification_results(self, test_data, test_labels, test_classes): if self.transform is True: if self.transform_method == 'StandardScaler': ss = StandardScaler() test_data = ss.fit_transform(test_data) if self.transform_method == 'MinMaxScaler': ss = MinMaxScaler() test_data = ss.fit_transform(test_data) feed_dict_test = {self.x: test_data, self.y_true: test_labels, self.y_true_cls: test_classes} cls_true = test_classes cls_pred = self.session.run(self.y_pred_cls, feed_dict=feed_dict_test) cm = confusion_matrix(y_true=cls_true, y_pred=cls_pred) print('Confusion matrix') print(cm) print('Detailed classification report') print(classification_report(y_true=cls_true, y_pred=cls_pred)) def __exit__(self, exc_type, exc_val, exc_tb): self.session.close() if self.separate_writer is False: self.summary_writer.close() else: self.train_writer.close() if self.train_validate_split is not None: self.validate_writer.close() if self.test_log is True: self.test_writer.close() def __del__(self): self.session.close() if self.separate_writer is False: self.summary_writer.close() else: self.train_writer.close() if self.train_validate_split is not None: self.validate_writer.close() if self.test_log is True: self.test_writer.close()
mit
chenyyx/scikit-learn-doc-zh
examples/zh/semi_supervised/plot_label_propagation_digits_active_learning.py
36
4076
""" ======================================== Label Propagation digits active learning ======================================== Demonstrates an active learning technique to learn handwritten digits using label propagation. We start by training a label propagation model with only 10 labeled points, then we select the top five most uncertain points to label. Next, we train with 15 labeled points (original 10 + 5 new ones). We repeat this process four times to have a model trained with 30 labeled examples. Note you can increase this to label more than 30 by changing `max_iterations`. Labeling more than 30 can be useful to get a sense for the speed of convergence of this active learning technique. A plot will appear showing the top 5 most uncertain digits for each iteration of training. These may or may not contain mistakes, but we will train the next model with their true labels. """ print(__doc__) # Authors: Clay Woolam <clay@woolam.org> # License: BSD import numpy as np import matplotlib.pyplot as plt from scipy import stats from sklearn import datasets from sklearn.semi_supervised import label_propagation from sklearn.metrics import classification_report, confusion_matrix digits = datasets.load_digits() rng = np.random.RandomState(0) indices = np.arange(len(digits.data)) rng.shuffle(indices) X = digits.data[indices[:330]] y = digits.target[indices[:330]] images = digits.images[indices[:330]] n_total_samples = len(y) n_labeled_points = 10 max_iterations = 5 unlabeled_indices = np.arange(n_total_samples)[n_labeled_points:] f = plt.figure() for i in range(max_iterations): if len(unlabeled_indices) == 0: print("No unlabeled items left to label.") break y_train = np.copy(y) y_train[unlabeled_indices] = -1 lp_model = label_propagation.LabelSpreading(gamma=0.25, max_iter=5) lp_model.fit(X, y_train) predicted_labels = lp_model.transduction_[unlabeled_indices] true_labels = y[unlabeled_indices] cm = confusion_matrix(true_labels, predicted_labels, labels=lp_model.classes_) print("Iteration %i %s" % (i, 70 * "_")) print("Label Spreading model: %d labeled & %d unlabeled (%d total)" % (n_labeled_points, n_total_samples - n_labeled_points, n_total_samples)) print(classification_report(true_labels, predicted_labels)) print("Confusion matrix") print(cm) # compute the entropies of transduced label distributions pred_entropies = stats.distributions.entropy( lp_model.label_distributions_.T) # select up to 5 digit examples that the classifier is most uncertain about uncertainty_index = np.argsort(pred_entropies)[::-1] uncertainty_index = uncertainty_index[ np.in1d(uncertainty_index, unlabeled_indices)][:5] # keep track of indices that we get labels for delete_indices = np.array([]) # for more than 5 iterations, visualize the gain only on the first 5 if i < 5: f.text(.05, (1 - (i + 1) * .183), "model %d\n\nfit with\n%d labels" % ((i + 1), i * 5 + 10), size=10) for index, image_index in enumerate(uncertainty_index): image = images[image_index] # for more than 5 iterations, visualize the gain only on the first 5 if i < 5: sub = f.add_subplot(5, 5, index + 1 + (5 * i)) sub.imshow(image, cmap=plt.cm.gray_r) sub.set_title("predict: %i\ntrue: %i" % ( lp_model.transduction_[image_index], y[image_index]), size=10) sub.axis('off') # labeling 5 points, remote from labeled set delete_index, = np.where(unlabeled_indices == image_index) delete_indices = np.concatenate((delete_indices, delete_index)) unlabeled_indices = np.delete(unlabeled_indices, delete_indices) n_labeled_points += len(uncertainty_index) f.suptitle("Active learning with Label Propagation.\nRows show 5 most " "uncertain labels to learn with the next model.") plt.subplots_adjust(0.12, 0.03, 0.9, 0.8, 0.2, 0.45) plt.show()
gpl-3.0
AlexGidiotis/Multimodal-Gesture-Recognition-with-LSTMs-and-CTC
skeletal_network/load_skeleton.py
1
2178
import pandas as pd import numpy as np # The arrays loaded are not in proper format so we modify them to x,y pairs. Also we filter irrelevant values. def modify_array(arr): # arrays to be returned arr_x = [] arr_y = [] for item in arr: # Get the items in proper format item = item.strip('[').strip(']').split() # Filter values if int(item[0]) >= 640 : item[0] = 320 if int(item[1]) >= 480 : item[1] = 240 # Save to the lists to be returned arr_x.append(int(item[0])) arr_y.append(int(item[1])) return arr_x, arr_y # Opens a data file and imports values # args: sk_data_path: path to the data folder # data_file: file to be imported # returns: df: a dataframe with all the imported values # skeletal data files come in the following format: # Frame: f Hip,Shoulder_Center,Left: lsx,lsy lex,ley lwx,lwy lhx,lhy Right: rsx,rsy rex,rey rwx,rwy rhx,rhy def import_data(sk_data_path, data_file): data_f = open(sk_data_path + '/' + data_file, 'r') # Read the data from csv file read_df = pd.read_csv(data_f) frame = read_df['Unnamed: 0'].as_matrix() hip = read_df['hip_center'].as_matrix() shoulder_cent = read_df['shoulder_center'].as_matrix() l_shoulder = read_df['left_shoulder'].as_matrix() l_elbow = read_df['left_elbow'].as_matrix() l_wrist = read_df['left_wrist'].as_matrix() l_hand = read_df['left_hand'].as_matrix() r_shoulder = read_df['right_shoulder'].as_matrix() r_elbow = read_df['right_elbow'].as_matrix() r_wrist = read_df['right_wrist'].as_matrix() r_hand = read_df['right_hand'].as_matrix() # Create the new dataframe for further processing df = pd.DataFrame() df['frame'] = frame df['hipX'], df['hipY'] = modify_array(hip) df['shcX'], df['shcY'] = modify_array(shoulder_cent) df['lsX'], df['lsY'] = modify_array(l_shoulder) df['leX'], df['leY'] = modify_array(l_elbow) df['lwX'], df['lwY'] = modify_array(l_wrist) df['lhX'], df['lhY'] = modify_array(l_hand) df['rsX'], df['rsY'] = modify_array(r_shoulder) df['reX'], df['reY'] = modify_array(r_elbow) df['rwX'], df['rwY'] = modify_array(r_wrist) df['rhX'], df['rhY'] = modify_array(r_hand) return df
mit
vinodkc/spark
python/pyspark/pandas/data_type_ops/boolean_ops.py
2
13344
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import numbers from typing import TYPE_CHECKING, Union import pandas as pd from pandas.api.types import CategoricalDtype from pyspark import sql as spark from pyspark.pandas.base import column_op, IndexOpsMixin from pyspark.pandas.data_type_ops.base import ( is_valid_operand_for_numeric_arithmetic, DataTypeOps, T_IndexOps, transform_boolean_operand_to_numeric, _as_bool_type, _as_categorical_type, _as_other_type, ) from pyspark.pandas.internal import InternalField from pyspark.pandas.typedef import Dtype, extension_dtypes, pandas_on_spark_type from pyspark.pandas.typedef.typehints import as_spark_type from pyspark.sql import functions as F from pyspark.sql.types import BooleanType, StringType if TYPE_CHECKING: from pyspark.pandas.indexes import Index # noqa: F401 (SPARK-34943) from pyspark.pandas.series import Series # noqa: F401 (SPARK-34943) class BooleanOps(DataTypeOps): """ The class for binary operations of pandas-on-Spark objects with spark type: BooleanType. """ @property def pretty_name(self) -> str: return "booleans" def add(self, left, right) -> Union["Series", "Index"]: if not is_valid_operand_for_numeric_arithmetic(right): raise TypeError( "Addition can not be applied to %s and the given type." % self.pretty_name ) if isinstance(right, bool): return left.__or__(right) elif isinstance(right, numbers.Number): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return left + right else: assert isinstance(right, IndexOpsMixin) if isinstance(right, IndexOpsMixin) and isinstance(right.spark.data_type, BooleanType): return left.__or__(right) else: left = transform_boolean_operand_to_numeric(left, right.spark.data_type) return left + right def sub(self, left, right) -> Union["Series", "Index"]: if not is_valid_operand_for_numeric_arithmetic(right, allow_bool=False): raise TypeError( "Subtraction can not be applied to %s and the given type." % self.pretty_name ) if isinstance(right, numbers.Number) and not isinstance(right, bool): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return left - right else: assert isinstance(right, IndexOpsMixin) left = transform_boolean_operand_to_numeric(left, right.spark.data_type) return left - right def mul(self, left, right) -> Union["Series", "Index"]: if not is_valid_operand_for_numeric_arithmetic(right): raise TypeError( "Multiplication can not be applied to %s and the given type." % self.pretty_name ) if isinstance(right, bool): return left.__and__(right) elif isinstance(right, numbers.Number): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return left * right else: assert isinstance(right, IndexOpsMixin) if isinstance(right, IndexOpsMixin) and isinstance(right.spark.data_type, BooleanType): return left.__and__(right) else: left = transform_boolean_operand_to_numeric(left, right.spark.data_type) return left * right def truediv(self, left, right) -> Union["Series", "Index"]: if not is_valid_operand_for_numeric_arithmetic(right, allow_bool=False): raise TypeError( "True division can not be applied to %s and the given type." % self.pretty_name ) if isinstance(right, numbers.Number) and not isinstance(right, bool): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return left / right else: assert isinstance(right, IndexOpsMixin) left = transform_boolean_operand_to_numeric(left, right.spark.data_type) return left / right def floordiv(self, left, right) -> Union["Series", "Index"]: if not is_valid_operand_for_numeric_arithmetic(right, allow_bool=False): raise TypeError( "Floor division can not be applied to %s and the given type." % self.pretty_name ) if isinstance(right, numbers.Number) and not isinstance(right, bool): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return left // right else: assert isinstance(right, IndexOpsMixin) left = transform_boolean_operand_to_numeric(left, right.spark.data_type) return left // right def mod(self, left, right) -> Union["Series", "Index"]: if not is_valid_operand_for_numeric_arithmetic(right, allow_bool=False): raise TypeError( "Modulo can not be applied to %s and the given type." % self.pretty_name ) if isinstance(right, numbers.Number) and not isinstance(right, bool): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return left % right else: assert isinstance(right, IndexOpsMixin) left = transform_boolean_operand_to_numeric(left, right.spark.data_type) return left % right def pow(self, left, right) -> Union["Series", "Index"]: if not is_valid_operand_for_numeric_arithmetic(right, allow_bool=False): raise TypeError( "Exponentiation can not be applied to %s and the given type." % self.pretty_name ) if isinstance(right, numbers.Number) and not isinstance(right, bool): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return left ** right else: assert isinstance(right, IndexOpsMixin) left = transform_boolean_operand_to_numeric(left, right.spark.data_type) return left ** right def radd(self, left, right) -> Union["Series", "Index"]: if isinstance(right, bool): return left.__or__(right) elif isinstance(right, numbers.Number): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return right + left else: raise TypeError( "Addition can not be applied to %s and the given type." % self.pretty_name ) def rsub(self, left, right) -> Union["Series", "Index"]: if isinstance(right, numbers.Number) and not isinstance(right, bool): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return right - left else: raise TypeError( "Subtraction can not be applied to %s and the given type." % self.pretty_name ) def rmul(self, left, right) -> Union["Series", "Index"]: if isinstance(right, bool): return left.__and__(right) elif isinstance(right, numbers.Number): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return right * left else: raise TypeError( "Multiplication can not be applied to %s and the given type." % self.pretty_name ) def rtruediv(self, left, right) -> Union["Series", "Index"]: if isinstance(right, numbers.Number) and not isinstance(right, bool): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return right / left else: raise TypeError( "True division can not be applied to %s and the given type." % self.pretty_name ) def rfloordiv(self, left, right) -> Union["Series", "Index"]: if isinstance(right, numbers.Number) and not isinstance(right, bool): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return right // left else: raise TypeError( "Floor division can not be applied to %s and the given type." % self.pretty_name ) def rpow(self, left, right) -> Union["Series", "Index"]: if isinstance(right, numbers.Number) and not isinstance(right, bool): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return right ** left else: raise TypeError( "Exponentiation can not be applied to %s and the given type." % self.pretty_name ) def rmod(self, left, right) -> Union["Series", "Index"]: if isinstance(right, numbers.Number) and not isinstance(right, bool): left = left.spark.transform(lambda scol: scol.cast(as_spark_type(type(right)))) return right % left else: raise TypeError( "Modulo can not be applied to %s and the given type." % self.pretty_name ) def __and__(self, left, right) -> Union["Series", "Index"]: if isinstance(right, IndexOpsMixin) and isinstance(right.dtype, extension_dtypes): return right.__and__(left) else: def and_func(left, right): if not isinstance(right, spark.Column): if pd.isna(right): right = F.lit(None) else: right = F.lit(right) scol = left & right return F.when(scol.isNull(), False).otherwise(scol) return column_op(and_func)(left, right) def __or__(self, left, right) -> Union["Series", "Index"]: if isinstance(right, IndexOpsMixin) and isinstance(right.dtype, extension_dtypes): return right.__or__(left) else: def or_func(left, right): if not isinstance(right, spark.Column) and pd.isna(right): return F.lit(False) else: scol = left | F.lit(right) return F.when(left.isNull() | scol.isNull(), False).otherwise(scol) return column_op(or_func)(left, right) def astype(self, index_ops: T_IndexOps, dtype: Union[str, type, Dtype]) -> T_IndexOps: dtype, spark_type = pandas_on_spark_type(dtype) if isinstance(dtype, CategoricalDtype): return _as_categorical_type(index_ops, dtype, spark_type) elif isinstance(spark_type, BooleanType): return _as_bool_type(index_ops, dtype) elif isinstance(spark_type, StringType): if isinstance(dtype, extension_dtypes): scol = F.when( index_ops.spark.column.isNotNull(), F.when(index_ops.spark.column, "True").otherwise("False"), ) else: null_str = str(None) casted = F.when(index_ops.spark.column, "True").otherwise("False") scol = F.when(index_ops.spark.column.isNull(), null_str).otherwise(casted) return index_ops._with_new_scol( scol.alias(index_ops._internal.data_spark_column_names[0]), field=InternalField(dtype=dtype), ) else: return _as_other_type(index_ops, dtype, spark_type) class BooleanExtensionOps(BooleanOps): """ The class for binary operations of pandas-on-Spark objects with spark type BooleanType, and dtype BooleanDtype. """ def __and__(self, left, right) -> Union["Series", "Index"]: def and_func(left, right): if not isinstance(right, spark.Column): if pd.isna(right): right = F.lit(None) else: right = F.lit(right) return left & right return column_op(and_func)(left, right) def __or__(self, left, right) -> Union["Series", "Index"]: def or_func(left, right): if not isinstance(right, spark.Column): if pd.isna(right): right = F.lit(None) else: right = F.lit(right) return left | right return column_op(or_func)(left, right) def restore(self, col: pd.Series) -> pd.Series: """Restore column when to_pandas.""" return col.astype(self.dtype)
apache-2.0
calben/matlabconverters
matlabconverters/loaders.py
1
1129
import numpy as np import pandas as pd from scipy.io import loadmat def load_mat(mat: str, show_debug=False) -> {}: data = loadmat(mat) if(show_debug): print("Mat has " + str(len(data.keys())) + " keys.") if verify_flat_mat(data): print("Mat is flat.") else: print("Mat is not flat.") return data def verify_flat_mat(data: {}, show_debug = False) -> bool: try: for k, v in data.items(): if "__" not in k: if not (isinstance(v, (np.ndarray, np.generic))): return False return True except Exception as e: print(e) return False def strip_mat_metadata(mat : {}, show_debug = False) -> {}: result = {} for k, v in mat.items(): if "__" not in k: if (isinstance(v, (np.ndarray, np.generic))): result[k] = v if(show_debug): print("Keys := " + str(result.keys())) return result def load_mat_to_pandas(mat : str, show_debug = False) -> pd.DataFrame: return pd.DataFrame(strip_mat_metadata(load_mat(mat, show_debug)))
mit
bjorand/influxdb-python
influxdb/tests/influxdb08/dataframe_client_test.py
8
12409
# -*- coding: utf-8 -*- """ unit tests for misc module """ from .client_test import _mocked_session import unittest import json import requests_mock from nose.tools import raises from datetime import timedelta from influxdb.tests import skipIfPYpy, using_pypy import copy import warnings if not using_pypy: import pandas as pd from pandas.util.testing import assert_frame_equal from influxdb.influxdb08 import DataFrameClient @skipIfPYpy class TestDataFrameClient(unittest.TestCase): def setUp(self): # By default, raise exceptions on warnings warnings.simplefilter('error', FutureWarning) def test_write_points_from_dataframe(self): now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]], index=[now, now + timedelta(hours=1)], columns=["column_one", "column_two", "column_three"]) points = [ { "points": [ ["1", 1, 1.0, 0], ["2", 2, 2.0, 3600] ], "name": "foo", "columns": ["column_one", "column_two", "column_three", "time"] } ] with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/db/db/series") cli = DataFrameClient(database='db') cli.write_points({"foo": dataframe}) self.assertListEqual(json.loads(m.last_request.body), points) def test_write_points_from_dataframe_with_float_nan(self): now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[[1, float("NaN"), 1.0], [2, 2, 2.0]], index=[now, now + timedelta(hours=1)], columns=["column_one", "column_two", "column_three"]) points = [ { "points": [ [1, None, 1.0, 0], [2, 2, 2.0, 3600] ], "name": "foo", "columns": ["column_one", "column_two", "column_three", "time"] } ] with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/db/db/series") cli = DataFrameClient(database='db') cli.write_points({"foo": dataframe}) self.assertListEqual(json.loads(m.last_request.body), points) def test_write_points_from_dataframe_in_batches(self): now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]], index=[now, now + timedelta(hours=1)], columns=["column_one", "column_two", "column_three"]) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/db/db/series") cli = DataFrameClient(database='db') self.assertTrue(cli.write_points({"foo": dataframe}, batch_size=1)) def test_write_points_from_dataframe_with_numeric_column_names(self): now = pd.Timestamp('1970-01-01 00:00+00:00') # df with numeric column names dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]], index=[now, now + timedelta(hours=1)]) points = [ { "points": [ ["1", 1, 1.0, 0], ["2", 2, 2.0, 3600] ], "name": "foo", "columns": ['0', '1', '2', "time"] } ] with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/db/db/series") cli = DataFrameClient(database='db') cli.write_points({"foo": dataframe}) self.assertListEqual(json.loads(m.last_request.body), points) def test_write_points_from_dataframe_with_period_index(self): dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]], index=[pd.Period('1970-01-01'), pd.Period('1970-01-02')], columns=["column_one", "column_two", "column_three"]) points = [ { "points": [ ["1", 1, 1.0, 0], ["2", 2, 2.0, 86400] ], "name": "foo", "columns": ["column_one", "column_two", "column_three", "time"] } ] with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/db/db/series") cli = DataFrameClient(database='db') cli.write_points({"foo": dataframe}) self.assertListEqual(json.loads(m.last_request.body), points) def test_write_points_from_dataframe_with_time_precision(self): now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]], index=[now, now + timedelta(hours=1)], columns=["column_one", "column_two", "column_three"]) points = [ { "points": [ ["1", 1, 1.0, 0], ["2", 2, 2.0, 3600] ], "name": "foo", "columns": ["column_one", "column_two", "column_three", "time"] } ] points_ms = copy.deepcopy(points) points_ms[0]["points"][1][-1] = 3600 * 1000 points_us = copy.deepcopy(points) points_us[0]["points"][1][-1] = 3600 * 1000000 with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/db/db/series") cli = DataFrameClient(database='db') cli.write_points({"foo": dataframe}, time_precision='s') self.assertListEqual(json.loads(m.last_request.body), points) cli.write_points({"foo": dataframe}, time_precision='m') self.assertListEqual(json.loads(m.last_request.body), points_ms) cli.write_points({"foo": dataframe}, time_precision='u') self.assertListEqual(json.loads(m.last_request.body), points_us) @raises(TypeError) def test_write_points_from_dataframe_fails_without_time_index(self): dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]], columns=["column_one", "column_two", "column_three"]) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/db/db/series") cli = DataFrameClient(database='db') cli.write_points({"foo": dataframe}) @raises(TypeError) def test_write_points_from_dataframe_fails_with_series(self): now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.Series(data=[1.0, 2.0], index=[now, now + timedelta(hours=1)]) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/db/db/series") cli = DataFrameClient(database='db') cli.write_points({"foo": dataframe}) def test_query_into_dataframe(self): data = [ { "name": "foo", "columns": ["time", "sequence_number", "column_one"], "points": [ [3600, 16, 2], [3600, 15, 1], [0, 14, 2], [0, 13, 1] ] } ] # dataframe sorted ascending by time first, then sequence_number dataframe = pd.DataFrame(data=[[13, 1], [14, 2], [15, 1], [16, 2]], index=pd.to_datetime([0, 0, 3600, 3600], unit='s', utc=True), columns=['sequence_number', 'column_one']) with _mocked_session('get', 200, data): cli = DataFrameClient('host', 8086, 'username', 'password', 'db') result = cli.query('select column_one from foo;') assert_frame_equal(dataframe, result) def test_query_multiple_time_series(self): data = [ { "name": "series1", "columns": ["time", "mean", "min", "max", "stddev"], "points": [[0, 323048, 323048, 323048, 0]] }, { "name": "series2", "columns": ["time", "mean", "min", "max", "stddev"], "points": [[0, -2.8233, -2.8503, -2.7832, 0.0173]] }, { "name": "series3", "columns": ["time", "mean", "min", "max", "stddev"], "points": [[0, -0.01220, -0.01220, -0.01220, 0]] } ] dataframes = { 'series1': pd.DataFrame(data=[[323048, 323048, 323048, 0]], index=pd.to_datetime([0], unit='s', utc=True), columns=['mean', 'min', 'max', 'stddev']), 'series2': pd.DataFrame(data=[[-2.8233, -2.8503, -2.7832, 0.0173]], index=pd.to_datetime([0], unit='s', utc=True), columns=['mean', 'min', 'max', 'stddev']), 'series3': pd.DataFrame(data=[[-0.01220, -0.01220, -0.01220, 0]], index=pd.to_datetime([0], unit='s', utc=True), columns=['mean', 'min', 'max', 'stddev']) } with _mocked_session('get', 200, data): cli = DataFrameClient('host', 8086, 'username', 'password', 'db') result = cli.query("""select mean(value), min(value), max(value), stddev(value) from series1, series2, series3""") self.assertEqual(dataframes.keys(), result.keys()) for key in dataframes.keys(): assert_frame_equal(dataframes[key], result[key]) def test_query_with_empty_result(self): with _mocked_session('get', 200, []): cli = DataFrameClient('host', 8086, 'username', 'password', 'db') result = cli.query('select column_one from foo;') self.assertEqual(result, []) def test_list_series(self): response = [ { 'columns': ['time', 'name'], 'name': 'list_series_result', 'points': [[0, 'seriesA'], [0, 'seriesB']] } ] with _mocked_session('get', 200, response): cli = DataFrameClient('host', 8086, 'username', 'password', 'db') series_list = cli.get_list_series() self.assertEqual(series_list, ['seriesA', 'seriesB']) def test_datetime_to_epoch(self): timestamp = pd.Timestamp('2013-01-01 00:00:00.000+00:00') cli = DataFrameClient('host', 8086, 'username', 'password', 'db') self.assertEqual( cli._datetime_to_epoch(timestamp), 1356998400.0 ) self.assertEqual( cli._datetime_to_epoch(timestamp, time_precision='s'), 1356998400.0 ) self.assertEqual( cli._datetime_to_epoch(timestamp, time_precision='m'), 1356998400000.0 ) self.assertEqual( cli._datetime_to_epoch(timestamp, time_precision='ms'), 1356998400000.0 ) self.assertEqual( cli._datetime_to_epoch(timestamp, time_precision='u'), 1356998400000000.0 )
mit
hbar/python-ChargedParticleTools
lib/ChargedParticleTools/IonizationCrossSection.py
1
2226
from numpy import * import matplotlib.pyplot as pl class IonizationCrossSection(object): def __init__ (self,element,Ei=1e4,shell='k',subshell=1): self.element = element self.shell = shell self.ionizationEnergy = Ei Z = element.z print self.shell if self.shell=='k' or self.shell=='K': An = 3.135e9 * Z**(-4.3434) Bn = exp(0.665 - 0.614 * log(Z) + 0.0810*(log(Z))**2 - 0.00005*(log(Z))**3 ) self.label=self.element.symbol + '(K)' if ((shell=='l' or shell=='L') and subshell == 1) or shell=='L1': An = 2.203e12 * Z**(-5.109) Bn = 12.909 * Z**(-1.006) self.label=self.element.symbol + r'(L$_1$)' if ((shell=='l' or shell=='L') and subshell == 2) or shell=='L2': An = 7.5231e12 * Z**(-5.3305) Bn = exp(4.4243 - 2.0777 * log(Z) + 0.2039*(log(Z))**2 ) - 0.5 self.label=self.element.symbol + r'(L$_2$)' if ((shell=='l' or shell=='L') and subshell == 3) or shell=='L3': An = 6.599e12 * Z**(-5.0797) Bn = 4.8642* Z**(-0.5645) - 0.5 self.label=self.element.symbol + r'(L$_3$)' # else: # An = nan # Bn = nan # print 'Electron Shell Input Error' self.constantAn = An self.constantBn = Bn def crossSection(self,Energy): U = Energy/self.ionizationEnergy An = self.constantAn Bn = self.constantBn print An, Bn sigma = An/(Bn + U) * log(U) for i in range(len(U)): if sigma[i] < 0.0: sigma[i] = 0.0 return sigma def plotU(self,U=linspace(1,5,100)): An = self.constantAn Bn = self.constantBn sigma = An/(Bn + U) * log(U) pl.semilogy(U,sigma) # pl.plot(U,sigma) pl.xlabel('U = E/Ei') pl.ylabel(r'cross section $\sigma(U)$ [barns]') def plotE(self,Energy=linspace(1,30e3,1000)): print Energy sigma=self.crossSection(Energy) print sigma pl.semilogy(Energy*1e-3,sigma,label=self.label) pl.xlabel('Energy [keV]') pl.ylabel(r'cross section $\sigma(U)$ [barns]')
mit
maheshakya/scikit-learn
doc/tutorial/text_analytics/skeletons/exercise_02_sentiment.py
256
2406
"""Build a sentiment analysis / polarity model Sentiment analysis can be casted as a binary text classification problem, that is fitting a linear classifier on features extracted from the text of the user messages so as to guess wether the opinion of the author is positive or negative. In this examples we will use a movie review dataset. """ # Author: Olivier Grisel <olivier.grisel@ensta.org> # License: Simplified BSD import sys from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.svm import LinearSVC from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.datasets import load_files from sklearn.cross_validation import train_test_split from sklearn import metrics if __name__ == "__main__": # NOTE: we put the following in a 'if __name__ == "__main__"' protected # block to be able to use a multi-core grid search that also works under # Windows, see: http://docs.python.org/library/multiprocessing.html#windows # The multiprocessing module is used as the backend of joblib.Parallel # that is used when n_jobs != 1 in GridSearchCV # the training data folder must be passed as first argument movie_reviews_data_folder = sys.argv[1] dataset = load_files(movie_reviews_data_folder, shuffle=False) print("n_samples: %d" % len(dataset.data)) # split the dataset in training and test set: docs_train, docs_test, y_train, y_test = train_test_split( dataset.data, dataset.target, test_size=0.25, random_state=None) # TASK: Build a vectorizer / classifier pipeline that filters out tokens # that are too rare or too frequent # TASK: Build a grid search to find out whether unigrams or bigrams are # more useful. # Fit the pipeline on the training set using grid search for the parameters # TASK: print the cross-validated scores for the each parameters set # explored by the grid search # TASK: Predict the outcome on the testing set and store it in a variable # named y_predicted # Print the classification report print(metrics.classification_report(y_test, y_predicted, target_names=dataset.target_names)) # Print and plot the confusion matrix cm = metrics.confusion_matrix(y_test, y_predicted) print(cm) # import matplotlib.pyplot as plt # plt.matshow(cm) # plt.show()
bsd-3-clause
andreiapostoae/dota2-predictor
training/query.py
2
7404
""" Module responsible for querying the result of a game """ import operator import os import logging import numpy as np from os import listdir from sklearn.externals import joblib from preprocessing.augmenter import augment_with_advantages from tools.metadata import get_hero_dict, get_last_patch logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def _query_missing(model, scaler, radiant_heroes, dire_heroes, synergies, counters, similarities, heroes_released): """ Query the best missing hero that can be picked given 4 heroes in one team and 5 heroes in the other. Args: model: estimator that has fitted the data scaler: the scaler used for fitting the data radiant_heroes: list of hero IDs from radiant team dire_heroes: list of hero IDs from dire team synergies: matrix defining the synergy scores between heroes counters: matrix defining the counter scores between heroes similarities: matrix defining similarities between heroes heroes_released: number of heroes released in the queried patch Returns: list of variable length containing hero suggestions """ all_heroes = radiant_heroes + dire_heroes base_similarity_radiant = 0 base_similarity_dire = 0 radiant = len(radiant_heroes) == 4 for i in range(4): for j in range(4): if i > j: base_similarity_radiant += similarities[radiant_heroes[i], radiant_heroes[j]] base_similarity_dire += similarities[dire_heroes[i], dire_heroes[j]] query_base = np.zeros((heroes_released, 2 * heroes_released + 3)) for i in range(heroes_released): if radiant: radiant_heroes.append(i + 1) else: dire_heroes.append(i + 1) for j in range(5): query_base[i][radiant_heroes[j] - 1] = 1 query_base[i][dire_heroes[j] - 1 + heroes_released] = 1 query_base[i][-3:] = augment_with_advantages(synergies, counters, radiant_heroes, dire_heroes) if radiant: del radiant_heroes[-1] else: del dire_heroes[-1] if radiant: probabilities = model.predict_proba(scaler.transform(query_base))[:, 1] else: probabilities = model.predict_proba(scaler.transform(query_base))[:, 0] heroes_dict = get_hero_dict() similarities_list = [] results_dict = {} for i, prob in enumerate(probabilities): if i + 1 not in all_heroes and i != 23: if radiant: similarity_new = base_similarity_radiant for j in range(4): similarity_new += similarities[i + 1][radiant_heroes[j]] similarities_list.append(similarity_new) else: similarity_new = base_similarity_dire for j in range(4): similarity_new += similarities[i + 1][dire_heroes[j]] similarities_list.append(similarity_new) results_dict[heroes_dict[i + 1]] = (prob, similarity_new) results_list = sorted(results_dict.items(), key=operator.itemgetter(1), reverse=True) similarities_list.sort() max_similarity_allowed = similarities_list[len(similarities_list) / 4] filtered_list = [x for x in results_list if x[1][1] < max_similarity_allowed] return filtered_list def _query_full(model, scaler, radiant_heroes, dire_heroes, synergies, counters, heroes_released): """ Query the result of a game when both teams have their line-ups finished. Args: model: estimator that has fitted the data scaler: the scaler used for fitting the data radiant_heroes: list of hero IDs from radiant team dire_heroes: list of hero IDs from dire team synergies: matrix defining the synergy scores between heroes counters: matrix defining the counter scores between heroes heroes_released: number of heroes released in the queried patch Returns: string with info about the predicted winner team """ features = np.zeros(2 * heroes_released + 3) for i in range(5): features[radiant_heroes[i] - 1] = 1 features[dire_heroes[i] - 1 + heroes_released] = 1 extra_data = augment_with_advantages(synergies, counters, radiant_heroes, dire_heroes) features[-3:] = extra_data features_reshaped = features.reshape(1, -1) features_final = scaler.transform(features_reshaped) probability = model.predict_proba(features_final)[:, 1] * 100 if probability > 50: return "Radiant has %.3f%% chance" % probability else: return "Dire has %.3f%% chance" % (100 - probability) def query(mmr, radiant_heroes, dire_heroes, synergies=None, counters=None, similarities=None): if similarities is None: sims = np.loadtxt('pretrained/similarities_all.csv') else: sims = np.loadtxt(similarities) if counters is None: cnts = np.loadtxt('pretrained/counters_all.csv') else: cnts = np.loadtxt(counters) if synergies is None: syns = np.loadtxt('pretrained/synergies_all.csv') else: syns = np.loadtxt(synergies) if mmr < 0 or mmr > 10000: logger.error("MMR should be a number between 0 and 10000") return if mmr < 2000: model_dict = joblib.load(os.path.join("pretrained", "2000-.pkl")) logger.info("Using 0-2000 MMR model") elif mmr > 5000: model_dict = joblib.load(os.path.join("pretrained", "5000+.pkl")) logger.info("Using 5000-10000 MMR model") else: file_list = [int(valid_file[:4]) for valid_file in listdir('pretrained') if '.pkl' in valid_file] file_list.sort() min_distance = 10000 final_mmr = -1000 for model_mmr in file_list: if abs(mmr - model_mmr) < min_distance: min_distance = abs(mmr - model_mmr) final_mmr = model_mmr logger.info("Using closest model available: %d MMR model", final_mmr) model_dict = joblib.load(os.path.join("pretrained", str(final_mmr) + ".pkl")) scaler = model_dict['scaler'] model = model_dict['model'] last_patch_info = get_last_patch() heroes_released = last_patch_info['heroes_released'] if len(radiant_heroes) + len(dire_heroes) == 10: return _query_full(model, scaler, radiant_heroes, dire_heroes, syns, cnts, heroes_released) return _query_missing(model, scaler, radiant_heroes, dire_heroes, syns, cnts, sims, heroes_released)
mit
hchen13/bigdatarecruit
DataMining/dataMiningFunc.py
1
22603
from tool import database, helper import pandas as pd import numpy as np import json # ******************************** hr排行 ************************************* # 获取公司hr数量排行 # @return DataFrame def lagouCompanyHrRankDf(): # 获取数据库连接和sql conn = database.getDatabaseConn() sql_lagou_hr = database.getLagouHrInfo() sql_lagou_recruit_day = database.getLagourHrComId() sql_lagou_company = database.getLagouCompanyInfo() # 读取数据 lagou_hr_df = pd.read_sql(sql_lagou_hr, conn) lagou_recruit_day = pd.read_sql(sql_lagou_recruit_day, conn) lagou_company = pd.read_sql(sql_lagou_company, conn) # 连接三张表,首先获取公司hr数量 res_lrd_df = pd.merge(lagou_recruit_day, lagou_hr_df, on='publisher_id', how='left') res_com_df = pd.merge(lagou_company, res_lrd_df, on='company_id', how='left') res_com_df = res_com_df.set_index('company_id') res_g = res_com_df.groupby(['company_id']) res_hr_num_df = res_g.size().to_frame().rename(columns={0: 'hr_num'}) # 然后将数量信息和公司表连接 company_hr_num_df = pd.concat([lagou_company.set_index('company_id'), res_hr_num_df], axis=1) res = company_hr_num_df.sort_values('hr_num', ascending=False) return res # 统计拉钩公司hr数量排行 def lagouCompanyHrNum(): df = lagouCompanyHrRankDf() res = pd.DataFrame(df.set_index('short_name'), columns=['hr_num']).sort_values('hr_num', ascending=False) return res # 统计拉钩hr数量在前100的公司规模占比 def lagouCompanySizeByHrNum(): df = lagouCompanyHrRankDf()[:100] res = df.groupby('size').size().sort_values(ascending=False).to_json(orient='index', force_ascii=False) return res # 统计拉钩hr数量在前100的公司类型占比 def lagouCompanySizeByHrNum(): df = lagouCompanyHrRankDf()[:100] res = df.groupby('finance_stage').size().sort_values(ascending=False).to_json(orient='index', force_ascii=False) return res # 统计拉钩招聘数量在前100的公司 def lagouCompanyPositionNum(): df = lagouCompanyHrRankDf() res = df.sort_values('total_num', ascending=False)[:100].to_json(orient='index', force_ascii=False) return res # 统计hr各时段处理简历的数量 def hrRecruitTime(): res = database.getLagouHrActiveTime() d = pd.DataFrame(res, columns = ['id', 'time']) data = d[d.time != '暂无'] res = data.groupby('time').size().sort_values() return res.to_json(orient='index', force_ascii=False) # 统计51job各行业职位数辆 前60 def get51IndustryNum(): # 获取行业数据 sql = database.get51IndustrySql() # 获取数据库连接 conn = database.getDatabaseConn() data = pd.read_sql(sql, conn) data = data[(True ^ data.industry.isin(['1000-5000人', '5000-10000人', '500-1000人', '少于50人', '150-500人', '50-150人']))] data_sort = data.groupby('industry').size().sort_values(ascending=False)[:60] return data_sort.to_json(orient='index', force_ascii=False) ####################################### 编程语言排行 ################################################################ # 通过关键字查找数量 # @params df 要查找的DataFrame数据集 # @params query_key 要查找的字段 # @params query_list 要查找的字符串 # @return DataFrame def getNumByKeyWords(df, query_key, query_list): query_rank = {} for item in query_list: name = item.replace("\\", '') name = 'objective-c' if name == 'ios' else name num = 0 for value in query_key: num += df[df[value].str.contains(item)].size query_rank[name] = num query_series = pd.Series(query_rank) res = pd.DataFrame([query_series], index=['数量']).T.sort_values(['数量']) return res # 编程语言排行 # @param sql 查询sql # @param query_key 查询字段 # @return def programingPositionRank(sql, query_key): # 获取数据库连接 conn = database.getDatabaseConn() # 获取常用语言 programing_language_list = helper.getProgramingLanguage() # 获取数据 lg_rd_df = pd.read_sql(sql, conn) conn.close() # 查询数据 lg_df_programing_rank = getNumByKeyWords(lg_rd_df, query_key, programing_language_list) return lg_df_programing_rank # 统计拉钩招聘职位中编程语言排行 def lagouRecruitCodeRank(): # 获取拉钩的sql sql = database.getLagouPositionSql() query_key = ['position_name', 'position_labels'] res = programingPositionRank(sql, query_key) return res.to_json(orient='index', force_ascii=False) # 获取智联招聘编程语言排行 def zhilianPositionCodeRank(): # 获取智联的sql sql = database.getZhilianPositionSql() query_key = ['position_name', 'position_type'] res = programingPositionRank(sql, query_key) return res.to_json(orient='index', force_ascii=False) # 获取51job编程语言职位排行 def job51PositionCodeRank(): # 获取51job的sql sql = database.get51jobPositionSql() query_key = ['name', 'position_labels'] res = programingPositionRank(sql, query_key) return res.to_json(orient='index', force_ascii=False) # *********************************** 获取职位排行 ********************************* # @param df DataFrame def getPositionRank(df, column_name): res_list = ','.join(df[column_name]).split(',') res_def = pd.DataFrame(res_list, index=np.arange(len(res_list))) res_def = res_def.rename(columns={0: 'position_labels'}) res_group = res_def.groupby('position_labels') # 销售岗 sale_total_num = res_group.size()[False ^ res_group.size().index.str.contains('销售|客户代表')].sum() # 教师 teacher_total_num = res_group.size()[False ^ res_group.size().index.str.contains('教师|老师')].sum() # 人事 renshi_total_num = res_group.size()[False ^ res_group.size().index.str.contains('人事')].sum() # 前端 frontend_total_num = res_group.size()[False ^ res_group.size().index.str.contains('前端')].sum() res_choose = res_group.size()[True ^ res_group.size().index.str.contains( '教师|老师|销售|客户代表|五险一金|节日福利|双休|立即上岗|应届生|员工旅游|交通补助|培训|出差补贴|话补|加班补助|全勤奖|人事|带薪年假|前端开发')] res_choose['销售'] = sale_total_num res_choose['教师'] = teacher_total_num res_choose['人事'] = renshi_total_num res_choose['前端开发'] = frontend_total_num return res_choose # 获取51job全国招聘职位数排行 前60 def job51PositionRank(): # 获取51job的sql sql = database.get51jobPositionLabels() sql_Other = database.get51jobOtherName() # 获取数据库连接 conn = database.getDatabaseConn() position_res_df = pd.concat([pd.read_sql(sql, conn), pd.read_sql(sql_Other, conn)]) res_choose = getPositionRank(position_res_df, 'position_labels') return res_choose.sort_values(ascending=False)[0:60].to_json(orient='index', force_ascii=False) # 获取智联全国招聘职位数排行 前60 def zhilianPositionRank(): # 获取51job的sql sql = database.getZhilianPositionType() sql_Other = database.getZhilianPositionName() # 获取数据库连接 conn = database.getDatabaseConn() position_res_df = pd.concat([pd.read_sql(sql, conn), pd.read_sql(sql_Other, conn)]) res_choose = getPositionRank(position_res_df, 'position_type') return res_choose.sort_values(ascending=False)[0:60].to_json(orient='index', force_ascii=False) # 获取拉钩全国招聘职位数排行 前60 (it行业招聘职位排行) def lagouPositionRank(): # 获取拉钩的sql sql = database.getLagouSecondtype() # 获取数据库连接 conn = database.getDatabaseConn() position_res_df = pd.read_sql(sql, conn) res_choose = getPositionRank(position_res_df, 'second_type') return res_choose.sort_values(ascending=False)[0:60].to_json(orient='index', force_ascii=False) # ********************************* 公司招聘职位数排行 ******************************** # 智联公司招聘职位数 def zhilianCompanyPositionNum(): # 获取51job的sql sql_position = database.getZhilianPositionSql() sql_company = database.getZhilianCompanySql() # 获取数据库连接 conn = database.getDatabaseConn() zp_df = pd.read_sql(sql_position, conn) zc_df = pd.read_sql(sql_company, conn) res_zp = pd.merge(zp_df, zc_df, on='company_md5', how='left') res_zp_g = res_zp.groupby('full_name').size().sort_values(ascending=False) return res_zp_g[0:60].to_json(orient='index', force_ascii=False) # 智联招聘职位前100里,公司规模占比 # @param type 1 规模 2 企业性质 3 行业 def zhilianCompanyHighNumType(type=1): # 获取51job的sql sql_position = database.getZhilianPositionSql() sql_company = database.getZhilianCompanySql() # 获取数据库连接 conn = database.getDatabaseConn() zp_df = pd.read_sql(sql_position, conn) zc_df = pd.read_sql(sql_company, conn) res_zp = pd.merge(zp_df, zc_df, on='company_md5', how='left') res_zp_g = res_zp.groupby('full_name').size() res_zp_g = pd.DataFrame(list(zip(res_zp_g.index, res_zp_g.values))).rename( columns={0: 'full_name', 1: "total_recruit_num"}) res_total = pd.merge(zc_df, res_zp_g, on='full_name', how='left').sort_values('total_recruit_num', ascending=False)[:100] if type == 1: query_column = 'size' elif type == 2: query_column = 'company_nature' elif type == 3: query_column = 'industry' res = res_total.groupby(query_column).size().sort_values(ascending=False) return res.to_json(orient='index', force_ascii=False) # 51公司招聘职位数 def job51CompanyPositionNum(): # 获取51job的sql sql_position = database.get51JobPositionSql() sql_company = database.get51JobCompanySql() # 获取数据库连接 conn = database.getDatabaseConn() j5_df = pd.read_sql(sql_position, conn) j5c_df = pd.read_sql(sql_company, conn) res_j5 = pd.merge(j5_df, j5c_df, on='company_md5', how='left') res_j5_g = res_j5.groupby('full_name').size().sort_values(ascending=False) return res_j5_g[0:60].to_json(orient='index', force_ascii=False) # 51job招聘职位前100里,公司规模占比 # @param type 1 规模 2 企业性质 3 行业 def job51CompanyHighNumType(type=1): # 获取51job的sql sql_position = database.get51JobPositionSql() sql_company = database.get51JobCompanySql() # 获取数据库连接 conn = database.getDatabaseConn() j5_df = pd.read_sql(sql_position, conn) j5c_df = pd.read_sql(sql_company, conn) res_j5 = pd.merge(j5_df, j5c_df, on='company_md5', how='left') res_j5_g = res_j5.groupby('full_name').size() res_j5_g = pd.DataFrame(list(zip(res_j5_g.index, res_j5_g.values))).rename( columns={0: 'full_name', 1: "total_recruit_num"}) res_total = pd.merge(j5c_df, res_j5_g, on='full_name', how='left').sort_values('total_recruit_num', ascending=False)[:100] if type == 1: query_column = 'size' elif type == 2: query_column = 'company_nature' elif type == 3: query_column = 'industry' res = res_total.groupby(query_column).size().sort_values(ascending=False) return res.to_json(orient='index', force_ascii=False) # 获取工作年限数统计 # @param sql 统计字段work_year # @return Series def workYearNum(sql): # 获取数据库连接 conn = database.getDatabaseConn() df = pd.read_sql(sql, conn) df_g = df.groupby('work_year') return df_g.size().sort_values(ascending=False)[:7] # 智联工作年限招聘数 def zhilianWorkYearNum(): sql = database.getZhilianZCSql() res_series = workYearNum(sql) return res_series.to_json(orient='index', force_ascii=False) # 51工作年限招聘数 def j5WorkYearNum(): sql = database.getJ5ZCSql() res_series = workYearNum(sql) return res_series.to_json(orient='index', force_ascii=False) # 拉钩工作年限招聘数 def lagouWorkYearNum(): sql = database.getLagouPositionInfo() res_series = workYearNum(sql) return res_series.to_json(orient='index', force_ascii=False) def salarySplit(line): import re res = re.match(r'([\d]+)K-([\d]+)K', line) if not res: res = re.match(r'([\d]+)k-([\d]+)k', line) if res: salary_low = res[1] salary_high = res[2] salary_mean = (int(salary_low) + int(salary_high)) / 2 else: res = re.match(r'([\d]+).*', line) salary_low = res[1] salary_high = res[1] salary_mean = res[1] return pd.Series([salary_low, salary_high, salary_mean]) # 拉钩薪资整体情况 # @return DataFrame 包含最高、最低、平均工资的招聘职位信息 def lagouSalaryDetail(): sql = database.getLagouPositionInfo() # 获取数据库连接 conn = database.getDatabaseConn() df = pd.read_sql(sql, conn) tmp = df['salary'].apply(salarySplit).rename(columns={0:'salary_low', 1:'salary_high', 2:'salary_mean'}) df = df.combine_first(tmp) return df # 拉钩整体平均薪资情况(中位数) def lagouWholeSalaryDistribution(): df = lagouSalaryDetail() df_filter = pd.DataFrame(df, columns=['salary_high', 'salary_low', 'salary_mean']) return df_filter.salary_mean.describe()['50%'] # 拉钩个工作年限薪资情况 # @param type 1, 50% 中位数 2,std 标准差 # @return json def lagouWorkYearSalary(type = 1): df = lagouSalaryDetail() df_work_res = df[df.work_year != '1-3'].groupby('work_year').salary_mean.describe().sort_values(['50%'],ascending=False) if type == 1: res = df_work_res['50%'].apply(lambda x: round(x, 2)) elif type == 2: res = df_work_res['std'].apply(lambda x: round(x, 2)) return res.to_json(orient='index', force_ascii=False) # 51job网站薪资处理函数 def job51SalaryDeal(line): import re patten1 = r'([\d]+.?[\d]?)-([\d]+.?[\d]?)千/月' patten2 = r'([\d]+.?[\d]?)-([\d]+.?[\d]?)万/月' patten3 = r'([\d]+.?[\d]?)-([\d]+.?[\d]?)万/年' low = high = mean = 0 if re.compile(patten1).match(line): low = float(re.compile(patten1).match(line).group(1)) high = float(re.compile(patten1).match(line).group(2)) mean = int((low + high)) / 2 elif re.compile(patten2).match(line): low = float(re.compile(patten2).match(line).group(1)) * 10 high = float(re.compile(patten2).match(line).group(2)) * 10 mean = int((low + high)) / 2 elif re.compile(patten3).match(line): low = float(re.compile(patten3).match(line).group(1)) * 10 / 12 high = float(re.compile(patten3).match(line).group(2)) * 10 / 12 mean = int(low + high) / 2 return pd.Series([round(low, 2), round(high, 2), round(mean, 2)]) # 51job薪资情况 # 获取51job工作年限,教育水平,薪资 (此方法运行时间将近15分钟) # @param type 1、默认使用以生成好的h5文件 2、重新生成 def job51SalaryPosition(type=1): import os # 获取数据库连接 if type == 1 & os.path.exists('./salaryWE.h5'): df_res = pd.read_hdf('./salaryWE.h5') else: conn = database.getDatabaseConn() sql = database.getJ5ZCSql() df_51job_salary = pd.read_sql(sql, conn) df_51job_salary = df_51job_salary[df_51job_salary.salary != 'NULL'] df_51job_salary_deal = df_51job_salary[True ^ df_51job_salary['salary'].str.contains('天|小时|\+')] df_tmp = df_51job_salary_deal.salary.apply(job51SalaryDeal) df_res = df_51job_salary_deal.combine_first(df_tmp.rename(columns={0: 'low', 1: 'high', 2: 'mean'})) df_res.to_hdf('./salaryWE.h5', 'salary_all') return df_res # 返回标准函数 def resDeal(df_res): res_dict = {} df = df_res[df_res.index != 'NULL'] res_mean_dict = df['mean'].to_dict() res_std_dict = df['std'].to_dict() res_count_dict = df['count'].to_dict() res_dict['key_name'] = list(res_mean_dict.keys()) res_dict['count'] = list(res_count_dict.values()) res_dict['salary'] = list(map(lambda x: int(x * 1000), res_mean_dict.values())) res_dict['std'] = list(map(lambda x: round(x + 20, 2), res_std_dict.values())) return json.dumps(res_dict) # 获取51job整体薪资中位数 # @param type 1、从h5结果获取数据 2、重新生成数据 def get51jobSalaryMiddle(type=1): df = job51SalaryPosition(type) return df.describe().apply(lambda x: round(x * 1000, 2))['mean']['mean'] # 获取51job教育程度招聘数情况 def get51jobRecruitNumByEducation(): # 获取数据库连接 conn = database.getDatabaseConn() sql = database.getJ5ZCSql() df_51job_salary = pd.read_sql(sql, conn) return df_51job_salary.groupby('education').size().sort_values(ascending=False).to_json(orient='index', force_ascii=False) # 获取51job教育程度与薪资关系 def get51jobSalaryByEducation(): df = job51SalaryPosition() df_res = df.groupby('education')['mean'].describe().sort_values(['mean'], ascending=False) return resDeal(df_res) # 51job工作年限与薪资关系 def get51jobSalaryByWorkYear(): df = job51SalaryPosition() df_res = df.groupby('work_year')['mean'].describe().sort_values(['mean']) return resDeal(df_res) # 51job根据教育水平和工作年限分析薪资情况 def get51jobSalaryByWE(): df = job51SalaryPosition() df_rename = df.rename(columns={'work_year' : '工作年限', 'mean' : '平均薪资', 'education' : '教育程度'}) df_res = df_rename.pivot_table(index=['工作年限'], columns='教育程度', values=['平均薪资']).rename(columns={'NULL' : '其他'}).apply(lambda x: round(x * 1000,0)) return df_res.T.to_json(orient='split', force_ascii=False) # 51job行业薪资情况 # @return 行业名称 平均薪资 标准差 def get51jobSalaryByIndustry(): df = job51SalaryPosition() df = df[(True ^ df.industry.isin(['1000-5000人', '5000-10000人', '500-1000人', '少于50人', '150-500人', '50-150人']))] df_res = df.groupby('industry')['mean'].describe() df_j5_industry_salary = df_res[df_res['count'] > 10].sort_values('mean', ascending=False).apply( lambda x: round(x, 2)) res_mean = df_j5_industry_salary['mean'].to_dict() res_std = df_j5_industry_salary['std'].to_dict() return list(res_mean.keys()), list(map(lambda x: int(x * 1000), res_mean.values())), list(res_std.values()) # 51job行业薪资标准差情况 def get51jobSalaryStdByIndustry(): df = job51SalaryPosition() df = df[(True ^ df.industry.isin(['1000-5000人', '5000-10000人', '500-1000人', '少于50人', '150-500人', '50-150人']))] df_res = df.groupby('industry')['mean'].describe() df_j5_industry_salary = df_res[df_res['count'] > 10].sort_values('mean', ascending=False).apply( lambda x: round(x, 2)) return pd.DataFrame(df_j5_industry_salary, columns=['mean', 'std']).to_json(orient='split', force_ascii=False) # 智联 具体职位薪资排行 # @param type 1 只分析职位 2 加入工作年限和地区 # @param sort_type 1, 高到低 2, 低到高 def getZLSalaryByPosition(type = 1, sort_type = 1): sql = database.getZLSalaryByPositionSql() conn = database.getDatabaseConn() df = pd.read_sql(sql, conn) if type == 1: condition = ['position_type'] elif type == 2: condition = ['position_type', 'work_year', 'city'] sort_status = True if sort_type == 1 else False df_res = df.groupby(condition).describe().salary_high.sort_values('mean', ascending=sort_status)[:100] res = pd.concat([df_res['std'].apply(lambda x: int(x)), df_res['mean'].apply(lambda x: int(x)), df_res['50%'].apply(lambda x: int(x))], axis=1).rename(columns={'std':'标准差','mean':'平均值','50%':'中位数'}) res.to_excel('output/PositionSalaryByWE.xlsx') return res.to_json(orient='index', force_ascii=False) # 城市薪资排行 # @param type 1、全部 2、工作年限1-3的 def getCitySalary(type = 1): df_51 = job51SalaryPosition() df_lagou = lagouSalaryDetail() city_mix_df = pd.concat([pd.DataFrame(df_51, columns=['city', 'salary_mean', 'work_year']), pd.DataFrame(df_lagou, columns=['city', 'salary_mean', 'work_year'])]) if type == 1: g_df = city_mix_df.groupby('city') g_df_res = g_df.describe().apply(lambda x: round(x, 2)) g_df_res[('salary_mean', 'mean')] = g_df_res[('salary_mean', 'mean')].apply(lambda x: x * 1000) g_df_res[('salary_mean', '50%')] = g_df_res[('salary_mean', '50%')].apply(lambda x: x * 1000) g_df_res = g_df_res[ (g_df_res[('salary_mean', 'std')] < 20) & (g_df_res[('salary_mean', 'count')] > 18)].sort_values( ('salary_mean', 'mean'), ascending=False) else: g_df = city_mix_df[city_mix_df['work_year'] == '1-3年'].groupby('city') g_df_res = g_df.describe().apply(lambda x: round(x, 2)) g_df_res[('salary_mean', 'mean')] = g_df_res[('salary_mean', 'mean')].apply(lambda x: x * 1000) g_df_res[('salary_mean', '50%')] = g_df_res[('salary_mean', '50%')].apply(lambda x: x * 1000) g_df_res = g_df_res[ (g_df_res[('salary_mean', 'std')] < 20) & (g_df_res[('salary_mean', 'count')] > 5)].sort_values( ('salary_mean', 'mean'), ascending=False) res_df = pd.DataFrame(g_df_res, columns=[('salary_mean', 'std'), ('salary_mean', 'mean'), ('salary_mean', '50%')]).rename( columns={'salary_mean': '薪资/k', 'mean': '平均数', 'std': '标准差', '50%': '中位数', }) return res_df # 城市薪资排行转excel def citySalaryToExcel(type = 1, path = "output/citySalary.xlsx"): df = getCitySalary(type) df.to_excel(path) # echarts地图之城市薪资展示数据处理 TODO df格式不对 def citySalaryToEcharts(type = 1): df = getCitySalary(type) df_copy = pd.concat([df.index, df[('salary_mean', '50%')]], axis=1) import json res = str(json.loads( pd.DataFrame(df_copy, columns=['city', '中位数']).rename(columns={'city': 'name', '中位数': 'value'}).to_json( orient='index', force_ascii=False)).values()).replace("\'name\'", "name").replace("\'value\'", "value") return res
gpl-3.0
xumi1993/seispy
seispy/plotR.py
1
3583
import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from matplotlib.lines import Line2D from seispy.rfcorrect import SACStation from seispy.rf import CfgParser import argparse import numpy as np from os.path import join import sys def init_figure(): h = plt.figure(figsize=(8, 10)) gs = GridSpec(1, 3) gs.update(wspace=0.25) axr = plt.subplot(gs[0, 0:-1]) axr.grid(color='gray', linestyle='--', linewidth=0.4, axis='x') axb = plt.subplot(gs[0, -1]) axb.grid(color='gray', linestyle='--', linewidth=0.4, axis='x') return h, axr, axb def read_process_data(lst): stadata = SACStation(lst, only_r=True) idx = np.argsort(stadata.bazi) stadata.event = stadata.event[idx] stadata.bazi = stadata.bazi[idx] stadata.datar = stadata.datar[idx] time_axis = np.arange(stadata.RFlength) * stadata.sampling - stadata.shift return stadata, time_axis def plot_waves(axr, axb, stadata, time_axis, enf=12): bound = np.zeros(stadata.RFlength) for i in range(stadata.ev_num): datar = stadata.datar[i] * enf + (i + 1) # axr.plot(time_axis, stadata.datar[i], linewidth=0.2, color='black') axr.fill_between(time_axis, datar, bound + i+1, where=datar > i+1, facecolor='red', alpha=0.7) axr.fill_between(time_axis, datar, bound + i+1, where=datar < i+1, facecolor='blue', alpha=0.7) axb.scatter(stadata.bazi, np.arange(stadata.ev_num) + 1, s=7) def set_fig(axr, axb, stadata, station, xmin=-2, xmax=80): y_range = np.arange(stadata.ev_num) + 1 x_range = np.arange(0, xmax+2, 5) space = 2 # set axr axr.set_xlim(xmin, xmax) axr.set_xticks(x_range) axr.set_xticklabels(x_range, fontsize=8) axr.set_ylim(0, stadata.ev_num + space) axr.set_yticks(y_range) axr.set_yticklabels(stadata.event, fontsize=5) axr.set_xlabel('Time after P (s)', fontsize=13) axr.set_ylabel('Event', fontsize=13) axr.add_line(Line2D([0, 0], axr.get_ylim(), color='black')) axr.set_title('R components ({})'.format(station), fontsize=16) # set axb axb.set_xlim(0, 360) axb.set_xticks(np.linspace(0, 360, 7)) axb.set_xticklabels(np.linspace(0, 360, 7, dtype='i'), fontsize=8) axb.set_ylim(0, stadata.ev_num + space) axb.set_yticks(y_range) axb.set_yticklabels(y_range, fontsize=5) axb.set_xlabel(r'Back-azimuth ($^\circ$)', fontsize=13) def plotr(station, cfg_file, enf=6): pa = CfgParser(cfg_file) # pa.rfpath = join(pa.rfpath, station) lst = join(pa.rfpath, station + 'finallist.dat') h, axr, axb = init_figure() stadata, time_axis = read_process_data(lst) plot_waves(axr, axb, stadata, time_axis, enf=enf) set_fig(axr, axb, stadata, station) h.savefig(join(pa.imagepath, station + '_RT_bazorder_{:.1f}.pdf'.format(stadata.f0[0])), format='pdf') plt.show() def main(): parser = argparse.ArgumentParser(description="Plot R&T receiver functions") parser.add_argument('-s', help='Station as folder name of RFs and list', dest='station', type=str) parser.add_argument('-e', help='Enlargement factor', dest='enf', type=int, default=6) parser.add_argument('cfg_file', type=str, help='Path to configure file') arg = parser.parse_args() if len(sys.argv) == 1: parser.print_help() sys.exit(1) plotr(arg.station, arg.cfg_file, enf=arg.enf) if __name__ == '__main__': station = 'XE.ES01' cfg_file = '/Users/xumj/Researches/Tibet_MTZ/process/paraRF.cfg' plotr(station, cfg_file)
gpl-3.0
andyh616/mne-python
mne/decoding/tests/test_ems.py
19
1969
# Author: Denis A. Engemann <d.engemann@gmail.com> # # License: BSD (3-clause) import os.path as op from nose.tools import assert_equal, assert_raises from mne import io, Epochs, read_events, pick_types from mne.utils import requires_sklearn from mne.decoding import compute_ems data_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data') curdir = op.join(op.dirname(__file__)) raw_fname = op.join(data_dir, 'test_raw.fif') event_name = op.join(data_dir, 'test-eve.fif') tmin, tmax = -0.2, 0.5 event_id = dict(aud_l=1, vis_l=3) @requires_sklearn def test_ems(): """Test event-matched spatial filters""" raw = io.Raw(raw_fname, preload=False) # create unequal number of events events = read_events(event_name) events[-2, 2] = 3 picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') picks = picks[1:13:3] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) assert_raises(ValueError, compute_ems, epochs, ['aud_l', 'vis_l']) epochs.equalize_event_counts(epochs.event_id, copy=False) assert_raises(KeyError, compute_ems, epochs, ['blah', 'hahah']) surrogates, filters, conditions = compute_ems(epochs) assert_equal(list(set(conditions)), [1, 3]) events = read_events(event_name) event_id2 = dict(aud_l=1, aud_r=2, vis_l=3) epochs = Epochs(raw, events, event_id2, tmin, tmax, picks=picks, baseline=(None, 0), preload=True) epochs.equalize_event_counts(epochs.event_id, copy=False) n_expected = sum([len(epochs[k]) for k in ['aud_l', 'vis_l']]) assert_raises(ValueError, compute_ems, epochs) surrogates, filters, conditions = compute_ems(epochs, ['aud_r', 'vis_l']) assert_equal(n_expected, len(surrogates)) assert_equal(n_expected, len(conditions)) assert_equal(list(set(conditions)), [2, 3]) raw.close()
bsd-3-clause
metaml/nupic
external/linux32/lib/python2.6/site-packages/matplotlib/dates.py
54
33991
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutils`. :class:`datetime` objects are converted to floating point numbers which represent the number of days since 0001-01-01 UTC. The helper functions :func:`date2num`, :func:`num2date` and :func:`drange` are used to facilitate easy conversion to and from :mod:`datetime` and numeric ranges. A wide range of specific and general purpose date tick locators and formatters are provided in this module. See :mod:`matplotlib.ticker` for general information on tick locators and formatters. These are described below. All the matplotlib date converters, tickers and formatters are timezone aware, and the default timezone is given by the timezone parameter in your :file:`matplotlibrc` file. If you leave out a :class:`tz` timezone instance, the default from your rc file will be assumed. If you want to use a custom time zone, pass a :class:`pytz.timezone` instance with the tz keyword argument to :func:`num2date`, :func:`plot_date`, and any custom date tickers or locators you create. See `pytz <http://pytz.sourceforge.net>`_ for information on :mod:`pytz` and timezone handling. The `dateutil module <http://labix.org/python-dateutil>`_ provides additional code to handle date ticking, making it easy to place ticks on any kinds of dates. See examples below. Date tickers ------------ Most of the date tickers can locate single or multiple values. For example:: # tick on mondays every week loc = WeekdayLocator(byweekday=MO, tz=tz) # tick on mondays and saturdays loc = WeekdayLocator(byweekday=(MO, SA)) In addition, most of the constructors take an interval argument:: # tick on mondays every second week loc = WeekdayLocator(byweekday=MO, interval=2) The rrule locator allows completely general date ticking:: # tick every 5th easter rule = rrulewrapper(YEARLY, byeaster=1, interval=5) loc = RRuleLocator(rule) Here are all the date tickers: * :class:`MinuteLocator`: locate minutes * :class:`HourLocator`: locate hours * :class:`DayLocator`: locate specifed days of the month * :class:`WeekdayLocator`: Locate days of the week, eg MO, TU * :class:`MonthLocator`: locate months, eg 7 for july * :class:`YearLocator`: locate years that are multiples of base * :class:`RRuleLocator`: locate using a :class:`matplotlib.dates.rrulewrapper`. The :class:`rrulewrapper` is a simple wrapper around a :class:`dateutils.rrule` (`dateutil <https://moin.conectiva.com.br/DateUtil>`_) which allow almost arbitrary date tick specifications. See `rrule example <../examples/pylab_examples/date_demo_rrule.html>`_. Date formatters --------------- Here all all the date formatters: * :class:`DateFormatter`: use :func:`strftime` format strings * :class:`IndexDateFormatter`: date plots with implicit *x* indexing. """ import re, time, math, datetime import pytz # compatability for 2008c and older versions try: import pytz.zoneinfo except ImportError: pytz.zoneinfo = pytz.tzinfo pytz.zoneinfo.UTC = pytz.UTC import matplotlib import numpy as np import matplotlib.units as units import matplotlib.cbook as cbook import matplotlib.ticker as ticker from pytz import timezone from dateutil.rrule import rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, \ MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY from dateutil.relativedelta import relativedelta import dateutil.parser __all__ = ( 'date2num', 'num2date', 'drange', 'epoch2num', 'num2epoch', 'mx2num', 'DateFormatter', 'IndexDateFormatter', 'DateLocator', 'RRuleLocator', 'YearLocator', 'MonthLocator', 'WeekdayLocator', 'DayLocator', 'HourLocator', 'MinuteLocator', 'SecondLocator', 'rrule', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU', 'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', 'SECONDLY', 'relativedelta', 'seconds', 'minutes', 'hours', 'weeks') UTC = pytz.timezone('UTC') def _get_rc_timezone(): s = matplotlib.rcParams['timezone'] return pytz.timezone(s) HOURS_PER_DAY = 24. MINUTES_PER_DAY = 60.*HOURS_PER_DAY SECONDS_PER_DAY = 60.*MINUTES_PER_DAY MUSECONDS_PER_DAY = 1e6*SECONDS_PER_DAY SEC_PER_MIN = 60 SEC_PER_HOUR = 3600 SEC_PER_DAY = SEC_PER_HOUR * 24 SEC_PER_WEEK = SEC_PER_DAY * 7 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = ( MO, TU, WE, TH, FR, SA, SU) WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) def _to_ordinalf(dt): """ Convert :mod:`datetime` to the Gregorian date as UTC float days, preserving hours, minutes, seconds and microseconds. Return value is a :func:`float`. """ if hasattr(dt, 'tzinfo') and dt.tzinfo is not None: delta = dt.tzinfo.utcoffset(dt) if delta is not None: dt -= delta base = float(dt.toordinal()) if hasattr(dt, 'hour'): base += (dt.hour/HOURS_PER_DAY + dt.minute/MINUTES_PER_DAY + dt.second/SECONDS_PER_DAY + dt.microsecond/MUSECONDS_PER_DAY ) return base def _from_ordinalf(x, tz=None): """ Convert Gregorian float of the date, preserving hours, minutes, seconds and microseconds. Return value is a :class:`datetime`. """ if tz is None: tz = _get_rc_timezone() ix = int(x) dt = datetime.datetime.fromordinal(ix) remainder = float(x) - ix hour, remainder = divmod(24*remainder, 1) minute, remainder = divmod(60*remainder, 1) second, remainder = divmod(60*remainder, 1) microsecond = int(1e6*remainder) if microsecond<10: microsecond=0 # compensate for rounding errors dt = datetime.datetime( dt.year, dt.month, dt.day, int(hour), int(minute), int(second), microsecond, tzinfo=UTC).astimezone(tz) if microsecond>999990: # compensate for rounding errors dt += datetime.timedelta(microseconds=1e6-microsecond) return dt class strpdate2num: """ Use this class to parse date strings to matplotlib datenums when you know the date format string of the date you are parsing. See :file:`examples/load_demo.py`. """ def __init__(self, fmt): """ fmt: any valid strptime format is supported """ self.fmt = fmt def __call__(self, s): """s : string to be converted return value: a date2num float """ return date2num(datetime.datetime(*time.strptime(s, self.fmt)[:6])) def datestr2num(d): """ Convert a date string to a datenum using :func:`dateutil.parser.parse`. *d* can be a single string or a sequence of strings. """ if cbook.is_string_like(d): dt = dateutil.parser.parse(d) return date2num(dt) else: return date2num([dateutil.parser.parse(s) for s in d]) def date2num(d): """ *d* is either a :class:`datetime` instance or a sequence of datetimes. Return value is a floating point number (or sequence of floats) which gives number of days (fraction part represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC. """ if not cbook.iterable(d): return _to_ordinalf(d) else: return np.asarray([_to_ordinalf(val) for val in d]) def julian2num(j): 'Convert a Julian date (or sequence) to a matplotlib date (or sequence).' if cbook.iterable(j): j = np.asarray(j) return j + 1721425.5 def num2julian(n): 'Convert a matplotlib date (or sequence) to a Julian date (or sequence).' if cbook.iterable(n): n = np.asarray(n) return n - 1721425.5 def num2date(x, tz=None): """ *x* is a float value which gives number of days (fraction part represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC. Return value is a :class:`datetime` instance in timezone *tz* (default to rcparams TZ value). If *x* is a sequence, a sequence of :class:`datetime` objects will be returned. """ if tz is None: tz = _get_rc_timezone() if not cbook.iterable(x): return _from_ordinalf(x, tz) else: return [_from_ordinalf(val, tz) for val in x] def drange(dstart, dend, delta): """ Return a date range as float Gregorian ordinals. *dstart* and *dend* are :class:`datetime` instances. *delta* is a :class:`datetime.timedelta` instance. """ step = (delta.days + delta.seconds/SECONDS_PER_DAY + delta.microseconds/MUSECONDS_PER_DAY) f1 = _to_ordinalf(dstart) f2 = _to_ordinalf(dend) return np.arange(f1, f2, step) ### date tickers and formatters ### class DateFormatter(ticker.Formatter): """ Tick location is seconds since the epoch. Use a :func:`strftime` format string. Python only supports :mod:`datetime` :func:`strftime` formatting for years greater than 1900. Thanks to Andrew Dalke, Dalke Scientific Software who contributed the :func:`strftime` code below to include dates earlier than this year. """ illegal_s = re.compile(r"((^|[^%])(%%)*%s)") def __init__(self, fmt, tz=None): """ *fmt* is an :func:`strftime` format string; *tz* is the :class:`tzinfo` instance. """ if tz is None: tz = _get_rc_timezone() self.fmt = fmt self.tz = tz def __call__(self, x, pos=0): dt = num2date(x, self.tz) return self.strftime(dt, self.fmt) def set_tzinfo(self, tz): self.tz = tz def _findall(self, text, substr): # Also finds overlaps sites = [] i = 0 while 1: j = text.find(substr, i) if j == -1: break sites.append(j) i=j+1 return sites # Dalke: I hope I did this math right. Every 28 years the # calendar repeats, except through century leap years excepting # the 400 year leap years. But only if you're using the Gregorian # calendar. def strftime(self, dt, fmt): fmt = self.illegal_s.sub(r"\1", fmt) fmt = fmt.replace("%s", "s") if dt.year > 1900: return cbook.unicode_safe(dt.strftime(fmt)) year = dt.year # For every non-leap year century, advance by # 6 years to get into the 28-year repeat cycle delta = 2000 - year off = 6*(delta // 100 + delta // 400) year = year + off # Move to around the year 2000 year = year + ((2000 - year)//28)*28 timetuple = dt.timetuple() s1 = time.strftime(fmt, (year,) + timetuple[1:]) sites1 = self._findall(s1, str(year)) s2 = time.strftime(fmt, (year+28,) + timetuple[1:]) sites2 = self._findall(s2, str(year+28)) sites = [] for site in sites1: if site in sites2: sites.append(site) s = s1 syear = "%4d" % (dt.year,) for site in sites: s = s[:site] + syear + s[site+4:] return cbook.unicode_safe(s) class IndexDateFormatter(ticker.Formatter): """ Use with :class:`~matplotlib.ticker.IndexLocator` to cycle format strings by index. """ def __init__(self, t, fmt, tz=None): """ *t* is a sequence of dates (floating point days). *fmt* is a :func:`strftime` format string. """ if tz is None: tz = _get_rc_timezone() self.t = t self.fmt = fmt self.tz = tz def __call__(self, x, pos=0): 'Return the label for time *x* at position *pos*' ind = int(round(x)) if ind>=len(self.t) or ind<=0: return '' dt = num2date(self.t[ind], self.tz) return cbook.unicode_safe(dt.strftime(self.fmt)) class AutoDateFormatter(ticker.Formatter): """ This class attempts to figure out the best format to use. This is most useful when used with the :class:`AutoDateLocator`. """ # This can be improved by providing some user-level direction on # how to choose the best format (precedence, etc...) # Perhaps a 'struct' that has a field for each time-type where a # zero would indicate "don't show" and a number would indicate # "show" with some sort of priority. Same priorities could mean # show all with the same priority. # Or more simply, perhaps just a format string for each # possibility... def __init__(self, locator, tz=None): self._locator = locator self._formatter = DateFormatter("%b %d %Y %H:%M:%S %Z", tz) self._tz = tz def __call__(self, x, pos=0): scale = float( self._locator._get_unit() ) if ( scale == 365.0 ): self._formatter = DateFormatter("%Y", self._tz) elif ( scale == 30.0 ): self._formatter = DateFormatter("%b %Y", self._tz) elif ( (scale == 1.0) or (scale == 7.0) ): self._formatter = DateFormatter("%b %d %Y", self._tz) elif ( scale == (1.0/24.0) ): self._formatter = DateFormatter("%H:%M:%S %Z", self._tz) elif ( scale == (1.0/(24*60)) ): self._formatter = DateFormatter("%H:%M:%S %Z", self._tz) elif ( scale == (1.0/(24*3600)) ): self._formatter = DateFormatter("%H:%M:%S %Z", self._tz) else: self._formatter = DateFormatter("%b %d %Y %H:%M:%S %Z", self._tz) return self._formatter(x, pos) class rrulewrapper: def __init__(self, freq, **kwargs): self._construct = kwargs.copy() self._construct["freq"] = freq self._rrule = rrule(**self._construct) def set(self, **kwargs): self._construct.update(kwargs) self._rrule = rrule(**self._construct) def __getattr__(self, name): if name in self.__dict__: return self.__dict__[name] return getattr(self._rrule, name) class DateLocator(ticker.Locator): hms0d = {'byhour':0, 'byminute':0,'bysecond':0} def __init__(self, tz=None): """ *tz* is a :class:`tzinfo` instance. """ if tz is None: tz = _get_rc_timezone() self.tz = tz def set_tzinfo(self, tz): self.tz = tz def datalim_to_dt(self): dmin, dmax = self.axis.get_data_interval() return num2date(dmin, self.tz), num2date(dmax, self.tz) def viewlim_to_dt(self): vmin, vmax = self.axis.get_view_interval() return num2date(vmin, self.tz), num2date(vmax, self.tz) def _get_unit(self): """ Return how many days a unit of the locator is; used for intelligent autoscaling. """ return 1 def nonsingular(self, vmin, vmax): unit = self._get_unit() vmin -= 2*unit vmax += 2*unit return vmin, vmax class RRuleLocator(DateLocator): # use the dateutil rrule instance def __init__(self, o, tz=None): DateLocator.__init__(self, tz) self.rule = o def __call__(self): # if no data have been set, this will tank with a ValueError try: dmin, dmax = self.viewlim_to_dt() except ValueError: return [] if dmin>dmax: dmax, dmin = dmin, dmax delta = relativedelta(dmax, dmin) self.rule.set(dtstart=dmin-delta, until=dmax+delta) dates = self.rule.between(dmin, dmax, True) return date2num(dates) def _get_unit(self): """ Return how many days a unit of the locator is; used for intelligent autoscaling. """ freq = self.rule._rrule._freq if ( freq == YEARLY ): return 365 elif ( freq == MONTHLY ): return 30 elif ( freq == WEEKLY ): return 7 elif ( freq == DAILY ): return 1 elif ( freq == HOURLY ): return (1.0/24.0) elif ( freq == MINUTELY ): return (1.0/(24*60)) elif ( freq == SECONDLY ): return (1.0/(24*3600)) else: # error return -1 #or should this just return '1'? def autoscale(self): """ Set the view limits to include the data range. """ dmin, dmax = self.datalim_to_dt() if dmin>dmax: dmax, dmin = dmin, dmax delta = relativedelta(dmax, dmin) self.rule.set(dtstart=dmin-delta, until=dmax+delta) dmin, dmax = self.datalim_to_dt() vmin = self.rule.before(dmin, True) if not vmin: vmin=dmin vmax = self.rule.after(dmax, True) if not vmax: vmax=dmax vmin = date2num(vmin) vmax = date2num(vmax) return self.nonsingular(vmin, vmax) class AutoDateLocator(DateLocator): """ On autoscale, this class picks the best :class:`MultipleDateLocator` to set the view limits and the tick locations. """ def __init__(self, tz=None): DateLocator.__init__(self, tz) self._locator = YearLocator() self._freq = YEARLY def __call__(self): 'Return the locations of the ticks' self.refresh() return self._locator() def set_axis(self, axis): DateLocator.set_axis(self, axis) self._locator.set_axis(axis) def refresh(self): 'Refresh internal information based on current limits.' dmin, dmax = self.viewlim_to_dt() self._locator = self.get_locator(dmin, dmax) def _get_unit(self): if ( self._freq == YEARLY ): return 365.0 elif ( self._freq == MONTHLY ): return 30.0 elif ( self._freq == WEEKLY ): return 7.0 elif ( self._freq == DAILY ): return 1.0 elif ( self._freq == HOURLY ): return 1.0/24 elif ( self._freq == MINUTELY ): return 1.0/(24*60) elif ( self._freq == SECONDLY ): return 1.0/(24*3600) else: # error return -1 def autoscale(self): 'Try to choose the view limits intelligently.' dmin, dmax = self.datalim_to_dt() self._locator = self.get_locator(dmin, dmax) return self._locator.autoscale() def get_locator(self, dmin, dmax): 'Pick the best locator based on a distance.' delta = relativedelta(dmax, dmin) numYears = (delta.years * 1.0) numMonths = (numYears * 12.0) + delta.months numDays = (numMonths * 31.0) + delta.days numHours = (numDays * 24.0) + delta.hours numMinutes = (numHours * 60.0) + delta.minutes numSeconds = (numMinutes * 60.0) + delta.seconds numticks = 5 # self._freq = YEARLY interval = 1 bymonth = 1 bymonthday = 1 byhour = 0 byminute = 0 bysecond = 0 if ( numYears >= numticks ): self._freq = YEARLY elif ( numMonths >= numticks ): self._freq = MONTHLY bymonth = range(1, 13) if ( (0 <= numMonths) and (numMonths <= 14) ): interval = 1 # show every month elif ( (15 <= numMonths) and (numMonths <= 29) ): interval = 3 # show every 3 months elif ( (30 <= numMonths) and (numMonths <= 44) ): interval = 4 # show every 4 months else: # 45 <= numMonths <= 59 interval = 6 # show every 6 months elif ( numDays >= numticks ): self._freq = DAILY bymonth = None bymonthday = range(1, 32) if ( (0 <= numDays) and (numDays <= 9) ): interval = 1 # show every day elif ( (10 <= numDays) and (numDays <= 19) ): interval = 2 # show every 2 days elif ( (20 <= numDays) and (numDays <= 49) ): interval = 3 # show every 3 days elif ( (50 <= numDays) and (numDays <= 99) ): interval = 7 # show every 1 week else: # 100 <= numDays <= ~150 interval = 14 # show every 2 weeks elif ( numHours >= numticks ): self._freq = HOURLY bymonth = None bymonthday = None byhour = range(0, 24) # show every hour if ( (0 <= numHours) and (numHours <= 14) ): interval = 1 # show every hour elif ( (15 <= numHours) and (numHours <= 30) ): interval = 2 # show every 2 hours elif ( (30 <= numHours) and (numHours <= 45) ): interval = 3 # show every 3 hours elif ( (45 <= numHours) and (numHours <= 68) ): interval = 4 # show every 4 hours elif ( (68 <= numHours) and (numHours <= 90) ): interval = 6 # show every 6 hours else: # 90 <= numHours <= 120 interval = 12 # show every 12 hours elif ( numMinutes >= numticks ): self._freq = MINUTELY bymonth = None bymonthday = None byhour = None byminute = range(0, 60) if ( numMinutes > (10.0 * numticks) ): interval = 10 # end if elif ( numSeconds >= numticks ): self._freq = SECONDLY bymonth = None bymonthday = None byhour = None byminute = None bysecond = range(0, 60) if ( numSeconds > (10.0 * numticks) ): interval = 10 # end if else: # do what? # microseconds as floats, but floats from what reference point? pass rrule = rrulewrapper( self._freq, interval=interval, \ dtstart=dmin, until=dmax, \ bymonth=bymonth, bymonthday=bymonthday, \ byhour=byhour, byminute = byminute, \ bysecond=bysecond ) locator = RRuleLocator(rrule, self.tz) locator.set_axis(self.axis) locator.set_view_interval(*self.axis.get_view_interval()) locator.set_data_interval(*self.axis.get_data_interval()) return locator class YearLocator(DateLocator): """ Make ticks on a given day of each year that is a multiple of base. Examples:: # Tick every year on Jan 1st locator = YearLocator() # Tick every 5 years on July 4th locator = YearLocator(5, month=7, day=4) """ def __init__(self, base=1, month=1, day=1, tz=None): """ Mark years that are multiple of base on a given month and day (default jan 1). """ DateLocator.__init__(self, tz) self.base = ticker.Base(base) self.replaced = { 'month' : month, 'day' : day, 'hour' : 0, 'minute' : 0, 'second' : 0, 'tzinfo' : tz } def _get_unit(self): """ Return how many days a unit of the locator is; used for intelligent autoscaling. """ return 365 def __call__(self): dmin, dmax = self.viewlim_to_dt() ymin = self.base.le(dmin.year) ymax = self.base.ge(dmax.year) ticks = [dmin.replace(year=ymin, **self.replaced)] while 1: dt = ticks[-1] if dt.year>=ymax: return date2num(ticks) year = dt.year + self.base.get_base() ticks.append(dt.replace(year=year, **self.replaced)) def autoscale(self): """ Set the view limits to include the data range. """ dmin, dmax = self.datalim_to_dt() ymin = self.base.le(dmin.year) ymax = self.base.ge(dmax.year) vmin = dmin.replace(year=ymin, **self.replaced) vmax = dmax.replace(year=ymax, **self.replaced) vmin = date2num(vmin) vmax = date2num(vmax) return self.nonsingular(vmin, vmax) class MonthLocator(RRuleLocator): """ Make ticks on occurances of each month month, eg 1, 3, 12. """ def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None): """ Mark every month in *bymonth*; *bymonth* can be an int or sequence. Default is ``range(1,13)``, i.e. every month. *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second occurance. """ if bymonth is None: bymonth=range(1,13) o = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday, interval=interval, **self.hms0d) RRuleLocator.__init__(self, o, tz) def _get_unit(self): """ Return how many days a unit of the locator is; used for intelligent autoscaling. """ return 30 class WeekdayLocator(RRuleLocator): """ Make ticks on occurances of each weekday. """ def __init__(self, byweekday=1, interval=1, tz=None): """ Mark every weekday in *byweekday*; *byweekday* can be a number or sequence. Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA, SU, the constants from :mod:`dateutils.rrule`. *interval* specifies the number of weeks to skip. For example, ``interval=2`` plots every second week. """ o = rrulewrapper(DAILY, byweekday=byweekday, interval=interval, **self.hms0d) RRuleLocator.__init__(self, o, tz) def _get_unit(self): """ return how many days a unit of the locator is; used for intelligent autoscaling. """ return 7 class DayLocator(RRuleLocator): """ Make ticks on occurances of each day of the month. For example, 1, 15, 30. """ def __init__(self, bymonthday=None, interval=1, tz=None): """ Mark every day in *bymonthday*; *bymonthday* can be an int or sequence. Default is to tick every day of the month: ``bymonthday=range(1,32)`` """ if bymonthday is None: bymonthday=range(1,32) o = rrulewrapper(DAILY, bymonthday=bymonthday, interval=interval, **self.hms0d) RRuleLocator.__init__(self, o, tz) def _get_unit(self): """ Return how many days a unit of the locator is; used for intelligent autoscaling. """ return 1 class HourLocator(RRuleLocator): """ Make ticks on occurances of each hour. """ def __init__(self, byhour=None, interval=1, tz=None): """ Mark every hour in *byhour*; *byhour* can be an int or sequence. Default is to tick every hour: ``byhour=range(24)`` *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second occurrence. """ if byhour is None: byhour=range(24) rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval, byminute=0, bysecond=0) RRuleLocator.__init__(self, rule, tz) def _get_unit(self): """ return how many days a unit of the locator is; use for intelligent autoscaling """ return 1/24. class MinuteLocator(RRuleLocator): """ Make ticks on occurances of each minute. """ def __init__(self, byminute=None, interval=1, tz=None): """ Mark every minute in *byminute*; *byminute* can be an int or sequence. Default is to tick every minute: ``byminute=range(60)`` *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second occurrence. """ if byminute is None: byminute=range(60) rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval, bysecond=0) RRuleLocator.__init__(self, rule, tz) def _get_unit(self): """ Return how many days a unit of the locator is; used for intelligent autoscaling. """ return 1./(24*60) class SecondLocator(RRuleLocator): """ Make ticks on occurances of each second. """ def __init__(self, bysecond=None, interval=1, tz=None): """ Mark every second in *bysecond*; *bysecond* can be an int or sequence. Default is to tick every second: ``bysecond = range(60)`` *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second occurrence. """ if bysecond is None: bysecond=range(60) rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval) RRuleLocator.__init__(self, rule, tz) def _get_unit(self): """ Return how many days a unit of the locator is; used for intelligent autoscaling. """ return 1./(24*60*60) def _close_to_dt(d1, d2, epsilon=5): 'Assert that datetimes *d1* and *d2* are within *epsilon* microseconds.' delta = d2-d1 mus = abs(delta.days*MUSECONDS_PER_DAY + delta.seconds*1e6 + delta.microseconds) assert(mus<epsilon) def _close_to_num(o1, o2, epsilon=5): 'Assert that float ordinals *o1* and *o2* are within *epsilon* microseconds.' delta = abs((o2-o1)*MUSECONDS_PER_DAY) assert(delta<epsilon) def epoch2num(e): """ Convert an epoch or sequence of epochs to the new date format, that is days since 0001. """ spd = 24.*3600. return 719163 + np.asarray(e)/spd def num2epoch(d): """ Convert days since 0001 to epoch. *d* can be a number or sequence. """ spd = 24.*3600. return (np.asarray(d)-719163)*spd def mx2num(mxdates): """ Convert mx :class:`datetime` instance (or sequence of mx instances) to the new date format. """ scalar = False if not cbook.iterable(mxdates): scalar = True mxdates = [mxdates] ret = epoch2num([m.ticks() for m in mxdates]) if scalar: return ret[0] else: return ret def date_ticker_factory(span, tz=None, numticks=5): """ Create a date locator with *numticks* (approx) and a date formatter for *span* in days. Return value is (locator, formatter). """ if span==0: span = 1/24. minutes = span*24*60 hours = span*24 days = span weeks = span/7. months = span/31. # approx years = span/365. if years>numticks: locator = YearLocator(int(years/numticks), tz=tz) # define fmt = '%Y' elif months>numticks: locator = MonthLocator(tz=tz) fmt = '%b %Y' elif weeks>numticks: locator = WeekdayLocator(tz=tz) fmt = '%a, %b %d' elif days>numticks: locator = DayLocator(interval=int(math.ceil(days/numticks)), tz=tz) fmt = '%b %d' elif hours>numticks: locator = HourLocator(interval=int(math.ceil(hours/numticks)), tz=tz) fmt = '%H:%M\n%b %d' elif minutes>numticks: locator = MinuteLocator(interval=int(math.ceil(minutes/numticks)), tz=tz) fmt = '%H:%M:%S' else: locator = MinuteLocator(tz=tz) fmt = '%H:%M:%S' formatter = DateFormatter(fmt, tz=tz) return locator, formatter def seconds(s): 'Return seconds as days.' return float(s)/SEC_PER_DAY def minutes(m): 'Return minutes as days.' return float(m)/MINUTES_PER_DAY def hours(h): 'Return hours as days.' return h/24. def weeks(w): 'Return weeks as days.' return w*7. class DateConverter(units.ConversionInterface): def axisinfo(unit): 'return the unit AxisInfo' if unit=='date': majloc = AutoDateLocator() majfmt = AutoDateFormatter(majloc) return units.AxisInfo( majloc = majloc, majfmt = majfmt, label='', ) else: return None axisinfo = staticmethod(axisinfo) def convert(value, unit): if units.ConversionInterface.is_numlike(value): return value return date2num(value) convert = staticmethod(convert) def default_units(x): 'Return the default unit for *x* or None' return 'date' default_units = staticmethod(default_units) units.registry[datetime.date] = DateConverter() units.registry[datetime.datetime] = DateConverter() if __name__=='__main__': #tz = None tz = pytz.timezone('US/Pacific') #tz = UTC dt = datetime.datetime(1011, 10, 9, 13, 44, 22, 101010, tzinfo=tz) x = date2num(dt) _close_to_dt(dt, num2date(x, tz)) #tz = _get_rc_timezone() d1 = datetime.datetime( 2000, 3, 1, tzinfo=tz) d2 = datetime.datetime( 2000, 3, 5, tzinfo=tz) #d1 = datetime.datetime( 2002, 1, 5, tzinfo=tz) #d2 = datetime.datetime( 2003, 12, 1, tzinfo=tz) delta = datetime.timedelta(hours=6) dates = drange(d1, d2, delta) # MGDTODO: Broken on transforms branch #print 'orig', d1 #print 'd2n and back', num2date(date2num(d1), tz) from _transforms import Value, Interval v1 = Value(date2num(d1)) v2 = Value(date2num(d2)) dlim = Interval(v1,v2) vlim = Interval(v1,v2) #locator = HourLocator(byhour=(3,15), tz=tz) #locator = MinuteLocator(byminute=(15,30,45), tz=tz) #locator = YearLocator(base=5, month=7, day=4, tz=tz) #locator = MonthLocator(bymonthday=15) locator = DayLocator(tz=tz) locator.set_data_interval(dlim) locator.set_view_interval(vlim) dmin, dmax = locator.autoscale() vlim.set_bounds(dmin, dmax) ticks = locator() fmt = '%Y-%m-%d %H:%M:%S %Z' formatter = DateFormatter(fmt, tz) #for t in ticks: print formatter(t) for t in dates: print formatter(t)
agpl-3.0
spurihwr/ImageProcessingProjects
Image_Recognition/PCABasedImageReco.py
1
2899
#################################################################### # This code is PCA base face recognition programme. It reads 5 # faces from ORL database and the rest 5 are used as test. # PCA_Performance shows the recognition performance. # # Download the ORL database from internet. # This code was modified by Saurabh Puri in order to show the face # recognition task ####################################################################### from sklearn.decomposition import PCA from sklearn.svm import SVC from sklearn.metrics import accuracy_score import numpy as np import cv2 zz=1; noc=40; #no_of_classes nots=5; #no_of_training_set #width and height is hardcoded but could be derived from the image itself #sometimes for a better performance, cropping of image is required as PCA is generally very sensitive to variations in the image (like light, shadow, etc.) w = 112 h = 92 #Split the dataset into training and test set #Folder location: ./att_faces/s*/*.pgm #First half images in each class is considered as training set and other half are considered to be test set X_train = np.empty(w*h, dtype=np.float32) y_train = np.empty(1, dtype=np.int32) X_test = np.empty(w*h, dtype=np.float32) y_test = np.empty(1, dtype=np.int32) for i in range(1,noc+1): for j in range(1,nots+1): #print(str(i) +' '+ str(j)) file= "./att_faces/s" + str(i) + "/" + str(j) + ".pgm" im = cv2.imread(file) im = im.transpose((2,0,1)) im = np.expand_dims(im,axis=0) imgray = im[0][0] im1D = imgray.flatten('F') X_train = np.vstack((X_train,im1D)) y_train = np.hstack((y_train,i-1)) for i in range(1,noc+1): for j in range(nots+1,nots+6): #print(str(i) +' '+ str(j)) file= "./att_faces/s" + str(i) + "/" + str(j) + ".pgm" im = cv2.imread(file) im = im.transpose((2,0,1)) im = np.expand_dims(im,axis=0) imgray = im[0][0] im1D = imgray.flatten('F') X_test = np.vstack((X_test,im1D)) y_test = np.hstack((y_test,i-1)) #delete first row as it was empty X_train = np.delete(X_train,(0),axis=0) y_train = np.delete(y_train,(0),axis=0) X_test = np.delete(X_test,(0),axis=0) y_test = np.delete(y_test,(0),axis=0) print('loaded') #normalize to 0-1 X_train = X_train/255 X_test = X_test/255 # initiate PCA and fit to the training data pca = PCA(n_components=40) pca.fit(X_train) # transform X_transformed = pca.transform(X_train) newdata_transformed = pca.transform(X_test) #initiate a classifier and then fit eigen faces and labels clf = SVC() clf.fit(X_transformed,y_train) # predict new labels using the trained classifier pred_labels = clf.predict(newdata_transformed) #output the accuracy_score score = accuracy_score(y_test,pred_labels,True) print(score) ##Print the predicted labels #print(pred_labels)
mit
olologin/scikit-learn
examples/applications/plot_tomography_l1_reconstruction.py
81
5461
""" ====================================================================== Compressive sensing: tomography reconstruction with L1 prior (Lasso) ====================================================================== This example shows the reconstruction of an image from a set of parallel projections, acquired along different angles. Such a dataset is acquired in **computed tomography** (CT). Without any prior information on the sample, the number of projections required to reconstruct the image is of the order of the linear size ``l`` of the image (in pixels). For simplicity we consider here a sparse image, where only pixels on the boundary of objects have a non-zero value. Such data could correspond for example to a cellular material. Note however that most images are sparse in a different basis, such as the Haar wavelets. Only ``l/7`` projections are acquired, therefore it is necessary to use prior information available on the sample (its sparsity): this is an example of **compressive sensing**. The tomography projection operation is a linear transformation. In addition to the data-fidelity term corresponding to a linear regression, we penalize the L1 norm of the image to account for its sparsity. The resulting optimization problem is called the :ref:`lasso`. We use the class :class:`sklearn.linear_model.Lasso`, that uses the coordinate descent algorithm. Importantly, this implementation is more computationally efficient on a sparse matrix, than the projection operator used here. The reconstruction with L1 penalization gives a result with zero error (all pixels are successfully labeled with 0 or 1), even if noise was added to the projections. In comparison, an L2 penalization (:class:`sklearn.linear_model.Ridge`) produces a large number of labeling errors for the pixels. Important artifacts are observed on the reconstructed image, contrary to the L1 penalization. Note in particular the circular artifact separating the pixels in the corners, that have contributed to fewer projections than the central disk. """ print(__doc__) # Author: Emmanuelle Gouillart <emmanuelle.gouillart@nsup.org> # License: BSD 3 clause import numpy as np from scipy import sparse from scipy import ndimage from sklearn.linear_model import Lasso from sklearn.linear_model import Ridge import matplotlib.pyplot as plt def _weights(x, dx=1, orig=0): x = np.ravel(x) floor_x = np.floor((x - orig) / dx) alpha = (x - orig - floor_x * dx) / dx return np.hstack((floor_x, floor_x + 1)), np.hstack((1 - alpha, alpha)) def _generate_center_coordinates(l_x): X, Y = np.mgrid[:l_x, :l_x].astype(np.float64) center = l_x / 2. X += 0.5 - center Y += 0.5 - center return X, Y def build_projection_operator(l_x, n_dir): """ Compute the tomography design matrix. Parameters ---------- l_x : int linear size of image array n_dir : int number of angles at which projections are acquired. Returns ------- p : sparse matrix of shape (n_dir l_x, l_x**2) """ X, Y = _generate_center_coordinates(l_x) angles = np.linspace(0, np.pi, n_dir, endpoint=False) data_inds, weights, camera_inds = [], [], [] data_unravel_indices = np.arange(l_x ** 2) data_unravel_indices = np.hstack((data_unravel_indices, data_unravel_indices)) for i, angle in enumerate(angles): Xrot = np.cos(angle) * X - np.sin(angle) * Y inds, w = _weights(Xrot, dx=1, orig=X.min()) mask = np.logical_and(inds >= 0, inds < l_x) weights += list(w[mask]) camera_inds += list(inds[mask] + i * l_x) data_inds += list(data_unravel_indices[mask]) proj_operator = sparse.coo_matrix((weights, (camera_inds, data_inds))) return proj_operator def generate_synthetic_data(): """ Synthetic binary data """ rs = np.random.RandomState(0) n_pts = 36. x, y = np.ogrid[0:l, 0:l] mask_outer = (x - l / 2) ** 2 + (y - l / 2) ** 2 < (l / 2) ** 2 mask = np.zeros((l, l)) points = l * rs.rand(2, n_pts) mask[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 mask = ndimage.gaussian_filter(mask, sigma=l / n_pts) res = np.logical_and(mask > mask.mean(), mask_outer) return res - ndimage.binary_erosion(res) # Generate synthetic images, and projections l = 128 proj_operator = build_projection_operator(l, l / 7.) data = generate_synthetic_data() proj = proj_operator * data.ravel()[:, np.newaxis] proj += 0.15 * np.random.randn(*proj.shape) # Reconstruction with L2 (Ridge) penalization rgr_ridge = Ridge(alpha=0.2) rgr_ridge.fit(proj_operator, proj.ravel()) rec_l2 = rgr_ridge.coef_.reshape(l, l) # Reconstruction with L1 (Lasso) penalization # the best value of alpha was determined using cross validation # with LassoCV rgr_lasso = Lasso(alpha=0.001) rgr_lasso.fit(proj_operator, proj.ravel()) rec_l1 = rgr_lasso.coef_.reshape(l, l) plt.figure(figsize=(8, 3.3)) plt.subplot(131) plt.imshow(data, cmap=plt.cm.gray, interpolation='nearest') plt.axis('off') plt.title('original image') plt.subplot(132) plt.imshow(rec_l2, cmap=plt.cm.gray, interpolation='nearest') plt.title('L2 penalization') plt.axis('off') plt.subplot(133) plt.imshow(rec_l1, cmap=plt.cm.gray, interpolation='nearest') plt.title('L1 penalization') plt.axis('off') plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1) plt.show()
bsd-3-clause
adjih/openlab
tools/memmap.py
6
9300
#! /usr/bin/env python ## ## memmap.py ## Copyright HiKoB 2012 ## Author: Antoine Fraboulet ## ## Generates charts for .text, .rodata, .bss and .data sections ## ## import os, sys from pylab import * from optparse import OptionParser from subprocess import Popen, PIPE, STDOUT import jstreemap ## ################################################## ## ################################################## import re pretty_re = re.compile("([^/(]+)(?:\((.+)\))?$") def pretty(s): g = pretty_re.search(s).groups() return g[1] or g[0] def pretty2(s): return os.path.basename(s) ## ################################################## ## ################################################## def draw_chart(fig, name, labels, sizes, png): # make a square figure and axes matplotlib.pyplot.figure(fig, figsize=(10,10)) ax = matplotlib.pyplot.axes([0.1, 0.1, 0.8, 0.8]) matplotlib.pyplot.pie(sizes, labels=labels, colors= ('#707070', '#808080', '#909090', '#A0A0A0', '#B0B0B0', '#C0C0C0', '#101010', '#202020', '#303030', '#404040', '#505050', '#606060', '#D0D0D0', '#E0E0E0', '#F0F0F0'), autopct='%1.1f%%', #pctdistance = 1.1, #labeldistance = 1.2, shadow=False) matplotlib.pyplot.title('Memory map for ' + name + " (%d bytes)" % sum(sizes)) # , bbox={'facecolor':'0.8', 'pad':5}) # matplotlib.pyplot.autumn() matplotlib.pyplot.savefig(png) return ## ################################################## ## ################################################## def draw_chart_flat(fig, section, sizes, png): """ draw_chart_flat( section, sizes, png) section : section name sizes : dictionary (file,size) png : image name """ labels = sizes.keys() fracs = [] for k in labels: fracs.append( sizes.get(k) ) labels = map(pretty2, labels) draw_chart(fig, section, labels, fracs, png) def draw_chart_toplevel(fig, section, tmap, png): """ draw_chart_toplevel(section, tmap, png) section : section name tmap : tmap is [[name, parent, size], ... ] png : image name """ #[[row[i] for row in tmap] for i in range(3)] print "============== %s" % section dict = {} for l in tmap: name = l[0] parent = l[1] size = l[2] dict[parent] = dict.get(parent,0) + size print dict draw_chart_flat(fig, section, dict, png) def draw_chart_library(fig, section, tmap, png): """ """ # get all lib names i = 0 dict = {} for l in tmap: name = l[0] parent = l[1] size = l[2] dict[parent] = dict.get(parent,0) + size # for each lib for lib in dict.keys(): libdict = {} for m in tmap: file = m[0] parent = m[1] size = m[2] if lib == parent: # parent if file != None: libdict[file] = libdict.get(file,0) + size else: libdict[parent] = libdict.get(parent,0) + size print "============== %s,%s" % (section,lib) draw_chart_flat (fig + i,".bss.%s" % lib, libdict, "mem.bss.%s.png" % lib) i += 1 ## ################################################## ## ################################################## def build_flat(map, section): sizes = {} for l in map: if l.startswith(" " + section + " "): ls = l.split() size = int(ls[2],16) if size != 0: sizes[ls[3]] = sizes.get(ls[3],0) + size print "%s %d lines" % (section,len(sizes)) return sizes ## ################################################## ## ################################################## def build_treemap(flat): tmap = [] fullnames = flat.keys() for k in fullnames: g = pretty_re.search(k).groups() name = g[1] parent = g[0] size = flat.get(k) tmap.append ( [ name, parent, size ] ) return tmap ## ################################################## ## ################################################## def build(map, section): flat = build_flat(map, section) tmap = build_treemap(flat) return (flat, tmap) ## ################################################## ## ################################################## parser = OptionParser() parser.add_option("-e", "--elf", help="select ELF file", action="store", type="string", dest="file_elf", metavar="FILE") parser.add_option("-m", "--map", help="select MAP file", action="store", type="string", dest="file_map", metavar="FILE") parser.add_option("-o", "--out", help="select output file", action="store", type="string", dest="file_out", metavar="FILE") parser.add_option("-t", "--title", help="html title", action="store", type="string", dest="title") parser.add_option("-j", "--jscript", action="store_true", dest="javascript") parser.add_option("-c", "--camembert", action="store_true", dest="camembert" ) parser.add_option("-v", "--verbose", action="store_true", dest="verbose" ) def main(): ## ## usage: ## ## ./memmap.py -j [-m out.map] [-o out.html] > [file.html] ## (options, args) = parser.parse_args() title = "" ## ## if options.verbose: print "example: memmap.py -j -t title -m out.map -o memmap.html" print "example: memmap.py -j -t title -e prog.elf -o memmap.html" print "firefox file://`pwd`/memmap.html" ## ## if options.file_map: title = "Memory map for %s" % options.file_map map = file(options.file_map).read().split("\n") ## ## if options.file_elf: title = "Memory map for %s" % options.file_elf cmd = ["arm-none-eabi-ld", "-M", options.file_elf] command = Popen(cmd, stdout=PIPE, stderr=STDOUT) stdout, stderr = command.communicate() map = stdout.split("\n") ## ## outfile = "memmap" if options.file_out: outfile = options.file_out ## ## if options.title: title = options.title ## ## Load structures and build treemap ## (bss, tm_bss) = build(map,".bss") (data, tm_data) = build(map,".data") (text, tm_text) = build(map,".text") (rodata, tm_rodata) = build(map,".rodata") ## ## js-treemap ## tm1 = """ new TreeParentNode( "root", [ new TreeParentNode("Flash", [ new TreeParentNode(".text", [ """ tm2 = """ ] ), new TreeParentNode(".rodata", [ """ tm3 = """ ] ) ] ), new TreeParentNode("RAM", [ new TreeParentNode(".data", [ """ tm4 = """ ] ), new TreeParentNode(".bss", [ """ tm5 = """ ] ) ] ) ] ); """ tm = tm1.split('\n') ## tm = tm + tm_text.getnodes() for i in tm_text: tm.append("new TreeNode (\" %s \", %d)%s" % (i[0], i[2], ",")) tm = tm + tm2.split('\n') ## tm = tm + rodata.getnodes() for i in tm_rodata: tm.append("new TreeNode (\" %s \", %d)%s" % (i[0], i[2], ",")) tm = tm + tm3.split('\n') ## tm = tm + tm_data.getnodes() for i in tm_data: tm.append("new TreeNode (\" %s \", %d)%s" % (i[0], i[2], ",")) tm = tm + tm4.split('\n') ## tm = tm + tm_bss.getnodes() for i in tm_bss: tm.append("new TreeNode (\" %s \", %d)%s" % (i[0], i[2], ",")) tm = tm + tm5.split('\n') ## ## JavaScript / JsTreeMap ## if options.javascript: fd = open(outfile, 'w') for l in jstreemap.html(tm,title): fd.write("%s\n" % l) fd.close() ## ## Camembert section ## # draw_chart_flat(section, flat, "mem" + section + ".png") # print_html(tmbss, tmdata, tmtext) if options.camembert: draw_chart_toplevel(1,".text", tm_text, outfile + ".tl.text.png") draw_chart_toplevel(2,".bss", tm_bss, outfile + ".tl.bss.png") draw_chart_toplevel(3,".data", tm_data, outfile + ".tl.data.png") draw_chart_toplevel(4,".rodata", tm_rodata, outfile + ".tl.rodata.png") return 0 if __name__ == "__main__": main() ## ################################################## ## ################################################## # tm = """ # new TreeParentNode( "root", [ # new TreeNode( "a", 1 ), # new TreeNode( "BBBBBBBB", 2 ), # new TreeNode( "CCCCCC", 3 ), # new TreeNode( "d", 4 ), # new TreeNode( "e", 5 ), # new TreeNode( "f", 6 ), # new TreeNode( "g", 7 ), # new TreeNode( "h", 8 ), # new TreeNode( "i", 9 ), # new TreeNode( "j", 10 ), # new TreeNode( "k", 11 ), # new TreeNode( "l", 13 ), # new TreeNode( "m", 14 ), # new TreeParentNode( "n", [ # new TreeNode( "Alpha", 7 ), # new TreeParentNode( "Beta", [ # new TreeNode( "apples", 1 ), # new TreeNode( "pears", 2 ), # new TreeNode( "bananas", 3 ) # ] ) # ] ) # , # new TreeNode( "o", 16 ), # new TreeNode( "p", 17 ), # new TreeNode( "q", 18 ) # ] ); # """
gpl-3.0
luo66/scikit-learn
examples/text/document_clustering.py
230
8356
""" ======================================= Clustering text documents using k-means ======================================= This is an example showing how the scikit-learn can be used to cluster documents by topics using a bag-of-words approach. This example uses a scipy.sparse matrix to store the features instead of standard numpy arrays. Two feature extraction methods can be used in this example: - TfidfVectorizer uses a in-memory vocabulary (a python dict) to map the most frequent words to features indices and hence compute a word occurrence frequency (sparse) matrix. The word frequencies are then reweighted using the Inverse Document Frequency (IDF) vector collected feature-wise over the corpus. - HashingVectorizer hashes word occurrences to a fixed dimensional space, possibly with collisions. The word count vectors are then normalized to each have l2-norm equal to one (projected to the euclidean unit-ball) which seems to be important for k-means to work in high dimensional space. HashingVectorizer does not provide IDF weighting as this is a stateless model (the fit method does nothing). When IDF weighting is needed it can be added by pipelining its output to a TfidfTransformer instance. Two algorithms are demoed: ordinary k-means and its more scalable cousin minibatch k-means. Additionally, latent sematic analysis can also be used to reduce dimensionality and discover latent patterns in the data. It can be noted that k-means (and minibatch k-means) are very sensitive to feature scaling and that in this case the IDF weighting helps improve the quality of the clustering by quite a lot as measured against the "ground truth" provided by the class label assignments of the 20 newsgroups dataset. This improvement is not visible in the Silhouette Coefficient which is small for both as this measure seem to suffer from the phenomenon called "Concentration of Measure" or "Curse of Dimensionality" for high dimensional datasets such as text data. Other measures such as V-measure and Adjusted Rand Index are information theoretic based evaluation scores: as they are only based on cluster assignments rather than distances, hence not affected by the curse of dimensionality. Note: as k-means is optimizing a non-convex objective function, it will likely end up in a local optimum. Several runs with independent random init might be necessary to get a good convergence. """ # Author: Peter Prettenhofer <peter.prettenhofer@gmail.com> # Lars Buitinck <L.J.Buitinck@uva.nl> # License: BSD 3 clause from __future__ import print_function from sklearn.datasets import fetch_20newsgroups from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import HashingVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Normalizer from sklearn import metrics from sklearn.cluster import KMeans, MiniBatchKMeans import logging from optparse import OptionParser import sys from time import time import numpy as np # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') # parse commandline arguments op = OptionParser() op.add_option("--lsa", dest="n_components", type="int", help="Preprocess documents with latent semantic analysis.") op.add_option("--no-minibatch", action="store_false", dest="minibatch", default=True, help="Use ordinary k-means algorithm (in batch mode).") op.add_option("--no-idf", action="store_false", dest="use_idf", default=True, help="Disable Inverse Document Frequency feature weighting.") op.add_option("--use-hashing", action="store_true", default=False, help="Use a hashing feature vectorizer") op.add_option("--n-features", type=int, default=10000, help="Maximum number of features (dimensions)" " to extract from text.") op.add_option("--verbose", action="store_true", dest="verbose", default=False, help="Print progress reports inside k-means algorithm.") print(__doc__) op.print_help() (opts, args) = op.parse_args() if len(args) > 0: op.error("this script takes no arguments.") sys.exit(1) ############################################################################### # Load some categories from the training set categories = [ 'alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space', ] # Uncomment the following to do the analysis on all the categories #categories = None print("Loading 20 newsgroups dataset for categories:") print(categories) dataset = fetch_20newsgroups(subset='all', categories=categories, shuffle=True, random_state=42) print("%d documents" % len(dataset.data)) print("%d categories" % len(dataset.target_names)) print() labels = dataset.target true_k = np.unique(labels).shape[0] print("Extracting features from the training dataset using a sparse vectorizer") t0 = time() if opts.use_hashing: if opts.use_idf: # Perform an IDF normalization on the output of HashingVectorizer hasher = HashingVectorizer(n_features=opts.n_features, stop_words='english', non_negative=True, norm=None, binary=False) vectorizer = make_pipeline(hasher, TfidfTransformer()) else: vectorizer = HashingVectorizer(n_features=opts.n_features, stop_words='english', non_negative=False, norm='l2', binary=False) else: vectorizer = TfidfVectorizer(max_df=0.5, max_features=opts.n_features, min_df=2, stop_words='english', use_idf=opts.use_idf) X = vectorizer.fit_transform(dataset.data) print("done in %fs" % (time() - t0)) print("n_samples: %d, n_features: %d" % X.shape) print() if opts.n_components: print("Performing dimensionality reduction using LSA") t0 = time() # Vectorizer results are normalized, which makes KMeans behave as # spherical k-means for better results. Since LSA/SVD results are # not normalized, we have to redo the normalization. svd = TruncatedSVD(opts.n_components) normalizer = Normalizer(copy=False) lsa = make_pipeline(svd, normalizer) X = lsa.fit_transform(X) print("done in %fs" % (time() - t0)) explained_variance = svd.explained_variance_ratio_.sum() print("Explained variance of the SVD step: {}%".format( int(explained_variance * 100))) print() ############################################################################### # Do the actual clustering if opts.minibatch: km = MiniBatchKMeans(n_clusters=true_k, init='k-means++', n_init=1, init_size=1000, batch_size=1000, verbose=opts.verbose) else: km = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1, verbose=opts.verbose) print("Clustering sparse data with %s" % km) t0 = time() km.fit(X) print("done in %0.3fs" % (time() - t0)) print() print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels, km.labels_)) print("Completeness: %0.3f" % metrics.completeness_score(labels, km.labels_)) print("V-measure: %0.3f" % metrics.v_measure_score(labels, km.labels_)) print("Adjusted Rand-Index: %.3f" % metrics.adjusted_rand_score(labels, km.labels_)) print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X, km.labels_, sample_size=1000)) print() if not opts.use_hashing: print("Top terms per cluster:") if opts.n_components: original_space_centroids = svd.inverse_transform(km.cluster_centers_) order_centroids = original_space_centroids.argsort()[:, ::-1] else: order_centroids = km.cluster_centers_.argsort()[:, ::-1] terms = vectorizer.get_feature_names() for i in range(true_k): print("Cluster %d:" % i, end='') for ind in order_centroids[i, :10]: print(' %s' % terms[ind], end='') print()
bsd-3-clause
psachin/swift
swift/common/middleware/x_profile/html_viewer.py
6
21032
# Copyright (c) 2010-2012 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import cgi import os import random import re import string import tempfile from swift import gettext_ as _ from exceptions import PLOTLIBNotInstalled, ODFLIBNotInstalled,\ NotFoundException, MethodNotAllowed, DataLoadFailure, ProfileException from profile_model import Stats2 PLOTLIB_INSTALLED = True try: import matplotlib # use agg backend for writing to file, not for rendering in a window. # otherwise some platform will complain "no display name and $DISPLAY # environment variable" matplotlib.use('agg') import matplotlib.pyplot as plt except ImportError: PLOTLIB_INSTALLED = False empty_description = """ The default profile of current process or the profile you requested is empty. <input type="submit" name="refresh" value="Refresh"/> """ profile_tmpl = """ <select name="profile"> <option value="current">current</option> <option value="all">all</option> ${profile_list} </select> """ sort_tmpl = """ <select name="sort"> <option value="time">time</option> <option value="cumulative">cumulative</option> <option value="calls">calls</option> <option value="pcalls">pcalls</option> <option value="name">name</option> <option value="file">file</option> <option value="module">module</option> <option value="line">line</option> <option value="nfl">nfl</option> <option value="stdname">stdname</option> </select> """ limit_tmpl = """ <select name="limit"> <option value="-1">all</option> <option value="0.1">10%</option> <option value="0.2">20%</option> <option value="0.3">30%</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="50">50</option> <option value="100">100</option> <option value="200">200</option> <option value="300">300</option> <option value="400">400</option> <option value="500">500</option> </select> """ fulldirs_tmpl = """ <input type="checkbox" name="fulldirs" value="1" ${fulldir_checked}/> """ mode_tmpl = """ <select name="mode"> <option value="stats">stats</option> <option value="callees">callees</option> <option value="callers">callers</option> </select> """ nfl_filter_tmpl = """ <input type="text" name="nfl_filter" value="${nfl_filter}" placeholder="filename part" /> """ formelements_tmpl = """ <div> <table> <tr> <td> <strong>Profile</strong> <td> <strong>Sort</strong> </td> <td> <strong>Limit</strong> </td> <td> <strong>Full Path</strong> </td> <td> <strong>Filter</strong> </td> <td> </td> <td> <strong>Plot Metric</strong> </td> <td> <strong>Plot Type</strong> <td> </td> <td> <strong>Format</strong> </td> <td> <td> </td> <td> </td> </tr> <tr> <td> ${profile} <td> ${sort} </td> <td> ${limit} </td> <td> ${fulldirs} </td> <td> ${nfl_filter} </td> <td> <input type="submit" name="query" value="query"/> </td> <td> <select name='metric'> <option value='nc'>call count</option> <option value='cc'>primitive call count</option> <option value='tt'>total time</option> <option value='ct'>cumulative time</option> </select> </td> <td> <select name='plottype'> <option value='bar'>bar</option> <option value='pie'>pie</option> </select> <td> <input type="submit" name="plot" value="plot"/> </td> <td> <select name='format'> <option value='default'>binary</option> <option value='json'>json</option> <option value='csv'>csv</option> <option value='ods'>ODF.ods</option> </select> </td> <td> <input type="submit" name="download" value="download"/> </td> <td> <input type="submit" name="clear" value="clear"/> </td> </tr> </table> </div> """ index_tmpl = """ <html> <head> <title>profile results</title> <style> <!-- tr.normal { background-color: #ffffff } tr.hover { background-color: #88eeee } //--> </style> </head> <body> <form action="${action}" method="POST"> <div class="form-text"> ${description} </div> <hr /> ${formelements} </form> <pre> ${profilehtml} </pre> </body> </html> """ class HTMLViewer(object): format_dict = {'default': 'application/octet-stream', 'json': 'application/json', 'csv': 'text/csv', 'ods': 'application/vnd.oasis.opendocument.spreadsheet', 'python': 'text/html'} def __init__(self, app_path, profile_module, profile_log): self.app_path = app_path self.profile_module = profile_module self.profile_log = profile_log def _get_param(self, query_dict, key, default=None, multiple=False): value = query_dict.get(key, default) if value is None or value == '': return default if multiple: return value if isinstance(value, list): return eval(value[0]) if isinstance(default, int) else value[0] else: return value def render(self, url, method, path_entry, query_dict, clear_callback): plot = self._get_param(query_dict, 'plot', None) download = self._get_param(query_dict, 'download', None) clear = self._get_param(query_dict, 'clear', None) action = plot or download or clear profile_id = self._get_param(query_dict, 'profile', 'current') sort = self._get_param(query_dict, 'sort', 'time') limit = self._get_param(query_dict, 'limit', -1) fulldirs = self._get_param(query_dict, 'fulldirs', 0) nfl_filter = self._get_param(query_dict, 'nfl_filter', '').strip() metric_selected = self._get_param(query_dict, 'metric', 'cc') plot_type = self._get_param(query_dict, 'plottype', 'bar') download_format = self._get_param(query_dict, 'format', 'default') content = '' # GET /__profile, POST /__profile if len(path_entry) == 2 and method in ['GET', 'POST']: log_files = self.profile_log.get_logfiles(profile_id) if action == 'plot': content, headers = self.plot(log_files, sort, limit, nfl_filter, metric_selected, plot_type) elif action == 'download': content, headers = self.download(log_files, sort, limit, nfl_filter, download_format) else: if action == 'clear': self.profile_log.clear(profile_id) clear_callback and clear_callback() content, headers = self.index_page(log_files, sort, limit, fulldirs, nfl_filter, profile_id, url) # GET /__profile__/all # GET /__profile__/current # GET /__profile__/profile_id # GET /__profile__/profile_id/ # GET /__profile__/profile_id/account.py:50(GETorHEAD) # GET /__profile__/profile_id/swift/proxy/controllers # /account.py:50(GETorHEAD) # with QUERY_STRING: ?format=[default|json|csv|ods] elif len(path_entry) > 2 and method == 'GET': profile_id = path_entry[2] log_files = self.profile_log.get_logfiles(profile_id) pids = self.profile_log.get_all_pids() # return all profiles in a json format by default. # GET /__profile__/ if profile_id == '': content = '{"profile_ids": ["' + '","'.join(pids) + '"]}' headers = [('content-type', self.format_dict['json'])] else: if len(path_entry) > 3 and path_entry[3] != '': nfl_filter = '/'.join(path_entry[3:]) if path_entry[-1].find(':0') == -1: nfl_filter = '/' + nfl_filter content, headers = self.download(log_files, sort, -1, nfl_filter, download_format) headers.append(('Access-Control-Allow-Origin', '*')) else: raise MethodNotAllowed(_('method %s is not allowed.') % method) return content, headers def index_page(self, log_files=None, sort='time', limit=-1, fulldirs=0, nfl_filter='', profile_id='current', url='#'): headers = [('content-type', 'text/html')] if len(log_files) == 0: return empty_description, headers try: stats = Stats2(*log_files) except (IOError, ValueError): raise DataLoadFailure(_('Can not load profile data from %s.') % log_files) if not fulldirs: stats.strip_dirs() stats.sort_stats(sort) nfl_filter_esc =\ nfl_filter.replace('(', '\(').replace(')', '\)') amount = [nfl_filter_esc, limit] if nfl_filter_esc else [limit] profile_html = self.generate_stats_html(stats, self.app_path, profile_id, *amount) description = "Profiling information is generated by using\ '%s' profiler." % self.profile_module sort_repl = '<option value="%s">' % sort sort_selected = '<option value="%s" selected>' % sort sort = sort_tmpl.replace(sort_repl, sort_selected) plist = ''.join(['<option value="%s">%s</option>' % (p, p) for p in self.profile_log.get_all_pids()]) profile_element = string.Template(profile_tmpl).substitute( {'profile_list': plist}) profile_repl = '<option value="%s">' % profile_id profile_selected = '<option value="%s" selected>' % profile_id profile_element = profile_element.replace(profile_repl, profile_selected) limit_repl = '<option value="%s">' % limit limit_selected = '<option value="%s" selected>' % limit limit = limit_tmpl.replace(limit_repl, limit_selected) fulldirs_checked = 'checked' if fulldirs else '' fulldirs_element = string.Template(fulldirs_tmpl).substitute( {'fulldir_checked': fulldirs_checked}) nfl_filter_element = string.Template(nfl_filter_tmpl).\ substitute({'nfl_filter': nfl_filter}) form_elements = string.Template(formelements_tmpl).substitute( {'description': description, 'action': url, 'profile': profile_element, 'sort': sort, 'limit': limit, 'fulldirs': fulldirs_element, 'nfl_filter': nfl_filter_element, } ) content = string.Template(index_tmpl).substitute( {'formelements': form_elements, 'action': url, 'description': description, 'profilehtml': profile_html, }) return content, headers def download(self, log_files, sort='time', limit=-1, nfl_filter='', output_format='default'): if len(log_files) == 0: raise NotFoundException(_('no log file found')) try: nfl_esc = nfl_filter.replace('(', '\(').replace(')', '\)') # remove the slash that is intentionally added in the URL # to avoid failure of filtering stats data. if nfl_esc.startswith('/'): nfl_esc = nfl_esc[1:] stats = Stats2(*log_files) stats.sort_stats(sort) if output_format == 'python': data = self.format_source_code(nfl_filter) elif output_format == 'json': data = stats.to_json(nfl_esc, limit) elif output_format == 'csv': data = stats.to_csv(nfl_esc, limit) elif output_format == 'ods': data = stats.to_ods(nfl_esc, limit) else: data = stats.print_stats() return data, [('content-type', self.format_dict[output_format])] except ODFLIBNotInstalled: raise except Exception as ex: raise ProfileException(_('Data download error: %s') % ex) def plot(self, log_files, sort='time', limit=10, nfl_filter='', metric_selected='cc', plot_type='bar'): if not PLOTLIB_INSTALLED: raise PLOTLIBNotInstalled(_('python-matplotlib not installed.')) if len(log_files) == 0: raise NotFoundException(_('no log file found')) try: stats = Stats2(*log_files) stats.sort_stats(sort) stats_dict = stats.stats __, func_list = stats.get_print_list([nfl_filter, limit]) nfls = [] performance = [] names = {'nc': 'Total Call Count', 'cc': 'Primitive Call Count', 'tt': 'Total Time', 'ct': 'Cumulative Time'} for func in func_list: cc, nc, tt, ct, __ = stats_dict[func] metric = {'cc': cc, 'nc': nc, 'tt': tt, 'ct': ct} nfls.append(func[2]) performance.append(metric[metric_selected]) y_pos = range(len(nfls)) error = [random.random() for _unused in y_pos] plt.clf() if plot_type == 'pie': plt.pie(x=performance, explode=None, labels=nfls, autopct='%1.1f%%') else: plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4) plt.yticks(y_pos, nfls) plt.xlabel(names[metric_selected]) plt.title('Profile Statistics (by %s)' % names[metric_selected]) # plt.gcf().tight_layout(pad=1.2) with tempfile.TemporaryFile() as profile_img: plt.savefig(profile_img, format='png', dpi=300) profile_img.seek(0) data = profile_img.read() return data, [('content-type', 'image/jpg')] except Exception as ex: raise ProfileException(_('plotting results failed due to %s') % ex) def format_source_code(self, nfl): nfls = re.split('[:()]', nfl) file_path = nfls[0] try: lineno = int(nfls[1]) except (TypeError, ValueError, IndexError): lineno = 0 # for security reason, this need to be fixed. if not file_path.endswith('.py'): return _('The file type are forbidden to access!') try: data = [] i = 0 with open(file_path) as f: lines = f.readlines() max_width = str(len(str(len(lines)))) fmt = '<span id="L%d" rel="#L%d">%' + max_width\ + 'd|<code>%s</code></span>' for line in lines: l = cgi.escape(line, quote=None) i = i + 1 if i == lineno: fmt2 = '<span id="L%d" style="background-color: \ rgb(127,255,127)">%' + max_width +\ 'd|<code>%s</code></span>' data.append(fmt2 % (i, i, l)) else: data.append(fmt % (i, i, i, l)) data = ''.join(data) except Exception: return _('Can not access the file %s.') % file_path return '<pre>%s</pre>' % data def generate_stats_html(self, stats, app_path, profile_id, *selection): html = [] for filename in stats.files: html.append('<p>%s</p>' % filename) try: for func in stats.top_level: html.append('<p>%s</p>' % func[2]) html.append('%s function calls' % stats.total_calls) if stats.total_calls != stats.prim_calls: html.append("(%d primitive calls)" % stats.prim_calls) html.append('in %.3f seconds' % stats.total_tt) if stats.fcn_list: stat_list = stats.fcn_list[:] msg = "<p>Ordered by: %s</p>" % stats.sort_type else: stat_list = stats.stats.keys() msg = '<p>Random listing order was used</p>' for sel in selection: stat_list, msg = stats.eval_print_amount(sel, stat_list, msg) html.append(msg) html.append('<table style="border-width: 1px">') if stat_list: html.append('<tr><th>#</th><th>Call Count</th>\ <th>Total Time</th><th>Time/Call</th>\ <th>Cumulative Time</th>\ <th>Cumulative Time/Call</th>\ <th>Filename:Lineno(Function)</th>\ <th>JSON</th>\ </tr>') count = 0 for func in stat_list: count = count + 1 html.append('<tr onMouseOver="this.className=\'hover\'"\ onMouseOut="this.className=\'normal\'">\ <td>%d)</td>' % count) cc, nc, tt, ct, __ = stats.stats[func] c = str(nc) if nc != cc: c = c + '/' + str(cc) html.append('<td>%s</td>' % c) html.append('<td>%f</td>' % tt) if nc == 0: html.append('<td>-</td>') else: html.append('<td>%f</td>' % (float(tt) / nc)) html.append('<td>%f</td>' % ct) if cc == 0: html.append('<td>-</td>') else: html.append('<td>%f</td>' % (float(ct) / cc)) nfls = cgi.escape(stats.func_std_string(func)) if nfls.split(':')[0] not in ['', 'profile'] and\ os.path.isfile(nfls.split(':')[0]): html.append('<td><a href="%s/%s%s?format=python#L%d">\ %s</a></td>' % (app_path, profile_id, nfls, func[1], nfls)) else: html.append('<td>%s</td>' % nfls) if not nfls.startswith('/'): nfls = '/' + nfls html.append('<td><a href="%s/%s%s?format=json">\ --></a></td></tr>' % (app_path, profile_id, nfls)) except Exception as ex: html.append("Exception:" % str(ex)) return ''.join(html)
apache-2.0
ScottFreeLLC/AlphaPy
alphapy/plots.py
1
33611
################################################################################ # # Package : AlphaPy # Module : plots # Created : July 11, 2013 # # Copyright 2019 ScottFree Analytics LLC # Mark Conway & Robert D. Scott II # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ################################################################################ # # Model Plots # # 1. Calibration # 2. Feature Importance # 3. Learning Curve # 4. ROC Curve # 5. Confusion Matrix # 6. Validation Curve # 7. Partial Dependence # 8. Decision Boundary # # EDA Plots # # 1. Scatter Plot Matrix # 2. Facet Grid # 3. Distribution Plot # 4. Box Plot # 5. Swarm Plot # # Time Series # # 1. Time Series # 2. Candlestick # print(__doc__) # # Imports # from alphapy.estimators import get_estimators from alphapy.globals import BSEP, PSEP, SSEP, USEP from alphapy.globals import ModelType from alphapy.globals import Partition, datasets from alphapy.globals import Q1, Q3 from alphapy.utilities import remove_list_items from bokeh.plotting import figure, show, output_file from itertools import cycle from itertools import product import logging import math import matplotlib matplotlib.use('PS') import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np import pandas as pd from scipy import interp import seaborn as sns from sklearn.calibration import calibration_curve from sklearn.ensemble.partial_dependence import partial_dependence from sklearn.ensemble.partial_dependence import plot_partial_dependence from sklearn.metrics import auc from sklearn.metrics import confusion_matrix from sklearn.metrics import roc_curve from sklearn.model_selection import cross_val_score from sklearn.model_selection import learning_curve from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import train_test_split from sklearn.model_selection import validation_curve # # Initialize logger # logger = logging.getLogger(__name__) # # Function get_partition_data # def get_partition_data(model, partition): r"""Get the X, y pair for a given model and partition Parameters ---------- model : alphapy.Model The model object with partition data. partition : alphapy.Partition Reference to the dataset. Returns ------- X : numpy array The feature matrix. y : numpy array The target vector. Raises ------ TypeError Partition must be train or test. """ if partition == Partition.train: X = model.X_train y = model.y_train elif partition == Partition.test: X = model.X_test y = model.y_test else: raise TypeError('Partition must be train or test') return X, y # # Function generate_plots # def generate_plots(model, partition): r"""Generate plots while running the pipeline. Parameters ---------- model : alphapy.Model The model object with plotting specifications. partition : alphapy.Partition Reference to the dataset. Returns ------- None : None """ logger.info('='*80) logger.info("Generating Plots for partition: %s", datasets[partition]) # Extract model parameters calibration_plot = model.specs['calibration_plot'] confusion_matrix = model.specs['confusion_matrix'] importances = model.specs['importances'] learning_curve = model.specs['learning_curve'] roc_curve = model.specs['roc_curve'] # Generate plots if calibration_plot: plot_calibration(model, partition) if confusion_matrix: plot_confusion_matrix(model, partition) if roc_curve: plot_roc_curve(model, partition) if partition == Partition.train: if learning_curve: plot_learning_curve(model, partition) if importances: plot_importance(model, partition) # # Function get_plot_directory # def get_plot_directory(model): r"""Get the plot output directory of a model. Parameters ---------- model : alphapy.Model The model object with directory information. Returns ------- plot_directory : str The output directory to write the plot. """ directory = model.specs['directory'] plot_directory = SSEP.join([directory, 'plots']) return plot_directory # # Function write_plot # def write_plot(vizlib, plot, plot_type, tag, directory=None): r"""Save the plot to a file, or display it interactively. Parameters ---------- vizlib : str The visualization library: ``'matplotlib'``, ``'seaborn'``, or ``'bokeh'``. plot : module Plotting context, e.g., ``plt``. plot_type : str Type of plot to generate. tag : str Unique identifier for the plot. directory : str, optional The full specification for the directory location. if ``directory`` is *None*, then the plot is displayed interactively. Returns ------- None : None. Raises ------ ValueError Unrecognized data visualization library. References ---------- Visualization Libraries: * Matplotlib : http://matplotlib.org/ * Seaborn : https://seaborn.pydata.org/ * Bokeh : http://bokeh.pydata.org/en/latest/ """ # Validate visualization library if (vizlib == 'matplotlib' or vizlib == 'seaborn' or vizlib == 'bokeh'): # supported library pass elif vizlib == 'plotly': raise ValueError("Unsupported data visualization library: %s" % vizlib) else: raise ValueError("Unrecognized data visualization library: %s" % vizlib) # Save or display the plot if directory: if vizlib == 'bokeh': file_only = ''.join([plot_type, USEP, tag, '.html']) else: file_only = ''.join([plot_type, USEP, tag, '.png']) file_all = SSEP.join([directory, file_only]) logger.info("Writing plot to %s", file_all) if vizlib == 'matplotlib': plot.tight_layout() plot.savefig(file_all) elif vizlib == 'seaborn': plot.savefig(file_all) else: output_file(file_all, title=tag) show(plot) else: if vizlib == 'bokeh': show(plot) else: plot.plot() # # Function plot_calibration # def plot_calibration(model, partition): r"""Display scikit-learn calibration plots. Parameters ---------- model : alphapy.Model The model object with plotting specifications. partition : alphapy.Partition Reference to the dataset. Returns ------- None : None References ---------- Code excerpts from authors: * Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> * Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> http://scikit-learn.org/stable/auto_examples/calibration/plot_calibration_curve.html#sphx-glr-auto-examples-calibration-plot-calibration-curve-py """ logger.info("Generating Calibration Plot") # For classification only if model.specs['model_type'] != ModelType.classification: logger.info('Calibration plot is for classification only') return None # Get X, Y for correct partition X, y = get_partition_data(model, partition) plt.style.use('classic') plt.figure(figsize=(10, 10)) ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2) ax2 = plt.subplot2grid((3, 1), (2, 0)) ax1.plot([0, 1], [0, 1], "k:", label="Perfectly Calibrated") for algo in model.algolist: logger.info("Calibration for Algorithm: %s", algo) clf = model.estimators[algo] if hasattr(clf, "predict_proba"): prob_pos = model.probas[(algo, partition)] else: # use decision function prob_pos = clf.decision_function(X) prob_pos = \ (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min()) fraction_of_positives, mean_predicted_value = \ calibration_curve(y, prob_pos, n_bins=10) ax1.plot(mean_predicted_value, fraction_of_positives, "s-", label="%s" % (algo, )) ax2.hist(prob_pos, range=(0, 1), bins=10, label=algo, histtype="step", lw=2) ax1.set_ylabel("Fraction of Positives") ax1.set_ylim([-0.05, 1.05]) ax1.legend(loc="lower right") ax1.set_title('Calibration Plots [Reliability Curve]') ax2.set_xlabel("Mean Predicted Value") ax2.set_ylabel("Count") ax2.legend(loc="upper center", ncol=2) plot_dir = get_plot_directory(model) pstring = datasets[partition] write_plot('matplotlib', plt, 'calibration', pstring, plot_dir) # # Function plot_importances # def plot_importance(model, partition): r"""Display scikit-learn feature importances. Parameters ---------- model : alphapy.Model The model object with plotting specifications. partition : alphapy.Partition Reference to the dataset. Returns ------- None : None References ---------- http://scikit-learn.org/stable/auto_examples/ensemble/plot_forest_importances.html """ logger.info("Generating Feature Importance Plots") plot_dir = get_plot_directory(model) pstring = datasets[partition] # Get X, Y for correct partition X, y = get_partition_data(model, partition) # For each algorithm that has importances, generate the plot. n_top = 10 for algo in model.algolist: logger.info("Feature Importances for Algorithm: %s", algo) try: importances = model.importances[algo] # forest was input parameter indices = np.argsort(importances)[::-1] # log the feature ranking logger.info("Feature Ranking:") for f in range(n_top): logger.info("%d. Feature %d (%f)" % (f + 1, indices[f], importances[indices[f]])) # plot the feature importances title = BSEP.join([algo, "Feature Importances [", pstring, "]"]) plt.style.use('classic') plt.figure() plt.title(title) plt.bar(list(range(n_top)), importances[indices][:n_top], color="b", align="center") plt.xticks(list(range(n_top)), indices[:n_top]) plt.xlim([-1, n_top]) # save the plot tag = USEP.join([pstring, algo]) write_plot('matplotlib', plt, 'feature_importance', tag, plot_dir) except: logger.info("%s does not have feature importances", algo) # # Function plot_learning_curve # def plot_learning_curve(model, partition): r"""Generate learning curves for a given partition. Parameters ---------- model : alphapy.Model The model object with plotting specifications. partition : alphapy.Partition Reference to the dataset. Returns ------- None : None References ---------- http://scikit-learn.org/stable/auto_examples/ensemble/plot_forest_importances.html """ logger.info("Generating Learning Curves") plot_dir = get_plot_directory(model) pstring = datasets[partition] # Extract model parameters. cv_folds = model.specs['cv_folds'] n_jobs = model.specs['n_jobs'] seed = model.specs['seed'] shuffle = model.specs['shuffle'] verbosity = model.specs['verbosity'] # Get original estimators estimators = get_estimators(model) # Get X, Y for correct partition. X, y = get_partition_data(model, partition) # Set cross-validation parameters to get mean train and test curves. cv = StratifiedKFold(n_splits=cv_folds, shuffle=shuffle, random_state=seed) # Plot a learning curve for each algorithm. ylim = (0.4, 1.01) for algo in model.algolist: logger.info("Learning Curve for Algorithm: %s", algo) # get estimator est = estimators[algo].estimator # plot learning curve title = BSEP.join([algo, "Learning Curve [", pstring, "]"]) # set up plot plt.style.use('classic') plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel("Training Examples") plt.ylabel("Score") # call learning curve function train_sizes=np.linspace(0.1, 1.0, cv_folds) train_sizes, train_scores, test_scores = \ learning_curve(est, X, y, train_sizes=train_sizes, cv=cv, n_jobs=n_jobs, verbose=verbosity) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid() # plot data plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color="g") plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training Score") plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-Validation Score") plt.legend(loc="lower right") # save the plot tag = USEP.join([pstring, algo]) write_plot('matplotlib', plt, 'learning_curve', tag, plot_dir) # # Function plot_roc_curve # def plot_roc_curve(model, partition): r"""Display ROC Curves with Cross-Validation. Parameters ---------- model : alphapy.Model The model object with plotting specifications. partition : alphapy.Partition Reference to the dataset. Returns ------- None : None References ---------- http://scikit-learn.org/stable/modules/model_evaluation.html#receiver-operating-characteristic-roc """ logger.info("Generating ROC Curves") pstring = datasets[partition] # For classification only if model.specs['model_type'] != ModelType.classification: logger.info('ROC Curves are for classification only') return None # Get X, Y for correct partition. X, y = get_partition_data(model, partition) # Initialize plot parameters. plt.style.use('classic') plt.figure() colors = cycle(['cyan', 'indigo', 'seagreen', 'yellow', 'blue', 'darkorange']) lw = 2 # Plot a ROC Curve for each algorithm. for algo in model.algolist: logger.info("ROC Curve for Algorithm: %s", algo) # get estimator estimator = model.estimators[algo] # compute ROC curve and ROC area for each class probas = model.probas[(algo, partition)] fpr, tpr, _ = roc_curve(y, probas) roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, lw=lw, label='%s (area = %0.2f)' % (algo, roc_auc)) # draw the luck line plt.plot([0, 1], [0, 1], linestyle='--', color='k', label='Luck') # define plot characteristics plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') title = BSEP.join([algo, "ROC Curve [", pstring, "]"]) plt.title(title) plt.legend(loc="lower right") # save chart plot_dir = get_plot_directory(model) write_plot('matplotlib', plt, 'roc_curve', pstring, plot_dir) # # Function plot_confusion_matrix # def plot_confusion_matrix(model, partition): r"""Draw the confusion matrix. Parameters ---------- model : alphapy.Model The model object with plotting specifications. partition : alphapy.Partition Reference to the dataset. Returns ------- None : None References ---------- http://scikit-learn.org/stable/modules/model_evaluation.html#confusion-matrix """ logger.info("Generating Confusion Matrices") plot_dir = get_plot_directory(model) pstring = datasets[partition] # For classification only if model.specs['model_type'] != ModelType.classification: logger.info('Confusion Matrix is for classification only') return None # Get X, Y for correct partition. X, y = get_partition_data(model, partition) for algo in model.algolist: logger.info("Confusion Matrix for Algorithm: %s", algo) # get predictions for this partition y_pred = model.preds[(algo, partition)] # compute confusion matrix cm = confusion_matrix(y, y_pred) logger.info('Confusion Matrix:') logger.info('%s', cm) # initialize plot np.set_printoptions(precision=2) plt.style.use('classic') plt.figure() # plot the confusion matrix cmap = plt.cm.Blues plt.imshow(cm, interpolation='nearest', cmap=cmap) title = BSEP.join([algo, "Confusion Matrix [", pstring, "]"]) plt.title(title) plt.colorbar() # set up x and y axes y_values, y_counts = np.unique(y, return_counts=True) tick_marks = np.arange(len(y_values)) plt.xticks(tick_marks, y_values, rotation=45) plt.yticks(tick_marks, y_values) # normalize confusion matrix cmn = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] # place text in square of confusion matrix thresh = (cm.max() + cm.min()) / 2.0 for i, j in product(list(range(cm.shape[0])), list(range(cm.shape[1]))): cmr = round(cmn[i, j], 3) plt.text(j, i, cmr, horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") # labels plt.tight_layout() plt.ylabel('True Label') plt.xlabel('Predicted Label') # save the chart tag = USEP.join([pstring, algo]) write_plot('matplotlib', plt, 'confusion', tag, plot_dir) # # Function plot_validation_curve # def plot_validation_curve(model, partition, pname, prange): r"""Generate scikit-learn validation curves. Parameters ---------- model : alphapy.Model The model object with plotting specifications. partition : alphapy.Partition Reference to the dataset. pname : str Name of the hyperparameter to test. prange : numpy array The values of the hyperparameter that will be evaluated. Returns ------- None : None References ---------- http://scikit-learn.org/stable/auto_examples/model_selection/plot_validation_curve.html#sphx-glr-auto-examples-model-selection-plot-validation-curve-py """ logger.info("Generating Validation Curves") plot_dir = get_plot_directory(model) pstring = datasets[partition] # Extract model parameters. cv_folds = model.specs['cv_folds'] n_jobs = model.specs['n_jobs'] scorer = model.specs['scorer'] verbosity = model.specs['verbosity'] # Get X, Y for correct partition. X, y = get_partition_data(model, partition) # Define plotting constants. spacing = 0.5 alpha = 0.2 # Calculate a validation curve for each algorithm. for algo in model.algolist: logger.info("Algorithm: %s", algo) # get estimator estimator = model.estimators[algo] # set up plot train_scores, test_scores = validation_curve( estimator, X, y, param_name=pname, param_range=prange, cv=cv_folds, scoring=scorer, n_jobs=n_jobs) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) # set up figure plt.style.use('classic') plt.figure() # plot learning curves title = BSEP.join([algo, "Validation Curve [", pstring, "]"]) plt.title(title) # x-axis x_min, x_max = min(prange) - spacing, max(prange) + spacing plt.xlabel(pname) plt.xlim(x_min, x_max) # y-axis plt.ylabel("Score") plt.ylim(0.0, 1.1) # plot scores plt.plot(prange, train_scores_mean, label="Training Score", color="r") plt.fill_between(prange, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=alpha, color="r") plt.plot(prange, test_scores_mean, label="Cross-Validation Score", color="g") plt.fill_between(prange, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=alpha, color="g") plt.legend(loc="best") # save the plot tag = USEP.join([pstring, algo]) write_plot('matplotlib', plt, 'validation_curve', tag, plot_dir) # # Function plot_boundary # def plot_boundary(model, partition, f1=0, f2=1): r"""Display a comparison of classifiers Parameters ---------- model : alphapy.Model The model object with plotting specifications. partition : alphapy.Partition Reference to the dataset. f1 : int Number of the first feature to compare. f2 : int Number of the second feature to compare. Returns ------- None : None References ---------- Code excerpts from authors: * Gael Varoquaux * Andreas Muller http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html """ logger.info("Generating Boundary Plots") pstring = datasets[partition] # For classification only if model.specs['model_type'] != ModelType.classification: logger.info('Boundary Plots are for classification only') return None # Get X, Y for correct partition X, y = get_partition_data(model, partition) # Subset for the two boundary features X = X[[f1, f2]] # Initialize plot n_classifiers = len(model.algolist) plt.figure(figsize=(3 * 2, n_classifiers * 2)) plt.subplots_adjust(bottom=.2, top=.95) xx = np.linspace(3, 9, 100) yy = np.linspace(1, 5, 100).T xx, yy = np.meshgrid(xx, yy) Xfull = np.c_[xx.ravel(), yy.ravel()] # Plot each classification probability for index, name in enumerate(model.algolist): # predictions y_pred = model.preds[(algo, partition)] classif_rate = np.mean(y_pred.ravel() == y.ravel()) * 100 logger.info("Classification Rate for %s : %f " % (name, classif_rate)) # probabilities probas = model.probas[(algo, partition)] n_classes = np.unique(y_pred).size # plot each class for k in range(n_classes): plt.subplot(n_classifiers, n_classes, index * n_classes + k + 1) plt.title("Class %d" % k) if k == 0: plt.ylabel(name) imshow_handle = plt.imshow(probas[:, k].reshape((100, 100)), extent=(3, 9, 1, 5), origin='lower') plt.xticks(()) plt.yticks(()) idx = (y_pred == k) if idx.any(): plt.scatter(X[idx, 0], X[idx, 1], marker='o', c='k') # Plot the probability color bar ax = plt.axes([0.15, 0.04, 0.7, 0.05]) plt.title("Probability") plt.colorbar(imshow_handle, cax=ax, orientation='horizontal') # Save the plot plot_dir = get_plot_directory(model) write_plot('matplotlib', figure, 'boundary', pstring, plot_dir) # # Function plot_partial_dependence # def plot_partial_dependence(est, X, features, fnames, tag, n_jobs=-1, verbosity=0, directory=None): r"""Display a Partial Dependence Plot. Parameters ---------- est : estimator The scikit-learn estimator for calculating partial dependence. X : numpy array The data on which the estimator was trained. features : list of int Feature numbers of ``X``. fnames : list of str The feature names to plot. tag : str Unique identifier for the plot n_jobs : int, optional The maximum number of parallel jobs. verbosity : int, optional The amount of logging from 0 (minimum) and higher. directory : str Directory where the plot will be stored. Returns ------- None : None. References ---------- http://scikit-learn.org/stable/auto_examples/ensemble/plot_partial_dependence.html#sphx-glr-auto-examples-ensemble-plot-partial-dependence-py """ logger.info("Generating Partial Dependence Plot") # Plot partial dependence fig, axs = plot_partial_dependence(est, X, features, feature_names=fnames, grid_resolution=50, n_jobs=n_jobs, verbose=verbosity) title = "Partial Dependence Plot" fig.suptitle(title) plt.subplots_adjust(top=0.9) # tight_layout causes overlap with suptitle # Save the plot write_plot(model, 'matplotlib', plt, 'partial_dependence', tag, directory) # # Function plot_scatter # def plot_scatter(df, features, target, tag='eda', directory=None): r"""Plot a scatterplot matrix, also known as a pair plot. Parameters ---------- df : pandas.DataFrame The dataframe containing the features. features: list of str The features to compare in the scatterplot. target : str The target variable for contrast. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- https://seaborn.pydata.org/examples/scatterplot_matrix.html """ logger.info("Generating Scatter Plot") # Get the feature subset features.append(target) df = df[features] # Generate the pair plot sns.set() sns_plot = sns.pairplot(df, hue=target) # Save the plot write_plot('seaborn', sns_plot, 'scatter_plot', tag, directory) # # Function plot_facet_grid # def plot_facet_grid(df, target, frow, fcol, tag='eda', directory=None): r"""Plot a Seaborn faceted histogram grid. Parameters ---------- df : pandas.DataFrame The dataframe containing the features. target : str The target variable for contrast. frow : list of str Feature names for the row elements of the grid. fcol : list of str Feature names for the column elements of the grid. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- http://seaborn.pydata.org/generated/seaborn.FacetGrid.html """ logger.info("Generating Facet Grid") # Calculate the number of bins using the Freedman-Diaconis rule. tlen = len(df[target]) tmax = df[target].max() tmin = df[target].min() trange = tmax - tmin iqr = df[target].quantile(Q3) - df[target].quantile(Q1) h = 2 * iqr * (tlen ** (-1/3)) nbins = math.ceil(trange / h) # Generate the pair plot sns.set(style="darkgrid") fg = sns.FacetGrid(df, row=frow, col=fcol, margin_titles=True) bins = np.linspace(tmin, tmax, nbins) fg.map(plt.hist, target, color="steelblue", bins=bins, lw=0) # Save the plot write_plot('seaborn', fg, 'facet_grid', tag, directory) # # Function plot_distribution # def plot_distribution(df, target, tag='eda', directory=None): r"""Display a Distribution Plot. Parameters ---------- df : pandas.DataFrame The dataframe containing the ``target`` feature. target : str The target variable for the distribution plot. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- http://seaborn.pydata.org/generated/seaborn.distplot.html """ logger.info("Generating Distribution Plot") # Generate the distribution plot dist_plot = sns.distplot(df[target]) dist_fig = dist_plot.get_figure() # Save the plot write_plot('seaborn', dist_fig, 'distribution_plot', tag, directory) # # Function plot_box # def plot_box(df, x, y, hue, tag='eda', directory=None): r"""Display a Box Plot. Parameters ---------- df : pandas.DataFrame The dataframe containing the ``x`` and ``y`` features. x : str Variable name in ``df`` to display along the x-axis. y : str Variable name in ``df`` to display along the y-axis. hue : str Variable name to be used as hue, i.e., another data dimension. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- http://seaborn.pydata.org/generated/seaborn.boxplot.html """ logger.info("Generating Box Plot") # Generate the box plot box_plot = sns.boxplot(x=x, y=y, hue=hue, data=df) sns.despine(offset=10, trim=True) box_fig = box_plot.get_figure() # Save the plot write_plot('seaborn', box_fig, 'box_plot', tag, directory) # # Function plot_swarm # def plot_swarm(df, x, y, hue, tag='eda', directory=None): r"""Display a Swarm Plot. Parameters ---------- df : pandas.DataFrame The dataframe containing the ``x`` and ``y`` features. x : str Variable name in ``df`` to display along the x-axis. y : str Variable name in ``df`` to display along the y-axis. hue : str Variable name to be used as hue, i.e., another data dimension. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- http://seaborn.pydata.org/generated/seaborn.swarmplot.html """ logger.info("Generating Swarm Plot") # Generate the swarm plot swarm_plot = sns.swarmplot(x=x, y=y, hue=hue, data=df) swarm_fig = swarm_plot.get_figure() # Save the plot write_plot('seaborn', swarm_fig, 'swarm_plot', tag, directory) # # Time Series Plots # # # Function plot_time_series # def plot_time_series(df, target, tag='eda', directory=None): r"""Plot time series data. Parameters ---------- df : pandas.DataFrame The dataframe containing the ``target`` feature. target : str The target variable for the time series plot. tag : str Unique identifier for the plot. directory : str, optional The full specification of the plot location. Returns ------- None : None. References ---------- http://seaborn.pydata.org/generated/seaborn.tsplot.html """ logger.info("Generating Time Series Plot") # Generate the time series plot ts_plot = sns.tsplot(data=df[target]) ts_fig = ts_plot.get_figure() # Save the plot write_plot('seaborn', ts_fig, 'time_series_plot', tag, directory) # # Function plot_candlestick # def plot_candlestick(df, symbol, datecol='date', directory=None): r"""Plot time series data. Parameters ---------- df : pandas.DataFrame The dataframe containing the ``target`` feature. symbol : str Unique identifier of the data to plot. datecol : str, optional The name of the date column. directory : str, optional The full specification of the plot location. Returns ------- None : None. Notes ----- The dataframe ``df`` must contain these columns: * ``open`` * ``high`` * ``low`` * ``close`` References ---------- http://bokeh.pydata.org/en/latest/docs/gallery/candlestick.html """ df[datecol] = pd.to_datetime(df[datecol]) mids = (df.open + df.close) / 2 spans = abs(df.close - df.open) inc = df.close > df.open dec = df.open > df.close w = 12 * 60 * 60 * 1000 # half day in ms TOOLS = "pan, wheel_zoom, box_zoom, reset, save" p = figure(x_axis_type="datetime", tools=TOOLS, plot_width=1000, toolbar_location="left") p.title = BSEP.join([symbol.upper(), "Candlestick"]) p.xaxis.major_label_orientation = math.pi / 4 p.grid.grid_line_alpha = 0.3 p.segment(df.date, df.high, df.date, df.low, color="black") p.rect(df.date[inc], mids[inc], w, spans[inc], fill_color="#D5E1DD", line_color="black") p.rect(df.date[dec], mids[dec], w, spans[dec], fill_color="#F2583E", line_color="black") # Save the plot write_plot('bokeh', p, 'candlestick_chart', symbol, directory)
apache-2.0
guyhwilson/guyhwilson.github.io
markdown_generator/talks.py
199
4000
# coding: utf-8 # # Talks markdown generator for academicpages # # Takes a TSV of talks with metadata and converts them for use with [academicpages.github.io](academicpages.github.io). This is an interactive Jupyter notebook ([see more info here](http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.html)). The core python code is also in `talks.py`. Run either from the `markdown_generator` folder after replacing `talks.tsv` with one containing your data. # # TODO: Make this work with BibTex and other databases, rather than Stuart's non-standard TSV format and citation style. # In[1]: import pandas as pd import os # ## Data format # # The TSV needs to have the following columns: title, type, url_slug, venue, date, location, talk_url, description, with a header at the top. Many of these fields can be blank, but the columns must be in the TSV. # # - Fields that cannot be blank: `title`, `url_slug`, `date`. All else can be blank. `type` defaults to "Talk" # - `date` must be formatted as YYYY-MM-DD. # - `url_slug` will be the descriptive part of the .md file and the permalink URL for the page about the paper. # - The .md file will be `YYYY-MM-DD-[url_slug].md` and the permalink will be `https://[yourdomain]/talks/YYYY-MM-DD-[url_slug]` # - The combination of `url_slug` and `date` must be unique, as it will be the basis for your filenames # # ## Import TSV # # Pandas makes this easy with the read_csv function. We are using a TSV, so we specify the separator as a tab, or `\t`. # # I found it important to put this data in a tab-separated values format, because there are a lot of commas in this kind of data and comma-separated values can get messed up. However, you can modify the import statement, as pandas also has read_excel(), read_json(), and others. # In[3]: talks = pd.read_csv("talks.tsv", sep="\t", header=0) talks # ## Escape special characters # # YAML is very picky about how it takes a valid string, so we are replacing single and double quotes (and ampersands) with their HTML encoded equivilents. This makes them look not so readable in raw format, but they are parsed and rendered nicely. # In[4]: html_escape_table = { "&": "&amp;", '"': "&quot;", "'": "&apos;" } def html_escape(text): if type(text) is str: return "".join(html_escape_table.get(c,c) for c in text) else: return "False" # ## Creating the markdown files # # This is where the heavy lifting is done. This loops through all the rows in the TSV dataframe, then starts to concatentate a big string (```md```) that contains the markdown for each type. It does the YAML metadata first, then does the description for the individual page. # In[5]: loc_dict = {} for row, item in talks.iterrows(): md_filename = str(item.date) + "-" + item.url_slug + ".md" html_filename = str(item.date) + "-" + item.url_slug year = item.date[:4] md = "---\ntitle: \"" + item.title + '"\n' md += "collection: talks" + "\n" if len(str(item.type)) > 3: md += 'type: "' + item.type + '"\n' else: md += 'type: "Talk"\n' md += "permalink: /talks/" + html_filename + "\n" if len(str(item.venue)) > 3: md += 'venue: "' + item.venue + '"\n' if len(str(item.location)) > 3: md += "date: " + str(item.date) + "\n" if len(str(item.location)) > 3: md += 'location: "' + str(item.location) + '"\n' md += "---\n" if len(str(item.talk_url)) > 3: md += "\n[More information here](" + item.talk_url + ")\n" if len(str(item.description)) > 3: md += "\n" + html_escape(item.description) + "\n" md_filename = os.path.basename(md_filename) #print(md) with open("../_talks/" + md_filename, 'w') as f: f.write(md) # These files are in the talks directory, one directory below where we're working from.
mit
timothydmorton/VESPA
vespa/stars/trilegal.py
1
9246
from __future__ import print_function,division import logging import subprocess as sp import os, re import time try: import numpy as np import pandas as pd from astropy.units import UnitsError from astropy.coordinates import SkyCoord except ImportError: np, pd = (None, None) UnitsError, SkyCoord = (None, None) from .extinction import get_AV_infinity NONMAG_COLS = ['Gc','logAge', '[M/H]', 'm_ini', 'logL', 'logTe', 'logg', 'm-M0', 'Av', 'm2/m1', 'mbol', 'Mact'] #all the rest are mags def get_trilegal(filename,ra,dec,folder='.', galactic=False, filterset='kepler_2mass',area=1,maglim=27,binaries=False, trilegal_version='1.6',sigma_AV=0.1,convert_h5=True): """Runs get_trilegal perl script; optionally saves output into .h5 file Depends on a perl script provided by L. Girardi; calls the web form simulation, downloads the file, and (optionally) converts to HDF format. Uses A_V at infinity from :func:`utils.get_AV_infinity`. .. note:: Would be desirable to re-write the get_trilegal script all in python. :param filename: Desired output filename. If extension not provided, it will be added. :param ra,dec: Coordinates (ecliptic) for line-of-sight simulation. :param folder: (optional) Folder to which to save file. *Acknowledged, file control in this function is a bit wonky.* :param filterset: (optional) Filter set for which to call TRILEGAL. :param area: (optional) Area of TRILEGAL simulation [sq. deg] :param maglim: (optional) Limiting magnitude in first mag (by default will be Kepler band) If want to limit in different band, then you have to got directly to the ``get_trilegal`` perl script. :param binaries: (optional) Whether to have TRILEGAL include binary stars. Default ``False``. :param trilegal_version: (optional) Default ``'1.6'``. :param sigma_AV: (optional) Fractional spread in A_V along the line of sight. :param convert_h5: (optional) If true, text file downloaded from TRILEGAL will be converted into a ``pandas.DataFrame`` stored in an HDF file, with ``'df'`` path. """ if galactic: l, b = ra, dec else: try: c = SkyCoord(ra,dec) except UnitsError: c = SkyCoord(ra,dec,unit='deg') l,b = (c.galactic.l.value,c.galactic.b.value) if os.path.isabs(filename): folder = '' if not re.search('\.dat$',filename): outfile = '{}/{}.dat'.format(folder,filename) else: outfile = '{}/{}'.format(folder,filename) AV = get_AV_infinity(l,b,frame='galactic') #cmd = 'get_trilegal %s %f %f %f %i %.3f %.2f %s 1 %.1f %s' % (trilegal_version,l,b, # area,binaries,AV,sigma_AV, # filterset,maglim,outfile) #sp.Popen(cmd,shell=True).wait() trilegal_webcall(trilegal_version,l,b,area,binaries,AV,sigma_AV,filterset,maglim,outfile) if convert_h5: df = pd.read_table(outfile, sep='\s+', skipfooter=1, engine='python') df = df.rename(columns={'#Gc':'Gc'}) for col in df.columns: if col not in NONMAG_COLS: df.rename(columns={col:'{}_mag'.format(col)},inplace=True) if not re.search('\.h5$', filename): h5file = '{}/{}.h5'.format(folder,filename) else: h5file = '{}/{}'.format(folder,filename) df.to_hdf(h5file,'df') with pd.HDFStore(h5file) as store: attrs = store.get_storer('df').attrs attrs.trilegal_args = {'version':trilegal_version, 'ra':ra, 'dec':dec, 'l':l,'b':b,'area':area, 'AV':AV, 'sigma_AV':sigma_AV, 'filterset':filterset, 'maglim':maglim, 'binaries':binaries} os.remove(outfile) def trilegal_webcall(trilegal_version,l,b,area,binaries,AV,sigma_AV,filterset,maglim, outfile): """Calls TRILEGAL webserver and downloads results file. :param trilegal_version: Version of trilegal (only tested on 1.6). :param l,b: Coordinates (galactic) for line-of-sight simulation. :param area: Area of TRILEGAL simulation [sq. deg] :param binaries: Whether to have TRILEGAL include binary stars. Default ``False``. :param AV: Extinction along the line of sight. :param sigma_AV: Fractional spread in A_V along the line of sight. :param filterset: (optional) Filter set for which to call TRILEGAL. :param maglim: Limiting magnitude in mag (by default will be 1st band of filterset) If want to limit in different band, then you have to change function directly. :param outfile: Desired output filename. """ webserver = 'http://stev.oapd.inaf.it' args = [l,b,area,AV,sigma_AV,filterset,maglim,1,binaries] mainparams = ('imf_file=tab_imf%2Fimf_chabrier_lognormal.dat&binary_frac=0.3&' 'binary_mrinf=0.7&binary_mrsup=1&extinction_h_r=100000&extinction_h_z=' '110&extinction_kind=2&extinction_rho_sun=0.00015&extinction_infty={}&' 'extinction_sigma={}&r_sun=8700&z_sun=24.2&thindisk_h_r=2800&' 'thindisk_r_min=0&thindisk_r_max=15000&thindisk_kind=3&thindisk_h_z0=' '95&thindisk_hz_tau0=4400000000&thindisk_hz_alpha=1.6666&' 'thindisk_rho_sun=59&thindisk_file=tab_sfr%2Ffile_sfr_thindisk_mod.dat&' 'thindisk_a=0.8&thindisk_b=0&thickdisk_kind=0&thickdisk_h_r=2800&' 'thickdisk_r_min=0&thickdisk_r_max=15000&thickdisk_h_z=800&' 'thickdisk_rho_sun=0.0015&thickdisk_file=tab_sfr%2Ffile_sfr_thickdisk.dat&' 'thickdisk_a=1&thickdisk_b=0&halo_kind=2&halo_r_eff=2800&halo_q=0.65&' 'halo_rho_sun=0.00015&halo_file=tab_sfr%2Ffile_sfr_halo.dat&halo_a=1&' 'halo_b=0&bulge_kind=2&bulge_am=2500&bulge_a0=95&bulge_eta=0.68&' 'bulge_csi=0.31&bulge_phi0=15&bulge_rho_central=406.0&' 'bulge_cutoffmass=0.01&bulge_file=tab_sfr%2Ffile_sfr_bulge_zoccali_p03.dat&' 'bulge_a=1&bulge_b=-2.0e9&object_kind=0&object_mass=1280&object_dist=1658&' 'object_av=1.504&object_avkind=1&object_cutoffmass=0.8&' 'object_file=tab_sfr%2Ffile_sfr_m4.dat&object_a=1&object_b=0&' 'output_kind=1').format(AV,sigma_AV) cmdargs = [trilegal_version,l,b,area,filterset,1,maglim,binaries,mainparams, webserver,trilegal_version] cmd = ("wget -o lixo -Otmpfile --post-data='submit_form=Submit&trilegal_version={}" "&gal_coord=1&gc_l={}&gc_b={}&eq_alpha=0&eq_delta=0&field={}&photsys_file=" "tab_mag_odfnew%2Ftab_mag_{}.dat&icm_lim={}&mag_lim={}&mag_res=0.1&" "binary_kind={}&{}' {}/cgi-bin/trilegal_{}").format(*cmdargs) complete = False while not complete: notconnected = True busy = True print("TRILEGAL is being called with \n l={} deg, b={} deg, area={} sqrdeg\n " "Av={} with {} fractional r.m.s. spread \n in the {} system, complete down to " "mag={} in its {}th filter, use_binaries set to {}.".format(*args)) sp.Popen(cmd,shell=True).wait() if os.path.exists('tmpfile') and os.path.getsize('tmpfile')>0: notconnected = False else: print("No communication with {}, will retry in 2 min".format(webserver)) time.sleep(120) if not notconnected: with open('tmpfile','r') as f: lines = f.readlines() for line in lines: if 'The results will be available after about 2 minutes' in line: busy = False break sp.Popen('rm -f lixo tmpfile',shell=True) if not busy: filenameidx = line.find('<a href=../tmp/') +15 fileendidx = line[filenameidx:].find('.dat') filename = line[filenameidx:filenameidx+fileendidx+4] print("retrieving data from {} ...".format(filename)) while not complete: time.sleep(40) modcmd = 'wget -o lixo -O{} {}/tmp/{}'.format(filename,webserver,filename) modcall = sp.Popen(modcmd,shell=True).wait() if os.path.getsize(filename)>0: with open(filename,'r') as f: lastline = f.readlines()[-1] if 'normally' in lastline: complete = True print('model downloaded!..') if not complete: print('still running...') else: print('Server busy, trying again in 2 minutes') time.sleep(120) sp.Popen('mv {} {}'.format(filename,outfile),shell=True).wait() print('results copied to {}'.format(outfile))
mit